clang 24.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"
48#include "clang/AST/OSLog.h"
52#include "clang/AST/Type.h"
53#include "clang/AST/TypeLoc.h"
58#include "llvm/ADT/APFixedPoint.h"
59#include "llvm/ADT/Sequence.h"
60#include "llvm/ADT/SmallBitVector.h"
61#include "llvm/ADT/StringExtras.h"
62#include "llvm/Support/Casting.h"
63#include "llvm/Support/Debug.h"
64#include "llvm/Support/SaveAndRestore.h"
65#include "llvm/Support/SipHash.h"
66#include "llvm/Support/TimeProfiler.h"
67#include "llvm/Support/raw_ostream.h"
68#include <cstring>
69#include <functional>
70#include <limits>
71#include <optional>
72
73#define DEBUG_TYPE "exprconstant"
74
75using namespace clang;
76using llvm::APFixedPoint;
77using llvm::APInt;
78using llvm::APSInt;
79using llvm::APFloat;
80using llvm::FixedPointSemantics;
81
82namespace {
83 struct LValue;
84 class CallStackFrame;
85 class EvalInfo;
86
87 using SourceLocExprScopeGuard =
89
91 return B.getType();
92 }
93
94 /// Get an LValue path entry, which is known to not be an array index, as a
95 /// field declaration.
96 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
97 return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer());
98 }
99 /// Get an LValue path entry, which is known to not be an array index, as a
100 /// base class declaration.
101 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
102 return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer());
103 }
104 /// Determine whether this LValue path entry for a base class names a virtual
105 /// base class.
106 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
107 return E.getAsBaseOrMember().getInt();
108 }
109
110 /// Given an expression, determine the type used to store the result of
111 /// evaluating that expression.
112 static QualType getStorageType(const ASTContext &Ctx, const Expr *E) {
113 if (E->isPRValue())
114 return E->getType();
115 return Ctx.getLValueReferenceType(E->getType());
116 }
117
118 static unsigned countNonVirtualBases(const CXXRecordDecl *RD) {
119 return llvm::count_if(RD->bases(), [](auto &B) { return !B.isVirtual(); });
120 }
121
122 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
123 /// This will look through a single cast.
124 ///
125 /// Returns null if we couldn't unwrap a function with alloc_size.
126 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
127 if (!E->getType()->isPointerType())
128 return nullptr;
129
130 E = E->IgnoreParens();
131 // If we're doing a variable assignment from e.g. malloc(N), there will
132 // probably be a cast of some kind. In exotic cases, we might also see a
133 // top-level ExprWithCleanups. Ignore them either way.
134 if (const auto *FE = dyn_cast<FullExpr>(E))
135 E = FE->getSubExpr()->IgnoreParens();
136
137 if (const auto *Cast = dyn_cast<CastExpr>(E))
138 E = Cast->getSubExpr()->IgnoreParens();
139
140 if (const auto *CE = dyn_cast<CallExpr>(E))
141 return CE->getCalleeAllocSizeAttr() ? CE : nullptr;
142 return nullptr;
143 }
144
145 /// Determines whether or not the given Base contains a call to a function
146 /// with the alloc_size attribute.
147 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
148 const auto *E = Base.dyn_cast<const Expr *>();
149 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
150 }
151
152 /// Determines whether the given kind of constant expression is only ever
153 /// used for name mangling. If so, it's permitted to reference things that we
154 /// can't generate code for (in particular, dllimported functions).
155 static bool isForManglingOnly(ConstantExprKind Kind) {
156 switch (Kind) {
157 case ConstantExprKind::Normal:
158 case ConstantExprKind::ClassTemplateArgument:
159 case ConstantExprKind::ImmediateInvocation:
160 // Note that non-type template arguments of class type are emitted as
161 // template parameter objects.
162 return false;
163
164 case ConstantExprKind::NonClassTemplateArgument:
165 return true;
166 }
167 llvm_unreachable("unknown ConstantExprKind");
168 }
169
170 static bool isTemplateArgument(ConstantExprKind Kind) {
171 switch (Kind) {
172 case ConstantExprKind::Normal:
173 case ConstantExprKind::ImmediateInvocation:
174 return false;
175
176 case ConstantExprKind::ClassTemplateArgument:
177 case ConstantExprKind::NonClassTemplateArgument:
178 return true;
179 }
180 llvm_unreachable("unknown ConstantExprKind");
181 }
182
183 /// The bound to claim that an array of unknown bound has.
184 /// The value in MostDerivedArraySize is undefined in this case. So, set it
185 /// to an arbitrary value that's likely to loudly break things if it's used.
186 static const uint64_t AssumedSizeForUnsizedArray =
187 std::numeric_limits<uint64_t>::max() / 2;
188
189 /// Determines if an LValue with the given LValueBase will have an unsized
190 /// array in its designator.
191 /// Find the path length and type of the most-derived subobject in the given
192 /// path, and find the size of the containing array, if any.
193 static unsigned
194 findMostDerivedSubobject(const ASTContext &Ctx, APValue::LValueBase Base,
196 uint64_t &ArraySize, QualType &Type, bool &IsArray,
197 bool &FirstEntryIsUnsizedArray) {
198 // This only accepts LValueBases from APValues, and APValues don't support
199 // arrays that lack size info.
200 assert(!isBaseAnAllocSizeCall(Base) &&
201 "Unsized arrays shouldn't appear here");
202 unsigned MostDerivedLength = 0;
203 // The type of Base is a reference type if the base is a constexpr-unknown
204 // variable. In that case, look through the reference type.
205 Type = getType(Base).getNonReferenceType();
206
207 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
208 if (Type->isArrayType()) {
209 const ArrayType *AT = Ctx.getAsArrayType(Type);
210 Type = AT->getElementType();
211 MostDerivedLength = I + 1;
212 IsArray = true;
213
214 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
215 ArraySize = CAT->getZExtSize();
216 } else {
217 assert(I == 0 && "unexpected unsized array designator");
218 FirstEntryIsUnsizedArray = true;
219 ArraySize = AssumedSizeForUnsizedArray;
220 }
221 } else if (Type->isAnyComplexType()) {
222 const ComplexType *CT = Type->castAs<ComplexType>();
223 Type = CT->getElementType();
224 ArraySize = 2;
225 MostDerivedLength = I + 1;
226 IsArray = true;
227 } else if (const auto *VT = Type->getAs<VectorType>()) {
228 Type = VT->getElementType();
229 ArraySize = VT->getNumElements();
230 MostDerivedLength = I + 1;
231 IsArray = true;
232 } else if (const FieldDecl *FD = getAsField(Path[I])) {
233 Type = FD->getType();
234 ArraySize = 0;
235 MostDerivedLength = I + 1;
236 IsArray = false;
237 } else {
238 // Path[I] describes a base class.
239 ArraySize = 0;
240 IsArray = false;
241 }
242 }
243 return MostDerivedLength;
244 }
245
246 /// A path from a glvalue to a subobject of that glvalue.
247 struct SubobjectDesignator {
248 /// True if the subobject was named in a manner not supported by C++11. Such
249 /// lvalues can still be folded, but they are not core constant expressions
250 /// and we cannot perform lvalue-to-rvalue conversions on them.
251 LLVM_PREFERRED_TYPE(bool)
252 unsigned Invalid : 1;
253
254 /// Is this a pointer one past the end of an object?
255 LLVM_PREFERRED_TYPE(bool)
256 unsigned IsOnePastTheEnd : 1;
257
258 /// Indicator of whether the first entry is an unsized array.
259 LLVM_PREFERRED_TYPE(bool)
260 unsigned FirstEntryIsAnUnsizedArray : 1;
261
262 /// Indicator of whether the most-derived object is an array element.
263 LLVM_PREFERRED_TYPE(bool)
264 unsigned MostDerivedIsArrayElement : 1;
265
266 /// The length of the path to the most-derived object of which this is a
267 /// subobject.
268 unsigned MostDerivedPathLength : 28;
269
270 /// The size of the array of which the most-derived object is an element.
271 /// This will always be 0 if the most-derived object is not an array
272 /// element. 0 is not an indicator of whether or not the most-derived object
273 /// is an array, however, because 0-length arrays are allowed.
274 ///
275 /// If the current array is an unsized array, the value of this is
276 /// undefined.
277 uint64_t MostDerivedArraySize;
278 /// The type of the most derived object referred to by this address.
279 QualType MostDerivedType;
280
281 typedef APValue::LValuePathEntry PathEntry;
282
283 /// The entries on the path from the glvalue to the designated subobject.
285
286 SubobjectDesignator() : Invalid(true) {}
287
288 explicit SubobjectDesignator(QualType T)
289 : Invalid(false), IsOnePastTheEnd(false),
290 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
291 MostDerivedPathLength(0), MostDerivedArraySize(0),
292 MostDerivedType(T.isNull() ? QualType() : T.getNonReferenceType()) {}
293
294 SubobjectDesignator(const ASTContext &Ctx, const APValue &V)
295 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
296 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
297 MostDerivedPathLength(0), MostDerivedArraySize(0) {
298 assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
299 if (!Invalid) {
300 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
301 llvm::append_range(Entries, V.getLValuePath());
302 if (V.getLValueBase()) {
303 bool IsArray = false;
304 bool FirstIsUnsizedArray = false;
305 MostDerivedPathLength = findMostDerivedSubobject(
306 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
307 MostDerivedType, IsArray, FirstIsUnsizedArray);
308 MostDerivedIsArrayElement = IsArray;
309 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
310 }
311 }
312 }
313
314 void truncate(ASTContext &Ctx, APValue::LValueBase Base,
315 unsigned NewLength) {
316 if (Invalid)
317 return;
318
319 assert(Base && "cannot truncate path for null pointer");
320 assert(NewLength <= Entries.size() && "not a truncation");
321
322 if (NewLength == Entries.size())
323 return;
324 Entries.resize(NewLength);
325
326 bool IsArray = false;
327 bool FirstIsUnsizedArray = false;
328 MostDerivedPathLength = findMostDerivedSubobject(
329 Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray,
330 FirstIsUnsizedArray);
331 MostDerivedIsArrayElement = IsArray;
332 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
333 }
334
335 void setInvalid() {
336 Invalid = true;
337 Entries.clear();
338 }
339
340 /// Determine whether the most derived subobject is an array without a
341 /// known bound.
342 bool isMostDerivedAnUnsizedArray() const {
343 assert(!Invalid && "Calling this makes no sense on invalid designators");
344 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
345 }
346
347 /// Determine what the most derived array's size is. Results in an assertion
348 /// failure if the most derived array lacks a size.
349 uint64_t getMostDerivedArraySize() const {
350 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
351 return MostDerivedArraySize;
352 }
353
354 /// Determine whether this is a one-past-the-end pointer.
355 bool isOnePastTheEnd() const {
356 assert(!Invalid);
357 if (IsOnePastTheEnd)
358 return true;
359 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
360 Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==
361 MostDerivedArraySize)
362 return true;
363 return false;
364 }
365
366 /// Get the range of valid index adjustments in the form
367 /// {maximum value that can be subtracted from this pointer,
368 /// maximum value that can be added to this pointer}
369 std::pair<uint64_t, uint64_t> validIndexAdjustments() {
370 if (Invalid || isMostDerivedAnUnsizedArray())
371 return {0, 0};
372
373 // [expr.add]p4: For the purposes of these operators, a pointer to a
374 // nonarray object behaves the same as a pointer to the first element of
375 // an array of length one with the type of the object as its element type.
376 bool IsArray = MostDerivedPathLength == Entries.size() &&
377 MostDerivedIsArrayElement;
378 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
379 : (uint64_t)IsOnePastTheEnd;
380 uint64_t ArraySize =
381 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
382 return {ArrayIndex, ArraySize - ArrayIndex};
383 }
384
385 /// Check that this refers to a valid subobject.
386 bool isValidSubobject() const {
387 if (Invalid)
388 return false;
389 return !isOnePastTheEnd();
390 }
391 /// Check that this refers to a valid subobject, and if not, produce a
392 /// relevant diagnostic and set the designator as invalid.
393 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
394
395 /// Get the type of the designated object.
396 QualType getType(ASTContext &Ctx) const {
397 assert(!Invalid && "invalid designator has no subobject type");
398 return MostDerivedPathLength == Entries.size()
399 ? MostDerivedType
400 : Ctx.getCanonicalTagType(getAsBaseClass(Entries.back()));
401 }
402
403 /// Update this designator to refer to the first element within this array.
404 void addArrayUnchecked(const ConstantArrayType *CAT) {
405 Entries.push_back(PathEntry::ArrayIndex(0));
406
407 // This is a most-derived object.
408 MostDerivedType = CAT->getElementType();
409 MostDerivedIsArrayElement = true;
410 MostDerivedArraySize = CAT->getZExtSize();
411 MostDerivedPathLength = Entries.size();
412 }
413 /// Update this designator to refer to the first element within the array of
414 /// elements of type T. This is an array of unknown size.
415 void addUnsizedArrayUnchecked(QualType ElemTy) {
416 Entries.push_back(PathEntry::ArrayIndex(0));
417
418 MostDerivedType = ElemTy;
419 MostDerivedIsArrayElement = true;
420 // The value in MostDerivedArraySize is undefined in this case. So, set it
421 // to an arbitrary value that's likely to loudly break things if it's
422 // used.
423 MostDerivedArraySize = AssumedSizeForUnsizedArray;
424 MostDerivedPathLength = Entries.size();
425 }
426 /// Update this designator to refer to the given base or member of this
427 /// object.
428 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
429 Entries.push_back(APValue::BaseOrMemberType(D, Virtual));
430
431 // If this isn't a base class, it's a new most-derived object.
432 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
433 MostDerivedType = FD->getType();
434 MostDerivedIsArrayElement = false;
435 MostDerivedArraySize = 0;
436 MostDerivedPathLength = Entries.size();
437 }
438 }
439 /// Update this designator to refer to the given complex component.
440 void addComplexUnchecked(QualType EltTy, bool Imag) {
441 Entries.push_back(PathEntry::ArrayIndex(Imag));
442
443 // This is technically a most-derived object, though in practice this
444 // is unlikely to matter.
445 MostDerivedType = EltTy;
446 MostDerivedIsArrayElement = true;
447 MostDerivedArraySize = 2;
448 MostDerivedPathLength = Entries.size();
449 }
450
451 void addVectorElementUnchecked(QualType EltTy, uint64_t Size,
452 uint64_t Idx) {
453 Entries.push_back(PathEntry::ArrayIndex(Idx));
454 MostDerivedType = EltTy;
455 MostDerivedPathLength = Entries.size();
456 MostDerivedArraySize = 0;
457 MostDerivedIsArrayElement = false;
458 }
459
460 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
461 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
462 const APSInt &N);
463 /// Add N to the address of this subobject.
464 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N, const LValue &LV);
465 };
466
467 /// A scope at the end of which an object can need to be destroyed.
468 enum class ScopeKind {
469 Block,
470 FullExpression,
471 Call
472 };
473
474 /// A reference to a particular call and its arguments.
475 struct CallRef {
476 CallRef() : OrigCallee(), CallIndex(0), Version() {}
477 CallRef(const FunctionDecl *Callee, unsigned CallIndex, unsigned Version)
478 : OrigCallee(Callee), CallIndex(CallIndex), Version(Version) {}
479
480 explicit operator bool() const { return OrigCallee; }
481
482 /// Get the parameter that the caller initialized, corresponding to the
483 /// given parameter in the callee.
484 const ParmVarDecl *getOrigParam(const ParmVarDecl *PVD) const {
485 return OrigCallee ? OrigCallee->getParamDecl(PVD->getFunctionScopeIndex())
486 : PVD;
487 }
488
489 /// The callee at the point where the arguments were evaluated. This might
490 /// be different from the actual callee (a different redeclaration, or a
491 /// virtual override), but this function's parameters are the ones that
492 /// appear in the parameter map.
493 const FunctionDecl *OrigCallee;
494 /// The call index of the frame that holds the argument values.
495 unsigned CallIndex;
496 /// The version of the parameters corresponding to this call.
497 unsigned Version;
498 };
499
500 /// A stack frame in the constexpr call stack.
501 class CallStackFrame : public interp::Frame {
502 public:
503 EvalInfo &Info;
504
505 /// Parent - The caller of this stack frame.
506 CallStackFrame *Caller;
507
508 /// Callee - The function which was called.
509 const FunctionDecl *Callee;
510
511 /// This - The binding for the this pointer in this call, if any.
512 const LValue *This;
513
514 /// CallExpr - The syntactical structure of member function calls
515 const Expr *CallExpr;
516
517 /// Information on how to find the arguments to this call. Our arguments
518 /// are stored in our parent's CallStackFrame, using the ParmVarDecl* as a
519 /// key and this value as the version.
520 CallRef Arguments;
521
522 /// Source location information about the default argument or default
523 /// initializer expression we're evaluating, if any.
524 CurrentSourceLocExprScope CurSourceLocExprScope;
525
526 // Note that we intentionally use std::map here so that references to
527 // values are stable.
528 typedef std::pair<const void *, unsigned> MapKeyTy;
529 typedef std::map<MapKeyTy, APValue> MapTy;
530 /// Temporaries - Temporary lvalues materialized within this stack frame.
531 MapTy Temporaries;
532
533 /// CallRange - The source range of the call expression for this call.
534 SourceRange CallRange;
535
536 /// Index - The call index of this call.
537 unsigned Index;
538
539 /// The stack of integers for tracking version numbers for temporaries.
540 SmallVector<unsigned, 2> TempVersionStack = {1};
541 unsigned CurTempVersion = TempVersionStack.back();
542
543 unsigned getTempVersion() const { return TempVersionStack.back(); }
544
545 void pushTempVersion() {
546 TempVersionStack.push_back(++CurTempVersion);
547 }
548
549 void popTempVersion() {
550 TempVersionStack.pop_back();
551 }
552
553 CallRef createCall(const FunctionDecl *Callee) {
554 return {Callee, Index, ++CurTempVersion};
555 }
556
557 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
558 // on the overall stack usage of deeply-recursing constexpr evaluations.
559 // (We should cache this map rather than recomputing it repeatedly.)
560 // But let's try this and see how it goes; we can look into caching the map
561 // as a later change.
562
563 /// LambdaCaptureFields - Mapping from captured variables/this to
564 /// corresponding data members in the closure class.
565 llvm::DenseMap<const ValueDecl *, FieldDecl *> LambdaCaptureFields;
566 FieldDecl *LambdaThisCaptureField = nullptr;
567
568 CallStackFrame(EvalInfo &Info, SourceRange CallRange,
569 const FunctionDecl *Callee, const LValue *This,
570 const Expr *CallExpr, CallRef Arguments);
571 ~CallStackFrame();
572
573 // Return the temporary for Key whose version number is Version.
574 APValue *getTemporary(const void *Key, unsigned Version) {
575 MapKeyTy KV(Key, Version);
576 auto LB = Temporaries.lower_bound(KV);
577 if (LB != Temporaries.end() && LB->first == KV)
578 return &LB->second;
579 return nullptr;
580 }
581
582 // Return the current temporary for Key in the map.
583 APValue *getCurrentTemporary(const void *Key) {
584 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
585 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
586 return &std::prev(UB)->second;
587 return nullptr;
588 }
589
590 // Return the version number of the current temporary for Key.
591 unsigned getCurrentTemporaryVersion(const void *Key) const {
592 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
593 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
594 return std::prev(UB)->first.second;
595 return 0;
596 }
597
598 /// Allocate storage for an object of type T in this stack frame.
599 /// Populates LV with a handle to the created object. Key identifies
600 /// the temporary within the stack frame, and must not be reused without
601 /// bumping the temporary version number.
602 template<typename KeyT>
603 APValue &createTemporary(const KeyT *Key, QualType T,
604 ScopeKind Scope, LValue &LV);
605
606 /// Allocate storage for a parameter of a function call made in this frame.
607 APValue &createParam(CallRef Args, const ParmVarDecl *PVD, LValue &LV);
608
609 void describe(llvm::raw_ostream &OS) const override;
610
611 Frame *getCaller() const override { return Caller; }
612 SourceRange getCallRange() const override { return CallRange; }
613 const FunctionDecl *getCallee() const override { return Callee; }
614
615 bool isStdFunction() const {
616 for (const DeclContext *DC = Callee; DC; DC = DC->getParent())
617 if (DC->isStdNamespace())
618 return true;
619 return false;
620 }
621
622 /// Whether we're in a context where [[msvc::constexpr]] evaluation is
623 /// permitted. See MSConstexprDocs for description of permitted contexts.
624 bool CanEvalMSConstexpr = false;
625
626 private:
627 APValue &createLocal(APValue::LValueBase Base, const void *Key, QualType T,
628 ScopeKind Scope);
629 };
630
631 /// Temporarily override 'this'.
632 class ThisOverrideRAII {
633 public:
634 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
635 : Frame(Frame), OldThis(Frame.This) {
636 if (Enable)
637 Frame.This = NewThis;
638 }
639 ~ThisOverrideRAII() {
640 Frame.This = OldThis;
641 }
642 private:
643 CallStackFrame &Frame;
644 const LValue *OldThis;
645 };
646
647 // A shorthand time trace scope struct, prints source range, for example
648 // {"name":"EvaluateAsRValue","args":{"detail":"<test.cc:8:21, col:25>"}}}
649 class ExprTimeTraceScope {
650 public:
651 ExprTimeTraceScope(const Expr *E, const ASTContext &Ctx, StringRef Name)
652 : TimeScope(Name, [E, &Ctx] {
654 }) {}
655
656 private:
657 llvm::TimeTraceScope TimeScope;
658 };
659
660 /// RAII object used to change the current ability of
661 /// [[msvc::constexpr]] evaulation.
662 struct MSConstexprContextRAII {
663 CallStackFrame &Frame;
664 bool OldValue;
665 explicit MSConstexprContextRAII(CallStackFrame &Frame, bool Value)
666 : Frame(Frame), OldValue(Frame.CanEvalMSConstexpr) {
667 Frame.CanEvalMSConstexpr = Value;
668 }
669
670 ~MSConstexprContextRAII() { Frame.CanEvalMSConstexpr = OldValue; }
671 };
672}
673
674static bool HandleDestruction(EvalInfo &Info, const Expr *E,
675 const LValue &This, QualType ThisType);
676static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
678 QualType T);
679
680namespace {
681 /// A cleanup, and a flag indicating whether it is lifetime-extended.
682 class Cleanup {
683 llvm::PointerIntPair<APValue*, 2, ScopeKind> Value;
684 APValue::LValueBase Base;
685 QualType T;
686
687 public:
688 Cleanup(APValue *Val, APValue::LValueBase Base, QualType T,
689 ScopeKind Scope)
690 : Value(Val, Scope), Base(Base), T(T) {}
691
692 /// Determine whether this cleanup should be performed at the end of the
693 /// given kind of scope.
694 bool isDestroyedAtEndOf(ScopeKind K) const {
695 return (int)Value.getInt() >= (int)K;
696 }
697 bool endLifetime(EvalInfo &Info, bool RunDestructors) {
698 if (RunDestructors) {
699 SourceLocation Loc;
700 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>())
701 Loc = VD->getLocation();
702 else if (const Expr *E = Base.dyn_cast<const Expr*>())
703 Loc = E->getExprLoc();
704 return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T);
705 }
706 *Value.getPointer() = APValue();
707 return true;
708 }
709
710 bool hasSideEffect() {
711 return T.isDestructedType();
712 }
713 };
714
715 /// A reference to an object whose construction we are currently evaluating.
716 struct ObjectUnderConstruction {
717 APValue::LValueBase Base;
718 ArrayRef<APValue::LValuePathEntry> Path;
719 friend bool operator==(const ObjectUnderConstruction &LHS,
720 const ObjectUnderConstruction &RHS) {
721 return LHS.Base == RHS.Base && LHS.Path == RHS.Path;
722 }
723 friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {
724 return llvm::hash_combine(Obj.Base, Obj.Path);
725 }
726 };
727 enum class ConstructionPhase {
728 None,
729 Bases,
730 AfterBases,
731 AfterFields,
732 Destroying,
733 DestroyingBases
734 };
735}
736
737namespace llvm {
738template<> struct DenseMapInfo<ObjectUnderConstruction> {
739 using Base = DenseMapInfo<APValue::LValueBase>;
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 final : public interp::State {
797 public:
798 /// CurrentCall - The top of the constexpr call stack.
799 CallStackFrame *CurrentCall;
800
801 /// CallStackDepth - The number of calls in the call stack right now.
802 unsigned CallStackDepth;
803
804 /// NextCallIndex - The next call index to assign.
805 unsigned NextCallIndex;
806
807 /// StepsLeft - The remaining number of evaluation steps we're permitted
808 /// to perform. This is essentially a limit for the number of statements
809 /// we will evaluate.
810 unsigned StepsLeft;
811
812 /// Enable the experimental new constant interpreter. If an expression is
813 /// not supported by the interpreter, an error is triggered.
814 bool EnableNewConstInterp;
815
816 /// BottomFrame - The frame in which evaluation started. This must be
817 /// initialized after CurrentCall and CallStackDepth.
818 CallStackFrame BottomFrame;
819
820 /// A stack of values whose lifetimes end at the end of some surrounding
821 /// evaluation frame.
822 llvm::SmallVector<Cleanup, 16> CleanupStack;
823
824 /// EvaluatingDecl - This is the declaration whose initializer is being
825 /// evaluated, if any.
826 APValue::LValueBase EvaluatingDecl;
827
828 enum class EvaluatingDeclKind {
829 None,
830 /// We're evaluating the construction of EvaluatingDecl.
831 Ctor,
832 /// We're evaluating the destruction of EvaluatingDecl.
833 Dtor,
834 };
835 EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None;
836
837 /// EvaluatingDeclValue - This is the value being constructed for the
838 /// declaration whose initializer is being evaluated, if any.
839 APValue *EvaluatingDeclValue;
840
841 /// Stack of loops and 'switch' statements which we're currently
842 /// breaking/continuing; null entries are used to mark unlabeled
843 /// break/continue.
844 SmallVector<const Stmt *> BreakContinueStack;
845
846 /// Set of objects that are currently being constructed.
847 llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
848 ObjectsUnderConstruction;
849
850 /// Current heap allocations, along with the location where each was
851 /// allocated. We use std::map here because we need stable addresses
852 /// for the stored APValues.
853 std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs;
854
855 /// The number of heap allocations performed so far in this evaluation.
856 unsigned NumHeapAllocs = 0;
857
858 struct EvaluatingConstructorRAII {
859 EvalInfo &EI;
860 ObjectUnderConstruction Object;
861 bool DidInsert;
862 EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
863 bool HasBases)
864 : EI(EI), Object(Object) {
865 DidInsert =
866 EI.ObjectsUnderConstruction
867 .insert({Object, HasBases ? ConstructionPhase::Bases
868 : ConstructionPhase::AfterBases})
869 .second;
870 }
871 void finishedConstructingBases() {
872 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
873 }
874 void finishedConstructingFields() {
875 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields;
876 }
877 ~EvaluatingConstructorRAII() {
878 if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
879 }
880 };
881
882 struct EvaluatingDestructorRAII {
883 EvalInfo &EI;
884 ObjectUnderConstruction Object;
885 bool DidInsert;
886 EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object)
887 : EI(EI), Object(Object) {
888 DidInsert = EI.ObjectsUnderConstruction
889 .insert({Object, ConstructionPhase::Destroying})
890 .second;
891 }
892 void startedDestroyingBases() {
893 EI.ObjectsUnderConstruction[Object] =
894 ConstructionPhase::DestroyingBases;
895 }
896 ~EvaluatingDestructorRAII() {
897 if (DidInsert)
898 EI.ObjectsUnderConstruction.erase(Object);
899 }
900 };
901
902 ConstructionPhase
903 isEvaluatingCtorDtor(APValue::LValueBase Base,
904 ArrayRef<APValue::LValuePathEntry> Path) {
905 return ObjectsUnderConstruction.lookup({Base, Path});
906 }
907
908 /// If we're currently speculatively evaluating, the outermost call stack
909 /// depth at which we can mutate state, otherwise 0.
910 unsigned SpeculativeEvaluationDepth = 0;
911
912 /// The current array initialization index, if we're performing array
913 /// initialization.
914 uint64_t ArrayInitIndex = -1;
915
916 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
917 : State(const_cast<ASTContext &>(C), S), CurrentCall(nullptr),
918 CallStackDepth(0), NextCallIndex(1),
919 StepsLeft(C.getLangOpts().ConstexprStepLimit),
920 EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp),
921 BottomFrame(*this, SourceLocation(), /*Callee=*/nullptr,
922 /*This=*/nullptr,
923 /*CallExpr=*/nullptr, CallRef()),
924 EvaluatingDecl((const ValueDecl *)nullptr),
925 EvaluatingDeclValue(nullptr) {
926 EvalMode = Mode;
927 }
928
929 ~EvalInfo() {
930 discardCleanups();
931 }
932
933 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value,
934 EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) {
935 EvaluatingDecl = Base;
936 IsEvaluatingDecl = EDK;
937 EvaluatingDeclValue = &Value;
938 }
939
940 bool CheckCallLimit(SourceLocation Loc) {
941 // Don't perform any constexpr calls (other than the call we're checking)
942 // when checking a potential constant expression.
943 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
944 return false;
945 if (NextCallIndex == 0) {
946 // NextCallIndex has wrapped around.
947 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
948 return false;
949 }
950 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
951 return true;
952 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
953 << getLangOpts().ConstexprCallDepth;
954 return false;
955 }
956
957 bool CheckArraySize(SourceLocation Loc, unsigned BitWidth,
958 uint64_t ElemCount, bool Diag) {
959 // FIXME: GH63562
960 // APValue stores array extents as unsigned,
961 // so anything that is greater that unsigned would overflow when
962 // constructing the array, we catch this here.
963 if (BitWidth > ConstantArrayType::getMaxSizeBits(Ctx) ||
964 ElemCount > uint64_t(std::numeric_limits<unsigned>::max())) {
965 if (Diag)
966 FFDiag(Loc, diag::note_constexpr_new_too_large) << ElemCount;
967 return false;
968 }
969
970 // FIXME: GH63562
971 // Arrays allocate an APValue per element.
972 // We use the number of constexpr steps as a proxy for the maximum size
973 // of arrays to avoid exhausting the system resources, as initialization
974 // of each element is likely to take some number of steps anyway.
975 uint64_t Limit = getLangOpts().ConstexprStepLimit;
976 if (Limit != 0 && ElemCount > Limit) {
977 if (Diag) {
978 FFDiag(Loc, diag::note_constexpr_new_exceeds_limits, 1)
979 << ElemCount << Limit;
980 Note(Loc, diag::note_constexpr_steps);
981 }
982 return false;
983 }
984 return true;
985 }
986
987 std::pair<CallStackFrame *, unsigned>
988 getCallFrameAndDepth(unsigned CallIndex) {
989 assert(CallIndex && "no call index in getCallFrameAndDepth");
990 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
991 // be null in this loop.
992 unsigned Depth = CallStackDepth;
993 CallStackFrame *Frame = CurrentCall;
994 while (Frame->Index > CallIndex) {
995 Frame = Frame->Caller;
996 --Depth;
997 }
998 if (Frame->Index == CallIndex)
999 return {Frame, Depth};
1000 return {nullptr, 0};
1001 }
1002
1003 bool nextStep(const Stmt *S) {
1004 if (getLangOpts().ConstexprStepLimit == 0)
1005 return true;
1006
1007 if (!StepsLeft) {
1008 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded, 1)
1009 << getLangOpts().ConstexprStepLimit;
1010 Note(S->getBeginLoc(), diag::note_constexpr_steps);
1011 return false;
1012 }
1013 --StepsLeft;
1014 return true;
1015 }
1016
1017 APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV);
1018
1019 std::optional<DynAlloc *> lookupDynamicAlloc(DynamicAllocLValue DA) {
1020 std::optional<DynAlloc *> Result;
1021 auto It = HeapAllocs.find(DA);
1022 if (It != HeapAllocs.end())
1023 Result = &It->second;
1024 return Result;
1025 }
1026
1027 /// Get the allocated storage for the given parameter of the given call.
1028 APValue *getParamSlot(CallRef Call, const ParmVarDecl *PVD) {
1029 CallStackFrame *Frame = getCallFrameAndDepth(Call.CallIndex).first;
1030 return Frame ? Frame->getTemporary(Call.getOrigParam(PVD), Call.Version)
1031 : nullptr;
1032 }
1033
1034 /// Information about a stack frame for std::allocator<T>::[de]allocate.
1035 struct StdAllocatorCaller {
1036 unsigned FrameIndex;
1037 QualType ElemType;
1038 const Expr *Call;
1039 explicit operator bool() const { return FrameIndex != 0; };
1040 };
1041
1042 StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const {
1043 for (const CallStackFrame *Call = CurrentCall; Call->Caller != nullptr;
1044 Call = Call->Caller) {
1045 const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee);
1046 if (!MD)
1047 continue;
1048 const IdentifierInfo *FnII = MD->getIdentifier();
1049 if (!FnII || !FnII->isStr(FnName))
1050 continue;
1051
1052 const auto *CTSD =
1053 dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent());
1054 if (!CTSD)
1055 continue;
1056
1057 const IdentifierInfo *ClassII = CTSD->getIdentifier();
1058 const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
1059 if (CTSD->isInStdNamespace() && ClassII &&
1060 ClassII->isStr("allocator") && TAL.size() >= 1 &&
1061 TAL[0].getKind() == TemplateArgument::Type)
1062 return {Call->Index, TAL[0].getAsType(), Call->CallExpr};
1063 }
1064
1065 return {};
1066 }
1067
1068 void performLifetimeExtension() {
1069 // Disable the cleanups for lifetime-extended temporaries.
1070 llvm::erase_if(CleanupStack, [](Cleanup &C) {
1071 return !C.isDestroyedAtEndOf(ScopeKind::FullExpression);
1072 });
1073 }
1074
1075 /// Throw away any remaining cleanups at the end of evaluation. If any
1076 /// cleanups would have had a side-effect, note that as an unmodeled
1077 /// side-effect and return false. Otherwise, return true.
1078 bool discardCleanups() {
1079 for (Cleanup &C : CleanupStack) {
1080 if (C.hasSideEffect() && !noteSideEffect()) {
1081 CleanupStack.clear();
1082 return false;
1083 }
1084 }
1085 CleanupStack.clear();
1086 return true;
1087 }
1088
1089 private:
1090 const interp::Frame *getCurrentFrame() override { return CurrentCall; }
1091
1092 unsigned getCallStackDepth() override { return CallStackDepth; }
1093 bool stepsLeft() const override { return StepsLeft > 0; }
1094
1095 public:
1096 /// Notes that we failed to evaluate an expression that other expressions
1097 /// directly depend on, and determine if we should keep evaluating. This
1098 /// should only be called if we actually intend to keep evaluating.
1099 ///
1100 /// Call noteSideEffect() instead if we may be able to ignore the value that
1101 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1102 ///
1103 /// (Foo(), 1) // use noteSideEffect
1104 /// (Foo() || true) // use noteSideEffect
1105 /// Foo() + 1 // use noteFailure
1106 [[nodiscard]] bool noteFailure() {
1107 // Failure when evaluating some expression often means there is some
1108 // subexpression whose evaluation was skipped. Therefore, (because we
1109 // don't track whether we skipped an expression when unwinding after an
1110 // evaluation failure) every evaluation failure that bubbles up from a
1111 // subexpression implies that a side-effect has potentially happened. We
1112 // skip setting the HasSideEffects flag to true until we decide to
1113 // continue evaluating after that point, which happens here.
1114 bool KeepGoing = keepEvaluatingAfterFailure();
1115 EvalStatus.HasSideEffects |= KeepGoing;
1116 return KeepGoing;
1117 }
1118
1119 class ArrayInitLoopIndex {
1120 EvalInfo &Info;
1121 uint64_t OuterIndex;
1122
1123 public:
1124 ArrayInitLoopIndex(EvalInfo &Info)
1125 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1126 Info.ArrayInitIndex = 0;
1127 }
1128 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1129
1130 operator uint64_t&() { return Info.ArrayInitIndex; }
1131 };
1132 };
1133
1134 /// Object used to treat all foldable expressions as constant expressions.
1135 struct FoldConstant {
1136 EvalInfo &Info;
1137 bool Enabled;
1138 bool HadNoPriorDiags;
1139 EvaluationMode OldMode;
1140
1141 explicit FoldConstant(EvalInfo &Info, bool Enabled)
1142 : Info(Info),
1143 Enabled(Enabled),
1144 HadNoPriorDiags(Info.EvalStatus.Diag &&
1145 Info.EvalStatus.Diag->empty() &&
1146 !Info.EvalStatus.HasSideEffects),
1147 OldMode(Info.EvalMode) {
1148 if (Enabled)
1149 Info.EvalMode = EvaluationMode::ConstantFold;
1150 }
1151 void keepDiagnostics() { Enabled = false; }
1152 ~FoldConstant() {
1153 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
1154 !Info.EvalStatus.HasSideEffects) {
1155 Info.EvalStatus.Diag->clear();
1156 Info.EvalStatus.DiagEmitted = false;
1157 }
1158 Info.EvalMode = OldMode;
1159 }
1160 };
1161
1162 /// RAII object used to set the current evaluation mode to ignore
1163 /// side-effects.
1164 struct IgnoreSideEffectsRAII {
1165 EvalInfo &Info;
1166 EvaluationMode OldMode;
1167 explicit IgnoreSideEffectsRAII(EvalInfo &Info)
1168 : Info(Info), OldMode(Info.EvalMode) {
1169 Info.EvalMode = EvaluationMode::IgnoreSideEffects;
1170 }
1171
1172 ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
1173 };
1174
1175 /// RAII object used to optionally suppress diagnostics and side-effects from
1176 /// a speculative evaluation.
1177 class SpeculativeEvaluationRAII {
1178 EvalInfo *Info = nullptr;
1179 Expr::EvalStatus OldStatus;
1180 unsigned OldSpeculativeEvaluationDepth = 0;
1181
1182 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1183 Info = Other.Info;
1184 OldStatus = Other.OldStatus;
1185 OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
1186 Other.Info = nullptr;
1187 }
1188
1189 void maybeRestoreState() {
1190 if (!Info)
1191 return;
1192
1193 Info->EvalStatus = OldStatus;
1194 Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
1195 }
1196
1197 public:
1198 SpeculativeEvaluationRAII() = default;
1199
1200 SpeculativeEvaluationRAII(
1201 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1202 : Info(&Info), OldStatus(Info.EvalStatus),
1203 OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
1204 Info.EvalStatus.Diag = NewDiag;
1205 Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
1206 }
1207
1208 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1209 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1210 moveFromAndCancel(std::move(Other));
1211 }
1212
1213 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1214 maybeRestoreState();
1215 moveFromAndCancel(std::move(Other));
1216 return *this;
1217 }
1218
1219 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1220 };
1221
1222 /// RAII object wrapping a full-expression or block scope, and handling
1223 /// the ending of the lifetime of temporaries created within it.
1224 template<ScopeKind Kind>
1225 class ScopeRAII {
1226 EvalInfo &Info;
1227 unsigned OldStackSize;
1228 public:
1229 ScopeRAII(EvalInfo &Info)
1230 : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1231 // Push a new temporary version. This is needed to distinguish between
1232 // temporaries created in different iterations of a loop.
1233 Info.CurrentCall->pushTempVersion();
1234 }
1235 bool destroy(bool RunDestructors = true) {
1236 bool OK = cleanup(Info, RunDestructors, OldStackSize);
1237 OldStackSize = std::numeric_limits<unsigned>::max();
1238 return OK;
1239 }
1240 ~ScopeRAII() {
1241 if (OldStackSize != std::numeric_limits<unsigned>::max())
1242 destroy(false);
1243 // Body moved to a static method to encourage the compiler to inline away
1244 // instances of this class.
1245 Info.CurrentCall->popTempVersion();
1246 }
1247 private:
1248 static bool cleanup(EvalInfo &Info, bool RunDestructors,
1249 unsigned OldStackSize) {
1250 assert(OldStackSize <= Info.CleanupStack.size() &&
1251 "running cleanups out of order?");
1252
1253 // Run all cleanups for a block scope, and non-lifetime-extended cleanups
1254 // for a full-expression scope.
1255 bool Success = true;
1256 for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) {
1257 if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) {
1258 if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) {
1259 Success = false;
1260 break;
1261 }
1262 }
1263 }
1264
1265 // Compact any retained cleanups.
1266 auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
1267 if (Kind != ScopeKind::Block)
1268 NewEnd =
1269 std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) {
1270 return C.isDestroyedAtEndOf(Kind);
1271 });
1272 Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
1273 return Success;
1274 }
1275 };
1276 typedef ScopeRAII<ScopeKind::Block> BlockScopeRAII;
1277 typedef ScopeRAII<ScopeKind::FullExpression> FullExpressionRAII;
1278 typedef ScopeRAII<ScopeKind::Call> CallScopeRAII;
1279}
1280
1281bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1282 CheckSubobjectKind CSK) {
1283 if (Invalid)
1284 return false;
1285 if (isOnePastTheEnd()) {
1286 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1287 << CSK;
1288 setInvalid();
1289 return false;
1290 }
1291 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1292 // must actually be at least one array element; even a VLA cannot have a
1293 // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1294 return true;
1295}
1296
1297void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1298 const Expr *E) {
1299 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1300 // Do not set the designator as invalid: we can represent this situation,
1301 // and correct handling of __builtin_object_size requires us to do so.
1302}
1303
1304void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1305 const Expr *E,
1306 const APSInt &N) {
1307 // If we're complaining, we must be able to statically determine the size of
1308 // the most derived array.
1309 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1310 Info.CCEDiag(E, diag::note_constexpr_array_index)
1311 << N << /*array*/ 0
1312 << static_cast<unsigned>(getMostDerivedArraySize());
1313 else
1314 Info.CCEDiag(E, diag::note_constexpr_array_index)
1315 << N << /*non-array*/ 1;
1316 setInvalid();
1317}
1318
1319CallStackFrame::CallStackFrame(EvalInfo &Info, SourceRange CallRange,
1320 const FunctionDecl *Callee, const LValue *This,
1321 const Expr *CallExpr, CallRef Call)
1322 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1323 CallExpr(CallExpr), Arguments(Call), CallRange(CallRange),
1324 Index(Info.NextCallIndex++) {
1325 Info.CurrentCall = this;
1326 ++Info.CallStackDepth;
1327}
1328
1329CallStackFrame::~CallStackFrame() {
1330 assert(Info.CurrentCall == this && "calls retired out of order");
1331 --Info.CallStackDepth;
1332 Info.CurrentCall = Caller;
1333}
1334
1335static bool isRead(AccessKinds AK) {
1336 return AK == AK_Read || AK == AK_ReadObjectRepresentation ||
1337 AK == AK_IsWithinLifetime || AK == AK_Dereference;
1338}
1339
1341 switch (AK) {
1342 case AK_Read:
1344 case AK_MemberCall:
1345 case AK_DynamicCast:
1346 case AK_TypeId:
1348 case AK_Dereference:
1349 return false;
1350 case AK_Assign:
1351 case AK_Increment:
1352 case AK_Decrement:
1353 case AK_Construct:
1354 case AK_Destroy:
1355 return true;
1356 }
1357 llvm_unreachable("unknown access kind");
1358}
1359
1360static bool isAnyAccess(AccessKinds AK) {
1361 return isRead(AK) || isModification(AK);
1362}
1363
1364/// Is this an access per the C++ definition?
1366 return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy &&
1367 AK != AK_IsWithinLifetime && AK != AK_Dereference;
1368}
1369
1370/// Is this kind of access valid on an indeterminate object value?
1372 switch (AK) {
1373 case AK_Read:
1374 case AK_Increment:
1375 case AK_Decrement:
1376 case AK_Dereference:
1377 // These need the object's value.
1378 return false;
1379
1382 case AK_Assign:
1383 case AK_Construct:
1384 case AK_Destroy:
1385 // Construction and destruction don't need the value.
1386 return true;
1387
1388 case AK_MemberCall:
1389 case AK_DynamicCast:
1390 case AK_TypeId:
1391 // These aren't really meaningful on scalars.
1392 return true;
1393 }
1394 llvm_unreachable("unknown access kind");
1395}
1396
1397namespace {
1398 struct ComplexValue {
1399 private:
1400 bool IsInt;
1401
1402 public:
1403 APSInt IntReal, IntImag;
1404 APFloat FloatReal, FloatImag;
1405
1406 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1407
1408 void makeComplexFloat() { IsInt = false; }
1409 bool isComplexFloat() const { return !IsInt; }
1410 APFloat &getComplexFloatReal() { return FloatReal; }
1411 APFloat &getComplexFloatImag() { return FloatImag; }
1412
1413 void makeComplexInt() { IsInt = true; }
1414 bool isComplexInt() const { return IsInt; }
1415 APSInt &getComplexIntReal() { return IntReal; }
1416 APSInt &getComplexIntImag() { return IntImag; }
1417
1418 void moveInto(APValue &v) const {
1419 if (isComplexFloat())
1420 v = APValue(FloatReal, FloatImag);
1421 else
1422 v = APValue(IntReal, IntImag);
1423 }
1424 void setFrom(const APValue &v) {
1425 assert(v.isComplexFloat() || v.isComplexInt());
1426 if (v.isComplexFloat()) {
1427 makeComplexFloat();
1428 FloatReal = v.getComplexFloatReal();
1429 FloatImag = v.getComplexFloatImag();
1430 } else {
1431 makeComplexInt();
1432 IntReal = v.getComplexIntReal();
1433 IntImag = v.getComplexIntImag();
1434 }
1435 }
1436 };
1437
1438 struct LValue {
1439 APValue::LValueBase Base;
1440 CharUnits Offset;
1441 SubobjectDesignator Designator;
1442 bool IsNullPtr : 1;
1443 bool InvalidBase : 1;
1444 // P2280R4 track if we have an unknown reference or pointer.
1445 bool AllowConstexprUnknown = false;
1446
1447 const APValue::LValueBase getLValueBase() const { return Base; }
1448 bool allowConstexprUnknown() const { return AllowConstexprUnknown; }
1449 CharUnits &getLValueOffset() { return Offset; }
1450 const CharUnits &getLValueOffset() const { return Offset; }
1451 SubobjectDesignator &getLValueDesignator() { return Designator; }
1452 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1453 bool isNullPointer() const { return IsNullPtr;}
1454
1455 unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1456 unsigned getLValueVersion() const { return Base.getVersion(); }
1457
1458 bool pointsToCompleteClass(const CXXRecordDecl *D) const {
1459 if (Designator.Entries.empty())
1460 return true;
1461
1462 return Designator.MostDerivedType->getAsCXXRecordDecl() == D;
1463 }
1464
1465 void moveInto(APValue &V) const {
1466 if (Designator.Invalid)
1467 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
1468 else {
1469 assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1470 V = APValue(Base, Offset, Designator.Entries,
1471 Designator.IsOnePastTheEnd, IsNullPtr);
1472 }
1473 if (AllowConstexprUnknown)
1474 V.setConstexprUnknown();
1475 }
1476 void setFrom(const ASTContext &Ctx, const APValue &V) {
1477 assert(V.isLValue() && "Setting LValue from a non-LValue?");
1478 Base = V.getLValueBase();
1479 Offset = V.getLValueOffset();
1480 InvalidBase = false;
1481 Designator = SubobjectDesignator(Ctx, V);
1482 IsNullPtr = V.isNullPointer();
1483 AllowConstexprUnknown = V.allowConstexprUnknown();
1484 }
1485
1486 void set(APValue::LValueBase B, bool BInvalid = false) {
1487#ifndef NDEBUG
1488 // We only allow a few types of invalid bases. Enforce that here.
1489 if (BInvalid) {
1490 const auto *E = B.get<const Expr *>();
1491 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1492 "Unexpected type of invalid base");
1493 }
1494#endif
1495
1496 Base = B;
1497 Offset = CharUnits::fromQuantity(0);
1498 InvalidBase = BInvalid;
1499 Designator = SubobjectDesignator(getType(B));
1500 IsNullPtr = false;
1501 AllowConstexprUnknown = false;
1502 }
1503
1504 void setNull(ASTContext &Ctx, QualType PointerTy) {
1505 Base = (const ValueDecl *)nullptr;
1506 Offset =
1508 InvalidBase = false;
1509 Designator = SubobjectDesignator(PointerTy->getPointeeType());
1510 IsNullPtr = true;
1511 AllowConstexprUnknown = false;
1512 }
1513
1514 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1515 set(B, true);
1516 }
1517
1518 std::string toString(ASTContext &Ctx, QualType T) const {
1519 APValue Printable;
1520 moveInto(Printable);
1521 return Printable.getAsString(Ctx, T);
1522 }
1523
1524 private:
1525 // Check that this LValue is not based on a null pointer. If it is, produce
1526 // a diagnostic and mark the designator as invalid.
1527 template <typename GenDiagType>
1528 bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
1529 if (Designator.Invalid)
1530 return false;
1531 if (IsNullPtr) {
1532 GenDiag();
1533 Designator.setInvalid();
1534 return false;
1535 }
1536 return true;
1537 }
1538
1539 public:
1540 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1541 CheckSubobjectKind CSK) {
1542 return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1543 Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1544 });
1545 }
1546
1547 bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1548 AccessKinds AK) {
1549 return checkNullPointerDiagnosingWith([&Info, E, AK] {
1550 if (AK == AccessKinds::AK_Dereference)
1551 Info.FFDiag(E, diag::note_constexpr_dereferencing_null);
1552 else
1553 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1554 });
1555 }
1556
1557 // Check this LValue refers to an object. If not, set the designator to be
1558 // invalid and emit a diagnostic.
1559 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1560 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1561 Designator.checkSubobject(Info, E, CSK);
1562 }
1563
1564 void addDecl(EvalInfo &Info, const Expr *E,
1565 const Decl *D, bool Virtual = false) {
1566 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1567 Designator.addDeclUnchecked(D, Virtual);
1568 }
1569 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1570 if (!Designator.Entries.empty()) {
1571 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1572 Designator.setInvalid();
1573 return;
1574 }
1575 if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1576 assert(!Base || getType(Base).getNonReferenceType()->isPointerType() ||
1577 getType(Base).getNonReferenceType()->isArrayType());
1578 Designator.FirstEntryIsAnUnsizedArray = true;
1579 Designator.addUnsizedArrayUnchecked(ElemTy);
1580 }
1581 }
1582 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1583 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1584 Designator.addArrayUnchecked(CAT);
1585 }
1586 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1587 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1588 Designator.addComplexUnchecked(EltTy, Imag);
1589 }
1590 void addVectorElement(EvalInfo &Info, const Expr *E, QualType EltTy,
1591 uint64_t Size, uint64_t Idx) {
1592 if (checkSubobject(Info, E, CSK_VectorElement))
1593 Designator.addVectorElementUnchecked(EltTy, Size, Idx);
1594 }
1595 void clearIsNullPointer() {
1596 IsNullPtr = false;
1597 }
1598 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1599 const APSInt &Index, CharUnits ElementSize) {
1600 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1601 // but we're not required to diagnose it and it's valid in C++.)
1602 if (!Index)
1603 return;
1604
1605 // Compute the new offset in the appropriate width, wrapping at 64 bits.
1606 // FIXME: When compiling for a 32-bit target, we should use 32-bit
1607 // offsets.
1608 uint64_t Offset64 = Offset.getQuantity();
1609 uint64_t ElemSize64 = ElementSize.getQuantity();
1610 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1611 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1612
1613 if (checkNullPointer(Info, E, CSK_ArrayIndex))
1614 Designator.adjustIndex(Info, E, Index, *this);
1615 clearIsNullPointer();
1616 }
1617 void adjustOffset(CharUnits N) {
1618 Offset += N;
1619 if (N.getQuantity())
1620 clearIsNullPointer();
1621 }
1622 };
1623
1624 struct MemberPtr {
1625 MemberPtr() {}
1626 explicit MemberPtr(const ValueDecl *Decl)
1627 : DeclAndIsDerivedMember(Decl, false) {}
1628
1629 /// The member or (direct or indirect) field referred to by this member
1630 /// pointer, or 0 if this is a null member pointer.
1631 const ValueDecl *getDecl() const {
1632 return DeclAndIsDerivedMember.getPointer();
1633 }
1634 /// Is this actually a member of some type derived from the relevant class?
1635 bool isDerivedMember() const {
1636 return DeclAndIsDerivedMember.getInt();
1637 }
1638 /// Get the class which the declaration actually lives in.
1639 const CXXRecordDecl *getContainingRecord() const {
1640 return cast<CXXRecordDecl>(
1641 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1642 }
1643
1644 void moveInto(APValue &V) const {
1645 V = APValue(getDecl(), isDerivedMember(), Path);
1646 }
1647 void setFrom(const APValue &V) {
1648 assert(V.isMemberPointer());
1649 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1650 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1651 Path.clear();
1652 llvm::append_range(Path, V.getMemberPointerPath());
1653 }
1654
1655 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1656 /// whether the member is a member of some class derived from the class type
1657 /// of the member pointer.
1658 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1659 /// Path - The path of base/derived classes from the member declaration's
1660 /// class (exclusive) to the class type of the member pointer (inclusive).
1661 SmallVector<const CXXRecordDecl*, 4> Path;
1662
1663 /// Perform a cast towards the class of the Decl (either up or down the
1664 /// hierarchy).
1665 bool castBack(const CXXRecordDecl *Class) {
1666 assert(!Path.empty());
1667 const CXXRecordDecl *Expected;
1668 if (Path.size() >= 2)
1669 Expected = Path[Path.size() - 2];
1670 else
1671 Expected = getContainingRecord();
1672 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1673 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1674 // if B does not contain the original member and is not a base or
1675 // derived class of the class containing the original member, the result
1676 // of the cast is undefined.
1677 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1678 // (D::*). We consider that to be a language defect.
1679 return false;
1680 }
1681 Path.pop_back();
1682 return true;
1683 }
1684 /// Perform a base-to-derived member pointer cast.
1685 bool castToDerived(const CXXRecordDecl *Derived) {
1686 if (!getDecl())
1687 return true;
1688 if (!isDerivedMember()) {
1689 Path.push_back(Derived);
1690 return true;
1691 }
1692 if (!castBack(Derived))
1693 return false;
1694 if (Path.empty())
1695 DeclAndIsDerivedMember.setInt(false);
1696 return true;
1697 }
1698 /// Perform a derived-to-base member pointer cast.
1699 bool castToBase(const CXXRecordDecl *Base) {
1700 if (!getDecl())
1701 return true;
1702 if (Path.empty())
1703 DeclAndIsDerivedMember.setInt(true);
1704 if (isDerivedMember()) {
1705 Path.push_back(Base);
1706 return true;
1707 }
1708 return castBack(Base);
1709 }
1710 };
1711
1712 /// Compare two member pointers, which are assumed to be of the same type.
1713 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1714 if (!LHS.getDecl() || !RHS.getDecl())
1715 return !LHS.getDecl() && !RHS.getDecl();
1716 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1717 return false;
1718 return LHS.Path == RHS.Path;
1719 }
1720}
1721
1722void SubobjectDesignator::adjustIndex(EvalInfo &Info, const Expr *E, APSInt N,
1723 const LValue &LV) {
1724 if (Invalid || !N)
1725 return;
1726 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
1727 if (isMostDerivedAnUnsizedArray()) {
1728 diagnoseUnsizedArrayPointerArithmetic(Info, E);
1729 // Can't verify -- trust that the user is doing the right thing (or if
1730 // not, trust that the caller will catch the bad behavior).
1731 // FIXME: Should we reject if this overflows, at least?
1732 Entries.back() =
1733 PathEntry::ArrayIndex(Entries.back().getAsArrayIndex() + TruncatedN);
1734 return;
1735 }
1736
1737 // [expr.add]p4: For the purposes of these operators, a pointer to a
1738 // nonarray object behaves the same as a pointer to the first element of
1739 // an array of length one with the type of the object as its element type.
1740 bool IsArray =
1741 MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement;
1742 uint64_t ArrayIndex =
1743 IsArray ? Entries.back().getAsArrayIndex() : (uint64_t)IsOnePastTheEnd;
1744 uint64_t ArraySize = IsArray ? getMostDerivedArraySize() : (uint64_t)1;
1745
1746 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
1747 if (!Info.checkingPotentialConstantExpression() ||
1748 !LV.AllowConstexprUnknown) {
1749 // Calculate the actual index in a wide enough type, so we can include
1750 // it in the note.
1751 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
1752 (llvm::APInt &)N += ArrayIndex;
1753 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
1754 diagnosePointerArithmetic(Info, E, N);
1755 }
1756 setInvalid();
1757 return;
1758 }
1759
1760 ArrayIndex += TruncatedN;
1761 assert(ArrayIndex <= ArraySize &&
1762 "bounds check succeeded for out-of-bounds index");
1763
1764 if (IsArray)
1765 Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
1766 else
1767 IsOnePastTheEnd = (ArrayIndex != 0);
1768}
1769
1770static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1771static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1772 const LValue &This, const Expr *E,
1773 bool AllowNonLiteralTypes = false);
1774static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1775 bool InvalidBaseOK = false);
1776static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1777 bool InvalidBaseOK = false);
1778static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1779 EvalInfo &Info);
1780static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1781static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1782static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1783 EvalInfo &Info);
1784static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1785static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1786static bool EvaluateMatrix(const Expr *E, APValue &Result, EvalInfo &Info);
1787static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1788 EvalInfo &Info);
1789static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1790static std::optional<uint64_t>
1791EvaluateBuiltinStrLen(const Expr *E, EvalInfo &Info,
1792 std::string *StringResult = nullptr);
1793
1794/// Evaluate an integer or fixed point expression into an APResult.
1795static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1796 EvalInfo &Info);
1797
1798/// Evaluate only a fixed point expression into an APResult.
1799static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1800 EvalInfo &Info);
1801
1802//===----------------------------------------------------------------------===//
1803// Misc utilities
1804//===----------------------------------------------------------------------===//
1805
1806/// Negate an APSInt in place, converting it to a signed form if necessary, and
1807/// preserving its value (by extending by up to one bit as needed).
1808static void negateAsSigned(APSInt &Int) {
1809 if (Int.isUnsigned() || Int.isMinSignedValue()) {
1810 Int = Int.extend(Int.getBitWidth() + 1);
1811 Int.setIsSigned(true);
1812 }
1813 Int = -Int;
1814}
1815
1816template<typename KeyT>
1817APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T,
1818 ScopeKind Scope, LValue &LV) {
1819 unsigned Version = getTempVersion();
1820 APValue::LValueBase Base(Key, Index, Version);
1821 LV.set(Base);
1822 return createLocal(Base, Key, T, Scope);
1823}
1824
1825/// Allocate storage for a parameter of a function call made in this frame.
1826APValue &CallStackFrame::createParam(CallRef Args, const ParmVarDecl *PVD,
1827 LValue &LV) {
1828 assert(Args.CallIndex == Index && "creating parameter in wrong frame");
1829 APValue::LValueBase Base(PVD, Index, Args.Version);
1830 LV.set(Base);
1831 // We always destroy parameters at the end of the call, even if we'd allow
1832 // them to live to the end of the full-expression at runtime, in order to
1833 // give portable results and match other compilers.
1834 return createLocal(Base, PVD, PVD->getType(), ScopeKind::Call);
1835}
1836
1837APValue &CallStackFrame::createLocal(APValue::LValueBase Base, const void *Key,
1838 QualType T, ScopeKind Scope) {
1839 assert(Base.getCallIndex() == Index && "lvalue for wrong frame");
1840 unsigned Version = Base.getVersion();
1841 APValue &Result = Temporaries[MapKeyTy(Key, Version)];
1842 assert(Result.isAbsent() && "local created multiple times");
1843
1844 // If we're creating a local immediately in the operand of a speculative
1845 // evaluation, don't register a cleanup to be run outside the speculative
1846 // evaluation context, since we won't actually be able to initialize this
1847 // object.
1848 if (Index <= Info.SpeculativeEvaluationDepth) {
1849 if (T.isDestructedType())
1850 Info.noteSideEffect();
1851 } else {
1852 Info.CleanupStack.push_back(Cleanup(&Result, Base, T, Scope));
1853 }
1854 return Result;
1855}
1856
1857APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) {
1858 if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) {
1859 FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded);
1860 return nullptr;
1861 }
1862
1863 DynamicAllocLValue DA(NumHeapAllocs++);
1865 auto Result = HeapAllocs.emplace(std::piecewise_construct,
1866 std::forward_as_tuple(DA), std::tuple<>());
1867 assert(Result.second && "reused a heap alloc index?");
1868 Result.first->second.AllocExpr = E;
1869 return &Result.first->second.Value;
1870}
1871
1872/// Produce a string describing the given constexpr call.
1873void CallStackFrame::describe(raw_ostream &Out) const {
1874 bool IsMemberCall = false;
1875 bool ExplicitInstanceParam = false;
1876 clang::PrintingPolicy PrintingPolicy = Info.Ctx.getPrintingPolicy();
1877 PrintingPolicy.SuppressLambdaBody = true;
1878
1879 if (const auto *MD = dyn_cast<CXXMethodDecl>(Callee)) {
1880 IsMemberCall = !isa<CXXConstructorDecl>(MD) && !MD->isStatic();
1881 ExplicitInstanceParam = MD->isExplicitObjectMemberFunction();
1882 }
1883
1884 if (!IsMemberCall)
1885 Callee->getNameForDiagnostic(Out, PrintingPolicy,
1886 /*Qualified=*/false);
1887
1888 if (This && IsMemberCall) {
1889 if (const auto *MCE = dyn_cast_if_present<CXXMemberCallExpr>(CallExpr)) {
1890 const Expr *Object = MCE->getImplicitObjectArgument();
1891 Object->printPretty(Out, /*Helper=*/nullptr, PrintingPolicy,
1892 /*Indentation=*/0);
1893 if (Object->getType()->isPointerType())
1894 Out << "->";
1895 else
1896 Out << ".";
1897 } else if (const auto *OCE =
1898 dyn_cast_if_present<CXXOperatorCallExpr>(CallExpr)) {
1899 OCE->getArg(0)->printPretty(Out, /*Helper=*/nullptr, PrintingPolicy,
1900 /*Indentation=*/0);
1901 Out << ".";
1902 } else {
1903 APValue Val;
1904 This->moveInto(Val);
1905 Val.printPretty(
1906 Out, Info.Ctx,
1907 Info.Ctx.getLValueReferenceType(This->Designator.MostDerivedType));
1908 Out << ".";
1909 }
1910 Callee->getNameForDiagnostic(Out, PrintingPolicy,
1911 /*Qualified=*/false);
1912 }
1913
1914 Out << '(';
1915
1916 llvm::ListSeparator Comma;
1917 for (const ParmVarDecl *Param :
1918 Callee->parameters().slice(ExplicitInstanceParam)) {
1919 Out << Comma;
1920 const APValue *V = Info.getParamSlot(Arguments, Param);
1921 if (V)
1922 V->printPretty(Out, Info.Ctx, Param->getType());
1923 else
1924 Out << "<...>";
1925 }
1926
1927 Out << ')';
1928}
1929
1930/// Evaluate an expression to see if it had side-effects, and discard its
1931/// result.
1932/// \return \c true if the caller should keep evaluating.
1933static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
1934 assert(!E->isValueDependent());
1935 APValue Scratch;
1936 if (!Evaluate(Scratch, Info, E))
1937 // We don't need the value, but we might have skipped a side effect here.
1938 return Info.noteSideEffect();
1939 return true;
1940}
1941
1942/// Should this call expression be treated as forming an opaque constant?
1943static bool IsOpaqueConstantCall(const CallExpr *E) {
1944 unsigned Builtin = E->getBuiltinCallee();
1945 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1946 Builtin == Builtin::BI__builtin___NSStringMakeConstantString ||
1947 Builtin == Builtin::BI__builtin_ptrauth_sign_constant ||
1948 Builtin == Builtin::BI__builtin_function_start);
1949}
1950
1951static bool IsOpaqueConstantCall(const LValue &LVal) {
1952 const auto *BaseExpr =
1953 llvm::dyn_cast_if_present<CallExpr>(LVal.Base.dyn_cast<const Expr *>());
1954 return BaseExpr && IsOpaqueConstantCall(BaseExpr);
1955}
1956
1958 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1959 // constant expression of pointer type that evaluates to...
1960
1961 // ... a null pointer value, or a prvalue core constant expression of type
1962 // std::nullptr_t.
1963 if (!B)
1964 return true;
1965
1966 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1967 // ... the address of an object with static storage duration,
1968 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1969 return VD->hasGlobalStorage();
1971 return true;
1972 // ... the address of a function,
1973 // ... the address of a GUID [MS extension],
1974 // ... the address of an unnamed global constant
1976 }
1977
1978 if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>())
1979 return true;
1980
1981 const Expr *E = B.get<const Expr*>();
1982 switch (E->getStmtClass()) {
1983 default:
1984 return false;
1985 case Expr::CompoundLiteralExprClass: {
1987 return CLE->isFileScope() && CLE->isLValue();
1988 }
1989 case Expr::MaterializeTemporaryExprClass:
1990 // A materialized temporary might have been lifetime-extended to static
1991 // storage duration.
1992 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
1993 // A string literal has static storage duration.
1994 case Expr::StringLiteralClass:
1995 case Expr::PredefinedExprClass:
1996 case Expr::ObjCStringLiteralClass:
1997 case Expr::ObjCEncodeExprClass:
1998 return true;
1999 case Expr::ObjCBoxedExprClass:
2000 case Expr::ObjCArrayLiteralClass:
2001 case Expr::ObjCDictionaryLiteralClass:
2002 return cast<ObjCObjectLiteral>(E)->isExpressibleAsConstantInitializer();
2003 case Expr::CallExprClass:
2005 // For GCC compatibility, &&label has static storage duration.
2006 case Expr::AddrLabelExprClass:
2007 return true;
2008 // A Block literal expression may be used as the initialization value for
2009 // Block variables at global or local static scope.
2010 case Expr::BlockExprClass:
2011 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
2012 // The APValue generated from a __builtin_source_location will be emitted as a
2013 // literal.
2014 case Expr::SourceLocExprClass:
2015 return true;
2016 case Expr::ImplicitValueInitExprClass:
2017 // FIXME:
2018 // We can never form an lvalue with an implicit value initialization as its
2019 // base through expression evaluation, so these only appear in one case: the
2020 // implicit variable declaration we invent when checking whether a constexpr
2021 // constructor can produce a constant expression. We must assume that such
2022 // an expression might be a global lvalue.
2023 return true;
2024 }
2025}
2026
2027static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
2028 return LVal.Base.dyn_cast<const ValueDecl*>();
2029}
2030
2031// Information about an LValueBase that is some kind of string.
2034 StringRef Bytes;
2036};
2037
2038// Gets the lvalue base of LVal as a string.
2039static bool GetLValueBaseAsString(const EvalInfo &Info, const LValue &LVal,
2040 LValueBaseString &AsString) {
2041 const auto *BaseExpr = LVal.Base.dyn_cast<const Expr *>();
2042 if (!BaseExpr)
2043 return false;
2044
2045 // For ObjCEncodeExpr, we need to compute and store the string.
2046 if (const auto *EE = dyn_cast<ObjCEncodeExpr>(BaseExpr)) {
2047 Info.Ctx.getObjCEncodingForType(EE->getEncodedType(),
2048 AsString.ObjCEncodeStorage);
2049 AsString.Bytes = AsString.ObjCEncodeStorage;
2050 AsString.CharWidth = 1;
2051 return true;
2052 }
2053
2054 // Otherwise, we have a StringLiteral.
2055 const auto *Lit = dyn_cast<StringLiteral>(BaseExpr);
2056 if (const auto *PE = dyn_cast<PredefinedExpr>(BaseExpr))
2057 Lit = PE->getFunctionName();
2058
2059 if (!Lit)
2060 return false;
2061
2062 AsString.Bytes = Lit->getBytes();
2063 AsString.CharWidth = Lit->getCharByteWidth();
2064 return true;
2065}
2066
2067// Determine whether two string literals potentially overlap. This will be the
2068// case if they agree on the values of all the bytes on the overlapping region
2069// between them.
2070//
2071// The overlapping region is the portion of the two string literals that must
2072// overlap in memory if the pointers actually point to the same address at
2073// runtime. For example, if LHS is "abcdef" + 3 and RHS is "cdef\0gh" + 1 then
2074// the overlapping region is "cdef\0", which in this case does agree, so the
2075// strings are potentially overlapping. Conversely, for "foobar" + 3 versus
2076// "bazbar" + 3, the overlapping region contains all of both strings, so they
2077// are not potentially overlapping, even though they agree from the given
2078// addresses onwards.
2079//
2080// See open core issue CWG2765 which is discussing the desired rule here.
2081static bool ArePotentiallyOverlappingStringLiterals(const EvalInfo &Info,
2082 const LValue &LHS,
2083 const LValue &RHS) {
2084 LValueBaseString LHSString, RHSString;
2085 if (!GetLValueBaseAsString(Info, LHS, LHSString) ||
2086 !GetLValueBaseAsString(Info, RHS, RHSString))
2087 return false;
2088
2089 // This is the byte offset to the location of the first character of LHS
2090 // within RHS. We don't need to look at the characters of one string that
2091 // would appear before the start of the other string if they were merged.
2092 CharUnits Offset = RHS.Offset - LHS.Offset;
2093 if (Offset.isNegative()) {
2094 if (LHSString.Bytes.size() < (size_t)-Offset.getQuantity())
2095 return false;
2096 LHSString.Bytes = LHSString.Bytes.drop_front(-Offset.getQuantity());
2097 } else {
2098 if (RHSString.Bytes.size() < (size_t)Offset.getQuantity())
2099 return false;
2100 RHSString.Bytes = RHSString.Bytes.drop_front(Offset.getQuantity());
2101 }
2102
2103 bool LHSIsLonger = LHSString.Bytes.size() > RHSString.Bytes.size();
2104 StringRef Longer = LHSIsLonger ? LHSString.Bytes : RHSString.Bytes;
2105 StringRef Shorter = LHSIsLonger ? RHSString.Bytes : LHSString.Bytes;
2106 int ShorterCharWidth = (LHSIsLonger ? RHSString : LHSString).CharWidth;
2107
2108 // The null terminator isn't included in the string data, so check for it
2109 // manually. If the longer string doesn't have a null terminator where the
2110 // shorter string ends, they aren't potentially overlapping.
2111 for (int NullByte : llvm::seq(ShorterCharWidth)) {
2112 if (Shorter.size() + NullByte >= Longer.size())
2113 break;
2114 if (Longer[Shorter.size() + NullByte])
2115 return false;
2116 }
2117
2118 // Otherwise, they're potentially overlapping if and only if the overlapping
2119 // region is the same.
2120 return Shorter == Longer.take_front(Shorter.size());
2121}
2122
2123static bool IsWeakLValue(const LValue &Value) {
2125 return Decl && Decl->isWeak();
2126}
2127
2128static bool isZeroSized(const LValue &Value) {
2130 if (isa_and_nonnull<VarDecl>(Decl)) {
2131 QualType Ty = Decl->getType();
2132 if (Ty->isArrayType())
2133 return Ty->isIncompleteType() ||
2134 Decl->getASTContext().getTypeSize(Ty) == 0;
2135 }
2136 return false;
2137}
2138
2139static bool HasSameBase(const LValue &A, const LValue &B) {
2140 if (!A.getLValueBase())
2141 return !B.getLValueBase();
2142 if (!B.getLValueBase())
2143 return false;
2144
2145 if (A.getLValueBase().getOpaqueValue() !=
2146 B.getLValueBase().getOpaqueValue())
2147 return false;
2148
2149 return A.getLValueCallIndex() == B.getLValueCallIndex() &&
2150 A.getLValueVersion() == B.getLValueVersion();
2151}
2152
2153static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
2154 assert(Base && "no location for a null lvalue");
2155 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2156
2157 // For a parameter, find the corresponding call stack frame (if it still
2158 // exists), and point at the parameter of the function definition we actually
2159 // invoked.
2160 if (auto *PVD = dyn_cast_or_null<ParmVarDecl>(VD)) {
2161 unsigned Idx = PVD->getFunctionScopeIndex();
2162 for (CallStackFrame *F = Info.CurrentCall; F; F = F->Caller) {
2163 if (F->Arguments.CallIndex == Base.getCallIndex() &&
2164 F->Arguments.Version == Base.getVersion() && F->Callee &&
2165 Idx < F->Callee->getNumParams()) {
2166 VD = F->Callee->getParamDecl(Idx);
2167 break;
2168 }
2169 }
2170 }
2171
2172 if (VD)
2173 Info.Note(VD->getLocation(), diag::note_declared_at);
2174 else if (const Expr *E = Base.dyn_cast<const Expr*>())
2175 Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
2176 else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
2177 // FIXME: Produce a note for dangling pointers too.
2178 if (std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA))
2179 Info.Note((*Alloc)->AllocExpr->getExprLoc(),
2180 diag::note_constexpr_dynamic_alloc_here);
2181 }
2182
2183 // We have no information to show for a typeid(T) object.
2184}
2185
2190
2191/// Materialized temporaries that we've already checked to determine if they're
2192/// initializsed by a constant expression.
2195
2197 EvalInfo &Info, SourceLocation DiagLoc,
2198 QualType Type, const APValue &Value,
2199 ConstantExprKind Kind,
2200 const FieldDecl *SubobjectDecl,
2201 CheckedTemporaries &CheckedTemps,
2202 bool IsCompleteClass = true);
2203
2204/// Check that this reference or pointer core constant expression is a valid
2205/// value for an address or reference constant expression. Return true if we
2206/// can fold this expression, whether or not it's a constant expression.
2207static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
2208 QualType Type, const LValue &LVal,
2209 ConstantExprKind Kind,
2210 CheckedTemporaries &CheckedTemps) {
2211 bool IsReferenceType = Type->isReferenceType();
2212
2213 APValue::LValueBase Base = LVal.getLValueBase();
2214 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
2215
2216 const Expr *BaseE = Base.dyn_cast<const Expr *>();
2217 const ValueDecl *BaseVD = Base.dyn_cast<const ValueDecl*>();
2218
2219 // Additional restrictions apply in a template argument. We only enforce the
2220 // C++20 restrictions here; additional syntactic and semantic restrictions
2221 // are applied elsewhere.
2222 if (isTemplateArgument(Kind)) {
2223 int InvalidBaseKind = -1;
2224 StringRef Ident;
2225 if (Base.is<TypeInfoLValue>())
2226 InvalidBaseKind = 0;
2227 else if (isa_and_nonnull<StringLiteral>(BaseE))
2228 InvalidBaseKind = 1;
2229 else if (isa_and_nonnull<MaterializeTemporaryExpr>(BaseE) ||
2230 isa_and_nonnull<LifetimeExtendedTemporaryDecl>(BaseVD))
2231 InvalidBaseKind = 2;
2232 else if (auto *PE = dyn_cast_or_null<PredefinedExpr>(BaseE)) {
2233 InvalidBaseKind = 3;
2234 Ident = PE->getIdentKindName();
2235 }
2236
2237 if (InvalidBaseKind != -1) {
2238 Info.FFDiag(Loc, diag::note_constexpr_invalid_template_arg)
2239 << IsReferenceType << !Designator.Entries.empty() << InvalidBaseKind
2240 << Ident;
2241 return false;
2242 }
2243 }
2244
2245 if (auto *FD = dyn_cast_or_null<FunctionDecl>(BaseVD);
2246 FD && FD->isImmediateFunction()) {
2247 Info.FFDiag(Loc, diag::note_consteval_address_accessible)
2248 << !Type->isAnyPointerType();
2249 Info.Note(FD->getLocation(), diag::note_declared_at);
2250 return false;
2251 }
2252
2253 // Check that the object is a global. Note that the fake 'this' object we
2254 // manufacture when checking potential constant expressions is conservatively
2255 // assumed to be global here.
2256 if (!IsGlobalLValue(Base)) {
2257 if (Info.getLangOpts().CPlusPlus11) {
2258 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
2259 << IsReferenceType << !Designator.Entries.empty() << !!BaseVD
2260 << BaseVD;
2261 auto *VarD = dyn_cast_or_null<VarDecl>(BaseVD);
2262 if (VarD && VarD->isConstexpr()) {
2263 // Non-static local constexpr variables have unintuitive semantics:
2264 // constexpr int a = 1;
2265 // constexpr const int *p = &a;
2266 // ... is invalid because the address of 'a' is not constant. Suggest
2267 // adding a 'static' in this case.
2268 Info.Note(VarD->getLocation(), diag::note_constexpr_not_static)
2269 << VarD
2270 << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static ");
2271 } else {
2272 NoteLValueLocation(Info, Base);
2273 }
2274 } else {
2275 Info.FFDiag(Loc);
2276 }
2277 // Don't allow references to temporaries to escape.
2278 return false;
2279 }
2280 assert((Info.checkingPotentialConstantExpression() ||
2281 LVal.getLValueCallIndex() == 0) &&
2282 "have call index for global lvalue");
2283
2284 if (LVal.allowConstexprUnknown()) {
2285 if (BaseVD) {
2286 Info.FFDiag(Loc, diag::note_constexpr_var_init_non_constant, 1) << BaseVD;
2287 NoteLValueLocation(Info, Base);
2288 } else {
2289 Info.FFDiag(Loc);
2290 }
2291 return false;
2292 }
2293
2294 if (Base.is<DynamicAllocLValue>()) {
2295 Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc)
2296 << IsReferenceType << !Designator.Entries.empty();
2297 NoteLValueLocation(Info, Base);
2298 return false;
2299 }
2300
2301 if (BaseVD) {
2302 if (const VarDecl *Var = dyn_cast<const VarDecl>(BaseVD)) {
2303 // Check if this is a thread-local variable.
2304 if (Var->getTLSKind())
2305 // FIXME: Diagnostic!
2306 return false;
2307
2308 // A dllimport variable never acts like a constant, unless we're
2309 // evaluating a value for use only in name mangling, and unless it's a
2310 // static local. For the latter case, we'd still need to evaluate the
2311 // constant expression in case we're inside a (inlined) function.
2312 if (!isForManglingOnly(Kind) && Var->hasAttr<DLLImportAttr>() &&
2313 !Var->isStaticLocal())
2314 return false;
2315
2316 // In CUDA/HIP device compilation, only device side variables have
2317 // constant addresses.
2318 if (Info.getLangOpts().CUDA && Info.getLangOpts().CUDAIsDevice &&
2319 Info.Ctx.CUDAConstantEvalCtx.NoWrongSidedVars) {
2320 if ((!Var->hasAttr<CUDADeviceAttr>() &&
2321 !Var->hasAttr<CUDAConstantAttr>() &&
2322 !Var->getType()->isCUDADeviceBuiltinSurfaceType() &&
2323 !Var->getType()->isCUDADeviceBuiltinTextureType()) ||
2324 Var->hasAttr<HIPManagedAttr>())
2325 return false;
2326 }
2327 }
2328 if (const auto *FD = dyn_cast<const FunctionDecl>(BaseVD)) {
2329 // __declspec(dllimport) must be handled very carefully:
2330 // We must never initialize an expression with the thunk in C++.
2331 // Doing otherwise would allow the same id-expression to yield
2332 // different addresses for the same function in different translation
2333 // units. However, this means that we must dynamically initialize the
2334 // expression with the contents of the import address table at runtime.
2335 //
2336 // The C language has no notion of ODR; furthermore, it has no notion of
2337 // dynamic initialization. This means that we are permitted to
2338 // perform initialization with the address of the thunk.
2339 if (Info.getLangOpts().CPlusPlus && !isForManglingOnly(Kind) &&
2340 FD->hasAttr<DLLImportAttr>())
2341 // FIXME: Diagnostic!
2342 return false;
2343 }
2344 } else if (const auto *MTE =
2345 dyn_cast_or_null<MaterializeTemporaryExpr>(BaseE)) {
2346 if (CheckedTemps.insert(MTE).second) {
2347 QualType TempType = getType(Base);
2348 if (TempType.isDestructedType()) {
2349 Info.FFDiag(MTE->getExprLoc(),
2350 diag::note_constexpr_unsupported_temporary_nontrivial_dtor)
2351 << TempType;
2352 return false;
2353 }
2354
2355 APValue *V = MTE->getOrCreateValue(false);
2356 assert(V && "evasluation result refers to uninitialised temporary");
2358 Info, MTE->getExprLoc(), TempType, *V, Kind,
2359 /*SubobjectDecl=*/nullptr, CheckedTemps))
2360 return false;
2361 }
2362 }
2363
2364 // Allow address constant expressions to be past-the-end pointers. This is
2365 // an extension: the standard requires them to point to an object.
2366 if (!IsReferenceType)
2367 return true;
2368
2369 // A reference constant expression must refer to an object.
2370 if (!Base) {
2371 // FIXME: diagnostic
2372 Info.CCEDiag(Loc);
2373 return true;
2374 }
2375
2376 // Does this refer one past the end of some object?
2377 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
2378 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
2379 << !Designator.Entries.empty() << !!BaseVD << BaseVD;
2380 NoteLValueLocation(Info, Base);
2381 }
2382
2383 return true;
2384}
2385
2386/// Member pointers are constant expressions unless they point to a
2387/// non-virtual dllimport member function.
2388static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
2389 SourceLocation Loc,
2390 QualType Type,
2391 const APValue &Value,
2392 ConstantExprKind Kind) {
2393 const ValueDecl *Member = Value.getMemberPointerDecl();
2394 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
2395 if (!FD)
2396 return true;
2397 if (FD->isImmediateFunction()) {
2398 Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0;
2399 Info.Note(FD->getLocation(), diag::note_declared_at);
2400 return false;
2401 }
2402 return isForManglingOnly(Kind) || FD->isVirtual() ||
2403 !FD->hasAttr<DLLImportAttr>();
2404}
2405
2406/// Check that this core constant expression is of literal type, and if not,
2407/// produce an appropriate diagnostic.
2408static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
2409 const LValue *This = nullptr) {
2410 // The restriction to literal types does not exist in C++23 anymore.
2411 if (Info.getLangOpts().CPlusPlus23)
2412 return true;
2413
2414 if (!E->isPRValue() || E->getType()->isLiteralType(Info.Ctx))
2415 return true;
2416
2417 // C++1y: A constant initializer for an object o [...] may also invoke
2418 // constexpr constructors for o and its subobjects even if those objects
2419 // are of non-literal class types.
2420 //
2421 // C++11 missed this detail for aggregates, so classes like this:
2422 // struct foo_t { union { int i; volatile int j; } u; };
2423 // are not (obviously) initializable like so:
2424 // __attribute__((__require_constant_initialization__))
2425 // static const foo_t x = {{0}};
2426 // because "i" is a subobject with non-literal initialization (due to the
2427 // volatile member of the union). See:
2428 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2429 // Therefore, we use the C++1y behavior.
2430 if (This && Info.EvaluatingDecl == This->getLValueBase())
2431 return true;
2432
2433 // Prvalue constant expressions must be of literal types.
2434 if (Info.getLangOpts().CPlusPlus11)
2435 Info.FFDiag(E, diag::note_constexpr_nonliteral)
2436 << E->getType();
2437 else
2438 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2439 return false;
2440}
2441
2443 EvalInfo &Info, SourceLocation DiagLoc,
2444 QualType Type, const APValue &Value,
2445 ConstantExprKind Kind,
2446 const FieldDecl *SubobjectDecl,
2447 CheckedTemporaries &CheckedTemps,
2448 bool IsCompleteClass) {
2449 if (!Value.hasValue()) {
2450 if (SubobjectDecl) {
2451 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2452 << /*(name)*/ 1 << SubobjectDecl;
2453 Info.Note(SubobjectDecl->getLocation(),
2454 diag::note_constexpr_subobject_declared_here);
2455 } else {
2456 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2457 << /*of type*/ 0 << Type;
2458 }
2459 return false;
2460 }
2461
2462 // We allow _Atomic(T) to be initialized from anything that T can be
2463 // initialized from.
2464 if (const AtomicType *AT = Type->getAs<AtomicType>())
2465 Type = AT->getValueType();
2466
2467 // Core issue 1454: For a literal constant expression of array or class type,
2468 // each subobject of its value shall have been initialized by a constant
2469 // expression.
2470 if (Value.isArray()) {
2472 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
2473 if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2474 Value.getArrayInitializedElt(I), Kind,
2475 SubobjectDecl, CheckedTemps))
2476 return false;
2477 }
2478 if (!Value.hasArrayFiller())
2479 return true;
2480 return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2481 Value.getArrayFiller(), Kind, SubobjectDecl,
2482 CheckedTemps);
2483 }
2484 if (Value.isUnion() && Value.getUnionField()) {
2485 return CheckEvaluationResult(
2486 CERK, Info, DiagLoc, Value.getUnionField()->getType(),
2487 Value.getUnionValue(), Kind, Value.getUnionField(), CheckedTemps);
2488 }
2489 if (Value.isStruct()) {
2490 auto *RD = Type->castAsRecordDecl();
2491 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2492 unsigned BaseIndex = 0;
2493 for (const CXXBaseSpecifier &BS : CD->bases()) {
2494 if (BS.isVirtual())
2495 continue;
2496 const APValue &BaseValue = Value.getStructBase(BaseIndex);
2497 if (!BaseValue.hasValue()) {
2498 SourceLocation TypeBeginLoc = BS.getBaseTypeLoc();
2499 Info.FFDiag(TypeBeginLoc, diag::note_constexpr_uninitialized_base)
2500 << BS.getType() << SourceRange(TypeBeginLoc, BS.getEndLoc());
2501 return false;
2502 }
2503 if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(), BaseValue,
2504 Kind, /*SubobjectDecl=*/nullptr,
2505 CheckedTemps, /*IsCompleteClass=*/false))
2506 return false;
2507 ++BaseIndex;
2508 }
2509 }
2510 for (const auto *I : RD->fields()) {
2511 if (I->isUnnamedBitField())
2512 continue;
2513
2514 if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),
2515 Value.getStructField(I->getFieldIndex()), Kind,
2516 I, CheckedTemps))
2517 return false;
2518 }
2519
2520 if (IsCompleteClass) {
2521 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2522 unsigned BaseIndex = 0;
2523 for (const CXXBaseSpecifier &BS : CD->vbases()) {
2524 assert(BS.isVirtual());
2525 const APValue &BaseValue = Value.getStructVirtualBase(BaseIndex);
2526 if (!BaseValue.hasValue()) {
2527 SourceLocation TypeBeginLoc = BS.getBaseTypeLoc();
2528 Info.FFDiag(TypeBeginLoc, diag::note_constexpr_uninitialized_base)
2529 << BS.getType() << SourceRange(TypeBeginLoc, BS.getEndLoc());
2530 return false;
2531 }
2532 if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(),
2533 BaseValue, Kind, /*SubobjectDecl=*/nullptr,
2534 CheckedTemps, /*IsCompleteClass=*/false))
2535 return false;
2536 ++BaseIndex;
2537 }
2538 }
2539 }
2540 }
2541
2542 if (Value.isLValue() &&
2544 LValue LVal;
2545 LVal.setFrom(Info.Ctx, Value);
2546 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Kind,
2547 CheckedTemps);
2548 }
2549
2550 if (Value.isMemberPointer() &&
2552 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Kind);
2553
2554 // Everything else is fine.
2555 return true;
2556}
2557
2558/// Check that this core constant expression value is a valid value for a
2559/// constant expression. If not, report an appropriate diagnostic. Does not
2560/// check that the expression is of literal type.
2561static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
2562 QualType Type, const APValue &Value,
2563 ConstantExprKind Kind) {
2564 // Nothing to check for a constant expression of type 'cv void'.
2565 if (Type->isVoidType())
2566 return true;
2567
2568 CheckedTemporaries CheckedTemps;
2570 Info, DiagLoc, Type, Value, Kind,
2571 /*SubobjectDecl=*/nullptr, CheckedTemps);
2572}
2573
2574/// Check that this evaluated value is fully-initialized and can be loaded by
2575/// an lvalue-to-rvalue conversion.
2576static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,
2577 QualType Type, const APValue &Value) {
2578 CheckedTemporaries CheckedTemps;
2579 return CheckEvaluationResult(
2581 ConstantExprKind::Normal, /*SubobjectDecl=*/nullptr, CheckedTemps);
2582}
2583
2584/// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless
2585/// "the allocated storage is deallocated within the evaluation".
2586static bool CheckMemoryLeaks(EvalInfo &Info) {
2587 if (!Info.HeapAllocs.empty()) {
2588 // We can still fold to a constant despite a compile-time memory leak,
2589 // so long as the heap allocation isn't referenced in the result (we check
2590 // that in CheckConstantExpression).
2591 Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr,
2592 diag::note_constexpr_memory_leak)
2593 << unsigned(Info.HeapAllocs.size() - 1);
2594 }
2595 return true;
2596}
2597
2598static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
2599 // A null base expression indicates a null pointer. These are always
2600 // evaluatable, and they are false unless the offset is zero.
2601 if (!Value.getLValueBase()) {
2602 // TODO: Should a non-null pointer with an offset of zero evaluate to true?
2603 Result = !Value.getLValueOffset().isZero();
2604 return true;
2605 }
2606
2607 // We have a non-null base. These are generally known to be true, but if it's
2608 // a weak declaration it can be null at runtime.
2609 Result = true;
2610 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
2611 return !Decl || !Decl->isWeak();
2612}
2613
2614static bool HandleConversionToBool(const APValue &Val, bool &Result) {
2615 // TODO: This function should produce notes if it fails.
2616 switch (Val.getKind()) {
2617 case APValue::None:
2619 return false;
2620 case APValue::Int:
2621 Result = Val.getInt().getBoolValue();
2622 return true;
2624 Result = Val.getFixedPoint().getBoolValue();
2625 return true;
2626 case APValue::Float:
2627 Result = !Val.getFloat().isZero();
2628 return true;
2630 Result = Val.getComplexIntReal().getBoolValue() ||
2631 Val.getComplexIntImag().getBoolValue();
2632 return true;
2634 Result = !Val.getComplexFloatReal().isZero() ||
2635 !Val.getComplexFloatImag().isZero();
2636 return true;
2637 case APValue::LValue:
2638 return EvalPointerValueAsBool(Val, Result);
2640 if (Val.getMemberPointerDecl() && Val.getMemberPointerDecl()->isWeak()) {
2641 return false;
2642 }
2644 return true;
2645 case APValue::Vector:
2646 case APValue::Matrix:
2647 case APValue::Array:
2648 case APValue::Struct:
2649 case APValue::Union:
2651 return false;
2652 }
2653
2654 llvm_unreachable("unknown APValue kind");
2655}
2656
2657static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2658 EvalInfo &Info) {
2659 assert(!E->isValueDependent());
2660 assert(E->isPRValue() && "missing lvalue-to-rvalue conv in bool condition");
2661 APValue Val;
2662 if (!Evaluate(Val, Info, E))
2663 return false;
2664 return HandleConversionToBool(Val, Result);
2665}
2666
2667template<typename T>
2668static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2669 const T &SrcValue, QualType DestType) {
2670 Info.CCEDiag(E, diag::note_constexpr_overflow) << SrcValue << DestType;
2671 if (const auto *OBT = DestType->getAs<OverflowBehaviorType>();
2672 OBT && OBT->isTrapKind()) {
2673 return false;
2674 }
2675 return Info.noteUndefinedBehavior();
2676}
2677
2678static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2679 QualType SrcType, const APFloat &Value,
2680 QualType DestType, APSInt &Result) {
2681 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2682 // Determine whether we are converting to unsigned or signed.
2683 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2684
2685 Result = APSInt(DestWidth, !DestSigned);
2686 bool ignored;
2687 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2688 & APFloat::opInvalidOp)
2689 return HandleOverflow(Info, E, Value, DestType);
2690 return true;
2691}
2692
2693/// Get rounding mode to use in evaluation of the specified expression.
2694///
2695/// If rounding mode is unknown at compile time, still try to evaluate the
2696/// expression. If the result is exact, it does not depend on rounding mode.
2697/// So return "tonearest" mode instead of "dynamic".
2698static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E) {
2699 llvm::RoundingMode RM =
2700 E->getFPFeaturesInEffect(Info.getLangOpts()).getRoundingMode();
2701 if (RM == llvm::RoundingMode::Dynamic)
2702 RM = llvm::RoundingMode::NearestTiesToEven;
2703 return RM;
2704}
2705
2706/// Check if the given floating-point evaluation result is allowed for
2707/// compile-time constant folding during translation (as opposed to mandatory
2708/// constant expression evaluation).
2710 const Expr *E,
2711 APFloat::opStatus St) {
2712 // In a constant context, assume that any dynamic rounding mode or FP
2713 // exception state matches the default floating-point environment.
2714 if (Info.InConstantContext)
2715 return true;
2716
2717 FPOptions FPO = E->getFPFeaturesInEffect(Info.getLangOpts());
2718 if ((St & APFloat::opInexact) &&
2719 FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) {
2720 // Inexact result means that it depends on rounding mode. If the requested
2721 // mode is dynamic, the evaluation cannot be made in compile time.
2722 Info.FFDiag(E, diag::note_constexpr_dynamic_rounding);
2723 return false;
2724 }
2725
2726 if ((St != APFloat::opOK) &&
2727 (FPO.getRoundingMode() == llvm::RoundingMode::Dynamic ||
2729 FPO.getAllowFEnvAccess())) {
2730 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
2731 return false;
2732 }
2733
2734 if ((St & APFloat::opStatus::opInvalidOp) &&
2736 // There is no usefully definable result.
2737 Info.FFDiag(E);
2738 return false;
2739 }
2740
2741 // FIXME: if:
2742 // - evaluation triggered other FP exception, and
2743 // - exception mode is not "ignore", and
2744 // - the expression being evaluated is not a part of global variable
2745 // initializer,
2746 // the evaluation probably need to be rejected.
2747 return true;
2748}
2749
2750static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2751 QualType SrcType, QualType DestType,
2752 APFloat &Result) {
2753 assert((isa<CastExpr>(E) || isa<CompoundAssignOperator>(E) ||
2755 "HandleFloatToFloatCast has been checked with only CastExpr, "
2756 "CompoundAssignOperator and ConvertVectorExpr. Please either validate "
2757 "the new expression or address the root cause of this usage.");
2758 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2759 APFloat::opStatus St;
2760 APFloat Value = Result;
2761 bool ignored;
2762 St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored);
2764}
2765
2766static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2767 QualType DestType, QualType SrcType,
2768 const APSInt &Value) {
2769 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2770 // Figure out if this is a truncate, extend or noop cast.
2771 // If the input is signed, do a sign extend, noop, or truncate.
2772 APSInt Result = Value.extOrTrunc(DestWidth);
2773 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2774 if (DestType->isBooleanType())
2775 Result = Value.getBoolValue();
2776 return Result;
2777}
2778
2779static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2780 const FPOptions FPO,
2781 QualType SrcType, const APSInt &Value,
2782 QualType DestType, APFloat &Result) {
2783 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2784 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2785 APFloat::opStatus St = Result.convertFromAPInt(Value, Value.isSigned(), RM);
2787}
2788
2789static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2790 APValue &Value, const FieldDecl *FD) {
2791 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2792
2793 if (!Value.isInt()) {
2794 // Trying to store a pointer-cast-to-integer into a bitfield.
2795 // FIXME: In this case, we should provide the diagnostic for casting
2796 // a pointer to an integer.
2797 assert(Value.isLValue() && "integral value neither int nor lvalue?");
2798 Info.FFDiag(E);
2799 return false;
2800 }
2801
2802 APSInt &Int = Value.getInt();
2803 unsigned OldBitWidth = Int.getBitWidth();
2804 unsigned NewBitWidth = FD->getBitWidthValue();
2805 if (NewBitWidth < OldBitWidth)
2806 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2807 return true;
2808}
2809
2810/// Perform the given integer operation, which is known to need at most BitWidth
2811/// bits, and check for overflow in the original type (if that type was not an
2812/// unsigned type).
2813template<typename Operation>
2814static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2815 const APSInt &LHS, const APSInt &RHS,
2816 unsigned BitWidth, Operation Op,
2817 APSInt &Result) {
2818 if (LHS.isUnsigned()) {
2819 Result = Op(LHS, RHS);
2820 return true;
2821 }
2822
2823 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2824 Result = Value.trunc(LHS.getBitWidth());
2825 if (Result.extend(BitWidth) != Value && !E->getType().isWrapType()) {
2826 if (Info.checkingForUndefinedBehavior())
2827 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2828 diag::warn_integer_constant_overflow)
2829 << toString(Result, 10, Result.isSigned(), /*formatAsCLiteral=*/false,
2830 /*UpperCase=*/true, /*InsertSeparators=*/true)
2831 << E->getType() << E->getSourceRange();
2832 return HandleOverflow(Info, E, Value, E->getType());
2833 }
2834 return true;
2835}
2836
2837/// Perform the given binary integer operation.
2838static bool handleIntIntBinOp(EvalInfo &Info, const BinaryOperator *E,
2839 const APSInt &LHS, BinaryOperatorKind Opcode,
2840 APSInt RHS, APSInt &Result) {
2841 bool HandleOverflowResult = true;
2842 switch (Opcode) {
2843 default:
2844 Info.FFDiag(E);
2845 return false;
2846 case BO_Mul:
2847 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2848 std::multiplies<APSInt>(), Result);
2849 case BO_Add:
2850 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2851 std::plus<APSInt>(), Result);
2852 case BO_Sub:
2853 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2854 std::minus<APSInt>(), Result);
2855 case BO_And: Result = LHS & RHS; return true;
2856 case BO_Xor: Result = LHS ^ RHS; return true;
2857 case BO_Or: Result = LHS | RHS; return true;
2858 case BO_Div:
2859 case BO_Rem:
2860 if (RHS == 0) {
2861 Info.FFDiag(E, diag::note_expr_divide_by_zero)
2862 << E->getRHS()->getSourceRange();
2863 return false;
2864 }
2865 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2866 // this operation and gives the two's complement result.
2867 if (RHS.isNegative() && RHS.isAllOnes() && LHS.isSigned() &&
2868 LHS.isMinSignedValue())
2869 HandleOverflowResult = HandleOverflow(
2870 Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
2871 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2872 return HandleOverflowResult;
2873 case BO_Shl: {
2874 if (Info.getLangOpts().OpenCL)
2875 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2876 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2877 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2878 RHS.isUnsigned());
2879 else if (RHS.isSigned() && RHS.isNegative()) {
2880 // During constant-folding, a negative shift is an opposite shift. Such
2881 // a shift is not a constant expression.
2882 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2883 if (!Info.noteUndefinedBehavior())
2884 return false;
2885 RHS = -RHS;
2886 goto shift_right;
2887 }
2888 shift_left:
2889 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2890 // the shifted type.
2891 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2892 if (SA != RHS) {
2893 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2894 << RHS << E->getType() << LHS.getBitWidth();
2895 if (!Info.noteUndefinedBehavior())
2896 return false;
2897 } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) {
2898 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2899 // operand, and must not overflow the corresponding unsigned type.
2900 // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2901 // E1 x 2^E2 module 2^N.
2902 if (LHS.isNegative()) {
2903 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2904 if (!Info.noteUndefinedBehavior())
2905 return false;
2906 } else if (LHS.countl_zero() < SA) {
2907 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2908 if (!Info.noteUndefinedBehavior())
2909 return false;
2910 }
2911 }
2912 Result = LHS << SA;
2913 return true;
2914 }
2915 case BO_Shr: {
2916 if (Info.getLangOpts().OpenCL)
2917 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2918 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2919 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2920 RHS.isUnsigned());
2921 else if (RHS.isSigned() && RHS.isNegative()) {
2922 // During constant-folding, a negative shift is an opposite shift. Such a
2923 // shift is not a constant expression.
2924 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2925 if (!Info.noteUndefinedBehavior())
2926 return false;
2927 RHS = -RHS;
2928 goto shift_left;
2929 }
2930 shift_right:
2931 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2932 // shifted type.
2933 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2934 if (SA != RHS) {
2935 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2936 << RHS << E->getType() << LHS.getBitWidth();
2937 if (!Info.noteUndefinedBehavior())
2938 return false;
2939 }
2940
2941 Result = LHS >> SA;
2942 return true;
2943 }
2944
2945 case BO_LT: Result = LHS < RHS; return true;
2946 case BO_GT: Result = LHS > RHS; return true;
2947 case BO_LE: Result = LHS <= RHS; return true;
2948 case BO_GE: Result = LHS >= RHS; return true;
2949 case BO_EQ: Result = LHS == RHS; return true;
2950 case BO_NE: Result = LHS != RHS; return true;
2951 case BO_Cmp:
2952 llvm_unreachable("BO_Cmp should be handled elsewhere");
2953 }
2954}
2955
2956/// Perform the given binary floating-point operation, in-place, on LHS.
2957static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E,
2958 APFloat &LHS, BinaryOperatorKind Opcode,
2959 const APFloat &RHS) {
2960 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2961 APFloat::opStatus St;
2962 switch (Opcode) {
2963 default:
2964 Info.FFDiag(E);
2965 return false;
2966 case BO_Mul:
2967 St = LHS.multiply(RHS, RM);
2968 break;
2969 case BO_Add:
2970 St = LHS.add(RHS, RM);
2971 break;
2972 case BO_Sub:
2973 St = LHS.subtract(RHS, RM);
2974 break;
2975 case BO_Div:
2976 // [expr.mul]p4:
2977 // If the second operand of / or % is zero the behavior is undefined.
2978 if (RHS.isZero())
2979 Info.CCEDiag(E, diag::note_expr_divide_by_zero);
2980 St = LHS.divide(RHS, RM);
2981 break;
2982 }
2983
2984 // FIXME: The standard quote below is deleted by P3899R3.
2985 // [expr.pre]p4:
2986 // If during the evaluation of an expression, the result is not
2987 // mathematically defined [...], the behavior is undefined.
2988 // FIXME: C++ rules require us to not conform to IEEE 754 here.
2989 // FIXME: The NaN check should not be applied outside of "constant contexts"
2990 // because it prevents NaN propagation and the "invalid" status is the
2991 // responsibility of checkFloatingPointResultForConstantFolding.
2992 if (LHS.isNaN()) {
2993 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
2994 return Info.noteUndefinedBehavior();
2995 }
2996
2998}
2999
3000static bool handleLogicalOpForVector(const APInt &LHSValue,
3001 BinaryOperatorKind Opcode,
3002 const APInt &RHSValue, APInt &Result) {
3003 bool LHS = (LHSValue != 0);
3004 bool RHS = (RHSValue != 0);
3005
3006 if (Opcode == BO_LAnd)
3007 Result = LHS && RHS;
3008 else
3009 Result = LHS || RHS;
3010 return true;
3011}
3012static bool handleLogicalOpForVector(const APFloat &LHSValue,
3013 BinaryOperatorKind Opcode,
3014 const APFloat &RHSValue, APInt &Result) {
3015 bool LHS = !LHSValue.isZero();
3016 bool RHS = !RHSValue.isZero();
3017
3018 if (Opcode == BO_LAnd)
3019 Result = LHS && RHS;
3020 else
3021 Result = LHS || RHS;
3022 return true;
3023}
3024
3025static bool handleLogicalOpForVector(const APValue &LHSValue,
3026 BinaryOperatorKind Opcode,
3027 const APValue &RHSValue, APInt &Result) {
3028 // The result is always an int type, however operands match the first.
3029 if (LHSValue.getKind() == APValue::Int)
3030 return handleLogicalOpForVector(LHSValue.getInt(), Opcode,
3031 RHSValue.getInt(), Result);
3032 assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
3033 return handleLogicalOpForVector(LHSValue.getFloat(), Opcode,
3034 RHSValue.getFloat(), Result);
3035}
3036
3037template <typename APTy>
3038static bool
3040 const APTy &RHSValue, APInt &Result) {
3041 switch (Opcode) {
3042 default:
3043 llvm_unreachable("unsupported binary operator");
3044 case BO_EQ:
3045 Result = (LHSValue == RHSValue);
3046 break;
3047 case BO_NE:
3048 Result = (LHSValue != RHSValue);
3049 break;
3050 case BO_LT:
3051 Result = (LHSValue < RHSValue);
3052 break;
3053 case BO_GT:
3054 Result = (LHSValue > RHSValue);
3055 break;
3056 case BO_LE:
3057 Result = (LHSValue <= RHSValue);
3058 break;
3059 case BO_GE:
3060 Result = (LHSValue >= RHSValue);
3061 break;
3062 }
3063
3064 // The boolean operations on these vector types use an instruction that
3065 // results in a mask of '-1' for the 'truth' value. Ensure that we negate 1
3066 // to -1 to make sure that we produce the correct value.
3067 Result.negate();
3068
3069 return true;
3070}
3071
3072static bool handleCompareOpForVector(const APValue &LHSValue,
3073 BinaryOperatorKind Opcode,
3074 const APValue &RHSValue, APInt &Result) {
3075 // The result is always an int type, however operands match the first.
3076 if (LHSValue.getKind() == APValue::Int)
3077 return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode,
3078 RHSValue.getInt(), Result);
3079 assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
3080 return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode,
3081 RHSValue.getFloat(), Result);
3082}
3083
3084// Perform binary operations for vector types, in place on the LHS.
3085static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E,
3086 BinaryOperatorKind Opcode,
3087 APValue &LHSValue,
3088 const APValue &RHSValue) {
3089 assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI &&
3090 "Operation not supported on vector types");
3091
3092 const auto *VT = E->getType()->castAs<VectorType>();
3093 unsigned NumElements = VT->getNumElements();
3094 QualType EltTy = VT->getElementType();
3095
3096 // In the cases (typically C as I've observed) where we aren't evaluating
3097 // constexpr but are checking for cases where the LHS isn't yet evaluatable,
3098 // just give up.
3099 if (!LHSValue.isVector()) {
3100 assert(LHSValue.isLValue() &&
3101 "A vector result that isn't a vector OR uncalculated LValue");
3102 Info.FFDiag(E);
3103 return false;
3104 }
3105
3106 assert(LHSValue.getVectorLength() == NumElements &&
3107 RHSValue.getVectorLength() == NumElements && "Different vector sizes");
3108
3109 SmallVector<APValue, 4> ResultElements;
3110
3111 for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) {
3112 APValue LHSElt = LHSValue.getVectorElt(EltNum);
3113 APValue RHSElt = RHSValue.getVectorElt(EltNum);
3114
3115 if (EltTy->isIntegerType()) {
3116 APSInt EltResult{Info.Ctx.getIntWidth(EltTy),
3117 EltTy->isUnsignedIntegerType()};
3118 bool Success = true;
3119
3120 if (BinaryOperator::isLogicalOp(Opcode))
3121 Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3122 else if (BinaryOperator::isComparisonOp(Opcode))
3123 Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3124 else
3125 Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode,
3126 RHSElt.getInt(), EltResult);
3127
3128 if (!Success) {
3129 Info.FFDiag(E);
3130 return false;
3131 }
3132 ResultElements.emplace_back(EltResult);
3133
3134 } else if (EltTy->isFloatingType()) {
3135 assert(LHSElt.getKind() == APValue::Float &&
3136 RHSElt.getKind() == APValue::Float &&
3137 "Mismatched LHS/RHS/Result Type");
3138 APFloat LHSFloat = LHSElt.getFloat();
3139
3140 if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode,
3141 RHSElt.getFloat())) {
3142 Info.FFDiag(E);
3143 return false;
3144 }
3145
3146 ResultElements.emplace_back(LHSFloat);
3147 }
3148 }
3149
3150 LHSValue = APValue(ResultElements.data(), ResultElements.size());
3151 return true;
3152}
3153
3154/// Cast an lvalue referring to a base subobject to a derived class, by
3155/// truncating the lvalue's path to the given length.
3156static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
3157 const RecordDecl *TruncatedType,
3158 unsigned TruncatedElements) {
3159 SubobjectDesignator &D = Result.Designator;
3160
3161 // Check we actually point to a derived class object.
3162 if (TruncatedElements == D.Entries.size())
3163 return true;
3164 assert(TruncatedElements >= D.MostDerivedPathLength &&
3165 "not casting to a derived class");
3166 if (!Result.checkSubobject(Info, E, CSK_Derived))
3167 return false;
3168
3169 // Truncate the path to the subobject, and remove any derived-to-base offsets.
3170 const RecordDecl *RD = TruncatedType;
3171 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
3172 if (RD->isInvalidDecl()) return false;
3173 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3174 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
3175 if (isVirtualBaseClass(D.Entries[I]))
3176 Result.Offset -= Layout.getVBaseClassOffset(Base);
3177 else
3178 Result.Offset -= Layout.getBaseClassOffset(Base);
3179 RD = Base;
3180 }
3181 D.Entries.resize(TruncatedElements);
3182 return true;
3183}
3184
3185static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3186 const CXXRecordDecl *Derived,
3187 const CXXRecordDecl *Base,
3188 const ASTRecordLayout *RL = nullptr) {
3189 if (!RL) {
3190 if (Derived->isInvalidDecl()) return false;
3191 RL = &Info.Ctx.getASTRecordLayout(Derived);
3192 }
3193
3194 Obj.addDecl(Info, E, Base, /*Virtual=*/false);
3195 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
3196 return true;
3197}
3198
3199static bool HandleLValueDirectVirtualBase(EvalInfo &Info, const Expr *E,
3200 LValue &Obj,
3201 const CXXRecordDecl *Derived,
3202 const CXXRecordDecl *Base,
3203 const ASTRecordLayout *RL = nullptr) {
3204 if (!RL) {
3205 if (Derived->isInvalidDecl())
3206 return false;
3207 RL = &Info.Ctx.getASTRecordLayout(Derived);
3208 }
3209
3210 Obj.addDecl(Info, E, Base, /*Virtual=*/true);
3211 Obj.getLValueOffset() += RL->getVBaseClassOffset(Base);
3212 return true;
3213}
3214
3215static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3216 const CXXRecordDecl *DerivedDecl,
3217 const CXXBaseSpecifier *Base) {
3218 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
3219
3220 if (!Base->isVirtual())
3221 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
3222
3223 SubobjectDesignator &D = Obj.Designator;
3224 if (D.Invalid)
3225 return false;
3226
3227 // Extract most-derived object and corresponding type.
3228 // FIXME: After implementing P2280R4 it became possible to get references
3229 // here. We do MostDerivedType->getAsCXXRecordDecl() in several other
3230 // locations and if we see crashes in those locations in the future
3231 // it may make more sense to move this fix into Lvalue::set.
3232 DerivedDecl = D.MostDerivedType.getNonReferenceType()->getAsCXXRecordDecl();
3233 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
3234 return false;
3235
3236 // Find the virtual base class.
3237 if (DerivedDecl->isInvalidDecl()) return false;
3238 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
3239 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
3240 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
3241 return true;
3242}
3243
3244static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
3245 QualType Type, LValue &Result) {
3246 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3247 PathE = E->path_end();
3248 PathI != PathE; ++PathI) {
3250 *PathI))
3251 return false;
3252 Type = (*PathI)->getType();
3253 }
3254 return true;
3255}
3256
3257/// Cast an lvalue referring to a derived class to a known base subobject.
3258static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
3259 const CXXRecordDecl *DerivedRD,
3260 const CXXRecordDecl *BaseRD) {
3261 CXXBasePaths Paths(/*FindAmbiguities=*/false,
3262 /*RecordPaths=*/true, /*DetectVirtual=*/false);
3263 if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
3264 llvm_unreachable("Class must be derived from the passed in base class!");
3265
3266 for (CXXBasePathElement &Elem : Paths.front())
3267 if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
3268 return false;
3269 return true;
3270}
3271
3272/// Update LVal to refer to the given field, which must be a member of the type
3273/// currently described by LVal.
3274static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
3275 const FieldDecl *FD,
3276 const ASTRecordLayout *RL = nullptr) {
3277 if (!RL) {
3278 const RecordDecl *RD = FD->getParent();
3279 if (RD->isInvalidDecl())
3280 return false;
3281 // There are some cases where the base is not yet complete but we haven't
3282 // disagnosed (such as in a template instantation of an attribute that
3283 // references the expression, ala enable_if). These aren't necessarily
3284 // constant expressions so we return 'false', but they might be, so we don't
3285 // diagnose.
3286 if (!RD->isCompleteDefinition())
3287 return false;
3288 RL = &Info.Ctx.getASTRecordLayout(RD);
3289 }
3290
3291 unsigned I = FD->getFieldIndex();
3292 LVal.addDecl(Info, E, FD);
3293 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
3294 return true;
3295}
3296
3297/// Update LVal to refer to the given indirect field.
3298static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
3299 LValue &LVal,
3300 const IndirectFieldDecl *IFD) {
3301 for (const auto *C : IFD->chain())
3302 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
3303 return false;
3304 return true;
3305}
3306
3311
3312/// Get the size of the given type in char units.
3313static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, QualType Type,
3315 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
3316 // extension.
3317 if (Type->isVoidType() || Type->isFunctionType()) {
3318 Size = CharUnits::One();
3319 return true;
3320 }
3321
3322 if (Type->isDependentType()) {
3323 Info.FFDiag(Loc);
3324 return false;
3325 }
3326
3327 if (!Type->isConstantSizeType()) {
3328 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
3329 // FIXME: Better diagnostic.
3330 Info.FFDiag(Loc);
3331 return false;
3332 }
3333
3334 if (SOT == SizeOfType::SizeOf)
3335 Size = Info.Ctx.getTypeSizeInChars(Type);
3336 else
3337 Size = Info.Ctx.getTypeInfoDataSizeInChars(Type).Width;
3338 return true;
3339}
3340
3341/// Update a pointer value to model pointer arithmetic.
3342/// \param Info - Information about the ongoing evaluation.
3343/// \param E - The expression being evaluated, for diagnostic purposes.
3344/// \param LVal - The pointer value to be updated.
3345/// \param EltTy - The pointee type represented by LVal.
3346/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
3347static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3348 LValue &LVal, QualType EltTy,
3349 APSInt Adjustment) {
3350 CharUnits SizeOfPointee;
3351 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
3352 return false;
3353
3354 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
3355 return true;
3356}
3357
3358static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3359 LValue &LVal, QualType EltTy,
3360 int64_t Adjustment) {
3361 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
3362 APSInt::get(Adjustment));
3363}
3364
3365/// Update an lvalue to refer to a component of a complex number.
3366/// \param Info - Information about the ongoing evaluation.
3367/// \param LVal - The lvalue to be updated.
3368/// \param EltTy - The complex number's component type.
3369/// \param Imag - False for the real component, true for the imaginary.
3370static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
3371 LValue &LVal, QualType EltTy,
3372 bool Imag) {
3373 if (Imag) {
3374 CharUnits SizeOfComponent;
3375 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
3376 return false;
3377 LVal.Offset += SizeOfComponent;
3378 }
3379 LVal.addComplex(Info, E, EltTy, Imag);
3380 return true;
3381}
3382
3383static bool HandleLValueVectorElement(EvalInfo &Info, const Expr *E,
3384 LValue &LVal, QualType EltTy,
3385 uint64_t Size, uint64_t Idx) {
3386 if (Idx) {
3387 CharUnits SizeOfElement;
3388 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfElement))
3389 return false;
3390 LVal.Offset += SizeOfElement * Idx;
3391 }
3392 LVal.addVectorElement(Info, E, EltTy, Size, Idx);
3393 return true;
3394}
3395
3396/// Try to evaluate the initializer for a variable declaration.
3397///
3398/// \param Info Information about the ongoing evaluation.
3399/// \param E An expression to be used when printing diagnostics.
3400/// \param VD The variable whose initializer should be obtained.
3401/// \param Version The version of the variable within the frame.
3402/// \param Frame The frame in which the variable was created. Must be null
3403/// if this variable is not local to the evaluation.
3404/// \param Result Filled in with a pointer to the value of the variable.
3405static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
3406 const VarDecl *VD, CallStackFrame *Frame,
3407 unsigned Version, APValue *&Result) {
3408 // C++23 [expr.const]p8 If we have a reference type allow unknown references
3409 // and pointers.
3410 bool AllowConstexprUnknown =
3411 Info.getLangOpts().CPlusPlus23 && VD->getType()->isReferenceType();
3412
3413 APValue::LValueBase Base(VD, Frame ? Frame->Index : 0, Version);
3414
3415 auto CheckUninitReference = [&](bool IsLocalVariable) {
3416 if (!Result || (!Result->hasValue() && VD->getType()->isReferenceType())) {
3417 // C++23 [expr.const]p8
3418 // ... For such an object that is not usable in constant expressions, the
3419 // dynamic type of the object is constexpr-unknown. For such a reference
3420 // that is not usable in constant expressions, the reference is treated
3421 // as binding to an unspecified object of the referenced type whose
3422 // lifetime and that of all subobjects includes the entire constant
3423 // evaluation and whose dynamic type is constexpr-unknown.
3424 //
3425 // Variables that are part of the current evaluation are not
3426 // constexpr-unknown.
3427 if (!AllowConstexprUnknown || IsLocalVariable) {
3428 if (!Info.checkingPotentialConstantExpression())
3429 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
3430 return false;
3431 }
3432 Result = nullptr;
3433 }
3434 return true;
3435 };
3436
3437 // If this is a local variable, dig out its value.
3438 if (Frame) {
3439 Result = Frame->getTemporary(VD, Version);
3440 if (Result)
3441 return CheckUninitReference(/*IsLocalVariable=*/true);
3442
3443 if (!isa<ParmVarDecl>(VD)) {
3444 // Assume variables referenced within a lambda's call operator that were
3445 // not declared within the call operator are captures and during checking
3446 // of a potential constant expression, assume they are unknown constant
3447 // expressions.
3448 assert(isLambdaCallOperator(Frame->Callee) &&
3449 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
3450 "missing value for local variable");
3451 if (Info.checkingPotentialConstantExpression())
3452 return false;
3453
3454 llvm_unreachable(
3455 "A variable in a frame should either be a local or a parameter");
3456 }
3457 }
3458
3459 // If we're currently evaluating the initializer of this declaration, use that
3460 // in-flight value.
3461 if (Info.EvaluatingDecl == Base) {
3462 Result = Info.EvaluatingDeclValue;
3463 return CheckUninitReference(/*IsLocalVariable=*/false);
3464 }
3465
3466 // P2280R4 struck the restriction that variable of reference type lifetime
3467 // should begin within the evaluation of E
3468 // Used to be C++20 [expr.const]p5.12.2:
3469 // ... its lifetime began within the evaluation of E;
3470 if (isa<ParmVarDecl>(VD)) {
3471 if (AllowConstexprUnknown) {
3472 Result = nullptr;
3473 return true;
3474 }
3475
3476 // Assume parameters of a potential constant expression are usable in
3477 // constant expressions.
3478 if (!Info.checkingPotentialConstantExpression() ||
3479 !Info.CurrentCall->Callee ||
3480 !Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
3481 if (Info.getLangOpts().CPlusPlus11) {
3482 Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown)
3483 << VD;
3484 NoteLValueLocation(Info, Base);
3485 } else {
3486 Info.FFDiag(E);
3487 }
3488 }
3489 return false;
3490 }
3491
3492 if (E->isValueDependent())
3493 return false;
3494
3495 // Dig out the initializer, and use the declaration which it's attached to.
3496 // FIXME: We should eventually check whether the variable has a reachable
3497 // initializing declaration.
3498 const Expr *Init = VD->getAnyInitializer(VD);
3499 // P2280R4 struck the restriction that variable of reference type should have
3500 // a preceding initialization.
3501 // Used to be C++20 [expr.const]p5.12:
3502 // ... reference has a preceding initialization and either ...
3503 if (!Init && !AllowConstexprUnknown) {
3504 // Don't diagnose during potential constant expression checking; an
3505 // initializer might be added later.
3506 if (!Info.checkingPotentialConstantExpression()) {
3507 Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1)
3508 << VD;
3509 NoteLValueLocation(Info, Base);
3510 }
3511 return false;
3512 }
3513
3514 // P2280R4 struck the initialization requirement for variables of reference
3515 // type so we can no longer assume we have an Init.
3516 // Used to be C++20 [expr.const]p5.12:
3517 // ... reference has a preceding initialization and either ...
3518 if (Init && Init->isValueDependent()) {
3519 // The DeclRefExpr is not value-dependent, but the variable it refers to
3520 // has a value-dependent initializer. This should only happen in
3521 // constant-folding cases, where the variable is not actually of a suitable
3522 // type for use in a constant expression (otherwise the DeclRefExpr would
3523 // have been value-dependent too), so diagnose that.
3524 assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx));
3525 if (!Info.checkingPotentialConstantExpression()) {
3526 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
3527 ? diag::note_constexpr_ltor_non_constexpr
3528 : diag::note_constexpr_ltor_non_integral, 1)
3529 << VD << VD->getType();
3530 NoteLValueLocation(Info, Base);
3531 }
3532 return false;
3533 }
3534
3535 // Check that we can fold the initializer. In C++, we will have already done
3536 // this in the cases where it matters for conformance.
3537 // P2280R4 struck the initialization requirement for variables of reference
3538 // type so we can no longer assume we have an Init.
3539 // Used to be C++20 [expr.const]p5.12:
3540 // ... reference has a preceding initialization and either ...
3541 if (Init && !VD->evaluateValue() && !AllowConstexprUnknown) {
3542 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3543 NoteLValueLocation(Info, Base);
3544 return false;
3545 }
3546
3547 // Check that the variable is actually usable in constant expressions. For a
3548 // const integral variable or a reference, we might have a non-constant
3549 // initializer that we can nonetheless evaluate the initializer for. Such
3550 // variables are not usable in constant expressions. In C++98, the
3551 // initializer also syntactically needs to be an ICE.
3552 //
3553 // FIXME: We don't diagnose cases that aren't potentially usable in constant
3554 // expressions here; doing so would regress diagnostics for things like
3555 // reading from a volatile constexpr variable.
3556 if ((Info.getLangOpts().CPlusPlus && !VD->hasConstantInitialization() &&
3557 VD->mightBeUsableInConstantExpressions(Info.Ctx) &&
3558 !AllowConstexprUnknown) ||
3559 ((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) &&
3560 !Info.getLangOpts().CPlusPlus11 && !VD->hasICEInitializer(Info.Ctx))) {
3561 if (Init) {
3562 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3563 NoteLValueLocation(Info, Base);
3564 } else {
3565 Info.CCEDiag(E);
3566 }
3567 }
3568
3569 // Never use the initializer of a weak variable, not even for constant
3570 // folding. We can't be sure that this is the definition that will be used.
3571 if (VD->isWeak()) {
3572 Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD;
3573 NoteLValueLocation(Info, Base);
3574 return false;
3575 }
3576
3577 Result = const_cast<APValue *>(VD->getEvaluatedValue());
3578
3579 if (!Result && !AllowConstexprUnknown)
3580 return false;
3581
3582 return CheckUninitReference(/*IsLocalVariable=*/false);
3583}
3584
3585/// Get the base index of the given base class within an APValue representing
3586/// the given derived class.
3587static unsigned getBaseIndex(const CXXRecordDecl *Derived,
3588 const CXXRecordDecl *Base) {
3589 Base = Base->getCanonicalDecl();
3590 unsigned Index = 0;
3591 for (const CXXBaseSpecifier &B : Derived->bases()) {
3592 if (B.isVirtual())
3593 continue;
3595 return Index;
3596 ++Index;
3597 }
3598
3599 for (const CXXBaseSpecifier &B : Derived->vbases()) {
3601 return Index;
3602 ++Index;
3603 }
3604
3605 llvm_unreachable("base class missing from derived class's bases list");
3606}
3607
3608/// Extract the value of a character from a string literal.
3609static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
3610 uint64_t Index) {
3611 assert(!isa<SourceLocExpr>(Lit) &&
3612 "SourceLocExpr should have already been converted to a StringLiteral");
3613
3614 // FIXME: Support MakeStringConstant
3615 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
3616 std::string Str;
3617 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
3618 assert(Index <= Str.size() && "Index too large");
3619 return APSInt::getUnsigned(Str.c_str()[Index]);
3620 }
3621
3622 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
3623 Lit = PE->getFunctionName();
3624 const StringLiteral *S = cast<StringLiteral>(Lit);
3625 const ConstantArrayType *CAT =
3626 Info.Ctx.getAsConstantArrayType(S->getType());
3627 assert(CAT && "string literal isn't an array");
3628 QualType CharType = CAT->getElementType();
3629 assert(CharType->isIntegerType() && "unexpected character type");
3630 APSInt Value(Info.Ctx.getTypeSize(CharType),
3631 CharType->isUnsignedIntegerType());
3632 if (Index < S->getLength())
3633 Value = S->getCodeUnit(Index);
3634 return Value;
3635}
3636
3637// Expand a string literal into an array of characters.
3638//
3639// FIXME: This is inefficient; we should probably introduce something similar
3640// to the LLVM ConstantDataArray to make this cheaper.
3641static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
3642 APValue &Result,
3643 QualType AllocType = QualType()) {
3644 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
3645 AllocType.isNull() ? S->getType() : AllocType);
3646 assert(CAT && "string literal isn't an array");
3647 QualType CharType = CAT->getElementType();
3648 assert(CharType->isIntegerType() && "unexpected character type");
3649
3650 unsigned Elts = CAT->getZExtSize();
3652 std::min(S->getLength(), Elts), Elts);
3653 APSInt Value(Info.Ctx.getTypeSize(CharType),
3654 CharType->isUnsignedIntegerType());
3655 if (Result.hasArrayFiller())
3656 Result.getArrayFiller() = APValue(Value);
3657 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
3658 Value = S->getCodeUnit(I);
3659 Result.getArrayInitializedElt(I) = APValue(Value);
3660 }
3661}
3662
3663// Expand an array so that it has more than Index filled elements.
3664static void expandArray(APValue &Array, unsigned Index) {
3665 unsigned Size = Array.getArraySize();
3666 assert(Index < Size);
3667
3668 // Always at least double the number of elements for which we store a value.
3669 unsigned OldElts = Array.getArrayInitializedElts();
3670 unsigned NewElts = std::max(Index+1, OldElts * 2);
3671 NewElts = std::min(Size, std::max(NewElts, 8u));
3672
3673 // Copy the data across.
3674 APValue NewValue(APValue::UninitArray(), NewElts, Size);
3675 for (unsigned I = 0; I != OldElts; ++I)
3676 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
3677 for (unsigned I = OldElts; I != NewElts; ++I)
3678 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
3679 if (NewValue.hasArrayFiller())
3680 NewValue.getArrayFiller() = Array.getArrayFiller();
3681 Array.swap(NewValue);
3682}
3683
3684// Expand an indeterminate vector to materialize all elements.
3685static void expandVector(APValue &Vec, unsigned NumElements) {
3686 assert(Vec.isIndeterminate());
3688 Vec = APValue(Elts.data(), Elts.size());
3689}
3690
3691/// Determine whether a type would actually be read by an lvalue-to-rvalue
3692/// conversion. If it's of class type, we may assume that the copy operation
3693/// is trivial. Note that this is never true for a union type with fields
3694/// (because the copy always "reads" the active member) and always true for
3695/// a non-class type.
3696static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD);
3698 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3699 return !RD || isReadByLvalueToRvalueConversion(RD);
3700}
3702 // FIXME: A trivial copy of a union copies the object representation, even if
3703 // the union is empty.
3704 if (RD->isUnion())
3705 return !RD->field_empty();
3706 if (RD->isEmpty())
3707 return false;
3708
3709 for (auto *Field : RD->fields())
3710 if (!Field->isUnnamedBitField() &&
3711 isReadByLvalueToRvalueConversion(Field->getType()))
3712 return true;
3713
3714 for (auto &BaseSpec : RD->bases())
3715 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
3716 return true;
3717
3718 return false;
3719}
3720
3721/// Diagnose an attempt to read from any unreadable field within the specified
3722/// type, which might be a class type.
3723static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK,
3724 QualType T) {
3725 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3726 if (!RD)
3727 return false;
3728
3729 if (!RD->hasMutableFields())
3730 return false;
3731
3732 for (auto *Field : RD->fields()) {
3733 // If we're actually going to read this field in some way, then it can't
3734 // be mutable. If we're in a union, then assigning to a mutable field
3735 // (even an empty one) can change the active member, so that's not OK.
3736 // FIXME: Add core issue number for the union case.
3737 if (Field->isMutable() &&
3738 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
3739 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field;
3740 Info.Note(Field->getLocation(), diag::note_declared_at);
3741 return true;
3742 }
3743
3744 if (diagnoseMutableFields(Info, E, AK, Field->getType()))
3745 return true;
3746 }
3747
3748 for (auto &BaseSpec : RD->bases())
3749 if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType()))
3750 return true;
3751
3752 // All mutable fields were empty, and thus not actually read.
3753 return false;
3754}
3755
3756static bool lifetimeStartedInEvaluation(EvalInfo &Info,
3758 bool MutableSubobject = false) {
3759 // A temporary or transient heap allocation we created.
3760 if (Base.getCallIndex() || Base.is<DynamicAllocLValue>())
3761 return true;
3762
3763 switch (Info.IsEvaluatingDecl) {
3764 case EvalInfo::EvaluatingDeclKind::None:
3765 return false;
3766
3767 case EvalInfo::EvaluatingDeclKind::Ctor:
3768 // The variable whose initializer we're evaluating.
3769 if (Info.EvaluatingDecl == Base)
3770 return true;
3771
3772 // A temporary lifetime-extended by the variable whose initializer we're
3773 // evaluating.
3774 if (auto *BaseE = Base.dyn_cast<const Expr *>())
3775 if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
3776 return Info.EvaluatingDecl == BaseMTE->getExtendingDecl();
3777 return false;
3778
3779 case EvalInfo::EvaluatingDeclKind::Dtor:
3780 // C++2a [expr.const]p6:
3781 // [during constant destruction] the lifetime of a and its non-mutable
3782 // subobjects (but not its mutable subobjects) [are] considered to start
3783 // within e.
3784 if (MutableSubobject || Base != Info.EvaluatingDecl)
3785 return false;
3786 // FIXME: We can meaningfully extend this to cover non-const objects, but
3787 // we will need special handling: we should be able to access only
3788 // subobjects of such objects that are themselves declared const.
3790 return T.isConstQualified() || T->isReferenceType();
3791 }
3792
3793 llvm_unreachable("unknown evaluating decl kind");
3794}
3795
3796static bool CheckArraySize(EvalInfo &Info, const ConstantArrayType *CAT,
3797 SourceLocation CallLoc = {}) {
3798 return Info.CheckArraySize(
3799 CAT->getSizeExpr() ? CAT->getSizeExpr()->getBeginLoc() : CallLoc,
3800 CAT->getNumAddressingBits(Info.Ctx), CAT->getZExtSize(),
3801 /*Diag=*/true);
3802}
3803
3804static bool handleScalarCast(EvalInfo &Info, const FPOptions FPO, const Expr *E,
3805 QualType SourceTy, QualType DestTy,
3806 APValue const &Original, APValue &Result) {
3807 // boolean must be checked before integer
3808 // since IsIntegerType() is true for bool
3809 if (SourceTy->isBooleanType()) {
3810 if (DestTy->isBooleanType()) {
3811 Result = Original;
3812 return true;
3813 }
3814 if (DestTy->isIntegerType() || DestTy->isRealFloatingType()) {
3815 bool BoolResult;
3816 if (!HandleConversionToBool(Original, BoolResult))
3817 return false;
3818 uint64_t IntResult = BoolResult;
3819 QualType IntType = DestTy->isIntegerType()
3820 ? DestTy
3821 : Info.Ctx.getIntTypeForBitwidth(64, false);
3822 Result = APValue(Info.Ctx.MakeIntValue(IntResult, IntType));
3823 }
3824 if (DestTy->isRealFloatingType()) {
3825 APValue Result2 = APValue(APFloat(0.0));
3826 if (!HandleIntToFloatCast(Info, E, FPO,
3827 Info.Ctx.getIntTypeForBitwidth(64, false),
3828 Result.getInt(), DestTy, Result2.getFloat()))
3829 return false;
3830 Result = std::move(Result2);
3831 }
3832 return true;
3833 }
3834 if (SourceTy->isIntegerType()) {
3835 if (DestTy->isRealFloatingType()) {
3836 Result = APValue(APFloat(0.0));
3837 return HandleIntToFloatCast(Info, E, FPO, SourceTy, Original.getInt(),
3838 DestTy, Result.getFloat());
3839 }
3840 if (DestTy->isBooleanType()) {
3841 bool BoolResult;
3842 if (!HandleConversionToBool(Original, BoolResult))
3843 return false;
3844 uint64_t IntResult = BoolResult;
3845 Result = APValue(Info.Ctx.MakeIntValue(IntResult, DestTy));
3846 return true;
3847 }
3848 if (DestTy->isIntegerType()) {
3849 Result = APValue(
3850 HandleIntToIntCast(Info, E, DestTy, SourceTy, Original.getInt()));
3851 return true;
3852 }
3853 } else if (SourceTy->isRealFloatingType()) {
3854 if (DestTy->isRealFloatingType()) {
3855 Result = Original;
3856 return HandleFloatToFloatCast(Info, E, SourceTy, DestTy,
3857 Result.getFloat());
3858 }
3859 if (DestTy->isBooleanType()) {
3860 bool BoolResult;
3861 if (!HandleConversionToBool(Original, BoolResult))
3862 return false;
3863 uint64_t IntResult = BoolResult;
3864 Result = APValue(Info.Ctx.MakeIntValue(IntResult, DestTy));
3865 return true;
3866 }
3867 if (DestTy->isIntegerType()) {
3868 Result = APValue(APSInt());
3869 return HandleFloatToIntCast(Info, E, SourceTy, Original.getFloat(),
3870 DestTy, Result.getInt());
3871 }
3872 }
3873
3874 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3875 return false;
3876}
3877
3878// do the heavy lifting for casting to aggregate types
3879// because we have to deal with bitfields specially
3880static bool constructAggregate(EvalInfo &Info, const FPOptions FPO,
3881 const Expr *E, APValue &Result,
3882 QualType ResultType,
3883 SmallVectorImpl<APValue> &Elements,
3884 SmallVectorImpl<QualType> &ElTypes) {
3885
3887 {&Result, ResultType, 0}};
3888
3889 unsigned ElI = 0;
3890 while (!WorkList.empty() && ElI < Elements.size()) {
3891 auto [Res, Type, BitWidth] = WorkList.pop_back_val();
3892
3893 if (Type->isRealFloatingType()) {
3894 if (!handleScalarCast(Info, FPO, E, ElTypes[ElI], Type, Elements[ElI],
3895 *Res))
3896 return false;
3897 ElI++;
3898 continue;
3899 }
3900 if (Type->isIntegerType()) {
3901 if (!handleScalarCast(Info, FPO, E, ElTypes[ElI], Type, Elements[ElI],
3902 *Res))
3903 return false;
3904 if (BitWidth > 0) {
3905 if (!Res->isInt())
3906 return false;
3907 APSInt &Int = Res->getInt();
3908 unsigned OldBitWidth = Int.getBitWidth();
3909 unsigned NewBitWidth = BitWidth;
3910 if (NewBitWidth < OldBitWidth)
3911 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
3912 }
3913 ElI++;
3914 continue;
3915 }
3916 if (Type->isVectorType()) {
3917 QualType ElTy = Type->castAs<VectorType>()->getElementType();
3918 unsigned NumEl = Type->castAs<VectorType>()->getNumElements();
3919 SmallVector<APValue> Vals(NumEl);
3920 for (unsigned I = 0; I < NumEl; ++I) {
3921 if (!handleScalarCast(Info, FPO, E, ElTypes[ElI], ElTy, Elements[ElI],
3922 Vals[I]))
3923 return false;
3924 ElI++;
3925 }
3926 *Res = APValue(Vals.data(), NumEl);
3927 continue;
3928 }
3929 if (Type->isConstantArrayType()) {
3930 QualType ElTy = cast<ConstantArrayType>(Info.Ctx.getAsArrayType(Type))
3931 ->getElementType();
3932 uint64_t Size =
3933 cast<ConstantArrayType>(Info.Ctx.getAsArrayType(Type))->getZExtSize();
3934 *Res = APValue(APValue::UninitArray(), Size, Size);
3935 for (int64_t I = Size - 1; I > -1; --I)
3936 WorkList.emplace_back(&Res->getArrayInitializedElt(I), ElTy, 0u);
3937 continue;
3938 }
3939 if (Type->isRecordType()) {
3940 const RecordDecl *RD = Type->getAsRecordDecl();
3941
3942 unsigned NumBases = 0;
3943 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
3944 NumBases = CXXRD->getNumBases();
3945
3946 *Res = APValue(APValue::UninitStruct(), NumBases, RD->getNumFields());
3947
3949 // we need to traverse backwards
3950 // Visit the base classes.
3951 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3952 if (CXXRD->getNumBases() > 0) {
3953 assert(CXXRD->getNumBases() == 1);
3954 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[0];
3955 ReverseList.emplace_back(&Res->getStructBase(0), BS.getType(), 0u);
3956 }
3957 }
3958
3959 // Visit the fields.
3960 for (FieldDecl *FD : RD->fields()) {
3961 unsigned FDBW = 0;
3962 if (FD->isUnnamedBitField())
3963 continue;
3964 if (FD->isBitField()) {
3965 FDBW = FD->getBitWidthValue();
3966 }
3967
3968 ReverseList.emplace_back(&Res->getStructField(FD->getFieldIndex()),
3969 FD->getType(), FDBW);
3970 }
3971
3972 std::reverse(ReverseList.begin(), ReverseList.end());
3973 llvm::append_range(WorkList, ReverseList);
3974 continue;
3975 }
3976 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3977 return false;
3978 }
3979 return true;
3980}
3981
3982static bool handleElementwiseCast(EvalInfo &Info, const Expr *E,
3983 const FPOptions FPO,
3984 SmallVectorImpl<APValue> &Elements,
3985 SmallVectorImpl<QualType> &SrcTypes,
3986 SmallVectorImpl<QualType> &DestTypes,
3987 SmallVectorImpl<APValue> &Results) {
3988
3989 assert((Elements.size() == SrcTypes.size()) &&
3990 (Elements.size() == DestTypes.size()));
3991
3992 for (unsigned I = 0, ESz = Elements.size(); I < ESz; ++I) {
3993 APValue Original = Elements[I];
3994 QualType SourceTy = SrcTypes[I];
3995 QualType DestTy = DestTypes[I];
3996
3997 if (!handleScalarCast(Info, FPO, E, SourceTy, DestTy, Original, Results[I]))
3998 return false;
3999 }
4000 return true;
4001}
4002
4003static unsigned elementwiseSize(EvalInfo &Info, QualType BaseTy) {
4004
4005 SmallVector<QualType> WorkList = {BaseTy};
4006
4007 unsigned Size = 0;
4008 while (!WorkList.empty()) {
4009 QualType Type = WorkList.pop_back_val();
4011 Type->isBooleanType()) {
4012 ++Size;
4013 continue;
4014 }
4015 if (Type->isVectorType()) {
4016 unsigned NumEl = Type->castAs<VectorType>()->getNumElements();
4017 Size += NumEl;
4018 continue;
4019 }
4020 if (Type->isConstantMatrixType()) {
4021 unsigned NumEl =
4022 Type->castAs<ConstantMatrixType>()->getNumElementsFlattened();
4023 Size += NumEl;
4024 continue;
4025 }
4026 if (Type->isConstantArrayType()) {
4027 QualType ElTy = cast<ConstantArrayType>(Info.Ctx.getAsArrayType(Type))
4028 ->getElementType();
4029 uint64_t ArrSize =
4030 cast<ConstantArrayType>(Info.Ctx.getAsArrayType(Type))->getZExtSize();
4031 for (uint64_t I = 0; I < ArrSize; ++I) {
4032 WorkList.push_back(ElTy);
4033 }
4034 continue;
4035 }
4036 if (Type->isRecordType()) {
4037 const RecordDecl *RD = Type->getAsRecordDecl();
4038
4039 // Visit the base classes.
4040 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
4041 if (CXXRD->getNumBases() > 0) {
4042 assert(CXXRD->getNumBases() == 1);
4043 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[0];
4044 WorkList.push_back(BS.getType());
4045 }
4046 }
4047
4048 // visit the fields.
4049 for (FieldDecl *FD : RD->fields()) {
4050 if (FD->isUnnamedBitField())
4051 continue;
4052 WorkList.push_back(FD->getType());
4053 }
4054 continue;
4055 }
4056 }
4057 return Size;
4058}
4059
4060static bool hlslAggSplatHelper(EvalInfo &Info, const Expr *E, APValue &SrcVal,
4061 QualType &SrcTy) {
4062 SrcTy = E->getType();
4063
4064 if (!Evaluate(SrcVal, Info, E))
4065 return false;
4066
4067 assert((SrcVal.isFloat() || SrcVal.isInt() ||
4068 (SrcVal.isVector() && SrcVal.getVectorLength() == 1)) &&
4069 "Not a valid HLSLAggregateSplatCast.");
4070
4071 if (SrcVal.isVector()) {
4072 assert(SrcTy->isVectorType() && "Type mismatch.");
4073 SrcTy = SrcTy->castAs<VectorType>()->getElementType();
4074 SrcVal = SrcVal.getVectorElt(0);
4075 }
4076 if (SrcVal.isMatrix()) {
4077 assert(SrcTy->isConstantMatrixType() && "Type mismatch.");
4078 SrcTy = SrcTy->castAs<ConstantMatrixType>()->getElementType();
4079 SrcVal = SrcVal.getMatrixElt(0, 0);
4080 }
4081 return true;
4082}
4083
4084static bool flattenAPValue(EvalInfo &Info, const Expr *E, APValue Value,
4085 QualType BaseTy, SmallVectorImpl<APValue> &Elements,
4086 SmallVectorImpl<QualType> &Types, unsigned Size) {
4087
4088 SmallVector<std::pair<APValue, QualType>> WorkList = {{Value, BaseTy}};
4089 unsigned Populated = 0;
4090 while (!WorkList.empty() && Populated < Size) {
4091 auto [Work, Type] = WorkList.pop_back_val();
4092
4093 if (Work.isFloat() || Work.isInt()) {
4094 Elements.push_back(Work);
4095 Types.push_back(Type);
4096 Populated++;
4097 continue;
4098 }
4099 if (Work.isVector()) {
4100 assert(Type->isVectorType() && "Type mismatch.");
4101 QualType ElTy = Type->castAs<VectorType>()->getElementType();
4102 for (unsigned I = 0; I < Work.getVectorLength() && Populated < Size;
4103 I++) {
4104 Elements.push_back(Work.getVectorElt(I));
4105 Types.push_back(ElTy);
4106 Populated++;
4107 }
4108 continue;
4109 }
4110 if (Work.isMatrix()) {
4111 assert(Type->isConstantMatrixType() && "Type mismatch.");
4112 const auto *MT = Type->castAs<ConstantMatrixType>();
4113 QualType ElTy = MT->getElementType();
4114 // Matrix elements are flattened in row-major order.
4115 for (unsigned Row = 0; Row < Work.getMatrixNumRows() && Populated < Size;
4116 Row++) {
4117 for (unsigned Col = 0;
4118 Col < Work.getMatrixNumColumns() && Populated < Size; Col++) {
4119 Elements.push_back(Work.getMatrixElt(Row, Col));
4120 Types.push_back(ElTy);
4121 Populated++;
4122 }
4123 }
4124 continue;
4125 }
4126 if (Work.isArray()) {
4127 assert(Type->isConstantArrayType() && "Type mismatch.");
4128 QualType ElTy = cast<ConstantArrayType>(Info.Ctx.getAsArrayType(Type))
4129 ->getElementType();
4130 for (int64_t I = Work.getArraySize() - 1; I > -1; --I) {
4131 WorkList.emplace_back(Work.getArrayInitializedElt(I), ElTy);
4132 }
4133 continue;
4134 }
4135
4136 if (Work.isStruct()) {
4137 assert(Type->isRecordType() && "Type mismatch.");
4138
4139 const RecordDecl *RD = Type->getAsRecordDecl();
4140
4142 // Visit the fields.
4143 for (FieldDecl *FD : RD->fields()) {
4144 if (FD->isUnnamedBitField())
4145 continue;
4146 ReverseList.emplace_back(Work.getStructField(FD->getFieldIndex()),
4147 FD->getType());
4148 }
4149
4150 std::reverse(ReverseList.begin(), ReverseList.end());
4151 llvm::append_range(WorkList, ReverseList);
4152
4153 // Visit the base classes.
4154 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
4155 if (CXXRD->getNumBases() > 0) {
4156 assert(CXXRD->getNumBases() == 1);
4157 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[0];
4158 const APValue &Base = Work.getStructBase(0);
4159
4160 // Can happen in error cases.
4161 if (!Base.isStruct())
4162 return false;
4163
4164 WorkList.emplace_back(Base, BS.getType());
4165 }
4166 }
4167 continue;
4168 }
4169 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
4170 return false;
4171 }
4172 return true;
4173}
4174
4175namespace {
4176/// A handle to a complete object (an object that is not a subobject of
4177/// another object).
4178struct CompleteObject {
4179 /// The identity of the object.
4180 APValue::LValueBase Base;
4181 /// The value of the complete object.
4182 APValue *Value;
4183 /// The type of the complete object.
4184 QualType Type;
4185
4186 CompleteObject() : Value(nullptr) {}
4187 CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
4188 : Base(Base), Value(Value), Type(Type) {}
4189
4190 bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const {
4191 // If this isn't a "real" access (eg, if it's just accessing the type
4192 // info), allow it. We assume the type doesn't change dynamically for
4193 // subobjects of constexpr objects (even though we'd hit UB here if it
4194 // did). FIXME: Is this right?
4195 if (!isAnyAccess(AK))
4196 return true;
4197
4198 // In C++14 onwards, it is permitted to read a mutable member whose
4199 // lifetime began within the evaluation.
4200 // FIXME: Should we also allow this in C++11?
4201 if (!Info.getLangOpts().CPlusPlus14 &&
4202 AK != AccessKinds::AK_IsWithinLifetime)
4203 return false;
4204 return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);
4205 }
4206
4207 explicit operator bool() const { return !Type.isNull(); }
4208};
4209} // end anonymous namespace
4210
4211static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
4212 bool IsMutable = false) {
4213 // C++ [basic.type.qualifier]p1:
4214 // - A const object is an object of type const T or a non-mutable subobject
4215 // of a const object.
4216 if (ObjType.isConstQualified() && !IsMutable)
4217 SubobjType.addConst();
4218 // - A volatile object is an object of type const T or a subobject of a
4219 // volatile object.
4220 if (ObjType.isVolatileQualified())
4221 SubobjType.addVolatile();
4222 return SubobjType;
4223}
4224
4225/// Find the designated sub-object of an rvalue.
4226template <typename SubobjectHandler>
4227static typename SubobjectHandler::result_type
4228findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
4229 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
4230 if (Sub.Invalid)
4231 // A diagnostic will have already been produced.
4232 return handler.failed();
4233 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
4234 if (Info.getLangOpts().CPlusPlus11)
4235 Info.FFDiag(E, Sub.isOnePastTheEnd()
4236 ? diag::note_constexpr_access_past_end
4237 : diag::note_constexpr_access_unsized_array)
4238 << handler.AccessKind;
4239 else
4240 Info.FFDiag(E);
4241 return handler.failed();
4242 }
4243
4244 APValue *O = Obj.Value;
4245 QualType ObjType = Obj.Type;
4246 const FieldDecl *LastField = nullptr;
4247 const FieldDecl *VolatileField = nullptr;
4248
4249 // Walk the designator's path to find the subobject.
4250 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
4251 // Reading an indeterminate value is undefined, but assigning over one is OK.
4252 if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) ||
4253 (O->isIndeterminate() &&
4254 !isValidIndeterminateAccess(handler.AccessKind))) {
4255 // Object has ended lifetime.
4256 // If I is non-zero, some subobject (member or array element) of a
4257 // complete object has ended its lifetime, so this is valid for
4258 // IsWithinLifetime, resulting in false.
4259 if (I != 0 && handler.AccessKind == AK_IsWithinLifetime)
4260 return false;
4261 if (!Info.checkingPotentialConstantExpression()) {
4262 Info.FFDiag(E, diag::note_constexpr_access_uninit)
4263 << handler.AccessKind << O->isIndeterminate()
4264 << E->getSourceRange();
4265 NoteLValueLocation(Info, Obj.Base);
4266 }
4267 return handler.failed();
4268 }
4269
4270 // C++ [class.ctor]p5, C++ [class.dtor]p5:
4271 // const and volatile semantics are not applied on an object under
4272 // {con,de}struction.
4273 if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
4274 ObjType->isRecordType() &&
4275 Info.isEvaluatingCtorDtor(
4276 Obj.Base, ArrayRef(Sub.Entries.begin(), Sub.Entries.begin() + I)) !=
4277 ConstructionPhase::None) {
4278 ObjType = Info.Ctx.getCanonicalType(ObjType);
4279 ObjType.removeLocalConst();
4280 ObjType.removeLocalVolatile();
4281 }
4282
4283 // If this is our last pass, check that the final object type is OK.
4284 if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
4285 // Accesses to volatile objects are prohibited.
4286 if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
4287 if (Info.getLangOpts().CPlusPlus) {
4288 int DiagKind;
4289 SourceLocation Loc;
4290 const NamedDecl *Decl = nullptr;
4291 if (VolatileField) {
4292 DiagKind = 2;
4293 Loc = VolatileField->getLocation();
4294 Decl = VolatileField;
4295 } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
4296 DiagKind = 1;
4297 Loc = VD->getLocation();
4298 Decl = VD;
4299 } else {
4300 DiagKind = 0;
4301 if (auto *E = Obj.Base.dyn_cast<const Expr *>())
4302 Loc = E->getExprLoc();
4303 }
4304 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
4305 << handler.AccessKind << DiagKind << Decl;
4306 Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
4307 } else {
4308 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
4309 }
4310 return handler.failed();
4311 }
4312
4313 // If we are reading an object of class type, there may still be more
4314 // things we need to check: if there are any mutable subobjects, we
4315 // cannot perform this read. (This only happens when performing a trivial
4316 // copy or assignment.)
4317 if (ObjType->isRecordType() &&
4318 !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
4319 diagnoseMutableFields(Info, E, handler.AccessKind, ObjType))
4320 return handler.failed();
4321 }
4322
4323 if (I == N) {
4324 if (!handler.found(*O, ObjType, Obj.Base))
4325 return false;
4326
4327 // If we modified a bit-field, truncate it to the right width.
4328 if (isModification(handler.AccessKind) &&
4329 LastField && LastField->isBitField() &&
4330 !truncateBitfieldValue(Info, E, *O, LastField))
4331 return false;
4332
4333 return true;
4334 }
4335
4336 LastField = nullptr;
4337
4338 // The value of an atomic object is represented like a value of the
4339 // underlying type, so look through the _Atomic wrapper.
4340 if (const AtomicType *AT = ObjType->getAs<AtomicType>())
4341 ObjType = Info.Ctx.getQualifiedType(AT->getValueType(),
4342 ObjType.getQualifiers());
4343
4344 if (ObjType->isArrayType()) {
4345 // Next subobject is an array element.
4346 const ArrayType *AT = Info.Ctx.getAsArrayType(ObjType);
4348 "vla in literal type?");
4349 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
4350 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT);
4351 CAT && CAT->getSize().ule(Index)) {
4352 // Note, it should not be possible to form a pointer with a valid
4353 // designator which points more than one past the end of the array.
4354 if (Info.getLangOpts().CPlusPlus11)
4355 Info.FFDiag(E, diag::note_constexpr_access_past_end)
4356 << handler.AccessKind;
4357 else
4358 Info.FFDiag(E);
4359 return handler.failed();
4360 }
4361
4362 ObjType = AT->getElementType();
4363
4364 if (O->getArrayInitializedElts() > Index)
4365 O = &O->getArrayInitializedElt(Index);
4366 else if (!isRead(handler.AccessKind)) {
4367 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT);
4368 CAT && !CheckArraySize(Info, CAT, E->getExprLoc()))
4369 return handler.failed();
4370
4371 expandArray(*O, Index);
4372 O = &O->getArrayInitializedElt(Index);
4373 } else
4374 O = &O->getArrayFiller();
4375 } else if (ObjType->isAnyComplexType()) {
4376 // Next subobject is a complex number.
4377 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
4378 if (Index > 1) {
4379 if (Info.getLangOpts().CPlusPlus11)
4380 Info.FFDiag(E, diag::note_constexpr_access_past_end)
4381 << handler.AccessKind;
4382 else
4383 Info.FFDiag(E);
4384 return handler.failed();
4385 }
4386
4387 ObjType = getSubobjectType(
4388 ObjType, ObjType->castAs<ComplexType>()->getElementType());
4389
4390 assert(I == N - 1 && "extracting subobject of scalar?");
4391 if (O->isComplexInt()) {
4392 return handler.found(Index ? O->getComplexIntImag()
4393 : O->getComplexIntReal(), ObjType);
4394 } else {
4395 assert(O->isComplexFloat());
4396 return handler.found(Index ? O->getComplexFloatImag()
4397 : O->getComplexFloatReal(), ObjType);
4398 }
4399 } else if (const auto *VT = ObjType->getAs<VectorType>()) {
4400 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
4401 unsigned NumElements = VT->getNumElements();
4402 if (Index == NumElements) {
4403 if (Info.getLangOpts().CPlusPlus11)
4404 Info.FFDiag(E, diag::note_constexpr_access_past_end)
4405 << handler.AccessKind;
4406 else
4407 Info.FFDiag(E);
4408 return handler.failed();
4409 }
4410
4411 if (Index > NumElements) {
4412 Info.CCEDiag(E, diag::note_constexpr_array_index)
4413 << Index << /*array*/ 0 << NumElements;
4414 return handler.failed();
4415 }
4416
4417 ObjType = VT->getElementType();
4418 assert(I == N - 1 && "extracting subobject of scalar?");
4419
4420 if (O->isIndeterminate()) {
4421 if (isRead(handler.AccessKind)) {
4422 Info.FFDiag(E);
4423 return handler.failed();
4424 }
4425 expandVector(*O, NumElements);
4426 }
4427 assert(O->isVector() && "unexpected object during vector element access");
4428 return handler.found(O->getVectorElt(Index), ObjType, Obj.Base);
4429 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
4430 if (Field->isMutable() &&
4431 !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) {
4432 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
4433 << handler.AccessKind << Field;
4434 Info.Note(Field->getLocation(), diag::note_declared_at);
4435 return handler.failed();
4436 }
4437
4438 // Next subobject is a class, struct or union field.
4439 RecordDecl *RD = ObjType->castAsCanonical<RecordType>()->getDecl();
4440 if (RD->isUnion()) {
4441 const FieldDecl *UnionField = O->getUnionField();
4442 if (!UnionField ||
4443 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
4444 if (I == N - 1 && handler.AccessKind == AK_Construct) {
4445 // Placement new onto an inactive union member makes it active.
4446 O->setUnion(Field, APValue());
4447 } else {
4448 // Pointer to/into inactive union member: Not within lifetime
4449 if (handler.AccessKind == AK_IsWithinLifetime)
4450 return false;
4451 // FIXME: If O->getUnionValue() is absent, report that there's no
4452 // active union member rather than reporting the prior active union
4453 // member. We'll need to fix nullptr_t to not use APValue() as its
4454 // representation first.
4455 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
4456 << handler.AccessKind << Field << !UnionField << UnionField;
4457 return handler.failed();
4458 }
4459 }
4460 O = &O->getUnionValue();
4461 } else
4462 O = &O->getStructField(Field->getFieldIndex());
4463
4464 ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
4465 LastField = Field;
4466 if (Field->getType().isVolatileQualified())
4467 VolatileField = Field;
4468 } else {
4469 // Next subobject is a base class.
4470 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
4471 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
4472
4473 unsigned BaseIndex = getBaseIndex(Derived, Base);
4474 unsigned NumNonVirtualBases = O->getStructNumBases();
4475 if (BaseIndex >= NumNonVirtualBases) {
4476 O = &O->getStructVirtualBase(BaseIndex - NumNonVirtualBases);
4477 } else
4478 O = &O->getStructBase(BaseIndex);
4479
4480 ObjType = getSubobjectType(ObjType, Info.Ctx.getCanonicalTagType(Base));
4481 }
4482 }
4483}
4484
4485namespace {
4486struct ExtractSubobjectHandler {
4487 EvalInfo &Info;
4488 const Expr *E;
4489 APValue &Result;
4490 const AccessKinds AccessKind;
4491
4492 typedef bool result_type;
4493 bool failed() { return false; }
4494 bool found(APValue &Subobj, QualType SubobjType, APValue::LValueBase Base) {
4495 Result = Subobj;
4496 if (AccessKind == AK_ReadObjectRepresentation)
4497 return true;
4498 return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
4499 }
4500 bool found(APSInt &Value, QualType SubobjType) {
4501 Result = APValue(Value);
4502 return true;
4503 }
4504 bool found(APFloat &Value, QualType SubobjType) {
4505 Result = APValue(Value);
4506 return true;
4507 }
4508};
4509} // end anonymous namespace
4510
4511/// Extract the designated sub-object of an rvalue.
4512static bool extractSubobject(EvalInfo &Info, const Expr *E,
4513 const CompleteObject &Obj,
4514 const SubobjectDesignator &Sub, APValue &Result,
4515 AccessKinds AK = AK_Read) {
4516 assert(AK == AK_Read || AK == AK_ReadObjectRepresentation);
4517 ExtractSubobjectHandler Handler = {Info, E, Result, AK};
4518 return findSubobject(Info, E, Obj, Sub, Handler);
4519}
4520
4521namespace {
4522struct ModifySubobjectHandler {
4523 EvalInfo &Info;
4524 APValue &NewVal;
4525 const Expr *E;
4526
4527 typedef bool result_type;
4528 static const AccessKinds AccessKind = AK_Assign;
4529
4530 bool checkConst(QualType QT) {
4531 // Assigning to a const object has undefined behavior.
4532 if (QT.isConstQualified()) {
4533 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4534 return false;
4535 }
4536 return true;
4537 }
4538
4539 bool failed() { return false; }
4540 bool found(APValue &Subobj, QualType SubobjType, APValue::LValueBase Base) {
4541 if (!checkConst(SubobjType))
4542 return false;
4543 // We've been given ownership of NewVal, so just swap it in.
4544 Subobj.swap(NewVal);
4545 return true;
4546 }
4547 bool found(APSInt &Value, QualType SubobjType) {
4548 if (!checkConst(SubobjType))
4549 return false;
4550 if (!NewVal.isInt()) {
4551 // Maybe trying to write a cast pointer value into a complex?
4552 Info.FFDiag(E);
4553 return false;
4554 }
4555 Value = NewVal.getInt();
4556 return true;
4557 }
4558 bool found(APFloat &Value, QualType SubobjType) {
4559 if (!checkConst(SubobjType))
4560 return false;
4561 Value = NewVal.getFloat();
4562 return true;
4563 }
4564};
4565} // end anonymous namespace
4566
4567const AccessKinds ModifySubobjectHandler::AccessKind;
4568
4569/// Update the designated sub-object of an rvalue to the given value.
4570static bool modifySubobject(EvalInfo &Info, const Expr *E,
4571 const CompleteObject &Obj,
4572 const SubobjectDesignator &Sub,
4573 APValue &NewVal) {
4574 ModifySubobjectHandler Handler = { Info, NewVal, E };
4575 return findSubobject(Info, E, Obj, Sub, Handler);
4576}
4577
4578/// Find the position where two subobject designators diverge, or equivalently
4579/// the length of the common initial subsequence.
4580static unsigned FindDesignatorMismatch(QualType ObjType,
4581 const SubobjectDesignator &A,
4582 const SubobjectDesignator &B,
4583 bool &WasArrayIndex) {
4584 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
4585 for (/**/; I != N; ++I) {
4586 if (!ObjType.isNull() &&
4587 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
4588 // Next subobject is an array element.
4589 if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
4590 WasArrayIndex = true;
4591 return I;
4592 }
4593 if (ObjType->isAnyComplexType())
4594 ObjType = ObjType->castAs<ComplexType>()->getElementType();
4595 else
4596 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
4597 } else {
4598 if (A.Entries[I].getAsBaseOrMember() !=
4599 B.Entries[I].getAsBaseOrMember()) {
4600 WasArrayIndex = false;
4601 return I;
4602 }
4603 if (const FieldDecl *FD = getAsField(A.Entries[I]))
4604 // Next subobject is a field.
4605 ObjType = FD->getType();
4606 else
4607 // Next subobject is a base class.
4608 ObjType = QualType();
4609 }
4610 }
4611 WasArrayIndex = false;
4612 return I;
4613}
4614
4615/// Determine whether the given subobject designators refer to elements of the
4616/// same array object.
4618 const SubobjectDesignator &A,
4619 const SubobjectDesignator &B) {
4620 if (A.Entries.size() != B.Entries.size())
4621 return false;
4622
4623 bool IsArray = A.MostDerivedIsArrayElement;
4624 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
4625 // A is a subobject of the array element.
4626 return false;
4627
4628 // If A (and B) designates an array element, the last entry will be the array
4629 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
4630 // of length 1' case, and the entire path must match.
4631 bool WasArrayIndex;
4632 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
4633 return CommonLength >= A.Entries.size() - IsArray;
4634}
4635
4636/// Find the complete object to which an LValue refers.
4637static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
4638 AccessKinds AK, const LValue &LVal,
4639 QualType LValType) {
4640 if (LVal.InvalidBase) {
4641 Info.FFDiag(E);
4642 return CompleteObject();
4643 }
4644
4645 if (!LVal.Base) {
4647 Info.FFDiag(E, diag::note_constexpr_dereferencing_null);
4648 else
4649 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
4650 return CompleteObject();
4651 }
4652
4653 CallStackFrame *Frame = nullptr;
4654 unsigned Depth = 0;
4655 if (LVal.getLValueCallIndex()) {
4656 std::tie(Frame, Depth) =
4657 Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
4658 if (!Frame) {
4659 Info.FFDiag(E, diag::note_constexpr_access_uninit, 1)
4660 << AK << /*Indeterminate=*/false << E->getSourceRange();
4661 NoteLValueLocation(Info, LVal.Base);
4662 return CompleteObject();
4663 }
4664 }
4665
4666 bool IsAccess = isAnyAccess(AK);
4667
4668 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
4669 // is not a constant expression (even if the object is non-volatile). We also
4670 // apply this rule to C++98, in order to conform to the expected 'volatile'
4671 // semantics.
4672 if (isFormalAccess(AK) && LValType.isVolatileQualified()) {
4673 if (Info.getLangOpts().CPlusPlus)
4674 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
4675 << AK << LValType;
4676 else
4677 Info.FFDiag(E);
4678 return CompleteObject();
4679 }
4680
4681 // Compute value storage location and type of base object.
4682 APValue *BaseVal = nullptr;
4683 QualType BaseType = getType(LVal.Base);
4684
4685 if (Info.getLangOpts().CPlusPlus14 && LVal.Base == Info.EvaluatingDecl &&
4686 lifetimeStartedInEvaluation(Info, LVal.Base)) {
4687 // This is the object whose initializer we're evaluating, so its lifetime
4688 // started in the current evaluation.
4689 BaseVal = Info.EvaluatingDeclValue;
4690 } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) {
4691 // Allow reading from a GUID declaration.
4692 if (auto *GD = dyn_cast<MSGuidDecl>(D)) {
4693 if (isModification(AK)) {
4694 // All the remaining cases do not permit modification of the object.
4695 Info.FFDiag(E, diag::note_constexpr_modify_global);
4696 return CompleteObject();
4697 }
4698 APValue &V = GD->getAsAPValue();
4699 if (V.isAbsent()) {
4700 Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
4701 << GD->getType();
4702 return CompleteObject();
4703 }
4704 return CompleteObject(LVal.Base, &V, GD->getType());
4705 }
4706
4707 // Allow reading the APValue from an UnnamedGlobalConstantDecl.
4708 if (auto *GCD = dyn_cast<UnnamedGlobalConstantDecl>(D)) {
4709 if (isModification(AK)) {
4710 Info.FFDiag(E, diag::note_constexpr_modify_global);
4711 return CompleteObject();
4712 }
4713 return CompleteObject(LVal.Base, const_cast<APValue *>(&GCD->getValue()),
4714 GCD->getType());
4715 }
4716
4717 // Allow reading from template parameter objects.
4718 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) {
4719 if (isModification(AK)) {
4720 Info.FFDiag(E, diag::note_constexpr_modify_global);
4721 return CompleteObject();
4722 }
4723 return CompleteObject(LVal.Base, const_cast<APValue *>(&TPO->getValue()),
4724 TPO->getType());
4725 }
4726
4727 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
4728 // In C++11, constexpr, non-volatile variables initialized with constant
4729 // expressions are constant expressions too. Inside constexpr functions,
4730 // parameters are constant expressions even if they're non-const.
4731 // In C++1y, objects local to a constant expression (those with a Frame) are
4732 // both readable and writable inside constant expressions.
4733 // In C, such things can also be folded, although they are not ICEs.
4734 const VarDecl *VD = dyn_cast<VarDecl>(D);
4735 if (VD) {
4736 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
4737 VD = VDef;
4738 }
4739 if (!VD || VD->isInvalidDecl()) {
4740 Info.FFDiag(E);
4741 return CompleteObject();
4742 }
4743
4744 bool IsConstant = BaseType.isConstant(Info.Ctx);
4745 bool ConstexprVar = false;
4746 if (const auto *VD = dyn_cast_if_present<VarDecl>(
4747 Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()))
4748 ConstexprVar = VD->isConstexpr();
4749
4750 // Unless we're looking at a local variable or argument in a constexpr call,
4751 // the variable we're reading must be const (unless we are binding to a
4752 // reference).
4753 if (AK != clang::AK_Dereference && !Frame) {
4754 if (IsAccess && isa<ParmVarDecl>(VD)) {
4755 // Access of a parameter that's not associated with a frame isn't going
4756 // to work out, but we can leave it to evaluateVarDeclInit to provide a
4757 // suitable diagnostic.
4758 } else if (Info.getLangOpts().CPlusPlus14 &&
4759 lifetimeStartedInEvaluation(Info, LVal.Base)) {
4760 // OK, we can read and modify an object if we're in the process of
4761 // evaluating its initializer, because its lifetime began in this
4762 // evaluation.
4763 } else if (isModification(AK)) {
4764 // All the remaining cases do not permit modification of the object.
4765 Info.FFDiag(E, diag::note_constexpr_modify_global);
4766 return CompleteObject();
4767 } else if (VD->isConstexpr()) {
4768 // OK, we can read this variable.
4769 } else if (Info.getLangOpts().C23 && ConstexprVar) {
4770 Info.FFDiag(E);
4771 return CompleteObject();
4772 } else if (BaseType->isIntegralOrEnumerationType()) {
4773 if (!IsConstant) {
4774 if (!IsAccess)
4775 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4776 if (Info.getLangOpts().CPlusPlus) {
4777 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
4778 Info.Note(VD->getLocation(), diag::note_declared_at);
4779 } else {
4780 Info.FFDiag(E);
4781 }
4782 return CompleteObject();
4783 }
4784 } else if (!IsAccess) {
4785 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4786 } else if ((IsConstant || BaseType->isReferenceType()) &&
4787 Info.checkingPotentialConstantExpression() &&
4788 BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) {
4789 // This variable might end up being constexpr. Don't diagnose it yet.
4790 } else if (IsConstant) {
4791 // Keep evaluating to see what we can do. In particular, we support
4792 // folding of const floating-point types, in order to make static const
4793 // data members of such types (supported as an extension) more useful.
4794 if (Info.getLangOpts().CPlusPlus) {
4795 Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11
4796 ? diag::note_constexpr_ltor_non_constexpr
4797 : diag::note_constexpr_ltor_non_integral, 1)
4798 << VD << BaseType;
4799 Info.Note(VD->getLocation(), diag::note_declared_at);
4800 } else {
4801 Info.CCEDiag(E);
4802 }
4803 } else {
4804 // Never allow reading a non-const value.
4805 if (Info.getLangOpts().CPlusPlus) {
4806 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
4807 ? diag::note_constexpr_ltor_non_constexpr
4808 : diag::note_constexpr_ltor_non_integral, 1)
4809 << VD << BaseType;
4810 Info.Note(VD->getLocation(), diag::note_declared_at);
4811 } else {
4812 Info.FFDiag(E);
4813 }
4814 return CompleteObject();
4815 }
4816 }
4817
4818 // When binding to a reference, the variable does not need to be constexpr
4819 // or have constant initalization.
4820 if (AK != clang::AK_Dereference &&
4821 !evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(),
4822 BaseVal))
4823 return CompleteObject();
4824 // If evaluateVarDeclInit sees a constexpr-unknown variable, it returns
4825 // a null BaseVal. Any constexpr-unknown variable seen here is an error:
4826 // we can't access a constexpr-unknown object.
4827 if (AK != clang::AK_Dereference && !BaseVal) {
4828 if (!Info.checkingPotentialConstantExpression()) {
4829 Info.FFDiag(E, diag::note_constexpr_access_unknown_variable, 1)
4830 << AK << VD;
4831 Info.Note(VD->getLocation(), diag::note_declared_at);
4832 }
4833 return CompleteObject();
4834 }
4835 } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) {
4836 std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
4837 if (!Alloc) {
4838 Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK;
4839 return CompleteObject();
4840 }
4841 return CompleteObject(LVal.Base, &(*Alloc)->Value,
4842 LVal.Base.getDynamicAllocType());
4843 }
4844 // When binding to a reference, the variable does not need to be
4845 // within its lifetime.
4846 else if (AK != clang::AK_Dereference) {
4847 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4848
4849 if (!Frame) {
4850 if (const MaterializeTemporaryExpr *MTE =
4851 dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
4852 assert(MTE->getStorageDuration() == SD_Static &&
4853 "should have a frame for a non-global materialized temporary");
4854
4855 // C++20 [expr.const]p4: [DR2126]
4856 // An object or reference is usable in constant expressions if it is
4857 // - a temporary object of non-volatile const-qualified literal type
4858 // whose lifetime is extended to that of a variable that is usable
4859 // in constant expressions
4860 //
4861 // C++20 [expr.const]p5:
4862 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
4863 // - a non-volatile glvalue that refers to an object that is usable
4864 // in constant expressions, or
4865 // - a non-volatile glvalue of literal type that refers to a
4866 // non-volatile object whose lifetime began within the evaluation
4867 // of E;
4868 //
4869 // C++11 misses the 'began within the evaluation of e' check and
4870 // instead allows all temporaries, including things like:
4871 // int &&r = 1;
4872 // int x = ++r;
4873 // constexpr int k = r;
4874 // Therefore we use the C++14-onwards rules in C++11 too.
4875 //
4876 // Note that temporaries whose lifetimes began while evaluating a
4877 // variable's constructor are not usable while evaluating the
4878 // corresponding destructor, not even if they're of const-qualified
4879 // types.
4880 if (!MTE->isUsableInConstantExpressions(Info.Ctx) &&
4881 !lifetimeStartedInEvaluation(Info, LVal.Base)) {
4882 if (!IsAccess)
4883 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4884 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
4885 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
4886 return CompleteObject();
4887 }
4888
4889 BaseVal = MTE->getOrCreateValue(false);
4890 assert(BaseVal && "got reference to unevaluated temporary");
4891 } else if (const CompoundLiteralExpr *CLE =
4892 dyn_cast_or_null<CompoundLiteralExpr>(Base)) {
4893 // According to GCC info page:
4894 //
4895 // 6.28 Compound Literals
4896 //
4897 // As an optimization, G++ sometimes gives array compound literals
4898 // longer lifetimes: when the array either appears outside a function or
4899 // has a const-qualified type. If foo and its initializer had elements
4900 // of type char *const rather than char *, or if foo were a global
4901 // variable, the array would have static storage duration. But it is
4902 // probably safest just to avoid the use of array compound literals in
4903 // C++ code.
4904 //
4905 // Obey that rule by checking constness for converted array types.
4906 if (QualType CLETy = CLE->getType(); CLETy->isArrayType() &&
4907 !LValType->isArrayType() &&
4908 !CLETy.isConstant(Info.Ctx)) {
4909 Info.FFDiag(E);
4910 Info.Note(CLE->getExprLoc(), diag::note_declared_at);
4911 return CompleteObject();
4912 }
4913
4914 BaseVal = &CLE->getStaticValue();
4915 } else {
4916 if (!IsAccess)
4917 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4918 APValue Val;
4919 LVal.moveInto(Val);
4920 Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
4921 << AK
4922 << Val.getAsString(Info.Ctx,
4923 Info.Ctx.getLValueReferenceType(LValType));
4924 NoteLValueLocation(Info, LVal.Base);
4925 return CompleteObject();
4926 }
4927 } else if (AK != clang::AK_Dereference) {
4928 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
4929 assert(BaseVal && "missing value for temporary");
4930 }
4931 }
4932
4933 // In C++14, we can't safely access any mutable state when we might be
4934 // evaluating after an unmodeled side effect. Parameters are modeled as state
4935 // in the caller, but aren't visible once the call returns, so they can be
4936 // modified in a speculatively-evaluated call.
4937 //
4938 // FIXME: Not all local state is mutable. Allow local constant subobjects
4939 // to be read here (but take care with 'mutable' fields).
4940 unsigned VisibleDepth = Depth;
4941 if (llvm::isa_and_nonnull<ParmVarDecl>(
4942 LVal.Base.dyn_cast<const ValueDecl *>()))
4943 ++VisibleDepth;
4944 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
4945 Info.EvalStatus.HasSideEffects) ||
4946 (isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth))
4947 return CompleteObject();
4948
4949 return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
4950}
4951
4952/// Perform an lvalue-to-rvalue conversion on the given glvalue. This
4953/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
4954/// glvalue referred to by an entity of reference type.
4955///
4956/// \param Info - Information about the ongoing evaluation.
4957/// \param Conv - The expression for which we are performing the conversion.
4958/// Used for diagnostics.
4959/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
4960/// case of a non-class type).
4961/// \param LVal - The glvalue on which we are attempting to perform this action.
4962/// \param RVal - The produced value will be placed here.
4963/// \param WantObjectRepresentation - If true, we're looking for the object
4964/// representation rather than the value, and in particular,
4965/// there is no requirement that the result be fully initialized.
4966static bool
4968 const LValue &LVal, APValue &RVal,
4969 bool WantObjectRepresentation = false) {
4970 if (LVal.Designator.Invalid)
4971 return false;
4972
4973 // Check for special cases where there is no existing APValue to look at.
4974 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4975
4976 AccessKinds AK =
4977 WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;
4978
4979 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
4981 // Special-case character extraction so we don't have to construct an
4982 // APValue for the whole string.
4983 assert(LVal.Designator.Entries.size() <= 1 &&
4984 "Can only read characters from string literals");
4985 if (LVal.Designator.Entries.empty()) {
4986 // Fail for now for LValue to RValue conversion of an array.
4987 // (This shouldn't show up in C/C++, but it could be triggered by a
4988 // weird EvaluateAsRValue call from a tool.)
4989 Info.FFDiag(Conv);
4990 return false;
4991 }
4992 if (LVal.Designator.isOnePastTheEnd()) {
4993 if (Info.getLangOpts().CPlusPlus11)
4994 Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
4995 else
4996 Info.FFDiag(Conv);
4997 return false;
4998 }
4999 uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
5000 RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
5001 return true;
5002 }
5003 }
5004
5005 CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
5006 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
5007}
5008
5009static bool hlslElementwiseCastHelper(EvalInfo &Info, const Expr *E,
5010 QualType DestTy,
5011 SmallVectorImpl<APValue> &SrcVals,
5012 SmallVectorImpl<QualType> &SrcTypes) {
5013 APValue Val;
5014 if (!Evaluate(Val, Info, E))
5015 return false;
5016
5017 // must be dealing with a record
5018 if (Val.isLValue()) {
5019 LValue LVal;
5020 LVal.setFrom(Info.Ctx, Val);
5021 if (!handleLValueToRValueConversion(Info, E, E->getType(), LVal, Val))
5022 return false;
5023 }
5024
5025 unsigned NEls = elementwiseSize(Info, DestTy);
5026 // flatten the source
5027 if (!flattenAPValue(Info, E, Val, E->getType(), SrcVals, SrcTypes, NEls))
5028 return false;
5029
5030 return true;
5031}
5032
5033/// Perform an assignment of Val to LVal. Takes ownership of Val.
5034static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
5035 QualType LValType, APValue &Val) {
5036 if (LVal.Designator.Invalid)
5037 return false;
5038
5039 if (!Info.getLangOpts().CPlusPlus14) {
5040 Info.FFDiag(E);
5041 return false;
5042 }
5043
5044 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
5045 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
5046}
5047
5048namespace {
5049struct CompoundAssignSubobjectHandler {
5050 EvalInfo &Info;
5051 const CompoundAssignOperator *E;
5052 QualType PromotedLHSType;
5054 const APValue &RHS;
5055
5056 static const AccessKinds AccessKind = AK_Assign;
5057
5058 typedef bool result_type;
5059
5060 bool checkConst(QualType QT) {
5061 // Assigning to a const object has undefined behavior.
5062 if (QT.isConstQualified()) {
5063 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
5064 return false;
5065 }
5066 return true;
5067 }
5068
5069 bool failed() { return false; }
5070 bool found(APValue &Subobj, QualType SubobjType, APValue::LValueBase Base) {
5071 switch (Subobj.getKind()) {
5072 case APValue::Int:
5073 return found(Subobj.getInt(), SubobjType);
5074 case APValue::Float:
5075 return found(Subobj.getFloat(), SubobjType);
5078 // FIXME: Implement complex compound assignment.
5079 Info.FFDiag(E);
5080 return false;
5081 case APValue::LValue:
5082 return foundPointer(Subobj, SubobjType);
5083 case APValue::Vector:
5084 return foundVector(Subobj, SubobjType);
5086 Info.FFDiag(E, diag::note_constexpr_access_uninit)
5087 << /*read of=*/0 << /*uninitialized object=*/1
5088 << E->getLHS()->getSourceRange();
5089 NoteLValueLocation(Info, Base);
5090 return false;
5091 default:
5092 // FIXME: can this happen?
5093 Info.FFDiag(E);
5094 return false;
5095 }
5096 }
5097
5098 bool foundVector(APValue &Value, QualType SubobjType) {
5099 if (!checkConst(SubobjType))
5100 return false;
5101
5102 if (!SubobjType->isVectorType()) {
5103 Info.FFDiag(E);
5104 return false;
5105 }
5106 return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS);
5107 }
5108
5109 bool found(APSInt &Value, QualType SubobjType) {
5110 if (!checkConst(SubobjType))
5111 return false;
5112
5113 if (!SubobjType->isIntegerType()) {
5114 // We don't support compound assignment on integer-cast-to-pointer
5115 // values.
5116 Info.FFDiag(E);
5117 return false;
5118 }
5119
5120 if (RHS.isInt()) {
5121 APSInt LHS =
5122 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
5123 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
5124 return false;
5125 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
5126 return true;
5127 } else if (RHS.isFloat()) {
5128 const FPOptions FPO = E->getFPFeaturesInEffect(
5129 Info.Ctx.getLangOpts());
5130 APFloat FValue(0.0);
5131 return HandleIntToFloatCast(Info, E, FPO, SubobjType, Value,
5132 PromotedLHSType, FValue) &&
5133 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
5134 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
5135 Value);
5136 }
5137
5138 Info.FFDiag(E);
5139 return false;
5140 }
5141 bool found(APFloat &Value, QualType SubobjType) {
5142 return checkConst(SubobjType) &&
5143 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
5144 Value) &&
5145 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
5146 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
5147 }
5148 bool foundPointer(APValue &Subobj, QualType SubobjType) {
5149 if (!checkConst(SubobjType))
5150 return false;
5151
5152 QualType PointeeType;
5153 if (const PointerType *PT = SubobjType->getAs<PointerType>())
5154 PointeeType = PT->getPointeeType();
5155
5156 if (PointeeType.isNull() || !RHS.isInt() ||
5157 (Opcode != BO_Add && Opcode != BO_Sub)) {
5158 Info.FFDiag(E);
5159 return false;
5160 }
5161
5162 APSInt Offset = RHS.getInt();
5163 if (Opcode == BO_Sub)
5164 negateAsSigned(Offset);
5165
5166 LValue LVal;
5167 LVal.setFrom(Info.Ctx, Subobj);
5168 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
5169 return false;
5170 LVal.moveInto(Subobj);
5171 return true;
5172 }
5173};
5174} // end anonymous namespace
5175
5176const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
5177
5178/// Perform a compound assignment of LVal <op>= RVal.
5179static bool handleCompoundAssignment(EvalInfo &Info,
5180 const CompoundAssignOperator *E,
5181 const LValue &LVal, QualType LValType,
5182 QualType PromotedLValType,
5183 BinaryOperatorKind Opcode,
5184 const APValue &RVal) {
5185 if (LVal.Designator.Invalid)
5186 return false;
5187
5188 if (!Info.getLangOpts().CPlusPlus14) {
5189 Info.FFDiag(E);
5190 return false;
5191 }
5192
5193 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
5194 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
5195 RVal };
5196 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
5197}
5198
5199namespace {
5200struct IncDecSubobjectHandler {
5201 EvalInfo &Info;
5202 const UnaryOperator *E;
5204 APValue *Old;
5205
5206 typedef bool result_type;
5207
5208 bool checkConst(QualType QT) {
5209 // Assigning to a const object has undefined behavior.
5210 if (QT.isConstQualified()) {
5211 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
5212 return false;
5213 }
5214 return true;
5215 }
5216
5217 bool failed() { return false; }
5218 bool found(APValue &Subobj, QualType SubobjType, APValue::LValueBase Base) {
5219 // Stash the old value. Also clear Old, so we don't clobber it later
5220 // if we're post-incrementing a complex.
5221 if (Old) {
5222 *Old = Subobj;
5223 Old = nullptr;
5224 }
5225
5226 switch (Subobj.getKind()) {
5227 case APValue::Int:
5228 return found(Subobj.getInt(), SubobjType);
5229 case APValue::Float:
5230 return found(Subobj.getFloat(), SubobjType);
5232 return found(Subobj.getComplexIntReal(),
5233 SubobjType->castAs<ComplexType>()->getElementType()
5234 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
5236 return found(Subobj.getComplexFloatReal(),
5237 SubobjType->castAs<ComplexType>()->getElementType()
5238 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
5239 case APValue::LValue:
5240 return foundPointer(Subobj, SubobjType);
5241 default:
5242 // FIXME: can this happen?
5243 Info.FFDiag(E);
5244 return false;
5245 }
5246 }
5247 bool found(APSInt &Value, QualType SubobjType) {
5248 if (!checkConst(SubobjType))
5249 return false;
5250
5251 if (!SubobjType->isIntegerType()) {
5252 // We don't support increment / decrement on integer-cast-to-pointer
5253 // values.
5254 Info.FFDiag(E);
5255 return false;
5256 }
5257
5258 if (Old) *Old = APValue(Value);
5259
5260 // bool arithmetic promotes to int, and the conversion back to bool
5261 // doesn't reduce mod 2^n, so special-case it.
5262 if (SubobjType->isBooleanType()) {
5263 if (AccessKind == AK_Increment)
5264 Value = 1;
5265 else
5266 Value = !Value;
5267 return true;
5268 }
5269
5270 bool WasNegative = Value.isNegative();
5271 if (AccessKind == AK_Increment) {
5272 ++Value;
5273
5274 if (!WasNegative && Value.isNegative() && E->canOverflow() &&
5275 !SubobjType.isWrapType()) {
5276 APSInt ActualValue(Value, /*IsUnsigned*/true);
5277 return HandleOverflow(Info, E, ActualValue, SubobjType);
5278 }
5279 } else {
5280 --Value;
5281
5282 if (WasNegative && !Value.isNegative() && E->canOverflow() &&
5283 !SubobjType.isWrapType()) {
5284 unsigned BitWidth = Value.getBitWidth();
5285 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
5286 ActualValue.setBit(BitWidth);
5287 return HandleOverflow(Info, E, ActualValue, SubobjType);
5288 }
5289 }
5290 return true;
5291 }
5292 bool found(APFloat &Value, QualType SubobjType) {
5293 if (!checkConst(SubobjType))
5294 return false;
5295
5296 if (Old) *Old = APValue(Value);
5297
5298 APFloat One(Value.getSemantics(), 1);
5299 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
5300 APFloat::opStatus St;
5301 if (AccessKind == AK_Increment)
5302 St = Value.add(One, RM);
5303 else
5304 St = Value.subtract(One, RM);
5306 }
5307 bool foundPointer(APValue &Subobj, QualType SubobjType) {
5308 if (!checkConst(SubobjType))
5309 return false;
5310
5311 QualType PointeeType;
5312 if (const PointerType *PT = SubobjType->getAs<PointerType>())
5313 PointeeType = PT->getPointeeType();
5314 else {
5315 Info.FFDiag(E);
5316 return false;
5317 }
5318
5319 LValue LVal;
5320 LVal.setFrom(Info.Ctx, Subobj);
5321 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
5322 AccessKind == AK_Increment ? 1 : -1))
5323 return false;
5324 LVal.moveInto(Subobj);
5325 return true;
5326 }
5327};
5328} // end anonymous namespace
5329
5330/// Perform an increment or decrement on LVal.
5331static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
5332 QualType LValType, bool IsIncrement, APValue *Old) {
5333 if (LVal.Designator.Invalid)
5334 return false;
5335
5336 if (!Info.getLangOpts().CPlusPlus14) {
5337 Info.FFDiag(E);
5338 return false;
5339 }
5340
5341 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
5342 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
5343 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
5344 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
5345}
5346
5347/// Build an lvalue for the object argument of a member function call.
5348static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
5349 LValue &This) {
5350 if (Object->getType()->isPointerType() && Object->isPRValue())
5351 return EvaluatePointer(Object, This, Info);
5352
5353 if (Object->isGLValue())
5354 return EvaluateLValue(Object, This, Info);
5355
5356 if (Object->getType()->isLiteralType(Info.Ctx))
5357 return EvaluateTemporary(Object, This, Info);
5358
5359 if (Object->getType()->isRecordType() && Object->isPRValue())
5360 return EvaluateTemporary(Object, This, Info);
5361
5362 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
5363 return false;
5364}
5365
5366/// HandleMemberPointerAccess - Evaluate a member access operation and build an
5367/// lvalue referring to the result.
5368///
5369/// \param Info - Information about the ongoing evaluation.
5370/// \param LV - An lvalue referring to the base of the member pointer.
5371/// \param RHS - The member pointer expression.
5372/// \param IncludeMember - Specifies whether the member itself is included in
5373/// the resulting LValue subobject designator. This is not possible when
5374/// creating a bound member function.
5375/// \return The field or method declaration to which the member pointer refers,
5376/// or 0 if evaluation fails.
5377static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
5378 QualType LVType,
5379 LValue &LV,
5380 const Expr *RHS,
5381 bool IncludeMember = true) {
5382 MemberPtr MemPtr;
5383 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
5384 return nullptr;
5385
5386 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
5387 // member value, the behavior is undefined.
5388 if (!MemPtr.getDecl()) {
5389 // FIXME: Specific diagnostic.
5390 Info.FFDiag(RHS);
5391 return nullptr;
5392 }
5393
5394 if (MemPtr.isDerivedMember()) {
5395 // This is a member of some derived class. Truncate LV appropriately.
5396 // The end of the derived-to-base path for the base object must match the
5397 // derived-to-base path for the member pointer.
5398 // C++23 [expr.mptr.oper]p4:
5399 // If the result of E1 is an object [...] whose most derived object does
5400 // not contain the member to which E2 refers, the behavior is undefined.
5401 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
5402 LV.Designator.Entries.size()) {
5403 Info.FFDiag(RHS);
5404 return nullptr;
5405 }
5406 unsigned PathLengthToMember =
5407 LV.Designator.Entries.size() - MemPtr.Path.size();
5408 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
5409 const CXXRecordDecl *LVDecl = getAsBaseClass(
5410 LV.Designator.Entries[PathLengthToMember + I]);
5411 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
5412 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
5413 Info.FFDiag(RHS);
5414 return nullptr;
5415 }
5416 }
5417 // MemPtr.Path only contains the base classes of the class directly
5418 // containing the member E2. It is still necessary to check that the class
5419 // directly containing the member E2 lies on the derived-to-base path of E1
5420 // to avoid incorrectly permitting member pointer access into a sibling
5421 // class of the class containing the member E2. If this class would
5422 // correspond to the most-derived class of E1, it either isn't contained in
5423 // LV.Designator.Entries or the corresponding entry refers to an array
5424 // element instead. Therefore get the most derived class directly in this
5425 // case. Otherwise the previous entry should correpond to this class.
5426 const CXXRecordDecl *LastLVDecl =
5427 (PathLengthToMember > LV.Designator.MostDerivedPathLength)
5428 ? getAsBaseClass(LV.Designator.Entries[PathLengthToMember - 1])
5429 : LV.Designator.MostDerivedType->getAsCXXRecordDecl();
5430 const CXXRecordDecl *LastMPDecl = MemPtr.getContainingRecord();
5431 if (LastLVDecl->getCanonicalDecl() != LastMPDecl->getCanonicalDecl()) {
5432 Info.FFDiag(RHS);
5433 return nullptr;
5434 }
5435
5436 // Truncate the lvalue to the appropriate derived class.
5437 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
5438 PathLengthToMember))
5439 return nullptr;
5440 } else if (!MemPtr.Path.empty()) {
5441 // Extend the LValue path with the member pointer's path.
5442 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
5443 MemPtr.Path.size() + IncludeMember);
5444
5445 // Walk down to the appropriate base class.
5446 if (const PointerType *PT = LVType->getAs<PointerType>())
5447 LVType = PT->getPointeeType();
5448 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
5449 assert(RD && "member pointer access on non-class-type expression");
5450 // The first class in the path is that of the lvalue.
5451 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
5452 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
5453 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
5454 return nullptr;
5455 RD = Base;
5456 }
5457 // Finally cast to the class containing the member.
5458 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
5459 MemPtr.getContainingRecord()))
5460 return nullptr;
5461 }
5462
5463 // Add the member. Note that we cannot build bound member functions here.
5464 if (IncludeMember) {
5465 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
5466 if (!HandleLValueMember(Info, RHS, LV, FD))
5467 return nullptr;
5468 } else if (const IndirectFieldDecl *IFD =
5469 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
5470 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
5471 return nullptr;
5472 } else {
5473 llvm_unreachable("can't construct reference to bound member function");
5474 }
5475 }
5476
5477 return MemPtr.getDecl();
5478}
5479
5480static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
5481 const BinaryOperator *BO,
5482 LValue &LV,
5483 bool IncludeMember = true) {
5484 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
5485
5486 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
5487 if (Info.noteFailure()) {
5488 MemberPtr MemPtr;
5489 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
5490 }
5491 return nullptr;
5492 }
5493
5494 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
5495 BO->getRHS(), IncludeMember);
5496}
5497
5498/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
5499/// the provided lvalue, which currently refers to the base object.
5500static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
5501 LValue &Result) {
5502 SubobjectDesignator &D = Result.Designator;
5503 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
5504 return false;
5505
5506 QualType TargetQT = E->getType();
5507 if (const PointerType *PT = TargetQT->getAs<PointerType>())
5508 TargetQT = PT->getPointeeType();
5509
5510 auto InvalidCast = [&]() {
5511 if (!Info.checkingPotentialConstantExpression() ||
5512 !Result.AllowConstexprUnknown) {
5513 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
5514 << D.MostDerivedType << TargetQT;
5515 }
5516 return false;
5517 };
5518
5519 // Check this cast lands within the final derived-to-base subobject path.
5520 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size())
5521 return InvalidCast();
5522
5523 // Check the type of the final cast. We don't need to check the path,
5524 // since a cast can only be formed if the path is unique.
5525 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
5526 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
5527 const CXXRecordDecl *FinalType;
5528 if (NewEntriesSize == D.MostDerivedPathLength)
5529 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
5530 else
5531 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
5532 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl())
5533 return InvalidCast();
5534
5535 // Truncate the lvalue to the appropriate derived class.
5536 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
5537}
5538
5539/// Get the value to use for a default-initialized object of type T.
5540/// Return false if it encounters something invalid.
5542 bool IsCompleteClass = true) {
5543 bool Success = true;
5544
5545 // If there is already a value present don't overwrite it.
5546 if (!Result.isAbsent())
5547 return true;
5548
5549 if (auto *RD = T->getAsCXXRecordDecl()) {
5550 if (RD->isInvalidDecl()) {
5551 Result = APValue();
5552 return false;
5553 }
5554 if (RD->isUnion()) {
5555 Result = APValue((const FieldDecl *)nullptr);
5556 return true;
5557 }
5558
5559 // bases() includes directly specified virtual bases as well.
5560 unsigned NonVirtualBases = countNonVirtualBases(RD);
5561 Result =
5562 APValue(APValue::UninitStruct(), NonVirtualBases, RD->getNumFields(),
5563 IsCompleteClass ? RD->getNumVBases() : 0);
5564
5565 unsigned Index = 0;
5566 for (const CXXBaseSpecifier &B : RD->bases()) {
5567 if (B.isVirtual())
5568 continue;
5570 B.getType(), Result.getStructBase(Index), /*IsCompleteClass=*/false);
5571 ++Index;
5572 }
5573
5574 for (const auto *I : RD->fields()) {
5575 if (I->isUnnamedBitField())
5576 continue;
5578 I->getType(), Result.getStructField(I->getFieldIndex()));
5579 }
5580
5581 if (IsCompleteClass) {
5582 Index = 0;
5583
5584 for (const auto &B : RD->vbases()) {
5586 Result.getStructVirtualBase(Index),
5587 /*IsCompleteClass=*/false);
5588 ++Index;
5589 }
5590 } else {
5591 // Virtual bases should only exist at the top level of an APValue.
5592 assert(Result.getStructNumVirtualBases() == 0);
5593 }
5594
5595 return Success;
5596 }
5597
5598 if (auto *AT =
5599 dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
5600 Result = APValue(APValue::UninitArray(), 0, AT->getZExtSize());
5601 if (Result.hasArrayFiller())
5602 Success &=
5603 handleDefaultInitValue(AT->getElementType(), Result.getArrayFiller());
5604 return Success;
5605 }
5606
5608 return true;
5609}
5610
5611namespace {
5612enum EvalStmtResult {
5613 /// Evaluation failed.
5614 ESR_Failed,
5615 /// Hit a 'return' statement.
5616 ESR_Returned,
5617 /// Evaluation succeeded.
5618 ESR_Succeeded,
5619 /// Hit a 'continue' statement.
5620 ESR_Continue,
5621 /// Hit a 'break' statement.
5622 ESR_Break,
5623 /// Still scanning for 'case' or 'default' statement.
5624 ESR_CaseNotFound
5625};
5626}
5627/// Evaluates the initializer of a reference.
5628static bool EvaluateInitForDeclOfReferenceType(EvalInfo &Info,
5629 const ValueDecl *D,
5630 const Expr *Init, LValue &Result,
5631 APValue &Val) {
5632 assert(Init->isGLValue() && D->getType()->isReferenceType());
5633 // A reference is an lvalue.
5634 if (!EvaluateLValue(Init, Result, Info))
5635 return false;
5636 // [C++26][decl.ref]
5637 // The object designated by such a glvalue can be outside its lifetime
5638 // Because a null pointer value or a pointer past the end of an object
5639 // does not point to an object, a reference in a well-defined program cannot
5640 // refer to such things;
5641 if (!Result.Designator.Invalid && Result.Designator.isOnePastTheEnd()) {
5642 Info.FFDiag(Init, diag::note_constexpr_access_past_end) << AK_Dereference;
5643 return false;
5644 }
5645
5646 // Save the result.
5647 Result.moveInto(Val);
5648 return true;
5649}
5650
5651static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
5652 if (VD->isInvalidDecl())
5653 return false;
5654 // We don't need to evaluate the initializer for a static local.
5655 if (!VD->hasLocalStorage())
5656 return true;
5657
5658 LValue Result;
5659 APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(),
5660 ScopeKind::Block, Result);
5661
5662 const Expr *InitE = VD->getInit();
5663 if (!InitE) {
5664 if (VD->getType()->isDependentType())
5665 return Info.noteSideEffect();
5666 return handleDefaultInitValue(VD->getType(), Val);
5667 }
5668 if (InitE->isValueDependent())
5669 return false;
5670
5671 // For references to objects, check they do not designate a one-past-the-end
5672 // object.
5673 if (VD->getType()->isReferenceType()) {
5674 return EvaluateInitForDeclOfReferenceType(Info, VD, InitE, Result, Val);
5675 } else if (!EvaluateInPlace(Val, Info, Result, InitE)) {
5676 // Wipe out any partially-computed value, to allow tracking that this
5677 // evaluation failed.
5678 Val = APValue();
5679 return false;
5680 }
5681
5682 return true;
5683}
5684
5685static bool EvaluateDecompositionDeclInit(EvalInfo &Info,
5686 const DecompositionDecl *DD);
5687
5688static bool EvaluateDecl(EvalInfo &Info, const Decl *D,
5689 bool EvaluateConditionDecl = false) {
5690 bool OK = true;
5691 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
5692 OK &= EvaluateVarDecl(Info, VD);
5693
5694 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D);
5695 EvaluateConditionDecl && DD)
5696 OK &= EvaluateDecompositionDeclInit(Info, DD);
5697
5698 return OK;
5699}
5700
5701static bool EvaluateDecompositionDeclInit(EvalInfo &Info,
5702 const DecompositionDecl *DD) {
5703 bool OK = true;
5704 for (auto *BD : DD->flat_bindings())
5705 if (auto *VD = BD->getHoldingVar())
5706 OK &= EvaluateDecl(Info, VD, /*EvaluateConditionDecl=*/true);
5707
5708 return OK;
5709}
5710
5711static bool MaybeEvaluateDeferredVarDeclInit(EvalInfo &Info,
5712 const VarDecl *VD) {
5713 if (auto *DD = dyn_cast_if_present<DecompositionDecl>(VD)) {
5714 if (!EvaluateDecompositionDeclInit(Info, DD))
5715 return false;
5716 }
5717 return true;
5718}
5719
5720static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info) {
5721 assert(E->isValueDependent());
5722 if (Info.noteSideEffect())
5723 return true;
5724 assert(E->containsErrors() && "valid value-dependent expression should never "
5725 "reach invalid code path.");
5726 return false;
5727}
5728
5729/// Evaluate a condition (either a variable declaration or an expression).
5730static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
5731 const Expr *Cond, bool &Result) {
5732 if (Cond->isValueDependent())
5733 return false;
5734 FullExpressionRAII Scope(Info);
5735 if (CondDecl && !EvaluateDecl(Info, CondDecl))
5736 return false;
5738 return false;
5739 if (!MaybeEvaluateDeferredVarDeclInit(Info, CondDecl))
5740 return false;
5741 return Scope.destroy();
5742}
5743
5744namespace {
5745/// A location where the result (returned value) of evaluating a
5746/// statement should be stored.
5747struct StmtResult {
5748 /// The APValue that should be filled in with the returned value.
5749 APValue &Value;
5750 /// The location containing the result, if any (used to support RVO).
5751 const LValue *Slot;
5752};
5753
5754struct TempVersionRAII {
5755 CallStackFrame &Frame;
5756
5757 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
5758 Frame.pushTempVersion();
5759 }
5760
5761 ~TempVersionRAII() {
5762 Frame.popTempVersion();
5763 }
5764};
5765
5766}
5767
5768static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
5769 const Stmt *S,
5770 const SwitchCase *SC = nullptr);
5771
5772/// Helper to implement named break/continue. Returns 'true' if the evaluation
5773/// result should be propagated up. Otherwise, it sets the evaluation result
5774/// to either Continue to continue the current loop, or Succeeded to break it.
5775static bool ShouldPropagateBreakContinue(EvalInfo &Info,
5776 const Stmt *LoopOrSwitch,
5778 EvalStmtResult &ESR) {
5779 bool IsSwitch = isa<SwitchStmt>(LoopOrSwitch);
5780
5781 // For loops, map Succeeded to Continue so we don't have to check for both.
5782 if (!IsSwitch && ESR == ESR_Succeeded) {
5783 ESR = ESR_Continue;
5784 return false;
5785 }
5786
5787 if (ESR != ESR_Break && ESR != ESR_Continue)
5788 return false;
5789
5790 // Are we breaking out of or continuing this statement?
5791 bool CanBreakOrContinue = !IsSwitch || ESR == ESR_Break;
5792 const Stmt *StackTop = Info.BreakContinueStack.back();
5793 if (CanBreakOrContinue && (StackTop == nullptr || StackTop == LoopOrSwitch)) {
5794 Info.BreakContinueStack.pop_back();
5795 if (ESR == ESR_Break)
5796 ESR = ESR_Succeeded;
5797 return false;
5798 }
5799
5800 // We're not. Propagate the result up.
5801 for (BlockScopeRAII *S : Scopes) {
5802 if (!S->destroy()) {
5803 ESR = ESR_Failed;
5804 break;
5805 }
5806 }
5807 return true;
5808}
5809
5810/// Evaluate the body of a loop, and translate the result as appropriate.
5811static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
5812 const Stmt *Body,
5813 const SwitchCase *Case = nullptr) {
5814 BlockScopeRAII Scope(Info);
5815
5816 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case);
5817 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
5818 ESR = ESR_Failed;
5819
5820 return ESR;
5821}
5822
5823/// Evaluate a switch statement.
5824static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
5825 const SwitchStmt *SS) {
5826 BlockScopeRAII Scope(Info);
5827
5828 // Evaluate the switch condition.
5829 APSInt Value;
5830 {
5831 if (const Stmt *Init = SS->getInit()) {
5832 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
5833 if (ESR != ESR_Succeeded) {
5834 if (ESR != ESR_Failed && !Scope.destroy())
5835 ESR = ESR_Failed;
5836 return ESR;
5837 }
5838 }
5839
5840 FullExpressionRAII CondScope(Info);
5841 if (SS->getConditionVariable() &&
5842 !EvaluateDecl(Info, SS->getConditionVariable()))
5843 return ESR_Failed;
5844 if (SS->getCond()->isValueDependent()) {
5845 // We don't know what the value is, and which branch should jump to.
5846 EvaluateDependentExpr(SS->getCond(), Info);
5847 return ESR_Failed;
5848 }
5849 if (!EvaluateInteger(SS->getCond(), Value, Info))
5850 return ESR_Failed;
5851
5853 return ESR_Failed;
5854
5855 if (!CondScope.destroy())
5856 return ESR_Failed;
5857 }
5858
5859 // Find the switch case corresponding to the value of the condition.
5860 // FIXME: Cache this lookup.
5861 const SwitchCase *Found = nullptr;
5862 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
5863 SC = SC->getNextSwitchCase()) {
5864 if (isa<DefaultStmt>(SC)) {
5865 Found = SC;
5866 continue;
5867 }
5868
5869 const CaseStmt *CS = cast<CaseStmt>(SC);
5870 const Expr *LHS = CS->getLHS();
5871 const Expr *RHS = CS->getRHS();
5872 if (LHS->isValueDependent() || (RHS && RHS->isValueDependent()))
5873 return ESR_Failed;
5874 APSInt LHSValue = LHS->EvaluateKnownConstInt(Info.Ctx);
5875 APSInt RHSValue = RHS ? RHS->EvaluateKnownConstInt(Info.Ctx) : LHSValue;
5876 if (LHSValue <= Value && Value <= RHSValue) {
5877 Found = SC;
5878 break;
5879 }
5880 }
5881
5882 if (!Found)
5883 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5884
5885 // Search the switch body for the switch case and evaluate it from there.
5886 EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found);
5887 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
5888 return ESR_Failed;
5889 if (ShouldPropagateBreakContinue(Info, SS, /*Scopes=*/{}, ESR))
5890 return ESR;
5891
5892 switch (ESR) {
5893 case ESR_Break:
5894 llvm_unreachable("Should have been converted to Succeeded");
5895 case ESR_Succeeded:
5896 case ESR_Continue:
5897 case ESR_Failed:
5898 case ESR_Returned:
5899 return ESR;
5900 case ESR_CaseNotFound:
5901 // This can only happen if the switch case is nested within a statement
5902 // expression. We have no intention of supporting that.
5903 Info.FFDiag(Found->getBeginLoc(),
5904 diag::note_constexpr_stmt_expr_unsupported);
5905 return ESR_Failed;
5906 }
5907 llvm_unreachable("Invalid EvalStmtResult!");
5908}
5909
5910static bool CheckLocalVariableDeclaration(EvalInfo &Info, const VarDecl *VD) {
5911 // An expression E is a core constant expression unless the evaluation of E
5912 // would evaluate one of the following: [C++23] - a control flow that passes
5913 // through a declaration of a variable with static or thread storage duration
5914 // unless that variable is usable in constant expressions.
5915 if (VD->isLocalVarDecl() && VD->isStaticLocal() &&
5916 !VD->isUsableInConstantExpressions(Info.Ctx)) {
5917 Info.CCEDiag(VD->getLocation(), diag::note_constexpr_static_local)
5918 << (VD->getTSCSpec() == TSCS_unspecified ? 0 : 1) << VD;
5919 return false;
5920 }
5921 return true;
5922}
5923
5924// Evaluate a statement.
5925static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
5926 const Stmt *S, const SwitchCase *Case) {
5927 if (!Info.nextStep(S))
5928 return ESR_Failed;
5929
5930 // If we're hunting down a 'case' or 'default' label, recurse through
5931 // substatements until we hit the label.
5932 if (Case) {
5933 switch (S->getStmtClass()) {
5934 case Stmt::CompoundStmtClass:
5935 // FIXME: Precompute which substatement of a compound statement we
5936 // would jump to, and go straight there rather than performing a
5937 // linear scan each time.
5938 case Stmt::LabelStmtClass:
5939 case Stmt::AttributedStmtClass:
5940 case Stmt::DoStmtClass:
5941 break;
5942
5943 case Stmt::CaseStmtClass:
5944 case Stmt::DefaultStmtClass:
5945 if (Case == S)
5946 Case = nullptr;
5947 break;
5948
5949 case Stmt::IfStmtClass: {
5950 // FIXME: Precompute which side of an 'if' we would jump to, and go
5951 // straight there rather than scanning both sides.
5952 const IfStmt *IS = cast<IfStmt>(S);
5953
5954 // Wrap the evaluation in a block scope, in case it's a DeclStmt
5955 // preceded by our switch label.
5956 BlockScopeRAII Scope(Info);
5957
5958 // Step into the init statement in case it brings an (uninitialized)
5959 // variable into scope.
5960 if (const Stmt *Init = IS->getInit()) {
5961 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5962 if (ESR != ESR_CaseNotFound) {
5963 assert(ESR != ESR_Succeeded);
5964 return ESR;
5965 }
5966 }
5967
5968 // Condition variable must be initialized if it exists.
5969 // FIXME: We can skip evaluating the body if there's a condition
5970 // variable, as there can't be any case labels within it.
5971 // (The same is true for 'for' statements.)
5972
5973 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
5974 if (ESR == ESR_Failed)
5975 return ESR;
5976 if (ESR != ESR_CaseNotFound)
5977 return Scope.destroy() ? ESR : ESR_Failed;
5978 if (!IS->getElse())
5979 return ESR_CaseNotFound;
5980
5981 ESR = EvaluateStmt(Result, Info, IS->getElse(), Case);
5982 if (ESR == ESR_Failed)
5983 return ESR;
5984 if (ESR != ESR_CaseNotFound)
5985 return Scope.destroy() ? ESR : ESR_Failed;
5986 return ESR_CaseNotFound;
5987 }
5988
5989 case Stmt::WhileStmtClass: {
5990 EvalStmtResult ESR =
5991 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
5992 if (ShouldPropagateBreakContinue(Info, S, /*Scopes=*/{}, ESR))
5993 return ESR;
5994 if (ESR != ESR_Continue)
5995 return ESR;
5996 break;
5997 }
5998
5999 case Stmt::ForStmtClass: {
6000 const ForStmt *FS = cast<ForStmt>(S);
6001 BlockScopeRAII Scope(Info);
6002
6003 // Step into the init statement in case it brings an (uninitialized)
6004 // variable into scope.
6005 if (const Stmt *Init = FS->getInit()) {
6006 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
6007 if (ESR != ESR_CaseNotFound) {
6008 assert(ESR != ESR_Succeeded);
6009 return ESR;
6010 }
6011 }
6012
6013 EvalStmtResult ESR =
6014 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
6015 if (ShouldPropagateBreakContinue(Info, FS, /*Scopes=*/{}, ESR))
6016 return ESR;
6017 if (ESR != ESR_Continue)
6018 return ESR;
6019 if (const auto *Inc = FS->getInc()) {
6020 if (Inc->isValueDependent()) {
6021 if (!EvaluateDependentExpr(Inc, Info))
6022 return ESR_Failed;
6023 } else {
6024 FullExpressionRAII IncScope(Info);
6025 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
6026 return ESR_Failed;
6027 }
6028 }
6029 break;
6030 }
6031
6032 case Stmt::DeclStmtClass: {
6033 // Start the lifetime of any uninitialized variables we encounter. They
6034 // might be used by the selected branch of the switch.
6035 const DeclStmt *DS = cast<DeclStmt>(S);
6036 for (const auto *D : DS->decls()) {
6037 if (const auto *VD = dyn_cast<VarDecl>(D)) {
6038 if (!CheckLocalVariableDeclaration(Info, VD))
6039 return ESR_Failed;
6040 if (VD->hasLocalStorage() && !VD->getInit())
6041 if (!EvaluateVarDecl(Info, VD))
6042 return ESR_Failed;
6043 // FIXME: If the variable has initialization that can't be jumped
6044 // over, bail out of any immediately-surrounding compound-statement
6045 // too. There can't be any case labels here.
6046 }
6047 }
6048 return ESR_CaseNotFound;
6049 }
6050
6051 default:
6052 return ESR_CaseNotFound;
6053 }
6054 }
6055
6056 switch (S->getStmtClass()) {
6057 default:
6058 if (const Expr *E = dyn_cast<Expr>(S)) {
6059 if (E->isValueDependent()) {
6060 if (!EvaluateDependentExpr(E, Info))
6061 return ESR_Failed;
6062 } else {
6063 // Don't bother evaluating beyond an expression-statement which couldn't
6064 // be evaluated.
6065 // FIXME: Do we need the FullExpressionRAII object here?
6066 // VisitExprWithCleanups should create one when necessary.
6067 FullExpressionRAII Scope(Info);
6068 if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy())
6069 return ESR_Failed;
6070 }
6071 return ESR_Succeeded;
6072 }
6073
6074 Info.FFDiag(S->getBeginLoc()) << S->getSourceRange();
6075 return ESR_Failed;
6076
6077 case Stmt::NullStmtClass:
6078 return ESR_Succeeded;
6079
6080 case Stmt::DeclStmtClass: {
6081 const DeclStmt *DS = cast<DeclStmt>(S);
6082 for (const auto *D : DS->decls()) {
6083 const VarDecl *VD = dyn_cast_or_null<VarDecl>(D);
6084 if (VD && !CheckLocalVariableDeclaration(Info, VD))
6085 return ESR_Failed;
6086
6087 if (const auto *ESD = dyn_cast<CXXExpansionStmtDecl>(D)) {
6088 assert(ESD->getInstantiations() && "not expanded?");
6089 return EvaluateStmt(Result, Info, ESD->getInstantiations(), Case);
6090 }
6091
6092 // Each declaration initialization is its own full-expression.
6093 FullExpressionRAII Scope(Info);
6094 if (!EvaluateDecl(Info, D, /*EvaluateConditionDecl=*/true) &&
6095 !Info.noteFailure())
6096 return ESR_Failed;
6097 if (!Scope.destroy())
6098 return ESR_Failed;
6099 }
6100 return ESR_Succeeded;
6101 }
6102
6103 case Stmt::ReturnStmtClass: {
6104 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
6105 FullExpressionRAII Scope(Info);
6106 if (RetExpr && RetExpr->isValueDependent()) {
6107 EvaluateDependentExpr(RetExpr, Info);
6108 // We know we returned, but we don't know what the value is.
6109 return ESR_Failed;
6110 }
6111 if (RetExpr &&
6112 !(Result.Slot
6113 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
6114 : Evaluate(Result.Value, Info, RetExpr)))
6115 return ESR_Failed;
6116 return Scope.destroy() ? ESR_Returned : ESR_Failed;
6117 }
6118
6119 case Stmt::CompoundStmtClass: {
6120 BlockScopeRAII Scope(Info);
6121
6122 const CompoundStmt *CS = cast<CompoundStmt>(S);
6123 for (const auto *BI : CS->body()) {
6124 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
6125 if (ESR == ESR_Succeeded)
6126 Case = nullptr;
6127 else if (ESR != ESR_CaseNotFound) {
6128 if (ESR != ESR_Failed && !Scope.destroy())
6129 return ESR_Failed;
6130 return ESR;
6131 }
6132 }
6133 if (Case)
6134 return ESR_CaseNotFound;
6135 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
6136 }
6137
6138 case Stmt::IfStmtClass: {
6139 const IfStmt *IS = cast<IfStmt>(S);
6140
6141 // Evaluate the condition, as either a var decl or as an expression.
6142 BlockScopeRAII Scope(Info);
6143 if (const Stmt *Init = IS->getInit()) {
6144 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
6145 if (ESR != ESR_Succeeded) {
6146 if (ESR != ESR_Failed && !Scope.destroy())
6147 return ESR_Failed;
6148 return ESR;
6149 }
6150 }
6151 bool Cond;
6152 if (IS->isConsteval()) {
6154 // If we are not in a constant context, if consteval should not evaluate
6155 // to true.
6156 if (!Info.InConstantContext)
6157 Cond = !Cond;
6158 } else if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(),
6159 Cond))
6160 return ESR_Failed;
6161
6162 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
6163 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
6164 if (ESR != ESR_Succeeded) {
6165 if (ESR != ESR_Failed && !Scope.destroy())
6166 return ESR_Failed;
6167 return ESR;
6168 }
6169 }
6170 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
6171 }
6172
6173 case Stmt::WhileStmtClass: {
6174 const WhileStmt *WS = cast<WhileStmt>(S);
6175 while (true) {
6176 BlockScopeRAII Scope(Info);
6177 bool Continue;
6178 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
6179 Continue))
6180 return ESR_Failed;
6181 if (!Continue)
6182 break;
6183
6184 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
6185 if (ShouldPropagateBreakContinue(Info, WS, &Scope, ESR))
6186 return ESR;
6187
6188 if (ESR != ESR_Continue) {
6189 if (ESR != ESR_Failed && !Scope.destroy())
6190 return ESR_Failed;
6191 return ESR;
6192 }
6193 if (!Scope.destroy())
6194 return ESR_Failed;
6195 }
6196 return ESR_Succeeded;
6197 }
6198
6199 case Stmt::DoStmtClass: {
6200 const DoStmt *DS = cast<DoStmt>(S);
6201 bool Continue;
6202 do {
6203 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
6204 if (ShouldPropagateBreakContinue(Info, DS, /*Scopes=*/{}, ESR))
6205 return ESR;
6206 if (ESR != ESR_Continue)
6207 return ESR;
6208 Case = nullptr;
6209
6210 if (DS->getCond()->isValueDependent()) {
6211 EvaluateDependentExpr(DS->getCond(), Info);
6212 // Bailout as we don't know whether to keep going or terminate the loop.
6213 return ESR_Failed;
6214 }
6215 FullExpressionRAII CondScope(Info);
6216 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) ||
6217 !CondScope.destroy())
6218 return ESR_Failed;
6219 } while (Continue);
6220 return ESR_Succeeded;
6221 }
6222
6223 case Stmt::ForStmtClass: {
6224 const ForStmt *FS = cast<ForStmt>(S);
6225 BlockScopeRAII ForScope(Info);
6226 if (FS->getInit()) {
6227 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
6228 if (ESR != ESR_Succeeded) {
6229 if (ESR != ESR_Failed && !ForScope.destroy())
6230 return ESR_Failed;
6231 return ESR;
6232 }
6233 }
6234 while (true) {
6235 BlockScopeRAII IterScope(Info);
6236 bool Continue = true;
6237 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
6238 FS->getCond(), Continue))
6239 return ESR_Failed;
6240
6241 if (!Continue) {
6242 if (!IterScope.destroy())
6243 return ESR_Failed;
6244 break;
6245 }
6246
6247 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
6248 if (ShouldPropagateBreakContinue(Info, FS, {&IterScope, &ForScope}, ESR))
6249 return ESR;
6250 if (ESR != ESR_Continue) {
6251 if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))
6252 return ESR_Failed;
6253 return ESR;
6254 }
6255
6256 if (const auto *Inc = FS->getInc()) {
6257 if (Inc->isValueDependent()) {
6258 if (!EvaluateDependentExpr(Inc, Info))
6259 return ESR_Failed;
6260 } else {
6261 FullExpressionRAII IncScope(Info);
6262 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
6263 return ESR_Failed;
6264 }
6265 }
6266
6267 if (!IterScope.destroy())
6268 return ESR_Failed;
6269 }
6270 return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;
6271 }
6272
6273 case Stmt::CXXForRangeStmtClass: {
6275 BlockScopeRAII Scope(Info);
6276
6277 // Evaluate the init-statement if present.
6278 if (FS->getInit()) {
6279 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
6280 if (ESR != ESR_Succeeded) {
6281 if (ESR != ESR_Failed && !Scope.destroy())
6282 return ESR_Failed;
6283 return ESR;
6284 }
6285 }
6286
6287 // Initialize the __range variable.
6288 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
6289 if (ESR != ESR_Succeeded) {
6290 if (ESR != ESR_Failed && !Scope.destroy())
6291 return ESR_Failed;
6292 return ESR;
6293 }
6294
6295 // In error-recovery cases it's possible to get here even if we failed to
6296 // synthesize the __begin and __end variables.
6297 if (!FS->getBeginStmt() || !FS->getEndStmt() || !FS->getCond())
6298 return ESR_Failed;
6299
6300 // Create the __begin and __end iterators.
6301 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
6302 if (ESR != ESR_Succeeded) {
6303 if (ESR != ESR_Failed && !Scope.destroy())
6304 return ESR_Failed;
6305 return ESR;
6306 }
6307 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
6308 if (ESR != ESR_Succeeded) {
6309 if (ESR != ESR_Failed && !Scope.destroy())
6310 return ESR_Failed;
6311 return ESR;
6312 }
6313
6314 while (true) {
6315 // Condition: __begin != __end.
6316 {
6317 if (FS->getCond()->isValueDependent()) {
6318 EvaluateDependentExpr(FS->getCond(), Info);
6319 // We don't know whether to keep going or terminate the loop.
6320 return ESR_Failed;
6321 }
6322 bool Continue = true;
6323 FullExpressionRAII CondExpr(Info);
6324 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
6325 return ESR_Failed;
6326 if (!Continue)
6327 break;
6328 }
6329
6330 // User's variable declaration, initialized by *__begin.
6331 BlockScopeRAII InnerScope(Info);
6332 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
6333 if (ESR != ESR_Succeeded) {
6334 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
6335 return ESR_Failed;
6336 return ESR;
6337 }
6338
6339 // Loop body.
6340 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
6341 if (ShouldPropagateBreakContinue(Info, FS, {&InnerScope, &Scope}, ESR))
6342 return ESR;
6343 if (ESR != ESR_Continue) {
6344 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
6345 return ESR_Failed;
6346 return ESR;
6347 }
6348 if (FS->getInc()->isValueDependent()) {
6349 if (!EvaluateDependentExpr(FS->getInc(), Info))
6350 return ESR_Failed;
6351 } else {
6352 // Increment: ++__begin
6353 if (!EvaluateIgnoredValue(Info, FS->getInc()))
6354 return ESR_Failed;
6355 }
6356
6357 if (!InnerScope.destroy())
6358 return ESR_Failed;
6359 }
6360
6361 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
6362 }
6363
6364 case Stmt::CXXExpansionStmtInstantiationClass: {
6365 BlockScopeRAII Scope(Info);
6366 const auto *Expansion = cast<CXXExpansionStmtInstantiation>(S);
6367 for (const Stmt *PreambleStmt : Expansion->getPreambleStmts()) {
6368 EvalStmtResult ESR = EvaluateStmt(Result, Info, PreambleStmt);
6369 if (ESR != ESR_Succeeded) {
6370 if (ESR != ESR_Failed && !Scope.destroy())
6371 return ESR_Failed;
6372 return ESR;
6373 }
6374 }
6375
6376 // No need to push an extra scope for these since they're already
6377 // CompoundStmts.
6378 EvalStmtResult ESR = ESR_Succeeded;
6379 for (const Stmt *Instantiation : Expansion->getInstantiations()) {
6380 ESR = EvaluateStmt(Result, Info, Instantiation);
6381 if (ESR == ESR_Failed ||
6382 ShouldPropagateBreakContinue(Info, Expansion, &Scope, ESR))
6383 return ESR;
6384 if (ESR != ESR_Continue) {
6385 // Succeeded here actually means we encountered a 'break'.
6386 assert(ESR == ESR_Succeeded || ESR == ESR_Returned);
6387 break;
6388 }
6389 }
6390
6391 // Map Continue back to Succeeded if we fell off the end of the loop.
6392 if (ESR == ESR_Continue)
6393 ESR = ESR_Succeeded;
6394
6395 return Scope.destroy() ? ESR : ESR_Failed;
6396 }
6397
6398 case Stmt::SwitchStmtClass:
6399 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
6400
6401 case Stmt::ContinueStmtClass:
6402 case Stmt::BreakStmtClass: {
6403 auto *B = cast<LoopControlStmt>(S);
6404 Info.BreakContinueStack.push_back(B->getNamedLoopOrSwitch());
6405 return isa<ContinueStmt>(S) ? ESR_Continue : ESR_Break;
6406 }
6407
6408 case Stmt::LabelStmtClass:
6409 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
6410
6411 case Stmt::AttributedStmtClass: {
6412 const auto *AS = cast<AttributedStmt>(S);
6413 const auto *SS = AS->getSubStmt();
6414 MSConstexprContextRAII ConstexprContext(
6415 *Info.CurrentCall, hasSpecificAttr<MSConstexprAttr>(AS->getAttrs()) &&
6416 isa<ReturnStmt>(SS));
6417
6418 auto LO = Info.Ctx.getLangOpts();
6419 if (LO.CXXAssumptions && !LO.MSVCCompat) {
6420 for (auto *Attr : AS->getAttrs()) {
6421 auto *AA = dyn_cast<CXXAssumeAttr>(Attr);
6422 if (!AA)
6423 continue;
6424
6425 auto *Assumption = AA->getAssumption();
6426 if (Assumption->isValueDependent())
6427 return ESR_Failed;
6428
6429 if (Assumption->HasSideEffects(Info.Ctx))
6430 continue;
6431
6432 bool Value;
6433 if (!EvaluateAsBooleanCondition(Assumption, Value, Info))
6434 return ESR_Failed;
6435 if (!Value) {
6436 Info.CCEDiag(Assumption->getExprLoc(),
6437 diag::note_constexpr_assumption_failed);
6438 return ESR_Failed;
6439 }
6440 }
6441 }
6442
6443 return EvaluateStmt(Result, Info, SS, Case);
6444 }
6445
6446 case Stmt::CaseStmtClass:
6447 case Stmt::DefaultStmtClass:
6448 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
6449 case Stmt::CXXTryStmtClass:
6450 // Evaluate try blocks by evaluating all sub statements.
6451 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
6452 }
6453}
6454
6455/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
6456/// default constructor. If so, we'll fold it whether or not it's marked as
6457/// constexpr. If it is marked as constexpr, we will never implicitly define it,
6458/// so we need special handling.
6459static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
6460 const CXXConstructorDecl *CD,
6461 bool IsValueInitialization) {
6462 if (!CD->isTrivial() || !CD->isDefaultConstructor())
6463 return false;
6464
6465 // Value-initialization does not call a trivial default constructor, so such a
6466 // call is a core constant expression whether or not the constructor is
6467 // constexpr.
6468 if (!CD->isConstexpr() && !IsValueInitialization) {
6469 if (Info.getLangOpts().CPlusPlus11) {
6470 // FIXME: If DiagDecl is an implicitly-declared special member function,
6471 // we should be much more explicit about why it's not constexpr.
6472 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
6473 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
6474 Info.Note(CD->getLocation(), diag::note_declared_at);
6475 } else {
6476 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
6477 }
6478 }
6479 return true;
6480}
6481
6482/// CheckConstexprFunction - Check that a function can be called in a constant
6483/// expression.
6484static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
6486 const FunctionDecl *Definition,
6487 const Stmt *Body) {
6488 // Potential constant expressions can contain calls to declared, but not yet
6489 // defined, constexpr functions.
6490 if (Info.checkingPotentialConstantExpression() && !Definition &&
6491 Declaration->isConstexpr())
6492 return false;
6493
6494 // Bail out if the function declaration itself is invalid. We will
6495 // have produced a relevant diagnostic while parsing it, so just
6496 // note the problematic sub-expression.
6497 if (Declaration->isInvalidDecl()) {
6498 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
6499 return false;
6500 }
6501
6502 // DR1872: An instantiated virtual constexpr function can't be called in a
6503 // constant expression (prior to C++20). We can still constant-fold such a
6504 // call.
6505 if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) &&
6506 cast<CXXMethodDecl>(Declaration)->isVirtual())
6507 Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
6508
6509 if (Definition && Definition->isInvalidDecl()) {
6510 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
6511 return false;
6512 }
6513
6514 // Can we evaluate this function call?
6515 if (Definition && Body &&
6516 (Definition->isConstexpr() || (Info.CurrentCall->CanEvalMSConstexpr &&
6517 Definition->hasAttr<MSConstexprAttr>())))
6518 return true;
6519
6520 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
6521 // Special note for the assert() macro, as the normal error message falsely
6522 // implies we cannot use an assertion during constant evaluation.
6523 if (CallLoc.isMacroID() && DiagDecl->getIdentifier()) {
6524 // FIXME: Instead of checking for an implementation-defined function,
6525 // check and evaluate the assert() macro.
6526 StringRef Name = DiagDecl->getName();
6527 bool AssertFailed =
6528 Name == "__assert_rtn" || Name == "__assert_fail" || Name == "_wassert";
6529 if (AssertFailed) {
6530 Info.FFDiag(CallLoc, diag::note_constexpr_assert_failed);
6531 return false;
6532 }
6533 }
6534
6535 if (Info.getLangOpts().CPlusPlus11) {
6536 // If this function is not constexpr because it is an inherited
6537 // non-constexpr constructor, diagnose that directly.
6538 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
6539 if (CD && CD->isInheritingConstructor()) {
6540 auto *Inherited = CD->getInheritedConstructor().getConstructor();
6541 if (!Inherited->isConstexpr())
6542 DiagDecl = CD = Inherited;
6543 }
6544
6545 // FIXME: If DiagDecl is an implicitly-declared special member function
6546 // or an inheriting constructor, we should be much more explicit about why
6547 // it's not constexpr.
6548 if (CD && CD->isInheritingConstructor())
6549 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
6550 << CD->getInheritedConstructor().getConstructor()->getParent();
6551 else
6552 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
6553 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
6554 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
6555 } else {
6556 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
6557 }
6558 return false;
6559}
6560
6561namespace {
6562struct CheckDynamicTypeHandler {
6564 typedef bool result_type;
6565 bool failed() { return false; }
6566 bool found(APValue &Subobj, QualType SubobjType, APValue::LValueBase Base) {
6567 return true;
6568 }
6569 bool found(APSInt &Value, QualType SubobjType) { return true; }
6570 bool found(APFloat &Value, QualType SubobjType) { return true; }
6571};
6572} // end anonymous namespace
6573
6574/// Check that we can access the notional vptr of an object / determine its
6575/// dynamic type.
6576static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
6577 AccessKinds AK, bool Polymorphic) {
6578 if (This.Designator.Invalid)
6579 return false;
6580
6581 CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
6582
6583 if (!Obj)
6584 return false;
6585
6586 if (!Obj.Value) {
6587 // The object is not usable in constant expressions, so we can't inspect
6588 // its value to see if it's in-lifetime or what the active union members
6589 // are. We can still check for a one-past-the-end lvalue.
6590 if (This.Designator.isOnePastTheEnd() ||
6591 This.Designator.isMostDerivedAnUnsizedArray()) {
6592 Info.FFDiag(E, This.Designator.isOnePastTheEnd()
6593 ? diag::note_constexpr_access_past_end
6594 : diag::note_constexpr_access_unsized_array)
6595 << AK;
6596 return false;
6597 } else if (Polymorphic) {
6598 // Conservatively refuse to perform a polymorphic operation if we would
6599 // not be able to read a notional 'vptr' value.
6600 if (!Info.checkingPotentialConstantExpression() ||
6601 !This.AllowConstexprUnknown) {
6602 APValue Val;
6603 This.moveInto(Val);
6604 QualType StarThisType =
6605 Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
6606 Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
6607 << AK << Val.getAsString(Info.Ctx, StarThisType);
6608 }
6609 return false;
6610 }
6611 return true;
6612 }
6613
6614 CheckDynamicTypeHandler Handler{AK};
6615 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
6616}
6617
6618/// Check that the pointee of the 'this' pointer in a member function call is
6619/// either within its lifetime or in its period of construction or destruction.
6620static bool
6622 const LValue &This,
6623 const CXXMethodDecl *NamedMember) {
6624 return checkDynamicType(
6625 Info, E, This,
6626 isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false);
6627}
6628
6630 /// The dynamic class type of the object.
6632 /// The corresponding path length in the lvalue.
6633 unsigned PathLength;
6634};
6635
6636static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
6637 unsigned PathLength) {
6638 assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
6639 Designator.Entries.size() && "invalid path length");
6640 return (PathLength == Designator.MostDerivedPathLength)
6641 ? Designator.MostDerivedType->getAsCXXRecordDecl()
6642 : getAsBaseClass(Designator.Entries[PathLength - 1]);
6643}
6644
6645/// Determine the dynamic type of an object.
6646static std::optional<DynamicType> ComputeDynamicType(EvalInfo &Info,
6647 const Expr *E,
6648 LValue &This,
6649 AccessKinds AK) {
6650 // If we don't have an lvalue denoting an object of class type, there is no
6651 // meaningful dynamic type. (We consider objects of non-class type to have no
6652 // dynamic type.)
6653 if (!checkDynamicType(Info, E, This, AK,
6654 AK != AK_TypeId || This.AllowConstexprUnknown))
6655 return std::nullopt;
6656
6657 if (This.Designator.Invalid)
6658 return std::nullopt;
6659
6660 // Refuse to compute a dynamic type in the presence of virtual bases
6661 // before C++26. This shouldn't happen other than in constant-folding
6662 // situations, since literal types can't have virtual bases.
6663 const CXXRecordDecl *Class =
6664 This.Designator.MostDerivedType->getAsCXXRecordDecl();
6665 if (!Class || (!Info.getLangOpts().CPlusPlus26 && Class->getNumVBases())) {
6666 Info.FFDiag(E);
6667 return std::nullopt;
6668 }
6669
6670 // FIXME: For very deep class hierarchies, it might be beneficial to use a
6671 // binary search here instead. But the overwhelmingly common case is that
6672 // we're not in the middle of a constructor, so it probably doesn't matter
6673 // in practice.
6674 ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
6675 for (unsigned PathLength = This.Designator.MostDerivedPathLength;
6676 PathLength <= Path.size(); ++PathLength) {
6677 switch (Info.isEvaluatingCtorDtor(This.getLValueBase(),
6678 Path.slice(0, PathLength))) {
6679 case ConstructionPhase::Bases:
6680 case ConstructionPhase::DestroyingBases:
6681 // We're constructing or destroying a base class. This is not the dynamic
6682 // type.
6683 break;
6684
6685 case ConstructionPhase::None:
6686 case ConstructionPhase::AfterBases:
6687 case ConstructionPhase::AfterFields:
6688 case ConstructionPhase::Destroying:
6689 // We've finished constructing the base classes and not yet started
6690 // destroying them again, so this is the dynamic type.
6691 return DynamicType{getBaseClassType(This.Designator, PathLength),
6692 PathLength};
6693 }
6694 }
6695
6696 // CWG issue 1517: we're constructing a base class of the object described by
6697 // 'This', so that object has not yet begun its period of construction and
6698 // any polymorphic operation on it results in undefined behavior.
6699 Info.FFDiag(E);
6700 return std::nullopt;
6701}
6702
6703/// Perform virtual dispatch.
6705 EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
6706 llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
6707 std::optional<DynamicType> DynType = ComputeDynamicType(
6708 Info, E, This,
6710 if (!DynType)
6711 return nullptr;
6712
6713 // Find the final overrider. It must be declared in one of the classes on the
6714 // path from the dynamic type to the static type.
6715 // FIXME: If we ever allow literal types to have virtual base classes, that
6716 // won't be true.
6717 const CXXMethodDecl *Callee = Found;
6718 unsigned PathLength = DynType->PathLength;
6719 for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
6720 const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
6721 const CXXMethodDecl *Overrider =
6722 Found->getCorrespondingMethodDeclaredInClass(Class, false);
6723 if (Overrider) {
6724 Callee = Overrider;
6725 break;
6726 }
6727 }
6728
6729 // C++2a [class.abstract]p6:
6730 // the effect of making a virtual call to a pure virtual function [...] is
6731 // undefined
6732 if (Callee->isPureVirtual()) {
6733 Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
6734 Info.Note(Callee->getLocation(), diag::note_declared_at);
6735 return nullptr;
6736 }
6737
6738 // If necessary, walk the rest of the path to determine the sequence of
6739 // covariant adjustment steps to apply.
6740 if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
6741 Found->getReturnType())) {
6742 CovariantAdjustmentPath.push_back(Callee->getReturnType());
6743 for (unsigned CovariantPathLength = PathLength + 1;
6744 CovariantPathLength != This.Designator.Entries.size();
6745 ++CovariantPathLength) {
6746 const CXXRecordDecl *NextClass =
6747 getBaseClassType(This.Designator, CovariantPathLength);
6748 const CXXMethodDecl *Next =
6749 Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
6750 if (Next && !Info.Ctx.hasSameUnqualifiedType(
6751 Next->getReturnType(), CovariantAdjustmentPath.back()))
6752 CovariantAdjustmentPath.push_back(Next->getReturnType());
6753 }
6754 if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
6755 CovariantAdjustmentPath.back()))
6756 CovariantAdjustmentPath.push_back(Found->getReturnType());
6757 }
6758
6759 // Perform 'this' adjustment.
6760 if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
6761 return nullptr;
6762
6763 return Callee;
6764}
6765
6766/// Perform the adjustment from a value returned by a virtual function to
6767/// a value of the statically expected type, which may be a pointer or
6768/// reference to a base class of the returned type.
6769static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
6770 APValue &Result,
6771 ArrayRef<QualType> Path) {
6772 assert(Result.isLValue() &&
6773 "unexpected kind of APValue for covariant return");
6774 if (Result.isNullPointer())
6775 return true;
6776
6777 LValue LVal;
6778 LVal.setFrom(Info.Ctx, Result);
6779
6780 const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
6781 for (unsigned I = 1; I != Path.size(); ++I) {
6782 const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
6783 assert(OldClass && NewClass && "unexpected kind of covariant return");
6784 if (OldClass != NewClass &&
6785 !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
6786 return false;
6787 OldClass = NewClass;
6788 }
6789
6790 LVal.moveInto(Result);
6791 return true;
6792}
6793
6794/// Determine whether \p Base, which is known to be a direct base class of
6795/// \p Derived, is a public base class.
6796static bool isBaseClassPublic(const CXXRecordDecl *Derived,
6797 const CXXRecordDecl *Base) {
6798 for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
6799 if (BaseSpec.isVirtual())
6800 continue;
6801 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
6802 if (BaseClass && declaresSameEntity(BaseClass, Base))
6803 return BaseSpec.getAccessSpecifier() == AS_public;
6804 }
6805 for (const CXXBaseSpecifier &BaseSpec : Derived->vbases()) {
6806 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
6807 if (BaseClass && declaresSameEntity(BaseClass, Base))
6808 return BaseSpec.getAccessSpecifier() == AS_public;
6809 }
6810
6811 llvm_unreachable("Base is not a direct base of Derived");
6812}
6813
6814/// Apply the given dynamic cast operation on the provided lvalue.
6815///
6816/// This implements the hard case of dynamic_cast, requiring a "runtime check"
6817/// to find a suitable target subobject.
6818static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
6819 LValue &Ptr) {
6820 // We can't do anything with a non-symbolic pointer value.
6821 SubobjectDesignator &D = Ptr.Designator;
6822 if (D.Invalid)
6823 return false;
6824
6825 // C++ [expr.dynamic.cast]p6:
6826 // If v is a null pointer value, the result is a null pointer value.
6827 if (Ptr.isNullPointer() && !E->isGLValue())
6828 return true;
6829
6830 // For all the other cases, we need the pointer to point to an object within
6831 // its lifetime / period of construction / destruction, and we need to know
6832 // its dynamic type.
6833 std::optional<DynamicType> DynType =
6834 ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
6835 if (!DynType)
6836 return false;
6837
6838 // C++ [expr.dynamic.cast]p7:
6839 // If T is "pointer to cv void", then the result is a pointer to the most
6840 // derived object
6841 if (E->getType()->isVoidPointerType())
6842 return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
6843
6845 assert(C && "dynamic_cast target is not void pointer nor class");
6846 CanQualType CQT = Info.Ctx.getCanonicalTagType(C);
6847
6848 auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
6849 // C++ [expr.dynamic.cast]p9:
6850 if (!E->isGLValue()) {
6851 // The value of a failed cast to pointer type is the null pointer value
6852 // of the required result type.
6853 Ptr.setNull(Info.Ctx, E->getType());
6854 return true;
6855 }
6856
6857 // A failed cast to reference type throws [...] std::bad_cast.
6858 unsigned DiagKind;
6859 if (!Paths && (declaresSameEntity(DynType->Type, C) ||
6860 DynType->Type->isDerivedFrom(C)))
6861 DiagKind = 0;
6862 else if (!Paths || Paths->begin() == Paths->end())
6863 DiagKind = 1;
6864 else if (Paths->isAmbiguous(CQT))
6865 DiagKind = 2;
6866 else {
6867 assert(Paths->front().Access != AS_public && "why did the cast fail?");
6868 DiagKind = 3;
6869 }
6870 Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
6871 << DiagKind << Ptr.Designator.getType(Info.Ctx)
6872 << Info.Ctx.getCanonicalTagType(DynType->Type)
6873 << E->getType().getUnqualifiedType();
6874 return false;
6875 };
6876
6877 // Runtime check, phase 1:
6878 // Walk from the base subobject towards the derived object looking for the
6879 // target type.
6880 for (int PathLength = Ptr.Designator.Entries.size();
6881 PathLength >= (int)DynType->PathLength; --PathLength) {
6882 const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
6883 if (declaresSameEntity(Class, C))
6884 return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
6885 // We can only walk across public inheritance edges.
6886 if (PathLength > (int)DynType->PathLength &&
6887 !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
6888 Class))
6889 return RuntimeCheckFailed(nullptr);
6890 }
6891
6892 // Runtime check, phase 2:
6893 // Search the dynamic type for an unambiguous public base of type C.
6894 CXXBasePaths Paths(/*FindAmbiguities=*/true,
6895 /*RecordPaths=*/true, /*DetectVirtual=*/false);
6896 if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
6897 Paths.front().Access == AS_public) {
6898 // Downcast to the dynamic type...
6899 if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
6900 return false;
6901 // ... then upcast to the chosen base class subobject.
6902 for (CXXBasePathElement &Elem : Paths.front())
6903 if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
6904 return false;
6905 return true;
6906 }
6907
6908 // Otherwise, the runtime check fails.
6909 return RuntimeCheckFailed(&Paths);
6910}
6911
6912namespace {
6913struct StartLifetimeOfUnionMemberHandler {
6914 EvalInfo &Info;
6915 const Expr *LHSExpr;
6916 const FieldDecl *Field;
6917 bool DuringInit;
6918 bool Failed = false;
6919 static const AccessKinds AccessKind = AK_Assign;
6920
6921 typedef bool result_type;
6922 bool failed() { return Failed; }
6923 bool found(APValue &Subobj, QualType SubobjType, APValue::LValueBase Base) {
6924 // We are supposed to perform no initialization but begin the lifetime of
6925 // the object. We interpret that as meaning to do what default
6926 // initialization of the object would do if all constructors involved were
6927 // trivial:
6928 // * All base, non-variant member, and array element subobjects' lifetimes
6929 // begin
6930 // * No variant members' lifetimes begin
6931 // * All scalar subobjects whose lifetimes begin have indeterminate values
6932 assert(SubobjType->isUnionType());
6933 if (declaresSameEntity(Subobj.getUnionField(), Field)) {
6934 // This union member is already active. If it's also in-lifetime, there's
6935 // nothing to do.
6936 if (Subobj.getUnionValue().hasValue())
6937 return true;
6938 } else if (DuringInit) {
6939 // We're currently in the process of initializing a different union
6940 // member. If we carried on, that initialization would attempt to
6941 // store to an inactive union member, resulting in undefined behavior.
6942 Info.FFDiag(LHSExpr,
6943 diag::note_constexpr_union_member_change_during_init);
6944 return false;
6945 }
6947 Failed = !handleDefaultInitValue(Field->getType(), Result);
6948 Subobj.setUnion(Field, Result);
6949 return true;
6950 }
6951 bool found(APSInt &Value, QualType SubobjType) {
6952 llvm_unreachable("wrong value kind for union object");
6953 }
6954 bool found(APFloat &Value, QualType SubobjType) {
6955 llvm_unreachable("wrong value kind for union object");
6956 }
6957};
6958} // end anonymous namespace
6959
6960const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
6961
6962/// Handle a builtin simple-assignment or a call to a trivial assignment
6963/// operator whose left-hand side might involve a union member access. If it
6964/// does, implicitly start the lifetime of any accessed union elements per
6965/// C++20 [class.union]5.
6966static bool MaybeHandleUnionActiveMemberChange(EvalInfo &Info,
6967 const Expr *LHSExpr,
6968 const LValue &LHS) {
6969 if (LHS.InvalidBase || LHS.Designator.Invalid)
6970 return false;
6971
6973 // C++ [class.union]p5:
6974 // define the set S(E) of subexpressions of E as follows:
6975 unsigned PathLength = LHS.Designator.Entries.size();
6976 for (const Expr *E = LHSExpr; E != nullptr;) {
6977 // -- If E is of the form A.B, S(E) contains the elements of S(A)...
6978 if (auto *ME = dyn_cast<MemberExpr>(E)) {
6979 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
6980 // Note that we can't implicitly start the lifetime of a reference,
6981 // so we don't need to proceed any further if we reach one.
6982 if (!FD || FD->getType()->isReferenceType())
6983 break;
6984
6985 // ... and also contains A.B if B names a union member ...
6986 if (FD->getParent()->isUnion()) {
6987 // ... of a non-class, non-array type, or of a class type with a
6988 // trivial default constructor that is not deleted, or an array of
6989 // such types.
6990 auto *RD =
6991 FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6992 if (!RD || RD->hasTrivialDefaultConstructor())
6993 UnionPathLengths.push_back({PathLength - 1, FD});
6994 }
6995
6996 E = ME->getBase();
6997 --PathLength;
6998 assert(declaresSameEntity(FD,
6999 LHS.Designator.Entries[PathLength]
7000 .getAsBaseOrMember().getPointer()));
7001
7002 // -- If E is of the form A[B] and is interpreted as a built-in array
7003 // subscripting operator, S(E) is [S(the array operand, if any)].
7004 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
7005 // Step over an ArrayToPointerDecay implicit cast.
7006 auto *Base = ASE->getBase()->IgnoreImplicit();
7007 if (!Base->getType()->isArrayType())
7008 break;
7009
7010 E = Base;
7011 --PathLength;
7012
7013 } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
7014 // Step over a derived-to-base conversion.
7015 E = ICE->getSubExpr();
7016 if (ICE->getCastKind() == CK_NoOp)
7017 continue;
7018 if (ICE->getCastKind() != CK_DerivedToBase &&
7019 ICE->getCastKind() != CK_UncheckedDerivedToBase)
7020 break;
7021 // Walk path backwards as we walk up from the base to the derived class.
7022 for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
7023 if (Elt->isVirtual()) {
7024 // A class with virtual base classes never has a trivial default
7025 // constructor, so S(E) is empty in this case.
7026 E = nullptr;
7027 break;
7028 }
7029
7030 --PathLength;
7031 assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
7032 LHS.Designator.Entries[PathLength]
7033 .getAsBaseOrMember().getPointer()));
7034 }
7035
7036 // -- Otherwise, S(E) is empty.
7037 } else {
7038 break;
7039 }
7040 }
7041
7042 // Common case: no unions' lifetimes are started.
7043 if (UnionPathLengths.empty())
7044 return true;
7045
7046 // if modification of X [would access an inactive union member], an object
7047 // of the type of X is implicitly created
7048 CompleteObject Obj =
7049 findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
7050 if (!Obj)
7051 return false;
7052 for (std::pair<unsigned, const FieldDecl *> LengthAndField :
7053 llvm::reverse(UnionPathLengths)) {
7054 // Form a designator for the union object.
7055 SubobjectDesignator D = LHS.Designator;
7056 D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
7057
7058 bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) ==
7059 ConstructionPhase::AfterBases;
7060 StartLifetimeOfUnionMemberHandler StartLifetime{
7061 Info, LHSExpr, LengthAndField.second, DuringInit};
7062 if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
7063 return false;
7064 }
7065
7066 return true;
7067}
7068
7069static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg,
7070 CallRef Call, EvalInfo &Info, bool NonNull = false,
7071 APValue **EvaluatedArg = nullptr) {
7072 LValue LV;
7073 // Create the parameter slot and register its destruction. For a vararg
7074 // argument, create a temporary.
7075 // FIXME: For calling conventions that destroy parameters in the callee,
7076 // should we consider performing destruction when the function returns
7077 // instead?
7078 APValue &V = PVD ? Info.CurrentCall->createParam(Call, PVD, LV)
7079 : Info.CurrentCall->createTemporary(Arg, Arg->getType(),
7080 ScopeKind::Call, LV);
7081 if (!EvaluateInPlace(V, Info, LV, Arg))
7082 return false;
7083
7084 // Passing a null pointer to an __attribute__((nonnull)) parameter results in
7085 // undefined behavior, so is non-constant.
7086 if (NonNull && V.isLValue() && V.isNullPointer()) {
7087 Info.CCEDiag(Arg, diag::note_non_null_attribute_failed);
7088 return false;
7089 }
7090
7091 if (EvaluatedArg)
7092 *EvaluatedArg = &V;
7093
7094 return true;
7095}
7096
7097/// Evaluate the arguments to a function call.
7098static bool EvaluateArgs(ArrayRef<const Expr *> Args, CallRef Call,
7099 EvalInfo &Info, const FunctionDecl *Callee,
7100 bool RightToLeft = false,
7101 LValue *ObjectArg = nullptr) {
7102 bool Success = true;
7103 llvm::SmallBitVector ForbiddenNullArgs;
7104 if (Callee->hasAttr<NonNullAttr>()) {
7105 ForbiddenNullArgs.resize(Args.size());
7106 for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
7107 if (!Attr->args_size()) {
7108 ForbiddenNullArgs.set();
7109 break;
7110 } else
7111 for (auto Idx : Attr->args()) {
7112 unsigned ASTIdx = Idx.getASTIndex();
7113 if (ASTIdx >= Args.size())
7114 continue;
7115 ForbiddenNullArgs[ASTIdx] = true;
7116 }
7117 }
7118 }
7119 for (unsigned I = 0; I < Args.size(); I++) {
7120 unsigned Idx = RightToLeft ? Args.size() - I - 1 : I;
7121 const ParmVarDecl *PVD =
7122 Idx < Callee->getNumParams() ? Callee->getParamDecl(Idx) : nullptr;
7123 bool NonNull = !ForbiddenNullArgs.empty() && ForbiddenNullArgs[Idx];
7124 APValue *That = nullptr;
7125 if (!EvaluateCallArg(PVD, Args[Idx], Call, Info, NonNull, &That)) {
7126 // If we're checking for a potential constant expression, evaluate all
7127 // initializers even if some of them fail.
7128 if (!Info.noteFailure())
7129 return false;
7130 Success = false;
7131 }
7132 if (PVD && PVD->isExplicitObjectParameter() && That && That->isLValue())
7133 ObjectArg->setFrom(Info.Ctx, *That);
7134 }
7135 return Success;
7136}
7137
7138/// Perform a trivial copy from Param, which is the parameter of a copy or move
7139/// constructor or assignment operator.
7140static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param,
7141 const Expr *E, APValue &Result,
7142 bool CopyObjectRepresentation) {
7143 // Find the reference argument.
7144 CallStackFrame *Frame = Info.CurrentCall;
7145 APValue *RefValue = Info.getParamSlot(Frame->Arguments, Param);
7146 if (!RefValue) {
7147 Info.FFDiag(E);
7148 return false;
7149 }
7150
7151 // Copy out the contents of the RHS object.
7152 LValue RefLValue;
7153 RefLValue.setFrom(Info.Ctx, *RefValue);
7155 Info, E, Param->getType().getNonReferenceType(), RefLValue, Result,
7156 CopyObjectRepresentation);
7157}
7158
7159/// Evaluate a function call.
7161 const FunctionDecl *Callee,
7162 const LValue *ObjectArg, const Expr *E,
7163 ArrayRef<const Expr *> Args, CallRef Call,
7164 const Stmt *Body, EvalInfo &Info,
7165 APValue &Result, const LValue *ResultSlot) {
7166 if (!Info.CheckCallLimit(CallLoc))
7167 return false;
7168
7169 CallStackFrame Frame(Info, E->getSourceRange(), Callee, ObjectArg, E, Call);
7170
7171 // For a trivial copy or move assignment, perform an APValue copy. This is
7172 // essential for unions, where the operations performed by the assignment
7173 // operator cannot be represented as statements.
7174 //
7175 // Skip this for non-union classes with no fields; in that case, the defaulted
7176 // copy/move does not actually read the object.
7177 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
7178
7179 auto IsTrivialMemoryOperation = [&](const CXXMethodDecl *MD) {
7180 if (!MD || !MD->isDefaulted())
7181 return false;
7183 return false;
7184 return MD->getParent()->isUnion() ||
7185 (MD->isTrivial() &&
7187 };
7188
7189 if (IsTrivialMemoryOperation(MD)) {
7190 unsigned ExplicitOffset = MD->isExplicitObjectMemberFunction() ? 1 : 0;
7191 assert(ObjectArg);
7192 APValue RHSValue;
7193 if (!handleTrivialCopy(Info, MD->getParamDecl(0), Args[0], RHSValue,
7194 MD->getParent()->isUnion()))
7195 return false;
7196
7197 LValue Obj;
7198 if (!handleAssignment(Info, Args[ExplicitOffset], *ObjectArg,
7200 RHSValue))
7201 return false;
7202 ObjectArg->moveInto(Result);
7203 return true;
7204 } else if (MD && isLambdaCallOperator(MD)) {
7205 // We're in a lambda; determine the lambda capture field maps unless we're
7206 // just constexpr checking a lambda's call operator. constexpr checking is
7207 // done before the captures have been added to the closure object (unless
7208 // we're inferring constexpr-ness), so we don't have access to them in this
7209 // case. But since we don't need the captures to constexpr check, we can
7210 // just ignore them.
7211 if (!Info.checkingPotentialConstantExpression())
7212 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
7213 Frame.LambdaThisCaptureField);
7214 }
7215
7216 StmtResult Ret = {Result, ResultSlot};
7217 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
7218 if (ESR == ESR_Succeeded) {
7219 if (Callee->getReturnType()->isVoidType())
7220 return true;
7221 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
7222 }
7223 return ESR == ESR_Returned;
7224}
7225
7226static bool HandleConstructorCall(const Expr *E, const LValue &This,
7227 CallRef Call,
7228 const CXXConstructorDecl *Definition,
7229 EvalInfo &Info, APValue &Result,
7230 bool IsCompleteClass = true);
7231
7232static bool HandleConstructorCall(const Expr *E, const LValue &This,
7235 EvalInfo &Info, APValue &Result,
7236 bool IsCompleteClass = true) {
7237 CallScopeRAII CallScope(Info);
7238 CallRef Call = Info.CurrentCall->createCall(Definition);
7239 if (!EvaluateArgs(Args, Call, Info, Definition))
7240 return false;
7241
7242 return HandleConstructorCall(E, This, Call, Definition, Info, Result,
7243 IsCompleteClass) &&
7244 CallScope.destroy();
7245}
7246
7247/// Evaluate a constructor call.
7248static bool HandleConstructorCall(const Expr *E, const LValue &This,
7249 CallRef Call,
7251 EvalInfo &Info, APValue &Result,
7252 bool IsCompleteClass) {
7253
7254 SourceLocation CallLoc = E->getExprLoc();
7255 if (!Info.CheckCallLimit(CallLoc))
7256 return false;
7257
7258 const CXXRecordDecl *RD = Definition->getParent();
7259 if (!Info.getLangOpts().CPlusPlus26 && RD->getNumVBases()) {
7260 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
7261 return false;
7262 }
7263
7264 EvalInfo::EvaluatingConstructorRAII EvalObj(
7265 Info,
7266 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
7267 RD->getNumBases());
7268 CallStackFrame Frame(Info, E->getSourceRange(), Definition, &This, E, Call);
7269
7270 // FIXME: Creating an APValue just to hold a nonexistent return value is
7271 // wasteful.
7272 APValue RetVal;
7273 StmtResult Ret = {RetVal, nullptr};
7274
7275 // If it's a delegating constructor, delegate.
7276 if (Definition->isDelegatingConstructor()) {
7278 if ((*I)->getInit()->isValueDependent()) {
7279 if (!EvaluateDependentExpr((*I)->getInit(), Info))
7280 return false;
7281 } else {
7282 FullExpressionRAII InitScope(Info);
7283 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) ||
7284 !InitScope.destroy())
7285 return false;
7286 }
7287 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
7288 }
7289
7290 // For a trivial copy or move constructor, perform an APValue copy. This is
7291 // essential for unions (or classes with anonymous union members), where the
7292 // operations performed by the constructor cannot be represented by
7293 // ctor-initializers.
7294 //
7295 // Skip this for empty non-union classes; we should not perform an
7296 // lvalue-to-rvalue conversion on them because their copy constructor does not
7297 // actually read them.
7298 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
7299 (Definition->getParent()->isUnion() ||
7300 (Definition->isTrivial() &&
7302 return handleTrivialCopy(Info, Definition->getParamDecl(0), E, Result,
7303 Definition->getParent()->isUnion());
7304 }
7305
7306 // Reserve space for the struct members.
7307 if (!Result.hasValue()) {
7308 if (!RD->isUnion()) {
7309 unsigned NonVirtualBases = countNonVirtualBases(RD);
7310 Result = APValue(APValue::UninitStruct(), NonVirtualBases,
7311 RD->getNumFields(), RD->getNumVBases());
7312 } else
7313 // A union starts with no active member.
7314 Result = APValue((const FieldDecl*)nullptr);
7315 }
7316
7317 if (RD->isInvalidDecl()) return false;
7318 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7319
7320 // A scope for temporaries lifetime-extended by reference members.
7321 BlockScopeRAII LifetimeExtendedScope(Info);
7322
7323 bool Success = true;
7324 unsigned BasesSeen = 0;
7325 unsigned VirtualBasesSeen = 0;
7326 unsigned NonVirtualBases = countNonVirtualBases(RD);
7327
7329 auto SkipToField = [&](FieldDecl *FD, bool Indirect) {
7330 // We might be initializing the same field again if this is an indirect
7331 // field initialization.
7332 if (FieldIt == RD->field_end() ||
7333 FieldIt->getFieldIndex() > FD->getFieldIndex()) {
7334 assert(Indirect && "fields out of order?");
7335 return;
7336 }
7337
7338 // Default-initialize any fields with no explicit initializer.
7339 for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
7340 assert(FieldIt != RD->field_end() && "missing field?");
7341 if (!FieldIt->isUnnamedBitField())
7343 FieldIt->getType(),
7344 Result.getStructField(FieldIt->getFieldIndex()));
7345 }
7346 ++FieldIt;
7347 };
7348 for (const auto *I : Definition->inits()) {
7349 LValue Subobject = This;
7350 LValue SubobjectParent = This;
7351 APValue *Value = &Result;
7352
7353 // Determine the subobject to initialize.
7354 FieldDecl *FD = nullptr;
7355 if (I->isBaseInitializer()) {
7356 QualType BaseType(I->getBaseClass(), 0);
7357 if (I->isBaseVirtual()) {
7358 if (This.pointsToCompleteClass(RD)) {
7359 if (!HandleLValueDirectVirtualBase(Info, I->getInit(), Subobject, RD,
7360 BaseType->getAsCXXRecordDecl(),
7361 &Layout))
7362 return false;
7363 Value = &Result.getStructVirtualBase(VirtualBasesSeen++);
7364 } else {
7365 continue;
7366 }
7367
7368 } else {
7369 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
7370 BaseType->getAsCXXRecordDecl(), &Layout))
7371 return false;
7372 Value = &Result.getStructBase(BasesSeen++);
7373 }
7374 } else if ((FD = I->getMember())) {
7375 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
7376 return false;
7377 if (RD->isUnion()) {
7378 Result = APValue(FD);
7379 Value = &Result.getUnionValue();
7380 } else {
7381 SkipToField(FD, false);
7382 Value = &Result.getStructField(FD->getFieldIndex());
7383 }
7384 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
7385 // Walk the indirect field decl's chain to find the object to initialize,
7386 // and make sure we've initialized every step along it.
7387 auto IndirectFieldChain = IFD->chain();
7388 for (auto *C : IndirectFieldChain) {
7389 FD = cast<FieldDecl>(C);
7391 // Switch the union field if it differs. This happens if we had
7392 // preceding zero-initialization, and we're now initializing a union
7393 // subobject other than the first.
7394 // FIXME: In this case, the values of the other subobjects are
7395 // specified, since zero-initialization sets all padding bits to zero.
7396 if (!Value->hasValue() ||
7397 (Value->isUnion() &&
7398 !declaresSameEntity(Value->getUnionField(), FD))) {
7399 if (CD->isUnion())
7400 *Value = APValue(FD);
7401 else
7402 // FIXME: This immediately starts the lifetime of all members of
7403 // an anonymous struct. It would be preferable to strictly start
7404 // member lifetime in initialization order.
7405 Success &= handleDefaultInitValue(Info.Ctx.getCanonicalTagType(CD),
7406 *Value);
7407 }
7408 // Store Subobject as its parent before updating it for the last element
7409 // in the chain.
7410 if (C == IndirectFieldChain.back())
7411 SubobjectParent = Subobject;
7412 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
7413 return false;
7414 if (CD->isUnion())
7415 Value = &Value->getUnionValue();
7416 else {
7417 if (C == IndirectFieldChain.front() && !RD->isUnion())
7418 SkipToField(FD, true);
7419 Value = &Value->getStructField(FD->getFieldIndex());
7420 }
7421 }
7422 } else {
7423 llvm_unreachable("unknown base initializer kind");
7424 }
7425
7426 // Need to override This for implicit field initializers as in this case
7427 // This refers to innermost anonymous struct/union containing initializer,
7428 // not to currently constructed class.
7429 const Expr *Init = I->getInit();
7430 if (Init->isValueDependent()) {
7431 if (!EvaluateDependentExpr(Init, Info))
7432 return false;
7433 } else {
7434 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
7436 FullExpressionRAII InitScope(Info);
7437 if (FD && FD->getType()->isReferenceType() &&
7438 !FD->getType()->isFunctionReferenceType()) {
7439 LValue Result;
7441 *Value)) {
7442 if (!Info.noteFailure())
7443 return false;
7444 Success = false;
7445 }
7446 } else if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
7447 (FD && FD->isBitField() &&
7448 !truncateBitfieldValue(Info, Init, *Value, FD))) {
7449 // If we're checking for a potential constant expression, evaluate all
7450 // initializers even if some of them fail.
7451 if (!Info.noteFailure())
7452 return false;
7453 Success = false;
7454 }
7455 }
7456
7457 // This is the point at which the dynamic type of the object becomes this
7458 // class type.
7459 if (I->isBaseInitializer() && BasesSeen == NonVirtualBases)
7460 EvalObj.finishedConstructingBases();
7461 }
7462
7463 // Default-initialize any remaining fields.
7464 if (!RD->isUnion()) {
7465 for (; FieldIt != RD->field_end(); ++FieldIt) {
7466 if (!FieldIt->isUnnamedBitField())
7468 FieldIt->getType(),
7469 Result.getStructField(FieldIt->getFieldIndex()));
7470 }
7471 }
7472
7473 EvalObj.finishedConstructingFields();
7474
7475 return Success &&
7476 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed &&
7477 LifetimeExtendedScope.destroy();
7478}
7479
7480static bool HandleDestructionImpl(EvalInfo &Info, SourceRange CallRange,
7481 const LValue &This, APValue &Value,
7482 QualType T, bool IsCompleteClass = true) {
7483 // Objects can only be destroyed while they're within their lifetimes.
7484 // FIXME: We have no representation for whether an object of type nullptr_t
7485 // is in its lifetime; it usually doesn't matter. Perhaps we should model it
7486 // as indeterminate instead?
7487 if (Value.isAbsent() && !T->isNullPtrType()) {
7488 APValue Printable;
7489 This.moveInto(Printable);
7490 Info.FFDiag(CallRange.getBegin(),
7491 diag::note_constexpr_destroy_out_of_lifetime)
7492 << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T));
7493 return false;
7494 }
7495
7496 // Invent an expression for location purposes.
7497 // FIXME: We shouldn't need to do this.
7498 OpaqueValueExpr LocE(CallRange.getBegin(), Info.Ctx.IntTy, VK_PRValue);
7499
7500 // For arrays, destroy elements right-to-left.
7501 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) {
7502 uint64_t Size = CAT->getZExtSize();
7503 QualType ElemT = CAT->getElementType();
7504
7505 if (!CheckArraySize(Info, CAT, CallRange.getBegin()))
7506 return false;
7507
7508 LValue ElemLV = This;
7509 ElemLV.addArray(Info, &LocE, CAT);
7510 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size))
7511 return false;
7512
7513 // Ensure that we have actual array elements available to destroy; the
7514 // destructors might mutate the value, so we can't run them on the array
7515 // filler.
7516 if (Size && Size > Value.getArrayInitializedElts())
7517 expandArray(Value, Value.getArraySize() - 1);
7518
7519 // The size of the array might have been reduced by
7520 // a placement new.
7521 for (Size = Value.getArraySize(); Size != 0; --Size) {
7522 APValue &Elem = Value.getArrayInitializedElt(Size - 1);
7523 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) ||
7524 !HandleDestructionImpl(Info, CallRange, ElemLV, Elem, ElemT))
7525 return false;
7526 }
7527
7528 // End the lifetime of this array now.
7529 Value = APValue();
7530 return true;
7531 }
7532
7533 const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
7534 if (!RD) {
7535 if (T.isDestructedType()) {
7536 Info.FFDiag(CallRange.getBegin(),
7537 diag::note_constexpr_unsupported_destruction)
7538 << T;
7539 return false;
7540 }
7541
7542 Value = APValue();
7543 return true;
7544 }
7545
7546 if (!Info.getLangOpts().CPlusPlus26 && RD->getNumVBases()) {
7547 Info.FFDiag(CallRange.getBegin(), diag::note_constexpr_virtual_base) << RD;
7548 return false;
7549 }
7550
7551 // If an anonymous union would be destroyed, some enclosing destructor must
7552 // have been explicitly defined, and the anonymous union destruction should
7553 // have no effect.
7554 if (RD->isAnonymousStructOrUnion() && RD->isUnion()) {
7555 Value = APValue();
7556 return true;
7557 }
7558
7559 const CXXDestructorDecl *DD = RD->getDestructor();
7560 if (!DD && !RD->hasTrivialDestructor()) {
7561 Info.FFDiag(CallRange.getBegin());
7562 return false;
7563 }
7564
7565 if (!DD || DD->isTrivial()) {
7566 // A trivial destructor just ends the lifetime of the object. Check for
7567 // this case before checking for a body, because we might not bother
7568 // building a body for a trivial destructor. Note that it doesn't matter
7569 // whether the destructor is constexpr in this case; all trivial
7570 // destructors are constexpr.
7571 Value = APValue();
7572 return true;
7573 }
7574
7575 if (!Info.CheckCallLimit(CallRange.getBegin()))
7576 return false;
7577
7578 const FunctionDecl *Definition = nullptr;
7579 const Stmt *Body = DD->getBody(Definition);
7580
7581 if (!CheckConstexprFunction(Info, CallRange.getBegin(), DD, Definition, Body))
7582 return false;
7583
7584 CallStackFrame Frame(Info, CallRange, Definition, &This, /*CallExpr=*/nullptr,
7585 CallRef());
7586
7587 // We're now in the period of destruction of this object.
7588 EvalInfo::EvaluatingDestructorRAII EvalObj(
7589 Info,
7590 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries});
7591 unsigned NonVirtualBases = countNonVirtualBases(RD);
7592 unsigned NumVirtualBases = RD->getNumVBases();
7593 unsigned BasesLeft = NonVirtualBases;
7594 if (!EvalObj.DidInsert) {
7595 // C++2a [class.dtor]p19:
7596 // the behavior is undefined if the destructor is invoked for an object
7597 // whose lifetime has ended
7598 // (Note that formally the lifetime ends when the period of destruction
7599 // begins, even though certain uses of the object remain valid until the
7600 // period of destruction ends.)
7601 Info.FFDiag(CallRange.getBegin(), diag::note_constexpr_double_destroy);
7602 return false;
7603 }
7604
7605 // FIXME: Creating an APValue just to hold a nonexistent return value is
7606 // wasteful.
7607 APValue RetVal;
7608 StmtResult Ret = {RetVal, nullptr};
7609 if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed)
7610 return false;
7611
7612 // A union destructor does not implicitly destroy its members.
7613 if (RD->isUnion())
7614 return true;
7615
7616 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7617
7618 // We don't have a good way to iterate fields in reverse, so collect all the
7619 // fields first and then walk them backwards.
7620 SmallVector<FieldDecl*, 16> Fields(RD->fields());
7621 for (const FieldDecl *FD : llvm::reverse(Fields)) {
7622 if (FD->isUnnamedBitField())
7623 continue;
7624
7625 LValue Subobject = This;
7626 if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout))
7627 return false;
7628
7629 APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex());
7630 if (!HandleDestructionImpl(Info, CallRange, Subobject, *SubobjectValue,
7631 FD->getType()))
7632 return false;
7633 }
7634
7635 if (BasesLeft != 0 || NumVirtualBases != 0)
7636 EvalObj.startedDestroyingBases();
7637
7638 // Destroy base classes in reverse order.
7639 for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) {
7640 if (Base.isVirtual())
7641 continue;
7642 --BasesLeft;
7643
7644 QualType BaseType = Base.getType();
7645 LValue Subobject = This;
7646 if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD,
7647 BaseType->getAsCXXRecordDecl(), &Layout))
7648 return false;
7649
7650 APValue *SubobjectValue = &Value.getStructBase(BasesLeft);
7651 if (!HandleDestructionImpl(Info, CallRange, Subobject, *SubobjectValue,
7652 BaseType, /*IsCompleteClass=*/false))
7653 return false;
7654 }
7655 assert(BasesLeft == 0 && "NumBases was wrong?");
7656
7657 // Virtual bases.
7658 if (IsCompleteClass) {
7659 unsigned VirtualBasesLeft = NumVirtualBases;
7660 for (const CXXBaseSpecifier &Base : llvm::reverse(RD->vbases())) {
7661 --VirtualBasesLeft;
7662
7663 QualType BaseType = Base.getType();
7664 LValue Subobject = This;
7665 if (!HandleLValueDirectVirtualBase(Info, &LocE, Subobject, RD,
7666 BaseType->getAsCXXRecordDecl(),
7667 &Layout))
7668 return false;
7669
7670 APValue *SubobjectValue = &Value.getStructVirtualBase(VirtualBasesLeft);
7671 if (!HandleDestructionImpl(Info, CallRange, Subobject, *SubobjectValue,
7672 BaseType, /*IsCompleteClass=*/false))
7673 return false;
7674 }
7675 assert(VirtualBasesLeft == 0 && "NumVirtualBases was wrong?");
7676 }
7677
7678 // The period of destruction ends now. The object is gone.
7679 Value = APValue();
7680 return true;
7681}
7682
7683namespace {
7684struct DestroyObjectHandler {
7685 EvalInfo &Info;
7686 const Expr *E;
7687 const LValue &This;
7688 const AccessKinds AccessKind;
7689
7690 typedef bool result_type;
7691 bool failed() { return false; }
7692 bool found(APValue &Subobj, QualType SubobjType, APValue::LValueBase Base) {
7693 return HandleDestructionImpl(Info, E->getSourceRange(), This, Subobj,
7694 SubobjType);
7695 }
7696 bool found(APSInt &Value, QualType SubobjType) {
7697 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
7698 return false;
7699 }
7700 bool found(APFloat &Value, QualType SubobjType) {
7701 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
7702 return false;
7703 }
7704};
7705}
7706
7707/// Perform a destructor or pseudo-destructor call on the given object, which
7708/// might in general not be a complete object.
7709static bool HandleDestruction(EvalInfo &Info, const Expr *E,
7710 const LValue &This, QualType ThisType) {
7711 CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType);
7712 DestroyObjectHandler Handler = {Info, E, This, AK_Destroy};
7713 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
7714}
7715
7716/// Destroy and end the lifetime of the given complete object.
7717static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
7719 QualType T) {
7720 // If we've had an unmodeled side-effect, we can't rely on mutable state
7721 // (such as the object we're about to destroy) being correct.
7722 if (Info.EvalStatus.HasSideEffects)
7723 return false;
7724
7725 LValue LV;
7726 LV.set({LVBase});
7727 return HandleDestructionImpl(Info, Loc, LV, Value, T);
7728}
7729
7730/// Perform a call to 'operator new' or to `__builtin_operator_new'.
7731static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E,
7732 LValue &Result) {
7733 if (Info.checkingPotentialConstantExpression() ||
7734 Info.SpeculativeEvaluationDepth)
7735 return false;
7736
7737 // This is permitted only within a call to std::allocator<T>::allocate.
7738 auto Caller = Info.getStdAllocatorCaller("allocate");
7739 if (!Caller) {
7740 Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20
7741 ? diag::note_constexpr_new_untyped
7742 : diag::note_constexpr_new);
7743 return false;
7744 }
7745
7746 QualType ElemType = Caller.ElemType;
7747 if (ElemType->isIncompleteType() || ElemType->isFunctionType()) {
7748 Info.FFDiag(E->getExprLoc(),
7749 diag::note_constexpr_new_not_complete_object_type)
7750 << (ElemType->isIncompleteType() ? 0 : 1) << ElemType;
7751 return false;
7752 }
7753
7754 APSInt ByteSize;
7755 if (!EvaluateInteger(E->getArg(0), ByteSize, Info))
7756 return false;
7757 bool IsNothrow = false;
7758 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) {
7759 EvaluateIgnoredValue(Info, E->getArg(I));
7760 IsNothrow |= E->getType()->isNothrowT();
7761 }
7762
7763 CharUnits ElemSize;
7764 if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize))
7765 return false;
7766 APInt Size, Remainder;
7767 APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity());
7768 APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder);
7769 if (Remainder != 0) {
7770 // This likely indicates a bug in the implementation of 'std::allocator'.
7771 Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size)
7772 << ByteSize << APSInt(ElemSizeAP, true) << ElemType;
7773 return false;
7774 }
7775
7776 if (!Info.CheckArraySize(E->getBeginLoc(), ByteSize.getActiveBits(),
7777 Size.getZExtValue(), /*Diag=*/!IsNothrow)) {
7778 if (IsNothrow) {
7779 Result.setNull(Info.Ctx, E->getType());
7780 return true;
7781 }
7782 return false;
7783 }
7784
7785 QualType AllocType = Info.Ctx.getConstantArrayType(
7786 ElemType, Size, nullptr, ArraySizeModifier::Normal, 0);
7787 APValue *Val = Info.createHeapAlloc(Caller.Call, AllocType, Result);
7788 *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue());
7789 Result.addArray(Info, E, cast<ConstantArrayType>(AllocType));
7790 return true;
7791}
7792
7794 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
7795 if (CXXDestructorDecl *DD = RD->getDestructor())
7796 return DD->isVirtual();
7797 return false;
7798}
7799
7801 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
7802 if (CXXDestructorDecl *DD = RD->getDestructor())
7803 return DD->isVirtual() ? DD->getOperatorDelete() : nullptr;
7804 return nullptr;
7805}
7806
7807/// Check that the given object is a suitable pointer to a heap allocation that
7808/// still exists and is of the right kind for the purpose of a deletion.
7809///
7810/// On success, returns the heap allocation to deallocate. On failure, produces
7811/// a diagnostic and returns std::nullopt.
7812static std::optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E,
7813 const LValue &Pointer,
7814 DynAlloc::Kind DeallocKind) {
7815 auto PointerAsString = [&] {
7816 return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy);
7817 };
7818
7819 DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>();
7820 if (!DA) {
7821 Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc)
7822 << PointerAsString();
7823 if (Pointer.Base)
7824 NoteLValueLocation(Info, Pointer.Base);
7825 return std::nullopt;
7826 }
7827
7828 std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
7829 if (!Alloc) {
7830 Info.FFDiag(E, diag::note_constexpr_double_delete);
7831 return std::nullopt;
7832 }
7833
7834 if (DeallocKind != (*Alloc)->getKind()) {
7835 QualType AllocType = Pointer.Base.getDynamicAllocType();
7836 Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch)
7837 << DeallocKind << (*Alloc)->getKind() << AllocType;
7838 NoteLValueLocation(Info, Pointer.Base);
7839 return std::nullopt;
7840 }
7841
7842 bool Subobject = false;
7843 if (DeallocKind == DynAlloc::New) {
7844 Subobject = Pointer.Designator.MostDerivedPathLength != 0 ||
7845 Pointer.Designator.isOnePastTheEnd();
7846 } else {
7847 Subobject = Pointer.Designator.Entries.size() != 1 ||
7848 Pointer.Designator.Entries[0].getAsArrayIndex() != 0;
7849 }
7850 if (Subobject) {
7851 Info.FFDiag(E, diag::note_constexpr_delete_subobject)
7852 << PointerAsString() << Pointer.Designator.isOnePastTheEnd();
7853 return std::nullopt;
7854 }
7855
7856 return Alloc;
7857}
7858
7859// Perform a call to 'operator delete' or '__builtin_operator_delete'.
7860static bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) {
7861 if (Info.checkingPotentialConstantExpression() ||
7862 Info.SpeculativeEvaluationDepth)
7863 return false;
7864
7865 // This is permitted only within a call to std::allocator<T>::deallocate.
7866 if (!Info.getStdAllocatorCaller("deallocate")) {
7867 Info.FFDiag(E->getExprLoc());
7868 return true;
7869 }
7870
7871 LValue Pointer;
7872 if (!EvaluatePointer(E->getArg(0), Pointer, Info))
7873 return false;
7874 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
7875 EvaluateIgnoredValue(Info, E->getArg(I));
7876
7877 if (Pointer.Designator.Invalid)
7878 return false;
7879
7880 // Deleting a null pointer would have no effect, but it's not permitted by
7881 // std::allocator<T>::deallocate's contract.
7882 if (Pointer.isNullPointer()) {
7883 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_deallocate_null);
7884 return true;
7885 }
7886
7887 if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator))
7888 return false;
7889
7890 Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>());
7891 return true;
7892}
7893
7894//===----------------------------------------------------------------------===//
7895// Generic Evaluation
7896//===----------------------------------------------------------------------===//
7897namespace {
7898
7899class BitCastBuffer {
7900 // FIXME: We're going to need bit-level granularity when we support
7901 // bit-fields.
7902 // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
7903 // we don't support a host or target where that is the case. Still, we should
7904 // use a more generic type in case we ever do.
7905 SmallVector<std::optional<unsigned char>, 32> Bytes;
7906
7907 static_assert(std::numeric_limits<unsigned char>::digits >= 8,
7908 "Need at least 8 bit unsigned char");
7909
7910 bool TargetIsLittleEndian;
7911
7912public:
7913 BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
7914 : Bytes(Width.getQuantity()),
7915 TargetIsLittleEndian(TargetIsLittleEndian) {}
7916
7917 [[nodiscard]] bool readObject(CharUnits Offset, CharUnits Width,
7918 SmallVectorImpl<unsigned char> &Output) const {
7919 for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
7920 // If a byte of an integer is uninitialized, then the whole integer is
7921 // uninitialized.
7922 if (!Bytes[I.getQuantity()])
7923 return false;
7924 Output.push_back(*Bytes[I.getQuantity()]);
7925 }
7926 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
7927 std::reverse(Output.begin(), Output.end());
7928 return true;
7929 }
7930
7931 void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
7932 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
7933 std::reverse(Input.begin(), Input.end());
7934
7935 size_t Index = 0;
7936 for (unsigned char Byte : Input) {
7937 assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
7938 Bytes[Offset.getQuantity() + Index] = Byte;
7939 ++Index;
7940 }
7941 }
7942
7943 size_t size() { return Bytes.size(); }
7944};
7945
7946/// Traverse an APValue to produce an BitCastBuffer, emulating how the current
7947/// target would represent the value at runtime.
7948class APValueToBufferConverter {
7949 EvalInfo &Info;
7950 BitCastBuffer Buffer;
7951 const CastExpr *BCE;
7952
7953 APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
7954 const CastExpr *BCE)
7955 : Info(Info),
7956 Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
7957 BCE(BCE) {}
7958
7959 bool visit(const APValue &Val, QualType Ty) {
7960 return visit(Val, Ty, CharUnits::fromQuantity(0));
7961 }
7962
7963 // Write out Val with type Ty into Buffer starting at Offset.
7964 bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
7965 assert((size_t)Offset.getQuantity() <= Buffer.size());
7966
7967 // As a special case, nullptr_t has an indeterminate value.
7968 if (Ty->isNullPtrType())
7969 return true;
7970
7971 // Dig through Src to find the byte at SrcOffset.
7972 switch (Val.getKind()) {
7974 case APValue::None:
7975 return true;
7976
7977 case APValue::Int:
7978 return visitInt(Val.getInt(), Ty, Offset);
7979 case APValue::Float:
7980 return visitFloat(Val.getFloat(), Ty, Offset);
7981 case APValue::Array:
7982 return visitArray(Val, Ty, Offset);
7983 case APValue::Struct:
7984 return visitRecord(Val, Ty, Offset);
7985 case APValue::Vector:
7986 return visitVector(Val, Ty, Offset);
7987
7990 return visitComplex(Val, Ty, Offset);
7992 // FIXME: We should support these.
7993
7994 case APValue::LValue:
7995 case APValue::Matrix:
7996 case APValue::Union:
7999 Info.FFDiag(BCE->getBeginLoc(),
8000 diag::note_constexpr_bit_cast_unsupported_type)
8001 << Ty;
8002 return false;
8003 }
8004 }
8005 llvm_unreachable("Unhandled APValue::ValueKind");
8006 }
8007
8008 bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
8009 const RecordDecl *RD = Ty->getAsRecordDecl();
8010 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
8011
8012 // Visit the base classes.
8013 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
8014 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
8015 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
8016 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
8017 const APValue &Base = Val.getStructBase(I);
8018
8019 // Can happen in error cases.
8020 if (!Base.isStruct())
8021 return false;
8022
8023 if (!visitRecord(Base, BS.getType(),
8024 Layout.getBaseClassOffset(BaseDecl) + Offset))
8025 return false;
8026 }
8027 }
8028
8029 // Visit the fields.
8030 unsigned FieldIdx = 0;
8031 for (FieldDecl *FD : RD->fields()) {
8032 if (FD->isBitField()) {
8033 Info.FFDiag(BCE->getBeginLoc(),
8034 diag::note_constexpr_bit_cast_unsupported_bitfield);
8035 return false;
8036 }
8037
8038 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
8039
8040 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
8041 "only bit-fields can have sub-char alignment");
8042 CharUnits FieldOffset =
8043 Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
8044 QualType FieldTy = FD->getType();
8045 if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
8046 return false;
8047 ++FieldIdx;
8048 }
8049
8050 return true;
8051 }
8052
8053 bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
8054 const auto *CAT =
8055 dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
8056 if (!CAT)
8057 return false;
8058
8059 CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
8060 unsigned NumInitializedElts = Val.getArrayInitializedElts();
8061 unsigned ArraySize = Val.getArraySize();
8062 // First, initialize the initialized elements.
8063 for (unsigned I = 0; I != NumInitializedElts; ++I) {
8064 const APValue &SubObj = Val.getArrayInitializedElt(I);
8065 if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
8066 return false;
8067 }
8068
8069 // Next, initialize the rest of the array using the filler.
8070 if (Val.hasArrayFiller()) {
8071 const APValue &Filler = Val.getArrayFiller();
8072 for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
8073 if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
8074 return false;
8075 }
8076 }
8077
8078 return true;
8079 }
8080
8081 bool visitComplex(const APValue &Val, QualType Ty, CharUnits Offset) {
8082 const ComplexType *ComplexTy = Ty->castAs<ComplexType>();
8083 QualType EltTy = ComplexTy->getElementType();
8084 CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
8085 bool IsInt = Val.isComplexInt();
8086
8087 if (IsInt) {
8088 if (!visitInt(Val.getComplexIntReal(), EltTy,
8089 Offset + (0 * EltSizeChars)))
8090 return false;
8091 if (!visitInt(Val.getComplexIntImag(), EltTy,
8092 Offset + (1 * EltSizeChars)))
8093 return false;
8094 } else {
8095 if (!visitFloat(Val.getComplexFloatReal(), EltTy,
8096 Offset + (0 * EltSizeChars)))
8097 return false;
8098 if (!visitFloat(Val.getComplexFloatImag(), EltTy,
8099 Offset + (1 * EltSizeChars)))
8100 return false;
8101 }
8102
8103 return true;
8104 }
8105
8106 bool visitVector(const APValue &Val, QualType Ty, CharUnits Offset) {
8107 const VectorType *VTy = Ty->castAs<VectorType>();
8108 QualType EltTy = VTy->getElementType();
8109 unsigned NElts = VTy->getNumElements();
8110
8111 if (VTy->isPackedVectorBoolType(Info.Ctx)) {
8112 // Special handling for OpenCL bool vectors:
8113 // Since these vectors are stored as packed bits, but we can't write
8114 // individual bits to the BitCastBuffer, we'll buffer all of the elements
8115 // together into an appropriately sized APInt and write them all out at
8116 // once. Because we don't accept vectors where NElts * EltSize isn't a
8117 // multiple of the char size, there will be no padding space, so we don't
8118 // have to worry about writing data which should have been left
8119 // uninitialized.
8120 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
8121
8122 llvm::APInt Res = llvm::APInt::getZero(NElts);
8123 for (unsigned I = 0; I < NElts; ++I) {
8124 const llvm::APSInt &EltAsInt = Val.getVectorElt(I).getInt();
8125 assert(EltAsInt.isUnsigned() && EltAsInt.getBitWidth() == 1 &&
8126 "bool vector element must be 1-bit unsigned integer!");
8127
8128 Res.insertBits(EltAsInt, BigEndian ? (NElts - I - 1) : I);
8129 }
8130
8131 SmallVector<uint8_t, 8> Bytes(NElts / 8);
8132 llvm::StoreIntToMemory(Res, &*Bytes.begin(), NElts / 8);
8133 Buffer.writeObject(Offset, Bytes);
8134 } else {
8135 // Iterate over each of the elements and write them out to the buffer at
8136 // the appropriate offset.
8137 CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
8138 for (unsigned I = 0; I < NElts; ++I) {
8139 if (!visit(Val.getVectorElt(I), EltTy, Offset + I * EltSizeChars))
8140 return false;
8141 }
8142 }
8143
8144 return true;
8145 }
8146
8147 bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
8148 APSInt AdjustedVal = Val;
8149 unsigned Width = AdjustedVal.getBitWidth();
8150 if (Ty->isBooleanType()) {
8151 Width = Info.Ctx.getTypeSize(Ty);
8152 AdjustedVal = AdjustedVal.extend(Width);
8153 }
8154
8155 SmallVector<uint8_t, 8> Bytes(Width / 8);
8156 llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8);
8157 Buffer.writeObject(Offset, Bytes);
8158 return true;
8159 }
8160
8161 bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
8162 APSInt AsInt(Val.bitcastToAPInt());
8163 return visitInt(AsInt, Ty, Offset);
8164 }
8165
8166public:
8167 static std::optional<BitCastBuffer>
8168 convert(EvalInfo &Info, const APValue &Src, const CastExpr *BCE) {
8169 CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
8170 APValueToBufferConverter Converter(Info, DstSize, BCE);
8171 if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
8172 return std::nullopt;
8173 return Converter.Buffer;
8174 }
8175};
8176
8177/// Write an BitCastBuffer into an APValue.
8178class BufferToAPValueConverter {
8179 EvalInfo &Info;
8180 const BitCastBuffer &Buffer;
8181 const CastExpr *BCE;
8182
8183 BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
8184 const CastExpr *BCE)
8185 : Info(Info), Buffer(Buffer), BCE(BCE) {}
8186
8187 // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
8188 // with an invalid type, so anything left is a deficiency on our part (FIXME).
8189 // Ideally this will be unreachable.
8190 std::nullopt_t unsupportedType(QualType Ty) {
8191 Info.FFDiag(BCE->getBeginLoc(),
8192 diag::note_constexpr_bit_cast_unsupported_type)
8193 << Ty;
8194 return std::nullopt;
8195 }
8196
8197 std::nullopt_t unrepresentableValue(QualType Ty, const APSInt &Val) {
8198 Info.FFDiag(BCE->getBeginLoc(),
8199 diag::note_constexpr_bit_cast_unrepresentable_value)
8200 << Ty << toString(Val, /*Radix=*/10);
8201 return std::nullopt;
8202 }
8203
8204 std::optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
8205 const EnumType *EnumSugar = nullptr) {
8206 if (T->isNullPtrType()) {
8207 uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
8208 return APValue((Expr *)nullptr,
8209 /*Offset=*/CharUnits::fromQuantity(NullValue),
8210 APValue::NoLValuePath{}, /*IsNullPtr=*/true);
8211 }
8212
8213 CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
8214
8215 // Work around floating point types that contain unused padding bytes. This
8216 // is really just `long double` on x86, which is the only fundamental type
8217 // with padding bytes.
8218 if (T->isRealFloatingType()) {
8219 const llvm::fltSemantics &Semantics =
8220 Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
8221 unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics);
8222 assert(NumBits % 8 == 0);
8223 CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8);
8224 if (NumBytes != SizeOf)
8225 SizeOf = NumBytes;
8226 }
8227
8228 SmallVector<uint8_t, 8> Bytes;
8229 if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
8230 // If this is std::byte or unsigned char, then its okay to store an
8231 // indeterminate value.
8232 bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
8233 bool IsUChar =
8234 !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
8235 T->isSpecificBuiltinType(BuiltinType::Char_U));
8236 if (!IsStdByte && !IsUChar) {
8237 QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
8238 Info.FFDiag(BCE->getExprLoc(),
8239 diag::note_constexpr_bit_cast_indet_dest)
8240 << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
8241 return std::nullopt;
8242 }
8243
8245 }
8246
8247 APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
8248 llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
8249
8251 Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
8252
8253 unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0));
8254 if (IntWidth != Val.getBitWidth()) {
8255 APSInt Truncated = Val.trunc(IntWidth);
8256 if (Truncated.extend(Val.getBitWidth()) != Val)
8257 return unrepresentableValue(QualType(T, 0), Val);
8258 Val = Truncated;
8259 }
8260
8261 return APValue(Val);
8262 }
8263
8264 if (T->isRealFloatingType()) {
8265 const llvm::fltSemantics &Semantics =
8266 Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
8267 return APValue(APFloat(Semantics, Val));
8268 }
8269
8270 return unsupportedType(QualType(T, 0));
8271 }
8272
8273 std::optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
8274 const RecordDecl *RD = RTy->getAsRecordDecl();
8275 if (RD->isInvalidDecl())
8276 return std::nullopt;
8277 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
8278
8279 unsigned NumBases = 0;
8280 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
8281 NumBases = CXXRD->getNumBases();
8282
8283 APValue ResultVal(APValue::UninitStruct(), NumBases, RD->getNumFields());
8284
8285 // Visit the base classes.
8286 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
8287 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
8288 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
8289 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
8290
8291 std::optional<APValue> SubObj = visitType(
8292 BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
8293 if (!SubObj)
8294 return std::nullopt;
8295 ResultVal.getStructBase(I) = *SubObj;
8296 }
8297 }
8298
8299 // Visit the fields.
8300 unsigned FieldIdx = 0;
8301 for (FieldDecl *FD : RD->fields()) {
8302 // FIXME: We don't currently support bit-fields. A lot of the logic for
8303 // this is in CodeGen, so we need to factor it around.
8304 if (FD->isBitField()) {
8305 Info.FFDiag(BCE->getBeginLoc(),
8306 diag::note_constexpr_bit_cast_unsupported_bitfield);
8307 return std::nullopt;
8308 }
8309
8310 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
8311 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
8312
8313 CharUnits FieldOffset =
8314 CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
8315 Offset;
8316 QualType FieldTy = FD->getType();
8317 std::optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
8318 if (!SubObj)
8319 return std::nullopt;
8320 ResultVal.getStructField(FieldIdx) = *SubObj;
8321 ++FieldIdx;
8322 }
8323
8324 return ResultVal;
8325 }
8326
8327 std::optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
8328 QualType RepresentationType =
8329 Ty->getDecl()->getDefinitionOrSelf()->getIntegerType();
8330 assert(!RepresentationType.isNull() &&
8331 "enum forward decl should be caught by Sema");
8332 const auto *AsBuiltin =
8333 RepresentationType.getCanonicalType()->castAs<BuiltinType>();
8334 // Recurse into the underlying type. Treat std::byte transparently as
8335 // unsigned char.
8336 return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
8337 }
8338
8339 std::optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
8340 size_t Size = Ty->getLimitedSize();
8341 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
8342
8343 APValue ArrayValue(APValue::UninitArray(), Size, Size);
8344 for (size_t I = 0; I != Size; ++I) {
8345 std::optional<APValue> ElementValue =
8346 visitType(Ty->getElementType(), Offset + I * ElementWidth);
8347 if (!ElementValue)
8348 return std::nullopt;
8349 ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
8350 }
8351
8352 return ArrayValue;
8353 }
8354
8355 std::optional<APValue> visit(const ComplexType *Ty, CharUnits Offset) {
8356 QualType ElementType = Ty->getElementType();
8357 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(ElementType);
8358 bool IsInt = ElementType->isIntegerType();
8359
8360 std::optional<APValue> Values[2];
8361 for (unsigned I = 0; I != 2; ++I) {
8362 Values[I] = visitType(Ty->getElementType(), Offset + I * ElementWidth);
8363 if (!Values[I])
8364 return std::nullopt;
8365 }
8366
8367 if (IsInt)
8368 return APValue(Values[0]->getInt(), Values[1]->getInt());
8369 return APValue(Values[0]->getFloat(), Values[1]->getFloat());
8370 }
8371
8372 std::optional<APValue> visit(const VectorType *VTy, CharUnits Offset) {
8373 QualType EltTy = VTy->getElementType();
8374 unsigned NElts = VTy->getNumElements();
8375 unsigned EltSize =
8376 VTy->isPackedVectorBoolType(Info.Ctx) ? 1 : Info.Ctx.getTypeSize(EltTy);
8377
8378 SmallVector<APValue, 4> Elts;
8379 Elts.reserve(NElts);
8380 if (VTy->isPackedVectorBoolType(Info.Ctx)) {
8381 // Special handling for OpenCL bool vectors:
8382 // Since these vectors are stored as packed bits, but we can't read
8383 // individual bits from the BitCastBuffer, we'll buffer all of the
8384 // elements together into an appropriately sized APInt and write them all
8385 // out at once. Because we don't accept vectors where NElts * EltSize
8386 // isn't a multiple of the char size, there will be no padding space, so
8387 // we don't have to worry about reading any padding data which didn't
8388 // actually need to be accessed.
8389 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
8390
8391 SmallVector<uint8_t, 8> Bytes;
8392 Bytes.reserve(NElts / 8);
8393 if (!Buffer.readObject(Offset, CharUnits::fromQuantity(NElts / 8), Bytes))
8394 return std::nullopt;
8395
8396 APSInt SValInt(NElts, true);
8397 llvm::LoadIntFromMemory(SValInt, &*Bytes.begin(), Bytes.size());
8398
8399 for (unsigned I = 0; I < NElts; ++I) {
8400 llvm::APInt Elt =
8401 SValInt.extractBits(1, (BigEndian ? NElts - I - 1 : I) * EltSize);
8402 Elts.emplace_back(
8403 APSInt(std::move(Elt), !EltTy->isSignedIntegerType()));
8404 }
8405 } else {
8406 // Iterate over each of the elements and read them from the buffer at
8407 // the appropriate offset.
8408 CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
8409 for (unsigned I = 0; I < NElts; ++I) {
8410 std::optional<APValue> EltValue =
8411 visitType(EltTy, Offset + I * EltSizeChars);
8412 if (!EltValue)
8413 return std::nullopt;
8414 Elts.push_back(std::move(*EltValue));
8415 }
8416 }
8417
8418 return APValue(Elts.data(), Elts.size());
8419 }
8420
8421 std::optional<APValue> visit(const Type *Ty, CharUnits Offset) {
8422 return unsupportedType(QualType(Ty, 0));
8423 }
8424
8425 std::optional<APValue> visitType(QualType Ty, CharUnits Offset) {
8426 QualType Can = Ty.getCanonicalType();
8427
8428 switch (Can->getTypeClass()) {
8429#define TYPE(Class, Base) \
8430 case Type::Class: \
8431 return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
8432#define ABSTRACT_TYPE(Class, Base)
8433#define NON_CANONICAL_TYPE(Class, Base) \
8434 case Type::Class: \
8435 llvm_unreachable("non-canonical type should be impossible!");
8436#define DEPENDENT_TYPE(Class, Base) \
8437 case Type::Class: \
8438 llvm_unreachable( \
8439 "dependent types aren't supported in the constant evaluator!");
8440#define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base) \
8441 case Type::Class: \
8442 llvm_unreachable("either dependent or not canonical!");
8443#include "clang/AST/TypeNodes.inc"
8444 }
8445 llvm_unreachable("Unhandled Type::TypeClass");
8446 }
8447
8448public:
8449 // Pull out a full value of type DstType.
8450 static std::optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
8451 const CastExpr *BCE) {
8452 BufferToAPValueConverter Converter(Info, Buffer, BCE);
8453 return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
8454 }
8455};
8456
8457static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
8458 QualType Ty, EvalInfo *Info,
8459 const ASTContext &Ctx,
8460 bool CheckingDest) {
8461 Ty = Ty.getCanonicalType();
8462
8463 auto diag = [&](int Reason) {
8464 if (Info)
8465 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
8466 << CheckingDest << (Reason == 4) << Reason;
8467 return false;
8468 };
8469 auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
8470 if (Info)
8471 Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
8472 << NoteTy << Construct << Ty;
8473 return false;
8474 };
8475
8476 if (Ty->isUnionType())
8477 return diag(0);
8478 if (Ty->isPointerType())
8479 return diag(1);
8480 if (Ty->isMemberPointerType())
8481 return diag(2);
8482 if (Ty.isVolatileQualified())
8483 return diag(3);
8484
8485 if (RecordDecl *Record = Ty->getAsRecordDecl()) {
8486 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
8487 for (CXXBaseSpecifier &BS : CXXRD->bases())
8488 if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
8489 CheckingDest))
8490 return note(1, BS.getType(), BS.getBeginLoc());
8491 }
8492 for (FieldDecl *FD : Record->fields()) {
8493 if (FD->getType()->isReferenceType())
8494 return diag(4);
8495 if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
8496 CheckingDest))
8497 return note(0, FD->getType(), FD->getBeginLoc());
8498 }
8499 }
8500
8501 if (Ty->isArrayType() &&
8502 !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
8503 Info, Ctx, CheckingDest))
8504 return false;
8505
8506 if (const auto *VTy = Ty->getAs<VectorType>()) {
8507 QualType EltTy = VTy->getElementType();
8508 unsigned NElts = VTy->getNumElements();
8509 unsigned EltSize =
8510 VTy->isPackedVectorBoolType(Ctx) ? 1 : Ctx.getTypeSize(EltTy);
8511
8512 if ((NElts * EltSize) % Ctx.getCharWidth() != 0) {
8513 // The vector's size in bits is not a multiple of the target's byte size,
8514 // so its layout is unspecified. For now, we'll simply treat these cases
8515 // as unsupported (this should only be possible with OpenCL bool vectors
8516 // whose element count isn't a multiple of the byte size).
8517 if (Info)
8518 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_vector)
8519 << QualType(VTy, 0) << EltSize << NElts << Ctx.getCharWidth();
8520 return false;
8521 }
8522
8523 if (EltTy->isRealFloatingType() &&
8524 &Ctx.getFloatTypeSemantics(EltTy) == &APFloat::x87DoubleExtended()) {
8525 // The layout for x86_fp80 vectors seems to be handled very inconsistently
8526 // by both clang and LLVM, so for now we won't allow bit_casts involving
8527 // it in a constexpr context.
8528 if (Info)
8529 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_unsupported_type)
8530 << EltTy;
8531 return false;
8532 }
8533 }
8534
8535 return true;
8536}
8537
8538static bool checkBitCastConstexprEligibility(EvalInfo *Info,
8539 const ASTContext &Ctx,
8540 const CastExpr *BCE) {
8541 bool DestOK = checkBitCastConstexprEligibilityType(
8542 BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
8543 bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
8544 BCE->getBeginLoc(),
8545 BCE->getSubExpr()->getType(), Info, Ctx, false);
8546 return SourceOK;
8547}
8548
8549static bool handleRValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
8550 const APValue &SourceRValue,
8551 const CastExpr *BCE) {
8552 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
8553 "no host or target supports non 8-bit chars");
8554
8555 if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
8556 return false;
8557
8558 // Read out SourceValue into a char buffer.
8559 std::optional<BitCastBuffer> Buffer =
8560 APValueToBufferConverter::convert(Info, SourceRValue, BCE);
8561 if (!Buffer)
8562 return false;
8563
8564 // Write out the buffer into a new APValue.
8565 std::optional<APValue> MaybeDestValue =
8566 BufferToAPValueConverter::convert(Info, *Buffer, BCE);
8567 if (!MaybeDestValue)
8568 return false;
8569
8570 DestValue = std::move(*MaybeDestValue);
8571 return true;
8572}
8573
8574static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
8575 APValue &SourceValue,
8576 const CastExpr *BCE) {
8577 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
8578 "no host or target supports non 8-bit chars");
8579 assert(SourceValue.isLValue() &&
8580 "LValueToRValueBitcast requires an lvalue operand!");
8581
8582 LValue SourceLValue;
8583 APValue SourceRValue;
8584 SourceLValue.setFrom(Info.Ctx, SourceValue);
8586 Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,
8587 SourceRValue, /*WantObjectRepresentation=*/true))
8588 return false;
8589
8590 return handleRValueToRValueBitCast(Info, DestValue, SourceRValue, BCE);
8591}
8592
8593template <class Derived>
8594class ExprEvaluatorBase
8595 : public ConstStmtVisitor<Derived, bool> {
8596private:
8597 Derived &getDerived() { return static_cast<Derived&>(*this); }
8598 bool DerivedSuccess(const APValue &V, const Expr *E) {
8599 return getDerived().Success(V, E);
8600 }
8601 bool DerivedZeroInitialization(const Expr *E) {
8602 return getDerived().ZeroInitialization(E);
8603 }
8604
8605 // Check whether a conditional operator with a non-constant condition is a
8606 // potential constant expression. If neither arm is a potential constant
8607 // expression, then the conditional operator is not either.
8608 template<typename ConditionalOperator>
8609 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
8610 assert(Info.checkingPotentialConstantExpression());
8611
8612 // Speculatively evaluate both arms.
8613 SmallVector<PartialDiagnosticAt, 8> Diag;
8614 {
8615 SpeculativeEvaluationRAII Speculate(Info, &Diag);
8616 StmtVisitorTy::Visit(E->getFalseExpr());
8617 if (Diag.empty())
8618 return;
8619 }
8620
8621 {
8622 SpeculativeEvaluationRAII Speculate(Info, &Diag);
8623 Diag.clear();
8624 Info.EvalStatus.DiagEmitted = false;
8625 StmtVisitorTy::Visit(E->getTrueExpr());
8626 if (Diag.empty())
8627 return;
8628 }
8629
8630 Error(E, diag::note_constexpr_conditional_never_const);
8631 }
8632
8633
8634 template<typename ConditionalOperator>
8635 bool HandleConditionalOperator(const ConditionalOperator *E) {
8636 bool BoolResult;
8637 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
8638 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
8639 CheckPotentialConstantConditional(E);
8640 return false;
8641 }
8642 if (Info.noteFailure()) {
8643 StmtVisitorTy::Visit(E->getTrueExpr());
8644 StmtVisitorTy::Visit(E->getFalseExpr());
8645 }
8646 return false;
8647 }
8648
8649 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
8650 return StmtVisitorTy::Visit(EvalExpr);
8651 }
8652
8653protected:
8654 EvalInfo &Info;
8655 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
8656 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
8657
8658 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
8659 return Info.CCEDiag(E, D);
8660 }
8661
8662 bool ZeroInitialization(const Expr *E) { return Error(E); }
8663
8664 bool IsConstantEvaluatedBuiltinCall(const CallExpr *E) {
8665 unsigned BuiltinOp = E->getBuiltinCallee();
8666 return BuiltinOp != 0 &&
8667 Info.Ctx.BuiltinInfo.isConstantEvaluated(BuiltinOp);
8668 }
8669
8670public:
8671 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
8672
8673 EvalInfo &getEvalInfo() { return Info; }
8674
8675 /// Report an evaluation error. This should only be called when an error is
8676 /// first discovered. When propagating an error, just return false.
8677 bool Error(const Expr *E, diag::kind D) {
8678 Info.FFDiag(E, D) << E->getSourceRange();
8679 return false;
8680 }
8681 bool Error(const Expr *E) {
8682 return Error(E, diag::note_invalid_subexpr_in_const_expr);
8683 }
8684
8685 bool VisitStmt(const Stmt *) {
8686 llvm_unreachable("Expression evaluator should not be called on stmts");
8687 }
8688 bool VisitExpr(const Expr *E) {
8689 return Error(E);
8690 }
8691
8692 bool VisitEmbedExpr(const EmbedExpr *E) {
8693 const auto It = E->begin();
8694 return StmtVisitorTy::Visit(*It);
8695 }
8696
8697 bool VisitPredefinedExpr(const PredefinedExpr *E) {
8698 return StmtVisitorTy::Visit(E->getFunctionName());
8699 }
8700 bool VisitConstantExpr(const ConstantExpr *E) {
8701 if (E->hasAPValueResult())
8702 return DerivedSuccess(E->getAPValueResult(), E);
8703
8704 return StmtVisitorTy::Visit(E->getSubExpr());
8705 }
8706
8707 bool VisitParenExpr(const ParenExpr *E)
8708 { return StmtVisitorTy::Visit(E->getSubExpr()); }
8709 bool VisitUnaryExtension(const UnaryOperator *E)
8710 { return StmtVisitorTy::Visit(E->getSubExpr()); }
8711 bool VisitUnaryPlus(const UnaryOperator *E)
8712 { return StmtVisitorTy::Visit(E->getSubExpr()); }
8713 bool VisitChooseExpr(const ChooseExpr *E)
8714 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
8715 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
8716 { return StmtVisitorTy::Visit(E->getResultExpr()); }
8717 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
8718 { return StmtVisitorTy::Visit(E->getReplacement()); }
8719 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
8720 TempVersionRAII RAII(*Info.CurrentCall);
8721 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
8722 return StmtVisitorTy::Visit(E->getExpr());
8723 }
8724 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
8725 TempVersionRAII RAII(*Info.CurrentCall);
8726 // The initializer may not have been parsed yet, or might be erroneous.
8727 if (!E->getExpr())
8728 return Error(E);
8729 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
8730 return StmtVisitorTy::Visit(E->getExpr());
8731 }
8732
8733 bool VisitExprWithCleanups(const ExprWithCleanups *E) {
8734 FullExpressionRAII Scope(Info);
8735 return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy();
8736 }
8737
8738 // Temporaries are registered when created, so we don't care about
8739 // CXXBindTemporaryExpr.
8740 bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
8741 return StmtVisitorTy::Visit(E->getSubExpr());
8742 }
8743
8744 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
8745 if (E->getCastKind() != CK_PointerToIntegral)
8746 CCEDiag(E, diag::note_constexpr_invalid_cast)
8747 << diag::ConstexprInvalidCastKind::Reinterpret;
8748 return static_cast<Derived*>(this)->VisitCastExpr(E);
8749 }
8750 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
8751 if (!Info.Ctx.getLangOpts().CPlusPlus20)
8752 CCEDiag(E, diag::note_constexpr_invalid_cast)
8753 << diag::ConstexprInvalidCastKind::Dynamic;
8754 return static_cast<Derived*>(this)->VisitCastExpr(E);
8755 }
8756 bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
8757 return static_cast<Derived*>(this)->VisitCastExpr(E);
8758 }
8759
8760 bool VisitBinaryOperator(const BinaryOperator *E) {
8761 switch (E->getOpcode()) {
8762 default:
8763 return Error(E);
8764
8765 case BO_Comma:
8766 VisitIgnoredValue(E->getLHS());
8767 return StmtVisitorTy::Visit(E->getRHS());
8768
8769 case BO_PtrMemD:
8770 case BO_PtrMemI: {
8771 LValue Obj;
8772 if (!HandleMemberPointerAccess(Info, E, Obj))
8773 return false;
8775 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
8776 return false;
8777 return DerivedSuccess(Result, E);
8778 }
8779 }
8780 }
8781
8782 bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) {
8783 return StmtVisitorTy::Visit(E->getSemanticForm());
8784 }
8785
8786 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
8787 // Evaluate and cache the common expression. We treat it as a temporary,
8788 // even though it's not quite the same thing.
8789 LValue CommonLV;
8790 if (!Evaluate(Info.CurrentCall->createTemporary(
8791 E->getOpaqueValue(),
8792 getStorageType(Info.Ctx, E->getOpaqueValue()),
8793 ScopeKind::FullExpression, CommonLV),
8794 Info, E->getCommon()))
8795 return false;
8796
8797 return HandleConditionalOperator(E);
8798 }
8799
8800 bool VisitConditionalOperator(const ConditionalOperator *E) {
8801 bool IsBcpCall = false;
8802 // If the condition (ignoring parens) is a __builtin_constant_p call,
8803 // the result is a constant expression if it can be folded without
8804 // side-effects. This is an important GNU extension. See GCC PR38377
8805 // for discussion.
8806 if (const CallExpr *CallCE =
8807 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
8808 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
8809 IsBcpCall = true;
8810
8811 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
8812 // constant expression; we can't check whether it's potentially foldable.
8813 // FIXME: We should instead treat __builtin_constant_p as non-constant if
8814 // it would return 'false' in this mode.
8815 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
8816 return false;
8817
8818 FoldConstant Fold(Info, IsBcpCall);
8819 if (!HandleConditionalOperator(E)) {
8820 Fold.keepDiagnostics();
8821 return false;
8822 }
8823
8824 return true;
8825 }
8826
8827 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
8828 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E);
8829 Value && !Value->isAbsent())
8830 return DerivedSuccess(*Value, E);
8831
8832 const Expr *Source = E->getSourceExpr();
8833 if (!Source)
8834 return Error(E);
8835 if (Source == E) {
8836 assert(0 && "OpaqueValueExpr recursively refers to itself");
8837 return Error(E);
8838 }
8839 return StmtVisitorTy::Visit(Source);
8840 }
8841
8842 bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
8843 for (const Expr *SemE : E->semantics()) {
8844 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
8845 // FIXME: We can't handle the case where an OpaqueValueExpr is also the
8846 // result expression: there could be two different LValues that would
8847 // refer to the same object in that case, and we can't model that.
8848 if (SemE == E->getResultExpr())
8849 return Error(E);
8850
8851 // Unique OVEs get evaluated if and when we encounter them when
8852 // emitting the rest of the semantic form, rather than eagerly.
8853 if (OVE->isUnique())
8854 continue;
8855
8856 LValue LV;
8857 if (!Evaluate(Info.CurrentCall->createTemporary(
8858 OVE, getStorageType(Info.Ctx, OVE),
8859 ScopeKind::FullExpression, LV),
8860 Info, OVE->getSourceExpr()))
8861 return false;
8862 } else if (SemE == E->getResultExpr()) {
8863 if (!StmtVisitorTy::Visit(SemE))
8864 return false;
8865 } else {
8866 if (!EvaluateIgnoredValue(Info, SemE))
8867 return false;
8868 }
8869 }
8870 return true;
8871 }
8872
8873 bool VisitCallExpr(const CallExpr *E) {
8875 if (!handleCallExpr(E, Result, nullptr))
8876 return false;
8877 return DerivedSuccess(Result, E);
8878 }
8879
8880 bool handleCallExpr(const CallExpr *E, APValue &Result,
8881 const LValue *ResultSlot) {
8882 CallScopeRAII CallScope(Info);
8883
8884 const Expr *Callee = E->getCallee()->IgnoreParens();
8885 QualType CalleeType = Callee->getType();
8886
8887 const FunctionDecl *FD = nullptr;
8888 LValue *This = nullptr, ObjectArg;
8889 auto Args = ArrayRef(E->getArgs(), E->getNumArgs());
8890 bool HasQualifier = false;
8891
8892 CallRef Call;
8893
8894 // Extract function decl and 'this' pointer from the callee.
8895 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
8896 const CXXMethodDecl *Member = nullptr;
8897 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
8898 // Explicit bound member calls, such as x.f() or p->g();
8899 if (!EvaluateObjectArgument(Info, ME->getBase(), ObjectArg))
8900 return false;
8901 Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
8902 if (!Member)
8903 return Error(Callee);
8904 This = &ObjectArg;
8905 HasQualifier = ME->hasQualifier();
8906 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
8907 // Indirect bound member calls ('.*' or '->*').
8908 const ValueDecl *D =
8909 HandleMemberPointerAccess(Info, BE, ObjectArg, false);
8910 if (!D)
8911 return false;
8912 Member = dyn_cast<CXXMethodDecl>(D);
8913 if (!Member)
8914 return Error(Callee);
8915 This = &ObjectArg;
8916 } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
8917 if (!Info.getLangOpts().CPlusPlus20)
8918 Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
8919 return EvaluateObjectArgument(Info, PDE->getBase(), ObjectArg) &&
8920 HandleDestruction(Info, PDE, ObjectArg, PDE->getDestroyedType());
8921 } else
8922 return Error(Callee);
8923 FD = Member;
8924 } else if (CalleeType->isFunctionPointerType()) {
8925 LValue CalleeLV;
8926 if (!EvaluatePointer(Callee, CalleeLV, Info))
8927 return false;
8928
8929 if (!CalleeLV.getLValueOffset().isZero())
8930 return Error(Callee);
8931 if (CalleeLV.isNullPointer()) {
8932 Info.FFDiag(Callee, diag::note_constexpr_null_callee)
8933 << const_cast<Expr *>(Callee);
8934 return false;
8935 }
8936 FD = dyn_cast_or_null<FunctionDecl>(
8937 CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>());
8938 if (!FD)
8939 return Error(Callee);
8940 // Don't call function pointers which have been cast to some other type.
8941 // Per DR (no number yet), the caller and callee can differ in noexcept.
8942 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
8943 CalleeType->getPointeeType(), FD->getType())) {
8944 return Error(E);
8945 }
8946
8947 // For an (overloaded) assignment expression, evaluate the RHS before the
8948 // LHS.
8949 auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
8950 if (OCE && OCE->isAssignmentOp()) {
8951 assert(Args.size() == 2 && "wrong number of arguments in assignment");
8952 Call = Info.CurrentCall->createCall(FD);
8953 bool HasThis = false;
8954 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
8955 HasThis = MD->isImplicitObjectMemberFunction();
8956 if (!EvaluateArgs(HasThis ? Args.slice(1) : Args, Call, Info, FD,
8957 /*RightToLeft=*/true, &ObjectArg))
8958 return false;
8959 }
8960
8961 // Overloaded operator calls to member functions are represented as normal
8962 // calls with '*this' as the first argument.
8963 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8964 if (MD &&
8965 (MD->isImplicitObjectMemberFunction() || (OCE && MD->isStatic()))) {
8966 // FIXME: When selecting an implicit conversion for an overloaded
8967 // operator delete, we sometimes try to evaluate calls to conversion
8968 // operators without a 'this' parameter!
8969 if (Args.empty())
8970 return Error(E);
8971
8972 if (!EvaluateObjectArgument(Info, Args[0], ObjectArg))
8973 return false;
8974
8975 // If we are calling a static operator, the 'this' argument needs to be
8976 // ignored after being evaluated.
8977 if (MD->isInstance())
8978 This = &ObjectArg;
8979
8980 // If this is syntactically a simple assignment using a trivial
8981 // assignment operator, start the lifetimes of union members as needed,
8982 // per C++20 [class.union]5.
8983 if (Info.getLangOpts().CPlusPlus20 && OCE &&
8984 OCE->getOperator() == OO_Equal && MD->isTrivial() &&
8985 !MaybeHandleUnionActiveMemberChange(Info, Args[0], ObjectArg))
8986 return false;
8987
8988 Args = Args.slice(1);
8989 } else if (MD && MD->isLambdaStaticInvoker()) {
8990 // Map the static invoker for the lambda back to the call operator.
8991 // Conveniently, we don't have to slice out the 'this' argument (as is
8992 // being done for the non-static case), since a static member function
8993 // doesn't have an implicit argument passed in.
8994 const CXXRecordDecl *ClosureClass = MD->getParent();
8995 assert(
8996 ClosureClass->captures().empty() &&
8997 "Number of captures must be zero for conversion to function-ptr");
8998
8999 const CXXMethodDecl *LambdaCallOp =
9000 ClosureClass->getLambdaCallOperator();
9001
9002 // Set 'FD', the function that will be called below, to the call
9003 // operator. If the closure object represents a generic lambda, find
9004 // the corresponding specialization of the call operator.
9005
9006 if (ClosureClass->isGenericLambda()) {
9007 assert(MD->isFunctionTemplateSpecialization() &&
9008 "A generic lambda's static-invoker function must be a "
9009 "template specialization");
9010 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
9011 FunctionTemplateDecl *CallOpTemplate =
9012 LambdaCallOp->getDescribedFunctionTemplate();
9013 void *InsertPos = nullptr;
9014 FunctionDecl *CorrespondingCallOpSpecialization =
9015 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
9016 assert(CorrespondingCallOpSpecialization &&
9017 "We must always have a function call operator specialization "
9018 "that corresponds to our static invoker specialization");
9019 assert(isa<CXXMethodDecl>(CorrespondingCallOpSpecialization));
9020 FD = CorrespondingCallOpSpecialization;
9021 } else
9022 FD = LambdaCallOp;
9024 if (FD->getDeclName().isAnyOperatorNew()) {
9025 LValue Ptr;
9026 if (!HandleOperatorNewCall(Info, E, Ptr))
9027 return false;
9028 Ptr.moveInto(Result);
9029 return CallScope.destroy();
9030 } else {
9031 return HandleOperatorDeleteCall(Info, E) && CallScope.destroy();
9032 }
9033 }
9034 } else
9035 return Error(E);
9036
9037 // Evaluate the arguments now if we've not already done so.
9038 if (!Call) {
9039 Call = Info.CurrentCall->createCall(FD);
9040 if (!EvaluateArgs(Args, Call, Info, FD, /*RightToLeft*/ false,
9041 &ObjectArg))
9042 return false;
9043 }
9044
9045 SmallVector<QualType, 4> CovariantAdjustmentPath;
9046 if (This) {
9047 auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
9048 if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
9049 // Perform virtual dispatch, if necessary.
9050 FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
9051 CovariantAdjustmentPath);
9052 if (!FD)
9053 return false;
9054 } else if (NamedMember && NamedMember->isImplicitObjectMemberFunction()) {
9055 // Check that the 'this' pointer points to an object of the right type.
9056 // FIXME: If this is an assignment operator call, we may need to change
9057 // the active union member before we check this.
9058 if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
9059 return false;
9060 }
9061 }
9062
9063 // Destructor calls are different enough that they have their own codepath.
9064 if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
9065 assert(This && "no 'this' pointer for destructor call");
9066 return HandleDestruction(Info, E, *This,
9067 Info.Ctx.getCanonicalTagType(DD->getParent())) &&
9068 CallScope.destroy();
9069 }
9070
9071 const FunctionDecl *Definition = nullptr;
9072 Stmt *Body = FD->getBody(Definition);
9073 SourceLocation Loc = E->getExprLoc();
9074
9075 // Treat the object argument as `this` when evaluating defaulted
9076 // special menmber functions
9078 This = &ObjectArg;
9079
9080 if (!CheckConstexprFunction(Info, Loc, FD, Definition, Body) ||
9081 !HandleFunctionCall(Loc, Definition, This, E, Args, Call, Body, Info,
9082 Result, ResultSlot))
9083 return false;
9084
9085 if (!CovariantAdjustmentPath.empty() &&
9087 CovariantAdjustmentPath))
9088 return false;
9089
9090 return CallScope.destroy();
9091 }
9092
9093 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
9094 return StmtVisitorTy::Visit(E->getInitializer());
9095 }
9096 bool VisitInitListExpr(const InitListExpr *E) {
9097 if (E->getNumInits() == 0)
9098 return DerivedZeroInitialization(E);
9099 if (E->getNumInits() == 1)
9100 return StmtVisitorTy::Visit(E->getInit(0));
9101 return Error(E);
9102 }
9103 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
9104 return DerivedZeroInitialization(E);
9105 }
9106 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
9107 return DerivedZeroInitialization(E);
9108 }
9109 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
9110 return DerivedZeroInitialization(E);
9111 }
9112
9113 /// A member expression where the object is a prvalue is itself a prvalue.
9114 bool VisitMemberExpr(const MemberExpr *E) {
9115 assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
9116 "missing temporary materialization conversion");
9117 assert(!E->isArrow() && "missing call to bound member function?");
9118
9119 APValue Val;
9120 if (!Evaluate(Val, Info, E->getBase()))
9121 return false;
9122
9123 QualType BaseTy = E->getBase()->getType();
9124
9125 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
9126 if (!FD) return Error(E);
9127 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
9128 assert(BaseTy->castAsCanonical<RecordType>()->getDecl() ==
9129 FD->getParent()->getCanonicalDecl() &&
9130 "record / field mismatch");
9131
9132 // Note: there is no lvalue base here. But this case should only ever
9133 // happen in C or in C++98, where we cannot be evaluating a constexpr
9134 // constructor, which is the only case the base matters.
9135 CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
9136 SubobjectDesignator Designator(BaseTy);
9137 Designator.addDeclUnchecked(FD);
9138
9140 return extractSubobject(Info, E, Obj, Designator, Result) &&
9141 DerivedSuccess(Result, E);
9142 }
9143
9144 bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) {
9145 APValue Val;
9146 if (!Evaluate(Val, Info, E->getBase()))
9147 return false;
9148
9149 if (Val.isVector()) {
9150 SmallVector<uint32_t, 4> Indices;
9151 E->getEncodedElementAccess(Indices);
9152 if (Indices.size() == 1) {
9153 // Return scalar.
9154 return DerivedSuccess(Val.getVectorElt(Indices[0]), E);
9155 } else {
9156 // Construct new APValue vector.
9157 SmallVector<APValue, 4> Elts;
9158 for (unsigned I = 0; I < Indices.size(); ++I) {
9159 Elts.push_back(Val.getVectorElt(Indices[I]));
9160 }
9161 APValue VecResult(Elts.data(), Indices.size());
9162 return DerivedSuccess(VecResult, E);
9163 }
9164 }
9165
9166 return false;
9167 }
9168
9169 bool VisitCastExpr(const CastExpr *E) {
9170 switch (E->getCastKind()) {
9171 default:
9172 break;
9173
9174 case CK_AtomicToNonAtomic: {
9175 APValue AtomicVal;
9176 // This does not need to be done in place even for class/array types:
9177 // atomic-to-non-atomic conversion implies copying the object
9178 // representation.
9179 if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
9180 return false;
9181 return DerivedSuccess(AtomicVal, E);
9182 }
9183
9184 case CK_NoOp:
9185 case CK_UserDefinedConversion:
9186 return StmtVisitorTy::Visit(E->getSubExpr());
9187
9188 case CK_HLSLArrayRValue: {
9189 const Expr *SubExpr = E->getSubExpr();
9190 if (!SubExpr->isGLValue()) {
9191 APValue Val;
9192 if (!Evaluate(Val, Info, SubExpr))
9193 return false;
9194 return DerivedSuccess(Val, E);
9195 }
9196
9197 LValue LVal;
9198 if (!EvaluateLValue(SubExpr, LVal, Info))
9199 return false;
9200 APValue RVal;
9201 // Note, we use the subexpression's type in order to retain cv-qualifiers.
9202 if (!handleLValueToRValueConversion(Info, E, SubExpr->getType(), LVal,
9203 RVal))
9204 return false;
9205 return DerivedSuccess(RVal, E);
9206 }
9207 case CK_LValueToRValue: {
9208 LValue LVal;
9209 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
9210 return false;
9211 APValue RVal;
9212 // Note, we use the subexpression's type in order to retain cv-qualifiers.
9214 LVal, RVal))
9215 return false;
9216 return DerivedSuccess(RVal, E);
9217 }
9218 case CK_LValueToRValueBitCast: {
9219 APValue DestValue, SourceValue;
9220 if (!Evaluate(SourceValue, Info, E->getSubExpr()))
9221 return false;
9222 if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
9223 return false;
9224 return DerivedSuccess(DestValue, E);
9225 }
9226
9227 case CK_AddressSpaceConversion: {
9228 APValue Value;
9229 if (!Evaluate(Value, Info, E->getSubExpr()))
9230 return false;
9231 return DerivedSuccess(Value, E);
9232 }
9233 }
9234
9235 return Error(E);
9236 }
9237
9238 bool VisitUnaryPostInc(const UnaryOperator *UO) {
9239 return VisitUnaryPostIncDec(UO);
9240 }
9241 bool VisitUnaryPostDec(const UnaryOperator *UO) {
9242 return VisitUnaryPostIncDec(UO);
9243 }
9244 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
9245 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9246 return Error(UO);
9247
9248 LValue LVal;
9249 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
9250 return false;
9251 APValue RVal;
9252 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
9253 UO->isIncrementOp(), &RVal))
9254 return false;
9255 return DerivedSuccess(RVal, UO);
9256 }
9257
9258 bool VisitStmtExpr(const StmtExpr *E) {
9259 // We will have checked the full-expressions inside the statement expression
9260 // when they were completed, and don't need to check them again now.
9261 llvm::SaveAndRestore NotCheckingForUB(Info.CheckingForUndefinedBehavior,
9262 false);
9263
9264 const CompoundStmt *CS = E->getSubStmt();
9265 if (CS->body_empty())
9266 return true;
9267
9268 BlockScopeRAII Scope(Info);
9270 BE = CS->body_end();
9271 /**/; ++BI) {
9272 if (BI + 1 == BE) {
9273 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
9274 if (!FinalExpr) {
9275 Info.FFDiag((*BI)->getBeginLoc(),
9276 diag::note_constexpr_stmt_expr_unsupported);
9277 return false;
9278 }
9279 return this->Visit(FinalExpr) && Scope.destroy();
9280 }
9281
9283 StmtResult Result = { ReturnValue, nullptr };
9284 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
9285 if (ESR != ESR_Succeeded) {
9286 // FIXME: If the statement-expression terminated due to 'return',
9287 // 'break', or 'continue', it would be nice to propagate that to
9288 // the outer statement evaluation rather than bailing out.
9289 if (ESR != ESR_Failed)
9290 Info.FFDiag((*BI)->getBeginLoc(),
9291 diag::note_constexpr_stmt_expr_unsupported);
9292 return false;
9293 }
9294 }
9295
9296 llvm_unreachable("Return from function from the loop above.");
9297 }
9298
9299 bool VisitPackIndexingExpr(const PackIndexingExpr *E) {
9300 return StmtVisitorTy::Visit(E->getSelectedExpr());
9301 }
9302
9303 /// Visit a value which is evaluated, but whose value is ignored.
9304 void VisitIgnoredValue(const Expr *E) {
9305 EvaluateIgnoredValue(Info, E);
9306 }
9307
9308 /// Potentially visit a MemberExpr's base expression.
9309 void VisitIgnoredBaseExpression(const Expr *E) {
9310 // While MSVC doesn't evaluate the base expression, it does diagnose the
9311 // presence of side-effecting behavior.
9312 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
9313 return;
9314 VisitIgnoredValue(E);
9315 }
9316};
9317
9318} // namespace
9319
9320//===----------------------------------------------------------------------===//
9321// Common base class for lvalue and temporary evaluation.
9322//===----------------------------------------------------------------------===//
9323namespace {
9324template<class Derived>
9325class LValueExprEvaluatorBase
9326 : public ExprEvaluatorBase<Derived> {
9327protected:
9328 LValue &Result;
9329 bool InvalidBaseOK;
9330 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
9331 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
9332
9333 bool Success(APValue::LValueBase B) {
9334 Result.set(B);
9335 return true;
9336 }
9337
9338 bool evaluatePointer(const Expr *E, LValue &Result) {
9339 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
9340 }
9341
9342public:
9343 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
9344 : ExprEvaluatorBaseTy(Info), Result(Result),
9345 InvalidBaseOK(InvalidBaseOK) {}
9346
9347 bool Success(const APValue &V, const Expr *E) {
9348 Result.setFrom(this->Info.Ctx, V);
9349 return true;
9350 }
9351
9352 bool VisitMemberExpr(const MemberExpr *E) {
9353 // Handle non-static data members.
9354 QualType BaseTy;
9355 bool EvalOK;
9356 if (E->isArrow()) {
9357 EvalOK = evaluatePointer(E->getBase(), Result);
9358 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
9359 } else if (E->getBase()->isPRValue()) {
9360 assert(E->getBase()->getType()->isRecordType());
9361 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
9362 BaseTy = E->getBase()->getType();
9363 } else {
9364 EvalOK = this->Visit(E->getBase());
9365 BaseTy = E->getBase()->getType();
9366 }
9367 if (!EvalOK) {
9368 if (!InvalidBaseOK)
9369 return false;
9370 Result.setInvalid(E);
9371 return true;
9372 }
9373
9374 const ValueDecl *MD = E->getMemberDecl();
9375 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
9376 assert(BaseTy->castAsCanonical<RecordType>()->getDecl() ==
9377 FD->getParent()->getCanonicalDecl() &&
9378 "record / field mismatch");
9379 (void)BaseTy;
9380 if (!HandleLValueMember(this->Info, E, Result, FD))
9381 return false;
9382 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
9383 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
9384 return false;
9385 } else
9386 return this->Error(E);
9387
9388 if (MD->getType()->isReferenceType()) {
9389 APValue RefValue;
9390 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
9391 RefValue))
9392 return false;
9393 return Success(RefValue, E);
9394 }
9395 return true;
9396 }
9397
9398 bool VisitBinaryOperator(const BinaryOperator *E) {
9399 switch (E->getOpcode()) {
9400 default:
9401 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9402
9403 case BO_PtrMemD:
9404 case BO_PtrMemI:
9405 return HandleMemberPointerAccess(this->Info, E, Result);
9406 }
9407 }
9408
9409 bool VisitCastExpr(const CastExpr *E) {
9410 switch (E->getCastKind()) {
9411 default:
9412 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9413
9414 case CK_DerivedToBase:
9415 case CK_UncheckedDerivedToBase:
9416 if (!this->Visit(E->getSubExpr()))
9417 return false;
9418
9419 // Now figure out the necessary offset to add to the base LV to get from
9420 // the derived class to the base class.
9421 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
9422 Result);
9423 }
9424 }
9425};
9426}
9427
9428//===----------------------------------------------------------------------===//
9429// LValue Evaluation
9430//
9431// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
9432// function designators (in C), decl references to void objects (in C), and
9433// temporaries (if building with -Wno-address-of-temporary).
9434//
9435// LValue evaluation produces values comprising a base expression of one of the
9436// following types:
9437// - Declarations
9438// * VarDecl
9439// * FunctionDecl
9440// - Literals
9441// * CompoundLiteralExpr in C (and in global scope in C++)
9442// * StringLiteral
9443// * PredefinedExpr
9444// * ObjCStringLiteralExpr
9445// * ObjCEncodeExpr
9446// * AddrLabelExpr
9447// * BlockExpr
9448// * CallExpr for a MakeStringConstant builtin
9449// - typeid(T) expressions, as TypeInfoLValues
9450// - Locals and temporaries
9451// * MaterializeTemporaryExpr
9452// * Any Expr, with a CallIndex indicating the function in which the temporary
9453// was evaluated, for cases where the MaterializeTemporaryExpr is missing
9454// from the AST (FIXME).
9455// * A MaterializeTemporaryExpr that has static storage duration, with no
9456// CallIndex, for a lifetime-extended temporary.
9457// * The ConstantExpr that is currently being evaluated during evaluation of an
9458// immediate invocation.
9459// plus an offset in bytes.
9460//===----------------------------------------------------------------------===//
9461namespace {
9462class LValueExprEvaluator
9463 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
9464public:
9465 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
9466 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
9467
9468 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
9469 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
9470
9471 bool VisitCallExpr(const CallExpr *E);
9472 bool VisitDeclRefExpr(const DeclRefExpr *E);
9473 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
9474 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
9475 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
9476 bool VisitMemberExpr(const MemberExpr *E);
9477 bool VisitStringLiteral(const StringLiteral *E) {
9478 return Success(
9479 APValue::LValueBase(E, 0, Info.Ctx.getNextStringLiteralVersion()));
9480 }
9481 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
9482 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
9483 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
9484 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
9485 bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E);
9486 bool VisitUnaryDeref(const UnaryOperator *E);
9487 bool VisitUnaryReal(const UnaryOperator *E);
9488 bool VisitUnaryImag(const UnaryOperator *E);
9489 bool VisitUnaryPreInc(const UnaryOperator *UO) {
9490 return VisitUnaryPreIncDec(UO);
9491 }
9492 bool VisitUnaryPreDec(const UnaryOperator *UO) {
9493 return VisitUnaryPreIncDec(UO);
9494 }
9495 bool VisitBinAssign(const BinaryOperator *BO);
9496 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
9497
9498 bool VisitCastExpr(const CastExpr *E) {
9499 switch (E->getCastKind()) {
9500 default:
9501 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
9502
9503 case CK_LValueBitCast:
9504 this->CCEDiag(E, diag::note_constexpr_invalid_cast)
9505 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
9506 << Info.Ctx.getLangOpts().CPlusPlus << E->getSourceRange();
9507 if (!Visit(E->getSubExpr()))
9508 return false;
9509 Result.Designator.setInvalid();
9510 return true;
9511
9512 case CK_BaseToDerived:
9513 if (!Visit(E->getSubExpr()))
9514 return false;
9515 return HandleBaseToDerivedCast(Info, E, Result);
9516
9517 case CK_Dynamic:
9518 if (!Visit(E->getSubExpr()))
9519 return false;
9521 }
9522 }
9523};
9524} // end anonymous namespace
9525
9526/// Get an lvalue to a field of a lambda's closure type.
9527static bool HandleLambdaCapture(EvalInfo &Info, const Expr *E, LValue &Result,
9528 const CXXMethodDecl *MD, const FieldDecl *FD,
9529 bool LValueToRValueConversion) {
9530 // Static lambda function call operators can't have captures. We already
9531 // diagnosed this, so bail out here.
9532 if (MD->isStatic()) {
9533 assert(Info.CurrentCall->This == nullptr &&
9534 "This should not be set for a static call operator");
9535 return false;
9536 }
9537
9538 // Start with 'Result' referring to the complete closure object...
9540 // Self may be passed by reference or by value.
9541 const ParmVarDecl *Self = MD->getParamDecl(0);
9542 if (Self->getType()->isReferenceType()) {
9543 APValue *RefValue = Info.getParamSlot(Info.CurrentCall->Arguments, Self);
9544 if (!RefValue->allowConstexprUnknown() || RefValue->hasValue())
9545 Result.setFrom(Info.Ctx, *RefValue);
9546 } else {
9547 const ParmVarDecl *VD = Info.CurrentCall->Arguments.getOrigParam(Self);
9548 CallStackFrame *Frame =
9549 Info.getCallFrameAndDepth(Info.CurrentCall->Arguments.CallIndex)
9550 .first;
9551 unsigned Version = Info.CurrentCall->Arguments.Version;
9552 Result.set({VD, Frame->Index, Version});
9553 }
9554 } else
9555 Result = *Info.CurrentCall->This;
9556
9557 // ... then update it to refer to the field of the closure object
9558 // that represents the capture.
9559 if (!HandleLValueMember(Info, E, Result, FD))
9560 return false;
9561
9562 // And if the field is of reference type (or if we captured '*this' by
9563 // reference), update 'Result' to refer to what
9564 // the field refers to.
9565 if (LValueToRValueConversion) {
9566 APValue RVal;
9567 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result, RVal))
9568 return false;
9569 Result.setFrom(Info.Ctx, RVal);
9570 }
9571 return true;
9572}
9573
9574/// Evaluate an expression as an lvalue. This can be legitimately called on
9575/// expressions which are not glvalues, in three cases:
9576/// * function designators in C, and
9577/// * "extern void" objects
9578/// * @selector() expressions in Objective-C
9579static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
9580 bool InvalidBaseOK) {
9581 assert(!E->isValueDependent());
9582 assert(E->isGLValue() || E->getType()->isFunctionType() ||
9584 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
9585}
9586
9587bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
9588 const ValueDecl *D = E->getDecl();
9589
9590 // If we are within a lambda's call operator, check whether the 'VD' referred
9591 // to within 'E' actually represents a lambda-capture that maps to a
9592 // data-member/field within the closure object, and if so, evaluate to the
9593 // field or what the field refers to.
9594 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
9596 // We don't always have a complete capture-map when checking or inferring if
9597 // the function call operator meets the requirements of a constexpr function
9598 // - but we don't need to evaluate the captures to determine constexprness
9599 // (dcl.constexpr C++17).
9600 if (Info.checkingPotentialConstantExpression())
9601 return false;
9602
9603 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(D)) {
9604 const auto *MD = cast<CXXMethodDecl>(Info.CurrentCall->Callee);
9605 return HandleLambdaCapture(Info, E, Result, MD, FD,
9606 FD->getType()->isReferenceType());
9607 }
9608 }
9609
9610 if (isa<FunctionDecl, MSGuidDecl, TemplateParamObjectDecl,
9611 UnnamedGlobalConstantDecl>(D))
9612 return Success(cast<ValueDecl>(D));
9613 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
9614 return VisitVarDecl(E, VD);
9615 if (const BindingDecl *BD = dyn_cast<BindingDecl>(D))
9616 return Visit(BD->getBinding());
9617 return Error(E);
9618}
9619
9620bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
9621 CallStackFrame *Frame = nullptr;
9622 unsigned Version = 0;
9623 if (VD->hasLocalStorage()) {
9624 // Only if a local variable was declared in the function currently being
9625 // evaluated, do we expect to be able to find its value in the current
9626 // frame. (Otherwise it was likely declared in an enclosing context and
9627 // could either have a valid evaluatable value (for e.g. a constexpr
9628 // variable) or be ill-formed (and trigger an appropriate evaluation
9629 // diagnostic)).
9630 CallStackFrame *CurrFrame = Info.CurrentCall;
9631 if (CurrFrame->Callee && CurrFrame->Callee->Equals(VD->getDeclContext())) {
9632 // Function parameters are stored in some caller's frame. (Usually the
9633 // immediate caller, but for an inherited constructor they may be more
9634 // distant.)
9635 if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) {
9636 if (CurrFrame->Arguments) {
9637 VD = CurrFrame->Arguments.getOrigParam(PVD);
9638 Frame =
9639 Info.getCallFrameAndDepth(CurrFrame->Arguments.CallIndex).first;
9640 Version = CurrFrame->Arguments.Version;
9641 }
9642 } else {
9643 Frame = CurrFrame;
9644 Version = CurrFrame->getCurrentTemporaryVersion(VD);
9645 }
9646 }
9647 }
9648
9649 if (!VD->getType()->isReferenceType()) {
9650 if (Frame) {
9651 Result.set({VD, Frame->Index, Version});
9652 return true;
9653 }
9654 return Success(VD);
9655 }
9656
9657 if (!Info.getLangOpts().CPlusPlus11) {
9658 Info.CCEDiag(E, diag::note_constexpr_ltor_non_integral, 1)
9659 << VD << VD->getType();
9660 Info.Note(VD->getLocation(), diag::note_declared_at);
9661 }
9662
9663 APValue *V;
9664 if (!evaluateVarDeclInit(Info, E, VD, Frame, Version, V))
9665 return false;
9666
9667 if (!V) {
9668 Result.set(VD);
9669 Result.AllowConstexprUnknown = true;
9670 return true;
9671 }
9672
9673 return Success(*V, E);
9674}
9675
9676bool LValueExprEvaluator::VisitCallExpr(const CallExpr *E) {
9677 if (!IsConstantEvaluatedBuiltinCall(E))
9678 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9679
9680 switch (E->getBuiltinCallee()) {
9681 default:
9682 return false;
9683 case Builtin::BIas_const:
9684 case Builtin::BIforward:
9685 case Builtin::BIforward_like:
9686 case Builtin::BImove:
9687 case Builtin::BImove_if_noexcept:
9688 if (cast<FunctionDecl>(E->getCalleeDecl())->isConstexpr())
9689 return Visit(E->getArg(0));
9690 break;
9691 }
9692
9693 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9694}
9695
9696bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
9697 const MaterializeTemporaryExpr *E) {
9698 // Walk through the expression to find the materialized temporary itself.
9701 const Expr *Inner =
9702 E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
9703
9704 // If we passed any comma operators, evaluate their LHSs.
9705 for (const Expr *E : CommaLHSs)
9706 if (!EvaluateIgnoredValue(Info, E))
9707 return false;
9708
9709 // A materialized temporary with static storage duration can appear within the
9710 // result of a constant expression evaluation, so we need to preserve its
9711 // value for use outside this evaluation.
9712 APValue *Value;
9713 if (E->getStorageDuration() == SD_Static) {
9714 if (Info.EvalMode == EvaluationMode::ConstantFold)
9715 return false;
9716 // FIXME: What about SD_Thread?
9717 Value = E->getOrCreateValue(true);
9718 *Value = APValue();
9719 Result.set(E);
9720 } else {
9721 Value = &Info.CurrentCall->createTemporary(
9722 E, Inner->getType(),
9723 E->getStorageDuration() == SD_FullExpression ? ScopeKind::FullExpression
9724 : ScopeKind::Block,
9725 Result);
9726 }
9727
9728 QualType Type = Inner->getType();
9729
9730 // Materialize the temporary itself.
9731 if (!EvaluateInPlace(*Value, Info, Result, Inner)) {
9732 *Value = APValue();
9733 return false;
9734 }
9735
9736 // Adjust our lvalue to refer to the desired subobject.
9737 for (unsigned I = Adjustments.size(); I != 0; /**/) {
9738 --I;
9739 switch (Adjustments[I].Kind) {
9741 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
9742 Type, Result))
9743 return false;
9744 Type = Adjustments[I].DerivedToBase.BasePath->getType();
9745 break;
9746
9748 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
9749 return false;
9750 Type = Adjustments[I].Field->getType();
9751 break;
9752
9754 if (!HandleMemberPointerAccess(this->Info, Type, Result,
9755 Adjustments[I].Ptr.RHS))
9756 return false;
9757 Type = Adjustments[I].Ptr.MPT->getPointeeType();
9758 break;
9759 }
9760 }
9761
9762 return true;
9763}
9764
9765bool
9766LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
9767 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
9768 "lvalue compound literal in c++?");
9769 APValue *Lit;
9770 // If CompountLiteral has static storage, its value can be used outside
9771 // this expression. So evaluate it once and store it in ASTContext.
9772 if (E->hasStaticStorage()) {
9773 Lit = &E->getOrCreateStaticValue(Info.Ctx);
9774 Result.set(E);
9775 // Reset any previously evaluated state, otherwise evaluation below might
9776 // fail.
9777 // FIXME: Should we just re-use the previously evaluated value instead?
9778 *Lit = APValue();
9779 } else {
9780 assert(!Info.getLangOpts().CPlusPlus);
9781 Lit = &Info.CurrentCall->createTemporary(E, E->getInitializer()->getType(),
9782 ScopeKind::Block, Result);
9783 }
9784 // FIXME: Evaluating in place isn't always right. We should figure out how to
9785 // use appropriate evaluation context here, see
9786 // clang/test/AST/static-compound-literals-reeval.cpp for a failure.
9787 if (!EvaluateInPlace(*Lit, Info, Result, E->getInitializer())) {
9788 *Lit = APValue();
9789 return false;
9790 }
9791 return true;
9792}
9793
9794bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
9795 TypeInfoLValue TypeInfo;
9796
9797 if (!E->isPotentiallyEvaluated()) {
9798 if (E->isTypeOperand())
9799 TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
9800 else
9801 TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
9802 } else {
9803 if (!Info.Ctx.getLangOpts().CPlusPlus20) {
9804 Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
9805 << E->getExprOperand()->getType()
9806 << E->getExprOperand()->getSourceRange();
9807 }
9808
9809 if (!Visit(E->getExprOperand()))
9810 return false;
9811
9812 std::optional<DynamicType> DynType =
9814 if (!DynType)
9815 return false;
9816
9817 TypeInfo = TypeInfoLValue(
9818 Info.Ctx.getCanonicalTagType(DynType->Type).getTypePtr());
9819 }
9820
9821 return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
9822}
9823
9824bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
9825 return Success(E->getGuidDecl());
9826}
9827
9828bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
9829 // Handle static data members.
9830 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
9831 VisitIgnoredBaseExpression(E->getBase());
9832 return VisitVarDecl(E, VD);
9833 }
9834
9835 // Handle static member functions.
9836 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
9837 if (MD->isStatic()) {
9838 VisitIgnoredBaseExpression(E->getBase());
9839 return Success(MD);
9840 }
9841 }
9842
9843 // Handle non-static data members.
9844 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
9845}
9846
9847bool LValueExprEvaluator::VisitExtVectorElementExpr(
9848 const ExtVectorElementExpr *E) {
9849 bool Success = true;
9850
9851 APValue Val;
9852 if (!Evaluate(Val, Info, E->getBase())) {
9853 if (!Info.noteFailure())
9854 return false;
9855 Success = false;
9856 }
9857
9859 E->getEncodedElementAccess(Indices);
9860 // FIXME: support accessing more than one element
9861 if (Indices.size() > 1)
9862 return false;
9863
9864 if (Success) {
9865 Result.setFrom(Info.Ctx, Val);
9866 QualType BaseType = E->getBase()->getType();
9867 if (E->isArrow())
9868 BaseType = BaseType->getPointeeType();
9869 const auto *VT = BaseType->castAs<VectorType>();
9870 HandleLValueVectorElement(Info, E, Result, VT->getElementType(),
9871 VT->getNumElements(), Indices[0]);
9872 }
9873
9874 return Success;
9875}
9876
9877bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
9878 if (E->getBase()->getType()->isSveVLSBuiltinType())
9879 return Error(E);
9880
9881 APSInt Index;
9882 bool Success = true;
9883
9884 if (const auto *VT = E->getBase()->getType()->getAs<VectorType>()) {
9885 APValue Val;
9886 if (!Evaluate(Val, Info, E->getBase())) {
9887 if (!Info.noteFailure())
9888 return false;
9889 Success = false;
9890 }
9891
9892 if (!EvaluateInteger(E->getIdx(), Index, Info)) {
9893 if (!Info.noteFailure())
9894 return false;
9895 Success = false;
9896 }
9897
9898 if (Success) {
9899 Result.setFrom(Info.Ctx, Val);
9900 HandleLValueVectorElement(Info, E, Result, VT->getElementType(),
9901 VT->getNumElements(), Index.getZExtValue());
9902 }
9903
9904 return Success;
9905 }
9906
9907 // C++17's rules require us to evaluate the LHS first, regardless of which
9908 // side is the base.
9909 for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) {
9910 if (SubExpr == E->getBase() ? !evaluatePointer(SubExpr, Result)
9911 : !EvaluateInteger(SubExpr, Index, Info)) {
9912 if (!Info.noteFailure())
9913 return false;
9914 Success = false;
9915 }
9916 }
9917
9918 return Success &&
9919 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
9920}
9921
9922bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
9923 bool Success = evaluatePointer(E->getSubExpr(), Result);
9924 // [C++26][expr.unary.op]
9925 // If the operand points to an object or function, the result
9926 // denotes that object or function; otherwise, the behavior is undefined.
9927 // Because &(*(type*)0) is a common pattern, we do not fail the evaluation
9928 // immediately.
9930 return Success;
9932 E->getType())) ||
9933 Info.noteUndefinedBehavior();
9934}
9935
9936bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
9937 if (!Visit(E->getSubExpr()))
9938 return false;
9939 // __real is a no-op on scalar lvalues.
9940 if (E->getSubExpr()->getType()->isAnyComplexType())
9941 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
9942 return true;
9943}
9944
9945bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
9946 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
9947 "lvalue __imag__ on scalar?");
9948 if (!Visit(E->getSubExpr()))
9949 return false;
9950 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
9951 return true;
9952}
9953
9954bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
9955 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9956 return Error(UO);
9957
9958 if (!this->Visit(UO->getSubExpr()))
9959 return false;
9960
9961 return handleIncDec(
9962 this->Info, UO, Result, UO->getSubExpr()->getType(),
9963 UO->isIncrementOp(), nullptr);
9964}
9965
9966bool LValueExprEvaluator::VisitCompoundAssignOperator(
9967 const CompoundAssignOperator *CAO) {
9968 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9969 return Error(CAO);
9970
9971 bool Success = true;
9972
9973 // C++17 onwards require that we evaluate the RHS first.
9974 APValue RHS;
9975 if (!Evaluate(RHS, this->Info, CAO->getRHS())) {
9976 if (!Info.noteFailure())
9977 return false;
9978 Success = false;
9979 }
9980
9981 // The overall lvalue result is the result of evaluating the LHS.
9982 if (!this->Visit(CAO->getLHS()) || !Success)
9983 return false;
9984
9986 this->Info, CAO,
9987 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
9988 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
9989}
9990
9991bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
9992 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9993 return Error(E);
9994
9995 bool Success = true;
9996
9997 // C++17 onwards require that we evaluate the RHS first.
9998 APValue NewVal;
9999 if (!Evaluate(NewVal, this->Info, E->getRHS())) {
10000 if (!Info.noteFailure())
10001 return false;
10002 Success = false;
10003 }
10004
10005 if (!this->Visit(E->getLHS()) || !Success)
10006 return false;
10007
10008 if (Info.getLangOpts().CPlusPlus20 &&
10010 return false;
10011
10012 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
10013 NewVal);
10014}
10015
10016//===----------------------------------------------------------------------===//
10017// Pointer Evaluation
10018//===----------------------------------------------------------------------===//
10019
10020/// Convenience function. LVal's base must be a call to an alloc_size
10021/// function.
10023 const LValue &LVal,
10024 llvm::APInt &Result) {
10025 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
10026 "Can't get the size of a non alloc_size function");
10027 const auto *Base = LVal.getLValueBase().get<const Expr *>();
10028 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
10029 std::optional<llvm::APInt> Size =
10030 CE->evaluateBytesReturnedByAllocSizeCall(Ctx);
10031 if (!Size)
10032 return false;
10033
10034 Result = std::move(*Size);
10035 return true;
10036}
10037
10038/// Attempts to evaluate the given LValueBase as the result of a call to
10039/// a function with the alloc_size attribute. If it was possible to do so, this
10040/// function will return true, make Result's Base point to said function call,
10041/// and mark Result's Base as invalid.
10043 LValue &Result) {
10044 if (Base.isNull())
10045 return false;
10046
10047 // Because we do no form of static analysis, we only support const variables.
10048 //
10049 // Additionally, we can't support parameters, nor can we support static
10050 // variables (in the latter case, use-before-assign isn't UB; in the former,
10051 // we have no clue what they'll be assigned to).
10052 const auto *VD =
10053 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
10054 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
10055 return false;
10056
10057 const Expr *Init = VD->getAnyInitializer();
10058 if (!Init || Init->getType().isNull())
10059 return false;
10060
10061 const Expr *E = Init->IgnoreParens();
10062 if (!tryUnwrapAllocSizeCall(E))
10063 return false;
10064
10065 // Store E instead of E unwrapped so that the type of the LValue's base is
10066 // what the user wanted.
10067 Result.setInvalid(E);
10068
10069 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
10070 Result.addUnsizedArray(Info, E, Pointee);
10071 return true;
10072}
10073
10074namespace {
10075class PointerExprEvaluator
10076 : public ExprEvaluatorBase<PointerExprEvaluator> {
10077 LValue &Result;
10078 bool InvalidBaseOK;
10079
10080 bool Success(const Expr *E) {
10081 Result.set(E);
10082 return true;
10083 }
10084
10085 bool evaluateLValue(const Expr *E, LValue &Result) {
10086 return EvaluateLValue(E, Result, Info, InvalidBaseOK);
10087 }
10088
10089 bool evaluatePointer(const Expr *E, LValue &Result) {
10090 return EvaluatePointer(E, Result, Info, InvalidBaseOK);
10091 }
10092
10093 bool visitNonBuiltinCallExpr(const CallExpr *E);
10094public:
10095
10096 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
10097 : ExprEvaluatorBaseTy(info), Result(Result),
10098 InvalidBaseOK(InvalidBaseOK) {}
10099
10100 bool Success(const APValue &V, const Expr *E) {
10101 Result.setFrom(Info.Ctx, V);
10102 return true;
10103 }
10104 bool ZeroInitialization(const Expr *E) {
10105 Result.setNull(Info.Ctx, E->getType());
10106 return true;
10107 }
10108
10109 bool VisitBinaryOperator(const BinaryOperator *E);
10110 bool VisitCastExpr(const CastExpr* E);
10111 bool VisitUnaryAddrOf(const UnaryOperator *E);
10112 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
10113 { return Success(E); }
10114 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
10116 return Success(E);
10117 if (Info.noteFailure())
10118 EvaluateIgnoredValue(Info, E->getSubExpr());
10119 return Error(E);
10120 }
10121 bool VisitObjCArrayLiteral(const ObjCArrayLiteral *E) {
10122 return E->isExpressibleAsConstantInitializer() ? Success(E) : Error(E);
10123 }
10124 bool VisitObjCDictionaryLiteral(const ObjCDictionaryLiteral *E) {
10125 return E->isExpressibleAsConstantInitializer() ? Success(E) : Error(E);
10126 }
10127 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
10128 { return Success(E); }
10129 bool VisitCallExpr(const CallExpr *E);
10130 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
10131 bool VisitBlockExpr(const BlockExpr *E) {
10132 if (!E->getBlockDecl()->hasCaptures())
10133 return Success(E);
10134 return Error(E);
10135 }
10136 bool VisitCXXThisExpr(const CXXThisExpr *E) {
10137 auto DiagnoseInvalidUseOfThis = [&] {
10138 if (Info.getLangOpts().CPlusPlus11)
10139 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
10140 else
10141 Info.FFDiag(E);
10142 };
10143
10144 // Can't look at 'this' when checking a potential constant expression.
10145 if (Info.checkingPotentialConstantExpression())
10146 return false;
10147
10148 bool IsExplicitLambda =
10149 isLambdaCallWithExplicitObjectParameter(Info.CurrentCall->Callee);
10150 if (!IsExplicitLambda) {
10151 if (!Info.CurrentCall->This) {
10152 DiagnoseInvalidUseOfThis();
10153 return false;
10154 }
10155
10156 Result = *Info.CurrentCall->This;
10157 }
10158
10159 if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
10160 // Ensure we actually have captured 'this'. If something was wrong with
10161 // 'this' capture, the error would have been previously reported.
10162 // Otherwise we can be inside of a default initialization of an object
10163 // declared by lambda's body, so no need to return false.
10164 if (!Info.CurrentCall->LambdaThisCaptureField) {
10165 if (IsExplicitLambda && !Info.CurrentCall->This) {
10166 DiagnoseInvalidUseOfThis();
10167 return false;
10168 }
10169
10170 return true;
10171 }
10172
10173 const auto *MD = cast<CXXMethodDecl>(Info.CurrentCall->Callee);
10174 return HandleLambdaCapture(
10175 Info, E, Result, MD, Info.CurrentCall->LambdaThisCaptureField,
10176 Info.CurrentCall->LambdaThisCaptureField->getType()->isPointerType());
10177 }
10178 return true;
10179 }
10180
10181 bool VisitCXXNewExpr(const CXXNewExpr *E);
10182
10183 bool VisitSourceLocExpr(const SourceLocExpr *E) {
10184 assert(!E->isIntType() && "SourceLocExpr isn't a pointer type?");
10185 APValue LValResult = E->EvaluateInContext(
10186 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
10187 Result.setFrom(Info.Ctx, LValResult);
10188 return true;
10189 }
10190
10191 bool VisitEmbedExpr(const EmbedExpr *E) {
10192 llvm::report_fatal_error("Not yet implemented for ExprConstant.cpp");
10193 return true;
10194 }
10195
10196 bool VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr *E) {
10197 std::string ResultStr = E->ComputeName(Info.Ctx);
10198
10199 QualType CharTy = Info.Ctx.CharTy.withConst();
10200 APInt Size(Info.Ctx.getTypeSize(Info.Ctx.getSizeType()),
10201 ResultStr.size() + 1);
10202 QualType ArrayTy = Info.Ctx.getConstantArrayType(
10203 CharTy, Size, nullptr, ArraySizeModifier::Normal, 0);
10204
10205 StringLiteral *SL =
10206 StringLiteral::Create(Info.Ctx, ResultStr, StringLiteralKind::Ordinary,
10207 /*Pascal*/ false, ArrayTy, E->getLocation());
10208
10209 evaluateLValue(SL, Result);
10210 Result.addArray(Info, E, cast<ConstantArrayType>(ArrayTy));
10211 return true;
10212 }
10213
10214 // FIXME: Missing: @protocol, @selector
10215};
10216} // end anonymous namespace
10217
10218static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
10219 bool InvalidBaseOK) {
10220 assert(!E->isValueDependent());
10221 assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
10222 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
10223}
10224
10225bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
10226 if (E->getOpcode() != BO_Add &&
10227 E->getOpcode() != BO_Sub)
10228 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10229
10230 const Expr *PExp = E->getLHS();
10231 const Expr *IExp = E->getRHS();
10232 if (IExp->getType()->isPointerType())
10233 std::swap(PExp, IExp);
10234
10235 bool EvalPtrOK = evaluatePointer(PExp, Result);
10236 if (!EvalPtrOK && !Info.noteFailure())
10237 return false;
10238
10239 llvm::APSInt Offset;
10240 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
10241 return false;
10242
10243 if (E->getOpcode() == BO_Sub)
10244 negateAsSigned(Offset);
10245
10246 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
10247 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
10248}
10249
10250bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
10251 // [C11 6.5.3.2p3]: if the operand of '&' is the result of a unary '*'
10252 // operator, neither operator is evaluated and the result is as if both were
10253 // omitted (except that the operators' constraints, already enforced by Sema,
10254 // still apply, and the result is not an lvalue). So '&*p' is just the pointer
10255 // value 'p' with no dereference, and forming it is therefore not undefined
10256 // behavior even when 'p' is null, e.g. '&*(int *)0'. Evaluate the pointer
10257 // operand directly so we don't spuriously diagnose a null dereference.
10258 if (!Info.getLangOpts().CPlusPlus) {
10259 const Expr *Sub = E->getSubExpr()->IgnoreParens();
10260 if (const auto *Deref = dyn_cast<UnaryOperator>(Sub);
10261 Deref && Deref->getOpcode() == UO_Deref)
10262 return evaluatePointer(Deref->getSubExpr(), Result);
10263 }
10264 return evaluateLValue(E->getSubExpr(), Result);
10265}
10266
10267// Is the provided decl 'std::source_location::current'?
10269 if (!FD)
10270 return false;
10271 const IdentifierInfo *FnII = FD->getIdentifier();
10272 if (!FnII || !FnII->isStr("current"))
10273 return false;
10274
10275 const auto *RD = dyn_cast<RecordDecl>(FD->getParent());
10276 if (!RD)
10277 return false;
10278
10279 const IdentifierInfo *ClassII = RD->getIdentifier();
10280 return RD->isInStdNamespace() && ClassII && ClassII->isStr("source_location");
10281}
10282
10283bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
10284 const Expr *SubExpr = E->getSubExpr();
10285
10286 switch (E->getCastKind()) {
10287 default:
10288 break;
10289 case CK_BitCast:
10290 case CK_CPointerToObjCPointerCast:
10291 case CK_BlockPointerToObjCPointerCast:
10292 case CK_AnyPointerToBlockPointerCast:
10293 case CK_AddressSpaceConversion:
10294 if (!Visit(SubExpr))
10295 return false;
10296 if (E->getType()->isFunctionPointerType() ||
10297 SubExpr->getType()->isFunctionPointerType()) {
10298 // Casting between two function pointer types, or between a function
10299 // pointer and an object pointer, is always a reinterpret_cast.
10300 CCEDiag(E, diag::note_constexpr_invalid_cast)
10301 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
10302 << Info.Ctx.getLangOpts().CPlusPlus;
10303 Result.Designator.setInvalid();
10304 } else if (!E->getType()->isVoidPointerType()) {
10305 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
10306 // permitted in constant expressions in C++11. Bitcasts from cv void* are
10307 // also static_casts, but we disallow them as a resolution to DR1312.
10308 //
10309 // In some circumstances, we permit casting from void* to cv1 T*, when the
10310 // actual pointee object is actually a cv2 T.
10311 bool HasValidResult = !Result.InvalidBase && !Result.Designator.Invalid &&
10312 !Result.IsNullPtr;
10313 bool VoidPtrCastMaybeOK =
10314 Result.IsNullPtr ||
10315 (HasValidResult &&
10316 Info.Ctx.hasSimilarType(Result.Designator.getType(Info.Ctx),
10317 E->getType()->getPointeeType()));
10318 // 1. We'll allow it in std::allocator::allocate, and anything which that
10319 // calls.
10320 // 2. HACK 2022-03-28: Work around an issue with libstdc++'s
10321 // <source_location> header. Fixed in GCC 12 and later (2022-04-??).
10322 // We'll allow it in the body of std::source_location::current. GCC's
10323 // implementation had a parameter of type `void*`, and casts from
10324 // that back to `const __impl*` in its body.
10325 if (VoidPtrCastMaybeOK &&
10326 (Info.getStdAllocatorCaller("allocate") ||
10327 IsDeclSourceLocationCurrent(Info.CurrentCall->Callee) ||
10328 Info.getLangOpts().CPlusPlus26)) {
10329 // Permitted.
10330 } else {
10331 if (SubExpr->getType()->isVoidPointerType() &&
10332 Info.getLangOpts().CPlusPlus) {
10333 if (HasValidResult)
10334 CCEDiag(E, diag::note_constexpr_invalid_void_star_cast)
10335 << SubExpr->getType() << Info.getLangOpts().CPlusPlus26
10336 << Result.Designator.getType(Info.Ctx).getCanonicalType()
10337 << E->getType()->getPointeeType();
10338 else
10339 CCEDiag(E, diag::note_constexpr_invalid_cast)
10340 << diag::ConstexprInvalidCastKind::CastFrom
10341 << SubExpr->getType();
10342 } else
10343 CCEDiag(E, diag::note_constexpr_invalid_cast)
10344 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
10345 << Info.Ctx.getLangOpts().CPlusPlus;
10346 Result.Designator.setInvalid();
10347 }
10348 }
10349 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
10350 ZeroInitialization(E);
10351 return true;
10352
10353 case CK_DerivedToBase:
10354 case CK_UncheckedDerivedToBase:
10355 if (!evaluatePointer(E->getSubExpr(), Result))
10356 return false;
10357 if (!Result.Base && Result.Offset.isZero())
10358 return true;
10359
10360 // Now figure out the necessary offset to add to the base LV to get from
10361 // the derived class to the base class.
10362 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
10363 castAs<PointerType>()->getPointeeType(),
10364 Result);
10365
10366 case CK_BaseToDerived:
10367 if (!Visit(E->getSubExpr()))
10368 return false;
10369 if (!Result.Base && Result.Offset.isZero())
10370 return true;
10371 return HandleBaseToDerivedCast(Info, E, Result);
10372
10373 case CK_Dynamic:
10374 if (!Visit(E->getSubExpr()))
10375 return false;
10377
10378 case CK_NullToPointer:
10379 VisitIgnoredValue(E->getSubExpr());
10380 return ZeroInitialization(E);
10381
10382 case CK_IntegralToPointer: {
10383 CCEDiag(E, diag::note_constexpr_invalid_cast)
10384 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
10385 << Info.Ctx.getLangOpts().CPlusPlus;
10386
10387 APValue Value;
10388 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
10389 break;
10390
10391 if (Value.isInt()) {
10392 unsigned Size = Info.Ctx.getTypeSize(E->getType());
10393 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
10394 if (N == Info.Ctx.getTargetNullPointerValue(E->getType())) {
10395 Result.setNull(Info.Ctx, E->getType());
10396 } else {
10397 Result.Base = (Expr *)nullptr;
10398 Result.InvalidBase = false;
10399 Result.Offset = CharUnits::fromQuantity(N);
10400 Result.Designator.setInvalid();
10401 Result.IsNullPtr = false;
10402 }
10403 return true;
10404 } else {
10405 // In rare instances, the value isn't an lvalue.
10406 // For example, when the value is the difference between the addresses of
10407 // two labels. We reject that as a constant expression because we can't
10408 // compute a valid offset to convert into a pointer.
10409 if (!Value.isLValue())
10410 return false;
10411
10412 // Cast is of an lvalue, no need to change value.
10413 Result.setFrom(Info.Ctx, Value);
10414 return true;
10415 }
10416 }
10417
10418 case CK_ArrayToPointerDecay: {
10419 if (SubExpr->isGLValue()) {
10420 if (!evaluateLValue(SubExpr, Result))
10421 return false;
10422 } else {
10423 APValue &Value = Info.CurrentCall->createTemporary(
10424 SubExpr, SubExpr->getType(), ScopeKind::FullExpression, Result);
10425 if (!EvaluateInPlace(Value, Info, Result, SubExpr))
10426 return false;
10427 }
10428 // The result is a pointer to the first element of the array.
10429 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
10430 if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
10431 Result.addArray(Info, E, CAT);
10432 else
10433 Result.addUnsizedArray(Info, E, AT->getElementType());
10434 return true;
10435 }
10436
10437 case CK_FunctionToPointerDecay:
10438 return evaluateLValue(SubExpr, Result);
10439
10440 case CK_LValueToRValue: {
10441 LValue LVal;
10442 if (!evaluateLValue(E->getSubExpr(), LVal))
10443 return false;
10444
10445 APValue RVal;
10446 // Note, we use the subexpression's type in order to retain cv-qualifiers.
10448 LVal, RVal))
10449 return InvalidBaseOK &&
10450 evaluateLValueAsAllocSize(Info, LVal.Base, Result);
10451 return Success(RVal, E);
10452 }
10453 }
10454
10455 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10456}
10457
10459 UnaryExprOrTypeTrait ExprKind) {
10460 // C++ [expr.alignof]p3:
10461 // When alignof is applied to a reference type, the result is the
10462 // alignment of the referenced type.
10463 T = T.getNonReferenceType();
10464
10465 if (T.getQualifiers().hasUnaligned())
10466 return CharUnits::One();
10467
10468 const bool AlignOfReturnsPreferred =
10469 Ctx.getLangOpts().isCompatibleWith(LangOptions::ClangABI::Ver7);
10470
10471 // __alignof is defined to return the preferred alignment.
10472 // Before 8, clang returned the preferred alignment for alignof and _Alignof
10473 // as well.
10474 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
10475 return Ctx.toCharUnitsFromBits(Ctx.getPreferredTypeAlign(T.getTypePtr()));
10476 // alignof and _Alignof are defined to return the ABI alignment.
10477 else if (ExprKind == UETT_AlignOf)
10478 return Ctx.getTypeAlignInChars(T.getTypePtr());
10479 else
10480 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
10481}
10482
10483// Convert a builtin ID to the canonical x86 builtin ID the constant evaluators
10484// dispatch on in their x86 target-specific cases, or 0 if \p BuiltinOp is a
10485// target builtin those cases should not handle.
10486//
10487// Target-independent builtins are returned unchanged. Target builtin IDs of
10488// different targets overlap (each target numbers its builtins from
10489// Builtin::FirstTSBuiltin), so a target builtin ID is only meaningful for the
10490// target that owns it. Determine the owning target (translating an auxiliary ID
10491// back to its canonical value) and only return the ID when x86 owns it;
10492// otherwise an overlapping ID could be misinterpreted as an unrelated x86
10493// builtin.
10495 unsigned BuiltinOp) {
10496 // Target-independent builtins have the same ID regardless of the target, so
10497 // they can be dispatched as-is. This is the common case and is intentionally
10498 // kept to a single comparison so callers can use this on hot paths (e.g. the
10499 // bytecode interpreter's builtin dispatch) without re-deriving the ID from
10500 // the call expression.
10501 if (BuiltinOp < Builtin::FirstTSBuiltin)
10502 return BuiltinOp;
10503
10504 // Determine the target that owns this builtin, translating an auxiliary ID
10505 // back to its canonical value.
10506 const TargetInfo *OwningTarget;
10507 if (Ctx.BuiltinInfo.isAuxBuiltinID(BuiltinOp)) {
10508 OwningTarget = Ctx.getAuxTargetInfo();
10509 BuiltinOp = Ctx.BuiltinInfo.getAuxBuiltinID(BuiltinOp);
10510 } else {
10511 OwningTarget = &Ctx.getTargetInfo();
10512 }
10513
10514 if (!OwningTarget)
10515 return 0;
10516
10517 // x86 and x86_64 share a single builtin set and are the only architectures
10518 // whose target-specific builtins the constant evaluators currently fold.
10519 switch (OwningTarget->getTriple().getArch()) {
10520 case llvm::Triple::x86:
10521 case llvm::Triple::x86_64:
10522 return BuiltinOp;
10523 default:
10524 return 0;
10525 }
10526}
10527
10529 const CallExpr *E) {
10531}
10532
10534 UnaryExprOrTypeTrait ExprKind) {
10535 E = E->IgnoreParens();
10536
10537 // The kinds of expressions that we have special-case logic here for
10538 // should be kept up to date with the special checks for those
10539 // expressions in Sema.
10540
10541 // alignof decl is always accepted, even if it doesn't make sense: we default
10542 // to 1 in those cases.
10543 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
10544 return Ctx.getDeclAlign(DRE->getDecl(),
10545 /*RefAsPointee*/ true);
10546
10547 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
10548 return Ctx.getDeclAlign(ME->getMemberDecl(),
10549 /*RefAsPointee*/ true);
10550
10551 return GetAlignOfType(Ctx, E->getType(), ExprKind);
10552}
10553
10554static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) {
10555 if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>())
10556 return Info.Ctx.getDeclAlign(VD);
10557 if (const auto *E = Value.Base.dyn_cast<const Expr *>())
10558 return GetAlignOfExpr(Info.Ctx, E, UETT_AlignOf);
10559 return GetAlignOfType(Info.Ctx, Value.Base.getTypeInfoType(), UETT_AlignOf);
10560}
10561
10562/// Evaluate the value of the alignment argument to __builtin_align_{up,down},
10563/// __builtin_is_aligned and __builtin_assume_aligned.
10564static bool getAlignmentArgument(const Expr *E, QualType ForType,
10565 EvalInfo &Info, APSInt &Alignment) {
10566 if (!EvaluateInteger(E, Alignment, Info))
10567 return false;
10568 if (Alignment < 0 || !Alignment.isPowerOf2()) {
10569 Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment;
10570 return false;
10571 }
10572 unsigned SrcWidth = Info.Ctx.getIntWidth(ForType);
10573 APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1));
10574 if (APSInt::compareValues(Alignment, MaxValue) > 0) {
10575 Info.FFDiag(E, diag::note_constexpr_alignment_too_big)
10576 << MaxValue << ForType << Alignment;
10577 return false;
10578 }
10579 // Ensure both alignment and source value have the same bit width so that we
10580 // don't assert when computing the resulting value.
10581 APSInt ExtAlignment =
10582 APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true);
10583 assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 &&
10584 "Alignment should not be changed by ext/trunc");
10585 Alignment = ExtAlignment;
10586 assert(Alignment.getBitWidth() == SrcWidth);
10587 return true;
10588}
10589
10590// To be clear: this happily visits unsupported builtins. Better name welcomed.
10591bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
10592 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
10593 return true;
10594
10595 if (!(InvalidBaseOK && E->getCalleeAllocSizeAttr()))
10596 return false;
10597
10598 Result.setInvalid(E);
10599 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
10600 Result.addUnsizedArray(Info, E, PointeeTy);
10601 return true;
10602}
10603
10604bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
10605 if (!IsConstantEvaluatedBuiltinCall(E))
10606 return visitNonBuiltinCallExpr(E);
10607 return VisitBuiltinCallExpr(E, ConvertBuiltinIDToX86BuiltinID(Info.Ctx, E));
10608}
10609
10610// Determine if T is a character type for which we guarantee that
10611// sizeof(T) == 1.
10613 return T->isCharType() || T->isChar8Type();
10614}
10615
10616bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
10617 unsigned BuiltinOp) {
10618 if (IsOpaqueConstantCall(E))
10619 return Success(E);
10620
10621 switch (BuiltinOp) {
10622 case Builtin::BIaddressof:
10623 case Builtin::BI__addressof:
10624 case Builtin::BI__builtin_addressof:
10625 return evaluateLValue(E->getArg(0), Result);
10626 case Builtin::BI__builtin_assume_aligned: {
10627 // We need to be very careful here because: if the pointer does not have the
10628 // asserted alignment, then the behavior is undefined, and undefined
10629 // behavior is non-constant.
10630 if (!evaluatePointer(E->getArg(0), Result))
10631 return false;
10632
10633 LValue OffsetResult(Result);
10634 APSInt Alignment;
10635 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
10636 Alignment))
10637 return false;
10638 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
10639
10640 if (E->getNumArgs() > 2) {
10641 APSInt Offset;
10642 if (!EvaluateInteger(E->getArg(2), Offset, Info))
10643 return false;
10644
10645 int64_t AdditionalOffset = -Offset.getZExtValue();
10646 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
10647 }
10648
10649 // If there is a base object, then it must have the correct alignment.
10650 if (OffsetResult.Base) {
10651 CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult);
10652
10653 if (BaseAlignment < Align) {
10654 Result.Designator.setInvalid();
10655 CCEDiag(E->getArg(0), diag::note_constexpr_baa_insufficient_alignment)
10656 << 0 << BaseAlignment.getQuantity() << Align.getQuantity();
10657 return false;
10658 }
10659 }
10660
10661 // The offset must also have the correct alignment.
10662 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
10663 Result.Designator.setInvalid();
10664
10665 (OffsetResult.Base
10666 ? CCEDiag(E->getArg(0),
10667 diag::note_constexpr_baa_insufficient_alignment)
10668 << 1
10669 : CCEDiag(E->getArg(0),
10670 diag::note_constexpr_baa_value_insufficient_alignment))
10671 << OffsetResult.Offset.getQuantity() << Align.getQuantity();
10672 return false;
10673 }
10674
10675 return true;
10676 }
10677 case Builtin::BI__builtin_align_up:
10678 case Builtin::BI__builtin_align_down: {
10679 if (!evaluatePointer(E->getArg(0), Result))
10680 return false;
10681 APSInt Alignment;
10682 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
10683 Alignment))
10684 return false;
10685 CharUnits BaseAlignment = getBaseAlignment(Info, Result);
10686 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset);
10687 // For align_up/align_down, we can return the same value if the alignment
10688 // is known to be greater or equal to the requested value.
10689 if (PtrAlign.getQuantity() >= Alignment)
10690 return true;
10691
10692 // The alignment could be greater than the minimum at run-time, so we cannot
10693 // infer much about the resulting pointer value. One case is possible:
10694 // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we
10695 // can infer the correct index if the requested alignment is smaller than
10696 // the base alignment so we can perform the computation on the offset.
10697 if (BaseAlignment.getQuantity() >= Alignment) {
10698 assert(Alignment.getBitWidth() <= 64 &&
10699 "Cannot handle > 64-bit address-space");
10700 uint64_t Alignment64 = Alignment.getZExtValue();
10701 CharUnits NewOffset = CharUnits::fromQuantity(
10702 BuiltinOp == Builtin::BI__builtin_align_down
10703 ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64)
10704 : llvm::alignTo(Result.Offset.getQuantity(), Alignment64));
10705 Result.adjustOffset(NewOffset - Result.Offset);
10706 // TODO: diagnose out-of-bounds values/only allow for arrays?
10707 return true;
10708 }
10709 // Otherwise, we cannot constant-evaluate the result.
10710 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust)
10711 << Alignment;
10712 return false;
10713 }
10714 case Builtin::BI__builtin_operator_new:
10715 return HandleOperatorNewCall(Info, E, Result);
10716 case Builtin::BI__builtin_launder:
10717 return evaluatePointer(E->getArg(0), Result);
10718 case Builtin::BIstrchr:
10719 case Builtin::BIwcschr:
10720 case Builtin::BImemchr:
10721 case Builtin::BIwmemchr:
10722 if (Info.getLangOpts().CPlusPlus11)
10723 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
10724 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
10725 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
10726 else
10727 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
10728 [[fallthrough]];
10729 case Builtin::BI__builtin_strchr:
10730 case Builtin::BI__builtin_wcschr:
10731 case Builtin::BI__builtin_memchr:
10732 case Builtin::BI__builtin_char_memchr:
10733 case Builtin::BI__builtin_wmemchr: {
10734 if (!Visit(E->getArg(0)))
10735 return false;
10736 APSInt Desired;
10737 if (!EvaluateInteger(E->getArg(1), Desired, Info))
10738 return false;
10739 uint64_t MaxLength = uint64_t(-1);
10740 if (BuiltinOp != Builtin::BIstrchr &&
10741 BuiltinOp != Builtin::BIwcschr &&
10742 BuiltinOp != Builtin::BI__builtin_strchr &&
10743 BuiltinOp != Builtin::BI__builtin_wcschr) {
10744 APSInt N;
10745 if (!EvaluateInteger(E->getArg(2), N, Info))
10746 return false;
10747 MaxLength = N.getZExtValue();
10748 }
10749 // We cannot find the value if there are no candidates to match against.
10750 if (MaxLength == 0u)
10751 return ZeroInitialization(E);
10752 if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
10753 Result.Designator.Invalid)
10754 return false;
10755 QualType CharTy = Result.Designator.getType(Info.Ctx);
10756 bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
10757 BuiltinOp == Builtin::BI__builtin_memchr;
10758 assert(IsRawByte ||
10759 Info.Ctx.hasSameUnqualifiedType(
10760 CharTy, E->getArg(0)->getType()->getPointeeType()));
10761 // Pointers to const void may point to objects of incomplete type.
10762 if (IsRawByte && CharTy->isIncompleteType()) {
10763 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
10764 return false;
10765 }
10766 // Give up on byte-oriented matching against multibyte elements.
10767 // FIXME: We can compare the bytes in the correct order.
10768 if (IsRawByte && !isOneByteCharacterType(CharTy)) {
10769 Info.FFDiag(E, diag::note_constexpr_memchr_unsupported)
10770 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp) << CharTy;
10771 return false;
10772 }
10773 // Figure out what value we're actually looking for (after converting to
10774 // the corresponding unsigned type if necessary).
10775 uint64_t DesiredVal;
10776 bool StopAtNull = false;
10777 switch (BuiltinOp) {
10778 case Builtin::BIstrchr:
10779 case Builtin::BI__builtin_strchr:
10780 // strchr compares directly to the passed integer, and therefore
10781 // always fails if given an int that is not a char.
10782 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
10783 E->getArg(1)->getType(),
10784 Desired),
10785 Desired))
10786 return ZeroInitialization(E);
10787 StopAtNull = true;
10788 [[fallthrough]];
10789 case Builtin::BImemchr:
10790 case Builtin::BI__builtin_memchr:
10791 case Builtin::BI__builtin_char_memchr:
10792 // memchr compares by converting both sides to unsigned char. That's also
10793 // correct for strchr if we get this far (to cope with plain char being
10794 // unsigned in the strchr case).
10795 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
10796 break;
10797
10798 case Builtin::BIwcschr:
10799 case Builtin::BI__builtin_wcschr:
10800 StopAtNull = true;
10801 [[fallthrough]];
10802 case Builtin::BIwmemchr:
10803 case Builtin::BI__builtin_wmemchr:
10804 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
10805 DesiredVal = Desired.getZExtValue();
10806 break;
10807 }
10808
10809 for (; MaxLength; --MaxLength) {
10810 APValue Char;
10811 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
10812 !Char.isInt())
10813 return false;
10814 if (Char.getInt().getZExtValue() == DesiredVal)
10815 return true;
10816 if (StopAtNull && !Char.getInt())
10817 break;
10818 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
10819 return false;
10820 }
10821 // Not found: return nullptr.
10822 return ZeroInitialization(E);
10823 }
10824
10825 case Builtin::BImemcpy:
10826 case Builtin::BImemmove:
10827 case Builtin::BIwmemcpy:
10828 case Builtin::BIwmemmove:
10829 if (Info.getLangOpts().CPlusPlus11)
10830 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
10831 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
10832 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
10833 else
10834 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
10835 [[fallthrough]];
10836 case Builtin::BI__builtin_memcpy:
10837 case Builtin::BI__builtin_memmove:
10838 case Builtin::BI__builtin_wmemcpy:
10839 case Builtin::BI__builtin_wmemmove: {
10840 bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
10841 BuiltinOp == Builtin::BIwmemmove ||
10842 BuiltinOp == Builtin::BI__builtin_wmemcpy ||
10843 BuiltinOp == Builtin::BI__builtin_wmemmove;
10844 bool Move = BuiltinOp == Builtin::BImemmove ||
10845 BuiltinOp == Builtin::BIwmemmove ||
10846 BuiltinOp == Builtin::BI__builtin_memmove ||
10847 BuiltinOp == Builtin::BI__builtin_wmemmove;
10848
10849 // The result of mem* is the first argument.
10850 if (!Visit(E->getArg(0)))
10851 return false;
10852 LValue Dest = Result;
10853
10854 LValue Src;
10855 if (!EvaluatePointer(E->getArg(1), Src, Info))
10856 return false;
10857
10858 APSInt N;
10859 if (!EvaluateInteger(E->getArg(2), N, Info))
10860 return false;
10861 assert(!N.isSigned() && "memcpy and friends take an unsigned size");
10862
10863 // If the size is zero, we treat this as always being a valid no-op.
10864 // (Even if one of the src and dest pointers is null.)
10865 if (!N)
10866 return true;
10867
10868 // Otherwise, if either of the operands is null, we can't proceed. Don't
10869 // try to determine the type of the copied objects, because there aren't
10870 // any.
10871 if (!Src.Base || !Dest.Base) {
10872 APValue Val;
10873 (!Src.Base ? Src : Dest).moveInto(Val);
10874 Info.FFDiag(E, diag::note_constexpr_memcpy_null)
10875 << Move << WChar << !!Src.Base
10876 << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
10877 return false;
10878 }
10879 if (Src.Designator.Invalid || Dest.Designator.Invalid)
10880 return false;
10881
10882 // We require that Src and Dest are both pointers to arrays of
10883 // trivially-copyable type. (For the wide version, the designator will be
10884 // invalid if the designated object is not a wchar_t.)
10885 QualType T = Dest.Designator.getType(Info.Ctx);
10886 QualType SrcT = Src.Designator.getType(Info.Ctx);
10887 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
10888 // FIXME: Consider using our bit_cast implementation to support this.
10889 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
10890 return false;
10891 }
10892 if (T->isIncompleteType()) {
10893 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
10894 return false;
10895 }
10896 if (!T.isTriviallyCopyableType(Info.Ctx)) {
10897 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
10898 return false;
10899 }
10900
10901 // Figure out how many T's we're copying.
10902 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
10903 if (TSize == 0)
10904 return false;
10905 if (!WChar) {
10906 uint64_t Remainder;
10907 llvm::APInt OrigN = N;
10908 llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
10909 if (Remainder) {
10910 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
10911 << Move << WChar << 0 << T << toString(OrigN, 10, /*Signed*/false)
10912 << (unsigned)TSize;
10913 return false;
10914 }
10915 }
10916
10917 // Check that the copying will remain within the arrays, just so that we
10918 // can give a more meaningful diagnostic. This implicitly also checks that
10919 // N fits into 64 bits.
10920 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
10921 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
10922 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
10923 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
10924 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
10925 << toString(N, 10, /*Signed*/false);
10926 return false;
10927 }
10928 uint64_t NElems = N.getZExtValue();
10929 uint64_t NBytes = NElems * TSize;
10930
10931 // Check for overlap.
10932 int Direction = 1;
10933 if (HasSameBase(Src, Dest)) {
10934 uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
10935 uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
10936 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
10937 // Dest is inside the source region.
10938 if (!Move) {
10939 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
10940 return false;
10941 }
10942 // For memmove and friends, copy backwards.
10943 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
10944 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
10945 return false;
10946 Direction = -1;
10947 } else if (!Move && SrcOffset >= DestOffset &&
10948 SrcOffset - DestOffset < NBytes) {
10949 // Src is inside the destination region for memcpy: invalid.
10950 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
10951 return false;
10952 }
10953 }
10954
10955 while (true) {
10956 APValue Val;
10957 // FIXME: Set WantObjectRepresentation to true if we're copying a
10958 // char-like type?
10959 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
10960 !handleAssignment(Info, E, Dest, T, Val))
10961 return false;
10962 // Do not iterate past the last element; if we're copying backwards, that
10963 // might take us off the start of the array.
10964 if (--NElems == 0)
10965 return true;
10966 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
10967 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
10968 return false;
10969 }
10970 }
10971
10972 default:
10973 return false;
10974 }
10975}
10976
10977static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
10978 APValue &Result, const InitListExpr *ILE,
10979 QualType AllocType);
10980static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
10981 APValue &Result,
10982 const CXXConstructExpr *CCE,
10983 QualType AllocType);
10984
10985bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) {
10986 if (!Info.getLangOpts().CPlusPlus20)
10987 Info.CCEDiag(E, diag::note_constexpr_new);
10988
10989 // We cannot speculatively evaluate a delete expression.
10990 if (Info.SpeculativeEvaluationDepth)
10991 return false;
10992
10993 FunctionDecl *OperatorNew = E->getOperatorNew();
10994 QualType AllocType = E->getAllocatedType();
10995 QualType TargetType = AllocType;
10996
10997 bool IsNothrow = false;
10998 bool IsPlacement = false;
10999
11000 if (E->getNumPlacementArgs() == 1 &&
11001 E->getPlacementArg(0)->getType()->isNothrowT()) {
11002 // The only new-placement list we support is of the form (std::nothrow).
11003 //
11004 // FIXME: There is no restriction on this, but it's not clear that any
11005 // other form makes any sense. We get here for cases such as:
11006 //
11007 // new (std::align_val_t{N}) X(int)
11008 //
11009 // (which should presumably be valid only if N is a multiple of
11010 // alignof(int), and in any case can't be deallocated unless N is
11011 // alignof(X) and X has new-extended alignment).
11012 LValue Nothrow;
11013 if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info))
11014 return false;
11015 IsNothrow = true;
11016 } else if (OperatorNew->isReservedGlobalPlacementOperator()) {
11017 if (Info.CurrentCall->isStdFunction() || Info.getLangOpts().CPlusPlus26 ||
11018 (Info.CurrentCall->CanEvalMSConstexpr &&
11019 OperatorNew->hasAttr<MSConstexprAttr>())) {
11020 if (!EvaluatePointer(E->getPlacementArg(0), Result, Info))
11021 return false;
11022 if (Result.Designator.Invalid)
11023 return false;
11024 TargetType = E->getPlacementArg(0)->getType();
11025 IsPlacement = true;
11026 } else {
11027 Info.FFDiag(E, diag::note_constexpr_new_placement)
11028 << /*C++26 feature*/ 1 << E->getSourceRange();
11029 return false;
11030 }
11031 } else if (E->getNumPlacementArgs()) {
11032 Info.FFDiag(E, diag::note_constexpr_new_placement)
11033 << /*Unsupported*/ 0 << E->getSourceRange();
11034 return false;
11035 } else if (!OperatorNew
11036 ->isUsableAsGlobalAllocationFunctionInConstantEvaluation()) {
11037 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
11038 << isa<CXXMethodDecl>(OperatorNew) << OperatorNew;
11039 return false;
11040 }
11041
11042 const Expr *Init = E->getInitializer();
11043 const InitListExpr *ResizedArrayILE = nullptr;
11044 const CXXConstructExpr *ResizedArrayCCE = nullptr;
11045 bool ValueInit = false;
11046
11047 if (std::optional<const Expr *> ArraySize = E->getArraySize()) {
11048 const Expr *Stripped = *ArraySize;
11049 for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
11050 Stripped = ICE->getSubExpr())
11051 if (ICE->getCastKind() != CK_NoOp &&
11052 ICE->getCastKind() != CK_IntegralCast)
11053 break;
11054
11055 llvm::APSInt ArrayBound;
11056 if (!EvaluateInteger(Stripped, ArrayBound, Info))
11057 return false;
11058
11059 // C++ [expr.new]p9:
11060 // The expression is erroneous if:
11061 // -- [...] its value before converting to size_t [or] applying the
11062 // second standard conversion sequence is less than zero
11063 if (ArrayBound.isSigned() && ArrayBound.isNegative()) {
11064 if (IsNothrow)
11065 return ZeroInitialization(E);
11066
11067 Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative)
11068 << ArrayBound << (*ArraySize)->getSourceRange();
11069 return false;
11070 }
11071
11072 // -- its value is such that the size of the allocated object would
11073 // exceed the implementation-defined limit
11074 if (!Info.CheckArraySize(ArraySize.value()->getExprLoc(),
11076 Info.Ctx, AllocType, ArrayBound),
11077 ArrayBound.getZExtValue(), /*Diag=*/!IsNothrow)) {
11078 if (IsNothrow)
11079 return ZeroInitialization(E);
11080 return false;
11081 }
11082
11083 // -- the new-initializer is a braced-init-list and the number of
11084 // array elements for which initializers are provided [...]
11085 // exceeds the number of elements to initialize
11086 if (!Init) {
11087 // No initialization is performed.
11088 } else if (isa<CXXScalarValueInitExpr>(Init) ||
11090 ValueInit = true;
11091 } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) {
11092 ResizedArrayCCE = CCE;
11093 } else {
11094 auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType());
11095 assert(CAT && "unexpected type for array initializer");
11096
11097 unsigned Bits =
11098 std::max(CAT->getSizeBitWidth(), ArrayBound.getBitWidth());
11099 llvm::APInt InitBound = CAT->getSize().zext(Bits);
11100 llvm::APInt AllocBound = ArrayBound.zext(Bits);
11101 if (InitBound.ugt(AllocBound)) {
11102 if (IsNothrow)
11103 return ZeroInitialization(E);
11104
11105 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small)
11106 << toString(AllocBound, 10, /*Signed=*/false)
11107 << toString(InitBound, 10, /*Signed=*/false)
11108 << (*ArraySize)->getSourceRange();
11109 return false;
11110 }
11111
11112 // If the sizes differ, we must have an initializer list, and we need
11113 // special handling for this case when we initialize.
11114 if (InitBound != AllocBound)
11115 ResizedArrayILE = cast<InitListExpr>(Init);
11116 }
11117
11118 AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr,
11119 ArraySizeModifier::Normal, 0);
11120 } else if (E->isArray()) {
11121 // We have an array new-expression whose array size could not be
11122 // determined, e.g. 'new int[]()', where the bound is neither given nor
11123 // deducible from the initializer. This is ill-formed and already
11124 // diagnosed, so bail out rather than mis-evaluating a scalar allocation
11125 // as an array (which would later crash the evaluator).
11126 return false;
11127 } else {
11128 assert(!AllocType->isArrayType() &&
11129 "array allocation with non-array new");
11130 }
11131
11132 APValue *Val;
11133 if (IsPlacement) {
11135 struct FindObjectHandler {
11136 EvalInfo &Info;
11137 const Expr *E;
11138 QualType AllocType;
11139 const AccessKinds AccessKind;
11140 APValue *Value;
11141
11142 typedef bool result_type;
11143 bool failed() { return false; }
11144 bool checkConst(QualType QT) {
11145 if (QT.isConstQualified()) {
11146 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
11147 return false;
11148 }
11149 return true;
11150 }
11151 bool found(APValue &Subobj, QualType SubobjType,
11152 APValue::LValueBase Base) {
11153 if (!checkConst(SubobjType))
11154 return false;
11155 // FIXME: Reject the cases where [basic.life]p8 would not permit the
11156 // old name of the object to be used to name the new object.
11157 if (!Info.Ctx.hasSimilarType(SubobjType, AllocType)) {
11158 Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type)
11159 << SubobjType << AllocType;
11160 return false;
11161 }
11162 Value = &Subobj;
11163 return true;
11164 }
11165 bool found(APSInt &Value, QualType SubobjType) {
11166 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
11167 return false;
11168 }
11169 bool found(APFloat &Value, QualType SubobjType) {
11170 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
11171 return false;
11172 }
11173 } Handler = {Info, E, AllocType, AK, nullptr};
11174
11175 if (AllocType->isArrayType() &&
11176 Result.Designator.MostDerivedIsArrayElement &&
11177 Result.Designator.Entries.back().getAsArrayIndex() == 0) {
11178 // The destination of placement new is pointing to the first element
11179 // of an array. There's a special case in [expr.const]: "[...] if T is an
11180 // array type, to the first element of such an object [...]". Handle
11181 // that case here by dropping the last entry in the designator list.
11182 QualType AllocElementType =
11183 Info.Ctx.getAsArrayType(AllocType)->getElementType();
11184 if (Info.Ctx.hasSimilarType(AllocElementType,
11185 Result.Designator.MostDerivedType)) {
11186 Result.Designator.truncate(Info.Ctx, Result.Base,
11187 Result.Designator.MostDerivedPathLength - 1);
11188 }
11189 }
11190
11191 CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType);
11192 if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler))
11193 return false;
11194
11195 Val = Handler.Value;
11196
11197 // [basic.life]p1:
11198 // The lifetime of an object o of type T ends when [...] the storage
11199 // which the object occupies is [...] reused by an object that is not
11200 // nested within o (6.6.2).
11201 *Val = APValue();
11202 } else {
11203 // Perform the allocation and obtain a pointer to the resulting object.
11204 Val = Info.createHeapAlloc(E, AllocType, Result);
11205 if (!Val)
11206 return false;
11207 }
11208
11209 if (ValueInit) {
11210 ImplicitValueInitExpr VIE(AllocType);
11211 if (!EvaluateInPlace(*Val, Info, Result, &VIE))
11212 return false;
11213 } else if (ResizedArrayILE) {
11214 if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE,
11215 AllocType))
11216 return false;
11217 } else if (ResizedArrayCCE) {
11218 if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE,
11219 AllocType))
11220 return false;
11221 } else if (Init) {
11222 if (!EvaluateInPlace(*Val, Info, Result, Init))
11223 return false;
11224 } else if (!handleDefaultInitValue(AllocType, *Val)) {
11225 return false;
11226 }
11227
11228 // Array new returns a pointer to the first element, not a pointer to the
11229 // array.
11230 if (auto *AT = AllocType->getAsArrayTypeUnsafe())
11231 Result.addArray(Info, E, cast<ConstantArrayType>(AT));
11232
11233 return true;
11234}
11235//===----------------------------------------------------------------------===//
11236// Member Pointer Evaluation
11237//===----------------------------------------------------------------------===//
11238
11239namespace {
11240class MemberPointerExprEvaluator
11241 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
11242 MemberPtr &Result;
11243
11244 bool Success(const ValueDecl *D) {
11245 Result = MemberPtr(D);
11246 return true;
11247 }
11248public:
11249
11250 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
11251 : ExprEvaluatorBaseTy(Info), Result(Result) {}
11252
11253 bool Success(const APValue &V, const Expr *E) {
11254 Result.setFrom(V);
11255 return true;
11256 }
11257 bool ZeroInitialization(const Expr *E) {
11258 return Success((const ValueDecl*)nullptr);
11259 }
11260
11261 bool VisitCastExpr(const CastExpr *E);
11262 bool VisitUnaryAddrOf(const UnaryOperator *E);
11263};
11264} // end anonymous namespace
11265
11266static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
11267 EvalInfo &Info) {
11268 assert(!E->isValueDependent());
11269 assert(E->isPRValue() && E->getType()->isMemberPointerType());
11270 return MemberPointerExprEvaluator(Info, Result).Visit(E);
11271}
11272
11273bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
11274 switch (E->getCastKind()) {
11275 default:
11276 return ExprEvaluatorBaseTy::VisitCastExpr(E);
11277
11278 case CK_NullToMemberPointer:
11279 VisitIgnoredValue(E->getSubExpr());
11280 return ZeroInitialization(E);
11281
11282 case CK_BaseToDerivedMemberPointer: {
11283 if (!Visit(E->getSubExpr()))
11284 return false;
11285 if (E->path_empty())
11286 return true;
11287 // Base-to-derived member pointer casts store the path in derived-to-base
11288 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
11289 // the wrong end of the derived->base arc, so stagger the path by one class.
11290 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
11291 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
11292 PathI != PathE; ++PathI) {
11293 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
11294 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
11295 if (!Result.castToDerived(Derived))
11296 return Error(E);
11297 }
11298 if (!Result.castToDerived(E->getType()
11299 ->castAs<MemberPointerType>()
11300 ->getMostRecentCXXRecordDecl()))
11301 return Error(E);
11302 return true;
11303 }
11304
11305 case CK_DerivedToBaseMemberPointer:
11306 if (!Visit(E->getSubExpr()))
11307 return false;
11308 for (CastExpr::path_const_iterator PathI = E->path_begin(),
11309 PathE = E->path_end(); PathI != PathE; ++PathI) {
11310 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
11311 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
11312 if (!Result.castToBase(Base))
11313 return Error(E);
11314 }
11315 return true;
11316 }
11317}
11318
11319bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
11320 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
11321 // member can be formed.
11322 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
11323}
11324
11325//===----------------------------------------------------------------------===//
11326// Record Evaluation
11327//===----------------------------------------------------------------------===//
11328
11329namespace {
11330 class RecordExprEvaluator
11331 : public ExprEvaluatorBase<RecordExprEvaluator> {
11332 const LValue &This;
11333 APValue &Result;
11334 public:
11335
11336 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
11337 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
11338
11339 bool Success(const APValue &V, const Expr *E) {
11340 Result = V;
11341 return true;
11342 }
11343 bool ZeroInitialization(const Expr *E) {
11344 return ZeroInitialization(E, E->getType());
11345 }
11346 bool ZeroInitialization(const Expr *E, QualType T);
11347
11348 bool VisitCallExpr(const CallExpr *E) {
11349 return handleCallExpr(E, Result, &This);
11350 }
11351 bool VisitCastExpr(const CastExpr *E);
11352 bool VisitInitListExpr(const InitListExpr *E);
11353 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
11354 return VisitCXXConstructExpr(E, E->getType());
11355 }
11356 bool VisitLambdaExpr(const LambdaExpr *E);
11357 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
11358 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
11359 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
11360 bool VisitBinCmp(const BinaryOperator *E);
11361 bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E);
11362 bool VisitCXXParenListOrInitListExpr(const Expr *ExprToVisit,
11363 ArrayRef<Expr *> Args);
11364 bool VisitDesignatedInitUpdateExpr(const DesignatedInitUpdateExpr *E);
11365 };
11366}
11367
11368/// Perform zero-initialization on an object of non-union class type.
11369/// C++11 [dcl.init]p5:
11370/// To zero-initialize an object or reference of type T means:
11371/// [...]
11372/// -- if T is a (possibly cv-qualified) non-union class type,
11373/// each non-static data member and each base-class subobject is
11374/// zero-initialized
11375static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
11376 const RecordDecl *RD,
11377 const LValue &This, APValue &Result,
11378 bool IsCompleteClass = true) {
11379 assert(!RD->isUnion() && "Expected non-union class type");
11380 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
11381
11382 if (CD) {
11383 unsigned NonVirtualBases = countNonVirtualBases(CD);
11384 Result =
11385 APValue(APValue::UninitStruct(), NonVirtualBases, RD->getNumFields(),
11386 IsCompleteClass ? CD->getNumVBases() : 0);
11387 } else {
11389 }
11390
11391 if (RD->isInvalidDecl()) return false;
11392 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
11393
11394 if (CD) {
11395 unsigned Index = 0;
11396
11397 for (const auto &B : CD->bases()) {
11398 if (B.isVirtual())
11399 continue;
11401 LValue Subobject = This;
11402 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
11403 return false;
11404 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
11405 Result.getStructBase(Index),
11406 /*IsCompleteClass=*/false))
11407 return false;
11408 ++Index;
11409 }
11410 }
11411
11412 for (const auto *I : RD->fields()) {
11413 // -- if T is a reference type, no initialization is performed.
11414 if (I->isUnnamedBitField() || I->getType()->isReferenceType())
11415 continue;
11416
11417 LValue Subobject = This;
11418 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
11419 return false;
11420
11421 ImplicitValueInitExpr VIE(I->getType());
11422 if (!EvaluateInPlace(
11423 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
11424 return false;
11425 }
11426
11427 if (CD && This.pointsToCompleteClass(CD)) {
11428 unsigned Index = 0;
11429 for (const auto &B : CD->vbases()) {
11431 LValue Subobject = This;
11432 if (!HandleLValueDirectVirtualBase(Info, E, Subobject, CD, Base, &Layout))
11433 return false;
11434 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
11435 Result.getStructVirtualBase(Index),
11436 /*IsCompleteClass=*/false))
11437 return false;
11438 ++Index;
11439 }
11440 }
11441
11442 return true;
11443}
11444
11445bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
11446 const auto *RD = T->castAsRecordDecl();
11447 if (RD->isInvalidDecl()) return false;
11448 if (RD->isUnion()) {
11449 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
11450 // object's first non-static named data member is zero-initialized
11452 while (I != RD->field_end() && (*I)->isUnnamedBitField())
11453 ++I;
11454 if (I == RD->field_end()) {
11455 Result = APValue((const FieldDecl*)nullptr);
11456 return true;
11457 }
11458
11459 LValue Subobject = This;
11460 if (!HandleLValueMember(Info, E, Subobject, *I))
11461 return false;
11462 Result = APValue(*I);
11463 ImplicitValueInitExpr VIE(I->getType());
11464 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
11465 }
11466
11467 if (!Info.getLangOpts().CPlusPlus26) {
11468 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
11469 CXXRD && CXXRD->getNumVBases()) {
11470 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
11471 return false;
11472 }
11473 }
11474
11475 return HandleClassZeroInitialization(Info, E, RD, This, Result);
11476}
11477
11478bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
11479 switch (E->getCastKind()) {
11480 default:
11481 return ExprEvaluatorBaseTy::VisitCastExpr(E);
11482
11483 case CK_ConstructorConversion:
11484 return Visit(E->getSubExpr());
11485
11486 case CK_DerivedToBase:
11487 case CK_UncheckedDerivedToBase: {
11488 APValue DerivedObject;
11489 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
11490 return false;
11491 if (!DerivedObject.isStruct())
11492 return Error(E->getSubExpr());
11493
11494 // Derived-to-base rvalue conversion: just slice off the derived part.
11495 APValue *Value = &DerivedObject;
11496 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
11497 for (CastExpr::path_const_iterator PathI = E->path_begin(),
11498 PathE = E->path_end(); PathI != PathE; ++PathI) {
11499 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
11500 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
11501 Value = &Value->getStructBase(getBaseIndex(RD, Base));
11502 RD = Base;
11503 }
11504 Result = *Value;
11505 return true;
11506 }
11507 case CK_HLSLAggregateSplatCast: {
11508 APValue Val;
11509 QualType ValTy;
11510
11511 if (!hlslAggSplatHelper(Info, E->getSubExpr(), Val, ValTy))
11512 return false;
11513
11514 unsigned NEls = elementwiseSize(Info, E->getType());
11515 // splat our Val
11516 SmallVector<APValue> SplatEls(NEls, Val);
11517 SmallVector<QualType> SplatType(NEls, ValTy);
11518
11519 // cast the elements and construct our struct result
11520 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
11521 if (!constructAggregate(Info, FPO, E, Result, E->getType(), SplatEls,
11522 SplatType))
11523 return false;
11524
11525 return true;
11526 }
11527 case CK_HLSLElementwiseCast: {
11528 SmallVector<APValue> SrcEls;
11529 SmallVector<QualType> SrcTypes;
11530
11531 if (!hlslElementwiseCastHelper(Info, E->getSubExpr(), E->getType(), SrcEls,
11532 SrcTypes))
11533 return false;
11534
11535 // cast the elements and construct our struct result
11536 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
11537 if (!constructAggregate(Info, FPO, E, Result, E->getType(), SrcEls,
11538 SrcTypes))
11539 return false;
11540
11541 return true;
11542 }
11543 case CK_ToUnion: {
11544 const FieldDecl *Field = E->getTargetUnionField();
11545 LValue Subobject = This;
11546 if (!HandleLValueMember(Info, E, Subobject, Field))
11547 return false;
11548 Result = APValue(Field);
11549 if (!EvaluateInPlace(Result.getUnionValue(), Info, Subobject,
11550 E->getSubExpr()))
11551 return false;
11552 if (Field->isBitField()) {
11553 if (!truncateBitfieldValue(Info, E->getSubExpr(), Result.getUnionValue(),
11554 Field))
11555 return false;
11556 }
11557 return true;
11558 }
11559 }
11560}
11561
11562bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
11563 if (E->isTransparent())
11564 return Visit(E->getInit(0));
11565 return VisitCXXParenListOrInitListExpr(E, E->inits());
11566}
11567
11568bool RecordExprEvaluator::VisitCXXParenListOrInitListExpr(
11569 const Expr *ExprToVisit, ArrayRef<Expr *> Args) {
11570 const auto *RD = ExprToVisit->getType()->castAsRecordDecl();
11571 if (RD->isInvalidDecl()) return false;
11572 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
11573 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
11574
11575 EvalInfo::EvaluatingConstructorRAII EvalObj(
11576 Info,
11577 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
11578 CXXRD && CXXRD->getNumBases());
11579
11580 if (RD->isUnion()) {
11581 const FieldDecl *Field;
11582 if (auto *ILE = dyn_cast<InitListExpr>(ExprToVisit)) {
11583 Field = ILE->getInitializedFieldInUnion();
11584 } else if (auto *PLIE = dyn_cast<CXXParenListInitExpr>(ExprToVisit)) {
11585 Field = PLIE->getInitializedFieldInUnion();
11586 } else {
11587 llvm_unreachable(
11588 "Expression is neither an init list nor a C++ paren list");
11589 }
11590
11591 Result = APValue(Field);
11592 if (!Field)
11593 return true;
11594
11595 // If the initializer list for a union does not contain any elements, the
11596 // first element of the union is value-initialized.
11597 // FIXME: The element should be initialized from an initializer list.
11598 // Is this difference ever observable for initializer lists which
11599 // we don't build?
11600 ImplicitValueInitExpr VIE(Field->getType());
11601 const Expr *InitExpr = Args.empty() ? &VIE : Args[0];
11602
11603 LValue Subobject = This;
11604 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
11605 return false;
11606
11607 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
11608 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
11609 isa<CXXDefaultInitExpr>(InitExpr));
11610
11611 if (EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr)) {
11612 if (Field->isBitField())
11613 return truncateBitfieldValue(Info, InitExpr, Result.getUnionValue(),
11614 Field);
11615 return true;
11616 }
11617
11618 return false;
11619 }
11620
11621 if (!Result.hasValue())
11622 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
11623 RD->getNumFields());
11624 unsigned ElementNo = 0;
11625 bool Success = true;
11626
11627 // Initialize base classes.
11628 if (CXXRD && CXXRD->getNumBases()) {
11629 for (const auto &Base : CXXRD->bases()) {
11630 assert(ElementNo < Args.size() && "missing init for base class");
11631 const Expr *Init = Args[ElementNo];
11632
11633 LValue Subobject = This;
11634 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
11635 return false;
11636
11637 APValue &FieldVal = Result.getStructBase(ElementNo);
11638 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
11639 if (!Info.noteFailure())
11640 return false;
11641 Success = false;
11642 }
11643 ++ElementNo;
11644 }
11645
11646 EvalObj.finishedConstructingBases();
11647 }
11648
11649 // Initialize members.
11650 for (const auto *Field : RD->fields()) {
11651 // Anonymous bit-fields are not considered members of the class for
11652 // purposes of aggregate initialization.
11653 if (Field->isUnnamedBitField())
11654 continue;
11655
11656 LValue Subobject = This;
11657
11658 bool HaveInit = ElementNo < Args.size();
11659
11660 // FIXME: Diagnostics here should point to the end of the initializer
11661 // list, not the start.
11662 if (!HandleLValueMember(Info, HaveInit ? Args[ElementNo] : ExprToVisit,
11663 Subobject, Field, &Layout))
11664 return false;
11665
11666 // Perform an implicit value-initialization for members beyond the end of
11667 // the initializer list.
11668 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
11669 const Expr *Init = HaveInit ? Args[ElementNo++] : &VIE;
11670
11671 // If this is a child of a DesignatedInitUpdateExpr, skip elements which
11672 // aren't supposed to be modified.
11673 if (isa<NoInitExpr>(Init))
11674 continue;
11675
11676 if (Field->getType()->isIncompleteArrayType()) {
11677 if (auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType())) {
11678 if (!CAT->isZeroSize()) {
11679 // Bail out for now. This might sort of "work", but the rest of the
11680 // code isn't really prepared to handle it.
11681 Info.FFDiag(Init, diag::note_constexpr_unsupported_flexible_array);
11682 return false;
11683 }
11684 }
11685 }
11686
11687 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
11688 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
11690
11691 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
11692 if (Field->getType()->isReferenceType()) {
11693 LValue Result;
11695 FieldVal)) {
11696 if (!Info.noteFailure())
11697 return false;
11698 Success = false;
11699 }
11700 } else if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
11701 (Field->isBitField() &&
11702 !truncateBitfieldValue(Info, Init, FieldVal, Field))) {
11703 if (!Info.noteFailure())
11704 return false;
11705 Success = false;
11706 }
11707 }
11708
11709 EvalObj.finishedConstructingFields();
11710
11711 return Success;
11712}
11713
11714bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
11715 QualType T) {
11716 // Note that E's type is not necessarily the type of our class here; we might
11717 // be initializing an array element instead.
11718 const CXXConstructorDecl *FD = E->getConstructor();
11719 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
11720
11721 bool ZeroInit = E->requiresZeroInitialization();
11722 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
11723 if (ZeroInit)
11724 return ZeroInitialization(E, T);
11725
11727 }
11728
11729 const FunctionDecl *Definition = nullptr;
11730 auto Body = FD->getBody(Definition);
11731
11732 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
11733 return false;
11734
11735 // Avoid materializing a temporary for an elidable copy/move constructor.
11736 if (E->isElidable() && !ZeroInit) {
11737 // FIXME: This only handles the simplest case, where the source object
11738 // is passed directly as the first argument to the constructor.
11739 // This should also handle stepping though implicit casts and
11740 // and conversion sequences which involve two steps, with a
11741 // conversion operator followed by a converting constructor.
11742 const Expr *SrcObj = E->getArg(0);
11743 assert(SrcObj->isTemporaryObject(Info.Ctx, FD->getParent()));
11744 assert(Info.Ctx.hasSameUnqualifiedType(E->getType(), SrcObj->getType()));
11745 if (const MaterializeTemporaryExpr *ME =
11746 dyn_cast<MaterializeTemporaryExpr>(SrcObj))
11747 return Visit(ME->getSubExpr());
11748 }
11749
11750 if (ZeroInit && !ZeroInitialization(E, T))
11751 return false;
11752
11753 auto Args = ArrayRef(E->getArgs(), E->getNumArgs());
11754 return HandleConstructorCall(E, This, Args,
11756 Result);
11757}
11758
11759bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
11760 const CXXInheritedCtorInitExpr *E) {
11761 if (!Info.CurrentCall) {
11762 assert(Info.checkingPotentialConstantExpression());
11763 return false;
11764 }
11765
11766 const CXXConstructorDecl *FD = E->getConstructor();
11767 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
11768 return false;
11769
11770 const FunctionDecl *Definition = nullptr;
11771 auto Body = FD->getBody(Definition);
11772
11773 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
11774 return false;
11775
11776 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
11778 Result);
11779}
11780
11781bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
11782 const CXXStdInitializerListExpr *E) {
11783 const ConstantArrayType *ArrayType =
11784 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
11785
11786 LValue Array;
11787 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
11788 return false;
11789
11790 assert(ArrayType && "unexpected type for array initializer");
11791
11792 // Get a pointer to the first element of the array.
11793 Array.addArray(Info, E, ArrayType);
11794
11795 // FIXME: What if the initializer_list type has base classes, etc?
11796 Result = APValue(APValue::UninitStruct(), 0, 2);
11797 Array.moveInto(Result.getStructField(0));
11798
11799 auto *Record = E->getType()->castAsRecordDecl();
11800 RecordDecl::field_iterator Field = Record->field_begin();
11801 assert(Field != Record->field_end() &&
11802 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
11803 ArrayType->getElementType()) &&
11804 "Expected std::initializer_list first field to be const E *");
11805 ++Field;
11806 assert(Field != Record->field_end() &&
11807 "Expected std::initializer_list to have two fields");
11808
11809 if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType())) {
11810 // Length.
11811 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
11812 } else {
11813 // End pointer.
11814 assert(Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
11815 ArrayType->getElementType()) &&
11816 "Expected std::initializer_list second field to be const E *");
11817 if (!HandleLValueArrayAdjustment(Info, E, Array,
11818 ArrayType->getElementType(),
11819 ArrayType->getZExtSize()))
11820 return false;
11821 Array.moveInto(Result.getStructField(1));
11822 }
11823
11824 assert(++Field == Record->field_end() &&
11825 "Expected std::initializer_list to only have two fields");
11826
11827 return true;
11828}
11829
11830bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
11831 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
11832 if (ClosureClass->isInvalidDecl())
11833 return false;
11834
11835 const size_t NumFields = ClosureClass->getNumFields();
11836
11837 assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
11838 E->capture_init_end()) &&
11839 "The number of lambda capture initializers should equal the number of "
11840 "fields within the closure type");
11841
11842 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
11843 // Iterate through all the lambda's closure object's fields and initialize
11844 // them.
11845 auto *CaptureInitIt = E->capture_init_begin();
11846 bool Success = true;
11847 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(ClosureClass);
11848 for (const auto *Field : ClosureClass->fields()) {
11849 assert(CaptureInitIt != E->capture_init_end());
11850 // Get the initializer for this field
11851 Expr *const CurFieldInit = *CaptureInitIt++;
11852
11853 // If there is no initializer, either this is a VLA or an error has
11854 // occurred.
11855 if (!CurFieldInit || CurFieldInit->containsErrors())
11856 return Error(E);
11857
11858 LValue Subobject = This;
11859
11860 if (!HandleLValueMember(Info, E, Subobject, Field, &Layout))
11861 return false;
11862
11863 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
11864 if (!EvaluateInPlace(FieldVal, Info, Subobject, CurFieldInit)) {
11865 if (!Info.keepEvaluatingAfterFailure())
11866 return false;
11867 Success = false;
11868 }
11869 }
11870 return Success;
11871}
11872
11873bool RecordExprEvaluator::VisitDesignatedInitUpdateExpr(
11874 const DesignatedInitUpdateExpr *E) {
11875 if (!Visit(E->getBase()))
11876 return false;
11877 return Visit(E->getUpdater());
11878}
11879
11880static bool EvaluateRecord(const Expr *E, const LValue &This,
11881 APValue &Result, EvalInfo &Info) {
11882 assert(!E->isValueDependent());
11883 assert(E->isPRValue() && E->getType()->isRecordType() &&
11884 "can't evaluate expression as a record rvalue");
11885 return RecordExprEvaluator(Info, This, Result).Visit(E);
11886}
11887
11888//===----------------------------------------------------------------------===//
11889// Temporary Evaluation
11890//
11891// Temporaries are represented in the AST as rvalues, but generally behave like
11892// lvalues. The full-object of which the temporary is a subobject is implicitly
11893// materialized so that a reference can bind to it.
11894//===----------------------------------------------------------------------===//
11895namespace {
11896class TemporaryExprEvaluator
11897 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
11898public:
11899 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
11900 LValueExprEvaluatorBaseTy(Info, Result, false) {}
11901
11902 /// Visit an expression which constructs the value of this temporary.
11903 bool VisitConstructExpr(const Expr *E) {
11904 APValue &Value = Info.CurrentCall->createTemporary(
11905 E, E->getType(), ScopeKind::FullExpression, Result);
11906 return EvaluateInPlace(Value, Info, Result, E);
11907 }
11908
11909 bool VisitCastExpr(const CastExpr *E) {
11910 switch (E->getCastKind()) {
11911 default:
11912 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
11913
11914 case CK_ConstructorConversion:
11915 return VisitConstructExpr(E->getSubExpr());
11916 }
11917 }
11918 bool VisitInitListExpr(const InitListExpr *E) {
11919 return VisitConstructExpr(E);
11920 }
11921 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
11922 return VisitConstructExpr(E);
11923 }
11924 bool VisitCallExpr(const CallExpr *E) {
11925 return VisitConstructExpr(E);
11926 }
11927 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
11928 return VisitConstructExpr(E);
11929 }
11930 bool VisitLambdaExpr(const LambdaExpr *E) {
11931 return VisitConstructExpr(E);
11932 }
11933};
11934} // end anonymous namespace
11935
11936/// Evaluate an expression of record type as a temporary.
11937static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
11938 assert(!E->isValueDependent());
11939 assert(E->isPRValue() && E->getType()->isRecordType());
11940 return TemporaryExprEvaluator(Info, Result).Visit(E);
11941}
11942
11943//===----------------------------------------------------------------------===//
11944// Vector Evaluation
11945//===----------------------------------------------------------------------===//
11946
11947namespace {
11948 class VectorExprEvaluator
11949 : public ExprEvaluatorBase<VectorExprEvaluator> {
11950 APValue &Result;
11951 public:
11952
11953 VectorExprEvaluator(EvalInfo &info, APValue &Result)
11954 : ExprEvaluatorBaseTy(info), Result(Result) {}
11955
11956 bool Success(ArrayRef<APValue> V, const Expr *E) {
11957 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
11958 // FIXME: remove this APValue copy.
11959 Result = APValue(V.data(), V.size());
11960 return true;
11961 }
11962 bool Success(const APValue &V, const Expr *E) {
11963 assert(V.isVector());
11964 Result = V;
11965 return true;
11966 }
11967 bool ZeroInitialization(const Expr *E);
11968
11969 bool VisitUnaryReal(const UnaryOperator *E)
11970 { return Visit(E->getSubExpr()); }
11971 bool VisitCastExpr(const CastExpr* E);
11972 bool VisitInitListExpr(const InitListExpr *E);
11973 bool VisitUnaryImag(const UnaryOperator *E);
11974 bool VisitBinaryOperator(const BinaryOperator *E);
11975 bool VisitUnaryOperator(const UnaryOperator *E);
11976 bool VisitCallExpr(const CallExpr *E);
11977 bool VisitConvertVectorExpr(const ConvertVectorExpr *E);
11978 bool VisitShuffleVectorExpr(const ShuffleVectorExpr *E);
11979
11980 // FIXME: Missing: conditional operator (for GNU
11981 // conditional select), ExtVectorElementExpr
11982 };
11983} // end anonymous namespace
11984
11985static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
11986 assert(E->isPRValue() && E->getType()->isVectorType() &&
11987 "not a vector prvalue");
11988 return VectorExprEvaluator(Info, Result).Visit(E);
11989}
11990
11991static llvm::APInt ConvertBoolVectorToInt(const APValue &Val) {
11992 assert(Val.isVector() && "expected vector APValue");
11993 unsigned NumElts = Val.getVectorLength();
11994
11995 // Each element is one bit, so create an integer with NumElts bits.
11996 llvm::APInt Result(NumElts, 0);
11997
11998 for (unsigned I = 0; I < NumElts; ++I) {
11999 const APValue &Elt = Val.getVectorElt(I);
12000 assert(Elt.isInt() && "expected integer element in bool vector");
12001
12002 if (Elt.getInt().getBoolValue())
12003 Result.setBit(I);
12004 }
12005
12006 return Result;
12007}
12008
12009bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
12010 const VectorType *VTy = E->getType()->castAs<VectorType>();
12011 unsigned NElts = VTy->getNumElements();
12012
12013 const Expr *SE = E->getSubExpr();
12014 QualType SETy = SE->getType();
12015
12016 switch (E->getCastKind()) {
12017 case CK_VectorSplat: {
12018 APValue Val = APValue();
12019 if (SETy->isIntegerType()) {
12020 APSInt IntResult;
12021 if (!EvaluateInteger(SE, IntResult, Info))
12022 return false;
12023 Val = APValue(std::move(IntResult));
12024 } else if (SETy->isRealFloatingType()) {
12025 APFloat FloatResult(0.0);
12026 if (!EvaluateFloat(SE, FloatResult, Info))
12027 return false;
12028 Val = APValue(std::move(FloatResult));
12029 } else {
12030 return Error(E);
12031 }
12032
12033 // Splat and create vector APValue.
12034 SmallVector<APValue, 4> Elts(NElts, Val);
12035 return Success(Elts, E);
12036 }
12037 case CK_BitCast: {
12038 APValue SVal;
12039 if (!Evaluate(SVal, Info, SE))
12040 return false;
12041
12042 if (!SVal.isInt() && !SVal.isFloat() && !SVal.isVector()) {
12043 // Give up if the input isn't an int, float, or vector. For example, we
12044 // reject "(v4i16)(intptr_t)&a".
12045 Info.FFDiag(E, diag::note_constexpr_invalid_cast)
12046 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
12047 << Info.Ctx.getLangOpts().CPlusPlus;
12048 return false;
12049 }
12050
12051 if (!handleRValueToRValueBitCast(Info, Result, SVal, E))
12052 return false;
12053
12054 return true;
12055 }
12056 case CK_HLSLVectorTruncation: {
12057 APValue Val;
12058 SmallVector<APValue, 4> Elements;
12059 if (!EvaluateVector(SE, Val, Info))
12060 return Error(E);
12061 for (unsigned I = 0; I < NElts; I++)
12062 Elements.push_back(Val.getVectorElt(I));
12063 return Success(Elements, E);
12064 }
12065 case CK_HLSLMatrixTruncation: {
12066 // Matrix truncation occurs in row-major order.
12067 APValue Val;
12068 if (!EvaluateMatrix(SE, Val, Info))
12069 return Error(E);
12070 SmallVector<APValue, 16> Elements;
12071 for (unsigned Row = 0;
12072 Row < Val.getMatrixNumRows() && Elements.size() < NElts; Row++)
12073 for (unsigned Col = 0;
12074 Col < Val.getMatrixNumColumns() && Elements.size() < NElts; Col++)
12075 Elements.push_back(Val.getMatrixElt(Row, Col));
12076 return Success(Elements, E);
12077 }
12078 case CK_HLSLAggregateSplatCast: {
12079 APValue Val;
12080 QualType ValTy;
12081
12082 if (!hlslAggSplatHelper(Info, SE, Val, ValTy))
12083 return false;
12084
12085 // cast our Val once.
12087 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
12088 if (!handleScalarCast(Info, FPO, E, ValTy, VTy->getElementType(), Val,
12089 Result))
12090 return false;
12091
12092 SmallVector<APValue, 4> SplatEls(NElts, Result);
12093 return Success(SplatEls, E);
12094 }
12095 case CK_HLSLElementwiseCast: {
12096 SmallVector<APValue> SrcVals;
12097 SmallVector<QualType> SrcTypes;
12098
12099 if (!hlslElementwiseCastHelper(Info, SE, E->getType(), SrcVals, SrcTypes))
12100 return false;
12101
12102 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
12103 SmallVector<QualType, 4> DestTypes(NElts, VTy->getElementType());
12104 SmallVector<APValue, 4> ResultEls(NElts);
12105 if (!handleElementwiseCast(Info, E, FPO, SrcVals, SrcTypes, DestTypes,
12106 ResultEls))
12107 return false;
12108 return Success(ResultEls, E);
12109 }
12110 case CK_IntegralToFloating:
12111 case CK_FloatingToIntegral:
12112 case CK_IntegralCast:
12113 case CK_FloatingCast:
12114 case CK_FloatingToBoolean:
12115 case CK_IntegralToBoolean: {
12116 // These casts apply element-wise when the source is a vector type.
12117 assert(SETy->isVectorType() && "expected vector source type");
12118 APValue SrcVal;
12119 if (!EvaluateVector(SE, SrcVal, Info))
12120 return Error(E);
12121
12122 assert(SrcVal.getVectorLength() == NElts);
12123 QualType SrcEltTy = SETy->castAs<VectorType>()->getElementType();
12124 QualType DstEltTy = VTy->getElementType();
12125 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
12126
12127 SmallVector<APValue, 4> ResultEls(NElts);
12128 for (unsigned I = 0; I < NElts; ++I) {
12129 if (!handleScalarCast(Info, FPO, E, SrcEltTy, DstEltTy,
12130 SrcVal.getVectorElt(I), ResultEls[I]))
12131 return Error(E);
12132 }
12133 return Success(ResultEls, E);
12134 }
12135 default:
12136 return ExprEvaluatorBaseTy::VisitCastExpr(E);
12137 }
12138}
12139
12140bool
12141VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
12142 const VectorType *VT = E->getType()->castAs<VectorType>();
12143 unsigned NumInits = E->getNumInits();
12144 unsigned NumElements = VT->getNumElements();
12145
12146 QualType EltTy = VT->getElementType();
12147 SmallVector<APValue, 4> Elements;
12148
12149 // MFloat8 type doesn't have constants and thus constant folding
12150 // is impossible.
12151 if (EltTy->isMFloat8Type())
12152 return false;
12153
12154 // The number of initializers can be less than the number of
12155 // vector elements. For OpenCL, this can be due to nested vector
12156 // initialization. For GCC compatibility, missing trailing elements
12157 // should be initialized with zeroes.
12158 unsigned CountInits = 0, CountElts = 0;
12159 while (CountElts < NumElements) {
12160 // Handle nested vector initialization.
12161 if (CountInits < NumInits
12162 && E->getInit(CountInits)->getType()->isVectorType()) {
12163 APValue v;
12164 if (!EvaluateVector(E->getInit(CountInits), v, Info))
12165 return Error(E);
12166 unsigned vlen = v.getVectorLength();
12167 for (unsigned j = 0; j < vlen; j++)
12168 Elements.push_back(v.getVectorElt(j));
12169 CountElts += vlen;
12170 } else if (EltTy->isIntegerType()) {
12171 llvm::APSInt sInt(32);
12172 if (CountInits < NumInits) {
12173 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
12174 return false;
12175 } else // trailing integer zero.
12176 sInt = Info.Ctx.MakeIntValue(0, EltTy);
12177 Elements.push_back(APValue(sInt));
12178 CountElts++;
12179 } else {
12180 llvm::APFloat f(0.0);
12181 if (CountInits < NumInits) {
12182 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
12183 return false;
12184 } else // trailing float zero.
12185 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
12186 Elements.push_back(APValue(f));
12187 CountElts++;
12188 }
12189 CountInits++;
12190 }
12191 return Success(Elements, E);
12192}
12193
12194bool
12195VectorExprEvaluator::ZeroInitialization(const Expr *E) {
12196 const auto *VT = E->getType()->castAs<VectorType>();
12197 QualType EltTy = VT->getElementType();
12198 APValue ZeroElement;
12199 if (EltTy->isIntegerType())
12200 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
12201 else
12202 ZeroElement =
12203 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
12204
12205 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
12206 return Success(Elements, E);
12207}
12208
12209bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
12210 VisitIgnoredValue(E->getSubExpr());
12211 return ZeroInitialization(E);
12212}
12213
12214bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
12215 BinaryOperatorKind Op = E->getOpcode();
12216 assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp &&
12217 "Operation not supported on vector types");
12218
12219 if (Op == BO_Comma)
12220 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
12221
12222 Expr *LHS = E->getLHS();
12223 Expr *RHS = E->getRHS();
12224
12225 assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() &&
12226 "Must both be vector types");
12227 // Checking JUST the types are the same would be fine, except shifts don't
12228 // need to have their types be the same (since you always shift by an int).
12229 assert(LHS->getType()->castAs<VectorType>()->getNumElements() ==
12230 E->getType()->castAs<VectorType>()->getNumElements() &&
12231 RHS->getType()->castAs<VectorType>()->getNumElements() ==
12232 E->getType()->castAs<VectorType>()->getNumElements() &&
12233 "All operands must be the same size.");
12234
12235 APValue LHSValue;
12236 APValue RHSValue;
12237 bool LHSOK = Evaluate(LHSValue, Info, LHS);
12238 if (!LHSOK && !Info.noteFailure())
12239 return false;
12240 if (!Evaluate(RHSValue, Info, RHS) || !LHSOK)
12241 return false;
12242
12243 if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue))
12244 return false;
12245
12246 return Success(LHSValue, E);
12247}
12248
12249static std::optional<APValue> handleVectorUnaryOperator(ASTContext &Ctx,
12250 QualType ResultTy,
12252 APValue Elt) {
12253 switch (Op) {
12254 case UO_Plus:
12255 // Nothing to do here.
12256 return Elt;
12257 case UO_Minus:
12258 if (Elt.getKind() == APValue::Int) {
12259 Elt.getInt().negate();
12260 } else {
12261 assert(Elt.getKind() == APValue::Float &&
12262 "Vector can only be int or float type");
12263 Elt.getFloat().changeSign();
12264 }
12265 return Elt;
12266 case UO_Not:
12267 // This is only valid for integral types anyway, so we don't have to handle
12268 // float here.
12269 assert(Elt.getKind() == APValue::Int &&
12270 "Vector operator ~ can only be int");
12271 Elt.getInt().flipAllBits();
12272 return Elt;
12273 case UO_LNot: {
12274 if (Elt.getKind() == APValue::Int) {
12275 Elt.getInt() = !Elt.getInt();
12276 // operator ! on vectors returns -1 for 'truth', so negate it.
12277 Elt.getInt().negate();
12278 return Elt;
12279 }
12280 assert(Elt.getKind() == APValue::Float &&
12281 "Vector can only be int or float type");
12282 // Float types result in an int of the same size, but -1 for true, or 0 for
12283 // false.
12284 APSInt EltResult{Ctx.getIntWidth(ResultTy),
12285 ResultTy->isUnsignedIntegerType()};
12286 if (Elt.getFloat().isZero())
12287 EltResult.setAllBits();
12288 else
12289 EltResult.clearAllBits();
12290
12291 return APValue{EltResult};
12292 }
12293 default:
12294 // FIXME: Implement the rest of the unary operators.
12295 return std::nullopt;
12296 }
12297}
12298
12299bool VectorExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
12300 Expr *SubExpr = E->getSubExpr();
12301 const auto *VD = SubExpr->getType()->castAs<VectorType>();
12302 // This result element type differs in the case of negating a floating point
12303 // vector, since the result type is the a vector of the equivilant sized
12304 // integer.
12305 const QualType ResultEltTy = VD->getElementType();
12306 UnaryOperatorKind Op = E->getOpcode();
12307
12308 APValue SubExprValue;
12309 if (!Evaluate(SubExprValue, Info, SubExpr))
12310 return false;
12311
12312 // FIXME: This vector evaluator someday needs to be changed to be LValue
12313 // aware/keep LValue information around, rather than dealing with just vector
12314 // types directly. Until then, we cannot handle cases where the operand to
12315 // these unary operators is an LValue. The only case I've been able to see
12316 // cause this is operator++ assigning to a member expression (only valid in
12317 // altivec compilations) in C mode, so this shouldn't limit us too much.
12318 if (SubExprValue.isLValue())
12319 return false;
12320
12321 assert(SubExprValue.getVectorLength() == VD->getNumElements() &&
12322 "Vector length doesn't match type?");
12323
12324 SmallVector<APValue, 4> ResultElements;
12325 for (unsigned EltNum = 0; EltNum < VD->getNumElements(); ++EltNum) {
12326 std::optional<APValue> Elt = handleVectorUnaryOperator(
12327 Info.Ctx, ResultEltTy, Op, SubExprValue.getVectorElt(EltNum));
12328 if (!Elt)
12329 return false;
12330 ResultElements.push_back(*Elt);
12331 }
12332 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12333}
12334
12335static bool handleVectorElementCast(EvalInfo &Info, const FPOptions FPO,
12336 const Expr *E, QualType SourceTy,
12337 QualType DestTy, APValue const &Original,
12338 APValue &Result) {
12339 if (SourceTy->isIntegerType()) {
12340 if (DestTy->isRealFloatingType()) {
12341 Result = APValue(APFloat(0.0));
12342 return HandleIntToFloatCast(Info, E, FPO, SourceTy, Original.getInt(),
12343 DestTy, Result.getFloat());
12344 }
12345 if (DestTy->isIntegerType()) {
12346 Result = APValue(
12347 HandleIntToIntCast(Info, E, DestTy, SourceTy, Original.getInt()));
12348 return true;
12349 }
12350 } else if (SourceTy->isRealFloatingType()) {
12351 if (DestTy->isRealFloatingType()) {
12352 Result = Original;
12353 return HandleFloatToFloatCast(Info, E, SourceTy, DestTy,
12354 Result.getFloat());
12355 }
12356 if (DestTy->isIntegerType()) {
12357 Result = APValue(APSInt());
12358 return HandleFloatToIntCast(Info, E, SourceTy, Original.getFloat(),
12359 DestTy, Result.getInt());
12360 }
12361 }
12362
12363 Info.FFDiag(E, diag::err_convertvector_constexpr_unsupported_vector_cast)
12364 << SourceTy << DestTy;
12365 return false;
12366}
12367
12368static bool evalPackBuiltin(const CallExpr *E, EvalInfo &Info, APValue &Result,
12369 llvm::function_ref<APInt(const APSInt &)> PackFn) {
12370 APValue LHS, RHS;
12371 if (!EvaluateAsRValue(Info, E->getArg(0), LHS) ||
12372 !EvaluateAsRValue(Info, E->getArg(1), RHS))
12373 return false;
12374
12375 unsigned LHSVecLen = LHS.getVectorLength();
12376 unsigned RHSVecLen = RHS.getVectorLength();
12377
12378 assert(LHSVecLen != 0 && LHSVecLen == RHSVecLen &&
12379 "pack builtin LHSVecLen must equal to RHSVecLen");
12380
12381 const VectorType *VT0 = E->getArg(0)->getType()->castAs<VectorType>();
12382 const unsigned SrcBits = Info.Ctx.getIntWidth(VT0->getElementType());
12383
12384 const VectorType *DstVT = E->getType()->castAs<VectorType>();
12385 QualType DstElemTy = DstVT->getElementType();
12386 const bool DstIsUnsigned = DstElemTy->isUnsignedIntegerType();
12387
12388 const unsigned SrcPerLane = 128 / SrcBits;
12389 const unsigned Lanes = LHSVecLen * SrcBits / 128;
12390
12392 Out.reserve(LHSVecLen + RHSVecLen);
12393
12394 for (unsigned Lane = 0; Lane != Lanes; ++Lane) {
12395 unsigned base = Lane * SrcPerLane;
12396 for (unsigned I = 0; I != SrcPerLane; ++I)
12397 Out.emplace_back(APValue(
12398 APSInt(PackFn(LHS.getVectorElt(base + I).getInt()), DstIsUnsigned)));
12399 for (unsigned I = 0; I != SrcPerLane; ++I)
12400 Out.emplace_back(APValue(
12401 APSInt(PackFn(RHS.getVectorElt(base + I).getInt()), DstIsUnsigned)));
12402 }
12403
12404 Result = APValue(Out.data(), Out.size());
12405 return true;
12406}
12407
12409 EvalInfo &Info, const CallExpr *Call, APValue &Out,
12410 llvm::function_ref<std::pair<unsigned, int>(unsigned, unsigned)>
12411 GetSourceIndex) {
12412
12413 const auto *VT = Call->getType()->getAs<VectorType>();
12414 if (!VT)
12415 return false;
12416
12417 unsigned ShuffleMask = 0;
12418 APValue A, MaskVector, B;
12419 bool IsVectorMask = false;
12420 bool IsSingleOperand = (Call->getNumArgs() == 2);
12421
12422 if (IsSingleOperand) {
12423 QualType MaskType = Call->getArg(1)->getType();
12424 if (MaskType->isVectorType()) {
12425 IsVectorMask = true;
12426 if (!EvaluateAsRValue(Info, Call->getArg(0), A) ||
12427 !EvaluateAsRValue(Info, Call->getArg(1), MaskVector))
12428 return false;
12429 B = A;
12430 } else if (MaskType->isIntegerType()) {
12431 APSInt MaskImm;
12432 if (!EvaluateInteger(Call->getArg(1), MaskImm, Info))
12433 return false;
12434 ShuffleMask = static_cast<unsigned>(MaskImm.getZExtValue());
12435 if (!EvaluateAsRValue(Info, Call->getArg(0), A))
12436 return false;
12437 B = A;
12438 } else {
12439 return false;
12440 }
12441 } else {
12442 QualType Arg2Type = Call->getArg(2)->getType();
12443 if (Arg2Type->isVectorType()) {
12444 IsVectorMask = true;
12445 if (!EvaluateAsRValue(Info, Call->getArg(0), A) ||
12446 !EvaluateAsRValue(Info, Call->getArg(1), MaskVector) ||
12447 !EvaluateAsRValue(Info, Call->getArg(2), B))
12448 return false;
12449 } else if (Arg2Type->isIntegerType()) {
12450 APSInt MaskImm;
12451 if (!EvaluateInteger(Call->getArg(2), MaskImm, Info))
12452 return false;
12453 ShuffleMask = static_cast<unsigned>(MaskImm.getZExtValue());
12454 if (!EvaluateAsRValue(Info, Call->getArg(0), A) ||
12455 !EvaluateAsRValue(Info, Call->getArg(1), B))
12456 return false;
12457 } else {
12458 return false;
12459 }
12460 }
12461
12462 unsigned NumElts = VT->getNumElements();
12463 SmallVector<APValue, 64> ResultElements;
12464 ResultElements.reserve(NumElts);
12465
12466 for (unsigned DstIdx = 0; DstIdx != NumElts; ++DstIdx) {
12467 if (IsVectorMask) {
12468 ShuffleMask = static_cast<unsigned>(
12469 MaskVector.getVectorElt(DstIdx).getInt().getZExtValue());
12470 }
12471 auto [SrcVecIdx, SrcIdx] = GetSourceIndex(DstIdx, ShuffleMask);
12472
12473 if (SrcIdx < 0) {
12474 // Zero out this element
12475 QualType ElemTy = VT->getElementType();
12476 if (ElemTy->isRealFloatingType()) {
12477 ResultElements.push_back(
12478 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy))));
12479 } else if (ElemTy->isIntegerType()) {
12480 APValue Zero(Info.Ctx.MakeIntValue(0, ElemTy));
12481 ResultElements.push_back(APValue(Zero));
12482 } else {
12483 // Other types of fallback logic
12484 ResultElements.push_back(APValue());
12485 }
12486 } else {
12487 const APValue &Src = (SrcVecIdx == 0) ? A : B;
12488 ResultElements.push_back(Src.getVectorElt(SrcIdx));
12489 }
12490 }
12491
12492 Out = APValue(ResultElements.data(), ResultElements.size());
12493 return true;
12494}
12495static bool ConvertDoubleToFloatStrict(EvalInfo &Info, const Expr *E,
12496 APFloat OrigVal, APValue &Result) {
12497
12498 if (OrigVal.isInfinity()) {
12499 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << 0;
12500 return false;
12501 }
12502 if (OrigVal.isNaN()) {
12503 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << 1;
12504 return false;
12505 }
12506
12507 APFloat Val = OrigVal;
12508 bool LosesInfo = false;
12509 APFloat::opStatus Status = Val.convert(
12510 APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, &LosesInfo);
12511
12512 if (LosesInfo || Val.isDenormal()) {
12513 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic_strict);
12514 return false;
12515 }
12516
12517 if (Status != APFloat::opOK) {
12518 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
12519 return false;
12520 }
12521
12522 Result = APValue(Val);
12523 return true;
12524}
12526 EvalInfo &Info, const CallExpr *Call, APValue &Out,
12527 llvm::function_ref<APInt(const APInt &, uint64_t)> ShiftOp,
12528 llvm::function_ref<APInt(const APInt &, unsigned)> OverflowOp) {
12529
12530 APValue Source, Count;
12531 if (!EvaluateAsRValue(Info, Call->getArg(0), Source) ||
12532 !EvaluateAsRValue(Info, Call->getArg(1), Count))
12533 return false;
12534
12535 assert(Call->getNumArgs() == 2);
12536
12537 QualType SourceTy = Call->getArg(0)->getType();
12538 assert(SourceTy->isVectorType() &&
12539 Call->getArg(1)->getType()->isVectorType());
12540
12541 QualType DestEltTy = SourceTy->castAs<VectorType>()->getElementType();
12542 unsigned DestEltWidth = Source.getVectorElt(0).getInt().getBitWidth();
12543 unsigned DestLen = Source.getVectorLength();
12544 bool IsDestUnsigned = DestEltTy->isUnsignedIntegerType();
12545 unsigned CountEltWidth = Count.getVectorElt(0).getInt().getBitWidth();
12546 unsigned NumBitsInQWord = 64;
12547 unsigned NumCountElts = NumBitsInQWord / CountEltWidth;
12549 Result.reserve(DestLen);
12550
12551 uint64_t CountLQWord = 0;
12552 for (unsigned EltIdx = 0; EltIdx != NumCountElts; ++EltIdx) {
12553 uint64_t Elt = Count.getVectorElt(EltIdx).getInt().getZExtValue();
12554 CountLQWord |= (Elt << (EltIdx * CountEltWidth));
12555 }
12556
12557 for (unsigned EltIdx = 0; EltIdx != DestLen; ++EltIdx) {
12558 APInt Elt = Source.getVectorElt(EltIdx).getInt();
12559 if (CountLQWord < DestEltWidth) {
12560 Result.push_back(
12561 APValue(APSInt(ShiftOp(Elt, CountLQWord), IsDestUnsigned)));
12562 } else {
12563 Result.push_back(
12564 APValue(APSInt(OverflowOp(Elt, DestEltWidth), IsDestUnsigned)));
12565 }
12566 }
12567 Out = APValue(Result.data(), Result.size());
12568 return true;
12569}
12570
12571std::optional<APFloat> EvalScalarMinMaxFp(const APFloat &A, const APFloat &B,
12572 std::optional<APSInt> RoundingMode,
12573 bool IsMin) {
12574 APSInt DefaultMode(APInt(32, 4), /*isUnsigned=*/true);
12575 if (RoundingMode.value_or(DefaultMode) != 4)
12576 return std::nullopt;
12577 if (A.isNaN() || A.isInfinity() || A.isDenormal() || B.isNaN() ||
12578 B.isInfinity() || B.isDenormal())
12579 return std::nullopt;
12580 if (A.isZero() && B.isZero())
12581 return B;
12582 return IsMin ? llvm::minimum(A, B) : llvm::maximum(A, B);
12583}
12584
12585bool VectorExprEvaluator::VisitCallExpr(const CallExpr *E) {
12586 if (!IsConstantEvaluatedBuiltinCall(E))
12587 return ExprEvaluatorBaseTy::VisitCallExpr(E);
12588
12589 unsigned BuiltinOp = ConvertBuiltinIDToX86BuiltinID(Info.Ctx, E);
12590
12591 auto EvaluateBinOpExpr =
12592 [&](llvm::function_ref<APInt(const APSInt &, const APSInt &)> Fn) {
12593 APValue SourceLHS, SourceRHS;
12594 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
12595 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
12596 return false;
12597
12598 auto *DestTy = E->getType()->castAs<VectorType>();
12599 QualType DestEltTy = DestTy->getElementType();
12600 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
12601 unsigned SourceLen = SourceLHS.getVectorLength();
12602 SmallVector<APValue, 4> ResultElements;
12603 ResultElements.reserve(SourceLen);
12604
12605 if (SourceRHS.isInt()) {
12606 const APSInt &RHS = SourceRHS.getInt();
12607 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12608 const APSInt &LHS = SourceLHS.getVectorElt(EltNum).getInt();
12609 ResultElements.push_back(
12610 APValue(APSInt(Fn(LHS, RHS), DestUnsigned)));
12611 }
12612 } else {
12613 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12614 const APSInt &LHS = SourceLHS.getVectorElt(EltNum).getInt();
12615 const APSInt &RHS = SourceRHS.getVectorElt(EltNum).getInt();
12616 ResultElements.push_back(
12617 APValue(APSInt(Fn(LHS, RHS), DestUnsigned)));
12618 }
12619 }
12620 return Success(APValue(ResultElements.data(), SourceLen), E);
12621 };
12622
12623 auto EvaluateFpBinOpExpr =
12624 [&](llvm::function_ref<std::optional<APFloat>(
12625 const APFloat &, const APFloat &, std::optional<APSInt>)>
12626 Fn,
12627 bool IsScalar = false) {
12628 assert(E->getNumArgs() == 2 || E->getNumArgs() == 3);
12629 APValue A, B;
12630 if (!EvaluateAsRValue(Info, E->getArg(0), A) ||
12631 !EvaluateAsRValue(Info, E->getArg(1), B))
12632 return false;
12633
12634 assert(A.isVector() && B.isVector());
12635 assert(A.getVectorLength() == B.getVectorLength());
12636
12637 std::optional<APSInt> RoundingMode;
12638 if (E->getNumArgs() == 3) {
12639 APSInt Imm;
12640 if (!EvaluateInteger(E->getArg(2), Imm, Info))
12641 return false;
12642 RoundingMode = Imm;
12643 }
12644
12645 unsigned NumElems = A.getVectorLength();
12646 SmallVector<APValue, 4> ResultElements;
12647 ResultElements.reserve(NumElems);
12648
12649 for (unsigned EltNum = 0; EltNum < NumElems; ++EltNum) {
12650 if (IsScalar && EltNum > 0) {
12651 ResultElements.push_back(A.getVectorElt(EltNum));
12652 continue;
12653 }
12654 const APFloat &EltA = A.getVectorElt(EltNum).getFloat();
12655 const APFloat &EltB = B.getVectorElt(EltNum).getFloat();
12656 std::optional<APFloat> Result = Fn(EltA, EltB, RoundingMode);
12657 if (!Result)
12658 return false;
12659 ResultElements.push_back(APValue(*Result));
12660 }
12661 return Success(APValue(ResultElements.data(), NumElems), E);
12662 };
12663
12664 auto EvaluateScalarFpRoundMaskBinOp =
12665 [&](llvm::function_ref<std::optional<APFloat>(
12666 const APFloat &, const APFloat &, std::optional<APSInt>)>
12667 Fn) {
12668 assert(E->getNumArgs() == 5);
12669 APValue VecA, VecB, VecSrc;
12670 APSInt MaskVal, Rounding;
12671
12672 if (!EvaluateAsRValue(Info, E->getArg(0), VecA) ||
12673 !EvaluateAsRValue(Info, E->getArg(1), VecB) ||
12674 !EvaluateAsRValue(Info, E->getArg(2), VecSrc) ||
12675 !EvaluateInteger(E->getArg(3), MaskVal, Info) ||
12676 !EvaluateInteger(E->getArg(4), Rounding, Info))
12677 return false;
12678
12679 unsigned NumElems = VecA.getVectorLength();
12680 SmallVector<APValue, 8> ResultElements;
12681 ResultElements.reserve(NumElems);
12682
12683 if (MaskVal.getZExtValue() & 1) {
12684 const APFloat &EltA = VecA.getVectorElt(0).getFloat();
12685 const APFloat &EltB = VecB.getVectorElt(0).getFloat();
12686 std::optional<APFloat> Result = Fn(EltA, EltB, Rounding);
12687 if (!Result)
12688 return false;
12689 ResultElements.push_back(APValue(*Result));
12690 } else {
12691 ResultElements.push_back(VecSrc.getVectorElt(0));
12692 }
12693
12694 for (unsigned I = 1; I < NumElems; ++I)
12695 ResultElements.push_back(VecA.getVectorElt(I));
12696
12697 return Success(APValue(ResultElements.data(), NumElems), E);
12698 };
12699
12700 auto EvalSelectScalar = [&](unsigned Len) -> bool {
12701 APSInt Mask;
12702 APValue AVal, WVal;
12703 if (!EvaluateInteger(E->getArg(0), Mask, Info) ||
12704 !EvaluateAsRValue(Info, E->getArg(1), AVal) ||
12705 !EvaluateAsRValue(Info, E->getArg(2), WVal))
12706 return false;
12707
12708 bool TakeA0 = (Mask.getZExtValue() & 1u) != 0;
12710 Res.reserve(Len);
12711 Res.push_back(TakeA0 ? AVal.getVectorElt(0) : WVal.getVectorElt(0));
12712 for (unsigned I = 1; I < Len; ++I)
12713 Res.push_back(WVal.getVectorElt(I));
12714 APValue V(Res.data(), Res.size());
12715 return Success(V, E);
12716 };
12717
12718 auto EvalVectorDotProduct = [&](bool IsSaturating) -> bool {
12719 APValue Source, OperandA, OperandB;
12720 if (!EvaluateVector(E->getArg(0), Source, Info) ||
12721 !EvaluateVector(E->getArg(1), OperandA, Info) ||
12722 !EvaluateVector(E->getArg(2), OperandB, Info)) {
12723 return false;
12724 }
12725
12726 unsigned NumSrcElems = Source.getVectorLength();
12727 unsigned NumOperandElems = OperandA.getVectorLength();
12728 unsigned ElemsPerLane = NumOperandElems / NumSrcElems;
12729
12730 assert(OperandA.getVectorLength() == OperandB.getVectorLength());
12731
12733 Result.reserve(NumSrcElems);
12734 for (unsigned I = 0; I != NumSrcElems; ++I) {
12735 APSInt DotProduct = Source.getVectorElt(I).getInt();
12736 DotProduct = DotProduct.extend(64);
12737 for (unsigned J = 0; J != ElemsPerLane; ++J) {
12738 APSInt OpA = APSInt(
12739 OperandA.getVectorElt(ElemsPerLane * I + J).getInt().extend(64),
12740 false);
12741 APSInt OpB = APSInt(
12742 OperandB.getVectorElt(ElemsPerLane * I + J).getInt().extend(64),
12743 false);
12744 DotProduct += OpA * OpB;
12745 }
12746 if (IsSaturating) {
12747 DotProduct = APSInt(DotProduct.truncSSat(32), false);
12748 } else {
12749 DotProduct = APSInt(DotProduct.trunc(32), false);
12750 }
12751 Result.push_back(APValue(DotProduct));
12752 }
12753
12754 return Success(APValue(Result.data(), Result.size()), E);
12755 };
12756
12757 switch (BuiltinOp) {
12758 default:
12759 return false;
12760 case Builtin::BI__builtin_elementwise_popcount:
12761 case Builtin::BI__builtin_elementwise_bitreverse: {
12762 APValue Source;
12763 if (!EvaluateAsRValue(Info, E->getArg(0), Source))
12764 return false;
12765
12766 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
12767 unsigned SourceLen = Source.getVectorLength();
12768 SmallVector<APValue, 4> ResultElements;
12769 ResultElements.reserve(SourceLen);
12770
12771 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12772 APSInt Elt = Source.getVectorElt(EltNum).getInt();
12773 switch (BuiltinOp) {
12774 case Builtin::BI__builtin_elementwise_popcount:
12775 ResultElements.push_back(APValue(
12776 APSInt(APInt(Info.Ctx.getIntWidth(DestEltTy), Elt.popcount()),
12777 DestEltTy->isUnsignedIntegerOrEnumerationType())));
12778 break;
12779 case Builtin::BI__builtin_elementwise_bitreverse:
12780 ResultElements.push_back(
12781 APValue(APSInt(Elt.reverseBits(),
12782 DestEltTy->isUnsignedIntegerOrEnumerationType())));
12783 break;
12784 }
12785 }
12786
12787 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12788 }
12789 case Builtin::BI__builtin_elementwise_abs: {
12790 APValue Source;
12791 if (!EvaluateAsRValue(Info, E->getArg(0), Source))
12792 return false;
12793
12794 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
12795 unsigned SourceLen = Source.getVectorLength();
12796 SmallVector<APValue, 4> ResultElements;
12797 ResultElements.reserve(SourceLen);
12798
12799 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12800 APValue CurrentEle = Source.getVectorElt(EltNum);
12801 APValue Val = DestEltTy->isFloatingType()
12802 ? APValue(llvm::abs(CurrentEle.getFloat()))
12803 : APValue(APSInt(
12804 CurrentEle.getInt().abs(),
12805 DestEltTy->isUnsignedIntegerOrEnumerationType()));
12806 ResultElements.push_back(Val);
12807 }
12808
12809 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12810 }
12811
12812 case Builtin::BI__builtin_elementwise_add_sat:
12813 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
12814 return LHS.isSigned() ? LHS.sadd_sat(RHS) : LHS.uadd_sat(RHS);
12815 });
12816
12817 case Builtin::BI__builtin_elementwise_sub_sat:
12818 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
12819 return LHS.isSigned() ? LHS.ssub_sat(RHS) : LHS.usub_sat(RHS);
12820 });
12821
12822 case X86::BI__builtin_ia32_extract128i256:
12823 case X86::BI__builtin_ia32_vextractf128_pd256:
12824 case X86::BI__builtin_ia32_vextractf128_ps256:
12825 case X86::BI__builtin_ia32_vextractf128_si256: {
12826 APValue SourceVec, SourceImm;
12827 if (!EvaluateAsRValue(Info, E->getArg(0), SourceVec) ||
12828 !EvaluateAsRValue(Info, E->getArg(1), SourceImm))
12829 return false;
12830
12831 if (!SourceVec.isVector())
12832 return false;
12833
12834 const auto *RetVT = E->getType()->castAs<VectorType>();
12835 unsigned RetLen = RetVT->getNumElements();
12836 unsigned Idx = SourceImm.getInt().getZExtValue() & 1;
12837
12838 SmallVector<APValue, 32> ResultElements;
12839 ResultElements.reserve(RetLen);
12840
12841 for (unsigned I = 0; I < RetLen; I++)
12842 ResultElements.push_back(SourceVec.getVectorElt(Idx * RetLen + I));
12843
12844 return Success(APValue(ResultElements.data(), RetLen), E);
12845 }
12846
12847 case clang::X86::BI__builtin_ia32_cvtmask2b128:
12848 case clang::X86::BI__builtin_ia32_cvtmask2b256:
12849 case clang::X86::BI__builtin_ia32_cvtmask2b512:
12850 case clang::X86::BI__builtin_ia32_cvtmask2w128:
12851 case clang::X86::BI__builtin_ia32_cvtmask2w256:
12852 case clang::X86::BI__builtin_ia32_cvtmask2w512:
12853 case clang::X86::BI__builtin_ia32_cvtmask2d128:
12854 case clang::X86::BI__builtin_ia32_cvtmask2d256:
12855 case clang::X86::BI__builtin_ia32_cvtmask2d512:
12856 case clang::X86::BI__builtin_ia32_cvtmask2q128:
12857 case clang::X86::BI__builtin_ia32_cvtmask2q256:
12858 case clang::X86::BI__builtin_ia32_cvtmask2q512: {
12859 assert(E->getNumArgs() == 1);
12860 APSInt Mask;
12861 if (!EvaluateInteger(E->getArg(0), Mask, Info))
12862 return false;
12863
12864 QualType VecTy = E->getType();
12865 const VectorType *VT = VecTy->castAs<VectorType>();
12866 unsigned VectorLen = VT->getNumElements();
12867 QualType ElemTy = VT->getElementType();
12868 unsigned ElemWidth = Info.Ctx.getTypeSize(ElemTy);
12869
12871 for (unsigned I = 0; I != VectorLen; ++I) {
12872 bool BitSet = Mask[I];
12873 APSInt ElemVal(ElemWidth, /*isUnsigned=*/false);
12874 if (BitSet) {
12875 ElemVal.setAllBits();
12876 }
12877 Elems.push_back(APValue(ElemVal));
12878 }
12879 return Success(APValue(Elems.data(), VectorLen), E);
12880 }
12881
12882 case X86::BI__builtin_ia32_extracti32x4_256_mask:
12883 case X86::BI__builtin_ia32_extractf32x4_256_mask:
12884 case X86::BI__builtin_ia32_extracti32x4_mask:
12885 case X86::BI__builtin_ia32_extractf32x4_mask:
12886 case X86::BI__builtin_ia32_extracti32x8_mask:
12887 case X86::BI__builtin_ia32_extractf32x8_mask:
12888 case X86::BI__builtin_ia32_extracti64x2_256_mask:
12889 case X86::BI__builtin_ia32_extractf64x2_256_mask:
12890 case X86::BI__builtin_ia32_extracti64x2_512_mask:
12891 case X86::BI__builtin_ia32_extractf64x2_512_mask:
12892 case X86::BI__builtin_ia32_extracti64x4_mask:
12893 case X86::BI__builtin_ia32_extractf64x4_mask: {
12894 APValue SourceVec, MergeVec;
12895 APSInt Imm, MaskImm;
12896
12897 if (!EvaluateAsRValue(Info, E->getArg(0), SourceVec) ||
12898 !EvaluateInteger(E->getArg(1), Imm, Info) ||
12899 !EvaluateAsRValue(Info, E->getArg(2), MergeVec) ||
12900 !EvaluateInteger(E->getArg(3), MaskImm, Info))
12901 return false;
12902
12903 const auto *RetVT = E->getType()->castAs<VectorType>();
12904 unsigned RetLen = RetVT->getNumElements();
12905
12906 if (!SourceVec.isVector() || !MergeVec.isVector())
12907 return false;
12908 unsigned SrcLen = SourceVec.getVectorLength();
12909 unsigned Lanes = SrcLen / RetLen;
12910 unsigned Lane = static_cast<unsigned>(Imm.getZExtValue() % Lanes);
12911 unsigned Base = Lane * RetLen;
12912
12913 SmallVector<APValue, 32> ResultElements;
12914 ResultElements.reserve(RetLen);
12915 for (unsigned I = 0; I < RetLen; ++I) {
12916 if (MaskImm[I])
12917 ResultElements.push_back(SourceVec.getVectorElt(Base + I));
12918 else
12919 ResultElements.push_back(MergeVec.getVectorElt(I));
12920 }
12921 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12922 }
12923
12924 case clang::X86::BI__builtin_ia32_pavgb128:
12925 case clang::X86::BI__builtin_ia32_pavgw128:
12926 case clang::X86::BI__builtin_ia32_pavgb256:
12927 case clang::X86::BI__builtin_ia32_pavgw256:
12928 case clang::X86::BI__builtin_ia32_pavgb512:
12929 case clang::X86::BI__builtin_ia32_pavgw512:
12930 return EvaluateBinOpExpr(llvm::APIntOps::avgCeilU);
12931
12932 case clang::X86::BI__builtin_ia32_pmulhrsw128:
12933 case clang::X86::BI__builtin_ia32_pmulhrsw256:
12934 case clang::X86::BI__builtin_ia32_pmulhrsw512:
12935 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
12936 return (llvm::APIntOps::mulsExtended(LHS, RHS).ashr(14) + 1)
12937 .extractBits(16, 1);
12938 });
12939
12940 case clang::X86::BI__builtin_ia32_psadbw128:
12941 case clang::X86::BI__builtin_ia32_psadbw256:
12942 case clang::X86::BI__builtin_ia32_psadbw512: {
12943 APValue SourceLHS, SourceRHS;
12944 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
12945 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
12946 return false;
12947
12948 assert(SourceLHS.isVector() && SourceRHS.isVector());
12949 unsigned SourceLen = SourceLHS.getVectorLength();
12950 assert(SourceLen == SourceRHS.getVectorLength());
12951 assert((SourceLen % 8) == 0);
12952
12953 auto *DestTy = E->getType()->castAs<VectorType>();
12954 QualType DestEltTy = DestTy->getElementType();
12955 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
12956 SmallVector<APValue, 8> ResultElements;
12957 ResultElements.reserve(SourceLen / 8);
12958
12959 for (unsigned Lane = 0; Lane != SourceLen; Lane += 8) {
12960 APInt Sum(64, 0);
12961 for (unsigned I = 0; I != 8; ++I) {
12962 APInt LHS = SourceLHS.getVectorElt(Lane + I).getInt().extOrTrunc(8);
12963 APInt RHS = SourceRHS.getVectorElt(Lane + I).getInt().extOrTrunc(8);
12964 Sum += llvm::APIntOps::abdu(LHS, RHS).zext(64);
12965 }
12966 ResultElements.push_back(APValue(APSInt(Sum, DestUnsigned)));
12967 }
12968
12969 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12970 }
12971
12972 case clang::X86::BI__builtin_ia32_pmaddubsw128:
12973 case clang::X86::BI__builtin_ia32_pmaddubsw256:
12974 case clang::X86::BI__builtin_ia32_pmaddubsw512:
12975 case clang::X86::BI__builtin_ia32_pmaddwd128:
12976 case clang::X86::BI__builtin_ia32_pmaddwd256:
12977 case clang::X86::BI__builtin_ia32_pmaddwd512: {
12978 APValue SourceLHS, SourceRHS;
12979 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
12980 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
12981 return false;
12982
12983 auto *DestTy = E->getType()->castAs<VectorType>();
12984 QualType DestEltTy = DestTy->getElementType();
12985 unsigned SourceLen = SourceLHS.getVectorLength();
12986 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
12987 SmallVector<APValue, 4> ResultElements;
12988 ResultElements.reserve(SourceLen / 2);
12989
12990 for (unsigned EltNum = 0; EltNum < SourceLen; EltNum += 2) {
12991 const APSInt &LoLHS = SourceLHS.getVectorElt(EltNum).getInt();
12992 const APSInt &HiLHS = SourceLHS.getVectorElt(EltNum + 1).getInt();
12993 const APSInt &LoRHS = SourceRHS.getVectorElt(EltNum).getInt();
12994 const APSInt &HiRHS = SourceRHS.getVectorElt(EltNum + 1).getInt();
12995 unsigned BitWidth = 2 * LoLHS.getBitWidth();
12996
12997 switch (BuiltinOp) {
12998 case clang::X86::BI__builtin_ia32_pmaddubsw128:
12999 case clang::X86::BI__builtin_ia32_pmaddubsw256:
13000 case clang::X86::BI__builtin_ia32_pmaddubsw512:
13001 ResultElements.push_back(APValue(
13002 APSInt((LoLHS.zext(BitWidth) * LoRHS.sext(BitWidth))
13003 .sadd_sat((HiLHS.zext(BitWidth) * HiRHS.sext(BitWidth))),
13004 DestUnsigned)));
13005 break;
13006 case clang::X86::BI__builtin_ia32_pmaddwd128:
13007 case clang::X86::BI__builtin_ia32_pmaddwd256:
13008 case clang::X86::BI__builtin_ia32_pmaddwd512:
13009 ResultElements.push_back(
13010 APValue(APSInt((LoLHS.sext(BitWidth) * LoRHS.sext(BitWidth)) +
13011 (HiLHS.sext(BitWidth) * HiRHS.sext(BitWidth)),
13012 DestUnsigned)));
13013 break;
13014 }
13015 }
13016
13017 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13018 }
13019
13020 case clang::X86::BI__builtin_ia32_bmacor16x16x16_v16hi:
13021 case clang::X86::BI__builtin_ia32_bmacor16x16x16_v32hi:
13022 case clang::X86::BI__builtin_ia32_bmacxor16x16x16_v16hi:
13023 case clang::X86::BI__builtin_ia32_bmacxor16x16x16_v32hi: {
13024 // Bit Matrix Multiply and Accumulate (AVX512BMM). Each 256-bit lane holds
13025 // a 16x16 bit matrix as 16 x i16 elements; element i is row i and bit j of
13026 // that element is entry [i][j]. The accumulator (third argument, src1 in
13027 // the AMD ISA) provides the initial value of each result bit, into which
13028 // the bit-matrix product of the first two arguments (src2 * src3) is
13029 // reduced with OR (vbmacor) or XOR (vbmacxor):
13030 // for i in 0..15, j in 0..15:
13031 // bit = C[16*i+j]
13032 // for k in 0..15: bit OP= A[16*i+k] & B[16*k+j]
13033 // dest[16*i+j] = bit
13034 APValue SourceA, SourceB, SourceC;
13035 if (!EvaluateAsRValue(Info, E->getArg(0), SourceA) ||
13036 !EvaluateAsRValue(Info, E->getArg(1), SourceB) ||
13037 !EvaluateAsRValue(Info, E->getArg(2), SourceC))
13038 return false;
13039
13040 bool IsXor = E->getBuiltinCallee() ==
13041 clang::X86::BI__builtin_ia32_bmacxor16x16x16_v16hi ||
13042 E->getBuiltinCallee() ==
13043 clang::X86::BI__builtin_ia32_bmacxor16x16x16_v32hi;
13044
13045 unsigned SourceLen = SourceA.getVectorLength();
13046 assert(SourceLen % 16 == 0 && "BMM operates on 256-bit lanes of 16 x i16");
13047 auto *DestTy = E->getType()->castAs<VectorType>();
13048 QualType DestEltTy = DestTy->getElementType();
13049 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
13050
13051 SmallVector<APValue, 32> ResultElements(SourceLen);
13052 for (unsigned Lane = 0; Lane != SourceLen; Lane += 16) {
13053 for (unsigned I = 0; I != 16; ++I) {
13054 uint16_t A =
13055 (uint16_t)SourceA.getVectorElt(Lane + I).getInt().getZExtValue();
13056 uint16_t Dst =
13057 (uint16_t)SourceC.getVectorElt(Lane + I).getInt().getZExtValue();
13058 for (unsigned J = 0; J != 16; ++J) {
13059 // Seed the reduction with the accumulator bit, then fold in each
13060 // product term with the same operator (OR for vbmacor, XOR for
13061 // vbmacxor).
13062 unsigned Bit = (Dst >> J) & 1u;
13063 for (unsigned K = 0; K != 16; ++K) {
13064 uint16_t B = (uint16_t)SourceB.getVectorElt(Lane + K)
13065 .getInt()
13066 .getZExtValue();
13067 unsigned Product = ((A >> K) & 1u) & ((B >> J) & 1u);
13068 Bit = IsXor ? (Bit ^ Product) : (Bit | Product);
13069 }
13070 Dst = (Dst & ~(uint16_t(1) << J)) | (uint16_t(Bit) << J);
13071 }
13072 ResultElements[Lane + I] =
13073 APValue(APSInt(APInt(16, Dst), DestUnsigned));
13074 }
13075 }
13076 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13077 }
13078
13079 case clang::X86::BI__builtin_ia32_dbpsadbw128:
13080 case clang::X86::BI__builtin_ia32_dbpsadbw256:
13081 case clang::X86::BI__builtin_ia32_dbpsadbw512: {
13082 APValue SourceA, SourceB, SourceImm;
13083 if (!EvaluateAsRValue(Info, E->getArg(0), SourceA) ||
13084 !EvaluateAsRValue(Info, E->getArg(1), SourceB) ||
13085 !EvaluateAsRValue(Info, E->getArg(2), SourceImm))
13086 return false;
13087
13088 unsigned SourceLen = SourceA.getVectorLength();
13089 constexpr unsigned LaneSize = 16; // 128-bit lane = 16 bytes
13090 unsigned Imm = SourceImm.getInt().getZExtValue();
13091
13092 auto *DestTy = E->getType()->castAs<VectorType>();
13093 QualType DestEltTy = DestTy->getElementType();
13094 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
13095 SmallVector<APValue, 32> ResultElements;
13096 ResultElements.reserve(SourceLen / 2);
13097
13098 // Phase 1: Shuffle SourceB using all four 2-bit fields of imm8.
13099 // Within each 128-bit lane, for group j (0..3), select a 4-byte block
13100 // from SourceB based on bits [2*j+1:2*j] of imm8.
13101 SmallVector<uint8_t, 64> Shuffled(SourceLen);
13102 for (unsigned I = 0; I < SourceLen; I += LaneSize) {
13103 for (unsigned J = 0; J < 4; ++J) {
13104 unsigned Part = (Imm >> (2 * J)) & 3;
13105 for (unsigned K = 0; K < 4; ++K) {
13106 Shuffled[I + 4 * J + K] = static_cast<uint8_t>(
13107 SourceB.getVectorElt(I + 4 * Part + K).getInt().getZExtValue());
13108 }
13109 }
13110 }
13111
13112 // Phase 2: Sliding SAD computation.
13113 // For every group of 4 output u16 values, compute absolute differences
13114 // using overlapping windows into SourceA and the shuffled array.
13115 unsigned Size = SourceLen / 2; // number of output u16 elements
13116 for (unsigned I = 0; I < Size; I += 4) {
13117 unsigned Sad[4] = {0, 0, 0, 0};
13118 for (unsigned J = 0; J < 4; ++J) {
13119 uint8_t A1 = static_cast<uint8_t>(
13120 SourceA.getVectorElt(2 * I + J).getInt().getZExtValue());
13121 uint8_t A2 = static_cast<uint8_t>(
13122 SourceA.getVectorElt(2 * I + J + 4).getInt().getZExtValue());
13123 uint8_t B0 = Shuffled[2 * I + J];
13124 uint8_t B1 = Shuffled[2 * I + J + 1];
13125 uint8_t B2 = Shuffled[2 * I + J + 2];
13126 uint8_t B3 = Shuffled[2 * I + J + 3];
13127 Sad[0] += (A1 > B0) ? (A1 - B0) : (B0 - A1);
13128 Sad[1] += (A1 > B1) ? (A1 - B1) : (B1 - A1);
13129 Sad[2] += (A2 > B2) ? (A2 - B2) : (B2 - A2);
13130 Sad[3] += (A2 > B3) ? (A2 - B3) : (B3 - A2);
13131 }
13132 for (unsigned R = 0; R < 4; ++R)
13133 ResultElements.push_back(
13134 APValue(APSInt(APInt(16, Sad[R]), DestUnsigned)));
13135 }
13136
13137 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13138 }
13139
13140 case clang::X86::BI__builtin_ia32_mpsadbw128:
13141 case clang::X86::BI__builtin_ia32_mpsadbw256: {
13142 APValue SourceA, SourceB;
13143 APSInt SourceImm;
13144 if (!EvaluateVector(E->getArg(0), SourceA, Info) ||
13145 !EvaluateVector(E->getArg(1), SourceB, Info) ||
13146 !EvaluateInteger(E->getArg(2), SourceImm, Info))
13147 return false;
13148 unsigned SourceLen = SourceA.getVectorLength();
13149 constexpr unsigned LaneSize = 16;
13150 assert((SourceLen == LaneSize || SourceLen == 2 * LaneSize) &&
13151 "MPSADBW operates on 128-bit or 256-bit vectors");
13152 unsigned NumLanes = SourceLen / LaneSize;
13153 unsigned Imm = SourceImm.getZExtValue();
13154
13155 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
13156 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
13157 SmallVector<APValue, 16> ResultElements;
13158 ResultElements.reserve(SourceLen / 2);
13159
13160 for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
13161 unsigned Ctrl = (Imm >> (3 * Lane)) & 0x7;
13162 unsigned AOff = ((Ctrl >> 2) & 1) * 4;
13163 unsigned BOff = (Ctrl & 3) * 4;
13164 for (unsigned J = 0; J != 8; ++J) {
13165 uint16_t Sad = 0;
13166 for (unsigned K = 0; K != 4; ++K) {
13167 uint8_t A = static_cast<uint8_t>(
13168 SourceA.getVectorElt(Lane * LaneSize + AOff + J + K)
13169 .getInt()
13170 .getZExtValue());
13171 uint8_t B = static_cast<uint8_t>(
13172 SourceB.getVectorElt(Lane * LaneSize + BOff + K)
13173 .getInt()
13174 .getZExtValue());
13175 Sad += (A > B) ? (A - B) : (B - A);
13176 }
13177 ResultElements.push_back(APValue(APSInt(APInt(16, Sad), DestUnsigned)));
13178 }
13179 }
13180 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13181 }
13182
13183 case clang::X86::BI__builtin_ia32_pmulhuw128:
13184 case clang::X86::BI__builtin_ia32_pmulhuw256:
13185 case clang::X86::BI__builtin_ia32_pmulhuw512:
13186 return EvaluateBinOpExpr(llvm::APIntOps::mulhu);
13187
13188 case clang::X86::BI__builtin_ia32_pmulhw128:
13189 case clang::X86::BI__builtin_ia32_pmulhw256:
13190 case clang::X86::BI__builtin_ia32_pmulhw512:
13191 return EvaluateBinOpExpr(llvm::APIntOps::mulhs);
13192
13193 case clang::X86::BI__builtin_ia32_psllv2di:
13194 case clang::X86::BI__builtin_ia32_psllv4di:
13195 case clang::X86::BI__builtin_ia32_psllv4si:
13196 case clang::X86::BI__builtin_ia32_psllv8di:
13197 case clang::X86::BI__builtin_ia32_psllv8hi:
13198 case clang::X86::BI__builtin_ia32_psllv8si:
13199 case clang::X86::BI__builtin_ia32_psllv16hi:
13200 case clang::X86::BI__builtin_ia32_psllv16si:
13201 case clang::X86::BI__builtin_ia32_psllv32hi:
13202 case clang::X86::BI__builtin_ia32_psllwi128:
13203 case clang::X86::BI__builtin_ia32_pslldi128:
13204 case clang::X86::BI__builtin_ia32_psllqi128:
13205 case clang::X86::BI__builtin_ia32_psllwi256:
13206 case clang::X86::BI__builtin_ia32_pslldi256:
13207 case clang::X86::BI__builtin_ia32_psllqi256:
13208 case clang::X86::BI__builtin_ia32_psllwi512:
13209 case clang::X86::BI__builtin_ia32_pslldi512:
13210 case clang::X86::BI__builtin_ia32_psllqi512:
13211 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
13212 if (RHS.uge(LHS.getBitWidth())) {
13213 return APInt::getZero(LHS.getBitWidth());
13214 }
13215 return LHS.shl(RHS.getZExtValue());
13216 });
13217
13218 case clang::X86::BI__builtin_ia32_psrav4si:
13219 case clang::X86::BI__builtin_ia32_psrav8di:
13220 case clang::X86::BI__builtin_ia32_psrav8hi:
13221 case clang::X86::BI__builtin_ia32_psrav8si:
13222 case clang::X86::BI__builtin_ia32_psrav16hi:
13223 case clang::X86::BI__builtin_ia32_psrav16si:
13224 case clang::X86::BI__builtin_ia32_psrav32hi:
13225 case clang::X86::BI__builtin_ia32_psravq128:
13226 case clang::X86::BI__builtin_ia32_psravq256:
13227 case clang::X86::BI__builtin_ia32_psrawi128:
13228 case clang::X86::BI__builtin_ia32_psradi128:
13229 case clang::X86::BI__builtin_ia32_psraqi128:
13230 case clang::X86::BI__builtin_ia32_psrawi256:
13231 case clang::X86::BI__builtin_ia32_psradi256:
13232 case clang::X86::BI__builtin_ia32_psraqi256:
13233 case clang::X86::BI__builtin_ia32_psrawi512:
13234 case clang::X86::BI__builtin_ia32_psradi512:
13235 case clang::X86::BI__builtin_ia32_psraqi512:
13236 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
13237 if (RHS.uge(LHS.getBitWidth())) {
13238 return LHS.ashr(LHS.getBitWidth() - 1);
13239 }
13240 return LHS.ashr(RHS.getZExtValue());
13241 });
13242
13243 case clang::X86::BI__builtin_ia32_psrlv2di:
13244 case clang::X86::BI__builtin_ia32_psrlv4di:
13245 case clang::X86::BI__builtin_ia32_psrlv4si:
13246 case clang::X86::BI__builtin_ia32_psrlv8di:
13247 case clang::X86::BI__builtin_ia32_psrlv8hi:
13248 case clang::X86::BI__builtin_ia32_psrlv8si:
13249 case clang::X86::BI__builtin_ia32_psrlv16hi:
13250 case clang::X86::BI__builtin_ia32_psrlv16si:
13251 case clang::X86::BI__builtin_ia32_psrlv32hi:
13252 case clang::X86::BI__builtin_ia32_psrlwi128:
13253 case clang::X86::BI__builtin_ia32_psrldi128:
13254 case clang::X86::BI__builtin_ia32_psrlqi128:
13255 case clang::X86::BI__builtin_ia32_psrlwi256:
13256 case clang::X86::BI__builtin_ia32_psrldi256:
13257 case clang::X86::BI__builtin_ia32_psrlqi256:
13258 case clang::X86::BI__builtin_ia32_psrlwi512:
13259 case clang::X86::BI__builtin_ia32_psrldi512:
13260 case clang::X86::BI__builtin_ia32_psrlqi512:
13261 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
13262 if (RHS.uge(LHS.getBitWidth())) {
13263 return APInt::getZero(LHS.getBitWidth());
13264 }
13265 return LHS.lshr(RHS.getZExtValue());
13266 });
13267 case X86::BI__builtin_ia32_packsswb128:
13268 case X86::BI__builtin_ia32_packsswb256:
13269 case X86::BI__builtin_ia32_packsswb512:
13270 case X86::BI__builtin_ia32_packssdw128:
13271 case X86::BI__builtin_ia32_packssdw256:
13272 case X86::BI__builtin_ia32_packssdw512:
13273 return evalPackBuiltin(E, Info, Result, [](const APSInt &Src) {
13274 return APSInt(Src).truncSSat(Src.getBitWidth() / 2);
13275 });
13276 case X86::BI__builtin_ia32_packusdw128:
13277 case X86::BI__builtin_ia32_packusdw256:
13278 case X86::BI__builtin_ia32_packusdw512:
13279 case X86::BI__builtin_ia32_packuswb128:
13280 case X86::BI__builtin_ia32_packuswb256:
13281 case X86::BI__builtin_ia32_packuswb512:
13282 return evalPackBuiltin(E, Info, Result, [](const APSInt &Src) {
13283 return APSInt(Src).truncSSatU(Src.getBitWidth() / 2);
13284 });
13285 case clang::X86::BI__builtin_ia32_selectss_128:
13286 return EvalSelectScalar(4);
13287 case clang::X86::BI__builtin_ia32_selectsd_128:
13288 return EvalSelectScalar(2);
13289 case clang::X86::BI__builtin_ia32_selectsh_128:
13290 case clang::X86::BI__builtin_ia32_selectsbf_128:
13291 return EvalSelectScalar(8);
13292 case clang::X86::BI__builtin_ia32_pmuldq128:
13293 case clang::X86::BI__builtin_ia32_pmuldq256:
13294 case clang::X86::BI__builtin_ia32_pmuldq512:
13295 case clang::X86::BI__builtin_ia32_pmuludq128:
13296 case clang::X86::BI__builtin_ia32_pmuludq256:
13297 case clang::X86::BI__builtin_ia32_pmuludq512: {
13298 APValue SourceLHS, SourceRHS;
13299 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
13300 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
13301 return false;
13302
13303 unsigned SourceLen = SourceLHS.getVectorLength();
13304 SmallVector<APValue, 4> ResultElements;
13305 ResultElements.reserve(SourceLen / 2);
13306
13307 for (unsigned EltNum = 0; EltNum < SourceLen; EltNum += 2) {
13308 APSInt LHS = SourceLHS.getVectorElt(EltNum).getInt();
13309 APSInt RHS = SourceRHS.getVectorElt(EltNum).getInt();
13310
13311 switch (BuiltinOp) {
13312 case clang::X86::BI__builtin_ia32_pmuludq128:
13313 case clang::X86::BI__builtin_ia32_pmuludq256:
13314 case clang::X86::BI__builtin_ia32_pmuludq512:
13315 ResultElements.push_back(
13316 APValue(APSInt(llvm::APIntOps::muluExtended(LHS, RHS), true)));
13317 break;
13318 case clang::X86::BI__builtin_ia32_pmuldq128:
13319 case clang::X86::BI__builtin_ia32_pmuldq256:
13320 case clang::X86::BI__builtin_ia32_pmuldq512:
13321 ResultElements.push_back(
13322 APValue(APSInt(llvm::APIntOps::mulsExtended(LHS, RHS), false)));
13323 break;
13324 }
13325 }
13326
13327 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13328 }
13329
13330 case X86::BI__builtin_ia32_vpmadd52luq128:
13331 case X86::BI__builtin_ia32_vpmadd52luq256:
13332 case X86::BI__builtin_ia32_vpmadd52luq512: {
13333 APValue A, B, C;
13334 if (!EvaluateAsRValue(Info, E->getArg(0), A) ||
13335 !EvaluateAsRValue(Info, E->getArg(1), B) ||
13336 !EvaluateAsRValue(Info, E->getArg(2), C))
13337 return false;
13338
13339 unsigned ALen = A.getVectorLength();
13340 SmallVector<APValue, 4> ResultElements;
13341 ResultElements.reserve(ALen);
13342
13343 for (unsigned EltNum = 0; EltNum < ALen; EltNum += 1) {
13344 APInt AElt = A.getVectorElt(EltNum).getInt();
13345 APInt BElt = B.getVectorElt(EltNum).getInt().trunc(52);
13346 APInt CElt = C.getVectorElt(EltNum).getInt().trunc(52);
13347 APSInt ResElt(AElt + (BElt * CElt).zext(64), false);
13348 ResultElements.push_back(APValue(ResElt));
13349 }
13350
13351 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13352 }
13353 case X86::BI__builtin_ia32_vpmadd52huq128:
13354 case X86::BI__builtin_ia32_vpmadd52huq256:
13355 case X86::BI__builtin_ia32_vpmadd52huq512: {
13356 APValue A, B, C;
13357 if (!EvaluateAsRValue(Info, E->getArg(0), A) ||
13358 !EvaluateAsRValue(Info, E->getArg(1), B) ||
13359 !EvaluateAsRValue(Info, E->getArg(2), C))
13360 return false;
13361
13362 unsigned ALen = A.getVectorLength();
13363 SmallVector<APValue, 4> ResultElements;
13364 ResultElements.reserve(ALen);
13365
13366 for (unsigned EltNum = 0; EltNum < ALen; EltNum += 1) {
13367 APInt AElt = A.getVectorElt(EltNum).getInt();
13368 APInt BElt = B.getVectorElt(EltNum).getInt().trunc(52);
13369 APInt CElt = C.getVectorElt(EltNum).getInt().trunc(52);
13370 APSInt ResElt(AElt + llvm::APIntOps::mulhu(BElt, CElt).zext(64), false);
13371 ResultElements.push_back(APValue(ResElt));
13372 }
13373
13374 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13375 }
13376
13377 case clang::X86::BI__builtin_ia32_vprotbi:
13378 case clang::X86::BI__builtin_ia32_vprotdi:
13379 case clang::X86::BI__builtin_ia32_vprotqi:
13380 case clang::X86::BI__builtin_ia32_vprotwi:
13381 case clang::X86::BI__builtin_ia32_prold128:
13382 case clang::X86::BI__builtin_ia32_prold256:
13383 case clang::X86::BI__builtin_ia32_prold512:
13384 case clang::X86::BI__builtin_ia32_prolq128:
13385 case clang::X86::BI__builtin_ia32_prolq256:
13386 case clang::X86::BI__builtin_ia32_prolq512:
13387 return EvaluateBinOpExpr(
13388 [](const APSInt &LHS, const APSInt &RHS) { return LHS.rotl(RHS); });
13389
13390 case clang::X86::BI__builtin_ia32_prord128:
13391 case clang::X86::BI__builtin_ia32_prord256:
13392 case clang::X86::BI__builtin_ia32_prord512:
13393 case clang::X86::BI__builtin_ia32_prorq128:
13394 case clang::X86::BI__builtin_ia32_prorq256:
13395 case clang::X86::BI__builtin_ia32_prorq512:
13396 return EvaluateBinOpExpr(
13397 [](const APSInt &LHS, const APSInt &RHS) { return LHS.rotr(RHS); });
13398
13399 case Builtin::BI__builtin_elementwise_max:
13400 case Builtin::BI__builtin_elementwise_min: {
13401 APValue SourceLHS, SourceRHS;
13402 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
13403 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
13404 return false;
13405
13406 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
13407
13408 if (!DestEltTy->isIntegerType())
13409 return false;
13410
13411 unsigned SourceLen = SourceLHS.getVectorLength();
13412 SmallVector<APValue, 4> ResultElements;
13413 ResultElements.reserve(SourceLen);
13414
13415 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
13416 APSInt LHS = SourceLHS.getVectorElt(EltNum).getInt();
13417 APSInt RHS = SourceRHS.getVectorElt(EltNum).getInt();
13418 switch (BuiltinOp) {
13419 case Builtin::BI__builtin_elementwise_max:
13420 ResultElements.push_back(
13421 APValue(APSInt(std::max(LHS, RHS),
13422 DestEltTy->isUnsignedIntegerOrEnumerationType())));
13423 break;
13424 case Builtin::BI__builtin_elementwise_min:
13425 ResultElements.push_back(
13426 APValue(APSInt(std::min(LHS, RHS),
13427 DestEltTy->isUnsignedIntegerOrEnumerationType())));
13428 break;
13429 }
13430 }
13431
13432 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13433 }
13434 case X86::BI__builtin_ia32_vpshldd128:
13435 case X86::BI__builtin_ia32_vpshldd256:
13436 case X86::BI__builtin_ia32_vpshldd512:
13437 case X86::BI__builtin_ia32_vpshldq128:
13438 case X86::BI__builtin_ia32_vpshldq256:
13439 case X86::BI__builtin_ia32_vpshldq512:
13440 case X86::BI__builtin_ia32_vpshldw128:
13441 case X86::BI__builtin_ia32_vpshldw256:
13442 case X86::BI__builtin_ia32_vpshldw512: {
13443 APValue SourceHi, SourceLo, SourceAmt;
13444 if (!EvaluateAsRValue(Info, E->getArg(0), SourceHi) ||
13445 !EvaluateAsRValue(Info, E->getArg(1), SourceLo) ||
13446 !EvaluateAsRValue(Info, E->getArg(2), SourceAmt))
13447 return false;
13448
13449 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
13450 unsigned SourceLen = SourceHi.getVectorLength();
13451 SmallVector<APValue, 32> ResultElements;
13452 ResultElements.reserve(SourceLen);
13453
13454 APInt Amt = SourceAmt.getInt();
13455 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
13456 APInt Hi = SourceHi.getVectorElt(EltNum).getInt();
13457 APInt Lo = SourceLo.getVectorElt(EltNum).getInt();
13458 APInt R = llvm::APIntOps::fshl(Hi, Lo, Amt);
13459 ResultElements.push_back(
13461 }
13462
13463 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13464 }
13465 case X86::BI__builtin_ia32_vpshrdd128:
13466 case X86::BI__builtin_ia32_vpshrdd256:
13467 case X86::BI__builtin_ia32_vpshrdd512:
13468 case X86::BI__builtin_ia32_vpshrdq128:
13469 case X86::BI__builtin_ia32_vpshrdq256:
13470 case X86::BI__builtin_ia32_vpshrdq512:
13471 case X86::BI__builtin_ia32_vpshrdw128:
13472 case X86::BI__builtin_ia32_vpshrdw256:
13473 case X86::BI__builtin_ia32_vpshrdw512: {
13474 // NOTE: Reversed Hi/Lo operands.
13475 APValue SourceHi, SourceLo, SourceAmt;
13476 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLo) ||
13477 !EvaluateAsRValue(Info, E->getArg(1), SourceHi) ||
13478 !EvaluateAsRValue(Info, E->getArg(2), SourceAmt))
13479 return false;
13480
13481 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
13482 unsigned SourceLen = SourceHi.getVectorLength();
13483 SmallVector<APValue, 32> ResultElements;
13484 ResultElements.reserve(SourceLen);
13485
13486 APInt Amt = SourceAmt.getInt();
13487 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
13488 APInt Hi = SourceHi.getVectorElt(EltNum).getInt();
13489 APInt Lo = SourceLo.getVectorElt(EltNum).getInt();
13490 APInt R = llvm::APIntOps::fshr(Hi, Lo, Amt);
13491 ResultElements.push_back(
13493 }
13494
13495 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13496 }
13497 case X86::BI__builtin_ia32_compressdf128_mask:
13498 case X86::BI__builtin_ia32_compressdf256_mask:
13499 case X86::BI__builtin_ia32_compressdf512_mask:
13500 case X86::BI__builtin_ia32_compressdi128_mask:
13501 case X86::BI__builtin_ia32_compressdi256_mask:
13502 case X86::BI__builtin_ia32_compressdi512_mask:
13503 case X86::BI__builtin_ia32_compresshi128_mask:
13504 case X86::BI__builtin_ia32_compresshi256_mask:
13505 case X86::BI__builtin_ia32_compresshi512_mask:
13506 case X86::BI__builtin_ia32_compressqi128_mask:
13507 case X86::BI__builtin_ia32_compressqi256_mask:
13508 case X86::BI__builtin_ia32_compressqi512_mask:
13509 case X86::BI__builtin_ia32_compresssf128_mask:
13510 case X86::BI__builtin_ia32_compresssf256_mask:
13511 case X86::BI__builtin_ia32_compresssf512_mask:
13512 case X86::BI__builtin_ia32_compresssi128_mask:
13513 case X86::BI__builtin_ia32_compresssi256_mask:
13514 case X86::BI__builtin_ia32_compresssi512_mask: {
13515 APValue Source, Passthru;
13516 if (!EvaluateAsRValue(Info, E->getArg(0), Source) ||
13517 !EvaluateAsRValue(Info, E->getArg(1), Passthru))
13518 return false;
13519 APSInt Mask;
13520 if (!EvaluateInteger(E->getArg(2), Mask, Info))
13521 return false;
13522
13523 unsigned NumElts = Source.getVectorLength();
13524 SmallVector<APValue, 64> ResultElements;
13525 ResultElements.reserve(NumElts);
13526
13527 for (unsigned I = 0; I != NumElts; ++I) {
13528 if (Mask[I])
13529 ResultElements.push_back(Source.getVectorElt(I));
13530 }
13531 for (unsigned I = ResultElements.size(); I != NumElts; ++I) {
13532 ResultElements.push_back(Passthru.getVectorElt(I));
13533 }
13534
13535 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13536 }
13537 case X86::BI__builtin_ia32_expanddf128_mask:
13538 case X86::BI__builtin_ia32_expanddf256_mask:
13539 case X86::BI__builtin_ia32_expanddf512_mask:
13540 case X86::BI__builtin_ia32_expanddi128_mask:
13541 case X86::BI__builtin_ia32_expanddi256_mask:
13542 case X86::BI__builtin_ia32_expanddi512_mask:
13543 case X86::BI__builtin_ia32_expandhi128_mask:
13544 case X86::BI__builtin_ia32_expandhi256_mask:
13545 case X86::BI__builtin_ia32_expandhi512_mask:
13546 case X86::BI__builtin_ia32_expandqi128_mask:
13547 case X86::BI__builtin_ia32_expandqi256_mask:
13548 case X86::BI__builtin_ia32_expandqi512_mask:
13549 case X86::BI__builtin_ia32_expandsf128_mask:
13550 case X86::BI__builtin_ia32_expandsf256_mask:
13551 case X86::BI__builtin_ia32_expandsf512_mask:
13552 case X86::BI__builtin_ia32_expandsi128_mask:
13553 case X86::BI__builtin_ia32_expandsi256_mask:
13554 case X86::BI__builtin_ia32_expandsi512_mask: {
13555 APValue Source, Passthru;
13556 if (!EvaluateAsRValue(Info, E->getArg(0), Source) ||
13557 !EvaluateAsRValue(Info, E->getArg(1), Passthru))
13558 return false;
13559 APSInt Mask;
13560 if (!EvaluateInteger(E->getArg(2), Mask, Info))
13561 return false;
13562
13563 unsigned NumElts = Source.getVectorLength();
13564 SmallVector<APValue, 64> ResultElements;
13565 ResultElements.reserve(NumElts);
13566
13567 unsigned SourceIdx = 0;
13568 for (unsigned I = 0; I != NumElts; ++I) {
13569 if (Mask[I])
13570 ResultElements.push_back(Source.getVectorElt(SourceIdx++));
13571 else
13572 ResultElements.push_back(Passthru.getVectorElt(I));
13573 }
13574 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13575 }
13576 case X86::BI__builtin_ia32_vpconflictsi_128:
13577 case X86::BI__builtin_ia32_vpconflictsi_256:
13578 case X86::BI__builtin_ia32_vpconflictsi_512:
13579 case X86::BI__builtin_ia32_vpconflictdi_128:
13580 case X86::BI__builtin_ia32_vpconflictdi_256:
13581 case X86::BI__builtin_ia32_vpconflictdi_512: {
13582 APValue Source;
13583
13584 if (!EvaluateAsRValue(Info, E->getArg(0), Source))
13585 return false;
13586
13587 unsigned SourceLen = Source.getVectorLength();
13588 SmallVector<APValue, 32> ResultElements;
13589 ResultElements.reserve(SourceLen);
13590
13591 const auto *VecT = E->getType()->castAs<VectorType>();
13592 bool DestUnsigned =
13593 VecT->getElementType()->isUnsignedIntegerOrEnumerationType();
13594
13595 for (unsigned I = 0; I != SourceLen; ++I) {
13596 const APValue &EltI = Source.getVectorElt(I);
13597
13598 APInt ConflictMask(EltI.getInt().getBitWidth(), 0);
13599 for (unsigned J = 0; J != I; ++J) {
13600 const APValue &EltJ = Source.getVectorElt(J);
13601 ConflictMask.setBitVal(J, EltI.getInt() == EltJ.getInt());
13602 }
13603 ResultElements.push_back(APValue(APSInt(ConflictMask, DestUnsigned)));
13604 }
13605 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13606 }
13607 case X86::BI__builtin_ia32_blendpd:
13608 case X86::BI__builtin_ia32_blendpd256:
13609 case X86::BI__builtin_ia32_blendps:
13610 case X86::BI__builtin_ia32_blendps256:
13611 case X86::BI__builtin_ia32_pblendw128:
13612 case X86::BI__builtin_ia32_pblendw256:
13613 case X86::BI__builtin_ia32_pblendd128:
13614 case X86::BI__builtin_ia32_pblendd256: {
13615 APValue SourceF, SourceT, SourceC;
13616 if (!EvaluateAsRValue(Info, E->getArg(0), SourceF) ||
13617 !EvaluateAsRValue(Info, E->getArg(1), SourceT) ||
13618 !EvaluateAsRValue(Info, E->getArg(2), SourceC))
13619 return false;
13620
13621 const APInt &C = SourceC.getInt();
13622 unsigned SourceLen = SourceF.getVectorLength();
13623 SmallVector<APValue, 32> ResultElements;
13624 ResultElements.reserve(SourceLen);
13625 for (unsigned EltNum = 0; EltNum != SourceLen; ++EltNum) {
13626 const APValue &F = SourceF.getVectorElt(EltNum);
13627 const APValue &T = SourceT.getVectorElt(EltNum);
13628 ResultElements.push_back(C[EltNum % 8] ? T : F);
13629 }
13630
13631 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13632 }
13633
13634 case X86::BI__builtin_ia32_psignb128:
13635 case X86::BI__builtin_ia32_psignb256:
13636 case X86::BI__builtin_ia32_psignw128:
13637 case X86::BI__builtin_ia32_psignw256:
13638 case X86::BI__builtin_ia32_psignd128:
13639 case X86::BI__builtin_ia32_psignd256:
13640 return EvaluateBinOpExpr([](const APInt &AElem, const APInt &BElem) {
13641 if (BElem.isZero())
13642 return APInt::getZero(AElem.getBitWidth());
13643 if (BElem.isNegative())
13644 return -AElem;
13645 return AElem;
13646 });
13647
13648 case X86::BI__builtin_ia32_blendvpd:
13649 case X86::BI__builtin_ia32_blendvpd256:
13650 case X86::BI__builtin_ia32_blendvps:
13651 case X86::BI__builtin_ia32_blendvps256:
13652 case X86::BI__builtin_ia32_pblendvb128:
13653 case X86::BI__builtin_ia32_pblendvb256: {
13654 // SSE blendv by mask signbit: "Result = C[] < 0 ? T[] : F[]".
13655 APValue SourceF, SourceT, SourceC;
13656 if (!EvaluateAsRValue(Info, E->getArg(0), SourceF) ||
13657 !EvaluateAsRValue(Info, E->getArg(1), SourceT) ||
13658 !EvaluateAsRValue(Info, E->getArg(2), SourceC))
13659 return false;
13660
13661 unsigned SourceLen = SourceF.getVectorLength();
13662 SmallVector<APValue, 32> ResultElements;
13663 ResultElements.reserve(SourceLen);
13664
13665 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
13666 const APValue &F = SourceF.getVectorElt(EltNum);
13667 const APValue &T = SourceT.getVectorElt(EltNum);
13668 const APValue &C = SourceC.getVectorElt(EltNum);
13669 APInt M = C.isInt() ? (APInt)C.getInt() : C.getFloat().bitcastToAPInt();
13670 ResultElements.push_back(M.isNegative() ? T : F);
13671 }
13672
13673 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13674 }
13675 case X86::BI__builtin_ia32_selectb_128:
13676 case X86::BI__builtin_ia32_selectb_256:
13677 case X86::BI__builtin_ia32_selectb_512:
13678 case X86::BI__builtin_ia32_selectw_128:
13679 case X86::BI__builtin_ia32_selectw_256:
13680 case X86::BI__builtin_ia32_selectw_512:
13681 case X86::BI__builtin_ia32_selectd_128:
13682 case X86::BI__builtin_ia32_selectd_256:
13683 case X86::BI__builtin_ia32_selectd_512:
13684 case X86::BI__builtin_ia32_selectq_128:
13685 case X86::BI__builtin_ia32_selectq_256:
13686 case X86::BI__builtin_ia32_selectq_512:
13687 case X86::BI__builtin_ia32_selectph_128:
13688 case X86::BI__builtin_ia32_selectph_256:
13689 case X86::BI__builtin_ia32_selectph_512:
13690 case X86::BI__builtin_ia32_selectpbf_128:
13691 case X86::BI__builtin_ia32_selectpbf_256:
13692 case X86::BI__builtin_ia32_selectpbf_512:
13693 case X86::BI__builtin_ia32_selectps_128:
13694 case X86::BI__builtin_ia32_selectps_256:
13695 case X86::BI__builtin_ia32_selectps_512:
13696 case X86::BI__builtin_ia32_selectpd_128:
13697 case X86::BI__builtin_ia32_selectpd_256:
13698 case X86::BI__builtin_ia32_selectpd_512: {
13699 // AVX512 predicated move: "Result = Mask[] ? LHS[] : RHS[]".
13700 APValue SourceMask, SourceLHS, SourceRHS;
13701 if (!EvaluateAsRValue(Info, E->getArg(0), SourceMask) ||
13702 !EvaluateAsRValue(Info, E->getArg(1), SourceLHS) ||
13703 !EvaluateAsRValue(Info, E->getArg(2), SourceRHS))
13704 return false;
13705
13706 APSInt Mask = SourceMask.getInt();
13707 unsigned SourceLen = SourceLHS.getVectorLength();
13708 SmallVector<APValue, 4> ResultElements;
13709 ResultElements.reserve(SourceLen);
13710
13711 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
13712 const APValue &LHS = SourceLHS.getVectorElt(EltNum);
13713 const APValue &RHS = SourceRHS.getVectorElt(EltNum);
13714 ResultElements.push_back(Mask[EltNum] ? LHS : RHS);
13715 }
13716
13717 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13718 }
13719
13720 case X86::BI__builtin_ia32_cvtsd2ss: {
13721 APValue VecA, VecB;
13722 if (!EvaluateAsRValue(Info, E->getArg(0), VecA) ||
13723 !EvaluateAsRValue(Info, E->getArg(1), VecB))
13724 return false;
13725
13726 SmallVector<APValue, 4> Elements;
13727
13728 APValue ResultVal;
13729 if (!ConvertDoubleToFloatStrict(Info, E, VecB.getVectorElt(0).getFloat(),
13730 ResultVal))
13731 return false;
13732
13733 Elements.push_back(ResultVal);
13734
13735 unsigned NumEltsA = VecA.getVectorLength();
13736 for (unsigned I = 1; I < NumEltsA; ++I) {
13737 Elements.push_back(VecA.getVectorElt(I));
13738 }
13739
13740 return Success(Elements, E);
13741 }
13742 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: {
13743 APValue VecA, VecB, VecSrc, MaskValue;
13744
13745 if (!EvaluateAsRValue(Info, E->getArg(0), VecA) ||
13746 !EvaluateAsRValue(Info, E->getArg(1), VecB) ||
13747 !EvaluateAsRValue(Info, E->getArg(2), VecSrc) ||
13748 !EvaluateAsRValue(Info, E->getArg(3), MaskValue))
13749 return false;
13750
13751 unsigned Mask = MaskValue.getInt().getZExtValue();
13752 SmallVector<APValue, 4> Elements;
13753
13754 if (Mask & 1) {
13755 APValue ResultVal;
13756 if (!ConvertDoubleToFloatStrict(Info, E, VecB.getVectorElt(0).getFloat(),
13757 ResultVal))
13758 return false;
13759 Elements.push_back(ResultVal);
13760 } else {
13761 Elements.push_back(VecSrc.getVectorElt(0));
13762 }
13763
13764 unsigned NumEltsA = VecA.getVectorLength();
13765 for (unsigned I = 1; I < NumEltsA; ++I) {
13766 Elements.push_back(VecA.getVectorElt(I));
13767 }
13768
13769 return Success(Elements, E);
13770 }
13771 case X86::BI__builtin_ia32_cvtpd2ps:
13772 case X86::BI__builtin_ia32_cvtpd2ps256:
13773 case X86::BI__builtin_ia32_cvtpd2ps_mask:
13774 case X86::BI__builtin_ia32_cvtpd2ps512_mask: {
13775
13776 const auto BuiltinID = BuiltinOp;
13777 bool IsMasked = (BuiltinID == X86::BI__builtin_ia32_cvtpd2ps_mask ||
13778 BuiltinID == X86::BI__builtin_ia32_cvtpd2ps512_mask);
13779
13780 APValue InputValue;
13781 if (!EvaluateAsRValue(Info, E->getArg(0), InputValue))
13782 return false;
13783
13784 APValue MergeValue;
13785 unsigned Mask = 0xFFFFFFFF;
13786 bool NeedsMerge = false;
13787 if (IsMasked) {
13788 APValue MaskValue;
13789 if (!EvaluateAsRValue(Info, E->getArg(2), MaskValue))
13790 return false;
13791 Mask = MaskValue.getInt().getZExtValue();
13792 auto NumEltsResult = E->getType()->getAs<VectorType>()->getNumElements();
13793 for (unsigned I = 0; I < NumEltsResult; ++I) {
13794 if (!((Mask >> I) & 1)) {
13795 NeedsMerge = true;
13796 break;
13797 }
13798 }
13799 if (NeedsMerge) {
13800 if (!EvaluateAsRValue(Info, E->getArg(1), MergeValue))
13801 return false;
13802 }
13803 }
13804
13805 unsigned NumEltsResult =
13806 E->getType()->getAs<VectorType>()->getNumElements();
13807 unsigned NumEltsInput = InputValue.getVectorLength();
13808 SmallVector<APValue, 8> Elements;
13809 for (unsigned I = 0; I < NumEltsResult; ++I) {
13810 if (IsMasked && !((Mask >> I) & 1)) {
13811 if (!NeedsMerge) {
13812 return false;
13813 }
13814 Elements.push_back(MergeValue.getVectorElt(I));
13815 continue;
13816 }
13817
13818 if (I >= NumEltsInput) {
13819 Elements.push_back(APValue(APFloat::getZero(APFloat::IEEEsingle())));
13820 continue;
13821 }
13822
13823 APValue ResultVal;
13825 Info, E, InputValue.getVectorElt(I).getFloat(), ResultVal))
13826 return false;
13827
13828 Elements.push_back(ResultVal);
13829 }
13830 return Success(Elements, E);
13831 }
13832
13833 case X86::BI__builtin_ia32_shufps:
13834 case X86::BI__builtin_ia32_shufps256:
13835 case X86::BI__builtin_ia32_shufps512: {
13836 APValue R;
13837 if (!evalShuffleGeneric(
13838 Info, E, R,
13839 [](unsigned DstIdx,
13840 unsigned ShuffleMask) -> std::pair<unsigned, int> {
13841 constexpr unsigned LaneBits = 128u;
13842 unsigned NumElemPerLane = LaneBits / 32;
13843 unsigned NumSelectableElems = NumElemPerLane / 2;
13844 unsigned BitsPerElem = 2;
13845 unsigned IndexMask = (1u << BitsPerElem) - 1;
13846 unsigned MaskBits = 8;
13847 unsigned Lane = DstIdx / NumElemPerLane;
13848 unsigned ElemInLane = DstIdx % NumElemPerLane;
13849 unsigned LaneOffset = Lane * NumElemPerLane;
13850 unsigned BitIndex = (DstIdx * BitsPerElem) % MaskBits;
13851 unsigned SrcIdx = (ElemInLane < NumSelectableElems) ? 0 : 1;
13852 unsigned Index = (ShuffleMask >> BitIndex) & IndexMask;
13853 return {SrcIdx, static_cast<int>(LaneOffset + Index)};
13854 }))
13855 return false;
13856 return Success(R, E);
13857 }
13858 case X86::BI__builtin_ia32_shufpd:
13859 case X86::BI__builtin_ia32_shufpd256:
13860 case X86::BI__builtin_ia32_shufpd512: {
13861 APValue R;
13862 if (!evalShuffleGeneric(
13863 Info, E, R,
13864 [](unsigned DstIdx,
13865 unsigned ShuffleMask) -> std::pair<unsigned, int> {
13866 constexpr unsigned LaneBits = 128u;
13867 unsigned NumElemPerLane = LaneBits / 64;
13868 unsigned NumSelectableElems = NumElemPerLane / 2;
13869 unsigned BitsPerElem = 1;
13870 unsigned IndexMask = (1u << BitsPerElem) - 1;
13871 unsigned MaskBits = 8;
13872 unsigned Lane = DstIdx / NumElemPerLane;
13873 unsigned ElemInLane = DstIdx % NumElemPerLane;
13874 unsigned LaneOffset = Lane * NumElemPerLane;
13875 unsigned BitIndex = (DstIdx * BitsPerElem) % MaskBits;
13876 unsigned SrcIdx = (ElemInLane < NumSelectableElems) ? 0 : 1;
13877 unsigned Index = (ShuffleMask >> BitIndex) & IndexMask;
13878 return {SrcIdx, static_cast<int>(LaneOffset + Index)};
13879 }))
13880 return false;
13881 return Success(R, E);
13882 }
13883 case X86::BI__builtin_ia32_insertps128: {
13884 APValue R;
13885 if (!evalShuffleGeneric(
13886 Info, E, R,
13887 [](unsigned DstIdx, unsigned Mask) -> std::pair<unsigned, int> {
13888 // Bits [3:0]: zero mask - if bit is set, zero this element
13889 if ((Mask & (1 << DstIdx)) != 0) {
13890 return {0, -1};
13891 }
13892 // Bits [7:6]: select element from source vector Y (0-3)
13893 // Bits [5:4]: select destination position (0-3)
13894 unsigned SrcElem = (Mask >> 6) & 0x3;
13895 unsigned DstElem = (Mask >> 4) & 0x3;
13896 if (DstIdx == DstElem) {
13897 // Insert element from source vector (B) at this position
13898 return {1, static_cast<int>(SrcElem)};
13899 } else {
13900 // Copy from destination vector (A)
13901 return {0, static_cast<int>(DstIdx)};
13902 }
13903 }))
13904 return false;
13905 return Success(R, E);
13906 }
13907 case X86::BI__builtin_ia32_pshufb128:
13908 case X86::BI__builtin_ia32_pshufb256:
13909 case X86::BI__builtin_ia32_pshufb512: {
13910 APValue R;
13911 if (!evalShuffleGeneric(
13912 Info, E, R,
13913 [](unsigned DstIdx,
13914 unsigned ShuffleMask) -> std::pair<unsigned, int> {
13915 uint8_t Ctlb = static_cast<uint8_t>(ShuffleMask);
13916 if (Ctlb & 0x80)
13917 return std::make_pair(0, -1);
13918
13919 unsigned LaneBase = (DstIdx / 16) * 16;
13920 unsigned SrcOffset = Ctlb & 0x0F;
13921 unsigned SrcIdx = LaneBase + SrcOffset;
13922 return std::make_pair(0, static_cast<int>(SrcIdx));
13923 }))
13924 return false;
13925 return Success(R, E);
13926 }
13927
13928 case X86::BI__builtin_ia32_pshuflw:
13929 case X86::BI__builtin_ia32_pshuflw256:
13930 case X86::BI__builtin_ia32_pshuflw512: {
13931 APValue R;
13932 if (!evalShuffleGeneric(
13933 Info, E, R,
13934 [](unsigned DstIdx, unsigned Mask) -> std::pair<unsigned, int> {
13935 constexpr unsigned LaneBits = 128u;
13936 constexpr unsigned ElemBits = 16u;
13937 constexpr unsigned LaneElts = LaneBits / ElemBits;
13938 constexpr unsigned HalfSize = 4;
13939 unsigned LaneBase = (DstIdx / LaneElts) * LaneElts;
13940 unsigned LaneIdx = DstIdx % LaneElts;
13941 if (LaneIdx < HalfSize) {
13942 unsigned Sel = (Mask >> (2 * LaneIdx)) & 0x3;
13943 return std::make_pair(0, static_cast<int>(LaneBase + Sel));
13944 }
13945 return std::make_pair(0, static_cast<int>(DstIdx));
13946 }))
13947 return false;
13948 return Success(R, E);
13949 }
13950
13951 case X86::BI__builtin_ia32_pshufhw:
13952 case X86::BI__builtin_ia32_pshufhw256:
13953 case X86::BI__builtin_ia32_pshufhw512: {
13954 APValue R;
13955 if (!evalShuffleGeneric(
13956 Info, E, R,
13957 [](unsigned DstIdx, unsigned Mask) -> std::pair<unsigned, int> {
13958 constexpr unsigned LaneBits = 128u;
13959 constexpr unsigned ElemBits = 16u;
13960 constexpr unsigned LaneElts = LaneBits / ElemBits;
13961 constexpr unsigned HalfSize = 4;
13962 unsigned LaneBase = (DstIdx / LaneElts) * LaneElts;
13963 unsigned LaneIdx = DstIdx % LaneElts;
13964 if (LaneIdx >= HalfSize) {
13965 unsigned Rel = LaneIdx - HalfSize;
13966 unsigned Sel = (Mask >> (2 * Rel)) & 0x3;
13967 return std::make_pair(
13968 0, static_cast<int>(LaneBase + HalfSize + Sel));
13969 }
13970 return std::make_pair(0, static_cast<int>(DstIdx));
13971 }))
13972 return false;
13973 return Success(R, E);
13974 }
13975
13976 case X86::BI__builtin_ia32_pshufd:
13977 case X86::BI__builtin_ia32_pshufd256:
13978 case X86::BI__builtin_ia32_pshufd512:
13979 case X86::BI__builtin_ia32_vpermilps:
13980 case X86::BI__builtin_ia32_vpermilps256:
13981 case X86::BI__builtin_ia32_vpermilps512: {
13982 APValue R;
13983 if (!evalShuffleGeneric(
13984 Info, E, R,
13985 [](unsigned DstIdx, unsigned Mask) -> std::pair<unsigned, int> {
13986 constexpr unsigned LaneBits = 128u;
13987 constexpr unsigned ElemBits = 32u;
13988 constexpr unsigned LaneElts = LaneBits / ElemBits;
13989 unsigned LaneBase = (DstIdx / LaneElts) * LaneElts;
13990 unsigned LaneIdx = DstIdx % LaneElts;
13991 unsigned Sel = (Mask >> (2 * LaneIdx)) & 0x3;
13992 return std::make_pair(0, static_cast<int>(LaneBase + Sel));
13993 }))
13994 return false;
13995 return Success(R, E);
13996 }
13997
13998 case X86::BI__builtin_ia32_vpermilvarpd:
13999 case X86::BI__builtin_ia32_vpermilvarpd256:
14000 case X86::BI__builtin_ia32_vpermilvarpd512: {
14001 APValue R;
14002 if (!evalShuffleGeneric(
14003 Info, E, R,
14004 [](unsigned DstIdx, unsigned Mask) -> std::pair<unsigned, int> {
14005 unsigned NumElemPerLane = 2;
14006 unsigned Lane = DstIdx / NumElemPerLane;
14007 unsigned Offset = Mask & 0b10 ? 1 : 0;
14008 return std::make_pair(
14009 0, static_cast<int>(Lane * NumElemPerLane + Offset));
14010 }))
14011 return false;
14012 return Success(R, E);
14013 }
14014
14015 case X86::BI__builtin_ia32_vpermilpd:
14016 case X86::BI__builtin_ia32_vpermilpd256:
14017 case X86::BI__builtin_ia32_vpermilpd512: {
14018 APValue R;
14019 if (!evalShuffleGeneric(Info, E, R, [](unsigned DstIdx, unsigned Control) {
14020 unsigned NumElemPerLane = 2;
14021 unsigned BitsPerElem = 1;
14022 unsigned MaskBits = 8;
14023 unsigned IndexMask = 0x1;
14024 unsigned Lane = DstIdx / NumElemPerLane;
14025 unsigned LaneOffset = Lane * NumElemPerLane;
14026 unsigned BitIndex = (DstIdx * BitsPerElem) % MaskBits;
14027 unsigned Index = (Control >> BitIndex) & IndexMask;
14028 return std::make_pair(0, static_cast<int>(LaneOffset + Index));
14029 }))
14030 return false;
14031 return Success(R, E);
14032 }
14033
14034 case X86::BI__builtin_ia32_permdf256:
14035 case X86::BI__builtin_ia32_permdi256: {
14036 APValue R;
14037 if (!evalShuffleGeneric(Info, E, R, [](unsigned DstIdx, unsigned Control) {
14038 // permute4x64 operates on 4 64-bit elements
14039 // For element i (0-3), extract bits [2*i+1:2*i] from Control
14040 unsigned Index = (Control >> (2 * DstIdx)) & 0x3;
14041 return std::make_pair(0, static_cast<int>(Index));
14042 }))
14043 return false;
14044 return Success(R, E);
14045 }
14046
14047 case X86::BI__builtin_ia32_vpermilvarps:
14048 case X86::BI__builtin_ia32_vpermilvarps256:
14049 case X86::BI__builtin_ia32_vpermilvarps512: {
14050 APValue R;
14051 if (!evalShuffleGeneric(
14052 Info, E, R,
14053 [](unsigned DstIdx, unsigned Mask) -> std::pair<unsigned, int> {
14054 unsigned NumElemPerLane = 4;
14055 unsigned Lane = DstIdx / NumElemPerLane;
14056 unsigned Offset = Mask & 0b11;
14057 return std::make_pair(
14058 0, static_cast<int>(Lane * NumElemPerLane + Offset));
14059 }))
14060 return false;
14061 return Success(R, E);
14062 }
14063
14064 case X86::BI__builtin_ia32_vpmultishiftqb128:
14065 case X86::BI__builtin_ia32_vpmultishiftqb256:
14066 case X86::BI__builtin_ia32_vpmultishiftqb512: {
14067 assert(E->getNumArgs() == 2);
14068
14069 APValue A, B;
14070 if (!Evaluate(A, Info, E->getArg(0)) || !Evaluate(B, Info, E->getArg(1)))
14071 return false;
14072
14073 assert(A.getVectorLength() == B.getVectorLength());
14074 unsigned NumBytesInQWord = 8;
14075 unsigned NumBitsInByte = 8;
14076 unsigned NumBytes = A.getVectorLength();
14077 unsigned NumQWords = NumBytes / NumBytesInQWord;
14079 Result.reserve(NumBytes);
14080
14081 for (unsigned QWordId = 0; QWordId != NumQWords; ++QWordId) {
14082 APInt BQWord(64, 0);
14083 for (unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
14084 unsigned Idx = QWordId * NumBytesInQWord + ByteIdx;
14085 uint64_t Byte = B.getVectorElt(Idx).getInt().getZExtValue();
14086 BQWord.insertBits(APInt(8, Byte & 0xFF), ByteIdx * NumBitsInByte);
14087 }
14088
14089 for (unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
14090 unsigned Idx = QWordId * NumBytesInQWord + ByteIdx;
14091 uint64_t Ctrl = A.getVectorElt(Idx).getInt().getZExtValue() & 0x3F;
14092
14093 APInt Byte(8, 0);
14094 for (unsigned BitIdx = 0; BitIdx != NumBitsInByte; ++BitIdx) {
14095 Byte.setBitVal(BitIdx, BQWord[(Ctrl + BitIdx) & 0x3F]);
14096 }
14097 Result.push_back(APValue(APSInt(Byte, /*isUnsigned*/ true)));
14098 }
14099 }
14100 return Success(APValue(Result.data(), Result.size()), E);
14101 }
14102
14103 case X86::BI__builtin_ia32_phminposuw128: {
14104 APValue Source;
14105 if (!Evaluate(Source, Info, E->getArg(0)))
14106 return false;
14107 unsigned SourceLen = Source.getVectorLength();
14108 const VectorType *VT = E->getArg(0)->getType()->castAs<VectorType>();
14109 QualType ElemQT = VT->getElementType();
14110 unsigned ElemBitWidth = Info.Ctx.getTypeSize(ElemQT);
14111
14112 APInt MinIndex(ElemBitWidth, 0);
14113 APInt MinVal = Source.getVectorElt(0).getInt();
14114 for (unsigned I = 1; I != SourceLen; ++I) {
14115 APInt Val = Source.getVectorElt(I).getInt();
14116 if (MinVal.ugt(Val)) {
14117 MinVal = Val;
14118 MinIndex = I;
14119 }
14120 }
14121
14122 bool ResultUnsigned = E->getCallReturnType(Info.Ctx)
14123 ->castAs<VectorType>()
14124 ->getElementType()
14125 ->isUnsignedIntegerOrEnumerationType();
14126
14128 Result.reserve(SourceLen);
14129 Result.emplace_back(APSInt(MinVal, ResultUnsigned));
14130 Result.emplace_back(APSInt(MinIndex, ResultUnsigned));
14131 for (unsigned I = 0; I != SourceLen - 2; ++I) {
14132 Result.emplace_back(APSInt(APInt(ElemBitWidth, 0), ResultUnsigned));
14133 }
14134 return Success(APValue(Result.data(), Result.size()), E);
14135 }
14136
14137 case X86::BI__builtin_ia32_psraq128:
14138 case X86::BI__builtin_ia32_psraq256:
14139 case X86::BI__builtin_ia32_psraq512:
14140 case X86::BI__builtin_ia32_psrad128:
14141 case X86::BI__builtin_ia32_psrad256:
14142 case X86::BI__builtin_ia32_psrad512:
14143 case X86::BI__builtin_ia32_psraw128:
14144 case X86::BI__builtin_ia32_psraw256:
14145 case X86::BI__builtin_ia32_psraw512: {
14146 APValue R;
14147 if (!evalShiftWithCount(
14148 Info, E, R,
14149 [](const APInt &Elt, uint64_t Count) { return Elt.ashr(Count); },
14150 [](const APInt &Elt, unsigned Width) {
14151 return Elt.ashr(Width - 1);
14152 }))
14153 return false;
14154 return Success(R, E);
14155 }
14156
14157 case X86::BI__builtin_ia32_psllq128:
14158 case X86::BI__builtin_ia32_psllq256:
14159 case X86::BI__builtin_ia32_psllq512:
14160 case X86::BI__builtin_ia32_pslld128:
14161 case X86::BI__builtin_ia32_pslld256:
14162 case X86::BI__builtin_ia32_pslld512:
14163 case X86::BI__builtin_ia32_psllw128:
14164 case X86::BI__builtin_ia32_psllw256:
14165 case X86::BI__builtin_ia32_psllw512: {
14166 APValue R;
14167 if (!evalShiftWithCount(
14168 Info, E, R,
14169 [](const APInt &Elt, uint64_t Count) { return Elt.shl(Count); },
14170 [](const APInt &Elt, unsigned Width) {
14171 return APInt::getZero(Width);
14172 }))
14173 return false;
14174 return Success(R, E);
14175 }
14176
14177 case X86::BI__builtin_ia32_psrlq128:
14178 case X86::BI__builtin_ia32_psrlq256:
14179 case X86::BI__builtin_ia32_psrlq512:
14180 case X86::BI__builtin_ia32_psrld128:
14181 case X86::BI__builtin_ia32_psrld256:
14182 case X86::BI__builtin_ia32_psrld512:
14183 case X86::BI__builtin_ia32_psrlw128:
14184 case X86::BI__builtin_ia32_psrlw256:
14185 case X86::BI__builtin_ia32_psrlw512: {
14186 APValue R;
14187 if (!evalShiftWithCount(
14188 Info, E, R,
14189 [](const APInt &Elt, uint64_t Count) { return Elt.lshr(Count); },
14190 [](const APInt &Elt, unsigned Width) {
14191 return APInt::getZero(Width);
14192 }))
14193 return false;
14194 return Success(R, E);
14195 }
14196
14197 case X86::BI__builtin_ia32_pternlogd128_mask:
14198 case X86::BI__builtin_ia32_pternlogd256_mask:
14199 case X86::BI__builtin_ia32_pternlogd512_mask:
14200 case X86::BI__builtin_ia32_pternlogq128_mask:
14201 case X86::BI__builtin_ia32_pternlogq256_mask:
14202 case X86::BI__builtin_ia32_pternlogq512_mask: {
14203 APValue AValue, BValue, CValue, ImmValue, UValue;
14204 if (!EvaluateAsRValue(Info, E->getArg(0), AValue) ||
14205 !EvaluateAsRValue(Info, E->getArg(1), BValue) ||
14206 !EvaluateAsRValue(Info, E->getArg(2), CValue) ||
14207 !EvaluateAsRValue(Info, E->getArg(3), ImmValue) ||
14208 !EvaluateAsRValue(Info, E->getArg(4), UValue))
14209 return false;
14210
14211 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
14212 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
14213 APInt Imm = ImmValue.getInt();
14214 APInt U = UValue.getInt();
14215 unsigned ResultLen = AValue.getVectorLength();
14216 SmallVector<APValue, 16> ResultElements;
14217 ResultElements.reserve(ResultLen);
14218
14219 for (unsigned EltNum = 0; EltNum < ResultLen; ++EltNum) {
14220 APInt ALane = AValue.getVectorElt(EltNum).getInt();
14221 APInt BLane = BValue.getVectorElt(EltNum).getInt();
14222 APInt CLane = CValue.getVectorElt(EltNum).getInt();
14223
14224 if (U[EltNum]) {
14225 unsigned BitWidth = ALane.getBitWidth();
14226 APInt ResLane(BitWidth, 0);
14227
14228 for (unsigned Bit = 0; Bit < BitWidth; ++Bit) {
14229 unsigned ABit = ALane[Bit];
14230 unsigned BBit = BLane[Bit];
14231 unsigned CBit = CLane[Bit];
14232
14233 unsigned Idx = (ABit << 2) | (BBit << 1) | CBit;
14234 ResLane.setBitVal(Bit, Imm[Idx]);
14235 }
14236 ResultElements.push_back(APValue(APSInt(ResLane, DestUnsigned)));
14237 } else {
14238 ResultElements.push_back(APValue(APSInt(ALane, DestUnsigned)));
14239 }
14240 }
14241 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
14242 }
14243 case X86::BI__builtin_ia32_pternlogd128_maskz:
14244 case X86::BI__builtin_ia32_pternlogd256_maskz:
14245 case X86::BI__builtin_ia32_pternlogd512_maskz:
14246 case X86::BI__builtin_ia32_pternlogq128_maskz:
14247 case X86::BI__builtin_ia32_pternlogq256_maskz:
14248 case X86::BI__builtin_ia32_pternlogq512_maskz: {
14249 APValue AValue, BValue, CValue, ImmValue, UValue;
14250 if (!EvaluateAsRValue(Info, E->getArg(0), AValue) ||
14251 !EvaluateAsRValue(Info, E->getArg(1), BValue) ||
14252 !EvaluateAsRValue(Info, E->getArg(2), CValue) ||
14253 !EvaluateAsRValue(Info, E->getArg(3), ImmValue) ||
14254 !EvaluateAsRValue(Info, E->getArg(4), UValue))
14255 return false;
14256
14257 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
14258 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
14259 APInt Imm = ImmValue.getInt();
14260 APInt U = UValue.getInt();
14261 unsigned ResultLen = AValue.getVectorLength();
14262 SmallVector<APValue, 16> ResultElements;
14263 ResultElements.reserve(ResultLen);
14264
14265 for (unsigned EltNum = 0; EltNum < ResultLen; ++EltNum) {
14266 APInt ALane = AValue.getVectorElt(EltNum).getInt();
14267 APInt BLane = BValue.getVectorElt(EltNum).getInt();
14268 APInt CLane = CValue.getVectorElt(EltNum).getInt();
14269
14270 unsigned BitWidth = ALane.getBitWidth();
14271 APInt ResLane(BitWidth, 0);
14272
14273 if (U[EltNum]) {
14274 for (unsigned Bit = 0; Bit < BitWidth; ++Bit) {
14275 unsigned ABit = ALane[Bit];
14276 unsigned BBit = BLane[Bit];
14277 unsigned CBit = CLane[Bit];
14278
14279 unsigned Idx = (ABit << 2) | (BBit << 1) | CBit;
14280 ResLane.setBitVal(Bit, Imm[Idx]);
14281 }
14282 }
14283 ResultElements.push_back(APValue(APSInt(ResLane, DestUnsigned)));
14284 }
14285 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
14286 }
14287
14288 case Builtin::BI__builtin_elementwise_clzg:
14289 case Builtin::BI__builtin_elementwise_ctzg: {
14290 APValue SourceLHS;
14291 std::optional<APValue> Fallback;
14292 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS))
14293 return false;
14294 if (E->getNumArgs() > 1) {
14295 APValue FallbackTmp;
14296 if (!EvaluateAsRValue(Info, E->getArg(1), FallbackTmp))
14297 return false;
14298 Fallback = FallbackTmp;
14299 }
14300
14301 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
14302 unsigned SourceLen = SourceLHS.getVectorLength();
14303 SmallVector<APValue, 4> ResultElements;
14304 ResultElements.reserve(SourceLen);
14305
14306 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
14307 APSInt LHS = SourceLHS.getVectorElt(EltNum).getInt();
14308 if (!LHS) {
14309 // Without a fallback, a zero element is undefined
14310 if (!Fallback) {
14311 Info.FFDiag(E, diag::note_constexpr_countzeroes_zero)
14312 << /*IsTrailing=*/(BuiltinOp ==
14313 Builtin::BI__builtin_elementwise_ctzg);
14314 return false;
14315 }
14316 ResultElements.push_back(Fallback->getVectorElt(EltNum));
14317 continue;
14318 }
14319 switch (BuiltinOp) {
14320 case Builtin::BI__builtin_elementwise_clzg:
14321 ResultElements.push_back(APValue(
14322 APSInt(APInt(Info.Ctx.getIntWidth(DestEltTy), LHS.countl_zero()),
14323 DestEltTy->isUnsignedIntegerOrEnumerationType())));
14324 break;
14325 case Builtin::BI__builtin_elementwise_ctzg:
14326 ResultElements.push_back(APValue(
14327 APSInt(APInt(Info.Ctx.getIntWidth(DestEltTy), LHS.countr_zero()),
14328 DestEltTy->isUnsignedIntegerOrEnumerationType())));
14329 break;
14330 }
14331 }
14332
14333 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
14334 }
14335
14336 case Builtin::BI__builtin_elementwise_fma: {
14337 APValue SourceX, SourceY, SourceZ;
14338 if (!EvaluateAsRValue(Info, E->getArg(0), SourceX) ||
14339 !EvaluateAsRValue(Info, E->getArg(1), SourceY) ||
14340 !EvaluateAsRValue(Info, E->getArg(2), SourceZ))
14341 return false;
14342
14343 unsigned SourceLen = SourceX.getVectorLength();
14344 SmallVector<APValue> ResultElements;
14345 ResultElements.reserve(SourceLen);
14346 llvm::RoundingMode RM = getActiveRoundingMode(getEvalInfo(), E);
14347 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
14348 const APFloat &X = SourceX.getVectorElt(EltNum).getFloat();
14349 const APFloat &Y = SourceY.getVectorElt(EltNum).getFloat();
14350 const APFloat &Z = SourceZ.getVectorElt(EltNum).getFloat();
14351 APFloat Result(X);
14352 (void)Result.fusedMultiplyAdd(Y, Z, RM);
14353 ResultElements.push_back(APValue(Result));
14354 }
14355 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
14356 }
14357
14358 case clang::X86::BI__builtin_ia32_phaddw128:
14359 case clang::X86::BI__builtin_ia32_phaddw256:
14360 case clang::X86::BI__builtin_ia32_phaddd128:
14361 case clang::X86::BI__builtin_ia32_phaddd256:
14362 case clang::X86::BI__builtin_ia32_phaddsw128:
14363 case clang::X86::BI__builtin_ia32_phaddsw256:
14364
14365 case clang::X86::BI__builtin_ia32_phsubw128:
14366 case clang::X86::BI__builtin_ia32_phsubw256:
14367 case clang::X86::BI__builtin_ia32_phsubd128:
14368 case clang::X86::BI__builtin_ia32_phsubd256:
14369 case clang::X86::BI__builtin_ia32_phsubsw128:
14370 case clang::X86::BI__builtin_ia32_phsubsw256: {
14371 APValue SourceLHS, SourceRHS;
14372 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
14373 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
14374 return false;
14375 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
14376 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
14377
14378 unsigned NumElts = SourceLHS.getVectorLength();
14379 unsigned EltBits = Info.Ctx.getIntWidth(DestEltTy);
14380 unsigned EltsPerLane = 128 / EltBits;
14381 SmallVector<APValue, 4> ResultElements;
14382 ResultElements.reserve(NumElts);
14383
14384 for (unsigned LaneStart = 0; LaneStart != NumElts;
14385 LaneStart += EltsPerLane) {
14386 for (unsigned I = 0; I != EltsPerLane; I += 2) {
14387 APSInt LHSA = SourceLHS.getVectorElt(LaneStart + I).getInt();
14388 APSInt LHSB = SourceLHS.getVectorElt(LaneStart + I + 1).getInt();
14389 switch (BuiltinOp) {
14390 case clang::X86::BI__builtin_ia32_phaddw128:
14391 case clang::X86::BI__builtin_ia32_phaddw256:
14392 case clang::X86::BI__builtin_ia32_phaddd128:
14393 case clang::X86::BI__builtin_ia32_phaddd256: {
14394 APSInt Res(LHSA + LHSB, DestUnsigned);
14395 ResultElements.push_back(APValue(Res));
14396 break;
14397 }
14398 case clang::X86::BI__builtin_ia32_phaddsw128:
14399 case clang::X86::BI__builtin_ia32_phaddsw256: {
14400 APSInt Res(LHSA.sadd_sat(LHSB));
14401 ResultElements.push_back(APValue(Res));
14402 break;
14403 }
14404 case clang::X86::BI__builtin_ia32_phsubw128:
14405 case clang::X86::BI__builtin_ia32_phsubw256:
14406 case clang::X86::BI__builtin_ia32_phsubd128:
14407 case clang::X86::BI__builtin_ia32_phsubd256: {
14408 APSInt Res(LHSA - LHSB, DestUnsigned);
14409 ResultElements.push_back(APValue(Res));
14410 break;
14411 }
14412 case clang::X86::BI__builtin_ia32_phsubsw128:
14413 case clang::X86::BI__builtin_ia32_phsubsw256: {
14414 APSInt Res(LHSA.ssub_sat(LHSB));
14415 ResultElements.push_back(APValue(Res));
14416 break;
14417 }
14418 }
14419 }
14420 for (unsigned I = 0; I != EltsPerLane; I += 2) {
14421 APSInt RHSA = SourceRHS.getVectorElt(LaneStart + I).getInt();
14422 APSInt RHSB = SourceRHS.getVectorElt(LaneStart + I + 1).getInt();
14423 switch (BuiltinOp) {
14424 case clang::X86::BI__builtin_ia32_phaddw128:
14425 case clang::X86::BI__builtin_ia32_phaddw256:
14426 case clang::X86::BI__builtin_ia32_phaddd128:
14427 case clang::X86::BI__builtin_ia32_phaddd256: {
14428 APSInt Res(RHSA + RHSB, DestUnsigned);
14429 ResultElements.push_back(APValue(Res));
14430 break;
14431 }
14432 case clang::X86::BI__builtin_ia32_phaddsw128:
14433 case clang::X86::BI__builtin_ia32_phaddsw256: {
14434 APSInt Res(RHSA.sadd_sat(RHSB));
14435 ResultElements.push_back(APValue(Res));
14436 break;
14437 }
14438 case clang::X86::BI__builtin_ia32_phsubw128:
14439 case clang::X86::BI__builtin_ia32_phsubw256:
14440 case clang::X86::BI__builtin_ia32_phsubd128:
14441 case clang::X86::BI__builtin_ia32_phsubd256: {
14442 APSInt Res(RHSA - RHSB, DestUnsigned);
14443 ResultElements.push_back(APValue(Res));
14444 break;
14445 }
14446 case clang::X86::BI__builtin_ia32_phsubsw128:
14447 case clang::X86::BI__builtin_ia32_phsubsw256: {
14448 APSInt Res(RHSA.ssub_sat(RHSB));
14449 ResultElements.push_back(APValue(Res));
14450 break;
14451 }
14452 }
14453 }
14454 }
14455 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
14456 }
14457 case clang::X86::BI__builtin_ia32_haddpd:
14458 case clang::X86::BI__builtin_ia32_haddps:
14459 case clang::X86::BI__builtin_ia32_haddps256:
14460 case clang::X86::BI__builtin_ia32_haddpd256:
14461 case clang::X86::BI__builtin_ia32_hsubpd:
14462 case clang::X86::BI__builtin_ia32_hsubps:
14463 case clang::X86::BI__builtin_ia32_hsubps256:
14464 case clang::X86::BI__builtin_ia32_hsubpd256: {
14465 APValue SourceLHS, SourceRHS;
14466 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
14467 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
14468 return false;
14469 unsigned NumElts = SourceLHS.getVectorLength();
14470 SmallVector<APValue, 4> ResultElements;
14471 ResultElements.reserve(NumElts);
14472 llvm::RoundingMode RM = getActiveRoundingMode(getEvalInfo(), E);
14473 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
14474 unsigned EltBits = Info.Ctx.getTypeSize(DestEltTy);
14475 unsigned NumLanes = NumElts * EltBits / 128;
14476 unsigned NumElemsPerLane = NumElts / NumLanes;
14477 unsigned HalfElemsPerLane = NumElemsPerLane / 2;
14478
14479 for (unsigned L = 0; L != NumElts; L += NumElemsPerLane) {
14480 for (unsigned I = 0; I != HalfElemsPerLane; ++I) {
14481 APFloat LHSA = SourceLHS.getVectorElt(L + (2 * I) + 0).getFloat();
14482 APFloat LHSB = SourceLHS.getVectorElt(L + (2 * I) + 1).getFloat();
14483 switch (BuiltinOp) {
14484 case clang::X86::BI__builtin_ia32_haddpd:
14485 case clang::X86::BI__builtin_ia32_haddps:
14486 case clang::X86::BI__builtin_ia32_haddps256:
14487 case clang::X86::BI__builtin_ia32_haddpd256:
14488 LHSA.add(LHSB, RM);
14489 break;
14490 case clang::X86::BI__builtin_ia32_hsubpd:
14491 case clang::X86::BI__builtin_ia32_hsubps:
14492 case clang::X86::BI__builtin_ia32_hsubps256:
14493 case clang::X86::BI__builtin_ia32_hsubpd256:
14494 LHSA.subtract(LHSB, RM);
14495 break;
14496 }
14497 ResultElements.push_back(APValue(LHSA));
14498 }
14499 for (unsigned I = 0; I != HalfElemsPerLane; ++I) {
14500 APFloat RHSA = SourceRHS.getVectorElt(L + (2 * I) + 0).getFloat();
14501 APFloat RHSB = SourceRHS.getVectorElt(L + (2 * I) + 1).getFloat();
14502 switch (BuiltinOp) {
14503 case clang::X86::BI__builtin_ia32_haddpd:
14504 case clang::X86::BI__builtin_ia32_haddps:
14505 case clang::X86::BI__builtin_ia32_haddps256:
14506 case clang::X86::BI__builtin_ia32_haddpd256:
14507 RHSA.add(RHSB, RM);
14508 break;
14509 case clang::X86::BI__builtin_ia32_hsubpd:
14510 case clang::X86::BI__builtin_ia32_hsubps:
14511 case clang::X86::BI__builtin_ia32_hsubps256:
14512 case clang::X86::BI__builtin_ia32_hsubpd256:
14513 RHSA.subtract(RHSB, RM);
14514 break;
14515 }
14516 ResultElements.push_back(APValue(RHSA));
14517 }
14518 }
14519 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
14520 }
14521 case clang::X86::BI__builtin_ia32_addsubpd:
14522 case clang::X86::BI__builtin_ia32_addsubps:
14523 case clang::X86::BI__builtin_ia32_addsubpd256:
14524 case clang::X86::BI__builtin_ia32_addsubps256: {
14525 // Addsub: alternates between subtraction and addition
14526 // Result[i] = (i % 2 == 0) ? (a[i] - b[i]) : (a[i] + b[i])
14527 APValue SourceLHS, SourceRHS;
14528 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
14529 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
14530 return false;
14531 unsigned NumElems = SourceLHS.getVectorLength();
14532 SmallVector<APValue, 8> ResultElements;
14533 ResultElements.reserve(NumElems);
14534 llvm::RoundingMode RM = getActiveRoundingMode(getEvalInfo(), E);
14535
14536 for (unsigned I = 0; I != NumElems; ++I) {
14537 APFloat LHS = SourceLHS.getVectorElt(I).getFloat();
14538 APFloat RHS = SourceRHS.getVectorElt(I).getFloat();
14539 if (I % 2 == 0) {
14540 // Even indices: subtract
14541 LHS.subtract(RHS, RM);
14542 } else {
14543 // Odd indices: add
14544 LHS.add(RHS, RM);
14545 }
14546 ResultElements.push_back(APValue(LHS));
14547 }
14548 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
14549 }
14550 case clang::X86::BI__builtin_ia32_pclmulqdq128:
14551 case clang::X86::BI__builtin_ia32_pclmulqdq256:
14552 case clang::X86::BI__builtin_ia32_pclmulqdq512: {
14553 // PCLMULQDQ: carry-less multiplication of selected 64-bit halves
14554 // imm8 bit 0: selects lower (0) or upper (1) 64 bits of first operand
14555 // imm8 bit 4: selects lower (0) or upper (1) 64 bits of second operand
14556 APValue SourceLHS, SourceRHS;
14557 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
14558 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
14559 return false;
14560
14561 APSInt Imm8;
14562 if (!EvaluateInteger(E->getArg(2), Imm8, Info))
14563 return false;
14564
14565 // Extract bits 0 and 4 from imm8
14566 bool SelectUpperA = (Imm8 & 0x01) != 0;
14567 bool SelectUpperB = (Imm8 & 0x10) != 0;
14568
14569 unsigned NumElems = SourceLHS.getVectorLength();
14570 SmallVector<APValue, 8> ResultElements;
14571 ResultElements.reserve(NumElems);
14572 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
14573 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
14574
14575 // Process each 128-bit lane
14576 for (unsigned Lane = 0; Lane < NumElems; Lane += 2) {
14577 // Get the two 64-bit halves of the first operand
14578 APSInt A0 = SourceLHS.getVectorElt(Lane + 0).getInt();
14579 APSInt A1 = SourceLHS.getVectorElt(Lane + 1).getInt();
14580 // Get the two 64-bit halves of the second operand
14581 APSInt B0 = SourceRHS.getVectorElt(Lane + 0).getInt();
14582 APSInt B1 = SourceRHS.getVectorElt(Lane + 1).getInt();
14583
14584 // Select the appropriate 64-bit values based on imm8
14585 APInt A = SelectUpperA ? A1 : A0;
14586 APInt B = SelectUpperB ? B1 : B0;
14587
14588 // Extend both operands to 128 bits for carry-less multiplication
14589 APInt A128 = A.zext(128);
14590 APInt B128 = B.zext(128);
14591
14592 // Use APIntOps::clmul for carry-less multiplication
14593 APInt Result = llvm::APIntOps::clmul(A128, B128);
14594
14595 // Split the 128-bit result into two 64-bit halves
14596 APSInt ResultLow(Result.extractBits(64, 0), DestUnsigned);
14597 APSInt ResultHigh(Result.extractBits(64, 64), DestUnsigned);
14598
14599 ResultElements.push_back(APValue(ResultLow));
14600 ResultElements.push_back(APValue(ResultHigh));
14601 }
14602
14603 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
14604 }
14605 case Builtin::BI__builtin_elementwise_clmul:
14606 return EvaluateBinOpExpr(llvm::APIntOps::clmul);
14607 case Builtin::BI__builtin_elementwise_pext:
14608 return EvaluateBinOpExpr(llvm::APIntOps::pext);
14609 case Builtin::BI__builtin_elementwise_pdep:
14610 return EvaluateBinOpExpr(llvm::APIntOps::pdep);
14611 case Builtin::BI__builtin_elementwise_fshl:
14612 case Builtin::BI__builtin_elementwise_fshr: {
14613 APValue SourceHi, SourceLo, SourceShift;
14614 if (!EvaluateAsRValue(Info, E->getArg(0), SourceHi) ||
14615 !EvaluateAsRValue(Info, E->getArg(1), SourceLo) ||
14616 !EvaluateAsRValue(Info, E->getArg(2), SourceShift))
14617 return false;
14618
14619 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
14620 if (!DestEltTy->isIntegerType())
14621 return false;
14622
14623 unsigned SourceLen = SourceHi.getVectorLength();
14624 SmallVector<APValue> ResultElements;
14625 ResultElements.reserve(SourceLen);
14626 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
14627 const APSInt &Hi = SourceHi.getVectorElt(EltNum).getInt();
14628 const APSInt &Lo = SourceLo.getVectorElt(EltNum).getInt();
14629 const APSInt &Shift = SourceShift.getVectorElt(EltNum).getInt();
14630 switch (BuiltinOp) {
14631 case Builtin::BI__builtin_elementwise_fshl:
14632 ResultElements.push_back(APValue(
14633 APSInt(llvm::APIntOps::fshl(Hi, Lo, Shift), Hi.isUnsigned())));
14634 break;
14635 case Builtin::BI__builtin_elementwise_fshr:
14636 ResultElements.push_back(APValue(
14637 APSInt(llvm::APIntOps::fshr(Hi, Lo, Shift), Hi.isUnsigned())));
14638 break;
14639 }
14640 }
14641
14642 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
14643 }
14644
14645 case X86::BI__builtin_ia32_shuf_f32x4_256:
14646 case X86::BI__builtin_ia32_shuf_i32x4_256:
14647 case X86::BI__builtin_ia32_shuf_f64x2_256:
14648 case X86::BI__builtin_ia32_shuf_i64x2_256:
14649 case X86::BI__builtin_ia32_shuf_f32x4:
14650 case X86::BI__builtin_ia32_shuf_i32x4:
14651 case X86::BI__builtin_ia32_shuf_f64x2:
14652 case X86::BI__builtin_ia32_shuf_i64x2: {
14653 APValue SourceA, SourceB;
14654 if (!EvaluateAsRValue(Info, E->getArg(0), SourceA) ||
14655 !EvaluateAsRValue(Info, E->getArg(1), SourceB))
14656 return false;
14657
14658 APSInt Imm;
14659 if (!EvaluateInteger(E->getArg(2), Imm, Info))
14660 return false;
14661
14662 // Destination and sources A, B all have the same type.
14663 unsigned NumElems = SourceA.getVectorLength();
14664 const VectorType *VT = E->getArg(0)->getType()->castAs<VectorType>();
14665 QualType ElemQT = VT->getElementType();
14666 unsigned ElemBits = Info.Ctx.getTypeSize(ElemQT);
14667 unsigned LaneBits = 128u;
14668 unsigned NumLanes = (NumElems * ElemBits) / LaneBits;
14669 unsigned NumElemsPerLane = LaneBits / ElemBits;
14670
14671 unsigned DstLen = SourceA.getVectorLength();
14672 SmallVector<APValue, 16> ResultElements;
14673 ResultElements.reserve(DstLen);
14674
14675 APValue R;
14676 if (!evalShuffleGeneric(
14677 Info, E, R,
14678 [NumLanes, NumElemsPerLane](unsigned DstIdx, unsigned ShuffleMask)
14679 -> std::pair<unsigned, int> {
14680 // DstIdx determines source. ShuffleMask selects lane in source.
14681 unsigned BitsPerElem = NumLanes / 2;
14682 unsigned IndexMask = (1u << BitsPerElem) - 1;
14683 unsigned Lane = DstIdx / NumElemsPerLane;
14684 unsigned SrcIdx = (Lane < NumLanes / 2) ? 0 : 1;
14685 unsigned BitIdx = BitsPerElem * Lane;
14686 unsigned SrcLaneIdx = (ShuffleMask >> BitIdx) & IndexMask;
14687 unsigned ElemInLane = DstIdx % NumElemsPerLane;
14688 unsigned IdxToPick = SrcLaneIdx * NumElemsPerLane + ElemInLane;
14689 return {SrcIdx, IdxToPick};
14690 }))
14691 return false;
14692 return Success(R, E);
14693 }
14694
14695 case X86::BI__builtin_ia32_vgf2p8affineinvqb_v16qi:
14696 case X86::BI__builtin_ia32_vgf2p8affineinvqb_v32qi:
14697 case X86::BI__builtin_ia32_vgf2p8affineinvqb_v64qi:
14698 case X86::BI__builtin_ia32_vgf2p8affineqb_v16qi:
14699 case X86::BI__builtin_ia32_vgf2p8affineqb_v32qi:
14700 case X86::BI__builtin_ia32_vgf2p8affineqb_v64qi: {
14701
14702 APValue X, A;
14703 APSInt Imm;
14704 if (!EvaluateAsRValue(Info, E->getArg(0), X) ||
14705 !EvaluateAsRValue(Info, E->getArg(1), A) ||
14706 !EvaluateInteger(E->getArg(2), Imm, Info))
14707 return false;
14708
14709 assert(X.isVector() && A.isVector());
14710 assert(X.getVectorLength() == A.getVectorLength());
14711
14712 bool IsInverse = false;
14713 switch (BuiltinOp) {
14714 case X86::BI__builtin_ia32_vgf2p8affineinvqb_v16qi:
14715 case X86::BI__builtin_ia32_vgf2p8affineinvqb_v32qi:
14716 case X86::BI__builtin_ia32_vgf2p8affineinvqb_v64qi: {
14717 IsInverse = true;
14718 }
14719 }
14720
14721 unsigned NumBitsInByte = 8;
14722 unsigned NumBytesInQWord = 8;
14723 unsigned NumBitsInQWord = 64;
14724 unsigned NumBytes = A.getVectorLength();
14725 unsigned NumQWords = NumBytes / NumBytesInQWord;
14727 Result.reserve(NumBytes);
14728
14729 // computing A*X + Imm
14730 for (unsigned QWordIdx = 0; QWordIdx != NumQWords; ++QWordIdx) {
14731 // Extract the QWords from X, A
14732 APInt XQWord(NumBitsInQWord, 0);
14733 APInt AQWord(NumBitsInQWord, 0);
14734 for (unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
14735 unsigned Idx = QWordIdx * NumBytesInQWord + ByteIdx;
14736 APInt XByte = X.getVectorElt(Idx).getInt();
14737 APInt AByte = A.getVectorElt(Idx).getInt();
14738 XQWord.insertBits(XByte, ByteIdx * NumBitsInByte);
14739 AQWord.insertBits(AByte, ByteIdx * NumBitsInByte);
14740 }
14741
14742 for (unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
14743 uint8_t XByte =
14744 XQWord.lshr(ByteIdx * NumBitsInByte).getLoBits(8).getZExtValue();
14745 Result.push_back(APValue(APSInt(
14746 APInt(8, GFNIAffine(XByte, AQWord, Imm, IsInverse)), false)));
14747 }
14748 }
14749
14750 return Success(APValue(Result.data(), Result.size()), E);
14751 }
14752
14753 case X86::BI__builtin_ia32_vgf2p8mulb_v16qi:
14754 case X86::BI__builtin_ia32_vgf2p8mulb_v32qi:
14755 case X86::BI__builtin_ia32_vgf2p8mulb_v64qi: {
14756 APValue A, B;
14757 if (!EvaluateAsRValue(Info, E->getArg(0), A) ||
14758 !EvaluateAsRValue(Info, E->getArg(1), B))
14759 return false;
14760
14761 assert(A.isVector() && B.isVector());
14762 assert(A.getVectorLength() == B.getVectorLength());
14763
14764 unsigned NumBytes = A.getVectorLength();
14766 Result.reserve(NumBytes);
14767
14768 for (unsigned ByteIdx = 0; ByteIdx != NumBytes; ++ByteIdx) {
14769 uint8_t AByte = A.getVectorElt(ByteIdx).getInt().getZExtValue();
14770 uint8_t BByte = B.getVectorElt(ByteIdx).getInt().getZExtValue();
14771 Result.push_back(APValue(
14772 APSInt(APInt(8, GFNIMul(AByte, BByte)), /*IsUnsigned=*/false)));
14773 }
14774
14775 return Success(APValue(Result.data(), Result.size()), E);
14776 }
14777
14778 case X86::BI__builtin_ia32_insertf32x4_256:
14779 case X86::BI__builtin_ia32_inserti32x4_256:
14780 case X86::BI__builtin_ia32_insertf64x2_256:
14781 case X86::BI__builtin_ia32_inserti64x2_256:
14782 case X86::BI__builtin_ia32_insertf32x4:
14783 case X86::BI__builtin_ia32_inserti32x4:
14784 case X86::BI__builtin_ia32_insertf64x2_512:
14785 case X86::BI__builtin_ia32_inserti64x2_512:
14786 case X86::BI__builtin_ia32_insertf32x8:
14787 case X86::BI__builtin_ia32_inserti32x8:
14788 case X86::BI__builtin_ia32_insertf64x4:
14789 case X86::BI__builtin_ia32_inserti64x4:
14790 case X86::BI__builtin_ia32_vinsertf128_ps256:
14791 case X86::BI__builtin_ia32_vinsertf128_pd256:
14792 case X86::BI__builtin_ia32_vinsertf128_si256:
14793 case X86::BI__builtin_ia32_insert128i256: {
14794 APValue SourceDst, SourceSub;
14795 if (!EvaluateAsRValue(Info, E->getArg(0), SourceDst) ||
14796 !EvaluateAsRValue(Info, E->getArg(1), SourceSub))
14797 return false;
14798
14799 APSInt Imm;
14800 if (!EvaluateInteger(E->getArg(2), Imm, Info))
14801 return false;
14802
14803 assert(SourceDst.isVector() && SourceSub.isVector());
14804 unsigned DstLen = SourceDst.getVectorLength();
14805 unsigned SubLen = SourceSub.getVectorLength();
14806 assert(SubLen != 0 && DstLen != 0 && (DstLen % SubLen) == 0);
14807 unsigned NumLanes = DstLen / SubLen;
14808 unsigned LaneIdx = (Imm.getZExtValue() % NumLanes) * SubLen;
14809
14810 SmallVector<APValue, 16> ResultElements;
14811 ResultElements.reserve(DstLen);
14812
14813 for (unsigned EltNum = 0; EltNum < DstLen; ++EltNum) {
14814 if (EltNum >= LaneIdx && EltNum < LaneIdx + SubLen)
14815 ResultElements.push_back(SourceSub.getVectorElt(EltNum - LaneIdx));
14816 else
14817 ResultElements.push_back(SourceDst.getVectorElt(EltNum));
14818 }
14819
14820 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
14821 }
14822
14823 case clang::X86::BI__builtin_ia32_vec_set_v4hi:
14824 case clang::X86::BI__builtin_ia32_vec_set_v16qi:
14825 case clang::X86::BI__builtin_ia32_vec_set_v8hi:
14826 case clang::X86::BI__builtin_ia32_vec_set_v4si:
14827 case clang::X86::BI__builtin_ia32_vec_set_v2di:
14828 case clang::X86::BI__builtin_ia32_vec_set_v32qi:
14829 case clang::X86::BI__builtin_ia32_vec_set_v16hi:
14830 case clang::X86::BI__builtin_ia32_vec_set_v8si:
14831 case clang::X86::BI__builtin_ia32_vec_set_v4di: {
14832 APValue VecVal;
14833 APSInt Scalar, IndexAPS;
14834 if (!EvaluateVector(E->getArg(0), VecVal, Info) ||
14835 !EvaluateInteger(E->getArg(1), Scalar, Info) ||
14836 !EvaluateInteger(E->getArg(2), IndexAPS, Info))
14837 return false;
14838
14839 QualType ElemTy = E->getType()->castAs<VectorType>()->getElementType();
14840 unsigned ElemWidth = Info.Ctx.getIntWidth(ElemTy);
14841 bool ElemUnsigned = ElemTy->isUnsignedIntegerOrEnumerationType();
14842 Scalar.setIsUnsigned(ElemUnsigned);
14843 APSInt ElemAPS = Scalar.extOrTrunc(ElemWidth);
14844 APValue ElemAV(ElemAPS);
14845
14846 unsigned NumElems = VecVal.getVectorLength();
14847 unsigned Index =
14848 static_cast<unsigned>(IndexAPS.getZExtValue() & (NumElems - 1));
14849
14851 Elems.reserve(NumElems);
14852 for (unsigned ElemNum = 0; ElemNum != NumElems; ++ElemNum)
14853 Elems.push_back(ElemNum == Index ? ElemAV : VecVal.getVectorElt(ElemNum));
14854
14855 return Success(APValue(Elems.data(), NumElems), E);
14856 }
14857
14858 case X86::BI__builtin_ia32_pslldqi128_byteshift:
14859 case X86::BI__builtin_ia32_pslldqi256_byteshift:
14860 case X86::BI__builtin_ia32_pslldqi512_byteshift: {
14861 APValue R;
14862 if (!evalShuffleGeneric(
14863 Info, E, R,
14864 [](unsigned DstIdx, unsigned Shift) -> std::pair<unsigned, int> {
14865 unsigned LaneBase = (DstIdx / 16) * 16;
14866 unsigned LaneIdx = DstIdx % 16;
14867 if (LaneIdx < Shift)
14868 return std::make_pair(0, -1);
14869
14870 return std::make_pair(
14871 0, static_cast<int>(LaneBase + LaneIdx - Shift));
14872 }))
14873 return false;
14874 return Success(R, E);
14875 }
14876
14877 case X86::BI__builtin_ia32_psrldqi128_byteshift:
14878 case X86::BI__builtin_ia32_psrldqi256_byteshift:
14879 case X86::BI__builtin_ia32_psrldqi512_byteshift: {
14880 APValue R;
14881 if (!evalShuffleGeneric(
14882 Info, E, R,
14883 [](unsigned DstIdx, unsigned Shift) -> std::pair<unsigned, int> {
14884 unsigned LaneBase = (DstIdx / 16) * 16;
14885 unsigned LaneIdx = DstIdx % 16;
14886 if (LaneIdx + Shift < 16)
14887 return std::make_pair(
14888 0, static_cast<int>(LaneBase + LaneIdx + Shift));
14889
14890 return std::make_pair(0, -1);
14891 }))
14892 return false;
14893 return Success(R, E);
14894 }
14895
14896 case X86::BI__builtin_ia32_palignr128:
14897 case X86::BI__builtin_ia32_palignr256:
14898 case X86::BI__builtin_ia32_palignr512: {
14899 APValue R;
14900 if (!evalShuffleGeneric(Info, E, R, [](unsigned DstIdx, unsigned Shift) {
14901 // Default to -1 → zero-fill this destination element
14902 unsigned VecIdx = 1;
14903 int ElemIdx = -1;
14904
14905 int Lane = DstIdx / 16;
14906 int Offset = DstIdx % 16;
14907
14908 // Elements come from VecB first, then VecA after the shift boundary
14909 unsigned ShiftedIdx = Offset + (Shift & 0xFF);
14910 if (ShiftedIdx < 16) { // from VecB
14911 ElemIdx = ShiftedIdx + (Lane * 16);
14912 } else if (ShiftedIdx < 32) { // from VecA
14913 VecIdx = 0;
14914 ElemIdx = (ShiftedIdx - 16) + (Lane * 16);
14915 }
14916
14917 return std::pair<unsigned, int>{VecIdx, ElemIdx};
14918 }))
14919 return false;
14920 return Success(R, E);
14921 }
14922 case X86::BI__builtin_ia32_alignd128:
14923 case X86::BI__builtin_ia32_alignd256:
14924 case X86::BI__builtin_ia32_alignd512:
14925 case X86::BI__builtin_ia32_alignq128:
14926 case X86::BI__builtin_ia32_alignq256:
14927 case X86::BI__builtin_ia32_alignq512: {
14928 APValue R;
14929 unsigned NumElems = E->getType()->castAs<VectorType>()->getNumElements();
14930 if (!evalShuffleGeneric(Info, E, R,
14931 [NumElems](unsigned DstIdx, unsigned Shift) {
14932 unsigned Imm = Shift & 0xFF;
14933 unsigned EffectiveShift = Imm & (NumElems - 1);
14934 unsigned SourcePos = DstIdx + EffectiveShift;
14935 unsigned VecIdx = SourcePos < NumElems ? 1 : 0;
14936 unsigned ElemIdx = SourcePos & (NumElems - 1);
14937
14938 return std::pair<unsigned, int>{
14939 VecIdx, static_cast<int>(ElemIdx)};
14940 }))
14941 return false;
14942 return Success(R, E);
14943 }
14944 case X86::BI__builtin_ia32_permvarsi256:
14945 case X86::BI__builtin_ia32_permvarsf256:
14946 case X86::BI__builtin_ia32_permvardf512:
14947 case X86::BI__builtin_ia32_permvardi512:
14948 case X86::BI__builtin_ia32_permvarhi128: {
14949 APValue R;
14950 if (!evalShuffleGeneric(Info, E, R,
14951 [](unsigned DstIdx, unsigned ShuffleMask) {
14952 int Offset = ShuffleMask & 0x7;
14953 return std::pair<unsigned, int>{0, Offset};
14954 }))
14955 return false;
14956 return Success(R, E);
14957 }
14958 case X86::BI__builtin_ia32_permvarqi128:
14959 case X86::BI__builtin_ia32_permvarhi256:
14960 case X86::BI__builtin_ia32_permvarsi512:
14961 case X86::BI__builtin_ia32_permvarsf512: {
14962 APValue R;
14963 if (!evalShuffleGeneric(Info, E, R,
14964 [](unsigned DstIdx, unsigned ShuffleMask) {
14965 int Offset = ShuffleMask & 0xF;
14966 return std::pair<unsigned, int>{0, Offset};
14967 }))
14968 return false;
14969 return Success(R, E);
14970 }
14971 case X86::BI__builtin_ia32_permvardi256:
14972 case X86::BI__builtin_ia32_permvardf256: {
14973 APValue R;
14974 if (!evalShuffleGeneric(Info, E, R,
14975 [](unsigned DstIdx, unsigned ShuffleMask) {
14976 int Offset = ShuffleMask & 0x3;
14977 return std::pair<unsigned, int>{0, Offset};
14978 }))
14979 return false;
14980 return Success(R, E);
14981 }
14982 case X86::BI__builtin_ia32_permvarqi256:
14983 case X86::BI__builtin_ia32_permvarhi512: {
14984 APValue R;
14985 if (!evalShuffleGeneric(Info, E, R,
14986 [](unsigned DstIdx, unsigned ShuffleMask) {
14987 int Offset = ShuffleMask & 0x1F;
14988 return std::pair<unsigned, int>{0, Offset};
14989 }))
14990 return false;
14991 return Success(R, E);
14992 }
14993 case X86::BI__builtin_ia32_permvarqi512: {
14994 APValue R;
14995 if (!evalShuffleGeneric(Info, E, R,
14996 [](unsigned DstIdx, unsigned ShuffleMask) {
14997 int Offset = ShuffleMask & 0x3F;
14998 return std::pair<unsigned, int>{0, Offset};
14999 }))
15000 return false;
15001 return Success(R, E);
15002 }
15003 case X86::BI__builtin_ia32_vpermi2varq128:
15004 case X86::BI__builtin_ia32_vpermi2varpd128: {
15005 APValue R;
15006 if (!evalShuffleGeneric(Info, E, R,
15007 [](unsigned DstIdx, unsigned ShuffleMask) {
15008 int Offset = ShuffleMask & 0x1;
15009 unsigned SrcIdx = (ShuffleMask >> 1) & 0x1;
15010 return std::pair<unsigned, int>{SrcIdx, Offset};
15011 }))
15012 return false;
15013 return Success(R, E);
15014 }
15015 case X86::BI__builtin_ia32_vpermi2vard128:
15016 case X86::BI__builtin_ia32_vpermi2varps128:
15017 case X86::BI__builtin_ia32_vpermi2varq256:
15018 case X86::BI__builtin_ia32_vpermi2varpd256: {
15019 APValue R;
15020 if (!evalShuffleGeneric(Info, E, R,
15021 [](unsigned DstIdx, unsigned ShuffleMask) {
15022 int Offset = ShuffleMask & 0x3;
15023 unsigned SrcIdx = (ShuffleMask >> 2) & 0x1;
15024 return std::pair<unsigned, int>{SrcIdx, Offset};
15025 }))
15026 return false;
15027 return Success(R, E);
15028 }
15029 case X86::BI__builtin_ia32_vpermi2varhi128:
15030 case X86::BI__builtin_ia32_vpermi2vard256:
15031 case X86::BI__builtin_ia32_vpermi2varps256:
15032 case X86::BI__builtin_ia32_vpermi2varq512:
15033 case X86::BI__builtin_ia32_vpermi2varpd512: {
15034 APValue R;
15035 if (!evalShuffleGeneric(Info, E, R,
15036 [](unsigned DstIdx, unsigned ShuffleMask) {
15037 int Offset = ShuffleMask & 0x7;
15038 unsigned SrcIdx = (ShuffleMask >> 3) & 0x1;
15039 return std::pair<unsigned, int>{SrcIdx, Offset};
15040 }))
15041 return false;
15042 return Success(R, E);
15043 }
15044 case X86::BI__builtin_ia32_vpermi2varqi128:
15045 case X86::BI__builtin_ia32_vpermi2varhi256:
15046 case X86::BI__builtin_ia32_vpermi2vard512:
15047 case X86::BI__builtin_ia32_vpermi2varps512: {
15048 APValue R;
15049 if (!evalShuffleGeneric(Info, E, R,
15050 [](unsigned DstIdx, unsigned ShuffleMask) {
15051 int Offset = ShuffleMask & 0xF;
15052 unsigned SrcIdx = (ShuffleMask >> 4) & 0x1;
15053 return std::pair<unsigned, int>{SrcIdx, Offset};
15054 }))
15055 return false;
15056 return Success(R, E);
15057 }
15058 case X86::BI__builtin_ia32_vpermi2varqi256:
15059 case X86::BI__builtin_ia32_vpermi2varhi512: {
15060 APValue R;
15061 if (!evalShuffleGeneric(Info, E, R,
15062 [](unsigned DstIdx, unsigned ShuffleMask) {
15063 int Offset = ShuffleMask & 0x1F;
15064 unsigned SrcIdx = (ShuffleMask >> 5) & 0x1;
15065 return std::pair<unsigned, int>{SrcIdx, Offset};
15066 }))
15067 return false;
15068 return Success(R, E);
15069 }
15070 case X86::BI__builtin_ia32_vpermi2varqi512: {
15071 APValue R;
15072 if (!evalShuffleGeneric(Info, E, R,
15073 [](unsigned DstIdx, unsigned ShuffleMask) {
15074 int Offset = ShuffleMask & 0x3F;
15075 unsigned SrcIdx = (ShuffleMask >> 6) & 0x1;
15076 return std::pair<unsigned, int>{SrcIdx, Offset};
15077 }))
15078 return false;
15079 return Success(R, E);
15080 }
15081
15082 case clang::X86::BI__builtin_ia32_minps:
15083 case clang::X86::BI__builtin_ia32_minpd:
15084 case clang::X86::BI__builtin_ia32_minps256:
15085 case clang::X86::BI__builtin_ia32_minpd256:
15086 case clang::X86::BI__builtin_ia32_minps512:
15087 case clang::X86::BI__builtin_ia32_minpd512:
15088 case clang::X86::BI__builtin_ia32_minph128:
15089 case clang::X86::BI__builtin_ia32_minph256:
15090 case clang::X86::BI__builtin_ia32_minph512:
15091 return EvaluateFpBinOpExpr(
15092 [](const APFloat &A, const APFloat &B,
15093 std::optional<APSInt>) -> std::optional<APFloat> {
15094 if (A.isNaN() || A.isInfinity() || A.isDenormal() || B.isNaN() ||
15095 B.isInfinity() || B.isDenormal())
15096 return std::nullopt;
15097 if (A.isZero() && B.isZero())
15098 return B;
15099 return llvm::minimum(A, B);
15100 });
15101
15102 case clang::X86::BI__builtin_ia32_minss:
15103 case clang::X86::BI__builtin_ia32_minsd:
15104 return EvaluateFpBinOpExpr(
15105 [](const APFloat &A, const APFloat &B,
15106 std::optional<APSInt> RoundingMode) -> std::optional<APFloat> {
15107 return EvalScalarMinMaxFp(A, B, RoundingMode, /*IsMin=*/true);
15108 },
15109 /*IsScalar=*/true);
15110
15111 case clang::X86::BI__builtin_ia32_minsd_round_mask:
15112 case clang::X86::BI__builtin_ia32_minss_round_mask:
15113 case clang::X86::BI__builtin_ia32_minsh_round_mask:
15114 case clang::X86::BI__builtin_ia32_maxsd_round_mask:
15115 case clang::X86::BI__builtin_ia32_maxss_round_mask:
15116 case clang::X86::BI__builtin_ia32_maxsh_round_mask: {
15117 bool IsMin = BuiltinOp == clang::X86::BI__builtin_ia32_minsd_round_mask ||
15118 BuiltinOp == clang::X86::BI__builtin_ia32_minss_round_mask ||
15119 BuiltinOp == clang::X86::BI__builtin_ia32_minsh_round_mask;
15120 return EvaluateScalarFpRoundMaskBinOp(
15121 [IsMin](const APFloat &A, const APFloat &B,
15122 std::optional<APSInt> RoundingMode) -> std::optional<APFloat> {
15123 return EvalScalarMinMaxFp(A, B, RoundingMode, IsMin);
15124 });
15125 }
15126
15127 case clang::X86::BI__builtin_ia32_maxps:
15128 case clang::X86::BI__builtin_ia32_maxpd:
15129 case clang::X86::BI__builtin_ia32_maxps256:
15130 case clang::X86::BI__builtin_ia32_maxpd256:
15131 case clang::X86::BI__builtin_ia32_maxps512:
15132 case clang::X86::BI__builtin_ia32_maxpd512:
15133 case clang::X86::BI__builtin_ia32_maxph128:
15134 case clang::X86::BI__builtin_ia32_maxph256:
15135 case clang::X86::BI__builtin_ia32_maxph512:
15136 return EvaluateFpBinOpExpr(
15137 [](const APFloat &A, const APFloat &B,
15138 std::optional<APSInt>) -> std::optional<APFloat> {
15139 if (A.isNaN() || A.isInfinity() || A.isDenormal() || B.isNaN() ||
15140 B.isInfinity() || B.isDenormal())
15141 return std::nullopt;
15142 if (A.isZero() && B.isZero())
15143 return B;
15144 return llvm::maximum(A, B);
15145 });
15146
15147 case clang::X86::BI__builtin_ia32_maxss:
15148 case clang::X86::BI__builtin_ia32_maxsd:
15149 return EvaluateFpBinOpExpr(
15150 [](const APFloat &A, const APFloat &B,
15151 std::optional<APSInt> RoundingMode) -> std::optional<APFloat> {
15152 return EvalScalarMinMaxFp(A, B, RoundingMode, /*IsMin=*/false);
15153 },
15154 /*IsScalar=*/true);
15155
15156 case clang::X86::BI__builtin_ia32_vcvtps2ph:
15157 case clang::X86::BI__builtin_ia32_vcvtps2ph256: {
15158 APValue SrcVec;
15159 if (!EvaluateAsRValue(Info, E->getArg(0), SrcVec))
15160 return false;
15161
15162 APSInt Imm;
15163 if (!EvaluateInteger(E->getArg(1), Imm, Info))
15164 return false;
15165
15166 const auto *SrcVTy = E->getArg(0)->getType()->castAs<VectorType>();
15167 unsigned SrcNumElems = SrcVTy->getNumElements();
15168 const auto *DstVTy = E->getType()->castAs<VectorType>();
15169 unsigned DstNumElems = DstVTy->getNumElements();
15170 QualType DstElemTy = DstVTy->getElementType();
15171
15172 const llvm::fltSemantics &HalfSem =
15173 Info.Ctx.getFloatTypeSemantics(Info.Ctx.HalfTy);
15174
15175 int ImmVal = Imm.getZExtValue();
15176 bool UseMXCSR = (ImmVal & 4) != 0;
15177 bool IsFPConstrained =
15178 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained();
15179
15180 llvm::RoundingMode RM;
15181 if (!UseMXCSR) {
15182 switch (ImmVal & 3) {
15183 case 0:
15184 RM = llvm::RoundingMode::NearestTiesToEven;
15185 break;
15186 case 1:
15187 RM = llvm::RoundingMode::TowardNegative;
15188 break;
15189 case 2:
15190 RM = llvm::RoundingMode::TowardPositive;
15191 break;
15192 case 3:
15193 RM = llvm::RoundingMode::TowardZero;
15194 break;
15195 default:
15196 llvm_unreachable("Invalid immediate rounding mode");
15197 }
15198 } else {
15199 RM = llvm::RoundingMode::NearestTiesToEven;
15200 }
15201
15202 SmallVector<APValue, 8> ResultElements;
15203 ResultElements.reserve(DstNumElems);
15204
15205 for (unsigned I = 0; I < SrcNumElems; ++I) {
15206 APFloat SrcVal = SrcVec.getVectorElt(I).getFloat();
15207
15208 bool LostInfo;
15209 APFloat::opStatus St = SrcVal.convert(HalfSem, RM, &LostInfo);
15210
15211 if (UseMXCSR && IsFPConstrained && St != APFloat::opOK) {
15212 Info.FFDiag(E, diag::note_constexpr_dynamic_rounding);
15213 return false;
15214 }
15215
15216 APSInt DstInt(SrcVal.bitcastToAPInt(),
15218 ResultElements.push_back(APValue(DstInt));
15219 }
15220
15221 if (DstNumElems > SrcNumElems) {
15222 APSInt Zero = Info.Ctx.MakeIntValue(0, DstElemTy);
15223 for (unsigned I = SrcNumElems; I < DstNumElems; ++I) {
15224 ResultElements.push_back(APValue(Zero));
15225 }
15226 }
15227
15228 return Success(ResultElements, E);
15229 }
15230 case X86::BI__builtin_ia32_vperm2f128_pd256:
15231 case X86::BI__builtin_ia32_vperm2f128_ps256:
15232 case X86::BI__builtin_ia32_vperm2f128_si256:
15233 case X86::BI__builtin_ia32_permti256: {
15234 unsigned NumElements =
15235 E->getArg(0)->getType()->getAs<VectorType>()->getNumElements();
15236 unsigned PreservedBitsCnt = NumElements >> 2;
15237 APValue R;
15238 if (!evalShuffleGeneric(
15239 Info, E, R,
15240 [PreservedBitsCnt](unsigned DstIdx, unsigned ShuffleMask) {
15241 unsigned ControlBitsCnt = DstIdx >> PreservedBitsCnt << 2;
15242 unsigned ControlBits = ShuffleMask >> ControlBitsCnt;
15243
15244 if (ControlBits & 0b1000)
15245 return std::make_pair(0u, -1);
15246
15247 unsigned SrcVecIdx = (ControlBits & 0b10) >> 1;
15248 unsigned PreservedBitsMask = (1 << PreservedBitsCnt) - 1;
15249 int SrcIdx = ((ControlBits & 0b1) << PreservedBitsCnt) |
15250 (DstIdx & PreservedBitsMask);
15251 return std::make_pair(SrcVecIdx, SrcIdx);
15252 }))
15253 return false;
15254 return Success(R, E);
15255 }
15256 case X86::BI__builtin_ia32_vpdpwssd128:
15257 case X86::BI__builtin_ia32_vpdpwssd256:
15258 case X86::BI__builtin_ia32_vpdpwssd512:
15259 case X86::BI__builtin_ia32_vpdpbusd128:
15260 case X86::BI__builtin_ia32_vpdpbusd256:
15261 case X86::BI__builtin_ia32_vpdpbusd512:
15262 return EvalVectorDotProduct(false);
15263 case X86::BI__builtin_ia32_vpdpwssds128:
15264 case X86::BI__builtin_ia32_vpdpwssds256:
15265 case X86::BI__builtin_ia32_vpdpwssds512:
15266 case X86::BI__builtin_ia32_vpdpbusds128:
15267 case X86::BI__builtin_ia32_vpdpbusds256:
15268 case X86::BI__builtin_ia32_vpdpbusds512:
15269 return EvalVectorDotProduct(true);
15270 case X86::BI__builtin_ia32_cvtpd2dq:
15271 case X86::BI__builtin_ia32_cvtps2dq:
15272 case X86::BI__builtin_ia32_cvttpd2dq:
15273 case X86::BI__builtin_ia32_cvttps2dq:
15274 case X86::BI__builtin_ia32_cvtpd2dq256:
15275 case X86::BI__builtin_ia32_cvtps2dq256:
15276 case X86::BI__builtin_ia32_cvttpd2dq256:
15277 case X86::BI__builtin_ia32_cvttps2dq256: {
15278 APValue SrcVec;
15279 if (!EvaluateAsRValue(Info, E->getArg(0), SrcVec) || !SrcVec.isVector())
15280 return false;
15281
15282 const auto *VT = E->getType()->castAs<VectorType>();
15283 QualType EltTy = VT->getElementType();
15284 bool isUnsigned = EltTy->isUnsignedIntegerType();
15285 unsigned BitWidth = Info.Ctx.getIntWidth(EltTy);
15286
15287 unsigned NumSrcElems = SrcVec.getVectorLength();
15288 unsigned NumDstElems = VT->getNumElements();
15289
15290 SmallVector<APValue, 8> ResultElts;
15291 for (unsigned i = 0; i != NumDstElems; ++i) {
15292 if (i < NumSrcElems) {
15293 llvm::APFloat FloatElem = SrcVec.getVectorElt(i).getFloat();
15294 llvm::APSInt IntResult(BitWidth, isUnsigned);
15295 bool IsExact = false;
15296 // We only allow exact conversions so rounding mode does not matter for
15297 // cvt* and cvtt* builtins
15298 FloatElem.convertToInteger(IntResult, llvm::APFloat::rmTowardZero,
15299 &IsExact);
15300 if (!IsExact)
15301 return false;
15302 ResultElts.push_back(APValue(IntResult));
15303 } else
15304 // Pad remaining lanes with zero
15305 ResultElts.push_back(APValue(llvm::APSInt(BitWidth, isUnsigned)));
15306 }
15307 return Success(ResultElts, E);
15308 }
15309 }
15310}
15311
15312bool VectorExprEvaluator::VisitConvertVectorExpr(const ConvertVectorExpr *E) {
15313 APValue Source;
15314 QualType SourceVecType = E->getSrcExpr()->getType();
15315 if (!EvaluateAsRValue(Info, E->getSrcExpr(), Source))
15316 return false;
15317
15318 QualType DestTy = E->getType()->castAs<VectorType>()->getElementType();
15319 QualType SourceTy = SourceVecType->castAs<VectorType>()->getElementType();
15320
15321 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
15322
15323 auto SourceLen = Source.getVectorLength();
15324 SmallVector<APValue, 4> ResultElements;
15325 ResultElements.reserve(SourceLen);
15326 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
15327 APValue Elt;
15328 if (!handleVectorElementCast(Info, FPO, E, SourceTy, DestTy,
15329 Source.getVectorElt(EltNum), Elt))
15330 return false;
15331 ResultElements.push_back(std::move(Elt));
15332 }
15333
15334 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
15335}
15336
15337static bool handleVectorShuffle(EvalInfo &Info, const ShuffleVectorExpr *E,
15338 QualType ElemType, APValue const &VecVal1,
15339 APValue const &VecVal2, unsigned EltNum,
15340 APValue &Result) {
15341 unsigned const TotalElementsInInputVector1 = VecVal1.getVectorLength();
15342 unsigned const TotalElementsInInputVector2 = VecVal2.getVectorLength();
15343
15344 APSInt IndexVal = E->getShuffleMaskIdx(EltNum);
15345 int64_t index = IndexVal.getExtValue();
15346 // The spec says that -1 should be treated as undef for optimizations,
15347 // but in constexpr we'd have to produce an APValue::Indeterminate,
15348 // which is prohibited from being a top-level constant value. Emit a
15349 // diagnostic instead.
15350 if (index == -1) {
15351 Info.FFDiag(
15352 E, diag::err_shufflevector_minus_one_is_undefined_behavior_constexpr)
15353 << EltNum;
15354 return false;
15355 }
15356
15357 if (index < 0 ||
15358 index >= TotalElementsInInputVector1 + TotalElementsInInputVector2)
15359 llvm_unreachable("Out of bounds shuffle index");
15360
15361 if (index >= TotalElementsInInputVector1)
15362 Result = VecVal2.getVectorElt(index - TotalElementsInInputVector1);
15363 else
15364 Result = VecVal1.getVectorElt(index);
15365 return true;
15366}
15367
15368bool VectorExprEvaluator::VisitShuffleVectorExpr(const ShuffleVectorExpr *E) {
15369 // FIXME: Unary shuffle with mask not currently supported.
15370 if (E->getNumSubExprs() == 2)
15371 return Error(E);
15372 APValue VecVal1;
15373 const Expr *Vec1 = E->getExpr(0);
15374 if (!EvaluateAsRValue(Info, Vec1, VecVal1))
15375 return false;
15376 APValue VecVal2;
15377 const Expr *Vec2 = E->getExpr(1);
15378 if (!EvaluateAsRValue(Info, Vec2, VecVal2))
15379 return false;
15380
15381 VectorType const *DestVecTy = E->getType()->castAs<VectorType>();
15382 QualType DestElTy = DestVecTy->getElementType();
15383
15384 auto TotalElementsInOutputVector = DestVecTy->getNumElements();
15385
15386 SmallVector<APValue, 4> ResultElements;
15387 ResultElements.reserve(TotalElementsInOutputVector);
15388 for (unsigned EltNum = 0; EltNum < TotalElementsInOutputVector; ++EltNum) {
15389 APValue Elt;
15390 if (!handleVectorShuffle(Info, E, DestElTy, VecVal1, VecVal2, EltNum, Elt))
15391 return false;
15392 ResultElements.push_back(std::move(Elt));
15393 }
15394
15395 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
15396}
15397
15398//===----------------------------------------------------------------------===//
15399// Matrix Evaluation
15400//===----------------------------------------------------------------------===//
15401
15402namespace {
15403class MatrixExprEvaluator : public ExprEvaluatorBase<MatrixExprEvaluator> {
15404 APValue &Result;
15405
15406public:
15407 MatrixExprEvaluator(EvalInfo &Info, APValue &Result)
15408 : ExprEvaluatorBaseTy(Info), Result(Result) {}
15409
15410 bool Success(ArrayRef<APValue> M, const Expr *E) {
15411 auto *CMTy = E->getType()->castAs<ConstantMatrixType>();
15412 assert(M.size() == CMTy->getNumElementsFlattened());
15413 // FIXME: remove this APValue copy.
15414 Result = APValue(M.data(), CMTy->getNumRows(), CMTy->getNumColumns());
15415 return true;
15416 }
15417 bool Success(const APValue &M, const Expr *E) {
15418 assert(M.isMatrix() && "expected matrix");
15419 Result = M;
15420 return true;
15421 }
15422
15423 bool VisitCastExpr(const CastExpr *E);
15424 bool VisitInitListExpr(const InitListExpr *E);
15425};
15426} // end anonymous namespace
15427
15428static bool EvaluateMatrix(const Expr *E, APValue &Result, EvalInfo &Info) {
15429 assert(E->isPRValue() && E->getType()->isConstantMatrixType() &&
15430 "not a matrix prvalue");
15431 return MatrixExprEvaluator(Info, Result).Visit(E);
15432}
15433
15434bool MatrixExprEvaluator::VisitCastExpr(const CastExpr *E) {
15435 const auto *MT = E->getType()->castAs<ConstantMatrixType>();
15436 unsigned NumRows = MT->getNumRows();
15437 unsigned NumCols = MT->getNumColumns();
15438 unsigned NElts = NumRows * NumCols;
15439 QualType EltTy = MT->getElementType();
15440 const Expr *SE = E->getSubExpr();
15441
15442 switch (E->getCastKind()) {
15443 case CK_HLSLAggregateSplatCast: {
15444 APValue Val;
15445 QualType ValTy;
15446
15447 if (!hlslAggSplatHelper(Info, SE, Val, ValTy))
15448 return false;
15449
15450 APValue CastedVal;
15451 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
15452 if (!handleScalarCast(Info, FPO, E, ValTy, EltTy, Val, CastedVal))
15453 return false;
15454
15455 SmallVector<APValue, 16> SplatEls(NElts, CastedVal);
15456 return Success(SplatEls, E);
15457 }
15458 case CK_HLSLElementwiseCast: {
15459 SmallVector<APValue> SrcVals;
15460 SmallVector<QualType> SrcTypes;
15461
15462 if (!hlslElementwiseCastHelper(Info, SE, E->getType(), SrcVals, SrcTypes))
15463 return false;
15464
15465 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
15466 SmallVector<QualType, 16> DestTypes(NElts, EltTy);
15467 SmallVector<APValue, 16> ResultEls(NElts);
15468 if (!handleElementwiseCast(Info, E, FPO, SrcVals, SrcTypes, DestTypes,
15469 ResultEls))
15470 return false;
15471 return Success(ResultEls, E);
15472 }
15473 default:
15474 return ExprEvaluatorBaseTy::VisitCastExpr(E);
15475 }
15476}
15477
15478bool MatrixExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
15479 const auto *MT = E->getType()->castAs<ConstantMatrixType>();
15480 QualType EltTy = MT->getElementType();
15481
15482 assert(E->getNumInits() == MT->getNumElementsFlattened() &&
15483 "Expected number of elements in initializer list to match the number "
15484 "of matrix elements");
15485
15486 SmallVector<APValue, 16> Elements;
15487 Elements.reserve(MT->getNumElementsFlattened());
15488
15489 // The following loop assumes the elements of the matrix InitListExpr are in
15490 // row-major order, which matches the row-major ordering assumption of the
15491 // matrix APValue.
15492 for (unsigned I = 0, N = MT->getNumElementsFlattened(); I < N; ++I) {
15493 if (EltTy->isIntegerType()) {
15494 llvm::APSInt IntVal;
15495 if (!EvaluateInteger(E->getInit(I), IntVal, Info))
15496 return false;
15497 Elements.push_back(APValue(IntVal));
15498 } else {
15499 llvm::APFloat FloatVal(0.0);
15500 if (!EvaluateFloat(E->getInit(I), FloatVal, Info))
15501 return false;
15502 Elements.push_back(APValue(FloatVal));
15503 }
15504 }
15505
15506 return Success(Elements, E);
15507}
15508
15509//===----------------------------------------------------------------------===//
15510// Array Evaluation
15511//===----------------------------------------------------------------------===//
15512
15513namespace {
15514 class ArrayExprEvaluator
15515 : public ExprEvaluatorBase<ArrayExprEvaluator> {
15516 const LValue &This;
15517 APValue &Result;
15518 public:
15519
15520 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
15521 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
15522
15523 bool Success(const APValue &V, const Expr *E) {
15524 assert(V.isArray() && "expected array");
15525 Result = V;
15526 return true;
15527 }
15528
15529 bool ZeroInitialization(const Expr *E) {
15530 const ConstantArrayType *CAT =
15531 Info.Ctx.getAsConstantArrayType(E->getType());
15532 if (!CAT) {
15533 if (E->getType()->isIncompleteArrayType()) {
15534 // We can be asked to zero-initialize a flexible array member; this
15535 // is represented as an ImplicitValueInitExpr of incomplete array
15536 // type. In this case, the array has zero elements.
15537 Result = APValue(APValue::UninitArray(), 0, 0);
15538 return true;
15539 }
15540 // FIXME: We could handle VLAs here.
15541 return Error(E);
15542 }
15543
15544 Result = APValue(APValue::UninitArray(), 0, CAT->getZExtSize());
15545 if (!Result.hasArrayFiller())
15546 return true;
15547
15548 // Zero-initialize all elements.
15549 LValue Subobject = This;
15550 Subobject.addArray(Info, E, CAT);
15551 ImplicitValueInitExpr VIE(CAT->getElementType());
15552 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
15553 }
15554
15555 bool VisitCallExpr(const CallExpr *E) {
15556 return handleCallExpr(E, Result, &This);
15557 }
15558 bool VisitCastExpr(const CastExpr *E);
15559 bool VisitInitListExpr(const InitListExpr *E,
15560 QualType AllocType = QualType());
15561 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
15562 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
15563 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
15564 const LValue &Subobject,
15565 APValue *Value, QualType Type);
15566 bool VisitStringLiteral(const StringLiteral *E,
15567 QualType AllocType = QualType()) {
15568 expandStringLiteral(Info, E, Result, AllocType);
15569 return true;
15570 }
15571 bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E);
15572 bool VisitCXXParenListOrInitListExpr(const Expr *ExprToVisit,
15573 ArrayRef<Expr *> Args,
15574 const Expr *ArrayFiller,
15575 QualType AllocType = QualType());
15576 bool VisitDesignatedInitUpdateExpr(const DesignatedInitUpdateExpr *E);
15577 };
15578} // end anonymous namespace
15579
15580static bool EvaluateArray(const Expr *E, const LValue &This,
15581 APValue &Result, EvalInfo &Info) {
15582 assert(!E->isValueDependent());
15583 assert(E->isPRValue() && E->getType()->isArrayType() &&
15584 "not an array prvalue");
15585 return ArrayExprEvaluator(Info, This, Result).Visit(E);
15586}
15587
15588static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
15589 APValue &Result, const InitListExpr *ILE,
15590 QualType AllocType) {
15591 assert(!ILE->isValueDependent());
15592 assert(ILE->isPRValue() && ILE->getType()->isArrayType() &&
15593 "not an array prvalue");
15594 return ArrayExprEvaluator(Info, This, Result)
15595 .VisitInitListExpr(ILE, AllocType);
15596}
15597
15598static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
15599 APValue &Result,
15600 const CXXConstructExpr *CCE,
15601 QualType AllocType) {
15602 assert(!CCE->isValueDependent());
15603 assert(CCE->isPRValue() && CCE->getType()->isArrayType() &&
15604 "not an array prvalue");
15605 return ArrayExprEvaluator(Info, This, Result)
15606 .VisitCXXConstructExpr(CCE, This, &Result, AllocType);
15607}
15608
15609// Return true iff the given array filler may depend on the element index.
15610static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
15611 // For now, just allow non-class value-initialization and initialization
15612 // lists comprised of them.
15613 if (isa<ImplicitValueInitExpr>(FillerExpr))
15614 return false;
15615 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
15616 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
15617 if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
15618 return true;
15619 }
15620
15621 if (ILE->hasArrayFiller() &&
15622 MaybeElementDependentArrayFiller(ILE->getArrayFiller()))
15623 return true;
15624
15625 return false;
15626 }
15627 return true;
15628}
15629
15630bool ArrayExprEvaluator::VisitCastExpr(const CastExpr *E) {
15631 const Expr *SE = E->getSubExpr();
15632
15633 switch (E->getCastKind()) {
15634 default:
15635 return ExprEvaluatorBaseTy::VisitCastExpr(E);
15636 case CK_HLSLAggregateSplatCast: {
15637 APValue Val;
15638 QualType ValTy;
15639
15640 if (!hlslAggSplatHelper(Info, SE, Val, ValTy))
15641 return false;
15642
15643 unsigned NEls = elementwiseSize(Info, E->getType());
15644
15645 SmallVector<APValue> SplatEls(NEls, Val);
15646 SmallVector<QualType> SplatType(NEls, ValTy);
15647
15648 // cast the elements
15649 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
15650 if (!constructAggregate(Info, FPO, E, Result, E->getType(), SplatEls,
15651 SplatType))
15652 return false;
15653
15654 return true;
15655 }
15656 case CK_HLSLElementwiseCast: {
15657 SmallVector<APValue> SrcEls;
15658 SmallVector<QualType> SrcTypes;
15659
15660 if (!hlslElementwiseCastHelper(Info, SE, E->getType(), SrcEls, SrcTypes))
15661 return false;
15662
15663 // cast the elements
15664 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
15665 if (!constructAggregate(Info, FPO, E, Result, E->getType(), SrcEls,
15666 SrcTypes))
15667 return false;
15668 return true;
15669 }
15670 }
15671}
15672
15673bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E,
15674 QualType AllocType) {
15675 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
15676 AllocType.isNull() ? E->getType() : AllocType);
15677 if (!CAT)
15678 return Error(E);
15679
15680 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
15681 // an appropriately-typed string literal enclosed in braces.
15682 if (E->isStringLiteralInit()) {
15683 auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParenImpCasts());
15684 // FIXME: Support ObjCEncodeExpr here once we support it in
15685 // ArrayExprEvaluator generally.
15686 if (!SL)
15687 return Error(E);
15688 return VisitStringLiteral(SL, AllocType);
15689 }
15690 // Any other transparent list init will need proper handling of the
15691 // AllocType; we can't just recurse to the inner initializer.
15692 assert(!E->isTransparent() &&
15693 "transparent array list initialization is not string literal init?");
15694
15695 return VisitCXXParenListOrInitListExpr(E, E->inits(), E->getArrayFiller(),
15696 AllocType);
15697}
15698
15699bool ArrayExprEvaluator::VisitCXXParenListOrInitListExpr(
15700 const Expr *ExprToVisit, ArrayRef<Expr *> Args, const Expr *ArrayFiller,
15701 QualType AllocType) {
15702 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
15703 AllocType.isNull() ? ExprToVisit->getType() : AllocType);
15704
15705 bool Success = true;
15706
15707 unsigned NumEltsToInit = Args.size();
15708 unsigned NumElts = CAT->getZExtSize();
15709
15710 // If the initializer might depend on the array index, run it for each
15711 // array element.
15712 if (NumEltsToInit != NumElts &&
15713 MaybeElementDependentArrayFiller(ArrayFiller)) {
15714 NumEltsToInit = NumElts;
15715 } else {
15716 // Add additional elements represented by EmbedExpr.
15717 for (auto *Init : Args) {
15718 if (auto *EmbedS = dyn_cast<EmbedExpr>(Init->IgnoreParenImpCasts()))
15719 NumEltsToInit += EmbedS->getDataElementCount() - 1;
15720 }
15721 // If we have extra elements in the list, they will be discarded.
15722 if (NumEltsToInit > NumElts)
15723 NumEltsToInit = NumElts;
15724 // If we're overwriting memory which already has an object, make sure we
15725 // don't reduce the number of non-filler elements. (It's possible to
15726 // optimize this in some cases, but the logic gets really complicated.)
15727 if (Result.hasValue() && NumEltsToInit < Result.getArrayInitializedElts())
15728 NumEltsToInit = Result.getArrayInitializedElts();
15729 }
15730
15731 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
15732 << NumEltsToInit << ".\n");
15733
15734 if (!Result.hasValue()) {
15735 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
15736 } else if (Result.getArrayInitializedElts() != NumEltsToInit) {
15737 // Number of inititalized elts changed. Recreate the APValue, and copy over
15738 // the relevant elements. (This is essentially just fixing the internal
15739 // representation of the value, because it's tied to the number of
15740 // non-filler elements.)
15741 //
15742 // This should be hit rarely, but there are some edge cases:
15743 //
15744 // - The array could be zero-initialized.
15745 // - There could be a DesignatedInitListExpr.
15746 // - operator new[] can be used to start the lifetime early.
15747 APValue NewResult = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
15748 // First copy existing elements.
15749 unsigned NumOldElts = Result.getArrayInitializedElts();
15750 for (unsigned I = 0; I < NumOldElts; ++I) {
15751 NewResult.getArrayInitializedElt(I) =
15752 std::move(Result.getArrayInitializedElt(I));
15753 }
15754 // Then copy the array filler over the remaining elements.
15755 for (unsigned I = Result.getArrayInitializedElts(); I < NumEltsToInit; ++I)
15757 if (NewResult.hasArrayFiller() && Result.hasArrayFiller())
15758 NewResult.getArrayFiller() = Result.getArrayFiller();
15759 Result = std::move(NewResult);
15760 }
15761
15762 LValue Subobject = This;
15763 Subobject.addArray(Info, ExprToVisit, CAT);
15764 auto Eval = [&](const Expr *Init, unsigned ArrayIndex) {
15765 if (Init->isValueDependent())
15766 return EvaluateDependentExpr(Init, Info);
15767
15768 // If this is a child of a DesignatedInitUpdateExpr, skip elements which
15769 // aren't supposed to be modified.
15770 if (isa<NoInitExpr>(Init))
15771 return true;
15772
15773 if (!EvaluateInPlace(Result.getArrayInitializedElt(ArrayIndex), Info,
15774 Subobject, Init) ||
15775 !HandleLValueArrayAdjustment(Info, Init, Subobject,
15776 CAT->getElementType(), 1)) {
15777 if (!Info.noteFailure())
15778 return false;
15779 Success = false;
15780 }
15781 return true;
15782 };
15783 unsigned ArrayIndex = 0;
15784 QualType DestTy = CAT->getElementType();
15785 APSInt Value(Info.Ctx.getTypeSize(DestTy), DestTy->isUnsignedIntegerType());
15786 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
15787 const Expr *Init = Index < Args.size() ? Args[Index] : ArrayFiller;
15788 if (ArrayIndex >= NumEltsToInit)
15789 break;
15790 if (auto *EmbedS = dyn_cast<EmbedExpr>(Init->IgnoreParenImpCasts())) {
15791 StringLiteral *SL = EmbedS->getDataStringLiteral();
15792 for (unsigned I = EmbedS->getStartingElementPos(),
15793 N = EmbedS->getDataElementCount();
15794 I != EmbedS->getStartingElementPos() + N; ++I) {
15795 Value = SL->getCodeUnit(I);
15796 if (DestTy->isIntegerType()) {
15797 Result.getArrayInitializedElt(ArrayIndex) = APValue(Value);
15798 } else {
15799 assert(DestTy->isFloatingType() && "unexpected type");
15800 const FPOptions FPO =
15801 Init->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
15802 APFloat FValue(0.0);
15803 if (!HandleIntToFloatCast(Info, Init, FPO, EmbedS->getType(), Value,
15804 DestTy, FValue))
15805 return false;
15806 Result.getArrayInitializedElt(ArrayIndex) = APValue(FValue);
15807 }
15808 ArrayIndex++;
15809 }
15810 } else {
15811 if (!Eval(Init, ArrayIndex))
15812 return false;
15813 ++ArrayIndex;
15814 }
15815 }
15816
15817 if (!Result.hasArrayFiller())
15818 return Success;
15819
15820 // If we get here, we have a trivial filler, which we can just evaluate
15821 // once and splat over the rest of the array elements.
15822 assert(ArrayFiller && "no array filler for incomplete init list");
15823 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
15824 ArrayFiller) &&
15825 Success;
15826}
15827
15828bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
15829 LValue CommonLV;
15830 if (E->getCommonExpr() &&
15831 !Evaluate(Info.CurrentCall->createTemporary(
15832 E->getCommonExpr(),
15833 getStorageType(Info.Ctx, E->getCommonExpr()),
15834 ScopeKind::FullExpression, CommonLV),
15835 Info, E->getCommonExpr()->getSourceExpr()))
15836 return false;
15837
15839
15840 uint64_t Elements = CAT->getZExtSize();
15841 Result = APValue(APValue::UninitArray(), Elements, Elements);
15842
15843 LValue Subobject = This;
15844 Subobject.addArray(Info, E, CAT);
15845
15846 bool Success = true;
15847 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
15848 // C++ [class.temporary]/5
15849 // There are four contexts in which temporaries are destroyed at a different
15850 // point than the end of the full-expression. [...] The second context is
15851 // when a copy constructor is called to copy an element of an array while
15852 // the entire array is copied [...]. In either case, if the constructor has
15853 // one or more default arguments, the destruction of every temporary created
15854 // in a default argument is sequenced before the construction of the next
15855 // array element, if any.
15856 FullExpressionRAII Scope(Info);
15857
15858 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
15859 Info, Subobject, E->getSubExpr()) ||
15860 !HandleLValueArrayAdjustment(Info, E, Subobject,
15861 CAT->getElementType(), 1)) {
15862 if (!Info.noteFailure())
15863 return false;
15864 Success = false;
15865 }
15866
15867 // Make sure we run the destructors too.
15868 Scope.destroy();
15869 }
15870
15871 return Success;
15872}
15873
15874bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
15875 return VisitCXXConstructExpr(E, This, &Result, E->getType());
15876}
15877
15878bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
15879 const LValue &Subobject,
15880 APValue *Value,
15881 QualType Type) {
15882 bool HadZeroInit = Value->hasValue();
15883
15884 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
15885 unsigned FinalSize = CAT->getZExtSize();
15886
15887 // Preserve the array filler if we had prior zero-initialization.
15888 APValue Filler =
15889 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
15890 : APValue();
15891
15892 *Value = APValue(APValue::UninitArray(), 0, FinalSize);
15893 if (FinalSize == 0)
15894 return true;
15895
15896 bool HasTrivialConstructor = CheckTrivialDefaultConstructor(
15897 Info, E->getExprLoc(), E->getConstructor(),
15899 LValue ArrayElt = Subobject;
15900 ArrayElt.addArray(Info, E, CAT);
15901 // We do the whole initialization in two passes, first for just one element,
15902 // then for the whole array. It's possible we may find out we can't do const
15903 // init in the first pass, in which case we avoid allocating a potentially
15904 // large array. We don't do more passes because expanding array requires
15905 // copying the data, which is wasteful.
15906 for (const unsigned N : {1u, FinalSize}) {
15907 unsigned OldElts = Value->getArrayInitializedElts();
15908 if (OldElts == N)
15909 break;
15910
15911 // Expand the array to appropriate size.
15912 APValue NewValue(APValue::UninitArray(), N, FinalSize);
15913 for (unsigned I = 0; I < OldElts; ++I)
15914 NewValue.getArrayInitializedElt(I).swap(
15915 Value->getArrayInitializedElt(I));
15916 Value->swap(NewValue);
15917
15918 if (HadZeroInit)
15919 for (unsigned I = OldElts; I < N; ++I)
15920 Value->getArrayInitializedElt(I) = Filler;
15921
15922 if (HasTrivialConstructor && N == FinalSize && FinalSize != 1) {
15923 // If we have a trivial constructor, only evaluate it once and copy
15924 // the result into all the array elements.
15925 APValue &FirstResult = Value->getArrayInitializedElt(0);
15926 for (unsigned I = OldElts; I < FinalSize; ++I)
15927 Value->getArrayInitializedElt(I) = FirstResult;
15928 } else {
15929 for (unsigned I = OldElts; I < N; ++I) {
15930 if (!VisitCXXConstructExpr(E, ArrayElt,
15931 &Value->getArrayInitializedElt(I),
15932 CAT->getElementType()) ||
15933 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
15934 CAT->getElementType(), 1))
15935 return false;
15936 // When checking for const initilization any diagnostic is considered
15937 // an error.
15938 if (Info.EvalStatus.Diag && !Info.EvalStatus.Diag->empty() &&
15939 !Info.keepEvaluatingAfterFailure())
15940 return false;
15941 }
15942 }
15943 }
15944
15945 return true;
15946 }
15947
15948 if (!Type->isRecordType())
15949 return Error(E);
15950
15951 return RecordExprEvaluator(Info, Subobject, *Value)
15952 .VisitCXXConstructExpr(E, Type);
15953}
15954
15955bool ArrayExprEvaluator::VisitCXXParenListInitExpr(
15956 const CXXParenListInitExpr *E) {
15957 assert(E->getType()->isConstantArrayType() &&
15958 "Expression result is not a constant array type");
15959
15960 return VisitCXXParenListOrInitListExpr(E, E->getInitExprs(),
15961 E->getArrayFiller());
15962}
15963
15964bool ArrayExprEvaluator::VisitDesignatedInitUpdateExpr(
15965 const DesignatedInitUpdateExpr *E) {
15966 if (!Visit(E->getBase()))
15967 return false;
15968 return Visit(E->getUpdater());
15969}
15970
15971//===----------------------------------------------------------------------===//
15972// Integer Evaluation
15973//
15974// As a GNU extension, we support casting pointers to sufficiently-wide integer
15975// types and back in constant folding. Integer values are thus represented
15976// either as an integer-valued APValue, or as an lvalue-valued APValue.
15977//===----------------------------------------------------------------------===//
15978
15979namespace {
15980class IntExprEvaluator
15981 : public ExprEvaluatorBase<IntExprEvaluator> {
15982 APValue &Result;
15983public:
15984 IntExprEvaluator(EvalInfo &info, APValue &result)
15985 : ExprEvaluatorBaseTy(info), Result(result) {}
15986
15987 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
15988 assert(E->getType()->isIntegralOrEnumerationType() &&
15989 "Invalid evaluation result.");
15990 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
15991 "Invalid evaluation result.");
15992 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
15993 "Invalid evaluation result.");
15994 Result = APValue(SI);
15995 return true;
15996 }
15997 bool Success(const llvm::APSInt &SI, const Expr *E) {
15998 return Success(SI, E, Result);
15999 }
16000
16001 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
16002 assert(E->getType()->isIntegralOrEnumerationType() &&
16003 "Invalid evaluation result.");
16004 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
16005 "Invalid evaluation result.");
16006 Result = APValue(APSInt(I));
16007 Result.getInt().setIsUnsigned(
16009 return true;
16010 }
16011 bool Success(const llvm::APInt &I, const Expr *E) {
16012 return Success(I, E, Result);
16013 }
16014
16015 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
16016 assert(E->getType()->isIntegralOrEnumerationType() &&
16017 "Invalid evaluation result.");
16018 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
16019 return true;
16020 }
16021 bool Success(uint64_t Value, const Expr *E) {
16022 return Success(Value, E, Result);
16023 }
16024
16025 bool Success(CharUnits Size, const Expr *E) {
16026 return Success(Size.getQuantity(), E);
16027 }
16028
16029 bool Success(const APValue &V, const Expr *E) {
16030 // C++23 [expr.const]p8 If we have a variable that is unknown reference or
16031 // pointer allow further evaluation of the value.
16032 if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate() ||
16033 V.allowConstexprUnknown()) {
16034 Result = V;
16035 return true;
16036 }
16037 return Success(V.getInt(), E);
16038 }
16039
16040 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
16041
16042 friend std::optional<bool> EvaluateBuiltinIsWithinLifetime(IntExprEvaluator &,
16043 const CallExpr *);
16044
16045 //===--------------------------------------------------------------------===//
16046 // Visitor Methods
16047 //===--------------------------------------------------------------------===//
16048
16049 bool VisitIntegerLiteral(const IntegerLiteral *E) {
16050 return Success(E->getValue(), E);
16051 }
16052 bool VisitCharacterLiteral(const CharacterLiteral *E) {
16053 return Success(E->getValue(), E);
16054 }
16055
16056 bool CheckReferencedDecl(const Expr *E, const Decl *D);
16057 bool VisitDeclRefExpr(const DeclRefExpr *E) {
16058 if (CheckReferencedDecl(E, E->getDecl()))
16059 return true;
16060
16061 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
16062 }
16063 bool VisitMemberExpr(const MemberExpr *E) {
16064 if (CheckReferencedDecl(E, E->getMemberDecl())) {
16065 VisitIgnoredBaseExpression(E->getBase());
16066 return true;
16067 }
16068
16069 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
16070 }
16071
16072 bool VisitCallExpr(const CallExpr *E);
16073 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
16074 bool VisitBinaryOperator(const BinaryOperator *E);
16075 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
16076 bool VisitUnaryOperator(const UnaryOperator *E);
16077
16078 bool VisitCastExpr(const CastExpr* E);
16079 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
16080
16081 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
16082 return Success(E->getValue(), E);
16083 }
16084
16085 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
16086 return Success(E->getValue(), E);
16087 }
16088
16089 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
16090 if (Info.ArrayInitIndex == uint64_t(-1)) {
16091 // We were asked to evaluate this subexpression independent of the
16092 // enclosing ArrayInitLoopExpr. We can't do that.
16093 Info.FFDiag(E);
16094 return false;
16095 }
16096 return Success(Info.ArrayInitIndex, E);
16097 }
16098
16099 // Note, GNU defines __null as an integer, not a pointer.
16100 bool VisitGNUNullExpr(const GNUNullExpr *E) {
16101 return ZeroInitialization(E);
16102 }
16103
16104 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
16105 if (E->isStoredAsBoolean())
16106 return Success(E->getBoolValue(), E);
16107 if (E->getAPValue().isAbsent())
16108 return false;
16109 assert(E->getAPValue().isInt() && "APValue type not supported");
16110 return Success(E->getAPValue().getInt(), E);
16111 }
16112
16113 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
16114 return Success(E->getValue(), E);
16115 }
16116
16117 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
16118 return Success(E->getValue(), E);
16119 }
16120
16121 bool VisitOpenACCAsteriskSizeExpr(const OpenACCAsteriskSizeExpr *E) {
16122 // This should not be evaluated during constant expr evaluation, as it
16123 // should always be in an unevaluated context (the args list of a 'gang' or
16124 // 'tile' clause).
16125 return Error(E);
16126 }
16127
16128 bool VisitUnaryReal(const UnaryOperator *E);
16129 bool VisitUnaryImag(const UnaryOperator *E);
16130
16131 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
16132 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
16133 bool VisitSourceLocExpr(const SourceLocExpr *E);
16134 bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E);
16135 bool VisitRequiresExpr(const RequiresExpr *E);
16136 // FIXME: Missing: array subscript of vector, member of vector
16137};
16138
16139class FixedPointExprEvaluator
16140 : public ExprEvaluatorBase<FixedPointExprEvaluator> {
16141 APValue &Result;
16142
16143 public:
16144 FixedPointExprEvaluator(EvalInfo &info, APValue &result)
16145 : ExprEvaluatorBaseTy(info), Result(result) {}
16146
16147 bool Success(const llvm::APInt &I, const Expr *E) {
16148 return Success(
16149 APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
16150 }
16151
16152 bool Success(uint64_t Value, const Expr *E) {
16153 return Success(
16154 APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
16155 }
16156
16157 bool Success(const APValue &V, const Expr *E) {
16158 return Success(V.getFixedPoint(), E);
16159 }
16160
16161 bool Success(const APFixedPoint &V, const Expr *E) {
16162 assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
16163 assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
16164 "Invalid evaluation result.");
16165 Result = APValue(V);
16166 return true;
16167 }
16168
16169 bool ZeroInitialization(const Expr *E) {
16170 return Success(0, E);
16171 }
16172
16173 //===--------------------------------------------------------------------===//
16174 // Visitor Methods
16175 //===--------------------------------------------------------------------===//
16176
16177 bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
16178 return Success(E->getValue(), E);
16179 }
16180
16181 bool VisitCastExpr(const CastExpr *E);
16182 bool VisitUnaryOperator(const UnaryOperator *E);
16183 bool VisitBinaryOperator(const BinaryOperator *E);
16184};
16185} // end anonymous namespace
16186
16187/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
16188/// produce either the integer value or a pointer.
16189///
16190/// GCC has a heinous extension which folds casts between pointer types and
16191/// pointer-sized integral types. We support this by allowing the evaluation of
16192/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
16193/// Some simple arithmetic on such values is supported (they are treated much
16194/// like char*).
16196 EvalInfo &Info) {
16197 assert(!E->isValueDependent());
16198 assert(E->isPRValue() && E->getType()->isIntegralOrEnumerationType());
16199 return IntExprEvaluator(Info, Result).Visit(E);
16200}
16201
16202static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
16203 assert(!E->isValueDependent());
16204 APValue Val;
16205 if (!EvaluateIntegerOrLValue(E, Val, Info))
16206 return false;
16207 if (!Val.isInt()) {
16208 // FIXME: It would be better to produce the diagnostic for casting
16209 // a pointer to an integer.
16210 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
16211 return false;
16212 }
16213 Result = Val.getInt();
16214 return true;
16215}
16216
16217bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
16219 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
16220 return Success(Evaluated, E);
16221}
16222
16223static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
16224 EvalInfo &Info) {
16225 assert(!E->isValueDependent());
16226 if (E->getType()->isFixedPointType()) {
16227 APValue Val;
16228 if (!FixedPointExprEvaluator(Info, Val).Visit(E))
16229 return false;
16230 if (!Val.isFixedPoint())
16231 return false;
16232
16233 Result = Val.getFixedPoint();
16234 return true;
16235 }
16236 return false;
16237}
16238
16239static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
16240 EvalInfo &Info) {
16241 assert(!E->isValueDependent());
16242 if (E->getType()->isIntegerType()) {
16243 auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
16244 APSInt Val;
16245 if (!EvaluateInteger(E, Val, Info))
16246 return false;
16247 Result = APFixedPoint(Val, FXSema);
16248 return true;
16249 } else if (E->getType()->isFixedPointType()) {
16250 return EvaluateFixedPoint(E, Result, Info);
16251 }
16252 return false;
16253}
16254
16255/// Check whether the given declaration can be directly converted to an integral
16256/// rvalue. If not, no diagnostic is produced; there are other things we can
16257/// try.
16258bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
16259 // Enums are integer constant exprs.
16260 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
16261 // Check for signedness/width mismatches between E type and ECD value.
16262 bool SameSign = (ECD->getInitVal().isSigned()
16264 bool SameWidth = (ECD->getInitVal().getBitWidth()
16265 == Info.Ctx.getIntWidth(E->getType()));
16266 if (SameSign && SameWidth)
16267 return Success(ECD->getInitVal(), E);
16268 else {
16269 // Get rid of mismatch (otherwise Success assertions will fail)
16270 // by computing a new value matching the type of E.
16271 llvm::APSInt Val = ECD->getInitVal();
16272 if (!SameSign)
16273 Val.setIsSigned(!ECD->getInitVal().isSigned());
16274 if (!SameWidth)
16275 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
16276 return Success(Val, E);
16277 }
16278 }
16279 return false;
16280}
16281
16282/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
16283/// as GCC.
16285 const LangOptions &LangOpts) {
16286 assert(!T->isDependentType() && "unexpected dependent type");
16287
16288 QualType CanTy = T.getCanonicalType();
16289
16290 switch (CanTy->getTypeClass()) {
16291#define TYPE(ID, BASE)
16292#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
16293#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
16294#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
16295#include "clang/AST/TypeNodes.inc"
16296 case Type::Auto:
16297 case Type::DeducedTemplateSpecialization:
16298 llvm_unreachable("unexpected non-canonical or dependent type");
16299
16300 case Type::Builtin:
16301 switch (cast<BuiltinType>(CanTy)->getKind()) {
16302#define BUILTIN_TYPE(ID, SINGLETON_ID)
16303#define SIGNED_TYPE(ID, SINGLETON_ID) \
16304 case BuiltinType::ID: return GCCTypeClass::Integer;
16305#define FLOATING_TYPE(ID, SINGLETON_ID) \
16306 case BuiltinType::ID: return GCCTypeClass::RealFloat;
16307#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
16308 case BuiltinType::ID: break;
16309#include "clang/AST/BuiltinTypes.def"
16310 case BuiltinType::Void:
16311 return GCCTypeClass::Void;
16312
16313 case BuiltinType::Bool:
16314 return GCCTypeClass::Bool;
16315
16316 case BuiltinType::Char_U:
16317 case BuiltinType::UChar:
16318 case BuiltinType::WChar_U:
16319 case BuiltinType::Char8:
16320 case BuiltinType::Char16:
16321 case BuiltinType::Char32:
16322 case BuiltinType::UShort:
16323 case BuiltinType::UInt:
16324 case BuiltinType::ULong:
16325 case BuiltinType::ULongLong:
16326 case BuiltinType::UInt128:
16327 return GCCTypeClass::Integer;
16328
16329 case BuiltinType::UShortAccum:
16330 case BuiltinType::UAccum:
16331 case BuiltinType::ULongAccum:
16332 case BuiltinType::UShortFract:
16333 case BuiltinType::UFract:
16334 case BuiltinType::ULongFract:
16335 case BuiltinType::SatUShortAccum:
16336 case BuiltinType::SatUAccum:
16337 case BuiltinType::SatULongAccum:
16338 case BuiltinType::SatUShortFract:
16339 case BuiltinType::SatUFract:
16340 case BuiltinType::SatULongFract:
16341 return GCCTypeClass::None;
16342
16343 case BuiltinType::NullPtr:
16344
16345 case BuiltinType::ObjCId:
16346 case BuiltinType::ObjCClass:
16347 case BuiltinType::ObjCSel:
16348#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
16349 case BuiltinType::Id:
16350#include "clang/Basic/OpenCLImageTypes.def"
16351#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
16352 case BuiltinType::Id:
16353#include "clang/Basic/OpenCLExtensionTypes.def"
16354 case BuiltinType::OCLSampler:
16355 case BuiltinType::OCLEvent:
16356 case BuiltinType::OCLClkEvent:
16357 case BuiltinType::OCLQueue:
16358 case BuiltinType::OCLReserveID:
16359#define SVE_TYPE(Name, Id, SingletonId) \
16360 case BuiltinType::Id:
16361#include "clang/Basic/AArch64ACLETypes.def"
16362#define PPC_VECTOR_TYPE(Name, Id, Size) \
16363 case BuiltinType::Id:
16364#include "clang/Basic/PPCTypes.def"
16365#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
16366#include "clang/Basic/RISCVVTypes.def"
16367#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
16368#include "clang/Basic/WebAssemblyReferenceTypes.def"
16369#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
16370#include "clang/Basic/AMDGPUTypes.def"
16371#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
16372#include "clang/Basic/HLSLIntangibleTypes.def"
16373#define SPIRV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
16374#include "clang/Basic/SPIRVTypes.def"
16375 return GCCTypeClass::None;
16376
16377 case BuiltinType::Dependent:
16378 llvm_unreachable("unexpected dependent type");
16379 };
16380 llvm_unreachable("unexpected placeholder type");
16381
16382 case Type::Enum:
16383 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
16384
16385 case Type::Pointer:
16386 case Type::ConstantArray:
16387 case Type::VariableArray:
16388 case Type::IncompleteArray:
16389 case Type::FunctionNoProto:
16390 case Type::FunctionProto:
16391 case Type::ArrayParameter:
16392 return GCCTypeClass::Pointer;
16393
16394 case Type::MemberPointer:
16395 return CanTy->isMemberDataPointerType()
16398
16399 case Type::Complex:
16400 return GCCTypeClass::Complex;
16401
16402 case Type::Record:
16403 return CanTy->isUnionType() ? GCCTypeClass::Union
16405
16406 case Type::Atomic:
16407 // GCC classifies _Atomic T the same as T.
16409 CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
16410
16411 case Type::Vector:
16412 case Type::ExtVector:
16413 return GCCTypeClass::Vector;
16414
16415 case Type::BlockPointer:
16416 case Type::ConstantMatrix:
16417 case Type::ObjCObject:
16418 case Type::ObjCInterface:
16419 case Type::ObjCObjectPointer:
16420 case Type::Pipe:
16421 case Type::HLSLAttributedResource:
16422 case Type::HLSLInlineSpirv:
16423 case Type::OverflowBehavior:
16424 // Classify all other types that don't fit into the regular
16425 // classification the same way.
16426 return GCCTypeClass::None;
16427
16428 case Type::BitInt:
16429 return GCCTypeClass::BitInt;
16430
16431 case Type::LValueReference:
16432 case Type::RValueReference:
16433 llvm_unreachable("invalid type for expression");
16434 }
16435
16436 llvm_unreachable("unexpected type class");
16437}
16438
16439/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
16440/// as GCC.
16441static GCCTypeClass
16443 // If no argument was supplied, default to None. This isn't
16444 // ideal, however it is what gcc does.
16445 if (E->getNumArgs() == 0)
16446 return GCCTypeClass::None;
16447
16448 // FIXME: Bizarrely, GCC treats a call with more than one argument as not
16449 // being an ICE, but still folds it to a constant using the type of the first
16450 // argument.
16451 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
16452}
16453
16454/// EvaluateBuiltinConstantPForLValue - Determine the result of
16455/// __builtin_constant_p when applied to the given pointer.
16456///
16457/// A pointer is only "constant" if it is null (or a pointer cast to integer)
16458/// or it points to the first character of a string literal.
16461 if (Base.isNull()) {
16462 // A null base is acceptable.
16463 return true;
16464 } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
16465 if (!isa<StringLiteral>(E))
16466 return false;
16467 return LV.getLValueOffset().isZero();
16468 } else if (Base.is<TypeInfoLValue>()) {
16469 // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
16470 // evaluate to true.
16471 return true;
16472 } else {
16473 // Any other base is not constant enough for GCC.
16474 return false;
16475 }
16476}
16477
16478/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
16479/// GCC as we can manage.
16480static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
16481 // This evaluation is not permitted to have side-effects, so evaluate it in
16482 // a speculative evaluation context.
16483 SpeculativeEvaluationRAII SpeculativeEval(Info);
16484
16485 // Constant-folding is always enabled for the operand of __builtin_constant_p
16486 // (even when the enclosing evaluation context otherwise requires a strict
16487 // language-specific constant expression).
16488 FoldConstant Fold(Info, true);
16489
16490 QualType ArgType = Arg->getType();
16491
16492 // __builtin_constant_p always has one operand. The rules which gcc follows
16493 // are not precisely documented, but are as follows:
16494 //
16495 // - If the operand is of integral, floating, complex or enumeration type,
16496 // and can be folded to a known value of that type, it returns 1.
16497 // - If the operand can be folded to a pointer to the first character
16498 // of a string literal (or such a pointer cast to an integral type)
16499 // or to a null pointer or an integer cast to a pointer, it returns 1.
16500 //
16501 // Otherwise, it returns 0.
16502 //
16503 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
16504 // its support for this did not work prior to GCC 9 and is not yet well
16505 // understood.
16506 if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
16507 ArgType->isAnyComplexType() || ArgType->isPointerType() ||
16508 ArgType->isNullPtrType()) {
16509 APValue V;
16510 if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) {
16511 Fold.keepDiagnostics();
16512 return false;
16513 }
16514
16515 // For a pointer (possibly cast to integer), there are special rules.
16516 if (V.getKind() == APValue::LValue)
16518
16519 // Otherwise, any constant value is good enough.
16520 return V.hasValue();
16521 }
16522
16523 // Anything else isn't considered to be sufficiently constant.
16524 return false;
16525}
16526
16527/// Retrieves the "underlying object type" of the given expression,
16528/// as used by __builtin_object_size.
16530 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
16531 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
16532 return VD->getType();
16533 } else if (const Expr *E = B.dyn_cast<const Expr*>()) {
16535 return E->getType();
16536 } else if (B.is<TypeInfoLValue>()) {
16537 return B.getTypeInfoType();
16538 } else if (B.is<DynamicAllocLValue>()) {
16539 return B.getDynamicAllocType();
16540 }
16541
16542 return QualType();
16543}
16544
16545/// A more selective version of E->IgnoreParenCasts for
16546/// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
16547/// to change the type of E.
16548/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
16549///
16550/// Always returns an RValue with a pointer representation.
16551static const Expr *ignorePointerCastsAndParens(const Expr *E) {
16552 assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
16553
16554 const Expr *NoParens = E->IgnoreParens();
16555 const auto *Cast = dyn_cast<CastExpr>(NoParens);
16556 if (Cast == nullptr)
16557 return NoParens;
16558
16559 // We only conservatively allow a few kinds of casts, because this code is
16560 // inherently a simple solution that seeks to support the common case.
16561 auto CastKind = Cast->getCastKind();
16562 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
16563 CastKind != CK_AddressSpaceConversion)
16564 return NoParens;
16565
16566 const auto *SubExpr = Cast->getSubExpr();
16567 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isPRValue())
16568 return NoParens;
16569 return ignorePointerCastsAndParens(SubExpr);
16570}
16571
16572/// Checks to see if the given LValue's Designator is at the end of the LValue's
16573/// record layout. e.g.
16574/// struct { struct { int a, b; } fst, snd; } obj;
16575/// obj.fst // no
16576/// obj.snd // yes
16577/// obj.fst.a // no
16578/// obj.fst.b // no
16579/// obj.snd.a // no
16580/// obj.snd.b // yes
16581///
16582/// Please note: this function is specialized for how __builtin_object_size
16583/// views "objects".
16584///
16585/// If this encounters an invalid RecordDecl or otherwise cannot determine the
16586/// correct result, it will always return true.
16587static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
16588 assert(!LVal.Designator.Invalid);
16589
16590 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD) {
16591 const RecordDecl *Parent = FD->getParent();
16592 if (Parent->isInvalidDecl() || Parent->isUnion())
16593 return true;
16594 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
16595 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
16596 };
16597
16598 auto &Base = LVal.getLValueBase();
16599 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
16600 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
16601 if (!IsLastOrInvalidFieldDecl(FD))
16602 return false;
16603 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
16604 for (auto *FD : IFD->chain()) {
16605 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD)))
16606 return false;
16607 }
16608 }
16609 }
16610
16611 unsigned I = 0;
16612 QualType BaseType = getType(Base);
16613 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
16614 // If we don't know the array bound, conservatively assume we're looking at
16615 // the final array element.
16616 ++I;
16617 if (BaseType->isIncompleteArrayType())
16618 BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
16619 else
16620 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
16621 }
16622
16623 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
16624 const auto &Entry = LVal.Designator.Entries[I];
16625 if (BaseType->isArrayType()) {
16626 // Because __builtin_object_size treats arrays as objects, we can ignore
16627 // the index iff this is the last array in the Designator.
16628 if (I + 1 == E)
16629 return true;
16630 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
16631 uint64_t Index = Entry.getAsArrayIndex();
16632 if (Index + 1 != CAT->getZExtSize())
16633 return false;
16634 BaseType = CAT->getElementType();
16635 } else if (BaseType->isAnyComplexType()) {
16636 const auto *CT = BaseType->castAs<ComplexType>();
16637 uint64_t Index = Entry.getAsArrayIndex();
16638 if (Index != 1)
16639 return false;
16640 BaseType = CT->getElementType();
16641 } else if (auto *FD = getAsField(Entry)) {
16642 if (!IsLastOrInvalidFieldDecl(FD))
16643 return false;
16644 BaseType = FD->getType();
16645 } else {
16646 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
16647 return false;
16648 }
16649 }
16650 return true;
16651}
16652
16653/// Tests to see if the LValue has a user-specified designator (that isn't
16654/// necessarily valid). Note that this always returns 'true' if the LValue has
16655/// an unsized array as its first designator entry, because there's currently no
16656/// way to tell if the user typed *foo or foo[0].
16657static bool refersToCompleteObject(const LValue &LVal) {
16658 if (LVal.Designator.Invalid)
16659 return false;
16660
16661 if (!LVal.Designator.Entries.empty())
16662 return LVal.Designator.isMostDerivedAnUnsizedArray();
16663
16664 if (!LVal.InvalidBase)
16665 return true;
16666
16667 // If `E` is a MemberExpr, then the first part of the designator is hiding in
16668 // the LValueBase.
16669 const auto *E = LVal.Base.dyn_cast<const Expr *>();
16670 return !E || !isa<MemberExpr>(E);
16671}
16672
16673/// Attempts to detect a user writing into a piece of memory that's impossible
16674/// to figure out the size of by just using types.
16675static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
16676 const SubobjectDesignator &Designator = LVal.Designator;
16677 // Notes:
16678 // - Users can only write off of the end when we have an invalid base. Invalid
16679 // bases imply we don't know where the memory came from.
16680 // - We used to be a bit more aggressive here; we'd only be conservative if
16681 // the array at the end was flexible, or if it had 0 or 1 elements. This
16682 // broke some common standard library extensions (PR30346), but was
16683 // otherwise seemingly fine. It may be useful to reintroduce this behavior
16684 // with some sort of list. OTOH, it seems that GCC is always
16685 // conservative with the last element in structs (if it's an array), so our
16686 // current behavior is more compatible than an explicit list approach would
16687 // be.
16688 auto isFlexibleArrayMember = [&] {
16690 FAMKind StrictFlexArraysLevel =
16691 Ctx.getLangOpts().getStrictFlexArraysLevel();
16692
16693 if (Designator.isMostDerivedAnUnsizedArray())
16694 return true;
16695
16696 if (StrictFlexArraysLevel == FAMKind::Default)
16697 return true;
16698
16699 if (Designator.getMostDerivedArraySize() == 0 &&
16700 StrictFlexArraysLevel != FAMKind::IncompleteOnly)
16701 return true;
16702
16703 if (Designator.getMostDerivedArraySize() == 1 &&
16704 StrictFlexArraysLevel == FAMKind::OneZeroOrIncomplete)
16705 return true;
16706
16707 return false;
16708 };
16709
16710 return LVal.InvalidBase &&
16711 Designator.Entries.size() == Designator.MostDerivedPathLength &&
16712 Designator.MostDerivedIsArrayElement && isFlexibleArrayMember() &&
16713 isDesignatorAtObjectEnd(Ctx, LVal);
16714}
16715
16716/// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
16717/// Fails if the conversion would cause loss of precision.
16718static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
16719 CharUnits &Result) {
16720 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
16721 if (Int.ugt(CharUnitsMax))
16722 return false;
16723 Result = CharUnits::fromQuantity(Int.getZExtValue());
16724 return true;
16725}
16726
16727/// If we're evaluating the object size of an instance of a struct that
16728/// contains a flexible array member, add the size of the initializer.
16729static void addFlexibleArrayMemberInitSize(EvalInfo &Info, const QualType &T,
16730 const LValue &LV, CharUnits &Size) {
16731 if (!T.isNull() && T->isStructureType() &&
16732 T->castAsRecordDecl()->hasFlexibleArrayMember())
16733 if (const auto *V = LV.getLValueBase().dyn_cast<const ValueDecl *>())
16734 if (const auto *VD = dyn_cast<VarDecl>(V))
16735 if (VD->hasInit())
16736 Size += VD->getFlexibleArrayInitChars(Info.Ctx);
16737}
16738
16739/// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
16740/// determine how many bytes exist from the beginning of the object to either
16741/// the end of the current subobject, or the end of the object itself, depending
16742/// on what the LValue looks like + the value of Type.
16743///
16744/// If this returns false, the value of Result is undefined.
16745static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
16746 unsigned Type, const LValue &LVal,
16747 CharUnits &EndOffset) {
16748 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
16749
16750 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
16751 if (Ty.isNull())
16752 return false;
16753
16754 Ty = Ty.getNonReferenceType();
16755
16756 if (Ty->isIncompleteType() || Ty->isFunctionType())
16757 return false;
16758
16759 return HandleSizeof(Info, ExprLoc, Ty, Result);
16760 };
16761
16762 // We want to evaluate the size of the entire object. This is a valid fallback
16763 // for when Type=1 and the designator is invalid, because we're asked for an
16764 // upper-bound.
16765 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
16766 // Type=3 wants a lower bound, so we can't fall back to this.
16767 if (Type == 3 && !DetermineForCompleteObject)
16768 return false;
16769
16770 llvm::APInt APEndOffset;
16771 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
16772 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
16773 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
16774
16775 if (LVal.InvalidBase)
16776 return false;
16777
16778 QualType BaseTy = getObjectType(LVal.getLValueBase());
16779 const bool Ret = CheckedHandleSizeof(BaseTy, EndOffset);
16780 addFlexibleArrayMemberInitSize(Info, BaseTy, LVal, EndOffset);
16781 return Ret;
16782 }
16783
16784 // We want to evaluate the size of a subobject.
16785 const SubobjectDesignator &Designator = LVal.Designator;
16786
16787 // The following is a moderately common idiom in C:
16788 //
16789 // struct Foo { int a; char c[1]; };
16790 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
16791 // strcpy(&F->c[0], Bar);
16792 //
16793 // In order to not break too much legacy code, we need to support it.
16794 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
16795 // If we can resolve this to an alloc_size call, we can hand that back,
16796 // because we know for certain how many bytes there are to write to.
16797 llvm::APInt APEndOffset;
16798 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
16799 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
16800 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
16801
16802 // If we cannot determine the size of the initial allocation, then we can't
16803 // given an accurate upper-bound. However, we are still able to give
16804 // conservative lower-bounds for Type=3.
16805 if (Type == 1)
16806 return false;
16807 }
16808
16809 CharUnits BytesPerElem;
16810 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
16811 return false;
16812
16813 // According to the GCC documentation, we want the size of the subobject
16814 // denoted by the pointer. But that's not quite right -- what we actually
16815 // want is the size of the immediately-enclosing array, if there is one.
16816 int64_t ElemsRemaining;
16817 if (Designator.MostDerivedIsArrayElement &&
16818 Designator.Entries.size() == Designator.MostDerivedPathLength) {
16819 uint64_t ArraySize = Designator.getMostDerivedArraySize();
16820 uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
16821 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
16822 } else {
16823 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
16824 }
16825
16826 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
16827 return true;
16828}
16829
16830/// Tries to evaluate the __builtin_object_size for @p E.
16831///
16832/// If @p IsDynamic is true (i.e. we're evaluating
16833/// __builtin_dynamic_object_size) and the operand designates a flexible array
16834/// member annotated with 'counted_by', we refuse to fold so that IR generation
16835/// can emit the count-based runtime size computation.
16836static std::optional<uint64_t>
16837tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type, EvalInfo &Info,
16838 bool IsDynamic = false) {
16839
16840 // Determine the denoted object.
16841 LValue LVal;
16842 {
16843 // The operand of __builtin_object_size is never evaluated for side-effects.
16844 // If there are any, but we can determine the pointed-to object anyway, then
16845 // ignore the side-effects.
16846 SpeculativeEvaluationRAII SpeculativeEval(Info);
16847 IgnoreSideEffectsRAII Fold(Info);
16848
16849 if (E->isGLValue()) {
16850 // It's possible for us to be given GLValues if we're called via
16851 // Expr::tryEvaluateObjectSize.
16852 APValue RVal;
16853 if (!EvaluateAsRValue(Info, E, RVal))
16854 return std::nullopt;
16855 LVal.setFrom(Info.Ctx, RVal);
16856 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
16857 /*InvalidBaseOK=*/true))
16858 return std::nullopt;
16859 }
16860
16861 // If we point to before the start of the object, there are no accessible
16862 // bytes.
16863 if (LVal.getLValueOffset().isNegative())
16864 return 0;
16865
16866 // For __builtin_dynamic_object_size on a counted_by-annotated flexible
16867 // array member, defer to IR generation (emitCountedBySize in CGBuiltin):
16868 // its runtime computation uses the live 'count' field and is more accurate
16869 // than the layout/initializer-derived size we'd produce here. Use the same
16870 // findStructFieldAccess form-recognition CGBuiltin does, so we refuse to
16871 // fold on exactly the shapes that path handles (and, importantly, *not*
16872 // on '&af.fam' which designates the array-as-a-whole and stays on the
16873 // layout-derived path to match GCC). Checked after the negative-offset
16874 // early return above so that obviously out-of-bounds operands still fold
16875 // to 0, preserving existing behavior.
16876 if (IsDynamic) {
16877 const auto *ME = dyn_cast_or_null<MemberExpr>(findStructFieldAccess(E));
16878 const auto *FD = ME ? dyn_cast<FieldDecl>(ME->getMemberDecl()) : nullptr;
16879 if (FD && FD->getType()->isCountAttributedType())
16880 return std::nullopt;
16881 }
16882
16883 CharUnits EndOffset;
16884 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
16885 return std::nullopt;
16886
16887 // If we've fallen outside of the end offset, just pretend there's nothing to
16888 // write to/read from.
16889 if (EndOffset <= LVal.getLValueOffset())
16890 return 0;
16891 return (EndOffset - LVal.getLValueOffset()).getQuantity();
16892}
16893
16894bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
16895 if (!IsConstantEvaluatedBuiltinCall(E))
16896 return ExprEvaluatorBaseTy::VisitCallExpr(E);
16897 return VisitBuiltinCallExpr(E, ConvertBuiltinIDToX86BuiltinID(Info.Ctx, E));
16898}
16899
16900static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info,
16901 APValue &Val, APSInt &Alignment) {
16902 QualType SrcTy = E->getArg(0)->getType();
16903 if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment))
16904 return false;
16905 // Even though we are evaluating integer expressions we could get a pointer
16906 // argument for the __builtin_is_aligned() case.
16907 if (SrcTy->isPointerType()) {
16908 LValue Ptr;
16909 if (!EvaluatePointer(E->getArg(0), Ptr, Info))
16910 return false;
16911 Ptr.moveInto(Val);
16912 } else if (!SrcTy->isIntegralOrEnumerationType()) {
16913 Info.FFDiag(E->getArg(0));
16914 return false;
16915 } else {
16916 APSInt SrcInt;
16917 if (!EvaluateInteger(E->getArg(0), SrcInt, Info))
16918 return false;
16919 assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() &&
16920 "Bit widths must be the same");
16921 Val = APValue(SrcInt);
16922 }
16923 assert(Val.hasValue());
16924 return true;
16925}
16926
16927bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
16928 unsigned BuiltinOp) {
16929 auto EvalTestOp = [&](llvm::function_ref<bool(const APInt &, const APInt &)>
16930 Fn) {
16931 APValue SourceLHS, SourceRHS;
16932 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
16933 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
16934 return false;
16935
16936 unsigned SourceLen = SourceLHS.getVectorLength();
16937 const VectorType *VT = E->getArg(0)->getType()->castAs<VectorType>();
16938 QualType ElemQT = VT->getElementType();
16939 unsigned LaneWidth = Info.Ctx.getTypeSize(ElemQT);
16940
16941 APInt AWide(LaneWidth * SourceLen, 0);
16942 APInt BWide(LaneWidth * SourceLen, 0);
16943
16944 for (unsigned I = 0; I != SourceLen; ++I) {
16945 APInt ALane;
16946 APInt BLane;
16947 if (ElemQT->isIntegerType()) { // Get value.
16948 ALane = SourceLHS.getVectorElt(I).getInt();
16949 BLane = SourceRHS.getVectorElt(I).getInt();
16950 } else if (ElemQT->isFloatingType()) { // Get only sign bit.
16951 ALane =
16952 SourceLHS.getVectorElt(I).getFloat().bitcastToAPInt().isNegative();
16953 BLane =
16954 SourceRHS.getVectorElt(I).getFloat().bitcastToAPInt().isNegative();
16955 } else { // Must be integer or floating type.
16956 return false;
16957 }
16958 AWide.insertBits(ALane, I * LaneWidth);
16959 BWide.insertBits(BLane, I * LaneWidth);
16960 }
16961 return Success(Fn(AWide, BWide), E);
16962 };
16963
16964 auto HandleMaskBinOp =
16965 [&](llvm::function_ref<APSInt(const APSInt &, const APSInt &)> Fn)
16966 -> bool {
16967 APValue LHS, RHS;
16968 if (!Evaluate(LHS, Info, E->getArg(0)) ||
16969 !Evaluate(RHS, Info, E->getArg(1)))
16970 return false;
16971
16972 APSInt ResultInt = Fn(LHS.getInt(), RHS.getInt());
16973
16974 return Success(APValue(ResultInt), E);
16975 };
16976
16977 auto HandleCRC32 = [&](unsigned DataBytes) -> bool {
16978 APSInt CRC, Data;
16979 if (!EvaluateInteger(E->getArg(0), CRC, Info) ||
16980 !EvaluateInteger(E->getArg(1), Data, Info))
16981 return false;
16982
16983 uint64_t CRCVal = CRC.getZExtValue();
16984 uint64_t DataVal = Data.getZExtValue();
16985
16986 // CRC32C polynomial (iSCSI polynomial, bit-reversed)
16987 static const uint32_t CRC32C_POLY = 0x82F63B78;
16988
16989 // Process each byte
16990 uint32_t Result = static_cast<uint32_t>(CRCVal);
16991 for (unsigned I = 0; I != DataBytes; ++I) {
16992 uint8_t Byte = static_cast<uint8_t>((DataVal >> (I * 8)) & 0xFF);
16993 Result ^= Byte;
16994 for (int J = 0; J != 8; ++J) {
16995 Result = (Result >> 1) ^ ((Result & 1) ? CRC32C_POLY : 0);
16996 }
16997 }
16998
16999 return Success(Result, E);
17000 };
17001
17002 switch (BuiltinOp) {
17003 default:
17004 return false;
17005
17006 case X86::BI__builtin_ia32_crc32qi:
17007 return HandleCRC32(1);
17008 case X86::BI__builtin_ia32_crc32hi:
17009 return HandleCRC32(2);
17010 case X86::BI__builtin_ia32_crc32si:
17011 return HandleCRC32(4);
17012 case X86::BI__builtin_ia32_crc32di:
17013 return HandleCRC32(8);
17014
17015 case Builtin::BI__builtin_dynamic_object_size:
17016 case Builtin::BI__builtin_object_size: {
17017 // The type was checked when we built the expression.
17018 unsigned Type =
17019 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
17020 assert(Type <= 3 && "unexpected type");
17021
17022 bool IsDynamic = BuiltinOp == Builtin::BI__builtin_dynamic_object_size;
17023 if (std::optional<uint64_t> Size =
17024 tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, IsDynamic))
17025 return Success(*Size, E);
17026
17027 if (E->getArg(0)->HasSideEffects(Info.Ctx))
17028 return Success((Type & 2) ? 0 : -1, E);
17029
17030 // Expression had no side effects, but we couldn't statically determine the
17031 // size of the referenced object.
17032 switch (Info.EvalMode) {
17033 case EvaluationMode::ConstantExpression:
17034 case EvaluationMode::ConstantFold:
17035 case EvaluationMode::IgnoreSideEffects:
17036 // Leave it to IR generation.
17037 return Error(E);
17038 case EvaluationMode::ConstantExpressionUnevaluated:
17039 // Reduce it to a constant now.
17040 return Success((Type & 2) ? 0 : -1, E);
17041 }
17042
17043 llvm_unreachable("unexpected EvalMode");
17044 }
17045
17046 case Builtin::BI__builtin_os_log_format_buffer_size: {
17047 analyze_os_log::OSLogBufferLayout Layout;
17048 analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
17049 return Success(Layout.size().getQuantity(), E);
17050 }
17051
17052 case Builtin::BI__builtin_is_aligned: {
17053 APValue Src;
17054 APSInt Alignment;
17055 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
17056 return false;
17057 if (Src.isLValue()) {
17058 // If we evaluated a pointer, check the minimum known alignment.
17059 LValue Ptr;
17060 Ptr.setFrom(Info.Ctx, Src);
17061 CharUnits BaseAlignment = getBaseAlignment(Info, Ptr);
17062 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset);
17063 // We can return true if the known alignment at the computed offset is
17064 // greater than the requested alignment.
17065 assert(PtrAlign.isPowerOfTwo());
17066 assert(Alignment.isPowerOf2());
17067 if (PtrAlign.getQuantity() >= Alignment)
17068 return Success(1, E);
17069 // If the alignment is not known to be sufficient, some cases could still
17070 // be aligned at run time. However, if the requested alignment is less or
17071 // equal to the base alignment and the offset is not aligned, we know that
17072 // the run-time value can never be aligned.
17073 if (BaseAlignment.getQuantity() >= Alignment &&
17074 PtrAlign.getQuantity() < Alignment)
17075 return Success(0, E);
17076 // Otherwise we can't infer whether the value is sufficiently aligned.
17077 // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N)
17078 // in cases where we can't fully evaluate the pointer.
17079 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute)
17080 << Alignment;
17081 return false;
17082 }
17083 assert(Src.isInt());
17084 return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E);
17085 }
17086 case Builtin::BI__builtin_align_up: {
17087 APValue Src;
17088 APSInt Alignment;
17089 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
17090 return false;
17091 if (!Src.isInt())
17092 return Error(E);
17093 APSInt AlignedVal =
17094 APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1),
17095 Src.getInt().isUnsigned());
17096 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
17097 return Success(AlignedVal, E);
17098 }
17099 case Builtin::BI__builtin_align_down: {
17100 APValue Src;
17101 APSInt Alignment;
17102 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
17103 return false;
17104 if (!Src.isInt())
17105 return Error(E);
17106 APSInt AlignedVal =
17107 APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned());
17108 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
17109 return Success(AlignedVal, E);
17110 }
17111
17112 case Builtin::BI__builtin_bitreverseg:
17113 case Builtin::BI__builtin_bitreverse8:
17114 case Builtin::BI__builtin_bitreverse16:
17115 case Builtin::BI__builtin_bitreverse32:
17116 case Builtin::BI__builtin_bitreverse64:
17117 case Builtin::BI__builtin_elementwise_bitreverse: {
17118 APSInt Val;
17119 if (!EvaluateInteger(E->getArg(0), Val, Info))
17120 return false;
17121
17122 return Success(Val.reverseBits(), E);
17123 }
17124 case Builtin::BI__builtin_bswapg:
17125 case Builtin::BI__builtin_bswap16:
17126 case Builtin::BI__builtin_bswap32:
17127 case Builtin::BI__builtin_bswap64:
17128 case Builtin::BIstdc_memreverse8u8:
17129 case Builtin::BIstdc_memreverse8u16:
17130 case Builtin::BIstdc_memreverse8u32:
17131 case Builtin::BIstdc_memreverse8u64: {
17132 APSInt Val;
17133 if (!EvaluateInteger(E->getArg(0), Val, Info))
17134 return false;
17135 if (Val.getBitWidth() == 8 || Val.getBitWidth() == 1)
17136 return Success(Val, E);
17137
17138 return Success(Val.byteSwap(), E);
17139 }
17140
17141 case Builtin::BI__builtin_classify_type:
17142 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
17143
17144 case Builtin::BI__builtin_clrsb:
17145 case Builtin::BI__builtin_clrsbl:
17146 case Builtin::BI__builtin_clrsbll: {
17147 APSInt Val;
17148 if (!EvaluateInteger(E->getArg(0), Val, Info))
17149 return false;
17150
17151 return Success(Val.getBitWidth() - Val.getSignificantBits(), E);
17152 }
17153
17154 case Builtin::BI__builtin_clz:
17155 case Builtin::BI__builtin_clzl:
17156 case Builtin::BI__builtin_clzll:
17157 case Builtin::BI__builtin_clzs:
17158 case Builtin::BI__builtin_clzg:
17159 case Builtin::BI__builtin_elementwise_clzg:
17160 case Builtin::BI__lzcnt16: // Microsoft variants of count leading-zeroes
17161 case Builtin::BI__lzcnt:
17162 case Builtin::BI__lzcnt64: {
17163 APSInt Val;
17164 if (E->getArg(0)->getType()->isExtVectorBoolType()) {
17165 APValue Vec;
17166 if (!EvaluateVector(E->getArg(0), Vec, Info))
17167 return false;
17168 Val = ConvertBoolVectorToInt(Vec);
17169 } else if (!EvaluateInteger(E->getArg(0), Val, Info)) {
17170 return false;
17171 }
17172
17173 std::optional<APSInt> Fallback;
17174 if ((BuiltinOp == Builtin::BI__builtin_clzg ||
17175 BuiltinOp == Builtin::BI__builtin_elementwise_clzg) &&
17176 E->getNumArgs() > 1) {
17177 APSInt FallbackTemp;
17178 if (!EvaluateInteger(E->getArg(1), FallbackTemp, Info))
17179 return false;
17180 Fallback = FallbackTemp;
17181 }
17182
17183 if (!Val) {
17184 if (Fallback)
17185 return Success(*Fallback, E);
17186
17187 // When the argument is 0, the result of GCC builtins is undefined,
17188 // whereas for Microsoft intrinsics, the result is the bit-width of the
17189 // argument.
17190 bool ZeroIsUndefined = BuiltinOp != Builtin::BI__lzcnt16 &&
17191 BuiltinOp != Builtin::BI__lzcnt &&
17192 BuiltinOp != Builtin::BI__lzcnt64;
17193
17194 if (BuiltinOp == Builtin::BI__builtin_elementwise_clzg) {
17195 Info.FFDiag(E, diag::note_constexpr_countzeroes_zero)
17196 << /*IsTrailing=*/false;
17197 }
17198
17199 if (ZeroIsUndefined)
17200 return Error(E);
17201 }
17202
17203 return Success(Val.countl_zero(), E);
17204 }
17205
17206 case Builtin::BI__builtin_constant_p: {
17207 const Expr *Arg = E->getArg(0);
17208 if (EvaluateBuiltinConstantP(Info, Arg))
17209 return Success(true, E);
17210 if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
17211 // Outside a constant context, eagerly evaluate to false in the presence
17212 // of side-effects in order to avoid -Wunsequenced false-positives in
17213 // a branch on __builtin_constant_p(expr).
17214 return Success(false, E);
17215 }
17216 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
17217 return false;
17218 }
17219
17220 case Builtin::BI__noop:
17221 // __noop always evaluates successfully and returns 0.
17222 return Success(0, E);
17223
17224 case Builtin::BI__builtin_is_constant_evaluated: {
17225 const auto *Callee = Info.CurrentCall->getCallee();
17226 if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression &&
17227 (Info.CallStackDepth == 1 ||
17228 (Info.CallStackDepth == 2 && Callee->isInStdNamespace() &&
17229 Callee->getIdentifier() &&
17230 Callee->getIdentifier()->isStr("is_constant_evaluated")))) {
17231 // FIXME: Find a better way to avoid duplicated diagnostics.
17232 if (Info.EvalStatus.Diag)
17233 Info.report((Info.CallStackDepth == 1)
17234 ? E->getExprLoc()
17235 : Info.CurrentCall->getCallRange().getBegin(),
17236 diag::warn_is_constant_evaluated_always_true_constexpr)
17237 << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated"
17238 : "std::is_constant_evaluated");
17239 }
17240
17241 return Success(Info.InConstantContext, E);
17242 }
17243
17244 case Builtin::BI__builtin_is_within_lifetime:
17245 if (auto result = EvaluateBuiltinIsWithinLifetime(*this, E))
17246 return Success(*result, E);
17247 return false;
17248
17249 case Builtin::BI__builtin_ctz:
17250 case Builtin::BI__builtin_ctzl:
17251 case Builtin::BI__builtin_ctzll:
17252 case Builtin::BI__builtin_ctzs:
17253 case Builtin::BI__builtin_ctzg:
17254 case Builtin::BI__builtin_elementwise_ctzg: {
17255 APSInt Val;
17256 if (E->getArg(0)->getType()->isExtVectorBoolType()) {
17257 APValue Vec;
17258 if (!EvaluateVector(E->getArg(0), Vec, Info))
17259 return false;
17260 Val = ConvertBoolVectorToInt(Vec);
17261 } else if (!EvaluateInteger(E->getArg(0), Val, Info)) {
17262 return false;
17263 }
17264
17265 std::optional<APSInt> Fallback;
17266 if ((BuiltinOp == Builtin::BI__builtin_ctzg ||
17267 BuiltinOp == Builtin::BI__builtin_elementwise_ctzg) &&
17268 E->getNumArgs() > 1) {
17269 APSInt FallbackTemp;
17270 if (!EvaluateInteger(E->getArg(1), FallbackTemp, Info))
17271 return false;
17272 Fallback = FallbackTemp;
17273 }
17274
17275 if (!Val) {
17276 if (Fallback)
17277 return Success(*Fallback, E);
17278
17279 if (BuiltinOp == Builtin::BI__builtin_elementwise_ctzg) {
17280 Info.FFDiag(E, diag::note_constexpr_countzeroes_zero)
17281 << /*IsTrailing=*/true;
17282 }
17283 return Error(E);
17284 }
17285
17286 return Success(Val.countr_zero(), E);
17287 }
17288
17289 case Builtin::BI__builtin_eh_return_data_regno: {
17290 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
17291 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
17292 return Success(Operand, E);
17293 }
17294
17295 case Builtin::BI__builtin_elementwise_abs: {
17296 APSInt Val;
17297 if (!EvaluateInteger(E->getArg(0), Val, Info))
17298 return false;
17299
17300 return Success(Val.abs(), E);
17301 }
17302
17303 case Builtin::BI__builtin_expect:
17304 case Builtin::BI__builtin_expect_with_probability:
17305 return Visit(E->getArg(0));
17306
17307 case Builtin::BI__builtin_ptrauth_string_discriminator: {
17308 const auto *Literal =
17310 uint64_t Result = getPointerAuthStableSipHash(Literal->getString());
17311 return Success(Result, E);
17312 }
17313
17314 case Builtin::BI__builtin_infer_alloc_token: {
17315 // If we fail to infer a type, this fails to be a constant expression; this
17316 // can be checked with __builtin_constant_p(...).
17317 QualType AllocType = infer_alloc::inferPossibleType(E, Info.Ctx, nullptr);
17318 if (AllocType.isNull())
17319 return Error(
17320 E, diag::note_constexpr_infer_alloc_token_type_inference_failed);
17321 auto ATMD = infer_alloc::getAllocTokenMetadata(AllocType, Info.Ctx);
17322 if (!ATMD)
17323 return Error(E, diag::note_constexpr_infer_alloc_token_no_metadata);
17324 auto Mode =
17325 Info.getLangOpts().AllocTokenMode.value_or(llvm::DefaultAllocTokenMode);
17326 uint64_t BitWidth = Info.Ctx.getTypeSize(Info.Ctx.getSizeType());
17327 auto MaxTokensOpt = Info.getLangOpts().AllocTokenMax;
17328 uint64_t MaxTokens =
17329 MaxTokensOpt.value_or(0) ? *MaxTokensOpt : (~0ULL >> (64 - BitWidth));
17330 auto MaybeToken = llvm::getAllocToken(Mode, *ATMD, MaxTokens);
17331 if (!MaybeToken)
17332 return Error(E, diag::note_constexpr_infer_alloc_token_stateful_mode);
17333 return Success(llvm::APInt(BitWidth, *MaybeToken), E);
17334 }
17335
17336 case Builtin::BI__builtin_ffs:
17337 case Builtin::BI__builtin_ffsl:
17338 case Builtin::BI__builtin_ffsll: {
17339 APSInt Val;
17340 if (!EvaluateInteger(E->getArg(0), Val, Info))
17341 return false;
17342
17343 unsigned N = Val.countr_zero();
17344 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
17345 }
17346
17347 case Builtin::BI__builtin_fpclassify: {
17348 APFloat Val(0.0);
17349 if (!EvaluateFloat(E->getArg(5), Val, Info))
17350 return false;
17351 unsigned Arg;
17352 switch (Val.getCategory()) {
17353 case APFloat::fcNaN: Arg = 0; break;
17354 case APFloat::fcInfinity: Arg = 1; break;
17355 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
17356 case APFloat::fcZero: Arg = 4; break;
17357 }
17358 return Visit(E->getArg(Arg));
17359 }
17360
17361 case Builtin::BI__builtin_isinf_sign: {
17362 APFloat Val(0.0);
17363 return EvaluateFloat(E->getArg(0), Val, Info) &&
17364 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
17365 }
17366
17367 case Builtin::BI__builtin_isinf: {
17368 APFloat Val(0.0);
17369 return EvaluateFloat(E->getArg(0), Val, Info) &&
17370 Success(Val.isInfinity() ? 1 : 0, E);
17371 }
17372
17373 case Builtin::BI__builtin_isfinite: {
17374 APFloat Val(0.0);
17375 return EvaluateFloat(E->getArg(0), Val, Info) &&
17376 Success(Val.isFinite() ? 1 : 0, E);
17377 }
17378
17379 case Builtin::BI__builtin_isnan: {
17380 APFloat Val(0.0);
17381 return EvaluateFloat(E->getArg(0), Val, Info) &&
17382 Success(Val.isNaN() ? 1 : 0, E);
17383 }
17384
17385 case Builtin::BI__builtin_isnormal: {
17386 APFloat Val(0.0);
17387 return EvaluateFloat(E->getArg(0), Val, Info) &&
17388 Success(Val.isNormal() ? 1 : 0, E);
17389 }
17390
17391 case Builtin::BI__builtin_issubnormal: {
17392 APFloat Val(0.0);
17393 return EvaluateFloat(E->getArg(0), Val, Info) &&
17394 Success(Val.isDenormal() ? 1 : 0, E);
17395 }
17396
17397 case Builtin::BI__builtin_iszero: {
17398 APFloat Val(0.0);
17399 return EvaluateFloat(E->getArg(0), Val, Info) &&
17400 Success(Val.isZero() ? 1 : 0, E);
17401 }
17402
17403 case Builtin::BI__builtin_signbit:
17404 case Builtin::BI__builtin_signbitf:
17405 case Builtin::BI__builtin_signbitl: {
17406 APFloat Val(0.0);
17407 return EvaluateFloat(E->getArg(0), Val, Info) &&
17408 Success(Val.isNegative() ? 1 : 0, E);
17409 }
17410
17411 case Builtin::BI__builtin_isgreater:
17412 case Builtin::BI__builtin_isgreaterequal:
17413 case Builtin::BI__builtin_isless:
17414 case Builtin::BI__builtin_islessequal:
17415 case Builtin::BI__builtin_islessgreater:
17416 case Builtin::BI__builtin_isunordered: {
17417 APFloat LHS(0.0);
17418 APFloat RHS(0.0);
17419 if (!EvaluateFloat(E->getArg(0), LHS, Info) ||
17420 !EvaluateFloat(E->getArg(1), RHS, Info))
17421 return false;
17422
17423 return Success(
17424 [&] {
17425 switch (BuiltinOp) {
17426 case Builtin::BI__builtin_isgreater:
17427 return LHS > RHS;
17428 case Builtin::BI__builtin_isgreaterequal:
17429 return LHS >= RHS;
17430 case Builtin::BI__builtin_isless:
17431 return LHS < RHS;
17432 case Builtin::BI__builtin_islessequal:
17433 return LHS <= RHS;
17434 case Builtin::BI__builtin_islessgreater: {
17435 APFloat::cmpResult cmp = LHS.compare(RHS);
17436 return cmp == APFloat::cmpResult::cmpLessThan ||
17437 cmp == APFloat::cmpResult::cmpGreaterThan;
17438 }
17439 case Builtin::BI__builtin_isunordered:
17440 return LHS.compare(RHS) == APFloat::cmpResult::cmpUnordered;
17441 default:
17442 llvm_unreachable("Unexpected builtin ID: Should be a floating "
17443 "point comparison function");
17444 }
17445 }()
17446 ? 1
17447 : 0,
17448 E);
17449 }
17450
17451 case Builtin::BI__builtin_issignaling: {
17452 APFloat Val(0.0);
17453 return EvaluateFloat(E->getArg(0), Val, Info) &&
17454 Success(Val.isSignaling() ? 1 : 0, E);
17455 }
17456
17457 case Builtin::BI__builtin_isfpclass: {
17458 APSInt MaskVal;
17459 if (!EvaluateInteger(E->getArg(1), MaskVal, Info))
17460 return false;
17461 unsigned Test = static_cast<llvm::FPClassTest>(MaskVal.getZExtValue());
17462 APFloat Val(0.0);
17463 return EvaluateFloat(E->getArg(0), Val, Info) &&
17464 Success((Val.classify() & Test) ? 1 : 0, E);
17465 }
17466
17467 case Builtin::BI__builtin_parity:
17468 case Builtin::BI__builtin_parityl:
17469 case Builtin::BI__builtin_parityll: {
17470 APSInt Val;
17471 if (!EvaluateInteger(E->getArg(0), Val, Info))
17472 return false;
17473
17474 return Success(Val.popcount() % 2, E);
17475 }
17476
17477 case Builtin::BI__builtin_abs:
17478 case Builtin::BI__builtin_labs:
17479 case Builtin::BI__builtin_llabs: {
17480 APSInt Val;
17481 if (!EvaluateInteger(E->getArg(0), Val, Info))
17482 return false;
17483 if (Val == APSInt(APInt::getSignedMinValue(Val.getBitWidth()),
17484 /*IsUnsigned=*/false))
17485 return false;
17486 if (Val.isNegative())
17487 Val.negate();
17488 return Success(Val, E);
17489 }
17490
17491 case Builtin::BI__builtin_popcount:
17492 case Builtin::BI__builtin_popcountl:
17493 case Builtin::BI__builtin_popcountll:
17494 case Builtin::BI__builtin_popcountg:
17495 case Builtin::BI__builtin_elementwise_popcount:
17496 case Builtin::BI__popcnt16: // Microsoft variants of popcount
17497 case Builtin::BI__popcnt:
17498 case Builtin::BI__popcnt64: {
17499 APSInt Val;
17500 if (E->getArg(0)->getType()->isExtVectorBoolType()) {
17501 APValue Vec;
17502 if (!EvaluateVector(E->getArg(0), Vec, Info))
17503 return false;
17504 Val = ConvertBoolVectorToInt(Vec);
17505 } else if (!EvaluateInteger(E->getArg(0), Val, Info)) {
17506 return false;
17507 }
17508
17509 return Success(Val.popcount(), E);
17510 }
17511
17512 case Builtin::BI__builtin_rotateleft8:
17513 case Builtin::BI__builtin_rotateleft16:
17514 case Builtin::BI__builtin_rotateleft32:
17515 case Builtin::BI__builtin_rotateleft64:
17516 case Builtin::BI__builtin_rotateright8:
17517 case Builtin::BI__builtin_rotateright16:
17518 case Builtin::BI__builtin_rotateright32:
17519 case Builtin::BI__builtin_rotateright64:
17520 case Builtin::BI__builtin_stdc_rotate_left:
17521 case Builtin::BI__builtin_stdc_rotate_right:
17522 case Builtin::BIstdc_rotate_left_uc:
17523 case Builtin::BIstdc_rotate_left_us:
17524 case Builtin::BIstdc_rotate_left_ui:
17525 case Builtin::BIstdc_rotate_left_ul:
17526 case Builtin::BIstdc_rotate_left_ull:
17527 case Builtin::BIstdc_rotate_right_uc:
17528 case Builtin::BIstdc_rotate_right_us:
17529 case Builtin::BIstdc_rotate_right_ui:
17530 case Builtin::BIstdc_rotate_right_ul:
17531 case Builtin::BIstdc_rotate_right_ull:
17532 case Builtin::BI_rotl8: // Microsoft variants of rotate left
17533 case Builtin::BI_rotl16:
17534 case Builtin::BI_rotl:
17535 case Builtin::BI_lrotl:
17536 case Builtin::BI_rotl64:
17537 case Builtin::BI_rotr8: // Microsoft variants of rotate right
17538 case Builtin::BI_rotr16:
17539 case Builtin::BI_rotr:
17540 case Builtin::BI_lrotr:
17541 case Builtin::BI_rotr64: {
17542 APSInt Value, Amount;
17543 if (!EvaluateInteger(E->getArg(0), Value, Info) ||
17544 !EvaluateInteger(E->getArg(1), Amount, Info))
17545 return false;
17546
17547 Amount = NormalizeRotateAmount(Value, Amount);
17548
17549 switch (BuiltinOp) {
17550 case Builtin::BI__builtin_rotateright8:
17551 case Builtin::BI__builtin_rotateright16:
17552 case Builtin::BI__builtin_rotateright32:
17553 case Builtin::BI__builtin_rotateright64:
17554 case Builtin::BI__builtin_stdc_rotate_right:
17555 case Builtin::BIstdc_rotate_right_uc:
17556 case Builtin::BIstdc_rotate_right_us:
17557 case Builtin::BIstdc_rotate_right_ui:
17558 case Builtin::BIstdc_rotate_right_ul:
17559 case Builtin::BIstdc_rotate_right_ull:
17560 case Builtin::BI_rotr8:
17561 case Builtin::BI_rotr16:
17562 case Builtin::BI_rotr:
17563 case Builtin::BI_lrotr:
17564 case Builtin::BI_rotr64:
17565 return Success(
17566 APSInt(Value.rotr(Amount.getZExtValue()), Value.isUnsigned()), E);
17567 default:
17568 return Success(
17569 APSInt(Value.rotl(Amount.getZExtValue()), Value.isUnsigned()), E);
17570 }
17571 }
17572
17573 case Builtin::BIstdc_leading_zeros_uc:
17574 case Builtin::BIstdc_leading_zeros_us:
17575 case Builtin::BIstdc_leading_zeros_ui:
17576 case Builtin::BIstdc_leading_zeros_ul:
17577 case Builtin::BIstdc_leading_zeros_ull:
17578 case Builtin::BIstdc_leading_ones_uc:
17579 case Builtin::BIstdc_leading_ones_us:
17580 case Builtin::BIstdc_leading_ones_ui:
17581 case Builtin::BIstdc_leading_ones_ul:
17582 case Builtin::BIstdc_leading_ones_ull:
17583 case Builtin::BIstdc_trailing_zeros_uc:
17584 case Builtin::BIstdc_trailing_zeros_us:
17585 case Builtin::BIstdc_trailing_zeros_ui:
17586 case Builtin::BIstdc_trailing_zeros_ul:
17587 case Builtin::BIstdc_trailing_zeros_ull:
17588 case Builtin::BIstdc_trailing_ones_uc:
17589 case Builtin::BIstdc_trailing_ones_us:
17590 case Builtin::BIstdc_trailing_ones_ui:
17591 case Builtin::BIstdc_trailing_ones_ul:
17592 case Builtin::BIstdc_trailing_ones_ull:
17593 case Builtin::BIstdc_first_leading_zero_uc:
17594 case Builtin::BIstdc_first_leading_zero_us:
17595 case Builtin::BIstdc_first_leading_zero_ui:
17596 case Builtin::BIstdc_first_leading_zero_ul:
17597 case Builtin::BIstdc_first_leading_zero_ull:
17598 case Builtin::BIstdc_first_leading_one_uc:
17599 case Builtin::BIstdc_first_leading_one_us:
17600 case Builtin::BIstdc_first_leading_one_ui:
17601 case Builtin::BIstdc_first_leading_one_ul:
17602 case Builtin::BIstdc_first_leading_one_ull:
17603 case Builtin::BIstdc_first_trailing_zero_uc:
17604 case Builtin::BIstdc_first_trailing_zero_us:
17605 case Builtin::BIstdc_first_trailing_zero_ui:
17606 case Builtin::BIstdc_first_trailing_zero_ul:
17607 case Builtin::BIstdc_first_trailing_zero_ull:
17608 case Builtin::BIstdc_first_trailing_one_uc:
17609 case Builtin::BIstdc_first_trailing_one_us:
17610 case Builtin::BIstdc_first_trailing_one_ui:
17611 case Builtin::BIstdc_first_trailing_one_ul:
17612 case Builtin::BIstdc_first_trailing_one_ull:
17613 case Builtin::BIstdc_count_zeros_uc:
17614 case Builtin::BIstdc_count_zeros_us:
17615 case Builtin::BIstdc_count_zeros_ui:
17616 case Builtin::BIstdc_count_zeros_ul:
17617 case Builtin::BIstdc_count_zeros_ull:
17618 case Builtin::BIstdc_count_ones_uc:
17619 case Builtin::BIstdc_count_ones_us:
17620 case Builtin::BIstdc_count_ones_ui:
17621 case Builtin::BIstdc_count_ones_ul:
17622 case Builtin::BIstdc_count_ones_ull:
17623 case Builtin::BIstdc_has_single_bit_uc:
17624 case Builtin::BIstdc_has_single_bit_us:
17625 case Builtin::BIstdc_has_single_bit_ui:
17626 case Builtin::BIstdc_has_single_bit_ul:
17627 case Builtin::BIstdc_has_single_bit_ull:
17628 case Builtin::BIstdc_bit_width_uc:
17629 case Builtin::BIstdc_bit_width_us:
17630 case Builtin::BIstdc_bit_width_ui:
17631 case Builtin::BIstdc_bit_width_ul:
17632 case Builtin::BIstdc_bit_width_ull:
17633 case Builtin::BIstdc_bit_floor_uc:
17634 case Builtin::BIstdc_bit_floor_us:
17635 case Builtin::BIstdc_bit_floor_ui:
17636 case Builtin::BIstdc_bit_floor_ul:
17637 case Builtin::BIstdc_bit_floor_ull:
17638 case Builtin::BIstdc_bit_ceil_uc:
17639 case Builtin::BIstdc_bit_ceil_us:
17640 case Builtin::BIstdc_bit_ceil_ui:
17641 case Builtin::BIstdc_bit_ceil_ul:
17642 case Builtin::BIstdc_bit_ceil_ull:
17643 case Builtin::BI__builtin_stdc_leading_zeros:
17644 case Builtin::BI__builtin_stdc_leading_ones:
17645 case Builtin::BI__builtin_stdc_trailing_zeros:
17646 case Builtin::BI__builtin_stdc_trailing_ones:
17647 case Builtin::BI__builtin_stdc_first_leading_zero:
17648 case Builtin::BI__builtin_stdc_first_leading_one:
17649 case Builtin::BI__builtin_stdc_first_trailing_zero:
17650 case Builtin::BI__builtin_stdc_first_trailing_one:
17651 case Builtin::BI__builtin_stdc_count_zeros:
17652 case Builtin::BI__builtin_stdc_count_ones:
17653 case Builtin::BI__builtin_stdc_has_single_bit:
17654 case Builtin::BI__builtin_stdc_bit_width:
17655 case Builtin::BI__builtin_stdc_bit_floor:
17656 case Builtin::BI__builtin_stdc_bit_ceil: {
17657 APSInt Val;
17658 if (!EvaluateInteger(E->getArg(0), Val, Info))
17659 return false;
17660
17661 unsigned BitWidth = Val.getBitWidth();
17662 const unsigned ResBitWidth = Info.Ctx.getIntWidth(E->getType());
17663
17664 switch (BuiltinOp) {
17665 case Builtin::BIstdc_leading_zeros_uc:
17666 case Builtin::BIstdc_leading_zeros_us:
17667 case Builtin::BIstdc_leading_zeros_ui:
17668 case Builtin::BIstdc_leading_zeros_ul:
17669 case Builtin::BIstdc_leading_zeros_ull:
17670 case Builtin::BI__builtin_stdc_leading_zeros:
17671 return Success(APInt(ResBitWidth, Val.countl_zero()), E);
17672 case Builtin::BIstdc_leading_ones_uc:
17673 case Builtin::BIstdc_leading_ones_us:
17674 case Builtin::BIstdc_leading_ones_ui:
17675 case Builtin::BIstdc_leading_ones_ul:
17676 case Builtin::BIstdc_leading_ones_ull:
17677 case Builtin::BI__builtin_stdc_leading_ones:
17678 return Success(APInt(ResBitWidth, Val.countl_one()), E);
17679 case Builtin::BIstdc_trailing_zeros_uc:
17680 case Builtin::BIstdc_trailing_zeros_us:
17681 case Builtin::BIstdc_trailing_zeros_ui:
17682 case Builtin::BIstdc_trailing_zeros_ul:
17683 case Builtin::BIstdc_trailing_zeros_ull:
17684 case Builtin::BI__builtin_stdc_trailing_zeros:
17685 return Success(APInt(ResBitWidth, Val.countr_zero()), E);
17686 case Builtin::BIstdc_trailing_ones_uc:
17687 case Builtin::BIstdc_trailing_ones_us:
17688 case Builtin::BIstdc_trailing_ones_ui:
17689 case Builtin::BIstdc_trailing_ones_ul:
17690 case Builtin::BIstdc_trailing_ones_ull:
17691 case Builtin::BI__builtin_stdc_trailing_ones:
17692 return Success(APInt(ResBitWidth, Val.countr_one()), E);
17693 case Builtin::BIstdc_first_leading_zero_uc:
17694 case Builtin::BIstdc_first_leading_zero_us:
17695 case Builtin::BIstdc_first_leading_zero_ui:
17696 case Builtin::BIstdc_first_leading_zero_ul:
17697 case Builtin::BIstdc_first_leading_zero_ull:
17698 case Builtin::BI__builtin_stdc_first_leading_zero:
17699 return Success(
17700 APInt(ResBitWidth, Val.isAllOnes() ? 0 : Val.countl_one() + 1), E);
17701 case Builtin::BIstdc_first_leading_one_uc:
17702 case Builtin::BIstdc_first_leading_one_us:
17703 case Builtin::BIstdc_first_leading_one_ui:
17704 case Builtin::BIstdc_first_leading_one_ul:
17705 case Builtin::BIstdc_first_leading_one_ull:
17706 case Builtin::BI__builtin_stdc_first_leading_one:
17707 return Success(
17708 APInt(ResBitWidth, Val.isZero() ? 0 : Val.countl_zero() + 1), E);
17709 case Builtin::BIstdc_first_trailing_zero_uc:
17710 case Builtin::BIstdc_first_trailing_zero_us:
17711 case Builtin::BIstdc_first_trailing_zero_ui:
17712 case Builtin::BIstdc_first_trailing_zero_ul:
17713 case Builtin::BIstdc_first_trailing_zero_ull:
17714 case Builtin::BI__builtin_stdc_first_trailing_zero:
17715 return Success(
17716 APInt(ResBitWidth, Val.isAllOnes() ? 0 : Val.countr_one() + 1), E);
17717 case Builtin::BIstdc_first_trailing_one_uc:
17718 case Builtin::BIstdc_first_trailing_one_us:
17719 case Builtin::BIstdc_first_trailing_one_ui:
17720 case Builtin::BIstdc_first_trailing_one_ul:
17721 case Builtin::BIstdc_first_trailing_one_ull:
17722 case Builtin::BI__builtin_stdc_first_trailing_one:
17723 return Success(
17724 APInt(ResBitWidth, Val.isZero() ? 0 : Val.countr_zero() + 1), E);
17725 case Builtin::BIstdc_count_zeros_uc:
17726 case Builtin::BIstdc_count_zeros_us:
17727 case Builtin::BIstdc_count_zeros_ui:
17728 case Builtin::BIstdc_count_zeros_ul:
17729 case Builtin::BIstdc_count_zeros_ull:
17730 case Builtin::BI__builtin_stdc_count_zeros: {
17731 APInt Cnt(ResBitWidth, BitWidth - Val.popcount());
17732 return Success(APSInt(Cnt, /*IsUnsigned*/ true), E);
17733 }
17734 case Builtin::BIstdc_count_ones_uc:
17735 case Builtin::BIstdc_count_ones_us:
17736 case Builtin::BIstdc_count_ones_ui:
17737 case Builtin::BIstdc_count_ones_ul:
17738 case Builtin::BIstdc_count_ones_ull:
17739 case Builtin::BI__builtin_stdc_count_ones: {
17740 APInt Cnt(ResBitWidth, Val.popcount());
17741 return Success(APSInt(Cnt, /*IsUnsigned*/ true), E);
17742 }
17743 case Builtin::BIstdc_has_single_bit_uc:
17744 case Builtin::BIstdc_has_single_bit_us:
17745 case Builtin::BIstdc_has_single_bit_ui:
17746 case Builtin::BIstdc_has_single_bit_ul:
17747 case Builtin::BIstdc_has_single_bit_ull:
17748 case Builtin::BI__builtin_stdc_has_single_bit: {
17749 APInt Res(ResBitWidth, Val.popcount() == 1 ? 1 : 0);
17750 return Success(APSInt(Res, /*IsUnsigned*/ true), E);
17751 }
17752 case Builtin::BIstdc_bit_width_uc:
17753 case Builtin::BIstdc_bit_width_us:
17754 case Builtin::BIstdc_bit_width_ui:
17755 case Builtin::BIstdc_bit_width_ul:
17756 case Builtin::BIstdc_bit_width_ull:
17757 case Builtin::BI__builtin_stdc_bit_width:
17758 return Success(APInt(ResBitWidth, BitWidth - Val.countl_zero()), E);
17759 case Builtin::BIstdc_bit_floor_uc:
17760 case Builtin::BIstdc_bit_floor_us:
17761 case Builtin::BIstdc_bit_floor_ui:
17762 case Builtin::BIstdc_bit_floor_ul:
17763 case Builtin::BIstdc_bit_floor_ull:
17764 case Builtin::BI__builtin_stdc_bit_floor: {
17765 if (Val.isZero())
17766 return Success(APInt(BitWidth, 0), E);
17767 unsigned Exp = BitWidth - Val.countl_zero() - 1;
17768 return Success(
17769 APSInt(APInt::getOneBitSet(BitWidth, Exp), /*IsUnsigned*/ true), E);
17770 }
17771 case Builtin::BIstdc_bit_ceil_uc:
17772 case Builtin::BIstdc_bit_ceil_us:
17773 case Builtin::BIstdc_bit_ceil_ui:
17774 case Builtin::BIstdc_bit_ceil_ul:
17775 case Builtin::BIstdc_bit_ceil_ull:
17776 case Builtin::BI__builtin_stdc_bit_ceil: {
17777 if (Val.ule(1))
17778 return Success(APSInt(APInt(BitWidth, 1), /*IsUnsigned*/ true), E);
17779 APInt ValMinusOne = Val - 1;
17780 unsigned LZ = ValMinusOne.countl_zero();
17781 if (LZ == 0)
17782 return Success(APSInt(APInt(BitWidth, 0), /*IsUnsigned*/ true),
17783 E); // overflows; wrap to 0
17784 APInt Result = APInt::getOneBitSet(BitWidth, BitWidth - LZ);
17785 return Success(APSInt(Result, /*IsUnsigned*/ true), E);
17786 }
17787 default:
17788 llvm_unreachable("Unknown stdc builtin");
17789 }
17790 }
17791
17792 case Builtin::BI__builtin_elementwise_add_sat: {
17793 APSInt LHS, RHS;
17794 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
17795 !EvaluateInteger(E->getArg(1), RHS, Info))
17796 return false;
17797
17798 APInt Result = LHS.isSigned() ? LHS.sadd_sat(RHS) : LHS.uadd_sat(RHS);
17799 return Success(APSInt(Result, !LHS.isSigned()), E);
17800 }
17801 case Builtin::BI__builtin_elementwise_sub_sat: {
17802 APSInt LHS, RHS;
17803 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
17804 !EvaluateInteger(E->getArg(1), RHS, Info))
17805 return false;
17806
17807 APInt Result = LHS.isSigned() ? LHS.ssub_sat(RHS) : LHS.usub_sat(RHS);
17808 return Success(APSInt(Result, !LHS.isSigned()), E);
17809 }
17810 case Builtin::BI__builtin_elementwise_max: {
17811 APSInt LHS, RHS;
17812 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
17813 !EvaluateInteger(E->getArg(1), RHS, Info))
17814 return false;
17815
17816 APInt Result = std::max(LHS, RHS);
17817 return Success(APSInt(Result, !LHS.isSigned()), E);
17818 }
17819 case Builtin::BI__builtin_elementwise_min: {
17820 APSInt LHS, RHS;
17821 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
17822 !EvaluateInteger(E->getArg(1), RHS, Info))
17823 return false;
17824
17825 APInt Result = std::min(LHS, RHS);
17826 return Success(APSInt(Result, !LHS.isSigned()), E);
17827 }
17828 case Builtin::BI__builtin_elementwise_clmul: {
17829 APSInt LHS, RHS;
17830 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
17831 !EvaluateInteger(E->getArg(1), RHS, Info))
17832 return false;
17833
17834 APInt Result = llvm::APIntOps::clmul(LHS, RHS);
17835 return Success(APSInt(Result, LHS.isUnsigned()), E);
17836 }
17837 case Builtin::BI__builtin_elementwise_fshl:
17838 case Builtin::BI__builtin_elementwise_fshr: {
17839 APSInt Hi, Lo, Shift;
17840 if (!EvaluateInteger(E->getArg(0), Hi, Info) ||
17841 !EvaluateInteger(E->getArg(1), Lo, Info) ||
17842 !EvaluateInteger(E->getArg(2), Shift, Info))
17843 return false;
17844
17845 switch (BuiltinOp) {
17846 case Builtin::BI__builtin_elementwise_fshl: {
17847 APSInt Result(llvm::APIntOps::fshl(Hi, Lo, Shift), Hi.isUnsigned());
17848 return Success(Result, E);
17849 }
17850 case Builtin::BI__builtin_elementwise_fshr: {
17851 APSInt Result(llvm::APIntOps::fshr(Hi, Lo, Shift), Hi.isUnsigned());
17852 return Success(Result, E);
17853 }
17854 }
17855 llvm_unreachable("Fully covered switch above");
17856 }
17857 case Builtin::BIstrlen:
17858 case Builtin::BIwcslen:
17859 // A call to strlen is not a constant expression.
17860 if (Info.getLangOpts().CPlusPlus11)
17861 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
17862 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
17863 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
17864 else
17865 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
17866 [[fallthrough]];
17867 case Builtin::BI__builtin_strlen:
17868 case Builtin::BI__builtin_wcslen: {
17869 // As an extension, we support __builtin_strlen() as a constant expression,
17870 // and support folding strlen() to a constant.
17871 if (std::optional<uint64_t> StrLen =
17872 EvaluateBuiltinStrLen(E->getArg(0), Info))
17873 return Success(*StrLen, E);
17874 return false;
17875 }
17876
17877 case Builtin::BIstrcmp:
17878 case Builtin::BIwcscmp:
17879 case Builtin::BIstrncmp:
17880 case Builtin::BIwcsncmp:
17881 case Builtin::BImemcmp:
17882 case Builtin::BIbcmp:
17883 case Builtin::BIwmemcmp:
17884 // A call to strlen is not a constant expression.
17885 if (Info.getLangOpts().CPlusPlus11)
17886 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
17887 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
17888 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
17889 else
17890 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
17891 [[fallthrough]];
17892 case Builtin::BI__builtin_strcmp:
17893 case Builtin::BI__builtin_wcscmp:
17894 case Builtin::BI__builtin_strncmp:
17895 case Builtin::BI__builtin_wcsncmp:
17896 case Builtin::BI__builtin_memcmp:
17897 case Builtin::BI__builtin_bcmp:
17898 case Builtin::BI__builtin_wmemcmp: {
17899 LValue String1, String2;
17900 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
17901 !EvaluatePointer(E->getArg(1), String2, Info))
17902 return false;
17903
17904 uint64_t MaxLength = uint64_t(-1);
17905 if (BuiltinOp != Builtin::BIstrcmp &&
17906 BuiltinOp != Builtin::BIwcscmp &&
17907 BuiltinOp != Builtin::BI__builtin_strcmp &&
17908 BuiltinOp != Builtin::BI__builtin_wcscmp) {
17909 APSInt N;
17910 if (!EvaluateInteger(E->getArg(2), N, Info))
17911 return false;
17912 MaxLength = N.getZExtValue();
17913 }
17914
17915 // Empty substrings compare equal by definition.
17916 if (MaxLength == 0u)
17917 return Success(0, E);
17918
17919 if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
17920 !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
17921 String1.Designator.Invalid || String2.Designator.Invalid)
17922 return false;
17923
17924 QualType CharTy1 = String1.Designator.getType(Info.Ctx);
17925 QualType CharTy2 = String2.Designator.getType(Info.Ctx);
17926
17927 bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
17928 BuiltinOp == Builtin::BIbcmp ||
17929 BuiltinOp == Builtin::BI__builtin_memcmp ||
17930 BuiltinOp == Builtin::BI__builtin_bcmp;
17931
17932 assert(IsRawByte ||
17933 (Info.Ctx.hasSameUnqualifiedType(
17934 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
17935 Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
17936
17937 // For memcmp, allow comparing any arrays of '[[un]signed] char' or
17938 // 'char8_t', but no other types.
17939 if (IsRawByte &&
17940 !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) {
17941 // FIXME: Consider using our bit_cast implementation to support this.
17942 Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported)
17943 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp) << CharTy1
17944 << CharTy2;
17945 return false;
17946 }
17947
17948 const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
17949 return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
17950 handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
17951 Char1.isInt() && Char2.isInt();
17952 };
17953 const auto &AdvanceElems = [&] {
17954 return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
17955 HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
17956 };
17957
17958 bool StopAtNull =
17959 (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
17960 BuiltinOp != Builtin::BIwmemcmp &&
17961 BuiltinOp != Builtin::BI__builtin_memcmp &&
17962 BuiltinOp != Builtin::BI__builtin_bcmp &&
17963 BuiltinOp != Builtin::BI__builtin_wmemcmp);
17964 bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
17965 BuiltinOp == Builtin::BIwcsncmp ||
17966 BuiltinOp == Builtin::BIwmemcmp ||
17967 BuiltinOp == Builtin::BI__builtin_wcscmp ||
17968 BuiltinOp == Builtin::BI__builtin_wcsncmp ||
17969 BuiltinOp == Builtin::BI__builtin_wmemcmp;
17970
17971 for (; MaxLength; --MaxLength) {
17972 APValue Char1, Char2;
17973 if (!ReadCurElems(Char1, Char2))
17974 return false;
17975 if (Char1.getInt().ne(Char2.getInt())) {
17976 if (IsWide) // wmemcmp compares with wchar_t signedness.
17977 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
17978 // memcmp always compares unsigned chars.
17979 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
17980 }
17981 if (StopAtNull && !Char1.getInt())
17982 return Success(0, E);
17983 assert(!(StopAtNull && !Char2.getInt()));
17984 if (!AdvanceElems())
17985 return false;
17986 }
17987 // We hit the strncmp / memcmp limit.
17988 return Success(0, E);
17989 }
17990
17991 case Builtin::BI__atomic_always_lock_free:
17992 case Builtin::BI__atomic_is_lock_free:
17993 case Builtin::BI__c11_atomic_is_lock_free: {
17994 APSInt SizeVal;
17995 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
17996 return false;
17997
17998 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
17999 // of two less than or equal to the maximum inline atomic width, we know it
18000 // is lock-free. If the size isn't a power of two, or greater than the
18001 // maximum alignment where we promote atomics, we know it is not lock-free
18002 // (at least not in the sense of atomic_is_lock_free). Otherwise,
18003 // the answer can only be determined at runtime; for example, 16-byte
18004 // atomics have lock-free implementations on some, but not all,
18005 // x86-64 processors.
18006
18007 // Check power-of-two.
18008 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
18009 if (Size.isPowerOfTwo()) {
18010 // Check against inlining width.
18011 unsigned InlineWidthBits =
18012 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
18013 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
18014 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
18015 Size == CharUnits::One())
18016 return Success(1, E);
18017
18018 // If the pointer argument can be evaluated to a compile-time constant
18019 // integer (or nullptr), check if that value is appropriately aligned.
18020 const Expr *PtrArg = E->getArg(1);
18021 Expr::EvalResult ExprResult;
18022 APSInt IntResult;
18023 if (PtrArg->EvaluateAsRValue(ExprResult, Info.Ctx) &&
18024 ExprResult.Val.toIntegralConstant(IntResult, PtrArg->getType(),
18025 Info.Ctx) &&
18026 IntResult.isAligned(Size.getAsAlign()))
18027 return Success(1, E);
18028
18029 // Otherwise, check if the type's alignment against Size.
18030 if (auto *ICE = dyn_cast<ImplicitCastExpr>(PtrArg)) {
18031 // Drop the potential implicit-cast to 'const volatile void*', getting
18032 // the underlying type.
18033 if (ICE->getCastKind() == CK_BitCast)
18034 PtrArg = ICE->getSubExpr();
18035 }
18036
18037 if (auto PtrTy = PtrArg->getType()->getAs<PointerType>()) {
18038 QualType PointeeType = PtrTy->getPointeeType();
18039 if (!PointeeType->isIncompleteType() &&
18040 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
18041 // OK, we will inline operations on this object.
18042 return Success(1, E);
18043 }
18044 }
18045 }
18046 }
18047
18048 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
18049 Success(0, E) : Error(E);
18050 }
18051 case Builtin::BI__builtin_addcb:
18052 case Builtin::BI__builtin_addcs:
18053 case Builtin::BI__builtin_addc:
18054 case Builtin::BI__builtin_addcl:
18055 case Builtin::BI__builtin_addcll:
18056 case Builtin::BI__builtin_subcb:
18057 case Builtin::BI__builtin_subcs:
18058 case Builtin::BI__builtin_subc:
18059 case Builtin::BI__builtin_subcl:
18060 case Builtin::BI__builtin_subcll: {
18061 LValue CarryOutLValue;
18062 APSInt LHS, RHS, CarryIn, CarryOut, Result;
18063 QualType ResultType = E->getArg(0)->getType();
18064 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
18065 !EvaluateInteger(E->getArg(1), RHS, Info) ||
18066 !EvaluateInteger(E->getArg(2), CarryIn, Info) ||
18067 !EvaluatePointer(E->getArg(3), CarryOutLValue, Info))
18068 return false;
18069 // Copy the number of bits and sign.
18070 Result = LHS;
18071 CarryOut = LHS;
18072
18073 bool FirstOverflowed = false;
18074 bool SecondOverflowed = false;
18075 switch (BuiltinOp) {
18076 default:
18077 llvm_unreachable("Invalid value for BuiltinOp");
18078 case Builtin::BI__builtin_addcb:
18079 case Builtin::BI__builtin_addcs:
18080 case Builtin::BI__builtin_addc:
18081 case Builtin::BI__builtin_addcl:
18082 case Builtin::BI__builtin_addcll:
18083 Result =
18084 LHS.uadd_ov(RHS, FirstOverflowed).uadd_ov(CarryIn, SecondOverflowed);
18085 break;
18086 case Builtin::BI__builtin_subcb:
18087 case Builtin::BI__builtin_subcs:
18088 case Builtin::BI__builtin_subc:
18089 case Builtin::BI__builtin_subcl:
18090 case Builtin::BI__builtin_subcll:
18091 Result =
18092 LHS.usub_ov(RHS, FirstOverflowed).usub_ov(CarryIn, SecondOverflowed);
18093 break;
18094 }
18095
18096 // It is possible for both overflows to happen but CGBuiltin uses an OR so
18097 // this is consistent.
18098 CarryOut = (uint64_t)(FirstOverflowed | SecondOverflowed);
18099 APValue APV{CarryOut};
18100 if (!handleAssignment(Info, E, CarryOutLValue, ResultType, APV))
18101 return false;
18102 return Success(Result, E);
18103 }
18104 case Builtin::BI__builtin_add_overflow:
18105 case Builtin::BI__builtin_sub_overflow:
18106 case Builtin::BI__builtin_mul_overflow:
18107 case Builtin::BI__builtin_sadd_overflow:
18108 case Builtin::BI__builtin_uadd_overflow:
18109 case Builtin::BI__builtin_uaddl_overflow:
18110 case Builtin::BI__builtin_uaddll_overflow:
18111 case Builtin::BI__builtin_usub_overflow:
18112 case Builtin::BI__builtin_usubl_overflow:
18113 case Builtin::BI__builtin_usubll_overflow:
18114 case Builtin::BI__builtin_umul_overflow:
18115 case Builtin::BI__builtin_umull_overflow:
18116 case Builtin::BI__builtin_umulll_overflow:
18117 case Builtin::BI__builtin_saddl_overflow:
18118 case Builtin::BI__builtin_saddll_overflow:
18119 case Builtin::BI__builtin_ssub_overflow:
18120 case Builtin::BI__builtin_ssubl_overflow:
18121 case Builtin::BI__builtin_ssubll_overflow:
18122 case Builtin::BI__builtin_smul_overflow:
18123 case Builtin::BI__builtin_smull_overflow:
18124 case Builtin::BI__builtin_smulll_overflow: {
18125 LValue ResultLValue;
18126 APSInt LHS, RHS;
18127
18128 QualType ResultType = E->getArg(2)->getType()->getPointeeType();
18129 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
18130 !EvaluateInteger(E->getArg(1), RHS, Info) ||
18131 !EvaluatePointer(E->getArg(2), ResultLValue, Info))
18132 return false;
18133
18134 APSInt Result;
18135 bool DidOverflow = false;
18136
18137 // If the types don't have to match, enlarge all 3 to the largest of them.
18138 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
18139 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
18140 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
18141 bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
18143 bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
18145 uint64_t LHSSize = LHS.getBitWidth();
18146 uint64_t RHSSize = RHS.getBitWidth();
18147 uint64_t ResultSize = Info.Ctx.getIntWidth(ResultType);
18148 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
18149
18150 // Add an additional bit if the signedness isn't uniformly agreed to. We
18151 // could do this ONLY if there is a signed and an unsigned that both have
18152 // MaxBits, but the code to check that is pretty nasty. The issue will be
18153 // caught in the shrink-to-result later anyway.
18154 if (IsSigned && !AllSigned)
18155 ++MaxBits;
18156
18157 LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
18158 RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
18159 Result = APSInt(MaxBits, !IsSigned);
18160 }
18161
18162 // Find largest int.
18163 switch (BuiltinOp) {
18164 default:
18165 llvm_unreachable("Invalid value for BuiltinOp");
18166 case Builtin::BI__builtin_add_overflow:
18167 case Builtin::BI__builtin_sadd_overflow:
18168 case Builtin::BI__builtin_saddl_overflow:
18169 case Builtin::BI__builtin_saddll_overflow:
18170 case Builtin::BI__builtin_uadd_overflow:
18171 case Builtin::BI__builtin_uaddl_overflow:
18172 case Builtin::BI__builtin_uaddll_overflow:
18173 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
18174 : LHS.uadd_ov(RHS, DidOverflow);
18175 break;
18176 case Builtin::BI__builtin_sub_overflow:
18177 case Builtin::BI__builtin_ssub_overflow:
18178 case Builtin::BI__builtin_ssubl_overflow:
18179 case Builtin::BI__builtin_ssubll_overflow:
18180 case Builtin::BI__builtin_usub_overflow:
18181 case Builtin::BI__builtin_usubl_overflow:
18182 case Builtin::BI__builtin_usubll_overflow:
18183 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
18184 : LHS.usub_ov(RHS, DidOverflow);
18185 break;
18186 case Builtin::BI__builtin_mul_overflow:
18187 case Builtin::BI__builtin_smul_overflow:
18188 case Builtin::BI__builtin_smull_overflow:
18189 case Builtin::BI__builtin_smulll_overflow:
18190 case Builtin::BI__builtin_umul_overflow:
18191 case Builtin::BI__builtin_umull_overflow:
18192 case Builtin::BI__builtin_umulll_overflow:
18193 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
18194 : LHS.umul_ov(RHS, DidOverflow);
18195 break;
18196 }
18197
18198 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
18199 // since it will give us the behavior of a TruncOrSelf in the case where
18200 // its parameter <= its size. We previously set Result to be at least the
18201 // integer width of the result, so getIntWidth(ResultType) <=
18202 // Result.BitWidth will work exactly like TruncOrSelf.
18203 APSInt Temp = Result.extOrTrunc(Info.Ctx.getIntWidth(ResultType));
18204 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
18205
18206 // In the case where multiple sizes are allowed, truncate and see if
18207 // the values are the same.
18208 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
18209 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
18210 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
18211 if (!APSInt::isSameValue(Temp, Result))
18212 DidOverflow = true;
18213 }
18214 Result = Temp;
18215
18216 APValue APV{Result};
18217 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
18218 return false;
18219 return Success(DidOverflow, E);
18220 }
18221
18222 case Builtin::BI__builtin_reduce_add:
18223 case Builtin::BI__builtin_reduce_mul:
18224 case Builtin::BI__builtin_reduce_and:
18225 case Builtin::BI__builtin_reduce_or:
18226 case Builtin::BI__builtin_reduce_xor:
18227 case Builtin::BI__builtin_reduce_min:
18228 case Builtin::BI__builtin_reduce_max: {
18229 APValue Source;
18230 if (!EvaluateAsRValue(Info, E->getArg(0), Source))
18231 return false;
18232
18233 unsigned SourceLen = Source.getVectorLength();
18234 APSInt Reduced = Source.getVectorElt(0).getInt();
18235 for (unsigned EltNum = 1; EltNum < SourceLen; ++EltNum) {
18236 switch (BuiltinOp) {
18237 default:
18238 return false;
18239 case Builtin::BI__builtin_reduce_add: {
18241 Info, E, Reduced, Source.getVectorElt(EltNum).getInt(),
18242 Reduced.getBitWidth() + 1, std::plus<APSInt>(), Reduced))
18243 return false;
18244 break;
18245 }
18246 case Builtin::BI__builtin_reduce_mul: {
18248 Info, E, Reduced, Source.getVectorElt(EltNum).getInt(),
18249 Reduced.getBitWidth() * 2, std::multiplies<APSInt>(), Reduced))
18250 return false;
18251 break;
18252 }
18253 case Builtin::BI__builtin_reduce_and: {
18254 Reduced &= Source.getVectorElt(EltNum).getInt();
18255 break;
18256 }
18257 case Builtin::BI__builtin_reduce_or: {
18258 Reduced |= Source.getVectorElt(EltNum).getInt();
18259 break;
18260 }
18261 case Builtin::BI__builtin_reduce_xor: {
18262 Reduced ^= Source.getVectorElt(EltNum).getInt();
18263 break;
18264 }
18265 case Builtin::BI__builtin_reduce_min: {
18266 Reduced = std::min(Reduced, Source.getVectorElt(EltNum).getInt());
18267 break;
18268 }
18269 case Builtin::BI__builtin_reduce_max: {
18270 Reduced = std::max(Reduced, Source.getVectorElt(EltNum).getInt());
18271 break;
18272 }
18273 }
18274 }
18275
18276 return Success(Reduced, E);
18277 }
18278
18279 case clang::X86::BI__builtin_ia32_addcarryx_u32:
18280 case clang::X86::BI__builtin_ia32_addcarryx_u64:
18281 case clang::X86::BI__builtin_ia32_subborrow_u32:
18282 case clang::X86::BI__builtin_ia32_subborrow_u64: {
18283 LValue ResultLValue;
18284 APSInt CarryIn, LHS, RHS;
18285 QualType ResultType = E->getArg(3)->getType()->getPointeeType();
18286 if (!EvaluateInteger(E->getArg(0), CarryIn, Info) ||
18287 !EvaluateInteger(E->getArg(1), LHS, Info) ||
18288 !EvaluateInteger(E->getArg(2), RHS, Info) ||
18289 !EvaluatePointer(E->getArg(3), ResultLValue, Info))
18290 return false;
18291
18292 bool IsAdd = BuiltinOp == clang::X86::BI__builtin_ia32_addcarryx_u32 ||
18293 BuiltinOp == clang::X86::BI__builtin_ia32_addcarryx_u64;
18294
18295 unsigned BitWidth = LHS.getBitWidth();
18296 unsigned CarryInBit = CarryIn.ugt(0) ? 1 : 0;
18297 APInt ExResult =
18298 IsAdd
18299 ? (LHS.zext(BitWidth + 1) + (RHS.zext(BitWidth + 1) + CarryInBit))
18300 : (LHS.zext(BitWidth + 1) - (RHS.zext(BitWidth + 1) + CarryInBit));
18301
18302 APInt Result = ExResult.extractBits(BitWidth, 0);
18303 uint64_t CarryOut = ExResult.extractBitsAsZExtValue(1, BitWidth);
18304
18305 APValue APV{APSInt(Result, /*isUnsigned=*/true)};
18306 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
18307 return false;
18308 return Success(CarryOut, E);
18309 }
18310
18311 case clang::X86::BI__builtin_ia32_movmskps:
18312 case clang::X86::BI__builtin_ia32_movmskpd:
18313 case clang::X86::BI__builtin_ia32_pmovmskb128:
18314 case clang::X86::BI__builtin_ia32_pmovmskb256:
18315 case clang::X86::BI__builtin_ia32_movmskps256:
18316 case clang::X86::BI__builtin_ia32_movmskpd256: {
18317 APValue Source;
18318 if (!Evaluate(Source, Info, E->getArg(0)))
18319 return false;
18320 unsigned SourceLen = Source.getVectorLength();
18321 const VectorType *VT = E->getArg(0)->getType()->castAs<VectorType>();
18322 QualType ElemQT = VT->getElementType();
18323 unsigned ResultLen = Info.Ctx.getTypeSize(
18324 E->getCallReturnType(Info.Ctx)); // Always 32-bit integer.
18325 APInt Result(ResultLen, 0);
18326
18327 for (unsigned I = 0; I != SourceLen; ++I) {
18328 APInt Elem;
18329 if (ElemQT->isIntegerType()) {
18330 Elem = Source.getVectorElt(I).getInt();
18331 } else if (ElemQT->isRealFloatingType()) {
18332 Elem = Source.getVectorElt(I).getFloat().bitcastToAPInt();
18333 } else {
18334 return false;
18335 }
18336 Result.setBitVal(I, Elem.isNegative());
18337 }
18338 return Success(Result, E);
18339 }
18340
18341 case clang::X86::BI__builtin_ia32_bextr_u32:
18342 case clang::X86::BI__builtin_ia32_bextr_u64:
18343 case clang::X86::BI__builtin_ia32_bextri_u32:
18344 case clang::X86::BI__builtin_ia32_bextri_u64: {
18345 APSInt Val, Idx;
18346 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
18347 !EvaluateInteger(E->getArg(1), Idx, Info))
18348 return false;
18349
18350 unsigned BitWidth = Val.getBitWidth();
18351 uint64_t Shift = Idx.extractBitsAsZExtValue(8, 0);
18352 uint64_t Length = Idx.extractBitsAsZExtValue(8, 8);
18353 Length = Length > BitWidth ? BitWidth : Length;
18354
18355 // Handle out of bounds cases.
18356 if (Length == 0 || Shift >= BitWidth)
18357 return Success(0, E);
18358
18359 uint64_t Result = Val.getZExtValue() >> Shift;
18360 Result &= llvm::maskTrailingOnes<uint64_t>(Length);
18361 return Success(Result, E);
18362 }
18363
18364 case clang::X86::BI__builtin_ia32_bzhi_si:
18365 case clang::X86::BI__builtin_ia32_bzhi_di: {
18366 APSInt Val, Idx;
18367 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
18368 !EvaluateInteger(E->getArg(1), Idx, Info))
18369 return false;
18370
18371 unsigned BitWidth = Val.getBitWidth();
18372 unsigned Index = Idx.extractBitsAsZExtValue(8, 0);
18373 if (Index < BitWidth)
18374 Val.clearHighBits(BitWidth - Index);
18375 return Success(Val, E);
18376 }
18377
18378 case clang::X86::BI__builtin_ia32_ktestcqi:
18379 case clang::X86::BI__builtin_ia32_ktestchi:
18380 case clang::X86::BI__builtin_ia32_ktestcsi:
18381 case clang::X86::BI__builtin_ia32_ktestcdi: {
18382 APSInt A, B;
18383 if (!EvaluateInteger(E->getArg(0), A, Info) ||
18384 !EvaluateInteger(E->getArg(1), B, Info))
18385 return false;
18386
18387 return Success((~A & B) == 0, E);
18388 }
18389
18390 case clang::X86::BI__builtin_ia32_ktestzqi:
18391 case clang::X86::BI__builtin_ia32_ktestzhi:
18392 case clang::X86::BI__builtin_ia32_ktestzsi:
18393 case clang::X86::BI__builtin_ia32_ktestzdi: {
18394 APSInt A, B;
18395 if (!EvaluateInteger(E->getArg(0), A, Info) ||
18396 !EvaluateInteger(E->getArg(1), B, Info))
18397 return false;
18398
18399 return Success((A & B) == 0, E);
18400 }
18401
18402 case clang::X86::BI__builtin_ia32_kortestcqi:
18403 case clang::X86::BI__builtin_ia32_kortestchi:
18404 case clang::X86::BI__builtin_ia32_kortestcsi:
18405 case clang::X86::BI__builtin_ia32_kortestcdi: {
18406 APSInt A, B;
18407 if (!EvaluateInteger(E->getArg(0), A, Info) ||
18408 !EvaluateInteger(E->getArg(1), B, Info))
18409 return false;
18410
18411 return Success(~(A | B) == 0, E);
18412 }
18413
18414 case clang::X86::BI__builtin_ia32_kortestzqi:
18415 case clang::X86::BI__builtin_ia32_kortestzhi:
18416 case clang::X86::BI__builtin_ia32_kortestzsi:
18417 case clang::X86::BI__builtin_ia32_kortestzdi: {
18418 APSInt A, B;
18419 if (!EvaluateInteger(E->getArg(0), A, Info) ||
18420 !EvaluateInteger(E->getArg(1), B, Info))
18421 return false;
18422
18423 return Success((A | B) == 0, E);
18424 }
18425
18426 case clang::X86::BI__builtin_ia32_kunpckhi:
18427 case clang::X86::BI__builtin_ia32_kunpckdi:
18428 case clang::X86::BI__builtin_ia32_kunpcksi: {
18429 APSInt A, B;
18430 if (!EvaluateInteger(E->getArg(0), A, Info) ||
18431 !EvaluateInteger(E->getArg(1), B, Info))
18432 return false;
18433
18434 // Generic kunpack: extract lower half of each operand and concatenate
18435 // Result = A[HalfWidth-1:0] concat B[HalfWidth-1:0]
18436 unsigned BW = A.getBitWidth();
18437 APSInt Result(A.trunc(BW / 2).concat(B.trunc(BW / 2)), A.isUnsigned());
18438 return Success(Result, E);
18439 }
18440
18441 case clang::X86::BI__builtin_ia32_lzcnt_u16:
18442 case clang::X86::BI__builtin_ia32_lzcnt_u32:
18443 case clang::X86::BI__builtin_ia32_lzcnt_u64: {
18444 APSInt Val;
18445 if (!EvaluateInteger(E->getArg(0), Val, Info))
18446 return false;
18447 return Success(Val.countLeadingZeros(), E);
18448 }
18449
18450 case clang::X86::BI__builtin_ia32_tzcnt_u16:
18451 case clang::X86::BI__builtin_ia32_tzcnt_u32:
18452 case clang::X86::BI__builtin_ia32_tzcnt_u64: {
18453 APSInt Val;
18454 if (!EvaluateInteger(E->getArg(0), Val, Info))
18455 return false;
18456 return Success(Val.countTrailingZeros(), E);
18457 }
18458
18459 case clang::X86::BI__builtin_ia32_pdep_si:
18460 case clang::X86::BI__builtin_ia32_pdep_di:
18461 case Builtin::BI__builtin_elementwise_pdep: {
18462 APSInt Val, Msk;
18463 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
18464 !EvaluateInteger(E->getArg(1), Msk, Info))
18465 return false;
18466 return Success(llvm::APIntOps::pdep(Val, Msk), E);
18467 }
18468
18469 case clang::X86::BI__builtin_ia32_pext_si:
18470 case clang::X86::BI__builtin_ia32_pext_di:
18471 case Builtin::BI__builtin_elementwise_pext: {
18472 APSInt Val, Msk;
18473 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
18474 !EvaluateInteger(E->getArg(1), Msk, Info))
18475 return false;
18476 return Success(llvm::APIntOps::pext(Val, Msk), E);
18477 }
18478 case X86::BI__builtin_ia32_ptestz128:
18479 case X86::BI__builtin_ia32_ptestz256:
18480 case X86::BI__builtin_ia32_vtestzps:
18481 case X86::BI__builtin_ia32_vtestzps256:
18482 case X86::BI__builtin_ia32_vtestzpd:
18483 case X86::BI__builtin_ia32_vtestzpd256: {
18484 return EvalTestOp(
18485 [](const APInt &A, const APInt &B) { return (A & B) == 0; });
18486 }
18487 case X86::BI__builtin_ia32_ptestc128:
18488 case X86::BI__builtin_ia32_ptestc256:
18489 case X86::BI__builtin_ia32_vtestcps:
18490 case X86::BI__builtin_ia32_vtestcps256:
18491 case X86::BI__builtin_ia32_vtestcpd:
18492 case X86::BI__builtin_ia32_vtestcpd256: {
18493 return EvalTestOp(
18494 [](const APInt &A, const APInt &B) { return (~A & B) == 0; });
18495 }
18496 case X86::BI__builtin_ia32_ptestnzc128:
18497 case X86::BI__builtin_ia32_ptestnzc256:
18498 case X86::BI__builtin_ia32_vtestnzcps:
18499 case X86::BI__builtin_ia32_vtestnzcps256:
18500 case X86::BI__builtin_ia32_vtestnzcpd:
18501 case X86::BI__builtin_ia32_vtestnzcpd256: {
18502 return EvalTestOp([](const APInt &A, const APInt &B) {
18503 return ((A & B) != 0) && ((~A & B) != 0);
18504 });
18505 }
18506 case X86::BI__builtin_ia32_kandqi:
18507 case X86::BI__builtin_ia32_kandhi:
18508 case X86::BI__builtin_ia32_kandsi:
18509 case X86::BI__builtin_ia32_kanddi: {
18510 return HandleMaskBinOp(
18511 [](const APSInt &LHS, const APSInt &RHS) { return LHS & RHS; });
18512 }
18513
18514 case X86::BI__builtin_ia32_kandnqi:
18515 case X86::BI__builtin_ia32_kandnhi:
18516 case X86::BI__builtin_ia32_kandnsi:
18517 case X86::BI__builtin_ia32_kandndi: {
18518 return HandleMaskBinOp(
18519 [](const APSInt &LHS, const APSInt &RHS) { return ~LHS & RHS; });
18520 }
18521
18522 case X86::BI__builtin_ia32_korqi:
18523 case X86::BI__builtin_ia32_korhi:
18524 case X86::BI__builtin_ia32_korsi:
18525 case X86::BI__builtin_ia32_kordi: {
18526 return HandleMaskBinOp(
18527 [](const APSInt &LHS, const APSInt &RHS) { return LHS | RHS; });
18528 }
18529
18530 case X86::BI__builtin_ia32_kxnorqi:
18531 case X86::BI__builtin_ia32_kxnorhi:
18532 case X86::BI__builtin_ia32_kxnorsi:
18533 case X86::BI__builtin_ia32_kxnordi: {
18534 return HandleMaskBinOp(
18535 [](const APSInt &LHS, const APSInt &RHS) { return ~(LHS ^ RHS); });
18536 }
18537
18538 case X86::BI__builtin_ia32_kxorqi:
18539 case X86::BI__builtin_ia32_kxorhi:
18540 case X86::BI__builtin_ia32_kxorsi:
18541 case X86::BI__builtin_ia32_kxordi: {
18542 return HandleMaskBinOp(
18543 [](const APSInt &LHS, const APSInt &RHS) { return LHS ^ RHS; });
18544 }
18545
18546 case X86::BI__builtin_ia32_knotqi:
18547 case X86::BI__builtin_ia32_knothi:
18548 case X86::BI__builtin_ia32_knotsi:
18549 case X86::BI__builtin_ia32_knotdi: {
18550 APSInt Val;
18551 if (!EvaluateInteger(E->getArg(0), Val, Info))
18552 return false;
18553 APSInt Result = ~Val;
18554 return Success(APValue(Result), E);
18555 }
18556
18557 case X86::BI__builtin_ia32_kaddqi:
18558 case X86::BI__builtin_ia32_kaddhi:
18559 case X86::BI__builtin_ia32_kaddsi:
18560 case X86::BI__builtin_ia32_kadddi: {
18561 return HandleMaskBinOp(
18562 [](const APSInt &LHS, const APSInt &RHS) { return LHS + RHS; });
18563 }
18564
18565 case X86::BI__builtin_ia32_kmovb:
18566 case X86::BI__builtin_ia32_kmovw:
18567 case X86::BI__builtin_ia32_kmovd:
18568 case X86::BI__builtin_ia32_kmovq: {
18569 APSInt Val;
18570 if (!EvaluateInteger(E->getArg(0), Val, Info))
18571 return false;
18572 return Success(Val, E);
18573 }
18574
18575 case X86::BI__builtin_ia32_kshiftliqi:
18576 case X86::BI__builtin_ia32_kshiftlihi:
18577 case X86::BI__builtin_ia32_kshiftlisi:
18578 case X86::BI__builtin_ia32_kshiftlidi: {
18579 return HandleMaskBinOp([](const APSInt &LHS, const APSInt &RHS) {
18580 unsigned Amt = RHS.getZExtValue() & 0xFF;
18581 if (Amt >= LHS.getBitWidth())
18582 return APSInt(APInt::getZero(LHS.getBitWidth()), LHS.isUnsigned());
18583 return APSInt(LHS.shl(Amt), LHS.isUnsigned());
18584 });
18585 }
18586
18587 case X86::BI__builtin_ia32_kshiftriqi:
18588 case X86::BI__builtin_ia32_kshiftrihi:
18589 case X86::BI__builtin_ia32_kshiftrisi:
18590 case X86::BI__builtin_ia32_kshiftridi: {
18591 return HandleMaskBinOp([](const APSInt &LHS, const APSInt &RHS) {
18592 unsigned Amt = RHS.getZExtValue() & 0xFF;
18593 if (Amt >= LHS.getBitWidth())
18594 return APSInt(APInt::getZero(LHS.getBitWidth()), LHS.isUnsigned());
18595 return APSInt(LHS.lshr(Amt), LHS.isUnsigned());
18596 });
18597 }
18598
18599 case clang::X86::BI__builtin_ia32_vec_ext_v4hi:
18600 case clang::X86::BI__builtin_ia32_vec_ext_v16qi:
18601 case clang::X86::BI__builtin_ia32_vec_ext_v8hi:
18602 case clang::X86::BI__builtin_ia32_vec_ext_v4si:
18603 case clang::X86::BI__builtin_ia32_vec_ext_v2di:
18604 case clang::X86::BI__builtin_ia32_vec_ext_v32qi:
18605 case clang::X86::BI__builtin_ia32_vec_ext_v16hi:
18606 case clang::X86::BI__builtin_ia32_vec_ext_v8si:
18607 case clang::X86::BI__builtin_ia32_vec_ext_v4di: {
18608 APValue Vec;
18609 APSInt IdxAPS;
18610 if (!EvaluateVector(E->getArg(0), Vec, Info) ||
18611 !EvaluateInteger(E->getArg(1), IdxAPS, Info))
18612 return false;
18613 unsigned N = Vec.getVectorLength();
18614 unsigned Idx = static_cast<unsigned>(IdxAPS.getZExtValue() & (N - 1));
18615 return Success(Vec.getVectorElt(Idx).getInt(), E);
18616 }
18617
18618 case clang::X86::BI__builtin_ia32_cvtb2mask128:
18619 case clang::X86::BI__builtin_ia32_cvtb2mask256:
18620 case clang::X86::BI__builtin_ia32_cvtb2mask512:
18621 case clang::X86::BI__builtin_ia32_cvtw2mask128:
18622 case clang::X86::BI__builtin_ia32_cvtw2mask256:
18623 case clang::X86::BI__builtin_ia32_cvtw2mask512:
18624 case clang::X86::BI__builtin_ia32_cvtd2mask128:
18625 case clang::X86::BI__builtin_ia32_cvtd2mask256:
18626 case clang::X86::BI__builtin_ia32_cvtd2mask512:
18627 case clang::X86::BI__builtin_ia32_cvtq2mask128:
18628 case clang::X86::BI__builtin_ia32_cvtq2mask256:
18629 case clang::X86::BI__builtin_ia32_cvtq2mask512: {
18630 assert(E->getNumArgs() == 1);
18631 APValue Vec;
18632 if (!EvaluateVector(E->getArg(0), Vec, Info))
18633 return false;
18634
18635 unsigned VectorLen = Vec.getVectorLength();
18636 unsigned RetWidth = Info.Ctx.getIntWidth(E->getType());
18637 llvm::APInt Bits(RetWidth, 0);
18638
18639 for (unsigned ElemNum = 0; ElemNum != VectorLen; ++ElemNum) {
18640 const APSInt &A = Vec.getVectorElt(ElemNum).getInt();
18641 unsigned MSB = A[A.getBitWidth() - 1];
18642 Bits.setBitVal(ElemNum, MSB);
18643 }
18644
18645 APSInt RetMask(Bits, /*isUnsigned=*/true);
18646 return Success(APValue(RetMask), E);
18647 }
18648
18649 case clang::X86::BI__builtin_ia32_cmpb128_mask:
18650 case clang::X86::BI__builtin_ia32_cmpw128_mask:
18651 case clang::X86::BI__builtin_ia32_cmpd128_mask:
18652 case clang::X86::BI__builtin_ia32_cmpq128_mask:
18653 case clang::X86::BI__builtin_ia32_cmpb256_mask:
18654 case clang::X86::BI__builtin_ia32_cmpw256_mask:
18655 case clang::X86::BI__builtin_ia32_cmpd256_mask:
18656 case clang::X86::BI__builtin_ia32_cmpq256_mask:
18657 case clang::X86::BI__builtin_ia32_cmpb512_mask:
18658 case clang::X86::BI__builtin_ia32_cmpw512_mask:
18659 case clang::X86::BI__builtin_ia32_cmpd512_mask:
18660 case clang::X86::BI__builtin_ia32_cmpq512_mask:
18661 case clang::X86::BI__builtin_ia32_ucmpb128_mask:
18662 case clang::X86::BI__builtin_ia32_ucmpw128_mask:
18663 case clang::X86::BI__builtin_ia32_ucmpd128_mask:
18664 case clang::X86::BI__builtin_ia32_ucmpq128_mask:
18665 case clang::X86::BI__builtin_ia32_ucmpb256_mask:
18666 case clang::X86::BI__builtin_ia32_ucmpw256_mask:
18667 case clang::X86::BI__builtin_ia32_ucmpd256_mask:
18668 case clang::X86::BI__builtin_ia32_ucmpq256_mask:
18669 case clang::X86::BI__builtin_ia32_ucmpb512_mask:
18670 case clang::X86::BI__builtin_ia32_ucmpw512_mask:
18671 case clang::X86::BI__builtin_ia32_ucmpd512_mask:
18672 case clang::X86::BI__builtin_ia32_ucmpq512_mask: {
18673 assert(E->getNumArgs() == 4);
18674
18675 bool IsUnsigned =
18676 (BuiltinOp >= clang::X86::BI__builtin_ia32_ucmpb128_mask &&
18677 BuiltinOp <= clang::X86::BI__builtin_ia32_ucmpw512_mask);
18678
18679 APValue LHS, RHS;
18680 APSInt Mask, Opcode;
18681 if (!EvaluateVector(E->getArg(0), LHS, Info) ||
18682 !EvaluateVector(E->getArg(1), RHS, Info) ||
18683 !EvaluateInteger(E->getArg(2), Opcode, Info) ||
18684 !EvaluateInteger(E->getArg(3), Mask, Info))
18685 return false;
18686
18687 assert(LHS.getVectorLength() == RHS.getVectorLength());
18688
18689 unsigned VectorLen = LHS.getVectorLength();
18690 unsigned RetWidth = Mask.getBitWidth();
18691
18692 APSInt RetMask(llvm::APInt(RetWidth, 0), /*isUnsigned=*/true);
18693
18694 for (unsigned ElemNum = 0; ElemNum < VectorLen; ++ElemNum) {
18695 const APSInt &A = LHS.getVectorElt(ElemNum).getInt();
18696 const APSInt &B = RHS.getVectorElt(ElemNum).getInt();
18697 bool Result = false;
18698
18699 switch (Opcode.getExtValue() & 0x7) {
18700 case 0: // _MM_CMPINT_EQ
18701 Result = (A == B);
18702 break;
18703 case 1: // _MM_CMPINT_LT
18704 Result = IsUnsigned ? A.ult(B) : A.slt(B);
18705 break;
18706 case 2: // _MM_CMPINT_LE
18707 Result = IsUnsigned ? A.ule(B) : A.sle(B);
18708 break;
18709 case 3: // _MM_CMPINT_FALSE
18710 Result = false;
18711 break;
18712 case 4: // _MM_CMPINT_NE
18713 Result = (A != B);
18714 break;
18715 case 5: // _MM_CMPINT_NLT (>=)
18716 Result = IsUnsigned ? A.uge(B) : A.sge(B);
18717 break;
18718 case 6: // _MM_CMPINT_NLE (>)
18719 Result = IsUnsigned ? A.ugt(B) : A.sgt(B);
18720 break;
18721 case 7: // _MM_CMPINT_TRUE
18722 Result = true;
18723 break;
18724 }
18725
18726 RetMask.setBitVal(ElemNum, Mask[ElemNum] && Result);
18727 }
18728
18729 return Success(APValue(RetMask), E);
18730 }
18731 case X86::BI__builtin_ia32_cvtss2si:
18732 case X86::BI__builtin_ia32_cvtsd2si:
18733 case X86::BI__builtin_ia32_cvttss2si:
18734 case X86::BI__builtin_ia32_cvttsd2si:
18735 case X86::BI__builtin_ia32_cvtss2si64:
18736 case X86::BI__builtin_ia32_cvtsd2si64:
18737 case X86::BI__builtin_ia32_cvttss2si64:
18738 case X86::BI__builtin_ia32_cvttsd2si64: {
18739 APValue ArgVal;
18740 if (!EvaluateAsRValue(Info, E->getArg(0), ArgVal))
18741 return false;
18742
18743 assert(ArgVal.isVector() && "Expected a vector argument");
18744 llvm::APFloat FloatElem = ArgVal.getVectorElt(0).getFloat();
18745 unsigned BitWidth = Info.Ctx.getIntWidth(E->getType());
18747
18748 llvm::APSInt IntResult(BitWidth, isUnsigned);
18749 bool IsExact = false;
18750 // We only allow exact conversions so rounding mode does not matter for cvt*
18751 // and cvtt* builtins
18752 FloatElem.convertToInteger(IntResult, llvm::APFloat::rmTowardZero,
18753 &IsExact);
18754 if (!IsExact)
18755 return false;
18756
18757 return Success(IntResult, E);
18758 }
18759 case X86::BI__builtin_ia32_vpshufbitqmb128_mask:
18760 case X86::BI__builtin_ia32_vpshufbitqmb256_mask:
18761 case X86::BI__builtin_ia32_vpshufbitqmb512_mask: {
18762 assert(E->getNumArgs() == 3);
18763
18764 APValue Source, ShuffleMask;
18765 APSInt ZeroMask;
18766 if (!EvaluateVector(E->getArg(0), Source, Info) ||
18767 !EvaluateVector(E->getArg(1), ShuffleMask, Info) ||
18768 !EvaluateInteger(E->getArg(2), ZeroMask, Info))
18769 return false;
18770
18771 assert(Source.getVectorLength() == ShuffleMask.getVectorLength());
18772 assert(ZeroMask.getBitWidth() == Source.getVectorLength());
18773
18774 unsigned NumBytesInQWord = 8;
18775 unsigned NumBitsInByte = 8;
18776 unsigned NumBytes = Source.getVectorLength();
18777 unsigned NumQWords = NumBytes / NumBytesInQWord;
18778 unsigned RetWidth = ZeroMask.getBitWidth();
18779 APSInt RetMask(llvm::APInt(RetWidth, 0), /*isUnsigned=*/true);
18780
18781 for (unsigned QWordId = 0; QWordId != NumQWords; ++QWordId) {
18782 APInt SourceQWord(64, 0);
18783 for (unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
18784 uint64_t Byte = Source.getVectorElt(QWordId * NumBytesInQWord + ByteIdx)
18785 .getInt()
18786 .getZExtValue();
18787 SourceQWord.insertBits(APInt(8, Byte & 0xFF), ByteIdx * NumBitsInByte);
18788 }
18789
18790 for (unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
18791 unsigned SelIdx = QWordId * NumBytesInQWord + ByteIdx;
18792 unsigned M =
18793 ShuffleMask.getVectorElt(SelIdx).getInt().getZExtValue() & 0x3F;
18794 if (ZeroMask[SelIdx]) {
18795 RetMask.setBitVal(SelIdx, SourceQWord[M]);
18796 }
18797 }
18798 }
18799 return Success(APValue(RetMask), E);
18800 }
18801 }
18802}
18803
18804/// Determine whether this is a pointer past the end of the complete
18805/// object referred to by the lvalue.
18807 const LValue &LV) {
18808 // A null pointer can be viewed as being "past the end" but we don't
18809 // choose to look at it that way here.
18810 if (!LV.getLValueBase())
18811 return false;
18812
18813 // If the designator is valid and refers to a subobject, we're not pointing
18814 // past the end.
18815 if (!LV.getLValueDesignator().Invalid &&
18816 !LV.getLValueDesignator().isOnePastTheEnd())
18817 return false;
18818
18819 // A pointer to an incomplete type might be past-the-end if the type's size is
18820 // zero. We cannot tell because the type is incomplete.
18821 QualType Ty = getType(LV.getLValueBase());
18822 if (Ty->isIncompleteType())
18823 return true;
18824
18825 // Can't be past the end of an invalid object.
18826 if (LV.getLValueDesignator().Invalid)
18827 return false;
18828
18829 // We're a past-the-end pointer if we point to the byte after the object,
18830 // no matter what our type or path is.
18831 auto Size = Ctx.getTypeSizeInChars(Ty);
18832 return LV.getLValueOffset() == Size;
18833}
18834
18835namespace {
18836
18837/// Data recursive integer evaluator of certain binary operators.
18838///
18839/// We use a data recursive algorithm for binary operators so that we are able
18840/// to handle extreme cases of chained binary operators without causing stack
18841/// overflow.
18842class DataRecursiveIntBinOpEvaluator {
18843 struct EvalResult {
18844 APValue Val;
18845 bool Failed = false;
18846
18847 EvalResult() = default;
18848
18849 void swap(EvalResult &RHS) {
18850 Val.swap(RHS.Val);
18851 Failed = RHS.Failed;
18852 RHS.Failed = false;
18853 }
18854 };
18855
18856 struct Job {
18857 const Expr *E;
18858 EvalResult LHSResult; // meaningful only for binary operator expression.
18859 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
18860
18861 Job() = default;
18862 Job(Job &&) = default;
18863
18864 void startSpeculativeEval(EvalInfo &Info) {
18865 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
18866 }
18867
18868 private:
18869 SpeculativeEvaluationRAII SpecEvalRAII;
18870 };
18871
18872 SmallVector<Job, 16> Queue;
18873
18874 IntExprEvaluator &IntEval;
18875 EvalInfo &Info;
18876 APValue &FinalResult;
18877
18878public:
18879 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
18880 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
18881
18882 /// True if \param E is a binary operator that we are going to handle
18883 /// data recursively.
18884 /// We handle binary operators that are comma, logical, or that have operands
18885 /// with integral or enumeration type.
18886 static bool shouldEnqueue(const BinaryOperator *E) {
18887 return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
18891 }
18892
18893 bool Traverse(const BinaryOperator *E) {
18894 enqueue(E);
18895 EvalResult PrevResult;
18896 while (!Queue.empty())
18897 process(PrevResult);
18898
18899 if (PrevResult.Failed) return false;
18900
18901 FinalResult.swap(PrevResult.Val);
18902 return true;
18903 }
18904
18905private:
18906 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
18907 return IntEval.Success(Value, E, Result);
18908 }
18909 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
18910 return IntEval.Success(Value, E, Result);
18911 }
18912 bool Error(const Expr *E) {
18913 return IntEval.Error(E);
18914 }
18915 bool Error(const Expr *E, diag::kind D) {
18916 return IntEval.Error(E, D);
18917 }
18918
18919 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
18920 return Info.CCEDiag(E, D);
18921 }
18922
18923 // Returns true if visiting the RHS is necessary, false otherwise.
18924 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
18925 bool &SuppressRHSDiags);
18926
18927 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
18928 const BinaryOperator *E, APValue &Result);
18929
18930 void EvaluateExpr(const Expr *E, EvalResult &Result) {
18931 Result.Failed = !Evaluate(Result.Val, Info, E);
18932 if (Result.Failed)
18933 Result.Val = APValue();
18934 }
18935
18936 void process(EvalResult &Result);
18937
18938 void enqueue(const Expr *E) {
18939 E = E->IgnoreParens();
18940 Queue.resize(Queue.size()+1);
18941 Queue.back().E = E;
18942 Queue.back().Kind = Job::AnyExprKind;
18943 }
18944};
18945
18946}
18947
18948bool DataRecursiveIntBinOpEvaluator::
18949 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
18950 bool &SuppressRHSDiags) {
18951 if (E->getOpcode() == BO_Comma) {
18952 // Ignore LHS but note if we could not evaluate it.
18953 if (LHSResult.Failed)
18954 return Info.noteSideEffect();
18955 return true;
18956 }
18957
18958 if (E->isLogicalOp()) {
18959 bool LHSAsBool;
18960 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
18961 // We were able to evaluate the LHS, see if we can get away with not
18962 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
18963 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
18964 Success(LHSAsBool, E, LHSResult.Val);
18965 return false; // Ignore RHS
18966 }
18967 } else {
18968 LHSResult.Failed = true;
18969
18970 // Since we weren't able to evaluate the left hand side, it
18971 // might have had side effects.
18972 if (!Info.noteSideEffect())
18973 return false;
18974
18975 // We can't evaluate the LHS; however, sometimes the result
18976 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
18977 // Don't ignore RHS and suppress diagnostics from this arm.
18978 SuppressRHSDiags = true;
18979 }
18980
18981 return true;
18982 }
18983
18984 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
18986
18987 if (LHSResult.Failed && !Info.noteFailure())
18988 return false; // Ignore RHS;
18989
18990 return true;
18991}
18992
18993static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
18994 bool IsSub) {
18995 // Compute the new offset in the appropriate width, wrapping at 64 bits.
18996 // FIXME: When compiling for a 32-bit target, we should use 32-bit
18997 // offsets.
18998 assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
18999 CharUnits &Offset = LVal.getLValueOffset();
19000 uint64_t Offset64 = Offset.getQuantity();
19001 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
19002 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
19003 : Offset64 + Index64);
19004}
19005
19006bool DataRecursiveIntBinOpEvaluator::
19007 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
19008 const BinaryOperator *E, APValue &Result) {
19009 if (E->getOpcode() == BO_Comma) {
19010 if (RHSResult.Failed)
19011 return false;
19012 Result = RHSResult.Val;
19013 return true;
19014 }
19015
19016 if (E->isLogicalOp()) {
19017 bool lhsResult, rhsResult;
19018 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
19019 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
19020
19021 if (LHSIsOK) {
19022 if (RHSIsOK) {
19023 if (E->getOpcode() == BO_LOr)
19024 return Success(lhsResult || rhsResult, E, Result);
19025 else
19026 return Success(lhsResult && rhsResult, E, Result);
19027 }
19028 } else {
19029 if (RHSIsOK) {
19030 // We can't evaluate the LHS; however, sometimes the result
19031 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
19032 if (rhsResult == (E->getOpcode() == BO_LOr))
19033 return Success(rhsResult, E, Result);
19034 }
19035 }
19036
19037 return false;
19038 }
19039
19040 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
19042
19043 if (LHSResult.Failed || RHSResult.Failed)
19044 return false;
19045
19046 const APValue &LHSVal = LHSResult.Val;
19047 const APValue &RHSVal = RHSResult.Val;
19048
19049 // Handle cases like (unsigned long)&a + 4.
19050 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
19051 Result = LHSVal;
19052 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
19053 return true;
19054 }
19055
19056 // Handle cases like 4 + (unsigned long)&a
19057 if (E->getOpcode() == BO_Add &&
19058 RHSVal.isLValue() && LHSVal.isInt()) {
19059 Result = RHSVal;
19060 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
19061 return true;
19062 }
19063
19064 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
19065 // Handle (intptr_t)&&A - (intptr_t)&&B.
19066 if (!LHSVal.getLValueOffset().isZero() ||
19067 !RHSVal.getLValueOffset().isZero())
19068 return false;
19069 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
19070 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
19071 if (!LHSExpr || !RHSExpr)
19072 return false;
19073 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
19074 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
19075 if (!LHSAddrExpr || !RHSAddrExpr)
19076 return false;
19077 // Make sure both labels come from the same function.
19078 if (LHSAddrExpr->getLabel()->getDeclContext() !=
19079 RHSAddrExpr->getLabel()->getDeclContext())
19080 return false;
19081 Result = APValue(LHSAddrExpr, RHSAddrExpr);
19082 return true;
19083 }
19084
19085 // All the remaining cases expect both operands to be an integer
19086 if (!LHSVal.isInt() || !RHSVal.isInt())
19087 return Error(E);
19088
19089 // Set up the width and signedness manually, in case it can't be deduced
19090 // from the operation we're performing.
19091 // FIXME: Don't do this in the cases where we can deduce it.
19092 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
19094 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
19095 RHSVal.getInt(), Value))
19096 return false;
19097 return Success(Value, E, Result);
19098}
19099
19100void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
19101 Job &job = Queue.back();
19102
19103 switch (job.Kind) {
19104 case Job::AnyExprKind: {
19105 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
19106 if (shouldEnqueue(Bop)) {
19107 job.Kind = Job::BinOpKind;
19108 enqueue(Bop->getLHS());
19109 return;
19110 }
19111 }
19112
19113 EvaluateExpr(job.E, Result);
19114 Queue.pop_back();
19115 return;
19116 }
19117
19118 case Job::BinOpKind: {
19119 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
19120 bool SuppressRHSDiags = false;
19121 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
19122 Queue.pop_back();
19123 return;
19124 }
19125 if (SuppressRHSDiags)
19126 job.startSpeculativeEval(Info);
19127 job.LHSResult.swap(Result);
19128 job.Kind = Job::BinOpVisitedLHSKind;
19129 enqueue(Bop->getRHS());
19130 return;
19131 }
19132
19133 case Job::BinOpVisitedLHSKind: {
19134 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
19135 EvalResult RHS;
19136 RHS.swap(Result);
19137 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
19138 Queue.pop_back();
19139 return;
19140 }
19141 }
19142
19143 llvm_unreachable("Invalid Job::Kind!");
19144}
19145
19146namespace {
19147enum class CmpResult {
19148 Unequal,
19149 Less,
19150 Equal,
19151 Greater,
19152 Unordered,
19153};
19154}
19155
19156template <class SuccessCB, class AfterCB>
19157static bool
19159 SuccessCB &&Success, AfterCB &&DoAfter) {
19160 assert(!E->isValueDependent());
19161 assert(E->isComparisonOp() && "expected comparison operator");
19162 assert((E->getOpcode() == BO_Cmp ||
19164 "unsupported binary expression evaluation");
19165 auto Error = [&](const Expr *E) {
19166 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
19167 return false;
19168 };
19169
19170 bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp;
19171 bool IsEquality = E->isEqualityOp();
19172
19173 QualType LHSTy = E->getLHS()->getType();
19174 QualType RHSTy = E->getRHS()->getType();
19175
19176 if (LHSTy->isIntegralOrEnumerationType() &&
19177 RHSTy->isIntegralOrEnumerationType()) {
19178 APSInt LHS, RHS;
19179 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
19180 if (!LHSOK && !Info.noteFailure())
19181 return false;
19182 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
19183 return false;
19184 if (LHS < RHS)
19185 return Success(CmpResult::Less, E);
19186 if (LHS > RHS)
19187 return Success(CmpResult::Greater, E);
19188 return Success(CmpResult::Equal, E);
19189 }
19190
19191 if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
19192 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
19193 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
19194
19195 bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
19196 if (!LHSOK && !Info.noteFailure())
19197 return false;
19198 if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
19199 return false;
19200 if (LHSFX < RHSFX)
19201 return Success(CmpResult::Less, E);
19202 if (LHSFX > RHSFX)
19203 return Success(CmpResult::Greater, E);
19204 return Success(CmpResult::Equal, E);
19205 }
19206
19207 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
19208 ComplexValue LHS, RHS;
19209 bool LHSOK;
19210 if (E->isAssignmentOp()) {
19211 LValue LV;
19212 EvaluateLValue(E->getLHS(), LV, Info);
19213 LHSOK = false;
19214 } else if (LHSTy->isRealFloatingType()) {
19215 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
19216 if (LHSOK) {
19217 LHS.makeComplexFloat();
19218 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
19219 }
19220 } else {
19221 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
19222 }
19223 if (!LHSOK && !Info.noteFailure())
19224 return false;
19225
19226 if (E->getRHS()->getType()->isRealFloatingType()) {
19227 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
19228 return false;
19229 RHS.makeComplexFloat();
19230 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
19231 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
19232 return false;
19233
19234 if (LHS.isComplexFloat()) {
19235 APFloat::cmpResult CR_r =
19236 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
19237 APFloat::cmpResult CR_i =
19238 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
19239 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
19240 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
19241 } else {
19242 assert(IsEquality && "invalid complex comparison");
19243 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
19244 LHS.getComplexIntImag() == RHS.getComplexIntImag();
19245 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
19246 }
19247 }
19248
19249 if (LHSTy->isRealFloatingType() &&
19250 RHSTy->isRealFloatingType()) {
19251 APFloat RHS(0.0), LHS(0.0);
19252
19253 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
19254 if (!LHSOK && !Info.noteFailure())
19255 return false;
19256
19257 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
19258 return false;
19259
19260 assert(E->isComparisonOp() && "Invalid binary operator!");
19261 llvm::APFloatBase::cmpResult APFloatCmpResult = LHS.compare(RHS);
19262 if (!Info.InConstantContext &&
19263 APFloatCmpResult == APFloat::cmpUnordered &&
19264 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained()) {
19265 // Note: Compares may raise invalid in some cases involving NaN or sNaN.
19266 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
19267 return false;
19268 }
19269 auto GetCmpRes = [&]() {
19270 switch (APFloatCmpResult) {
19271 case APFloat::cmpEqual:
19272 return CmpResult::Equal;
19273 case APFloat::cmpLessThan:
19274 return CmpResult::Less;
19275 case APFloat::cmpGreaterThan:
19276 return CmpResult::Greater;
19277 case APFloat::cmpUnordered:
19278 return CmpResult::Unordered;
19279 }
19280 llvm_unreachable("Unrecognised APFloat::cmpResult enum");
19281 };
19282 return Success(GetCmpRes(), E);
19283 }
19284
19285 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
19286 LValue LHSValue, RHSValue;
19287
19288 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
19289 if (!LHSOK && !Info.noteFailure())
19290 return false;
19291
19292 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
19293 return false;
19294
19295 // Reject differing bases from the normal codepath; we special-case
19296 // comparisons to null.
19297 if (!HasSameBase(LHSValue, RHSValue)) {
19298 // Bail out early if we're checking potential constant expression.
19299 // Otherwise, prefer to diagnose other issues.
19300 if (Info.checkingPotentialConstantExpression() &&
19301 (LHSValue.AllowConstexprUnknown || RHSValue.AllowConstexprUnknown))
19302 return false;
19303 auto DiagComparison = [&] (unsigned DiagID, bool Reversed = false) {
19304 std::string LHS = LHSValue.toString(Info.Ctx, E->getLHS()->getType());
19305 std::string RHS = RHSValue.toString(Info.Ctx, E->getRHS()->getType());
19306 Info.FFDiag(E, DiagID)
19307 << (Reversed ? RHS : LHS) << (Reversed ? LHS : RHS);
19308 return false;
19309 };
19310 // Inequalities and subtractions between unrelated pointers have
19311 // unspecified or undefined behavior.
19312 if (!IsEquality)
19313 return DiagComparison(
19314 diag::note_constexpr_pointer_comparison_unspecified);
19315 // A constant address may compare equal to the address of a symbol.
19316 // The one exception is that address of an object cannot compare equal
19317 // to a null pointer constant.
19318 // TODO: Should we restrict this to actual null pointers, and exclude the
19319 // case of zero cast to pointer type?
19320 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
19321 (!RHSValue.Base && !RHSValue.Offset.isZero()))
19322 return DiagComparison(diag::note_constexpr_pointer_constant_comparison,
19323 !RHSValue.Base);
19324 // C++2c [intro.object]/10:
19325 // Two objects [...] may have the same address if [...] they are both
19326 // potentially non-unique objects.
19327 // C++2c [intro.object]/9:
19328 // An object is potentially non-unique if it is a string literal object,
19329 // the backing array of an initializer list, or a subobject thereof.
19330 //
19331 // This makes the comparison result unspecified, so it's not a constant
19332 // expression.
19333 //
19334 // TODO: Do we need to handle the initializer list case here?
19335 if (ArePotentiallyOverlappingStringLiterals(Info, LHSValue, RHSValue))
19336 return DiagComparison(diag::note_constexpr_literal_comparison);
19337 if (IsOpaqueConstantCall(LHSValue) || IsOpaqueConstantCall(RHSValue))
19338 return DiagComparison(diag::note_constexpr_opaque_call_comparison,
19339 !IsOpaqueConstantCall(LHSValue));
19340 // We can't tell whether weak symbols will end up pointing to the same
19341 // object.
19342 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
19343 return DiagComparison(diag::note_constexpr_pointer_weak_comparison,
19344 !IsWeakLValue(LHSValue));
19345 // We can't compare the address of the start of one object with the
19346 // past-the-end address of another object, per C++ DR1652.
19347 if (LHSValue.Base && LHSValue.Offset.isZero() &&
19348 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue))
19349 return DiagComparison(diag::note_constexpr_pointer_comparison_past_end,
19350 true);
19351 if (RHSValue.Base && RHSValue.Offset.isZero() &&
19352 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue))
19353 return DiagComparison(diag::note_constexpr_pointer_comparison_past_end,
19354 false);
19355 // We can't tell whether an object is at the same address as another
19356 // zero sized object.
19357 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
19358 (LHSValue.Base && isZeroSized(RHSValue)))
19359 return DiagComparison(
19360 diag::note_constexpr_pointer_comparison_zero_sized);
19361 if (LHSValue.AllowConstexprUnknown || RHSValue.AllowConstexprUnknown)
19362 return DiagComparison(
19363 diag::note_constexpr_pointer_comparison_unspecified);
19364 // FIXME: Verify both variables are live.
19365 return Success(CmpResult::Unequal, E);
19366 }
19367
19368 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
19369 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
19370
19371 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
19372 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
19373
19374 // C++11 [expr.rel]p2:
19375 // - If two pointers point to non-static data members of the same object,
19376 // or to subobjects or array elements fo such members, recursively, the
19377 // pointer to the later declared member compares greater provided the
19378 // two members have the same access control and provided their class is
19379 // not a union.
19380 // [...]
19381 // - Otherwise pointer comparisons are unspecified.
19382 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
19383 bool WasArrayIndex;
19384 unsigned Mismatch = FindDesignatorMismatch(
19385 LHSValue.Base.isNull() ? QualType()
19386 : getType(LHSValue.Base).getNonReferenceType(),
19387 LHSDesignator, RHSDesignator, WasArrayIndex);
19388 // At the point where the designators diverge, the comparison has a
19389 // specified value if:
19390 // - we are comparing array indices
19391 // - we are comparing fields of a union, or fields with the same access
19392 // Otherwise, the result is unspecified and thus the comparison is not a
19393 // constant expression.
19394 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
19395 Mismatch < RHSDesignator.Entries.size()) {
19396 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
19397 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
19398 if (!LF && !RF)
19399 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
19400 else if (!LF)
19401 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
19402 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
19403 << RF->getParent() << RF;
19404 else if (!RF)
19405 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
19406 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
19407 << LF->getParent() << LF;
19408 else if (!LF->getParent()->isUnion() &&
19409 LF->getAccess() != RF->getAccess())
19410 Info.CCEDiag(E,
19411 diag::note_constexpr_pointer_comparison_differing_access)
19412 << LF << LF->getAccess() << RF << RF->getAccess()
19413 << LF->getParent();
19414 }
19415 }
19416
19417 // The comparison here must be unsigned, and performed with the same
19418 // width as the pointer.
19419 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
19420 uint64_t CompareLHS = LHSOffset.getQuantity();
19421 uint64_t CompareRHS = RHSOffset.getQuantity();
19422 assert(PtrSize <= 64 && "Unexpected pointer width");
19423 uint64_t Mask = ~0ULL >> (64 - PtrSize);
19424 CompareLHS &= Mask;
19425 CompareRHS &= Mask;
19426
19427 // If there is a base and this is a relational operator, we can only
19428 // compare pointers within the object in question; otherwise, the result
19429 // depends on where the object is located in memory.
19430 if (!LHSValue.Base.isNull() && IsRelational) {
19431 QualType BaseTy = getType(LHSValue.Base).getNonReferenceType();
19432 if (BaseTy->isIncompleteType())
19433 return Error(E);
19434 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
19435 uint64_t OffsetLimit = Size.getQuantity();
19436 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
19437 return Error(E);
19438 }
19439
19440 if (CompareLHS < CompareRHS)
19441 return Success(CmpResult::Less, E);
19442 if (CompareLHS > CompareRHS)
19443 return Success(CmpResult::Greater, E);
19444 return Success(CmpResult::Equal, E);
19445 }
19446
19447 if (LHSTy->isMemberPointerType()) {
19448 assert(IsEquality && "unexpected member pointer operation");
19449 assert(RHSTy->isMemberPointerType() && "invalid comparison");
19450
19451 MemberPtr LHSValue, RHSValue;
19452
19453 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
19454 if (!LHSOK && !Info.noteFailure())
19455 return false;
19456
19457 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
19458 return false;
19459
19460 // If either operand is a pointer to a weak function, the comparison is not
19461 // constant.
19462 if (LHSValue.getDecl() && LHSValue.getDecl()->isWeak()) {
19463 Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison)
19464 << LHSValue.getDecl();
19465 return false;
19466 }
19467 if (RHSValue.getDecl() && RHSValue.getDecl()->isWeak()) {
19468 Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison)
19469 << RHSValue.getDecl();
19470 return false;
19471 }
19472
19473 // C++11 [expr.eq]p2:
19474 // If both operands are null, they compare equal. Otherwise if only one is
19475 // null, they compare unequal.
19476 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
19477 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
19478 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
19479 }
19480
19481 // Otherwise if either is a pointer to a virtual member function, the
19482 // result is unspecified.
19483 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
19484 if (MD->isVirtual())
19485 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
19486 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
19487 if (MD->isVirtual())
19488 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
19489
19490 // Otherwise they compare equal if and only if they would refer to the
19491 // same member of the same most derived object or the same subobject if
19492 // they were dereferenced with a hypothetical object of the associated
19493 // class type.
19494 bool Equal = LHSValue == RHSValue;
19495 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
19496 }
19497
19498 if (LHSTy->isNullPtrType()) {
19499 assert(E->isComparisonOp() && "unexpected nullptr operation");
19500 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
19501 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
19502 // are compared, the result is true of the operator is <=, >= or ==, and
19503 // false otherwise.
19504 LValue Res;
19505 if (!EvaluatePointer(E->getLHS(), Res, Info) ||
19506 !EvaluatePointer(E->getRHS(), Res, Info))
19507 return false;
19508 return Success(CmpResult::Equal, E);
19509 }
19510
19511 return DoAfter();
19512}
19513
19514bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
19515 if (!CheckLiteralType(Info, E))
19516 return false;
19517
19518 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
19520 switch (CR) {
19521 case CmpResult::Unequal:
19522 llvm_unreachable("should never produce Unequal for three-way comparison");
19523 case CmpResult::Less:
19524 CCR = ComparisonCategoryResult::Less;
19525 break;
19526 case CmpResult::Equal:
19527 CCR = ComparisonCategoryResult::Equal;
19528 break;
19529 case CmpResult::Greater:
19530 CCR = ComparisonCategoryResult::Greater;
19531 break;
19532 case CmpResult::Unordered:
19533 CCR = ComparisonCategoryResult::Unordered;
19534 break;
19535 }
19536 // Evaluation succeeded. Lookup the information for the comparison category
19537 // type and fetch the VarDecl for the result.
19538 const ComparisonCategoryInfo &CmpInfo =
19539 Info.Ctx.CompCategories.getInfoForType(E->getType());
19540 const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD;
19541 // Check and evaluate the result as a constant expression.
19542 LValue LV;
19543 LV.set(VD);
19544 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
19545 return false;
19546 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
19547 ConstantExprKind::Normal);
19548 };
19549 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
19550 return ExprEvaluatorBaseTy::VisitBinCmp(E);
19551 });
19552}
19553
19554bool RecordExprEvaluator::VisitCXXParenListInitExpr(
19555 const CXXParenListInitExpr *E) {
19556 return VisitCXXParenListOrInitListExpr(E, E->getInitExprs());
19557}
19558
19559bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
19560 // We don't support assignment in C. C++ assignments don't get here because
19561 // assignment is an lvalue in C++.
19562 if (E->isAssignmentOp()) {
19563 Error(E);
19564 if (!Info.noteFailure())
19565 return false;
19566 }
19567
19568 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
19569 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
19570
19571 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
19573 "DataRecursiveIntBinOpEvaluator should have handled integral types");
19574
19575 if (E->isComparisonOp()) {
19576 // Evaluate builtin binary comparisons by evaluating them as three-way
19577 // comparisons and then translating the result.
19578 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
19579 assert((CR != CmpResult::Unequal || E->isEqualityOp()) &&
19580 "should only produce Unequal for equality comparisons");
19581 bool IsEqual = CR == CmpResult::Equal,
19582 IsLess = CR == CmpResult::Less,
19583 IsGreater = CR == CmpResult::Greater;
19584 auto Op = E->getOpcode();
19585 switch (Op) {
19586 default:
19587 llvm_unreachable("unsupported binary operator");
19588 case BO_EQ:
19589 case BO_NE:
19590 return Success(IsEqual == (Op == BO_EQ), E);
19591 case BO_LT:
19592 return Success(IsLess, E);
19593 case BO_GT:
19594 return Success(IsGreater, E);
19595 case BO_LE:
19596 return Success(IsEqual || IsLess, E);
19597 case BO_GE:
19598 return Success(IsEqual || IsGreater, E);
19599 }
19600 };
19601 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
19602 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
19603 });
19604 }
19605
19606 QualType LHSTy = E->getLHS()->getType();
19607 QualType RHSTy = E->getRHS()->getType();
19608
19609 if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
19610 E->getOpcode() == BO_Sub) {
19611 LValue LHSValue, RHSValue;
19612
19613 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
19614 if (!LHSOK && !Info.noteFailure())
19615 return false;
19616
19617 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
19618 return false;
19619
19620 // Reject differing bases from the normal codepath; we special-case
19621 // comparisons to null.
19622 if (!HasSameBase(LHSValue, RHSValue)) {
19623 if (Info.checkingPotentialConstantExpression() &&
19624 (LHSValue.AllowConstexprUnknown || RHSValue.AllowConstexprUnknown))
19625 return false;
19626
19627 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
19628 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
19629
19630 auto DiagArith = [&](unsigned DiagID) {
19631 std::string LHS = LHSValue.toString(Info.Ctx, E->getLHS()->getType());
19632 std::string RHS = RHSValue.toString(Info.Ctx, E->getRHS()->getType());
19633 Info.FFDiag(E, DiagID) << LHS << RHS;
19634 if (LHSExpr && LHSExpr == RHSExpr)
19635 Info.Note(LHSExpr->getExprLoc(),
19636 diag::note_constexpr_repeated_literal_eval)
19637 << LHSExpr->getSourceRange();
19638 return false;
19639 };
19640
19641 if (!LHSExpr || !RHSExpr)
19642 return DiagArith(diag::note_constexpr_pointer_arith_unspecified);
19643
19644 if (ArePotentiallyOverlappingStringLiterals(Info, LHSValue, RHSValue))
19645 return DiagArith(diag::note_constexpr_literal_arith);
19646
19647 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
19648 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
19649 if (!LHSAddrExpr || !RHSAddrExpr)
19650 return Error(E);
19651 // Make sure both labels come from the same function.
19652 if (LHSAddrExpr->getLabel()->getDeclContext() !=
19653 RHSAddrExpr->getLabel()->getDeclContext())
19654 return Error(E);
19655 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
19656 }
19657 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
19658 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
19659
19660 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
19661 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
19662
19663 // C++11 [expr.add]p6:
19664 // Unless both pointers point to elements of the same array object, or
19665 // one past the last element of the array object, the behavior is
19666 // undefined.
19667 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
19668 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
19669 RHSDesignator))
19670 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
19671
19672 QualType Type = E->getLHS()->getType();
19673 QualType ElementType = Type->castAs<PointerType>()->getPointeeType();
19674
19675 CharUnits ElementSize;
19676 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
19677 return false;
19678
19679 // As an extension, a type may have zero size (empty struct or union in
19680 // C, array of zero length). Pointer subtraction in such cases has
19681 // undefined behavior, so is not constant.
19682 if (ElementSize.isZero()) {
19683 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
19684 << ElementType;
19685 return false;
19686 }
19687
19688 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
19689 // and produce incorrect results when it overflows. Such behavior
19690 // appears to be non-conforming, but is common, so perhaps we should
19691 // assume the standard intended for such cases to be undefined behavior
19692 // and check for them.
19693
19694 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
19695 // overflow in the final conversion to ptrdiff_t.
19696 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
19697 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
19698 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
19699 false);
19700 APSInt TrueResult = (LHS - RHS) / ElemSize;
19701 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
19702
19703 if (Result.extend(65) != TrueResult &&
19704 !HandleOverflow(Info, E, TrueResult, E->getType()))
19705 return false;
19706 return Success(Result, E);
19707 }
19708
19709 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
19710}
19711
19712/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
19713/// a result as the expression's type.
19714bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
19715 const UnaryExprOrTypeTraitExpr *E) {
19716 switch(E->getKind()) {
19717 case UETT_PreferredAlignOf:
19718 case UETT_AlignOf: {
19719 if (E->isArgumentType())
19720 return Success(
19721 GetAlignOfType(Info.Ctx, E->getArgumentType(), E->getKind()), E);
19722 else
19723 return Success(
19724 GetAlignOfExpr(Info.Ctx, E->getArgumentExpr(), E->getKind()), E);
19725 }
19726
19727 case UETT_PtrAuthTypeDiscriminator: {
19728 if (E->getArgumentType()->isDependentType())
19729 return false;
19730 return Success(
19731 Info.Ctx.getPointerAuthTypeDiscriminator(E->getArgumentType()), E);
19732 }
19733 case UETT_VecStep: {
19734 QualType Ty = E->getTypeOfArgument();
19735
19736 if (Ty->isVectorType()) {
19737 unsigned n = Ty->castAs<VectorType>()->getNumElements();
19738
19739 // The vec_step built-in functions that take a 3-component
19740 // vector return 4. (OpenCL 1.1 spec 6.11.12)
19741 if (n == 3)
19742 n = 4;
19743
19744 return Success(n, E);
19745 } else
19746 return Success(1, E);
19747 }
19748
19749 case UETT_DataSizeOf:
19750 case UETT_SizeOf: {
19751 QualType SrcTy = E->getTypeOfArgument();
19752 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
19753 // the result is the size of the referenced type."
19754 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
19755 SrcTy = Ref->getPointeeType();
19756
19757 CharUnits Sizeof;
19758 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof,
19759 E->getKind() == UETT_DataSizeOf ? SizeOfType::DataSizeOf
19760 : SizeOfType::SizeOf)) {
19761 return false;
19762 }
19763 return Success(Sizeof, E);
19764 }
19765 case UETT_OpenMPRequiredSimdAlign:
19766 assert(E->isArgumentType());
19767 return Success(
19768 Info.Ctx.toCharUnitsFromBits(
19769 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
19770 .getQuantity(),
19771 E);
19772 case UETT_VectorElements: {
19773 QualType Ty = E->getTypeOfArgument();
19774 // If the vector has a fixed size, we can determine the number of elements
19775 // at compile time.
19776 if (const auto *VT = Ty->getAs<VectorType>())
19777 return Success(VT->getNumElements(), E);
19778
19779 assert(Ty->isSizelessVectorType());
19780 if (Info.InConstantContext)
19781 Info.CCEDiag(E, diag::note_constexpr_non_const_vectorelements)
19782 << E->getSourceRange();
19783
19784 return false;
19785 }
19786 case UETT_CountOf: {
19787 QualType Ty = E->getTypeOfArgument();
19788 assert(Ty->isArrayType());
19789
19790 // We don't need to worry about array element qualifiers, so getting the
19791 // unsafe array type is fine.
19792 if (const auto *CAT =
19793 dyn_cast<ConstantArrayType>(Ty->getAsArrayTypeUnsafe())) {
19794 return Success(CAT->getSize(), E);
19795 }
19796
19797 assert(!Ty->isConstantSizeType());
19798
19799 // If it's a variable-length array type, we need to check whether it is a
19800 // multidimensional array. If so, we need to check the size expression of
19801 // the VLA to see if it's a constant size. If so, we can return that value.
19802 const auto *VAT = Info.Ctx.getAsVariableArrayType(Ty);
19803 assert(VAT);
19804 if (VAT->getElementType()->isArrayType()) {
19805 // Variable array size expression could be missing (e.g. int a[*][10]) In
19806 // that case, it can't be a constant expression.
19807 if (!VAT->getSizeExpr()) {
19808 Info.FFDiag(E->getBeginLoc());
19809 return false;
19810 }
19811
19812 std::optional<APSInt> Res =
19813 VAT->getSizeExpr()->getIntegerConstantExpr(Info.Ctx);
19814 if (Res) {
19815 // The resulting value always has type size_t, so we need to make the
19816 // returned APInt have the correct sign and bit-width.
19817 APInt Val{
19818 static_cast<unsigned>(Info.Ctx.getTypeSize(Info.Ctx.getSizeType())),
19819 Res->getZExtValue()};
19820 return Success(Val, E);
19821 }
19822 }
19823
19824 // Definitely a variable-length type, which is not an ICE.
19825 // FIXME: Better diagnostic.
19826 Info.FFDiag(E->getBeginLoc());
19827 return false;
19828 }
19829 }
19830
19831 llvm_unreachable("unknown expr/type trait");
19832}
19833
19834bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
19835 Info.Ctx.recordOffsetOfEvaluation(OOE);
19836 CharUnits Result;
19837 unsigned n = OOE->getNumComponents();
19838 if (n == 0)
19839 return Error(OOE);
19840 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
19841 for (unsigned i = 0; i != n; ++i) {
19842 OffsetOfNode ON = OOE->getComponent(i);
19843 switch (ON.getKind()) {
19844 case OffsetOfNode::Array: {
19845 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
19846 APSInt IdxResult;
19847 if (!EvaluateInteger(Idx, IdxResult, Info))
19848 return false;
19849 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
19850 if (!AT)
19851 return Error(OOE);
19852 CurrentType = AT->getElementType();
19853 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
19854 // Reject negative indices, indices too large to fit in int64_t,
19855 // and overflow in the offset computation.
19856 if (IdxResult.isNegative() || IdxResult.getActiveBits() > 63)
19857 return Error(OOE);
19858 int64_t IdxVal = IdxResult.getExtValue();
19859 int64_t ElemSize = ElementSize.getQuantity();
19860 if (IdxVal != 0 &&
19861 ElemSize > std::numeric_limits<int64_t>::max() / IdxVal)
19862 return Error(OOE, diag::note_constexpr_offsetof_overflow);
19863 int64_t Offset = IdxVal * ElemSize;
19864 if (Result.getQuantity() > std::numeric_limits<int64_t>::max() - Offset)
19865 return Error(OOE, diag::note_constexpr_offsetof_overflow);
19867 break;
19868 }
19869
19870 case OffsetOfNode::Field: {
19871 FieldDecl *MemberDecl = ON.getField();
19872 const auto *RD = CurrentType->getAsRecordDecl();
19873 if (!RD)
19874 return Error(OOE);
19875 if (RD->isInvalidDecl()) return false;
19876 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
19877 unsigned i = MemberDecl->getFieldIndex();
19878 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
19879 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
19880 CurrentType = MemberDecl->getType().getNonReferenceType();
19881 break;
19882 }
19883
19885 llvm_unreachable("dependent __builtin_offsetof");
19886
19887 case OffsetOfNode::Base: {
19888 CXXBaseSpecifier *BaseSpec = ON.getBase();
19889 if (BaseSpec->isVirtual())
19890 return Error(OOE);
19891
19892 // Find the layout of the class whose base we are looking into.
19893 const auto *RD = CurrentType->getAsCXXRecordDecl();
19894 if (!RD)
19895 return Error(OOE);
19896 if (RD->isInvalidDecl()) return false;
19897 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
19898
19899 // Find the base class itself.
19900 CurrentType = BaseSpec->getType();
19901 const auto *BaseRD = CurrentType->getAsCXXRecordDecl();
19902 if (!BaseRD)
19903 return Error(OOE);
19904
19905 // Add the offset to the base.
19906 Result += RL.getBaseClassOffset(BaseRD);
19907 break;
19908 }
19909 }
19910 }
19911 return Success(Result, OOE);
19912}
19913
19914bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
19915 switch (E->getOpcode()) {
19916 default:
19917 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
19918 // See C99 6.6p3.
19919 return Error(E);
19920 case UO_Extension:
19921 // FIXME: Should extension allow i-c-e extension expressions in its scope?
19922 // If so, we could clear the diagnostic ID.
19923 return Visit(E->getSubExpr());
19924 case UO_Plus:
19925 // The result is just the value.
19926 return Visit(E->getSubExpr());
19927 case UO_Minus: {
19928 if (!Visit(E->getSubExpr()))
19929 return false;
19930 if (!Result.isInt()) return Error(E);
19931 const APSInt &Value = Result.getInt();
19932 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
19933 !E->getType().isWrapType()) {
19934 if (Info.checkingForUndefinedBehavior())
19935 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
19936 diag::warn_integer_constant_overflow)
19937 << toString(Value, 10, Value.isSigned(), /*formatAsCLiteral=*/false,
19938 /*UpperCase=*/true, /*InsertSeparators=*/true)
19939 << E->getType() << E->getSourceRange();
19940
19941 if (!HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
19942 E->getType()))
19943 return false;
19944 }
19945 return Success(-Value, E);
19946 }
19947 case UO_Not: {
19948 if (!Visit(E->getSubExpr()))
19949 return false;
19950 if (!Result.isInt()) return Error(E);
19951 return Success(~Result.getInt(), E);
19952 }
19953 case UO_LNot: {
19954 bool bres;
19955 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
19956 return false;
19957 return Success(!bres, E);
19958 }
19959 }
19960}
19961
19962/// HandleCast - This is used to evaluate implicit or explicit casts where the
19963/// result type is integer.
19964bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
19965 const Expr *SubExpr = E->getSubExpr();
19966 QualType DestType = E->getType();
19967 QualType SrcType = SubExpr->getType();
19968
19969 switch (E->getCastKind()) {
19970 case CK_BaseToDerived:
19971 case CK_DerivedToBase:
19972 case CK_UncheckedDerivedToBase:
19973 case CK_Dynamic:
19974 case CK_ToUnion:
19975 case CK_ArrayToPointerDecay:
19976 case CK_FunctionToPointerDecay:
19977 case CK_NullToPointer:
19978 case CK_NullToMemberPointer:
19979 case CK_BaseToDerivedMemberPointer:
19980 case CK_DerivedToBaseMemberPointer:
19981 case CK_ReinterpretMemberPointer:
19982 case CK_ConstructorConversion:
19983 case CK_IntegralToPointer:
19984 case CK_ToVoid:
19985 case CK_VectorSplat:
19986 case CK_IntegralToFloating:
19987 case CK_FloatingCast:
19988 case CK_CPointerToObjCPointerCast:
19989 case CK_BlockPointerToObjCPointerCast:
19990 case CK_AnyPointerToBlockPointerCast:
19991 case CK_ObjCObjectLValueCast:
19992 case CK_FloatingRealToComplex:
19993 case CK_FloatingComplexToReal:
19994 case CK_FloatingComplexCast:
19995 case CK_FloatingComplexToIntegralComplex:
19996 case CK_IntegralRealToComplex:
19997 case CK_IntegralComplexCast:
19998 case CK_IntegralComplexToFloatingComplex:
19999 case CK_BuiltinFnToFnPtr:
20000 case CK_ZeroToOCLOpaqueType:
20001 case CK_NonAtomicToAtomic:
20002 case CK_AddressSpaceConversion:
20003 case CK_IntToOCLSampler:
20004 case CK_FloatingToFixedPoint:
20005 case CK_FixedPointToFloating:
20006 case CK_FixedPointCast:
20007 case CK_IntegralToFixedPoint:
20008 case CK_MatrixCast:
20009 case CK_HLSLAggregateSplatCast:
20010 llvm_unreachable("invalid cast kind for integral value");
20011
20012 case CK_BitCast:
20013 case CK_Dependent:
20014 case CK_LValueBitCast:
20015 case CK_ARCProduceObject:
20016 case CK_ARCConsumeObject:
20017 case CK_ARCReclaimReturnedObject:
20018 case CK_ARCExtendBlockObject:
20019 case CK_CopyAndAutoreleaseBlockObject:
20020 return Error(E);
20021
20022 case CK_UserDefinedConversion:
20023 case CK_LValueToRValue:
20024 case CK_AtomicToNonAtomic:
20025 case CK_NoOp:
20026 case CK_LValueToRValueBitCast:
20027 case CK_HLSLArrayRValue:
20028 return ExprEvaluatorBaseTy::VisitCastExpr(E);
20029
20030 case CK_MemberPointerToBoolean:
20031 case CK_PointerToBoolean:
20032 case CK_IntegralToBoolean:
20033 case CK_FloatingToBoolean:
20034 case CK_BooleanToSignedIntegral:
20035 case CK_FloatingComplexToBoolean:
20036 case CK_IntegralComplexToBoolean: {
20037 bool BoolResult;
20038 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
20039 return false;
20040 uint64_t IntResult = BoolResult;
20041 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
20042 IntResult = (uint64_t)-1;
20043 return Success(IntResult, E);
20044 }
20045
20046 case CK_FixedPointToIntegral: {
20047 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
20048 if (!EvaluateFixedPoint(SubExpr, Src, Info))
20049 return false;
20050 bool Overflowed;
20051 llvm::APSInt Result = Src.convertToInt(
20052 Info.Ctx.getIntWidth(DestType),
20053 DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
20054 if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
20055 return false;
20056 return Success(Result, E);
20057 }
20058
20059 case CK_FixedPointToBoolean: {
20060 // Unsigned padding does not affect this.
20061 APValue Val;
20062 if (!Evaluate(Val, Info, SubExpr))
20063 return false;
20064 return Success(Val.getFixedPoint().getBoolValue(), E);
20065 }
20066
20067 case CK_IntegralCast: {
20068 if (!Visit(SubExpr))
20069 return false;
20070
20071 if (!Result.isInt()) {
20072 // Allow casts of address-of-label differences if they are no-ops
20073 // or narrowing, if the result is at least 32 bits wide.
20074 // (The narrowing case isn't actually guaranteed to
20075 // be constant-evaluatable except in some narrow cases which are hard
20076 // to detect here. We let it through on the assumption the user knows
20077 // what they are doing.)
20078 if (Result.isAddrLabelDiff()) {
20079 unsigned DestBits = Info.Ctx.getTypeSize(DestType);
20080 return DestBits >= 32 && DestBits <= Info.Ctx.getTypeSize(SrcType);
20081 }
20082 // Only allow casts of lvalues if they are lossless.
20083 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
20084 }
20085
20086 if (Info.Ctx.getLangOpts().CPlusPlus && DestType->isEnumeralType()) {
20087 const auto *ED = DestType->getAsEnumDecl();
20088 // Check that the value is within the range of the enumeration values.
20089 //
20090 // This corressponds to [expr.static.cast]p10 which says:
20091 // A value of integral or enumeration type can be explicitly converted
20092 // to a complete enumeration type ... If the enumeration type does not
20093 // have a fixed underlying type, the value is unchanged if the original
20094 // value is within the range of the enumeration values ([dcl.enum]), and
20095 // otherwise, the behavior is undefined.
20096 //
20097 // This was resolved as part of DR2338 which has CD5 status.
20098 if (!ED->isFixed()) {
20099 llvm::APInt Min;
20100 llvm::APInt Max;
20101
20102 ED->getValueRange(Max, Min);
20103 --Max;
20104
20105 if (ED->getNumNegativeBits() &&
20106 (Max.slt(Result.getInt().getSExtValue()) ||
20107 Min.sgt(Result.getInt().getSExtValue())))
20108 Info.CCEDiag(E, diag::note_constexpr_unscoped_enum_out_of_range)
20109 << llvm::toString(Result.getInt(), 10) << Min.getSExtValue()
20110 << Max.getSExtValue() << ED;
20111 else if (!ED->getNumNegativeBits() &&
20112 Max.ult(Result.getInt().getZExtValue()))
20113 Info.CCEDiag(E, diag::note_constexpr_unscoped_enum_out_of_range)
20114 << llvm::toString(Result.getInt(), 10) << Min.getZExtValue()
20115 << Max.getZExtValue() << ED;
20116 }
20117 }
20118
20119 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
20120 Result.getInt()), E);
20121 }
20122
20123 case CK_PointerToIntegral: {
20124 CCEDiag(E, diag::note_constexpr_invalid_cast_ptrtoint)
20125 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
20126 << Info.Ctx.getLangOpts().CPlusPlus << E->getSourceRange();
20127
20128 LValue LV;
20129 if (!EvaluatePointer(SubExpr, LV, Info))
20130 return false;
20131
20132 if (LV.getLValueBase()) {
20133 CCEDiag(E, diag::note_constexpr_has_lvalue) << E->getSourceRange();
20134 // Only allow based lvalue casts if they are lossless.
20135 // FIXME: Allow a larger integer size than the pointer size, and allow
20136 // narrowing back down to pointer width in subsequent integral casts.
20137 // FIXME: Check integer type's active bits, not its type size.
20138 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
20139 return Error(E);
20140
20141 LV.Designator.setInvalid();
20142 LV.moveInto(Result);
20143 return true;
20144 }
20145
20146 APSInt AsInt;
20147 APValue V;
20148 LV.moveInto(V);
20149 if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
20150 llvm_unreachable("Can't cast this!");
20151
20152 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
20153 }
20154
20155 case CK_IntegralComplexToReal: {
20156 ComplexValue C;
20157 if (!EvaluateComplex(SubExpr, C, Info))
20158 return false;
20159 return Success(C.getComplexIntReal(), E);
20160 }
20161
20162 case CK_FloatingToIntegral: {
20163 APFloat F(0.0);
20164 if (!EvaluateFloat(SubExpr, F, Info))
20165 return false;
20166
20167 APSInt Value;
20168 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
20169 return false;
20170 return Success(Value, E);
20171 }
20172 case CK_HLSLVectorTruncation: {
20173 APValue Val;
20174 if (!EvaluateVector(SubExpr, Val, Info))
20175 return Error(E);
20176 return Success(Val.getVectorElt(0), E);
20177 }
20178 case CK_HLSLMatrixTruncation: {
20179 APValue Val;
20180 if (!EvaluateMatrix(SubExpr, Val, Info))
20181 return Error(E);
20182 return Success(Val.getMatrixElt(0, 0), E);
20183 }
20184 case CK_HLSLElementwiseCast: {
20185 SmallVector<APValue> SrcVals;
20186 SmallVector<QualType> SrcTypes;
20187
20188 if (!hlslElementwiseCastHelper(Info, SubExpr, DestType, SrcVals, SrcTypes))
20189 return false;
20190
20191 // cast our single element
20192 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
20193 APValue ResultVal;
20194 if (!handleScalarCast(Info, FPO, E, SrcTypes[0], DestType, SrcVals[0],
20195 ResultVal))
20196 return false;
20197 return Success(ResultVal, E);
20198 }
20199 }
20200
20201 llvm_unreachable("unknown cast resulting in integral value");
20202}
20203
20204bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
20205 if (E->getSubExpr()->getType()->isAnyComplexType()) {
20206 ComplexValue LV;
20207 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
20208 return false;
20209 if (!LV.isComplexInt())
20210 return Error(E);
20211 return Success(LV.getComplexIntReal(), E);
20212 }
20213
20214 return Visit(E->getSubExpr());
20215}
20216
20217bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
20218 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
20219 ComplexValue LV;
20220 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
20221 return false;
20222 if (!LV.isComplexInt())
20223 return Error(E);
20224 return Success(LV.getComplexIntImag(), E);
20225 }
20226
20227 VisitIgnoredValue(E->getSubExpr());
20228 return Success(0, E);
20229}
20230
20231bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
20232 return Success(E->getPackLength(), E);
20233}
20234
20235bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
20236 return Success(E->getValue(), E);
20237}
20238
20239bool IntExprEvaluator::VisitConceptSpecializationExpr(
20240 const ConceptSpecializationExpr *E) {
20241 return Success(E->isSatisfied(), E);
20242}
20243
20244bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) {
20245 return Success(E->isSatisfied(), E);
20246}
20247
20248bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
20249 switch (E->getOpcode()) {
20250 default:
20251 // Invalid unary operators
20252 return Error(E);
20253 case UO_Plus:
20254 // The result is just the value.
20255 return Visit(E->getSubExpr());
20256 case UO_Minus: {
20257 if (!Visit(E->getSubExpr())) return false;
20258 if (!Result.isFixedPoint())
20259 return Error(E);
20260 bool Overflowed;
20261 APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
20262 if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
20263 return false;
20264 return Success(Negated, E);
20265 }
20266 case UO_LNot: {
20267 bool bres;
20268 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
20269 return false;
20270 return Success(!bres, E);
20271 }
20272 }
20273}
20274
20275bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
20276 const Expr *SubExpr = E->getSubExpr();
20277 QualType DestType = E->getType();
20278 assert(DestType->isFixedPointType() &&
20279 "Expected destination type to be a fixed point type");
20280 auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
20281
20282 switch (E->getCastKind()) {
20283 case CK_FixedPointCast: {
20284 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
20285 if (!EvaluateFixedPoint(SubExpr, Src, Info))
20286 return false;
20287 bool Overflowed;
20288 APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
20289 if (Overflowed) {
20290 if (Info.checkingForUndefinedBehavior())
20291 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
20292 diag::warn_fixedpoint_constant_overflow)
20293 << Result.toString() << E->getType();
20294 if (!HandleOverflow(Info, E, Result, E->getType()))
20295 return false;
20296 }
20297 return Success(Result, E);
20298 }
20299 case CK_IntegralToFixedPoint: {
20300 APSInt Src;
20301 if (!EvaluateInteger(SubExpr, Src, Info))
20302 return false;
20303
20304 bool Overflowed;
20305 APFixedPoint IntResult = APFixedPoint::getFromIntValue(
20306 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
20307
20308 if (Overflowed) {
20309 if (Info.checkingForUndefinedBehavior())
20310 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
20311 diag::warn_fixedpoint_constant_overflow)
20312 << IntResult.toString() << E->getType();
20313 if (!HandleOverflow(Info, E, IntResult, E->getType()))
20314 return false;
20315 }
20316
20317 return Success(IntResult, E);
20318 }
20319 case CK_FloatingToFixedPoint: {
20320 APFloat Src(0.0);
20321 if (!EvaluateFloat(SubExpr, Src, Info))
20322 return false;
20323
20324 bool Overflowed;
20325 APFixedPoint Result = APFixedPoint::getFromFloatValue(
20326 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
20327
20328 if (Overflowed) {
20329 if (Info.checkingForUndefinedBehavior())
20330 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
20331 diag::warn_fixedpoint_constant_overflow)
20332 << Result.toString() << E->getType();
20333 if (!HandleOverflow(Info, E, Result, E->getType()))
20334 return false;
20335 }
20336
20337 return Success(Result, E);
20338 }
20339 case CK_NoOp:
20340 case CK_LValueToRValue:
20341 return ExprEvaluatorBaseTy::VisitCastExpr(E);
20342 default:
20343 return Error(E);
20344 }
20345}
20346
20347bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
20348 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
20349 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
20350
20351 const Expr *LHS = E->getLHS();
20352 const Expr *RHS = E->getRHS();
20353 FixedPointSemantics ResultFXSema =
20354 Info.Ctx.getFixedPointSemantics(E->getType());
20355
20356 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
20357 if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
20358 return false;
20359 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
20360 if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
20361 return false;
20362
20363 bool OpOverflow = false, ConversionOverflow = false;
20364 APFixedPoint Result(LHSFX.getSemantics());
20365 switch (E->getOpcode()) {
20366 case BO_Add: {
20367 Result = LHSFX.add(RHSFX, &OpOverflow)
20368 .convert(ResultFXSema, &ConversionOverflow);
20369 break;
20370 }
20371 case BO_Sub: {
20372 Result = LHSFX.sub(RHSFX, &OpOverflow)
20373 .convert(ResultFXSema, &ConversionOverflow);
20374 break;
20375 }
20376 case BO_Mul: {
20377 Result = LHSFX.mul(RHSFX, &OpOverflow)
20378 .convert(ResultFXSema, &ConversionOverflow);
20379 break;
20380 }
20381 case BO_Div: {
20382 if (RHSFX.getValue() == 0) {
20383 Info.FFDiag(E, diag::note_expr_divide_by_zero);
20384 return false;
20385 }
20386 Result = LHSFX.div(RHSFX, &OpOverflow)
20387 .convert(ResultFXSema, &ConversionOverflow);
20388 break;
20389 }
20390 case BO_Shl:
20391 case BO_Shr: {
20392 FixedPointSemantics LHSSema = LHSFX.getSemantics();
20393 llvm::APSInt RHSVal = RHSFX.getValue();
20394
20395 unsigned ShiftBW =
20396 LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding();
20397 unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1);
20398 // Embedded-C 4.1.6.2.2:
20399 // The right operand must be nonnegative and less than the total number
20400 // of (nonpadding) bits of the fixed-point operand ...
20401 if (RHSVal.isNegative())
20402 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal;
20403 else if (Amt != RHSVal)
20404 Info.CCEDiag(E, diag::note_constexpr_large_shift)
20405 << RHSVal << E->getType() << ShiftBW;
20406
20407 if (E->getOpcode() == BO_Shl)
20408 Result = LHSFX.shl(Amt, &OpOverflow);
20409 else
20410 Result = LHSFX.shr(Amt, &OpOverflow);
20411 break;
20412 }
20413 default:
20414 return false;
20415 }
20416 if (OpOverflow || ConversionOverflow) {
20417 if (Info.checkingForUndefinedBehavior())
20418 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
20419 diag::warn_fixedpoint_constant_overflow)
20420 << Result.toString() << E->getType();
20421 if (!HandleOverflow(Info, E, Result, E->getType()))
20422 return false;
20423 }
20424 return Success(Result, E);
20425}
20426
20427//===----------------------------------------------------------------------===//
20428// Float Evaluation
20429//===----------------------------------------------------------------------===//
20430
20431namespace {
20432class FloatExprEvaluator
20433 : public ExprEvaluatorBase<FloatExprEvaluator> {
20434 APFloat &Result;
20435public:
20436 FloatExprEvaluator(EvalInfo &info, APFloat &result)
20437 : ExprEvaluatorBaseTy(info), Result(result) {}
20438
20439 bool Success(const APValue &V, const Expr *e) {
20440 Result = V.getFloat();
20441 return true;
20442 }
20443
20444 bool ZeroInitialization(const Expr *E) {
20445 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
20446 return true;
20447 }
20448
20449 bool VisitCallExpr(const CallExpr *E);
20450
20451 bool VisitUnaryOperator(const UnaryOperator *E);
20452 bool VisitBinaryOperator(const BinaryOperator *E);
20453 bool VisitFloatingLiteral(const FloatingLiteral *E);
20454 bool VisitCastExpr(const CastExpr *E);
20455
20456 bool VisitUnaryReal(const UnaryOperator *E);
20457 bool VisitUnaryImag(const UnaryOperator *E);
20458
20459 // FIXME: Missing: array subscript of vector, member of vector
20460};
20461} // end anonymous namespace
20462
20463static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
20464 assert(!E->isValueDependent());
20465 assert(E->isPRValue() && E->getType()->isRealFloatingType());
20466 return FloatExprEvaluator(Info, Result).Visit(E);
20467}
20468
20469static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
20470 QualType ResultTy,
20471 const Expr *Arg,
20472 bool SNaN,
20473 llvm::APFloat &Result) {
20474 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
20475 if (!S || !S->isOrdinary())
20476 return false;
20477
20478 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
20479
20480 llvm::APInt fill;
20481
20482 // Treat empty strings as if they were zero.
20483 if (S->getString().empty())
20484 fill = llvm::APInt(32, 0);
20485 else if (S->getString().getAsInteger(0, fill))
20486 return false;
20487
20488 if (Context.getTargetInfo().isNan2008()) {
20489 if (SNaN)
20490 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
20491 else
20492 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
20493 } else {
20494 // Prior to IEEE 754-2008, architectures were allowed to choose whether
20495 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
20496 // a different encoding to what became a standard in 2008, and for pre-
20497 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
20498 // sNaN. This is now known as "legacy NaN" encoding.
20499 if (SNaN)
20500 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
20501 else
20502 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
20503 }
20504
20505 return true;
20506}
20507
20508bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
20509 if (!IsConstantEvaluatedBuiltinCall(E))
20510 return ExprEvaluatorBaseTy::VisitCallExpr(E);
20511
20512 unsigned BuiltinOp = ConvertBuiltinIDToX86BuiltinID(Info.Ctx, E);
20513
20514 switch (BuiltinOp) {
20515 default:
20516 return false;
20517
20518 case Builtin::BI__builtin_huge_val:
20519 case Builtin::BI__builtin_huge_valf:
20520 case Builtin::BI__builtin_huge_vall:
20521 case Builtin::BI__builtin_huge_valf16:
20522 case Builtin::BI__builtin_huge_valf128:
20523 case Builtin::BI__builtin_inf:
20524 case Builtin::BI__builtin_inff:
20525 case Builtin::BI__builtin_infl:
20526 case Builtin::BI__builtin_inff16:
20527 case Builtin::BI__builtin_inff128: {
20528 const llvm::fltSemantics &Sem =
20529 Info.Ctx.getFloatTypeSemantics(E->getType());
20530 Result = llvm::APFloat::getInf(Sem);
20531 return true;
20532 }
20533
20534 case Builtin::BI__builtin_nans:
20535 case Builtin::BI__builtin_nansf:
20536 case Builtin::BI__builtin_nansl:
20537 case Builtin::BI__builtin_nansf16:
20538 case Builtin::BI__builtin_nansf128:
20539 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
20540 true, Result))
20541 return Error(E);
20542 return true;
20543
20544 case Builtin::BI__builtin_nan:
20545 case Builtin::BI__builtin_nanf:
20546 case Builtin::BI__builtin_nanl:
20547 case Builtin::BI__builtin_nanf16:
20548 case Builtin::BI__builtin_nanf128:
20549 // If this is __builtin_nan() turn this into a nan, otherwise we
20550 // can't constant fold it.
20551 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
20552 false, Result))
20553 return Error(E);
20554 return true;
20555
20556 case Builtin::BI__builtin_elementwise_abs:
20557 case Builtin::BI__builtin_fabs:
20558 case Builtin::BI__builtin_fabsf:
20559 case Builtin::BI__builtin_fabsl:
20560 case Builtin::BI__builtin_fabsf128:
20561 // The C standard says "fabs raises no floating-point exceptions,
20562 // even if x is a signaling NaN. The returned value is independent of
20563 // the current rounding direction mode." Therefore constant folding can
20564 // proceed without regard to the floating point settings.
20565 // Reference, WG14 N2478 F.10.4.3
20566 if (!EvaluateFloat(E->getArg(0), Result, Info))
20567 return false;
20568
20569 if (Result.isNegative())
20570 Result.changeSign();
20571 return true;
20572
20573 case Builtin::BI__arithmetic_fence:
20574 return EvaluateFloat(E->getArg(0), Result, Info);
20575
20576 // FIXME: Builtin::BI__builtin_powi
20577 // FIXME: Builtin::BI__builtin_powif
20578 // FIXME: Builtin::BI__builtin_powil
20579
20580 case Builtin::BI__builtin_copysign:
20581 case Builtin::BI__builtin_copysignf:
20582 case Builtin::BI__builtin_copysignl:
20583 case Builtin::BI__builtin_copysignf128: {
20584 APFloat RHS(0.);
20585 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
20586 !EvaluateFloat(E->getArg(1), RHS, Info))
20587 return false;
20588 Result.copySign(RHS);
20589 return true;
20590 }
20591
20592 case Builtin::BI__builtin_fmax:
20593 case Builtin::BI__builtin_fmaxf:
20594 case Builtin::BI__builtin_fmaxl:
20595 case Builtin::BI__builtin_fmaxf16:
20596 case Builtin::BI__builtin_fmaxf128: {
20597 APFloat RHS(0.);
20598 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
20599 !EvaluateFloat(E->getArg(1), RHS, Info))
20600 return false;
20601 Result = maxnum(Result, RHS);
20602 return true;
20603 }
20604
20605 case Builtin::BI__builtin_fmin:
20606 case Builtin::BI__builtin_fminf:
20607 case Builtin::BI__builtin_fminl:
20608 case Builtin::BI__builtin_fminf16:
20609 case Builtin::BI__builtin_fminf128: {
20610 APFloat RHS(0.);
20611 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
20612 !EvaluateFloat(E->getArg(1), RHS, Info))
20613 return false;
20614 Result = minnum(Result, RHS);
20615 return true;
20616 }
20617
20618 case Builtin::BI__builtin_fmaximum_num:
20619 case Builtin::BI__builtin_fmaximum_numf:
20620 case Builtin::BI__builtin_fmaximum_numl:
20621 case Builtin::BI__builtin_fmaximum_numf16:
20622 case Builtin::BI__builtin_fmaximum_numf128: {
20623 APFloat RHS(0.);
20624 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
20625 !EvaluateFloat(E->getArg(1), RHS, Info))
20626 return false;
20627 Result = maximumnum(Result, RHS);
20628 return true;
20629 }
20630
20631 case Builtin::BI__builtin_fminimum_num:
20632 case Builtin::BI__builtin_fminimum_numf:
20633 case Builtin::BI__builtin_fminimum_numl:
20634 case Builtin::BI__builtin_fminimum_numf16:
20635 case Builtin::BI__builtin_fminimum_numf128: {
20636 APFloat RHS(0.);
20637 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
20638 !EvaluateFloat(E->getArg(1), RHS, Info))
20639 return false;
20640 Result = minimumnum(Result, RHS);
20641 return true;
20642 }
20643
20644 case Builtin::BI__builtin_elementwise_fma: {
20645 if (!E->getArg(0)->isPRValue() || !E->getArg(1)->isPRValue() ||
20646 !E->getArg(2)->isPRValue()) {
20647 return false;
20648 }
20649 APFloat SourceY(0.), SourceZ(0.);
20650 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
20651 !EvaluateFloat(E->getArg(1), SourceY, Info) ||
20652 !EvaluateFloat(E->getArg(2), SourceZ, Info))
20653 return false;
20654 llvm::RoundingMode RM = getActiveRoundingMode(getEvalInfo(), E);
20655 (void)Result.fusedMultiplyAdd(SourceY, SourceZ, RM);
20656 return true;
20657 }
20658
20659 case clang::X86::BI__builtin_ia32_vec_ext_v4sf: {
20660 APValue Vec;
20661 APSInt IdxAPS;
20662 if (!EvaluateVector(E->getArg(0), Vec, Info) ||
20663 !EvaluateInteger(E->getArg(1), IdxAPS, Info))
20664 return false;
20665 unsigned N = Vec.getVectorLength();
20666 unsigned Idx = static_cast<unsigned>(IdxAPS.getZExtValue() & (N - 1));
20667 return Success(Vec.getVectorElt(Idx), E);
20668 }
20669 }
20670}
20671
20672bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
20673 if (E->getSubExpr()->getType()->isAnyComplexType()) {
20674 ComplexValue CV;
20675 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
20676 return false;
20677 Result = CV.FloatReal;
20678 return true;
20679 }
20680
20681 return Visit(E->getSubExpr());
20682}
20683
20684bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
20685 if (E->getSubExpr()->getType()->isAnyComplexType()) {
20686 ComplexValue CV;
20687 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
20688 return false;
20689 Result = CV.FloatImag;
20690 return true;
20691 }
20692
20693 VisitIgnoredValue(E->getSubExpr());
20694 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
20695 Result = llvm::APFloat::getZero(Sem);
20696 return true;
20697}
20698
20699bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
20700 switch (E->getOpcode()) {
20701 default: return Error(E);
20702 case UO_Plus:
20703 return EvaluateFloat(E->getSubExpr(), Result, Info);
20704 case UO_Minus:
20705 // In C standard, WG14 N2478 F.3 p4
20706 // "the unary - raises no floating point exceptions,
20707 // even if the operand is signalling."
20708 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
20709 return false;
20710 Result.changeSign();
20711 return true;
20712 }
20713}
20714
20715bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
20716 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
20717 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
20718
20719 APFloat RHS(0.0);
20720 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
20721 if (!LHSOK && !Info.noteFailure())
20722 return false;
20723 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
20724 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
20725}
20726
20727bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
20728 Result = E->getValue();
20729 return true;
20730}
20731
20732bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
20733 const Expr* SubExpr = E->getSubExpr();
20734
20735 switch (E->getCastKind()) {
20736 default:
20737 return ExprEvaluatorBaseTy::VisitCastExpr(E);
20738
20739 case CK_HLSLAggregateSplatCast:
20740 llvm_unreachable("invalid cast kind for floating value");
20741
20742 case CK_IntegralToFloating: {
20743 APSInt IntResult;
20744 const FPOptions FPO = E->getFPFeaturesInEffect(
20745 Info.Ctx.getLangOpts());
20746 return EvaluateInteger(SubExpr, IntResult, Info) &&
20747 HandleIntToFloatCast(Info, E, FPO, SubExpr->getType(),
20748 IntResult, E->getType(), Result);
20749 }
20750
20751 case CK_FixedPointToFloating: {
20752 APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
20753 if (!EvaluateFixedPoint(SubExpr, FixResult, Info))
20754 return false;
20755 Result =
20756 FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->getType()));
20757 return true;
20758 }
20759
20760 case CK_FloatingCast: {
20761 if (!Visit(SubExpr))
20762 return false;
20763 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
20764 Result);
20765 }
20766
20767 case CK_FloatingComplexToReal: {
20768 ComplexValue V;
20769 if (!EvaluateComplex(SubExpr, V, Info))
20770 return false;
20771 Result = V.getComplexFloatReal();
20772 return true;
20773 }
20774 case CK_HLSLVectorTruncation: {
20775 APValue Val;
20776 if (!EvaluateVector(SubExpr, Val, Info))
20777 return Error(E);
20778 return Success(Val.getVectorElt(0), E);
20779 }
20780 case CK_HLSLMatrixTruncation: {
20781 APValue Val;
20782 if (!EvaluateMatrix(SubExpr, Val, Info))
20783 return Error(E);
20784 return Success(Val.getMatrixElt(0, 0), E);
20785 }
20786 case CK_HLSLElementwiseCast: {
20787 SmallVector<APValue> SrcVals;
20788 SmallVector<QualType> SrcTypes;
20789
20790 if (!hlslElementwiseCastHelper(Info, SubExpr, E->getType(), SrcVals,
20791 SrcTypes))
20792 return false;
20793 APValue Val;
20794
20795 // cast our single element
20796 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
20797 APValue ResultVal;
20798 if (!handleScalarCast(Info, FPO, E, SrcTypes[0], E->getType(), SrcVals[0],
20799 ResultVal))
20800 return false;
20801 return Success(ResultVal, E);
20802 }
20803 }
20804}
20805
20806//===----------------------------------------------------------------------===//
20807// Complex Evaluation (for float and integer)
20808//===----------------------------------------------------------------------===//
20809
20810namespace {
20811class ComplexExprEvaluator
20812 : public ExprEvaluatorBase<ComplexExprEvaluator> {
20813 ComplexValue &Result;
20814
20815public:
20816 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
20817 : ExprEvaluatorBaseTy(info), Result(Result) {}
20818
20819 bool Success(const APValue &V, const Expr *e) {
20820 Result.setFrom(V);
20821 return true;
20822 }
20823
20824 bool ZeroInitialization(const Expr *E);
20825
20826 //===--------------------------------------------------------------------===//
20827 // Visitor Methods
20828 //===--------------------------------------------------------------------===//
20829
20830 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
20831 bool VisitCastExpr(const CastExpr *E);
20832 bool VisitBinaryOperator(const BinaryOperator *E);
20833 bool VisitUnaryOperator(const UnaryOperator *E);
20834 bool VisitInitListExpr(const InitListExpr *E);
20835 bool VisitCallExpr(const CallExpr *E);
20836};
20837} // end anonymous namespace
20838
20839static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
20840 EvalInfo &Info) {
20841 assert(!E->isValueDependent());
20842 assert(E->isPRValue() && E->getType()->isAnyComplexType());
20843 return ComplexExprEvaluator(Info, Result).Visit(E);
20844}
20845
20846bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
20847 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
20848 if (ElemTy->isRealFloatingType()) {
20849 Result.makeComplexFloat();
20850 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
20851 Result.FloatReal = Zero;
20852 Result.FloatImag = Zero;
20853 } else {
20854 Result.makeComplexInt();
20855 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
20856 Result.IntReal = Zero;
20857 Result.IntImag = Zero;
20858 }
20859 return true;
20860}
20861
20862bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
20863 const Expr* SubExpr = E->getSubExpr();
20864
20865 if (SubExpr->getType()->isRealFloatingType()) {
20866 Result.makeComplexFloat();
20867 APFloat &Imag = Result.FloatImag;
20868 if (!EvaluateFloat(SubExpr, Imag, Info))
20869 return false;
20870
20871 Result.FloatReal = APFloat(Imag.getSemantics());
20872 return true;
20873 } else {
20874 assert(SubExpr->getType()->isIntegerType() &&
20875 "Unexpected imaginary literal.");
20876
20877 Result.makeComplexInt();
20878 APSInt &Imag = Result.IntImag;
20879 if (!EvaluateInteger(SubExpr, Imag, Info))
20880 return false;
20881
20882 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
20883 return true;
20884 }
20885}
20886
20887bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
20888
20889 switch (E->getCastKind()) {
20890 case CK_BitCast:
20891 case CK_BaseToDerived:
20892 case CK_DerivedToBase:
20893 case CK_UncheckedDerivedToBase:
20894 case CK_Dynamic:
20895 case CK_ToUnion:
20896 case CK_ArrayToPointerDecay:
20897 case CK_FunctionToPointerDecay:
20898 case CK_NullToPointer:
20899 case CK_NullToMemberPointer:
20900 case CK_BaseToDerivedMemberPointer:
20901 case CK_DerivedToBaseMemberPointer:
20902 case CK_MemberPointerToBoolean:
20903 case CK_ReinterpretMemberPointer:
20904 case CK_ConstructorConversion:
20905 case CK_IntegralToPointer:
20906 case CK_PointerToIntegral:
20907 case CK_PointerToBoolean:
20908 case CK_ToVoid:
20909 case CK_VectorSplat:
20910 case CK_IntegralCast:
20911 case CK_BooleanToSignedIntegral:
20912 case CK_IntegralToBoolean:
20913 case CK_IntegralToFloating:
20914 case CK_FloatingToIntegral:
20915 case CK_FloatingToBoolean:
20916 case CK_FloatingCast:
20917 case CK_CPointerToObjCPointerCast:
20918 case CK_BlockPointerToObjCPointerCast:
20919 case CK_AnyPointerToBlockPointerCast:
20920 case CK_ObjCObjectLValueCast:
20921 case CK_FloatingComplexToReal:
20922 case CK_FloatingComplexToBoolean:
20923 case CK_IntegralComplexToReal:
20924 case CK_IntegralComplexToBoolean:
20925 case CK_ARCProduceObject:
20926 case CK_ARCConsumeObject:
20927 case CK_ARCReclaimReturnedObject:
20928 case CK_ARCExtendBlockObject:
20929 case CK_CopyAndAutoreleaseBlockObject:
20930 case CK_BuiltinFnToFnPtr:
20931 case CK_ZeroToOCLOpaqueType:
20932 case CK_NonAtomicToAtomic:
20933 case CK_AddressSpaceConversion:
20934 case CK_IntToOCLSampler:
20935 case CK_FloatingToFixedPoint:
20936 case CK_FixedPointToFloating:
20937 case CK_FixedPointCast:
20938 case CK_FixedPointToBoolean:
20939 case CK_FixedPointToIntegral:
20940 case CK_IntegralToFixedPoint:
20941 case CK_MatrixCast:
20942 case CK_HLSLVectorTruncation:
20943 case CK_HLSLMatrixTruncation:
20944 case CK_HLSLElementwiseCast:
20945 case CK_HLSLAggregateSplatCast:
20946 llvm_unreachable("invalid cast kind for complex value");
20947
20948 case CK_LValueToRValue:
20949 case CK_AtomicToNonAtomic:
20950 case CK_NoOp:
20951 case CK_LValueToRValueBitCast:
20952 case CK_HLSLArrayRValue:
20953 return ExprEvaluatorBaseTy::VisitCastExpr(E);
20954
20955 case CK_Dependent:
20956 case CK_LValueBitCast:
20957 case CK_UserDefinedConversion:
20958 return Error(E);
20959
20960 case CK_FloatingRealToComplex: {
20961 APFloat &Real = Result.FloatReal;
20962 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
20963 return false;
20964
20965 Result.makeComplexFloat();
20966 Result.FloatImag = APFloat(Real.getSemantics());
20967 return true;
20968 }
20969
20970 case CK_FloatingComplexCast: {
20971 if (!Visit(E->getSubExpr()))
20972 return false;
20973
20974 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
20975 QualType From
20976 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
20977
20978 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
20979 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
20980 }
20981
20982 case CK_FloatingComplexToIntegralComplex: {
20983 if (!Visit(E->getSubExpr()))
20984 return false;
20985
20986 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
20987 QualType From
20988 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
20989 Result.makeComplexInt();
20990 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
20991 To, Result.IntReal) &&
20992 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
20993 To, Result.IntImag);
20994 }
20995
20996 case CK_IntegralRealToComplex: {
20997 APSInt &Real = Result.IntReal;
20998 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
20999 return false;
21000
21001 Result.makeComplexInt();
21002 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
21003 return true;
21004 }
21005
21006 case CK_IntegralComplexCast: {
21007 if (!Visit(E->getSubExpr()))
21008 return false;
21009
21010 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
21011 QualType From
21012 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
21013
21014 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
21015 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
21016 return true;
21017 }
21018
21019 case CK_IntegralComplexToFloatingComplex: {
21020 if (!Visit(E->getSubExpr()))
21021 return false;
21022
21023 const FPOptions FPO = E->getFPFeaturesInEffect(
21024 Info.Ctx.getLangOpts());
21025 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
21026 QualType From
21027 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
21028 Result.makeComplexFloat();
21029 return HandleIntToFloatCast(Info, E, FPO, From, Result.IntReal,
21030 To, Result.FloatReal) &&
21031 HandleIntToFloatCast(Info, E, FPO, From, Result.IntImag,
21032 To, Result.FloatImag);
21033 }
21034 }
21035
21036 llvm_unreachable("unknown cast resulting in complex value");
21037}
21038
21040 // Lookup Table for Multiplicative Inverse in GF(2^8)
21041 const uint8_t GFInv[256] = {
21042 0x00, 0x01, 0x8d, 0xf6, 0xcb, 0x52, 0x7b, 0xd1, 0xe8, 0x4f, 0x29, 0xc0,
21043 0xb0, 0xe1, 0xe5, 0xc7, 0x74, 0xb4, 0xaa, 0x4b, 0x99, 0x2b, 0x60, 0x5f,
21044 0x58, 0x3f, 0xfd, 0xcc, 0xff, 0x40, 0xee, 0xb2, 0x3a, 0x6e, 0x5a, 0xf1,
21045 0x55, 0x4d, 0xa8, 0xc9, 0xc1, 0x0a, 0x98, 0x15, 0x30, 0x44, 0xa2, 0xc2,
21046 0x2c, 0x45, 0x92, 0x6c, 0xf3, 0x39, 0x66, 0x42, 0xf2, 0x35, 0x20, 0x6f,
21047 0x77, 0xbb, 0x59, 0x19, 0x1d, 0xfe, 0x37, 0x67, 0x2d, 0x31, 0xf5, 0x69,
21048 0xa7, 0x64, 0xab, 0x13, 0x54, 0x25, 0xe9, 0x09, 0xed, 0x5c, 0x05, 0xca,
21049 0x4c, 0x24, 0x87, 0xbf, 0x18, 0x3e, 0x22, 0xf0, 0x51, 0xec, 0x61, 0x17,
21050 0x16, 0x5e, 0xaf, 0xd3, 0x49, 0xa6, 0x36, 0x43, 0xf4, 0x47, 0x91, 0xdf,
21051 0x33, 0x93, 0x21, 0x3b, 0x79, 0xb7, 0x97, 0x85, 0x10, 0xb5, 0xba, 0x3c,
21052 0xb6, 0x70, 0xd0, 0x06, 0xa1, 0xfa, 0x81, 0x82, 0x83, 0x7e, 0x7f, 0x80,
21053 0x96, 0x73, 0xbe, 0x56, 0x9b, 0x9e, 0x95, 0xd9, 0xf7, 0x02, 0xb9, 0xa4,
21054 0xde, 0x6a, 0x32, 0x6d, 0xd8, 0x8a, 0x84, 0x72, 0x2a, 0x14, 0x9f, 0x88,
21055 0xf9, 0xdc, 0x89, 0x9a, 0xfb, 0x7c, 0x2e, 0xc3, 0x8f, 0xb8, 0x65, 0x48,
21056 0x26, 0xc8, 0x12, 0x4a, 0xce, 0xe7, 0xd2, 0x62, 0x0c, 0xe0, 0x1f, 0xef,
21057 0x11, 0x75, 0x78, 0x71, 0xa5, 0x8e, 0x76, 0x3d, 0xbd, 0xbc, 0x86, 0x57,
21058 0x0b, 0x28, 0x2f, 0xa3, 0xda, 0xd4, 0xe4, 0x0f, 0xa9, 0x27, 0x53, 0x04,
21059 0x1b, 0xfc, 0xac, 0xe6, 0x7a, 0x07, 0xae, 0x63, 0xc5, 0xdb, 0xe2, 0xea,
21060 0x94, 0x8b, 0xc4, 0xd5, 0x9d, 0xf8, 0x90, 0x6b, 0xb1, 0x0d, 0xd6, 0xeb,
21061 0xc6, 0x0e, 0xcf, 0xad, 0x08, 0x4e, 0xd7, 0xe3, 0x5d, 0x50, 0x1e, 0xb3,
21062 0x5b, 0x23, 0x38, 0x34, 0x68, 0x46, 0x03, 0x8c, 0xdd, 0x9c, 0x7d, 0xa0,
21063 0xcd, 0x1a, 0x41, 0x1c};
21064
21065 return GFInv[Byte];
21066}
21067
21068uint8_t GFNIAffine(uint8_t XByte, const APInt &AQword, const APSInt &Imm,
21069 bool Inverse) {
21070 unsigned NumBitsInByte = 8;
21071 // Computing the affine transformation
21072 uint8_t RetByte = 0;
21073 for (uint32_t BitIdx = 0; BitIdx != NumBitsInByte; ++BitIdx) {
21074 uint8_t AByte =
21075 AQword.lshr((7 - static_cast<int32_t>(BitIdx)) * NumBitsInByte)
21076 .getLoBits(8)
21077 .getZExtValue();
21078 uint8_t Product;
21079 if (Inverse) {
21080 Product = AByte & GFNIMultiplicativeInverse(XByte);
21081 } else {
21082 Product = AByte & XByte;
21083 }
21084 uint8_t Parity = 0;
21085
21086 // Dot product in GF(2) uses XOR instead of addition
21087 for (unsigned PBitIdx = 0; PBitIdx != NumBitsInByte; ++PBitIdx) {
21088 Parity = Parity ^ ((Product >> PBitIdx) & 0x1);
21089 }
21090
21091 uint8_t Temp = Imm[BitIdx] ? 1 : 0;
21092 RetByte |= (Temp ^ Parity) << BitIdx;
21093 }
21094 return RetByte;
21095}
21096
21098 // Multiplying two polynomials of degree 7
21099 // Polynomial of degree 7
21100 // x^7 + x^6 + x^5 + x^4 + x^3 + x^2 + x + 1
21101 uint16_t TWord = 0;
21102 unsigned NumBitsInByte = 8;
21103 for (unsigned BitIdx = 0; BitIdx != NumBitsInByte; ++BitIdx) {
21104 if ((BByte >> BitIdx) & 0x1) {
21105 TWord = TWord ^ (AByte << BitIdx);
21106 }
21107 }
21108
21109 // When multiplying two polynomials of degree 7
21110 // results in a polynomial of degree 14
21111 // so the result has to be reduced to 7
21112 // Reduction polynomial is x^8 + x^4 + x^3 + x + 1 i.e. 0x11B
21113 for (int32_t BitIdx = 14; BitIdx > 7; --BitIdx) {
21114 if ((TWord >> BitIdx) & 0x1) {
21115 TWord = TWord ^ (0x11B << (BitIdx - 8));
21116 }
21117 }
21118 return (TWord & 0xFF);
21119}
21120
21121void HandleComplexComplexMul(APFloat A, APFloat B, APFloat C, APFloat D,
21122 APFloat &ResR, APFloat &ResI) {
21123 // This is an implementation of complex multiplication according to the
21124 // constraints laid out in C11 Annex G. The implementation uses the
21125 // following naming scheme:
21126 // (a + ib) * (c + id)
21127
21128 APFloat AC = A * C;
21129 APFloat BD = B * D;
21130 APFloat AD = A * D;
21131 APFloat BC = B * C;
21132 ResR = AC - BD;
21133 ResI = AD + BC;
21134 if (ResR.isNaN() && ResI.isNaN()) {
21135 bool Recalc = false;
21136 if (A.isInfinity() || B.isInfinity()) {
21137 A = APFloat::copySign(APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0),
21138 A);
21139 B = APFloat::copySign(APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0),
21140 B);
21141 if (C.isNaN())
21142 C = APFloat::copySign(APFloat(C.getSemantics()), C);
21143 if (D.isNaN())
21144 D = APFloat::copySign(APFloat(D.getSemantics()), D);
21145 Recalc = true;
21146 }
21147 if (C.isInfinity() || D.isInfinity()) {
21148 C = APFloat::copySign(APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0),
21149 C);
21150 D = APFloat::copySign(APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0),
21151 D);
21152 if (A.isNaN())
21153 A = APFloat::copySign(APFloat(A.getSemantics()), A);
21154 if (B.isNaN())
21155 B = APFloat::copySign(APFloat(B.getSemantics()), B);
21156 Recalc = true;
21157 }
21158 if (!Recalc && (AC.isInfinity() || BD.isInfinity() || AD.isInfinity() ||
21159 BC.isInfinity())) {
21160 if (A.isNaN())
21161 A = APFloat::copySign(APFloat(A.getSemantics()), A);
21162 if (B.isNaN())
21163 B = APFloat::copySign(APFloat(B.getSemantics()), B);
21164 if (C.isNaN())
21165 C = APFloat::copySign(APFloat(C.getSemantics()), C);
21166 if (D.isNaN())
21167 D = APFloat::copySign(APFloat(D.getSemantics()), D);
21168 Recalc = true;
21169 }
21170 if (Recalc) {
21171 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
21172 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
21173 }
21174 }
21175}
21176
21177void HandleComplexComplexDiv(APFloat A, APFloat B, APFloat C, APFloat D,
21178 APFloat &ResR, APFloat &ResI) {
21179 // This is an implementation of complex division according to the
21180 // constraints laid out in C11 Annex G. The implementation uses the
21181 // following naming scheme:
21182 // (a + ib) / (c + id)
21183
21184 int DenomLogB = 0;
21185 APFloat MaxCD = maxnum(abs(C), abs(D));
21186 if (MaxCD.isFinite()) {
21187 DenomLogB = ilogb(MaxCD);
21188 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
21189 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
21190 }
21191 APFloat Denom = C * C + D * D;
21192 ResR =
21193 scalbn((A * C + B * D) / Denom, -DenomLogB, APFloat::rmNearestTiesToEven);
21194 ResI =
21195 scalbn((B * C - A * D) / Denom, -DenomLogB, APFloat::rmNearestTiesToEven);
21196 if (ResR.isNaN() && ResI.isNaN()) {
21197 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
21198 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
21199 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
21200 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
21201 D.isFinite()) {
21202 A = APFloat::copySign(APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0),
21203 A);
21204 B = APFloat::copySign(APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0),
21205 B);
21206 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
21207 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
21208 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
21209 C = APFloat::copySign(APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0),
21210 C);
21211 D = APFloat::copySign(APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0),
21212 D);
21213 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
21214 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
21215 }
21216 }
21217}
21218
21220 // Normalize shift amount to [0, BitWidth) range to match runtime behavior
21221 APSInt NormAmt = Amount;
21222 unsigned BitWidth = Value.getBitWidth();
21223 unsigned AmtBitWidth = NormAmt.getBitWidth();
21224 if (BitWidth == 1) {
21225 // Rotating a 1-bit value is always a no-op
21226 NormAmt = APSInt(APInt(AmtBitWidth, 0), NormAmt.isUnsigned());
21227 } else if (BitWidth == 2) {
21228 // For 2-bit values: rotation amount is 0 or 1 based on
21229 // whether the amount is even or odd. We can't use srem here because
21230 // the divisor (2) would be misinterpreted as -2 in 2-bit signed arithmetic.
21231 NormAmt =
21232 APSInt(APInt(AmtBitWidth, NormAmt[0] ? 1 : 0), NormAmt.isUnsigned());
21233 } else {
21234 APInt Divisor;
21235 if (AmtBitWidth > BitWidth) {
21236 Divisor = llvm::APInt(AmtBitWidth, BitWidth);
21237 } else {
21238 Divisor = llvm::APInt(BitWidth, BitWidth);
21239 if (AmtBitWidth < BitWidth) {
21240 NormAmt = NormAmt.extend(BitWidth);
21241 }
21242 }
21243
21244 // Normalize to [0, BitWidth)
21245 if (NormAmt.isSigned()) {
21246 NormAmt = APSInt(NormAmt.srem(Divisor), /*isUnsigned=*/false);
21247 if (NormAmt.isNegative()) {
21248 APSInt SignedDivisor(Divisor, /*isUnsigned=*/false);
21249 NormAmt += SignedDivisor;
21250 }
21251 } else {
21252 NormAmt = APSInt(NormAmt.urem(Divisor), /*isUnsigned=*/true);
21253 }
21254 }
21255
21256 return NormAmt;
21257}
21258
21259bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
21260 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
21261 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
21262
21263 // Track whether the LHS or RHS is real at the type system level. When this is
21264 // the case we can simplify our evaluation strategy.
21265 bool LHSReal = false, RHSReal = false;
21266
21267 bool LHSOK;
21268 if (E->getLHS()->getType()->isRealFloatingType()) {
21269 LHSReal = true;
21270 APFloat &Real = Result.FloatReal;
21271 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
21272 if (LHSOK) {
21273 Result.makeComplexFloat();
21274 Result.FloatImag = APFloat(Real.getSemantics());
21275 }
21276 } else {
21277 LHSOK = Visit(E->getLHS());
21278 }
21279 if (!LHSOK && !Info.noteFailure())
21280 return false;
21281
21282 ComplexValue RHS;
21283 if (E->getRHS()->getType()->isRealFloatingType()) {
21284 RHSReal = true;
21285 APFloat &Real = RHS.FloatReal;
21286 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
21287 return false;
21288 RHS.makeComplexFloat();
21289 RHS.FloatImag = APFloat(Real.getSemantics());
21290 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
21291 return false;
21292
21293 assert(!(LHSReal && RHSReal) &&
21294 "Cannot have both operands of a complex operation be real.");
21295 switch (E->getOpcode()) {
21296 default: return Error(E);
21297 case BO_Add:
21298 if (Result.isComplexFloat()) {
21299 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
21300 APFloat::rmNearestTiesToEven);
21301 if (LHSReal)
21302 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
21303 else if (!RHSReal)
21304 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
21305 APFloat::rmNearestTiesToEven);
21306 } else {
21307 Result.getComplexIntReal() += RHS.getComplexIntReal();
21308 Result.getComplexIntImag() += RHS.getComplexIntImag();
21309 }
21310 break;
21311 case BO_Sub:
21312 if (Result.isComplexFloat()) {
21313 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
21314 APFloat::rmNearestTiesToEven);
21315 if (LHSReal) {
21316 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
21317 Result.getComplexFloatImag().changeSign();
21318 } else if (!RHSReal) {
21319 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
21320 APFloat::rmNearestTiesToEven);
21321 }
21322 } else {
21323 Result.getComplexIntReal() -= RHS.getComplexIntReal();
21324 Result.getComplexIntImag() -= RHS.getComplexIntImag();
21325 }
21326 break;
21327 case BO_Mul:
21328 if (Result.isComplexFloat()) {
21329 // This is an implementation of complex multiplication according to the
21330 // constraints laid out in C11 Annex G. The implementation uses the
21331 // following naming scheme:
21332 // (a + ib) * (c + id)
21333 ComplexValue LHS = Result;
21334 APFloat &A = LHS.getComplexFloatReal();
21335 APFloat &B = LHS.getComplexFloatImag();
21336 APFloat &C = RHS.getComplexFloatReal();
21337 APFloat &D = RHS.getComplexFloatImag();
21338 APFloat &ResR = Result.getComplexFloatReal();
21339 APFloat &ResI = Result.getComplexFloatImag();
21340 if (LHSReal) {
21341 assert(!RHSReal && "Cannot have two real operands for a complex op!");
21342 ResR = A;
21343 ResI = A;
21344 // ResR = A * C;
21345 // ResI = A * D;
21346 if (!handleFloatFloatBinOp(Info, E, ResR, BO_Mul, C) ||
21347 !handleFloatFloatBinOp(Info, E, ResI, BO_Mul, D))
21348 return false;
21349 } else if (RHSReal) {
21350 // ResR = C * A;
21351 // ResI = C * B;
21352 ResR = C;
21353 ResI = C;
21354 if (!handleFloatFloatBinOp(Info, E, ResR, BO_Mul, A) ||
21355 !handleFloatFloatBinOp(Info, E, ResI, BO_Mul, B))
21356 return false;
21357 } else {
21358 HandleComplexComplexMul(A, B, C, D, ResR, ResI);
21359 }
21360 } else {
21361 ComplexValue LHS = Result;
21362 Result.getComplexIntReal() =
21363 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
21364 LHS.getComplexIntImag() * RHS.getComplexIntImag());
21365 Result.getComplexIntImag() =
21366 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
21367 LHS.getComplexIntImag() * RHS.getComplexIntReal());
21368 }
21369 break;
21370 case BO_Div:
21371 if (Result.isComplexFloat()) {
21372 // This is an implementation of complex division according to the
21373 // constraints laid out in C11 Annex G. The implementation uses the
21374 // following naming scheme:
21375 // (a + ib) / (c + id)
21376 ComplexValue LHS = Result;
21377 APFloat &A = LHS.getComplexFloatReal();
21378 APFloat &B = LHS.getComplexFloatImag();
21379 APFloat &C = RHS.getComplexFloatReal();
21380 APFloat &D = RHS.getComplexFloatImag();
21381 APFloat &ResR = Result.getComplexFloatReal();
21382 APFloat &ResI = Result.getComplexFloatImag();
21383 if (RHSReal) {
21384 ResR = A;
21385 ResI = B;
21386 // ResR = A / C;
21387 // ResI = B / C;
21388 if (!handleFloatFloatBinOp(Info, E, ResR, BO_Div, C) ||
21389 !handleFloatFloatBinOp(Info, E, ResI, BO_Div, C))
21390 return false;
21391 } else {
21392 if (LHSReal) {
21393 // No real optimizations we can do here, stub out with zero.
21394 B = APFloat::getZero(A.getSemantics());
21395 }
21396 HandleComplexComplexDiv(A, B, C, D, ResR, ResI);
21397 }
21398 } else {
21399 ComplexValue LHS = Result;
21400 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
21401 RHS.getComplexIntImag() * RHS.getComplexIntImag();
21402 if (Den.isZero())
21403 return Error(E, diag::note_expr_divide_by_zero);
21404
21405 Result.getComplexIntReal() =
21406 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
21407 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
21408 Result.getComplexIntImag() =
21409 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
21410 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
21411 }
21412 break;
21413 }
21414
21415 return true;
21416}
21417
21418bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
21419 // Get the operand value into 'Result'.
21420 if (!Visit(E->getSubExpr()))
21421 return false;
21422
21423 switch (E->getOpcode()) {
21424 default:
21425 return Error(E);
21426 case UO_Extension:
21427 return true;
21428 case UO_Plus:
21429 // The result is always just the subexpr.
21430 return true;
21431 case UO_Minus:
21432 if (Result.isComplexFloat()) {
21433 Result.getComplexFloatReal().changeSign();
21434 Result.getComplexFloatImag().changeSign();
21435 }
21436 else {
21437 Result.getComplexIntReal() = -Result.getComplexIntReal();
21438 Result.getComplexIntImag() = -Result.getComplexIntImag();
21439 }
21440 return true;
21441 case UO_Not:
21442 if (Result.isComplexFloat())
21443 Result.getComplexFloatImag().changeSign();
21444 else
21445 Result.getComplexIntImag() = -Result.getComplexIntImag();
21446 return true;
21447 }
21448}
21449
21450bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
21451 if (E->getNumInits() == 2) {
21452 if (E->getType()->isComplexType()) {
21453 Result.makeComplexFloat();
21454 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
21455 return false;
21456 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
21457 return false;
21458 } else {
21459 Result.makeComplexInt();
21460 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
21461 return false;
21462 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
21463 return false;
21464 }
21465 return true;
21466 }
21467 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
21468}
21469
21470bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) {
21471 if (!IsConstantEvaluatedBuiltinCall(E))
21472 return ExprEvaluatorBaseTy::VisitCallExpr(E);
21473
21474 switch (E->getBuiltinCallee()) {
21475 case Builtin::BI__builtin_complex:
21476 Result.makeComplexFloat();
21477 if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info))
21478 return false;
21479 if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info))
21480 return false;
21481 return true;
21482
21483 default:
21484 return false;
21485 }
21486}
21487
21488//===----------------------------------------------------------------------===//
21489// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
21490// implicit conversion.
21491//===----------------------------------------------------------------------===//
21492
21493namespace {
21494class AtomicExprEvaluator :
21495 public ExprEvaluatorBase<AtomicExprEvaluator> {
21496 const LValue *This;
21497 APValue &Result;
21498public:
21499 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
21500 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
21501
21502 bool Success(const APValue &V, const Expr *E) {
21503 Result = V;
21504 return true;
21505 }
21506
21507 bool ZeroInitialization(const Expr *E) {
21508 ImplicitValueInitExpr VIE(
21509 E->getType()->castAs<AtomicType>()->getValueType());
21510 // For atomic-qualified class (and array) types in C++, initialize the
21511 // _Atomic-wrapped subobject directly, in-place.
21512 return This ? EvaluateInPlace(Result, Info, *This, &VIE)
21513 : Evaluate(Result, Info, &VIE);
21514 }
21515
21516 bool VisitCastExpr(const CastExpr *E) {
21517 switch (E->getCastKind()) {
21518 default:
21519 return ExprEvaluatorBaseTy::VisitCastExpr(E);
21520 case CK_NullToPointer:
21521 VisitIgnoredValue(E->getSubExpr());
21522 return ZeroInitialization(E);
21523 case CK_NonAtomicToAtomic:
21524 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
21525 : Evaluate(Result, Info, E->getSubExpr());
21526 }
21527 }
21528};
21529} // end anonymous namespace
21530
21531static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
21532 EvalInfo &Info) {
21533 assert(!E->isValueDependent());
21534 assert(E->isPRValue() && E->getType()->isAtomicType());
21535 return AtomicExprEvaluator(Info, This, Result).Visit(E);
21536}
21537
21538//===----------------------------------------------------------------------===//
21539// Void expression evaluation, primarily for a cast to void on the LHS of a
21540// comma operator
21541//===----------------------------------------------------------------------===//
21542
21543namespace {
21544class VoidExprEvaluator
21545 : public ExprEvaluatorBase<VoidExprEvaluator> {
21546public:
21547 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
21548
21549 bool Success(const APValue &V, const Expr *e) { return true; }
21550
21551 bool ZeroInitialization(const Expr *E) { return true; }
21552
21553 bool VisitCastExpr(const CastExpr *E) {
21554 switch (E->getCastKind()) {
21555 default:
21556 return ExprEvaluatorBaseTy::VisitCastExpr(E);
21557 case CK_ToVoid:
21558 VisitIgnoredValue(E->getSubExpr());
21559 return true;
21560 }
21561 }
21562
21563 bool VisitCallExpr(const CallExpr *E) {
21564 if (!IsConstantEvaluatedBuiltinCall(E))
21565 return ExprEvaluatorBaseTy::VisitCallExpr(E);
21566
21567 switch (E->getBuiltinCallee()) {
21568 case Builtin::BI__assume:
21569 case Builtin::BI__builtin_assume:
21570 // The argument is not evaluated!
21571 return true;
21572
21573 case Builtin::BI__builtin_operator_delete:
21574 return HandleOperatorDeleteCall(Info, E);
21575
21576 default:
21577 return false;
21578 }
21579 }
21580
21581 bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
21582};
21583} // end anonymous namespace
21584
21585bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
21586 // We cannot speculatively evaluate a delete expression.
21587 if (Info.SpeculativeEvaluationDepth)
21588 return false;
21589
21590 FunctionDecl *OperatorDelete = E->getOperatorDelete();
21591 if (!OperatorDelete
21592 ->isUsableAsGlobalAllocationFunctionInConstantEvaluation()) {
21593 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
21594 << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;
21595 return false;
21596 }
21597
21598 const Expr *Arg = E->getArgument();
21599
21600 LValue Pointer;
21601 if (!EvaluatePointer(Arg, Pointer, Info))
21602 return false;
21603 if (Pointer.Designator.Invalid)
21604 return false;
21605
21606 // Deleting a null pointer has no effect.
21607 if (Pointer.isNullPointer()) {
21608 // This is the only case where we need to produce an extension warning:
21609 // the only other way we can succeed is if we find a dynamic allocation,
21610 // and we will have warned when we allocated it in that case.
21611 if (!Info.getLangOpts().CPlusPlus20)
21612 Info.CCEDiag(E, diag::note_constexpr_new);
21613 return true;
21614 }
21615
21616 std::optional<DynAlloc *> Alloc = CheckDeleteKind(
21617 Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New);
21618 if (!Alloc)
21619 return false;
21620 QualType AllocType = Pointer.Base.getDynamicAllocType();
21621
21622 // For the non-array case, the designator must be empty if the static type
21623 // does not have a virtual destructor.
21624 if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 &&
21626 Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor)
21627 << Arg->getType()->getPointeeType() << AllocType;
21628 return false;
21629 }
21630
21631 // For a class type with a virtual destructor, the selected operator delete
21632 // is the one looked up when building the destructor.
21633 if (!E->isArrayForm() && !E->isGlobalDelete()) {
21634 const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType);
21635 if (VirtualDelete &&
21636 !VirtualDelete
21637 ->isUsableAsGlobalAllocationFunctionInConstantEvaluation()) {
21638 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
21639 << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete;
21640 return false;
21641 }
21642 }
21643
21644 if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(),
21645 (*Alloc)->Value, AllocType))
21646 return false;
21647
21648 if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) {
21649 // The element was already erased. This means the destructor call also
21650 // deleted the object.
21651 // FIXME: This probably results in undefined behavior before we get this
21652 // far, and should be diagnosed elsewhere first.
21653 Info.FFDiag(E, diag::note_constexpr_double_delete);
21654 return false;
21655 }
21656
21657 return true;
21658}
21659
21660static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
21661 assert(!E->isValueDependent());
21662 assert(E->isPRValue() && E->getType()->isVoidType());
21663 return VoidExprEvaluator(Info).Visit(E);
21664}
21665
21666//===----------------------------------------------------------------------===//
21667// Top level Expr::EvaluateAsRValue method.
21668//===----------------------------------------------------------------------===//
21669
21670static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
21671 assert(!E->isValueDependent());
21672 // In C, function designators are not lvalues, but we evaluate them as if they
21673 // are.
21674 QualType T = E->getType();
21675 if (E->isGLValue() || T->isFunctionType()) {
21676 LValue LV;
21677 if (!EvaluateLValue(E, LV, Info))
21678 return false;
21679 LV.moveInto(Result);
21680 } else if (T->isVectorType()) {
21681 if (!EvaluateVector(E, Result, Info))
21682 return false;
21683 } else if (T->isConstantMatrixType()) {
21684 if (!EvaluateMatrix(E, Result, Info))
21685 return false;
21686 } else if (T->isIntegralOrEnumerationType()) {
21687 if (!IntExprEvaluator(Info, Result).Visit(E))
21688 return false;
21689 } else if (T->hasPointerRepresentation()) {
21690 LValue LV;
21691 if (!EvaluatePointer(E, LV, Info))
21692 return false;
21693 LV.moveInto(Result);
21694 } else if (T->isRealFloatingType()) {
21695 llvm::APFloat F(0.0);
21696 if (!EvaluateFloat(E, F, Info))
21697 return false;
21698 Result = APValue(F);
21699 } else if (T->isAnyComplexType()) {
21700 ComplexValue C;
21701 if (!EvaluateComplex(E, C, Info))
21702 return false;
21703 C.moveInto(Result);
21704 } else if (T->isFixedPointType()) {
21705 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
21706 } else if (T->isMemberPointerType()) {
21707 MemberPtr P;
21708 if (!EvaluateMemberPointer(E, P, Info))
21709 return false;
21710 P.moveInto(Result);
21711 return true;
21712 } else if (T->isArrayType()) {
21713 LValue LV;
21714 APValue &Value =
21715 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
21716 if (!EvaluateArray(E, LV, Value, Info))
21717 return false;
21718 Result = Value;
21719 } else if (T->isRecordType()) {
21720 LValue LV;
21721 APValue &Value =
21722 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
21723 if (!EvaluateRecord(E, LV, Value, Info))
21724 return false;
21725 Result = Value;
21726 } else if (T->isVoidType()) {
21727 if (!Info.getLangOpts().CPlusPlus11)
21728 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
21729 << E->getType();
21730 if (!EvaluateVoid(E, Info))
21731 return false;
21732 } else if (T->isAtomicType()) {
21733 QualType Unqual = T.getAtomicUnqualifiedType();
21734 if (Unqual->isArrayType() || Unqual->isRecordType()) {
21735 LValue LV;
21736 APValue &Value = Info.CurrentCall->createTemporary(
21737 E, Unqual, ScopeKind::FullExpression, LV);
21738 if (!EvaluateAtomic(E, &LV, Value, Info))
21739 return false;
21740 Result = Value;
21741 } else {
21742 if (!EvaluateAtomic(E, nullptr, Result, Info))
21743 return false;
21744 }
21745 } else if (Info.getLangOpts().CPlusPlus11) {
21746 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
21747 return false;
21748 } else {
21749 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
21750 return false;
21751 }
21752
21753 return true;
21754}
21755
21756/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
21757/// cases, the in-place evaluation is essential, since later initializers for
21758/// an object can indirectly refer to subobjects which were initialized earlier.
21759static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
21760 const Expr *E, bool AllowNonLiteralTypes) {
21761 assert(!E->isValueDependent());
21762
21763 // Normally expressions passed to EvaluateInPlace have a type, but not when
21764 // a VarDecl initializer is evaluated before the untyped ParenListExpr is
21765 // replaced with a CXXConstructExpr. This can happen in LLDB.
21766 if (E->getType().isNull())
21767 return false;
21768
21769 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
21770 return false;
21771
21772 if (E->isPRValue()) {
21773 // Evaluate arrays and record types in-place, so that later initializers can
21774 // refer to earlier-initialized members of the object.
21775 QualType T = E->getType();
21776 if (T->isArrayType())
21777 return EvaluateArray(E, This, Result, Info);
21778 else if (T->isRecordType())
21779 return EvaluateRecord(E, This, Result, Info);
21780 else if (T->isAtomicType()) {
21781 QualType Unqual = T.getAtomicUnqualifiedType();
21782 if (Unqual->isArrayType() || Unqual->isRecordType())
21783 return EvaluateAtomic(E, &This, Result, Info);
21784 }
21785 }
21786
21787 // For any other type, in-place evaluation is unimportant.
21788 return Evaluate(Result, Info, E);
21789}
21790
21791/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
21792/// lvalue-to-rvalue cast if it is an lvalue.
21793static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
21794 assert(!E->isValueDependent());
21795
21796 if (E->getType().isNull())
21797 return false;
21798
21799 if (!CheckLiteralType(Info, E))
21800 return false;
21801
21802 if (Info.EnableNewConstInterp) {
21803 if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result))
21804 return false;
21805 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
21806 ConstantExprKind::Normal);
21807 }
21808
21809 if (!::Evaluate(Result, Info, E))
21810 return false;
21811
21812 // Implicit lvalue-to-rvalue cast.
21813 if (E->isGLValue()) {
21814 LValue LV;
21815 LV.setFrom(Info.Ctx, Result);
21816 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
21817 return false;
21818 }
21819
21820 // Check this core constant expression is a constant expression.
21821 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
21822 ConstantExprKind::Normal) &&
21823 CheckMemoryLeaks(Info);
21824}
21825
21826static bool FastEvaluateAsRValue(const Expr *Exp, APValue &Result,
21827 const ASTContext &Ctx, bool &IsConst) {
21828 // Fast-path evaluations of integer literals, since we sometimes see files
21829 // containing vast quantities of these.
21830 if (const auto *L = dyn_cast<IntegerLiteral>(Exp)) {
21831 Result =
21832 APValue(APSInt(L->getValue(), L->getType()->isUnsignedIntegerType()));
21833 IsConst = true;
21834 return true;
21835 }
21836
21837 if (const auto *L = dyn_cast<CXXBoolLiteralExpr>(Exp)) {
21838 Result = APValue(APSInt(APInt(1, L->getValue())));
21839 IsConst = true;
21840 return true;
21841 }
21842
21843 if (const auto *FL = dyn_cast<FloatingLiteral>(Exp)) {
21844 Result = APValue(FL->getValue());
21845 IsConst = true;
21846 return true;
21847 }
21848
21849 if (const auto *L = dyn_cast<CharacterLiteral>(Exp)) {
21850 Result = APValue(Ctx.MakeIntValue(L->getValue(), L->getType()));
21851 IsConst = true;
21852 return true;
21853 }
21854
21855 if (const auto *CE = dyn_cast<ConstantExpr>(Exp)) {
21856 if (CE->hasAPValueResult()) {
21857 APValue APV = CE->getAPValueResult();
21858 if (!APV.isLValue()) {
21859 Result = std::move(APV);
21860 IsConst = true;
21861 return true;
21862 }
21863 }
21864
21865 // The SubExpr is usually just an IntegerLiteral.
21866 return FastEvaluateAsRValue(CE->getSubExpr(), Result, Ctx, IsConst);
21867 }
21868
21869 // This case should be rare, but we need to check it before we check on
21870 // the type below.
21871 if (Exp->getType().isNull()) {
21872 IsConst = false;
21873 return true;
21874 }
21875
21876 return false;
21877}
21878
21881 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
21882 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
21883}
21884
21886 const ASTContext &Ctx, EvalInfo &Info) {
21887 assert(!E->isValueDependent());
21888 bool IsConst;
21889 if (FastEvaluateAsRValue(E, Result.Val, Ctx, IsConst))
21890 return IsConst;
21891
21892 return EvaluateAsRValue(Info, E, Result.Val);
21893}
21894
21896 const ASTContext &Ctx,
21897 Expr::SideEffectsKind AllowSideEffects,
21898 EvalInfo &Info) {
21899 assert(!E->isValueDependent());
21901 return false;
21902
21903 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
21904 !ExprResult.Val.isInt() ||
21905 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
21906 return false;
21907
21908 return true;
21909}
21910
21912 const ASTContext &Ctx,
21913 Expr::SideEffectsKind AllowSideEffects,
21914 EvalInfo &Info) {
21915 assert(!E->isValueDependent());
21916 if (!E->getType()->isFixedPointType())
21917 return false;
21918
21919 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
21920 return false;
21921
21922 if (!ExprResult.Val.isFixedPoint() ||
21923 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
21924 return false;
21925
21926 return true;
21927}
21928
21929/// EvaluateAsRValue - Return true if this is a constant which we can fold using
21930/// any crazy technique (that has nothing to do with language standards) that
21931/// we want to. If this function returns true, it returns the folded constant
21932/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
21933/// will be applied to the result.
21935 bool InConstantContext) const {
21936 assert(!isValueDependent() &&
21937 "Expression evaluator can't be called on a dependent expression.");
21938 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsRValue");
21939 EvalInfo Info(Ctx, Result, EvaluationMode::IgnoreSideEffects);
21940 Info.InConstantContext = InConstantContext;
21941 return ::EvaluateAsRValue(this, Result, Ctx, Info);
21942}
21943
21945 bool InConstantContext) const {
21946 assert(!isValueDependent() &&
21947 "Expression evaluator can't be called on a dependent expression.");
21948 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsBooleanCondition");
21949 EvalResult Scratch;
21950 return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
21951 HandleConversionToBool(Scratch.Val, Result);
21952}
21953
21955 SideEffectsKind AllowSideEffects,
21956 bool InConstantContext) const {
21957 assert(!isValueDependent() &&
21958 "Expression evaluator can't be called on a dependent expression.");
21959 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsInt");
21960 EvalInfo Info(Ctx, Result, EvaluationMode::IgnoreSideEffects);
21961 Info.InConstantContext = InConstantContext;
21962 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
21963}
21964
21966 SideEffectsKind AllowSideEffects,
21967 bool InConstantContext) const {
21968 assert(!isValueDependent() &&
21969 "Expression evaluator can't be called on a dependent expression.");
21970 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFixedPoint");
21971 EvalInfo Info(Ctx, Result, EvaluationMode::IgnoreSideEffects);
21972 Info.InConstantContext = InConstantContext;
21973 return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
21974}
21975
21976bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
21977 SideEffectsKind AllowSideEffects,
21978 bool InConstantContext) const {
21979 assert(!isValueDependent() &&
21980 "Expression evaluator can't be called on a dependent expression.");
21981
21982 if (!getType()->isRealFloatingType())
21983 return false;
21984
21985 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFloat");
21987 if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
21988 !ExprResult.Val.isFloat() ||
21989 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
21990 return false;
21991
21992 Result = ExprResult.Val.getFloat();
21993 return true;
21994}
21995
21997 bool InConstantContext) const {
21998 assert(!isValueDependent() &&
21999 "Expression evaluator can't be called on a dependent expression.");
22000
22001 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsLValue");
22002 EvalInfo Info(Ctx, Result, EvaluationMode::ConstantFold);
22003 Info.InConstantContext = InConstantContext;
22004 LValue LV;
22005 CheckedTemporaries CheckedTemps;
22006
22007 if (Info.EnableNewConstInterp) {
22008 if (!Info.Ctx.getInterpContext().evaluate(Info, this, Result.Val,
22009 ConstantExprKind::Normal))
22010 return false;
22011
22012 LV.setFrom(Ctx, Result.Val);
22014 Info, getExprLoc(), Ctx.getLValueReferenceType(getType()), LV,
22015 ConstantExprKind::Normal, CheckedTemps);
22016 }
22017
22018 if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() ||
22019 Result.HasSideEffects ||
22022 ConstantExprKind::Normal, CheckedTemps))
22023 return false;
22024
22025 LV.moveInto(Result.Val);
22026 return true;
22027}
22028
22030 APValue DestroyedValue, QualType Type,
22031 SourceLocation Loc, Expr::EvalStatus &EStatus,
22032 bool IsConstantDestruction) {
22033 EvalInfo Info(Ctx, EStatus,
22034 IsConstantDestruction ? EvaluationMode::ConstantExpression
22036 Info.setEvaluatingDecl(Base, DestroyedValue,
22037 EvalInfo::EvaluatingDeclKind::Dtor);
22038 Info.InConstantContext = IsConstantDestruction;
22039
22040 LValue LVal;
22041 LVal.set(Base);
22042
22043 if (!HandleDestruction(Info, Loc, Base, DestroyedValue, Type) ||
22044 EStatus.HasSideEffects)
22045 return false;
22046
22047 if (!Info.discardCleanups())
22048 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
22049
22050 return true;
22051}
22052
22054 ConstantExprKind Kind) const {
22055 assert(!isValueDependent() &&
22056 "Expression evaluator can't be called on a dependent expression.");
22057 bool IsConst;
22058 if (FastEvaluateAsRValue(this, Result.Val, Ctx, IsConst) &&
22059 Result.Val.hasValue())
22060 return true;
22061
22062 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsConstantExpr");
22064 EvalInfo Info(Ctx, Result, EM);
22065 Info.InConstantContext = true;
22066
22067 if (Info.EnableNewConstInterp) {
22068 if (!Info.Ctx.getInterpContext().evaluate(Info, this, Result.Val, Kind))
22069 return false;
22070 return CheckConstantExpression(Info, getExprLoc(),
22071 getStorageType(Ctx, this), Result.Val, Kind);
22072 }
22073
22074 // The type of the object we're initializing is 'const T' for a class NTTP.
22075 QualType T = getType();
22076 if (Kind == ConstantExprKind::ClassTemplateArgument)
22077 T.addConst();
22078
22079 // If we're evaluating a prvalue, fake up a MaterializeTemporaryExpr to
22080 // represent the result of the evaluation. CheckConstantExpression ensures
22081 // this doesn't escape.
22082 MaterializeTemporaryExpr BaseMTE(T, const_cast<Expr*>(this), true);
22083 APValue::LValueBase Base(&BaseMTE);
22084 Info.setEvaluatingDecl(Base, Result.Val);
22085
22086 LValue LVal;
22087 LVal.set(Base);
22088 // C++23 [intro.execution]/p5
22089 // A full-expression is [...] a constant-expression
22090 // So we need to make sure temporary objects are destroyed after having
22091 // evaluating the expression (per C++23 [class.temporary]/p4).
22092 FullExpressionRAII Scope(Info);
22093 if (!::EvaluateInPlace(Result.Val, Info, LVal, this) ||
22094 Result.HasSideEffects || !Scope.destroy())
22095 return false;
22096
22097 if (!Info.discardCleanups())
22098 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
22099
22100 if (!CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this),
22101 Result.Val, Kind))
22102 return false;
22103 if (!CheckMemoryLeaks(Info))
22104 return false;
22105
22106 // If this is a class template argument, it's required to have constant
22107 // destruction too.
22108 if (Kind == ConstantExprKind::ClassTemplateArgument &&
22110 true) ||
22111 Result.HasSideEffects)) {
22112 // FIXME: Prefix a note to indicate that the problem is lack of constant
22113 // destruction.
22114 return false;
22115 }
22116 return true;
22117}
22118
22120 Expr::EvalResult &EStatus,
22121 bool IsConstantInitialization) const {
22122 assert(!isValueDependent() &&
22123 "Expression evaluator can't be called on a dependent expression.");
22124 assert(VD && "Need a valid VarDecl");
22125
22126 llvm::TimeTraceScope TimeScope("EvaluateAsInitializer", [&] {
22127 std::string Name;
22128 llvm::raw_string_ostream OS(Name);
22129 VD->printQualifiedName(OS);
22130 return Name;
22131 });
22132
22133 EvalInfo Info(Ctx, EStatus,
22134 (IsConstantInitialization &&
22135 (Ctx.getLangOpts().CPlusPlus || Ctx.getLangOpts().C23))
22138 Info.setEvaluatingDecl(VD, EStatus.Val);
22139 Info.InConstantContext = IsConstantInitialization;
22140
22141 SourceLocation DeclLoc = VD->getLocation();
22142 QualType DeclTy = VD->getType();
22143
22144 if (Info.EnableNewConstInterp) {
22145 auto &InterpCtx = Ctx.getInterpContext();
22146 if (!InterpCtx.evaluateAsInitializer(Info, VD, this, EStatus.Val))
22147 return false;
22148
22149 return CheckConstantExpression(Info, DeclLoc, DeclTy, EStatus.Val,
22150 ConstantExprKind::Normal);
22151 } else {
22152 LValue LVal;
22153 LVal.set(VD);
22154
22155 {
22156 // C++23 [intro.execution]/p5
22157 // A full-expression is ... an init-declarator ([dcl.decl]) or a
22158 // mem-initializer.
22159 // So we need to make sure temporary objects are destroyed after having
22160 // evaluated the expression (per C++23 [class.temporary]/p4).
22161 //
22162 // FIXME: Otherwise this may break test/Modules/pr68702.cpp because the
22163 // serialization code calls ParmVarDecl::getDefaultArg() which strips the
22164 // outermost FullExpr, such as ExprWithCleanups.
22165 FullExpressionRAII Scope(Info);
22166 if (!EvaluateInPlace(EStatus.Val, Info, LVal, this,
22167 /*AllowNonLiteralTypes=*/true) ||
22168 EStatus.HasSideEffects)
22169 return false;
22170 }
22171
22172 // At this point, any lifetime-extended temporaries are completely
22173 // initialized.
22174 Info.performLifetimeExtension();
22175
22176 if (!Info.discardCleanups())
22177 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
22178 }
22179
22180 return CheckConstantExpression(Info, DeclLoc, DeclTy, EStatus.Val,
22181 ConstantExprKind::Normal) &&
22182 CheckMemoryLeaks(Info);
22183}
22184
22187 // This function is only meaningful for records and arrays of records.
22188 QualType VarTy = getType();
22189 if (VarTy->isArrayType()) {
22190 QualType ElemTy = getASTContext().getBaseElementType(VarTy);
22191 if (!ElemTy->isRecordType()) {
22192 ensureEvaluatedStmt()->HasConstantDestruction = true;
22193 return true;
22194 }
22195 } else if (!VarTy->isRecordType()) {
22196 ensureEvaluatedStmt()->HasConstantDestruction = true;
22197 return true;
22198 }
22199
22200 Expr::EvalStatus EStatus;
22201 EStatus.Diag = &Notes;
22202
22203 // Only treat the destruction as constant destruction if we formally have
22204 // constant initialization (or are usable in a constant expression).
22205 bool IsConstantDestruction = hasConstantInitialization();
22206 ASTContext &Ctx = getASTContext();
22207
22208 // Make a copy of the value for the destructor to mutate, if we know it.
22209 // Otherwise, treat the value as default-initialized; if the destructor works
22210 // anyway, then the destruction is constant (and must be essentially empty).
22211 APValue DestroyedValue;
22212 if (getEvaluatedValue())
22213 DestroyedValue = *getEvaluatedValue();
22214 else if (!handleDefaultInitValue(VarTy, DestroyedValue))
22215 return false;
22216
22217 if (Ctx.getLangOpts().EnableNewConstInterp) {
22218 EvalInfo Info(Ctx, EStatus,
22219 IsConstantDestruction ? EvaluationMode::ConstantExpression
22221 Info.InConstantContext = IsConstantDestruction;
22222 if (!Ctx.getInterpContext().evaluateDestruction(Info, this,
22223 std::move(DestroyedValue)))
22224 return false;
22225 ensureEvaluatedStmt()->HasConstantDestruction = true;
22226 return true;
22227 }
22228
22229 if (!EvaluateDestruction(Ctx, this, std::move(DestroyedValue), VarTy,
22230 getLocation(), EStatus, IsConstantDestruction) ||
22231 EStatus.HasSideEffects)
22232 return false;
22233
22234 ensureEvaluatedStmt()->HasConstantDestruction = true;
22235 return true;
22236}
22237
22238/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
22239/// constant folded, but discard the result.
22241 assert(!isValueDependent() &&
22242 "Expression evaluator can't be called on a dependent expression.");
22243
22245 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
22247}
22248
22249APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
22250 assert(!isValueDependent() &&
22251 "Expression evaluator can't be called on a dependent expression.");
22252
22253 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstInt");
22254 EvalResult EVResult;
22255 EvalInfo Info(Ctx, EVResult, EvaluationMode::IgnoreSideEffects);
22256 Info.InConstantContext = true;
22257
22258 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
22259 (void)Result;
22260 assert(Result && "Could not evaluate expression");
22261 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
22262
22263 return EVResult.Val.getInt();
22264}
22265
22268 assert(!isValueDependent() &&
22269 "Expression evaluator can't be called on a dependent expression.");
22270
22271 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstIntCheckOverflow");
22272 EvalResult EVResult;
22273 EVResult.Diag = Diag;
22274 EvalInfo Info(Ctx, EVResult, EvaluationMode::IgnoreSideEffects);
22275 Info.InConstantContext = true;
22276 Info.CheckingForUndefinedBehavior = true;
22277
22278 bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
22279 (void)Result;
22280 assert(Result && "Could not evaluate expression");
22281 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
22282
22283 return EVResult.Val.getInt();
22284}
22285
22287 assert(!isValueDependent() &&
22288 "Expression evaluator can't be called on a dependent expression.");
22289
22290 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateForOverflow");
22291 bool IsConst;
22292 EvalResult EVResult;
22293 if (!FastEvaluateAsRValue(this, EVResult.Val, Ctx, IsConst)) {
22294 EvalInfo Info(Ctx, EVResult, EvaluationMode::IgnoreSideEffects);
22295 Info.CheckingForUndefinedBehavior = true;
22296 (void)::EvaluateAsRValue(Info, this, EVResult.Val);
22297 }
22298}
22299
22301 assert(Val.isLValue());
22302 return IsGlobalLValue(Val.getLValueBase());
22303}
22304
22305/// isIntegerConstantExpr - this recursive routine will test if an expression is
22306/// an integer constant expression.
22307
22308/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
22309/// comma, etc
22310
22311// CheckICE - This function does the fundamental ICE checking: the returned
22312// ICEDiag contains an ICEKind indicating whether the expression is an ICE.
22313//
22314// Note that to reduce code duplication, this helper does no evaluation
22315// itself; the caller checks whether the expression is evaluatable, and
22316// in the rare cases where CheckICE actually cares about the evaluated
22317// value, it calls into Evaluate.
22318
22319namespace {
22320
22321enum ICEKind {
22322 /// This expression is an ICE.
22323 IK_ICE,
22324 /// This expression is not an ICE, but if it isn't evaluated, it's
22325 /// a legal subexpression for an ICE. This return value is used to handle
22326 /// the comma operator in C99 mode, and non-constant subexpressions.
22327 IK_ICEIfUnevaluated,
22328 /// This expression is not an ICE, and is not a legal subexpression for one.
22329 IK_NotICE
22330};
22331
22332struct ICEDiag {
22333 ICEKind Kind;
22334 SourceLocation Loc;
22335
22336 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
22337};
22338
22339}
22340
22341static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
22342
22343static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
22344
22345static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
22346 Expr::EvalResult EVResult;
22347 Expr::EvalStatus Status;
22348 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantExpression);
22349
22350 Info.InConstantContext = true;
22351 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
22352 !EVResult.Val.isInt())
22353 return ICEDiag(IK_NotICE, E->getBeginLoc());
22354
22355 return NoDiag();
22356}
22357
22358static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
22359 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
22361 return ICEDiag(IK_NotICE, E->getBeginLoc());
22362
22363 switch (E->getStmtClass()) {
22364#define ABSTRACT_STMT(Node)
22365#define STMT(Node, Base) case Expr::Node##Class:
22366#define EXPR(Node, Base)
22367#include "clang/AST/StmtNodes.inc"
22368 case Expr::PredefinedExprClass:
22369 case Expr::FloatingLiteralClass:
22370 case Expr::ImaginaryLiteralClass:
22371 case Expr::StringLiteralClass:
22372 case Expr::ArraySubscriptExprClass:
22373 case Expr::MatrixSingleSubscriptExprClass:
22374 case Expr::MatrixSubscriptExprClass:
22375 case Expr::ArraySectionExprClass:
22376 case Expr::OMPArrayShapingExprClass:
22377 case Expr::OMPIteratorExprClass:
22378 case Expr::CompoundAssignOperatorClass:
22379 case Expr::CompoundLiteralExprClass:
22380 case Expr::ExtVectorElementExprClass:
22381 case Expr::MatrixElementExprClass:
22382 case Expr::DesignatedInitExprClass:
22383 case Expr::ArrayInitLoopExprClass:
22384 case Expr::ArrayInitIndexExprClass:
22385 case Expr::NoInitExprClass:
22386 case Expr::DesignatedInitUpdateExprClass:
22387 case Expr::ImplicitValueInitExprClass:
22388 case Expr::ParenListExprClass:
22389 case Expr::VAArgExprClass:
22390 case Expr::AddrLabelExprClass:
22391 case Expr::StmtExprClass:
22392 case Expr::CXXMemberCallExprClass:
22393 case Expr::CUDAKernelCallExprClass:
22394 case Expr::CXXAddrspaceCastExprClass:
22395 case Expr::CXXDynamicCastExprClass:
22396 case Expr::CXXTypeidExprClass:
22397 case Expr::CXXUuidofExprClass:
22398 case Expr::MSPropertyRefExprClass:
22399 case Expr::MSPropertySubscriptExprClass:
22400 case Expr::CXXNullPtrLiteralExprClass:
22401 case Expr::UserDefinedLiteralClass:
22402 case Expr::CXXThisExprClass:
22403 case Expr::CXXThrowExprClass:
22404 case Expr::CXXNewExprClass:
22405 case Expr::CXXDeleteExprClass:
22406 case Expr::CXXPseudoDestructorExprClass:
22407 case Expr::UnresolvedLookupExprClass:
22408 case Expr::RecoveryExprClass:
22409 case Expr::DependentScopeDeclRefExprClass:
22410 case Expr::DependentTemplateIdExprClass:
22411 case Expr::CXXConstructExprClass:
22412 case Expr::CXXInheritedCtorInitExprClass:
22413 case Expr::CXXStdInitializerListExprClass:
22414 case Expr::CXXBindTemporaryExprClass:
22415 case Expr::ExprWithCleanupsClass:
22416 case Expr::CXXTemporaryObjectExprClass:
22417 case Expr::CXXUnresolvedConstructExprClass:
22418 case Expr::CXXDependentScopeMemberExprClass:
22419 case Expr::UnresolvedMemberExprClass:
22420 case Expr::ObjCStringLiteralClass:
22421 case Expr::ObjCBoxedExprClass:
22422 case Expr::ObjCArrayLiteralClass:
22423 case Expr::ObjCDictionaryLiteralClass:
22424 case Expr::ObjCEncodeExprClass:
22425 case Expr::ObjCMessageExprClass:
22426 case Expr::ObjCSelectorExprClass:
22427 case Expr::ObjCProtocolExprClass:
22428 case Expr::ObjCIvarRefExprClass:
22429 case Expr::ObjCPropertyRefExprClass:
22430 case Expr::ObjCSubscriptRefExprClass:
22431 case Expr::ObjCIsaExprClass:
22432 case Expr::ObjCAvailabilityCheckExprClass:
22433 case Expr::ShuffleVectorExprClass:
22434 case Expr::ConvertVectorExprClass:
22435 case Expr::BlockExprClass:
22436 case Expr::NoStmtClass:
22437 case Expr::OpaqueValueExprClass:
22438 case Expr::PackExpansionExprClass:
22439 case Expr::SubstNonTypeTemplateParmPackExprClass:
22440 case Expr::FunctionParmPackExprClass:
22441 case Expr::AsTypeExprClass:
22442 case Expr::ObjCIndirectCopyRestoreExprClass:
22443 case Expr::MaterializeTemporaryExprClass:
22444 case Expr::PseudoObjectExprClass:
22445 case Expr::AtomicExprClass:
22446 case Expr::LambdaExprClass:
22447 case Expr::CXXFoldExprClass:
22448 case Expr::CoawaitExprClass:
22449 case Expr::DependentCoawaitExprClass:
22450 case Expr::CoyieldExprClass:
22451 case Expr::SYCLUniqueStableNameExprClass:
22452 case Expr::CXXParenListInitExprClass:
22453 case Expr::HLSLOutArgExprClass:
22454 case Expr::CXXExpansionSelectExprClass:
22455 return ICEDiag(IK_NotICE, E->getBeginLoc());
22456
22457 case Expr::MemberExprClass: {
22458 if (Ctx.getLangOpts().C23) {
22459 const Expr *ME = E->IgnoreParenImpCasts();
22460 while (const auto *M = dyn_cast<MemberExpr>(ME)) {
22461 if (M->isArrow())
22462 return ICEDiag(IK_NotICE, E->getBeginLoc());
22463 ME = M->getBase()->IgnoreParenImpCasts();
22464 }
22465 const auto *DRE = dyn_cast<DeclRefExpr>(ME);
22466 if (DRE) {
22467 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
22468 VD && VD->isConstexpr())
22469 return CheckEvalInICE(E, Ctx);
22470 }
22471 }
22472 return ICEDiag(IK_NotICE, E->getBeginLoc());
22473 }
22474
22475 case Expr::InitListExprClass: {
22476 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
22477 // form "T x = { a };" is equivalent to "T x = a;".
22478 // Unless we're initializing a reference, T is a scalar as it is known to be
22479 // of integral or enumeration type.
22480 if (E->isPRValue())
22481 if (cast<InitListExpr>(E)->getNumInits() == 1)
22482 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
22483 return ICEDiag(IK_NotICE, E->getBeginLoc());
22484 }
22485
22486 case Expr::SizeOfPackExprClass:
22487 case Expr::GNUNullExprClass:
22488 case Expr::SourceLocExprClass:
22489 case Expr::EmbedExprClass:
22490 case Expr::OpenACCAsteriskSizeExprClass:
22491 return NoDiag();
22492
22493 case Expr::PackIndexingExprClass:
22494 return CheckICE(cast<PackIndexingExpr>(E)->getSelectedExpr(), Ctx);
22495
22496 case Expr::SubstNonTypeTemplateParmExprClass:
22497 return
22498 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
22499
22500 case Expr::ConstantExprClass:
22501 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
22502
22503 case Expr::ParenExprClass:
22504 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
22505 case Expr::GenericSelectionExprClass:
22506 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
22507 case Expr::IntegerLiteralClass:
22508 case Expr::FixedPointLiteralClass:
22509 case Expr::CharacterLiteralClass:
22510 case Expr::ObjCBoolLiteralExprClass:
22511 case Expr::CXXBoolLiteralExprClass:
22512 case Expr::CXXScalarValueInitExprClass:
22513 case Expr::TypeTraitExprClass:
22514 case Expr::ConceptSpecializationExprClass:
22515 case Expr::RequiresExprClass:
22516 case Expr::ArrayTypeTraitExprClass:
22517 case Expr::ExpressionTraitExprClass:
22518 case Expr::CXXNoexceptExprClass:
22519 case Expr::CXXReflectExprClass:
22520 return NoDiag();
22521 case Expr::CallExprClass:
22522 case Expr::CXXOperatorCallExprClass: {
22523 // C99 6.6/3 allows function calls within unevaluated subexpressions of
22524 // constant expressions, but they can never be ICEs because an ICE cannot
22525 // contain an operand of (pointer to) function type.
22526 const CallExpr *CE = cast<CallExpr>(E);
22527 if (CE->getBuiltinCallee())
22528 return CheckEvalInICE(E, Ctx);
22529 return ICEDiag(IK_NotICE, E->getBeginLoc());
22530 }
22531 case Expr::CXXRewrittenBinaryOperatorClass:
22532 return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(),
22533 Ctx);
22534 case Expr::DeclRefExprClass: {
22535 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
22536 if (isa<EnumConstantDecl>(D))
22537 return NoDiag();
22538
22539 // C++ and OpenCL (FIXME: spec reference?) allow reading const-qualified
22540 // integer variables in constant expressions:
22541 //
22542 // C++ 7.1.5.1p2
22543 // A variable of non-volatile const-qualified integral or enumeration
22544 // type initialized by an ICE can be used in ICEs.
22545 //
22546 // We sometimes use CheckICE to check the C++98 rules in C++11 mode. In
22547 // that mode, use of reference variables should not be allowed.
22548 const VarDecl *VD = dyn_cast<VarDecl>(D);
22549 if (VD && VD->isUsableInConstantExpressions(Ctx) &&
22550 !VD->getType()->isReferenceType())
22551 return NoDiag();
22552
22553 return ICEDiag(IK_NotICE, E->getBeginLoc());
22554 }
22555 case Expr::UnaryOperatorClass: {
22556 const UnaryOperator *Exp = cast<UnaryOperator>(E);
22557 switch (Exp->getOpcode()) {
22558 case UO_PostInc:
22559 case UO_PostDec:
22560 case UO_PreInc:
22561 case UO_PreDec:
22562 case UO_AddrOf:
22563 case UO_Deref:
22564 case UO_Coawait:
22565 // C99 6.6/3 allows increment and decrement within unevaluated
22566 // subexpressions of constant expressions, but they can never be ICEs
22567 // because an ICE cannot contain an lvalue operand.
22568 return ICEDiag(IK_NotICE, E->getBeginLoc());
22569 case UO_Extension:
22570 case UO_LNot:
22571 case UO_Plus:
22572 case UO_Minus:
22573 case UO_Not:
22574 case UO_Real:
22575 case UO_Imag:
22576 return CheckICE(Exp->getSubExpr(), Ctx);
22577 }
22578 llvm_unreachable("invalid unary operator class");
22579 }
22580 case Expr::OffsetOfExprClass: {
22581 // Note that per C99, offsetof must be an ICE. And AFAIK, using
22582 // EvaluateAsRValue matches the proposed gcc behavior for cases like
22583 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
22584 // compliance: we should warn earlier for offsetof expressions with
22585 // array subscripts that aren't ICEs, and if the array subscripts
22586 // are ICEs, the value of the offsetof must be an integer constant.
22587 return CheckEvalInICE(E, Ctx);
22588 }
22589 case Expr::UnaryExprOrTypeTraitExprClass: {
22591 if ((Exp->getKind() == UETT_SizeOf) &&
22593 return ICEDiag(IK_NotICE, E->getBeginLoc());
22594 if (Exp->getKind() == UETT_CountOf) {
22595 QualType ArgTy = Exp->getTypeOfArgument();
22596 if (ArgTy->isVariableArrayType()) {
22597 // We need to look whether the array is multidimensional. If it is,
22598 // then we want to check the size expression manually to see whether
22599 // it is an ICE or not.
22600 const auto *VAT = Ctx.getAsVariableArrayType(ArgTy);
22601 if (VAT->getElementType()->isArrayType())
22602 // Variable array size expression could be missing (e.g. int a[*][10])
22603 // In that case, it can't be a constant expression.
22604 return VAT->getSizeExpr() ? CheckICE(VAT->getSizeExpr(), Ctx)
22605 : ICEDiag(IK_NotICE, E->getBeginLoc());
22606
22607 // Otherwise, this is a regular VLA, which is definitely not an ICE.
22608 return ICEDiag(IK_NotICE, E->getBeginLoc());
22609 }
22610 }
22611 return NoDiag();
22612 }
22613 case Expr::BinaryOperatorClass: {
22614 const BinaryOperator *Exp = cast<BinaryOperator>(E);
22615 switch (Exp->getOpcode()) {
22616 case BO_PtrMemD:
22617 case BO_PtrMemI:
22618 case BO_Assign:
22619 case BO_MulAssign:
22620 case BO_DivAssign:
22621 case BO_RemAssign:
22622 case BO_AddAssign:
22623 case BO_SubAssign:
22624 case BO_ShlAssign:
22625 case BO_ShrAssign:
22626 case BO_AndAssign:
22627 case BO_XorAssign:
22628 case BO_OrAssign:
22629 // C99 6.6/3 allows assignments within unevaluated subexpressions of
22630 // constant expressions, but they can never be ICEs because an ICE cannot
22631 // contain an lvalue operand.
22632 return ICEDiag(IK_NotICE, E->getBeginLoc());
22633
22634 case BO_Mul:
22635 case BO_Div:
22636 case BO_Rem:
22637 case BO_Add:
22638 case BO_Sub:
22639 case BO_Shl:
22640 case BO_Shr:
22641 case BO_LT:
22642 case BO_GT:
22643 case BO_LE:
22644 case BO_GE:
22645 case BO_EQ:
22646 case BO_NE:
22647 case BO_And:
22648 case BO_Xor:
22649 case BO_Or:
22650 case BO_Comma:
22651 case BO_Cmp: {
22652 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
22653 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
22654 if (Exp->getOpcode() == BO_Div ||
22655 Exp->getOpcode() == BO_Rem) {
22656 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
22657 // we don't evaluate one.
22658 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
22659 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
22660 if (REval == 0)
22661 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
22662 if (REval.isSigned() && REval.isAllOnes()) {
22663 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
22664 if (LEval.isMinSignedValue())
22665 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
22666 }
22667 }
22668 }
22669 if (Exp->getOpcode() == BO_Comma) {
22670 if (Ctx.getLangOpts().C99) {
22671 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
22672 // if it isn't evaluated.
22673 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
22674 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
22675 } else {
22676 // In both C89 and C++, commas in ICEs are illegal.
22677 return ICEDiag(IK_NotICE, E->getBeginLoc());
22678 }
22679 }
22680 return Worst(LHSResult, RHSResult);
22681 }
22682 case BO_LAnd:
22683 case BO_LOr: {
22684 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
22685 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
22686 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
22687 // Rare case where the RHS has a comma "side-effect"; we need
22688 // to actually check the condition to see whether the side
22689 // with the comma is evaluated.
22690 if ((Exp->getOpcode() == BO_LAnd) !=
22691 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
22692 return RHSResult;
22693 return NoDiag();
22694 }
22695
22696 return Worst(LHSResult, RHSResult);
22697 }
22698 }
22699 llvm_unreachable("invalid binary operator kind");
22700 }
22701 case Expr::ImplicitCastExprClass:
22702 case Expr::CStyleCastExprClass:
22703 case Expr::CXXFunctionalCastExprClass:
22704 case Expr::CXXStaticCastExprClass:
22705 case Expr::CXXReinterpretCastExprClass:
22706 case Expr::CXXConstCastExprClass:
22707 case Expr::ObjCBridgedCastExprClass: {
22708 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
22709 if (isa<ExplicitCastExpr>(E)) {
22710 if (const FloatingLiteral *FL
22711 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
22712 unsigned DestWidth = Ctx.getIntWidth(E->getType());
22713 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
22714 APSInt IgnoredVal(DestWidth, !DestSigned);
22715 bool Ignored;
22716 // If the value does not fit in the destination type, the behavior is
22717 // undefined, so we are not required to treat it as a constant
22718 // expression.
22719 if (FL->getValue().convertToInteger(IgnoredVal,
22720 llvm::APFloat::rmTowardZero,
22721 &Ignored) & APFloat::opInvalidOp)
22722 return ICEDiag(IK_NotICE, E->getBeginLoc());
22723 return NoDiag();
22724 }
22725 }
22726 switch (cast<CastExpr>(E)->getCastKind()) {
22727 case CK_LValueToRValue:
22728 case CK_AtomicToNonAtomic:
22729 case CK_NonAtomicToAtomic:
22730 case CK_NoOp:
22731 case CK_IntegralToBoolean:
22732 case CK_IntegralCast:
22733 return CheckICE(SubExpr, Ctx);
22734 default:
22735 return ICEDiag(IK_NotICE, E->getBeginLoc());
22736 }
22737 }
22738 case Expr::BinaryConditionalOperatorClass: {
22740 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
22741 if (CommonResult.Kind == IK_NotICE) return CommonResult;
22742 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
22743 if (FalseResult.Kind == IK_NotICE) return FalseResult;
22744 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
22745 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
22746 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
22747 return FalseResult;
22748 }
22749 case Expr::ConditionalOperatorClass: {
22751 // If the condition (ignoring parens) is a __builtin_constant_p call,
22752 // then only the true side is actually considered in an integer constant
22753 // expression, and it is fully evaluated. This is an important GNU
22754 // extension. See GCC PR38377 for discussion.
22755 if (const CallExpr *CallCE
22756 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
22757 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
22758 return CheckEvalInICE(E, Ctx);
22759 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
22760 if (CondResult.Kind == IK_NotICE)
22761 return CondResult;
22762
22763 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
22764 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
22765
22766 if (TrueResult.Kind == IK_NotICE)
22767 return TrueResult;
22768 if (FalseResult.Kind == IK_NotICE)
22769 return FalseResult;
22770 if (CondResult.Kind == IK_ICEIfUnevaluated)
22771 return CondResult;
22772 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
22773 return NoDiag();
22774 // Rare case where the diagnostics depend on which side is evaluated
22775 // Note that if we get here, CondResult is 0, and at least one of
22776 // TrueResult and FalseResult is non-zero.
22777 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
22778 return FalseResult;
22779 return TrueResult;
22780 }
22781 case Expr::CXXDefaultArgExprClass:
22782 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
22783 case Expr::CXXDefaultInitExprClass:
22784 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
22785 case Expr::ChooseExprClass: {
22786 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
22787 }
22788 case Expr::BuiltinBitCastExprClass: {
22789 if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
22790 return ICEDiag(IK_NotICE, E->getBeginLoc());
22791 return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
22792 }
22793 }
22794
22795 llvm_unreachable("Invalid StmtClass!");
22796}
22797
22798/// Evaluate an expression as a C++11 integral constant expression.
22799static bool
22801 llvm::APSInt *Value,
22802 bool AllowRelaxedEval = false) {
22804 return false;
22805
22807 if (!E->isCXX11ConstantExpr(Ctx, &Result, AllowRelaxedEval))
22808 return false;
22809
22810 if (!Result.isInt())
22811 return false;
22812
22813 if (Value) *Value = Result.getInt();
22814 return true;
22815}
22816
22818 assert(!isValueDependent() &&
22819 "Expression evaluator can't be called on a dependent expression.");
22820
22821 ExprTimeTraceScope TimeScope(this, Ctx, "isIntegerConstantExpr");
22822
22823 if (Ctx.getLangOpts().CPlusPlus11)
22824 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr);
22825
22826 ICEDiag D = CheckICE(this, Ctx);
22827 if (D.Kind != IK_ICE)
22828 return false;
22829 return true;
22830}
22831
22832std::optional<llvm::APSInt>
22834 bool AllowRelaxedEval) const {
22835 if (isValueDependent()) {
22836 // Expression evaluator can't succeed on a dependent expression.
22837 return std::nullopt;
22838 }
22839
22840 if (Ctx.getLangOpts().CPlusPlus11) {
22841 APSInt Value;
22843 AllowRelaxedEval))
22844 return Value;
22845 return std::nullopt;
22846 }
22847
22848 if (!isIntegerConstantExpr(Ctx))
22849 return std::nullopt;
22850
22851 // The only possible side-effects here are due to UB discovered in the
22852 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
22853 // required to treat the expression as an ICE, so we produce the folded
22854 // value.
22856 Expr::EvalStatus Status;
22857 EvalInfo Info(Ctx, Status, EvaluationMode::IgnoreSideEffects);
22858 Info.InConstantContext = true;
22859
22860 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
22861 llvm_unreachable("ICE cannot be evaluated!");
22862
22863 return ExprResult.Val.getInt();
22864}
22865
22867 assert(!isValueDependent() &&
22868 "Expression evaluator can't be called on a dependent expression.");
22869
22870 return CheckICE(this, Ctx).Kind == IK_ICE;
22871}
22872
22874 bool AllowRelaxedEval) const {
22875 assert(!isValueDependent() &&
22876 "Expression evaluator can't be called on a dependent expression.");
22877
22878 // We support this checking in C++98 mode in order to diagnose compatibility
22879 // issues.
22880 assert(Ctx.getLangOpts().CPlusPlus);
22881
22882 bool IsConst;
22883 APValue Scratch;
22884 if (FastEvaluateAsRValue(this, Scratch, Ctx, IsConst) && Scratch.hasValue()) {
22885 if (Result)
22886 *Result = std::move(Scratch);
22887 return true;
22888 }
22889
22890 // Build evaluation settings.
22891 Expr::EvalStatus Status;
22892 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantExpression);
22894 Status.ExtendedDiag = AllowRelaxedEval ? &MSRelaxedDiag : nullptr;
22895
22896 bool IsConstExpr =
22897 ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) &&
22898 // NOTE: We don't produce a diagnostic for this, but the callers that
22899 // call us on arbitrary full-expressions should generally not care.
22900 Info.discardCleanups() && !Status.HasSideEffects;
22901
22902 return IsConstExpr && !Status.DiagEmitted;
22903}
22904
22906 const FunctionDecl *Callee,
22908 const Expr *This) const {
22909 assert(!isValueDependent() &&
22910 "Expression evaluator can't be called on a dependent expression.");
22911
22912 llvm::TimeTraceScope TimeScope("EvaluateWithSubstitution", [&] {
22913 std::string Name;
22914 llvm::raw_string_ostream OS(Name);
22915 Callee->getNameForDiagnostic(OS, Ctx.getPrintingPolicy(),
22916 /*Qualified=*/true);
22917 return Name;
22918 });
22919
22920 Expr::EvalStatus Status;
22921 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantExpressionUnevaluated);
22922 Info.InConstantContext = true;
22923
22924 if (Info.EnableNewConstInterp) {
22925 if (std::optional<bool> BoolResult =
22926 Info.Ctx.getInterpContext().evaluateWithSubstitution(
22927 Info, Callee, Args, This, this)) {
22928 Value = APValue(APSInt(APInt(1, static_cast<uint64_t>(*BoolResult))));
22929 return true;
22930 }
22931 return false;
22932 }
22933
22934 LValue ThisVal;
22935 const LValue *ThisPtr = nullptr;
22936 if (This) {
22937#ifndef NDEBUG
22938 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
22939 assert(MD && "Don't provide `this` for non-methods.");
22940 assert(MD->isImplicitObjectMemberFunction() &&
22941 "Don't provide `this` for methods without an implicit object.");
22942#endif
22943 if (!This->isValueDependent() &&
22944 EvaluateObjectArgument(Info, This, ThisVal) &&
22945 !Info.EvalStatus.HasSideEffects)
22946 ThisPtr = &ThisVal;
22947
22948 // Ignore any side-effects from a failed evaluation. This is safe because
22949 // they can't interfere with any other argument evaluation.
22950 Info.EvalStatus.HasSideEffects = false;
22951 }
22952
22953 CallRef Call = Info.CurrentCall->createCall(Callee);
22954 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
22955 I != E; ++I) {
22956 unsigned Idx = I - Args.begin();
22957 if (Idx >= Callee->getNumParams())
22958 break;
22959 const ParmVarDecl *PVD = Callee->getParamDecl(Idx);
22960 if ((*I)->isValueDependent() ||
22961 !EvaluateCallArg(PVD, *I, Call, Info) ||
22962 Info.EvalStatus.HasSideEffects) {
22963 // If evaluation fails, throw away the argument entirely.
22964 if (APValue *Slot = Info.getParamSlot(Call, PVD))
22965 *Slot = APValue();
22966 }
22967
22968 // Ignore any side-effects from a failed evaluation. This is safe because
22969 // they can't interfere with any other argument evaluation.
22970 Info.EvalStatus.HasSideEffects = false;
22971 }
22972
22973 // Parameter cleanups happen in the caller and are not part of this
22974 // evaluation.
22975 Info.discardCleanups();
22976 Info.EvalStatus.HasSideEffects = false;
22977
22978 // Build fake call to Callee.
22979 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, This,
22980 Call);
22981 // FIXME: Missing ExprWithCleanups in enable_if conditions?
22982 FullExpressionRAII Scope(Info);
22983 return Evaluate(Value, Info, this) && Scope.destroy() &&
22984 !Info.EvalStatus.HasSideEffects;
22985}
22986
22989 PartialDiagnosticAt> &Diags) {
22990 // FIXME: It would be useful to check constexpr function templates, but at the
22991 // moment the constant expression evaluator cannot cope with the non-rigorous
22992 // ASTs which we build for dependent expressions.
22993 if (FD->isDependentContext())
22994 return true;
22995
22996 llvm::TimeTraceScope TimeScope("isPotentialConstantExpr", [&] {
22997 std::string Name;
22998 llvm::raw_string_ostream OS(Name);
23000 /*Qualified=*/true);
23001 return Name;
23002 });
23003
23004 Expr::EvalStatus Status;
23005 Status.Diag = &Diags;
23006
23007 EvalInfo Info(FD->getASTContext(), Status,
23009 Info.InConstantContext = true;
23010 Info.CheckingPotentialConstantExpression = true;
23011
23012 // The constexpr VM attempts to compile all methods to bytecode here.
23013 if (Info.EnableNewConstInterp) {
23014 Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD);
23015 return Diags.empty();
23016 }
23017
23018 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
23019 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
23020
23021 // Fabricate an arbitrary expression on the stack and pretend that it
23022 // is a temporary being used as the 'this' pointer.
23023 LValue This;
23024 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getCanonicalTagType(RD)
23025 : Info.Ctx.IntTy);
23026 This.set({&VIE, Info.CurrentCall->Index});
23027
23029
23030 APValue Scratch;
23031 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
23032 // Evaluate the call as a constant initializer, to allow the construction
23033 // of objects of non-literal types.
23034 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
23035 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
23036 } else {
23037 SourceLocation Loc = FD->getLocation();
23039 Loc, FD, (MD && MD->isImplicitObjectMemberFunction()) ? &This : nullptr,
23040 &VIE, Args, CallRef(), FD->getBody(), Info, Scratch,
23041 /*ResultSlot=*/nullptr);
23042 }
23043
23044 return Diags.empty();
23045}
23046
23048 const FunctionDecl *FD,
23050 PartialDiagnosticAt> &Diags) {
23051 assert(!E->isValueDependent() &&
23052 "Expression evaluator can't be called on a dependent expression.");
23053
23054 Expr::EvalStatus Status;
23055 Status.Diag = &Diags;
23056
23057 EvalInfo Info(FD->getASTContext(), Status,
23059 Info.InConstantContext = true;
23060 Info.CheckingPotentialConstantExpression = true;
23061
23062 if (Info.EnableNewConstInterp) {
23063 Info.Ctx.getInterpContext().isPotentialConstantExprUnevaluated(Info, E, FD);
23064 return Diags.empty();
23065 }
23066
23067 // Fabricate a call stack frame to give the arguments a plausible cover story.
23068 CallStackFrame Frame(Info, SourceLocation(), FD, /*This=*/nullptr,
23069 /*CallExpr=*/nullptr, CallRef());
23070
23071 APValue ResultScratch;
23072 Evaluate(ResultScratch, Info, E);
23073 return Diags.empty();
23074}
23075
23076std::optional<uint64_t> Expr::tryEvaluateObjectSize(const ASTContext &Ctx,
23077 unsigned Type) const {
23078 if (!getType()->isPointerType())
23079 return std::nullopt;
23080
23081 Expr::EvalStatus Status;
23082 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantFold);
23083 if (Info.EnableNewConstInterp)
23084 return Info.Ctx.getInterpContext().tryEvaluateObjectSize(Info, this, Type);
23085 return tryEvaluateBuiltinObjectSize(this, Type, Info);
23086}
23087
23088static std::optional<uint64_t>
23089EvaluateBuiltinStrLen(const Expr *E, EvalInfo &Info,
23090 std::string *StringResult) {
23091 if (!E->getType()->hasPointerRepresentation() || !E->isPRValue())
23092 return std::nullopt;
23093
23094 LValue String;
23095
23096 if (!EvaluatePointer(E, String, Info))
23097 return std::nullopt;
23098
23099 QualType CharTy = E->getType()->getPointeeType();
23100
23101 // Fast path: if it's a string literal, search the string value.
23102 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
23103 String.getLValueBase().dyn_cast<const Expr *>())) {
23104 StringRef Str = S->getBytes();
23105 int64_t Off = String.Offset.getQuantity();
23106 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
23107 S->getCharByteWidth() == 1 &&
23108 // FIXME: Add fast-path for wchar_t too.
23109 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
23110 Str = Str.substr(Off);
23111
23112 StringRef::size_type Pos = Str.find(0);
23113 if (Pos != StringRef::npos)
23114 Str = Str.substr(0, Pos);
23115
23116 if (StringResult)
23117 *StringResult = Str;
23118 return Str.size();
23119 }
23120
23121 // Fall through to slow path.
23122 }
23123
23124 // Slow path: scan the bytes of the string looking for the terminating 0.
23125 for (uint64_t Strlen = 0; /**/; ++Strlen) {
23126 APValue Char;
23127 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
23128 !Char.isInt())
23129 return std::nullopt;
23130 if (!Char.getInt())
23131 return Strlen;
23132 else if (StringResult)
23133 StringResult->push_back(Char.getInt().getExtValue());
23134 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
23135 return std::nullopt;
23136 }
23137}
23138
23139std::optional<std::string> Expr::tryEvaluateString(ASTContext &Ctx) const {
23140 Expr::EvalStatus Status;
23141 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantFold);
23142 std::string StringResult;
23143
23144 if (Info.EnableNewConstInterp) {
23145 if (!Info.Ctx.getInterpContext().evaluateString(Info, this, StringResult))
23146 return std::nullopt;
23147 return StringResult;
23148 }
23149
23150 if (EvaluateBuiltinStrLen(this, Info, &StringResult))
23151 return StringResult;
23152 return std::nullopt;
23153}
23154
23155template <typename T>
23157 const Expr *SizeExpression,
23158 const Expr *PtrExpression,
23159 ASTContext &Ctx,
23160 Expr::EvalResult &Status) {
23161 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantExpression);
23162 Info.InConstantContext = true;
23163
23164 if (Info.EnableNewConstInterp)
23165 return Info.Ctx.getInterpContext().evaluateCharRange(Info, SizeExpression,
23166 PtrExpression, Result);
23167
23168 LValue String;
23169 FullExpressionRAII Scope(Info);
23170 APSInt SizeValue;
23171 if (!::EvaluateInteger(SizeExpression, SizeValue, Info))
23172 return false;
23173
23174 uint64_t Size = SizeValue.getZExtValue();
23175
23176 // FIXME: better protect against invalid or excessive sizes
23177 if constexpr (std::is_same_v<APValue, T>)
23178 Result = APValue(APValue::UninitArray{}, Size, Size);
23179 else {
23180 if (Size < Result.max_size())
23181 Result.reserve(Size);
23182 }
23183 if (!::EvaluatePointer(PtrExpression, String, Info))
23184 return false;
23185
23186 QualType CharTy = PtrExpression->getType()->getPointeeType();
23187 for (uint64_t I = 0; I < Size; ++I) {
23188 APValue Char;
23189 if (!handleLValueToRValueConversion(Info, PtrExpression, CharTy, String,
23190 Char))
23191 return false;
23192
23193 if constexpr (std::is_same_v<APValue, T>) {
23194 Result.getArrayInitializedElt(I) = std::move(Char);
23195 } else {
23196 APSInt C = Char.getInt();
23197
23198 assert(C.getBitWidth() <= 8 &&
23199 "string element not representable in char");
23200
23201 Result.push_back(static_cast<char>(C.getExtValue()));
23202 }
23203
23204 if (!HandleLValueArrayAdjustment(Info, PtrExpression, String, CharTy, 1))
23205 return false;
23206 }
23207
23208 return Scope.destroy() && CheckMemoryLeaks(Info);
23209}
23210
23212 const Expr *SizeExpression,
23213 const Expr *PtrExpression, ASTContext &Ctx,
23214 EvalResult &Status) const {
23215 return EvaluateCharRangeAsStringImpl(this, Result, SizeExpression,
23216 PtrExpression, Ctx, Status);
23217}
23218
23220 const Expr *SizeExpression,
23221 const Expr *PtrExpression, ASTContext &Ctx,
23222 EvalResult &Status) const {
23223 return EvaluateCharRangeAsStringImpl(this, Result, SizeExpression,
23224 PtrExpression, Ctx, Status);
23225}
23226
23227std::optional<uint64_t> Expr::tryEvaluateStrLen(const ASTContext &Ctx) const {
23228 Expr::EvalStatus Status;
23229 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantFold);
23230
23231 if (Info.EnableNewConstInterp)
23232 return Info.Ctx.getInterpContext().evaluateStrlen(Info, this);
23233 return EvaluateBuiltinStrLen(this, Info);
23234}
23235
23236namespace {
23237struct IsWithinLifetimeHandler {
23238 EvalInfo &Info;
23239 static constexpr AccessKinds AccessKind = AccessKinds::AK_IsWithinLifetime;
23240 using result_type = std::optional<bool>;
23241 std::optional<bool> failed() { return std::nullopt; }
23242 template <typename T>
23243 std::optional<bool> found(T &Subobj, QualType SubobjType,
23245 return true;
23246 }
23247 template <typename T>
23248 std::optional<bool> found(T &Subobj, QualType SubobjType) {
23249 return true;
23250 }
23251};
23252
23253std::optional<bool> EvaluateBuiltinIsWithinLifetime(IntExprEvaluator &IEE,
23254 const CallExpr *E) {
23255 EvalInfo &Info = IEE.Info;
23256 // Sometimes this is called during some sorts of constant folding / early
23257 // evaluation. These are meant for non-constant expressions and are not
23258 // necessary since this consteval builtin will never be evaluated at runtime.
23259 // Just fail to evaluate when not in a constant context.
23260 if (!Info.InConstantContext)
23261 return std::nullopt;
23262 assert(E->getBuiltinCallee() == Builtin::BI__builtin_is_within_lifetime);
23263 const Expr *Arg = E->getArg(0);
23264 if (Arg->isValueDependent())
23265 return std::nullopt;
23266 LValue Val;
23267 if (!EvaluatePointer(Arg, Val, Info))
23268 return std::nullopt;
23269
23270 if (Val.allowConstexprUnknown())
23271 return true;
23272
23273 auto Error = [&](int Diag) {
23274 bool CalledFromStd = false;
23275 const auto *Callee = Info.CurrentCall->getCallee();
23276 if (Callee && Callee->isInStdNamespace()) {
23277 const IdentifierInfo *Identifier = Callee->getIdentifier();
23278 CalledFromStd = Identifier && Identifier->isStr("is_within_lifetime");
23279 }
23280 Info.CCEDiag(CalledFromStd ? Info.CurrentCall->getCallRange().getBegin()
23281 : E->getExprLoc(),
23282 diag::err_invalid_is_within_lifetime)
23283 << (CalledFromStd ? "std::is_within_lifetime"
23284 : "__builtin_is_within_lifetime")
23285 << Diag;
23286 return std::nullopt;
23287 };
23288 // C++2c [meta.const.eval]p4:
23289 // During the evaluation of an expression E as a core constant expression, a
23290 // call to this function is ill-formed unless p points to an object that is
23291 // usable in constant expressions or whose complete object's lifetime began
23292 // within E.
23293
23294 // Make sure it points to an object
23295 // nullptr does not point to an object
23296 if (Val.isNullPointer() || Val.getLValueBase().isNull())
23297 return Error(0);
23298 QualType T = Val.getLValueBase().getType();
23299 assert(!T->isFunctionType() &&
23300 "Pointers to functions should have been typed as function pointers "
23301 "which would have been rejected earlier");
23302 assert(T->isObjectType());
23303 // Hypothetical array element is not an object
23304 if (Val.getLValueDesignator().isOnePastTheEnd())
23305 return Error(1);
23306 assert(Val.getLValueDesignator().isValidSubobject() &&
23307 "Unchecked case for valid subobject");
23308 // All other ill-formed values should have failed EvaluatePointer, so the
23309 // object should be a pointer to an object that is usable in a constant
23310 // expression or whose complete lifetime began within the expression
23311 CompleteObject CO =
23312 findCompleteObject(Info, E, AccessKinds::AK_IsWithinLifetime, Val, T);
23313 // The lifetime hasn't begun yet if we are still evaluating the
23314 // initializer ([basic.life]p(1.2))
23315 if (Info.EvaluatingDeclValue && CO.Value == Info.EvaluatingDeclValue)
23316 return Error(2);
23317
23318 if (!CO)
23319 return false;
23320 IsWithinLifetimeHandler handler{Info};
23321 return findSubobject(Info, E, CO, Val.getLValueDesignator(), handler);
23322}
23323} // namespace
Defines the clang::ASTContext interface.
#define V(N, I)
This file provides some common utility functions for processing Lambda related AST Constructs.
static bool isUnsigned(SValBuilder &SVB, NonLoc Value)
Defines enum values for all the target-independent builtin functions.
static Address castToBase(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy, Address OriginalBaseAddress, llvm::Value *Addr)
static uint32_t getBitWidth(const Expr *E)
llvm::APSInt APSInt
Definition Compiler.cpp:25
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 isValidIndeterminateAccess(AccessKinds AK)
Is this kind of access valid on an indeterminate object value?
static unsigned elementwiseSize(EvalInfo &Info, QualType BaseTy)
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 bool CheckEvaluationResult(CheckEvaluationResultKind CERK, EvalInfo &Info, SourceLocation DiagLoc, QualType Type, const APValue &Value, ConstantExprKind Kind, const FieldDecl *SubobjectDecl, CheckedTemporaries &CheckedTemps, bool IsCompleteClass=true)
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 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 hlslElementwiseCastHelper(EvalInfo &Info, const Expr *E, QualType DestTy, SmallVectorImpl< APValue > &SrcVals, SmallVectorImpl< QualType > &SrcTypes)
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 EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info)
std::optional< APFloat > EvalScalarMinMaxFp(const APFloat &A, const APFloat &B, std::optional< APSInt > RoundingMode, bool IsMin)
static bool CheckMemoryLeaks(EvalInfo &Info)
Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless "the allocated storage is dea...
static bool handleScalarCast(EvalInfo &Info, const FPOptions FPO, const Expr *E, QualType SourceTy, QualType DestTy, APValue const &Original, APValue &Result)
static ICEDiag CheckEvalInICE(const Expr *E, const ASTContext &Ctx)
static llvm::APInt ConvertBoolVectorToInt(const APValue &Val)
static bool flattenAPValue(EvalInfo &Info, const Expr *E, APValue Value, QualType BaseTy, SmallVectorImpl< APValue > &Elements, SmallVectorImpl< QualType > &Types, unsigned Size)
static bool hlslAggSplatHelper(EvalInfo &Info, const Expr *E, APValue &SrcVal, QualType &SrcTy)
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.
unsigned ConvertBuiltinIDToX86BuiltinID(const ASTContext &Ctx, unsigned BuiltinOp)
Convert a builtin ID to the canonical x86 builtin ID the constant evaluators dispatch on in their x86...
static bool ConvertDoubleToFloatStrict(EvalInfo &Info, const Expr *E, APFloat OrigVal, APValue &Result)
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 HandleLValueVectorElement(EvalInfo &Info, const Expr *E, LValue &LVal, QualType EltTy, uint64_t Size, uint64_t Idx)
static bool checkFloatingPointResultForConstantFolding(EvalInfo &Info, const Expr *E, APFloat::opStatus St)
Check if the given floating-point evaluation result is allowed for compile-time constant folding duri...
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 handleElementwiseCast(EvalInfo &Info, const Expr *E, const FPOptions FPO, SmallVectorImpl< APValue > &Elements, SmallVectorImpl< QualType > &SrcTypes, SmallVectorImpl< QualType > &DestTypes, SmallVectorImpl< APValue > &Results)
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 bool constructAggregate(EvalInfo &Info, const FPOptions FPO, const Expr *E, APValue &Result, QualType ResultType, SmallVectorImpl< APValue > &Elements, SmallVectorImpl< QualType > &ElTypes)
static void addFlexibleArrayMemberInitSize(EvalInfo &Info, const QualType &T, const LValue &LV, CharUnits &Size)
If we're evaluating the object size of an instance of a struct that contains a flexible array member,...
static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E, QualType Type, LValue &Result)
static bool evalShuffleGeneric(EvalInfo &Info, const CallExpr *Call, APValue &Out, llvm::function_ref< std::pair< unsigned, int >(unsigned, unsigned)> GetSourceIndex)
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 HandleLValueDirectVirtualBase(EvalInfo &Info, const Expr *E, LValue &Obj, const CXXRecordDecl *Derived, const CXXRecordDecl *Base, const ASTRecordLayout *RL=nullptr)
static bool HandleConversionToBool(const APValue &Val, bool &Result)
static void expandVector(APValue &Vec, unsigned NumElements)
CharUnits GetAlignOfExpr(const ASTContext &Ctx, const Expr *E, UnaryExprOrTypeTrait ExprKind)
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 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)
static std::optional< uint64_t > EvaluateBuiltinStrLen(const Expr *E, EvalInfo &Info, std::string *StringResult=nullptr)
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 EvaluateBuiltinConstantPForLValue(const APValue &LV)
EvaluateBuiltinConstantPForLValue - Determine the result of __builtin_constant_p when applied to the ...
static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg)
EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to GCC as we can manage.
static bool checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E, const LValue &This, const CXXMethodDecl *NamedMember)
Check that the pointee of the 'this' pointer in a member function call is either within its lifetime ...
static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type, const APValue &Value, ConstantExprKind Kind)
Check that this core constant expression value is a valid value for a constant expression.
static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result, EvalInfo &Info)
static std::optional< DynamicType > ComputeDynamicType(EvalInfo &Info, const Expr *E, LValue &This, AccessKinds AK)
Determine the dynamic type of an object.
static bool EvaluateDecl(EvalInfo &Info, const Decl *D, bool EvaluateConditionDecl=false)
static void expandArray(APValue &Array, unsigned Index)
static bool handleLogicalOpForVector(const APInt &LHSValue, BinaryOperatorKind Opcode, const APInt &RHSValue, APInt &Result)
static unsigned FindDesignatorMismatch(QualType ObjType, const SubobjectDesignator &A, const SubobjectDesignator &B, bool &WasArrayIndex)
Find the position where two subobject designators diverge, or equivalently the length of the common i...
static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx, const LValue &LV)
Determine whether this is a pointer past the end of the complete object referred to by the lvalue.
static unsigned getBaseIndex(const CXXRecordDecl *Derived, const CXXRecordDecl *Base)
Get the base index of the given base class within an APValue representing the given derived class.
static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result, EvalInfo &Info)
Evaluate only a fixed point expression into an APResult.
void HandleComplexComplexMul(APFloat A, APFloat B, APFloat C, APFloat D, APFloat &ResR, APFloat &ResI)
static bool HandleDestructionImpl(EvalInfo &Info, SourceRange CallRange, const LValue &This, APValue &Value, QualType T, bool IsCompleteClass=true)
static bool EvalPointerValueAsBool(const APValue &Value, bool &Result)
static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E, BinaryOperatorKind Opcode, APValue &LHSValue, const APValue &RHSValue)
static bool EvaluateMatrix(const Expr *E, APValue &Result, EvalInfo &Info)
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 HandleClassZeroInitialization(EvalInfo &Info, const Expr *E, const RecordDecl *RD, const LValue &This, APValue &Result, bool IsCompleteClass=true)
Perform zero-initialization on an object of non-union class type. C++11 [dcl.init]p5: To zero-initial...
static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx, const Expr *E, llvm::APSInt *Value, bool AllowRelaxedEval=false)
Evaluate an expression as a C++11 integral constant expression.
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 HandleConstructorCall(const Expr *E, const LValue &This, CallRef Call, const CXXConstructorDecl *Definition, EvalInfo &Info, APValue &Result, bool IsCompleteClass=true)
Evaluate a constructor call.
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 bool evalShiftWithCount(EvalInfo &Info, const CallExpr *Call, APValue &Out, llvm::function_ref< APInt(const APInt &, uint64_t)> ShiftOp, llvm::function_ref< APInt(const APInt &, unsigned)> OverflowOp)
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 bool handleDefaultInitValue(QualType T, APValue &Result, bool IsCompleteClass=true)
Get the value to use for a default-initialized object of type T.
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 std::optional< uint64_t > tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type, EvalInfo &Info, bool IsDynamic=false)
Tries to evaluate the __builtin_object_size for E.
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...
uint8_t GFNIMul(uint8_t AByte, uint8_t BByte)
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 ArePotentiallyOverlappingStringLiterals(const EvalInfo &Info, const LValue &LHS, const LValue &RHS)
uint8_t GFNIMultiplicativeInverse(uint8_t Byte)
uint8_t GFNIAffine(uint8_t XByte, const APInt &AQword, const APSInt &Imm, bool Inverse)
APSInt NormalizeRotateAmount(const APSInt &Value, const APSInt &Amount)
TokenType getType() const
Returns the token's type, e.g.
FormatToken * Next
The next token in the unwrapped line.
Result
Implement __builtin_bit_cast and related operations.
static bool isModification(AccessKinds AK)
Definition Interp.cpp:147
#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
llvm::json::Object Object
llvm::json::Array Array
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:208
BaseOrMemberType getAsBaseOrMember() const
Definition APValue.h:222
static LValuePathEntry ArrayIndex(uint64_t Index)
Definition APValue.h:216
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:122
bool hasArrayFiller() const
Definition APValue.h:637
const LValueBase getLValueBase() const
Definition APValue.cpp:1018
APValue & getArrayInitializedElt(unsigned I)
Definition APValue.h:629
void swap(APValue &RHS)
Swaps the contents of this and the given APValue.
Definition APValue.cpp:472
APSInt & getInt()
Definition APValue.h:511
APValue & getStructField(unsigned i)
Definition APValue.h:674
unsigned getMatrixNumColumns() const
Definition APValue.h:602
const FieldDecl * getUnionField() const
Definition APValue.h:695
bool isVector() const
Definition APValue.h:494
APSInt & getComplexIntImag()
Definition APValue.h:549
bool isAbsent() const
Definition APValue.h:484
bool isComplexInt() const
Definition APValue.h:491
llvm::PointerIntPair< const Decl *, 1, bool > BaseOrMemberType
A FieldDecl or CXXRecordDecl, along with a flag indicating whether we mean a virtual or non-virtual b...
Definition APValue.h:205
ValueKind getKind() const
Definition APValue.h:482
APValue & getStructVirtualBase(unsigned i)
Definition APValue.h:679
unsigned getArrayInitializedElts() const
Definition APValue.h:648
static APValue IndeterminateValue()
Definition APValue.h:453
bool isFloat() const
Definition APValue.h:489
unsigned getStructNumBases() const
Definition APValue.h:657
APFixedPoint & getFixedPoint()
Definition APValue.h:533
bool hasValue() const
Definition APValue.h:486
bool hasLValuePath() const
Definition APValue.cpp:1033
const ValueDecl * getMemberPointerDecl() const
Definition APValue.cpp:1101
APValue & getUnionValue()
Definition APValue.h:699
CharUnits & getLValueOffset()
Definition APValue.cpp:1028
void printPretty(raw_ostream &OS, const ASTContext &Ctx, QualType Ty) const
Definition APValue.cpp:709
bool isComplexFloat() const
Definition APValue.h:492
APValue & getVectorElt(unsigned I)
Definition APValue.h:585
APValue & getArrayFiller()
Definition APValue.h:640
unsigned getVectorLength() const
Definition APValue.h:593
bool isLValue() const
Definition APValue.h:493
void setUnion(const FieldDecl *Field, const APValue &Value)
Definition APValue.cpp:1094
bool isIndeterminate() const
Definition APValue.h:485
unsigned getMatrixNumRows() const
Definition APValue.h:598
bool isInt() const
Definition APValue.h:488
unsigned getArraySize() const
Definition APValue.h:652
bool allowConstexprUnknown() const
Definition APValue.h:330
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition APValue.cpp:991
bool isFixedPoint() const
Definition APValue.h:490
APValue & getMatrixElt(unsigned Idx)
Definition APValue.h:609
@ 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:497
APSInt & getComplexIntReal()
Definition APValue.h:541
APFloat & getComplexFloatImag()
Definition APValue.h:565
APFloat & getComplexFloatReal()
Definition APValue.h:557
APFloat & getFloat()
Definition APValue.h:525
APValue & getStructBase(unsigned i)
Definition APValue.h:669
bool isMatrix() const
Definition APValue.h:495
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:223
SourceManager & getSourceManager()
Definition ASTContext.h:884
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
unsigned getIntWidth(QualType T) const
const llvm::fltSemantics & getFloatTypeSemantics(QualType T) const
Return the APFloat 'semantics' for the specified scalar floating point type.
uint64_t getTargetNullPointerValue(QualType QT) const
Get target-dependent integer value for null pointer which is used for constant folding.
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D,...
unsigned getPreferredTypeAlign(QualType T) const
Return the "preferred" alignment of the specified type T for the current target, in bits.
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:825
const LangOptions & getLangOpts() const
Definition ASTContext.h:980
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
const TargetInfo * getAuxTargetInfo() const
Definition ASTContext.h:943
interp::Context & getInterpContext() const
Returns the clang bytecode interpreter context.
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:876
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
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:942
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
CanQualType getCanonicalTagType(const TagDecl *TD) const
uint64_t getCharWidth() const
Return the size of the character type, in bits.
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:4584
OpaqueValueExpr * getCommonExpr() const
Get the common subexpression shared by all initializations (the source array).
Definition Expr.h:6000
Expr * getSubExpr() const
Get the initializer to use for each array element.
Definition Expr.h:6005
Expr * getLHS()
An array access can be written A[4] or 4[A] (both are equivalent).
Definition Expr.h:2761
uint64_t getValue() const
Definition ExprCXX.h:3047
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3836
QualType getElementType() const
Definition TypeBase.h:3848
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition TypeBase.h:8306
Attr - This represents one attribute.
Definition Attr.h:46
BinaryConditionalOperator - The GNU extension to the conditional operator which allows the middle ope...
Definition Expr.h:4464
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression which will be evaluated if the condition evaluates to false; ...
Definition Expr.h:4518
OpaqueValueExpr * getOpaqueValue() const
getOpaqueValue - Return the opaque value placeholder.
Definition Expr.h:4502
Expr * getCommon() const
getCommon - Return the common expression, written to the left of the condition.
Definition Expr.h:4499
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:4049
static bool isLogicalOp(Opcode Opc)
Definition Expr.h:4182
Expr * getLHS() const
Definition Expr.h:4099
static bool isRelationalOp(Opcode Opc)
Definition Expr.h:4143
static bool isComparisonOp(Opcode Opc)
Definition Expr.h:4149
static Opcode getOpForCompoundAssignment(Opcode Opc)
Definition Expr.h:4196
SourceLocation getExprLoc() const
Definition Expr.h:4090
Expr * getRHS() const
Definition Expr.h:4101
static bool isAdditiveOp(Opcode Opc)
Definition Expr.h:4135
static bool isPtrMemOp(Opcode Opc)
predicates to categorize the respective opcodes.
Definition Expr.h:4126
static bool isAssignmentOp(Opcode Opc)
Definition Expr.h:4185
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operator.
Definition Expr.h:4262
Opcode getOpcode() const
Definition Expr.h:4094
static bool isEqualityOp(Opcode Opc)
Definition Expr.h:4146
bool hasCaptures() const
True if this block (or its nested blocks) captures anything of local storage from its enclosing scope...
Definition Decl.h:4925
const BlockDecl * getBlockDecl() const
Definition Expr.h:6701
bool isAuxBuiltinID(unsigned ID) const
Return true if the builtin ID belongs exclusively to the AuxTarget, and false if it belongs to both p...
Definition Builtins.h:443
unsigned getAuxBuiltinID(unsigned ID) const
Return real builtin ID (i.e.
Definition Builtins.h:449
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) const
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:1518
bool getValue() const
Definition ExprCXX.h:743
Represents a call to a C++ constructor.
Definition ExprCXX.h:1551
bool isElidable() const
Whether this construction is elidable.
Definition ExprCXX.h:1620
Expr * getArg(unsigned Arg)
Return the specified argument.
Definition ExprCXX.h:1694
bool requiresZeroInitialization() const
Whether this construction first requires zero-initialization before the initializer is called.
Definition ExprCXX.h:1653
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition ExprCXX.h:1614
unsigned getNumArgs() const
Return the number of arguments to the constructor call.
Definition ExprCXX.h:1691
Represents a C++ constructor within a class.
Definition DeclCXX.h:2637
bool isDefaultConstructor() const
Whether this constructor is a default constructor (C++ [class.ctor]p5), which can be used to default-...
Definition DeclCXX.cpp:3049
CXXCtorInitializer *const * init_const_iterator
Iterates through the member/base initializer list.
Definition DeclCXX.h:2720
Expr * getExpr()
Get the initialization expression that will be used.
Definition ExprCXX.cpp:1137
FunctionDecl * getOperatorDelete() const
Definition ExprCXX.h:2668
bool isArrayForm() const
Definition ExprCXX.h:2655
bool isGlobalDelete() const
Definition ExprCXX.h:2654
Represents a C++ destructor within a class.
Definition DeclCXX.h:2902
CXXForRangeStmt - This represents C++0x [stmt.ranged]'s ranged for statement, represented as 'for (ra...
Definition StmtCXX.h:136
DeclStmt * getBeginStmt()
Definition StmtCXX.h:164
DeclStmt * getLoopVarStmt()
Definition StmtCXX.h:170
DeclStmt * getEndStmt()
Definition StmtCXX.h:167
DeclStmt * getRangeStmt()
Definition StmtCXX.h:163
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will call.
Definition ExprCXX.h:1791
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2145
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:2719
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:2726
QualType getFunctionObjectParameterReferenceType() const
Return the type of the object pointed by this.
Definition DeclCXX.cpp:2870
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2288
bool isInstance() const
Definition DeclCXX.h:2172
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition DeclCXX.cpp:2751
bool isStatic() const
Definition DeclCXX.cpp:2417
bool isCopyAssignmentOperator() const
Determine whether this is a copy-assignment operator, regardless of whether it was declared implicitl...
Definition DeclCXX.cpp:2730
bool isLambdaStaticInvoker() const
Determine whether this is a lambda closure type's static member function that is used for the result ...
Definition DeclCXX.cpp:2895
bool isArray() const
Definition ExprCXX.h:2467
QualType getAllocatedType() const
Definition ExprCXX.h:2437
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:2472
Expr * getPlacementArg(unsigned I)
Definition ExprCXX.h:2506
unsigned getNumPlacementArgs() const
Definition ExprCXX.h:2497
SourceRange getSourceRange() const
Definition ExprCXX.h:2613
FunctionDecl * getOperatorNew() const
Definition ExprCXX.h:2462
Expr * getInitializer()
The initializer of this new-expression.
Definition ExprCXX.h:2536
bool getValue() const
Definition ExprCXX.h:4372
MutableArrayRef< Expr * > getInitExprs()
Definition ExprCXX.h:5221
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:1238
bool isGenericLambda() const
Determine whether this class describes a generic lambda function object (i.e.
Definition DeclCXX.cpp:1681
bool hasTrivialDestructor() const
Determine whether this class has a trivial destructor (C++ [class.dtor]p3)
Definition DeclCXX.h:1377
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:1792
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition DeclCXX.h:602
base_class_range vbases()
Definition DeclCXX.h:625
capture_const_range captures() const
Definition DeclCXX.h:1102
bool isEmpty() const
Determine whether this is an empty class in the sense of (C++11 [meta.unary.prop]).
Definition DeclCXX.h:1191
CXXDestructorDecl * getDestructor() const
Returns the destructor decl for this class.
Definition DeclCXX.cpp:2129
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition DeclCXX.cpp:1744
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:307
bool isImplicit() const
Definition ExprCXX.h:1180
bool isTypeOperand() const
Definition ExprCXX.h:887
QualType getTypeOperand(const ASTContext &Context) const
Retrieves the type operand of this typeid() expression after various required adjustments (removing r...
Definition ExprCXX.cpp:166
Expr * getExprOperand() const
Definition ExprCXX.h:898
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:1117
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2954
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3158
SourceLocation getBeginLoc() const
Definition Expr.h:3288
const AllocSizeAttr * getCalleeAllocSizeAttr() const
Try to get the alloc_size attribute of the callee. May return null.
Definition Expr.cpp:3604
unsigned getBuiltinCallee() const
getBuiltinCallee - If this is a call to a builtin, return the builtin ID of the callee.
Definition Expr.cpp:1598
Expr * getCallee()
Definition Expr.h:3101
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition Expr.h:3145
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operator.
Definition Expr.h:3247
Expr ** getArgs()
Retrieve the call arguments.
Definition Expr.h:3148
Decl * getCalleeDecl()
Definition Expr.h:3131
QualType getCallReturnType(const ASTContext &Ctx) const
getCallReturnType - Get the return type of the call expr.
Definition Expr.cpp:1609
CaseStmt - Represent a case statement.
Definition Stmt.h:1929
Expr * getLHS()
Definition Stmt.h:2012
Expr * getRHS()
Definition Stmt.h:2024
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition Expr.h:3687
path_iterator path_begin()
Definition Expr.h:3757
unsigned path_size() const
Definition Expr.h:3756
CastKind getCastKind() const
Definition Expr.h:3731
const FieldDecl * getTargetUnionField() const
Definition Expr.h:3781
path_iterator path_end()
Definition Expr.h:3758
const CXXBaseSpecifier *const * path_const_iterator
Definition Expr.h:3754
bool path_empty() const
Definition Expr.h:3755
Expr * getSubExpr()
Definition Expr.h:3737
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operation.
Definition Expr.h:3801
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:1640
Expr * getChosenSubExpr() const
getChosenSubExpr - Return the subexpression chosen according to the condition.
Definition Expr.h:4895
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:3355
QualType getElementType() const
Definition TypeBase.h:3365
CompoundAssignOperator - For compound assignments (e.g.
Definition Expr.h:4311
QualType getComputationLHSType() const
Definition Expr.h:4345
CompoundLiteralExpr - [C99 6.5.2.5].
Definition Expr.h:3616
bool hasStaticStorage() const
Definition Expr.h:3661
APValue & getOrCreateStaticValue(ASTContext &Ctx) const
Definition Expr.cpp:5707
bool isFileScope() const
Definition Expr.h:3648
const Expr * getInitializer() const
Definition Expr.h:3644
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition Stmt.h:1749
bool body_empty() const
Definition Stmt.h:1793
Stmt *const * const_body_iterator
Definition Stmt.h:1821
body_iterator body_end()
Definition Stmt.h:1814
body_range body()
Definition Stmt.h:1812
body_iterator body_begin()
Definition Stmt.h:1813
bool isSatisfied() const
Whether or not the concept with the given arguments was satisfied when the expression was created.
ConditionalOperator - The ?
Definition Expr.h:4402
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression representing the value of the expression if the condition eva...
Definition Expr.h:4434
Expr * getCond() const
getCond - Return the expression representing the condition for the ?
Definition Expr.h:4425
Expr * getTrueExpr() const
getTrueExpr - Return the subexpression representing the value of the expression if the condition eval...
Definition Expr.h:4429
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3874
unsigned getSizeBitWidth() const
Return the bit width of the size type.
Definition TypeBase.h:3937
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:251
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:291
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:3963
bool isZeroSize() const
Return true if the size is zero.
Definition TypeBase.h:3944
const Expr * getSizeExpr() const
Return a pointer to the size expression.
Definition TypeBase.h:3970
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3930
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition TypeBase.h:3950
APValue getAPValueResult() const
Definition Expr.cpp:419
bool hasAPValueResult() const
Definition Expr.h:1168
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4501
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operator.
Definition Expr.h:4807
Expr * getSrcExpr() const
getSrcExpr - Return the Expr to be converted.
Definition Expr.h:4820
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:1466
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2126
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition DeclBase.h:2259
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:1281
bool refersToEnclosingVariableOrCapture() const
Does this DeclRefExpr refer to an enclosing local or a captured variable?
Definition Expr.h:1485
ValueDecl * getDecl()
Definition Expr.h:1349
DeclStmt - Adaptor class for mixing declarations with statements and expressions.
Definition Stmt.h:1640
decl_range decls()
Definition Stmt.h:1688
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
bool isInStdNamespace() const
Definition DeclBase.cpp:453
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:550
bool isInvalidDecl() const
Definition DeclBase.h:596
SourceLocation getLocation() const
Definition DeclBase.h:447
DeclContext * getDeclContext()
Definition DeclBase.h:456
AccessSpecifier getAccess() const
Definition DeclBase.h:515
A decomposition declaration.
Definition DeclCXX.h:4274
auto flat_bindings() const
Definition DeclCXX.h:4319
InitListExpr * getUpdater() const
Definition Expr.h:5953
Designator - A designator in a C99 designated initializer.
Definition Designator.h:38
DoStmt - This represents a 'do/while' stmt.
Definition Stmt.h:2841
Stmt * getBody()
Definition Stmt.h:2866
Expr * getCond()
Definition Stmt.h:2859
Symbolic representation of a dynamic allocation.
Definition APValue.h:65
static unsigned getMaxIndex()
Definition APValue.h:85
const Expr * getBase() const
Definition Expr.h:6598
ChildElementIter< false > begin()
Definition Expr.h:5252
ExplicitCastExpr - An explicit cast written in the source code.
Definition Expr.h:3939
QualType getTypeAsWritten() const
getTypeAsWritten - Returns the type that this expression is casting to, as written in the source code...
Definition Expr.h:3966
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:85
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:682
@ SE_AllowSideEffects
Allow any unmodeled side effect.
Definition Expr.h:686
@ SE_AllowUndefinedBehavior
Allow UB that we can give a value, but not arbitrary unmodeled side effects.
Definition Expr.h:684
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:3106
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.
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Returns the set of floating point options that apply to this expression.
Definition Expr.cpp:4003
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3101
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:3097
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 EvaluateAsInitializer(const ASTContext &Ctx, const VarDecl *VD, EvalResult &Result, bool IsConstantInitializer) const
EvaluateAsInitializer - Evaluate an expression as if it were the initializer of the given declaration...
bool EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsFixedPoint - Return true if this is a constant which we can fold and convert to a fixed poi...
bool isEvaluatable(const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects) const
isEvaluatable - Call EvaluateAsRValue to see if this expression can be constant folded without side-e...
bool isPRValue() const
Definition Expr.h: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...
std::optional< uint64_t > tryEvaluateStrLen(const ASTContext &Ctx) const
If the current Expr is a pointer, this will try to statically determine the strlen of the string poin...
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:3700
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< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx, bool AllowRelaxedEval=false) const
isIntegerConstantExpr - Return the value if this expression is a valid integer 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:3264
Expr()=delete
ConstantExprKind
Definition Expr.h:760
std::optional< uint64_t > tryEvaluateObjectSize(const ASTContext &Ctx, unsigned Type) const
If the current Expr is a pointer, this will try to statically determine the number of bytes available...
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:283
QualType getType() const
Definition Expr.h:144
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 isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result=nullptr, bool AllowRelaxedEval=false) const
isCXX11ConstantExpr - Return true if this expression is a constant expression in C++11.
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:4450
void getEncodedElementAccess(SmallVectorImpl< uint32_t > &Elts) const
getEncodedElementAccess - Encode the elements accessed into an llvm aggregate Constant of ConstantInt...
Definition Expr.cpp:4563
bool isFPConstrained() const
LangOptions::FPExceptionModeKind getExceptionMode() const
RoundingMode getRoundingMode() const
Represents a member of a struct/union/class.
Definition Decl.h:3294
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3397
unsigned getBitWidthValue() const
Computes the bit width of this field, if this is a bit field.
Definition Decl.cpp:4815
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition Decl.h:3379
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3530
FieldDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this field.
Definition Decl.h:3541
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:105
llvm::APInt getValue() const
Returns an internal integer representation of the literal.
Definition Expr.h:1586
llvm::APFloat getValue() const
Definition Expr.h:1677
ForStmt - This represents a 'for (init;cond;inc)' stmt.
Definition Stmt.h:2897
Stmt * getInit()
Definition Stmt.h:2912
VarDecl * getConditionVariable() const
Retrieve the variable declared in this "for" statement, if any.
Definition Stmt.cpp:1120
Stmt * getBody()
Definition Stmt.h:2941
Expr * getInc()
Definition Stmt.h:2940
Expr * getCond()
Definition Stmt.h:2939
const Expr * getSubExpr() const
Definition Expr.h:1073
Represents a function declaration or definition.
Definition Decl.h:2058
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2927
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition Decl.cpp:3267
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition Decl.cpp:4248
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition Decl.cpp:4236
bool hasCXXExplicitFunctionObjectParameter() const
Definition Decl.cpp:3908
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition Decl.h:2503
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition Decl.cpp:4372
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition Decl.h:2596
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:3469
bool isDefaulted() const
Whether this function is defaulted.
Definition Decl.h:2511
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:3112
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:6485
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:2268
Stmt * getThen()
Definition Stmt.h:2357
Stmt * getInit()
Definition Stmt.h:2418
bool isNonNegatedConsteval() const
Definition Stmt.h:2453
Expr * getCond()
Definition Stmt.h:2345
Stmt * getElse()
Definition Stmt.h:2366
bool isConsteval() const
Definition Stmt.h:2448
VarDecl * getConditionVariable()
Retrieve the variable declared in this "if" statement, if any.
Definition Stmt.cpp:1068
const Expr * getSubExpr() const
Definition Expr.h:1754
Represents an implicitly-generated value initialization of an object of a given type.
Definition Expr.h:6074
Represents a field injected from an anonymous union/struct into the parent scope.
Definition Decl.h:3601
ArrayRef< NamedDecl * > chain() const
Definition Decl.h:3622
Describes an C or C++ initializer list.
Definition Expr.h:5319
bool isTransparent() const
Is this a transparent initializer list (that is, an InitListExpr that is purely syntactic,...
Definition Expr.cpp:2473
bool isStringLiteralInit() const
Is this an initializer for an array of characters, initialized by a string literal or an @encode?
Definition Expr.cpp:2459
unsigned getNumInits() const
Definition Expr.h:5352
Expr * getArrayFiller()
If this initializer list initializes an array with more elements than there are initializers in the l...
Definition Expr.h:5422
const Expr * getInit(unsigned Init) const
Definition Expr.h:5374
ArrayRef< Expr * > inits() const
Definition Expr.h:5372
capture_init_iterator capture_init_end()
Retrieve the iterator pointing one past the last initialization argument for this lambda expression.
Definition ExprCXX.h:2109
capture_init_iterator capture_init_begin()
Retrieve the first initialization argument for this lambda expression (which initializes the first ca...
Definition ExprCXX.h:2097
CXXRecordDecl * getLambdaClass() const
Retrieve the class that corresponds to the lambda.
Definition ExprCXX.cpp:1432
@ 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...
bool isCompatibleWith(ClangABI Version) const
Represents a prvalue temporary that is written into memory so that a reference can bind to it.
Definition ExprCXX.h:4960
StorageDuration getStorageDuration() const
Retrieve the storage duration for the materialized temporary.
Definition ExprCXX.h:4985
Expr * getSubExpr() const
Retrieve the temporary-generating subexpression whose value will be materialized into a glvalue.
Definition ExprCXX.h:4977
APValue * getOrCreateValue(bool MayCreate) const
Get the storage for the constant value of a materialized temporary of static storage duration.
Definition ExprCXX.h:4993
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3375
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3458
Expr * getBase() const
Definition Expr.h:3452
bool isArrow() const
Definition Expr.h:3559
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:1690
bool isExpressibleAsConstantInitializer() const
Definition ExprObjC.h:68
Expr * getIndexExpr(unsigned Idx)
Definition Expr.h:2597
const OffsetOfNode & getComponent(unsigned Idx) const
Definition Expr.h:2585
TypeSourceInfo * getTypeSourceInfo() const
Definition Expr.h:2578
unsigned getNumComponents() const
Definition Expr.h:2593
unsigned getArrayExprIndex() const
For an array element node, returns the index into the array of expressions.
Definition Expr.h:2490
FieldDecl * getField() const
For a field offsetof node, returns the field.
Definition Expr.h:2496
@ Array
An index into an array.
Definition Expr.h:2437
@ Identifier
A field in a dependent type, known only by its name.
Definition Expr.h:2441
@ Field
A field.
Definition Expr.h:2439
@ Base
An implicit indirection through a C++ base class, when the field found is in a base class.
Definition Expr.h:2444
Kind getKind() const
Determine what kind of offsetof node this is.
Definition Expr.h:2486
CXXBaseSpecifier * getBase() const
For a base class node, returns the base specifier.
Definition Expr.h:2506
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition Expr.h:1189
Expr * getSourceExpr() const
The source expression of an opaque value expression is the expression which originally generated the ...
Definition Expr.h:1239
Expr * getSelectedExpr() const
Definition ExprCXX.h:4679
const Expr * getSubExpr() const
Definition Expr.h:2210
Represents a parameter to a function.
Definition Decl.h:1819
unsigned getFunctionScopeIndex() const
Returns the index of this parameter in its prototype or method scope.
Definition Decl.h:1879
bool isExplicitObjectParameter() const
Definition Decl.h:1907
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3408
StringLiteral * getFunctionName()
Definition Expr.h:2060
Expr * getResultExpr()
Return the result-bearing expression, or null if there is none.
Definition Expr.h:6869
ArrayRef< Expr * > semantics()
Definition Expr.h:6893
A (possibly-)qualified type.
Definition TypeBase.h:938
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8591
QualType withConst() const
Definition TypeBase.h:1175
void addConst()
Add the const type qualifier to this QualType.
Definition TypeBase.h:1172
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1005
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8507
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8547
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:8692
QualType getCanonicalType() const
Definition TypeBase.h:8559
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8601
void removeLocalVolatile()
Definition TypeBase.h:8623
void addVolatile()
Add the volatile type qualifier to this QualType.
Definition TypeBase.h:1180
void removeLocalConst()
Definition TypeBase.h:8615
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8580
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition TypeBase.h:1561
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition TypeBase.h:8553
bool isWrapType() const
Returns true if it is a OverflowBehaviorType of Wrap kind.
Definition Type.cpp:3088
Represents a struct/union/class.
Definition Decl.h:4459
unsigned getNumFields() const
Returns the number of fields (non-static data members) in this record.
Definition Decl.h:4675
field_iterator field_end() const
Definition Decl.h:4665
field_range fields() const
Definition Decl.h:4662
specific_decl_iterator< FieldDecl > field_iterator
Definition Decl.h:4659
bool isAnonymousStructOrUnion() const
Whether this is an anonymous struct or union.
Definition Decl.h:4511
bool field_empty() const
Definition Decl.h:4670
field_iterator field_begin() const
Definition Decl.cpp:5338
bool isSatisfied() const
Whether or not the requires clause is satisfied.
SourceLocation getLocation() const
Definition Expr.h:2166
std::string ComputeName(ASTContext &Context) const
Definition Expr.cpp:593
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:4654
llvm::APSInt getShuffleMaskIdx(unsigned N) const
Definition Expr.h:4706
unsigned getNumSubExprs() const
getNumSubExprs - Return the size of the SubExprs array.
Definition Expr.h:4687
Expr * getExpr(unsigned Index)
getExpr - Return the Expr at the specified index.
Definition Expr.h:4693
unsigned getPackLength() const
Retrieve the length of the parameter pack.
Definition ExprCXX.h:4555
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:2291
bool isIntType() const
Definition Expr.h:5061
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:4623
Stmt - This represents one statement.
Definition Stmt.h:85
@ NoStmtClass
Definition Stmt.h:88
StmtClass getStmtClass() const
Definition Stmt.h:1502
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:343
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:355
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1810
unsigned getLength() const
Definition Expr.h:1920
StringRef getBytes() const
Allow access to clients that need the byte representation, such as ASTWriterStmt::VisitStringLiteral(...
Definition Expr.h:1886
uint32_t getCodeUnit(size_t i) const
Definition Expr.h:1893
StringRef getString() const
Definition Expr.h:1878
bool isOrdinary() const
Definition Expr.h:1927
unsigned getCharByteWidth() const
Definition Expr.h:1921
const SwitchCase * getNextSwitchCase() const
Definition Stmt.h:1902
SwitchStmt - This represents a 'switch' stmt.
Definition Stmt.h:2518
Expr * getCond()
Definition Stmt.h:2581
Stmt * getBody()
Definition Stmt.h:2593
VarDecl * getConditionVariable()
Retrieve the variable declared in this "switch" statement, if any.
Definition Stmt.cpp:1186
Stmt * getInit()
Definition Stmt.h:2598
SwitchCase * getSwitchCaseList()
Definition Stmt.h:2649
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:3952
TagDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:4962
bool isUnion() const
Definition Decl.h:4062
Exposes information about the current target.
Definition TargetInfo.h:227
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
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:8489
bool getBoolValue() const
Definition ExprCXX.h:2950
const APValue & getAPValue() const
Definition ExprCXX.h:2955
bool isStoredAsBoolean() const
Definition ExprCXX.h:2946
The base class of the type hierarchy.
Definition TypeBase.h:1879
bool isVoidType() const
Definition TypeBase.h:9116
bool isBooleanType() const
Definition TypeBase.h:9253
bool isFunctionReferenceType() const
Definition TypeBase.h:8818
bool isMFloat8Type() const
Definition TypeBase.h:9141
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2319
bool isPackedVectorBoolType(const ASTContext &ctx) const
Definition Type.cpp:455
bool isLiteralType(const ASTContext &Ctx) const
Return true if this is a literal type (C++11 [basic.types]p10)
Definition Type.cpp:3145
bool isIncompleteArrayType() const
Definition TypeBase.h:8851
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2296
bool isComplexType() const
isComplexType() does not include complex integers (a GCC extension).
Definition Type.cpp:761
const ArrayType * castAsArrayTypeUnsafe() const
A variant of castAs<> for array type which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9419
bool isUnsignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is unsigned or an enumeration types whose underlying ...
Definition Type.cpp:2387
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition Type.cpp:2203
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:8847
bool isNothrowT() const
Definition Type.cpp:3329
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition Type.h:41
bool isVoidPointerType() const
Definition Type.cpp:749
bool isConstantSizeType() const
Return true if this is not a variable sized type, according to the rules of C99 6....
Definition Type.cpp:2549
bool isArrayType() const
Definition TypeBase.h:8843
bool isFunctionPointerType() const
Definition TypeBase.h:8811
bool isCountAttributedType() const
Definition Type.cpp:778
bool isConstantMatrixType() const
Definition TypeBase.h:8911
bool isPointerType() const
Definition TypeBase.h:8744
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9160
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9410
bool isReferenceType() const
Definition TypeBase.h:8768
bool isEnumeralType() const
Definition TypeBase.h:8875
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:1984
bool isVariableArrayType() const
Definition TypeBase.h:8855
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition Type.cpp:2733
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:789
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:9238
bool isExtVectorBoolType() const
Definition TypeBase.h:8891
bool isMemberDataPointerType() const
Definition TypeBase.h:8836
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition TypeBase.h:9085
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2859
RecordDecl * castAsRecordDecl() const
Definition Type.h:48
bool isAnyComplexType() const
Definition TypeBase.h:8879
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9176
bool isMemberPointerType() const
Definition TypeBase.h:8825
bool isAtomicType() const
Definition TypeBase.h:8936
bool isComplexIntegerType() const
Definition Type.cpp:767
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9396
bool isObjectType() const
Determine whether this type is an object type.
Definition TypeBase.h:2574
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:2559
bool isFunctionType() const
Definition TypeBase.h:8740
bool isVectorType() const
Definition TypeBase.h:8883
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2437
bool isFloatingType() const
Definition Type.cpp:2421
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:2364
const T * castAsCanonical() const
Return this type's canonical type cast to the specified type.
Definition TypeBase.h:3005
bool isAnyPointerType() const
Definition TypeBase.h:8752
TypeClass getTypeClass() const
Definition TypeBase.h:2449
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9343
bool isNullPtrType() const
Definition TypeBase.h:9153
bool isRecordType() const
Definition TypeBase.h:8871
bool isUnionType() const
Definition Type.cpp:755
bool isSizelessVectorType() const
Returns true for all scalable vector types.
Definition Type.cpp:2695
bool hasPointerRepresentation() const
Whether this type is represented natively as a pointer.
Definition TypeBase.h:9287
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand.
Definition Expr.h:2636
QualType getArgumentType() const
Definition Expr.h:2679
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:2715
QualType getTypeOfArgument() const
Gets the argument type, or the type of the argument expression, whichever is appropriate.
Definition Expr.h:2705
UnaryExprOrTypeTrait getKind() const
Definition Expr.h:2668
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2255
SourceLocation getExprLoc() const
Definition Expr.h:2379
Expr * getSubExpr() const
Definition Expr.h:2296
Opcode getOpcode() const
Definition Expr.h:2291
static bool isIncrementOp(Opcode Op)
Definition Expr.h:2337
bool canOverflow() const
Returns true if the unary operator can cause an overflow.
Definition Expr.h:2309
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:5644
QualType getType() const
Definition Value.cpp:238
bool hasValue() const
Definition Value.h:135
Represents a variable declaration or definition.
Definition Decl.h:932
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition Decl.h:1593
bool hasInit() const
Definition Decl.cpp:2379
bool hasICEInitializer(const ASTContext &Context) const
Determine whether the initializer of this variable is an integer constant expression.
Definition Decl.cpp:2628
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition Decl.h:1602
const APValue * getEvaluatedValue() const
Return the already-evaluated value of this variable's initializer, or nullptr if the value is not yet...
Definition Decl.cpp:2620
CharUnits getFlexibleArrayInitChars(const ASTContext &Ctx) const
If hasFlexibleArrayInit is true, compute the number of additional bytes necessary to store those elem...
Definition Decl.cpp:2848
bool hasConstantInitialization() const
Determine whether this variable has constant initialization.
Definition Decl.cpp:2640
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
Definition Decl.cpp:2347
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:2467
EvaluatedStmt * ensureEvaluatedStmt() const
Convert the initializer for this declaration to the elaborated EvaluatedStmt form,...
Definition Decl.cpp:2538
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:1214
ThreadStorageClassSpecifier getTSCSpec() const
Definition Decl.h:1183
const Expr * getInit() const
Definition Decl.h:1391
const APValue * evaluateValue() const
Attempt to evaluate the value of the initializer attached to this declaration, and produce notes expl...
Definition Decl.cpp:2556
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition Decl.h:1190
DefinitionKind hasDefinition(ASTContext &) const
Check whether this variable is defined in this translation unit.
Definition Decl.cpp:2356
bool isLocalVarDecl() const
Returns true for local variable declarations other than parameters.
Definition Decl.h:1274
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:2509
const Expr * getAnyInitializer() const
Get the initializer for this variable, no matter which declaration it is attached to.
Definition Decl.h:1381
Expr * getSizeExpr() const
Definition TypeBase.h:4094
Represents a GCC generic vector type.
Definition TypeBase.h:4289
unsigned getNumElements() const
Definition TypeBase.h:4304
QualType getElementType() const
Definition TypeBase.h:4303
WhileStmt - This represents a 'while' stmt.
Definition Stmt.h:2706
Expr * getCond()
Definition Stmt.h:2758
VarDecl * getConditionVariable()
Retrieve the variable declared in this "while" statement, if any.
Definition Stmt.cpp:1247
Stmt * getBody()
Definition Stmt.h:2770
bool evaluateDestruction(State &Parent, const VarDecl *VD, APValue Value)
Evaluates the destruction of a variable.
Definition Context.cpp:164
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:81
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.
tooling::Replacements cleanup(const FormatStyle &Style, StringRef Code, ArrayRef< tooling::Range > Ranges, StringRef FileName="<stdin>")
Clean up any erroneous/redundant code in the given Ranges in Code.
Definition Format.cpp:4468
std::optional< llvm::AllocTokenMetadata > getAllocTokenMetadata(QualType T, const ASTContext &Ctx)
Get the information required for construction of an allocation token ID.
QualType inferPossibleType(const CallExpr *E, const ASTContext &Ctx, const CastExpr *CastE)
Infer the possible allocated type from an allocation call expression.
bool Sub(InterpState &S, CodePtr OpPC)
Definition Interp.h:448
bool NE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1523
llvm::FixedPointSemantics FixedPointSemantics
Definition Interp.h:57
bool This(InterpState &S, CodePtr OpPC)
Definition Interp.h:3178
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:3872
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.
void info(bool Verbose, unsigned Level, const char *Fmt, Ts &&...Args)
Prints an indented note to stderr when Verbose is set.
Definition Utils.h:57
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...
Top level wrappers for InstallAPI frontend operations.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
bool isa(CodeGen::Address addr)
Definition Address.h:330
const Expr * findStructFieldAccess(const Expr *E, const Expr **OutArrayIndex=nullptr, QualType *OutArrayElementTy=nullptr)
Walk E through parens, implicit casts, unary &/*, array subscripts and comma operators to find the he...
Definition Expr.cpp:5772
bool hasSpecificAttr(const Container &container)
@ NonNull
Values of this type can never be null.
Definition Specifiers.h:349
@ Success
Annotation was successful.
Definition Parser.h:65
Expr::ConstantExprKind ConstantExprKind
Definition Expr.h:1053
@ Self
'self' clause, allowed on Compute and Combined Constructs, plus 'update'.
bool operator==(const CallGraphNode::CallRecord &LHS, const CallGraphNode::CallRecord &RHS)
Definition CallGraph.h:218
@ AS_public
Definition Specifiers.h:125
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:237
Expr * Cond
};
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:44
@ CSK_ArrayToPointer
Definition State.h:48
@ CSK_Derived
Definition State.h:46
@ CSK_Base
Definition State.h:45
@ CSK_Real
Definition State.h:50
@ CSK_ArrayIndex
Definition State.h:49
@ CSK_Imag
Definition State.h:51
@ CSK_VectorElement
Definition State.h:52
@ CSK_Field
Definition State.h:47
@ SD_Static
Static storage duration.
Definition Specifiers.h:342
@ SD_FullExpression
Full-expression storage duration (for temporaries).
Definition Specifiers.h:339
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition ASTLambda.h:28
@ Result
The result type of a method or function.
Definition TypeBase.h:906
AccessKinds
Kinds of access we can perform on an object, for diagnostics.
Definition State.h:28
@ AK_TypeId
Definition State.h:36
@ AK_Construct
Definition State.h:37
@ AK_Increment
Definition State.h:32
@ AK_DynamicCast
Definition State.h:35
@ AK_Read
Definition State.h:29
@ AK_Assign
Definition State.h:31
@ AK_IsWithinLifetime
Definition State.h:39
@ AK_MemberCall
Definition State.h:34
@ AK_ReadObjectRepresentation
Definition State.h:30
@ AK_Dereference
Definition State.h:40
@ AK_Destroy
Definition State.h:38
@ AK_Decrement
Definition State.h:33
const FunctionProtoType * T
@ Off
Never emit colors regardless of the output stream.
@ Type
The name was classified as a type.
Definition Sema.h:559
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:136
EvaluationMode
Definition State.h:55
@ ConstantFold
Fold the expression to a constant.
Definition State.h:69
@ ConstantExpressionUnevaluated
Evaluate as a constant expression.
Definition State.h:65
@ ConstantExpression
Evaluate as a constant expression.
Definition State.h:58
@ IgnoreSideEffects
Evaluate in any way we know how.
Definition State.h:73
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition DeclBase.h:1305
U cast(CodeGen::Address addr)
Definition Address.h:327
@ None
The alignment was not explicit in code.
Definition ASTContext.h:176
@ ArrayBound
Array bound in array declarator or new-expression.
Definition Sema.h:839
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6031
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ Other
Other implicit parameter.
Definition Decl.h:1774
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::dependencies::ModuleID &ID)
__packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 int32_t
__packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 __packed_splat2 uint8_t
__packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 __packed_splat2 __packed_splat4 uint16_t
__packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 __packed_splat2 __packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 uint32_t
#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:657
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:659
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:613
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:641
bool HasSideEffects
Whether the evaluated expression has side effects.
Definition Expr.h:616
unsigned SuppressLambdaBody
Whether to suppress printing the body of a lambda.
DenseMapInfo< APValue::LValueBase > Base
static unsigned getHashValue(const ObjectUnderConstruction &Object)
static bool isEqual(const ObjectUnderConstruction &LHS, const ObjectUnderConstruction &RHS)
#define ilogb(__x)
Definition tgmath.h:851
#define scalbn(__x, __y)
Definition tgmath.h:1165