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"
37#include "ByteCode/Frame.h"
38#include "ByteCode/State.h"
39#include "ExprConstShared.h"
40#include "clang/AST/APValue.h"
42#include "clang/AST/ASTLambda.h"
43#include "clang/AST/Attr.h"
45#include "clang/AST/CharUnits.h"
48#include "clang/AST/Expr.h"
50#include "clang/AST/OSLog.h"
54#include "clang/AST/SemaProxy.h"
56#include "clang/AST/Type.h"
57#include "clang/AST/TypeLoc.h"
62#include "llvm/ADT/APFixedPoint.h"
63#include "llvm/ADT/Sequence.h"
64#include "llvm/ADT/SmallBitVector.h"
65#include "llvm/ADT/StringExtras.h"
66#include "llvm/ADT/bit.h"
67#include "llvm/Support/CRC.h"
68#include "llvm/Support/Casting.h"
69#include "llvm/Support/Debug.h"
70#include "llvm/Support/MathExtras.h"
71#include "llvm/Support/SaveAndRestore.h"
72#include "llvm/Support/SipHash.h"
73#include "llvm/Support/TimeProfiler.h"
74#include "llvm/Support/raw_ostream.h"
75#include <cstring>
76#include <functional>
77#include <limits>
78#include <optional>
79
80#define DEBUG_TYPE "exprconstant"
81
82using namespace clang;
83using llvm::APFixedPoint;
84using llvm::APInt;
85using llvm::APSInt;
86using llvm::APFloat;
87using llvm::FixedPointSemantics;
88
89namespace {
90 struct LValue;
91 class CallStackFrame;
92 class EvalInfo;
93
94 using SourceLocExprScopeGuard =
96
98 return B.getType();
99 }
100
101 /// Get an LValue path entry, which is known to not be an array index, as a
102 /// field declaration.
103 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
104 return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer());
105 }
106 /// Get an LValue path entry, which is known to not be an array index, as a
107 /// base class declaration.
108 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
109 return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer());
110 }
111 /// Determine whether this LValue path entry for a base class names a virtual
112 /// base class.
113 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
114 return E.getAsBaseOrMember().getInt();
115 }
116
117 /// Given an expression, determine the type used to store the result of
118 /// evaluating that expression.
119 static QualType getStorageType(const ASTContext &Ctx, const Expr *E) {
120 if (E->isPRValue())
121 return E->getType();
122 return Ctx.getLValueReferenceType(E->getType());
123 }
124
125 static unsigned countNonVirtualBases(const CXXRecordDecl *RD) {
126 return llvm::count_if(RD->bases(), [](auto &B) { return !B.isVirtual(); });
127 }
128
129 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
130 /// This will look through a single cast.
131 ///
132 /// Returns null if we couldn't unwrap a function with alloc_size.
133 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
134 if (!E->getType()->isPointerType())
135 return nullptr;
136
137 E = E->IgnoreParens();
138 // If we're doing a variable assignment from e.g. malloc(N), there will
139 // probably be a cast of some kind. In exotic cases, we might also see a
140 // top-level ExprWithCleanups. Ignore them either way.
141 if (const auto *FE = dyn_cast<FullExpr>(E))
142 E = FE->getSubExpr()->IgnoreParens();
143
144 if (const auto *Cast = dyn_cast<CastExpr>(E))
145 E = Cast->getSubExpr()->IgnoreParens();
146
147 if (const auto *CE = dyn_cast<CallExpr>(E))
148 return CE->getCalleeAllocSizeAttr() ? CE : nullptr;
149 return nullptr;
150 }
151
152 /// Determines whether or not the given Base contains a call to a function
153 /// with the alloc_size attribute.
154 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
155 const auto *E = Base.dyn_cast<const Expr *>();
156 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
157 }
158
159 /// The bound to claim that an array of unknown bound has.
160 /// The value in MostDerivedArraySize is undefined in this case. So, set it
161 /// to an arbitrary value that's likely to loudly break things if it's used.
162 static const uint64_t AssumedSizeForUnsizedArray =
163 std::numeric_limits<uint64_t>::max() / 2;
164
165 /// Determines if an LValue with the given LValueBase will have an unsized
166 /// array in its designator.
167 /// Find the path length and type of the most-derived subobject in the given
168 /// path, and find the size of the containing array, if any.
169 static unsigned
170 findMostDerivedSubobject(const ASTContext &Ctx, APValue::LValueBase Base,
172 uint64_t &ArraySize, QualType &Type, bool &IsArray,
173 bool &FirstEntryIsUnsizedArray) {
174 // This only accepts LValueBases from APValues, and APValues don't support
175 // arrays that lack size info.
176 assert(!isBaseAnAllocSizeCall(Base) &&
177 "Unsized arrays shouldn't appear here");
178 unsigned MostDerivedLength = 0;
179 // The type of Base is a reference type if the base is a constexpr-unknown
180 // variable. In that case, look through the reference type.
181 Type = getType(Base).getNonReferenceType();
182
183 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
184 if (Type->isArrayType()) {
185 const ArrayType *AT = Ctx.getAsArrayType(Type);
186 Type = AT->getElementType();
187 MostDerivedLength = I + 1;
188 IsArray = true;
189
190 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
191 ArraySize = CAT->getZExtSize();
192 } else {
193 assert(I == 0 && "unexpected unsized array designator");
194 FirstEntryIsUnsizedArray = true;
195 ArraySize = AssumedSizeForUnsizedArray;
196 }
197 } else if (Type->isAnyComplexType()) {
198 const ComplexType *CT = Type->castAs<ComplexType>();
199 Type = CT->getElementType();
200 ArraySize = 2;
201 MostDerivedLength = I + 1;
202 IsArray = true;
203 } else if (const auto *VT = Type->getAs<VectorType>()) {
204 Type = VT->getElementType();
205 ArraySize = VT->getNumElements();
206 MostDerivedLength = I + 1;
207 IsArray = true;
208 } else if (const FieldDecl *FD = getAsField(Path[I])) {
209 Type = FD->getType();
210 ArraySize = 0;
211 MostDerivedLength = I + 1;
212 IsArray = false;
213 } else {
214 // Path[I] describes a base class.
215 ArraySize = 0;
216 IsArray = false;
217 }
218 }
219 return MostDerivedLength;
220 }
221
222 /// A path from a glvalue to a subobject of that glvalue.
223 struct SubobjectDesignator {
224 /// True if the subobject was named in a manner not supported by C++11. Such
225 /// lvalues can still be folded, but they are not core constant expressions
226 /// and we cannot perform lvalue-to-rvalue conversions on them.
227 LLVM_PREFERRED_TYPE(bool)
228 unsigned Invalid : 1;
229
230 /// Is this a pointer one past the end of an object?
231 LLVM_PREFERRED_TYPE(bool)
232 unsigned IsOnePastTheEnd : 1;
233
234 /// Indicator of whether the first entry is an unsized array.
235 LLVM_PREFERRED_TYPE(bool)
236 unsigned FirstEntryIsAnUnsizedArray : 1;
237
238 /// Indicator of whether the most-derived object is an array element.
239 LLVM_PREFERRED_TYPE(bool)
240 unsigned MostDerivedIsArrayElement : 1;
241
242 /// The length of the path to the most-derived object of which this is a
243 /// subobject.
244 unsigned MostDerivedPathLength : 28;
245
246 /// The size of the array of which the most-derived object is an element.
247 /// This will always be 0 if the most-derived object is not an array
248 /// element. 0 is not an indicator of whether or not the most-derived object
249 /// is an array, however, because 0-length arrays are allowed.
250 ///
251 /// If the current array is an unsized array, the value of this is
252 /// undefined.
253 uint64_t MostDerivedArraySize;
254 /// The type of the most derived object referred to by this address.
255 QualType MostDerivedType;
256
257 typedef APValue::LValuePathEntry PathEntry;
258
259 /// The entries on the path from the glvalue to the designated subobject.
261
262 SubobjectDesignator() : Invalid(true) {}
263
264 explicit SubobjectDesignator(QualType T)
265 : Invalid(false), IsOnePastTheEnd(false),
266 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
267 MostDerivedPathLength(0), MostDerivedArraySize(0),
268 MostDerivedType(T.isNull() ? QualType() : T.getNonReferenceType()) {}
269
270 SubobjectDesignator(const ASTContext &Ctx, const APValue &V)
271 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
272 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
273 MostDerivedPathLength(0), MostDerivedArraySize(0) {
274 assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
275 if (!Invalid) {
276 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
277 llvm::append_range(Entries, V.getLValuePath());
278 if (V.getLValueBase()) {
279 bool IsArray = false;
280 bool FirstIsUnsizedArray = false;
281 MostDerivedPathLength = findMostDerivedSubobject(
282 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
283 MostDerivedType, IsArray, FirstIsUnsizedArray);
284 MostDerivedIsArrayElement = IsArray;
285 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
286 }
287 }
288 }
289
290 void truncate(ASTContext &Ctx, APValue::LValueBase Base,
291 unsigned NewLength) {
292 if (Invalid)
293 return;
294
295 assert(Base && "cannot truncate path for null pointer");
296 assert(NewLength <= Entries.size() && "not a truncation");
297
298 if (NewLength == Entries.size())
299 return;
300 Entries.resize(NewLength);
301
302 bool IsArray = false;
303 bool FirstIsUnsizedArray = false;
304 MostDerivedPathLength = findMostDerivedSubobject(
305 Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray,
306 FirstIsUnsizedArray);
307 MostDerivedIsArrayElement = IsArray;
308 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
309 }
310
311 void setInvalid() {
312 Invalid = true;
313 Entries.clear();
314 }
315
316 /// Determine whether the most derived subobject is an array without a
317 /// known bound.
318 bool isMostDerivedAnUnsizedArray() const {
319 assert(!Invalid && "Calling this makes no sense on invalid designators");
320 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
321 }
322
323 /// Determine what the most derived array's size is. Results in an assertion
324 /// failure if the most derived array lacks a size.
325 uint64_t getMostDerivedArraySize() const {
326 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
327 return MostDerivedArraySize;
328 }
329
330 /// Determine whether this is a one-past-the-end pointer.
331 bool isOnePastTheEnd() const {
332 assert(!Invalid);
333 if (IsOnePastTheEnd)
334 return true;
335 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
336 Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==
337 MostDerivedArraySize)
338 return true;
339 return false;
340 }
341
342 /// Get the range of valid index adjustments in the form
343 /// {maximum value that can be subtracted from this pointer,
344 /// maximum value that can be added to this pointer}
345 std::pair<uint64_t, uint64_t> validIndexAdjustments() {
346 if (Invalid || isMostDerivedAnUnsizedArray())
347 return {0, 0};
348
349 // [expr.add]p4: For the purposes of these operators, a pointer to a
350 // nonarray object behaves the same as a pointer to the first element of
351 // an array of length one with the type of the object as its element type.
352 bool IsArray = MostDerivedPathLength == Entries.size() &&
353 MostDerivedIsArrayElement;
354 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
355 : (uint64_t)IsOnePastTheEnd;
356 uint64_t ArraySize =
357 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
358 return {ArrayIndex, ArraySize - ArrayIndex};
359 }
360
361 /// Check that this refers to a valid subobject.
362 bool isValidSubobject() const {
363 if (Invalid)
364 return false;
365 return !isOnePastTheEnd();
366 }
367 /// Check that this refers to a valid subobject, and if not, produce a
368 /// relevant diagnostic and set the designator as invalid.
369 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
370
371 /// Get the type of the designated object.
372 QualType getType(ASTContext &Ctx) const {
373 assert(!Invalid && "invalid designator has no subobject type");
374 return MostDerivedPathLength == Entries.size()
375 ? MostDerivedType
376 : Ctx.getCanonicalTagType(getAsBaseClass(Entries.back()));
377 }
378
379 /// Update this designator to refer to the first element within this array.
380 void addArrayUnchecked(const ConstantArrayType *CAT) {
381 Entries.push_back(PathEntry::ArrayIndex(0));
382
383 // This is a most-derived object.
384 MostDerivedType = CAT->getElementType();
385 MostDerivedIsArrayElement = true;
386 MostDerivedArraySize = CAT->getZExtSize();
387 MostDerivedPathLength = Entries.size();
388 }
389 /// Update this designator to refer to the first element within the array of
390 /// elements of type T. This is an array of unknown size.
391 void addUnsizedArrayUnchecked(QualType ElemTy) {
392 Entries.push_back(PathEntry::ArrayIndex(0));
393
394 MostDerivedType = ElemTy;
395 MostDerivedIsArrayElement = true;
396 // The value in MostDerivedArraySize is undefined in this case. So, set it
397 // to an arbitrary value that's likely to loudly break things if it's
398 // used.
399 MostDerivedArraySize = AssumedSizeForUnsizedArray;
400 MostDerivedPathLength = Entries.size();
401 }
402 /// Update this designator to refer to the given base or member of this
403 /// object.
404 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
405 Entries.push_back(APValue::BaseOrMemberType(D, Virtual));
406
407 // If this isn't a base class, it's a new most-derived object.
408 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
409 MostDerivedType = FD->getType();
410 MostDerivedIsArrayElement = false;
411 MostDerivedArraySize = 0;
412 MostDerivedPathLength = Entries.size();
413 }
414 }
415 /// Update this designator to refer to the given complex component.
416 void addComplexUnchecked(QualType EltTy, bool Imag) {
417 Entries.push_back(PathEntry::ArrayIndex(Imag));
418
419 // This is technically a most-derived object, though in practice this
420 // is unlikely to matter.
421 MostDerivedType = EltTy;
422 MostDerivedIsArrayElement = true;
423 MostDerivedArraySize = 2;
424 MostDerivedPathLength = Entries.size();
425 }
426
427 void addVectorElementUnchecked(QualType EltTy, uint64_t Size,
428 uint64_t Idx) {
429 Entries.push_back(PathEntry::ArrayIndex(Idx));
430 MostDerivedType = EltTy;
431 MostDerivedPathLength = Entries.size();
432 MostDerivedArraySize = 0;
433 MostDerivedIsArrayElement = false;
434 }
435
436 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
437 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
438 const APSInt &N);
439 /// Add N to the address of this subobject.
440 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N, const LValue &LV);
441 };
442
443 /// A scope at the end of which an object can need to be destroyed.
444 enum class ScopeKind {
445 Block,
446 FullExpression,
447 Call
448 };
449
450 /// A reference to a particular call and its arguments.
451 struct CallRef {
452 CallRef() : OrigCallee(), CallIndex(0), Version() {}
453 CallRef(const FunctionDecl *Callee, unsigned CallIndex, unsigned Version)
454 : OrigCallee(Callee), CallIndex(CallIndex), Version(Version) {}
455
456 explicit operator bool() const { return OrigCallee; }
457
458 /// Get the parameter that the caller initialized, corresponding to the
459 /// given parameter in the callee.
460 const ParmVarDecl *getOrigParam(const ParmVarDecl *PVD) const {
461 return OrigCallee ? OrigCallee->getParamDecl(PVD->getFunctionScopeIndex())
462 : PVD;
463 }
464
465 /// The callee at the point where the arguments were evaluated. This might
466 /// be different from the actual callee (a different redeclaration, or a
467 /// virtual override), but this function's parameters are the ones that
468 /// appear in the parameter map.
469 const FunctionDecl *OrigCallee;
470 /// The call index of the frame that holds the argument values.
471 unsigned CallIndex;
472 /// The version of the parameters corresponding to this call.
473 unsigned Version;
474 };
475
476 /// A stack frame in the constexpr call stack.
477 class CallStackFrame : public interp::Frame {
478 public:
479 EvalInfo &Info;
480
481 /// Parent - The caller of this stack frame.
482 CallStackFrame *Caller;
483
484 /// Callee - The function which was called.
485 const FunctionDecl *Callee;
486
487 /// This - The binding for the this pointer in this call, if any.
488 const LValue *This;
489
490 /// CallExpr - The syntactical structure of member function calls
491 const Expr *CallExpr;
492
493 /// Information on how to find the arguments to this call. Our arguments
494 /// are stored in our parent's CallStackFrame, using the ParmVarDecl* as a
495 /// key and this value as the version.
496 CallRef Arguments;
497
498 /// Source location information about the default argument or default
499 /// initializer expression we're evaluating, if any.
500 CurrentSourceLocExprScope CurSourceLocExprScope;
501
502 // Note that we intentionally use std::map here so that references to
503 // values are stable.
504 typedef std::pair<const void *, unsigned> MapKeyTy;
505 typedef std::map<MapKeyTy, APValue> MapTy;
506 /// Temporaries - Temporary lvalues materialized within this stack frame.
507 MapTy Temporaries;
508
509 /// CallRange - The source range of the call expression for this call.
510 SourceRange CallRange;
511
512 /// Index - The call index of this call.
513 unsigned Index;
514
515 /// The stack of integers for tracking version numbers for temporaries.
516 SmallVector<unsigned, 2> TempVersionStack = {1};
517 unsigned CurTempVersion = TempVersionStack.back();
518
519 unsigned getTempVersion() const { return TempVersionStack.back(); }
520
521 void pushTempVersion() {
522 TempVersionStack.push_back(++CurTempVersion);
523 }
524
525 void popTempVersion() {
526 TempVersionStack.pop_back();
527 }
528
529 CallRef createCall(const FunctionDecl *Callee) {
530 return {Callee, Index, ++CurTempVersion};
531 }
532
533 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
534 // on the overall stack usage of deeply-recursing constexpr evaluations.
535 // (We should cache this map rather than recomputing it repeatedly.)
536 // But let's try this and see how it goes; we can look into caching the map
537 // as a later change.
538
539 /// LambdaCaptureFields - Mapping from captured variables/this to
540 /// corresponding data members in the closure class.
541 llvm::DenseMap<const ValueDecl *, FieldDecl *> LambdaCaptureFields;
542 FieldDecl *LambdaThisCaptureField = nullptr;
543
544 CallStackFrame(EvalInfo &Info, SourceRange CallRange,
545 const FunctionDecl *Callee, const LValue *This,
546 const Expr *CallExpr, CallRef Arguments);
547 ~CallStackFrame();
548
549 // Return the temporary for Key whose version number is Version.
550 APValue *getTemporary(const void *Key, unsigned Version) {
551 MapKeyTy KV(Key, Version);
552 auto LB = Temporaries.lower_bound(KV);
553 if (LB != Temporaries.end() && LB->first == KV)
554 return &LB->second;
555 return nullptr;
556 }
557
558 // Return the current temporary for Key in the map.
559 APValue *getCurrentTemporary(const void *Key) {
560 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
561 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
562 return &std::prev(UB)->second;
563 return nullptr;
564 }
565
566 // Return the version number of the current temporary for Key.
567 unsigned getCurrentTemporaryVersion(const void *Key) const {
568 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
569 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
570 return std::prev(UB)->first.second;
571 return 0;
572 }
573
574 /// Allocate storage for an object of type T in this stack frame.
575 /// Populates LV with a handle to the created object. Key identifies
576 /// the temporary within the stack frame, and must not be reused without
577 /// bumping the temporary version number.
578 template<typename KeyT>
579 APValue &createTemporary(const KeyT *Key, QualType T,
580 ScopeKind Scope, LValue &LV);
581
582 /// Allocate storage for a parameter of a function call made in this frame.
583 APValue &createParam(CallRef Args, const ParmVarDecl *PVD, LValue &LV);
584
585 void describe(llvm::raw_ostream &OS) const override;
586
587 Frame *getCaller() const override { return Caller; }
588 SourceRange getCallRange() const override { return CallRange; }
589 const FunctionDecl *getCallee() const override { return Callee; }
590
591 bool isStdFunction() const {
592 for (const DeclContext *DC = Callee; DC; DC = DC->getParent())
593 if (DC->isStdNamespace())
594 return true;
595 return false;
596 }
597
598 /// Whether we're in a context where [[msvc::constexpr]] evaluation is
599 /// permitted. See MSConstexprDocs for description of permitted contexts.
600 bool CanEvalMSConstexpr = false;
601
602 private:
603 APValue &createLocal(APValue::LValueBase Base, const void *Key, QualType T,
604 ScopeKind Scope);
605 };
606
607 /// Temporarily override 'this'.
608 class ThisOverrideRAII {
609 public:
610 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
611 : Frame(Frame), OldThis(Frame.This) {
612 if (Enable)
613 Frame.This = NewThis;
614 }
615 ~ThisOverrideRAII() {
616 Frame.This = OldThis;
617 }
618 private:
619 CallStackFrame &Frame;
620 const LValue *OldThis;
621 };
622
623 // A shorthand time trace scope struct, prints source range, for example
624 // {"name":"EvaluateAsRValue","args":{"detail":"<test.cc:8:21, col:25>"}}}
625 class ExprTimeTraceScope {
626 public:
627 ExprTimeTraceScope(const Expr *E, const ASTContext &Ctx, StringRef Name)
628 : TimeScope(Name, [E, &Ctx] {
630 }) {}
631
632 private:
633 llvm::TimeTraceScope TimeScope;
634 };
635
636 /// RAII object used to change the current ability of
637 /// [[msvc::constexpr]] evaulation.
638 struct MSConstexprContextRAII {
639 CallStackFrame &Frame;
640 bool OldValue;
641 explicit MSConstexprContextRAII(CallStackFrame &Frame, bool Value)
642 : Frame(Frame), OldValue(Frame.CanEvalMSConstexpr) {
643 Frame.CanEvalMSConstexpr = Value;
644 }
645
646 ~MSConstexprContextRAII() { Frame.CanEvalMSConstexpr = OldValue; }
647 };
648}
649
650static bool HandleDestruction(EvalInfo &Info, const Expr *E,
651 const LValue &This, QualType ThisType);
652static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
654 QualType T);
655
656namespace {
657 /// A cleanup, and a flag indicating whether it is lifetime-extended.
658 class Cleanup {
659 llvm::PointerIntPair<APValue*, 2, ScopeKind> Value;
660 APValue::LValueBase Base;
661 QualType T;
662
663 public:
664 Cleanup(APValue *Val, APValue::LValueBase Base, QualType T,
665 ScopeKind Scope)
666 : Value(Val, Scope), Base(Base), T(T) {}
667
668 /// Determine whether this cleanup should be performed at the end of the
669 /// given kind of scope.
670 bool isDestroyedAtEndOf(ScopeKind K) const {
671 return (int)Value.getInt() >= (int)K;
672 }
673 bool endLifetime(EvalInfo &Info, bool RunDestructors) {
674 if (RunDestructors) {
675 SourceLocation Loc;
676 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>())
677 Loc = VD->getLocation();
678 else if (const Expr *E = Base.dyn_cast<const Expr*>())
679 Loc = E->getExprLoc();
680 return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T);
681 }
682 *Value.getPointer() = APValue();
683 return true;
684 }
685
686 bool hasSideEffect() {
687 return T.isDestructedType();
688 }
689 };
690
691 /// A reference to an object whose construction we are currently evaluating.
692 struct ObjectUnderConstruction {
693 APValue::LValueBase Base;
694 ArrayRef<APValue::LValuePathEntry> Path;
695 friend bool operator==(const ObjectUnderConstruction &LHS,
696 const ObjectUnderConstruction &RHS) {
697 return LHS.Base == RHS.Base && LHS.Path == RHS.Path;
698 }
699 friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {
700 return llvm::hash_combine(Obj.Base, Obj.Path);
701 }
702 };
703 enum class ConstructionPhase {
704 None,
705 Bases,
706 AfterBases,
707 AfterFields,
708 Destroying,
709 DestroyingBases
710 };
711}
712
713namespace llvm {
714template<> struct DenseMapInfo<ObjectUnderConstruction> {
715 using Base = DenseMapInfo<APValue::LValueBase>;
716 static unsigned getHashValue(const ObjectUnderConstruction &Object) {
717 return hash_value(Object);
718 }
719 static bool isEqual(const ObjectUnderConstruction &LHS,
720 const ObjectUnderConstruction &RHS) {
721 return LHS == RHS;
722 }
723};
724}
725
726namespace {
727 /// A dynamically-allocated heap object.
728 struct DynAlloc {
729 /// The value of this heap-allocated object.
730 APValue Value;
731 /// The allocating expression; used for diagnostics. Either a CXXNewExpr
732 /// or a CallExpr (the latter is for direct calls to operator new inside
733 /// std::allocator<T>::allocate).
734 const Expr *AllocExpr = nullptr;
735
736 /// Get the kind of the allocation. This must match between allocation
737 /// and deallocation.
738 static DynAllocKind kindOfExpr(const Expr *AllocExpr) {
739 if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr))
740 return NE->isArray() ? DynAllocKind::ArrayNew : DynAllocKind::New;
741 assert(isa<CallExpr>(AllocExpr));
742 return DynAllocKind::StdAllocator;
743 }
744
745 DynAllocKind getKind() const { return kindOfExpr(AllocExpr); }
746 };
747
748 struct DynAllocOrder {
749 bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const {
750 return L.getIndex() < R.getIndex();
751 }
752 };
753
754 /// EvalInfo - This is a private struct used by the evaluator to capture
755 /// information about a subexpression as it is folded. It retains information
756 /// about the AST context, but also maintains information about the folded
757 /// expression.
758 ///
759 /// If an expression could be evaluated, it is still possible it is not a C
760 /// "integer constant expression" or constant expression. If not, this struct
761 /// captures information about how and why not.
762 ///
763 /// One bit of information passed *into* the request for constant folding
764 /// indicates whether the subexpression is "evaluated" or not according to C
765 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
766 /// evaluate the expression regardless of what the RHS is, but C only allows
767 /// certain things in certain situations.
768 class EvalInfo final : public interp::State {
769 public:
770 /// CurrentCall - The top of the constexpr call stack.
771 CallStackFrame *CurrentCall;
772
773 /// CallStackDepth - The number of calls in the call stack right now.
774 unsigned CallStackDepth;
775
776 /// NextCallIndex - The next call index to assign.
777 unsigned NextCallIndex;
778
779 /// StepsLeft - The remaining number of evaluation steps we're permitted
780 /// to perform. This is essentially a limit for the number of statements
781 /// we will evaluate.
782 unsigned StepsLeft;
783
784 /// BottomFrame - The frame in which evaluation started. This must be
785 /// initialized after CurrentCall and CallStackDepth.
786 CallStackFrame BottomFrame;
787
788 /// A stack of values whose lifetimes end at the end of some surrounding
789 /// evaluation frame.
790 llvm::SmallVector<Cleanup, 16> CleanupStack;
791
792 /// EvaluatingDecl - This is the declaration whose initializer is being
793 /// evaluated, if any.
794 APValue::LValueBase EvaluatingDecl;
795
796 enum class EvaluatingDeclKind {
797 None,
798 /// We're evaluating the construction of EvaluatingDecl.
799 Ctor,
800 /// We're evaluating the destruction of EvaluatingDecl.
801 Dtor,
802 };
803 EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None;
804
805 /// EvaluatingDeclValue - This is the value being constructed for the
806 /// declaration whose initializer is being evaluated, if any.
807 APValue *EvaluatingDeclValue;
808
809 /// Stack of loops and 'switch' statements which we're currently
810 /// breaking/continuing; null entries are used to mark unlabeled
811 /// break/continue.
812 SmallVector<const Stmt *> BreakContinueStack;
813
814 /// Set of objects that are currently being constructed.
815 llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
816 ObjectsUnderConstruction;
817
818 /// Current heap allocations, along with the location where each was
819 /// allocated. We use std::map here because we need stable addresses
820 /// for the stored APValues.
821 std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs;
822
823 /// The number of heap allocations performed so far in this evaluation.
824 uintptr_t NumHeapAllocs = 0;
825
826 struct EvaluatingConstructorRAII {
827 EvalInfo &EI;
828 ObjectUnderConstruction Object;
829 bool DidInsert;
830 EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
831 bool HasBases)
832 : EI(EI), Object(Object) {
833 DidInsert =
834 EI.ObjectsUnderConstruction
835 .insert({Object, HasBases ? ConstructionPhase::Bases
836 : ConstructionPhase::AfterBases})
837 .second;
838 }
839 void finishedConstructingBases() {
840 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
841 }
842 void finishedConstructingFields() {
843 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields;
844 }
845 ~EvaluatingConstructorRAII() {
846 if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
847 }
848 };
849
850 struct EvaluatingDestructorRAII {
851 EvalInfo &EI;
852 ObjectUnderConstruction Object;
853 bool DidInsert;
854 EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object)
855 : EI(EI), Object(Object) {
856 DidInsert = EI.ObjectsUnderConstruction
857 .insert({Object, ConstructionPhase::Destroying})
858 .second;
859 }
860 void startedDestroyingBases() {
861 EI.ObjectsUnderConstruction[Object] =
862 ConstructionPhase::DestroyingBases;
863 }
864 ~EvaluatingDestructorRAII() {
865 if (DidInsert)
866 EI.ObjectsUnderConstruction.erase(Object);
867 }
868 };
869
870 ConstructionPhase
871 isEvaluatingCtorDtor(APValue::LValueBase Base,
872 ArrayRef<APValue::LValuePathEntry> Path) {
873 return ObjectsUnderConstruction.lookup({Base, Path});
874 }
875
876 /// If we're currently speculatively evaluating, the outermost call stack
877 /// depth at which we can mutate state, otherwise 0.
878 unsigned SpeculativeEvaluationDepth = 0;
879
880 /// The current array initialization index, if we're performing array
881 /// initialization.
882 uint64_t ArrayInitIndex = -1;
883
884 EvalInfo(const ASTContext &C, SemaProxy *SProxy, Expr::EvalStatus &S,
885 EvaluationMode Mode)
886 : State(const_cast<ASTContext &>(C), SProxy, S), CurrentCall(nullptr),
887 CallStackDepth(0), NextCallIndex(1),
888 StepsLeft(C.getLangOpts().ConstexprStepLimit),
889 BottomFrame(*this, SourceLocation(), /*Callee=*/nullptr,
890 /*This=*/nullptr,
891 /*CallExpr=*/nullptr, CallRef()),
892 EvaluatingDecl((const ValueDecl *)nullptr),
893 EvaluatingDeclValue(nullptr) {
894 EvalMode = Mode;
895 }
896
897 ~EvalInfo() {
898 discardCleanups();
899 }
900
901 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value,
902 EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) {
903 EvaluatingDecl = Base;
904 IsEvaluatingDecl = EDK;
905 EvaluatingDeclValue = &Value;
906 }
907
908 bool CheckCallLimit(SourceLocation Loc) {
909 // Don't perform any constexpr calls (other than the call we're checking)
910 // when checking a potential constant expression.
911 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
912 return false;
913 if (NextCallIndex == 0) {
914 // NextCallIndex has wrapped around.
915 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
916 return false;
917 }
918 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
919 return true;
920 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
921 << getLangOpts().ConstexprCallDepth;
922 return false;
923 }
924
925 bool CheckArraySize(SourceLocation Loc, unsigned BitWidth,
926 uint64_t ElemCount, bool Diag) {
927 // FIXME: GH63562
928 // APValue stores array extents as unsigned,
929 // so anything that is greater that unsigned would overflow when
930 // constructing the array, we catch this here.
931 if (BitWidth > ConstantArrayType::getMaxSizeBits(Ctx) ||
932 ElemCount > uint64_t(std::numeric_limits<unsigned>::max())) {
933 if (Diag)
934 FFDiag(Loc, diag::note_constexpr_new_too_large) << ElemCount;
935 return false;
936 }
937
938 // FIXME: GH63562
939 // Arrays allocate an APValue per element.
940 // We use the number of constexpr steps as a proxy for the maximum size
941 // of arrays to avoid exhausting the system resources, as initialization
942 // of each element is likely to take some number of steps anyway.
943 uint64_t Limit = getLangOpts().ConstexprStepLimit;
944 if (Limit != 0 && ElemCount > Limit) {
945 if (Diag) {
946 FFDiag(Loc, diag::note_constexpr_new_exceeds_limits, 1)
947 << ElemCount << Limit;
948 Note(Loc, diag::note_constexpr_steps);
949 }
950 return false;
951 }
952 return true;
953 }
954
955 std::pair<CallStackFrame *, unsigned>
956 getCallFrameAndDepth(unsigned CallIndex) {
957 assert(CallIndex && "no call index in getCallFrameAndDepth");
958 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
959 // be null in this loop.
960 unsigned Depth = CallStackDepth;
961 CallStackFrame *Frame = CurrentCall;
962 while (Frame->Index > CallIndex) {
963 Frame = Frame->Caller;
964 --Depth;
965 }
966 if (Frame->Index == CallIndex)
967 return {Frame, Depth};
968 return {nullptr, 0};
969 }
970
971 bool nextStep(const Stmt *S) {
972 if (getLangOpts().ConstexprStepLimit == 0)
973 return true;
974
975 if (!StepsLeft) {
976 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded, 1)
977 << getLangOpts().ConstexprStepLimit;
978 Note(S->getBeginLoc(), diag::note_constexpr_steps);
979 return false;
980 }
981 --StepsLeft;
982 return true;
983 }
984
985 APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV);
986
987 std::optional<DynAlloc *> lookupDynamicAlloc(DynamicAllocLValue DA) {
988 std::optional<DynAlloc *> Result;
989 auto It = HeapAllocs.find(DA);
990 if (It != HeapAllocs.end())
991 Result = &It->second;
992 return Result;
993 }
994
995 /// Get the allocated storage for the given parameter of the given call.
996 APValue *getParamSlot(CallRef Call, const ParmVarDecl *PVD) {
997 CallStackFrame *Frame = getCallFrameAndDepth(Call.CallIndex).first;
998 return Frame ? Frame->getTemporary(Call.getOrigParam(PVD), Call.Version)
999 : nullptr;
1000 }
1001
1002 /// Information about a stack frame for std::allocator<T>::[de]allocate.
1003 struct StdAllocatorCaller {
1004 unsigned FrameIndex;
1005 QualType ElemType;
1006 const Expr *Call;
1007 explicit operator bool() const { return FrameIndex != 0; };
1008 };
1009
1010 StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const {
1011 for (const CallStackFrame *Call = CurrentCall; Call->Caller != nullptr;
1012 Call = Call->Caller) {
1013 const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee);
1014 if (!MD)
1015 continue;
1016 const IdentifierInfo *FnII = MD->getIdentifier();
1017 if (!FnII || !FnII->isStr(FnName))
1018 continue;
1019
1020 const auto *CTSD =
1021 dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent());
1022 if (!CTSD)
1023 continue;
1024
1025 const IdentifierInfo *ClassII = CTSD->getIdentifier();
1026 const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
1027 if (CTSD->isInStdNamespace() && ClassII &&
1028 ClassII->isStr("allocator") && TAL.size() >= 1 &&
1029 TAL[0].getKind() == TemplateArgument::Type)
1030 return {Call->Index, TAL[0].getAsType(), Call->CallExpr};
1031 }
1032
1033 return {};
1034 }
1035
1036 void performLifetimeExtension() {
1037 // Disable the cleanups for lifetime-extended temporaries.
1038 llvm::erase_if(CleanupStack, [](Cleanup &C) {
1039 return !C.isDestroyedAtEndOf(ScopeKind::FullExpression);
1040 });
1041 }
1042
1043 /// Throw away any remaining cleanups at the end of evaluation. If any
1044 /// cleanups would have had a side-effect, note that as an unmodeled
1045 /// side-effect and return false. Otherwise, return true.
1046 bool discardCleanups() {
1047 for (Cleanup &C : CleanupStack) {
1048 if (C.hasSideEffect() && !noteSideEffect()) {
1049 CleanupStack.clear();
1050 return false;
1051 }
1052 }
1053 CleanupStack.clear();
1054 return true;
1055 }
1056
1057 private:
1058 const interp::Frame *getCurrentFrame() override { return CurrentCall; }
1059
1060 unsigned getCallStackDepth() override { return CallStackDepth; }
1061 bool stepsLeft() const override { return StepsLeft > 0; }
1062
1063 public:
1064 /// Notes that we failed to evaluate an expression that other expressions
1065 /// directly depend on, and determine if we should keep evaluating. This
1066 /// should only be called if we actually intend to keep evaluating.
1067 ///
1068 /// Call noteSideEffect() instead if we may be able to ignore the value that
1069 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1070 ///
1071 /// (Foo(), 1) // use noteSideEffect
1072 /// (Foo() || true) // use noteSideEffect
1073 /// Foo() + 1 // use noteFailure
1074 [[nodiscard]] bool noteFailure() {
1075 // Failure when evaluating some expression often means there is some
1076 // subexpression whose evaluation was skipped. Therefore, (because we
1077 // don't track whether we skipped an expression when unwinding after an
1078 // evaluation failure) every evaluation failure that bubbles up from a
1079 // subexpression implies that a side-effect has potentially happened. We
1080 // skip setting the HasSideEffects flag to true until we decide to
1081 // continue evaluating after that point, which happens here.
1082 bool KeepGoing = keepEvaluatingAfterFailure();
1083 EvalStatus.HasSideEffects |= KeepGoing;
1084 return KeepGoing;
1085 }
1086
1087 class ArrayInitLoopIndex {
1088 EvalInfo &Info;
1089 uint64_t OuterIndex;
1090
1091 public:
1092 ArrayInitLoopIndex(EvalInfo &Info)
1093 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1094 Info.ArrayInitIndex = 0;
1095 }
1096 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1097
1098 operator uint64_t&() { return Info.ArrayInitIndex; }
1099 };
1100 };
1101
1102 /// Object used to treat all foldable expressions as constant expressions.
1103 struct FoldConstant {
1104 EvalInfo &Info;
1105 bool Enabled;
1106 bool HadNoPriorDiags;
1107 EvaluationMode OldMode;
1108
1109 explicit FoldConstant(EvalInfo &Info, bool Enabled)
1110 : Info(Info),
1111 Enabled(Enabled),
1112 HadNoPriorDiags(Info.EvalStatus.Diag &&
1113 Info.EvalStatus.Diag->empty() &&
1114 !Info.EvalStatus.HasSideEffects),
1115 OldMode(Info.EvalMode) {
1116 if (Enabled)
1117 Info.EvalMode = EvaluationMode::ConstantFold;
1118 }
1119 void keepDiagnostics() { Enabled = false; }
1120 ~FoldConstant() {
1121 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
1122 !Info.EvalStatus.HasSideEffects) {
1123 Info.EvalStatus.Diag->clear();
1124 Info.EvalStatus.DiagEmitted = false;
1125 }
1126 Info.EvalMode = OldMode;
1127 }
1128 };
1129
1130 /// RAII object used to set the current evaluation mode to ignore
1131 /// side-effects.
1132 struct IgnoreSideEffectsRAII {
1133 EvalInfo &Info;
1134 EvaluationMode OldMode;
1135 explicit IgnoreSideEffectsRAII(EvalInfo &Info)
1136 : Info(Info), OldMode(Info.EvalMode) {
1137 Info.EvalMode = EvaluationMode::IgnoreSideEffects;
1138 }
1139
1140 ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
1141 };
1142
1143 /// RAII object used to optionally suppress diagnostics and side-effects from
1144 /// a speculative evaluation.
1145 class SpeculativeEvaluationRAII {
1146 EvalInfo *Info = nullptr;
1147 Expr::EvalStatus OldStatus;
1148 unsigned OldSpeculativeEvaluationDepth = 0;
1149
1150 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1151 Info = Other.Info;
1152 OldStatus = Other.OldStatus;
1153 OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
1154 Other.Info = nullptr;
1155 }
1156
1157 void maybeRestoreState() {
1158 if (!Info)
1159 return;
1160
1161 Info->EvalStatus = OldStatus;
1162 Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
1163 }
1164
1165 public:
1166 SpeculativeEvaluationRAII() = default;
1167
1168 SpeculativeEvaluationRAII(
1169 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1170 : Info(&Info), OldStatus(Info.EvalStatus),
1171 OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
1172 Info.EvalStatus.Diag = NewDiag;
1173 Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
1174 }
1175
1176 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1177 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1178 moveFromAndCancel(std::move(Other));
1179 }
1180
1181 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1182 maybeRestoreState();
1183 moveFromAndCancel(std::move(Other));
1184 return *this;
1185 }
1186
1187 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1188 };
1189
1190 /// RAII object wrapping a full-expression or block scope, and handling
1191 /// the ending of the lifetime of temporaries created within it.
1192 template<ScopeKind Kind>
1193 class ScopeRAII {
1194 EvalInfo &Info;
1195 unsigned OldStackSize;
1196 public:
1197 ScopeRAII(EvalInfo &Info)
1198 : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1199 // Push a new temporary version. This is needed to distinguish between
1200 // temporaries created in different iterations of a loop.
1201 Info.CurrentCall->pushTempVersion();
1202 }
1203 bool destroy(bool RunDestructors = true) {
1204 bool OK = cleanup(Info, RunDestructors, OldStackSize);
1205 OldStackSize = std::numeric_limits<unsigned>::max();
1206 return OK;
1207 }
1208 ~ScopeRAII() {
1209 if (OldStackSize != std::numeric_limits<unsigned>::max())
1210 destroy(false);
1211 // Body moved to a static method to encourage the compiler to inline away
1212 // instances of this class.
1213 Info.CurrentCall->popTempVersion();
1214 }
1215 private:
1216 static bool cleanup(EvalInfo &Info, bool RunDestructors,
1217 unsigned OldStackSize) {
1218 assert(OldStackSize <= Info.CleanupStack.size() &&
1219 "running cleanups out of order?");
1220
1221 // Run all cleanups for a block scope, and non-lifetime-extended cleanups
1222 // for a full-expression scope.
1223 bool Success = true;
1224 for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) {
1225 if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) {
1226 if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) {
1227 Success = false;
1228 break;
1229 }
1230 }
1231 }
1232
1233 // Compact any retained cleanups.
1234 auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
1235 if (Kind != ScopeKind::Block)
1236 NewEnd =
1237 std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) {
1238 return C.isDestroyedAtEndOf(Kind);
1239 });
1240 Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
1241 return Success;
1242 }
1243 };
1244 typedef ScopeRAII<ScopeKind::Block> BlockScopeRAII;
1245 typedef ScopeRAII<ScopeKind::FullExpression> FullExpressionRAII;
1246 typedef ScopeRAII<ScopeKind::Call> CallScopeRAII;
1247}
1248
1249bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1250 CheckSubobjectKind CSK) {
1251 if (Invalid)
1252 return false;
1253 if (isOnePastTheEnd()) {
1254 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1255 << CSK;
1256 setInvalid();
1257 return false;
1258 }
1259 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1260 // must actually be at least one array element; even a VLA cannot have a
1261 // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1262 return true;
1263}
1264
1265void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1266 const Expr *E) {
1267 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1268 // Do not set the designator as invalid: we can represent this situation,
1269 // and correct handling of __builtin_object_size requires us to do so.
1270}
1271
1272void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1273 const Expr *E,
1274 const APSInt &N) {
1275 // If we're complaining, we must be able to statically determine the size of
1276 // the most derived array.
1277 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1278 Info.CCEDiag(E, diag::note_constexpr_array_index)
1279 << N << /*array*/ 0
1280 << static_cast<unsigned>(getMostDerivedArraySize());
1281 else
1282 Info.CCEDiag(E, diag::note_constexpr_array_index)
1283 << N << /*non-array*/ 1;
1284 setInvalid();
1285}
1286
1287CallStackFrame::CallStackFrame(EvalInfo &Info, SourceRange CallRange,
1288 const FunctionDecl *Callee, const LValue *This,
1289 const Expr *CallExpr, CallRef Call)
1290 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1291 CallExpr(CallExpr), Arguments(Call), CallRange(CallRange),
1292 Index(Info.NextCallIndex++) {
1293 Info.CurrentCall = this;
1294 ++Info.CallStackDepth;
1295}
1296
1297CallStackFrame::~CallStackFrame() {
1298 assert(Info.CurrentCall == this && "calls retired out of order");
1299 --Info.CallStackDepth;
1300 Info.CurrentCall = Caller;
1301}
1302
1303static bool isRead(AccessKinds AK) {
1304 return AK == AK_Read || AK == AK_ReadObjectRepresentation ||
1305 AK == AK_IsWithinLifetime || AK == AK_Dereference;
1306}
1307
1309 switch (AK) {
1310 case AK_Read:
1312 case AK_MemberCall:
1313 case AK_DynamicCast:
1314 case AK_TypeId:
1316 case AK_Dereference:
1317 return false;
1318 case AK_Assign:
1319 case AK_Increment:
1320 case AK_Decrement:
1321 case AK_Construct:
1322 case AK_Destroy:
1323 return true;
1324 }
1325 llvm_unreachable("unknown access kind");
1326}
1327
1328static bool isAnyAccess(AccessKinds AK) {
1329 return isRead(AK) || isModification(AK);
1330}
1331
1332/// Is this an access per the C++ definition?
1334 return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy &&
1335 AK != AK_IsWithinLifetime && AK != AK_Dereference;
1336}
1337
1338/// Is this kind of access valid on an indeterminate object value?
1340 switch (AK) {
1341 case AK_Read:
1342 case AK_Increment:
1343 case AK_Decrement:
1344 case AK_Dereference:
1345 // These need the object's value.
1346 return false;
1347
1350 case AK_Assign:
1351 case AK_Construct:
1352 case AK_Destroy:
1353 // Construction and destruction don't need the value.
1354 return true;
1355
1356 case AK_MemberCall:
1357 case AK_DynamicCast:
1358 case AK_TypeId:
1359 // These aren't really meaningful on scalars.
1360 return true;
1361 }
1362 llvm_unreachable("unknown access kind");
1363}
1364
1365namespace {
1366 struct ComplexValue {
1367 private:
1368 bool IsInt;
1369
1370 public:
1371 APSInt IntReal, IntImag;
1372 APFloat FloatReal, FloatImag;
1373
1374 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1375
1376 void makeComplexFloat() { IsInt = false; }
1377 bool isComplexFloat() const { return !IsInt; }
1378 APFloat &getComplexFloatReal() { return FloatReal; }
1379 APFloat &getComplexFloatImag() { return FloatImag; }
1380
1381 void makeComplexInt() { IsInt = true; }
1382 bool isComplexInt() const { return IsInt; }
1383 APSInt &getComplexIntReal() { return IntReal; }
1384 APSInt &getComplexIntImag() { return IntImag; }
1385
1386 void moveInto(APValue &v) const {
1387 if (isComplexFloat())
1388 v = APValue(FloatReal, FloatImag);
1389 else
1390 v = APValue(IntReal, IntImag);
1391 }
1392 void setFrom(const APValue &v) {
1393 assert(v.isComplexFloat() || v.isComplexInt());
1394 if (v.isComplexFloat()) {
1395 makeComplexFloat();
1396 FloatReal = v.getComplexFloatReal();
1397 FloatImag = v.getComplexFloatImag();
1398 } else {
1399 makeComplexInt();
1400 IntReal = v.getComplexIntReal();
1401 IntImag = v.getComplexIntImag();
1402 }
1403 }
1404 };
1405
1406 struct LValue {
1407 APValue::LValueBase Base;
1408 CharUnits Offset;
1409 SubobjectDesignator Designator;
1410 bool IsNullPtr : 1;
1411 bool InvalidBase : 1;
1412 // P2280R4 track if we have an unknown reference or pointer.
1413 bool AllowConstexprUnknown = false;
1414
1415 const APValue::LValueBase getLValueBase() const { return Base; }
1416 bool allowConstexprUnknown() const { return AllowConstexprUnknown; }
1417 CharUnits &getLValueOffset() { return Offset; }
1418 CharUnits getLValueOffset() const { return Offset; }
1419 SubobjectDesignator &getLValueDesignator() { return Designator; }
1420 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1421 bool isNullPointer() const { return IsNullPtr;}
1422
1423 unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1424 unsigned getLValueVersion() const { return Base.getVersion(); }
1425
1426 bool pointsToCompleteClass(const CXXRecordDecl *D) const {
1427 if (Designator.Entries.empty())
1428 return true;
1429
1430 return Designator.MostDerivedType->getAsCXXRecordDecl() == D;
1431 }
1432
1433 void moveInto(APValue &V) const {
1434 if (Designator.Invalid)
1435 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
1436 else {
1437 assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1438 V = APValue(Base, Offset, Designator.Entries,
1439 Designator.IsOnePastTheEnd, IsNullPtr);
1440 }
1441 if (AllowConstexprUnknown)
1442 V.setConstexprUnknown();
1443 }
1444 void setFrom(const ASTContext &Ctx, const APValue &V) {
1445 assert(V.isLValue() && "Setting LValue from a non-LValue?");
1446 Base = V.getLValueBase();
1447 Offset = V.getLValueOffset();
1448 InvalidBase = false;
1449 Designator = SubobjectDesignator(Ctx, V);
1450 IsNullPtr = V.isNullPointer();
1451 AllowConstexprUnknown = V.allowConstexprUnknown();
1452 }
1453
1454 void set(APValue::LValueBase B, bool BInvalid = false) {
1455#ifndef NDEBUG
1456 // We only allow a few types of invalid bases. Enforce that here.
1457 if (BInvalid) {
1458 const auto *E = B.get<const Expr *>();
1459 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1460 "Unexpected type of invalid base");
1461 }
1462#endif
1463
1464 Base = B;
1465 Offset = CharUnits::fromQuantity(0);
1466 InvalidBase = BInvalid;
1467 Designator = SubobjectDesignator(getType(B));
1468 IsNullPtr = false;
1469 AllowConstexprUnknown = false;
1470 }
1471
1472 void setNull(ASTContext &Ctx, QualType PointerTy) {
1473 Base = (const ValueDecl *)nullptr;
1474 Offset =
1476 InvalidBase = false;
1477 Designator = SubobjectDesignator(PointerTy->getPointeeType());
1478 IsNullPtr = true;
1479 AllowConstexprUnknown = false;
1480 }
1481
1482 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1483 set(B, true);
1484 }
1485
1486 std::string toString(ASTContext &Ctx, QualType T) const {
1487 APValue Printable;
1488 moveInto(Printable);
1489 return Printable.getAsString(Ctx, T);
1490 }
1491
1492 private:
1493 // Check that this LValue is not based on a null pointer. If it is, produce
1494 // a diagnostic and mark the designator as invalid.
1495 template <typename GenDiagType>
1496 bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
1497 if (Designator.Invalid)
1498 return false;
1499 if (IsNullPtr) {
1500 GenDiag();
1501 Designator.setInvalid();
1502 return false;
1503 }
1504 return true;
1505 }
1506
1507 public:
1508 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1509 CheckSubobjectKind CSK) {
1510 return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1511 Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1512 });
1513 }
1514
1515 bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1516 AccessKinds AK) {
1517 return checkNullPointerDiagnosingWith([&Info, E, AK] {
1518 if (AK == AccessKinds::AK_Dereference)
1519 Info.FFDiag(E, diag::note_constexpr_dereferencing_null);
1520 else
1521 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1522 });
1523 }
1524
1525 // Check this LValue refers to an object. If not, set the designator to be
1526 // invalid and emit a diagnostic.
1527 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1528 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1529 Designator.checkSubobject(Info, E, CSK);
1530 }
1531
1532 void addDecl(EvalInfo &Info, const Expr *E,
1533 const Decl *D, bool Virtual = false) {
1534 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1535 Designator.addDeclUnchecked(D, Virtual);
1536 }
1537 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1538 if (!Designator.Entries.empty()) {
1539 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1540 Designator.setInvalid();
1541 return;
1542 }
1543 if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1544 assert(!Base || getType(Base).getNonReferenceType()->isPointerType() ||
1545 getType(Base).getNonReferenceType()->isArrayType());
1546 Designator.FirstEntryIsAnUnsizedArray = true;
1547 Designator.addUnsizedArrayUnchecked(ElemTy);
1548 }
1549 }
1550 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1551 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1552 Designator.addArrayUnchecked(CAT);
1553 }
1554 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1555 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1556 Designator.addComplexUnchecked(EltTy, Imag);
1557 }
1558 void addVectorElement(EvalInfo &Info, const Expr *E, QualType EltTy,
1559 uint64_t Size, uint64_t Idx) {
1560 if (checkSubobject(Info, E, CSK_VectorElement))
1561 Designator.addVectorElementUnchecked(EltTy, Size, Idx);
1562 }
1563 void clearIsNullPointer() {
1564 IsNullPtr = false;
1565 }
1566 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1567 const APSInt &Index, CharUnits ElementSize) {
1568 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1569 // but we're not required to diagnose it and it's valid in C++.)
1570 if (!Index)
1571 return;
1572
1573 // Compute the new offset in the appropriate width, wrapping at 64 bits.
1574 // FIXME: When compiling for a 32-bit target, we should use 32-bit
1575 // offsets.
1576 uint64_t Offset64 = Offset.getQuantity();
1577 uint64_t ElemSize64 = ElementSize.getQuantity();
1578 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1579 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1580
1581 if (checkNullPointer(Info, E, CSK_ArrayIndex))
1582 Designator.adjustIndex(Info, E, Index, *this);
1583 clearIsNullPointer();
1584 }
1585 void adjustOffset(CharUnits N) {
1586 Offset += N;
1587 if (N.getQuantity())
1588 clearIsNullPointer();
1589 }
1590 };
1591
1592 struct MemberPtr {
1593 MemberPtr() {}
1594 explicit MemberPtr(const ValueDecl *Decl)
1595 : DeclAndIsDerivedMember(Decl, false) {}
1596
1597 /// The member or (direct or indirect) field referred to by this member
1598 /// pointer, or 0 if this is a null member pointer.
1599 const ValueDecl *getDecl() const {
1600 return DeclAndIsDerivedMember.getPointer();
1601 }
1602 /// Is this actually a member of some type derived from the relevant class?
1603 bool isDerivedMember() const {
1604 return DeclAndIsDerivedMember.getInt();
1605 }
1606 /// Get the class which the declaration actually lives in.
1607 const CXXRecordDecl *getContainingRecord() const {
1608 return cast<CXXRecordDecl>(
1609 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1610 }
1611
1612 void moveInto(APValue &V) const {
1613 V = APValue(getDecl(), isDerivedMember(), Path);
1614 }
1615 void setFrom(const APValue &V) {
1616 assert(V.isMemberPointer());
1617 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1618 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1619 Path.clear();
1620 llvm::append_range(Path, V.getMemberPointerPath());
1621 }
1622
1623 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1624 /// whether the member is a member of some class derived from the class type
1625 /// of the member pointer.
1626 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1627 /// Path - The path of base/derived classes from the member declaration's
1628 /// class (exclusive) to the class type of the member pointer (inclusive).
1629 SmallVector<const CXXRecordDecl*, 4> Path;
1630
1631 /// Perform a cast towards the class of the Decl (either up or down the
1632 /// hierarchy).
1633 bool castBack(const CXXRecordDecl *Class) {
1634 assert(!Path.empty());
1635 const CXXRecordDecl *Expected;
1636 if (Path.size() >= 2)
1637 Expected = Path[Path.size() - 2];
1638 else
1639 Expected = getContainingRecord();
1640 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1641 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1642 // if B does not contain the original member and is not a base or
1643 // derived class of the class containing the original member, the result
1644 // of the cast is undefined.
1645 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1646 // (D::*). We consider that to be a language defect.
1647 return false;
1648 }
1649 Path.pop_back();
1650 return true;
1651 }
1652 /// Perform a base-to-derived member pointer cast.
1653 bool castToDerived(const CXXRecordDecl *Derived) {
1654 if (!getDecl())
1655 return true;
1656 if (!isDerivedMember()) {
1657 Path.push_back(Derived);
1658 return true;
1659 }
1660 if (!castBack(Derived))
1661 return false;
1662 if (Path.empty())
1663 DeclAndIsDerivedMember.setInt(false);
1664 return true;
1665 }
1666 /// Perform a derived-to-base member pointer cast.
1667 bool castToBase(const CXXRecordDecl *Base) {
1668 if (!getDecl())
1669 return true;
1670 if (Path.empty())
1671 DeclAndIsDerivedMember.setInt(true);
1672 if (isDerivedMember()) {
1673 Path.push_back(Base);
1674 return true;
1675 }
1676 return castBack(Base);
1677 }
1678 };
1679
1680 /// Compare two member pointers, which are assumed to be of the same type.
1681 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1682 if (!LHS.getDecl() || !RHS.getDecl())
1683 return !LHS.getDecl() && !RHS.getDecl();
1684 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1685 return false;
1686 return LHS.Path == RHS.Path;
1687 }
1688}
1689
1690void SubobjectDesignator::adjustIndex(EvalInfo &Info, const Expr *E, APSInt N,
1691 const LValue &LV) {
1692 if (Invalid || !N)
1693 return;
1694 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
1695 if (isMostDerivedAnUnsizedArray()) {
1696 diagnoseUnsizedArrayPointerArithmetic(Info, E);
1697 // Can't verify -- trust that the user is doing the right thing (or if
1698 // not, trust that the caller will catch the bad behavior).
1699 // FIXME: Should we reject if this overflows, at least?
1700 Entries.back() =
1701 PathEntry::ArrayIndex(Entries.back().getAsArrayIndex() + TruncatedN);
1702 return;
1703 }
1704
1705 // [expr.add]p4: For the purposes of these operators, a pointer to a
1706 // nonarray object behaves the same as a pointer to the first element of
1707 // an array of length one with the type of the object as its element type.
1708 bool IsArray =
1709 MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement;
1710 uint64_t ArrayIndex =
1711 IsArray ? Entries.back().getAsArrayIndex() : (uint64_t)IsOnePastTheEnd;
1712 uint64_t ArraySize = IsArray ? getMostDerivedArraySize() : (uint64_t)1;
1713
1714 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
1715 if (!Info.checkingPotentialConstantExpression() ||
1716 !LV.AllowConstexprUnknown) {
1717 // Calculate the actual index in a wide enough type, so we can include
1718 // it in the note.
1719 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
1720 (llvm::APInt &)N += ArrayIndex;
1721 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
1722 diagnosePointerArithmetic(Info, E, N);
1723 }
1724 setInvalid();
1725 return;
1726 }
1727
1728 ArrayIndex += TruncatedN;
1729 assert(ArrayIndex <= ArraySize &&
1730 "bounds check succeeded for out-of-bounds index");
1731
1732 if (IsArray)
1733 Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
1734 else
1735 IsOnePastTheEnd = (ArrayIndex != 0);
1736}
1737
1738static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1739static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1740 const LValue &This, const Expr *E,
1741 bool AllowNonLiteralTypes = false);
1742static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1743 bool InvalidBaseOK = false);
1744static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1745 bool InvalidBaseOK = false);
1746static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1747 EvalInfo &Info);
1748static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1749static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1750static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1751 EvalInfo &Info);
1752static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1753static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1754static bool EvaluateMatrix(const Expr *E, APValue &Result, EvalInfo &Info);
1755static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1756 EvalInfo &Info);
1757static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1758static std::optional<uint64_t>
1759EvaluateBuiltinStrLen(const Expr *E, EvalInfo &Info,
1760 std::string *StringResult = nullptr);
1761
1762/// Evaluate an integer or fixed point expression into an APResult.
1763static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1764 EvalInfo &Info);
1765
1766/// Evaluate only a fixed point expression into an APResult.
1767static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1768 EvalInfo &Info);
1769
1770//===----------------------------------------------------------------------===//
1771// Misc utilities
1772//===----------------------------------------------------------------------===//
1773
1774/// Negate an APSInt in place, converting it to a signed form if necessary, and
1775/// preserving its value (by extending by up to one bit as needed).
1777 if (Int.isUnsigned() || Int.isMinSignedValue()) {
1778 Int = Int.extend(Int.getBitWidth() + 1);
1779 Int.setIsSigned(true);
1780 }
1781 Int = -Int;
1782}
1783
1784template<typename KeyT>
1785APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T,
1786 ScopeKind Scope, LValue &LV) {
1787 unsigned Version = getTempVersion();
1788 APValue::LValueBase Base(Key, Index, Version);
1789 LV.set(Base);
1790 return createLocal(Base, Key, T, Scope);
1791}
1792
1793/// Allocate storage for a parameter of a function call made in this frame.
1794APValue &CallStackFrame::createParam(CallRef Args, const ParmVarDecl *PVD,
1795 LValue &LV) {
1796 assert(Args.CallIndex == Index && "creating parameter in wrong frame");
1797 APValue::LValueBase Base(PVD, Index, Args.Version);
1798 LV.set(Base);
1799 // We always destroy parameters at the end of the call, even if we'd allow
1800 // them to live to the end of the full-expression at runtime, in order to
1801 // give portable results and match other compilers.
1802 return createLocal(Base, PVD, PVD->getType(), ScopeKind::Call);
1803}
1804
1805APValue &CallStackFrame::createLocal(APValue::LValueBase Base, const void *Key,
1806 QualType T, ScopeKind Scope) {
1807 assert(Base.getCallIndex() == Index && "lvalue for wrong frame");
1808 unsigned Version = Base.getVersion();
1809 APValue &Result = Temporaries[MapKeyTy(Key, Version)];
1810 assert(Result.isAbsent() && "local created multiple times");
1811
1812 // If we're creating a local immediately in the operand of a speculative
1813 // evaluation, don't register a cleanup to be run outside the speculative
1814 // evaluation context, since we won't actually be able to initialize this
1815 // object.
1816 if (Index <= Info.SpeculativeEvaluationDepth) {
1817 if (T.isDestructedType())
1818 Info.noteSideEffect();
1819 } else {
1820 Info.CleanupStack.push_back(Cleanup(&Result, Base, T, Scope));
1821 }
1822 return Result;
1823}
1824
1826 QualType AllocType,
1827 DynAllocKind AllocKind) {
1828 assert((AllocKind != DynAllocKind::None) &&
1829 "should only be called on dynamically allocated blocks");
1830 assert((AllocKind != DynAllocKind::BuiltinOperatorNew) &&
1831 "__builtin_operator_new should have been allowed only from "
1832 "std::allocator::allocate");
1833
1834 const TargetInfo &TI = Ctx.getTargetInfo();
1835 uint64_t DefaultNewAlign = TI.getNewAlign();
1836
1837 uint64_t TypeAlignment = Ctx.getTypeAlign(AllocType);
1838 assert(TypeAlignment > 0 && "Unknown alignment for allocated type!");
1839
1840 uint64_t AllocSize = Ctx.getTypeSize(AllocType);
1841
1842 if (AllocSize == 0) {
1843 switch (AllocKind) {
1844 // Allocating a zero-sized array is allowed, however it doesn't have
1845 // any alignment guarantees.
1848 return CharUnits::One();
1849
1850 // Flexible array members are allowed as only member as an extension.
1851 // In this case the size of the type will be zero, but the allocation
1852 // should still be suitable for the array element type.
1853 case DynAllocKind::New:
1855
1856 default:
1857 llvm_unreachable("Unhandled DynAllocKind");
1858 }
1859 }
1860
1861 assert(TypeAlignment <= AllocSize && "Invalid alignment/size for type!");
1862 assert(AllocSize % TypeAlignment == 0 && "Invalid alignment/size for type!");
1863
1864 // For new-extended alignment the ::operator new overload with
1865 // std::align_val_t parameter is used. According to C++
1866 // [basic.stc.dynamic.allocation]p3.1 this overload returns memory
1867 // according to the requested alignment. No stricter guarantees are
1868 // made.
1869 if (TypeAlignment > DefaultNewAlign)
1871
1872 switch (AllocKind) {
1873 // According to C++ [allocator.members]p5 it is unspecified how the
1874 // memory obtained from ::operator new is used by
1875 // std::allocator::allocate, therefore be conservative here.
1878
1879 // The non-array form of new does not permit allocation overhead and
1880 // therefore provides alignment as guaranteed by ::operator new.
1881 // According to C++ [basic.stc.dynamic.allocation]p3.3 the allocation
1882 // is suitably aligned for all objects without new-extended alignment
1883 // with the exact size of the allocation. An object of the exact size
1884 // AllocSize can have alignment of at most the lowest bit set in
1885 // AllocSize.
1886 case DynAllocKind::New:
1887 return Ctx.toCharUnitsFromBits(
1888 std::min(DefaultNewAlign, uint64_t(1) << llvm::countr_zero(AllocSize)));
1889
1891 const Type *ET = AllocType.getTypePtr()
1894 .getTypePtr();
1895 // According to C++ [expr.new]p17, unless the element type of an
1896 // array new expression is char, unsigned char or std::byte, the
1897 // allocation may be offset into the allocation returned by
1898 // ::operator new[]. Therefore no stricter alignment than the type's
1899 // alignment is guaranteed. For char, unsigned char and std::byte
1900 if (!ET->isSpecificBuiltinType(BuiltinType::UChar) &&
1901 !ET->isSpecificBuiltinType(BuiltinType::Char_U) &&
1902 !ET->isSpecificBuiltinType(BuiltinType::Char_S) && !ET->isStdByteType())
1904
1905 // Otherwise, the allocation is offset from the result of ::operator
1906 // new[] by a multiple of the strictest fundamental alignment.
1907 // According C++ [basic.stc.dynamic.allocation]p3.2 the allocation
1908 // returned by ::operator new[] is suitably aligned for all objects
1909 // without new-extended alignment and size up to the allocated size.
1910 uint64_t MaxFundamentalAlign =
1911 std::max(TI.getLongLongAlign(), TI.getLongDoubleAlign());
1912 return Ctx.toCharUnitsFromBits(std::min(
1913 {DefaultNewAlign, MaxFundamentalAlign, llvm::bit_floor(AllocSize)}));
1914 }
1915
1916 default:
1917 llvm_unreachable("Unhandled DynAllocKind");
1918 }
1919}
1920
1921APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) {
1922 if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) {
1923 FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded);
1924 return nullptr;
1925 }
1926
1927 DynamicAllocLValue DA(NumHeapAllocs++, DynAlloc::kindOfExpr(E));
1929 auto Result = HeapAllocs.emplace(std::piecewise_construct,
1930 std::forward_as_tuple(DA), std::tuple<>());
1931 assert(Result.second && "reused a heap alloc index?");
1932 Result.first->second.AllocExpr = E;
1933 return &Result.first->second.Value;
1934}
1935
1936/// Produce a string describing the given constexpr call.
1937void CallStackFrame::describe(raw_ostream &Out) const {
1938 bool IsMemberCall = false;
1939 bool ExplicitInstanceParam = false;
1940 clang::PrintingPolicy PrintingPolicy = Info.Ctx.getPrintingPolicy();
1941 PrintingPolicy.SuppressLambdaBody = true;
1942
1943 if (const auto *MD = dyn_cast<CXXMethodDecl>(Callee)) {
1944 IsMemberCall = !isa<CXXConstructorDecl>(MD) && !MD->isStatic();
1945 ExplicitInstanceParam = MD->isExplicitObjectMemberFunction();
1946 }
1947
1948 if (!IsMemberCall)
1949 Callee->getNameForDiagnostic(Out, PrintingPolicy,
1950 /*Qualified=*/false);
1951
1952 if (This && IsMemberCall) {
1953 if (const auto *MCE = dyn_cast_if_present<CXXMemberCallExpr>(CallExpr)) {
1954 const Expr *Object = MCE->getImplicitObjectArgument();
1955 Object->printPretty(Out, /*Helper=*/nullptr, PrintingPolicy,
1956 /*Indentation=*/0);
1957 if (Object->getType()->isPointerType())
1958 Out << "->";
1959 else
1960 Out << ".";
1961 } else if (const auto *OCE =
1962 dyn_cast_if_present<CXXOperatorCallExpr>(CallExpr)) {
1963 OCE->getArg(0)->printPretty(Out, /*Helper=*/nullptr, PrintingPolicy,
1964 /*Indentation=*/0);
1965 Out << ".";
1966 } else {
1967 APValue Val;
1968 This->moveInto(Val);
1969 Val.printPretty(
1970 Out, Info.Ctx,
1971 Info.Ctx.getLValueReferenceType(This->Designator.MostDerivedType));
1972 Out << ".";
1973 }
1974 Callee->getNameForDiagnostic(Out, PrintingPolicy,
1975 /*Qualified=*/false);
1976 }
1977
1978 Out << '(';
1979
1980 llvm::ListSeparator Comma;
1981 for (const ParmVarDecl *Param :
1982 Callee->parameters().slice(ExplicitInstanceParam)) {
1983 Out << Comma;
1984 const APValue *V = Info.getParamSlot(Arguments, Param);
1985 if (V)
1986 V->printPretty(Out, Info.Ctx, Param->getType());
1987 else
1988 Out << "<...>";
1989 }
1990
1991 Out << ')';
1992}
1993
1994/// Evaluate an expression to see if it had side-effects, and discard its
1995/// result.
1996/// \return \c true if the caller should keep evaluating.
1997static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
1998 assert(!E->isValueDependent());
1999 APValue Scratch;
2000 if (!Evaluate(Scratch, Info, E))
2001 // We don't need the value, but we might have skipped a side effect here.
2002 return Info.noteSideEffect();
2003 return true;
2004}
2005
2006static bool IsOpaqueConstantCall(const LValue &LVal) {
2007 const auto *BaseExpr =
2008 llvm::dyn_cast_if_present<CallExpr>(LVal.Base.dyn_cast<const Expr *>());
2009 return BaseExpr && isOpaqueConstantCall(BaseExpr);
2010}
2011
2013 if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>())
2014 return true;
2015
2016 return isGlobalLValue(B.dyn_cast<const ValueDecl *>(),
2017 B.dyn_cast<const Expr *>());
2018}
2019
2020bool isGlobalLValue(const ValueDecl *D, const Expr *E) {
2021 // C++11 [expr.const]p3 An address constant expression is a prvalue core
2022 // constant expression of pointer type that evaluates to...
2023
2024 // ... a null pointer value, or a prvalue core constant expression of type
2025 // std::nullptr_t.
2026 if (!D && !E)
2027 return true;
2028
2029 if (D) {
2030 // ... the address of an object with static storage duration,
2031 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
2032 return VD->hasGlobalStorage();
2034 return true;
2035 // ... the address of a function,
2036 // ... the address of a GUID [MS extension],
2037 // ... the address of an unnamed global constant
2039 }
2040
2041 assert(E);
2042
2043 switch (E->getStmtClass()) {
2044 default:
2045 return false;
2046 case Expr::CompoundLiteralExprClass: {
2048 return CLE->isFileScope() && CLE->isLValue();
2049 }
2050 case Expr::MaterializeTemporaryExprClass:
2051 // A materialized temporary might have been lifetime-extended to static
2052 // storage duration.
2053 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
2054 // A string literal has static storage duration.
2055 case Expr::StringLiteralClass:
2056 case Expr::PredefinedExprClass:
2057 case Expr::ObjCStringLiteralClass:
2058 case Expr::ObjCEncodeExprClass:
2059 return true;
2060 case Expr::ObjCBoxedExprClass:
2061 case Expr::ObjCArrayLiteralClass:
2062 case Expr::ObjCDictionaryLiteralClass:
2063 return cast<ObjCObjectLiteral>(E)->isExpressibleAsConstantInitializer();
2064 case Expr::CallExprClass:
2066 // For GCC compatibility, &&label has static storage duration.
2067 case Expr::AddrLabelExprClass:
2068 return true;
2069 // A Block literal expression may be used as the initialization value for
2070 // Block variables at global or local static scope.
2071 case Expr::BlockExprClass:
2072 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
2073 // The APValue generated from a __builtin_source_location will be emitted as a
2074 // literal.
2075 case Expr::SourceLocExprClass:
2076 return true;
2077 case Expr::ImplicitValueInitExprClass:
2078 // FIXME:
2079 // We can never form an lvalue with an implicit value initialization as its
2080 // base through expression evaluation, so these only appear in one case: the
2081 // implicit variable declaration we invent when checking whether a constexpr
2082 // constructor can produce a constant expression. We must assume that such
2083 // an expression might be a global lvalue.
2084 return true;
2085 }
2086
2087 llvm_unreachable("Unhandled stmt kind in switch with default?");
2088}
2089
2090static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
2091 return LVal.Base.dyn_cast<const ValueDecl*>();
2092}
2093
2094// Information about an LValueBase that is some kind of string.
2097 StringRef Bytes;
2099};
2100
2101// Gets the lvalue base of LVal as a string.
2102static bool GetLValueBaseAsString(const EvalInfo &Info, const LValue &LVal,
2103 LValueBaseString &AsString) {
2104 const auto *BaseExpr = LVal.Base.dyn_cast<const Expr *>();
2105 if (!BaseExpr)
2106 return false;
2107
2108 // For ObjCEncodeExpr, we need to compute and store the string.
2109 if (const auto *EE = dyn_cast<ObjCEncodeExpr>(BaseExpr)) {
2110 Info.Ctx.getObjCEncodingForType(EE->getEncodedType(),
2111 AsString.ObjCEncodeStorage);
2112 AsString.Bytes = AsString.ObjCEncodeStorage;
2113 AsString.CharWidth = 1;
2114 return true;
2115 }
2116
2117 // Otherwise, we have a StringLiteral.
2118 const auto *Lit = dyn_cast<StringLiteral>(BaseExpr);
2119 if (const auto *PE = dyn_cast<PredefinedExpr>(BaseExpr))
2120 Lit = PE->getFunctionName();
2121
2122 if (!Lit)
2123 return false;
2124
2125 AsString.Bytes = Lit->getBytes();
2126 AsString.CharWidth = Lit->getCharByteWidth();
2127 return true;
2128}
2129
2130// Determine whether two string literals potentially overlap. This will be the
2131// case if they agree on the values of all the bytes on the overlapping region
2132// between them.
2133//
2134// The overlapping region is the portion of the two string literals that must
2135// overlap in memory if the pointers actually point to the same address at
2136// runtime. For example, if LHS is "abcdef" + 3 and RHS is "cdef\0gh" + 1 then
2137// the overlapping region is "cdef\0", which in this case does agree, so the
2138// strings are potentially overlapping. Conversely, for "foobar" + 3 versus
2139// "bazbar" + 3, the overlapping region contains all of both strings, so they
2140// are not potentially overlapping, even though they agree from the given
2141// addresses onwards.
2142//
2143// See open core issue CWG2765 which is discussing the desired rule here.
2144static bool ArePotentiallyOverlappingStringLiterals(const EvalInfo &Info,
2145 const LValue &LHS,
2146 const LValue &RHS) {
2147 LValueBaseString LHSString, RHSString;
2148 if (!GetLValueBaseAsString(Info, LHS, LHSString) ||
2149 !GetLValueBaseAsString(Info, RHS, RHSString))
2150 return false;
2151
2152 // This is the byte offset to the location of the first character of LHS
2153 // within RHS. We don't need to look at the characters of one string that
2154 // would appear before the start of the other string if they were merged.
2155 CharUnits Offset = RHS.Offset - LHS.Offset;
2156 if (Offset.isNegative()) {
2157 if (LHSString.Bytes.size() < (size_t)-Offset.getQuantity())
2158 return false;
2159 LHSString.Bytes = LHSString.Bytes.drop_front(-Offset.getQuantity());
2160 } else {
2161 if (RHSString.Bytes.size() < (size_t)Offset.getQuantity())
2162 return false;
2163 RHSString.Bytes = RHSString.Bytes.drop_front(Offset.getQuantity());
2164 }
2165
2166 bool LHSIsLonger = LHSString.Bytes.size() > RHSString.Bytes.size();
2167 StringRef Longer = LHSIsLonger ? LHSString.Bytes : RHSString.Bytes;
2168 StringRef Shorter = LHSIsLonger ? RHSString.Bytes : LHSString.Bytes;
2169 int ShorterCharWidth = (LHSIsLonger ? RHSString : LHSString).CharWidth;
2170
2171 // The null terminator isn't included in the string data, so check for it
2172 // manually. If the longer string doesn't have a null terminator where the
2173 // shorter string ends, they aren't potentially overlapping.
2174 for (int NullByte : llvm::seq(ShorterCharWidth)) {
2175 if (Shorter.size() + NullByte >= Longer.size())
2176 break;
2177 if (Longer[Shorter.size() + NullByte])
2178 return false;
2179 }
2180
2181 // Otherwise, they're potentially overlapping if and only if the overlapping
2182 // region is the same.
2183 return Shorter == Longer.take_front(Shorter.size());
2184}
2185
2186static bool IsWeakLValue(const LValue &Value) {
2188 return Decl && Decl->isWeak();
2189}
2190
2191static bool isZeroSized(const LValue &Value) {
2193 if (isa_and_nonnull<VarDecl>(Decl)) {
2194 QualType Ty = Decl->getType();
2195 if (Ty->isArrayType())
2196 return Ty->isIncompleteType() ||
2197 Decl->getASTContext().getTypeSize(Ty) == 0;
2198 }
2199 return false;
2200}
2201
2202static bool HasSameBase(const LValue &A, const LValue &B) {
2203 if (!A.getLValueBase())
2204 return !B.getLValueBase();
2205 if (!B.getLValueBase())
2206 return false;
2207
2208 if (A.getLValueBase().getOpaqueValue() !=
2209 B.getLValueBase().getOpaqueValue())
2210 return false;
2211
2212 return A.getLValueCallIndex() == B.getLValueCallIndex() &&
2213 A.getLValueVersion() == B.getLValueVersion();
2214}
2215
2216static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
2217 assert(Base && "no location for a null lvalue");
2218 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2219
2220 // For a parameter, find the corresponding call stack frame (if it still
2221 // exists), and point at the parameter of the function definition we actually
2222 // invoked.
2223 if (auto *PVD = dyn_cast_or_null<ParmVarDecl>(VD)) {
2224 unsigned Idx = PVD->getFunctionScopeIndex();
2225 for (CallStackFrame *F = Info.CurrentCall; F; F = F->Caller) {
2226 if (F->Arguments.CallIndex == Base.getCallIndex() &&
2227 F->Arguments.Version == Base.getVersion() && F->Callee &&
2228 Idx < F->Callee->getNumParams()) {
2229 VD = F->Callee->getParamDecl(Idx);
2230 break;
2231 }
2232 }
2233 }
2234
2235 if (VD)
2236 Info.Note(VD->getLocation(), diag::note_declared_at);
2237 else if (const Expr *E = Base.dyn_cast<const Expr*>())
2238 Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
2239 else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
2240 // FIXME: Produce a note for dangling pointers too.
2241 if (std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA))
2242 Info.Note((*Alloc)->AllocExpr->getExprLoc(),
2243 diag::note_constexpr_dynamic_alloc_here);
2244 }
2245
2246 // We have no information to show for a typeid(T) object.
2247}
2248
2253
2254/// Materialized temporaries that we've already checked to determine if they're
2255/// initializsed by a constant expression.
2258
2260 EvalInfo &Info, SourceLocation DiagLoc,
2261 QualType Type, const APValue &Value,
2262 ConstantExprKind Kind,
2263 const FieldDecl *SubobjectDecl,
2264 CheckedTemporaries &CheckedTemps,
2265 bool IsCompleteClass = true);
2266
2267/// Check that this reference or pointer core constant expression is a valid
2268/// value for an address or reference constant expression. Return true if we
2269/// can fold this expression, whether or not it's a constant expression.
2270static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
2271 QualType Type, const LValue &LVal,
2272 ConstantExprKind Kind,
2273 CheckedTemporaries &CheckedTemps) {
2274 bool IsReferenceType = Type->isReferenceType();
2275
2276 APValue::LValueBase Base = LVal.getLValueBase();
2277 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
2278
2279 const Expr *BaseE = Base.dyn_cast<const Expr *>();
2280 const ValueDecl *BaseVD = Base.dyn_cast<const ValueDecl*>();
2281
2282 // Additional restrictions apply in a template argument. We only enforce the
2283 // C++20 restrictions here; additional syntactic and semantic restrictions
2284 // are applied elsewhere.
2285 if (isTemplateArgument(Kind)) {
2286 int InvalidBaseKind = -1;
2287 StringRef Ident;
2288 if (Base.is<TypeInfoLValue>())
2289 InvalidBaseKind = 0;
2290 else if (isa_and_nonnull<StringLiteral>(BaseE))
2291 InvalidBaseKind = 1;
2292 else if (isa_and_nonnull<MaterializeTemporaryExpr>(BaseE) ||
2293 isa_and_nonnull<LifetimeExtendedTemporaryDecl>(BaseVD))
2294 InvalidBaseKind = 2;
2295 else if (auto *PE = dyn_cast_or_null<PredefinedExpr>(BaseE)) {
2296 InvalidBaseKind = 3;
2297 Ident = PE->getIdentKindName();
2298 }
2299
2300 if (InvalidBaseKind != -1) {
2301 Info.FFDiag(Loc, diag::note_constexpr_invalid_template_arg)
2302 << IsReferenceType << !Designator.Entries.empty() << InvalidBaseKind
2303 << Ident;
2304 return false;
2305 }
2306 }
2307
2308 if (auto *FD = dyn_cast_or_null<FunctionDecl>(BaseVD);
2309 FD && FD->isImmediateFunction()) {
2310 Info.FFDiag(Loc, diag::note_consteval_address_accessible)
2311 << !Type->isAnyPointerType();
2312 Info.Note(FD->getLocation(), diag::note_declared_at);
2313 return false;
2314 }
2315
2316 // Check that the object is a global. Note that the fake 'this' object we
2317 // manufacture when checking potential constant expressions is conservatively
2318 // assumed to be global here.
2319 if (!IsGlobalLValue(Base)) {
2320 if (Info.getLangOpts().CPlusPlus11) {
2321 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
2322 << IsReferenceType << !Designator.Entries.empty() << !!BaseVD
2323 << BaseVD;
2324 auto *VarD = dyn_cast_or_null<VarDecl>(BaseVD);
2325 if (VarD && VarD->isConstexpr()) {
2326 // Non-static local constexpr variables have unintuitive semantics:
2327 // constexpr int a = 1;
2328 // constexpr const int *p = &a;
2329 // ... is invalid because the address of 'a' is not constant. Suggest
2330 // adding a 'static' in this case.
2331 Info.Note(VarD->getLocation(), diag::note_constexpr_not_static)
2332 << VarD
2333 << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static ");
2334 } else {
2335 NoteLValueLocation(Info, Base);
2336 }
2337 } else {
2338 Info.FFDiag(Loc);
2339 }
2340 // Don't allow references to temporaries to escape.
2341 return false;
2342 }
2343 assert((Info.checkingPotentialConstantExpression() ||
2344 LVal.getLValueCallIndex() == 0) &&
2345 "have call index for global lvalue");
2346
2347 if (LVal.allowConstexprUnknown()) {
2348 if (BaseVD) {
2349 Info.FFDiag(Loc, diag::note_constexpr_var_init_non_constant, 1) << BaseVD;
2350 NoteLValueLocation(Info, Base);
2351 } else {
2352 Info.FFDiag(Loc);
2353 }
2354 return false;
2355 }
2356
2357 if (Base.is<DynamicAllocLValue>()) {
2358 Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc)
2359 << IsReferenceType << !Designator.Entries.empty();
2360 NoteLValueLocation(Info, Base);
2361 return false;
2362 }
2363
2364 if (BaseVD) {
2365 if (const VarDecl *Var = dyn_cast<const VarDecl>(BaseVD)) {
2366 // Check if this is a thread-local variable.
2367 if (Var->getTLSKind())
2368 // FIXME: Diagnostic!
2369 return false;
2370
2371 // A dllimport variable never acts like a constant, unless we're
2372 // evaluating a value for use only in name mangling, and unless it's a
2373 // static local. For the latter case, we'd still need to evaluate the
2374 // constant expression in case we're inside a (inlined) function.
2375 if (!isForManglingOnly(Kind) && Var->hasAttr<DLLImportAttr>() &&
2376 !Var->isStaticLocal())
2377 return false;
2378
2379 // Address of a managed variable is never a constant expression.
2380 if (Info.getLangOpts().CUDA && Var->hasAttr<HIPManagedAttr>())
2381 return false;
2382
2383 // In CUDA/HIP device compilation, only device side variables have
2384 // constant addresses.
2385 if (Info.getLangOpts().CUDA && Info.getLangOpts().CUDAIsDevice &&
2386 Info.Ctx.CUDAConstantEvalCtx.NoWrongSidedVars) {
2387 if ((!Var->hasAttr<CUDADeviceAttr>() &&
2388 !Var->hasAttr<CUDAConstantAttr>() &&
2389 !Var->getType()->isCUDADeviceBuiltinSurfaceType() &&
2390 !Var->getType()->isCUDADeviceBuiltinTextureType()))
2391 return false;
2392 }
2393 }
2394 if (const auto *FD = dyn_cast<const FunctionDecl>(BaseVD)) {
2395 // __declspec(dllimport) must be handled very carefully:
2396 // We must never initialize an expression with the thunk in C++.
2397 // Doing otherwise would allow the same id-expression to yield
2398 // different addresses for the same function in different translation
2399 // units. However, this means that we must dynamically initialize the
2400 // expression with the contents of the import address table at runtime.
2401 //
2402 // The C language has no notion of ODR; furthermore, it has no notion of
2403 // dynamic initialization. This means that we are permitted to
2404 // perform initialization with the address of the thunk.
2405 if (Info.getLangOpts().CPlusPlus && !isForManglingOnly(Kind) &&
2406 FD->hasAttr<DLLImportAttr>())
2407 // FIXME: Diagnostic!
2408 return false;
2409 }
2410 } else if (const auto *MTE =
2411 dyn_cast_or_null<MaterializeTemporaryExpr>(BaseE)) {
2412 if (CheckedTemps.insert(MTE).second) {
2413 QualType TempType = getType(Base);
2414 if (TempType.isDestructedType()) {
2415 Info.FFDiag(MTE->getExprLoc(),
2416 diag::note_constexpr_unsupported_temporary_nontrivial_dtor)
2417 << TempType;
2418 return false;
2419 }
2420
2421 APValue *V = MTE->getOrCreateValue(false);
2422 assert(V && "evasluation result refers to uninitialised temporary");
2424 Info, MTE->getExprLoc(), TempType, *V, Kind,
2425 /*SubobjectDecl=*/nullptr, CheckedTemps))
2426 return false;
2427 }
2428 }
2429
2430 // Allow address constant expressions to be past-the-end pointers. This is
2431 // an extension: the standard requires them to point to an object.
2432 if (!IsReferenceType)
2433 return true;
2434
2435 // A reference constant expression must refer to an object.
2436 if (!Base) {
2437 // FIXME: diagnostic
2438 Info.CCEDiag(Loc);
2439 return true;
2440 }
2441
2442 // Does this refer one past the end of some object?
2443 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
2444 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
2445 << !Designator.Entries.empty() << !!BaseVD << BaseVD;
2446 NoteLValueLocation(Info, Base);
2447 }
2448
2449 return true;
2450}
2451
2452/// Member pointers are constant expressions unless they point to a
2453/// non-virtual dllimport member function.
2454static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
2455 SourceLocation Loc,
2456 QualType Type,
2457 const APValue &Value,
2458 ConstantExprKind Kind) {
2459 const ValueDecl *Member = Value.getMemberPointerDecl();
2460 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
2461 if (!FD)
2462 return true;
2463 if (FD->isImmediateFunction()) {
2464 Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0;
2465 Info.Note(FD->getLocation(), diag::note_declared_at);
2466 return false;
2467 }
2468 return isForManglingOnly(Kind) || FD->isVirtual() ||
2469 !FD->hasAttr<DLLImportAttr>();
2470}
2471
2472/// Check that this core constant expression is of literal type, and if not,
2473/// produce an appropriate diagnostic.
2474static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
2475 const LValue *This = nullptr) {
2476 // The restriction to literal types does not exist in C++23 anymore.
2477 if (Info.getLangOpts().CPlusPlus23)
2478 return true;
2479
2480 if (!E->isPRValue() || E->getType()->isLiteralType(Info.Ctx))
2481 return true;
2482
2483 // C++1y: A constant initializer for an object o [...] may also invoke
2484 // constexpr constructors for o and its subobjects even if those objects
2485 // are of non-literal class types.
2486 //
2487 // C++11 missed this detail for aggregates, so classes like this:
2488 // struct foo_t { union { int i; volatile int j; } u; };
2489 // are not (obviously) initializable like so:
2490 // __attribute__((__require_constant_initialization__))
2491 // static const foo_t x = {{0}};
2492 // because "i" is a subobject with non-literal initialization (due to the
2493 // volatile member of the union). See:
2494 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2495 // Therefore, we use the C++1y behavior.
2496 if (This && Info.EvaluatingDecl == This->getLValueBase())
2497 return true;
2498
2499 // Prvalue constant expressions must be of literal types.
2500 if (Info.getLangOpts().CPlusPlus11)
2501 Info.FFDiag(E, diag::note_constexpr_nonliteral)
2502 << E->getType();
2503 else
2504 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2505 return false;
2506}
2507
2509 EvalInfo &Info, SourceLocation DiagLoc,
2510 QualType Type, const APValue &Value,
2511 ConstantExprKind Kind,
2512 const FieldDecl *SubobjectDecl,
2513 CheckedTemporaries &CheckedTemps,
2514 bool IsCompleteClass) {
2515 if (!Value.hasValue()) {
2516 if (SubobjectDecl) {
2517 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2518 << /*(name)*/ 1 << SubobjectDecl;
2519 Info.Note(SubobjectDecl->getLocation(),
2520 diag::note_constexpr_subobject_declared_here);
2521 } else {
2522 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2523 << /*of type*/ 0 << Type;
2524 }
2525 return false;
2526 }
2527
2528 // We allow _Atomic(T) to be initialized from anything that T can be
2529 // initialized from.
2530 if (const AtomicType *AT = Type->getAs<AtomicType>())
2531 Type = AT->getValueType();
2532
2533 // Core issue 1454: For a literal constant expression of array or class type,
2534 // each subobject of its value shall have been initialized by a constant
2535 // expression.
2536 if (Value.isArray()) {
2538 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
2539 if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2540 Value.getArrayInitializedElt(I), Kind,
2541 SubobjectDecl, CheckedTemps))
2542 return false;
2543 }
2544 if (!Value.hasArrayFiller())
2545 return true;
2546 return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2547 Value.getArrayFiller(), Kind, SubobjectDecl,
2548 CheckedTemps);
2549 }
2550 if (Value.isUnion() && Value.getUnionField()) {
2551 return CheckEvaluationResult(
2552 CERK, Info, DiagLoc, Value.getUnionField()->getType(),
2553 Value.getUnionValue(), Kind, Value.getUnionField(), CheckedTemps);
2554 }
2555 if (Value.isStruct()) {
2556 auto *RD = Type->castAsRecordDecl();
2557 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2558 unsigned BaseIndex = 0;
2559 for (const CXXBaseSpecifier &BS : CD->bases()) {
2560 if (BS.isVirtual())
2561 continue;
2562 const APValue &BaseValue = Value.getStructBase(BaseIndex);
2563 if (!BaseValue.hasValue()) {
2564 SourceLocation TypeBeginLoc = BS.getBaseTypeLoc();
2565 Info.FFDiag(TypeBeginLoc, diag::note_constexpr_uninitialized_base)
2566 << BS.getType() << SourceRange(TypeBeginLoc, BS.getEndLoc());
2567 return false;
2568 }
2569 if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(), BaseValue,
2570 Kind, /*SubobjectDecl=*/nullptr,
2571 CheckedTemps, /*IsCompleteClass=*/false))
2572 return false;
2573 ++BaseIndex;
2574 }
2575 }
2576 for (const auto *I : RD->fields()) {
2577 if (I->isUnnamedBitField())
2578 continue;
2579
2580 if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),
2581 Value.getStructField(I->getFieldIndex()), Kind,
2582 I, CheckedTemps))
2583 return false;
2584 }
2585
2586 if (IsCompleteClass) {
2587 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2588 unsigned BaseIndex = 0;
2589 for (const CXXBaseSpecifier &BS : CD->vbases()) {
2590 assert(BS.isVirtual());
2591 const APValue &BaseValue = Value.getStructVirtualBase(BaseIndex);
2592 if (!BaseValue.hasValue()) {
2593 SourceLocation TypeBeginLoc = BS.getBaseTypeLoc();
2594 Info.FFDiag(TypeBeginLoc, diag::note_constexpr_uninitialized_base)
2595 << BS.getType() << SourceRange(TypeBeginLoc, BS.getEndLoc());
2596 return false;
2597 }
2598 if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(),
2599 BaseValue, Kind, /*SubobjectDecl=*/nullptr,
2600 CheckedTemps, /*IsCompleteClass=*/false))
2601 return false;
2602 ++BaseIndex;
2603 }
2604 }
2605 }
2606 }
2607
2608 if (Value.isLValue() &&
2610 LValue LVal;
2611 LVal.setFrom(Info.Ctx, Value);
2612 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Kind,
2613 CheckedTemps);
2614 }
2615
2616 if (Value.isMemberPointer() &&
2618 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Kind);
2619
2620 // Everything else is fine.
2621 return true;
2622}
2623
2624/// Check that this core constant expression value is a valid value for a
2625/// constant expression. If not, report an appropriate diagnostic. Does not
2626/// check that the expression is of literal type.
2627static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
2628 QualType Type, const APValue &Value,
2629 ConstantExprKind Kind) {
2630 // Nothing to check for a constant expression of type 'cv void'.
2631 if (Type->isVoidType())
2632 return true;
2633
2634 CheckedTemporaries CheckedTemps;
2636 Info, DiagLoc, Type, Value, Kind,
2637 /*SubobjectDecl=*/nullptr, CheckedTemps);
2638}
2639
2640/// Check that this evaluated value is fully-initialized and can be loaded by
2641/// an lvalue-to-rvalue conversion.
2642static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,
2643 QualType Type, const APValue &Value) {
2644 CheckedTemporaries CheckedTemps;
2645 return CheckEvaluationResult(
2647 ConstantExprKind::Normal, /*SubobjectDecl=*/nullptr, CheckedTemps);
2648}
2649
2650/// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless
2651/// "the allocated storage is deallocated within the evaluation".
2652static bool CheckMemoryLeaks(EvalInfo &Info) {
2653 if (!Info.HeapAllocs.empty()) {
2654 // We can still fold to a constant despite a compile-time memory leak,
2655 // so long as the heap allocation isn't referenced in the result (we check
2656 // that in CheckConstantExpression).
2657 Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr,
2658 diag::note_constexpr_memory_leak)
2659 << unsigned(Info.HeapAllocs.size() - 1);
2660 }
2661 return true;
2662}
2663
2664static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
2665 // A null base expression indicates a null pointer. These are always
2666 // evaluatable, and they are false unless the offset is zero.
2667 if (!Value.getLValueBase()) {
2668 // TODO: Should a non-null pointer with an offset of zero evaluate to true?
2669 Result = !Value.getLValueOffset().isZero();
2670 return true;
2671 }
2672
2673 // We have a non-null base. These are generally known to be true, but if it's
2674 // a weak declaration it can be null at runtime.
2675 Result = true;
2676 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
2677 return !Decl || !Decl->isWeak();
2678}
2679
2680static bool HandleConversionToBool(const APValue &Val, bool &Result) {
2681 // TODO: This function should produce notes if it fails.
2682 switch (Val.getKind()) {
2683 case APValue::None:
2685 return false;
2686 case APValue::Int:
2687 Result = Val.getInt().getBoolValue();
2688 return true;
2690 Result = Val.getFixedPoint().getBoolValue();
2691 return true;
2692 case APValue::Float:
2693 Result = !Val.getFloat().isZero();
2694 return true;
2696 Result = Val.getComplexIntReal().getBoolValue() ||
2697 Val.getComplexIntImag().getBoolValue();
2698 return true;
2700 Result = !Val.getComplexFloatReal().isZero() ||
2701 !Val.getComplexFloatImag().isZero();
2702 return true;
2703 case APValue::LValue:
2704 return EvalPointerValueAsBool(Val, Result);
2706 if (Val.getMemberPointerDecl() && Val.getMemberPointerDecl()->isWeak()) {
2707 return false;
2708 }
2710 return true;
2711 case APValue::Vector:
2712 case APValue::Matrix:
2713 case APValue::Array:
2714 case APValue::Struct:
2715 case APValue::Union:
2718 return false;
2719 }
2720
2721 llvm_unreachable("unknown APValue kind");
2722}
2723
2724static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2725 EvalInfo &Info) {
2726 assert(!E->isValueDependent());
2727 assert(E->isPRValue() && "missing lvalue-to-rvalue conv in bool condition");
2728 APValue Val;
2729 if (!Evaluate(Val, Info, E))
2730 return false;
2731 return HandleConversionToBool(Val, Result);
2732}
2733
2734template<typename T>
2735static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2736 const T &SrcValue, QualType DestType) {
2737 Info.CCEDiag(E, diag::note_constexpr_overflow) << SrcValue << DestType;
2738 if (const auto *OBT = DestType->getAs<OverflowBehaviorType>();
2739 OBT && OBT->isTrapKind()) {
2740 return false;
2741 }
2742 return Info.noteUndefinedBehavior();
2743}
2744
2745static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2746 QualType SrcType, const APFloat &Value,
2747 QualType DestType, APSInt &Result) {
2748 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2749 // Determine whether we are converting to unsigned or signed.
2750 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2751 // This handles converstion to bool.
2752 if (DestType->isBooleanType()) {
2753 Result = APSInt(APInt(1, !Value.isZero()), /*isUnsigned=*/true);
2754 return true;
2755 }
2756 Result = APSInt(DestWidth, !DestSigned);
2757 bool ignored;
2758
2759 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2760 & APFloat::opInvalidOp)
2761 return HandleOverflow(Info, E, Value, DestType);
2762 return true;
2763}
2764
2765/// Get rounding mode to use in evaluation of the specified expression.
2766///
2767/// If rounding mode is unknown at compile time, still try to evaluate the
2768/// expression. If the result is exact, it does not depend on rounding mode.
2769/// So return "tonearest" mode instead of "dynamic".
2770static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E) {
2771 llvm::RoundingMode RM =
2772 E->getFPFeaturesInEffect(Info.getLangOpts()).getRoundingMode();
2773 if (RM == llvm::RoundingMode::Dynamic)
2774 RM = llvm::RoundingMode::NearestTiesToEven;
2775 return RM;
2776}
2777
2778/// Check if the given floating-point evaluation result is allowed for
2779/// compile-time constant folding during translation (as opposed to mandatory
2780/// constant expression evaluation).
2782 const Expr *E,
2783 APFloat::opStatus St) {
2784 // In a constant context, assume that any dynamic rounding mode or FP
2785 // exception state matches the default floating-point environment.
2786 if (Info.InConstantContext)
2787 return true;
2788
2789 FPOptions FPO = E->getFPFeaturesInEffect(Info.getLangOpts());
2790 if ((St & APFloat::opInexact) &&
2791 FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) {
2792 // Inexact result means that it depends on rounding mode. If the requested
2793 // mode is dynamic, the evaluation cannot be made in compile time.
2794 Info.FFDiag(E, diag::note_constexpr_dynamic_rounding);
2795 return false;
2796 }
2797
2798 if ((St != APFloat::opOK) &&
2799 (FPO.getRoundingMode() == llvm::RoundingMode::Dynamic ||
2801 FPO.getAllowFEnvAccess())) {
2802 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
2803 return false;
2804 }
2805
2806 if ((St & APFloat::opStatus::opInvalidOp) &&
2808 // There is no usefully definable result.
2809 Info.FFDiag(E);
2810 return false;
2811 }
2812
2813 // FIXME: if:
2814 // - evaluation triggered other FP exception, and
2815 // - exception mode is not "ignore", and
2816 // - the expression being evaluated is not a part of global variable
2817 // initializer,
2818 // the evaluation probably need to be rejected.
2819 return true;
2820}
2821
2822static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2823 QualType SrcType, QualType DestType,
2824 APFloat &Result) {
2825 assert((isa<CastExpr>(E) || isa<CompoundAssignOperator>(E) ||
2827 "HandleFloatToFloatCast has been checked with only CastExpr, "
2828 "CompoundAssignOperator and ConvertVectorExpr. Please either validate "
2829 "the new expression or address the root cause of this usage.");
2830 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2831 APFloat::opStatus St;
2832 bool ignored;
2833 St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored);
2835}
2836
2837static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2838 QualType DestType, QualType SrcType,
2839 const APSInt &Value) {
2840 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2841 // Figure out if this is a truncate, extend or noop cast.
2842 // If the input is signed, do a sign extend, noop, or truncate.
2843 APSInt Result = Value.extOrTrunc(DestWidth);
2844 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2845 if (DestType->isBooleanType())
2846 Result = Value.getBoolValue();
2847 return Result;
2848}
2849
2850static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2851 const FPOptions FPO,
2852 QualType SrcType, const APSInt &Value,
2853 QualType DestType, APFloat &Result) {
2854 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2855 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2856 APFloat::opStatus St = Result.convertFromAPInt(Value, Value.isSigned(), RM);
2858}
2859
2860static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2861 APValue &Value, const FieldDecl *FD) {
2862 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2863
2864 if (!Value.isInt()) {
2865 // Trying to store a pointer-cast-to-integer into a bitfield.
2866 // FIXME: In this case, we should provide the diagnostic for casting
2867 // a pointer to an integer.
2868 assert(Value.isLValue() && "integral value neither int nor lvalue?");
2869 Info.FFDiag(E);
2870 return false;
2871 }
2872
2873 APSInt &Int = Value.getInt();
2874 unsigned OldBitWidth = Int.getBitWidth();
2875 unsigned NewBitWidth = FD->getBitWidthValue();
2876 if (NewBitWidth < OldBitWidth)
2877 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2878 return true;
2879}
2880
2881/// Perform the given integer operation, which is known to need at most BitWidth
2882/// bits, and check for overflow in the original type (if that type was not an
2883/// unsigned type).
2884template<typename Operation>
2885static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2886 const APSInt &LHS, const APSInt &RHS,
2887 unsigned BitWidth, Operation Op,
2888 APSInt &Result) {
2889 if (LHS.isUnsigned()) {
2890 Result = Op(LHS, RHS);
2891 return true;
2892 }
2893
2894 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2895 Result = Value.trunc(LHS.getBitWidth());
2896 if (Result.extend(BitWidth) != Value && !E->getType().isWrapType()) {
2897 if (Info.checkingForUndefinedBehavior())
2898 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2899 diag::warn_integer_constant_overflow)
2900 << toString(Result, 10, Result.isSigned(), /*formatAsCLiteral=*/false,
2901 /*UpperCase=*/true, /*InsertSeparators=*/true)
2902 << E->getType() << E->getSourceRange();
2903 return HandleOverflow(Info, E, Value, E->getType());
2904 }
2905 return true;
2906}
2907
2908/// Perform the given binary integer operation.
2909static bool handleIntIntBinOp(EvalInfo &Info, const BinaryOperator *E,
2910 const APSInt &LHS, BinaryOperatorKind Opcode,
2911 APSInt RHS, APSInt &Result) {
2912 bool HandleOverflowResult = true;
2913 switch (Opcode) {
2914 default:
2915 Info.FFDiag(E);
2916 return false;
2917 case BO_Mul:
2918 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2919 std::multiplies<APSInt>(), Result);
2920 case BO_Add:
2921 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2922 std::plus<APSInt>(), Result);
2923 case BO_Sub:
2924 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2925 std::minus<APSInt>(), Result);
2926 case BO_And: Result = LHS & RHS; return true;
2927 case BO_Xor: Result = LHS ^ RHS; return true;
2928 case BO_Or: Result = LHS | RHS; return true;
2929 case BO_Div:
2930 case BO_Rem:
2931 if (RHS == 0) {
2932 Info.FFDiag(E, diag::note_expr_divide_by_zero)
2933 << E->getRHS()->getSourceRange();
2934 return false;
2935 }
2936 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2937 // this operation and gives the two's complement result.
2938 if (RHS.isNegative() && RHS.isAllOnes() && LHS.isSigned() &&
2939 LHS.isMinSignedValue())
2940 HandleOverflowResult = HandleOverflow(
2941 Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
2942 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2943 return HandleOverflowResult;
2944 case BO_Shl: {
2945 if (Info.getLangOpts().OpenCL)
2946 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2947 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2948 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2949 RHS.isUnsigned());
2950 else if (RHS.isSigned() && RHS.isNegative()) {
2951 // During constant-folding, a negative shift is an opposite shift. Such
2952 // a shift is not a constant expression.
2953 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2954 if (!Info.noteUndefinedBehavior())
2955 return false;
2956 RHS = -RHS;
2957 goto shift_right;
2958 }
2959 shift_left:
2960 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2961 // the shifted type.
2962 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2963 if (SA != RHS) {
2964 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2965 << RHS << E->getType() << LHS.getBitWidth();
2966 if (!Info.noteUndefinedBehavior())
2967 return false;
2968 } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) {
2969 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2970 // operand, and must not overflow the corresponding unsigned type.
2971 // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2972 // E1 x 2^E2 module 2^N.
2973 if (LHS.isNegative()) {
2974 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2975 if (!Info.noteUndefinedBehavior())
2976 return false;
2977 } else if (LHS.countl_zero() < SA) {
2978 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2979 if (!Info.noteUndefinedBehavior())
2980 return false;
2981 }
2982 }
2983 Result = LHS << SA;
2984 return true;
2985 }
2986 case BO_Shr: {
2987 if (Info.getLangOpts().OpenCL)
2988 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2989 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2990 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2991 RHS.isUnsigned());
2992 else if (RHS.isSigned() && RHS.isNegative()) {
2993 // During constant-folding, a negative shift is an opposite shift. Such a
2994 // shift is not a constant expression.
2995 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2996 if (!Info.noteUndefinedBehavior())
2997 return false;
2998 RHS = -RHS;
2999 goto shift_left;
3000 }
3001 shift_right:
3002 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
3003 // shifted type.
3004 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
3005 if (SA != RHS) {
3006 Info.CCEDiag(E, diag::note_constexpr_large_shift)
3007 << RHS << E->getType() << LHS.getBitWidth();
3008 if (!Info.noteUndefinedBehavior())
3009 return false;
3010 }
3011
3012 Result = LHS >> SA;
3013 return true;
3014 }
3015
3016 case BO_LT: Result = LHS < RHS; return true;
3017 case BO_GT: Result = LHS > RHS; return true;
3018 case BO_LE: Result = LHS <= RHS; return true;
3019 case BO_GE: Result = LHS >= RHS; return true;
3020 case BO_EQ: Result = LHS == RHS; return true;
3021 case BO_NE: Result = LHS != RHS; return true;
3022 case BO_Cmp:
3023 llvm_unreachable("BO_Cmp should be handled elsewhere");
3024 }
3025}
3026
3027/// Perform the given binary floating-point operation, in-place, on LHS.
3028static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E,
3029 APFloat &LHS, BinaryOperatorKind Opcode,
3030 const APFloat &RHS) {
3031 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
3032 APFloat::opStatus St;
3033 switch (Opcode) {
3034 default:
3035 Info.FFDiag(E);
3036 return false;
3037 case BO_Mul:
3038 St = LHS.multiply(RHS, RM);
3039 break;
3040 case BO_Add:
3041 St = LHS.add(RHS, RM);
3042 break;
3043 case BO_Sub:
3044 St = LHS.subtract(RHS, RM);
3045 break;
3046 case BO_Div:
3047 // [expr.mul]p4:
3048 // If the second operand of / or % is zero the behavior is undefined.
3049 if (RHS.isZero())
3050 Info.CCEDiag(E, diag::note_expr_divide_by_zero);
3051 St = LHS.divide(RHS, RM);
3052 break;
3053 }
3054
3055 // FIXME: The standard quote below is deleted by P3899R3.
3056 // [expr.pre]p4:
3057 // If during the evaluation of an expression, the result is not
3058 // mathematically defined [...], the behavior is undefined.
3059 // FIXME: C++ rules require us to not conform to IEEE 754 here.
3060 // FIXME: The NaN check should not be applied outside of "constant contexts"
3061 // because it prevents NaN propagation and the "invalid" status is the
3062 // responsibility of checkFloatingPointResultForConstantFolding.
3063 if (LHS.isNaN()) {
3064 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
3065 return Info.noteUndefinedBehavior();
3066 }
3067
3069}
3070
3071static bool handleLogicalOpForVector(const APInt &LHSValue,
3072 BinaryOperatorKind Opcode,
3073 const APInt &RHSValue, APInt &Result) {
3074 bool LHS = (LHSValue != 0);
3075 bool RHS = (RHSValue != 0);
3076
3077 if (Opcode == BO_LAnd)
3078 Result = LHS && RHS;
3079 else
3080 Result = LHS || RHS;
3081 return true;
3082}
3083static bool handleLogicalOpForVector(const APFloat &LHSValue,
3084 BinaryOperatorKind Opcode,
3085 const APFloat &RHSValue, APInt &Result) {
3086 bool LHS = !LHSValue.isZero();
3087 bool RHS = !RHSValue.isZero();
3088
3089 if (Opcode == BO_LAnd)
3090 Result = LHS && RHS;
3091 else
3092 Result = LHS || RHS;
3093 return true;
3094}
3095
3096static bool handleLogicalOpForVector(const APValue &LHSValue,
3097 BinaryOperatorKind Opcode,
3098 const APValue &RHSValue, APInt &Result) {
3099 // The result is always an int type, however operands match the first.
3100 if (LHSValue.getKind() == APValue::Int)
3101 return handleLogicalOpForVector(LHSValue.getInt(), Opcode,
3102 RHSValue.getInt(), Result);
3103 assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
3104 return handleLogicalOpForVector(LHSValue.getFloat(), Opcode,
3105 RHSValue.getFloat(), Result);
3106}
3107
3108template <typename APTy>
3109static bool
3111 const APTy &RHSValue, APInt &Result) {
3112 switch (Opcode) {
3113 default:
3114 llvm_unreachable("unsupported binary operator");
3115 case BO_EQ:
3116 Result = (LHSValue == RHSValue);
3117 break;
3118 case BO_NE:
3119 Result = (LHSValue != RHSValue);
3120 break;
3121 case BO_LT:
3122 Result = (LHSValue < RHSValue);
3123 break;
3124 case BO_GT:
3125 Result = (LHSValue > RHSValue);
3126 break;
3127 case BO_LE:
3128 Result = (LHSValue <= RHSValue);
3129 break;
3130 case BO_GE:
3131 Result = (LHSValue >= RHSValue);
3132 break;
3133 }
3134
3135 // The boolean operations on these vector types use an instruction that
3136 // results in a mask of '-1' for the 'truth' value. Ensure that we negate 1
3137 // to -1 to make sure that we produce the correct value.
3138 Result.negate();
3139
3140 return true;
3141}
3142
3143static bool handleCompareOpForVector(const APValue &LHSValue,
3144 BinaryOperatorKind Opcode,
3145 const APValue &RHSValue, APInt &Result) {
3146 // The result is always an int type, however operands match the first.
3147 if (LHSValue.getKind() == APValue::Int)
3148 return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode,
3149 RHSValue.getInt(), Result);
3150 assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
3151 return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode,
3152 RHSValue.getFloat(), Result);
3153}
3154
3155// Perform binary operations for vector types, in place on the LHS.
3156static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E,
3157 BinaryOperatorKind Opcode,
3158 APValue &LHSValue,
3159 const APValue &RHSValue) {
3160 assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI &&
3161 "Operation not supported on vector types");
3162
3163 const auto *VT = E->getType()->castAs<VectorType>();
3164 unsigned NumElements = VT->getNumElements();
3165 QualType EltTy = VT->getElementType();
3166
3167 // In the cases (typically C as I've observed) where we aren't evaluating
3168 // constexpr but are checking for cases where the LHS isn't yet evaluatable,
3169 // just give up.
3170 if (!LHSValue.isVector()) {
3171 assert(LHSValue.isLValue() &&
3172 "A vector result that isn't a vector OR uncalculated LValue");
3173 Info.FFDiag(E);
3174 return false;
3175 }
3176
3177 assert(LHSValue.getVectorLength() == NumElements &&
3178 RHSValue.getVectorLength() == NumElements && "Different vector sizes");
3179
3180 SmallVector<APValue, 4> ResultElements;
3181
3182 for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) {
3183 APValue LHSElt = LHSValue.getVectorElt(EltNum);
3184 APValue RHSElt = RHSValue.getVectorElt(EltNum);
3185
3186 if (EltTy->isIntegerType()) {
3187 APSInt EltResult{Info.Ctx.getIntWidth(EltTy),
3188 EltTy->isUnsignedIntegerType()};
3189 bool Success = true;
3190
3191 if (BinaryOperator::isLogicalOp(Opcode))
3192 Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3193 else if (BinaryOperator::isComparisonOp(Opcode))
3194 Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3195 else
3196 Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode,
3197 RHSElt.getInt(), EltResult);
3198
3199 if (!Success) {
3200 Info.FFDiag(E);
3201 return false;
3202 }
3203 ResultElements.emplace_back(EltResult);
3204
3205 } else if (EltTy->isFloatingType()) {
3206 assert(LHSElt.getKind() == APValue::Float &&
3207 RHSElt.getKind() == APValue::Float &&
3208 "Mismatched LHS/RHS/Result Type");
3209 APFloat LHSFloat = LHSElt.getFloat();
3210
3211 if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode,
3212 RHSElt.getFloat())) {
3213 Info.FFDiag(E);
3214 return false;
3215 }
3216
3217 ResultElements.emplace_back(LHSFloat);
3218 }
3219 }
3220
3221 LHSValue = APValue(ResultElements.data(), ResultElements.size());
3222 return true;
3223}
3224
3225/// Cast an lvalue referring to a base subobject to a derived class, by
3226/// truncating the lvalue's path to the given length.
3227static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
3228 const RecordDecl *TruncatedType,
3229 unsigned TruncatedElements) {
3230 SubobjectDesignator &D = Result.Designator;
3231
3232 // Check we actually point to a derived class object.
3233 if (TruncatedElements == D.Entries.size())
3234 return true;
3235 assert(TruncatedElements >= D.MostDerivedPathLength &&
3236 "not casting to a derived class");
3237 if (!Result.checkSubobject(Info, E, CSK_Derived))
3238 return false;
3239
3240 // Truncate the path to the subobject, and remove any derived-to-base offsets.
3241 const RecordDecl *RD = TruncatedType;
3242 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
3243 if (RD->isInvalidDecl()) return false;
3244 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3245 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
3246 if (isVirtualBaseClass(D.Entries[I]))
3247 Result.Offset -= Layout.getVBaseClassOffset(Base);
3248 else
3249 Result.Offset -= Layout.getBaseClassOffset(Base);
3250 RD = Base;
3251 }
3252 D.Entries.resize(TruncatedElements);
3253 return true;
3254}
3255
3256static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3257 const CXXRecordDecl *Derived,
3258 const CXXRecordDecl *Base,
3259 const ASTRecordLayout *RL = nullptr) {
3260 if (!RL) {
3261 if (Derived->isInvalidDecl()) return false;
3262 RL = &Info.Ctx.getASTRecordLayout(Derived);
3263 }
3264
3265 Obj.addDecl(Info, E, Base, /*Virtual=*/false);
3266 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
3267 return true;
3268}
3269
3270static bool HandleLValueDirectVirtualBase(EvalInfo &Info, const Expr *E,
3271 LValue &Obj,
3272 const CXXRecordDecl *Derived,
3273 const CXXRecordDecl *Base,
3274 const ASTRecordLayout *RL = nullptr) {
3275 if (!RL) {
3276 if (Derived->isInvalidDecl())
3277 return false;
3278 RL = &Info.Ctx.getASTRecordLayout(Derived);
3279 }
3280
3281 Obj.addDecl(Info, E, Base, /*Virtual=*/true);
3282 Obj.getLValueOffset() += RL->getVBaseClassOffset(Base);
3283 return true;
3284}
3285
3286static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3287 const CXXRecordDecl *DerivedDecl,
3288 const CXXBaseSpecifier *Base) {
3289 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
3290
3291 if (!Base->isVirtual())
3292 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
3293
3294 SubobjectDesignator &D = Obj.Designator;
3295 if (D.Invalid)
3296 return false;
3297
3298 // Extract most-derived object and corresponding type.
3299 // FIXME: After implementing P2280R4 it became possible to get references
3300 // here. We do MostDerivedType->getAsCXXRecordDecl() in several other
3301 // locations and if we see crashes in those locations in the future
3302 // it may make more sense to move this fix into Lvalue::set.
3303 DerivedDecl = D.MostDerivedType.getNonReferenceType()->getAsCXXRecordDecl();
3304 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
3305 return false;
3306
3307 // Find the virtual base class.
3308 if (DerivedDecl->isInvalidDecl()) return false;
3309 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
3310 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
3311 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
3312 return true;
3313}
3314
3315static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
3316 QualType Type, LValue &Result) {
3317 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3318 PathE = E->path_end();
3319 PathI != PathE; ++PathI) {
3321 *PathI))
3322 return false;
3323 Type = (*PathI)->getType();
3324 }
3325 return true;
3326}
3327
3328/// Cast an lvalue referring to a derived class to a known base subobject.
3329static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
3330 const CXXRecordDecl *DerivedRD,
3331 const CXXRecordDecl *BaseRD) {
3332 CXXBasePaths Paths(/*FindAmbiguities=*/false,
3333 /*RecordPaths=*/true, /*DetectVirtual=*/false);
3334 if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
3335 llvm_unreachable("Class must be derived from the passed in base class!");
3336
3337 for (CXXBasePathElement &Elem : Paths.front())
3338 if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
3339 return false;
3340 return true;
3341}
3342
3343/// Update LVal to refer to the given field, which must be a member of the type
3344/// currently described by LVal.
3345static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
3346 const FieldDecl *FD,
3347 const ASTRecordLayout *RL = nullptr) {
3348 if (!RL) {
3349 const RecordDecl *RD = FD->getParent();
3350 if (RD->isInvalidDecl())
3351 return false;
3352 // There are some cases where the base is not yet complete but we haven't
3353 // disagnosed (such as in a template instantation of an attribute that
3354 // references the expression, ala enable_if). These aren't necessarily
3355 // constant expressions so we return 'false', but they might be, so we don't
3356 // diagnose.
3357 if (!RD->isCompleteDefinition())
3358 return false;
3359 RL = &Info.Ctx.getASTRecordLayout(RD);
3360 }
3361
3362 unsigned I = FD->getFieldIndex();
3363 LVal.addDecl(Info, E, FD);
3364 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
3365 return true;
3366}
3367
3368/// Update LVal to refer to the given indirect field.
3369static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
3370 LValue &LVal,
3371 const IndirectFieldDecl *IFD) {
3372 for (const auto *C : IFD->chain())
3373 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
3374 return false;
3375 return true;
3376}
3377
3382
3383/// Get the size of the given type in char units.
3384static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, QualType Type,
3386 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
3387 // extension.
3388 if (Type->isVoidType() || Type->isFunctionType()) {
3389 Size = CharUnits::One();
3390 return true;
3391 }
3392
3393 if (Type->isDependentType()) {
3394 Info.FFDiag(Loc);
3395 return false;
3396 }
3397
3398 if (!Type->isConstantSizeType()) {
3399 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
3400 // FIXME: Better diagnostic.
3401 Info.FFDiag(Loc);
3402 return false;
3403 }
3404
3405 if (SOT == SizeOfType::SizeOf)
3406 Size = Info.Ctx.getTypeSizeInChars(Type);
3407 else
3408 Size = Info.Ctx.getTypeInfoDataSizeInChars(Type).Width;
3409 return true;
3410}
3411
3412/// Update a pointer value to model pointer arithmetic.
3413/// \param Info - Information about the ongoing evaluation.
3414/// \param E - The expression being evaluated, for diagnostic purposes.
3415/// \param LVal - The pointer value to be updated.
3416/// \param EltTy - The pointee type represented by LVal.
3417/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
3418static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3419 LValue &LVal, QualType EltTy,
3420 APSInt Adjustment) {
3421 CharUnits SizeOfPointee;
3422 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
3423 return false;
3424
3425 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
3426 return true;
3427}
3428
3429static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3430 LValue &LVal, QualType EltTy,
3431 int64_t Adjustment) {
3432 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
3433 APSInt::get(Adjustment));
3434}
3435
3436/// Update an lvalue to refer to a component of a complex number.
3437/// \param Info - Information about the ongoing evaluation.
3438/// \param LVal - The lvalue to be updated.
3439/// \param EltTy - The complex number's component type.
3440/// \param Imag - False for the real component, true for the imaginary.
3441static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
3442 LValue &LVal, QualType EltTy,
3443 bool Imag) {
3444 if (Imag) {
3445 CharUnits SizeOfComponent;
3446 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
3447 return false;
3448 LVal.Offset += SizeOfComponent;
3449 }
3450 LVal.addComplex(Info, E, EltTy, Imag);
3451 return true;
3452}
3453
3454static bool HandleLValueVectorElement(EvalInfo &Info, const Expr *E,
3455 LValue &LVal, QualType EltTy,
3456 uint64_t Size, uint64_t Idx) {
3457 if (Idx) {
3458 CharUnits SizeOfElement;
3459 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfElement))
3460 return false;
3461 LVal.Offset += SizeOfElement * Idx;
3462 }
3463 LVal.addVectorElement(Info, E, EltTy, Size, Idx);
3464 return true;
3465}
3466
3467/// Try to evaluate the initializer for a variable declaration.
3468///
3469/// \param Info Information about the ongoing evaluation.
3470/// \param E An expression to be used when printing diagnostics.
3471/// \param VD The variable whose initializer should be obtained.
3472/// \param Version The version of the variable within the frame.
3473/// \param Frame The frame in which the variable was created. Must be null
3474/// if this variable is not local to the evaluation.
3475/// \param Result Filled in with a pointer to the value of the variable.
3476static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
3477 const VarDecl *VD, CallStackFrame *Frame,
3478 unsigned Version, APValue *&Result) {
3479 // C++23 [expr.const]p8 If we have a reference type allow unknown references
3480 // and pointers.
3481 bool AllowConstexprUnknown =
3482 Info.getLangOpts().CPlusPlus23 && VD->getType()->isReferenceType();
3483
3484 APValue::LValueBase Base(VD, Frame ? Frame->Index : 0, Version);
3485
3486 auto CheckUninitReference = [&](bool IsLocalVariable) {
3487 if (!Result || (!Result->hasValue() && VD->getType()->isReferenceType())) {
3488 // C++23 [expr.const]p8
3489 // ... For such an object that is not usable in constant expressions, the
3490 // dynamic type of the object is constexpr-unknown. For such a reference
3491 // that is not usable in constant expressions, the reference is treated
3492 // as binding to an unspecified object of the referenced type whose
3493 // lifetime and that of all subobjects includes the entire constant
3494 // evaluation and whose dynamic type is constexpr-unknown.
3495 //
3496 // Variables that are part of the current evaluation are not
3497 // constexpr-unknown.
3498 if (!AllowConstexprUnknown || IsLocalVariable) {
3499 if (!Info.checkingPotentialConstantExpression())
3500 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
3501 return false;
3502 }
3503 Result = nullptr;
3504 }
3505 return true;
3506 };
3507
3508 // If this is a local variable, dig out its value.
3509 if (Frame) {
3510 Result = Frame->getTemporary(VD, Version);
3511 if (Result)
3512 return CheckUninitReference(/*IsLocalVariable=*/true);
3513
3514 if (!isa<ParmVarDecl>(VD)) {
3515 // Assume variables referenced within a lambda's call operator that were
3516 // not declared within the call operator are captures and during checking
3517 // of a potential constant expression, assume they are unknown constant
3518 // expressions.
3519 assert(isLambdaCallOperator(Frame->Callee) &&
3520 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
3521 "missing value for local variable");
3522 if (Info.checkingPotentialConstantExpression())
3523 return false;
3524
3525 llvm_unreachable(
3526 "A variable in a frame should either be a local or a parameter");
3527 }
3528 }
3529
3530 // If we're currently evaluating the initializer of this declaration, use that
3531 // in-flight value.
3532 if (Info.EvaluatingDecl == Base) {
3533 Result = Info.EvaluatingDeclValue;
3534 return CheckUninitReference(/*IsLocalVariable=*/false);
3535 }
3536
3537 // P2280R4 struck the restriction that variable of reference type lifetime
3538 // should begin within the evaluation of E
3539 // Used to be C++20 [expr.const]p5.12.2:
3540 // ... its lifetime began within the evaluation of E;
3541 if (isa<ParmVarDecl>(VD)) {
3542 if (AllowConstexprUnknown) {
3543 Result = nullptr;
3544 return true;
3545 }
3546
3547 // Assume parameters of a potential constant expression are usable in
3548 // constant expressions.
3549 if (!Info.checkingPotentialConstantExpression() ||
3550 !Info.CurrentCall->Callee ||
3551 !Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
3552 if (Info.getLangOpts().CPlusPlus11) {
3553 Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown)
3554 << VD;
3555 NoteLValueLocation(Info, Base);
3556 } else {
3557 Info.FFDiag(E);
3558 }
3559 }
3560 return false;
3561 }
3562
3563 if (E->isValueDependent())
3564 return false;
3565
3566 // Dig out the initializer, and use the declaration which it's attached to.
3567 // FIXME: We should eventually check whether the variable has a reachable
3568 // initializing declaration.
3569 const Expr *Init = VD->getAnyInitializer(VD);
3570 // P2280R4 struck the restriction that variable of reference type should have
3571 // a preceding initialization.
3572 // Used to be C++20 [expr.const]p5.12:
3573 // ... reference has a preceding initialization and either ...
3574 if (!Init && !AllowConstexprUnknown) {
3575 // Don't diagnose during potential constant expression checking; an
3576 // initializer might be added later.
3577 if (!Info.checkingPotentialConstantExpression()) {
3578 Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1)
3579 << VD;
3580 NoteLValueLocation(Info, Base);
3581 }
3582 return false;
3583 }
3584
3585 // P2280R4 struck the initialization requirement for variables of reference
3586 // type so we can no longer assume we have an Init.
3587 // Used to be C++20 [expr.const]p5.12:
3588 // ... reference has a preceding initialization and either ...
3589 if (Init && Init->isValueDependent()) {
3590 if (!Info.checkingPotentialConstantExpression()) {
3591 Info.FFDiag(E,
3592 Info.getLangOpts().CPlusPlus11
3593 ? diag::note_constexpr_ltor_non_constexpr
3594 : diag::note_constexpr_ltor_non_integral,
3595 1)
3596 << VD << VD->getType();
3597 NoteLValueLocation(Info, Base);
3598 }
3599
3600 // A recovery initializer can be value-dependent even when the expression
3601 // referring to the variable is not.
3602 if (Init->containsErrors())
3603 return false;
3604
3605 // The DeclRefExpr is not value-dependent, but the variable it refers to
3606 // has a value-dependent initializer. This should only happen in
3607 // constant-folding cases, where the variable is not actually of a suitable
3608 // type for use in a constant expression (otherwise the DeclRefExpr would
3609 // have been value-dependent too), so diagnose that.
3610 assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx));
3611 return false;
3612 }
3613
3614 // Check that we can fold the initializer. In C++, we will have already done
3615 // this in the cases where it matters for conformance.
3616 // P2280R4 struck the initialization requirement for variables of reference
3617 // type so we can no longer assume we have an Init.
3618 // Used to be C++20 [expr.const]p5.12:
3619 // ... reference has a preceding initialization and either ...
3620 if (Init && !VD->evaluateValue() && !AllowConstexprUnknown) {
3621 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3622 NoteLValueLocation(Info, Base);
3623 return false;
3624 }
3625
3626 // Check that the variable is actually usable in constant expressions. For a
3627 // const integral variable or a reference, we might have a non-constant
3628 // initializer that we can nonetheless evaluate the initializer for. Such
3629 // variables are not usable in constant expressions. In C++98, the
3630 // initializer also syntactically needs to be an ICE.
3631 //
3632 // FIXME: We don't diagnose cases that aren't potentially usable in constant
3633 // expressions here; doing so would regress diagnostics for things like
3634 // reading from a volatile constexpr variable.
3635 if ((Info.getLangOpts().CPlusPlus && !VD->hasConstantInitialization() &&
3636 VD->mightBeUsableInConstantExpressions(Info.Ctx) &&
3637 !AllowConstexprUnknown) ||
3638 ((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) &&
3639 !Info.getLangOpts().CPlusPlus11 && !VD->hasICEInitializer(Info.Ctx))) {
3640 if (Init) {
3641 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3642 NoteLValueLocation(Info, Base);
3643 } else {
3644 Info.CCEDiag(E);
3645 }
3646 }
3647
3648 // Never use the initializer of a weak variable, not even for constant
3649 // folding. We can't be sure that this is the definition that will be used.
3650 if (VD->isWeak()) {
3651 Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD;
3652 NoteLValueLocation(Info, Base);
3653 return false;
3654 }
3655
3656 Result = const_cast<APValue *>(VD->getEvaluatedValue());
3657
3658 if (!Result && !AllowConstexprUnknown)
3659 return false;
3660
3661 return CheckUninitReference(/*IsLocalVariable=*/false);
3662}
3663
3664/// Get the base index of the given base class within an APValue representing
3665/// the given derived class.
3666static unsigned getBaseIndex(const CXXRecordDecl *Derived,
3667 const CXXRecordDecl *Base) {
3668 Base = Base->getCanonicalDecl();
3669 unsigned Index = 0;
3670 for (const CXXBaseSpecifier &B : Derived->bases()) {
3671 if (B.isVirtual())
3672 continue;
3674 return Index;
3675 ++Index;
3676 }
3677
3678 for (const CXXBaseSpecifier &B : Derived->vbases()) {
3680 return Index;
3681 ++Index;
3682 }
3683
3684 llvm_unreachable("base class missing from derived class's bases list");
3685}
3686
3687/// Extract the value of a character from a string literal.
3688static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
3689 uint64_t Index) {
3690 assert(!isa<SourceLocExpr>(Lit) &&
3691 "SourceLocExpr should have already been converted to a StringLiteral");
3692
3693 // FIXME: Support MakeStringConstant
3694 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
3695 std::string Str;
3696 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
3697 assert(Index <= Str.size() && "Index too large");
3698 return APSInt::getUnsigned(Str.c_str()[Index]);
3699 }
3700
3701 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
3702 Lit = PE->getFunctionName();
3703 const StringLiteral *S = cast<StringLiteral>(Lit);
3704 const ConstantArrayType *CAT =
3705 Info.Ctx.getAsConstantArrayType(S->getType());
3706 assert(CAT && "string literal isn't an array");
3707 QualType CharType = CAT->getElementType();
3708 assert(CharType->isIntegerType() && "unexpected character type");
3709 APSInt Value(Info.Ctx.getTypeSize(CharType),
3710 CharType->isUnsignedIntegerType());
3711 if (Index < S->getLength())
3712 Value = S->getCodeUnit(Index);
3713 return Value;
3714}
3715
3716// Expand a string literal into an array of characters.
3717//
3718// FIXME: This is inefficient; we should probably introduce something similar
3719// to the LLVM ConstantDataArray to make this cheaper.
3720static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
3721 APValue &Result,
3722 QualType AllocType = QualType()) {
3723 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
3724 AllocType.isNull() ? S->getType() : AllocType);
3725 assert(CAT && "string literal isn't an array");
3726 QualType CharType = CAT->getElementType();
3727 assert(CharType->isIntegerType() && "unexpected character type");
3728
3729 unsigned Elts = CAT->getZExtSize();
3731 std::min(S->getLength(), Elts), Elts);
3732 APSInt Value(Info.Ctx.getTypeSize(CharType),
3733 CharType->isUnsignedIntegerType());
3734 if (Result.hasArrayFiller())
3735 Result.getArrayFiller() = APValue(Value);
3736 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
3737 Value = S->getCodeUnit(I);
3738 Result.getArrayInitializedElt(I) = APValue(Value);
3739 }
3740}
3741
3742// Expand an array so that it has more than Index filled elements.
3743static void expandArray(APValue &Array, unsigned Index) {
3744 unsigned Size = Array.getArraySize();
3745 assert(Index < Size);
3746
3747 // Always at least double the number of elements for which we store a value.
3748 unsigned OldElts = Array.getArrayInitializedElts();
3749 unsigned NewElts = std::max(Index+1, OldElts * 2);
3750 NewElts = std::min(Size, std::max(NewElts, 8u));
3751
3752 // Copy the data across.
3753 APValue NewValue(APValue::UninitArray(), NewElts, Size);
3754 for (unsigned I = 0; I != OldElts; ++I)
3755 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
3756 for (unsigned I = OldElts; I != NewElts; ++I)
3757 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
3758 if (NewValue.hasArrayFiller())
3759 NewValue.getArrayFiller() = Array.getArrayFiller();
3760 Array.swap(NewValue);
3761}
3762
3763// Expand an indeterminate vector to materialize all elements.
3764static void expandVector(APValue &Vec, unsigned NumElements) {
3765 assert(Vec.isIndeterminate());
3767 Vec = APValue(Elts.data(), Elts.size());
3768}
3769
3770/// Determine whether a type would actually be read by an lvalue-to-rvalue
3771/// conversion. If it's of class type, we may assume that the copy operation
3772/// is trivial. Note that this is never true for a union type with fields
3773/// (because the copy always "reads" the active member) and always true for
3774/// a non-class type.
3775bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD);
3777 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3778 return !RD || isReadByLvalueToRvalueConversion(RD);
3779}
3781 // FIXME: A trivial copy of a union copies the object representation, even if
3782 // the union is empty.
3783 if (RD->isUnion())
3784 return !RD->field_empty();
3785 if (RD->isEmpty())
3786 return false;
3787
3788 for (auto *Field : RD->fields())
3789 if (!Field->isUnnamedBitField() &&
3790 isReadByLvalueToRvalueConversion(Field->getType()))
3791 return true;
3792
3793 for (auto &BaseSpec : RD->bases())
3794 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
3795 return true;
3796
3797 return false;
3798}
3799
3800/// Diagnose an attempt to read from any unreadable field within the specified
3801/// type, which might be a class type.
3802static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK,
3803 QualType T) {
3804 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3805 if (!RD)
3806 return false;
3807
3808 if (!RD->hasMutableFields())
3809 return false;
3810
3811 for (auto *Field : RD->fields()) {
3812 // If we're actually going to read this field in some way, then it can't
3813 // be mutable. If we're in a union, then assigning to a mutable field
3814 // (even an empty one) can change the active member, so that's not OK.
3815 // FIXME: Add core issue number for the union case.
3816 if (Field->isMutable() &&
3817 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
3818 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field;
3819 Info.Note(Field->getLocation(), diag::note_declared_at);
3820 return true;
3821 }
3822
3823 if (diagnoseMutableFields(Info, E, AK, Field->getType()))
3824 return true;
3825 }
3826
3827 for (auto &BaseSpec : RD->bases())
3828 if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType()))
3829 return true;
3830
3831 // All mutable fields were empty, and thus not actually read.
3832 return false;
3833}
3834
3835static bool lifetimeStartedInEvaluation(EvalInfo &Info,
3837 bool MutableSubobject = false) {
3838 // A temporary or transient heap allocation we created.
3839 if (Base.getCallIndex() || Base.is<DynamicAllocLValue>())
3840 return true;
3841
3842 switch (Info.IsEvaluatingDecl) {
3843 case EvalInfo::EvaluatingDeclKind::None:
3844 return false;
3845
3846 case EvalInfo::EvaluatingDeclKind::Ctor:
3847 // The variable whose initializer we're evaluating.
3848 if (Info.EvaluatingDecl == Base)
3849 return true;
3850
3851 // A temporary lifetime-extended by the variable whose initializer we're
3852 // evaluating.
3853 if (auto *BaseE = Base.dyn_cast<const Expr *>())
3854 if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
3855 return Info.EvaluatingDecl == BaseMTE->getExtendingDecl();
3856 return false;
3857
3858 case EvalInfo::EvaluatingDeclKind::Dtor:
3859 // C++2a [expr.const]p6:
3860 // [during constant destruction] the lifetime of a and its non-mutable
3861 // subobjects (but not its mutable subobjects) [are] considered to start
3862 // within e.
3863 if (MutableSubobject || Base != Info.EvaluatingDecl)
3864 return false;
3865 // FIXME: We can meaningfully extend this to cover non-const objects, but
3866 // we will need special handling: we should be able to access only
3867 // subobjects of such objects that are themselves declared const.
3869 return T.isConstQualified() || T->isReferenceType();
3870 }
3871
3872 llvm_unreachable("unknown evaluating decl kind");
3873}
3874
3875static bool CheckArraySize(EvalInfo &Info, const ConstantArrayType *CAT,
3876 SourceLocation CallLoc = {}) {
3877 return Info.CheckArraySize(
3878 CAT->getSizeExpr() ? CAT->getSizeExpr()->getBeginLoc() : CallLoc,
3879 CAT->getNumAddressingBits(Info.Ctx), CAT->getZExtSize(),
3880 /*Diag=*/true);
3881}
3882
3883static bool handleScalarCast(EvalInfo &Info, const FPOptions FPO, const Expr *E,
3884 QualType SourceTy, QualType DestTy,
3885 APValue const &Original, APValue &Result) {
3886 // boolean must be checked before integer
3887 // since IsIntegerType() is true for bool
3888 if (SourceTy->isBooleanType()) {
3889 if (DestTy->isBooleanType()) {
3890 Result = Original;
3891 return true;
3892 }
3893 if (DestTy->isIntegerType() || DestTy->isRealFloatingType()) {
3894 bool BoolResult;
3895 if (!HandleConversionToBool(Original, BoolResult))
3896 return false;
3897 uint64_t IntResult = BoolResult;
3898 QualType IntType = DestTy->isIntegerType()
3899 ? DestTy
3900 : Info.Ctx.getIntTypeForBitwidth(64, false);
3901 Result = APValue(Info.Ctx.MakeIntValue(IntResult, IntType));
3902 }
3903 if (DestTy->isRealFloatingType()) {
3904 APValue Result2 = APValue(APFloat(0.0));
3905 if (!HandleIntToFloatCast(Info, E, FPO,
3906 Info.Ctx.getIntTypeForBitwidth(64, false),
3907 Result.getInt(), DestTy, Result2.getFloat()))
3908 return false;
3909 Result = std::move(Result2);
3910 }
3911 return true;
3912 }
3913 if (SourceTy->isIntegerType()) {
3914 if (DestTy->isRealFloatingType()) {
3915 Result = APValue(APFloat(0.0));
3916 return HandleIntToFloatCast(Info, E, FPO, SourceTy, Original.getInt(),
3917 DestTy, Result.getFloat());
3918 }
3919 if (DestTy->isBooleanType()) {
3920 bool BoolResult;
3921 if (!HandleConversionToBool(Original, BoolResult))
3922 return false;
3923 uint64_t IntResult = BoolResult;
3924 Result = APValue(Info.Ctx.MakeIntValue(IntResult, DestTy));
3925 return true;
3926 }
3927 if (DestTy->isIntegerType()) {
3928 Result = APValue(
3929 HandleIntToIntCast(Info, E, DestTy, SourceTy, Original.getInt()));
3930 return true;
3931 }
3932 } else if (SourceTy->isRealFloatingType()) {
3933 if (DestTy->isRealFloatingType()) {
3934 Result = Original;
3935 return HandleFloatToFloatCast(Info, E, SourceTy, DestTy,
3936 Result.getFloat());
3937 }
3938 if (DestTy->isBooleanType()) {
3939 bool BoolResult;
3940 if (!HandleConversionToBool(Original, BoolResult))
3941 return false;
3942 uint64_t IntResult = BoolResult;
3943 Result = APValue(Info.Ctx.MakeIntValue(IntResult, DestTy));
3944 return true;
3945 }
3946 if (DestTy->isIntegerType()) {
3947 Result = APValue(APSInt());
3948 return HandleFloatToIntCast(Info, E, SourceTy, Original.getFloat(),
3949 DestTy, Result.getInt());
3950 }
3951 }
3952
3953 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3954 return false;
3955}
3956
3957// do the heavy lifting for casting to aggregate types
3958// because we have to deal with bitfields specially
3959static bool constructAggregate(EvalInfo &Info, const FPOptions FPO,
3960 const Expr *E, APValue &Result,
3961 QualType ResultType,
3962 SmallVectorImpl<APValue> &Elements,
3963 SmallVectorImpl<QualType> &ElTypes) {
3964
3966 {&Result, ResultType, 0}};
3967
3968 unsigned ElI = 0;
3969 while (!WorkList.empty() && ElI < Elements.size()) {
3970 auto [Res, Type, BitWidth] = WorkList.pop_back_val();
3971
3972 if (Type->isRealFloatingType()) {
3973 if (!handleScalarCast(Info, FPO, E, ElTypes[ElI], Type, Elements[ElI],
3974 *Res))
3975 return false;
3976 ElI++;
3977 continue;
3978 }
3979 if (Type->isIntegerType()) {
3980 if (!handleScalarCast(Info, FPO, E, ElTypes[ElI], Type, Elements[ElI],
3981 *Res))
3982 return false;
3983 if (BitWidth > 0) {
3984 if (!Res->isInt())
3985 return false;
3986 APSInt &Int = Res->getInt();
3987 unsigned OldBitWidth = Int.getBitWidth();
3988 unsigned NewBitWidth = BitWidth;
3989 if (NewBitWidth < OldBitWidth)
3990 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
3991 }
3992 ElI++;
3993 continue;
3994 }
3995 if (Type->isVectorType()) {
3996 QualType ElTy = Type->castAs<VectorType>()->getElementType();
3997 unsigned NumEl = Type->castAs<VectorType>()->getNumElements();
3998 SmallVector<APValue> Vals(NumEl);
3999 for (unsigned I = 0; I < NumEl; ++I) {
4000 if (!handleScalarCast(Info, FPO, E, ElTypes[ElI], ElTy, Elements[ElI],
4001 Vals[I]))
4002 return false;
4003 ElI++;
4004 }
4005 *Res = APValue(Vals.data(), NumEl);
4006 continue;
4007 }
4008 if (Type->isConstantArrayType()) {
4009 QualType ElTy = cast<ConstantArrayType>(Info.Ctx.getAsArrayType(Type))
4010 ->getElementType();
4011 uint64_t Size =
4012 cast<ConstantArrayType>(Info.Ctx.getAsArrayType(Type))->getZExtSize();
4013 *Res = APValue(APValue::UninitArray(), Size, Size);
4014 for (int64_t I = Size - 1; I > -1; --I)
4015 WorkList.emplace_back(&Res->getArrayInitializedElt(I), ElTy, 0u);
4016 continue;
4017 }
4018 if (Type->isRecordType()) {
4019 const RecordDecl *RD = Type->getAsRecordDecl();
4020
4021 unsigned NumBases = 0;
4022 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
4023 NumBases = CXXRD->getNumBases();
4024
4025 *Res = APValue(APValue::UninitStruct(), NumBases, RD->getNumFields());
4026
4028 // we need to traverse backwards
4029 // Visit the base classes.
4030 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
4031 if (CXXRD->getNumBases() > 0) {
4032 assert(CXXRD->getNumBases() == 1);
4033 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[0];
4034 ReverseList.emplace_back(&Res->getStructBase(0), BS.getType(), 0u);
4035 }
4036 }
4037
4038 // Visit the fields.
4039 for (FieldDecl *FD : RD->fields()) {
4040 unsigned FDBW = 0;
4041 if (FD->isUnnamedBitField())
4042 continue;
4043 if (FD->isBitField()) {
4044 FDBW = FD->getBitWidthValue();
4045 }
4046
4047 ReverseList.emplace_back(&Res->getStructField(FD->getFieldIndex()),
4048 FD->getType(), FDBW);
4049 }
4050
4051 std::reverse(ReverseList.begin(), ReverseList.end());
4052 llvm::append_range(WorkList, ReverseList);
4053 continue;
4054 }
4055 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
4056 return false;
4057 }
4058 return true;
4059}
4060
4061static bool handleElementwiseCast(EvalInfo &Info, const Expr *E,
4062 const FPOptions FPO,
4063 SmallVectorImpl<APValue> &Elements,
4064 SmallVectorImpl<QualType> &SrcTypes,
4065 SmallVectorImpl<QualType> &DestTypes,
4066 SmallVectorImpl<APValue> &Results) {
4067
4068 assert((Elements.size() == SrcTypes.size()) &&
4069 (Elements.size() == DestTypes.size()));
4070
4071 for (unsigned I = 0, ESz = Elements.size(); I < ESz; ++I) {
4072 APValue Original = Elements[I];
4073 QualType SourceTy = SrcTypes[I];
4074 QualType DestTy = DestTypes[I];
4075
4076 if (!handleScalarCast(Info, FPO, E, SourceTy, DestTy, Original, Results[I]))
4077 return false;
4078 }
4079 return true;
4080}
4081
4082static unsigned elementwiseSize(EvalInfo &Info, QualType BaseTy) {
4083
4084 SmallVector<QualType> WorkList = {BaseTy};
4085
4086 unsigned Size = 0;
4087 while (!WorkList.empty()) {
4088 QualType Type = WorkList.pop_back_val();
4090 Type->isBooleanType()) {
4091 ++Size;
4092 continue;
4093 }
4094 if (Type->isVectorType()) {
4095 unsigned NumEl = Type->castAs<VectorType>()->getNumElements();
4096 Size += NumEl;
4097 continue;
4098 }
4099 if (Type->isConstantMatrixType()) {
4100 unsigned NumEl =
4101 Type->castAs<ConstantMatrixType>()->getNumElementsFlattened();
4102 Size += NumEl;
4103 continue;
4104 }
4105 if (Type->isConstantArrayType()) {
4106 QualType ElTy = cast<ConstantArrayType>(Info.Ctx.getAsArrayType(Type))
4107 ->getElementType();
4108 uint64_t ArrSize =
4109 cast<ConstantArrayType>(Info.Ctx.getAsArrayType(Type))->getZExtSize();
4110 for (uint64_t I = 0; I < ArrSize; ++I) {
4111 WorkList.push_back(ElTy);
4112 }
4113 continue;
4114 }
4115 if (Type->isRecordType()) {
4116 const RecordDecl *RD = Type->getAsRecordDecl();
4117
4118 // Visit the base classes.
4119 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
4120 if (CXXRD->getNumBases() > 0) {
4121 assert(CXXRD->getNumBases() == 1);
4122 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[0];
4123 WorkList.push_back(BS.getType());
4124 }
4125 }
4126
4127 // visit the fields.
4128 for (FieldDecl *FD : RD->fields()) {
4129 if (FD->isUnnamedBitField())
4130 continue;
4131 WorkList.push_back(FD->getType());
4132 }
4133 continue;
4134 }
4135 }
4136 return Size;
4137}
4138
4139static bool hlslAggSplatHelper(EvalInfo &Info, const Expr *E, APValue &SrcVal,
4140 QualType &SrcTy) {
4141 SrcTy = E->getType();
4142
4143 if (!Evaluate(SrcVal, Info, E))
4144 return false;
4145
4146 assert((SrcVal.isFloat() || SrcVal.isInt() ||
4147 (SrcVal.isVector() && SrcVal.getVectorLength() == 1)) &&
4148 "Not a valid HLSLAggregateSplatCast.");
4149
4150 if (SrcVal.isVector()) {
4151 assert(SrcTy->isVectorType() && "Type mismatch.");
4152 SrcTy = SrcTy->castAs<VectorType>()->getElementType();
4153 SrcVal = SrcVal.getVectorElt(0);
4154 }
4155 if (SrcVal.isMatrix()) {
4156 assert(SrcTy->isConstantMatrixType() && "Type mismatch.");
4157 SrcTy = SrcTy->castAs<ConstantMatrixType>()->getElementType();
4158 SrcVal = SrcVal.getMatrixElt(0, 0);
4159 }
4160 return true;
4161}
4162
4163static bool flattenAPValue(EvalInfo &Info, const Expr *E, APValue Value,
4164 QualType BaseTy, SmallVectorImpl<APValue> &Elements,
4165 SmallVectorImpl<QualType> &Types, unsigned Size) {
4166
4167 SmallVector<std::pair<APValue, QualType>> WorkList = {{Value, BaseTy}};
4168 unsigned Populated = 0;
4169 while (!WorkList.empty() && Populated < Size) {
4170 auto [Work, Type] = WorkList.pop_back_val();
4171
4172 if (Work.isFloat() || Work.isInt()) {
4173 Elements.push_back(Work);
4174 Types.push_back(Type);
4175 Populated++;
4176 continue;
4177 }
4178 if (Work.isVector()) {
4179 assert(Type->isVectorType() && "Type mismatch.");
4180 QualType ElTy = Type->castAs<VectorType>()->getElementType();
4181 for (unsigned I = 0; I < Work.getVectorLength() && Populated < Size;
4182 I++) {
4183 Elements.push_back(Work.getVectorElt(I));
4184 Types.push_back(ElTy);
4185 Populated++;
4186 }
4187 continue;
4188 }
4189 if (Work.isMatrix()) {
4190 assert(Type->isConstantMatrixType() && "Type mismatch.");
4191 const auto *MT = Type->castAs<ConstantMatrixType>();
4192 QualType ElTy = MT->getElementType();
4193 // Matrix elements are flattened in row-major order.
4194 for (unsigned Row = 0; Row < Work.getMatrixNumRows() && Populated < Size;
4195 Row++) {
4196 for (unsigned Col = 0;
4197 Col < Work.getMatrixNumColumns() && Populated < Size; Col++) {
4198 Elements.push_back(Work.getMatrixElt(Row, Col));
4199 Types.push_back(ElTy);
4200 Populated++;
4201 }
4202 }
4203 continue;
4204 }
4205 if (Work.isArray()) {
4206 assert(Type->isConstantArrayType() && "Type mismatch.");
4207 QualType ElTy = cast<ConstantArrayType>(Info.Ctx.getAsArrayType(Type))
4208 ->getElementType();
4209 for (int64_t I = Work.getArraySize() - 1; I > -1; --I) {
4210 WorkList.emplace_back(Work.getArrayInitializedElt(I), ElTy);
4211 }
4212 continue;
4213 }
4214
4215 if (Work.isStruct()) {
4216 assert(Type->isRecordType() && "Type mismatch.");
4217
4218 const RecordDecl *RD = Type->getAsRecordDecl();
4219
4221 // Visit the fields.
4222 for (FieldDecl *FD : RD->fields()) {
4223 if (FD->isUnnamedBitField())
4224 continue;
4225 ReverseList.emplace_back(Work.getStructField(FD->getFieldIndex()),
4226 FD->getType());
4227 }
4228
4229 std::reverse(ReverseList.begin(), ReverseList.end());
4230 llvm::append_range(WorkList, ReverseList);
4231
4232 // Visit the base classes.
4233 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
4234 if (CXXRD->getNumBases() > 0) {
4235 assert(CXXRD->getNumBases() == 1);
4236 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[0];
4237 const APValue &Base = Work.getStructBase(0);
4238
4239 // Can happen in error cases.
4240 if (!Base.isStruct())
4241 return false;
4242
4243 WorkList.emplace_back(Base, BS.getType());
4244 }
4245 }
4246 continue;
4247 }
4248 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
4249 return false;
4250 }
4251 return true;
4252}
4253
4254namespace {
4255/// A handle to a complete object (an object that is not a subobject of
4256/// another object).
4257struct CompleteObject {
4258 /// The identity of the object.
4259 APValue::LValueBase Base;
4260 /// The value of the complete object.
4261 APValue *Value;
4262 /// The type of the complete object.
4263 QualType Type;
4264
4265 CompleteObject() : Value(nullptr) {}
4266 CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
4267 : Base(Base), Value(Value), Type(Type) {}
4268
4269 bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const {
4270 // If this isn't a "real" access (eg, if it's just accessing the type
4271 // info), allow it. We assume the type doesn't change dynamically for
4272 // subobjects of constexpr objects (even though we'd hit UB here if it
4273 // did). FIXME: Is this right?
4274 if (!isAnyAccess(AK))
4275 return true;
4276
4277 // In C++14 onwards, it is permitted to read a mutable member whose
4278 // lifetime began within the evaluation.
4279 // FIXME: Should we also allow this in C++11?
4280 if (!Info.getLangOpts().CPlusPlus14 &&
4281 AK != AccessKinds::AK_IsWithinLifetime)
4282 return false;
4283 return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);
4284 }
4285
4286 explicit operator bool() const { return !Type.isNull(); }
4287};
4288} // end anonymous namespace
4289
4290static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
4291 bool IsMutable = false) {
4292 // C++ [basic.type.qualifier]p1:
4293 // - A const object is an object of type const T or a non-mutable subobject
4294 // of a const object.
4295 if (ObjType.isConstQualified() && !IsMutable)
4296 SubobjType.addConst();
4297 // - A volatile object is an object of type const T or a subobject of a
4298 // volatile object.
4299 if (ObjType.isVolatileQualified())
4300 SubobjType.addVolatile();
4301 return SubobjType;
4302}
4303
4304/// Find the designated sub-object of an rvalue.
4305template <typename SubobjectHandler>
4306static typename SubobjectHandler::result_type
4307findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
4308 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
4309 if (Sub.Invalid)
4310 // A diagnostic will have already been produced.
4311 return handler.failed();
4312 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
4313 if (Info.getLangOpts().CPlusPlus11)
4314 Info.FFDiag(E, Sub.isOnePastTheEnd()
4315 ? diag::note_constexpr_access_past_end
4316 : diag::note_constexpr_access_unsized_array)
4317 << handler.AccessKind;
4318 else
4319 Info.FFDiag(E);
4320 return handler.failed();
4321 }
4322
4323 APValue *O = Obj.Value;
4324 QualType ObjType = Obj.Type;
4325 const FieldDecl *LastField = nullptr;
4326 const FieldDecl *VolatileField = nullptr;
4327
4328 // Walk the designator's path to find the subobject.
4329 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
4330 // Reading an indeterminate value is undefined, but assigning over one is OK.
4331 if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) ||
4332 (O->isIndeterminate() &&
4333 !isValidIndeterminateAccess(handler.AccessKind))) {
4334 // Object has ended lifetime.
4335 // If I is non-zero, some subobject (member or array element) of a
4336 // complete object has ended its lifetime, so this is valid for
4337 // IsWithinLifetime, resulting in false.
4338 if (I != 0 && handler.AccessKind == AK_IsWithinLifetime)
4339 return false;
4340 if (!Info.checkingPotentialConstantExpression()) {
4341 Info.FFDiag(E, diag::note_constexpr_access_uninit)
4342 << handler.AccessKind << O->isIndeterminate()
4343 << E->getSourceRange();
4344 NoteLValueLocation(Info, Obj.Base);
4345 }
4346 return handler.failed();
4347 }
4348
4349 // C++ [class.ctor]p5, C++ [class.dtor]p5:
4350 // const and volatile semantics are not applied on an object under
4351 // {con,de}struction.
4352 if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
4353 ObjType->isRecordType() &&
4354 Info.isEvaluatingCtorDtor(
4355 Obj.Base, ArrayRef(Sub.Entries.begin(), Sub.Entries.begin() + I)) !=
4356 ConstructionPhase::None) {
4357 ObjType = Info.Ctx.getCanonicalType(ObjType);
4358 ObjType.removeLocalConst();
4359 ObjType.removeLocalVolatile();
4360 }
4361
4362 // If this is our last pass, check that the final object type is OK.
4363 if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
4364 // Accesses to volatile objects are prohibited.
4365 if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
4366 if (Info.getLangOpts().CPlusPlus) {
4367 int DiagKind;
4368 SourceLocation Loc;
4369 const NamedDecl *Decl = nullptr;
4370 if (VolatileField) {
4371 DiagKind = 2;
4372 Loc = VolatileField->getLocation();
4373 Decl = VolatileField;
4374 } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
4375 DiagKind = 1;
4376 Loc = VD->getLocation();
4377 Decl = VD;
4378 } else {
4379 DiagKind = 0;
4380 if (auto *E = Obj.Base.dyn_cast<const Expr *>())
4381 Loc = E->getExprLoc();
4382 }
4383 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
4384 << handler.AccessKind << DiagKind << Decl;
4385 Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
4386 } else {
4387 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
4388 }
4389 return handler.failed();
4390 }
4391
4392 // If we are reading an object of class type, there may still be more
4393 // things we need to check: if there are any mutable subobjects, we
4394 // cannot perform this read. (This only happens when performing a trivial
4395 // copy or assignment.)
4396 if (ObjType->isRecordType() &&
4397 !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
4398 diagnoseMutableFields(Info, E, handler.AccessKind, ObjType))
4399 return handler.failed();
4400 }
4401
4402 if (I == N) {
4403 if (!handler.found(*O, ObjType, Obj.Base))
4404 return false;
4405
4406 // If we modified a bit-field, truncate it to the right width.
4407 if (isModification(handler.AccessKind) &&
4408 LastField && LastField->isBitField() &&
4409 !truncateBitfieldValue(Info, E, *O, LastField))
4410 return false;
4411
4412 return true;
4413 }
4414
4415 LastField = nullptr;
4416
4417 // The value of an atomic object is represented like a value of the
4418 // underlying type, so look through the _Atomic wrapper.
4419 if (const AtomicType *AT = ObjType->getAs<AtomicType>())
4420 ObjType = Info.Ctx.getQualifiedType(AT->getValueType(),
4421 ObjType.getQualifiers());
4422
4423 if (ObjType->isArrayType()) {
4424 // Next subobject is an array element.
4425 const ArrayType *AT = Info.Ctx.getAsArrayType(ObjType);
4427 "vla in literal type?");
4428 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
4429 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT);
4430 CAT && CAT->getSize().ule(Index)) {
4431 // Note, it should not be possible to form a pointer with a valid
4432 // designator which points more than one past the end of the array.
4433 if (Info.getLangOpts().CPlusPlus11)
4434 Info.FFDiag(E, diag::note_constexpr_access_past_end)
4435 << handler.AccessKind;
4436 else
4437 Info.FFDiag(E);
4438 return handler.failed();
4439 }
4440
4441 ObjType = AT->getElementType();
4442
4443 if (O->getArrayInitializedElts() > Index)
4444 O = &O->getArrayInitializedElt(Index);
4445 else if (!isRead(handler.AccessKind)) {
4446 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT);
4447 CAT && !CheckArraySize(Info, CAT, E->getExprLoc()))
4448 return handler.failed();
4449
4450 expandArray(*O, Index);
4451 O = &O->getArrayInitializedElt(Index);
4452 } else
4453 O = &O->getArrayFiller();
4454 } else if (ObjType->isAnyComplexType()) {
4455 // Next subobject is a complex number.
4456 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
4457 if (Index > 1) {
4458 if (Info.getLangOpts().CPlusPlus11)
4459 Info.FFDiag(E, diag::note_constexpr_access_past_end)
4460 << handler.AccessKind;
4461 else
4462 Info.FFDiag(E);
4463 return handler.failed();
4464 }
4465
4466 ObjType = getSubobjectType(
4467 ObjType, ObjType->castAs<ComplexType>()->getElementType());
4468
4469 assert(I == N - 1 && "extracting subobject of scalar?");
4470 if (O->isComplexInt()) {
4471 return handler.found(Index ? O->getComplexIntImag()
4472 : O->getComplexIntReal(), ObjType);
4473 } else {
4474 assert(O->isComplexFloat());
4475 return handler.found(Index ? O->getComplexFloatImag()
4476 : O->getComplexFloatReal(), ObjType);
4477 }
4478 } else if (const auto *VT = ObjType->getAs<VectorType>()) {
4479 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
4480 unsigned NumElements = VT->getNumElements();
4481 if (Index == NumElements) {
4482 if (Info.getLangOpts().CPlusPlus11)
4483 Info.FFDiag(E, diag::note_constexpr_access_past_end)
4484 << handler.AccessKind;
4485 else
4486 Info.FFDiag(E);
4487 return handler.failed();
4488 }
4489
4490 if (Index > NumElements) {
4491 Info.CCEDiag(E, diag::note_constexpr_array_index)
4492 << Index << /*array*/ 0 << NumElements;
4493 return handler.failed();
4494 }
4495
4496 ObjType = VT->getElementType();
4497 assert(I == N - 1 && "extracting subobject of scalar?");
4498
4499 if (O->isIndeterminate()) {
4500 if (isRead(handler.AccessKind)) {
4501 Info.FFDiag(E);
4502 return handler.failed();
4503 }
4504 expandVector(*O, NumElements);
4505 }
4506 assert(O->isVector() && "unexpected object during vector element access");
4507 return handler.found(O->getVectorElt(Index), ObjType, Obj.Base);
4508 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
4509 if (Field->isMutable() &&
4510 !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) {
4511 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
4512 << handler.AccessKind << Field;
4513 Info.Note(Field->getLocation(), diag::note_declared_at);
4514 return handler.failed();
4515 }
4516
4517 // Next subobject is a class, struct or union field.
4518 RecordDecl *RD = ObjType->castAsCanonical<RecordType>()->getDecl();
4519 if (RD->isUnion()) {
4520 const FieldDecl *UnionField = O->getUnionField();
4521 if (!UnionField ||
4522 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
4523 if (I == N - 1 && handler.AccessKind == AK_Construct) {
4524 // Placement new onto an inactive union member makes it active.
4525 O->setUnion(Field, APValue());
4526 } else {
4527 // Pointer to/into inactive union member: Not within lifetime
4528 if (handler.AccessKind == AK_IsWithinLifetime)
4529 return false;
4530 // FIXME: If O->getUnionValue() is absent, report that there's no
4531 // active union member rather than reporting the prior active union
4532 // member. We'll need to fix nullptr_t to not use APValue() as its
4533 // representation first.
4534 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
4535 << handler.AccessKind << Field << !UnionField << UnionField;
4536 return handler.failed();
4537 }
4538 }
4539 O = &O->getUnionValue();
4540 } else
4541 O = &O->getStructField(Field->getFieldIndex());
4542
4543 ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
4544 LastField = Field;
4545 if (Field->getType().isVolatileQualified())
4546 VolatileField = Field;
4547 } else {
4548 // Next subobject is a base class.
4549 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
4550 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
4551
4552 unsigned BaseIndex = getBaseIndex(Derived, Base);
4553 unsigned NumNonVirtualBases = O->getStructNumBases();
4554 if (BaseIndex >= NumNonVirtualBases) {
4555 O = &O->getStructVirtualBase(BaseIndex - NumNonVirtualBases);
4556 } else
4557 O = &O->getStructBase(BaseIndex);
4558
4559 ObjType = getSubobjectType(ObjType, Info.Ctx.getCanonicalTagType(Base));
4560 }
4561 }
4562}
4563
4564namespace {
4565struct ExtractSubobjectHandler {
4566 EvalInfo &Info;
4567 const Expr *E;
4568 APValue &Result;
4569 const AccessKinds AccessKind;
4570
4571 typedef bool result_type;
4572 bool failed() { return false; }
4573 bool found(APValue &Subobj, QualType SubobjType, APValue::LValueBase Base) {
4574 Result = Subobj;
4575 if (AccessKind == AK_ReadObjectRepresentation)
4576 return true;
4577 return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
4578 }
4579 bool found(APSInt &Value, QualType SubobjType) {
4580 Result = APValue(Value);
4581 return true;
4582 }
4583 bool found(APFloat &Value, QualType SubobjType) {
4584 Result = APValue(Value);
4585 return true;
4586 }
4587};
4588} // end anonymous namespace
4589
4590/// Extract the designated sub-object of an rvalue.
4591static bool extractSubobject(EvalInfo &Info, const Expr *E,
4592 const CompleteObject &Obj,
4593 const SubobjectDesignator &Sub, APValue &Result,
4594 AccessKinds AK = AK_Read) {
4595 assert(AK == AK_Read || AK == AK_ReadObjectRepresentation);
4596 ExtractSubobjectHandler Handler = {Info, E, Result, AK};
4597 return findSubobject(Info, E, Obj, Sub, Handler);
4598}
4599
4600namespace {
4601struct ModifySubobjectHandler {
4602 EvalInfo &Info;
4603 APValue &NewVal;
4604 const Expr *E;
4605
4606 typedef bool result_type;
4607 static const AccessKinds AccessKind = AK_Assign;
4608
4609 bool checkConst(QualType QT) {
4610 // Assigning to a const object has undefined behavior.
4611 if (QT.isConstQualified()) {
4612 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4613 return false;
4614 }
4615 return true;
4616 }
4617
4618 bool failed() { return false; }
4619 bool found(APValue &Subobj, QualType SubobjType, APValue::LValueBase Base) {
4620 if (!checkConst(SubobjType))
4621 return false;
4622 // We've been given ownership of NewVal, so just swap it in.
4623 Subobj.swap(NewVal);
4624 return true;
4625 }
4626 bool found(APSInt &Value, QualType SubobjType) {
4627 if (!checkConst(SubobjType))
4628 return false;
4629 if (!NewVal.isInt()) {
4630 // Maybe trying to write a cast pointer value into a complex?
4631 Info.FFDiag(E);
4632 return false;
4633 }
4634 Value = NewVal.getInt();
4635 return true;
4636 }
4637 bool found(APFloat &Value, QualType SubobjType) {
4638 if (!checkConst(SubobjType))
4639 return false;
4640 Value = NewVal.getFloat();
4641 return true;
4642 }
4643};
4644} // end anonymous namespace
4645
4646const AccessKinds ModifySubobjectHandler::AccessKind;
4647
4648/// Update the designated sub-object of an rvalue to the given value.
4649static bool modifySubobject(EvalInfo &Info, const Expr *E,
4650 const CompleteObject &Obj,
4651 const SubobjectDesignator &Sub,
4652 APValue &NewVal) {
4653 ModifySubobjectHandler Handler = { Info, NewVal, E };
4654 return findSubobject(Info, E, Obj, Sub, Handler);
4655}
4656
4657/// Find the position where two subobject designators diverge, or equivalently
4658/// the length of the common initial subsequence.
4659static unsigned FindDesignatorMismatch(QualType ObjType,
4660 const SubobjectDesignator &A,
4661 const SubobjectDesignator &B,
4662 bool &WasArrayIndex) {
4663 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
4664 for (/**/; I != N; ++I) {
4665 if (!ObjType.isNull() &&
4666 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
4667 // Next subobject is an array element.
4668 if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
4669 WasArrayIndex = true;
4670 return I;
4671 }
4672 if (ObjType->isAnyComplexType())
4673 ObjType = ObjType->castAs<ComplexType>()->getElementType();
4674 else
4675 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
4676 } else {
4677 if (A.Entries[I].getAsBaseOrMember() !=
4678 B.Entries[I].getAsBaseOrMember()) {
4679 WasArrayIndex = false;
4680 return I;
4681 }
4682 if (const FieldDecl *FD = getAsField(A.Entries[I]))
4683 // Next subobject is a field.
4684 ObjType = FD->getType();
4685 else
4686 // Next subobject is a base class.
4687 ObjType = QualType();
4688 }
4689 }
4690 WasArrayIndex = false;
4691 return I;
4692}
4693
4694/// Determine whether the given subobject designators refer to elements of the
4695/// same array object.
4697 const SubobjectDesignator &A,
4698 const SubobjectDesignator &B) {
4699 if (A.Entries.size() != B.Entries.size())
4700 return false;
4701
4702 bool IsArray = A.MostDerivedIsArrayElement;
4703 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
4704 // A is a subobject of the array element.
4705 return false;
4706
4707 // If A (and B) designates an array element, the last entry will be the array
4708 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
4709 // of length 1' case, and the entire path must match.
4710 bool WasArrayIndex;
4711 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
4712 return CommonLength >= A.Entries.size() - IsArray;
4713}
4714
4715/// Find the complete object to which an LValue refers.
4716static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
4717 AccessKinds AK, const LValue &LVal,
4718 QualType LValType) {
4719 if (LVal.InvalidBase) {
4720 Info.FFDiag(E);
4721 return CompleteObject();
4722 }
4723
4724 if (!LVal.Base) {
4726 Info.FFDiag(E, diag::note_constexpr_dereferencing_null);
4727 else
4728 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
4729 return CompleteObject();
4730 }
4731
4732 CallStackFrame *Frame = nullptr;
4733 unsigned Depth = 0;
4734 if (LVal.getLValueCallIndex()) {
4735 std::tie(Frame, Depth) =
4736 Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
4737 if (!Frame) {
4738 Info.FFDiag(E, diag::note_constexpr_access_uninit, 1)
4739 << AK << /*Indeterminate=*/false << E->getSourceRange();
4740 NoteLValueLocation(Info, LVal.Base);
4741 return CompleteObject();
4742 }
4743 }
4744
4745 bool IsAccess = isAnyAccess(AK);
4746
4747 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
4748 // is not a constant expression (even if the object is non-volatile). We also
4749 // apply this rule to C++98, in order to conform to the expected 'volatile'
4750 // semantics.
4751 if (isFormalAccess(AK) && LValType.isVolatileQualified()) {
4752 if (Info.getLangOpts().CPlusPlus)
4753 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
4754 << AK << LValType;
4755 else
4756 Info.FFDiag(E);
4757 return CompleteObject();
4758 }
4759
4760 // Compute value storage location and type of base object.
4761 APValue *BaseVal = nullptr;
4762 QualType BaseType = getType(LVal.Base);
4763
4764 if (Info.getLangOpts().CPlusPlus14 && LVal.Base == Info.EvaluatingDecl &&
4765 lifetimeStartedInEvaluation(Info, LVal.Base)) {
4766 // This is the object whose initializer we're evaluating, so its lifetime
4767 // started in the current evaluation.
4768 BaseVal = Info.EvaluatingDeclValue;
4769 } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) {
4770 // Allow reading from a GUID declaration.
4771 if (auto *GD = dyn_cast<MSGuidDecl>(D)) {
4772 if (isModification(AK)) {
4773 // All the remaining cases do not permit modification of the object.
4774 Info.FFDiag(E, diag::note_constexpr_modify_global);
4775 return CompleteObject();
4776 }
4777 APValue &V = GD->getAsAPValue();
4778 if (V.isAbsent()) {
4779 Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
4780 << GD->getType();
4781 return CompleteObject();
4782 }
4783 return CompleteObject(LVal.Base, &V, GD->getType());
4784 }
4785
4786 // Allow reading the APValue from an UnnamedGlobalConstantDecl.
4787 if (auto *GCD = dyn_cast<UnnamedGlobalConstantDecl>(D)) {
4788 if (isModification(AK)) {
4789 Info.FFDiag(E, diag::note_constexpr_modify_global);
4790 return CompleteObject();
4791 }
4792 return CompleteObject(LVal.Base, const_cast<APValue *>(&GCD->getValue()),
4793 GCD->getType());
4794 }
4795
4796 // Allow reading from template parameter objects.
4797 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) {
4798 if (isModification(AK)) {
4799 Info.FFDiag(E, diag::note_constexpr_modify_global);
4800 return CompleteObject();
4801 }
4802 return CompleteObject(LVal.Base, const_cast<APValue *>(&TPO->getValue()),
4803 TPO->getType());
4804 }
4805
4806 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
4807 // In C++11, constexpr, non-volatile variables initialized with constant
4808 // expressions are constant expressions too. Inside constexpr functions,
4809 // parameters are constant expressions even if they're non-const.
4810 // In C++1y, objects local to a constant expression (those with a Frame) are
4811 // both readable and writable inside constant expressions.
4812 // In C, such things can also be folded, although they are not ICEs.
4813 const VarDecl *VD = dyn_cast<VarDecl>(D);
4814 if (VD) {
4815 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
4816 VD = VDef;
4817 }
4818 if (!VD || VD->isInvalidDecl()) {
4819 Info.FFDiag(E);
4820 return CompleteObject();
4821 }
4822
4823 bool IsConstant = BaseType.isConstant(Info.Ctx);
4824 bool ConstexprVar = false;
4825 if (const auto *VD = dyn_cast_if_present<VarDecl>(
4826 Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()))
4827 ConstexprVar = VD->isConstexpr();
4828
4829 // Unless we're looking at a local variable or argument in a constexpr call,
4830 // the variable we're reading must be const (unless we are binding to a
4831 // reference).
4832 if (AK != clang::AK_Dereference && !Frame) {
4833 if (IsAccess && isa<ParmVarDecl>(VD)) {
4834 // Access of a parameter that's not associated with a frame isn't going
4835 // to work out, but we can leave it to evaluateVarDeclInit to provide a
4836 // suitable diagnostic.
4837 } else if (Info.getLangOpts().CPlusPlus14 &&
4838 lifetimeStartedInEvaluation(Info, LVal.Base)) {
4839 // OK, we can read and modify an object if we're in the process of
4840 // evaluating its initializer, because its lifetime began in this
4841 // evaluation.
4842 } else if (isModification(AK)) {
4843 // All the remaining cases do not permit modification of the object.
4844 Info.FFDiag(E, diag::note_constexpr_modify_global);
4845 return CompleteObject();
4846 } else if (VD->isConstexpr()) {
4847 // OK, we can read this variable.
4848 } else if (Info.getLangOpts().C23 && ConstexprVar) {
4849 Info.FFDiag(E);
4850 return CompleteObject();
4851 } else if (VD->isCXXForRangeImplicitVar()) {
4852 if (!IsAccess)
4853 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4854 Info.FFDiag(E, diag::note_constexpr_ltor_for_range_var) << VD;
4855 return CompleteObject();
4856 } else if (BaseType->isIntegralOrEnumerationType()) {
4857 if (!IsConstant) {
4858 if (!IsAccess)
4859 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4860 if (Info.getLangOpts().CPlusPlus) {
4861 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
4862 Info.Note(VD->getLocation(), diag::note_declared_at);
4863 } else {
4864 Info.FFDiag(E);
4865 }
4866 return CompleteObject();
4867 }
4868 } else if (!IsAccess) {
4869 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4870 } else if ((IsConstant || BaseType->isReferenceType()) &&
4871 Info.checkingPotentialConstantExpression() &&
4872 BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) {
4873 // This variable might end up being constexpr. Don't diagnose it yet.
4874 } else if (IsConstant) {
4875 // Keep evaluating to see what we can do. In particular, we support
4876 // folding of const floating-point types, in order to make static const
4877 // data members of such types (supported as an extension) more useful.
4878 if (Info.getLangOpts().CPlusPlus) {
4879 Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11
4880 ? diag::note_constexpr_ltor_non_constexpr
4881 : diag::note_constexpr_ltor_non_integral, 1)
4882 << VD << BaseType;
4883 Info.Note(VD->getLocation(), diag::note_declared_at);
4884 } else {
4885 Info.CCEDiag(E);
4886 }
4887 } else {
4888 // Never allow reading a non-const value.
4889 if (Info.getLangOpts().CPlusPlus) {
4890 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
4891 ? diag::note_constexpr_ltor_non_constexpr
4892 : diag::note_constexpr_ltor_non_integral, 1)
4893 << VD << BaseType;
4894 Info.Note(VD->getLocation(), diag::note_declared_at);
4895 } else {
4896 Info.FFDiag(E);
4897 }
4898 return CompleteObject();
4899 }
4900 }
4901
4902 // When binding to a reference, the variable does not need to be constexpr
4903 // or have constant initalization.
4904 if (AK != clang::AK_Dereference &&
4905 !evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(),
4906 BaseVal))
4907 return CompleteObject();
4908 // If evaluateVarDeclInit sees a constexpr-unknown variable, it returns
4909 // a null BaseVal. Any constexpr-unknown variable seen here is an error:
4910 // we can't access a constexpr-unknown object.
4911 if (AK != clang::AK_Dereference && !BaseVal) {
4912 if (!Info.checkingPotentialConstantExpression()) {
4913 Info.FFDiag(E, diag::note_constexpr_access_unknown_variable, 1)
4914 << AK << VD;
4915 Info.Note(VD->getLocation(), diag::note_declared_at);
4916 }
4917 return CompleteObject();
4918 }
4919 } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) {
4920 std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
4921 if (!Alloc) {
4922 Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK;
4923 return CompleteObject();
4924 }
4925 return CompleteObject(LVal.Base, &(*Alloc)->Value,
4926 LVal.Base.getDynamicAllocType());
4927 }
4928 // When binding to a reference, the variable does not need to be
4929 // within its lifetime.
4930 else if (AK != clang::AK_Dereference) {
4931 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4932
4933 if (!Frame) {
4934 if (const MaterializeTemporaryExpr *MTE =
4935 dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
4936 assert(MTE->getStorageDuration() == SD_Static &&
4937 "should have a frame for a non-global materialized temporary");
4938
4939 // C++20 [expr.const]p4: [DR2126]
4940 // An object or reference is usable in constant expressions if it is
4941 // - a temporary object of non-volatile const-qualified literal type
4942 // whose lifetime is extended to that of a variable that is usable
4943 // in constant expressions
4944 //
4945 // C++20 [expr.const]p5:
4946 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
4947 // - a non-volatile glvalue that refers to an object that is usable
4948 // in constant expressions, or
4949 // - a non-volatile glvalue of literal type that refers to a
4950 // non-volatile object whose lifetime began within the evaluation
4951 // of E;
4952 //
4953 // C++11 misses the 'began within the evaluation of e' check and
4954 // instead allows all temporaries, including things like:
4955 // int &&r = 1;
4956 // int x = ++r;
4957 // constexpr int k = r;
4958 // Therefore we use the C++14-onwards rules in C++11 too.
4959 //
4960 // Note that temporaries whose lifetimes began while evaluating a
4961 // variable's constructor are not usable while evaluating the
4962 // corresponding destructor, not even if they're of const-qualified
4963 // types.
4964 if (!MTE->isUsableInConstantExpressions(Info.Ctx) &&
4965 !lifetimeStartedInEvaluation(Info, LVal.Base)) {
4966 if (!IsAccess)
4967 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4968 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
4969 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
4970 return CompleteObject();
4971 }
4972
4973 BaseVal = MTE->getOrCreateValue(false);
4974 assert(BaseVal && "got reference to unevaluated temporary");
4975 } else if (const CompoundLiteralExpr *CLE =
4976 dyn_cast_or_null<CompoundLiteralExpr>(Base)) {
4977 // According to GCC info page:
4978 //
4979 // 6.28 Compound Literals
4980 //
4981 // As an optimization, G++ sometimes gives array compound literals
4982 // longer lifetimes: when the array either appears outside a function or
4983 // has a const-qualified type. If foo and its initializer had elements
4984 // of type char *const rather than char *, or if foo were a global
4985 // variable, the array would have static storage duration. But it is
4986 // probably safest just to avoid the use of array compound literals in
4987 // C++ code.
4988 //
4989 // Obey that rule by checking constness for converted array types.
4990 if (QualType CLETy = CLE->getType(); CLETy->isArrayType() &&
4991 !LValType->isArrayType() &&
4992 !CLETy.isConstant(Info.Ctx)) {
4993 Info.FFDiag(E);
4994 Info.Note(CLE->getExprLoc(), diag::note_declared_at);
4995 return CompleteObject();
4996 }
4997
4998 BaseVal = &CLE->getStaticValue();
4999 } else {
5000 if (!IsAccess)
5001 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
5002 APValue Val;
5003 LVal.moveInto(Val);
5004 Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
5005 << AK
5006 << Val.getAsString(Info.Ctx,
5007 Info.Ctx.getLValueReferenceType(LValType));
5008 NoteLValueLocation(Info, LVal.Base);
5009 return CompleteObject();
5010 }
5011 } else if (AK != clang::AK_Dereference) {
5012 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
5013 assert(BaseVal && "missing value for temporary");
5014 }
5015 }
5016
5017 // In C++14, we can't safely access any mutable state when we might be
5018 // evaluating after an unmodeled side effect. Parameters are modeled as state
5019 // in the caller, but aren't visible once the call returns, so they can be
5020 // modified in a speculatively-evaluated call.
5021 //
5022 // FIXME: Not all local state is mutable. Allow local constant subobjects
5023 // to be read here (but take care with 'mutable' fields).
5024 unsigned VisibleDepth = Depth;
5025 if (llvm::isa_and_nonnull<ParmVarDecl>(
5026 LVal.Base.dyn_cast<const ValueDecl *>()))
5027 ++VisibleDepth;
5028 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
5029 Info.EvalStatus.HasSideEffects) ||
5030 (isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth))
5031 return CompleteObject();
5032
5033 return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
5034}
5035
5036/// Perform an lvalue-to-rvalue conversion on the given glvalue. This
5037/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
5038/// glvalue referred to by an entity of reference type.
5039///
5040/// \param Info - Information about the ongoing evaluation.
5041/// \param Conv - The expression for which we are performing the conversion.
5042/// Used for diagnostics.
5043/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
5044/// case of a non-class type).
5045/// \param LVal - The glvalue on which we are attempting to perform this action.
5046/// \param RVal - The produced value will be placed here.
5047/// \param WantObjectRepresentation - If true, we're looking for the object
5048/// representation rather than the value, and in particular,
5049/// there is no requirement that the result be fully initialized.
5050static bool
5052 const LValue &LVal, APValue &RVal,
5053 bool WantObjectRepresentation = false) {
5054 if (LVal.Designator.Invalid)
5055 return false;
5056
5057 // Check for special cases where there is no existing APValue to look at.
5058 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
5059
5060 AccessKinds AK =
5061 WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;
5062
5063 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
5065 // Special-case character extraction so we don't have to construct an
5066 // APValue for the whole string.
5067 assert(LVal.Designator.Entries.size() <= 1 &&
5068 "Can only read characters from string literals");
5069 if (LVal.Designator.Entries.empty()) {
5070 // Fail for now for LValue to RValue conversion of an array.
5071 // (This shouldn't show up in C/C++, but it could be triggered by a
5072 // weird EvaluateAsRValue call from a tool.)
5073 Info.FFDiag(Conv);
5074 return false;
5075 }
5076 if (LVal.Designator.isOnePastTheEnd()) {
5077 if (Info.getLangOpts().CPlusPlus11)
5078 Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
5079 else
5080 Info.FFDiag(Conv);
5081 return false;
5082 }
5083 uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
5084 RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
5085 return true;
5086 }
5087 }
5088
5089 CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
5090 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
5091}
5092
5093static bool hlslElementwiseCastHelper(EvalInfo &Info, const Expr *E,
5094 QualType DestTy,
5095 SmallVectorImpl<APValue> &SrcVals,
5096 SmallVectorImpl<QualType> &SrcTypes) {
5097 APValue Val;
5098 if (!Evaluate(Val, Info, E))
5099 return false;
5100
5101 // must be dealing with a record
5102 if (Val.isLValue()) {
5103 LValue LVal;
5104 LVal.setFrom(Info.Ctx, Val);
5105 if (!handleLValueToRValueConversion(Info, E, E->getType(), LVal, Val))
5106 return false;
5107 }
5108
5109 unsigned NEls = elementwiseSize(Info, DestTy);
5110 // flatten the source
5111 if (!flattenAPValue(Info, E, Val, E->getType(), SrcVals, SrcTypes, NEls))
5112 return false;
5113
5114 return true;
5115}
5116
5117/// Perform an assignment of Val to LVal. Takes ownership of Val.
5118static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
5119 QualType LValType, APValue &Val) {
5120 if (LVal.Designator.Invalid)
5121 return false;
5122
5123 if (!Info.getLangOpts().CPlusPlus14) {
5124 Info.FFDiag(E);
5125 return false;
5126 }
5127
5128 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
5129 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
5130}
5131
5132namespace {
5133struct CompoundAssignSubobjectHandler {
5134 EvalInfo &Info;
5135 const CompoundAssignOperator *E;
5136 QualType PromotedLHSType;
5138 const APValue &RHS;
5139
5140 static const AccessKinds AccessKind = AK_Assign;
5141
5142 typedef bool result_type;
5143
5144 bool checkConst(QualType QT) {
5145 // Assigning to a const object has undefined behavior.
5146 if (QT.isConstQualified()) {
5147 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
5148 return false;
5149 }
5150 return true;
5151 }
5152
5153 bool failed() { return false; }
5154 bool found(APValue &Subobj, QualType SubobjType, APValue::LValueBase Base) {
5155 switch (Subobj.getKind()) {
5156 case APValue::Int:
5157 return found(Subobj.getInt(), SubobjType);
5158 case APValue::Float:
5159 return found(Subobj.getFloat(), SubobjType);
5162 // FIXME: Implement complex compound assignment.
5163 Info.FFDiag(E);
5164 return false;
5165 case APValue::LValue:
5166 return foundPointer(Subobj, SubobjType);
5167 case APValue::Vector:
5168 return foundVector(Subobj, SubobjType);
5170 Info.FFDiag(E, diag::note_constexpr_access_uninit)
5171 << /*read of=*/0 << /*uninitialized object=*/1
5172 << E->getLHS()->getSourceRange();
5173 NoteLValueLocation(Info, Base);
5174 return false;
5175 default:
5176 // FIXME: can this happen?
5177 Info.FFDiag(E);
5178 return false;
5179 }
5180 }
5181
5182 bool foundVector(APValue &Value, QualType SubobjType) {
5183 if (!checkConst(SubobjType))
5184 return false;
5185
5186 if (!SubobjType->isVectorType()) {
5187 Info.FFDiag(E);
5188 return false;
5189 }
5190 return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS);
5191 }
5192
5193 bool found(APSInt &Value, QualType SubobjType) {
5194 if (!checkConst(SubobjType))
5195 return false;
5196
5197 if (!SubobjType->isIntegerType()) {
5198 // We don't support compound assignment on integer-cast-to-pointer
5199 // values.
5200 Info.FFDiag(E);
5201 return false;
5202 }
5203
5204 if (RHS.isInt()) {
5205 APSInt LHS =
5206 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
5207 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
5208 return false;
5209 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
5210 return true;
5211 } else if (RHS.isFloat()) {
5212 const FPOptions FPO = E->getFPFeaturesInEffect(
5213 Info.Ctx.getLangOpts());
5214 APFloat FValue(0.0);
5215 return HandleIntToFloatCast(Info, E, FPO, SubobjType, Value,
5216 PromotedLHSType, FValue) &&
5217 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
5218 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
5219 Value);
5220 }
5221
5222 Info.FFDiag(E);
5223 return false;
5224 }
5225 bool found(APFloat &Value, QualType SubobjType) {
5226 return checkConst(SubobjType) &&
5227 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
5228 Value) &&
5229 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
5230 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
5231 }
5232 bool foundPointer(APValue &Subobj, QualType SubobjType) {
5233 if (!checkConst(SubobjType))
5234 return false;
5235
5236 QualType PointeeType;
5237 if (const PointerType *PT = SubobjType->getAs<PointerType>())
5238 PointeeType = PT->getPointeeType();
5239
5240 if (PointeeType.isNull() || !RHS.isInt() ||
5241 (Opcode != BO_Add && Opcode != BO_Sub)) {
5242 Info.FFDiag(E);
5243 return false;
5244 }
5245
5246 APSInt Offset = RHS.getInt();
5247 if (Opcode == BO_Sub)
5248 negateAsSigned(Offset);
5249
5250 LValue LVal;
5251 LVal.setFrom(Info.Ctx, Subobj);
5252 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
5253 return false;
5254 LVal.moveInto(Subobj);
5255 return true;
5256 }
5257};
5258} // end anonymous namespace
5259
5260const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
5261
5262/// Perform a compound assignment of LVal <op>= RVal.
5263static bool handleCompoundAssignment(EvalInfo &Info,
5264 const CompoundAssignOperator *E,
5265 const LValue &LVal, QualType LValType,
5266 QualType PromotedLValType,
5267 BinaryOperatorKind Opcode,
5268 const APValue &RVal) {
5269 if (LVal.Designator.Invalid)
5270 return false;
5271
5272 if (!Info.getLangOpts().CPlusPlus14) {
5273 Info.FFDiag(E);
5274 return false;
5275 }
5276
5277 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
5278 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
5279 RVal };
5280 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
5281}
5282
5283namespace {
5284struct IncDecSubobjectHandler {
5285 EvalInfo &Info;
5286 const UnaryOperator *E;
5288 APValue *Old;
5289
5290 typedef bool result_type;
5291
5292 bool checkConst(QualType QT) {
5293 // Assigning to a const object has undefined behavior.
5294 if (QT.isConstQualified()) {
5295 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
5296 return false;
5297 }
5298 return true;
5299 }
5300
5301 bool failed() { return false; }
5302 bool found(APValue &Subobj, QualType SubobjType, APValue::LValueBase Base) {
5303 // Stash the old value. Also clear Old, so we don't clobber it later
5304 // if we're post-incrementing a complex.
5305 if (Old) {
5306 *Old = Subobj;
5307 Old = nullptr;
5308 }
5309
5310 switch (Subobj.getKind()) {
5311 case APValue::Int:
5312 return found(Subobj.getInt(), SubobjType);
5313 case APValue::Float:
5314 return found(Subobj.getFloat(), SubobjType);
5316 return found(Subobj.getComplexIntReal(),
5317 SubobjType->castAs<ComplexType>()->getElementType()
5318 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
5320 return found(Subobj.getComplexFloatReal(),
5321 SubobjType->castAs<ComplexType>()->getElementType()
5322 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
5323 case APValue::LValue:
5324 return foundPointer(Subobj, SubobjType);
5325 default:
5326 // FIXME: can this happen?
5327 Info.FFDiag(E);
5328 return false;
5329 }
5330 }
5331 bool found(APSInt &Value, QualType SubobjType) {
5332 if (!checkConst(SubobjType))
5333 return false;
5334
5335 if (!SubobjType->isIntegerType()) {
5336 // We don't support increment / decrement on integer-cast-to-pointer
5337 // values.
5338 Info.FFDiag(E);
5339 return false;
5340 }
5341
5342 if (Old) *Old = APValue(Value);
5343
5344 // bool arithmetic promotes to int, and the conversion back to bool
5345 // doesn't reduce mod 2^n, so special-case it.
5346 if (SubobjType->isBooleanType()) {
5347 if (AccessKind == AK_Increment)
5348 Value = 1;
5349 else
5350 Value = !Value;
5351 return true;
5352 }
5353
5354 bool WasNegative = Value.isNegative();
5355 if (AccessKind == AK_Increment) {
5356 ++Value;
5357
5358 if (!WasNegative && Value.isNegative() && E->canOverflow() &&
5359 !SubobjType.isWrapType()) {
5360 APSInt ActualValue(Value, /*IsUnsigned*/true);
5361 return HandleOverflow(Info, E, ActualValue, SubobjType);
5362 }
5363 } else {
5364 --Value;
5365
5366 if (WasNegative && !Value.isNegative() && E->canOverflow() &&
5367 !SubobjType.isWrapType()) {
5368 unsigned BitWidth = Value.getBitWidth();
5369 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
5370 ActualValue.setBit(BitWidth);
5371 return HandleOverflow(Info, E, ActualValue, SubobjType);
5372 }
5373 }
5374 return true;
5375 }
5376 bool found(APFloat &Value, QualType SubobjType) {
5377 if (!checkConst(SubobjType))
5378 return false;
5379
5380 if (Old) *Old = APValue(Value);
5381
5382 APFloat One(Value.getSemantics(), 1);
5383 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
5384 APFloat::opStatus St;
5385 if (AccessKind == AK_Increment)
5386 St = Value.add(One, RM);
5387 else
5388 St = Value.subtract(One, RM);
5390 }
5391 bool foundPointer(APValue &Subobj, QualType SubobjType) {
5392 if (!checkConst(SubobjType))
5393 return false;
5394
5395 QualType PointeeType;
5396 if (const PointerType *PT = SubobjType->getAs<PointerType>())
5397 PointeeType = PT->getPointeeType();
5398 else {
5399 Info.FFDiag(E);
5400 return false;
5401 }
5402
5403 LValue LVal;
5404 LVal.setFrom(Info.Ctx, Subobj);
5405 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
5406 AccessKind == AK_Increment ? 1 : -1))
5407 return false;
5408 LVal.moveInto(Subobj);
5409 return true;
5410 }
5411};
5412} // end anonymous namespace
5413
5414/// Perform an increment or decrement on LVal.
5415static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
5416 QualType LValType, bool IsIncrement, APValue *Old) {
5417 if (LVal.Designator.Invalid)
5418 return false;
5419
5420 if (!Info.getLangOpts().CPlusPlus14) {
5421 Info.FFDiag(E);
5422 return false;
5423 }
5424
5425 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
5426 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
5427 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
5428 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
5429}
5430
5431/// Build an lvalue for the object argument of a member function call.
5432static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
5433 LValue &This) {
5434 if (Object->getType()->isPointerType() && Object->isPRValue())
5435 return EvaluatePointer(Object, This, Info);
5436
5437 if (Object->isGLValue())
5438 return EvaluateLValue(Object, This, Info);
5439
5440 if (Object->getType()->isLiteralType(Info.Ctx))
5441 return EvaluateTemporary(Object, This, Info);
5442
5443 if (Object->getType()->isRecordType() && Object->isPRValue())
5444 return EvaluateTemporary(Object, This, Info);
5445
5446 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
5447 return false;
5448}
5449
5450/// HandleMemberPointerAccess - Evaluate a member access operation and build an
5451/// lvalue referring to the result.
5452///
5453/// \param Info - Information about the ongoing evaluation.
5454/// \param LV - An lvalue referring to the base of the member pointer.
5455/// \param RHS - The member pointer expression.
5456/// \param IncludeMember - Specifies whether the member itself is included in
5457/// the resulting LValue subobject designator. This is not possible when
5458/// creating a bound member function.
5459/// \return The field or method declaration to which the member pointer refers,
5460/// or 0 if evaluation fails.
5461static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
5462 QualType LVType,
5463 LValue &LV,
5464 const Expr *RHS,
5465 bool IncludeMember = true) {
5466 MemberPtr MemPtr;
5467 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
5468 return nullptr;
5469
5470 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
5471 // member value, the behavior is undefined.
5472 if (!MemPtr.getDecl()) {
5473 // FIXME: Specific diagnostic.
5474 Info.FFDiag(RHS);
5475 return nullptr;
5476 }
5477
5478 if (MemPtr.isDerivedMember()) {
5479 // This is a member of some derived class. Truncate LV appropriately.
5480 // The end of the derived-to-base path for the base object must match the
5481 // derived-to-base path for the member pointer.
5482 // C++23 [expr.mptr.oper]p4:
5483 // If the result of E1 is an object [...] whose most derived object does
5484 // not contain the member to which E2 refers, the behavior is undefined.
5485 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
5486 LV.Designator.Entries.size()) {
5487 Info.FFDiag(RHS);
5488 return nullptr;
5489 }
5490 unsigned PathLengthToMember =
5491 LV.Designator.Entries.size() - MemPtr.Path.size();
5492 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
5493 const CXXRecordDecl *LVDecl = getAsBaseClass(
5494 LV.Designator.Entries[PathLengthToMember + I]);
5495 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
5496 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
5497 Info.FFDiag(RHS);
5498 return nullptr;
5499 }
5500 }
5501 // MemPtr.Path only contains the base classes of the class directly
5502 // containing the member E2. It is still necessary to check that the class
5503 // directly containing the member E2 lies on the derived-to-base path of E1
5504 // to avoid incorrectly permitting member pointer access into a sibling
5505 // class of the class containing the member E2. If this class would
5506 // correspond to the most-derived class of E1, it either isn't contained in
5507 // LV.Designator.Entries or the corresponding entry refers to an array
5508 // element instead. Therefore get the most derived class directly in this
5509 // case. Otherwise the previous entry should correpond to this class.
5510 const CXXRecordDecl *LastLVDecl =
5511 (PathLengthToMember > LV.Designator.MostDerivedPathLength)
5512 ? getAsBaseClass(LV.Designator.Entries[PathLengthToMember - 1])
5513 : LV.Designator.MostDerivedType->getAsCXXRecordDecl();
5514 const CXXRecordDecl *LastMPDecl = MemPtr.getContainingRecord();
5515 if (LastLVDecl->getCanonicalDecl() != LastMPDecl->getCanonicalDecl()) {
5516 Info.FFDiag(RHS);
5517 return nullptr;
5518 }
5519
5520 // Truncate the lvalue to the appropriate derived class.
5521 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
5522 PathLengthToMember))
5523 return nullptr;
5524 } else if (!MemPtr.Path.empty()) {
5525 // Extend the LValue path with the member pointer's path.
5526 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
5527 MemPtr.Path.size() + IncludeMember);
5528
5529 // Walk down to the appropriate base class.
5530 if (const PointerType *PT = LVType->getAs<PointerType>())
5531 LVType = PT->getPointeeType();
5532 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
5533 assert(RD && "member pointer access on non-class-type expression");
5534 // The first class in the path is that of the lvalue.
5535 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
5536 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
5537 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
5538 return nullptr;
5539 RD = Base;
5540 }
5541 // Finally cast to the class containing the member.
5542 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
5543 MemPtr.getContainingRecord()))
5544 return nullptr;
5545 }
5546
5547 // Add the member. Note that we cannot build bound member functions here.
5548 if (IncludeMember) {
5549 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
5550 if (!HandleLValueMember(Info, RHS, LV, FD))
5551 return nullptr;
5552 } else if (const IndirectFieldDecl *IFD =
5553 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
5554 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
5555 return nullptr;
5556 } else {
5557 llvm_unreachable("can't construct reference to bound member function");
5558 }
5559 }
5560
5561 return MemPtr.getDecl();
5562}
5563
5564static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
5565 const BinaryOperator *BO,
5566 LValue &LV,
5567 bool IncludeMember = true) {
5568 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
5569
5570 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
5571 if (Info.noteFailure()) {
5572 MemberPtr MemPtr;
5573 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
5574 }
5575 return nullptr;
5576 }
5577
5578 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
5579 BO->getRHS(), IncludeMember);
5580}
5581
5582/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
5583/// the provided lvalue, which currently refers to the base object.
5584static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
5585 LValue &Result) {
5586 SubobjectDesignator &D = Result.Designator;
5587 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
5588 return false;
5589
5590 QualType TargetQT = E->getType();
5591 if (const PointerType *PT = TargetQT->getAs<PointerType>())
5592 TargetQT = PT->getPointeeType();
5593
5594 auto InvalidCast = [&]() {
5595 if (!Info.checkingPotentialConstantExpression() ||
5596 !Result.AllowConstexprUnknown) {
5597 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
5598 << D.MostDerivedType << TargetQT;
5599 }
5600 return false;
5601 };
5602
5603 // Check this cast lands within the final derived-to-base subobject path.
5604 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size())
5605 return InvalidCast();
5606
5607 // Check the type of the final cast. We don't need to check the path,
5608 // since a cast can only be formed if the path is unique.
5609 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
5610 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
5611 const CXXRecordDecl *FinalType;
5612 if (NewEntriesSize == D.MostDerivedPathLength)
5613 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
5614 else
5615 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
5616 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl())
5617 return InvalidCast();
5618
5619 // Truncate the lvalue to the appropriate derived class.
5620 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
5621}
5622
5623/// Get the value to use for a default-initialized object of type T.
5624/// Return false if it encounters something invalid.
5626 bool IsCompleteClass = true) {
5627 bool Success = true;
5628
5629 // If there is already a value present don't overwrite it.
5630 if (!Result.isAbsent())
5631 return true;
5632
5633 if (auto *RD = T->getAsCXXRecordDecl()) {
5634 if (RD->isInvalidDecl()) {
5635 Result = APValue();
5636 return false;
5637 }
5638 if (RD->isUnion()) {
5639 Result = APValue((const FieldDecl *)nullptr);
5640 return true;
5641 }
5642
5643 // bases() includes directly specified virtual bases as well.
5644 unsigned NonVirtualBases = countNonVirtualBases(RD);
5645 Result =
5646 APValue(APValue::UninitStruct(), NonVirtualBases, RD->getNumFields(),
5647 IsCompleteClass ? RD->getNumVBases() : 0);
5648
5649 unsigned Index = 0;
5650 for (const CXXBaseSpecifier &B : RD->bases()) {
5651 if (B.isVirtual())
5652 continue;
5654 B.getType(), Result.getStructBase(Index), /*IsCompleteClass=*/false);
5655 ++Index;
5656 }
5657
5658 for (const auto *I : RD->fields()) {
5659 if (I->isUnnamedBitField())
5660 continue;
5662 I->getType(), Result.getStructField(I->getFieldIndex()));
5663 }
5664
5665 if (IsCompleteClass) {
5666 Index = 0;
5667
5668 for (const auto &B : RD->vbases()) {
5670 Result.getStructVirtualBase(Index),
5671 /*IsCompleteClass=*/false);
5672 ++Index;
5673 }
5674 } else {
5675 // Virtual bases should only exist at the top level of an APValue.
5676 assert(Result.getStructNumVirtualBases() == 0);
5677 }
5678
5679 return Success;
5680 }
5681
5682 if (auto *AT =
5683 dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
5684 Result = APValue(APValue::UninitArray(), 0, AT->getZExtSize());
5685 if (Result.hasArrayFiller())
5686 Success &=
5687 handleDefaultInitValue(AT->getElementType(), Result.getArrayFiller());
5688 return Success;
5689 }
5690
5692 return true;
5693}
5694
5695namespace {
5696enum EvalStmtResult {
5697 /// Evaluation failed.
5698 ESR_Failed,
5699 /// Hit a 'return' statement.
5700 ESR_Returned,
5701 /// Evaluation succeeded.
5702 ESR_Succeeded,
5703 /// Hit a 'continue' statement.
5704 ESR_Continue,
5705 /// Hit a 'break' statement.
5706 ESR_Break,
5707 /// Still scanning for 'case' or 'default' statement.
5708 ESR_CaseNotFound
5709};
5710}
5711/// Evaluates the initializer of a reference.
5712static bool EvaluateInitForDeclOfReferenceType(EvalInfo &Info,
5713 const ValueDecl *D,
5714 const Expr *Init, LValue &Result,
5715 APValue &Val) {
5716 assert(Init->isGLValue() && D->getType()->isReferenceType());
5717 // A reference is an lvalue.
5718 if (!EvaluateLValue(Init, Result, Info))
5719 return false;
5720 // [C++26][decl.ref]
5721 // The object designated by such a glvalue can be outside its lifetime
5722 // Because a null pointer value or a pointer past the end of an object
5723 // does not point to an object, a reference in a well-defined program cannot
5724 // refer to such things;
5725 if (!Result.Designator.Invalid && Result.Designator.isOnePastTheEnd()) {
5726 Info.FFDiag(Init, diag::note_constexpr_access_past_end) << AK_Dereference;
5727 return false;
5728 }
5729
5730 // Save the result.
5731 Result.moveInto(Val);
5732 return true;
5733}
5734
5735static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
5736 if (VD->isInvalidDecl())
5737 return false;
5738 // We don't need to evaluate the initializer for a static local.
5739 if (!VD->hasLocalStorage())
5740 return true;
5741
5742 LValue Result;
5743 APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(),
5744 ScopeKind::Block, Result);
5745
5746 const Expr *InitE = VD->getInit();
5747 if (!InitE) {
5748 if (VD->getType()->isDependentType())
5749 return Info.noteSideEffect();
5750 return handleDefaultInitValue(VD->getType(), Val);
5751 }
5752 if (InitE->isValueDependent())
5753 return false;
5754
5755 // For references to objects, check they do not designate a one-past-the-end
5756 // object.
5757 if (VD->getType()->isReferenceType()) {
5758 return EvaluateInitForDeclOfReferenceType(Info, VD, InitE, Result, Val);
5759 } else if (!EvaluateInPlace(Val, Info, Result, InitE)) {
5760 // Wipe out any partially-computed value, to allow tracking that this
5761 // evaluation failed.
5762 Val = APValue();
5763 return false;
5764 }
5765
5766 return true;
5767}
5768
5769static bool EvaluateDecompositionDeclInit(EvalInfo &Info,
5770 const DecompositionDecl *DD);
5771
5772static bool EvaluateDecl(EvalInfo &Info, const Decl *D,
5773 bool EvaluateConditionDecl = false) {
5774 bool OK = true;
5775 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
5776 OK &= EvaluateVarDecl(Info, VD);
5777
5778 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D);
5779 EvaluateConditionDecl && DD)
5780 OK &= EvaluateDecompositionDeclInit(Info, DD);
5781
5782 return OK;
5783}
5784
5785static bool EvaluateDecompositionDeclInit(EvalInfo &Info,
5786 const DecompositionDecl *DD) {
5787 bool OK = true;
5788 for (auto *BD : DD->flat_bindings())
5789 if (auto *VD = BD->getHoldingVar())
5790 OK &= EvaluateDecl(Info, VD, /*EvaluateConditionDecl=*/true);
5791
5792 return OK;
5793}
5794
5795static bool MaybeEvaluateDeferredVarDeclInit(EvalInfo &Info,
5796 const VarDecl *VD) {
5797 if (auto *DD = dyn_cast_if_present<DecompositionDecl>(VD)) {
5798 if (!EvaluateDecompositionDeclInit(Info, DD))
5799 return false;
5800 }
5801 return true;
5802}
5803
5804static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info) {
5805 assert(E->isValueDependent());
5806 if (Info.noteSideEffect())
5807 return true;
5808 assert(E->containsErrors() && "valid value-dependent expression should never "
5809 "reach invalid code path.");
5810 return false;
5811}
5812
5813/// Evaluate a condition (either a variable declaration or an expression).
5814static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
5815 const Expr *Cond, bool &Result) {
5816 if (Cond->isValueDependent())
5817 return false;
5818 FullExpressionRAII Scope(Info);
5819 if (CondDecl && !EvaluateDecl(Info, CondDecl))
5820 return false;
5821 if (!EvaluateAsBooleanCondition(Cond, Result, Info))
5822 return false;
5823 if (!MaybeEvaluateDeferredVarDeclInit(Info, CondDecl))
5824 return false;
5825 return Scope.destroy();
5826}
5827
5828namespace {
5829/// A location where the result (returned value) of evaluating a
5830/// statement should be stored.
5831struct StmtResult {
5832 /// The APValue that should be filled in with the returned value.
5833 APValue &Value;
5834 /// The location containing the result, if any (used to support RVO).
5835 const LValue *Slot;
5836};
5837
5838struct TempVersionRAII {
5839 CallStackFrame &Frame;
5840
5841 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
5842 Frame.pushTempVersion();
5843 }
5844
5845 ~TempVersionRAII() {
5846 Frame.popTempVersion();
5847 }
5848};
5849
5850}
5851
5852static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
5853 const Stmt *S,
5854 const SwitchCase *SC = nullptr);
5855
5856/// Helper to implement named break/continue. Returns 'true' if the evaluation
5857/// result should be propagated up. Otherwise, it sets the evaluation result
5858/// to either Continue to continue the current loop, or Succeeded to break it.
5859static bool ShouldPropagateBreakContinue(EvalInfo &Info,
5860 const Stmt *LoopOrSwitch,
5862 EvalStmtResult &ESR) {
5863 bool IsSwitch = isa<SwitchStmt>(LoopOrSwitch);
5864
5865 // For loops, map Succeeded to Continue so we don't have to check for both.
5866 if (!IsSwitch && ESR == ESR_Succeeded) {
5867 ESR = ESR_Continue;
5868 return false;
5869 }
5870
5871 if (ESR != ESR_Break && ESR != ESR_Continue)
5872 return false;
5873
5874 // Are we breaking out of or continuing this statement?
5875 bool CanBreakOrContinue = !IsSwitch || ESR == ESR_Break;
5876 const Stmt *StackTop = Info.BreakContinueStack.back();
5877 if (CanBreakOrContinue && (StackTop == nullptr || StackTop == LoopOrSwitch)) {
5878 Info.BreakContinueStack.pop_back();
5879 if (ESR == ESR_Break)
5880 ESR = ESR_Succeeded;
5881 return false;
5882 }
5883
5884 // We're not. Propagate the result up.
5885 for (BlockScopeRAII *S : Scopes) {
5886 if (!S->destroy()) {
5887 ESR = ESR_Failed;
5888 break;
5889 }
5890 }
5891 return true;
5892}
5893
5894/// Evaluate the body of a loop, and translate the result as appropriate.
5895static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
5896 const Stmt *Body,
5897 const SwitchCase *Case = nullptr) {
5898 BlockScopeRAII Scope(Info);
5899
5900 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case);
5901 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
5902 ESR = ESR_Failed;
5903
5904 return ESR;
5905}
5906
5907/// Evaluate a switch statement.
5908static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
5909 const SwitchStmt *SS) {
5910 BlockScopeRAII Scope(Info);
5911
5912 // Evaluate the switch condition.
5913 APSInt Value;
5914 {
5915 if (const Stmt *Init = SS->getInit()) {
5916 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
5917 if (ESR != ESR_Succeeded) {
5918 if (ESR != ESR_Failed && !Scope.destroy())
5919 ESR = ESR_Failed;
5920 return ESR;
5921 }
5922 }
5923
5924 FullExpressionRAII CondScope(Info);
5925 if (SS->getConditionVariable() &&
5926 !EvaluateDecl(Info, SS->getConditionVariable()))
5927 return ESR_Failed;
5928 if (SS->getCond()->isValueDependent()) {
5929 // We don't know what the value is, and which branch should jump to.
5930 EvaluateDependentExpr(SS->getCond(), Info);
5931 return ESR_Failed;
5932 }
5933 if (!EvaluateInteger(SS->getCond(), Value, Info))
5934 return ESR_Failed;
5935
5937 return ESR_Failed;
5938
5939 if (!CondScope.destroy())
5940 return ESR_Failed;
5941 }
5942
5943 // Find the switch case corresponding to the value of the condition.
5944 // FIXME: Cache this lookup.
5945 const SwitchCase *Found = nullptr;
5946 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
5947 SC = SC->getNextSwitchCase()) {
5948 if (isa<DefaultStmt>(SC)) {
5949 Found = SC;
5950 continue;
5951 }
5952
5953 const CaseStmt *CS = cast<CaseStmt>(SC);
5954 const Expr *LHS = CS->getLHS();
5955 const Expr *RHS = CS->getRHS();
5956 if (LHS->isValueDependent() || (RHS && RHS->isValueDependent()))
5957 return ESR_Failed;
5958 APSInt LHSValue = LHS->EvaluateKnownConstInt(Info.Ctx);
5959 APSInt RHSValue = RHS ? RHS->EvaluateKnownConstInt(Info.Ctx) : LHSValue;
5960 if (LHSValue <= Value && Value <= RHSValue) {
5961 Found = SC;
5962 break;
5963 }
5964 }
5965
5966 if (!Found)
5967 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5968
5969 // Search the switch body for the switch case and evaluate it from there.
5970 EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found);
5971 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
5972 return ESR_Failed;
5973 if (ShouldPropagateBreakContinue(Info, SS, /*Scopes=*/{}, ESR))
5974 return ESR;
5975
5976 switch (ESR) {
5977 case ESR_Break:
5978 llvm_unreachable("Should have been converted to Succeeded");
5979 case ESR_Succeeded:
5980 case ESR_Continue:
5981 case ESR_Failed:
5982 case ESR_Returned:
5983 return ESR;
5984 case ESR_CaseNotFound:
5985 // This can only happen if the switch case is nested within a statement
5986 // expression. We have no intention of supporting that.
5987 Info.FFDiag(Found->getBeginLoc(),
5988 diag::note_constexpr_stmt_expr_unsupported);
5989 return ESR_Failed;
5990 }
5991 llvm_unreachable("Invalid EvalStmtResult!");
5992}
5993
5994static bool CheckLocalVariableDeclaration(EvalInfo &Info, const VarDecl *VD) {
5995 // An expression E is a core constant expression unless the evaluation of E
5996 // would evaluate one of the following: [C++23] - a control flow that passes
5997 // through a declaration of a variable with static or thread storage duration
5998 // unless that variable is usable in constant expressions.
5999 if (VD->isLocalVarDecl() && VD->isStaticLocal() &&
6000 !VD->isUsableInConstantExpressions(Info.Ctx)) {
6001 Info.CCEDiag(VD->getLocation(), diag::note_constexpr_static_local)
6002 << (VD->getTSCSpec() == TSCS_unspecified ? 0 : 1) << VD;
6003 return false;
6004 }
6005 return true;
6006}
6007
6008// Evaluate a statement.
6009static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
6010 const Stmt *S, const SwitchCase *Case) {
6011 if (!Info.nextStep(S))
6012 return ESR_Failed;
6013
6014 // If we're hunting down a 'case' or 'default' label, recurse through
6015 // substatements until we hit the label.
6016 if (Case) {
6017 switch (S->getStmtClass()) {
6018 case Stmt::CompoundStmtClass:
6019 // FIXME: Precompute which substatement of a compound statement we
6020 // would jump to, and go straight there rather than performing a
6021 // linear scan each time.
6022 case Stmt::LabelStmtClass:
6023 case Stmt::AttributedStmtClass:
6024 case Stmt::DoStmtClass:
6025 break;
6026
6027 case Stmt::CaseStmtClass:
6028 case Stmt::DefaultStmtClass:
6029 if (Case == S)
6030 Case = nullptr;
6031 break;
6032
6033 case Stmt::IfStmtClass: {
6034 // FIXME: Precompute which side of an 'if' we would jump to, and go
6035 // straight there rather than scanning both sides.
6036 const IfStmt *IS = cast<IfStmt>(S);
6037
6038 // Wrap the evaluation in a block scope, in case it's a DeclStmt
6039 // preceded by our switch label.
6040 BlockScopeRAII Scope(Info);
6041
6042 // Step into the init statement in case it brings an (uninitialized)
6043 // variable into scope.
6044 if (const Stmt *Init = IS->getInit()) {
6045 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
6046 if (ESR != ESR_CaseNotFound) {
6047 assert(ESR != ESR_Succeeded);
6048 return ESR;
6049 }
6050 }
6051
6052 // Condition variable must be initialized if it exists.
6053 // FIXME: We can skip evaluating the body if there's a condition
6054 // variable, as there can't be any case labels within it.
6055 // (The same is true for 'for' statements.)
6056
6057 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
6058 if (ESR == ESR_Failed)
6059 return ESR;
6060 if (ESR != ESR_CaseNotFound)
6061 return Scope.destroy() ? ESR : ESR_Failed;
6062 if (!IS->getElse())
6063 return ESR_CaseNotFound;
6064
6065 ESR = EvaluateStmt(Result, Info, IS->getElse(), Case);
6066 if (ESR == ESR_Failed)
6067 return ESR;
6068 if (ESR != ESR_CaseNotFound)
6069 return Scope.destroy() ? ESR : ESR_Failed;
6070 return ESR_CaseNotFound;
6071 }
6072
6073 case Stmt::WhileStmtClass: {
6074 EvalStmtResult ESR =
6075 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
6076 if (ShouldPropagateBreakContinue(Info, S, /*Scopes=*/{}, ESR))
6077 return ESR;
6078 if (ESR != ESR_Continue)
6079 return ESR;
6080 break;
6081 }
6082
6083 case Stmt::ForStmtClass: {
6084 const ForStmt *FS = cast<ForStmt>(S);
6085 BlockScopeRAII Scope(Info);
6086
6087 // Step into the init statement in case it brings an (uninitialized)
6088 // variable into scope.
6089 if (const Stmt *Init = FS->getInit()) {
6090 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
6091 if (ESR != ESR_CaseNotFound) {
6092 assert(ESR != ESR_Succeeded);
6093 return ESR;
6094 }
6095 }
6096
6097 EvalStmtResult ESR =
6098 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
6099 if (ShouldPropagateBreakContinue(Info, FS, /*Scopes=*/{}, ESR))
6100 return ESR;
6101 if (ESR != ESR_Continue)
6102 return ESR;
6103 if (const auto *Inc = FS->getInc()) {
6104 if (Inc->isValueDependent()) {
6105 if (!EvaluateDependentExpr(Inc, Info))
6106 return ESR_Failed;
6107 } else {
6108 FullExpressionRAII IncScope(Info);
6109 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
6110 return ESR_Failed;
6111 }
6112 }
6113 break;
6114 }
6115
6116 case Stmt::DeclStmtClass: {
6117 // Start the lifetime of any uninitialized variables we encounter. They
6118 // might be used by the selected branch of the switch.
6119 const DeclStmt *DS = cast<DeclStmt>(S);
6120 for (const auto *D : DS->decls()) {
6121 if (const auto *VD = dyn_cast<VarDecl>(D)) {
6122 if (!CheckLocalVariableDeclaration(Info, VD))
6123 return ESR_Failed;
6124 if (VD->hasLocalStorage() && !VD->getInit())
6125 if (!EvaluateVarDecl(Info, VD))
6126 return ESR_Failed;
6127 // FIXME: If the variable has initialization that can't be jumped
6128 // over, bail out of any immediately-surrounding compound-statement
6129 // too. There can't be any case labels here.
6130 }
6131 }
6132 return ESR_CaseNotFound;
6133 }
6134
6135 default:
6136 return ESR_CaseNotFound;
6137 }
6138 }
6139
6140 switch (S->getStmtClass()) {
6141 default:
6142 if (const Expr *E = dyn_cast<Expr>(S)) {
6143 if (E->isValueDependent()) {
6144 if (!EvaluateDependentExpr(E, Info))
6145 return ESR_Failed;
6146 } else {
6147 // Don't bother evaluating beyond an expression-statement which couldn't
6148 // be evaluated.
6149 // FIXME: Do we need the FullExpressionRAII object here?
6150 // VisitExprWithCleanups should create one when necessary.
6151 FullExpressionRAII Scope(Info);
6152 if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy())
6153 return ESR_Failed;
6154 }
6155 return ESR_Succeeded;
6156 }
6157
6158 Info.FFDiag(S->getBeginLoc()) << S->getSourceRange();
6159 return ESR_Failed;
6160
6161 case Stmt::NullStmtClass:
6162 return ESR_Succeeded;
6163
6164 case Stmt::DeclStmtClass: {
6165 const DeclStmt *DS = cast<DeclStmt>(S);
6166 for (const auto *D : DS->decls()) {
6167 const VarDecl *VD = dyn_cast_or_null<VarDecl>(D);
6168 if (VD && !CheckLocalVariableDeclaration(Info, VD))
6169 return ESR_Failed;
6170
6171 if (const auto *ESD = dyn_cast<CXXExpansionStmtDecl>(D)) {
6172 assert(ESD->getInstantiations() && "not expanded?");
6173 return EvaluateStmt(Result, Info, ESD->getInstantiations(), Case);
6174 }
6175
6176 // Each declaration initialization is its own full-expression.
6177 FullExpressionRAII Scope(Info);
6178 if (!EvaluateDecl(Info, D, /*EvaluateConditionDecl=*/true) &&
6179 !Info.noteFailure())
6180 return ESR_Failed;
6181 if (!Scope.destroy())
6182 return ESR_Failed;
6183 }
6184 return ESR_Succeeded;
6185 }
6186
6187 case Stmt::ReturnStmtClass: {
6188 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
6189 FullExpressionRAII Scope(Info);
6190 if (RetExpr && RetExpr->isValueDependent()) {
6191 EvaluateDependentExpr(RetExpr, Info);
6192 // We know we returned, but we don't know what the value is.
6193 return ESR_Failed;
6194 }
6195 if (RetExpr &&
6196 !(Result.Slot
6197 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
6198 : Evaluate(Result.Value, Info, RetExpr)))
6199 return ESR_Failed;
6200 return Scope.destroy() ? ESR_Returned : ESR_Failed;
6201 }
6202
6203 case Stmt::CompoundStmtClass: {
6204 BlockScopeRAII Scope(Info);
6205
6206 const CompoundStmt *CS = cast<CompoundStmt>(S);
6207 for (const auto *BI : CS->body()) {
6208 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
6209 if (ESR == ESR_Succeeded)
6210 Case = nullptr;
6211 else if (ESR != ESR_CaseNotFound) {
6212 if (ESR != ESR_Failed && !Scope.destroy())
6213 return ESR_Failed;
6214 return ESR;
6215 }
6216 }
6217 if (Case)
6218 return ESR_CaseNotFound;
6219 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
6220 }
6221
6222 case Stmt::IfStmtClass: {
6223 const IfStmt *IS = cast<IfStmt>(S);
6224
6225 // Evaluate the condition, as either a var decl or as an expression.
6226 BlockScopeRAII Scope(Info);
6227 if (const Stmt *Init = IS->getInit()) {
6228 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
6229 if (ESR != ESR_Succeeded) {
6230 if (ESR != ESR_Failed && !Scope.destroy())
6231 return ESR_Failed;
6232 return ESR;
6233 }
6234 }
6235 bool Cond;
6236 if (IS->isConsteval()) {
6237 Cond = IS->isNonNegatedConsteval();
6238 // If we are not in a constant context, if consteval should not evaluate
6239 // to true.
6240 if (!Info.InConstantContext)
6241 Cond = !Cond;
6242 } else if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(),
6243 Cond))
6244 return ESR_Failed;
6245
6246 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
6247 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
6248 if (ESR != ESR_Succeeded) {
6249 if (ESR != ESR_Failed && !Scope.destroy())
6250 return ESR_Failed;
6251 return ESR;
6252 }
6253 }
6254 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
6255 }
6256
6257 case Stmt::WhileStmtClass: {
6258 const WhileStmt *WS = cast<WhileStmt>(S);
6259 while (true) {
6260 BlockScopeRAII Scope(Info);
6261 bool Continue;
6262 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
6263 Continue))
6264 return ESR_Failed;
6265 if (!Continue)
6266 break;
6267
6268 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
6269 if (ShouldPropagateBreakContinue(Info, WS, &Scope, ESR))
6270 return ESR;
6271
6272 if (ESR != ESR_Continue) {
6273 if (ESR != ESR_Failed && !Scope.destroy())
6274 return ESR_Failed;
6275 return ESR;
6276 }
6277 if (!Scope.destroy())
6278 return ESR_Failed;
6279 }
6280 return ESR_Succeeded;
6281 }
6282
6283 case Stmt::DoStmtClass: {
6284 const DoStmt *DS = cast<DoStmt>(S);
6285 bool Continue;
6286 do {
6287 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
6288 if (ShouldPropagateBreakContinue(Info, DS, /*Scopes=*/{}, ESR))
6289 return ESR;
6290 if (ESR != ESR_Continue)
6291 return ESR;
6292 Case = nullptr;
6293
6294 if (DS->getCond()->isValueDependent()) {
6295 EvaluateDependentExpr(DS->getCond(), Info);
6296 // Bailout as we don't know whether to keep going or terminate the loop.
6297 return ESR_Failed;
6298 }
6299 FullExpressionRAII CondScope(Info);
6300 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) ||
6301 !CondScope.destroy())
6302 return ESR_Failed;
6303 } while (Continue);
6304 return ESR_Succeeded;
6305 }
6306
6307 case Stmt::ForStmtClass: {
6308 const ForStmt *FS = cast<ForStmt>(S);
6309 BlockScopeRAII ForScope(Info);
6310 if (FS->getInit()) {
6311 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
6312 if (ESR != ESR_Succeeded) {
6313 if (ESR != ESR_Failed && !ForScope.destroy())
6314 return ESR_Failed;
6315 return ESR;
6316 }
6317 }
6318 while (true) {
6319 BlockScopeRAII IterScope(Info);
6320 bool Continue = true;
6321 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
6322 FS->getCond(), Continue))
6323 return ESR_Failed;
6324
6325 if (!Continue) {
6326 if (!IterScope.destroy())
6327 return ESR_Failed;
6328 break;
6329 }
6330
6331 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
6332 if (ShouldPropagateBreakContinue(Info, FS, {&IterScope, &ForScope}, ESR))
6333 return ESR;
6334 if (ESR != ESR_Continue) {
6335 if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))
6336 return ESR_Failed;
6337 return ESR;
6338 }
6339
6340 if (const auto *Inc = FS->getInc()) {
6341 if (Inc->isValueDependent()) {
6342 if (!EvaluateDependentExpr(Inc, Info))
6343 return ESR_Failed;
6344 } else {
6345 FullExpressionRAII IncScope(Info);
6346 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
6347 return ESR_Failed;
6348 }
6349 }
6350
6351 if (!IterScope.destroy())
6352 return ESR_Failed;
6353 }
6354 return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;
6355 }
6356
6357 case Stmt::CXXForRangeStmtClass: {
6359 BlockScopeRAII Scope(Info);
6360
6361 // Evaluate the init-statement if present.
6362 if (FS->getInit()) {
6363 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
6364 if (ESR != ESR_Succeeded) {
6365 if (ESR != ESR_Failed && !Scope.destroy())
6366 return ESR_Failed;
6367 return ESR;
6368 }
6369 }
6370
6371 // Initialize the __range variable.
6372 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
6373 if (ESR != ESR_Succeeded) {
6374 if (ESR != ESR_Failed && !Scope.destroy())
6375 return ESR_Failed;
6376 return ESR;
6377 }
6378
6379 // In error-recovery cases it's possible to get here even if we failed to
6380 // synthesize the __begin and __end variables.
6381 if (!FS->getBeginStmt() || !FS->getEndStmt() || !FS->getCond())
6382 return ESR_Failed;
6383
6384 // Create the __begin and __end iterators.
6385 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
6386 if (ESR != ESR_Succeeded) {
6387 if (ESR != ESR_Failed && !Scope.destroy())
6388 return ESR_Failed;
6389 return ESR;
6390 }
6391 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
6392 if (ESR != ESR_Succeeded) {
6393 if (ESR != ESR_Failed && !Scope.destroy())
6394 return ESR_Failed;
6395 return ESR;
6396 }
6397
6398 while (true) {
6399 // Condition: __begin != __end.
6400 {
6401 if (FS->getCond()->isValueDependent()) {
6402 EvaluateDependentExpr(FS->getCond(), Info);
6403 // We don't know whether to keep going or terminate the loop.
6404 return ESR_Failed;
6405 }
6406 bool Continue = true;
6407 FullExpressionRAII CondExpr(Info);
6408 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
6409 return ESR_Failed;
6410 if (!Continue)
6411 break;
6412 }
6413
6414 // User's variable declaration, initialized by *__begin.
6415 BlockScopeRAII InnerScope(Info);
6416 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
6417 if (ESR != ESR_Succeeded) {
6418 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
6419 return ESR_Failed;
6420 return ESR;
6421 }
6422
6423 // Loop body.
6424 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
6425 if (ShouldPropagateBreakContinue(Info, FS, {&InnerScope, &Scope}, ESR))
6426 return ESR;
6427 if (ESR != ESR_Continue) {
6428 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
6429 return ESR_Failed;
6430 return ESR;
6431 }
6432 if (FS->getInc()->isValueDependent()) {
6433 if (!EvaluateDependentExpr(FS->getInc(), Info))
6434 return ESR_Failed;
6435 } else {
6436 // Increment: ++__begin
6437 if (!EvaluateIgnoredValue(Info, FS->getInc()))
6438 return ESR_Failed;
6439 }
6440
6441 if (!InnerScope.destroy())
6442 return ESR_Failed;
6443 }
6444
6445 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
6446 }
6447
6448 case Stmt::CXXExpansionStmtInstantiationClass: {
6449 BlockScopeRAII Scope(Info);
6450 const auto *Expansion = cast<CXXExpansionStmtInstantiation>(S);
6451 for (const Stmt *PreambleStmt : Expansion->getPreambleStmts()) {
6452 EvalStmtResult ESR = EvaluateStmt(Result, Info, PreambleStmt);
6453 if (ESR != ESR_Succeeded) {
6454 if (ESR != ESR_Failed && !Scope.destroy())
6455 return ESR_Failed;
6456 return ESR;
6457 }
6458 }
6459
6460 // No need to push an extra scope for these since they're already
6461 // CompoundStmts.
6462 EvalStmtResult ESR = ESR_Succeeded;
6463 for (const Stmt *Instantiation : Expansion->getInstantiations()) {
6464 ESR = EvaluateStmt(Result, Info, Instantiation);
6465 if (ESR == ESR_Failed ||
6466 ShouldPropagateBreakContinue(Info, Expansion, &Scope, ESR))
6467 return ESR;
6468 if (ESR != ESR_Continue) {
6469 // Succeeded here actually means we encountered a 'break'.
6470 assert(ESR == ESR_Succeeded || ESR == ESR_Returned);
6471 break;
6472 }
6473 }
6474
6475 // Map Continue back to Succeeded if we fell off the end of the loop.
6476 if (ESR == ESR_Continue)
6477 ESR = ESR_Succeeded;
6478
6479 return Scope.destroy() ? ESR : ESR_Failed;
6480 }
6481
6482 case Stmt::SwitchStmtClass:
6483 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
6484
6485 case Stmt::ContinueStmtClass:
6486 case Stmt::BreakStmtClass: {
6487 auto *B = cast<LoopControlStmt>(S);
6488 const Stmt *LoopOrSwitch = nullptr;
6489 if (B->isNamed()) {
6490 LoopOrSwitch = B->getNamedLoopOrSwitch();
6491 // May be null if the named loop is outside of the
6492 // current evaluation context, i.e. not a valid target.
6493 if (!LoopOrSwitch) {
6494 Info.FFDiag(S->getBeginLoc(),
6495 diag::note_break_continue_label_outside_context)
6496 << isa<ContinueStmt>(B);
6497 return ESR_Failed;
6498 }
6499 }
6500
6501 Info.BreakContinueStack.push_back(LoopOrSwitch);
6502 return isa<ContinueStmt>(S) ? ESR_Continue : ESR_Break;
6503 }
6504
6505 case Stmt::LabelStmtClass:
6506 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
6507
6508 case Stmt::AttributedStmtClass: {
6509 const auto *AS = cast<AttributedStmt>(S);
6510 const auto *SS = AS->getSubStmt();
6511 MSConstexprContextRAII ConstexprContext(
6512 *Info.CurrentCall, hasSpecificAttr<MSConstexprAttr>(AS->getAttrs()) &&
6513 isa<ReturnStmt>(SS));
6514
6515 auto LO = Info.Ctx.getLangOpts();
6516 if (LO.CXXAssumptions && !LO.MSVCCompat) {
6517 for (auto *Attr : AS->getAttrs()) {
6518 auto *AA = dyn_cast<CXXAssumeAttr>(Attr);
6519 if (!AA)
6520 continue;
6521
6522 auto *Assumption = AA->getAssumption();
6523 if (Assumption->isValueDependent())
6524 return ESR_Failed;
6525
6526 if (Assumption->HasSideEffects(Info.Ctx))
6527 continue;
6528
6529 bool Value;
6530 if (!EvaluateAsBooleanCondition(Assumption, Value, Info))
6531 return ESR_Failed;
6532 if (!Value) {
6533 Info.CCEDiag(Assumption->getExprLoc(),
6534 diag::note_constexpr_assumption_failed);
6535 return ESR_Failed;
6536 }
6537 }
6538 }
6539
6540 return EvaluateStmt(Result, Info, SS, Case);
6541 }
6542
6543 case Stmt::CaseStmtClass:
6544 case Stmt::DefaultStmtClass:
6545 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
6546 case Stmt::CXXTryStmtClass:
6547 // Evaluate try blocks by evaluating all sub statements.
6548 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
6549 }
6550}
6551
6552/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
6553/// default constructor. If so, we'll fold it whether or not it's marked as
6554/// constexpr. If it is marked as constexpr, we will never implicitly define it,
6555/// so we need special handling.
6556static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
6557 const CXXConstructorDecl *CD,
6558 bool IsValueInitialization) {
6559 if (!CD->isTrivial() || !CD->isDefaultConstructor())
6560 return false;
6561
6562 // Value-initialization does not call a trivial default constructor, so such a
6563 // call is a core constant expression whether or not the constructor is
6564 // constexpr.
6565 if (!CD->isConstexpr() && !IsValueInitialization) {
6566 if (Info.getLangOpts().CPlusPlus11) {
6567 // FIXME: If DiagDecl is an implicitly-declared special member function,
6568 // we should be much more explicit about why it's not constexpr.
6569 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
6570 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
6571 Info.Note(CD->getLocation(), diag::note_declared_at);
6572 } else {
6573 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
6574 }
6575 }
6576 return true;
6577}
6578
6579/// CheckConstexprFunction - Check that a function can be called in a constant
6580/// expression.
6581static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
6583 const FunctionDecl *Definition,
6584 const Stmt *Body) {
6585 // Potential constant expressions can contain calls to declared, but not yet
6586 // defined, constexpr functions.
6587 if (Info.checkingPotentialConstantExpression() && !Definition &&
6588 Declaration->isConstexpr())
6589 return false;
6590
6591 // Bail out if the function declaration itself is invalid. We will
6592 // have produced a relevant diagnostic while parsing it, so just
6593 // note the problematic sub-expression.
6594 if (Declaration->isInvalidDecl()) {
6595 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
6596 return false;
6597 }
6598
6599 // DR1872: An instantiated virtual constexpr function can't be called in a
6600 // constant expression (prior to C++20). We can still constant-fold such a
6601 // call.
6602 if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) &&
6603 cast<CXXMethodDecl>(Declaration)->isVirtual())
6604 Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
6605
6606 if (Definition && Definition->isInvalidDecl()) {
6607 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
6608 return false;
6609 }
6610
6611 // Can we evaluate this function call?
6612 if (Definition && Body &&
6613 (Definition->isConstexpr() || (Info.CurrentCall->CanEvalMSConstexpr &&
6614 Definition->hasAttr<MSConstexprAttr>())))
6615 return true;
6616
6617 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
6618 // Special note for the assert() macro, as the normal error message falsely
6619 // implies we cannot use an assertion during constant evaluation.
6620 if (CallLoc.isMacroID() && DiagDecl->getIdentifier()) {
6621 // FIXME: Instead of checking for an implementation-defined function,
6622 // check and evaluate the assert() macro.
6623 StringRef Name = DiagDecl->getName();
6624 bool AssertFailed =
6625 Name == "__assert_rtn" || Name == "__assert_fail" || Name == "_wassert";
6626 if (AssertFailed) {
6627 Info.FFDiag(CallLoc, diag::note_constexpr_assert_failed);
6628 return false;
6629 }
6630 }
6631
6632 if (Info.getLangOpts().CPlusPlus11) {
6633 // If this function is not constexpr because it is an inherited
6634 // non-constexpr constructor, diagnose that directly.
6635 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
6636 if (CD && CD->isInheritingConstructor()) {
6637 auto *Inherited = CD->getInheritedConstructor().getConstructor();
6638 if (!Inherited->isConstexpr())
6639 DiagDecl = CD = Inherited;
6640 }
6641
6642 // FIXME: If DiagDecl is an implicitly-declared special member function
6643 // or an inheriting constructor, we should be much more explicit about why
6644 // it's not constexpr.
6645 if (CD && CD->isInheritingConstructor())
6646 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
6647 << CD->getInheritedConstructor().getConstructor()->getParent();
6648 else
6649 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
6650 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
6651 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
6652 } else {
6653 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
6654 }
6655 return false;
6656}
6657
6658namespace {
6659struct CheckDynamicTypeHandler {
6661 typedef bool result_type;
6662 bool failed() { return false; }
6663 bool found(APValue &Subobj, QualType SubobjType, APValue::LValueBase Base) {
6664 return true;
6665 }
6666 bool found(APSInt &Value, QualType SubobjType) { return true; }
6667 bool found(APFloat &Value, QualType SubobjType) { return true; }
6668};
6669} // end anonymous namespace
6670
6671/// Check that we can access the notional vptr of an object / determine its
6672/// dynamic type.
6673static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
6674 AccessKinds AK, bool Polymorphic) {
6675 if (This.Designator.Invalid)
6676 return false;
6677
6678 CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
6679
6680 if (!Obj)
6681 return false;
6682
6683 if (!Obj.Value) {
6684 // The object is not usable in constant expressions, so we can't inspect
6685 // its value to see if it's in-lifetime or what the active union members
6686 // are. We can still check for a one-past-the-end lvalue.
6687 if (This.Designator.isOnePastTheEnd() ||
6688 This.Designator.isMostDerivedAnUnsizedArray()) {
6689 Info.FFDiag(E, This.Designator.isOnePastTheEnd()
6690 ? diag::note_constexpr_access_past_end
6691 : diag::note_constexpr_access_unsized_array)
6692 << AK;
6693 return false;
6694 } else if (Polymorphic) {
6695 // Conservatively refuse to perform a polymorphic operation if we would
6696 // not be able to read a notional 'vptr' value.
6697 if (!Info.checkingPotentialConstantExpression() ||
6698 !This.AllowConstexprUnknown) {
6699 APValue Val;
6700 This.moveInto(Val);
6701 QualType StarThisType =
6702 Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
6703 Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
6704 << AK << Val.getAsString(Info.Ctx, StarThisType);
6705 }
6706 return false;
6707 }
6708 return true;
6709 }
6710
6711 CheckDynamicTypeHandler Handler{AK};
6712 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
6713}
6714
6715/// Check that the pointee of the 'this' pointer in a member function call is
6716/// either within its lifetime or in its period of construction or destruction.
6717static bool
6719 const LValue &This,
6720 const CXXMethodDecl *NamedMember) {
6721 return checkDynamicType(
6722 Info, E, This,
6723 isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false);
6724}
6725
6727 /// The dynamic class type of the object.
6729 /// The corresponding path length in the lvalue.
6730 unsigned PathLength;
6731};
6732
6733static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
6734 unsigned PathLength) {
6735 assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
6736 Designator.Entries.size() && "invalid path length");
6737 return (PathLength == Designator.MostDerivedPathLength)
6738 ? Designator.MostDerivedType->getAsCXXRecordDecl()
6739 : getAsBaseClass(Designator.Entries[PathLength - 1]);
6740}
6741
6742/// Determine the dynamic type of an object.
6743static std::optional<DynamicType> ComputeDynamicType(EvalInfo &Info,
6744 const Expr *E,
6745 LValue &This,
6746 AccessKinds AK) {
6747 // If we don't have an lvalue denoting an object of class type, there is no
6748 // meaningful dynamic type. (We consider objects of non-class type to have no
6749 // dynamic type.)
6750 if (!checkDynamicType(Info, E, This, AK,
6751 AK != AK_TypeId || This.AllowConstexprUnknown))
6752 return std::nullopt;
6753
6754 if (This.Designator.Invalid)
6755 return std::nullopt;
6756
6757 // Refuse to compute a dynamic type in the presence of virtual bases
6758 // before C++26. This shouldn't happen other than in constant-folding
6759 // situations, since literal types can't have virtual bases.
6760 const CXXRecordDecl *Class =
6761 This.Designator.MostDerivedType->getAsCXXRecordDecl();
6762 if (!Class || (!Info.getLangOpts().CPlusPlus26 && Class->getNumVBases())) {
6763 Info.FFDiag(E);
6764 return std::nullopt;
6765 }
6766
6767 // FIXME: For very deep class hierarchies, it might be beneficial to use a
6768 // binary search here instead. But the overwhelmingly common case is that
6769 // we're not in the middle of a constructor, so it probably doesn't matter
6770 // in practice.
6771 ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
6772 for (unsigned PathLength = This.Designator.MostDerivedPathLength;
6773 PathLength <= Path.size(); ++PathLength) {
6774 switch (Info.isEvaluatingCtorDtor(This.getLValueBase(),
6775 Path.slice(0, PathLength))) {
6776 case ConstructionPhase::Bases:
6777 case ConstructionPhase::DestroyingBases:
6778 // We're constructing or destroying a base class. This is not the dynamic
6779 // type.
6780 break;
6781
6782 case ConstructionPhase::None:
6783 case ConstructionPhase::AfterBases:
6784 case ConstructionPhase::AfterFields:
6785 case ConstructionPhase::Destroying:
6786 // We've finished constructing the base classes and not yet started
6787 // destroying them again, so this is the dynamic type.
6788 return DynamicType{getBaseClassType(This.Designator, PathLength),
6789 PathLength};
6790 }
6791 }
6792
6793 // CWG issue 1517: we're constructing a base class of the object described by
6794 // 'This', so that object has not yet begun its period of construction and
6795 // any polymorphic operation on it results in undefined behavior.
6796 Info.FFDiag(E);
6797 return std::nullopt;
6798}
6799
6800/// Perform virtual dispatch.
6802 EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
6803 llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
6804 std::optional<DynamicType> DynType = ComputeDynamicType(
6805 Info, E, This,
6807 if (!DynType)
6808 return nullptr;
6809
6810 // Find the final overrider. It must be declared in one of the classes on the
6811 // path from the dynamic type to the static type.
6812 // FIXME: If we ever allow literal types to have virtual base classes, that
6813 // won't be true.
6814 const CXXMethodDecl *Callee = Found;
6815 unsigned PathLength = DynType->PathLength;
6816 for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
6817 const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
6818 const CXXMethodDecl *Overrider =
6819 Found->getCorrespondingMethodDeclaredInClass(Class, false);
6820 if (Overrider) {
6821 Callee = Overrider;
6822 break;
6823 }
6824 }
6825
6826 // C++2a [class.abstract]p6:
6827 // the effect of making a virtual call to a pure virtual function [...] is
6828 // undefined
6829 if (Callee->isPureVirtual()) {
6830 Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
6831 Info.Note(Callee->getLocation(), diag::note_declared_at);
6832 return nullptr;
6833 }
6834
6835 // If necessary, walk the rest of the path to determine the sequence of
6836 // covariant adjustment steps to apply.
6837 if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
6838 Found->getReturnType())) {
6839 CovariantAdjustmentPath.push_back(Callee->getReturnType());
6840 for (unsigned CovariantPathLength = PathLength + 1;
6841 CovariantPathLength != This.Designator.Entries.size();
6842 ++CovariantPathLength) {
6843 const CXXRecordDecl *NextClass =
6844 getBaseClassType(This.Designator, CovariantPathLength);
6845 const CXXMethodDecl *Next =
6846 Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
6847 if (Next && !Info.Ctx.hasSameUnqualifiedType(
6848 Next->getReturnType(), CovariantAdjustmentPath.back()))
6849 CovariantAdjustmentPath.push_back(Next->getReturnType());
6850 }
6851 if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
6852 CovariantAdjustmentPath.back()))
6853 CovariantAdjustmentPath.push_back(Found->getReturnType());
6854 }
6855
6856 // Perform 'this' adjustment.
6857 if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
6858 return nullptr;
6859
6860 return Callee;
6861}
6862
6863/// Perform the adjustment from a value returned by a virtual function to
6864/// a value of the statically expected type, which may be a pointer or
6865/// reference to a base class of the returned type.
6866static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
6867 APValue &Result,
6868 ArrayRef<QualType> Path) {
6869 assert(Result.isLValue() &&
6870 "unexpected kind of APValue for covariant return");
6871 if (Result.isNullPointer())
6872 return true;
6873
6874 LValue LVal;
6875 LVal.setFrom(Info.Ctx, Result);
6876
6877 const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
6878 for (unsigned I = 1; I != Path.size(); ++I) {
6879 const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
6880 assert(OldClass && NewClass && "unexpected kind of covariant return");
6881 if (OldClass != NewClass &&
6882 !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
6883 return false;
6884 OldClass = NewClass;
6885 }
6886
6887 LVal.moveInto(Result);
6888 return true;
6889}
6890
6891/// Determine whether \p Base, which is known to be a direct base class of
6892/// \p Derived, is a public base class.
6893static bool isBaseClassPublic(const CXXRecordDecl *Derived,
6894 const CXXRecordDecl *Base) {
6895 for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
6896 if (BaseSpec.isVirtual())
6897 continue;
6898 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
6899 if (BaseClass && declaresSameEntity(BaseClass, Base))
6900 return BaseSpec.getAccessSpecifier() == AS_public;
6901 }
6902 for (const CXXBaseSpecifier &BaseSpec : Derived->vbases()) {
6903 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
6904 if (BaseClass && declaresSameEntity(BaseClass, Base))
6905 return BaseSpec.getAccessSpecifier() == AS_public;
6906 }
6907
6908 llvm_unreachable("Base is not a direct base of Derived");
6909}
6910
6911/// Apply the given dynamic cast operation on the provided lvalue.
6912///
6913/// This implements the hard case of dynamic_cast, requiring a "runtime check"
6914/// to find a suitable target subobject.
6915static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
6916 LValue &Ptr) {
6917 // We can't do anything with a non-symbolic pointer value.
6918 SubobjectDesignator &D = Ptr.Designator;
6919 if (D.Invalid)
6920 return false;
6921
6922 // C++ [expr.dynamic.cast]p6:
6923 // If v is a null pointer value, the result is a null pointer value.
6924 if (Ptr.isNullPointer() && !E->isGLValue())
6925 return true;
6926
6927 // For all the other cases, we need the pointer to point to an object within
6928 // its lifetime / period of construction / destruction, and we need to know
6929 // its dynamic type.
6930 std::optional<DynamicType> DynType =
6931 ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
6932 if (!DynType)
6933 return false;
6934
6935 // C++ [expr.dynamic.cast]p7:
6936 // If T is "pointer to cv void", then the result is a pointer to the most
6937 // derived object
6938 if (E->getType()->isVoidPointerType())
6939 return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
6940
6942 assert(C && "dynamic_cast target is not void pointer nor class");
6943 CanQualType CQT = Info.Ctx.getCanonicalTagType(C);
6944
6945 auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
6946 // C++ [expr.dynamic.cast]p9:
6947 if (!E->isGLValue()) {
6948 // The value of a failed cast to pointer type is the null pointer value
6949 // of the required result type.
6950 Ptr.setNull(Info.Ctx, E->getType());
6951 return true;
6952 }
6953
6954 // A failed cast to reference type throws [...] std::bad_cast.
6955 unsigned DiagKind;
6956 if (!Paths && (declaresSameEntity(DynType->Type, C) ||
6957 DynType->Type->isDerivedFrom(C)))
6958 DiagKind = 0;
6959 else if (!Paths || Paths->begin() == Paths->end())
6960 DiagKind = 1;
6961 else if (Paths->isAmbiguous(CQT))
6962 DiagKind = 2;
6963 else {
6964 assert(Paths->front().Access != AS_public && "why did the cast fail?");
6965 DiagKind = 3;
6966 }
6967 Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
6968 << DiagKind << Ptr.Designator.getType(Info.Ctx)
6969 << Info.Ctx.getCanonicalTagType(DynType->Type)
6970 << E->getType().getUnqualifiedType();
6971 return false;
6972 };
6973
6974 // Runtime check, phase 1:
6975 // Walk from the base subobject towards the derived object looking for the
6976 // target type.
6977 for (int PathLength = Ptr.Designator.Entries.size();
6978 PathLength >= (int)DynType->PathLength; --PathLength) {
6979 const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
6980 if (declaresSameEntity(Class, C))
6981 return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
6982 // We can only walk across public inheritance edges.
6983 if (PathLength > (int)DynType->PathLength &&
6984 !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
6985 Class))
6986 return RuntimeCheckFailed(nullptr);
6987 }
6988
6989 // Runtime check, phase 2:
6990 // Search the dynamic type for an unambiguous public base of type C.
6991 CXXBasePaths Paths(/*FindAmbiguities=*/true,
6992 /*RecordPaths=*/true, /*DetectVirtual=*/false);
6993 if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
6994 Paths.front().Access == AS_public) {
6995 // Downcast to the dynamic type...
6996 if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
6997 return false;
6998 // ... then upcast to the chosen base class subobject.
6999 for (CXXBasePathElement &Elem : Paths.front())
7000 if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
7001 return false;
7002 return true;
7003 }
7004
7005 // Otherwise, the runtime check fails.
7006 return RuntimeCheckFailed(&Paths);
7007}
7008
7009namespace {
7010struct StartLifetimeOfUnionMemberHandler {
7011 EvalInfo &Info;
7012 const Expr *LHSExpr;
7013 const FieldDecl *Field;
7014 bool DuringInit;
7015 bool Failed = false;
7016 static const AccessKinds AccessKind = AK_Assign;
7017
7018 typedef bool result_type;
7019 bool failed() { return Failed; }
7020 bool found(APValue &Subobj, QualType SubobjType, APValue::LValueBase Base) {
7021 // We are supposed to perform no initialization but begin the lifetime of
7022 // the object. We interpret that as meaning to do what default
7023 // initialization of the object would do if all constructors involved were
7024 // trivial:
7025 // * All base, non-variant member, and array element subobjects' lifetimes
7026 // begin
7027 // * No variant members' lifetimes begin
7028 // * All scalar subobjects whose lifetimes begin have indeterminate values
7029 assert(SubobjType->isUnionType());
7030 if (declaresSameEntity(Subobj.getUnionField(), Field)) {
7031 // This union member is already active. If it's also in-lifetime, there's
7032 // nothing to do.
7033 if (Subobj.getUnionValue().hasValue())
7034 return true;
7035 } else if (DuringInit) {
7036 // We're currently in the process of initializing a different union
7037 // member. If we carried on, that initialization would attempt to
7038 // store to an inactive union member, resulting in undefined behavior.
7039 Info.FFDiag(LHSExpr,
7040 diag::note_constexpr_union_member_change_during_init);
7041 return false;
7042 }
7044 Failed = !handleDefaultInitValue(Field->getType(), Result);
7045 Subobj.setUnion(Field, Result);
7046 return true;
7047 }
7048 bool found(APSInt &Value, QualType SubobjType) {
7049 llvm_unreachable("wrong value kind for union object");
7050 }
7051 bool found(APFloat &Value, QualType SubobjType) {
7052 llvm_unreachable("wrong value kind for union object");
7053 }
7054};
7055} // end anonymous namespace
7056
7057const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
7058
7059/// Handle a builtin simple-assignment or a call to a trivial assignment
7060/// operator whose left-hand side might involve a union member access. If it
7061/// does, implicitly start the lifetime of any accessed union elements per
7062/// C++20 [class.union]5.
7063static bool MaybeHandleUnionActiveMemberChange(EvalInfo &Info,
7064 const Expr *LHSExpr,
7065 const LValue &LHS) {
7066 if (LHS.InvalidBase || LHS.Designator.Invalid)
7067 return false;
7068
7070 // C++ [class.union]p5:
7071 // define the set S(E) of subexpressions of E as follows:
7072 unsigned PathLength = LHS.Designator.Entries.size();
7073 for (const Expr *E = LHSExpr; E != nullptr;) {
7074 // -- If E is of the form A.B, S(E) contains the elements of S(A)...
7075 if (auto *ME = dyn_cast<MemberExpr>(E)) {
7076 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
7077 // Note that we can't implicitly start the lifetime of a reference,
7078 // so we don't need to proceed any further if we reach one.
7079 if (!FD || FD->getType()->isReferenceType())
7080 break;
7081
7082 // ... and also contains A.B if B names a union member ...
7083 if (FD->getParent()->isUnion()) {
7084 // ... of a non-class, non-array type, or of a class type with a
7085 // trivial default constructor that is not deleted, or an array of
7086 // such types.
7087 auto *RD =
7088 FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
7089 if (!RD || RD->hasTrivialDefaultConstructor())
7090 UnionPathLengths.push_back({PathLength - 1, FD});
7091 }
7092
7093 E = ME->getBase();
7094 --PathLength;
7095 assert(declaresSameEntity(FD,
7096 LHS.Designator.Entries[PathLength]
7097 .getAsBaseOrMember().getPointer()));
7098
7099 // -- If E is of the form A[B] and is interpreted as a built-in array
7100 // subscripting operator, S(E) is [S(the array operand, if any)].
7101 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
7102 // Step over an ArrayToPointerDecay implicit cast.
7103 auto *Base = ASE->getBase()->IgnoreImplicit();
7104 if (!Base->getType()->isArrayType())
7105 break;
7106
7107 E = Base;
7108 --PathLength;
7109
7110 } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
7111 // Step over a derived-to-base conversion.
7112 E = ICE->getSubExpr();
7113 if (ICE->getCastKind() == CK_NoOp)
7114 continue;
7115 if (ICE->getCastKind() != CK_DerivedToBase &&
7116 ICE->getCastKind() != CK_UncheckedDerivedToBase)
7117 break;
7118 // Walk path backwards as we walk up from the base to the derived class.
7119 for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
7120 if (Elt->isVirtual()) {
7121 // A class with virtual base classes never has a trivial default
7122 // constructor, so S(E) is empty in this case.
7123 E = nullptr;
7124 break;
7125 }
7126
7127 --PathLength;
7128 assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
7129 LHS.Designator.Entries[PathLength]
7130 .getAsBaseOrMember().getPointer()));
7131 }
7132
7133 // -- Otherwise, S(E) is empty.
7134 } else {
7135 break;
7136 }
7137 }
7138
7139 // Common case: no unions' lifetimes are started.
7140 if (UnionPathLengths.empty())
7141 return true;
7142
7143 // if modification of X [would access an inactive union member], an object
7144 // of the type of X is implicitly created
7145 CompleteObject Obj =
7146 findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
7147 if (!Obj)
7148 return false;
7149 for (std::pair<unsigned, const FieldDecl *> LengthAndField :
7150 llvm::reverse(UnionPathLengths)) {
7151 // Form a designator for the union object.
7152 SubobjectDesignator D = LHS.Designator;
7153 D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
7154
7155 bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) ==
7156 ConstructionPhase::AfterBases;
7157 StartLifetimeOfUnionMemberHandler StartLifetime{
7158 Info, LHSExpr, LengthAndField.second, DuringInit};
7159 if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
7160 return false;
7161 }
7162
7163 return true;
7164}
7165
7166static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg,
7167 CallRef Call, EvalInfo &Info, bool NonNull = false,
7168 APValue **EvaluatedArg = nullptr) {
7169 LValue LV;
7170 // Create the parameter slot and register its destruction. For a vararg
7171 // argument, create a temporary.
7172 // FIXME: For calling conventions that destroy parameters in the callee,
7173 // should we consider performing destruction when the function returns
7174 // instead?
7175 APValue &V = PVD ? Info.CurrentCall->createParam(Call, PVD, LV)
7176 : Info.CurrentCall->createTemporary(Arg, Arg->getType(),
7177 ScopeKind::Call, LV);
7178 if (!EvaluateInPlace(V, Info, LV, Arg))
7179 return false;
7180
7181 // Passing a null pointer to an __attribute__((nonnull)) parameter results in
7182 // undefined behavior, so is non-constant.
7183 if (NonNull && V.isLValue() && V.isNullPointer()) {
7184 Info.CCEDiag(Arg, diag::note_non_null_attribute_failed);
7185 return false;
7186 }
7187
7188 if (EvaluatedArg)
7189 *EvaluatedArg = &V;
7190
7191 return true;
7192}
7193
7194/// Evaluate the arguments to a function call.
7195static bool EvaluateArgs(ArrayRef<const Expr *> Args, CallRef Call,
7196 EvalInfo &Info, const FunctionDecl *Callee,
7197 bool RightToLeft = false,
7198 LValue *ObjectArg = nullptr) {
7199 bool Success = true;
7200 llvm::SmallBitVector ForbiddenNullArgs;
7201 if (Callee->hasAttr<NonNullAttr>()) {
7202 ForbiddenNullArgs.resize(Args.size());
7203 for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
7204 if (!Attr->args_size()) {
7205 ForbiddenNullArgs.set();
7206 break;
7207 } else
7208 for (auto Idx : Attr->args()) {
7209 unsigned ASTIdx = Idx.getASTIndex();
7210 if (ASTIdx >= Args.size())
7211 continue;
7212 ForbiddenNullArgs[ASTIdx] = true;
7213 }
7214 }
7215 }
7216 for (unsigned I = 0; I < Args.size(); I++) {
7217 unsigned Idx = RightToLeft ? Args.size() - I - 1 : I;
7218 const ParmVarDecl *PVD =
7219 Idx < Callee->getNumParams() ? Callee->getParamDecl(Idx) : nullptr;
7220 bool NonNull = !ForbiddenNullArgs.empty() && ForbiddenNullArgs[Idx];
7221 APValue *That = nullptr;
7222 if (!EvaluateCallArg(PVD, Args[Idx], Call, Info, NonNull, &That)) {
7223 // If we're checking for a potential constant expression, evaluate all
7224 // initializers even if some of them fail.
7225 if (!Info.noteFailure())
7226 return false;
7227 Success = false;
7228 }
7229 if (PVD && PVD->isExplicitObjectParameter() && That && That->isLValue())
7230 ObjectArg->setFrom(Info.Ctx, *That);
7231 }
7232 return Success;
7233}
7234
7235/// Perform a trivial copy from Param, which is the parameter of a copy or move
7236/// constructor or assignment operator.
7237static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param,
7238 const Expr *E, APValue &Result,
7239 bool CopyObjectRepresentation) {
7240 // Find the reference argument.
7241 CallStackFrame *Frame = Info.CurrentCall;
7242 APValue *RefValue = Info.getParamSlot(Frame->Arguments, Param);
7243 if (!RefValue) {
7244 Info.FFDiag(E);
7245 return false;
7246 }
7247
7248 // Copy out the contents of the RHS object.
7249 LValue RefLValue;
7250 RefLValue.setFrom(Info.Ctx, *RefValue);
7252 Info, E, Param->getType().getNonReferenceType(), RefLValue, Result,
7253 CopyObjectRepresentation);
7254}
7255
7257 // If the function is a specialization of a member function template which has
7258 // been declared a friend by another class, 'FD' might be a Decl marked as an
7259 // explicit specialization, which would then be classified as "not implicitly
7260 // instantiable". Walking to the most recent Decl resolves this.
7261 FD = FD->getMostRecentDecl();
7262
7263 if (FD->isDefined() || !FD->isImplicitlyInstantiable() || !FD->isConstexpr())
7264 return false;
7265
7267 return Pattern && Pattern->isDefined();
7268}
7269
7271 EvalInfo &Info,
7272 SourceLocation Loc) {
7273 // [C++26] [temp.inst] p5
7274 // [...] the function template specialization is implicitly instantiated
7275 // when the specialization is referenced in a context that requires a function
7276 // definition to exist or if the existence of the definition affects the
7277 // semantics of the program.
7278
7279 SemaProxy *SProxy = Info.getSemaProxy();
7281 Info.InConstantContext)
7282 SProxy->instantiateFunctionDefinition(Loc, const_cast<FunctionDecl *>(FD));
7283}
7284
7285/// Evaluate a function call.
7287 const FunctionDecl *Callee,
7288 const LValue *ObjectArg, const Expr *E,
7289 ArrayRef<const Expr *> Args, CallRef Call,
7290 const Stmt *Body, EvalInfo &Info,
7291 APValue &Result, const LValue *ResultSlot) {
7292 if (!Info.CheckCallLimit(CallLoc))
7293 return false;
7294
7295 CallStackFrame Frame(Info, E->getSourceRange(), Callee, ObjectArg, E, Call);
7296
7297 // For a trivial copy or move assignment, perform an APValue copy. This is
7298 // essential for unions, where the operations performed by the assignment
7299 // operator cannot be represented as statements.
7300 //
7301 // Skip this for non-union classes with no fields; in that case, the defaulted
7302 // copy/move does not actually read the object.
7303 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
7304
7305 auto IsTrivialMemoryOperation = [&](const CXXMethodDecl *MD) {
7306 if (!MD || !MD->isDefaulted())
7307 return false;
7309 return false;
7310 return MD->getParent()->isUnion() ||
7311 (MD->isTrivial() &&
7313 };
7314
7315 if (IsTrivialMemoryOperation(MD)) {
7316 unsigned ExplicitOffset = MD->isExplicitObjectMemberFunction() ? 1 : 0;
7317 assert(ObjectArg);
7318 APValue RHSValue;
7319 if (!handleTrivialCopy(Info, MD->getParamDecl(0), Args[0], RHSValue,
7320 MD->getParent()->isUnion()))
7321 return false;
7322
7323 if (!handleAssignment(Info, Args[ExplicitOffset], *ObjectArg,
7325 RHSValue))
7326 return false;
7327 ObjectArg->moveInto(Result);
7328 return true;
7329 } else if (MD && isLambdaCallOperator(MD)) {
7330 // We're in a lambda; determine the lambda capture field maps unless we're
7331 // just constexpr checking a lambda's call operator. constexpr checking is
7332 // done before the captures have been added to the closure object (unless
7333 // we're inferring constexpr-ness), so we don't have access to them in this
7334 // case. But since we don't need the captures to constexpr check, we can
7335 // just ignore them.
7336 if (!Info.checkingPotentialConstantExpression())
7337 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
7338 Frame.LambdaThisCaptureField);
7339 }
7340
7341 StmtResult Ret = {Result, ResultSlot};
7342 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
7343 if (ESR == ESR_Succeeded) {
7344 if (Callee->getReturnType()->isVoidType())
7345 return true;
7346 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
7347 }
7348 return ESR == ESR_Returned;
7349}
7350
7351static bool HandleConstructorCall(const Expr *E, const LValue &This,
7352 CallRef Call,
7353 const CXXConstructorDecl *Definition,
7354 EvalInfo &Info, APValue &Result,
7355 bool IsCompleteClass = true);
7356
7357static bool HandleConstructorCall(const Expr *E, const LValue &This,
7360 EvalInfo &Info, APValue &Result,
7361 bool IsCompleteClass = true) {
7362 CallScopeRAII CallScope(Info);
7363 CallRef Call = Info.CurrentCall->createCall(Definition);
7364 if (!EvaluateArgs(Args, Call, Info, Definition))
7365 return false;
7366
7367 return HandleConstructorCall(E, This, Call, Definition, Info, Result,
7368 IsCompleteClass) &&
7369 CallScope.destroy();
7370}
7371
7372/// Evaluate a constructor call.
7373static bool HandleConstructorCall(const Expr *E, const LValue &This,
7374 CallRef Call,
7376 EvalInfo &Info, APValue &Result,
7377 bool IsCompleteClass) {
7378
7379 SourceLocation CallLoc = E->getExprLoc();
7380 if (!Info.CheckCallLimit(CallLoc))
7381 return false;
7382
7383 const CXXRecordDecl *RD = Definition->getParent();
7384 if (!Info.getLangOpts().CPlusPlus26 && RD->getNumVBases()) {
7385 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
7386 return false;
7387 }
7388
7389 EvalInfo::EvaluatingConstructorRAII EvalObj(
7390 Info,
7391 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
7392 RD->getNumBases());
7393 CallStackFrame Frame(Info, E->getSourceRange(), Definition, &This, E, Call);
7394
7395 // FIXME: Creating an APValue just to hold a nonexistent return value is
7396 // wasteful.
7397 APValue RetVal;
7398 StmtResult Ret = {RetVal, nullptr};
7399
7400 // If it's a delegating constructor, delegate.
7401 if (Definition->isDelegatingConstructor()) {
7403 if ((*I)->getInit()->isValueDependent()) {
7404 if (!EvaluateDependentExpr((*I)->getInit(), Info))
7405 return false;
7406 } else {
7407 FullExpressionRAII InitScope(Info);
7408 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) ||
7409 !InitScope.destroy())
7410 return false;
7411 }
7412 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
7413 }
7414
7415 // For a trivial copy or move constructor, perform an APValue copy. This is
7416 // essential for unions (or classes with anonymous union members), where the
7417 // operations performed by the constructor cannot be represented by
7418 // ctor-initializers.
7419 //
7420 // Skip this for empty non-union classes; we should not perform an
7421 // lvalue-to-rvalue conversion on them because their copy constructor does not
7422 // actually read them.
7423 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
7424 (Definition->getParent()->isUnion() ||
7425 (Definition->isTrivial() &&
7427 return handleTrivialCopy(Info, Definition->getParamDecl(0), E, Result,
7428 Definition->getParent()->isUnion());
7429 }
7430
7431 // Reserve space for the struct members.
7432 if (!Result.hasValue()) {
7433 if (!RD->isUnion()) {
7434 unsigned NonVirtualBases = countNonVirtualBases(RD);
7435 Result = APValue(APValue::UninitStruct(), NonVirtualBases,
7436 RD->getNumFields(), RD->getNumVBases());
7437 } else
7438 // A union starts with no active member.
7439 Result = APValue((const FieldDecl*)nullptr);
7440 }
7441
7442 if (RD->isInvalidDecl()) return false;
7443 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7444
7445 // A scope for temporaries lifetime-extended by reference members.
7446 BlockScopeRAII LifetimeExtendedScope(Info);
7447
7448 bool Success = true;
7449 unsigned BasesSeen = 0;
7450 unsigned VirtualBasesSeen = 0;
7451 unsigned NonVirtualBases = countNonVirtualBases(RD);
7452
7454 auto SkipToField = [&](FieldDecl *FD, bool Indirect) {
7455 // We might be initializing the same field again if this is an indirect
7456 // field initialization.
7457 if (FieldIt == RD->field_end() ||
7458 FieldIt->getFieldIndex() > FD->getFieldIndex()) {
7459 assert(Indirect && "fields out of order?");
7460 return;
7461 }
7462
7463 // Default-initialize any fields with no explicit initializer.
7464 for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
7465 assert(FieldIt != RD->field_end() && "missing field?");
7466 if (!FieldIt->isUnnamedBitField())
7468 FieldIt->getType(),
7469 Result.getStructField(FieldIt->getFieldIndex()));
7470 }
7471 ++FieldIt;
7472 };
7473 for (const auto *I : Definition->inits()) {
7474 LValue Subobject = This;
7475 LValue SubobjectParent = This;
7476 APValue *Value = &Result;
7477
7478 // Determine the subobject to initialize.
7479 FieldDecl *FD = nullptr;
7480 if (I->isBaseInitializer()) {
7481 QualType BaseType(I->getBaseClass(), 0);
7482 if (I->isBaseVirtual()) {
7483 if (This.pointsToCompleteClass(RD)) {
7484 if (!HandleLValueDirectVirtualBase(Info, I->getInit(), Subobject, RD,
7485 BaseType->getAsCXXRecordDecl(),
7486 &Layout))
7487 return false;
7488 Value = &Result.getStructVirtualBase(VirtualBasesSeen++);
7489 } else {
7490 continue;
7491 }
7492
7493 } else {
7494 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
7495 BaseType->getAsCXXRecordDecl(), &Layout))
7496 return false;
7497 Value = &Result.getStructBase(BasesSeen++);
7498 }
7499 } else if ((FD = I->getMember())) {
7500 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
7501 return false;
7502 if (RD->isUnion()) {
7503 Result = APValue(FD);
7504 Value = &Result.getUnionValue();
7505 } else {
7506 SkipToField(FD, false);
7507 Value = &Result.getStructField(FD->getFieldIndex());
7508 }
7509 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
7510 // Walk the indirect field decl's chain to find the object to initialize,
7511 // and make sure we've initialized every step along it.
7512 auto IndirectFieldChain = IFD->chain();
7513 for (auto *C : IndirectFieldChain) {
7514 FD = cast<FieldDecl>(C);
7516 // Switch the union field if it differs. This happens if we had
7517 // preceding zero-initialization, and we're now initializing a union
7518 // subobject other than the first.
7519 // FIXME: In this case, the values of the other subobjects are
7520 // specified, since zero-initialization sets all padding bits to zero.
7521 if (!Value->hasValue() ||
7522 (Value->isUnion() &&
7523 !declaresSameEntity(Value->getUnionField(), FD))) {
7524 if (CD->isUnion())
7525 *Value = APValue(FD);
7526 else
7527 // FIXME: This immediately starts the lifetime of all members of
7528 // an anonymous struct. It would be preferable to strictly start
7529 // member lifetime in initialization order.
7530 Success &= handleDefaultInitValue(Info.Ctx.getCanonicalTagType(CD),
7531 *Value);
7532 }
7533 // Store Subobject as its parent before updating it for the last element
7534 // in the chain.
7535 if (C == IndirectFieldChain.back())
7536 SubobjectParent = Subobject;
7537 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
7538 return false;
7539 if (CD->isUnion())
7540 Value = &Value->getUnionValue();
7541 else {
7542 if (C == IndirectFieldChain.front() && !RD->isUnion())
7543 SkipToField(FD, true);
7544 Value = &Value->getStructField(FD->getFieldIndex());
7545 }
7546 }
7547 } else {
7548 llvm_unreachable("unknown base initializer kind");
7549 }
7550
7551 // Need to override This for implicit field initializers as in this case
7552 // This refers to innermost anonymous struct/union containing initializer,
7553 // not to currently constructed class.
7554 const Expr *Init = I->getInit();
7555 if (Init->isValueDependent()) {
7556 if (!EvaluateDependentExpr(Init, Info))
7557 return false;
7558 } else {
7559 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
7561 FullExpressionRAII InitScope(Info);
7562 if (FD && FD->getType()->isReferenceType() &&
7563 !FD->getType()->isFunctionReferenceType()) {
7564 LValue Result;
7566 *Value)) {
7567 if (!Info.noteFailure())
7568 return false;
7569 Success = false;
7570 }
7571 } else if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
7572 (FD && FD->isBitField() &&
7573 !truncateBitfieldValue(Info, Init, *Value, FD))) {
7574 // If we're checking for a potential constant expression, evaluate all
7575 // initializers even if some of them fail.
7576 if (!Info.noteFailure())
7577 return false;
7578 Success = false;
7579 }
7580 }
7581
7582 // This is the point at which the dynamic type of the object becomes this
7583 // class type.
7584 if (I->isBaseInitializer() && BasesSeen == NonVirtualBases)
7585 EvalObj.finishedConstructingBases();
7586 }
7587
7588 // Default-initialize any remaining fields.
7589 if (!RD->isUnion()) {
7590 for (; FieldIt != RD->field_end(); ++FieldIt) {
7591 if (!FieldIt->isUnnamedBitField())
7593 FieldIt->getType(),
7594 Result.getStructField(FieldIt->getFieldIndex()));
7595 }
7596 }
7597
7598 EvalObj.finishedConstructingFields();
7599
7600 return Success &&
7601 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed &&
7602 LifetimeExtendedScope.destroy();
7603}
7604
7605static bool HandleDestructionImpl(EvalInfo &Info, SourceRange CallRange,
7606 const LValue &This, APValue &Value,
7607 QualType T, bool IsCompleteClass = true) {
7608 // Objects can only be destroyed while they're within their lifetimes.
7609 // FIXME: We have no representation for whether an object of type nullptr_t
7610 // is in its lifetime; it usually doesn't matter. Perhaps we should model it
7611 // as indeterminate instead?
7612 if (Value.isAbsent() && !T->isNullPtrType()) {
7613 APValue Printable;
7614 This.moveInto(Printable);
7615 Info.FFDiag(CallRange.getBegin(),
7616 diag::note_constexpr_destroy_out_of_lifetime)
7617 << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T));
7618 return false;
7619 }
7620
7621 // Invent an expression for location purposes.
7622 // FIXME: We shouldn't need to do this.
7623 OpaqueValueExpr LocE(CallRange.getBegin(), Info.Ctx.IntTy, VK_PRValue);
7624
7625 // For arrays, destroy elements right-to-left.
7626 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) {
7627 uint64_t Size = CAT->getZExtSize();
7628 QualType ElemT = CAT->getElementType();
7629
7630 if (!CheckArraySize(Info, CAT, CallRange.getBegin()))
7631 return false;
7632
7633 LValue ElemLV = This;
7634 ElemLV.addArray(Info, &LocE, CAT);
7635 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size))
7636 return false;
7637
7638 // Ensure that we have actual array elements available to destroy; the
7639 // destructors might mutate the value, so we can't run them on the array
7640 // filler.
7641 if (Size && Size > Value.getArrayInitializedElts())
7642 expandArray(Value, Value.getArraySize() - 1);
7643
7644 // The size of the array might have been reduced by
7645 // a placement new.
7646 for (Size = Value.getArraySize(); Size != 0; --Size) {
7647 APValue &Elem = Value.getArrayInitializedElt(Size - 1);
7648 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) ||
7649 !HandleDestructionImpl(Info, CallRange, ElemLV, Elem, ElemT))
7650 return false;
7651 }
7652
7653 // End the lifetime of this array now.
7654 Value = APValue();
7655 return true;
7656 }
7657
7658 const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
7659 if (!RD) {
7660 if (T.isDestructedType()) {
7661 Info.FFDiag(CallRange.getBegin(),
7662 diag::note_constexpr_unsupported_destruction)
7663 << T;
7664 return false;
7665 }
7666
7667 Value = APValue();
7668 return true;
7669 }
7670
7671 if (!Info.getLangOpts().CPlusPlus26 && RD->getNumVBases()) {
7672 Info.FFDiag(CallRange.getBegin(), diag::note_constexpr_virtual_base) << RD;
7673 return false;
7674 }
7675
7676 // If an anonymous union would be destroyed, some enclosing destructor must
7677 // have been explicitly defined, and the anonymous union destruction should
7678 // have no effect.
7679 if (RD->isAnonymousStructOrUnion() && RD->isUnion()) {
7680 Value = APValue();
7681 return true;
7682 }
7683
7684 const CXXDestructorDecl *DD = RD->getDestructor();
7685 if (!DD && !RD->hasTrivialDestructor()) {
7686 Info.FFDiag(CallRange.getBegin());
7687 return false;
7688 }
7689
7690 if (!DD || DD->isTrivial()) {
7691 // A trivial destructor just ends the lifetime of the object. Check for
7692 // this case before checking for a body, because we might not bother
7693 // building a body for a trivial destructor. Note that it doesn't matter
7694 // whether the destructor is constexpr in this case; all trivial
7695 // destructors are constexpr.
7696 Value = APValue();
7697 return true;
7698 }
7699
7700 if (!Info.CheckCallLimit(CallRange.getBegin()))
7701 return false;
7702
7703 TryInstantiateFunctionBeforeCall(DD, Info, CallRange.getBegin());
7704
7705 const FunctionDecl *Definition = nullptr;
7706 const Stmt *Body = DD->getBody(Definition);
7707
7708 if (!CheckConstexprFunction(Info, CallRange.getBegin(), DD, Definition, Body))
7709 return false;
7710
7711 CallStackFrame Frame(Info, CallRange, Definition, &This, /*CallExpr=*/nullptr,
7712 CallRef());
7713
7714 // We're now in the period of destruction of this object.
7715 EvalInfo::EvaluatingDestructorRAII EvalObj(
7716 Info,
7717 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries});
7718 unsigned NonVirtualBases = countNonVirtualBases(RD);
7719 unsigned NumVirtualBases = RD->getNumVBases();
7720 unsigned BasesLeft = NonVirtualBases;
7721 if (!EvalObj.DidInsert) {
7722 // C++2a [class.dtor]p19:
7723 // the behavior is undefined if the destructor is invoked for an object
7724 // whose lifetime has ended
7725 // (Note that formally the lifetime ends when the period of destruction
7726 // begins, even though certain uses of the object remain valid until the
7727 // period of destruction ends.)
7728 Info.FFDiag(CallRange.getBegin(), diag::note_constexpr_double_destroy);
7729 return false;
7730 }
7731
7732 // FIXME: Creating an APValue just to hold a nonexistent return value is
7733 // wasteful.
7734 APValue RetVal;
7735 StmtResult Ret = {RetVal, nullptr};
7736 if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed)
7737 return false;
7738
7739 // A union destructor does not implicitly destroy its members.
7740 if (RD->isUnion())
7741 return true;
7742
7743 if (!ASTContext::hasLayout(RD))
7744 return false;
7745 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7746
7747 // We don't have a good way to iterate fields in reverse, so collect all the
7748 // fields first and then walk them backwards.
7749 SmallVector<FieldDecl*, 16> Fields(RD->fields());
7750 for (const FieldDecl *FD : llvm::reverse(Fields)) {
7751 if (FD->isUnnamedBitField())
7752 continue;
7753
7754 LValue Subobject = This;
7755 if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout))
7756 return false;
7757
7758 APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex());
7759 if (!HandleDestructionImpl(Info, CallRange, Subobject, *SubobjectValue,
7760 FD->getType()))
7761 return false;
7762 }
7763
7764 if (BasesLeft != 0 || NumVirtualBases != 0)
7765 EvalObj.startedDestroyingBases();
7766
7767 // Destroy base classes in reverse order.
7768 for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) {
7769 if (Base.isVirtual())
7770 continue;
7771 --BasesLeft;
7772
7773 QualType BaseType = Base.getType();
7774 LValue Subobject = This;
7775 if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD,
7776 BaseType->getAsCXXRecordDecl(), &Layout))
7777 return false;
7778
7779 APValue *SubobjectValue = &Value.getStructBase(BasesLeft);
7780 if (!HandleDestructionImpl(Info, CallRange, Subobject, *SubobjectValue,
7781 BaseType, /*IsCompleteClass=*/false))
7782 return false;
7783 }
7784 assert(BasesLeft == 0 && "NumBases was wrong?");
7785
7786 // Virtual bases.
7787 if (IsCompleteClass) {
7788 unsigned VirtualBasesLeft = NumVirtualBases;
7789 for (const CXXBaseSpecifier &Base : llvm::reverse(RD->vbases())) {
7790 --VirtualBasesLeft;
7791
7792 QualType BaseType = Base.getType();
7793 LValue Subobject = This;
7794 if (!HandleLValueDirectVirtualBase(Info, &LocE, Subobject, RD,
7795 BaseType->getAsCXXRecordDecl(),
7796 &Layout))
7797 return false;
7798
7799 APValue *SubobjectValue = &Value.getStructVirtualBase(VirtualBasesLeft);
7800 if (!HandleDestructionImpl(Info, CallRange, Subobject, *SubobjectValue,
7801 BaseType, /*IsCompleteClass=*/false))
7802 return false;
7803 }
7804 assert(VirtualBasesLeft == 0 && "NumVirtualBases was wrong?");
7805 }
7806
7807 // The period of destruction ends now. The object is gone.
7808 Value = APValue();
7809 return true;
7810}
7811
7812namespace {
7813struct DestroyObjectHandler {
7814 EvalInfo &Info;
7815 const Expr *E;
7816 const LValue &This;
7817 const AccessKinds AccessKind;
7818
7819 typedef bool result_type;
7820 bool failed() { return false; }
7821 bool found(APValue &Subobj, QualType SubobjType, APValue::LValueBase Base) {
7822 return HandleDestructionImpl(Info, E->getSourceRange(), This, Subobj,
7823 SubobjType);
7824 }
7825 bool found(APSInt &Value, QualType SubobjType) {
7826 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
7827 return false;
7828 }
7829 bool found(APFloat &Value, QualType SubobjType) {
7830 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
7831 return false;
7832 }
7833};
7834}
7835
7836/// Perform a destructor or pseudo-destructor call on the given object, which
7837/// might in general not be a complete object.
7838static bool HandleDestruction(EvalInfo &Info, const Expr *E,
7839 const LValue &This, QualType ThisType) {
7840 CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType);
7841 DestroyObjectHandler Handler = {Info, E, This, AK_Destroy};
7842 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
7843}
7844
7845/// Destroy and end the lifetime of the given complete object.
7846static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
7848 QualType T) {
7849 // If we've had an unmodeled side-effect, we can't rely on mutable state
7850 // (such as the object we're about to destroy) being correct.
7851 if (Info.EvalStatus.HasSideEffects)
7852 return false;
7853
7854 LValue LV;
7855 LV.set({LVBase});
7856 return HandleDestructionImpl(Info, Loc, LV, Value, T);
7857}
7858
7859/// Perform a call to 'operator new' or to `__builtin_operator_new'.
7860static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E,
7861 LValue &Result) {
7862 if (Info.checkingPotentialConstantExpression() ||
7863 Info.SpeculativeEvaluationDepth)
7864 return false;
7865
7866 // This is permitted only within a call to std::allocator<T>::allocate.
7867 auto Caller = Info.getStdAllocatorCaller("allocate");
7868 if (!Caller) {
7869 Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20
7870 ? diag::note_constexpr_new_untyped
7871 : diag::note_constexpr_new);
7872 return false;
7873 }
7874
7875 QualType ElemType = Caller.ElemType;
7876 if (ElemType->isIncompleteType() || ElemType->isFunctionType()) {
7877 Info.FFDiag(E->getExprLoc(),
7878 diag::note_constexpr_new_not_complete_object_type)
7879 << (ElemType->isIncompleteType() ? 0 : 1) << ElemType;
7880 return false;
7881 }
7882
7883 APSInt ByteSize;
7884 if (!EvaluateInteger(E->getArg(0), ByteSize, Info))
7885 return false;
7886 bool IsNothrow = false;
7887 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) {
7888 EvaluateIgnoredValue(Info, E->getArg(I));
7889 IsNothrow |= E->getType()->isNothrowT();
7890 }
7891
7892 CharUnits ElemSize;
7893 if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize))
7894 return false;
7895 APInt Size, Remainder;
7896 APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity());
7897 APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder);
7898 if (Remainder != 0) {
7899 // This likely indicates a bug in the implementation of 'std::allocator'.
7900 Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size)
7901 << ByteSize << APSInt(ElemSizeAP, true) << ElemType;
7902 return false;
7903 }
7904
7905 if (!Info.CheckArraySize(E->getBeginLoc(), ByteSize.getActiveBits(),
7906 Size.getZExtValue(), /*Diag=*/!IsNothrow)) {
7907 if (IsNothrow) {
7908 Result.setNull(Info.Ctx, E->getType());
7909 return true;
7910 }
7911 return false;
7912 }
7913
7914 QualType AllocType = Info.Ctx.getConstantArrayType(
7915 ElemType, Size, nullptr, ArraySizeModifier::Normal, 0);
7916 APValue *Val = Info.createHeapAlloc(Caller.Call, AllocType, Result);
7917 *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue());
7918 Result.addArray(Info, E, cast<ConstantArrayType>(AllocType));
7919 return true;
7920}
7921
7923 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
7924 if (CXXDestructorDecl *DD = RD->getDestructor())
7925 return DD->isVirtual();
7926 return false;
7927}
7928
7930 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
7931 if (CXXDestructorDecl *DD = RD->getDestructor())
7932 return DD->isVirtual() ? DD->getOperatorDelete() : nullptr;
7933 return nullptr;
7934}
7935
7936/// Check that the given object is a suitable pointer to a heap allocation that
7937/// still exists and is of the right kind for the purpose of a deletion.
7938///
7939/// On success, returns the heap allocation to deallocate. On failure, produces
7940/// a diagnostic and returns std::nullopt.
7941static std::optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E,
7942 const LValue &Pointer,
7943 DynAllocKind DeallocKind) {
7944 auto PointerAsString = [&] {
7945 return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy);
7946 };
7947
7948 DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>();
7949 if (!DA) {
7950 Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc)
7951 << PointerAsString();
7952 if (Pointer.Base)
7953 NoteLValueLocation(Info, Pointer.Base);
7954 return std::nullopt;
7955 }
7956
7957 std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
7958 if (!Alloc) {
7959 Info.FFDiag(E, diag::note_constexpr_double_delete);
7960 return std::nullopt;
7961 }
7962
7963 if (DeallocKind != (*Alloc)->getKind()) {
7964 QualType AllocType = Pointer.Base.getDynamicAllocType();
7965 Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch)
7966 << DeallocKind << (*Alloc)->getKind() << AllocType;
7967 NoteLValueLocation(Info, Pointer.Base);
7968 return std::nullopt;
7969 }
7970
7971 bool Subobject = false;
7972 if (DeallocKind == DynAllocKind::New) {
7973 Subobject = Pointer.Designator.MostDerivedPathLength != 0 ||
7974 Pointer.Designator.isOnePastTheEnd();
7975 } else {
7976 Subobject = Pointer.Designator.Entries.size() != 1 ||
7977 Pointer.Designator.Entries[0].getAsArrayIndex() != 0;
7978 }
7979 if (Subobject) {
7980 Info.FFDiag(E, diag::note_constexpr_delete_subobject)
7981 << PointerAsString() << Pointer.Designator.isOnePastTheEnd();
7982 return std::nullopt;
7983 }
7984
7985 return Alloc;
7986}
7987
7988// Perform a call to 'operator delete' or '__builtin_operator_delete'.
7989static bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) {
7990 if (Info.checkingPotentialConstantExpression() ||
7991 Info.SpeculativeEvaluationDepth)
7992 return false;
7993
7994 // This is permitted only within a call to std::allocator<T>::deallocate.
7995 if (!Info.getStdAllocatorCaller("deallocate")) {
7996 Info.FFDiag(E->getExprLoc());
7997 return true;
7998 }
7999
8000 LValue Pointer;
8001 if (!EvaluatePointer(E->getArg(0), Pointer, Info))
8002 return false;
8003 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
8004 EvaluateIgnoredValue(Info, E->getArg(I));
8005
8006 if (Pointer.Designator.Invalid)
8007 return false;
8008
8009 // Deleting a null pointer would have no effect, but it's not permitted by
8010 // std::allocator<T>::deallocate's contract.
8011 if (Pointer.isNullPointer()) {
8012 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_deallocate_null);
8013 return true;
8014 }
8015
8017 return false;
8018
8019 Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>());
8020 return true;
8021}
8022
8023//===----------------------------------------------------------------------===//
8024// Generic Evaluation
8025//===----------------------------------------------------------------------===//
8026namespace {
8027
8028class BitCastBuffer {
8029 // FIXME: We're going to need bit-level granularity when we support
8030 // bit-fields.
8031 // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
8032 // we don't support a host or target where that is the case. Still, we should
8033 // use a more generic type in case we ever do.
8034 SmallVector<std::optional<unsigned char>, 32> Bytes;
8035
8036 static_assert(std::numeric_limits<unsigned char>::digits >= 8,
8037 "Need at least 8 bit unsigned char");
8038
8039 bool TargetIsLittleEndian;
8040
8041public:
8042 BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
8043 : Bytes(Width.getQuantity()),
8044 TargetIsLittleEndian(TargetIsLittleEndian) {}
8045
8046 [[nodiscard]] bool readObject(CharUnits Offset, CharUnits Width,
8047 SmallVectorImpl<unsigned char> &Output) const {
8048 for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
8049 // If a byte of an integer is uninitialized, then the whole integer is
8050 // uninitialized.
8051 if (!Bytes[I.getQuantity()])
8052 return false;
8053 Output.push_back(*Bytes[I.getQuantity()]);
8054 }
8055 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
8056 std::reverse(Output.begin(), Output.end());
8057 return true;
8058 }
8059
8060 void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
8061 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
8062 std::reverse(Input.begin(), Input.end());
8063
8064 size_t Index = 0;
8065 for (unsigned char Byte : Input) {
8066 assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
8067 Bytes[Offset.getQuantity() + Index] = Byte;
8068 ++Index;
8069 }
8070 }
8071
8072 size_t size() { return Bytes.size(); }
8073};
8074
8075/// Traverse an APValue to produce an BitCastBuffer, emulating how the current
8076/// target would represent the value at runtime.
8077class APValueToBufferConverter {
8078 EvalInfo &Info;
8079 BitCastBuffer Buffer;
8080 const CastExpr *BCE;
8081
8082 APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
8083 const CastExpr *BCE)
8084 : Info(Info),
8085 Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
8086 BCE(BCE) {}
8087
8088 bool visit(const APValue &Val, QualType Ty) {
8089 return visit(Val, Ty, CharUnits::fromQuantity(0));
8090 }
8091
8092 // Write out Val with type Ty into Buffer starting at Offset.
8093 bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
8094 assert((size_t)Offset.getQuantity() <= Buffer.size());
8095
8096 // As a special case, nullptr_t has an indeterminate value.
8097 if (Ty->isNullPtrType())
8098 return true;
8099
8100 // Dig through Src to find the byte at SrcOffset.
8101 switch (Val.getKind()) {
8103 case APValue::None:
8104 return true;
8105
8106 case APValue::Int:
8107 return visitInt(Val.getInt(), Ty, Offset);
8108 case APValue::Float:
8109 return visitFloat(Val.getFloat(), Ty, Offset);
8110 case APValue::Array:
8111 return visitArray(Val, Ty, Offset);
8112 case APValue::Struct:
8113 return visitRecord(Val, Ty, Offset);
8114 case APValue::Vector:
8115 return visitVector(Val, Ty, Offset);
8116
8119 return visitComplex(Val, Ty, Offset);
8121 // FIXME: We should support these.
8122
8123 case APValue::LValue:
8124 case APValue::Matrix:
8125 case APValue::Union:
8128 case APValue::Reflection: {
8129 Info.FFDiag(BCE->getBeginLoc(),
8130 diag::note_constexpr_bit_cast_unsupported_type)
8131 << Ty;
8132 return false;
8133 }
8134 }
8135 llvm_unreachable("Unhandled APValue::ValueKind");
8136 }
8137
8138 bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
8139 const RecordDecl *RD = Ty->getAsRecordDecl();
8140 if (!ASTContext::hasLayout(RD))
8141 return false;
8142 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
8143
8144 // Visit the base classes.
8145 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
8146 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
8147 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
8148 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
8149 const APValue &Base = Val.getStructBase(I);
8150
8151 // Can happen in error cases.
8152 if (!Base.isStruct())
8153 return false;
8154
8155 if (!visitRecord(Base, BS.getType(),
8156 Layout.getBaseClassOffset(BaseDecl) + Offset))
8157 return false;
8158 }
8159 }
8160
8161 // Visit the fields.
8162 unsigned FieldIdx = 0;
8163 for (FieldDecl *FD : RD->fields()) {
8164 if (FD->isBitField()) {
8165 Info.FFDiag(BCE->getBeginLoc(),
8166 diag::note_constexpr_bit_cast_unsupported_bitfield);
8167 return false;
8168 }
8169
8170 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
8171
8172 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
8173 "only bit-fields can have sub-char alignment");
8174 CharUnits FieldOffset =
8175 Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
8176 QualType FieldTy = FD->getType();
8177 if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
8178 return false;
8179 ++FieldIdx;
8180 }
8181
8182 return true;
8183 }
8184
8185 bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
8186 const auto *CAT =
8187 dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
8188 if (!CAT)
8189 return false;
8190
8191 CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
8192 unsigned NumInitializedElts = Val.getArrayInitializedElts();
8193 unsigned ArraySize = Val.getArraySize();
8194 // First, initialize the initialized elements.
8195 for (unsigned I = 0; I != NumInitializedElts; ++I) {
8196 const APValue &SubObj = Val.getArrayInitializedElt(I);
8197 if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
8198 return false;
8199 }
8200
8201 // Next, initialize the rest of the array using the filler.
8202 if (Val.hasArrayFiller()) {
8203 const APValue &Filler = Val.getArrayFiller();
8204 for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
8205 if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
8206 return false;
8207 }
8208 }
8209
8210 return true;
8211 }
8212
8213 bool visitComplex(const APValue &Val, QualType Ty, CharUnits Offset) {
8214 const ComplexType *ComplexTy = Ty->castAs<ComplexType>();
8215 QualType EltTy = ComplexTy->getElementType();
8216 CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
8217 bool IsInt = Val.isComplexInt();
8218
8219 if (IsInt) {
8220 if (!visitInt(Val.getComplexIntReal(), EltTy,
8221 Offset + (0 * EltSizeChars)))
8222 return false;
8223 if (!visitInt(Val.getComplexIntImag(), EltTy,
8224 Offset + (1 * EltSizeChars)))
8225 return false;
8226 } else {
8227 if (!visitFloat(Val.getComplexFloatReal(), EltTy,
8228 Offset + (0 * EltSizeChars)))
8229 return false;
8230 if (!visitFloat(Val.getComplexFloatImag(), EltTy,
8231 Offset + (1 * EltSizeChars)))
8232 return false;
8233 }
8234
8235 return true;
8236 }
8237
8238 bool visitVector(const APValue &Val, QualType Ty, CharUnits Offset) {
8239 const VectorType *VTy = Ty->castAs<VectorType>();
8240 QualType EltTy = VTy->getElementType();
8241 unsigned NElts = VTy->getNumElements();
8242
8243 if (VTy->isPackedVectorBoolType(Info.Ctx)) {
8244 // Special handling for OpenCL bool vectors:
8245 // Since these vectors are stored as packed bits, but we can't write
8246 // individual bits to the BitCastBuffer, we'll buffer all of the elements
8247 // together into an appropriately sized APInt and write them all out at
8248 // once. Because we don't accept vectors where NElts * EltSize isn't a
8249 // multiple of the char size, there will be no padding space, so we don't
8250 // have to worry about writing data which should have been left
8251 // uninitialized.
8252 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
8253
8254 llvm::APInt Res = llvm::APInt::getZero(NElts);
8255 for (unsigned I = 0; I < NElts; ++I) {
8256 const llvm::APSInt &EltAsInt = Val.getVectorElt(I).getInt();
8257 assert(EltAsInt.isUnsigned() && EltAsInt.getBitWidth() == 1 &&
8258 "bool vector element must be 1-bit unsigned integer!");
8259
8260 Res.insertBits(EltAsInt, BigEndian ? (NElts - I - 1) : I);
8261 }
8262
8263 SmallVector<uint8_t, 8> Bytes(NElts / 8);
8264 llvm::StoreIntToMemory(Res, &*Bytes.begin(), NElts / 8);
8265 Buffer.writeObject(Offset, Bytes);
8266 } else {
8267 // Iterate over each of the elements and write them out to the buffer at
8268 // the appropriate offset.
8269 CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
8270 for (unsigned I = 0; I < NElts; ++I) {
8271 if (!visit(Val.getVectorElt(I), EltTy, Offset + I * EltSizeChars))
8272 return false;
8273 }
8274 }
8275
8276 return true;
8277 }
8278
8279 bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
8280 APSInt AdjustedVal = Val;
8281 unsigned Width = AdjustedVal.getBitWidth();
8282 if (Ty->isBooleanType()) {
8283 Width = Info.Ctx.getTypeSize(Ty);
8284 AdjustedVal = AdjustedVal.extend(Width);
8285 }
8286
8287 SmallVector<uint8_t, 8> Bytes(Width / 8);
8288 llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8);
8289 Buffer.writeObject(Offset, Bytes);
8290 return true;
8291 }
8292
8293 bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
8294 APSInt AsInt(Val.bitcastToAPInt());
8295 return visitInt(AsInt, Ty, Offset);
8296 }
8297
8298public:
8299 static std::optional<BitCastBuffer>
8300 convert(EvalInfo &Info, const APValue &Src, const CastExpr *BCE) {
8301 CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
8302 APValueToBufferConverter Converter(Info, DstSize, BCE);
8303 if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
8304 return std::nullopt;
8305 return Converter.Buffer;
8306 }
8307};
8308
8309/// Write an BitCastBuffer into an APValue.
8310class BufferToAPValueConverter {
8311 EvalInfo &Info;
8312 const BitCastBuffer &Buffer;
8313 const CastExpr *BCE;
8314
8315 BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
8316 const CastExpr *BCE)
8317 : Info(Info), Buffer(Buffer), BCE(BCE) {}
8318
8319 // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
8320 // with an invalid type, so anything left is a deficiency on our part (FIXME).
8321 // Ideally this will be unreachable.
8322 std::nullopt_t unsupportedType(QualType Ty) {
8323 Info.FFDiag(BCE->getBeginLoc(),
8324 diag::note_constexpr_bit_cast_unsupported_type)
8325 << Ty;
8326 return std::nullopt;
8327 }
8328
8329 std::nullopt_t unrepresentableValue(QualType Ty, const APSInt &Val) {
8330 Info.FFDiag(BCE->getBeginLoc(),
8331 diag::note_constexpr_bit_cast_unrepresentable_value)
8332 << Ty << toString(Val, /*Radix=*/10);
8333 return std::nullopt;
8334 }
8335
8336 std::optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
8337 const EnumType *EnumSugar = nullptr) {
8338 if (T->isNullPtrType()) {
8339 uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
8340 return APValue((Expr *)nullptr,
8341 /*Offset=*/CharUnits::fromQuantity(NullValue),
8342 APValue::NoLValuePath{}, /*IsNullPtr=*/true);
8343 }
8344
8345 CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
8346
8347 // Work around floating point types that contain unused padding bytes. This
8348 // is really just `long double` on x86, which is the only fundamental type
8349 // with padding bytes.
8350 if (T->isRealFloatingType()) {
8351 const llvm::fltSemantics &Semantics =
8352 Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
8353 unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics);
8354 assert(NumBits % 8 == 0);
8355 CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8);
8356 if (NumBytes != SizeOf)
8357 SizeOf = NumBytes;
8358 }
8359
8360 SmallVector<uint8_t, 8> Bytes;
8361 if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
8362 // If this is std::byte or unsigned char, then its okay to store an
8363 // indeterminate value.
8364 bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
8365 bool IsUChar =
8366 !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
8367 T->isSpecificBuiltinType(BuiltinType::Char_U));
8368 if (!IsStdByte && !IsUChar) {
8369 QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
8370 Info.FFDiag(BCE->getExprLoc(),
8371 diag::note_constexpr_bit_cast_indet_dest)
8372 << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
8373 return std::nullopt;
8374 }
8375
8377 }
8378
8379 APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
8380 llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
8381
8383 Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
8384
8385 unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0));
8386 if (IntWidth != Val.getBitWidth()) {
8387 APSInt Truncated = Val.trunc(IntWidth);
8388 if (Truncated.extend(Val.getBitWidth()) != Val)
8389 return unrepresentableValue(QualType(T, 0), Val);
8390 Val = Truncated;
8391 }
8392
8393 return APValue(Val);
8394 }
8395
8396 if (T->isRealFloatingType()) {
8397 const llvm::fltSemantics &Semantics =
8398 Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
8399 return APValue(APFloat(Semantics, Val));
8400 }
8401
8402 return unsupportedType(QualType(T, 0));
8403 }
8404
8405 std::optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
8406 const RecordDecl *RD = RTy->getAsRecordDecl();
8407 if (RD->isInvalidDecl())
8408 return std::nullopt;
8409 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
8410
8411 unsigned NumBases = 0;
8412 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
8413 NumBases = CXXRD->getNumBases();
8414
8415 APValue ResultVal(APValue::UninitStruct(), NumBases, RD->getNumFields());
8416
8417 // Visit the base classes.
8418 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
8419 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
8420 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
8421 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
8422
8423 std::optional<APValue> SubObj = visitType(
8424 BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
8425 if (!SubObj)
8426 return std::nullopt;
8427 ResultVal.getStructBase(I) = *SubObj;
8428 }
8429 }
8430
8431 // Visit the fields.
8432 unsigned FieldIdx = 0;
8433 for (FieldDecl *FD : RD->fields()) {
8434 // FIXME: We don't currently support bit-fields. A lot of the logic for
8435 // this is in CodeGen, so we need to factor it around.
8436 if (FD->isBitField()) {
8437 Info.FFDiag(BCE->getBeginLoc(),
8438 diag::note_constexpr_bit_cast_unsupported_bitfield);
8439 return std::nullopt;
8440 }
8441
8442 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
8443 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
8444
8445 CharUnits FieldOffset =
8446 CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
8447 Offset;
8448 QualType FieldTy = FD->getType();
8449 std::optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
8450 if (!SubObj)
8451 return std::nullopt;
8452 ResultVal.getStructField(FieldIdx) = *SubObj;
8453 ++FieldIdx;
8454 }
8455
8456 return ResultVal;
8457 }
8458
8459 std::optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
8460 QualType RepresentationType =
8461 Ty->getDecl()->getDefinitionOrSelf()->getIntegerType();
8462 assert(!RepresentationType.isNull() &&
8463 "enum forward decl should be caught by Sema");
8464 const auto *AsBuiltin =
8465 RepresentationType.getCanonicalType()->castAs<BuiltinType>();
8466 // Recurse into the underlying type. Treat std::byte transparently as
8467 // unsigned char.
8468 return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
8469 }
8470
8471 std::optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
8472 size_t Size = Ty->getLimitedSize();
8473 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
8474
8475 APValue ArrayValue(APValue::UninitArray(), Size, Size);
8476 for (size_t I = 0; I != Size; ++I) {
8477 std::optional<APValue> ElementValue =
8478 visitType(Ty->getElementType(), Offset + I * ElementWidth);
8479 if (!ElementValue)
8480 return std::nullopt;
8481 ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
8482 }
8483
8484 return ArrayValue;
8485 }
8486
8487 std::optional<APValue> visit(const ComplexType *Ty, CharUnits Offset) {
8488 QualType ElementType = Ty->getElementType();
8489 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(ElementType);
8490 bool IsInt = ElementType->isIntegerType();
8491
8492 std::optional<APValue> Values[2];
8493 for (unsigned I = 0; I != 2; ++I) {
8494 Values[I] = visitType(Ty->getElementType(), Offset + I * ElementWidth);
8495 if (!Values[I])
8496 return std::nullopt;
8497 }
8498
8499 if (IsInt)
8500 return APValue(Values[0]->getInt(), Values[1]->getInt());
8501 return APValue(Values[0]->getFloat(), Values[1]->getFloat());
8502 }
8503
8504 std::optional<APValue> visit(const VectorType *VTy, CharUnits Offset) {
8505 QualType EltTy = VTy->getElementType();
8506 unsigned NElts = VTy->getNumElements();
8507 unsigned EltSize =
8508 VTy->isPackedVectorBoolType(Info.Ctx) ? 1 : Info.Ctx.getTypeSize(EltTy);
8509
8510 SmallVector<APValue, 4> Elts;
8511 Elts.reserve(NElts);
8512 if (VTy->isPackedVectorBoolType(Info.Ctx)) {
8513 // Special handling for OpenCL bool vectors:
8514 // Since these vectors are stored as packed bits, but we can't read
8515 // individual bits from the BitCastBuffer, we'll buffer all of the
8516 // elements together into an appropriately sized APInt and write them all
8517 // out at once. Because we don't accept vectors where NElts * EltSize
8518 // isn't a multiple of the char size, there will be no padding space, so
8519 // we don't have to worry about reading any padding data which didn't
8520 // actually need to be accessed.
8521 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
8522
8523 SmallVector<uint8_t, 8> Bytes;
8524 Bytes.reserve(NElts / 8);
8525 if (!Buffer.readObject(Offset, CharUnits::fromQuantity(NElts / 8), Bytes))
8526 return std::nullopt;
8527
8528 APSInt SValInt(NElts, true);
8529 llvm::LoadIntFromMemory(SValInt, &*Bytes.begin(), Bytes.size());
8530
8531 for (unsigned I = 0; I < NElts; ++I) {
8532 llvm::APInt Elt =
8533 SValInt.extractBits(1, (BigEndian ? NElts - I - 1 : I) * EltSize);
8534 Elts.emplace_back(
8535 APSInt(std::move(Elt), !EltTy->isSignedIntegerType()));
8536 }
8537 } else {
8538 // Iterate over each of the elements and read them from the buffer at
8539 // the appropriate offset.
8540 CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
8541 for (unsigned I = 0; I < NElts; ++I) {
8542 std::optional<APValue> EltValue =
8543 visitType(EltTy, Offset + I * EltSizeChars);
8544 if (!EltValue)
8545 return std::nullopt;
8546 Elts.push_back(std::move(*EltValue));
8547 }
8548 }
8549
8550 return APValue(Elts.data(), Elts.size());
8551 }
8552
8553 std::optional<APValue> visit(const Type *Ty, CharUnits Offset) {
8554 return unsupportedType(QualType(Ty, 0));
8555 }
8556
8557 std::optional<APValue> visitType(QualType Ty, CharUnits Offset) {
8558 QualType Can = Ty.getCanonicalType();
8559
8560 switch (Can->getTypeClass()) {
8561#define TYPE(Class, Base) \
8562 case Type::Class: \
8563 return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
8564#define ABSTRACT_TYPE(Class, Base)
8565#define NON_CANONICAL_TYPE(Class, Base) \
8566 case Type::Class: \
8567 llvm_unreachable("non-canonical type should be impossible!");
8568#define DEPENDENT_TYPE(Class, Base) \
8569 case Type::Class: \
8570 llvm_unreachable( \
8571 "dependent types aren't supported in the constant evaluator!");
8572#define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base) \
8573 case Type::Class: \
8574 llvm_unreachable("either dependent or not canonical!");
8575#include "clang/AST/TypeNodes.inc"
8576 }
8577 llvm_unreachable("Unhandled Type::TypeClass");
8578 }
8579
8580public:
8581 // Pull out a full value of type DstType.
8582 static std::optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
8583 const CastExpr *BCE) {
8584 BufferToAPValueConverter Converter(Info, Buffer, BCE);
8585 return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
8586 }
8587};
8588
8589static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
8590 QualType Ty, EvalInfo *Info,
8591 const ASTContext &Ctx,
8592 bool CheckingDest) {
8593 Ty = Ty.getCanonicalType();
8594
8595 auto diag = [&](int Reason) {
8596 if (Info)
8597 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
8598 << CheckingDest << (Reason == 4) << Reason;
8599 return false;
8600 };
8601 auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
8602 if (Info)
8603 Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
8604 << NoteTy << Construct << Ty;
8605 return false;
8606 };
8607
8608 if (Ty->isUnionType())
8609 return diag(0);
8610 if (Ty->isPointerType())
8611 return diag(1);
8612 if (Ty->isMemberPointerType())
8613 return diag(2);
8614 if (Ty.isVolatileQualified())
8615 return diag(3);
8616
8617 if (RecordDecl *Record = Ty->getAsRecordDecl()) {
8618 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
8619 for (CXXBaseSpecifier &BS : CXXRD->bases())
8620 if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
8621 CheckingDest))
8622 return note(1, BS.getType(), BS.getBeginLoc());
8623 }
8624 for (FieldDecl *FD : Record->fields()) {
8625 if (FD->getType()->isReferenceType())
8626 return diag(4);
8627 if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
8628 CheckingDest))
8629 return note(0, FD->getType(), FD->getBeginLoc());
8630 }
8631 }
8632
8633 if (Ty->isArrayType() &&
8634 !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
8635 Info, Ctx, CheckingDest))
8636 return false;
8637
8638 if (const auto *VTy = Ty->getAs<VectorType>()) {
8639 QualType EltTy = VTy->getElementType();
8640 unsigned NElts = VTy->getNumElements();
8641 unsigned EltSize =
8642 VTy->isPackedVectorBoolType(Ctx) ? 1 : Ctx.getTypeSize(EltTy);
8643
8644 if ((NElts * EltSize) % Ctx.getCharWidth() != 0) {
8645 // The vector's size in bits is not a multiple of the target's byte size,
8646 // so its layout is unspecified. For now, we'll simply treat these cases
8647 // as unsupported (this should only be possible with OpenCL bool vectors
8648 // whose element count isn't a multiple of the byte size).
8649 if (Info)
8650 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_vector)
8651 << QualType(VTy, 0) << EltSize << NElts << Ctx.getCharWidth();
8652 return false;
8653 }
8654
8655 if (EltTy->isRealFloatingType() &&
8656 &Ctx.getFloatTypeSemantics(EltTy) == &APFloat::x87DoubleExtended()) {
8657 // The layout for x86_fp80 vectors seems to be handled very inconsistently
8658 // by both clang and LLVM, so for now we won't allow bit_casts involving
8659 // it in a constexpr context.
8660 if (Info)
8661 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_unsupported_type)
8662 << EltTy;
8663 return false;
8664 }
8665 }
8666
8667 return true;
8668}
8669
8670static bool checkBitCastConstexprEligibility(EvalInfo *Info,
8671 const ASTContext &Ctx,
8672 const CastExpr *BCE) {
8673 bool DestOK = checkBitCastConstexprEligibilityType(
8674 BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
8675 bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
8676 BCE->getBeginLoc(),
8677 BCE->getSubExpr()->getType(), Info, Ctx, false);
8678 return SourceOK;
8679}
8680
8681static bool handleRValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
8682 const APValue &SourceRValue,
8683 const CastExpr *BCE) {
8684 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
8685 "no host or target supports non 8-bit chars");
8686
8687 if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
8688 return false;
8689
8690 // Read out SourceValue into a char buffer.
8691 std::optional<BitCastBuffer> Buffer =
8692 APValueToBufferConverter::convert(Info, SourceRValue, BCE);
8693 if (!Buffer)
8694 return false;
8695
8696 // Write out the buffer into a new APValue.
8697 std::optional<APValue> MaybeDestValue =
8698 BufferToAPValueConverter::convert(Info, *Buffer, BCE);
8699 if (!MaybeDestValue)
8700 return false;
8701
8702 DestValue = std::move(*MaybeDestValue);
8703 return true;
8704}
8705
8706static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
8707 APValue &SourceValue,
8708 const CastExpr *BCE) {
8709 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
8710 "no host or target supports non 8-bit chars");
8711 assert(SourceValue.isLValue() &&
8712 "LValueToRValueBitcast requires an lvalue operand!");
8713
8714 LValue SourceLValue;
8715 APValue SourceRValue;
8716 SourceLValue.setFrom(Info.Ctx, SourceValue);
8718 Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,
8719 SourceRValue, /*WantObjectRepresentation=*/true))
8720 return false;
8721
8722 return handleRValueToRValueBitCast(Info, DestValue, SourceRValue, BCE);
8723}
8724
8725template <class Derived>
8726class ExprEvaluatorBase
8727 : public ConstStmtVisitor<Derived, bool> {
8728private:
8729 Derived &getDerived() { return static_cast<Derived&>(*this); }
8730 bool DerivedSuccess(const APValue &V, const Expr *E) {
8731 return getDerived().Success(V, E);
8732 }
8733 bool DerivedZeroInitialization(const Expr *E) {
8734 return getDerived().ZeroInitialization(E);
8735 }
8736
8737 // Check whether a conditional operator with a non-constant condition is a
8738 // potential constant expression. If neither arm is a potential constant
8739 // expression, then the conditional operator is not either.
8740 template<typename ConditionalOperator>
8741 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
8742 assert(Info.checkingPotentialConstantExpression());
8743
8744 // Speculatively evaluate both arms.
8745 SmallVector<PartialDiagnosticAt, 8> Diag;
8746 {
8747 SpeculativeEvaluationRAII Speculate(Info, &Diag);
8748 StmtVisitorTy::Visit(E->getFalseExpr());
8749 if (Diag.empty())
8750 return;
8751 }
8752
8753 {
8754 SpeculativeEvaluationRAII Speculate(Info, &Diag);
8755 Diag.clear();
8756 Info.EvalStatus.DiagEmitted = false;
8757 StmtVisitorTy::Visit(E->getTrueExpr());
8758 if (Diag.empty())
8759 return;
8760 }
8761
8762 Error(E, diag::note_constexpr_conditional_never_const);
8763 }
8764
8765
8766 template<typename ConditionalOperator>
8767 bool HandleConditionalOperator(const ConditionalOperator *E) {
8768 bool BoolResult;
8769 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
8770 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
8771 CheckPotentialConstantConditional(E);
8772 return false;
8773 }
8774 if (Info.noteFailure()) {
8775 StmtVisitorTy::Visit(E->getTrueExpr());
8776 StmtVisitorTy::Visit(E->getFalseExpr());
8777 }
8778 return false;
8779 }
8780
8781 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
8782 return StmtVisitorTy::Visit(EvalExpr);
8783 }
8784
8785protected:
8786 EvalInfo &Info;
8787 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
8788 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
8789
8790 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
8791 return Info.CCEDiag(E, D);
8792 }
8793
8794 bool ZeroInitialization(const Expr *E) { return Error(E); }
8795
8796 bool IsConstantEvaluatedBuiltinCall(const CallExpr *E) {
8797 unsigned BuiltinOp = E->getBuiltinCallee();
8798 return BuiltinOp != 0 &&
8799 Info.Ctx.BuiltinInfo.isConstantEvaluated(BuiltinOp);
8800 }
8801
8802public:
8803 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
8804
8805 EvalInfo &getEvalInfo() { return Info; }
8806
8807 /// Report an evaluation error. This should only be called when an error is
8808 /// first discovered. When propagating an error, just return false.
8809 bool Error(const Expr *E, diag::kind D) {
8810 Info.FFDiag(E, D) << E->getSourceRange();
8811 return false;
8812 }
8813 bool Error(const Expr *E) {
8814 return Error(E, diag::note_invalid_subexpr_in_const_expr);
8815 }
8816
8817 bool VisitStmt(const Stmt *) {
8818 llvm_unreachable("Expression evaluator should not be called on stmts");
8819 }
8820 bool VisitExpr(const Expr *E) {
8821 return Error(E);
8822 }
8823
8824 bool VisitEmbedExpr(const EmbedExpr *E) {
8825 const auto It = E->begin();
8826 return StmtVisitorTy::Visit(*It);
8827 }
8828
8829 bool VisitPredefinedExpr(const PredefinedExpr *E) {
8830 return StmtVisitorTy::Visit(E->getFunctionName());
8831 }
8832 bool VisitConstantExpr(const ConstantExpr *E) {
8833 if (E->hasAPValueResult())
8834 return DerivedSuccess(E->getAPValueResult(), E);
8835
8836 return StmtVisitorTy::Visit(E->getSubExpr());
8837 }
8838
8839 bool VisitParenExpr(const ParenExpr *E)
8840 { return StmtVisitorTy::Visit(E->getSubExpr()); }
8841 bool VisitUnaryExtension(const UnaryOperator *E)
8842 { return StmtVisitorTy::Visit(E->getSubExpr()); }
8843 bool VisitUnaryPlus(const UnaryOperator *E)
8844 { return StmtVisitorTy::Visit(E->getSubExpr()); }
8845 bool VisitChooseExpr(const ChooseExpr *E)
8846 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
8847 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
8848 { return StmtVisitorTy::Visit(E->getResultExpr()); }
8849 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
8850 { return StmtVisitorTy::Visit(E->getReplacement()); }
8851 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
8852 TempVersionRAII RAII(*Info.CurrentCall);
8853 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
8854 return StmtVisitorTy::Visit(E->getExpr());
8855 }
8856 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
8857 TempVersionRAII RAII(*Info.CurrentCall);
8858 // The initializer may not have been parsed yet, or might be erroneous.
8859 if (!E->getExpr())
8860 return Error(E);
8861 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
8862 return StmtVisitorTy::Visit(E->getExpr());
8863 }
8864
8865 bool VisitExprWithCleanups(const ExprWithCleanups *E) {
8866 FullExpressionRAII Scope(Info);
8867 return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy();
8868 }
8869
8870 // Temporaries are registered when created, so we don't care about
8871 // CXXBindTemporaryExpr.
8872 bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
8873 return StmtVisitorTy::Visit(E->getSubExpr());
8874 }
8875
8876 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
8877 if (E->getCastKind() != CK_PointerToIntegral)
8878 CCEDiag(E, diag::note_constexpr_invalid_cast)
8879 << diag::ConstexprInvalidCastKind::Reinterpret;
8880 return static_cast<Derived*>(this)->VisitCastExpr(E);
8881 }
8882 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
8883 if (!Info.Ctx.getLangOpts().CPlusPlus20)
8884 CCEDiag(E, diag::note_constexpr_invalid_cast)
8885 << diag::ConstexprInvalidCastKind::Dynamic;
8886 return static_cast<Derived*>(this)->VisitCastExpr(E);
8887 }
8888 bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
8889 return static_cast<Derived*>(this)->VisitCastExpr(E);
8890 }
8891
8892 bool VisitBinaryOperator(const BinaryOperator *E) {
8893 switch (E->getOpcode()) {
8894 default:
8895 return Error(E);
8896
8897 case BO_Comma:
8898 VisitIgnoredValue(E->getLHS());
8899 return StmtVisitorTy::Visit(E->getRHS());
8900
8901 case BO_PtrMemD:
8902 case BO_PtrMemI: {
8903 LValue Obj;
8904 if (!HandleMemberPointerAccess(Info, E, Obj))
8905 return false;
8907 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
8908 return false;
8909 return DerivedSuccess(Result, E);
8910 }
8911 }
8912 }
8913
8914 bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) {
8915 return StmtVisitorTy::Visit(E->getSemanticForm());
8916 }
8917
8918 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
8919 // Evaluate and cache the common expression. We treat it as a temporary,
8920 // even though it's not quite the same thing.
8921 LValue CommonLV;
8922 if (!Evaluate(Info.CurrentCall->createTemporary(
8923 E->getOpaqueValue(),
8924 getStorageType(Info.Ctx, E->getOpaqueValue()),
8925 ScopeKind::FullExpression, CommonLV),
8926 Info, E->getCommon()))
8927 return false;
8928
8929 return HandleConditionalOperator(E);
8930 }
8931
8932 bool VisitConditionalOperator(const ConditionalOperator *E) {
8933 bool IsBcpCall = false;
8934 // If the condition (ignoring parens) is a __builtin_constant_p call,
8935 // the result is a constant expression if it can be folded without
8936 // side-effects. This is an important GNU extension. See GCC PR38377
8937 // for discussion.
8938 if (const CallExpr *CallCE =
8939 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
8940 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
8941 IsBcpCall = true;
8942
8943 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
8944 // constant expression; we can't check whether it's potentially foldable.
8945 // FIXME: We should instead treat __builtin_constant_p as non-constant if
8946 // it would return 'false' in this mode.
8947 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
8948 return false;
8949
8950 FoldConstant Fold(Info, IsBcpCall);
8951 if (!HandleConditionalOperator(E)) {
8952 Fold.keepDiagnostics();
8953 return false;
8954 }
8955
8956 return true;
8957 }
8958
8959 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
8960 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E);
8961 Value && !Value->isAbsent())
8962 return DerivedSuccess(*Value, E);
8963
8964 const Expr *Source = E->getSourceExpr();
8965 if (!Source)
8966 return Error(E);
8967 if (Source == E) {
8968 assert(0 && "OpaqueValueExpr recursively refers to itself");
8969 return Error(E);
8970 }
8971 return StmtVisitorTy::Visit(Source);
8972 }
8973
8974 bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
8975 for (const Expr *SemE : E->semantics()) {
8976 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
8977 // FIXME: We can't handle the case where an OpaqueValueExpr is also the
8978 // result expression: there could be two different LValues that would
8979 // refer to the same object in that case, and we can't model that.
8980 if (SemE == E->getResultExpr())
8981 return Error(E);
8982
8983 // Unique OVEs get evaluated if and when we encounter them when
8984 // emitting the rest of the semantic form, rather than eagerly.
8985 if (OVE->isUnique())
8986 continue;
8987
8988 LValue LV;
8989 if (!Evaluate(Info.CurrentCall->createTemporary(
8990 OVE, getStorageType(Info.Ctx, OVE),
8991 ScopeKind::FullExpression, LV),
8992 Info, OVE->getSourceExpr()))
8993 return false;
8994 } else if (SemE == E->getResultExpr()) {
8995 if (!StmtVisitorTy::Visit(SemE))
8996 return false;
8997 } else {
8998 if (!EvaluateIgnoredValue(Info, SemE))
8999 return false;
9000 }
9001 }
9002 return true;
9003 }
9004
9005 bool VisitCallExpr(const CallExpr *E) {
9007 if (!handleCallExpr(E, Result, nullptr))
9008 return false;
9009 return DerivedSuccess(Result, E);
9010 }
9011
9012 bool handleCallExpr(const CallExpr *E, APValue &Result,
9013 const LValue *ResultSlot) {
9014 CallScopeRAII CallScope(Info);
9015
9016 const Expr *Callee = E->getCallee()->IgnoreParens();
9017 QualType CalleeType = Callee->getType();
9018
9019 const FunctionDecl *FD = nullptr;
9020 LValue *This = nullptr, ObjectArg;
9021 auto Args = ArrayRef(E->getArgs(), E->getNumArgs());
9022 bool HasQualifier = false;
9023
9024 CallRef Call;
9025
9026 // Extract function decl and 'this' pointer from the callee.
9027 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
9028 const CXXMethodDecl *Member = nullptr;
9029 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
9030 // Explicit bound member calls, such as x.f() or p->g();
9031 if (!EvaluateObjectArgument(Info, ME->getBase(), ObjectArg))
9032 return false;
9033 Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
9034 if (!Member)
9035 return Error(Callee);
9036 This = &ObjectArg;
9037 HasQualifier = ME->hasQualifier();
9038 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
9039 // Indirect bound member calls ('.*' or '->*').
9040 const ValueDecl *D =
9041 HandleMemberPointerAccess(Info, BE, ObjectArg, false);
9042 if (!D)
9043 return false;
9044 Member = dyn_cast<CXXMethodDecl>(D);
9045 if (!Member)
9046 return Error(Callee);
9047 This = &ObjectArg;
9048 } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
9049 if (!Info.getLangOpts().CPlusPlus20)
9050 Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
9051 return EvaluateObjectArgument(Info, PDE->getBase(), ObjectArg) &&
9052 HandleDestruction(Info, PDE, ObjectArg, PDE->getDestroyedType());
9053 } else
9054 return Error(Callee);
9055 FD = Member;
9056 } else if (CalleeType->isFunctionPointerType()) {
9057 LValue CalleeLV;
9058 if (!EvaluatePointer(Callee, CalleeLV, Info))
9059 return false;
9060
9061 if (!CalleeLV.getLValueOffset().isZero())
9062 return Error(Callee);
9063 if (CalleeLV.isNullPointer()) {
9064 Info.FFDiag(Callee, diag::note_constexpr_null_callee)
9065 << const_cast<Expr *>(Callee);
9066 return false;
9067 }
9068 FD = dyn_cast_or_null<FunctionDecl>(
9069 CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>());
9070 if (!FD)
9071 return Error(Callee);
9072 // Don't call function pointers which have been cast to some other type.
9073 // Per DR (no number yet), the caller and callee can differ in noexcept.
9074 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
9075 CalleeType->getPointeeType(), FD->getType())) {
9076 return Error(E);
9077 }
9078
9079 // For an (overloaded) assignment expression, evaluate the RHS before the
9080 // LHS.
9081 auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
9082 if (OCE && OCE->isAssignmentOp()) {
9083 assert(Args.size() == 2 && "wrong number of arguments in assignment");
9084 Call = Info.CurrentCall->createCall(FD);
9085 bool HasThis = false;
9086 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
9087 HasThis = MD->isImplicitObjectMemberFunction();
9088 if (!EvaluateArgs(HasThis ? Args.slice(1) : Args, Call, Info, FD,
9089 /*RightToLeft=*/true, &ObjectArg))
9090 return false;
9091 }
9092
9093 // Overloaded operator calls to member functions are represented as normal
9094 // calls with '*this' as the first argument.
9095 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
9096 if (MD &&
9097 (MD->isImplicitObjectMemberFunction() || (OCE && MD->isStatic()))) {
9098 // FIXME: When selecting an implicit conversion for an overloaded
9099 // operator delete, we sometimes try to evaluate calls to conversion
9100 // operators without a 'this' parameter!
9101 if (Args.empty())
9102 return Error(E);
9103
9104 if (!EvaluateObjectArgument(Info, Args[0], ObjectArg))
9105 return false;
9106
9107 // If we are calling a static operator, the 'this' argument needs to be
9108 // ignored after being evaluated.
9109 if (MD->isInstance())
9110 This = &ObjectArg;
9111
9112 // If this is syntactically a simple assignment using a trivial
9113 // assignment operator, start the lifetimes of union members as needed,
9114 // per C++20 [class.union]5.
9115 if (Info.getLangOpts().CPlusPlus20 && OCE &&
9116 OCE->getOperator() == OO_Equal && MD->isTrivial() &&
9117 !MaybeHandleUnionActiveMemberChange(Info, Args[0], ObjectArg))
9118 return false;
9119
9120 Args = Args.slice(1);
9121 } else if (MD && MD->isLambdaStaticInvoker()) {
9122 // Map the static invoker for the lambda back to the call operator.
9123 // Conveniently, we don't have to slice out the 'this' argument (as is
9124 // being done for the non-static case), since a static member function
9125 // doesn't have an implicit argument passed in.
9126 const CXXRecordDecl *ClosureClass = MD->getParent();
9127 assert(
9128 ClosureClass->captures().empty() &&
9129 "Number of captures must be zero for conversion to function-ptr");
9130
9131 const CXXMethodDecl *LambdaCallOp =
9132 ClosureClass->getLambdaCallOperator();
9133
9134 // Set 'FD', the function that will be called below, to the call
9135 // operator. If the closure object represents a generic lambda, find
9136 // the corresponding specialization of the call operator.
9137
9138 if (ClosureClass->isGenericLambda()) {
9139 assert(MD->isFunctionTemplateSpecialization() &&
9140 "A generic lambda's static-invoker function must be a "
9141 "template specialization");
9142 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
9143 FunctionTemplateDecl *CallOpTemplate =
9144 LambdaCallOp->getDescribedFunctionTemplate();
9145 llvm::FoldingSetInsertToken InsertToken;
9146 FunctionDecl *CorrespondingCallOpSpecialization =
9147 CallOpTemplate->findSpecialization(TAL->asArray(), InsertToken);
9148 assert(CorrespondingCallOpSpecialization &&
9149 "We must always have a function call operator specialization "
9150 "that corresponds to our static invoker specialization");
9151 assert(isa<CXXMethodDecl>(CorrespondingCallOpSpecialization));
9152 FD = CorrespondingCallOpSpecialization;
9153 } else
9154 FD = LambdaCallOp;
9156 if (FD->getDeclName().isAnyOperatorNew()) {
9157 LValue Ptr;
9158 if (!HandleOperatorNewCall(Info, E, Ptr))
9159 return false;
9160 Ptr.moveInto(Result);
9161 return CallScope.destroy();
9162 } else {
9163 return HandleOperatorDeleteCall(Info, E) && CallScope.destroy();
9164 }
9165 }
9166 } else
9167 return Error(E);
9168
9169 // Evaluate the arguments now if we've not already done so.
9170 if (!Call) {
9171 Call = Info.CurrentCall->createCall(FD);
9172 if (!EvaluateArgs(Args, Call, Info, FD, /*RightToLeft*/ false,
9173 &ObjectArg))
9174 return false;
9175 }
9176
9177 SmallVector<QualType, 4> CovariantAdjustmentPath;
9178 if (This) {
9179 auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
9180 if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
9181 // Perform virtual dispatch, if necessary.
9182 FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
9183 CovariantAdjustmentPath);
9184 if (!FD)
9185 return false;
9186 } else if (NamedMember && NamedMember->isImplicitObjectMemberFunction()) {
9187 // Check that the 'this' pointer points to an object of the right type.
9188 // FIXME: If this is an assignment operator call, we may need to change
9189 // the active union member before we check this.
9190 if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
9191 return false;
9192 }
9193 }
9194
9195 // Destructor calls are different enough that they have their own codepath.
9196 if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
9197 assert(This && "no 'this' pointer for destructor call");
9198 return HandleDestruction(Info, E, *This,
9199 Info.Ctx.getCanonicalTagType(DD->getParent())) &&
9200 CallScope.destroy();
9201 }
9202
9203 SourceLocation Loc = E->getExprLoc();
9204
9205 TryInstantiateFunctionBeforeCall(FD, Info, Loc);
9206
9207 const FunctionDecl *Definition = nullptr;
9208 Stmt *Body = FD->getBody(Definition);
9209
9210 // Treat the object argument as `this` when evaluating defaulted
9211 // special menmber functions
9213 This = &ObjectArg;
9214
9215 if (!CheckConstexprFunction(Info, Loc, FD, Definition, Body) ||
9216 !HandleFunctionCall(Loc, Definition, This, E, Args, Call, Body, Info,
9217 Result, ResultSlot))
9218 return false;
9219
9220 if (!CovariantAdjustmentPath.empty() &&
9222 CovariantAdjustmentPath))
9223 return false;
9224
9225 return CallScope.destroy();
9226 }
9227
9228 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
9229 return StmtVisitorTy::Visit(E->getInitializer());
9230 }
9231 bool VisitInitListExpr(const InitListExpr *E) {
9232 if (E->getNumInits() == 0)
9233 return DerivedZeroInitialization(E);
9234 if (E->getNumInits() == 1)
9235 return StmtVisitorTy::Visit(E->getInit(0));
9236 return Error(E);
9237 }
9238 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
9239 return DerivedZeroInitialization(E);
9240 }
9241 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
9242 return DerivedZeroInitialization(E);
9243 }
9244 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
9245 return DerivedZeroInitialization(E);
9246 }
9247
9248 /// A member expression where the object is a prvalue is itself a prvalue.
9249 bool VisitMemberExpr(const MemberExpr *E) {
9250 assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
9251 "missing temporary materialization conversion");
9252 assert(!E->isArrow() && "missing call to bound member function?");
9253
9254 APValue Val;
9255 if (!Evaluate(Val, Info, E->getBase()))
9256 return false;
9257
9258 QualType BaseTy = E->getBase()->getType();
9259
9260 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
9261 if (!FD) return Error(E);
9262 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
9263 assert(BaseTy->castAsCanonical<RecordType>()->getDecl() ==
9264 FD->getParent()->getCanonicalDecl() &&
9265 "record / field mismatch");
9266
9267 // Note: there is no lvalue base here. But this case should only ever
9268 // happen in C or in C++98, where we cannot be evaluating a constexpr
9269 // constructor, which is the only case the base matters.
9270 CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
9271 SubobjectDesignator Designator(BaseTy);
9272 Designator.addDeclUnchecked(FD);
9273
9275 return extractSubobject(Info, E, Obj, Designator, Result) &&
9276 DerivedSuccess(Result, E);
9277 }
9278
9279 bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) {
9280 APValue Val;
9281 if (!Evaluate(Val, Info, E->getBase()))
9282 return false;
9283
9284 if (Val.isVector()) {
9285 SmallVector<uint32_t, 4> Indices;
9286 E->getEncodedElementAccess(Indices);
9287 if (Indices.size() == 1) {
9288 // Return scalar.
9289 return DerivedSuccess(Val.getVectorElt(Indices[0]), E);
9290 } else {
9291 // Construct new APValue vector.
9292 SmallVector<APValue, 4> Elts;
9293 for (unsigned I = 0; I < Indices.size(); ++I) {
9294 Elts.push_back(Val.getVectorElt(Indices[I]));
9295 }
9296 APValue VecResult(Elts.data(), Indices.size());
9297 return DerivedSuccess(VecResult, E);
9298 }
9299 }
9300
9301 return false;
9302 }
9303
9304 bool VisitCastExpr(const CastExpr *E) {
9305 switch (E->getCastKind()) {
9306 default:
9307 break;
9308
9309 case CK_AtomicToNonAtomic: {
9310 APValue AtomicVal;
9311 // This does not need to be done in place even for class/array types:
9312 // atomic-to-non-atomic conversion implies copying the object
9313 // representation.
9314 if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
9315 return false;
9316 return DerivedSuccess(AtomicVal, E);
9317 }
9318
9319 case CK_NoOp:
9320 case CK_UserDefinedConversion:
9321 return StmtVisitorTy::Visit(E->getSubExpr());
9322
9323 case CK_HLSLArrayRValue: {
9324 const Expr *SubExpr = E->getSubExpr();
9325 if (!SubExpr->isGLValue()) {
9326 APValue Val;
9327 if (!Evaluate(Val, Info, SubExpr))
9328 return false;
9329 return DerivedSuccess(Val, E);
9330 }
9331
9332 LValue LVal;
9333 if (!EvaluateLValue(SubExpr, LVal, Info))
9334 return false;
9335 APValue RVal;
9336 // Note, we use the subexpression's type in order to retain cv-qualifiers.
9337 if (!handleLValueToRValueConversion(Info, E, SubExpr->getType(), LVal,
9338 RVal))
9339 return false;
9340 return DerivedSuccess(RVal, E);
9341 }
9342 case CK_LValueToRValue: {
9343 LValue LVal;
9344 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
9345 return false;
9346 APValue RVal;
9347 // Note, we use the subexpression's type in order to retain cv-qualifiers.
9349 LVal, RVal))
9350 return false;
9351 return DerivedSuccess(RVal, E);
9352 }
9353 case CK_LValueToRValueBitCast: {
9354 APValue DestValue, SourceValue;
9355 if (!Evaluate(SourceValue, Info, E->getSubExpr()))
9356 return false;
9357 if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
9358 return false;
9359 return DerivedSuccess(DestValue, E);
9360 }
9361
9362 case CK_AddressSpaceConversion: {
9363 APValue Value;
9364 if (!Evaluate(Value, Info, E->getSubExpr()))
9365 return false;
9366 return DerivedSuccess(Value, E);
9367 }
9368 }
9369
9370 return Error(E);
9371 }
9372
9373 bool VisitUnaryPostInc(const UnaryOperator *UO) {
9374 return VisitUnaryPostIncDec(UO);
9375 }
9376 bool VisitUnaryPostDec(const UnaryOperator *UO) {
9377 return VisitUnaryPostIncDec(UO);
9378 }
9379 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
9380 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9381 return Error(UO);
9382
9383 LValue LVal;
9384 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
9385 return false;
9386 APValue RVal;
9387 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
9388 UO->isIncrementOp(), &RVal))
9389 return false;
9390 return DerivedSuccess(RVal, UO);
9391 }
9392
9393 bool VisitStmtExpr(const StmtExpr *E) {
9394 // We will have checked the full-expressions inside the statement expression
9395 // when they were completed, and don't need to check them again now.
9396 llvm::SaveAndRestore NotCheckingForUB(Info.CheckingForUndefinedBehavior,
9397 false);
9398
9399 const CompoundStmt *CS = E->getSubStmt();
9400 if (CS->body_empty())
9401 return true;
9402
9403 BlockScopeRAII Scope(Info);
9405 BE = CS->body_end();
9406 /**/; ++BI) {
9407 if (BI + 1 == BE) {
9408 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
9409 if (!FinalExpr) {
9410 Info.FFDiag((*BI)->getBeginLoc(),
9411 diag::note_constexpr_stmt_expr_unsupported);
9412 return false;
9413 }
9414 return this->Visit(FinalExpr) && Scope.destroy();
9415 }
9416
9418 StmtResult Result = { ReturnValue, nullptr };
9419 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
9420 if (ESR != ESR_Succeeded) {
9421 // FIXME: If the statement-expression terminated due to 'return',
9422 // 'break', or 'continue', it would be nice to propagate that to
9423 // the outer statement evaluation rather than bailing out.
9424 if (ESR != ESR_Failed)
9425 Info.FFDiag((*BI)->getBeginLoc(),
9426 diag::note_constexpr_stmt_expr_unsupported);
9427 return false;
9428 }
9429 }
9430
9431 llvm_unreachable("Return from function from the loop above.");
9432 }
9433
9434 bool VisitPackIndexingExpr(const PackIndexingExpr *E) {
9435 return StmtVisitorTy::Visit(E->getSelectedExpr());
9436 }
9437
9438 /// Visit a value which is evaluated, but whose value is ignored.
9439 void VisitIgnoredValue(const Expr *E) {
9440 EvaluateIgnoredValue(Info, E);
9441 }
9442
9443 /// Potentially visit a MemberExpr's base expression.
9444 void VisitIgnoredBaseExpression(const Expr *E) {
9445 // While MSVC doesn't evaluate the base expression, it does diagnose the
9446 // presence of side-effecting behavior.
9447 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
9448 return;
9449 VisitIgnoredValue(E);
9450 }
9451};
9452
9453} // namespace
9454
9455//===----------------------------------------------------------------------===//
9456// Common base class for lvalue and temporary evaluation.
9457//===----------------------------------------------------------------------===//
9458namespace {
9459template<class Derived>
9460class LValueExprEvaluatorBase
9461 : public ExprEvaluatorBase<Derived> {
9462protected:
9463 LValue &Result;
9464 bool InvalidBaseOK;
9465 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
9466 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
9467
9468 bool Success(APValue::LValueBase B) {
9469 Result.set(B);
9470 return true;
9471 }
9472
9473 bool evaluatePointer(const Expr *E, LValue &Result) {
9474 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
9475 }
9476
9477public:
9478 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
9479 : ExprEvaluatorBaseTy(Info), Result(Result),
9480 InvalidBaseOK(InvalidBaseOK) {}
9481
9482 bool Success(const APValue &V, const Expr *E) {
9483 Result.setFrom(this->Info.Ctx, V);
9484 return true;
9485 }
9486
9487 bool VisitMemberExpr(const MemberExpr *E) {
9488 // Handle non-static data members.
9489 QualType BaseTy;
9490 bool EvalOK;
9491 if (E->isArrow()) {
9492 EvalOK = evaluatePointer(E->getBase(), Result);
9493 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
9494 } else if (E->getBase()->isPRValue()) {
9495 assert(E->getBase()->getType()->isRecordType());
9496 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
9497 BaseTy = E->getBase()->getType();
9498 } else {
9499 EvalOK = this->Visit(E->getBase());
9500 BaseTy = E->getBase()->getType();
9501 }
9502 if (!EvalOK) {
9503 if (!InvalidBaseOK)
9504 return false;
9505 Result.setInvalid(E);
9506 return true;
9507 }
9508
9509 const ValueDecl *MD = E->getMemberDecl();
9510 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
9511 assert(BaseTy->castAsCanonical<RecordType>()->getDecl() ==
9512 FD->getParent()->getCanonicalDecl() &&
9513 "record / field mismatch");
9514 (void)BaseTy;
9515 if (!HandleLValueMember(this->Info, E, Result, FD))
9516 return false;
9517 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
9518 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
9519 return false;
9520 } else
9521 return this->Error(E);
9522
9523 if (MD->getType()->isReferenceType()) {
9524 APValue RefValue;
9525 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
9526 RefValue))
9527 return false;
9528 return Success(RefValue, E);
9529 }
9530 return true;
9531 }
9532
9533 bool VisitBinaryOperator(const BinaryOperator *E) {
9534 switch (E->getOpcode()) {
9535 default:
9536 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9537
9538 case BO_PtrMemD:
9539 case BO_PtrMemI:
9540 return HandleMemberPointerAccess(this->Info, E, Result);
9541 }
9542 }
9543
9544 bool VisitCastExpr(const CastExpr *E) {
9545 switch (E->getCastKind()) {
9546 default:
9547 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9548
9549 case CK_DerivedToBase:
9550 case CK_UncheckedDerivedToBase:
9551 if (!this->Visit(E->getSubExpr()))
9552 return false;
9553
9554 // Now figure out the necessary offset to add to the base LV to get from
9555 // the derived class to the base class.
9556 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
9557 Result);
9558 }
9559 }
9560};
9561}
9562
9563//===----------------------------------------------------------------------===//
9564// LValue Evaluation
9565//
9566// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
9567// function designators (in C), decl references to void objects (in C), and
9568// temporaries (if building with -Wno-address-of-temporary).
9569//
9570// LValue evaluation produces values comprising a base expression of one of the
9571// following types:
9572// - Declarations
9573// * VarDecl
9574// * FunctionDecl
9575// - Literals
9576// * CompoundLiteralExpr in C (and in global scope in C++)
9577// * StringLiteral
9578// * PredefinedExpr
9579// * ObjCStringLiteralExpr
9580// * ObjCEncodeExpr
9581// * AddrLabelExpr
9582// * BlockExpr
9583// * CallExpr for a MakeStringConstant builtin
9584// - typeid(T) expressions, as TypeInfoLValues
9585// - Locals and temporaries
9586// * MaterializeTemporaryExpr
9587// * Any Expr, with a CallIndex indicating the function in which the temporary
9588// was evaluated, for cases where the MaterializeTemporaryExpr is missing
9589// from the AST (FIXME).
9590// * A MaterializeTemporaryExpr that has static storage duration, with no
9591// CallIndex, for a lifetime-extended temporary.
9592// * The ConstantExpr that is currently being evaluated during evaluation of an
9593// immediate invocation.
9594// plus an offset in bytes.
9595//===----------------------------------------------------------------------===//
9596namespace {
9597class LValueExprEvaluator
9598 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
9599public:
9600 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
9601 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
9602
9603 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
9604 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
9605
9606 bool VisitCallExpr(const CallExpr *E);
9607 bool VisitDeclRefExpr(const DeclRefExpr *E);
9608 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
9609 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
9610 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
9611 bool VisitMemberExpr(const MemberExpr *E);
9612 bool VisitStringLiteral(const StringLiteral *E) {
9613 return Success(
9614 APValue::LValueBase(E, 0, Info.Ctx.getNextStringLiteralVersion()));
9615 }
9616 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
9617 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
9618 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
9619 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
9620 bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E);
9621 bool VisitUnaryDeref(const UnaryOperator *E);
9622 bool VisitUnaryReal(const UnaryOperator *E);
9623 bool VisitUnaryImag(const UnaryOperator *E);
9624 bool VisitUnaryPreInc(const UnaryOperator *UO) {
9625 return VisitUnaryPreIncDec(UO);
9626 }
9627 bool VisitUnaryPreDec(const UnaryOperator *UO) {
9628 return VisitUnaryPreIncDec(UO);
9629 }
9630 bool VisitBinAssign(const BinaryOperator *BO);
9631 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
9632
9633 bool VisitCastExpr(const CastExpr *E) {
9634 switch (E->getCastKind()) {
9635 default:
9636 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
9637
9638 case CK_LValueBitCast:
9639 this->CCEDiag(E, diag::note_constexpr_invalid_cast)
9640 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
9641 << Info.Ctx.getLangOpts().CPlusPlus << E->getSourceRange();
9642 if (!Visit(E->getSubExpr()))
9643 return false;
9644 Result.Designator.setInvalid();
9645 return true;
9646
9647 case CK_BaseToDerived:
9648 if (!Visit(E->getSubExpr()))
9649 return false;
9650 return HandleBaseToDerivedCast(Info, E, Result);
9651
9652 case CK_Dynamic:
9653 if (!Visit(E->getSubExpr()))
9654 return false;
9656 }
9657 }
9658};
9659} // end anonymous namespace
9660
9661/// Get an lvalue to a field of a lambda's closure type.
9662static bool HandleLambdaCapture(EvalInfo &Info, const Expr *E, LValue &Result,
9663 const CXXMethodDecl *MD, const FieldDecl *FD,
9664 bool LValueToRValueConversion) {
9665 // Static lambda function call operators can't have captures. We already
9666 // diagnosed this, so bail out here.
9667 if (MD->isStatic()) {
9668 assert(Info.CurrentCall->This == nullptr &&
9669 "This should not be set for a static call operator");
9670 return false;
9671 }
9672
9673 // Start with 'Result' referring to the complete closure object...
9675 // Self may be passed by reference or by value.
9676 const ParmVarDecl *Self = MD->getParamDecl(0);
9677 if (Self->getType()->isReferenceType()) {
9678 APValue *RefValue = Info.getParamSlot(Info.CurrentCall->Arguments, Self);
9679 if (!RefValue->allowConstexprUnknown() || RefValue->hasValue())
9680 Result.setFrom(Info.Ctx, *RefValue);
9681 } else {
9682 const ParmVarDecl *VD = Info.CurrentCall->Arguments.getOrigParam(Self);
9683 CallStackFrame *Frame =
9684 Info.getCallFrameAndDepth(Info.CurrentCall->Arguments.CallIndex)
9685 .first;
9686 unsigned Version = Info.CurrentCall->Arguments.Version;
9687 Result.set({VD, Frame->Index, Version});
9688 }
9689 } else
9690 Result = *Info.CurrentCall->This;
9691
9692 // ... then update it to refer to the field of the closure object
9693 // that represents the capture.
9694 if (!HandleLValueMember(Info, E, Result, FD))
9695 return false;
9696
9697 // And if the field is of reference type (or if we captured '*this' by
9698 // reference), update 'Result' to refer to what
9699 // the field refers to.
9700 if (LValueToRValueConversion) {
9701 APValue RVal;
9702 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result, RVal))
9703 return false;
9704 Result.setFrom(Info.Ctx, RVal);
9705 }
9706 return true;
9707}
9708
9709/// Evaluate an expression as an lvalue. This can be legitimately called on
9710/// expressions which are not glvalues, in three cases:
9711/// * function designators in C, and
9712/// * "extern void" objects
9713/// * @selector() expressions in Objective-C
9714static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
9715 bool InvalidBaseOK) {
9716 assert(!E->isValueDependent());
9717 assert(E->isGLValue() || E->getType()->isFunctionType() ||
9719 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
9720}
9721
9722bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
9723 const ValueDecl *D = E->getDecl();
9724
9725 // If we are within a lambda's call operator, check whether the 'VD' referred
9726 // to within 'E' actually represents a lambda-capture that maps to a
9727 // data-member/field within the closure object, and if so, evaluate to the
9728 // field or what the field refers to.
9729 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
9731 // We don't always have a complete capture-map when checking or inferring if
9732 // the function call operator meets the requirements of a constexpr function
9733 // - but we don't need to evaluate the captures to determine constexprness
9734 // (dcl.constexpr C++17).
9735 if (Info.checkingPotentialConstantExpression())
9736 return false;
9737
9738 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(D)) {
9739 const auto *MD = cast<CXXMethodDecl>(Info.CurrentCall->Callee);
9740 return HandleLambdaCapture(Info, E, Result, MD, FD,
9741 FD->getType()->isReferenceType());
9742 }
9743 }
9744
9745 if (isa<FunctionDecl, MSGuidDecl, TemplateParamObjectDecl,
9746 UnnamedGlobalConstantDecl>(D))
9747 return Success(cast<ValueDecl>(D));
9748 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
9749 return VisitVarDecl(E, VD);
9750 if (const BindingDecl *BD = dyn_cast<BindingDecl>(D))
9751 return Visit(BD->getBinding());
9752 return Error(E);
9753}
9754
9755bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
9756 CallStackFrame *Frame = nullptr;
9757 unsigned Version = 0;
9758 if (VD->hasLocalStorage()) {
9759 // Only if a local variable was declared in the function currently being
9760 // evaluated, do we expect to be able to find its value in the current
9761 // frame. (Otherwise it was likely declared in an enclosing context and
9762 // could either have a valid evaluatable value (for e.g. a constexpr
9763 // variable) or be ill-formed (and trigger an appropriate evaluation
9764 // diagnostic)).
9765 CallStackFrame *CurrFrame = Info.CurrentCall;
9766 if (CurrFrame->Callee && CurrFrame->Callee->Equals(VD->getDeclContext())) {
9767 // Function parameters are stored in some caller's frame. (Usually the
9768 // immediate caller, but for an inherited constructor they may be more
9769 // distant.)
9770 if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) {
9771 if (CurrFrame->Arguments) {
9772 VD = CurrFrame->Arguments.getOrigParam(PVD);
9773 Frame =
9774 Info.getCallFrameAndDepth(CurrFrame->Arguments.CallIndex).first;
9775 Version = CurrFrame->Arguments.Version;
9776 }
9777 } else {
9778 Frame = CurrFrame;
9779 Version = CurrFrame->getCurrentTemporaryVersion(VD);
9780 }
9781 }
9782 }
9783
9784 if (!VD->getType()->isReferenceType()) {
9785 if (Frame) {
9786 Result.set({VD, Frame->Index, Version});
9787 return true;
9788 }
9789 return Success(VD);
9790 }
9791
9792 if (!Info.getLangOpts().CPlusPlus11) {
9793 Info.CCEDiag(E, diag::note_constexpr_ltor_non_integral, 1)
9794 << VD << VD->getType();
9795 Info.Note(VD->getLocation(), diag::note_declared_at);
9796 }
9797
9798 APValue *V;
9799 if (!evaluateVarDeclInit(Info, E, VD, Frame, Version, V))
9800 return false;
9801
9802 if (!V) {
9803 Result.set(VD);
9804 Result.AllowConstexprUnknown = true;
9805 return true;
9806 }
9807
9808 return Success(*V, E);
9809}
9810
9811bool LValueExprEvaluator::VisitCallExpr(const CallExpr *E) {
9812 if (!IsConstantEvaluatedBuiltinCall(E))
9813 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9814
9815 switch (E->getBuiltinCallee()) {
9816 default:
9817 return false;
9818 case Builtin::BIas_const:
9819 case Builtin::BIforward:
9820 case Builtin::BIforward_like:
9821 case Builtin::BImove:
9822 case Builtin::BImove_if_noexcept:
9823 if (cast<FunctionDecl>(E->getCalleeDecl())->isConstexpr())
9824 return Visit(E->getArg(0));
9825 break;
9826 }
9827
9828 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9829}
9830
9831bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
9832 const MaterializeTemporaryExpr *E) {
9833 // Walk through the expression to find the materialized temporary itself.
9836 const Expr *Inner =
9837 E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
9838
9839 // If we passed any comma operators, evaluate their LHSs.
9840 for (const Expr *E : CommaLHSs)
9841 if (!EvaluateIgnoredValue(Info, E))
9842 return false;
9843
9844 // A materialized temporary with static storage duration can appear within the
9845 // result of a constant expression evaluation, so we need to preserve its
9846 // value for use outside this evaluation.
9847 APValue *Value;
9848 if (E->getStorageDuration() == SD_Static) {
9849 if (Info.EvalMode == EvaluationMode::ConstantFold)
9850 return false;
9851 // FIXME: What about SD_Thread?
9852 Value = E->getOrCreateValue(true);
9853 *Value = APValue();
9854 Result.set(E);
9855 } else {
9856 Value = &Info.CurrentCall->createTemporary(
9857 E, Inner->getType(),
9858 E->getStorageDuration() == SD_FullExpression ? ScopeKind::FullExpression
9859 : ScopeKind::Block,
9860 Result);
9861 }
9862
9863 QualType Type = Inner->getType();
9864
9865 // Materialize the temporary itself.
9866 if (!EvaluateInPlace(*Value, Info, Result, Inner)) {
9867 *Value = APValue();
9868 return false;
9869 }
9870
9871 // Adjust our lvalue to refer to the desired subobject.
9872 for (unsigned I = Adjustments.size(); I != 0; /**/) {
9873 --I;
9874 switch (Adjustments[I].Kind) {
9876 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
9877 Type, Result))
9878 return false;
9879 Type = Adjustments[I].DerivedToBase.BasePath->getType();
9880 break;
9881
9883 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
9884 return false;
9885 Type = Adjustments[I].Field->getType();
9886 break;
9887
9889 if (!HandleMemberPointerAccess(this->Info, Type, Result,
9890 Adjustments[I].Ptr.RHS))
9891 return false;
9892 Type = Adjustments[I].Ptr.MPT->getPointeeType();
9893 break;
9894 }
9895 }
9896
9897 return true;
9898}
9899
9900bool
9901LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
9902 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
9903 "lvalue compound literal in c++?");
9904 APValue *Lit;
9905 // If CompountLiteral has static storage, its value can be used outside
9906 // this expression. So evaluate it once and store it in ASTContext.
9907 if (E->hasStaticStorage()) {
9908 Lit = &E->getOrCreateStaticValue(Info.Ctx);
9909 Result.set(E);
9910 // Reset any previously evaluated state, otherwise evaluation below might
9911 // fail.
9912 // FIXME: Should we just re-use the previously evaluated value instead?
9913 *Lit = APValue();
9914 } else {
9915 assert(!Info.getLangOpts().CPlusPlus);
9916 Lit = &Info.CurrentCall->createTemporary(E, E->getInitializer()->getType(),
9917 ScopeKind::Block, Result);
9918 }
9919 // FIXME: Evaluating in place isn't always right. We should figure out how to
9920 // use appropriate evaluation context here, see
9921 // clang/test/AST/static-compound-literals-reeval.cpp for a failure.
9922 if (!EvaluateInPlace(*Lit, Info, Result, E->getInitializer())) {
9923 *Lit = APValue();
9924 return false;
9925 }
9926 return true;
9927}
9928
9929bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
9930 TypeInfoLValue TypeInfo;
9931
9932 if (!E->isPotentiallyEvaluated()) {
9933 if (E->isTypeOperand())
9934 TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
9935 else
9936 TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
9937 } else {
9938 if (!Info.Ctx.getLangOpts().CPlusPlus20) {
9939 Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
9940 << E->getExprOperand()->getType()
9941 << E->getExprOperand()->getSourceRange();
9942 }
9943
9944 if (!Visit(E->getExprOperand()))
9945 return false;
9946
9947 std::optional<DynamicType> DynType =
9949 if (!DynType)
9950 return false;
9951
9952 TypeInfo = TypeInfoLValue(
9953 Info.Ctx.getCanonicalTagType(DynType->Type).getTypePtr());
9954 }
9955
9956 return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
9957}
9958
9959bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
9960 return Success(E->getGuidDecl());
9961}
9962
9963bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
9964 // Handle static data members.
9965 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
9966 VisitIgnoredBaseExpression(E->getBase());
9967 return VisitVarDecl(E, VD);
9968 }
9969
9970 // Handle static member functions.
9971 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
9972 if (MD->isStatic()) {
9973 VisitIgnoredBaseExpression(E->getBase());
9974 return Success(MD);
9975 }
9976 }
9977
9978 // Handle non-static data members.
9979 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
9980}
9981
9982bool LValueExprEvaluator::VisitExtVectorElementExpr(
9983 const ExtVectorElementExpr *E) {
9984 bool Success = true;
9985
9986 APValue Val;
9987 if (!Evaluate(Val, Info, E->getBase())) {
9988 if (!Info.noteFailure())
9989 return false;
9990 Success = false;
9991 }
9992
9994 E->getEncodedElementAccess(Indices);
9995 // FIXME: support accessing more than one element
9996 if (Indices.size() > 1)
9997 return false;
9998
9999 if (Success) {
10000 Result.setFrom(Info.Ctx, Val);
10001 QualType BaseType = E->getBase()->getType();
10002 if (E->isArrow())
10003 BaseType = BaseType->getPointeeType();
10004 const auto *VT = BaseType->castAs<VectorType>();
10005 HandleLValueVectorElement(Info, E, Result, VT->getElementType(),
10006 VT->getNumElements(), Indices[0]);
10007 }
10008
10009 return Success;
10010}
10011
10012bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
10013 if (E->getBase()->getType()->isSveVLSBuiltinType())
10014 return Error(E);
10015
10016 APSInt Index;
10017 bool Success = true;
10018
10019 if (const auto *VT = E->getBase()->getType()->getAs<VectorType>()) {
10020 APValue Val;
10021 if (!Evaluate(Val, Info, E->getBase())) {
10022 if (!Info.noteFailure())
10023 return false;
10024 Success = false;
10025 }
10026
10027 if (!EvaluateInteger(E->getIdx(), Index, Info)) {
10028 if (!Info.noteFailure())
10029 return false;
10030 Success = false;
10031 }
10032
10033 if (Success) {
10034 Result.setFrom(Info.Ctx, Val);
10035 HandleLValueVectorElement(Info, E, Result, VT->getElementType(),
10036 VT->getNumElements(), Index.getZExtValue());
10037 }
10038
10039 return Success;
10040 }
10041
10042 // C++17's rules require us to evaluate the LHS first, regardless of which
10043 // side is the base.
10044 for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) {
10045 if (SubExpr == E->getBase() ? !evaluatePointer(SubExpr, Result)
10046 : !EvaluateInteger(SubExpr, Index, Info)) {
10047 if (!Info.noteFailure())
10048 return false;
10049 Success = false;
10050 }
10051 }
10052
10053 return Success &&
10054 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
10055}
10056
10057bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
10058 bool Success = evaluatePointer(E->getSubExpr(), Result);
10059 // [C++26][expr.unary.op]
10060 // If the operand points to an object or function, the result
10061 // denotes that object or function; otherwise, the behavior is undefined.
10062 // Because &(*(type*)0) is a common pattern, we do not fail the evaluation
10063 // immediately.
10065 return Success;
10067 E->getType())) ||
10068 Info.noteUndefinedBehavior();
10069}
10070
10071bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
10072 if (!Visit(E->getSubExpr()))
10073 return false;
10074 // __real is a no-op on scalar lvalues.
10075 if (E->getSubExpr()->getType()->isAnyComplexType())
10076 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
10077 return true;
10078}
10079
10080bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
10081 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
10082 "lvalue __imag__ on scalar?");
10083 if (!Visit(E->getSubExpr()))
10084 return false;
10085 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
10086 return true;
10087}
10088
10089bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
10090 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
10091 return Error(UO);
10092
10093 if (!this->Visit(UO->getSubExpr()))
10094 return false;
10095
10096 return handleIncDec(
10097 this->Info, UO, Result, UO->getSubExpr()->getType(),
10098 UO->isIncrementOp(), nullptr);
10099}
10100
10101bool LValueExprEvaluator::VisitCompoundAssignOperator(
10102 const CompoundAssignOperator *CAO) {
10103 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
10104 return Error(CAO);
10105
10106 bool Success = true;
10107
10108 // C++17 onwards require that we evaluate the RHS first.
10109 APValue RHS;
10110 if (!Evaluate(RHS, this->Info, CAO->getRHS())) {
10111 if (!Info.noteFailure())
10112 return false;
10113 Success = false;
10114 }
10115
10116 // The overall lvalue result is the result of evaluating the LHS.
10117 if (!this->Visit(CAO->getLHS()) || !Success)
10118 return false;
10119
10121 this->Info, CAO,
10122 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
10123 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
10124}
10125
10126bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
10127 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
10128 return Error(E);
10129
10130 bool Success = true;
10131
10132 // C++17 onwards require that we evaluate the RHS first.
10133 APValue NewVal;
10134 if (!Evaluate(NewVal, this->Info, E->getRHS())) {
10135 if (!Info.noteFailure())
10136 return false;
10137 Success = false;
10138 }
10139
10140 if (!this->Visit(E->getLHS()) || !Success)
10141 return false;
10142
10143 if (Info.getLangOpts().CPlusPlus20 &&
10145 return false;
10146
10147 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
10148 NewVal);
10149}
10150
10151//===----------------------------------------------------------------------===//
10152// Pointer Evaluation
10153//===----------------------------------------------------------------------===//
10154
10155/// Convenience function. LVal's base must be a call to an alloc_size
10156/// function.
10158 const LValue &LVal,
10159 llvm::APInt &Result) {
10160 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
10161 "Can't get the size of a non alloc_size function");
10162 const auto *Base = LVal.getLValueBase().get<const Expr *>();
10163 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
10164 std::optional<llvm::APInt> Size =
10165 CE->evaluateBytesReturnedByAllocSizeCall(Ctx);
10166 if (!Size)
10167 return false;
10168
10169 Result = std::move(*Size);
10170 return true;
10171}
10172
10173/// Attempts to evaluate the given LValueBase as the result of a call to
10174/// a function with the alloc_size attribute. If it was possible to do so, this
10175/// function will return true, make Result's Base point to said function call,
10176/// and mark Result's Base as invalid.
10178 LValue &Result) {
10179 if (Base.isNull())
10180 return false;
10181
10182 // Because we do no form of static analysis, we only support const variables.
10183 //
10184 // Additionally, we can't support parameters, nor can we support static
10185 // variables (in the latter case, use-before-assign isn't UB; in the former,
10186 // we have no clue what they'll be assigned to).
10187 const auto *VD =
10188 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
10189 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
10190 return false;
10191
10192 const Expr *Init = VD->getAnyInitializer();
10193 if (!Init || Init->getType().isNull())
10194 return false;
10195
10196 const Expr *E = Init->IgnoreParens();
10197 if (!tryUnwrapAllocSizeCall(E))
10198 return false;
10199
10200 // Store E instead of E unwrapped so that the type of the LValue's base is
10201 // what the user wanted.
10202 Result.setInvalid(E);
10203
10204 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
10205 Result.addUnsizedArray(Info, E, Pointee);
10206 return true;
10207}
10208
10209namespace {
10210class PointerExprEvaluator
10211 : public ExprEvaluatorBase<PointerExprEvaluator> {
10212 LValue &Result;
10213 bool InvalidBaseOK;
10214
10215 bool Success(const Expr *E) {
10216 Result.set(E);
10217 return true;
10218 }
10219
10220 bool evaluateLValue(const Expr *E, LValue &Result) {
10221 return EvaluateLValue(E, Result, Info, InvalidBaseOK);
10222 }
10223
10224 bool evaluatePointer(const Expr *E, LValue &Result) {
10225 return EvaluatePointer(E, Result, Info, InvalidBaseOK);
10226 }
10227
10228 bool visitNonBuiltinCallExpr(const CallExpr *E);
10229public:
10230
10231 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
10232 : ExprEvaluatorBaseTy(info), Result(Result),
10233 InvalidBaseOK(InvalidBaseOK) {}
10234
10235 bool Success(const APValue &V, const Expr *E) {
10236 Result.setFrom(Info.Ctx, V);
10237 return true;
10238 }
10239 bool ZeroInitialization(const Expr *E) {
10240 Result.setNull(Info.Ctx, E->getType());
10241 return true;
10242 }
10243
10244 bool VisitBinaryOperator(const BinaryOperator *E);
10245 bool VisitCastExpr(const CastExpr* E);
10246 bool VisitUnaryAddrOf(const UnaryOperator *E);
10247 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
10248 { return Success(E); }
10249 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
10251 return Success(E);
10252 if (Info.noteFailure())
10253 EvaluateIgnoredValue(Info, E->getSubExpr());
10254 return Error(E);
10255 }
10256 bool VisitObjCArrayLiteral(const ObjCArrayLiteral *E) {
10257 return E->isExpressibleAsConstantInitializer() ? Success(E) : Error(E);
10258 }
10259 bool VisitObjCDictionaryLiteral(const ObjCDictionaryLiteral *E) {
10260 return E->isExpressibleAsConstantInitializer() ? Success(E) : Error(E);
10261 }
10262 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
10263 { return Success(E); }
10264 bool VisitCallExpr(const CallExpr *E);
10265 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
10266 bool VisitBlockExpr(const BlockExpr *E) {
10267 if (!E->getBlockDecl()->hasCaptures())
10268 return Success(E);
10269 return Error(E);
10270 }
10271 bool VisitCXXThisExpr(const CXXThisExpr *E) {
10272 auto DiagnoseInvalidUseOfThis = [&] {
10273 if (Info.getLangOpts().CPlusPlus11)
10274 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
10275 else
10276 Info.FFDiag(E);
10277 };
10278
10279 // Can't look at 'this' when checking a potential constant expression.
10280 if (Info.checkingPotentialConstantExpression())
10281 return false;
10282
10283 bool IsExplicitLambda =
10284 isLambdaCallWithExplicitObjectParameter(Info.CurrentCall->Callee);
10285 if (!IsExplicitLambda) {
10286 if (!Info.CurrentCall->This) {
10287 DiagnoseInvalidUseOfThis();
10288 return false;
10289 }
10290
10291 Result = *Info.CurrentCall->This;
10292 }
10293
10294 if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
10295 // Ensure we actually have captured 'this'. If something was wrong with
10296 // 'this' capture, the error would have been previously reported.
10297 // Otherwise we can be inside of a default initialization of an object
10298 // declared by lambda's body, so no need to return false.
10299 if (!Info.CurrentCall->LambdaThisCaptureField) {
10300 if (IsExplicitLambda && !Info.CurrentCall->This) {
10301 DiagnoseInvalidUseOfThis();
10302 return false;
10303 }
10304
10305 return true;
10306 }
10307
10308 const auto *MD = cast<CXXMethodDecl>(Info.CurrentCall->Callee);
10309 return HandleLambdaCapture(
10310 Info, E, Result, MD, Info.CurrentCall->LambdaThisCaptureField,
10311 Info.CurrentCall->LambdaThisCaptureField->getType()->isPointerType());
10312 }
10313 return true;
10314 }
10315
10316 bool VisitCXXNewExpr(const CXXNewExpr *E);
10317
10318 bool VisitSourceLocExpr(const SourceLocExpr *E) {
10319 assert(!E->isIntType() && "SourceLocExpr isn't a pointer type?");
10320 APValue LValResult = E->EvaluateInContext(
10321 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
10322 Result.setFrom(Info.Ctx, LValResult);
10323 return true;
10324 }
10325
10326 bool VisitEmbedExpr(const EmbedExpr *E) {
10327 llvm::report_fatal_error("Not yet implemented for ExprConstant.cpp");
10328 return true;
10329 }
10330
10331 bool VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr *E) {
10332 std::string ResultStr = E->ComputeName(Info.Ctx);
10333
10334 QualType CharTy = Info.Ctx.CharTy.withConst();
10335 APInt Size(Info.Ctx.getTypeSize(Info.Ctx.getSizeType()),
10336 ResultStr.size() + 1);
10337 QualType ArrayTy = Info.Ctx.getConstantArrayType(
10338 CharTy, Size, nullptr, ArraySizeModifier::Normal, 0);
10339
10340 StringLiteral *SL =
10341 StringLiteral::Create(Info.Ctx, ResultStr, StringLiteralKind::Ordinary,
10342 /*Pascal*/ false, ArrayTy, E->getLocation());
10343
10344 evaluateLValue(SL, Result);
10345 Result.addArray(Info, E, cast<ConstantArrayType>(ArrayTy));
10346 return true;
10347 }
10348
10349 // FIXME: Missing: @protocol, @selector
10350};
10351} // end anonymous namespace
10352
10353static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
10354 bool InvalidBaseOK) {
10355 assert(!E->isValueDependent());
10356 assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
10357 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
10358}
10359
10360bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
10361 if (E->getOpcode() != BO_Add &&
10362 E->getOpcode() != BO_Sub)
10363 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10364
10365 const Expr *PExp = E->getLHS();
10366 const Expr *IExp = E->getRHS();
10367 if (IExp->getType()->isPointerType())
10368 std::swap(PExp, IExp);
10369
10370 bool EvalPtrOK = evaluatePointer(PExp, Result);
10371 if (!EvalPtrOK && !Info.noteFailure())
10372 return false;
10373
10374 llvm::APSInt Offset;
10375 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
10376 return false;
10377
10378 if (E->getOpcode() == BO_Sub)
10379 negateAsSigned(Offset);
10380
10381 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
10382 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
10383}
10384
10385bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
10386 // [C11 6.5.3.2p3]: if the operand of '&' is the result of a unary '*'
10387 // operator, neither operator is evaluated and the result is as if both were
10388 // omitted (except that the operators' constraints, already enforced by Sema,
10389 // still apply, and the result is not an lvalue). So '&*p' is just the pointer
10390 // value 'p' with no dereference, and forming it is therefore not undefined
10391 // behavior even when 'p' is null, e.g. '&*(int *)0'. Evaluate the pointer
10392 // operand directly so we don't spuriously diagnose a null dereference.
10393 if (!Info.getLangOpts().CPlusPlus) {
10394 const Expr *Sub = E->getSubExpr()->IgnoreParens();
10395 if (const auto *Deref = dyn_cast<UnaryOperator>(Sub);
10396 Deref && Deref->getOpcode() == UO_Deref)
10397 return evaluatePointer(Deref->getSubExpr(), Result);
10398 }
10399 return evaluateLValue(E->getSubExpr(), Result);
10400}
10401
10402// Is the provided decl 'std::source_location::current'?
10404 if (!FD)
10405 return false;
10406 const IdentifierInfo *FnII = FD->getIdentifier();
10407 if (!FnII || !FnII->isStr("current"))
10408 return false;
10409
10410 const auto *RD = dyn_cast<RecordDecl>(FD->getParent());
10411 if (!RD)
10412 return false;
10413
10414 const IdentifierInfo *ClassII = RD->getIdentifier();
10415 return RD->isInStdNamespace() && ClassII && ClassII->isStr("source_location");
10416}
10417
10418bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
10419 const Expr *SubExpr = E->getSubExpr();
10420
10421 switch (E->getCastKind()) {
10422 default:
10423 break;
10424 case CK_BitCast:
10425 case CK_CPointerToObjCPointerCast:
10426 case CK_BlockPointerToObjCPointerCast:
10427 case CK_AnyPointerToBlockPointerCast:
10428 case CK_AddressSpaceConversion:
10429 if (!Visit(SubExpr))
10430 return false;
10431 if (E->getType()->isFunctionPointerType() ||
10432 SubExpr->getType()->isFunctionPointerType()) {
10433 // Casting between two function pointer types, or between a function
10434 // pointer and an object pointer, is always a reinterpret_cast.
10435 CCEDiag(E, diag::note_constexpr_invalid_cast)
10436 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
10437 << Info.Ctx.getLangOpts().CPlusPlus;
10438 Result.Designator.setInvalid();
10439 } else if (!E->getType()->isVoidPointerType()) {
10440 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
10441 // permitted in constant expressions in C++11. Bitcasts from cv void* are
10442 // also static_casts, but we disallow them as a resolution to DR1312.
10443 //
10444 // In some circumstances, we permit casting from void* to cv1 T*, when the
10445 // actual pointee object is actually a cv2 T.
10446 bool HasValidResult = !Result.InvalidBase && !Result.Designator.Invalid &&
10447 !Result.IsNullPtr;
10448 bool VoidPtrCastMaybeOK =
10449 Result.IsNullPtr ||
10450 (HasValidResult &&
10451 Info.Ctx.hasSimilarType(Result.Designator.getType(Info.Ctx),
10452 E->getType()->getPointeeType()));
10453 // 1. We'll allow it in std::allocator::allocate, and anything which that
10454 // calls.
10455 // 2. HACK 2022-03-28: Work around an issue with libstdc++'s
10456 // <source_location> header. Fixed in GCC 12 and later (2022-04-??).
10457 // We'll allow it in the body of std::source_location::current. GCC's
10458 // implementation had a parameter of type `void*`, and casts from
10459 // that back to `const __impl*` in its body.
10460 if (VoidPtrCastMaybeOK &&
10461 (Info.getStdAllocatorCaller("allocate") ||
10462 IsDeclSourceLocationCurrent(Info.CurrentCall->Callee) ||
10463 Info.getLangOpts().CPlusPlus26)) {
10464 // Permitted.
10465 } else {
10466 if (SubExpr->getType()->isVoidPointerType() &&
10467 Info.getLangOpts().CPlusPlus) {
10468 if (HasValidResult)
10469 CCEDiag(E, diag::note_constexpr_invalid_void_star_cast)
10470 << SubExpr->getType() << Info.getLangOpts().CPlusPlus26
10471 << Result.Designator.getType(Info.Ctx).getCanonicalType()
10472 << E->getType()->getPointeeType();
10473 else
10474 CCEDiag(E, diag::note_constexpr_invalid_cast)
10475 << diag::ConstexprInvalidCastKind::CastFrom
10476 << SubExpr->getType();
10477 } else
10478 CCEDiag(E, diag::note_constexpr_invalid_cast)
10479 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
10480 << Info.Ctx.getLangOpts().CPlusPlus;
10481 Result.Designator.setInvalid();
10482 }
10483 }
10484 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
10485 ZeroInitialization(E);
10486 return true;
10487
10488 case CK_DerivedToBase:
10489 case CK_UncheckedDerivedToBase:
10490 if (!evaluatePointer(E->getSubExpr(), Result))
10491 return false;
10492 if (!Result.Base && Result.Offset.isZero())
10493 return true;
10494
10495 // Now figure out the necessary offset to add to the base LV to get from
10496 // the derived class to the base class.
10497 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
10498 castAs<PointerType>()->getPointeeType(),
10499 Result);
10500
10501 case CK_BaseToDerived:
10502 if (!Visit(E->getSubExpr()))
10503 return false;
10504 if (!Result.Base && Result.Offset.isZero())
10505 return true;
10506 return HandleBaseToDerivedCast(Info, E, Result);
10507
10508 case CK_Dynamic:
10509 if (!Visit(E->getSubExpr()))
10510 return false;
10512
10513 case CK_NullToPointer:
10514 VisitIgnoredValue(E->getSubExpr());
10515 return ZeroInitialization(E);
10516
10517 case CK_IntegralToPointer: {
10518 CCEDiag(E, diag::note_constexpr_invalid_cast)
10519 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
10520 << Info.Ctx.getLangOpts().CPlusPlus;
10521
10522 APValue Value;
10523 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
10524 break;
10525
10526 if (Value.isInt()) {
10527 unsigned Size = Info.Ctx.getTypeSize(E->getType());
10528 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
10529 if (N == Info.Ctx.getTargetNullPointerValue(E->getType())) {
10530 Result.setNull(Info.Ctx, E->getType());
10531 } else {
10532 Result.Base = (Expr *)nullptr;
10533 Result.InvalidBase = false;
10534 Result.Offset = CharUnits::fromQuantity(N);
10535 Result.Designator.setInvalid();
10536 Result.IsNullPtr = false;
10537 }
10538 return true;
10539 } else {
10540 // In rare instances, the value isn't an lvalue.
10541 // For example, when the value is the difference between the addresses of
10542 // two labels. We reject that as a constant expression because we can't
10543 // compute a valid offset to convert into a pointer.
10544 if (!Value.isLValue())
10545 return false;
10546
10547 // Cast is of an lvalue, no need to change value.
10548 Result.setFrom(Info.Ctx, Value);
10549 return true;
10550 }
10551 }
10552
10553 case CK_ArrayToPointerDecay: {
10554 if (SubExpr->isGLValue()) {
10555 if (!evaluateLValue(SubExpr, Result))
10556 return false;
10557 } else {
10558 APValue &Value = Info.CurrentCall->createTemporary(
10559 SubExpr, SubExpr->getType(), ScopeKind::FullExpression, Result);
10560 if (!EvaluateInPlace(Value, Info, Result, SubExpr))
10561 return false;
10562 }
10563 // The result is a pointer to the first element of the array.
10564 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
10565 if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
10566 Result.addArray(Info, E, CAT);
10567 else
10568 Result.addUnsizedArray(Info, E, AT->getElementType());
10569 return true;
10570 }
10571
10572 case CK_FunctionToPointerDecay:
10573 return evaluateLValue(SubExpr, Result);
10574
10575 case CK_LValueToRValue: {
10576 LValue LVal;
10577 if (!evaluateLValue(E->getSubExpr(), LVal))
10578 return false;
10579
10580 APValue RVal;
10581 // Note, we use the subexpression's type in order to retain cv-qualifiers.
10583 LVal, RVal))
10584 return InvalidBaseOK &&
10585 evaluateLValueAsAllocSize(Info, LVal.Base, Result);
10586 return Success(RVal, E);
10587 }
10588 }
10589
10590 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10591}
10592
10594 UnaryExprOrTypeTrait ExprKind) {
10595 // C++ [expr.alignof]p3:
10596 // When alignof is applied to a reference type, the result is the
10597 // alignment of the referenced type.
10598 T = T.getNonReferenceType();
10599
10600 if (T.getQualifiers().hasUnaligned())
10601 return CharUnits::One();
10602
10603 const bool AlignOfReturnsPreferred =
10604 Ctx.getLangOpts().isCompatibleWith(LangOptions::ClangABI::Ver7);
10605
10606 // __alignof is defined to return the preferred alignment.
10607 // Before 8, clang returned the preferred alignment for alignof and _Alignof
10608 // as well.
10609 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
10610 return Ctx.toCharUnitsFromBits(Ctx.getPreferredTypeAlign(T.getTypePtr()));
10611 // alignof and _Alignof are defined to return the ABI alignment.
10612 else if (ExprKind == UETT_AlignOf)
10613 return Ctx.getTypeAlignInChars(T.getTypePtr());
10614 else
10615 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
10616}
10617
10618// Convert a builtin ID to the canonical x86 builtin ID the constant evaluators
10619// dispatch on in their x86 target-specific cases, or 0 if \p BuiltinOp is a
10620// target builtin those cases should not handle.
10621//
10622// Target-independent builtins are returned unchanged. Target builtin IDs of
10623// different targets overlap (each target numbers its builtins from
10624// Builtin::FirstTSBuiltin), so a target builtin ID is only meaningful for the
10625// target that owns it. Determine the owning target (translating an auxiliary ID
10626// back to its canonical value) and only return the ID when x86 owns it;
10627// otherwise an overlapping ID could be misinterpreted as an unrelated x86
10628// builtin.
10630 unsigned BuiltinOp) {
10631 // Target-independent builtins have the same ID regardless of the target, so
10632 // they can be dispatched as-is. This is the common case and is intentionally
10633 // kept to a single comparison so callers can use this on hot paths (e.g. the
10634 // bytecode interpreter's builtin dispatch) without re-deriving the ID from
10635 // the call expression.
10636 if (BuiltinOp < Builtin::FirstTSBuiltin)
10637 return BuiltinOp;
10638
10639 // Determine the target that owns this builtin, translating an auxiliary ID
10640 // back to its canonical value.
10641 const TargetInfo *OwningTarget;
10642 if (Ctx.BuiltinInfo.isAuxBuiltinID(BuiltinOp)) {
10643 OwningTarget = Ctx.getAuxTargetInfo();
10644 BuiltinOp = Ctx.BuiltinInfo.getAuxBuiltinID(BuiltinOp);
10645 } else {
10646 OwningTarget = &Ctx.getTargetInfo();
10647 }
10648
10649 if (!OwningTarget)
10650 return 0;
10651
10652 // x86 and x86_64 share a single builtin set and are the only architectures
10653 // whose target-specific builtins the constant evaluators currently fold.
10654 switch (OwningTarget->getTriple().getArch()) {
10655 case llvm::Triple::x86:
10656 case llvm::Triple::x86_64:
10657 return BuiltinOp;
10658 default:
10659 return 0;
10660 }
10661}
10662
10664 const CallExpr *E) {
10666}
10667
10669 UnaryExprOrTypeTrait ExprKind) {
10670 E = E->IgnoreParens();
10671
10672 // The kinds of expressions that we have special-case logic here for
10673 // should be kept up to date with the special checks for those
10674 // expressions in Sema.
10675
10676 // alignof decl is always accepted, even if it doesn't make sense: we default
10677 // to 1 in those cases.
10678 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
10679 return Ctx.getDeclAlign(DRE->getDecl(),
10680 /*ForAlignOf=*/true);
10681
10682 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
10683 return Ctx.getDeclAlign(ME->getMemberDecl(),
10684 /*ForAlignOf=*/true);
10685
10686 return GetAlignOfType(Ctx, E->getType(), ExprKind);
10687}
10688
10689static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) {
10690 if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>())
10691 return Info.Ctx.getDeclAlign(VD);
10692 if (const auto *E = Value.Base.dyn_cast<const Expr *>())
10693 return GetAlignOfExpr(Info.Ctx, E, UETT_AlignOf);
10694 if (const auto &DA = Value.Base.dyn_cast<DynamicAllocLValue>())
10695 return GetAlignOfDynamicAlloc(Info.getASTContext(), Value.Base.getType(),
10696 DA.getAllocKind());
10697 return GetAlignOfType(Info.Ctx, Value.Base.getTypeInfoType(), UETT_AlignOf);
10698}
10699
10700/// Evaluate the value of the alignment argument to __builtin_align_{up,down},
10701/// __builtin_is_aligned and __builtin_assume_aligned.
10702static bool getAlignmentArgument(const Expr *E, QualType ForType,
10703 EvalInfo &Info, APSInt &Alignment) {
10704 if (!EvaluateInteger(E, Alignment, Info))
10705 return false;
10706 if (Alignment < 0 || !Alignment.isPowerOf2()) {
10707 Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment;
10708 return false;
10709 }
10710 unsigned SrcWidth = Info.Ctx.getIntWidth(ForType);
10711 APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1));
10712 if (APSInt::compareValues(Alignment, MaxValue) > 0) {
10713 Info.FFDiag(E, diag::note_constexpr_alignment_too_big)
10714 << MaxValue << ForType << Alignment;
10715 return false;
10716 }
10717 // Ensure both alignment and source value have the same bit width so that we
10718 // don't assert when computing the resulting value.
10719 APSInt ExtAlignment =
10720 APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true);
10721 assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 &&
10722 "Alignment should not be changed by ext/trunc");
10723 Alignment = ExtAlignment;
10724 assert(Alignment.getBitWidth() == SrcWidth);
10725 return true;
10726}
10727
10728// To be clear: this happily visits unsupported builtins. Better name welcomed.
10729bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
10730 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
10731 return true;
10732
10733 if (!(InvalidBaseOK && E->getCalleeAllocSizeAttr()))
10734 return false;
10735
10736 Result.setInvalid(E);
10737 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
10738 Result.addUnsizedArray(Info, E, PointeeTy);
10739 return true;
10740}
10741
10742bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
10743 if (!IsConstantEvaluatedBuiltinCall(E))
10744 return visitNonBuiltinCallExpr(E);
10745 return VisitBuiltinCallExpr(E, ConvertBuiltinIDToX86BuiltinID(Info.Ctx, E));
10746}
10747
10748// Determine if T is a character type for which we guarantee that
10749// sizeof(T) == 1.
10751 return T->isCharType() || T->isChar8Type();
10752}
10753
10754bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
10755 unsigned BuiltinOp) {
10756 if (isOpaqueConstantCall(E))
10757 return Success(E);
10758
10759 switch (BuiltinOp) {
10760 case Builtin::BIaddressof:
10761 case Builtin::BI__addressof:
10762 case Builtin::BI__builtin_addressof:
10763 return evaluateLValue(E->getArg(0), Result);
10764 case Builtin::BI__builtin_assume_aligned: {
10765 // We need to be very careful here because: if the pointer does not have the
10766 // asserted alignment, then the behavior is undefined, and undefined
10767 // behavior is non-constant.
10768 if (!evaluatePointer(E->getArg(0), Result))
10769 return false;
10770
10771 LValue OffsetResult(Result);
10772 APSInt Alignment;
10773 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
10774 Alignment))
10775 return false;
10776 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
10777
10778 if (E->getNumArgs() > 2) {
10779 APSInt Offset;
10780 if (!EvaluateInteger(E->getArg(2), Offset, Info))
10781 return false;
10782
10783 int64_t AdditionalOffset = -Offset.getZExtValue();
10784 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
10785 }
10786
10787 // If there is a base object, then it must have the correct alignment.
10788 if (OffsetResult.Base) {
10789 CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult);
10790
10791 if (BaseAlignment < Align) {
10792 Result.Designator.setInvalid();
10793 CCEDiag(E->getArg(0), diag::note_constexpr_baa_insufficient_alignment)
10794 << 0 << BaseAlignment.getQuantity() << Align.getQuantity();
10795 return false;
10796 }
10797 }
10798
10799 // The offset must also have the correct alignment.
10800 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
10801 Result.Designator.setInvalid();
10802
10803 (OffsetResult.Base
10804 ? CCEDiag(E->getArg(0),
10805 diag::note_constexpr_baa_insufficient_alignment)
10806 << 1
10807 : CCEDiag(E->getArg(0),
10808 diag::note_constexpr_baa_value_insufficient_alignment))
10809 << OffsetResult.Offset.getQuantity() << Align.getQuantity();
10810 return false;
10811 }
10812
10813 return true;
10814 }
10815 case Builtin::BI__builtin_align_up:
10816 case Builtin::BI__builtin_align_down: {
10817 if (!evaluatePointer(E->getArg(0), Result))
10818 return false;
10819 APSInt Alignment;
10820 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
10821 Alignment))
10822 return false;
10823
10824 if (!Result.Base) {
10825 // Null pointers are always aligned and align_up/align_down preserve null.
10826 if (Result.Offset.isZero())
10827 return true;
10828
10829 // Non-null pointers without a base (for example, integer-to-pointer
10830 // casts such as (void *)32) do not have enough information to perform
10831 // pointer arithmetic during constant evaluation.
10832 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust)
10833 << Alignment;
10834 return false;
10835 }
10836
10837 CharUnits BaseAlignment = getBaseAlignment(Info, Result);
10838 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset);
10839 // For align_up/align_down, we can return the same value if the alignment
10840 // is known to be greater or equal to the requested value.
10841 if (PtrAlign.getQuantity() >= Alignment)
10842 return true;
10843
10844 // The alignment could be greater than the minimum at run-time, so we cannot
10845 // infer much about the resulting pointer value. One case is possible:
10846 // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we
10847 // can infer the correct index if the requested alignment is smaller than
10848 // the base alignment so we can perform the computation on the offset.
10849 if (BaseAlignment.getQuantity() >= Alignment) {
10850 assert(Alignment.getBitWidth() <= 64 &&
10851 "Cannot handle > 64-bit address-space");
10852 uint64_t Alignment64 = Alignment.getZExtValue();
10853 CharUnits NewOffset = CharUnits::fromQuantity(
10854 BuiltinOp == Builtin::BI__builtin_align_down
10855 ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64)
10856 : llvm::alignTo(Result.Offset.getQuantity(), Alignment64));
10857 Result.adjustOffset(NewOffset - Result.Offset);
10858 // TODO: diagnose out-of-bounds values/only allow for arrays?
10859 return true;
10860 }
10861 // Otherwise, we cannot constant-evaluate the result.
10862 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust)
10863 << Alignment;
10864 return false;
10865 }
10866 case Builtin::BI__builtin_operator_new:
10867 return HandleOperatorNewCall(Info, E, Result);
10868 case Builtin::BI__builtin_launder:
10869 return evaluatePointer(E->getArg(0), Result);
10870 case Builtin::BIstrchr:
10871 case Builtin::BIwcschr:
10872 case Builtin::BImemchr:
10873 case Builtin::BIwmemchr:
10874 if (Info.getLangOpts().CPlusPlus11)
10875 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
10876 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
10877 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
10878 else
10879 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
10880 [[fallthrough]];
10881 case Builtin::BI__builtin_strchr:
10882 case Builtin::BI__builtin_wcschr:
10883 case Builtin::BI__builtin_memchr:
10884 case Builtin::BI__builtin_char_memchr:
10885 case Builtin::BI__builtin_wmemchr: {
10886 if (!Visit(E->getArg(0)))
10887 return false;
10888 APSInt Desired;
10889 if (!EvaluateInteger(E->getArg(1), Desired, Info))
10890 return false;
10891 uint64_t MaxLength = uint64_t(-1);
10892 if (BuiltinOp != Builtin::BIstrchr &&
10893 BuiltinOp != Builtin::BIwcschr &&
10894 BuiltinOp != Builtin::BI__builtin_strchr &&
10895 BuiltinOp != Builtin::BI__builtin_wcschr) {
10896 APSInt N;
10897 if (!EvaluateInteger(E->getArg(2), N, Info))
10898 return false;
10899 MaxLength = N.getZExtValue();
10900 }
10901 // We cannot find the value if there are no candidates to match against.
10902 if (MaxLength == 0u)
10903 return ZeroInitialization(E);
10904 if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
10905 Result.Designator.Invalid)
10906 return false;
10907 QualType CharTy = Result.Designator.getType(Info.Ctx);
10908 bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
10909 BuiltinOp == Builtin::BI__builtin_memchr;
10910 assert(IsRawByte ||
10911 Info.Ctx.hasSameUnqualifiedType(
10912 CharTy, E->getArg(0)->getType()->getPointeeType()));
10913 // Pointers to const void may point to objects of incomplete type.
10914 if (IsRawByte && CharTy->isIncompleteType()) {
10915 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
10916 return false;
10917 }
10918 // Give up on byte-oriented matching against multibyte elements.
10919 // FIXME: We can compare the bytes in the correct order.
10920 if (IsRawByte && !isOneByteCharacterType(CharTy)) {
10921 Info.FFDiag(E, diag::note_constexpr_memchr_unsupported)
10922 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp) << CharTy;
10923 return false;
10924 }
10925 // Figure out what value we're actually looking for (after converting to
10926 // the corresponding unsigned type if necessary).
10927 uint64_t DesiredVal;
10928 bool StopAtNull = false;
10929 switch (BuiltinOp) {
10930 case Builtin::BIstrchr:
10931 case Builtin::BI__builtin_strchr:
10932 StopAtNull = true;
10933 [[fallthrough]];
10934 case Builtin::BImemchr:
10935 case Builtin::BI__builtin_memchr:
10936 case Builtin::BI__builtin_char_memchr:
10937 // memchr compares by converting both sides to unsigned char. That's also
10938 // correct for strchr if we get this far (to cope with plain char being
10939 // unsigned in the strchr case).
10940 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
10941 break;
10942
10943 case Builtin::BIwcschr:
10944 case Builtin::BI__builtin_wcschr:
10945 StopAtNull = true;
10946 [[fallthrough]];
10947 case Builtin::BIwmemchr:
10948 case Builtin::BI__builtin_wmemchr:
10949 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
10950 DesiredVal = Desired.getZExtValue();
10951 break;
10952 }
10953
10954 for (; MaxLength; --MaxLength) {
10955 APValue Char;
10956 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
10957 !Char.isInt())
10958 return false;
10959 if (Char.getInt().getZExtValue() == DesiredVal)
10960 return true;
10961 if (StopAtNull && !Char.getInt())
10962 break;
10963 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
10964 return false;
10965 }
10966 // Not found: return nullptr.
10967 return ZeroInitialization(E);
10968 }
10969
10970 case Builtin::BImemcpy:
10971 case Builtin::BImemmove:
10972 case Builtin::BIwmemcpy:
10973 case Builtin::BIwmemmove:
10974 if (Info.getLangOpts().CPlusPlus11)
10975 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
10976 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
10977 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
10978 else
10979 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
10980 [[fallthrough]];
10981 case Builtin::BI__builtin_memcpy:
10982 case Builtin::BI__builtin_memmove:
10983 case Builtin::BI__builtin_wmemcpy:
10984 case Builtin::BI__builtin_wmemmove: {
10985 bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
10986 BuiltinOp == Builtin::BIwmemmove ||
10987 BuiltinOp == Builtin::BI__builtin_wmemcpy ||
10988 BuiltinOp == Builtin::BI__builtin_wmemmove;
10989 bool Move = BuiltinOp == Builtin::BImemmove ||
10990 BuiltinOp == Builtin::BIwmemmove ||
10991 BuiltinOp == Builtin::BI__builtin_memmove ||
10992 BuiltinOp == Builtin::BI__builtin_wmemmove;
10993
10994 // The result of mem* is the first argument.
10995 if (!Visit(E->getArg(0)))
10996 return false;
10997 LValue Dest = Result;
10998
10999 LValue Src;
11000 if (!EvaluatePointer(E->getArg(1), Src, Info))
11001 return false;
11002
11003 APSInt N;
11004 if (!EvaluateInteger(E->getArg(2), N, Info))
11005 return false;
11006 assert(!N.isSigned() && "memcpy and friends take an unsigned size");
11007
11008 // If the size is zero, we treat this as always being a valid no-op.
11009 // (Even if one of the src and dest pointers is null.)
11010 if (!N)
11011 return true;
11012
11013 // Otherwise, if either of the operands is null, we can't proceed. Don't
11014 // try to determine the type of the copied objects, because there aren't
11015 // any.
11016 if (!Src.Base || !Dest.Base) {
11017 APValue Val;
11018 (!Src.Base ? Src : Dest).moveInto(Val);
11019 Info.FFDiag(E, diag::note_constexpr_memcpy_null)
11020 << Move << WChar << !!Src.Base
11021 << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
11022 return false;
11023 }
11024 if (Src.Designator.Invalid || Dest.Designator.Invalid)
11025 return false;
11026
11027 // We require that Src and Dest are both pointers to arrays of
11028 // trivially-copyable type. (For the wide version, the designator will be
11029 // invalid if the designated object is not a wchar_t.)
11030 QualType T = Dest.Designator.getType(Info.Ctx);
11031 QualType SrcT = Src.Designator.getType(Info.Ctx);
11032 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
11033 // FIXME: Consider using our bit_cast implementation to support this.
11034 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
11035 return false;
11036 }
11037 if (T->isIncompleteType()) {
11038 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
11039 return false;
11040 }
11041 if (!T.isTriviallyCopyableType(Info.Ctx)) {
11042 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
11043 return false;
11044 }
11045
11046 // Figure out how many T's we're copying.
11047 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
11048 if (TSize == 0)
11049 return false;
11050 if (!WChar) {
11051 uint64_t Remainder;
11052 llvm::APInt OrigN = N;
11053 llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
11054 if (Remainder) {
11055 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
11056 << Move << WChar << 0 << T << toString(OrigN, 10, /*Signed*/false)
11057 << (unsigned)TSize;
11058 return false;
11059 }
11060 }
11061
11062 // Check that the copying will remain within the arrays, just so that we
11063 // can give a more meaningful diagnostic. This implicitly also checks that
11064 // N fits into 64 bits.
11065 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
11066 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
11067 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
11068 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
11069 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
11070 << toString(N, 10, /*Signed*/false);
11071 return false;
11072 }
11073 uint64_t NElems = N.getZExtValue();
11074 uint64_t NBytes = NElems * TSize;
11075
11076 // Check for overlap.
11077 int Direction = 1;
11078 if (HasSameBase(Src, Dest)) {
11079 uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
11080 uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
11081 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
11082 // Dest is inside the source region.
11083 if (!Move) {
11084 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
11085 return false;
11086 }
11087 // For memmove and friends, copy backwards.
11088 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
11089 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
11090 return false;
11091 Direction = -1;
11092 } else if (!Move && SrcOffset >= DestOffset &&
11093 SrcOffset - DestOffset < NBytes) {
11094 // Src is inside the destination region for memcpy: invalid.
11095 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
11096 return false;
11097 }
11098 }
11099
11100 while (true) {
11101 APValue Val;
11102 // FIXME: Set WantObjectRepresentation to true if we're copying a
11103 // char-like type?
11104 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
11105 !handleAssignment(Info, E, Dest, T, Val))
11106 return false;
11107 // Do not iterate past the last element; if we're copying backwards, that
11108 // might take us off the start of the array.
11109 if (--NElems == 0)
11110 return true;
11111 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
11112 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
11113 return false;
11114 }
11115 }
11116
11117 default:
11118 return false;
11119 }
11120}
11121
11122static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
11123 APValue &Result, const InitListExpr *ILE,
11124 QualType AllocType);
11125static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
11126 APValue &Result,
11127 const CXXConstructExpr *CCE,
11128 QualType AllocType);
11129
11130bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) {
11131 if (!Info.getLangOpts().CPlusPlus20)
11132 Info.CCEDiag(E, diag::note_constexpr_new);
11133
11134 // We cannot speculatively evaluate a delete expression.
11135 if (Info.SpeculativeEvaluationDepth)
11136 return false;
11137
11138 FunctionDecl *OperatorNew = E->getOperatorNew();
11139 QualType AllocType = E->getAllocatedType();
11140 QualType TargetType = AllocType;
11141
11142 bool IsNothrow = false;
11143 bool IsPlacement = false;
11144
11145 // The only new-placement list we support (other than the reserved placement
11146 // form) is of the form (std::nothrow).
11147 //
11148 // FIXME: There is no restriction on this, but it's not clear that any
11149 // other form makes any sense. We get here for cases such as:
11150 //
11151 // new (std::align_val_t{N}) X(int)
11152 //
11153 // (which should presumably be valid only if N is a multiple of
11154 // alignof(int), and in any case can't be deallocated unless N is
11155 // alignof(X) and X has new-extended alignment).
11156 bool HasNothrowArg = E->getNumPlacementArgs() == 1 &&
11158
11159 if (OperatorNew->isReservedGlobalPlacementOperator()) {
11160 if (Info.CurrentCall->isStdFunction() || Info.getLangOpts().CPlusPlus26 ||
11161 (Info.CurrentCall->CanEvalMSConstexpr &&
11162 OperatorNew->hasAttr<MSConstexprAttr>())) {
11163 if (!EvaluatePointer(E->getPlacementArg(0), Result, Info))
11164 return false;
11165 if (Result.Designator.Invalid)
11166 return false;
11167 TargetType = E->getPlacementArg(0)->getType();
11168 IsPlacement = true;
11169 } else {
11170 Info.FFDiag(E, diag::note_constexpr_new_placement)
11171 << /*C++26 feature*/ 1 << E->getSourceRange();
11172 return false;
11173 }
11174 } else if (E->getNumPlacementArgs() && !HasNothrowArg) {
11175 Info.FFDiag(E, diag::note_constexpr_new_placement)
11176 << /*Unsupported*/ 0 << E->getSourceRange();
11177 return false;
11178 } else if (!OperatorNew
11179 ->isUsableAsGlobalAllocationFunctionInConstantEvaluation()) {
11180 // [expr.const] only permits new-expressions that select a replaceable
11181 // global allocation function. Check this before evaluating a
11182 // (std::nothrow) placement argument.
11183 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
11184 << isa<CXXMethodDecl>(OperatorNew) << OperatorNew;
11185 return false;
11186 } else if (HasNothrowArg) {
11187 LValue Nothrow;
11188 if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info))
11189 return false;
11190 IsNothrow = true;
11191 }
11192
11193 const Expr *Init = E->getInitializer();
11194 const InitListExpr *ResizedArrayILE = nullptr;
11195 const CXXConstructExpr *ResizedArrayCCE = nullptr;
11196 bool ValueInit = false;
11197
11198 if (std::optional<const Expr *> ArraySize = E->getArraySize()) {
11199 const Expr *Stripped = *ArraySize;
11200 for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
11201 Stripped = ICE->getSubExpr())
11202 if (ICE->getCastKind() != CK_NoOp &&
11203 ICE->getCastKind() != CK_IntegralCast)
11204 break;
11205
11206 llvm::APSInt ArrayBound;
11207 if (!EvaluateInteger(Stripped, ArrayBound, Info))
11208 return false;
11209
11210 // C++ [expr.new]p9:
11211 // The expression is erroneous if:
11212 // -- [...] its value before converting to size_t [or] applying the
11213 // second standard conversion sequence is less than zero
11214 if (ArrayBound.isSigned() && ArrayBound.isNegative()) {
11215 if (IsNothrow)
11216 return ZeroInitialization(E);
11217
11218 Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative)
11219 << ArrayBound << (*ArraySize)->getSourceRange();
11220 return false;
11221 }
11222
11223 // -- its value is such that the size of the allocated object would
11224 // exceed the implementation-defined limit
11225 if (!Info.CheckArraySize(ArraySize.value()->getExprLoc(),
11227 Info.Ctx, AllocType, ArrayBound),
11228 ArrayBound.getZExtValue(), /*Diag=*/!IsNothrow)) {
11229 if (IsNothrow)
11230 return ZeroInitialization(E);
11231 return false;
11232 }
11233
11234 // -- the new-initializer is a braced-init-list and the number of
11235 // array elements for which initializers are provided [...]
11236 // exceeds the number of elements to initialize
11237 if (!Init) {
11238 // No initialization is performed.
11239 } else if (isa<CXXScalarValueInitExpr>(Init) ||
11241 ValueInit = true;
11242 } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) {
11243 ResizedArrayCCE = CCE;
11244 } else {
11245 auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType());
11246 assert(CAT && "unexpected type for array initializer");
11247
11248 unsigned Bits =
11249 std::max(CAT->getSizeBitWidth(), ArrayBound.getBitWidth());
11250 llvm::APInt InitBound = CAT->getSize().zext(Bits);
11251 llvm::APInt AllocBound = ArrayBound.zext(Bits);
11252 if (InitBound.ugt(AllocBound)) {
11253 if (IsNothrow)
11254 return ZeroInitialization(E);
11255
11256 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small)
11257 << toString(AllocBound, 10, /*Signed=*/false)
11258 << toString(InitBound, 10, /*Signed=*/false)
11259 << (*ArraySize)->getSourceRange();
11260 return false;
11261 }
11262
11263 // If the sizes differ, we must have an initializer list, and we need
11264 // special handling for this case when we initialize.
11265 if (InitBound != AllocBound)
11266 ResizedArrayILE = cast<InitListExpr>(Init);
11267 }
11268
11269 AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr,
11270 ArraySizeModifier::Normal, 0);
11271 } else if (E->isArray()) {
11272 // We have an array new-expression whose array size could not be
11273 // determined, e.g. 'new int[]()', where the bound is neither given nor
11274 // deducible from the initializer. This is ill-formed and already
11275 // diagnosed, so bail out rather than mis-evaluating a scalar allocation
11276 // as an array (which would later crash the evaluator).
11277 return false;
11278 } else {
11279 assert(!AllocType->isArrayType() &&
11280 "array allocation with non-array new");
11281 }
11282
11283 APValue *Val;
11284 if (IsPlacement) {
11286 struct FindObjectHandler {
11287 EvalInfo &Info;
11288 const Expr *E;
11289 QualType AllocType;
11290 const AccessKinds AccessKind;
11291 APValue *Value;
11292
11293 typedef bool result_type;
11294 bool failed() { return false; }
11295 bool checkConst(QualType QT) {
11296 if (QT.isConstQualified()) {
11297 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
11298 return false;
11299 }
11300 return true;
11301 }
11302 bool found(APValue &Subobj, QualType SubobjType,
11303 APValue::LValueBase Base) {
11304 if (!checkConst(SubobjType))
11305 return false;
11306 // FIXME: Reject the cases where [basic.life]p8 would not permit the
11307 // old name of the object to be used to name the new object.
11308 if (!Info.Ctx.hasSimilarType(SubobjType, AllocType)) {
11309 Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type)
11310 << SubobjType << AllocType;
11311 return false;
11312 }
11313 Value = &Subobj;
11314 return true;
11315 }
11316 bool found(APSInt &Value, QualType SubobjType) {
11317 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
11318 return false;
11319 }
11320 bool found(APFloat &Value, QualType SubobjType) {
11321 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
11322 return false;
11323 }
11324 } Handler = {Info, E, AllocType, AK, nullptr};
11325
11326 if (AllocType->isArrayType() &&
11327 Result.Designator.MostDerivedIsArrayElement &&
11328 Result.Designator.Entries.back().getAsArrayIndex() == 0) {
11329 // The destination of placement new is pointing to the first element
11330 // of an array. There's a special case in [expr.const]: "[...] if T is an
11331 // array type, to the first element of such an object [...]". Handle
11332 // that case here by dropping the last entry in the designator list.
11333 QualType AllocElementType =
11334 Info.Ctx.getAsArrayType(AllocType)->getElementType();
11335 if (Info.Ctx.hasSimilarType(AllocElementType,
11336 Result.Designator.MostDerivedType)) {
11337 Result.Designator.truncate(Info.Ctx, Result.Base,
11338 Result.Designator.MostDerivedPathLength - 1);
11339 }
11340 }
11341
11342 CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType);
11343 if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler))
11344 return false;
11345
11346 Val = Handler.Value;
11347
11348 // [basic.life]p1:
11349 // The lifetime of an object o of type T ends when [...] the storage
11350 // which the object occupies is [...] reused by an object that is not
11351 // nested within o (6.6.2).
11352 *Val = APValue();
11353 } else {
11354 // Perform the allocation and obtain a pointer to the resulting object.
11355 Val = Info.createHeapAlloc(E, AllocType, Result);
11356 if (!Val)
11357 return false;
11358 }
11359
11360 if (ValueInit) {
11361 ImplicitValueInitExpr VIE(AllocType);
11362 if (!EvaluateInPlace(*Val, Info, Result, &VIE))
11363 return false;
11364 } else if (ResizedArrayILE) {
11365 if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE,
11366 AllocType))
11367 return false;
11368 } else if (ResizedArrayCCE) {
11369 if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE,
11370 AllocType))
11371 return false;
11372 } else if (Init) {
11373 if (!EvaluateInPlace(*Val, Info, Result, Init))
11374 return false;
11375 } else if (!handleDefaultInitValue(AllocType, *Val)) {
11376 return false;
11377 }
11378
11379 // Array new returns a pointer to the first element, not a pointer to the
11380 // array.
11381 if (auto *AT = AllocType->getAsArrayTypeUnsafe())
11382 Result.addArray(Info, E, cast<ConstantArrayType>(AT));
11383
11384 return true;
11385}
11386
11387//===----------------------------------------------------------------------===//
11388// Reflection expression evaluation
11389//===----------------------------------------------------------------------===//
11390
11391namespace {
11392class ReflectionEvaluator : public ExprEvaluatorBase<ReflectionEvaluator> {
11393
11394 using BaseType = ExprEvaluatorBase<ReflectionEvaluator>;
11395
11396 APValue &Result;
11397
11398public:
11399 ReflectionEvaluator(EvalInfo &E, APValue &Result)
11400 : ExprEvaluatorBaseTy(E), Result(Result) {}
11401
11402 bool Success(const APValue &V, const Expr *E) {
11403 Result = V;
11404 return true;
11405 }
11406
11407 bool VisitCXXReflectExpr(const CXXReflectExpr *E);
11408 bool ZeroInitialization(const Expr *E);
11409};
11410
11411bool ReflectionEvaluator::VisitCXXReflectExpr(const CXXReflectExpr *E) {
11412 switch (E->getKind()) {
11413 case ReflectionKind::Null: {
11414 assert(false && "null reflection can't be constructed from parsing a "
11415 "reflection operand");
11416 return false;
11417 }
11418 case ReflectionKind::Type: {
11419 APValue ReflectionValue(ReflectionKind::Type, E->getOpaqueValue());
11420 return Success(ReflectionValue, E);
11421 }
11422 }
11423 assert(false && "unknown or unimplemented reflection entities");
11424 return false;
11425}
11426
11427bool ReflectionEvaluator::ZeroInitialization(const Expr *E) {
11428 Result = APValue(ReflectionKind::Null, /*Operand=*/nullptr);
11429 return true;
11430}
11431
11432} // end anonymous namespace
11433
11434static bool EvaluateReflection(const Expr *E, APValue &Result, EvalInfo &Info) {
11435 assert(E->isPRValue() && E->getType()->isMetaInfoType());
11436 return ReflectionEvaluator(Info, Result).Visit(E);
11437}
11438
11439static bool EvaluateReflectionMetafunctionBuiltin(EvalInfo &Info,
11440 const CallExpr *E,
11441 unsigned BuiltinOp,
11442 APValue &Result) {
11443 switch (BuiltinOp) {
11444 case Builtin::BI__builtin_meta_is_type: {
11445 APValue Reflection;
11446 if (!EvaluateReflection(E->getArg(0), Reflection, Info))
11447 return false;
11448 Result = APValue(Info.Ctx.MakeIntValue(
11450 E->getType()));
11451 return true;
11452 }
11453 default:
11454 llvm_unreachable("unknown metafunction builtin");
11455 }
11456}
11457
11458//===----------------------------------------------------------------------===//
11459// Member Pointer Evaluation
11460//===----------------------------------------------------------------------===//
11461
11462namespace {
11463class MemberPointerExprEvaluator
11464 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
11465 MemberPtr &Result;
11466
11467 bool Success(const ValueDecl *D) {
11468 Result = MemberPtr(D);
11469 return true;
11470 }
11471public:
11472
11473 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
11474 : ExprEvaluatorBaseTy(Info), Result(Result) {}
11475
11476 bool Success(const APValue &V, const Expr *E) {
11477 Result.setFrom(V);
11478 return true;
11479 }
11480 bool ZeroInitialization(const Expr *E) {
11481 return Success((const ValueDecl*)nullptr);
11482 }
11483
11484 bool VisitCastExpr(const CastExpr *E);
11485 bool VisitUnaryAddrOf(const UnaryOperator *E);
11486};
11487} // end anonymous namespace
11488
11489static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
11490 EvalInfo &Info) {
11491 assert(!E->isValueDependent());
11492 assert(E->isPRValue() && E->getType()->isMemberPointerType());
11493 return MemberPointerExprEvaluator(Info, Result).Visit(E);
11494}
11495
11496bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
11497 switch (E->getCastKind()) {
11498 default:
11499 return ExprEvaluatorBaseTy::VisitCastExpr(E);
11500
11501 case CK_NullToMemberPointer:
11502 VisitIgnoredValue(E->getSubExpr());
11503 return ZeroInitialization(E);
11504
11505 case CK_BaseToDerivedMemberPointer: {
11506 if (!Visit(E->getSubExpr()))
11507 return false;
11508 if (E->path_empty())
11509 return true;
11510 // Base-to-derived member pointer casts store the path in derived-to-base
11511 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
11512 // the wrong end of the derived->base arc, so stagger the path by one class.
11513 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
11514 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
11515 PathI != PathE; ++PathI) {
11516 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
11517 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
11518 if (!Result.castToDerived(Derived))
11519 return Error(E);
11520 }
11521 if (!Result.castToDerived(E->getType()
11522 ->castAs<MemberPointerType>()
11523 ->getMostRecentCXXRecordDecl()))
11524 return Error(E);
11525 return true;
11526 }
11527
11528 case CK_DerivedToBaseMemberPointer:
11529 if (!Visit(E->getSubExpr()))
11530 return false;
11531 for (CastExpr::path_const_iterator PathI = E->path_begin(),
11532 PathE = E->path_end(); PathI != PathE; ++PathI) {
11533 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
11534 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
11535 if (!Result.castToBase(Base))
11536 return Error(E);
11537 }
11538 return true;
11539 }
11540}
11541
11542bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
11543 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
11544 // member can be formed.
11545 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
11546}
11547
11548//===----------------------------------------------------------------------===//
11549// Record Evaluation
11550//===----------------------------------------------------------------------===//
11551
11552namespace {
11553 class RecordExprEvaluator
11554 : public ExprEvaluatorBase<RecordExprEvaluator> {
11555 const LValue &This;
11556 APValue &Result;
11557 public:
11558
11559 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
11560 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
11561
11562 bool Success(const APValue &V, const Expr *E) {
11563 Result = V;
11564 return true;
11565 }
11566 bool ZeroInitialization(const Expr *E) {
11567 return ZeroInitialization(E, E->getType());
11568 }
11569 bool ZeroInitialization(const Expr *E, QualType T);
11570
11571 bool VisitCallExpr(const CallExpr *E) {
11572 return handleCallExpr(E, Result, &This);
11573 }
11574 bool VisitCastExpr(const CastExpr *E);
11575 bool VisitInitListExpr(const InitListExpr *E);
11576 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
11577 return VisitCXXConstructExpr(E, E->getType());
11578 }
11579 bool VisitLambdaExpr(const LambdaExpr *E);
11580 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
11581 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
11582 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
11583 bool VisitBinCmp(const BinaryOperator *E);
11584 bool VisitTypeTraitExpr(const TypeTraitExpr *E);
11585 bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E);
11586 bool VisitCXXParenListOrInitListExpr(const Expr *ExprToVisit,
11587 ArrayRef<Expr *> Args);
11588 bool VisitDesignatedInitUpdateExpr(const DesignatedInitUpdateExpr *E);
11589 };
11590}
11591
11592/// Perform zero-initialization on an object of non-union class type.
11593/// C++11 [dcl.init]p5:
11594/// To zero-initialize an object or reference of type T means:
11595/// [...]
11596/// -- if T is a (possibly cv-qualified) non-union class type,
11597/// each non-static data member and each base-class subobject is
11598/// zero-initialized
11599static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
11600 const RecordDecl *RD,
11601 const LValue &This, APValue &Result,
11602 bool IsCompleteClass = true) {
11603 assert(!RD->isUnion() && "Expected non-union class type");
11604 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
11605
11606 if (CD) {
11607 unsigned NonVirtualBases = countNonVirtualBases(CD);
11608 Result =
11609 APValue(APValue::UninitStruct(), NonVirtualBases, RD->getNumFields(),
11610 IsCompleteClass ? CD->getNumVBases() : 0);
11611 } else {
11613 }
11614
11615 if (RD->isInvalidDecl()) return false;
11616 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
11617
11618 if (CD) {
11619 unsigned Index = 0;
11620
11621 for (const auto &B : CD->bases()) {
11622 if (B.isVirtual())
11623 continue;
11625 LValue Subobject = This;
11626 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
11627 return false;
11628 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
11629 Result.getStructBase(Index),
11630 /*IsCompleteClass=*/false))
11631 return false;
11632 ++Index;
11633 }
11634 }
11635
11636 for (const auto *I : RD->fields()) {
11637 // -- if T is a reference type, no initialization is performed.
11638 if (I->isUnnamedBitField() || I->getType()->isReferenceType())
11639 continue;
11640
11641 LValue Subobject = This;
11642 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
11643 return false;
11644
11645 ImplicitValueInitExpr VIE(I->getType());
11646 if (!EvaluateInPlace(
11647 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
11648 return false;
11649 }
11650
11651 if (CD && This.pointsToCompleteClass(CD)) {
11652 unsigned Index = 0;
11653 for (const auto &B : CD->vbases()) {
11655 LValue Subobject = This;
11656 if (!HandleLValueDirectVirtualBase(Info, E, Subobject, CD, Base, &Layout))
11657 return false;
11658 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
11659 Result.getStructVirtualBase(Index),
11660 /*IsCompleteClass=*/false))
11661 return false;
11662 ++Index;
11663 }
11664 }
11665
11666 return true;
11667}
11668
11669bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
11670 const auto *RD = T->castAsRecordDecl();
11671 if (RD->isInvalidDecl()) return false;
11672 if (RD->isUnion()) {
11673 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
11674 // object's first non-static named data member is zero-initialized
11676 while (I != RD->field_end() && (*I)->isUnnamedBitField())
11677 ++I;
11678 if (I == RD->field_end()) {
11679 Result = APValue((const FieldDecl*)nullptr);
11680 return true;
11681 }
11682
11683 LValue Subobject = This;
11684 if (!HandleLValueMember(Info, E, Subobject, *I))
11685 return false;
11686 Result = APValue(*I);
11687 ImplicitValueInitExpr VIE(I->getType());
11688 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
11689 }
11690
11691 if (!Info.getLangOpts().CPlusPlus26) {
11692 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
11693 CXXRD && CXXRD->getNumVBases()) {
11694 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
11695 return false;
11696 }
11697 }
11698
11699 return HandleClassZeroInitialization(Info, E, RD, This, Result);
11700}
11701
11702bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
11703 switch (E->getCastKind()) {
11704 default:
11705 return ExprEvaluatorBaseTy::VisitCastExpr(E);
11706
11707 case CK_ConstructorConversion:
11708 return Visit(E->getSubExpr());
11709
11710 case CK_DerivedToBase:
11711 case CK_UncheckedDerivedToBase: {
11712 APValue DerivedObject;
11713 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
11714 return false;
11715 if (!DerivedObject.isStruct())
11716 return Error(E->getSubExpr());
11717
11718 // Derived-to-base rvalue conversion: just slice off the derived part.
11719 APValue *Value = &DerivedObject;
11720 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
11721 for (CastExpr::path_const_iterator PathI = E->path_begin(),
11722 PathE = E->path_end(); PathI != PathE; ++PathI) {
11723 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
11724 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
11725 Value = &Value->getStructBase(getBaseIndex(RD, Base));
11726 RD = Base;
11727 }
11728 Result = *Value;
11729 return true;
11730 }
11731 case CK_HLSLAggregateSplatCast: {
11732 APValue Val;
11733 QualType ValTy;
11734
11735 if (!hlslAggSplatHelper(Info, E->getSubExpr(), Val, ValTy))
11736 return false;
11737
11738 unsigned NEls = elementwiseSize(Info, E->getType());
11739 // splat our Val
11740 SmallVector<APValue> SplatEls(NEls, Val);
11741 SmallVector<QualType> SplatType(NEls, ValTy);
11742
11743 // cast the elements and construct our struct result
11744 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
11745 if (!constructAggregate(Info, FPO, E, Result, E->getType(), SplatEls,
11746 SplatType))
11747 return false;
11748
11749 return true;
11750 }
11751 case CK_HLSLElementwiseCast: {
11752 SmallVector<APValue> SrcEls;
11753 SmallVector<QualType> SrcTypes;
11754
11755 if (!hlslElementwiseCastHelper(Info, E->getSubExpr(), E->getType(), SrcEls,
11756 SrcTypes))
11757 return false;
11758
11759 // cast the elements and construct our struct result
11760 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
11761 if (!constructAggregate(Info, FPO, E, Result, E->getType(), SrcEls,
11762 SrcTypes))
11763 return false;
11764
11765 return true;
11766 }
11767 case CK_ToUnion: {
11768 const FieldDecl *Field = E->getTargetUnionField();
11769 LValue Subobject = This;
11770 if (!HandleLValueMember(Info, E, Subobject, Field))
11771 return false;
11772 Result = APValue(Field);
11773 if (!EvaluateInPlace(Result.getUnionValue(), Info, Subobject,
11774 E->getSubExpr()))
11775 return false;
11776 if (Field->isBitField()) {
11777 if (!truncateBitfieldValue(Info, E->getSubExpr(), Result.getUnionValue(),
11778 Field))
11779 return false;
11780 }
11781 return true;
11782 }
11783 }
11784}
11785
11786bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
11787 if (E->isTransparent())
11788 return Visit(E->getInit(0));
11789 return VisitCXXParenListOrInitListExpr(E, E->inits());
11790}
11791
11792bool RecordExprEvaluator::VisitCXXParenListOrInitListExpr(
11793 const Expr *ExprToVisit, ArrayRef<Expr *> Args) {
11794 const auto *RD = ExprToVisit->getType()->castAsRecordDecl();
11795 if (RD->isInvalidDecl()) return false;
11796 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
11797 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
11798
11799 EvalInfo::EvaluatingConstructorRAII EvalObj(
11800 Info,
11801 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
11802 CXXRD && CXXRD->getNumBases());
11803
11804 if (RD->isUnion()) {
11805 const FieldDecl *Field;
11806 if (auto *ILE = dyn_cast<InitListExpr>(ExprToVisit)) {
11807 Field = ILE->getInitializedFieldInUnion();
11808 } else if (auto *PLIE = dyn_cast<CXXParenListInitExpr>(ExprToVisit)) {
11809 Field = PLIE->getInitializedFieldInUnion();
11810 } else {
11811 llvm_unreachable(
11812 "Expression is neither an init list nor a C++ paren list");
11813 }
11814
11815 Result = APValue(Field);
11816 if (!Field)
11817 return true;
11818
11819 // If the initializer list for a union does not contain any elements, the
11820 // first element of the union is value-initialized.
11821 // FIXME: The element should be initialized from an initializer list.
11822 // Is this difference ever observable for initializer lists which
11823 // we don't build?
11824 ImplicitValueInitExpr VIE(Field->getType());
11825 const Expr *InitExpr = Args.empty() ? &VIE : Args[0];
11826
11827 LValue Subobject = This;
11828 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
11829 return false;
11830
11831 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
11832 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
11833 isa<CXXDefaultInitExpr>(InitExpr));
11834
11835 if (EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr)) {
11836 if (Field->isBitField())
11837 return truncateBitfieldValue(Info, InitExpr, Result.getUnionValue(),
11838 Field);
11839 return true;
11840 }
11841
11842 return false;
11843 }
11844
11845 if (!Result.hasValue())
11846 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
11847 RD->getNumFields());
11848 unsigned ElementNo = 0;
11849 bool Success = true;
11850
11851 // Initialize base classes.
11852 if (CXXRD && CXXRD->getNumBases()) {
11853 for (const auto &Base : CXXRD->bases()) {
11854 assert(ElementNo < Args.size() && "missing init for base class");
11855 const Expr *Init = Args[ElementNo];
11856
11857 LValue Subobject = This;
11858 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
11859 return false;
11860
11861 APValue &FieldVal = Result.getStructBase(ElementNo);
11862 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
11863 if (!Info.noteFailure())
11864 return false;
11865 Success = false;
11866 }
11867 ++ElementNo;
11868 }
11869
11870 EvalObj.finishedConstructingBases();
11871 }
11872
11873 // Initialize members.
11874 for (const auto *Field : RD->fields()) {
11875 // Anonymous bit-fields are not considered members of the class for
11876 // purposes of aggregate initialization.
11877 if (Field->isUnnamedBitField())
11878 continue;
11879
11880 LValue Subobject = This;
11881
11882 bool HaveInit = ElementNo < Args.size();
11883
11884 // FIXME: Diagnostics here should point to the end of the initializer
11885 // list, not the start.
11886 if (!HandleLValueMember(Info, HaveInit ? Args[ElementNo] : ExprToVisit,
11887 Subobject, Field, &Layout))
11888 return false;
11889
11890 // Perform an implicit value-initialization for members beyond the end of
11891 // the initializer list.
11892 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
11893 const Expr *Init = HaveInit ? Args[ElementNo++] : &VIE;
11894
11895 // If this is a child of a DesignatedInitUpdateExpr, skip elements which
11896 // aren't supposed to be modified.
11897 if (isa<NoInitExpr>(Init))
11898 continue;
11899
11900 if (Field->getType()->isIncompleteArrayType()) {
11901 if (auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType())) {
11902 if (!CAT->isZeroSize()) {
11903 // Bail out for now. This might sort of "work", but the rest of the
11904 // code isn't really prepared to handle it.
11905 Info.FFDiag(Init, diag::note_constexpr_unsupported_flexible_array);
11906 return false;
11907 }
11908 }
11909 }
11910
11911 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
11912 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
11914
11915 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
11916 if (Field->getType()->isReferenceType()) {
11917 LValue Result;
11919 FieldVal)) {
11920 if (!Info.noteFailure())
11921 return false;
11922 Success = false;
11923 }
11924 } else if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
11925 (Field->isBitField() &&
11926 !truncateBitfieldValue(Info, Init, FieldVal, Field))) {
11927 if (!Info.noteFailure())
11928 return false;
11929 Success = false;
11930 }
11931 }
11932
11933 EvalObj.finishedConstructingFields();
11934
11935 return Success;
11936}
11937
11938bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
11939 QualType T) {
11940 // Note that E's type is not necessarily the type of our class here; we might
11941 // be initializing an array element instead.
11942 const CXXConstructorDecl *FD = E->getConstructor();
11943 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
11944
11945 bool ZeroInit = E->requiresZeroInitialization();
11946 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
11947 if (ZeroInit)
11948 return ZeroInitialization(E, T);
11949
11951 }
11952
11954
11955 const FunctionDecl *Definition = nullptr;
11956 auto Body = FD->getBody(Definition);
11957
11958 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
11959 return false;
11960
11961 // Avoid materializing a temporary for an elidable copy/move constructor.
11962 if (E->isElidable() && !ZeroInit) {
11963 // FIXME: This only handles the simplest case, where the source object
11964 // is passed directly as the first argument to the constructor.
11965 // This should also handle stepping though implicit casts and
11966 // and conversion sequences which involve two steps, with a
11967 // conversion operator followed by a converting constructor.
11968 const Expr *SrcObj = E->getArg(0);
11969 assert(SrcObj->isTemporaryObject(Info.Ctx, FD->getParent()));
11970 assert(Info.Ctx.hasSameUnqualifiedType(E->getType(), SrcObj->getType()));
11971 if (const MaterializeTemporaryExpr *ME =
11972 dyn_cast<MaterializeTemporaryExpr>(SrcObj))
11973 return Visit(ME->getSubExpr());
11974 }
11975
11976 if (ZeroInit && !ZeroInitialization(E, T))
11977 return false;
11978
11979 auto Args = ArrayRef(E->getArgs(), E->getNumArgs());
11980 return HandleConstructorCall(E, This, Args,
11982 Result);
11983}
11984
11985bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
11986 const CXXInheritedCtorInitExpr *E) {
11987 if (!Info.CurrentCall) {
11988 assert(Info.checkingPotentialConstantExpression());
11989 return false;
11990 }
11991
11992 const CXXConstructorDecl *FD = E->getConstructor();
11993 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
11994 return false;
11995
11997
11998 const FunctionDecl *Definition = nullptr;
11999 auto Body = FD->getBody(Definition);
12000
12001 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
12002 return false;
12003
12004 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
12006 Result);
12007}
12008
12009bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
12010 const CXXStdInitializerListExpr *E) {
12011 const ConstantArrayType *ArrayType =
12012 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
12013
12014 LValue Array;
12015 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
12016 return false;
12017
12018 assert(ArrayType && "unexpected type for array initializer");
12019
12020 // Get a pointer to the first element of the array.
12021 Array.addArray(Info, E, ArrayType);
12022
12023 // FIXME: What if the initializer_list type has base classes, etc?
12024 Result = APValue(APValue::UninitStruct(), 0, 2);
12025 Array.moveInto(Result.getStructField(0));
12026
12027 auto *Record = E->getType()->castAsRecordDecl();
12028 RecordDecl::field_iterator Field = Record->field_begin();
12029 assert(Field != Record->field_end() &&
12030 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
12031 ArrayType->getElementType()) &&
12032 "Expected std::initializer_list first field to be const E *");
12033 ++Field;
12034 assert(Field != Record->field_end() &&
12035 "Expected std::initializer_list to have two fields");
12036
12037 if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType())) {
12038 // Length.
12039 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
12040 } else {
12041 // End pointer.
12042 assert(Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
12043 ArrayType->getElementType()) &&
12044 "Expected std::initializer_list second field to be const E *");
12045 if (!HandleLValueArrayAdjustment(Info, E, Array,
12046 ArrayType->getElementType(),
12047 ArrayType->getZExtSize()))
12048 return false;
12049 Array.moveInto(Result.getStructField(1));
12050 }
12051
12052 assert(++Field == Record->field_end() &&
12053 "Expected std::initializer_list to only have two fields");
12054
12055 return true;
12056}
12057
12058bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
12059 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
12060 if (ClosureClass->isInvalidDecl())
12061 return false;
12062
12063 const size_t NumFields = ClosureClass->getNumFields();
12064
12065 assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
12066 E->capture_init_end()) &&
12067 "The number of lambda capture initializers should equal the number of "
12068 "fields within the closure type");
12069
12070 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
12071 // Iterate through all the lambda's closure object's fields and initialize
12072 // them.
12073 auto *CaptureInitIt = E->capture_init_begin();
12074 bool Success = true;
12075 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(ClosureClass);
12076 for (const auto *Field : ClosureClass->fields()) {
12077 assert(CaptureInitIt != E->capture_init_end());
12078 // Get the initializer for this field
12079 Expr *const CurFieldInit = *CaptureInitIt++;
12080
12081 // If there is no initializer, either this is a VLA or an error has
12082 // occurred.
12083 if (!CurFieldInit || CurFieldInit->containsErrors())
12084 return Error(E);
12085
12086 LValue Subobject = This;
12087
12088 if (!HandleLValueMember(Info, E, Subobject, Field, &Layout))
12089 return false;
12090
12091 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
12092 if (!EvaluateInPlace(FieldVal, Info, Subobject, CurFieldInit)) {
12093 if (!Info.keepEvaluatingAfterFailure())
12094 return false;
12095 Success = false;
12096 }
12097 }
12098 return Success;
12099}
12100
12101bool RecordExprEvaluator::VisitDesignatedInitUpdateExpr(
12102 const DesignatedInitUpdateExpr *E) {
12103 if (!Visit(E->getBase()))
12104 return false;
12105 return Visit(E->getUpdater());
12106}
12107
12108static bool EvaluateRecord(const Expr *E, const LValue &This,
12109 APValue &Result, EvalInfo &Info) {
12110 assert(!E->isValueDependent());
12111 assert(E->isPRValue() && E->getType()->isRecordType() &&
12112 "can't evaluate expression as a record rvalue");
12113 return RecordExprEvaluator(Info, This, Result).Visit(E);
12114}
12115
12116//===----------------------------------------------------------------------===//
12117// Temporary Evaluation
12118//
12119// Temporaries are represented in the AST as rvalues, but generally behave like
12120// lvalues. The full-object of which the temporary is a subobject is implicitly
12121// materialized so that a reference can bind to it.
12122//===----------------------------------------------------------------------===//
12123namespace {
12124class TemporaryExprEvaluator
12125 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
12126public:
12127 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
12128 LValueExprEvaluatorBaseTy(Info, Result, false) {}
12129
12130 /// Visit an expression which constructs the value of this temporary.
12131 bool VisitConstructExpr(const Expr *E) {
12132 APValue &Value = Info.CurrentCall->createTemporary(
12133 E, E->getType(), ScopeKind::FullExpression, Result);
12134 return EvaluateInPlace(Value, Info, Result, E);
12135 }
12136
12137 bool VisitCastExpr(const CastExpr *E) {
12138 switch (E->getCastKind()) {
12139 default:
12140 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
12141
12142 case CK_ConstructorConversion:
12143 return VisitConstructExpr(E->getSubExpr());
12144 }
12145 }
12146 bool VisitInitListExpr(const InitListExpr *E) {
12147 return VisitConstructExpr(E);
12148 }
12149 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
12150 return VisitConstructExpr(E);
12151 }
12152 bool VisitCallExpr(const CallExpr *E) {
12153 return VisitConstructExpr(E);
12154 }
12155 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
12156 return VisitConstructExpr(E);
12157 }
12158 bool VisitLambdaExpr(const LambdaExpr *E) {
12159 return VisitConstructExpr(E);
12160 }
12161};
12162} // end anonymous namespace
12163
12164/// Evaluate an expression of record type as a temporary.
12165static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
12166 assert(!E->isValueDependent());
12167 assert(E->isPRValue() && E->getType()->isRecordType());
12168 return TemporaryExprEvaluator(Info, Result).Visit(E);
12169}
12170
12171//===----------------------------------------------------------------------===//
12172// Vector Evaluation
12173//===----------------------------------------------------------------------===//
12174
12175namespace {
12176 class VectorExprEvaluator
12177 : public ExprEvaluatorBase<VectorExprEvaluator> {
12178 APValue &Result;
12179 public:
12180
12181 VectorExprEvaluator(EvalInfo &info, APValue &Result)
12182 : ExprEvaluatorBaseTy(info), Result(Result) {}
12183
12184 bool Success(ArrayRef<APValue> V, const Expr *E) {
12185 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
12186 // FIXME: remove this APValue copy.
12187 Result = APValue(V.data(), V.size());
12188 return true;
12189 }
12190 bool Success(const APValue &V, const Expr *E) {
12191 assert(V.isVector());
12192 Result = V;
12193 return true;
12194 }
12195 bool ZeroInitialization(const Expr *E);
12196
12197 bool VisitUnaryReal(const UnaryOperator *E)
12198 { return Visit(E->getSubExpr()); }
12199 bool VisitCastExpr(const CastExpr* E);
12200 bool VisitInitListExpr(const InitListExpr *E);
12201 bool VisitUnaryImag(const UnaryOperator *E);
12202 bool VisitBinaryOperator(const BinaryOperator *E);
12203 bool VisitUnaryOperator(const UnaryOperator *E);
12204 bool VisitCallExpr(const CallExpr *E);
12205 bool VisitConvertVectorExpr(const ConvertVectorExpr *E);
12206 bool VisitShuffleVectorExpr(const ShuffleVectorExpr *E);
12207
12208 // FIXME: Missing: conditional operator (for GNU
12209 // conditional select), ExtVectorElementExpr
12210 };
12211} // end anonymous namespace
12212
12213static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
12214 assert(E->isPRValue() && E->getType()->isVectorType() &&
12215 "not a vector prvalue");
12216 return VectorExprEvaluator(Info, Result).Visit(E);
12217}
12218
12219static llvm::APInt ConvertBoolVectorToInt(const APValue &Val) {
12220 assert(Val.isVector() && "expected vector APValue");
12221 unsigned NumElts = Val.getVectorLength();
12222
12223 // Each element is one bit, so create an integer with NumElts bits.
12224 llvm::APInt Result(NumElts, 0);
12225
12226 for (unsigned I = 0; I < NumElts; ++I) {
12227 const APValue &Elt = Val.getVectorElt(I);
12228 assert(Elt.isInt() && "expected integer element in bool vector");
12229
12230 if (Elt.getInt().getBoolValue())
12231 Result.setBit(I);
12232 }
12233
12234 return Result;
12235}
12236
12237bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
12238 const VectorType *VTy = E->getType()->castAs<VectorType>();
12239 unsigned NElts = VTy->getNumElements();
12240
12241 const Expr *SE = E->getSubExpr();
12242 QualType SETy = SE->getType();
12243
12244 switch (E->getCastKind()) {
12245 case CK_VectorSplat: {
12246 APValue Val = APValue();
12247 if (SETy->isIntegerType()) {
12248 APSInt IntResult;
12249 if (!EvaluateInteger(SE, IntResult, Info))
12250 return false;
12251 Val = APValue(std::move(IntResult));
12252 } else if (SETy->isRealFloatingType()) {
12253 APFloat FloatResult(0.0);
12254 if (!EvaluateFloat(SE, FloatResult, Info))
12255 return false;
12256 Val = APValue(std::move(FloatResult));
12257 } else {
12258 return Error(E);
12259 }
12260
12261 // Splat and create vector APValue.
12262 SmallVector<APValue, 4> Elts(NElts, Val);
12263 return Success(Elts, E);
12264 }
12265 case CK_BitCast: {
12266 APValue SVal;
12267 if (!Evaluate(SVal, Info, SE))
12268 return false;
12269
12270 if (!SVal.isInt() && !SVal.isFloat() && !SVal.isVector()) {
12271 // Give up if the input isn't an int, float, or vector. For example, we
12272 // reject "(v4i16)(intptr_t)&a".
12273 Info.FFDiag(E, diag::note_constexpr_invalid_cast)
12274 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
12275 << Info.Ctx.getLangOpts().CPlusPlus;
12276 return false;
12277 }
12278
12279 if (!handleRValueToRValueBitCast(Info, Result, SVal, E))
12280 return false;
12281
12282 return true;
12283 }
12284 case CK_HLSLVectorTruncation: {
12285 APValue Val;
12286 SmallVector<APValue, 4> Elements;
12287 if (!EvaluateVector(SE, Val, Info))
12288 return Error(E);
12289 for (unsigned I = 0; I < NElts; I++)
12290 Elements.push_back(Val.getVectorElt(I));
12291 return Success(Elements, E);
12292 }
12293 case CK_HLSLMatrixTruncation: {
12294 // Matrix truncation occurs in row-major order.
12295 APValue Val;
12296 if (!EvaluateMatrix(SE, Val, Info))
12297 return Error(E);
12298 SmallVector<APValue, 16> Elements;
12299 for (unsigned Row = 0;
12300 Row < Val.getMatrixNumRows() && Elements.size() < NElts; Row++)
12301 for (unsigned Col = 0;
12302 Col < Val.getMatrixNumColumns() && Elements.size() < NElts; Col++)
12303 Elements.push_back(Val.getMatrixElt(Row, Col));
12304 return Success(Elements, E);
12305 }
12306 case CK_HLSLAggregateSplatCast: {
12307 APValue Val;
12308 QualType ValTy;
12309
12310 if (!hlslAggSplatHelper(Info, SE, Val, ValTy))
12311 return false;
12312
12313 // cast our Val once.
12315 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
12316 if (!handleScalarCast(Info, FPO, E, ValTy, VTy->getElementType(), Val,
12317 Result))
12318 return false;
12319
12320 SmallVector<APValue, 4> SplatEls(NElts, Result);
12321 return Success(SplatEls, E);
12322 }
12323 case CK_HLSLElementwiseCast: {
12324 SmallVector<APValue> SrcVals;
12325 SmallVector<QualType> SrcTypes;
12326
12327 if (!hlslElementwiseCastHelper(Info, SE, E->getType(), SrcVals, SrcTypes))
12328 return false;
12329
12330 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
12331 SmallVector<QualType, 4> DestTypes(NElts, VTy->getElementType());
12332 SmallVector<APValue, 4> ResultEls(NElts);
12333 if (!handleElementwiseCast(Info, E, FPO, SrcVals, SrcTypes, DestTypes,
12334 ResultEls))
12335 return false;
12336 return Success(ResultEls, E);
12337 }
12338 case CK_IntegralToFloating:
12339 case CK_FloatingToIntegral:
12340 case CK_IntegralCast:
12341 case CK_FloatingCast:
12342 case CK_FloatingToBoolean:
12343 case CK_IntegralToBoolean: {
12344 // These casts apply element-wise when the source is a vector type.
12345 assert(SETy->isVectorType() && "expected vector source type");
12346 APValue SrcVal;
12347 if (!EvaluateVector(SE, SrcVal, Info))
12348 return Error(E);
12349
12350 assert(SrcVal.getVectorLength() == NElts);
12351 QualType SrcEltTy = SETy->castAs<VectorType>()->getElementType();
12352 QualType DstEltTy = VTy->getElementType();
12353 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
12354
12355 SmallVector<APValue, 4> ResultEls(NElts);
12356 for (unsigned I = 0; I < NElts; ++I) {
12357 if (!handleScalarCast(Info, FPO, E, SrcEltTy, DstEltTy,
12358 SrcVal.getVectorElt(I), ResultEls[I]))
12359 return Error(E);
12360 }
12361 return Success(ResultEls, E);
12362 }
12363 default:
12364 return ExprEvaluatorBaseTy::VisitCastExpr(E);
12365 }
12366}
12367
12368bool
12369VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
12370 const VectorType *VT = E->getType()->castAs<VectorType>();
12371 unsigned NumInits = E->getNumInits();
12372 unsigned NumElements = VT->getNumElements();
12373
12374 QualType EltTy = VT->getElementType();
12375 SmallVector<APValue, 4> Elements;
12376
12377 // MFloat8 type doesn't have constants and thus constant folding
12378 // is impossible.
12379 if (EltTy->isMFloat8Type())
12380 return false;
12381
12382 // The number of initializers can be less than the number of
12383 // vector elements. For OpenCL, this can be due to nested vector
12384 // initialization. For GCC compatibility, missing trailing elements
12385 // should be initialized with zeroes.
12386 unsigned CountInits = 0, CountElts = 0;
12387 while (CountElts < NumElements) {
12388 // Handle nested vector initialization.
12389 if (CountInits < NumInits
12390 && E->getInit(CountInits)->getType()->isVectorType()) {
12391 APValue v;
12392 if (!EvaluateVector(E->getInit(CountInits), v, Info))
12393 return Error(E);
12394 unsigned vlen = v.getVectorLength();
12395 for (unsigned j = 0; j < vlen; j++)
12396 Elements.push_back(v.getVectorElt(j));
12397 CountElts += vlen;
12398 } else if (EltTy->isIntegerType()) {
12399 llvm::APSInt sInt(32);
12400 if (CountInits < NumInits) {
12401 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
12402 return false;
12403 } else // trailing integer zero.
12404 sInt = Info.Ctx.MakeIntValue(0, EltTy);
12405 Elements.push_back(APValue(sInt));
12406 CountElts++;
12407 } else {
12408 llvm::APFloat f(0.0);
12409 if (CountInits < NumInits) {
12410 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
12411 return false;
12412 } else // trailing float zero.
12413 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
12414 Elements.push_back(APValue(f));
12415 CountElts++;
12416 }
12417 CountInits++;
12418 }
12419 return Success(Elements, E);
12420}
12421
12422bool
12423VectorExprEvaluator::ZeroInitialization(const Expr *E) {
12424 const auto *VT = E->getType()->castAs<VectorType>();
12425 QualType EltTy = VT->getElementType();
12426 APValue ZeroElement;
12427 if (EltTy->isIntegerType())
12428 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
12429 else
12430 ZeroElement =
12431 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
12432
12433 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
12434 return Success(Elements, E);
12435}
12436
12437bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
12438 VisitIgnoredValue(E->getSubExpr());
12439 return ZeroInitialization(E);
12440}
12441
12442bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
12443 BinaryOperatorKind Op = E->getOpcode();
12444 assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp &&
12445 "Operation not supported on vector types");
12446
12447 if (Op == BO_Comma)
12448 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
12449
12450 Expr *LHS = E->getLHS();
12451 Expr *RHS = E->getRHS();
12452
12453 [[maybe_unused]] QualType LHSType = LHS->getType().getAtomicUnqualifiedType();
12454 [[maybe_unused]] QualType RHSType = RHS->getType().getAtomicUnqualifiedType();
12455 assert(LHSType->isVectorType() && RHSType->isVectorType() &&
12456 "Must both be vector types");
12457 // Checking JUST the types are the same would be fine, except shifts don't
12458 // need to have their types be the same (since you always shift by an int).
12459 assert(LHSType->castAs<VectorType>()->getNumElements() ==
12460 E->getType()->castAs<VectorType>()->getNumElements() &&
12461 RHSType->castAs<VectorType>()->getNumElements() ==
12462 E->getType()->castAs<VectorType>()->getNumElements() &&
12463 "All operands must be the same size.");
12464
12465 APValue LHSValue;
12466 APValue RHSValue;
12467 bool LHSOK = Evaluate(LHSValue, Info, LHS);
12468 if (!LHSOK && !Info.noteFailure())
12469 return false;
12470 if (!Evaluate(RHSValue, Info, RHS) || !LHSOK)
12471 return false;
12472
12473 if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue))
12474 return false;
12475
12476 return Success(LHSValue, E);
12477}
12478
12479static std::optional<APValue> handleVectorUnaryOperator(ASTContext &Ctx,
12480 QualType ResultTy,
12482 APValue Elt) {
12483 switch (Op) {
12484 case UO_Plus:
12485 // Nothing to do here.
12486 return Elt;
12487 case UO_Minus:
12488 if (Elt.getKind() == APValue::Int) {
12489 Elt.getInt().negate();
12490 } else {
12491 assert(Elt.getKind() == APValue::Float &&
12492 "Vector can only be int or float type");
12493 Elt.getFloat().changeSign();
12494 }
12495 return Elt;
12496 case UO_Not:
12497 // This is only valid for integral types anyway, so we don't have to handle
12498 // float here.
12499 assert(Elt.getKind() == APValue::Int &&
12500 "Vector operator ~ can only be int");
12501 Elt.getInt().flipAllBits();
12502 return Elt;
12503 case UO_LNot: {
12504 if (Elt.getKind() == APValue::Int) {
12505 Elt.getInt() = !Elt.getInt();
12506 // operator ! on vectors returns -1 for 'truth', so negate it.
12507 Elt.getInt().negate();
12508 return Elt;
12509 }
12510 assert(Elt.getKind() == APValue::Float &&
12511 "Vector can only be int or float type");
12512 // Float types result in an int of the same size, but -1 for true, or 0 for
12513 // false.
12514 APSInt EltResult{Ctx.getIntWidth(ResultTy),
12515 ResultTy->isUnsignedIntegerType()};
12516 if (Elt.getFloat().isZero())
12517 EltResult.setAllBits();
12518 else
12519 EltResult.clearAllBits();
12520
12521 return APValue{EltResult};
12522 }
12523 default:
12524 // FIXME: Implement the rest of the unary operators.
12525 return std::nullopt;
12526 }
12527}
12528
12529bool VectorExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
12530 Expr *SubExpr = E->getSubExpr();
12531 const auto *VD = SubExpr->getType()->castAs<VectorType>();
12532 // This result element type differs in the case of negating a floating point
12533 // vector, since the result type is the a vector of the equivilant sized
12534 // integer.
12535 const QualType ResultEltTy = VD->getElementType();
12536 UnaryOperatorKind Op = E->getOpcode();
12537
12538 APValue SubExprValue;
12539 if (!Evaluate(SubExprValue, Info, SubExpr))
12540 return false;
12541
12542 // FIXME: This vector evaluator someday needs to be changed to be LValue
12543 // aware/keep LValue information around, rather than dealing with just vector
12544 // types directly. Until then, we cannot handle cases where the operand to
12545 // these unary operators is an LValue. The only case I've been able to see
12546 // cause this is operator++ assigning to a member expression (only valid in
12547 // altivec compilations) in C mode, so this shouldn't limit us too much.
12548 if (SubExprValue.isLValue())
12549 return false;
12550
12551 assert(SubExprValue.getVectorLength() == VD->getNumElements() &&
12552 "Vector length doesn't match type?");
12553
12554 SmallVector<APValue, 4> ResultElements;
12555 for (unsigned EltNum = 0; EltNum < VD->getNumElements(); ++EltNum) {
12556 std::optional<APValue> Elt = handleVectorUnaryOperator(
12557 Info.Ctx, ResultEltTy, Op, SubExprValue.getVectorElt(EltNum));
12558 if (!Elt)
12559 return false;
12560 ResultElements.push_back(*Elt);
12561 }
12562 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12563}
12564
12565static bool handleVectorElementCast(EvalInfo &Info, const FPOptions FPO,
12566 const Expr *E, QualType SourceTy,
12567 QualType DestTy, APValue const &Original,
12568 APValue &Result) {
12569 if (SourceTy->isIntegerType()) {
12570 if (DestTy->isRealFloatingType()) {
12571 Result = APValue(APFloat(0.0));
12572 return HandleIntToFloatCast(Info, E, FPO, SourceTy, Original.getInt(),
12573 DestTy, Result.getFloat());
12574 }
12575 if (DestTy->isIntegerType()) {
12576 Result = APValue(
12577 HandleIntToIntCast(Info, E, DestTy, SourceTy, Original.getInt()));
12578 return true;
12579 }
12580 } else if (SourceTy->isRealFloatingType()) {
12581 if (DestTy->isRealFloatingType()) {
12582 Result = Original;
12583 return HandleFloatToFloatCast(Info, E, SourceTy, DestTy,
12584 Result.getFloat());
12585 }
12586 if (DestTy->isIntegerType()) {
12587 Result = APValue(APSInt());
12588 return HandleFloatToIntCast(Info, E, SourceTy, Original.getFloat(),
12589 DestTy, Result.getInt());
12590 }
12591 }
12592
12593 Info.FFDiag(E, diag::err_convertvector_constexpr_unsupported_vector_cast)
12594 << SourceTy << DestTy;
12595 return false;
12596}
12597
12598static bool evalPackBuiltin(const CallExpr *E, EvalInfo &Info, APValue &Result,
12599 llvm::function_ref<APInt(const APSInt &)> PackFn) {
12600 APValue LHS, RHS;
12601 if (!EvaluateAsRValue(Info, E->getArg(0), LHS) ||
12602 !EvaluateAsRValue(Info, E->getArg(1), RHS))
12603 return false;
12604
12605 unsigned LHSVecLen = LHS.getVectorLength();
12606 unsigned RHSVecLen = RHS.getVectorLength();
12607
12608 assert(LHSVecLen != 0 && LHSVecLen == RHSVecLen &&
12609 "pack builtin LHSVecLen must equal to RHSVecLen");
12610
12611 const VectorType *VT0 = E->getArg(0)->getType()->castAs<VectorType>();
12612 const unsigned SrcBits = Info.Ctx.getIntWidth(VT0->getElementType());
12613
12614 const VectorType *DstVT = E->getType()->castAs<VectorType>();
12615 QualType DstElemTy = DstVT->getElementType();
12616 const bool DstIsUnsigned = DstElemTy->isUnsignedIntegerType();
12617
12618 const unsigned SrcPerLane = 128 / SrcBits;
12619 const unsigned Lanes = LHSVecLen * SrcBits / 128;
12620
12622 Out.reserve(LHSVecLen + RHSVecLen);
12623
12624 for (unsigned Lane = 0; Lane != Lanes; ++Lane) {
12625 unsigned base = Lane * SrcPerLane;
12626 for (unsigned I = 0; I != SrcPerLane; ++I)
12627 Out.emplace_back(APValue(
12628 APSInt(PackFn(LHS.getVectorElt(base + I).getInt()), DstIsUnsigned)));
12629 for (unsigned I = 0; I != SrcPerLane; ++I)
12630 Out.emplace_back(APValue(
12631 APSInt(PackFn(RHS.getVectorElt(base + I).getInt()), DstIsUnsigned)));
12632 }
12633
12634 Result = APValue(Out.data(), Out.size());
12635 return true;
12636}
12637
12639 EvalInfo &Info, const CallExpr *Call, APValue &Out,
12640 llvm::function_ref<std::pair<unsigned, int>(unsigned, unsigned)>
12641 GetSourceIndex) {
12642
12643 const auto *VT = Call->getType()->getAs<VectorType>();
12644 if (!VT)
12645 return false;
12646
12647 unsigned ShuffleMask = 0;
12648 APValue A, MaskVector, B;
12649 bool IsVectorMask = false;
12650 bool IsSingleOperand = (Call->getNumArgs() == 2);
12651
12652 if (IsSingleOperand) {
12653 QualType MaskType = Call->getArg(1)->getType();
12654 if (MaskType->isVectorType()) {
12655 IsVectorMask = true;
12656 if (!EvaluateAsRValue(Info, Call->getArg(0), A) ||
12657 !EvaluateAsRValue(Info, Call->getArg(1), MaskVector))
12658 return false;
12659 B = A;
12660 } else if (MaskType->isIntegerType()) {
12661 APSInt MaskImm;
12662 if (!EvaluateInteger(Call->getArg(1), MaskImm, Info))
12663 return false;
12664 ShuffleMask = static_cast<unsigned>(MaskImm.getZExtValue());
12665 if (!EvaluateAsRValue(Info, Call->getArg(0), A))
12666 return false;
12667 B = A;
12668 } else {
12669 return false;
12670 }
12671 } else {
12672 QualType Arg2Type = Call->getArg(2)->getType();
12673 if (Arg2Type->isVectorType()) {
12674 IsVectorMask = true;
12675 if (!EvaluateAsRValue(Info, Call->getArg(0), A) ||
12676 !EvaluateAsRValue(Info, Call->getArg(1), MaskVector) ||
12677 !EvaluateAsRValue(Info, Call->getArg(2), B))
12678 return false;
12679 } else if (Arg2Type->isIntegerType()) {
12680 APSInt MaskImm;
12681 if (!EvaluateInteger(Call->getArg(2), MaskImm, Info))
12682 return false;
12683 ShuffleMask = static_cast<unsigned>(MaskImm.getZExtValue());
12684 if (!EvaluateAsRValue(Info, Call->getArg(0), A) ||
12685 !EvaluateAsRValue(Info, Call->getArg(1), B))
12686 return false;
12687 } else {
12688 return false;
12689 }
12690 }
12691
12692 unsigned NumElts = VT->getNumElements();
12693 SmallVector<APValue, 64> ResultElements;
12694 ResultElements.reserve(NumElts);
12695
12696 for (unsigned DstIdx = 0; DstIdx != NumElts; ++DstIdx) {
12697 if (IsVectorMask) {
12698 ShuffleMask = static_cast<unsigned>(
12699 MaskVector.getVectorElt(DstIdx).getInt().getZExtValue());
12700 }
12701 auto [SrcVecIdx, SrcIdx] = GetSourceIndex(DstIdx, ShuffleMask);
12702
12703 if (SrcIdx < 0) {
12704 // Zero out this element
12705 QualType ElemTy = VT->getElementType();
12706 if (ElemTy->isRealFloatingType()) {
12707 ResultElements.push_back(
12708 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy))));
12709 } else if (ElemTy->isIntegerType()) {
12710 APValue Zero(Info.Ctx.MakeIntValue(0, ElemTy));
12711 ResultElements.push_back(APValue(Zero));
12712 } else {
12713 // Other types of fallback logic
12714 ResultElements.push_back(APValue());
12715 }
12716 } else {
12717 const APValue &Src = (SrcVecIdx == 0) ? A : B;
12718 ResultElements.push_back(Src.getVectorElt(SrcIdx));
12719 }
12720 }
12721
12722 Out = APValue(ResultElements.data(), ResultElements.size());
12723 return true;
12724}
12725static bool ConvertDoubleToFloatStrict(EvalInfo &Info, const Expr *E,
12726 APFloat OrigVal, APValue &Result) {
12727
12728 if (OrigVal.isInfinity()) {
12729 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << 0;
12730 return false;
12731 }
12732 if (OrigVal.isNaN()) {
12733 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << 1;
12734 return false;
12735 }
12736
12737 APFloat Val = OrigVal;
12738 bool LosesInfo = false;
12739 APFloat::opStatus Status = Val.convert(
12740 APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, &LosesInfo);
12741
12742 if (LosesInfo || Val.isDenormal()) {
12743 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic_strict);
12744 return false;
12745 }
12746
12747 if (Status != APFloat::opOK) {
12748 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
12749 return false;
12750 }
12751
12752 Result = APValue(Val);
12753 return true;
12754}
12756 EvalInfo &Info, const CallExpr *Call, APValue &Out,
12757 llvm::function_ref<APInt(const APInt &, uint64_t)> ShiftOp,
12758 llvm::function_ref<APInt(const APInt &, unsigned)> OverflowOp) {
12759
12760 APValue Source, Count;
12761 if (!EvaluateAsRValue(Info, Call->getArg(0), Source) ||
12762 !EvaluateAsRValue(Info, Call->getArg(1), Count))
12763 return false;
12764
12765 assert(Call->getNumArgs() == 2);
12766
12767 QualType SourceTy = Call->getArg(0)->getType();
12768 assert(SourceTy->isVectorType() &&
12769 Call->getArg(1)->getType()->isVectorType());
12770
12771 QualType DestEltTy = SourceTy->castAs<VectorType>()->getElementType();
12772 unsigned DestEltWidth = Source.getVectorElt(0).getInt().getBitWidth();
12773 unsigned DestLen = Source.getVectorLength();
12774 bool IsDestUnsigned = DestEltTy->isUnsignedIntegerType();
12775 unsigned CountEltWidth = Count.getVectorElt(0).getInt().getBitWidth();
12776 unsigned NumBitsInQWord = 64;
12777 unsigned NumCountElts = NumBitsInQWord / CountEltWidth;
12779 Result.reserve(DestLen);
12780
12781 uint64_t CountLQWord = 0;
12782 for (unsigned EltIdx = 0; EltIdx != NumCountElts; ++EltIdx) {
12783 uint64_t Elt = Count.getVectorElt(EltIdx).getInt().getZExtValue();
12784 CountLQWord |= (Elt << (EltIdx * CountEltWidth));
12785 }
12786
12787 for (unsigned EltIdx = 0; EltIdx != DestLen; ++EltIdx) {
12788 APInt Elt = Source.getVectorElt(EltIdx).getInt();
12789 if (CountLQWord < DestEltWidth) {
12790 Result.push_back(
12791 APValue(APSInt(ShiftOp(Elt, CountLQWord), IsDestUnsigned)));
12792 } else {
12793 Result.push_back(
12794 APValue(APSInt(OverflowOp(Elt, DestEltWidth), IsDestUnsigned)));
12795 }
12796 }
12797 Out = APValue(Result.data(), Result.size());
12798 return true;
12799}
12800
12801std::optional<APFloat> EvalScalarMinMaxFp(const APFloat &A, const APFloat &B,
12802 std::optional<APSInt> RoundingMode,
12803 bool IsMin) {
12804 APSInt DefaultMode(APInt(32, 4), /*isUnsigned=*/true);
12805 if (RoundingMode.value_or(DefaultMode) != 4)
12806 return std::nullopt;
12807 if (A.isNaN() || A.isInfinity() || A.isDenormal() || B.isNaN() ||
12808 B.isInfinity() || B.isDenormal())
12809 return std::nullopt;
12810 if (A.isZero() && B.isZero())
12811 return B;
12812 return IsMin ? llvm::minimum(A, B) : llvm::maximum(A, B);
12813}
12814
12815bool VectorExprEvaluator::VisitCallExpr(const CallExpr *E) {
12816 if (!IsConstantEvaluatedBuiltinCall(E))
12817 return ExprEvaluatorBaseTy::VisitCallExpr(E);
12818
12819 unsigned BuiltinOp = ConvertBuiltinIDToX86BuiltinID(Info.Ctx, E);
12820
12821 auto EvaluateBinOpExpr =
12822 [&](llvm::function_ref<APInt(const APSInt &, const APSInt &)> Fn) {
12823 APValue SourceLHS, SourceRHS;
12824 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
12825 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
12826 return false;
12827
12828 auto *DestTy = E->getType()->castAs<VectorType>();
12829 QualType DestEltTy = DestTy->getElementType();
12830 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
12831 unsigned SourceLen = SourceLHS.getVectorLength();
12832 SmallVector<APValue, 4> ResultElements;
12833 ResultElements.reserve(SourceLen);
12834
12835 if (SourceRHS.isInt()) {
12836 const APSInt &RHS = SourceRHS.getInt();
12837 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12838 const APSInt &LHS = SourceLHS.getVectorElt(EltNum).getInt();
12839 ResultElements.push_back(
12840 APValue(APSInt(Fn(LHS, RHS), DestUnsigned)));
12841 }
12842 } else {
12843 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12844 const APSInt &LHS = SourceLHS.getVectorElt(EltNum).getInt();
12845 const APSInt &RHS = SourceRHS.getVectorElt(EltNum).getInt();
12846 ResultElements.push_back(
12847 APValue(APSInt(Fn(LHS, RHS), DestUnsigned)));
12848 }
12849 }
12850 return Success(APValue(ResultElements.data(), SourceLen), E);
12851 };
12852
12853 auto EvaluateFpBinOpExpr =
12854 [&](llvm::function_ref<std::optional<APFloat>(
12855 const APFloat &, const APFloat &, std::optional<APSInt>)>
12856 Fn,
12857 bool IsScalar = false) {
12858 assert(E->getNumArgs() == 2 || E->getNumArgs() == 3);
12859 APValue A, B;
12860 if (!EvaluateAsRValue(Info, E->getArg(0), A) ||
12861 !EvaluateAsRValue(Info, E->getArg(1), B))
12862 return false;
12863
12864 assert(A.isVector() && B.isVector());
12865 assert(A.getVectorLength() == B.getVectorLength());
12866
12867 std::optional<APSInt> RoundingMode;
12868 if (E->getNumArgs() == 3) {
12869 APSInt Imm;
12870 if (!EvaluateInteger(E->getArg(2), Imm, Info))
12871 return false;
12872 RoundingMode = Imm;
12873 }
12874
12875 unsigned NumElems = A.getVectorLength();
12876 SmallVector<APValue, 4> ResultElements;
12877 ResultElements.reserve(NumElems);
12878
12879 for (unsigned EltNum = 0; EltNum < NumElems; ++EltNum) {
12880 if (IsScalar && EltNum > 0) {
12881 ResultElements.push_back(A.getVectorElt(EltNum));
12882 continue;
12883 }
12884 const APFloat &EltA = A.getVectorElt(EltNum).getFloat();
12885 const APFloat &EltB = B.getVectorElt(EltNum).getFloat();
12886 std::optional<APFloat> Result = Fn(EltA, EltB, RoundingMode);
12887 if (!Result)
12888 return false;
12889 ResultElements.push_back(APValue(*Result));
12890 }
12891 return Success(APValue(ResultElements.data(), NumElems), E);
12892 };
12893
12894 auto EvaluateScalarFpRoundMaskBinOp =
12895 [&](llvm::function_ref<std::optional<APFloat>(
12896 const APFloat &, const APFloat &, std::optional<APSInt>)>
12897 Fn) {
12898 assert(E->getNumArgs() == 5);
12899 APValue VecA, VecB, VecSrc;
12900 APSInt MaskVal, Rounding;
12901
12902 if (!EvaluateAsRValue(Info, E->getArg(0), VecA) ||
12903 !EvaluateAsRValue(Info, E->getArg(1), VecB) ||
12904 !EvaluateAsRValue(Info, E->getArg(2), VecSrc) ||
12905 !EvaluateInteger(E->getArg(3), MaskVal, Info) ||
12906 !EvaluateInteger(E->getArg(4), Rounding, Info))
12907 return false;
12908
12909 unsigned NumElems = VecA.getVectorLength();
12910 SmallVector<APValue, 8> ResultElements;
12911 ResultElements.reserve(NumElems);
12912
12913 if (MaskVal.getZExtValue() & 1) {
12914 const APFloat &EltA = VecA.getVectorElt(0).getFloat();
12915 const APFloat &EltB = VecB.getVectorElt(0).getFloat();
12916 std::optional<APFloat> Result = Fn(EltA, EltB, Rounding);
12917 if (!Result)
12918 return false;
12919 ResultElements.push_back(APValue(*Result));
12920 } else {
12921 ResultElements.push_back(VecSrc.getVectorElt(0));
12922 }
12923
12924 for (unsigned I = 1; I < NumElems; ++I)
12925 ResultElements.push_back(VecA.getVectorElt(I));
12926
12927 return Success(APValue(ResultElements.data(), NumElems), E);
12928 };
12929
12930 auto EvalSelectScalar = [&](unsigned Len) -> bool {
12931 APSInt Mask;
12932 APValue AVal, WVal;
12933 if (!EvaluateInteger(E->getArg(0), Mask, Info) ||
12934 !EvaluateAsRValue(Info, E->getArg(1), AVal) ||
12935 !EvaluateAsRValue(Info, E->getArg(2), WVal))
12936 return false;
12937
12938 bool TakeA0 = (Mask.getZExtValue() & 1u) != 0;
12940 Res.reserve(Len);
12941 Res.push_back(TakeA0 ? AVal.getVectorElt(0) : WVal.getVectorElt(0));
12942 for (unsigned I = 1; I < Len; ++I)
12943 Res.push_back(WVal.getVectorElt(I));
12944 APValue V(Res.data(), Res.size());
12945 return Success(V, E);
12946 };
12947
12948 auto EvalVectorDotProduct = [&](bool IsSaturating) -> bool {
12949 APValue Source, OperandA, OperandB;
12950 if (!EvaluateVector(E->getArg(0), Source, Info) ||
12951 !EvaluateVector(E->getArg(1), OperandA, Info) ||
12952 !EvaluateVector(E->getArg(2), OperandB, Info)) {
12953 return false;
12954 }
12955
12956 unsigned NumSrcElems = Source.getVectorLength();
12957 unsigned NumOperandElems = OperandA.getVectorLength();
12958 unsigned ElemsPerLane = NumOperandElems / NumSrcElems;
12959
12960 assert(OperandA.getVectorLength() == OperandB.getVectorLength());
12961
12963 Result.reserve(NumSrcElems);
12964 for (unsigned I = 0; I != NumSrcElems; ++I) {
12965 APSInt DotProduct = Source.getVectorElt(I).getInt();
12966 DotProduct = DotProduct.extend(64);
12967 for (unsigned J = 0; J != ElemsPerLane; ++J) {
12968 APSInt OpA = APSInt(
12969 OperandA.getVectorElt(ElemsPerLane * I + J).getInt().extend(64),
12970 false);
12971 APSInt OpB = APSInt(
12972 OperandB.getVectorElt(ElemsPerLane * I + J).getInt().extend(64),
12973 false);
12974 DotProduct += OpA * OpB;
12975 }
12976 if (IsSaturating) {
12977 DotProduct = APSInt(DotProduct.truncSSat(32), false);
12978 } else {
12979 DotProduct = APSInt(DotProduct.trunc(32), false);
12980 }
12981 Result.push_back(APValue(DotProduct));
12982 }
12983
12984 return Success(APValue(Result.data(), Result.size()), E);
12985 };
12986
12987 switch (BuiltinOp) {
12988 default:
12989 return false;
12990 case Builtin::BI__builtin_elementwise_popcount:
12991 case Builtin::BI__builtin_elementwise_bitreverse: {
12992 APValue Source;
12993 if (!EvaluateAsRValue(Info, E->getArg(0), Source))
12994 return false;
12995
12996 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
12997 unsigned SourceLen = Source.getVectorLength();
12998 SmallVector<APValue, 4> ResultElements;
12999 ResultElements.reserve(SourceLen);
13000
13001 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
13002 APSInt Elt = Source.getVectorElt(EltNum).getInt();
13003 switch (BuiltinOp) {
13004 case Builtin::BI__builtin_elementwise_popcount:
13005 ResultElements.push_back(APValue(
13006 APSInt(APInt(Info.Ctx.getIntWidth(DestEltTy), Elt.popcount()),
13007 DestEltTy->isUnsignedIntegerOrEnumerationType())));
13008 break;
13009 case Builtin::BI__builtin_elementwise_bitreverse:
13010 ResultElements.push_back(
13011 APValue(APSInt(Elt.reverseBits(),
13012 DestEltTy->isUnsignedIntegerOrEnumerationType())));
13013 break;
13014 }
13015 }
13016
13017 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13018 }
13019 case Builtin::BI__builtin_elementwise_abs: {
13020 APValue Source;
13021 if (!EvaluateAsRValue(Info, E->getArg(0), Source))
13022 return false;
13023
13024 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
13025 unsigned SourceLen = Source.getVectorLength();
13026 SmallVector<APValue, 4> ResultElements;
13027 ResultElements.reserve(SourceLen);
13028
13029 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
13030 APValue CurrentEle = Source.getVectorElt(EltNum);
13031 APValue Val = DestEltTy->isFloatingType()
13032 ? APValue(llvm::abs(CurrentEle.getFloat()))
13033 : APValue(APSInt(
13034 CurrentEle.getInt().abs(),
13035 DestEltTy->isUnsignedIntegerOrEnumerationType()));
13036 ResultElements.push_back(Val);
13037 }
13038
13039 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13040 }
13041
13042 case Builtin::BI__builtin_elementwise_add_sat:
13043 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
13044 return LHS.isSigned() ? LHS.sadd_sat(RHS) : LHS.uadd_sat(RHS);
13045 });
13046
13047 case Builtin::BI__builtin_elementwise_sub_sat:
13048 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
13049 return LHS.isSigned() ? LHS.ssub_sat(RHS) : LHS.usub_sat(RHS);
13050 });
13051
13052 case X86::BI__builtin_ia32_extract128i256:
13053 case X86::BI__builtin_ia32_vextractf128_pd256:
13054 case X86::BI__builtin_ia32_vextractf128_ps256:
13055 case X86::BI__builtin_ia32_vextractf128_si256: {
13056 APValue SourceVec, SourceImm;
13057 if (!EvaluateAsRValue(Info, E->getArg(0), SourceVec) ||
13058 !EvaluateAsRValue(Info, E->getArg(1), SourceImm))
13059 return false;
13060
13061 if (!SourceVec.isVector())
13062 return false;
13063
13064 const auto *RetVT = E->getType()->castAs<VectorType>();
13065 unsigned RetLen = RetVT->getNumElements();
13066 unsigned Idx = SourceImm.getInt().getZExtValue() & 1;
13067
13068 SmallVector<APValue, 32> ResultElements;
13069 ResultElements.reserve(RetLen);
13070
13071 for (unsigned I = 0; I < RetLen; I++)
13072 ResultElements.push_back(SourceVec.getVectorElt(Idx * RetLen + I));
13073
13074 return Success(APValue(ResultElements.data(), RetLen), E);
13075 }
13076
13077 case clang::X86::BI__builtin_ia32_cvtmask2b128:
13078 case clang::X86::BI__builtin_ia32_cvtmask2b256:
13079 case clang::X86::BI__builtin_ia32_cvtmask2b512:
13080 case clang::X86::BI__builtin_ia32_cvtmask2w128:
13081 case clang::X86::BI__builtin_ia32_cvtmask2w256:
13082 case clang::X86::BI__builtin_ia32_cvtmask2w512:
13083 case clang::X86::BI__builtin_ia32_cvtmask2d128:
13084 case clang::X86::BI__builtin_ia32_cvtmask2d256:
13085 case clang::X86::BI__builtin_ia32_cvtmask2d512:
13086 case clang::X86::BI__builtin_ia32_cvtmask2q128:
13087 case clang::X86::BI__builtin_ia32_cvtmask2q256:
13088 case clang::X86::BI__builtin_ia32_cvtmask2q512: {
13089 assert(E->getNumArgs() == 1);
13090 APSInt Mask;
13091 if (!EvaluateInteger(E->getArg(0), Mask, Info))
13092 return false;
13093
13094 QualType VecTy = E->getType();
13095 const VectorType *VT = VecTy->castAs<VectorType>();
13096 unsigned VectorLen = VT->getNumElements();
13097 QualType ElemTy = VT->getElementType();
13098 unsigned ElemWidth = Info.Ctx.getTypeSize(ElemTy);
13099
13101 for (unsigned I = 0; I != VectorLen; ++I) {
13102 bool BitSet = Mask[I];
13103 APSInt ElemVal(ElemWidth, /*isUnsigned=*/false);
13104 if (BitSet) {
13105 ElemVal.setAllBits();
13106 }
13107 Elems.push_back(APValue(ElemVal));
13108 }
13109 return Success(APValue(Elems.data(), VectorLen), E);
13110 }
13111
13112 case X86::BI__builtin_ia32_extracti32x4_256_mask:
13113 case X86::BI__builtin_ia32_extractf32x4_256_mask:
13114 case X86::BI__builtin_ia32_extracti32x4_mask:
13115 case X86::BI__builtin_ia32_extractf32x4_mask:
13116 case X86::BI__builtin_ia32_extracti32x8_mask:
13117 case X86::BI__builtin_ia32_extractf32x8_mask:
13118 case X86::BI__builtin_ia32_extracti64x2_256_mask:
13119 case X86::BI__builtin_ia32_extractf64x2_256_mask:
13120 case X86::BI__builtin_ia32_extracti64x2_512_mask:
13121 case X86::BI__builtin_ia32_extractf64x2_512_mask:
13122 case X86::BI__builtin_ia32_extracti64x4_mask:
13123 case X86::BI__builtin_ia32_extractf64x4_mask: {
13124 APValue SourceVec, MergeVec;
13125 APSInt Imm, MaskImm;
13126
13127 if (!EvaluateAsRValue(Info, E->getArg(0), SourceVec) ||
13128 !EvaluateInteger(E->getArg(1), Imm, Info) ||
13129 !EvaluateAsRValue(Info, E->getArg(2), MergeVec) ||
13130 !EvaluateInteger(E->getArg(3), MaskImm, Info))
13131 return false;
13132
13133 const auto *RetVT = E->getType()->castAs<VectorType>();
13134 unsigned RetLen = RetVT->getNumElements();
13135
13136 if (!SourceVec.isVector() || !MergeVec.isVector())
13137 return false;
13138 unsigned SrcLen = SourceVec.getVectorLength();
13139 unsigned Lanes = SrcLen / RetLen;
13140 unsigned Lane = static_cast<unsigned>(Imm.getZExtValue() % Lanes);
13141 unsigned Base = Lane * RetLen;
13142
13143 SmallVector<APValue, 32> ResultElements;
13144 ResultElements.reserve(RetLen);
13145 for (unsigned I = 0; I < RetLen; ++I) {
13146 if (MaskImm[I])
13147 ResultElements.push_back(SourceVec.getVectorElt(Base + I));
13148 else
13149 ResultElements.push_back(MergeVec.getVectorElt(I));
13150 }
13151 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13152 }
13153
13154 case clang::X86::BI__builtin_ia32_pavgb128:
13155 case clang::X86::BI__builtin_ia32_pavgw128:
13156 case clang::X86::BI__builtin_ia32_pavgb256:
13157 case clang::X86::BI__builtin_ia32_pavgw256:
13158 case clang::X86::BI__builtin_ia32_pavgb512:
13159 case clang::X86::BI__builtin_ia32_pavgw512:
13160 return EvaluateBinOpExpr(llvm::APIntOps::avgCeilU);
13161
13162 case clang::X86::BI__builtin_ia32_pmulhrsw128:
13163 case clang::X86::BI__builtin_ia32_pmulhrsw256:
13164 case clang::X86::BI__builtin_ia32_pmulhrsw512:
13165 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
13166 return (llvm::APIntOps::mulsExtended(LHS, RHS).ashr(14) + 1)
13167 .extractBits(16, 1);
13168 });
13169
13170 case clang::X86::BI__builtin_ia32_psadbw128:
13171 case clang::X86::BI__builtin_ia32_psadbw256:
13172 case clang::X86::BI__builtin_ia32_psadbw512: {
13173 APValue SourceLHS, SourceRHS;
13174 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
13175 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
13176 return false;
13177
13178 assert(SourceLHS.isVector() && SourceRHS.isVector());
13179 unsigned SourceLen = SourceLHS.getVectorLength();
13180 assert(SourceLen == SourceRHS.getVectorLength());
13181 assert((SourceLen % 8) == 0);
13182
13183 auto *DestTy = E->getType()->castAs<VectorType>();
13184 QualType DestEltTy = DestTy->getElementType();
13185 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
13186 SmallVector<APValue, 8> ResultElements;
13187 ResultElements.reserve(SourceLen / 8);
13188
13189 for (unsigned Lane = 0; Lane != SourceLen; Lane += 8) {
13190 APInt Sum(64, 0);
13191 for (unsigned I = 0; I != 8; ++I) {
13192 APInt LHS = SourceLHS.getVectorElt(Lane + I).getInt().extOrTrunc(8);
13193 APInt RHS = SourceRHS.getVectorElt(Lane + I).getInt().extOrTrunc(8);
13194 Sum += llvm::APIntOps::abdu(LHS, RHS).zext(64);
13195 }
13196 ResultElements.push_back(APValue(APSInt(Sum, DestUnsigned)));
13197 }
13198
13199 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13200 }
13201
13202 case clang::X86::BI__builtin_ia32_pmaddubsw128:
13203 case clang::X86::BI__builtin_ia32_pmaddubsw256:
13204 case clang::X86::BI__builtin_ia32_pmaddubsw512:
13205 case clang::X86::BI__builtin_ia32_pmaddwd128:
13206 case clang::X86::BI__builtin_ia32_pmaddwd256:
13207 case clang::X86::BI__builtin_ia32_pmaddwd512: {
13208 APValue SourceLHS, SourceRHS;
13209 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
13210 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
13211 return false;
13212
13213 auto *DestTy = E->getType()->castAs<VectorType>();
13214 QualType DestEltTy = DestTy->getElementType();
13215 unsigned SourceLen = SourceLHS.getVectorLength();
13216 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
13217 SmallVector<APValue, 4> ResultElements;
13218 ResultElements.reserve(SourceLen / 2);
13219
13220 for (unsigned EltNum = 0; EltNum < SourceLen; EltNum += 2) {
13221 const APSInt &LoLHS = SourceLHS.getVectorElt(EltNum).getInt();
13222 const APSInt &HiLHS = SourceLHS.getVectorElt(EltNum + 1).getInt();
13223 const APSInt &LoRHS = SourceRHS.getVectorElt(EltNum).getInt();
13224 const APSInt &HiRHS = SourceRHS.getVectorElt(EltNum + 1).getInt();
13225 unsigned BitWidth = 2 * LoLHS.getBitWidth();
13226
13227 switch (BuiltinOp) {
13228 case clang::X86::BI__builtin_ia32_pmaddubsw128:
13229 case clang::X86::BI__builtin_ia32_pmaddubsw256:
13230 case clang::X86::BI__builtin_ia32_pmaddubsw512:
13231 ResultElements.push_back(APValue(
13232 APSInt((LoLHS.zext(BitWidth) * LoRHS.sext(BitWidth))
13233 .sadd_sat((HiLHS.zext(BitWidth) * HiRHS.sext(BitWidth))),
13234 DestUnsigned)));
13235 break;
13236 case clang::X86::BI__builtin_ia32_pmaddwd128:
13237 case clang::X86::BI__builtin_ia32_pmaddwd256:
13238 case clang::X86::BI__builtin_ia32_pmaddwd512:
13239 ResultElements.push_back(
13240 APValue(APSInt((LoLHS.sext(BitWidth) * LoRHS.sext(BitWidth)) +
13241 (HiLHS.sext(BitWidth) * HiRHS.sext(BitWidth)),
13242 DestUnsigned)));
13243 break;
13244 }
13245 }
13246
13247 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13248 }
13249
13250 case clang::X86::BI__builtin_ia32_bmacor16x16x16_v16hi:
13251 case clang::X86::BI__builtin_ia32_bmacor16x16x16_v32hi:
13252 case clang::X86::BI__builtin_ia32_bmacxor16x16x16_v16hi:
13253 case clang::X86::BI__builtin_ia32_bmacxor16x16x16_v32hi: {
13254 // Bit Matrix Multiply and Accumulate (AVX512BMM). Each 256-bit lane holds
13255 // a 16x16 bit matrix as 16 x i16 elements; element i is row i and bit j of
13256 // that element is entry [i][j]. The accumulator (third argument, src1 in
13257 // the AMD ISA) provides the initial value of each result bit, into which
13258 // the bit-matrix product of the first two arguments (src2 * src3) is
13259 // reduced with OR (vbmacor) or XOR (vbmacxor):
13260 // for i in 0..15, j in 0..15:
13261 // bit = C[16*i+j]
13262 // for k in 0..15: bit OP= A[16*i+k] & B[16*k+j]
13263 // dest[16*i+j] = bit
13264 APValue SourceA, SourceB, SourceC;
13265 if (!EvaluateAsRValue(Info, E->getArg(0), SourceA) ||
13266 !EvaluateAsRValue(Info, E->getArg(1), SourceB) ||
13267 !EvaluateAsRValue(Info, E->getArg(2), SourceC))
13268 return false;
13269
13270 bool IsXor = E->getBuiltinCallee() ==
13271 clang::X86::BI__builtin_ia32_bmacxor16x16x16_v16hi ||
13272 E->getBuiltinCallee() ==
13273 clang::X86::BI__builtin_ia32_bmacxor16x16x16_v32hi;
13274
13275 unsigned SourceLen = SourceA.getVectorLength();
13276 assert(SourceLen % 16 == 0 && "BMM operates on 256-bit lanes of 16 x i16");
13277 auto *DestTy = E->getType()->castAs<VectorType>();
13278 QualType DestEltTy = DestTy->getElementType();
13279 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
13280
13281 SmallVector<APValue, 32> ResultElements(SourceLen);
13282 for (unsigned Lane = 0; Lane != SourceLen; Lane += 16) {
13283 for (unsigned I = 0; I != 16; ++I) {
13284 uint16_t A =
13285 (uint16_t)SourceA.getVectorElt(Lane + I).getInt().getZExtValue();
13286 uint16_t Dst =
13287 (uint16_t)SourceC.getVectorElt(Lane + I).getInt().getZExtValue();
13288 for (unsigned J = 0; J != 16; ++J) {
13289 // Seed the reduction with the accumulator bit, then fold in each
13290 // product term with the same operator (OR for vbmacor, XOR for
13291 // vbmacxor).
13292 unsigned Bit = (Dst >> J) & 1u;
13293 for (unsigned K = 0; K != 16; ++K) {
13294 uint16_t B = (uint16_t)SourceB.getVectorElt(Lane + K)
13295 .getInt()
13296 .getZExtValue();
13297 unsigned Product = ((A >> K) & 1u) & ((B >> J) & 1u);
13298 Bit = IsXor ? (Bit ^ Product) : (Bit | Product);
13299 }
13300 Dst = (Dst & ~(uint16_t(1) << J)) | (uint16_t(Bit) << J);
13301 }
13302 ResultElements[Lane + I] =
13303 APValue(APSInt(APInt(16, Dst), DestUnsigned));
13304 }
13305 }
13306 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13307 }
13308
13309 case clang::X86::BI__builtin_ia32_dbpsadbw128:
13310 case clang::X86::BI__builtin_ia32_dbpsadbw256:
13311 case clang::X86::BI__builtin_ia32_dbpsadbw512: {
13312 APValue SourceA, SourceB, SourceImm;
13313 if (!EvaluateAsRValue(Info, E->getArg(0), SourceA) ||
13314 !EvaluateAsRValue(Info, E->getArg(1), SourceB) ||
13315 !EvaluateAsRValue(Info, E->getArg(2), SourceImm))
13316 return false;
13317
13318 unsigned SourceLen = SourceA.getVectorLength();
13319 constexpr unsigned LaneSize = 16; // 128-bit lane = 16 bytes
13320 unsigned Imm = SourceImm.getInt().getZExtValue();
13321
13322 auto *DestTy = E->getType()->castAs<VectorType>();
13323 QualType DestEltTy = DestTy->getElementType();
13324 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
13325 SmallVector<APValue, 32> ResultElements;
13326 ResultElements.reserve(SourceLen / 2);
13327
13328 // Phase 1: Shuffle SourceB using all four 2-bit fields of imm8.
13329 // Within each 128-bit lane, for group j (0..3), select a 4-byte block
13330 // from SourceB based on bits [2*j+1:2*j] of imm8.
13331 SmallVector<uint8_t, 64> Shuffled(SourceLen);
13332 for (unsigned I = 0; I < SourceLen; I += LaneSize) {
13333 for (unsigned J = 0; J < 4; ++J) {
13334 unsigned Part = (Imm >> (2 * J)) & 3;
13335 for (unsigned K = 0; K < 4; ++K) {
13336 Shuffled[I + 4 * J + K] = static_cast<uint8_t>(
13337 SourceB.getVectorElt(I + 4 * Part + K).getInt().getZExtValue());
13338 }
13339 }
13340 }
13341
13342 // Phase 2: Sliding SAD computation.
13343 // For every group of 4 output u16 values, compute absolute differences
13344 // using overlapping windows into SourceA and the shuffled array.
13345 unsigned Size = SourceLen / 2; // number of output u16 elements
13346 for (unsigned I = 0; I < Size; I += 4) {
13347 unsigned Sad[4] = {0, 0, 0, 0};
13348 for (unsigned J = 0; J < 4; ++J) {
13349 uint8_t A1 = static_cast<uint8_t>(
13350 SourceA.getVectorElt(2 * I + J).getInt().getZExtValue());
13351 uint8_t A2 = static_cast<uint8_t>(
13352 SourceA.getVectorElt(2 * I + J + 4).getInt().getZExtValue());
13353 uint8_t B0 = Shuffled[2 * I + J];
13354 uint8_t B1 = Shuffled[2 * I + J + 1];
13355 uint8_t B2 = Shuffled[2 * I + J + 2];
13356 uint8_t B3 = Shuffled[2 * I + J + 3];
13357 Sad[0] += (A1 > B0) ? (A1 - B0) : (B0 - A1);
13358 Sad[1] += (A1 > B1) ? (A1 - B1) : (B1 - A1);
13359 Sad[2] += (A2 > B2) ? (A2 - B2) : (B2 - A2);
13360 Sad[3] += (A2 > B3) ? (A2 - B3) : (B3 - A2);
13361 }
13362 for (unsigned R = 0; R < 4; ++R)
13363 ResultElements.push_back(
13364 APValue(APSInt(APInt(16, Sad[R]), DestUnsigned)));
13365 }
13366
13367 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13368 }
13369
13370 case clang::X86::BI__builtin_ia32_mpsadbw128:
13371 case clang::X86::BI__builtin_ia32_mpsadbw256: {
13372 APValue SourceA, SourceB;
13373 APSInt SourceImm;
13374 if (!EvaluateVector(E->getArg(0), SourceA, Info) ||
13375 !EvaluateVector(E->getArg(1), SourceB, Info) ||
13376 !EvaluateInteger(E->getArg(2), SourceImm, Info))
13377 return false;
13378 unsigned SourceLen = SourceA.getVectorLength();
13379 constexpr unsigned LaneSize = 16;
13380 assert((SourceLen == LaneSize || SourceLen == 2 * LaneSize) &&
13381 "MPSADBW operates on 128-bit or 256-bit vectors");
13382 unsigned NumLanes = SourceLen / LaneSize;
13383 unsigned Imm = SourceImm.getZExtValue();
13384
13385 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
13386 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
13387 SmallVector<APValue, 16> ResultElements;
13388 ResultElements.reserve(SourceLen / 2);
13389
13390 for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
13391 unsigned Ctrl = (Imm >> (3 * Lane)) & 0x7;
13392 unsigned AOff = ((Ctrl >> 2) & 1) * 4;
13393 unsigned BOff = (Ctrl & 3) * 4;
13394 for (unsigned J = 0; J != 8; ++J) {
13395 uint16_t Sad = 0;
13396 for (unsigned K = 0; K != 4; ++K) {
13397 uint8_t A = static_cast<uint8_t>(
13398 SourceA.getVectorElt(Lane * LaneSize + AOff + J + K)
13399 .getInt()
13400 .getZExtValue());
13401 uint8_t B = static_cast<uint8_t>(
13402 SourceB.getVectorElt(Lane * LaneSize + BOff + K)
13403 .getInt()
13404 .getZExtValue());
13405 Sad += (A > B) ? (A - B) : (B - A);
13406 }
13407 ResultElements.push_back(APValue(APSInt(APInt(16, Sad), DestUnsigned)));
13408 }
13409 }
13410 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13411 }
13412
13413 case clang::X86::BI__builtin_ia32_pmulhuw128:
13414 case clang::X86::BI__builtin_ia32_pmulhuw256:
13415 case clang::X86::BI__builtin_ia32_pmulhuw512:
13416 return EvaluateBinOpExpr(llvm::APIntOps::mulhu);
13417
13418 case clang::X86::BI__builtin_ia32_pmulhw128:
13419 case clang::X86::BI__builtin_ia32_pmulhw256:
13420 case clang::X86::BI__builtin_ia32_pmulhw512:
13421 return EvaluateBinOpExpr(llvm::APIntOps::mulhs);
13422
13423 case clang::X86::BI__builtin_ia32_psllv2di:
13424 case clang::X86::BI__builtin_ia32_psllv4di:
13425 case clang::X86::BI__builtin_ia32_psllv4si:
13426 case clang::X86::BI__builtin_ia32_psllv8di:
13427 case clang::X86::BI__builtin_ia32_psllv8hi:
13428 case clang::X86::BI__builtin_ia32_psllv8si:
13429 case clang::X86::BI__builtin_ia32_psllv16hi:
13430 case clang::X86::BI__builtin_ia32_psllv16si:
13431 case clang::X86::BI__builtin_ia32_psllv32hi:
13432 case clang::X86::BI__builtin_ia32_psllwi128:
13433 case clang::X86::BI__builtin_ia32_pslldi128:
13434 case clang::X86::BI__builtin_ia32_psllqi128:
13435 case clang::X86::BI__builtin_ia32_psllwi256:
13436 case clang::X86::BI__builtin_ia32_pslldi256:
13437 case clang::X86::BI__builtin_ia32_psllqi256:
13438 case clang::X86::BI__builtin_ia32_psllwi512:
13439 case clang::X86::BI__builtin_ia32_pslldi512:
13440 case clang::X86::BI__builtin_ia32_psllqi512:
13441 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
13442 if (RHS.uge(LHS.getBitWidth())) {
13443 return APInt::getZero(LHS.getBitWidth());
13444 }
13445 return LHS.shl(RHS.getZExtValue());
13446 });
13447
13448 case clang::X86::BI__builtin_ia32_psrav4si:
13449 case clang::X86::BI__builtin_ia32_psrav8di:
13450 case clang::X86::BI__builtin_ia32_psrav8hi:
13451 case clang::X86::BI__builtin_ia32_psrav8si:
13452 case clang::X86::BI__builtin_ia32_psrav16hi:
13453 case clang::X86::BI__builtin_ia32_psrav16si:
13454 case clang::X86::BI__builtin_ia32_psrav32hi:
13455 case clang::X86::BI__builtin_ia32_psravq128:
13456 case clang::X86::BI__builtin_ia32_psravq256:
13457 case clang::X86::BI__builtin_ia32_psrawi128:
13458 case clang::X86::BI__builtin_ia32_psradi128:
13459 case clang::X86::BI__builtin_ia32_psraqi128:
13460 case clang::X86::BI__builtin_ia32_psrawi256:
13461 case clang::X86::BI__builtin_ia32_psradi256:
13462 case clang::X86::BI__builtin_ia32_psraqi256:
13463 case clang::X86::BI__builtin_ia32_psrawi512:
13464 case clang::X86::BI__builtin_ia32_psradi512:
13465 case clang::X86::BI__builtin_ia32_psraqi512:
13466 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
13467 if (RHS.uge(LHS.getBitWidth())) {
13468 return LHS.ashr(LHS.getBitWidth() - 1);
13469 }
13470 return LHS.ashr(RHS.getZExtValue());
13471 });
13472
13473 case clang::X86::BI__builtin_ia32_psrlv2di:
13474 case clang::X86::BI__builtin_ia32_psrlv4di:
13475 case clang::X86::BI__builtin_ia32_psrlv4si:
13476 case clang::X86::BI__builtin_ia32_psrlv8di:
13477 case clang::X86::BI__builtin_ia32_psrlv8hi:
13478 case clang::X86::BI__builtin_ia32_psrlv8si:
13479 case clang::X86::BI__builtin_ia32_psrlv16hi:
13480 case clang::X86::BI__builtin_ia32_psrlv16si:
13481 case clang::X86::BI__builtin_ia32_psrlv32hi:
13482 case clang::X86::BI__builtin_ia32_psrlwi128:
13483 case clang::X86::BI__builtin_ia32_psrldi128:
13484 case clang::X86::BI__builtin_ia32_psrlqi128:
13485 case clang::X86::BI__builtin_ia32_psrlwi256:
13486 case clang::X86::BI__builtin_ia32_psrldi256:
13487 case clang::X86::BI__builtin_ia32_psrlqi256:
13488 case clang::X86::BI__builtin_ia32_psrlwi512:
13489 case clang::X86::BI__builtin_ia32_psrldi512:
13490 case clang::X86::BI__builtin_ia32_psrlqi512:
13491 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
13492 if (RHS.uge(LHS.getBitWidth())) {
13493 return APInt::getZero(LHS.getBitWidth());
13494 }
13495 return LHS.lshr(RHS.getZExtValue());
13496 });
13497 case X86::BI__builtin_ia32_packsswb128:
13498 case X86::BI__builtin_ia32_packsswb256:
13499 case X86::BI__builtin_ia32_packsswb512:
13500 case X86::BI__builtin_ia32_packssdw128:
13501 case X86::BI__builtin_ia32_packssdw256:
13502 case X86::BI__builtin_ia32_packssdw512:
13503 return evalPackBuiltin(E, Info, Result, [](const APSInt &Src) {
13504 return APSInt(Src).truncSSat(Src.getBitWidth() / 2);
13505 });
13506 case X86::BI__builtin_ia32_packusdw128:
13507 case X86::BI__builtin_ia32_packusdw256:
13508 case X86::BI__builtin_ia32_packusdw512:
13509 case X86::BI__builtin_ia32_packuswb128:
13510 case X86::BI__builtin_ia32_packuswb256:
13511 case X86::BI__builtin_ia32_packuswb512:
13512 return evalPackBuiltin(E, Info, Result, [](const APSInt &Src) {
13513 return APSInt(Src).truncSSatU(Src.getBitWidth() / 2);
13514 });
13515 case clang::X86::BI__builtin_ia32_selectss_128:
13516 return EvalSelectScalar(4);
13517 case clang::X86::BI__builtin_ia32_selectsd_128:
13518 return EvalSelectScalar(2);
13519 case clang::X86::BI__builtin_ia32_selectsh_128:
13520 case clang::X86::BI__builtin_ia32_selectsbf_128:
13521 return EvalSelectScalar(8);
13522 case clang::X86::BI__builtin_ia32_pmuldq128:
13523 case clang::X86::BI__builtin_ia32_pmuldq256:
13524 case clang::X86::BI__builtin_ia32_pmuldq512:
13525 case clang::X86::BI__builtin_ia32_pmuludq128:
13526 case clang::X86::BI__builtin_ia32_pmuludq256:
13527 case clang::X86::BI__builtin_ia32_pmuludq512: {
13528 APValue SourceLHS, SourceRHS;
13529 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
13530 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
13531 return false;
13532
13533 unsigned SourceLen = SourceLHS.getVectorLength();
13534 SmallVector<APValue, 4> ResultElements;
13535 ResultElements.reserve(SourceLen / 2);
13536
13537 for (unsigned EltNum = 0; EltNum < SourceLen; EltNum += 2) {
13538 APSInt LHS = SourceLHS.getVectorElt(EltNum).getInt();
13539 APSInt RHS = SourceRHS.getVectorElt(EltNum).getInt();
13540
13541 switch (BuiltinOp) {
13542 case clang::X86::BI__builtin_ia32_pmuludq128:
13543 case clang::X86::BI__builtin_ia32_pmuludq256:
13544 case clang::X86::BI__builtin_ia32_pmuludq512:
13545 ResultElements.push_back(
13546 APValue(APSInt(llvm::APIntOps::muluExtended(LHS, RHS), true)));
13547 break;
13548 case clang::X86::BI__builtin_ia32_pmuldq128:
13549 case clang::X86::BI__builtin_ia32_pmuldq256:
13550 case clang::X86::BI__builtin_ia32_pmuldq512:
13551 ResultElements.push_back(
13552 APValue(APSInt(llvm::APIntOps::mulsExtended(LHS, RHS), false)));
13553 break;
13554 }
13555 }
13556
13557 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13558 }
13559
13560 case X86::BI__builtin_ia32_vpmadd52luq128:
13561 case X86::BI__builtin_ia32_vpmadd52luq256:
13562 case X86::BI__builtin_ia32_vpmadd52luq512: {
13563 APValue A, B, C;
13564 if (!EvaluateAsRValue(Info, E->getArg(0), A) ||
13565 !EvaluateAsRValue(Info, E->getArg(1), B) ||
13566 !EvaluateAsRValue(Info, E->getArg(2), C))
13567 return false;
13568
13569 unsigned ALen = A.getVectorLength();
13570 SmallVector<APValue, 4> ResultElements;
13571 ResultElements.reserve(ALen);
13572
13573 for (unsigned EltNum = 0; EltNum < ALen; EltNum += 1) {
13574 APInt AElt = A.getVectorElt(EltNum).getInt();
13575 APInt BElt = B.getVectorElt(EltNum).getInt().trunc(52);
13576 APInt CElt = C.getVectorElt(EltNum).getInt().trunc(52);
13577 APSInt ResElt(AElt + (BElt * CElt).zext(64), false);
13578 ResultElements.push_back(APValue(ResElt));
13579 }
13580
13581 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13582 }
13583 case X86::BI__builtin_ia32_vpmadd52huq128:
13584 case X86::BI__builtin_ia32_vpmadd52huq256:
13585 case X86::BI__builtin_ia32_vpmadd52huq512: {
13586 APValue A, B, C;
13587 if (!EvaluateAsRValue(Info, E->getArg(0), A) ||
13588 !EvaluateAsRValue(Info, E->getArg(1), B) ||
13589 !EvaluateAsRValue(Info, E->getArg(2), C))
13590 return false;
13591
13592 unsigned ALen = A.getVectorLength();
13593 SmallVector<APValue, 4> ResultElements;
13594 ResultElements.reserve(ALen);
13595
13596 for (unsigned EltNum = 0; EltNum < ALen; EltNum += 1) {
13597 APInt AElt = A.getVectorElt(EltNum).getInt();
13598 APInt BElt = B.getVectorElt(EltNum).getInt().trunc(52);
13599 APInt CElt = C.getVectorElt(EltNum).getInt().trunc(52);
13600 APSInt ResElt(AElt + llvm::APIntOps::mulhu(BElt, CElt).zext(64), false);
13601 ResultElements.push_back(APValue(ResElt));
13602 }
13603
13604 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13605 }
13606
13607 case clang::X86::BI__builtin_ia32_vprotbi:
13608 case clang::X86::BI__builtin_ia32_vprotdi:
13609 case clang::X86::BI__builtin_ia32_vprotqi:
13610 case clang::X86::BI__builtin_ia32_vprotwi:
13611 case clang::X86::BI__builtin_ia32_prold128:
13612 case clang::X86::BI__builtin_ia32_prold256:
13613 case clang::X86::BI__builtin_ia32_prold512:
13614 case clang::X86::BI__builtin_ia32_prolq128:
13615 case clang::X86::BI__builtin_ia32_prolq256:
13616 case clang::X86::BI__builtin_ia32_prolq512:
13617 return EvaluateBinOpExpr(
13618 [](const APSInt &LHS, const APSInt &RHS) { return LHS.rotl(RHS); });
13619
13620 case clang::X86::BI__builtin_ia32_prord128:
13621 case clang::X86::BI__builtin_ia32_prord256:
13622 case clang::X86::BI__builtin_ia32_prord512:
13623 case clang::X86::BI__builtin_ia32_prorq128:
13624 case clang::X86::BI__builtin_ia32_prorq256:
13625 case clang::X86::BI__builtin_ia32_prorq512:
13626 return EvaluateBinOpExpr(
13627 [](const APSInt &LHS, const APSInt &RHS) { return LHS.rotr(RHS); });
13628
13629 case Builtin::BI__builtin_elementwise_max:
13630 case Builtin::BI__builtin_elementwise_min: {
13631 APValue SourceLHS, SourceRHS;
13632 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
13633 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
13634 return false;
13635
13636 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
13637
13638 if (!DestEltTy->isIntegerType())
13639 return false;
13640
13641 unsigned SourceLen = SourceLHS.getVectorLength();
13642 SmallVector<APValue, 4> ResultElements;
13643 ResultElements.reserve(SourceLen);
13644
13645 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
13646 APSInt LHS = SourceLHS.getVectorElt(EltNum).getInt();
13647 APSInt RHS = SourceRHS.getVectorElt(EltNum).getInt();
13648 switch (BuiltinOp) {
13649 case Builtin::BI__builtin_elementwise_max:
13650 ResultElements.push_back(
13651 APValue(APSInt(std::max(LHS, RHS),
13652 DestEltTy->isUnsignedIntegerOrEnumerationType())));
13653 break;
13654 case Builtin::BI__builtin_elementwise_min:
13655 ResultElements.push_back(
13656 APValue(APSInt(std::min(LHS, RHS),
13657 DestEltTy->isUnsignedIntegerOrEnumerationType())));
13658 break;
13659 }
13660 }
13661
13662 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13663 }
13664 case X86::BI__builtin_ia32_vpshldd128:
13665 case X86::BI__builtin_ia32_vpshldd256:
13666 case X86::BI__builtin_ia32_vpshldd512:
13667 case X86::BI__builtin_ia32_vpshldq128:
13668 case X86::BI__builtin_ia32_vpshldq256:
13669 case X86::BI__builtin_ia32_vpshldq512:
13670 case X86::BI__builtin_ia32_vpshldw128:
13671 case X86::BI__builtin_ia32_vpshldw256:
13672 case X86::BI__builtin_ia32_vpshldw512: {
13673 APValue SourceHi, SourceLo, SourceAmt;
13674 if (!EvaluateAsRValue(Info, E->getArg(0), SourceHi) ||
13675 !EvaluateAsRValue(Info, E->getArg(1), SourceLo) ||
13676 !EvaluateAsRValue(Info, E->getArg(2), SourceAmt))
13677 return false;
13678
13679 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
13680 unsigned SourceLen = SourceHi.getVectorLength();
13681 SmallVector<APValue, 32> ResultElements;
13682 ResultElements.reserve(SourceLen);
13683
13684 APInt Amt = SourceAmt.getInt();
13685 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
13686 APInt Hi = SourceHi.getVectorElt(EltNum).getInt();
13687 APInt Lo = SourceLo.getVectorElt(EltNum).getInt();
13688 APInt R = llvm::APIntOps::fshl(Hi, Lo, Amt);
13689 ResultElements.push_back(
13691 }
13692
13693 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13694 }
13695 case X86::BI__builtin_ia32_vpshrdd128:
13696 case X86::BI__builtin_ia32_vpshrdd256:
13697 case X86::BI__builtin_ia32_vpshrdd512:
13698 case X86::BI__builtin_ia32_vpshrdq128:
13699 case X86::BI__builtin_ia32_vpshrdq256:
13700 case X86::BI__builtin_ia32_vpshrdq512:
13701 case X86::BI__builtin_ia32_vpshrdw128:
13702 case X86::BI__builtin_ia32_vpshrdw256:
13703 case X86::BI__builtin_ia32_vpshrdw512: {
13704 // NOTE: Reversed Hi/Lo operands.
13705 APValue SourceHi, SourceLo, SourceAmt;
13706 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLo) ||
13707 !EvaluateAsRValue(Info, E->getArg(1), SourceHi) ||
13708 !EvaluateAsRValue(Info, E->getArg(2), SourceAmt))
13709 return false;
13710
13711 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
13712 unsigned SourceLen = SourceHi.getVectorLength();
13713 SmallVector<APValue, 32> ResultElements;
13714 ResultElements.reserve(SourceLen);
13715
13716 APInt Amt = SourceAmt.getInt();
13717 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
13718 APInt Hi = SourceHi.getVectorElt(EltNum).getInt();
13719 APInt Lo = SourceLo.getVectorElt(EltNum).getInt();
13720 APInt R = llvm::APIntOps::fshr(Hi, Lo, Amt);
13721 ResultElements.push_back(
13723 }
13724
13725 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13726 }
13727 case X86::BI__builtin_ia32_compressdf128_mask:
13728 case X86::BI__builtin_ia32_compressdf256_mask:
13729 case X86::BI__builtin_ia32_compressdf512_mask:
13730 case X86::BI__builtin_ia32_compressdi128_mask:
13731 case X86::BI__builtin_ia32_compressdi256_mask:
13732 case X86::BI__builtin_ia32_compressdi512_mask:
13733 case X86::BI__builtin_ia32_compresshi128_mask:
13734 case X86::BI__builtin_ia32_compresshi256_mask:
13735 case X86::BI__builtin_ia32_compresshi512_mask:
13736 case X86::BI__builtin_ia32_compressqi128_mask:
13737 case X86::BI__builtin_ia32_compressqi256_mask:
13738 case X86::BI__builtin_ia32_compressqi512_mask:
13739 case X86::BI__builtin_ia32_compresssf128_mask:
13740 case X86::BI__builtin_ia32_compresssf256_mask:
13741 case X86::BI__builtin_ia32_compresssf512_mask:
13742 case X86::BI__builtin_ia32_compresssi128_mask:
13743 case X86::BI__builtin_ia32_compresssi256_mask:
13744 case X86::BI__builtin_ia32_compresssi512_mask: {
13745 APValue Source, Passthru;
13746 if (!EvaluateAsRValue(Info, E->getArg(0), Source) ||
13747 !EvaluateAsRValue(Info, E->getArg(1), Passthru))
13748 return false;
13749 APSInt Mask;
13750 if (!EvaluateInteger(E->getArg(2), Mask, Info))
13751 return false;
13752
13753 unsigned NumElts = Source.getVectorLength();
13754 SmallVector<APValue, 64> ResultElements;
13755 ResultElements.reserve(NumElts);
13756
13757 for (unsigned I = 0; I != NumElts; ++I) {
13758 if (Mask[I])
13759 ResultElements.push_back(Source.getVectorElt(I));
13760 }
13761 for (unsigned I = ResultElements.size(); I != NumElts; ++I) {
13762 ResultElements.push_back(Passthru.getVectorElt(I));
13763 }
13764
13765 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13766 }
13767 case X86::BI__builtin_ia32_expanddf128_mask:
13768 case X86::BI__builtin_ia32_expanddf256_mask:
13769 case X86::BI__builtin_ia32_expanddf512_mask:
13770 case X86::BI__builtin_ia32_expanddi128_mask:
13771 case X86::BI__builtin_ia32_expanddi256_mask:
13772 case X86::BI__builtin_ia32_expanddi512_mask:
13773 case X86::BI__builtin_ia32_expandhi128_mask:
13774 case X86::BI__builtin_ia32_expandhi256_mask:
13775 case X86::BI__builtin_ia32_expandhi512_mask:
13776 case X86::BI__builtin_ia32_expandqi128_mask:
13777 case X86::BI__builtin_ia32_expandqi256_mask:
13778 case X86::BI__builtin_ia32_expandqi512_mask:
13779 case X86::BI__builtin_ia32_expandsf128_mask:
13780 case X86::BI__builtin_ia32_expandsf256_mask:
13781 case X86::BI__builtin_ia32_expandsf512_mask:
13782 case X86::BI__builtin_ia32_expandsi128_mask:
13783 case X86::BI__builtin_ia32_expandsi256_mask:
13784 case X86::BI__builtin_ia32_expandsi512_mask: {
13785 APValue Source, Passthru;
13786 if (!EvaluateAsRValue(Info, E->getArg(0), Source) ||
13787 !EvaluateAsRValue(Info, E->getArg(1), Passthru))
13788 return false;
13789 APSInt Mask;
13790 if (!EvaluateInteger(E->getArg(2), Mask, Info))
13791 return false;
13792
13793 unsigned NumElts = Source.getVectorLength();
13794 SmallVector<APValue, 64> ResultElements;
13795 ResultElements.reserve(NumElts);
13796
13797 unsigned SourceIdx = 0;
13798 for (unsigned I = 0; I != NumElts; ++I) {
13799 if (Mask[I])
13800 ResultElements.push_back(Source.getVectorElt(SourceIdx++));
13801 else
13802 ResultElements.push_back(Passthru.getVectorElt(I));
13803 }
13804 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13805 }
13806 case X86::BI__builtin_ia32_vpconflictsi_128:
13807 case X86::BI__builtin_ia32_vpconflictsi_256:
13808 case X86::BI__builtin_ia32_vpconflictsi_512:
13809 case X86::BI__builtin_ia32_vpconflictdi_128:
13810 case X86::BI__builtin_ia32_vpconflictdi_256:
13811 case X86::BI__builtin_ia32_vpconflictdi_512: {
13812 APValue Source;
13813
13814 if (!EvaluateAsRValue(Info, E->getArg(0), Source))
13815 return false;
13816
13817 unsigned SourceLen = Source.getVectorLength();
13818 SmallVector<APValue, 32> ResultElements;
13819 ResultElements.reserve(SourceLen);
13820
13821 const auto *VecT = E->getType()->castAs<VectorType>();
13822 bool DestUnsigned =
13823 VecT->getElementType()->isUnsignedIntegerOrEnumerationType();
13824
13825 for (unsigned I = 0; I != SourceLen; ++I) {
13826 const APValue &EltI = Source.getVectorElt(I);
13827
13828 APInt ConflictMask(EltI.getInt().getBitWidth(), 0);
13829 for (unsigned J = 0; J != I; ++J) {
13830 const APValue &EltJ = Source.getVectorElt(J);
13831 ConflictMask.setBitVal(J, EltI.getInt() == EltJ.getInt());
13832 }
13833 ResultElements.push_back(APValue(APSInt(ConflictMask, DestUnsigned)));
13834 }
13835 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13836 }
13837 case X86::BI__builtin_ia32_blendpd:
13838 case X86::BI__builtin_ia32_blendpd256:
13839 case X86::BI__builtin_ia32_blendps:
13840 case X86::BI__builtin_ia32_blendps256:
13841 case X86::BI__builtin_ia32_pblendw128:
13842 case X86::BI__builtin_ia32_pblendw256:
13843 case X86::BI__builtin_ia32_pblendd128:
13844 case X86::BI__builtin_ia32_pblendd256: {
13845 APValue SourceF, SourceT, SourceC;
13846 if (!EvaluateAsRValue(Info, E->getArg(0), SourceF) ||
13847 !EvaluateAsRValue(Info, E->getArg(1), SourceT) ||
13848 !EvaluateAsRValue(Info, E->getArg(2), SourceC))
13849 return false;
13850
13851 const APInt &C = SourceC.getInt();
13852 unsigned SourceLen = SourceF.getVectorLength();
13853 SmallVector<APValue, 32> ResultElements;
13854 ResultElements.reserve(SourceLen);
13855 for (unsigned EltNum = 0; EltNum != SourceLen; ++EltNum) {
13856 const APValue &F = SourceF.getVectorElt(EltNum);
13857 const APValue &T = SourceT.getVectorElt(EltNum);
13858 ResultElements.push_back(C[EltNum % 8] ? T : F);
13859 }
13860
13861 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13862 }
13863
13864 case X86::BI__builtin_ia32_psignb128:
13865 case X86::BI__builtin_ia32_psignb256:
13866 case X86::BI__builtin_ia32_psignw128:
13867 case X86::BI__builtin_ia32_psignw256:
13868 case X86::BI__builtin_ia32_psignd128:
13869 case X86::BI__builtin_ia32_psignd256:
13870 return EvaluateBinOpExpr([](const APInt &AElem, const APInt &BElem) {
13871 if (BElem.isZero())
13872 return APInt::getZero(AElem.getBitWidth());
13873 if (BElem.isNegative())
13874 return -AElem;
13875 return AElem;
13876 });
13877
13878 case X86::BI__builtin_ia32_blendvpd:
13879 case X86::BI__builtin_ia32_blendvpd256:
13880 case X86::BI__builtin_ia32_blendvps:
13881 case X86::BI__builtin_ia32_blendvps256:
13882 case X86::BI__builtin_ia32_pblendvb128:
13883 case X86::BI__builtin_ia32_pblendvb256: {
13884 // SSE blendv by mask signbit: "Result = C[] < 0 ? T[] : F[]".
13885 APValue SourceF, SourceT, SourceC;
13886 if (!EvaluateAsRValue(Info, E->getArg(0), SourceF) ||
13887 !EvaluateAsRValue(Info, E->getArg(1), SourceT) ||
13888 !EvaluateAsRValue(Info, E->getArg(2), SourceC))
13889 return false;
13890
13891 unsigned SourceLen = SourceF.getVectorLength();
13892 SmallVector<APValue, 32> ResultElements;
13893 ResultElements.reserve(SourceLen);
13894
13895 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
13896 const APValue &F = SourceF.getVectorElt(EltNum);
13897 const APValue &T = SourceT.getVectorElt(EltNum);
13898 const APValue &C = SourceC.getVectorElt(EltNum);
13899 APInt M = C.isInt() ? (APInt)C.getInt() : C.getFloat().bitcastToAPInt();
13900 ResultElements.push_back(M.isNegative() ? T : F);
13901 }
13902
13903 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13904 }
13905 case X86::BI__builtin_ia32_selectb_128:
13906 case X86::BI__builtin_ia32_selectb_256:
13907 case X86::BI__builtin_ia32_selectb_512:
13908 case X86::BI__builtin_ia32_selectw_128:
13909 case X86::BI__builtin_ia32_selectw_256:
13910 case X86::BI__builtin_ia32_selectw_512:
13911 case X86::BI__builtin_ia32_selectd_128:
13912 case X86::BI__builtin_ia32_selectd_256:
13913 case X86::BI__builtin_ia32_selectd_512:
13914 case X86::BI__builtin_ia32_selectq_128:
13915 case X86::BI__builtin_ia32_selectq_256:
13916 case X86::BI__builtin_ia32_selectq_512:
13917 case X86::BI__builtin_ia32_selectph_128:
13918 case X86::BI__builtin_ia32_selectph_256:
13919 case X86::BI__builtin_ia32_selectph_512:
13920 case X86::BI__builtin_ia32_selectpbf_128:
13921 case X86::BI__builtin_ia32_selectpbf_256:
13922 case X86::BI__builtin_ia32_selectpbf_512:
13923 case X86::BI__builtin_ia32_selectps_128:
13924 case X86::BI__builtin_ia32_selectps_256:
13925 case X86::BI__builtin_ia32_selectps_512:
13926 case X86::BI__builtin_ia32_selectpd_128:
13927 case X86::BI__builtin_ia32_selectpd_256:
13928 case X86::BI__builtin_ia32_selectpd_512: {
13929 // AVX512 predicated move: "Result = Mask[] ? LHS[] : RHS[]".
13930 APValue SourceMask, SourceLHS, SourceRHS;
13931 if (!EvaluateAsRValue(Info, E->getArg(0), SourceMask) ||
13932 !EvaluateAsRValue(Info, E->getArg(1), SourceLHS) ||
13933 !EvaluateAsRValue(Info, E->getArg(2), SourceRHS))
13934 return false;
13935
13936 APSInt Mask = SourceMask.getInt();
13937 unsigned SourceLen = SourceLHS.getVectorLength();
13938 SmallVector<APValue, 4> ResultElements;
13939 ResultElements.reserve(SourceLen);
13940
13941 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
13942 const APValue &LHS = SourceLHS.getVectorElt(EltNum);
13943 const APValue &RHS = SourceRHS.getVectorElt(EltNum);
13944 ResultElements.push_back(Mask[EltNum] ? LHS : RHS);
13945 }
13946
13947 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13948 }
13949
13950 case X86::BI__builtin_ia32_cvtsd2ss: {
13951 APValue VecA, VecB;
13952 if (!EvaluateAsRValue(Info, E->getArg(0), VecA) ||
13953 !EvaluateAsRValue(Info, E->getArg(1), VecB))
13954 return false;
13955
13956 SmallVector<APValue, 4> Elements;
13957
13958 APValue ResultVal;
13959 if (!ConvertDoubleToFloatStrict(Info, E, VecB.getVectorElt(0).getFloat(),
13960 ResultVal))
13961 return false;
13962
13963 Elements.push_back(ResultVal);
13964
13965 unsigned NumEltsA = VecA.getVectorLength();
13966 for (unsigned I = 1; I < NumEltsA; ++I) {
13967 Elements.push_back(VecA.getVectorElt(I));
13968 }
13969
13970 return Success(Elements, E);
13971 }
13972 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: {
13973 APValue VecA, VecB, VecSrc, MaskValue;
13974
13975 if (!EvaluateAsRValue(Info, E->getArg(0), VecA) ||
13976 !EvaluateAsRValue(Info, E->getArg(1), VecB) ||
13977 !EvaluateAsRValue(Info, E->getArg(2), VecSrc) ||
13978 !EvaluateAsRValue(Info, E->getArg(3), MaskValue))
13979 return false;
13980
13981 unsigned Mask = MaskValue.getInt().getZExtValue();
13982 SmallVector<APValue, 4> Elements;
13983
13984 if (Mask & 1) {
13985 APValue ResultVal;
13986 if (!ConvertDoubleToFloatStrict(Info, E, VecB.getVectorElt(0).getFloat(),
13987 ResultVal))
13988 return false;
13989 Elements.push_back(ResultVal);
13990 } else {
13991 Elements.push_back(VecSrc.getVectorElt(0));
13992 }
13993
13994 unsigned NumEltsA = VecA.getVectorLength();
13995 for (unsigned I = 1; I < NumEltsA; ++I) {
13996 Elements.push_back(VecA.getVectorElt(I));
13997 }
13998
13999 return Success(Elements, E);
14000 }
14001 case X86::BI__builtin_ia32_cvtpd2ps:
14002 case X86::BI__builtin_ia32_cvtpd2ps256:
14003 case X86::BI__builtin_ia32_cvtpd2ps_mask:
14004 case X86::BI__builtin_ia32_cvtpd2ps512_mask: {
14005
14006 const auto BuiltinID = BuiltinOp;
14007 bool IsMasked = (BuiltinID == X86::BI__builtin_ia32_cvtpd2ps_mask ||
14008 BuiltinID == X86::BI__builtin_ia32_cvtpd2ps512_mask);
14009
14010 APValue InputValue;
14011 if (!EvaluateAsRValue(Info, E->getArg(0), InputValue))
14012 return false;
14013
14014 APValue MergeValue;
14015 unsigned Mask = 0xFFFFFFFF;
14016 bool NeedsMerge = false;
14017 if (IsMasked) {
14018 APValue MaskValue;
14019 if (!EvaluateAsRValue(Info, E->getArg(2), MaskValue))
14020 return false;
14021 Mask = MaskValue.getInt().getZExtValue();
14022 auto NumEltsResult = E->getType()->getAs<VectorType>()->getNumElements();
14023 for (unsigned I = 0; I < NumEltsResult; ++I) {
14024 if (!((Mask >> I) & 1)) {
14025 NeedsMerge = true;
14026 break;
14027 }
14028 }
14029 if (NeedsMerge) {
14030 if (!EvaluateAsRValue(Info, E->getArg(1), MergeValue))
14031 return false;
14032 }
14033 }
14034
14035 unsigned NumEltsResult =
14036 E->getType()->getAs<VectorType>()->getNumElements();
14037 unsigned NumEltsInput = InputValue.getVectorLength();
14038 SmallVector<APValue, 8> Elements;
14039 for (unsigned I = 0; I < NumEltsResult; ++I) {
14040 if (IsMasked && !((Mask >> I) & 1)) {
14041 if (!NeedsMerge) {
14042 return false;
14043 }
14044 Elements.push_back(MergeValue.getVectorElt(I));
14045 continue;
14046 }
14047
14048 if (I >= NumEltsInput) {
14049 Elements.push_back(APValue(APFloat::getZero(APFloat::IEEEsingle())));
14050 continue;
14051 }
14052
14053 APValue ResultVal;
14055 Info, E, InputValue.getVectorElt(I).getFloat(), ResultVal))
14056 return false;
14057
14058 Elements.push_back(ResultVal);
14059 }
14060 return Success(Elements, E);
14061 }
14062
14063 case X86::BI__builtin_ia32_shufps:
14064 case X86::BI__builtin_ia32_shufps256:
14065 case X86::BI__builtin_ia32_shufps512: {
14066 APValue R;
14067 if (!evalShuffleGeneric(
14068 Info, E, R,
14069 [](unsigned DstIdx,
14070 unsigned ShuffleMask) -> std::pair<unsigned, int> {
14071 constexpr unsigned LaneBits = 128u;
14072 unsigned NumElemPerLane = LaneBits / 32;
14073 unsigned NumSelectableElems = NumElemPerLane / 2;
14074 unsigned BitsPerElem = 2;
14075 unsigned IndexMask = (1u << BitsPerElem) - 1;
14076 unsigned MaskBits = 8;
14077 unsigned Lane = DstIdx / NumElemPerLane;
14078 unsigned ElemInLane = DstIdx % NumElemPerLane;
14079 unsigned LaneOffset = Lane * NumElemPerLane;
14080 unsigned BitIndex = (DstIdx * BitsPerElem) % MaskBits;
14081 unsigned SrcIdx = (ElemInLane < NumSelectableElems) ? 0 : 1;
14082 unsigned Index = (ShuffleMask >> BitIndex) & IndexMask;
14083 return {SrcIdx, static_cast<int>(LaneOffset + Index)};
14084 }))
14085 return false;
14086 return Success(R, E);
14087 }
14088 case X86::BI__builtin_ia32_shufpd:
14089 case X86::BI__builtin_ia32_shufpd256:
14090 case X86::BI__builtin_ia32_shufpd512: {
14091 APValue R;
14092 if (!evalShuffleGeneric(
14093 Info, E, R,
14094 [](unsigned DstIdx,
14095 unsigned ShuffleMask) -> std::pair<unsigned, int> {
14096 constexpr unsigned LaneBits = 128u;
14097 unsigned NumElemPerLane = LaneBits / 64;
14098 unsigned NumSelectableElems = NumElemPerLane / 2;
14099 unsigned BitsPerElem = 1;
14100 unsigned IndexMask = (1u << BitsPerElem) - 1;
14101 unsigned MaskBits = 8;
14102 unsigned Lane = DstIdx / NumElemPerLane;
14103 unsigned ElemInLane = DstIdx % NumElemPerLane;
14104 unsigned LaneOffset = Lane * NumElemPerLane;
14105 unsigned BitIndex = (DstIdx * BitsPerElem) % MaskBits;
14106 unsigned SrcIdx = (ElemInLane < NumSelectableElems) ? 0 : 1;
14107 unsigned Index = (ShuffleMask >> BitIndex) & IndexMask;
14108 return {SrcIdx, static_cast<int>(LaneOffset + Index)};
14109 }))
14110 return false;
14111 return Success(R, E);
14112 }
14113 case X86::BI__builtin_ia32_insertps128: {
14114 APValue R;
14115 if (!evalShuffleGeneric(
14116 Info, E, R,
14117 [](unsigned DstIdx, unsigned Mask) -> std::pair<unsigned, int> {
14118 // Bits [3:0]: zero mask - if bit is set, zero this element
14119 if ((Mask & (1 << DstIdx)) != 0) {
14120 return {0, -1};
14121 }
14122 // Bits [7:6]: select element from source vector Y (0-3)
14123 // Bits [5:4]: select destination position (0-3)
14124 unsigned SrcElem = (Mask >> 6) & 0x3;
14125 unsigned DstElem = (Mask >> 4) & 0x3;
14126 if (DstIdx == DstElem) {
14127 // Insert element from source vector (B) at this position
14128 return {1, static_cast<int>(SrcElem)};
14129 } else {
14130 // Copy from destination vector (A)
14131 return {0, static_cast<int>(DstIdx)};
14132 }
14133 }))
14134 return false;
14135 return Success(R, E);
14136 }
14137 case X86::BI__builtin_ia32_pshufb128:
14138 case X86::BI__builtin_ia32_pshufb256:
14139 case X86::BI__builtin_ia32_pshufb512: {
14140 APValue R;
14141 if (!evalShuffleGeneric(
14142 Info, E, R,
14143 [](unsigned DstIdx,
14144 unsigned ShuffleMask) -> std::pair<unsigned, int> {
14145 uint8_t Ctlb = static_cast<uint8_t>(ShuffleMask);
14146 if (Ctlb & 0x80)
14147 return std::make_pair(0, -1);
14148
14149 unsigned LaneBase = (DstIdx / 16) * 16;
14150 unsigned SrcOffset = Ctlb & 0x0F;
14151 unsigned SrcIdx = LaneBase + SrcOffset;
14152 return std::make_pair(0, static_cast<int>(SrcIdx));
14153 }))
14154 return false;
14155 return Success(R, E);
14156 }
14157
14158 case X86::BI__builtin_ia32_pshuflw:
14159 case X86::BI__builtin_ia32_pshuflw256:
14160 case X86::BI__builtin_ia32_pshuflw512: {
14161 APValue R;
14162 if (!evalShuffleGeneric(
14163 Info, E, R,
14164 [](unsigned DstIdx, unsigned Mask) -> std::pair<unsigned, int> {
14165 constexpr unsigned LaneBits = 128u;
14166 constexpr unsigned ElemBits = 16u;
14167 constexpr unsigned LaneElts = LaneBits / ElemBits;
14168 constexpr unsigned HalfSize = 4;
14169 unsigned LaneBase = (DstIdx / LaneElts) * LaneElts;
14170 unsigned LaneIdx = DstIdx % LaneElts;
14171 if (LaneIdx < HalfSize) {
14172 unsigned Sel = (Mask >> (2 * LaneIdx)) & 0x3;
14173 return std::make_pair(0, static_cast<int>(LaneBase + Sel));
14174 }
14175 return std::make_pair(0, static_cast<int>(DstIdx));
14176 }))
14177 return false;
14178 return Success(R, E);
14179 }
14180
14181 case X86::BI__builtin_ia32_pshufhw:
14182 case X86::BI__builtin_ia32_pshufhw256:
14183 case X86::BI__builtin_ia32_pshufhw512: {
14184 APValue R;
14185 if (!evalShuffleGeneric(
14186 Info, E, R,
14187 [](unsigned DstIdx, unsigned Mask) -> std::pair<unsigned, int> {
14188 constexpr unsigned LaneBits = 128u;
14189 constexpr unsigned ElemBits = 16u;
14190 constexpr unsigned LaneElts = LaneBits / ElemBits;
14191 constexpr unsigned HalfSize = 4;
14192 unsigned LaneBase = (DstIdx / LaneElts) * LaneElts;
14193 unsigned LaneIdx = DstIdx % LaneElts;
14194 if (LaneIdx >= HalfSize) {
14195 unsigned Rel = LaneIdx - HalfSize;
14196 unsigned Sel = (Mask >> (2 * Rel)) & 0x3;
14197 return std::make_pair(
14198 0, static_cast<int>(LaneBase + HalfSize + Sel));
14199 }
14200 return std::make_pair(0, static_cast<int>(DstIdx));
14201 }))
14202 return false;
14203 return Success(R, E);
14204 }
14205
14206 case X86::BI__builtin_ia32_pshufd:
14207 case X86::BI__builtin_ia32_pshufd256:
14208 case X86::BI__builtin_ia32_pshufd512:
14209 case X86::BI__builtin_ia32_vpermilps:
14210 case X86::BI__builtin_ia32_vpermilps256:
14211 case X86::BI__builtin_ia32_vpermilps512: {
14212 APValue R;
14213 if (!evalShuffleGeneric(
14214 Info, E, R,
14215 [](unsigned DstIdx, unsigned Mask) -> std::pair<unsigned, int> {
14216 constexpr unsigned LaneBits = 128u;
14217 constexpr unsigned ElemBits = 32u;
14218 constexpr unsigned LaneElts = LaneBits / ElemBits;
14219 unsigned LaneBase = (DstIdx / LaneElts) * LaneElts;
14220 unsigned LaneIdx = DstIdx % LaneElts;
14221 unsigned Sel = (Mask >> (2 * LaneIdx)) & 0x3;
14222 return std::make_pair(0, static_cast<int>(LaneBase + Sel));
14223 }))
14224 return false;
14225 return Success(R, E);
14226 }
14227
14228 case X86::BI__builtin_ia32_vpermilvarpd:
14229 case X86::BI__builtin_ia32_vpermilvarpd256:
14230 case X86::BI__builtin_ia32_vpermilvarpd512: {
14231 APValue R;
14232 if (!evalShuffleGeneric(
14233 Info, E, R,
14234 [](unsigned DstIdx, unsigned Mask) -> std::pair<unsigned, int> {
14235 unsigned NumElemPerLane = 2;
14236 unsigned Lane = DstIdx / NumElemPerLane;
14237 unsigned Offset = Mask & 0b10 ? 1 : 0;
14238 return std::make_pair(
14239 0, static_cast<int>(Lane * NumElemPerLane + Offset));
14240 }))
14241 return false;
14242 return Success(R, E);
14243 }
14244
14245 case X86::BI__builtin_ia32_vpermilpd:
14246 case X86::BI__builtin_ia32_vpermilpd256:
14247 case X86::BI__builtin_ia32_vpermilpd512: {
14248 APValue R;
14249 if (!evalShuffleGeneric(Info, E, R, [](unsigned DstIdx, unsigned Control) {
14250 unsigned NumElemPerLane = 2;
14251 unsigned BitsPerElem = 1;
14252 unsigned MaskBits = 8;
14253 unsigned IndexMask = 0x1;
14254 unsigned Lane = DstIdx / NumElemPerLane;
14255 unsigned LaneOffset = Lane * NumElemPerLane;
14256 unsigned BitIndex = (DstIdx * BitsPerElem) % MaskBits;
14257 unsigned Index = (Control >> BitIndex) & IndexMask;
14258 return std::make_pair(0, static_cast<int>(LaneOffset + Index));
14259 }))
14260 return false;
14261 return Success(R, E);
14262 }
14263
14264 case X86::BI__builtin_ia32_permdf256:
14265 case X86::BI__builtin_ia32_permdi256: {
14266 APValue R;
14267 if (!evalShuffleGeneric(Info, E, R, [](unsigned DstIdx, unsigned Control) {
14268 // permute4x64 operates on 4 64-bit elements
14269 // For element i (0-3), extract bits [2*i+1:2*i] from Control
14270 unsigned Index = (Control >> (2 * DstIdx)) & 0x3;
14271 return std::make_pair(0, static_cast<int>(Index));
14272 }))
14273 return false;
14274 return Success(R, E);
14275 }
14276
14277 case X86::BI__builtin_ia32_vpermilvarps:
14278 case X86::BI__builtin_ia32_vpermilvarps256:
14279 case X86::BI__builtin_ia32_vpermilvarps512: {
14280 APValue R;
14281 if (!evalShuffleGeneric(
14282 Info, E, R,
14283 [](unsigned DstIdx, unsigned Mask) -> std::pair<unsigned, int> {
14284 unsigned NumElemPerLane = 4;
14285 unsigned Lane = DstIdx / NumElemPerLane;
14286 unsigned Offset = Mask & 0b11;
14287 return std::make_pair(
14288 0, static_cast<int>(Lane * NumElemPerLane + Offset));
14289 }))
14290 return false;
14291 return Success(R, E);
14292 }
14293
14294 case X86::BI__builtin_ia32_vpmultishiftqb128:
14295 case X86::BI__builtin_ia32_vpmultishiftqb256:
14296 case X86::BI__builtin_ia32_vpmultishiftqb512: {
14297 assert(E->getNumArgs() == 2);
14298
14299 APValue A, B;
14300 if (!Evaluate(A, Info, E->getArg(0)) || !Evaluate(B, Info, E->getArg(1)))
14301 return false;
14302
14303 assert(A.getVectorLength() == B.getVectorLength());
14304 unsigned NumBytesInQWord = 8;
14305 unsigned NumBitsInByte = 8;
14306 unsigned NumBytes = A.getVectorLength();
14307 unsigned NumQWords = NumBytes / NumBytesInQWord;
14309 Result.reserve(NumBytes);
14310
14311 for (unsigned QWordId = 0; QWordId != NumQWords; ++QWordId) {
14312 APInt BQWord(64, 0);
14313 for (unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
14314 unsigned Idx = QWordId * NumBytesInQWord + ByteIdx;
14315 uint64_t Byte = B.getVectorElt(Idx).getInt().getZExtValue();
14316 BQWord.insertBits(APInt(8, Byte & 0xFF), ByteIdx * NumBitsInByte);
14317 }
14318
14319 for (unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
14320 unsigned Idx = QWordId * NumBytesInQWord + ByteIdx;
14321 uint64_t Ctrl = A.getVectorElt(Idx).getInt().getZExtValue() & 0x3F;
14322
14323 APInt Byte(8, 0);
14324 for (unsigned BitIdx = 0; BitIdx != NumBitsInByte; ++BitIdx) {
14325 Byte.setBitVal(BitIdx, BQWord[(Ctrl + BitIdx) & 0x3F]);
14326 }
14327 Result.push_back(APValue(APSInt(Byte, /*isUnsigned*/ true)));
14328 }
14329 }
14330 return Success(APValue(Result.data(), Result.size()), E);
14331 }
14332
14333 case X86::BI__builtin_ia32_phminposuw128: {
14334 APValue Source;
14335 if (!Evaluate(Source, Info, E->getArg(0)))
14336 return false;
14337 unsigned SourceLen = Source.getVectorLength();
14338 const VectorType *VT = E->getArg(0)->getType()->castAs<VectorType>();
14339 QualType ElemQT = VT->getElementType();
14340 unsigned ElemBitWidth = Info.Ctx.getTypeSize(ElemQT);
14341
14342 APInt MinIndex(ElemBitWidth, 0);
14343 APInt MinVal = Source.getVectorElt(0).getInt();
14344 for (unsigned I = 1; I != SourceLen; ++I) {
14345 APInt Val = Source.getVectorElt(I).getInt();
14346 if (MinVal.ugt(Val)) {
14347 MinVal = Val;
14348 MinIndex = I;
14349 }
14350 }
14351
14352 bool ResultUnsigned = E->getCallReturnType(Info.Ctx)
14353 ->castAs<VectorType>()
14354 ->getElementType()
14355 ->isUnsignedIntegerOrEnumerationType();
14356
14358 Result.reserve(SourceLen);
14359 Result.emplace_back(APSInt(MinVal, ResultUnsigned));
14360 Result.emplace_back(APSInt(MinIndex, ResultUnsigned));
14361 for (unsigned I = 0; I != SourceLen - 2; ++I) {
14362 Result.emplace_back(APSInt(APInt(ElemBitWidth, 0), ResultUnsigned));
14363 }
14364 return Success(APValue(Result.data(), Result.size()), E);
14365 }
14366
14367 case X86::BI__builtin_ia32_psraq128:
14368 case X86::BI__builtin_ia32_psraq256:
14369 case X86::BI__builtin_ia32_psraq512:
14370 case X86::BI__builtin_ia32_psrad128:
14371 case X86::BI__builtin_ia32_psrad256:
14372 case X86::BI__builtin_ia32_psrad512:
14373 case X86::BI__builtin_ia32_psraw128:
14374 case X86::BI__builtin_ia32_psraw256:
14375 case X86::BI__builtin_ia32_psraw512: {
14376 APValue R;
14377 if (!evalShiftWithCount(
14378 Info, E, R,
14379 [](const APInt &Elt, uint64_t Count) { return Elt.ashr(Count); },
14380 [](const APInt &Elt, unsigned Width) {
14381 return Elt.ashr(Width - 1);
14382 }))
14383 return false;
14384 return Success(R, E);
14385 }
14386
14387 case X86::BI__builtin_ia32_psllq128:
14388 case X86::BI__builtin_ia32_psllq256:
14389 case X86::BI__builtin_ia32_psllq512:
14390 case X86::BI__builtin_ia32_pslld128:
14391 case X86::BI__builtin_ia32_pslld256:
14392 case X86::BI__builtin_ia32_pslld512:
14393 case X86::BI__builtin_ia32_psllw128:
14394 case X86::BI__builtin_ia32_psllw256:
14395 case X86::BI__builtin_ia32_psllw512: {
14396 APValue R;
14397 if (!evalShiftWithCount(
14398 Info, E, R,
14399 [](const APInt &Elt, uint64_t Count) { return Elt.shl(Count); },
14400 [](const APInt &Elt, unsigned Width) {
14401 return APInt::getZero(Width);
14402 }))
14403 return false;
14404 return Success(R, E);
14405 }
14406
14407 case X86::BI__builtin_ia32_psrlq128:
14408 case X86::BI__builtin_ia32_psrlq256:
14409 case X86::BI__builtin_ia32_psrlq512:
14410 case X86::BI__builtin_ia32_psrld128:
14411 case X86::BI__builtin_ia32_psrld256:
14412 case X86::BI__builtin_ia32_psrld512:
14413 case X86::BI__builtin_ia32_psrlw128:
14414 case X86::BI__builtin_ia32_psrlw256:
14415 case X86::BI__builtin_ia32_psrlw512: {
14416 APValue R;
14417 if (!evalShiftWithCount(
14418 Info, E, R,
14419 [](const APInt &Elt, uint64_t Count) { return Elt.lshr(Count); },
14420 [](const APInt &Elt, unsigned Width) {
14421 return APInt::getZero(Width);
14422 }))
14423 return false;
14424 return Success(R, E);
14425 }
14426
14427 case X86::BI__builtin_ia32_pternlogd128_mask:
14428 case X86::BI__builtin_ia32_pternlogd256_mask:
14429 case X86::BI__builtin_ia32_pternlogd512_mask:
14430 case X86::BI__builtin_ia32_pternlogq128_mask:
14431 case X86::BI__builtin_ia32_pternlogq256_mask:
14432 case X86::BI__builtin_ia32_pternlogq512_mask: {
14433 APValue AValue, BValue, CValue, ImmValue, UValue;
14434 if (!EvaluateAsRValue(Info, E->getArg(0), AValue) ||
14435 !EvaluateAsRValue(Info, E->getArg(1), BValue) ||
14436 !EvaluateAsRValue(Info, E->getArg(2), CValue) ||
14437 !EvaluateAsRValue(Info, E->getArg(3), ImmValue) ||
14438 !EvaluateAsRValue(Info, E->getArg(4), UValue))
14439 return false;
14440
14441 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
14442 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
14443 APInt Imm = ImmValue.getInt();
14444 APInt U = UValue.getInt();
14445 unsigned ResultLen = AValue.getVectorLength();
14446 SmallVector<APValue, 16> ResultElements;
14447 ResultElements.reserve(ResultLen);
14448
14449 for (unsigned EltNum = 0; EltNum < ResultLen; ++EltNum) {
14450 APInt ALane = AValue.getVectorElt(EltNum).getInt();
14451 APInt BLane = BValue.getVectorElt(EltNum).getInt();
14452 APInt CLane = CValue.getVectorElt(EltNum).getInt();
14453
14454 if (U[EltNum]) {
14455 unsigned BitWidth = ALane.getBitWidth();
14456 APInt ResLane(BitWidth, 0);
14457
14458 for (unsigned Bit = 0; Bit < BitWidth; ++Bit) {
14459 unsigned ABit = ALane[Bit];
14460 unsigned BBit = BLane[Bit];
14461 unsigned CBit = CLane[Bit];
14462
14463 unsigned Idx = (ABit << 2) | (BBit << 1) | CBit;
14464 ResLane.setBitVal(Bit, Imm[Idx]);
14465 }
14466 ResultElements.push_back(APValue(APSInt(ResLane, DestUnsigned)));
14467 } else {
14468 ResultElements.push_back(APValue(APSInt(ALane, DestUnsigned)));
14469 }
14470 }
14471 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
14472 }
14473 case X86::BI__builtin_ia32_pternlogd128_maskz:
14474 case X86::BI__builtin_ia32_pternlogd256_maskz:
14475 case X86::BI__builtin_ia32_pternlogd512_maskz:
14476 case X86::BI__builtin_ia32_pternlogq128_maskz:
14477 case X86::BI__builtin_ia32_pternlogq256_maskz:
14478 case X86::BI__builtin_ia32_pternlogq512_maskz: {
14479 APValue AValue, BValue, CValue, ImmValue, UValue;
14480 if (!EvaluateAsRValue(Info, E->getArg(0), AValue) ||
14481 !EvaluateAsRValue(Info, E->getArg(1), BValue) ||
14482 !EvaluateAsRValue(Info, E->getArg(2), CValue) ||
14483 !EvaluateAsRValue(Info, E->getArg(3), ImmValue) ||
14484 !EvaluateAsRValue(Info, E->getArg(4), UValue))
14485 return false;
14486
14487 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
14488 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
14489 APInt Imm = ImmValue.getInt();
14490 APInt U = UValue.getInt();
14491 unsigned ResultLen = AValue.getVectorLength();
14492 SmallVector<APValue, 16> ResultElements;
14493 ResultElements.reserve(ResultLen);
14494
14495 for (unsigned EltNum = 0; EltNum < ResultLen; ++EltNum) {
14496 APInt ALane = AValue.getVectorElt(EltNum).getInt();
14497 APInt BLane = BValue.getVectorElt(EltNum).getInt();
14498 APInt CLane = CValue.getVectorElt(EltNum).getInt();
14499
14500 unsigned BitWidth = ALane.getBitWidth();
14501 APInt ResLane(BitWidth, 0);
14502
14503 if (U[EltNum]) {
14504 for (unsigned Bit = 0; Bit < BitWidth; ++Bit) {
14505 unsigned ABit = ALane[Bit];
14506 unsigned BBit = BLane[Bit];
14507 unsigned CBit = CLane[Bit];
14508
14509 unsigned Idx = (ABit << 2) | (BBit << 1) | CBit;
14510 ResLane.setBitVal(Bit, Imm[Idx]);
14511 }
14512 }
14513 ResultElements.push_back(APValue(APSInt(ResLane, DestUnsigned)));
14514 }
14515 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
14516 }
14517
14518 case Builtin::BI__builtin_elementwise_clzg:
14519 case Builtin::BI__builtin_elementwise_ctzg: {
14520 APValue SourceLHS;
14521 std::optional<APValue> Fallback;
14522 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS))
14523 return false;
14524 if (E->getNumArgs() > 1) {
14525 APValue FallbackTmp;
14526 if (!EvaluateAsRValue(Info, E->getArg(1), FallbackTmp))
14527 return false;
14528 Fallback = FallbackTmp;
14529 }
14530
14531 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
14532 unsigned SourceLen = SourceLHS.getVectorLength();
14533 SmallVector<APValue, 4> ResultElements;
14534 ResultElements.reserve(SourceLen);
14535
14536 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
14537 APSInt LHS = SourceLHS.getVectorElt(EltNum).getInt();
14538 if (!LHS) {
14539 // Without a fallback, a zero element is undefined
14540 if (!Fallback) {
14541 Info.FFDiag(E, diag::note_constexpr_countzeroes_zero)
14542 << /*IsTrailing=*/(BuiltinOp ==
14543 Builtin::BI__builtin_elementwise_ctzg);
14544 return false;
14545 }
14546 ResultElements.push_back(Fallback->getVectorElt(EltNum));
14547 continue;
14548 }
14549 switch (BuiltinOp) {
14550 case Builtin::BI__builtin_elementwise_clzg:
14551 ResultElements.push_back(APValue(
14552 APSInt(APInt(Info.Ctx.getIntWidth(DestEltTy), LHS.countl_zero()),
14553 DestEltTy->isUnsignedIntegerOrEnumerationType())));
14554 break;
14555 case Builtin::BI__builtin_elementwise_ctzg:
14556 ResultElements.push_back(APValue(
14557 APSInt(APInt(Info.Ctx.getIntWidth(DestEltTy), LHS.countr_zero()),
14558 DestEltTy->isUnsignedIntegerOrEnumerationType())));
14559 break;
14560 }
14561 }
14562
14563 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
14564 }
14565
14566 case Builtin::BI__builtin_elementwise_fma: {
14567 APValue SourceX, SourceY, SourceZ;
14568 if (!EvaluateAsRValue(Info, E->getArg(0), SourceX) ||
14569 !EvaluateAsRValue(Info, E->getArg(1), SourceY) ||
14570 !EvaluateAsRValue(Info, E->getArg(2), SourceZ))
14571 return false;
14572
14573 unsigned SourceLen = SourceX.getVectorLength();
14574 SmallVector<APValue> ResultElements;
14575 ResultElements.reserve(SourceLen);
14576 llvm::RoundingMode RM = getActiveRoundingMode(getEvalInfo(), E);
14577 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
14578 const APFloat &X = SourceX.getVectorElt(EltNum).getFloat();
14579 const APFloat &Y = SourceY.getVectorElt(EltNum).getFloat();
14580 const APFloat &Z = SourceZ.getVectorElt(EltNum).getFloat();
14581 APFloat Result(X);
14582 (void)Result.fusedMultiplyAdd(Y, Z, RM);
14583 ResultElements.push_back(APValue(Result));
14584 }
14585 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
14586 }
14587
14588 case clang::X86::BI__builtin_ia32_phaddw128:
14589 case clang::X86::BI__builtin_ia32_phaddw256:
14590 case clang::X86::BI__builtin_ia32_phaddd128:
14591 case clang::X86::BI__builtin_ia32_phaddd256:
14592 case clang::X86::BI__builtin_ia32_phaddsw128:
14593 case clang::X86::BI__builtin_ia32_phaddsw256:
14594
14595 case clang::X86::BI__builtin_ia32_phsubw128:
14596 case clang::X86::BI__builtin_ia32_phsubw256:
14597 case clang::X86::BI__builtin_ia32_phsubd128:
14598 case clang::X86::BI__builtin_ia32_phsubd256:
14599 case clang::X86::BI__builtin_ia32_phsubsw128:
14600 case clang::X86::BI__builtin_ia32_phsubsw256: {
14601 APValue SourceLHS, SourceRHS;
14602 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
14603 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
14604 return false;
14605 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
14606 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
14607
14608 unsigned NumElts = SourceLHS.getVectorLength();
14609 unsigned EltBits = Info.Ctx.getIntWidth(DestEltTy);
14610 unsigned EltsPerLane = 128 / EltBits;
14611 SmallVector<APValue, 4> ResultElements;
14612 ResultElements.reserve(NumElts);
14613
14614 for (unsigned LaneStart = 0; LaneStart != NumElts;
14615 LaneStart += EltsPerLane) {
14616 for (unsigned I = 0; I != EltsPerLane; I += 2) {
14617 APSInt LHSA = SourceLHS.getVectorElt(LaneStart + I).getInt();
14618 APSInt LHSB = SourceLHS.getVectorElt(LaneStart + I + 1).getInt();
14619 switch (BuiltinOp) {
14620 case clang::X86::BI__builtin_ia32_phaddw128:
14621 case clang::X86::BI__builtin_ia32_phaddw256:
14622 case clang::X86::BI__builtin_ia32_phaddd128:
14623 case clang::X86::BI__builtin_ia32_phaddd256: {
14624 APSInt Res(LHSA + LHSB, DestUnsigned);
14625 ResultElements.push_back(APValue(Res));
14626 break;
14627 }
14628 case clang::X86::BI__builtin_ia32_phaddsw128:
14629 case clang::X86::BI__builtin_ia32_phaddsw256: {
14630 APSInt Res(LHSA.sadd_sat(LHSB));
14631 ResultElements.push_back(APValue(Res));
14632 break;
14633 }
14634 case clang::X86::BI__builtin_ia32_phsubw128:
14635 case clang::X86::BI__builtin_ia32_phsubw256:
14636 case clang::X86::BI__builtin_ia32_phsubd128:
14637 case clang::X86::BI__builtin_ia32_phsubd256: {
14638 APSInt Res(LHSA - LHSB, DestUnsigned);
14639 ResultElements.push_back(APValue(Res));
14640 break;
14641 }
14642 case clang::X86::BI__builtin_ia32_phsubsw128:
14643 case clang::X86::BI__builtin_ia32_phsubsw256: {
14644 APSInt Res(LHSA.ssub_sat(LHSB));
14645 ResultElements.push_back(APValue(Res));
14646 break;
14647 }
14648 }
14649 }
14650 for (unsigned I = 0; I != EltsPerLane; I += 2) {
14651 APSInt RHSA = SourceRHS.getVectorElt(LaneStart + I).getInt();
14652 APSInt RHSB = SourceRHS.getVectorElt(LaneStart + I + 1).getInt();
14653 switch (BuiltinOp) {
14654 case clang::X86::BI__builtin_ia32_phaddw128:
14655 case clang::X86::BI__builtin_ia32_phaddw256:
14656 case clang::X86::BI__builtin_ia32_phaddd128:
14657 case clang::X86::BI__builtin_ia32_phaddd256: {
14658 APSInt Res(RHSA + RHSB, DestUnsigned);
14659 ResultElements.push_back(APValue(Res));
14660 break;
14661 }
14662 case clang::X86::BI__builtin_ia32_phaddsw128:
14663 case clang::X86::BI__builtin_ia32_phaddsw256: {
14664 APSInt Res(RHSA.sadd_sat(RHSB));
14665 ResultElements.push_back(APValue(Res));
14666 break;
14667 }
14668 case clang::X86::BI__builtin_ia32_phsubw128:
14669 case clang::X86::BI__builtin_ia32_phsubw256:
14670 case clang::X86::BI__builtin_ia32_phsubd128:
14671 case clang::X86::BI__builtin_ia32_phsubd256: {
14672 APSInt Res(RHSA - RHSB, DestUnsigned);
14673 ResultElements.push_back(APValue(Res));
14674 break;
14675 }
14676 case clang::X86::BI__builtin_ia32_phsubsw128:
14677 case clang::X86::BI__builtin_ia32_phsubsw256: {
14678 APSInt Res(RHSA.ssub_sat(RHSB));
14679 ResultElements.push_back(APValue(Res));
14680 break;
14681 }
14682 }
14683 }
14684 }
14685 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
14686 }
14687 case clang::X86::BI__builtin_ia32_haddpd:
14688 case clang::X86::BI__builtin_ia32_haddps:
14689 case clang::X86::BI__builtin_ia32_haddps256:
14690 case clang::X86::BI__builtin_ia32_haddpd256:
14691 case clang::X86::BI__builtin_ia32_hsubpd:
14692 case clang::X86::BI__builtin_ia32_hsubps:
14693 case clang::X86::BI__builtin_ia32_hsubps256:
14694 case clang::X86::BI__builtin_ia32_hsubpd256: {
14695 APValue SourceLHS, SourceRHS;
14696 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
14697 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
14698 return false;
14699 unsigned NumElts = SourceLHS.getVectorLength();
14700 SmallVector<APValue, 4> ResultElements;
14701 ResultElements.reserve(NumElts);
14702 llvm::RoundingMode RM = getActiveRoundingMode(getEvalInfo(), E);
14703 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
14704 unsigned EltBits = Info.Ctx.getTypeSize(DestEltTy);
14705 unsigned NumLanes = NumElts * EltBits / 128;
14706 unsigned NumElemsPerLane = NumElts / NumLanes;
14707 unsigned HalfElemsPerLane = NumElemsPerLane / 2;
14708
14709 for (unsigned L = 0; L != NumElts; L += NumElemsPerLane) {
14710 for (unsigned I = 0; I != HalfElemsPerLane; ++I) {
14711 APFloat LHSA = SourceLHS.getVectorElt(L + (2 * I) + 0).getFloat();
14712 APFloat LHSB = SourceLHS.getVectorElt(L + (2 * I) + 1).getFloat();
14713 switch (BuiltinOp) {
14714 case clang::X86::BI__builtin_ia32_haddpd:
14715 case clang::X86::BI__builtin_ia32_haddps:
14716 case clang::X86::BI__builtin_ia32_haddps256:
14717 case clang::X86::BI__builtin_ia32_haddpd256:
14718 LHSA.add(LHSB, RM);
14719 break;
14720 case clang::X86::BI__builtin_ia32_hsubpd:
14721 case clang::X86::BI__builtin_ia32_hsubps:
14722 case clang::X86::BI__builtin_ia32_hsubps256:
14723 case clang::X86::BI__builtin_ia32_hsubpd256:
14724 LHSA.subtract(LHSB, RM);
14725 break;
14726 }
14727 ResultElements.push_back(APValue(LHSA));
14728 }
14729 for (unsigned I = 0; I != HalfElemsPerLane; ++I) {
14730 APFloat RHSA = SourceRHS.getVectorElt(L + (2 * I) + 0).getFloat();
14731 APFloat RHSB = SourceRHS.getVectorElt(L + (2 * I) + 1).getFloat();
14732 switch (BuiltinOp) {
14733 case clang::X86::BI__builtin_ia32_haddpd:
14734 case clang::X86::BI__builtin_ia32_haddps:
14735 case clang::X86::BI__builtin_ia32_haddps256:
14736 case clang::X86::BI__builtin_ia32_haddpd256:
14737 RHSA.add(RHSB, RM);
14738 break;
14739 case clang::X86::BI__builtin_ia32_hsubpd:
14740 case clang::X86::BI__builtin_ia32_hsubps:
14741 case clang::X86::BI__builtin_ia32_hsubps256:
14742 case clang::X86::BI__builtin_ia32_hsubpd256:
14743 RHSA.subtract(RHSB, RM);
14744 break;
14745 }
14746 ResultElements.push_back(APValue(RHSA));
14747 }
14748 }
14749 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
14750 }
14751 case clang::X86::BI__builtin_ia32_addsubpd:
14752 case clang::X86::BI__builtin_ia32_addsubps:
14753 case clang::X86::BI__builtin_ia32_addsubpd256:
14754 case clang::X86::BI__builtin_ia32_addsubps256: {
14755 // Addsub: alternates between subtraction and addition
14756 // Result[i] = (i % 2 == 0) ? (a[i] - b[i]) : (a[i] + b[i])
14757 APValue SourceLHS, SourceRHS;
14758 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
14759 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
14760 return false;
14761 unsigned NumElems = SourceLHS.getVectorLength();
14762 SmallVector<APValue, 8> ResultElements;
14763 ResultElements.reserve(NumElems);
14764 llvm::RoundingMode RM = getActiveRoundingMode(getEvalInfo(), E);
14765
14766 for (unsigned I = 0; I != NumElems; ++I) {
14767 APFloat LHS = SourceLHS.getVectorElt(I).getFloat();
14768 APFloat RHS = SourceRHS.getVectorElt(I).getFloat();
14769 if (I % 2 == 0) {
14770 // Even indices: subtract
14771 LHS.subtract(RHS, RM);
14772 } else {
14773 // Odd indices: add
14774 LHS.add(RHS, RM);
14775 }
14776 ResultElements.push_back(APValue(LHS));
14777 }
14778 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
14779 }
14780 case clang::X86::BI__builtin_ia32_pclmulqdq128:
14781 case clang::X86::BI__builtin_ia32_pclmulqdq256:
14782 case clang::X86::BI__builtin_ia32_pclmulqdq512: {
14783 // PCLMULQDQ: carry-less multiplication of selected 64-bit halves
14784 // imm8 bit 0: selects lower (0) or upper (1) 64 bits of first operand
14785 // imm8 bit 4: selects lower (0) or upper (1) 64 bits of second operand
14786 APValue SourceLHS, SourceRHS;
14787 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
14788 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
14789 return false;
14790
14791 APSInt Imm8;
14792 if (!EvaluateInteger(E->getArg(2), Imm8, Info))
14793 return false;
14794
14795 // Extract bits 0 and 4 from imm8
14796 bool SelectUpperA = (Imm8 & 0x01) != 0;
14797 bool SelectUpperB = (Imm8 & 0x10) != 0;
14798
14799 unsigned NumElems = SourceLHS.getVectorLength();
14800 SmallVector<APValue, 8> ResultElements;
14801 ResultElements.reserve(NumElems);
14802 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
14803 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
14804
14805 // Process each 128-bit lane
14806 for (unsigned Lane = 0; Lane < NumElems; Lane += 2) {
14807 // Get the two 64-bit halves of the first operand
14808 APSInt A0 = SourceLHS.getVectorElt(Lane + 0).getInt();
14809 APSInt A1 = SourceLHS.getVectorElt(Lane + 1).getInt();
14810 // Get the two 64-bit halves of the second operand
14811 APSInt B0 = SourceRHS.getVectorElt(Lane + 0).getInt();
14812 APSInt B1 = SourceRHS.getVectorElt(Lane + 1).getInt();
14813
14814 // Select the appropriate 64-bit values based on imm8
14815 APInt A = SelectUpperA ? A1 : A0;
14816 APInt B = SelectUpperB ? B1 : B0;
14817
14818 // Extend both operands to 128 bits for carry-less multiplication
14819 APInt A128 = A.zext(128);
14820 APInt B128 = B.zext(128);
14821
14822 // Use APIntOps::clmul for carry-less multiplication
14823 APInt Result = llvm::APIntOps::clmul(A128, B128);
14824
14825 // Split the 128-bit result into two 64-bit halves
14826 APSInt ResultLow(Result.extractBits(64, 0), DestUnsigned);
14827 APSInt ResultHigh(Result.extractBits(64, 64), DestUnsigned);
14828
14829 ResultElements.push_back(APValue(ResultLow));
14830 ResultElements.push_back(APValue(ResultHigh));
14831 }
14832
14833 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
14834 }
14835 case Builtin::BI__builtin_elementwise_clmul:
14836 return EvaluateBinOpExpr(llvm::APIntOps::clmul);
14837 case Builtin::BI__builtin_elementwise_pext:
14838 return EvaluateBinOpExpr(llvm::APIntOps::pext);
14839 case Builtin::BI__builtin_elementwise_pdep:
14840 return EvaluateBinOpExpr(llvm::APIntOps::pdep);
14841 case Builtin::BI__builtin_elementwise_fshl:
14842 case Builtin::BI__builtin_elementwise_fshr: {
14843 APValue SourceHi, SourceLo, SourceShift;
14844 if (!EvaluateAsRValue(Info, E->getArg(0), SourceHi) ||
14845 !EvaluateAsRValue(Info, E->getArg(1), SourceLo) ||
14846 !EvaluateAsRValue(Info, E->getArg(2), SourceShift))
14847 return false;
14848
14849 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
14850 if (!DestEltTy->isIntegerType())
14851 return false;
14852
14853 unsigned SourceLen = SourceHi.getVectorLength();
14854 SmallVector<APValue> ResultElements;
14855 ResultElements.reserve(SourceLen);
14856 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
14857 const APSInt &Hi = SourceHi.getVectorElt(EltNum).getInt();
14858 const APSInt &Lo = SourceLo.getVectorElt(EltNum).getInt();
14859 const APSInt &Shift = SourceShift.getVectorElt(EltNum).getInt();
14860 switch (BuiltinOp) {
14861 case Builtin::BI__builtin_elementwise_fshl:
14862 ResultElements.push_back(APValue(
14863 APSInt(llvm::APIntOps::fshl(Hi, Lo, Shift), Hi.isUnsigned())));
14864 break;
14865 case Builtin::BI__builtin_elementwise_fshr:
14866 ResultElements.push_back(APValue(
14867 APSInt(llvm::APIntOps::fshr(Hi, Lo, Shift), Hi.isUnsigned())));
14868 break;
14869 }
14870 }
14871
14872 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
14873 }
14874
14875 case X86::BI__builtin_ia32_shuf_f32x4_256:
14876 case X86::BI__builtin_ia32_shuf_i32x4_256:
14877 case X86::BI__builtin_ia32_shuf_f64x2_256:
14878 case X86::BI__builtin_ia32_shuf_i64x2_256:
14879 case X86::BI__builtin_ia32_shuf_f32x4:
14880 case X86::BI__builtin_ia32_shuf_i32x4:
14881 case X86::BI__builtin_ia32_shuf_f64x2:
14882 case X86::BI__builtin_ia32_shuf_i64x2: {
14883 APValue SourceA, SourceB;
14884 if (!EvaluateAsRValue(Info, E->getArg(0), SourceA) ||
14885 !EvaluateAsRValue(Info, E->getArg(1), SourceB))
14886 return false;
14887
14888 APSInt Imm;
14889 if (!EvaluateInteger(E->getArg(2), Imm, Info))
14890 return false;
14891
14892 // Destination and sources A, B all have the same type.
14893 unsigned NumElems = SourceA.getVectorLength();
14894 const VectorType *VT = E->getArg(0)->getType()->castAs<VectorType>();
14895 QualType ElemQT = VT->getElementType();
14896 unsigned ElemBits = Info.Ctx.getTypeSize(ElemQT);
14897 unsigned LaneBits = 128u;
14898 unsigned NumLanes = (NumElems * ElemBits) / LaneBits;
14899 unsigned NumElemsPerLane = LaneBits / ElemBits;
14900
14901 unsigned DstLen = SourceA.getVectorLength();
14902 SmallVector<APValue, 16> ResultElements;
14903 ResultElements.reserve(DstLen);
14904
14905 APValue R;
14906 if (!evalShuffleGeneric(
14907 Info, E, R,
14908 [NumLanes, NumElemsPerLane](unsigned DstIdx, unsigned ShuffleMask)
14909 -> std::pair<unsigned, int> {
14910 // DstIdx determines source. ShuffleMask selects lane in source.
14911 unsigned BitsPerElem = NumLanes / 2;
14912 unsigned IndexMask = (1u << BitsPerElem) - 1;
14913 unsigned Lane = DstIdx / NumElemsPerLane;
14914 unsigned SrcIdx = (Lane < NumLanes / 2) ? 0 : 1;
14915 unsigned BitIdx = BitsPerElem * Lane;
14916 unsigned SrcLaneIdx = (ShuffleMask >> BitIdx) & IndexMask;
14917 unsigned ElemInLane = DstIdx % NumElemsPerLane;
14918 unsigned IdxToPick = SrcLaneIdx * NumElemsPerLane + ElemInLane;
14919 return {SrcIdx, IdxToPick};
14920 }))
14921 return false;
14922 return Success(R, E);
14923 }
14924
14925 case X86::BI__builtin_ia32_vgf2p8affineinvqb_v16qi:
14926 case X86::BI__builtin_ia32_vgf2p8affineinvqb_v32qi:
14927 case X86::BI__builtin_ia32_vgf2p8affineinvqb_v64qi:
14928 case X86::BI__builtin_ia32_vgf2p8affineqb_v16qi:
14929 case X86::BI__builtin_ia32_vgf2p8affineqb_v32qi:
14930 case X86::BI__builtin_ia32_vgf2p8affineqb_v64qi: {
14931
14932 APValue X, A;
14933 APSInt Imm;
14934 if (!EvaluateAsRValue(Info, E->getArg(0), X) ||
14935 !EvaluateAsRValue(Info, E->getArg(1), A) ||
14936 !EvaluateInteger(E->getArg(2), Imm, Info))
14937 return false;
14938
14939 assert(X.isVector() && A.isVector());
14940 assert(X.getVectorLength() == A.getVectorLength());
14941
14942 bool IsInverse = false;
14943 switch (BuiltinOp) {
14944 case X86::BI__builtin_ia32_vgf2p8affineinvqb_v16qi:
14945 case X86::BI__builtin_ia32_vgf2p8affineinvqb_v32qi:
14946 case X86::BI__builtin_ia32_vgf2p8affineinvqb_v64qi: {
14947 IsInverse = true;
14948 }
14949 }
14950
14951 unsigned NumBitsInByte = 8;
14952 unsigned NumBytesInQWord = 8;
14953 unsigned NumBitsInQWord = 64;
14954 unsigned NumBytes = A.getVectorLength();
14955 unsigned NumQWords = NumBytes / NumBytesInQWord;
14957 Result.reserve(NumBytes);
14958
14959 // computing A*X + Imm
14960 for (unsigned QWordIdx = 0; QWordIdx != NumQWords; ++QWordIdx) {
14961 // Extract the QWords from X, A
14962 APInt XQWord(NumBitsInQWord, 0);
14963 APInt AQWord(NumBitsInQWord, 0);
14964 for (unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
14965 unsigned Idx = QWordIdx * NumBytesInQWord + ByteIdx;
14966 APInt XByte = X.getVectorElt(Idx).getInt();
14967 APInt AByte = A.getVectorElt(Idx).getInt();
14968 XQWord.insertBits(XByte, ByteIdx * NumBitsInByte);
14969 AQWord.insertBits(AByte, ByteIdx * NumBitsInByte);
14970 }
14971
14972 for (unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
14973 uint8_t XByte =
14974 XQWord.lshr(ByteIdx * NumBitsInByte).getLoBits(8).getZExtValue();
14975 Result.push_back(APValue(APSInt(
14976 APInt(8, GFNIAffine(XByte, AQWord, Imm, IsInverse)), false)));
14977 }
14978 }
14979
14980 return Success(APValue(Result.data(), Result.size()), E);
14981 }
14982
14983 case X86::BI__builtin_ia32_vgf2p8mulb_v16qi:
14984 case X86::BI__builtin_ia32_vgf2p8mulb_v32qi:
14985 case X86::BI__builtin_ia32_vgf2p8mulb_v64qi: {
14986 APValue A, B;
14987 if (!EvaluateAsRValue(Info, E->getArg(0), A) ||
14988 !EvaluateAsRValue(Info, E->getArg(1), B))
14989 return false;
14990
14991 assert(A.isVector() && B.isVector());
14992 assert(A.getVectorLength() == B.getVectorLength());
14993
14994 unsigned NumBytes = A.getVectorLength();
14996 Result.reserve(NumBytes);
14997
14998 for (unsigned ByteIdx = 0; ByteIdx != NumBytes; ++ByteIdx) {
14999 uint8_t AByte = A.getVectorElt(ByteIdx).getInt().getZExtValue();
15000 uint8_t BByte = B.getVectorElt(ByteIdx).getInt().getZExtValue();
15001 Result.push_back(APValue(
15002 APSInt(APInt(8, GFNIMul(AByte, BByte)), /*IsUnsigned=*/false)));
15003 }
15004
15005 return Success(APValue(Result.data(), Result.size()), E);
15006 }
15007
15008 case X86::BI__builtin_ia32_insertf32x4_256:
15009 case X86::BI__builtin_ia32_inserti32x4_256:
15010 case X86::BI__builtin_ia32_insertf64x2_256:
15011 case X86::BI__builtin_ia32_inserti64x2_256:
15012 case X86::BI__builtin_ia32_insertf32x4:
15013 case X86::BI__builtin_ia32_inserti32x4:
15014 case X86::BI__builtin_ia32_insertf64x2_512:
15015 case X86::BI__builtin_ia32_inserti64x2_512:
15016 case X86::BI__builtin_ia32_insertf32x8:
15017 case X86::BI__builtin_ia32_inserti32x8:
15018 case X86::BI__builtin_ia32_insertf64x4:
15019 case X86::BI__builtin_ia32_inserti64x4:
15020 case X86::BI__builtin_ia32_vinsertf128_ps256:
15021 case X86::BI__builtin_ia32_vinsertf128_pd256:
15022 case X86::BI__builtin_ia32_vinsertf128_si256:
15023 case X86::BI__builtin_ia32_insert128i256: {
15024 APValue SourceDst, SourceSub;
15025 if (!EvaluateAsRValue(Info, E->getArg(0), SourceDst) ||
15026 !EvaluateAsRValue(Info, E->getArg(1), SourceSub))
15027 return false;
15028
15029 APSInt Imm;
15030 if (!EvaluateInteger(E->getArg(2), Imm, Info))
15031 return false;
15032
15033 assert(SourceDst.isVector() && SourceSub.isVector());
15034 unsigned DstLen = SourceDst.getVectorLength();
15035 unsigned SubLen = SourceSub.getVectorLength();
15036 assert(SubLen != 0 && DstLen != 0 && (DstLen % SubLen) == 0);
15037 unsigned NumLanes = DstLen / SubLen;
15038 unsigned LaneIdx = (Imm.getZExtValue() % NumLanes) * SubLen;
15039
15040 SmallVector<APValue, 16> ResultElements;
15041 ResultElements.reserve(DstLen);
15042
15043 for (unsigned EltNum = 0; EltNum < DstLen; ++EltNum) {
15044 if (EltNum >= LaneIdx && EltNum < LaneIdx + SubLen)
15045 ResultElements.push_back(SourceSub.getVectorElt(EltNum - LaneIdx));
15046 else
15047 ResultElements.push_back(SourceDst.getVectorElt(EltNum));
15048 }
15049
15050 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
15051 }
15052
15053 case clang::X86::BI__builtin_ia32_vec_set_v4hi:
15054 case clang::X86::BI__builtin_ia32_vec_set_v16qi:
15055 case clang::X86::BI__builtin_ia32_vec_set_v8hi:
15056 case clang::X86::BI__builtin_ia32_vec_set_v4si:
15057 case clang::X86::BI__builtin_ia32_vec_set_v2di:
15058 case clang::X86::BI__builtin_ia32_vec_set_v32qi:
15059 case clang::X86::BI__builtin_ia32_vec_set_v16hi:
15060 case clang::X86::BI__builtin_ia32_vec_set_v8si:
15061 case clang::X86::BI__builtin_ia32_vec_set_v4di: {
15062 APValue VecVal;
15063 APSInt Scalar, IndexAPS;
15064 if (!EvaluateVector(E->getArg(0), VecVal, Info) ||
15065 !EvaluateInteger(E->getArg(1), Scalar, Info) ||
15066 !EvaluateInteger(E->getArg(2), IndexAPS, Info))
15067 return false;
15068
15069 QualType ElemTy = E->getType()->castAs<VectorType>()->getElementType();
15070 unsigned ElemWidth = Info.Ctx.getIntWidth(ElemTy);
15071 bool ElemUnsigned = ElemTy->isUnsignedIntegerOrEnumerationType();
15072 Scalar.setIsUnsigned(ElemUnsigned);
15073 APSInt ElemAPS = Scalar.extOrTrunc(ElemWidth);
15074 APValue ElemAV(ElemAPS);
15075
15076 unsigned NumElems = VecVal.getVectorLength();
15077 unsigned Index =
15078 static_cast<unsigned>(IndexAPS.getZExtValue() & (NumElems - 1));
15079
15081 Elems.reserve(NumElems);
15082 for (unsigned ElemNum = 0; ElemNum != NumElems; ++ElemNum)
15083 Elems.push_back(ElemNum == Index ? ElemAV : VecVal.getVectorElt(ElemNum));
15084
15085 return Success(APValue(Elems.data(), NumElems), E);
15086 }
15087
15088 case X86::BI__builtin_ia32_pslldqi128_byteshift:
15089 case X86::BI__builtin_ia32_pslldqi256_byteshift:
15090 case X86::BI__builtin_ia32_pslldqi512_byteshift: {
15091 APValue R;
15092 if (!evalShuffleGeneric(
15093 Info, E, R,
15094 [](unsigned DstIdx, unsigned Shift) -> std::pair<unsigned, int> {
15095 unsigned LaneBase = (DstIdx / 16) * 16;
15096 unsigned LaneIdx = DstIdx % 16;
15097 if (LaneIdx < Shift)
15098 return std::make_pair(0, -1);
15099
15100 return std::make_pair(
15101 0, static_cast<int>(LaneBase + LaneIdx - Shift));
15102 }))
15103 return false;
15104 return Success(R, E);
15105 }
15106
15107 case X86::BI__builtin_ia32_psrldqi128_byteshift:
15108 case X86::BI__builtin_ia32_psrldqi256_byteshift:
15109 case X86::BI__builtin_ia32_psrldqi512_byteshift: {
15110 APValue R;
15111 if (!evalShuffleGeneric(
15112 Info, E, R,
15113 [](unsigned DstIdx, unsigned Shift) -> std::pair<unsigned, int> {
15114 unsigned LaneBase = (DstIdx / 16) * 16;
15115 unsigned LaneIdx = DstIdx % 16;
15116 if (LaneIdx + Shift < 16)
15117 return std::make_pair(
15118 0, static_cast<int>(LaneBase + LaneIdx + Shift));
15119
15120 return std::make_pair(0, -1);
15121 }))
15122 return false;
15123 return Success(R, E);
15124 }
15125
15126 case X86::BI__builtin_ia32_palignr128:
15127 case X86::BI__builtin_ia32_palignr256:
15128 case X86::BI__builtin_ia32_palignr512: {
15129 APValue R;
15130 if (!evalShuffleGeneric(Info, E, R, [](unsigned DstIdx, unsigned Shift) {
15131 // Default to -1 → zero-fill this destination element
15132 unsigned VecIdx = 1;
15133 int ElemIdx = -1;
15134
15135 int Lane = DstIdx / 16;
15136 int Offset = DstIdx % 16;
15137
15138 // Elements come from VecB first, then VecA after the shift boundary
15139 unsigned ShiftedIdx = Offset + (Shift & 0xFF);
15140 if (ShiftedIdx < 16) { // from VecB
15141 ElemIdx = ShiftedIdx + (Lane * 16);
15142 } else if (ShiftedIdx < 32) { // from VecA
15143 VecIdx = 0;
15144 ElemIdx = (ShiftedIdx - 16) + (Lane * 16);
15145 }
15146
15147 return std::pair<unsigned, int>{VecIdx, ElemIdx};
15148 }))
15149 return false;
15150 return Success(R, E);
15151 }
15152 case X86::BI__builtin_ia32_alignd128:
15153 case X86::BI__builtin_ia32_alignd256:
15154 case X86::BI__builtin_ia32_alignd512:
15155 case X86::BI__builtin_ia32_alignq128:
15156 case X86::BI__builtin_ia32_alignq256:
15157 case X86::BI__builtin_ia32_alignq512: {
15158 APValue R;
15159 unsigned NumElems = E->getType()->castAs<VectorType>()->getNumElements();
15160 if (!evalShuffleGeneric(Info, E, R,
15161 [NumElems](unsigned DstIdx, unsigned Shift) {
15162 unsigned Imm = Shift & 0xFF;
15163 unsigned EffectiveShift = Imm & (NumElems - 1);
15164 unsigned SourcePos = DstIdx + EffectiveShift;
15165 unsigned VecIdx = SourcePos < NumElems ? 1 : 0;
15166 unsigned ElemIdx = SourcePos & (NumElems - 1);
15167
15168 return std::pair<unsigned, int>{
15169 VecIdx, static_cast<int>(ElemIdx)};
15170 }))
15171 return false;
15172 return Success(R, E);
15173 }
15174 case X86::BI__builtin_ia32_permvarsi256:
15175 case X86::BI__builtin_ia32_permvarsf256:
15176 case X86::BI__builtin_ia32_permvardf512:
15177 case X86::BI__builtin_ia32_permvardi512:
15178 case X86::BI__builtin_ia32_permvarhi128: {
15179 APValue R;
15180 if (!evalShuffleGeneric(Info, E, R,
15181 [](unsigned DstIdx, unsigned ShuffleMask) {
15182 int Offset = ShuffleMask & 0x7;
15183 return std::pair<unsigned, int>{0, Offset};
15184 }))
15185 return false;
15186 return Success(R, E);
15187 }
15188 case X86::BI__builtin_ia32_permvarqi128:
15189 case X86::BI__builtin_ia32_permvarhi256:
15190 case X86::BI__builtin_ia32_permvarsi512:
15191 case X86::BI__builtin_ia32_permvarsf512: {
15192 APValue R;
15193 if (!evalShuffleGeneric(Info, E, R,
15194 [](unsigned DstIdx, unsigned ShuffleMask) {
15195 int Offset = ShuffleMask & 0xF;
15196 return std::pair<unsigned, int>{0, Offset};
15197 }))
15198 return false;
15199 return Success(R, E);
15200 }
15201 case X86::BI__builtin_ia32_permvardi256:
15202 case X86::BI__builtin_ia32_permvardf256: {
15203 APValue R;
15204 if (!evalShuffleGeneric(Info, E, R,
15205 [](unsigned DstIdx, unsigned ShuffleMask) {
15206 int Offset = ShuffleMask & 0x3;
15207 return std::pair<unsigned, int>{0, Offset};
15208 }))
15209 return false;
15210 return Success(R, E);
15211 }
15212 case X86::BI__builtin_ia32_permvarqi256:
15213 case X86::BI__builtin_ia32_permvarhi512: {
15214 APValue R;
15215 if (!evalShuffleGeneric(Info, E, R,
15216 [](unsigned DstIdx, unsigned ShuffleMask) {
15217 int Offset = ShuffleMask & 0x1F;
15218 return std::pair<unsigned, int>{0, Offset};
15219 }))
15220 return false;
15221 return Success(R, E);
15222 }
15223 case X86::BI__builtin_ia32_permvarqi512: {
15224 APValue R;
15225 if (!evalShuffleGeneric(Info, E, R,
15226 [](unsigned DstIdx, unsigned ShuffleMask) {
15227 int Offset = ShuffleMask & 0x3F;
15228 return std::pair<unsigned, int>{0, Offset};
15229 }))
15230 return false;
15231 return Success(R, E);
15232 }
15233 case X86::BI__builtin_ia32_vpermi2varq128:
15234 case X86::BI__builtin_ia32_vpermi2varpd128: {
15235 APValue R;
15236 if (!evalShuffleGeneric(Info, E, R,
15237 [](unsigned DstIdx, unsigned ShuffleMask) {
15238 int Offset = ShuffleMask & 0x1;
15239 unsigned SrcIdx = (ShuffleMask >> 1) & 0x1;
15240 return std::pair<unsigned, int>{SrcIdx, Offset};
15241 }))
15242 return false;
15243 return Success(R, E);
15244 }
15245 case X86::BI__builtin_ia32_vpermi2vard128:
15246 case X86::BI__builtin_ia32_vpermi2varps128:
15247 case X86::BI__builtin_ia32_vpermi2varq256:
15248 case X86::BI__builtin_ia32_vpermi2varpd256: {
15249 APValue R;
15250 if (!evalShuffleGeneric(Info, E, R,
15251 [](unsigned DstIdx, unsigned ShuffleMask) {
15252 int Offset = ShuffleMask & 0x3;
15253 unsigned SrcIdx = (ShuffleMask >> 2) & 0x1;
15254 return std::pair<unsigned, int>{SrcIdx, Offset};
15255 }))
15256 return false;
15257 return Success(R, E);
15258 }
15259 case X86::BI__builtin_ia32_vpermi2varhi128:
15260 case X86::BI__builtin_ia32_vpermi2vard256:
15261 case X86::BI__builtin_ia32_vpermi2varps256:
15262 case X86::BI__builtin_ia32_vpermi2varq512:
15263 case X86::BI__builtin_ia32_vpermi2varpd512: {
15264 APValue R;
15265 if (!evalShuffleGeneric(Info, E, R,
15266 [](unsigned DstIdx, unsigned ShuffleMask) {
15267 int Offset = ShuffleMask & 0x7;
15268 unsigned SrcIdx = (ShuffleMask >> 3) & 0x1;
15269 return std::pair<unsigned, int>{SrcIdx, Offset};
15270 }))
15271 return false;
15272 return Success(R, E);
15273 }
15274 case X86::BI__builtin_ia32_vpermi2varqi128:
15275 case X86::BI__builtin_ia32_vpermi2varhi256:
15276 case X86::BI__builtin_ia32_vpermi2vard512:
15277 case X86::BI__builtin_ia32_vpermi2varps512: {
15278 APValue R;
15279 if (!evalShuffleGeneric(Info, E, R,
15280 [](unsigned DstIdx, unsigned ShuffleMask) {
15281 int Offset = ShuffleMask & 0xF;
15282 unsigned SrcIdx = (ShuffleMask >> 4) & 0x1;
15283 return std::pair<unsigned, int>{SrcIdx, Offset};
15284 }))
15285 return false;
15286 return Success(R, E);
15287 }
15288 case X86::BI__builtin_ia32_vpermi2varqi256:
15289 case X86::BI__builtin_ia32_vpermi2varhi512: {
15290 APValue R;
15291 if (!evalShuffleGeneric(Info, E, R,
15292 [](unsigned DstIdx, unsigned ShuffleMask) {
15293 int Offset = ShuffleMask & 0x1F;
15294 unsigned SrcIdx = (ShuffleMask >> 5) & 0x1;
15295 return std::pair<unsigned, int>{SrcIdx, Offset};
15296 }))
15297 return false;
15298 return Success(R, E);
15299 }
15300 case X86::BI__builtin_ia32_vpermi2varqi512: {
15301 APValue R;
15302 if (!evalShuffleGeneric(Info, E, R,
15303 [](unsigned DstIdx, unsigned ShuffleMask) {
15304 int Offset = ShuffleMask & 0x3F;
15305 unsigned SrcIdx = (ShuffleMask >> 6) & 0x1;
15306 return std::pair<unsigned, int>{SrcIdx, Offset};
15307 }))
15308 return false;
15309 return Success(R, E);
15310 }
15311
15312 case clang::X86::BI__builtin_ia32_minps:
15313 case clang::X86::BI__builtin_ia32_minpd:
15314 case clang::X86::BI__builtin_ia32_minps256:
15315 case clang::X86::BI__builtin_ia32_minpd256:
15316 case clang::X86::BI__builtin_ia32_minps512:
15317 case clang::X86::BI__builtin_ia32_minpd512:
15318 case clang::X86::BI__builtin_ia32_minph128:
15319 case clang::X86::BI__builtin_ia32_minph256:
15320 case clang::X86::BI__builtin_ia32_minph512:
15321 return EvaluateFpBinOpExpr(
15322 [](const APFloat &A, const APFloat &B,
15323 std::optional<APSInt>) -> std::optional<APFloat> {
15324 if (A.isNaN() || A.isInfinity() || A.isDenormal() || B.isNaN() ||
15325 B.isInfinity() || B.isDenormal())
15326 return std::nullopt;
15327 if (A.isZero() && B.isZero())
15328 return B;
15329 return llvm::minimum(A, B);
15330 });
15331
15332 case clang::X86::BI__builtin_ia32_minss:
15333 case clang::X86::BI__builtin_ia32_minsd:
15334 return EvaluateFpBinOpExpr(
15335 [](const APFloat &A, const APFloat &B,
15336 std::optional<APSInt> RoundingMode) -> std::optional<APFloat> {
15337 return EvalScalarMinMaxFp(A, B, RoundingMode, /*IsMin=*/true);
15338 },
15339 /*IsScalar=*/true);
15340
15341 case clang::X86::BI__builtin_ia32_minsd_round_mask:
15342 case clang::X86::BI__builtin_ia32_minss_round_mask:
15343 case clang::X86::BI__builtin_ia32_minsh_round_mask:
15344 case clang::X86::BI__builtin_ia32_maxsd_round_mask:
15345 case clang::X86::BI__builtin_ia32_maxss_round_mask:
15346 case clang::X86::BI__builtin_ia32_maxsh_round_mask: {
15347 bool IsMin = BuiltinOp == clang::X86::BI__builtin_ia32_minsd_round_mask ||
15348 BuiltinOp == clang::X86::BI__builtin_ia32_minss_round_mask ||
15349 BuiltinOp == clang::X86::BI__builtin_ia32_minsh_round_mask;
15350 return EvaluateScalarFpRoundMaskBinOp(
15351 [IsMin](const APFloat &A, const APFloat &B,
15352 std::optional<APSInt> RoundingMode) -> std::optional<APFloat> {
15353 return EvalScalarMinMaxFp(A, B, RoundingMode, IsMin);
15354 });
15355 }
15356
15357 case clang::X86::BI__builtin_ia32_maxps:
15358 case clang::X86::BI__builtin_ia32_maxpd:
15359 case clang::X86::BI__builtin_ia32_maxps256:
15360 case clang::X86::BI__builtin_ia32_maxpd256:
15361 case clang::X86::BI__builtin_ia32_maxps512:
15362 case clang::X86::BI__builtin_ia32_maxpd512:
15363 case clang::X86::BI__builtin_ia32_maxph128:
15364 case clang::X86::BI__builtin_ia32_maxph256:
15365 case clang::X86::BI__builtin_ia32_maxph512:
15366 return EvaluateFpBinOpExpr(
15367 [](const APFloat &A, const APFloat &B,
15368 std::optional<APSInt>) -> std::optional<APFloat> {
15369 if (A.isNaN() || A.isInfinity() || A.isDenormal() || B.isNaN() ||
15370 B.isInfinity() || B.isDenormal())
15371 return std::nullopt;
15372 if (A.isZero() && B.isZero())
15373 return B;
15374 return llvm::maximum(A, B);
15375 });
15376
15377 case clang::X86::BI__builtin_ia32_maxss:
15378 case clang::X86::BI__builtin_ia32_maxsd:
15379 return EvaluateFpBinOpExpr(
15380 [](const APFloat &A, const APFloat &B,
15381 std::optional<APSInt> RoundingMode) -> std::optional<APFloat> {
15382 return EvalScalarMinMaxFp(A, B, RoundingMode, /*IsMin=*/false);
15383 },
15384 /*IsScalar=*/true);
15385
15386 case clang::X86::BI__builtin_ia32_vcvtps2ph:
15387 case clang::X86::BI__builtin_ia32_vcvtps2ph256: {
15388 APValue SrcVec;
15389 if (!EvaluateAsRValue(Info, E->getArg(0), SrcVec))
15390 return false;
15391
15392 APSInt Imm;
15393 if (!EvaluateInteger(E->getArg(1), Imm, Info))
15394 return false;
15395
15396 const auto *SrcVTy = E->getArg(0)->getType()->castAs<VectorType>();
15397 unsigned SrcNumElems = SrcVTy->getNumElements();
15398 const auto *DstVTy = E->getType()->castAs<VectorType>();
15399 unsigned DstNumElems = DstVTy->getNumElements();
15400 QualType DstElemTy = DstVTy->getElementType();
15401
15402 const llvm::fltSemantics &HalfSem =
15403 Info.Ctx.getFloatTypeSemantics(Info.Ctx.HalfTy);
15404
15405 int ImmVal = Imm.getZExtValue();
15406 bool UseMXCSR = (ImmVal & 4) != 0;
15407 bool IsFPConstrained =
15408 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained();
15409
15410 llvm::RoundingMode RM;
15411 if (!UseMXCSR) {
15412 switch (ImmVal & 3) {
15413 case 0:
15414 RM = llvm::RoundingMode::NearestTiesToEven;
15415 break;
15416 case 1:
15417 RM = llvm::RoundingMode::TowardNegative;
15418 break;
15419 case 2:
15420 RM = llvm::RoundingMode::TowardPositive;
15421 break;
15422 case 3:
15423 RM = llvm::RoundingMode::TowardZero;
15424 break;
15425 default:
15426 llvm_unreachable("Invalid immediate rounding mode");
15427 }
15428 } else {
15429 RM = llvm::RoundingMode::NearestTiesToEven;
15430 }
15431
15432 SmallVector<APValue, 8> ResultElements;
15433 ResultElements.reserve(DstNumElems);
15434
15435 for (unsigned I = 0; I < SrcNumElems; ++I) {
15436 APFloat SrcVal = SrcVec.getVectorElt(I).getFloat();
15437
15438 bool LostInfo;
15439 APFloat::opStatus St = SrcVal.convert(HalfSem, RM, &LostInfo);
15440
15441 if (UseMXCSR && IsFPConstrained && St != APFloat::opOK) {
15442 Info.FFDiag(E, diag::note_constexpr_dynamic_rounding);
15443 return false;
15444 }
15445
15446 APSInt DstInt(SrcVal.bitcastToAPInt(),
15448 ResultElements.push_back(APValue(DstInt));
15449 }
15450
15451 if (DstNumElems > SrcNumElems) {
15452 APSInt Zero = Info.Ctx.MakeIntValue(0, DstElemTy);
15453 for (unsigned I = SrcNumElems; I < DstNumElems; ++I) {
15454 ResultElements.push_back(APValue(Zero));
15455 }
15456 }
15457
15458 return Success(ResultElements, E);
15459 }
15460 case X86::BI__builtin_ia32_vperm2f128_pd256:
15461 case X86::BI__builtin_ia32_vperm2f128_ps256:
15462 case X86::BI__builtin_ia32_vperm2f128_si256:
15463 case X86::BI__builtin_ia32_permti256: {
15464 unsigned NumElements =
15465 E->getArg(0)->getType()->getAs<VectorType>()->getNumElements();
15466 unsigned PreservedBitsCnt = NumElements >> 2;
15467 APValue R;
15468 if (!evalShuffleGeneric(
15469 Info, E, R,
15470 [PreservedBitsCnt](unsigned DstIdx, unsigned ShuffleMask) {
15471 unsigned ControlBitsCnt = DstIdx >> PreservedBitsCnt << 2;
15472 unsigned ControlBits = ShuffleMask >> ControlBitsCnt;
15473
15474 if (ControlBits & 0b1000)
15475 return std::make_pair(0u, -1);
15476
15477 unsigned SrcVecIdx = (ControlBits & 0b10) >> 1;
15478 unsigned PreservedBitsMask = (1 << PreservedBitsCnt) - 1;
15479 int SrcIdx = ((ControlBits & 0b1) << PreservedBitsCnt) |
15480 (DstIdx & PreservedBitsMask);
15481 return std::make_pair(SrcVecIdx, SrcIdx);
15482 }))
15483 return false;
15484 return Success(R, E);
15485 }
15486 case X86::BI__builtin_ia32_vpdpwssd128:
15487 case X86::BI__builtin_ia32_vpdpwssd256:
15488 case X86::BI__builtin_ia32_vpdpwssd512:
15489 case X86::BI__builtin_ia32_vpdpbusd128:
15490 case X86::BI__builtin_ia32_vpdpbusd256:
15491 case X86::BI__builtin_ia32_vpdpbusd512:
15492 return EvalVectorDotProduct(false);
15493 case X86::BI__builtin_ia32_vpdpwssds128:
15494 case X86::BI__builtin_ia32_vpdpwssds256:
15495 case X86::BI__builtin_ia32_vpdpwssds512:
15496 case X86::BI__builtin_ia32_vpdpbusds128:
15497 case X86::BI__builtin_ia32_vpdpbusds256:
15498 case X86::BI__builtin_ia32_vpdpbusds512:
15499 return EvalVectorDotProduct(true);
15500 case X86::BI__builtin_ia32_cvtpd2dq:
15501 case X86::BI__builtin_ia32_cvtps2dq:
15502 case X86::BI__builtin_ia32_cvttpd2dq:
15503 case X86::BI__builtin_ia32_cvttps2dq:
15504 case X86::BI__builtin_ia32_cvtpd2dq256:
15505 case X86::BI__builtin_ia32_cvtps2dq256:
15506 case X86::BI__builtin_ia32_cvttpd2dq256:
15507 case X86::BI__builtin_ia32_cvttps2dq256: {
15508 APValue SrcVec;
15509 if (!EvaluateAsRValue(Info, E->getArg(0), SrcVec) || !SrcVec.isVector())
15510 return false;
15511
15512 const auto *VT = E->getType()->castAs<VectorType>();
15513 QualType EltTy = VT->getElementType();
15514 bool isUnsigned = EltTy->isUnsignedIntegerType();
15515 unsigned BitWidth = Info.Ctx.getIntWidth(EltTy);
15516
15517 unsigned NumSrcElems = SrcVec.getVectorLength();
15518 unsigned NumDstElems = VT->getNumElements();
15519
15520 SmallVector<APValue, 8> ResultElts;
15521 for (unsigned i = 0; i != NumDstElems; ++i) {
15522 if (i < NumSrcElems) {
15523 llvm::APFloat FloatElem = SrcVec.getVectorElt(i).getFloat();
15524 llvm::APSInt IntResult(BitWidth, isUnsigned);
15525 bool IsExact = false;
15526 // We only allow exact conversions so rounding mode does not matter for
15527 // cvt* and cvtt* builtins
15528 FloatElem.convertToInteger(IntResult, llvm::APFloat::rmTowardZero,
15529 &IsExact);
15530 if (!IsExact)
15531 return false;
15532 ResultElts.push_back(APValue(IntResult));
15533 } else
15534 // Pad remaining lanes with zero
15535 ResultElts.push_back(APValue(llvm::APSInt(BitWidth, isUnsigned)));
15536 }
15537 return Success(ResultElts, E);
15538 }
15539 }
15540}
15541
15542bool VectorExprEvaluator::VisitConvertVectorExpr(const ConvertVectorExpr *E) {
15543 APValue Source;
15544 QualType SourceVecType = E->getSrcExpr()->getType();
15545 if (!EvaluateAsRValue(Info, E->getSrcExpr(), Source))
15546 return false;
15547
15548 QualType DestTy = E->getType()->castAs<VectorType>()->getElementType();
15549 QualType SourceTy = SourceVecType->castAs<VectorType>()->getElementType();
15550
15551 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
15552
15553 auto SourceLen = Source.getVectorLength();
15554 SmallVector<APValue, 4> ResultElements;
15555 ResultElements.reserve(SourceLen);
15556 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
15557 APValue Elt;
15558 if (!handleVectorElementCast(Info, FPO, E, SourceTy, DestTy,
15559 Source.getVectorElt(EltNum), Elt))
15560 return false;
15561 ResultElements.push_back(std::move(Elt));
15562 }
15563
15564 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
15565}
15566
15567static bool handleVectorShuffle(EvalInfo &Info, const ShuffleVectorExpr *E,
15568 QualType ElemType, APValue const &VecVal1,
15569 APValue const &VecVal2, unsigned EltNum,
15570 APValue &Result) {
15571 unsigned const TotalElementsInInputVector1 = VecVal1.getVectorLength();
15572 unsigned const TotalElementsInInputVector2 = VecVal2.getVectorLength();
15573
15574 APSInt IndexVal = E->getShuffleMaskIdx(EltNum);
15575 int64_t index = IndexVal.getExtValue();
15576 // The spec says that -1 should be treated as undef for optimizations,
15577 // but in constexpr we'd have to produce an APValue::Indeterminate,
15578 // which is prohibited from being a top-level constant value. Emit a
15579 // diagnostic instead.
15580 if (index == -1) {
15581 Info.FFDiag(
15582 E, diag::err_shufflevector_minus_one_is_undefined_behavior_constexpr)
15583 << EltNum;
15584 return false;
15585 }
15586
15587 if (index < 0 ||
15588 index >= TotalElementsInInputVector1 + TotalElementsInInputVector2)
15589 llvm_unreachable("Out of bounds shuffle index");
15590
15591 if (index >= TotalElementsInInputVector1)
15592 Result = VecVal2.getVectorElt(index - TotalElementsInInputVector1);
15593 else
15594 Result = VecVal1.getVectorElt(index);
15595 return true;
15596}
15597
15598bool VectorExprEvaluator::VisitShuffleVectorExpr(const ShuffleVectorExpr *E) {
15599 // FIXME: Unary shuffle with mask not currently supported.
15600 if (E->getNumSubExprs() == 2)
15601 return Error(E);
15602 APValue VecVal1;
15603 const Expr *Vec1 = E->getExpr(0);
15604 if (!EvaluateAsRValue(Info, Vec1, VecVal1))
15605 return false;
15606 APValue VecVal2;
15607 const Expr *Vec2 = E->getExpr(1);
15608 if (!EvaluateAsRValue(Info, Vec2, VecVal2))
15609 return false;
15610
15611 VectorType const *DestVecTy = E->getType()->castAs<VectorType>();
15612 QualType DestElTy = DestVecTy->getElementType();
15613
15614 auto TotalElementsInOutputVector = DestVecTy->getNumElements();
15615
15616 SmallVector<APValue, 4> ResultElements;
15617 ResultElements.reserve(TotalElementsInOutputVector);
15618 for (unsigned EltNum = 0; EltNum < TotalElementsInOutputVector; ++EltNum) {
15619 APValue Elt;
15620 if (!handleVectorShuffle(Info, E, DestElTy, VecVal1, VecVal2, EltNum, Elt))
15621 return false;
15622 ResultElements.push_back(std::move(Elt));
15623 }
15624
15625 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
15626}
15627
15628//===----------------------------------------------------------------------===//
15629// Matrix Evaluation
15630//===----------------------------------------------------------------------===//
15631
15632namespace {
15633class MatrixExprEvaluator : public ExprEvaluatorBase<MatrixExprEvaluator> {
15634 APValue &Result;
15635
15636public:
15637 MatrixExprEvaluator(EvalInfo &Info, APValue &Result)
15638 : ExprEvaluatorBaseTy(Info), Result(Result) {}
15639
15640 bool Success(ArrayRef<APValue> M, const Expr *E) {
15641 auto *CMTy = E->getType()->castAs<ConstantMatrixType>();
15642 assert(M.size() == CMTy->getNumElementsFlattened());
15643 // FIXME: remove this APValue copy.
15644 Result = APValue(M.data(), CMTy->getNumRows(), CMTy->getNumColumns());
15645 return true;
15646 }
15647 bool Success(const APValue &M, const Expr *E) {
15648 assert(M.isMatrix() && "expected matrix");
15649 Result = M;
15650 return true;
15651 }
15652
15653 bool VisitCastExpr(const CastExpr *E);
15654 bool VisitInitListExpr(const InitListExpr *E);
15655};
15656} // end anonymous namespace
15657
15658static bool EvaluateMatrix(const Expr *E, APValue &Result, EvalInfo &Info) {
15659 assert(E->isPRValue() && E->getType()->isConstantMatrixType() &&
15660 "not a matrix prvalue");
15661 return MatrixExprEvaluator(Info, Result).Visit(E);
15662}
15663
15664bool MatrixExprEvaluator::VisitCastExpr(const CastExpr *E) {
15665 const auto *MT = E->getType()->castAs<ConstantMatrixType>();
15666 unsigned NumRows = MT->getNumRows();
15667 unsigned NumCols = MT->getNumColumns();
15668 unsigned NElts = NumRows * NumCols;
15669 QualType EltTy = MT->getElementType();
15670 const Expr *SE = E->getSubExpr();
15671
15672 switch (E->getCastKind()) {
15673 case CK_HLSLAggregateSplatCast: {
15674 APValue Val;
15675 QualType ValTy;
15676
15677 if (!hlslAggSplatHelper(Info, SE, Val, ValTy))
15678 return false;
15679
15680 APValue CastedVal;
15681 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
15682 if (!handleScalarCast(Info, FPO, E, ValTy, EltTy, Val, CastedVal))
15683 return false;
15684
15685 SmallVector<APValue, 16> SplatEls(NElts, CastedVal);
15686 return Success(SplatEls, E);
15687 }
15688 case CK_HLSLElementwiseCast: {
15689 SmallVector<APValue> SrcVals;
15690 SmallVector<QualType> SrcTypes;
15691
15692 if (!hlslElementwiseCastHelper(Info, SE, E->getType(), SrcVals, SrcTypes))
15693 return false;
15694
15695 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
15696 SmallVector<QualType, 16> DestTypes(NElts, EltTy);
15697 SmallVector<APValue, 16> ResultEls(NElts);
15698 if (!handleElementwiseCast(Info, E, FPO, SrcVals, SrcTypes, DestTypes,
15699 ResultEls))
15700 return false;
15701 return Success(ResultEls, E);
15702 }
15703 default:
15704 return ExprEvaluatorBaseTy::VisitCastExpr(E);
15705 }
15706}
15707
15708bool MatrixExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
15709 const auto *MT = E->getType()->castAs<ConstantMatrixType>();
15710 QualType EltTy = MT->getElementType();
15711
15712 assert(E->getNumInits() == MT->getNumElementsFlattened() &&
15713 "Expected number of elements in initializer list to match the number "
15714 "of matrix elements");
15715
15716 SmallVector<APValue, 16> Elements;
15717 Elements.reserve(MT->getNumElementsFlattened());
15718
15719 // The following loop assumes the elements of the matrix InitListExpr are in
15720 // row-major order, which matches the row-major ordering assumption of the
15721 // matrix APValue.
15722 for (unsigned I = 0, N = MT->getNumElementsFlattened(); I < N; ++I) {
15723 if (EltTy->isIntegerType()) {
15724 llvm::APSInt IntVal;
15725 if (!EvaluateInteger(E->getInit(I), IntVal, Info))
15726 return false;
15727 Elements.push_back(APValue(IntVal));
15728 } else {
15729 llvm::APFloat FloatVal(0.0);
15730 if (!EvaluateFloat(E->getInit(I), FloatVal, Info))
15731 return false;
15732 Elements.push_back(APValue(FloatVal));
15733 }
15734 }
15735
15736 return Success(Elements, E);
15737}
15738
15739//===----------------------------------------------------------------------===//
15740// Array Evaluation
15741//===----------------------------------------------------------------------===//
15742
15743namespace {
15744 class ArrayExprEvaluator
15745 : public ExprEvaluatorBase<ArrayExprEvaluator> {
15746 const LValue &This;
15747 APValue &Result;
15748 public:
15749
15750 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
15751 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
15752
15753 bool Success(const APValue &V, const Expr *E) {
15754 assert(V.isArray() && "expected array");
15755 Result = V;
15756 return true;
15757 }
15758
15759 bool ZeroInitialization(const Expr *E) {
15760 const ConstantArrayType *CAT =
15761 Info.Ctx.getAsConstantArrayType(E->getType());
15762 if (!CAT) {
15763 if (E->getType()->isIncompleteArrayType()) {
15764 // We can be asked to zero-initialize a flexible array member; this
15765 // is represented as an ImplicitValueInitExpr of incomplete array
15766 // type. In this case, the array has zero elements.
15767 Result = APValue(APValue::UninitArray(), 0, 0);
15768 return true;
15769 }
15770 // FIXME: We could handle VLAs here.
15771 return Error(E);
15772 }
15773
15774 Result = APValue(APValue::UninitArray(), 0, CAT->getZExtSize());
15775 if (!Result.hasArrayFiller())
15776 return true;
15777
15778 // Zero-initialize all elements.
15779 LValue Subobject = This;
15780 Subobject.addArray(Info, E, CAT);
15781 ImplicitValueInitExpr VIE(CAT->getElementType());
15782 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
15783 }
15784
15785 bool VisitCallExpr(const CallExpr *E) {
15786 return handleCallExpr(E, Result, &This);
15787 }
15788 bool VisitCastExpr(const CastExpr *E);
15789 bool VisitInitListExpr(const InitListExpr *E,
15790 QualType AllocType = QualType());
15791 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
15792 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
15793 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
15794 const LValue &Subobject,
15795 APValue *Value, QualType Type);
15796 bool VisitStringLiteral(const StringLiteral *E,
15797 QualType AllocType = QualType()) {
15798 expandStringLiteral(Info, E, Result, AllocType);
15799 return true;
15800 }
15801 bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E);
15802 bool VisitCXXParenListOrInitListExpr(const Expr *ExprToVisit,
15803 ArrayRef<Expr *> Args,
15804 const Expr *ArrayFiller,
15805 QualType AllocType = QualType());
15806 bool VisitDesignatedInitUpdateExpr(const DesignatedInitUpdateExpr *E);
15807 };
15808} // end anonymous namespace
15809
15810static bool EvaluateArray(const Expr *E, const LValue &This,
15811 APValue &Result, EvalInfo &Info) {
15812 assert(!E->isValueDependent());
15813 assert(E->isPRValue() && E->getType()->isArrayType() &&
15814 "not an array prvalue");
15815 return ArrayExprEvaluator(Info, This, Result).Visit(E);
15816}
15817
15818static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
15819 APValue &Result, const InitListExpr *ILE,
15820 QualType AllocType) {
15821 assert(!ILE->isValueDependent());
15822 assert(ILE->isPRValue() && ILE->getType()->isArrayType() &&
15823 "not an array prvalue");
15824 return ArrayExprEvaluator(Info, This, Result)
15825 .VisitInitListExpr(ILE, AllocType);
15826}
15827
15828static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
15829 APValue &Result,
15830 const CXXConstructExpr *CCE,
15831 QualType AllocType) {
15832 assert(!CCE->isValueDependent());
15833 assert(CCE->isPRValue() && CCE->getType()->isArrayType() &&
15834 "not an array prvalue");
15835 return ArrayExprEvaluator(Info, This, Result)
15836 .VisitCXXConstructExpr(CCE, This, &Result, AllocType);
15837}
15838
15839// Return true iff the given array filler may depend on the element index.
15840static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
15841 // For now, just allow non-class value-initialization and initialization
15842 // lists comprised of them.
15843 if (isa<ImplicitValueInitExpr>(FillerExpr))
15844 return false;
15845 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
15846 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
15847 if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
15848 return true;
15849 }
15850
15851 if (ILE->hasArrayFiller() &&
15852 MaybeElementDependentArrayFiller(ILE->getArrayFiller()))
15853 return true;
15854
15855 return false;
15856 }
15857 return true;
15858}
15859
15860bool ArrayExprEvaluator::VisitCastExpr(const CastExpr *E) {
15861 const Expr *SE = E->getSubExpr();
15862
15863 switch (E->getCastKind()) {
15864 default:
15865 return ExprEvaluatorBaseTy::VisitCastExpr(E);
15866 case CK_HLSLAggregateSplatCast: {
15867 APValue Val;
15868 QualType ValTy;
15869
15870 if (!hlslAggSplatHelper(Info, SE, Val, ValTy))
15871 return false;
15872
15873 unsigned NEls = elementwiseSize(Info, E->getType());
15874
15875 SmallVector<APValue> SplatEls(NEls, Val);
15876 SmallVector<QualType> SplatType(NEls, ValTy);
15877
15878 // cast the elements
15879 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
15880 if (!constructAggregate(Info, FPO, E, Result, E->getType(), SplatEls,
15881 SplatType))
15882 return false;
15883
15884 return true;
15885 }
15886 case CK_HLSLElementwiseCast: {
15887 SmallVector<APValue> SrcEls;
15888 SmallVector<QualType> SrcTypes;
15889
15890 if (!hlslElementwiseCastHelper(Info, SE, E->getType(), SrcEls, SrcTypes))
15891 return false;
15892
15893 // cast the elements
15894 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
15895 if (!constructAggregate(Info, FPO, E, Result, E->getType(), SrcEls,
15896 SrcTypes))
15897 return false;
15898 return true;
15899 }
15900 }
15901}
15902
15903bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E,
15904 QualType AllocType) {
15905 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
15906 AllocType.isNull() ? E->getType() : AllocType);
15907 if (!CAT)
15908 return Error(E);
15909
15910 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
15911 // an appropriately-typed string literal enclosed in braces.
15912 if (E->isStringLiteralInit()) {
15913 auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParenImpCasts());
15914 // FIXME: Support ObjCEncodeExpr here once we support it in
15915 // ArrayExprEvaluator generally.
15916 if (!SL)
15917 return Error(E);
15918 return VisitStringLiteral(SL, AllocType);
15919 }
15920 // Any other transparent list init will need proper handling of the
15921 // AllocType; we can't just recurse to the inner initializer.
15922 assert(!E->isTransparent() &&
15923 "transparent array list initialization is not string literal init?");
15924
15925 return VisitCXXParenListOrInitListExpr(E, E->inits(), E->getArrayFiller(),
15926 AllocType);
15927}
15928
15929bool ArrayExprEvaluator::VisitCXXParenListOrInitListExpr(
15930 const Expr *ExprToVisit, ArrayRef<Expr *> Args, const Expr *ArrayFiller,
15931 QualType AllocType) {
15932 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
15933 AllocType.isNull() ? ExprToVisit->getType() : AllocType);
15934
15935 bool Success = true;
15936
15937 unsigned NumEltsToInit = Args.size();
15938 unsigned NumElts = CAT->getZExtSize();
15939
15940 // If the initializer might depend on the array index, run it for each
15941 // array element.
15942 if (NumEltsToInit != NumElts &&
15943 MaybeElementDependentArrayFiller(ArrayFiller)) {
15944 NumEltsToInit = NumElts;
15945 } else {
15946 // Add additional elements represented by EmbedExpr.
15947 for (auto *Init : Args) {
15948 if (auto *EmbedS = dyn_cast<EmbedExpr>(Init->IgnoreParenImpCasts()))
15949 NumEltsToInit += EmbedS->getDataElementCount() - 1;
15950 }
15951 // If we have extra elements in the list, they will be discarded.
15952 if (NumEltsToInit > NumElts)
15953 NumEltsToInit = NumElts;
15954 // If we're overwriting memory which already has an object, make sure we
15955 // don't reduce the number of non-filler elements. (It's possible to
15956 // optimize this in some cases, but the logic gets really complicated.)
15957 if (Result.hasValue() && NumEltsToInit < Result.getArrayInitializedElts())
15958 NumEltsToInit = Result.getArrayInitializedElts();
15959 }
15960
15961 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
15962 << NumEltsToInit << ".\n");
15963
15964 if (!Result.hasValue()) {
15965 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
15966 } else if (Result.getArrayInitializedElts() != NumEltsToInit) {
15967 // Number of inititalized elts changed. Recreate the APValue, and copy over
15968 // the relevant elements. (This is essentially just fixing the internal
15969 // representation of the value, because it's tied to the number of
15970 // non-filler elements.)
15971 //
15972 // This should be hit rarely, but there are some edge cases:
15973 //
15974 // - The array could be zero-initialized.
15975 // - There could be a DesignatedInitListExpr.
15976 // - operator new[] can be used to start the lifetime early.
15977 APValue NewResult = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
15978 // First copy existing elements.
15979 unsigned NumOldElts = Result.getArrayInitializedElts();
15980 for (unsigned I = 0; I < NumOldElts; ++I) {
15981 NewResult.getArrayInitializedElt(I) =
15982 std::move(Result.getArrayInitializedElt(I));
15983 }
15984 // Then copy the array filler over the remaining elements.
15985 for (unsigned I = Result.getArrayInitializedElts(); I < NumEltsToInit; ++I)
15987 if (NewResult.hasArrayFiller() && Result.hasArrayFiller())
15988 NewResult.getArrayFiller() = Result.getArrayFiller();
15989 Result = std::move(NewResult);
15990 }
15991
15992 LValue Subobject = This;
15993 Subobject.addArray(Info, ExprToVisit, CAT);
15994 auto Eval = [&](const Expr *Init, unsigned ArrayIndex) {
15995 if (Init->isValueDependent())
15996 return EvaluateDependentExpr(Init, Info);
15997
15998 // If this is a child of a DesignatedInitUpdateExpr, skip elements which
15999 // aren't supposed to be modified.
16000 if (isa<NoInitExpr>(Init))
16001 return true;
16002
16003 if (!EvaluateInPlace(Result.getArrayInitializedElt(ArrayIndex), Info,
16004 Subobject, Init) ||
16005 !HandleLValueArrayAdjustment(Info, Init, Subobject,
16006 CAT->getElementType(), 1)) {
16007 if (!Info.noteFailure())
16008 return false;
16009 Success = false;
16010 }
16011 return true;
16012 };
16013 unsigned ArrayIndex = 0;
16014 QualType DestTy = CAT->getElementType();
16015 APSInt Value(Info.Ctx.getTypeSize(DestTy), DestTy->isUnsignedIntegerType());
16016 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
16017 const Expr *Init = Index < Args.size() ? Args[Index] : ArrayFiller;
16018 if (ArrayIndex >= NumEltsToInit)
16019 break;
16020 if (auto *EmbedS = dyn_cast<EmbedExpr>(Init->IgnoreParenImpCasts())) {
16021 StringLiteral *SL = EmbedS->getDataStringLiteral();
16022 for (unsigned I = EmbedS->getStartingElementPos(),
16023 N = EmbedS->getDataElementCount();
16024 I != EmbedS->getStartingElementPos() + N; ++I) {
16025 Value = SL->getCodeUnit(I);
16026 if (DestTy->isIntegerType()) {
16027 Result.getArrayInitializedElt(ArrayIndex) = APValue(Value);
16028 } else {
16029 assert(DestTy->isFloatingType() && "unexpected type");
16030 const FPOptions FPO =
16031 Init->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
16032 APFloat FValue(0.0);
16033 if (!HandleIntToFloatCast(Info, Init, FPO, EmbedS->getType(), Value,
16034 DestTy, FValue))
16035 return false;
16036 Result.getArrayInitializedElt(ArrayIndex) = APValue(FValue);
16037 }
16038 ArrayIndex++;
16039 }
16040 } else {
16041 if (!Eval(Init, ArrayIndex))
16042 return false;
16043 ++ArrayIndex;
16044 }
16045 }
16046
16047 if (!Result.hasArrayFiller())
16048 return Success;
16049
16050 // If we get here, we have a trivial filler, which we can just evaluate
16051 // once and splat over the rest of the array elements.
16052 assert(ArrayFiller && "no array filler for incomplete init list");
16053 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
16054 ArrayFiller) &&
16055 Success;
16056}
16057
16058bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
16059 LValue CommonLV;
16060 if (E->getCommonExpr() &&
16061 !Evaluate(Info.CurrentCall->createTemporary(
16062 E->getCommonExpr(),
16063 getStorageType(Info.Ctx, E->getCommonExpr()),
16064 ScopeKind::FullExpression, CommonLV),
16065 Info, E->getCommonExpr()->getSourceExpr()))
16066 return false;
16067
16069 if (!CheckArraySize(Info, CAT, E->getExprLoc()))
16070 return false;
16071
16072 uint64_t Elements = CAT->getZExtSize();
16073 Result = APValue(APValue::UninitArray(), Elements, Elements);
16074
16075 LValue Subobject = This;
16076 Subobject.addArray(Info, E, CAT);
16077
16078 bool Success = true;
16079 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
16080 // C++ [class.temporary]/5
16081 // There are four contexts in which temporaries are destroyed at a different
16082 // point than the end of the full-expression. [...] The second context is
16083 // when a copy constructor is called to copy an element of an array while
16084 // the entire array is copied [...]. In either case, if the constructor has
16085 // one or more default arguments, the destruction of every temporary created
16086 // in a default argument is sequenced before the construction of the next
16087 // array element, if any.
16088 FullExpressionRAII Scope(Info);
16089
16090 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
16091 Info, Subobject, E->getSubExpr()) ||
16092 !HandleLValueArrayAdjustment(Info, E, Subobject,
16093 CAT->getElementType(), 1)) {
16094 if (!Info.noteFailure())
16095 return false;
16096 Success = false;
16097 }
16098
16099 // Make sure we run the destructors too.
16100 Scope.destroy();
16101 }
16102
16103 return Success;
16104}
16105
16106bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
16107 return VisitCXXConstructExpr(E, This, &Result, E->getType());
16108}
16109
16110bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
16111 const LValue &Subobject,
16112 APValue *Value,
16113 QualType Type) {
16114 bool HadZeroInit = Value->hasValue();
16115
16116 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
16117 if (!CheckArraySize(Info, CAT, E->getExprLoc()))
16118 return false;
16119 unsigned FinalSize = CAT->getZExtSize();
16120
16121 // Preserve the array filler if we had prior zero-initialization.
16122 APValue Filler =
16123 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
16124 : APValue();
16125
16126 *Value = APValue(APValue::UninitArray(), 0, FinalSize);
16127 if (FinalSize == 0)
16128 return true;
16129
16130 bool HasTrivialConstructor = CheckTrivialDefaultConstructor(
16131 Info, E->getExprLoc(), E->getConstructor(),
16133 LValue ArrayElt = Subobject;
16134 ArrayElt.addArray(Info, E, CAT);
16135 // We do the whole initialization in two passes, first for just one element,
16136 // then for the whole array. It's possible we may find out we can't do const
16137 // init in the first pass, in which case we avoid allocating a potentially
16138 // large array. We don't do more passes because expanding array requires
16139 // copying the data, which is wasteful.
16140 for (const unsigned N : {1u, FinalSize}) {
16141 unsigned OldElts = Value->getArrayInitializedElts();
16142 if (OldElts == N)
16143 break;
16144
16145 // Expand the array to appropriate size.
16146 APValue NewValue(APValue::UninitArray(), N, FinalSize);
16147 for (unsigned I = 0; I < OldElts; ++I)
16148 NewValue.getArrayInitializedElt(I).swap(
16149 Value->getArrayInitializedElt(I));
16150 Value->swap(NewValue);
16151
16152 if (HadZeroInit)
16153 for (unsigned I = OldElts; I < N; ++I)
16154 Value->getArrayInitializedElt(I) = Filler;
16155
16156 if (HasTrivialConstructor && N == FinalSize && FinalSize != 1) {
16157 // If we have a trivial constructor, only evaluate it once and copy
16158 // the result into all the array elements.
16159 APValue &FirstResult = Value->getArrayInitializedElt(0);
16160 for (unsigned I = OldElts; I < FinalSize; ++I)
16161 Value->getArrayInitializedElt(I) = FirstResult;
16162 } else {
16163 for (unsigned I = OldElts; I < N; ++I) {
16164 if (!VisitCXXConstructExpr(E, ArrayElt,
16165 &Value->getArrayInitializedElt(I),
16166 CAT->getElementType()) ||
16167 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
16168 CAT->getElementType(), 1))
16169 return false;
16170 // When checking for const initilization any diagnostic is considered
16171 // an error.
16172 if (Info.EvalStatus.Diag && !Info.EvalStatus.Diag->empty() &&
16173 !Info.keepEvaluatingAfterFailure())
16174 return false;
16175 }
16176 }
16177 }
16178
16179 return true;
16180 }
16181
16182 if (!Type->isRecordType())
16183 return Error(E);
16184
16185 return RecordExprEvaluator(Info, Subobject, *Value)
16186 .VisitCXXConstructExpr(E, Type);
16187}
16188
16189bool ArrayExprEvaluator::VisitCXXParenListInitExpr(
16190 const CXXParenListInitExpr *E) {
16191 assert(E->getType()->isConstantArrayType() &&
16192 "Expression result is not a constant array type");
16193
16194 return VisitCXXParenListOrInitListExpr(E, E->getInitExprs(),
16195 E->getArrayFiller());
16196}
16197
16198bool ArrayExprEvaluator::VisitDesignatedInitUpdateExpr(
16199 const DesignatedInitUpdateExpr *E) {
16200 if (!Visit(E->getBase()))
16201 return false;
16202 return Visit(E->getUpdater());
16203}
16204
16205//===----------------------------------------------------------------------===//
16206// Integer Evaluation
16207//
16208// As a GNU extension, we support casting pointers to sufficiently-wide integer
16209// types and back in constant folding. Integer values are thus represented
16210// either as an integer-valued APValue, or as an lvalue-valued APValue.
16211//===----------------------------------------------------------------------===//
16212
16213namespace {
16214class IntExprEvaluator
16215 : public ExprEvaluatorBase<IntExprEvaluator> {
16216 APValue &Result;
16217public:
16218 IntExprEvaluator(EvalInfo &info, APValue &result)
16219 : ExprEvaluatorBaseTy(info), Result(result) {}
16220
16221 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
16222 assert(E->getType()->isIntegralOrEnumerationType() &&
16223 "Invalid evaluation result.");
16224 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
16225 "Invalid evaluation result.");
16226 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
16227 "Invalid evaluation result.");
16228 Result = APValue(SI);
16229 return true;
16230 }
16231 bool Success(const llvm::APSInt &SI, const Expr *E) {
16232 return Success(SI, E, Result);
16233 }
16234
16235 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
16236 assert(E->getType()->isIntegralOrEnumerationType() &&
16237 "Invalid evaluation result.");
16238 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
16239 "Invalid evaluation result.");
16240 Result = APValue(APSInt(I));
16241 Result.getInt().setIsUnsigned(
16243 return true;
16244 }
16245 bool Success(const llvm::APInt &I, const Expr *E) {
16246 return Success(I, E, Result);
16247 }
16248
16249 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
16250 assert(E->getType()->isIntegralOrEnumerationType() &&
16251 "Invalid evaluation result.");
16252 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
16253 return true;
16254 }
16255 bool Success(uint64_t Value, const Expr *E) {
16256 return Success(Value, E, Result);
16257 }
16258
16259 bool Success(CharUnits Size, const Expr *E) {
16260 return Success(Size.getQuantity(), E);
16261 }
16262
16263 bool Success(const APValue &V, const Expr *E) {
16264 // C++23 [expr.const]p8 If we have a variable that is unknown reference or
16265 // pointer allow further evaluation of the value.
16266 if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate() ||
16267 V.allowConstexprUnknown()) {
16268 Result = V;
16269 return true;
16270 }
16271 return Success(V.getInt(), E);
16272 }
16273
16274 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
16275
16276 friend std::optional<bool> EvaluateBuiltinIsWithinLifetime(IntExprEvaluator &,
16277 const CallExpr *);
16278
16279 //===--------------------------------------------------------------------===//
16280 // Visitor Methods
16281 //===--------------------------------------------------------------------===//
16282
16283 bool VisitIntegerLiteral(const IntegerLiteral *E) {
16284 return Success(E->getValue(), E);
16285 }
16286 bool VisitCharacterLiteral(const CharacterLiteral *E) {
16287 return Success(E->getValue(), E);
16288 }
16289
16290 bool CheckReferencedDecl(const Expr *E, const Decl *D);
16291 bool VisitDeclRefExpr(const DeclRefExpr *E) {
16292 if (CheckReferencedDecl(E, E->getDecl()))
16293 return true;
16294
16295 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
16296 }
16297 bool VisitMemberExpr(const MemberExpr *E) {
16298 if (CheckReferencedDecl(E, E->getMemberDecl())) {
16299 VisitIgnoredBaseExpression(E->getBase());
16300 return true;
16301 }
16302
16303 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
16304 }
16305
16306 bool VisitCallExpr(const CallExpr *E);
16307 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
16308 bool VisitBinaryOperator(const BinaryOperator *E);
16309 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
16310 bool VisitUnaryOperator(const UnaryOperator *E);
16311
16312 bool VisitCastExpr(const CastExpr* E);
16313 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
16314
16315 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
16316 return Success(E->getValue(), E);
16317 }
16318
16319 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
16320 return Success(E->getValue(), E);
16321 }
16322
16323 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
16324 if (Info.ArrayInitIndex == uint64_t(-1)) {
16325 // We were asked to evaluate this subexpression independent of the
16326 // enclosing ArrayInitLoopExpr. We can't do that.
16327 Info.FFDiag(E);
16328 return false;
16329 }
16330 return Success(Info.ArrayInitIndex, E);
16331 }
16332
16333 // Note, GNU defines __null as an integer, not a pointer.
16334 bool VisitGNUNullExpr(const GNUNullExpr *E) {
16335 return ZeroInitialization(E);
16336 }
16337
16338 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
16339 if (E->isStoredAsBoolean())
16340 return Success(E->getBoolValue(), E);
16341 if (E->getAPValue().isAbsent())
16342 return false;
16343 assert(E->getAPValue().isInt() && "APValue type not supported");
16344 return Success(E->getAPValue().getInt(), E);
16345 }
16346
16347 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
16348 return Success(E->getValue(), E);
16349 }
16350
16351 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
16352 return Success(E->getValue(), E);
16353 }
16354
16355 bool VisitOpenACCAsteriskSizeExpr(const OpenACCAsteriskSizeExpr *E) {
16356 // This should not be evaluated during constant expr evaluation, as it
16357 // should always be in an unevaluated context (the args list of a 'gang' or
16358 // 'tile' clause).
16359 return Error(E);
16360 }
16361
16362 bool VisitUnaryReal(const UnaryOperator *E);
16363 bool VisitUnaryImag(const UnaryOperator *E);
16364
16365 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
16366 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
16367 bool VisitSourceLocExpr(const SourceLocExpr *E);
16368 bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E);
16369 bool VisitRequiresExpr(const RequiresExpr *E);
16370 // FIXME: Missing: array subscript of vector, member of vector
16371};
16372
16373class FixedPointExprEvaluator
16374 : public ExprEvaluatorBase<FixedPointExprEvaluator> {
16375 APValue &Result;
16376
16377 public:
16378 FixedPointExprEvaluator(EvalInfo &info, APValue &result)
16379 : ExprEvaluatorBaseTy(info), Result(result) {}
16380
16381 bool Success(const llvm::APInt &I, const Expr *E) {
16382 return Success(
16383 APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
16384 }
16385
16386 bool Success(uint64_t Value, const Expr *E) {
16387 return Success(
16388 APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
16389 }
16390
16391 bool Success(const APValue &V, const Expr *E) {
16392 return Success(V.getFixedPoint(), E);
16393 }
16394
16395 bool Success(const APFixedPoint &V, const Expr *E) {
16396 assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
16397 assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
16398 "Invalid evaluation result.");
16399 Result = APValue(V);
16400 return true;
16401 }
16402
16403 bool ZeroInitialization(const Expr *E) {
16404 return Success(0, E);
16405 }
16406
16407 //===--------------------------------------------------------------------===//
16408 // Visitor Methods
16409 //===--------------------------------------------------------------------===//
16410
16411 bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
16412 return Success(E->getValue(), E);
16413 }
16414
16415 bool VisitCastExpr(const CastExpr *E);
16416 bool VisitUnaryOperator(const UnaryOperator *E);
16417 bool VisitBinaryOperator(const BinaryOperator *E);
16418};
16419} // end anonymous namespace
16420
16421/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
16422/// produce either the integer value or a pointer.
16423///
16424/// GCC has a heinous extension which folds casts between pointer types and
16425/// pointer-sized integral types. We support this by allowing the evaluation of
16426/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
16427/// Some simple arithmetic on such values is supported (they are treated much
16428/// like char*).
16430 EvalInfo &Info) {
16431 assert(!E->isValueDependent());
16432 assert(E->isPRValue() && E->getType()->isIntegralOrEnumerationType());
16433 return IntExprEvaluator(Info, Result).Visit(E);
16434}
16435
16436static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
16437 assert(!E->isValueDependent());
16438 APValue Val;
16439 if (!EvaluateIntegerOrLValue(E, Val, Info))
16440 return false;
16441 if (!Val.isInt()) {
16442 // FIXME: It would be better to produce the diagnostic for casting
16443 // a pointer to an integer.
16444 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
16445 return false;
16446 }
16447 Result = Val.getInt();
16448 return true;
16449}
16450
16451bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
16453 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
16454 return Success(Evaluated, E);
16455}
16456
16457static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
16458 EvalInfo &Info) {
16459 assert(!E->isValueDependent());
16460 if (E->getType()->isFixedPointType()) {
16461 APValue Val;
16462 if (!FixedPointExprEvaluator(Info, Val).Visit(E))
16463 return false;
16464 if (!Val.isFixedPoint())
16465 return false;
16466
16467 Result = Val.getFixedPoint();
16468 return true;
16469 }
16470 return false;
16471}
16472
16473static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
16474 EvalInfo &Info) {
16475 assert(!E->isValueDependent());
16476 if (E->getType()->isIntegerType()) {
16477 auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
16478 APSInt Val;
16479 if (!EvaluateInteger(E, Val, Info))
16480 return false;
16481 Result = APFixedPoint(Val, FXSema);
16482 return true;
16483 } else if (E->getType()->isFixedPointType()) {
16484 return EvaluateFixedPoint(E, Result, Info);
16485 }
16486 return false;
16487}
16488
16489/// Check whether the given declaration can be directly converted to an integral
16490/// rvalue. If not, no diagnostic is produced; there are other things we can
16491/// try.
16492bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
16493 // Enums are integer constant exprs.
16494 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
16495 // Check for signedness/width mismatches between E type and ECD value.
16496 bool SameSign = (ECD->getInitVal().isSigned()
16498 bool SameWidth = (ECD->getInitVal().getBitWidth()
16499 == Info.Ctx.getIntWidth(E->getType()));
16500 if (SameSign && SameWidth)
16501 return Success(ECD->getInitVal(), E);
16502 else {
16503 // Get rid of mismatch (otherwise Success assertions will fail)
16504 // by computing a new value matching the type of E.
16505 llvm::APSInt Val = ECD->getInitVal();
16506 if (!SameSign)
16507 Val.setIsSigned(!ECD->getInitVal().isSigned());
16508 if (!SameWidth)
16509 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
16510 return Success(Val, E);
16511 }
16512 }
16513 return false;
16514}
16515
16516/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
16517/// as GCC.
16519 const LangOptions &LangOpts) {
16520 assert(!T->isDependentType() && "unexpected dependent type");
16521
16522 QualType CanTy = T.getCanonicalType();
16523
16524 switch (CanTy->getTypeClass()) {
16525#define TYPE(ID, BASE)
16526#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
16527#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
16528#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
16529#include "clang/AST/TypeNodes.inc"
16530 case Type::Auto:
16531 case Type::DeducedTemplateSpecialization:
16532 llvm_unreachable("unexpected non-canonical or dependent type");
16533
16534 case Type::Builtin:
16535 switch (cast<BuiltinType>(CanTy)->getKind()) {
16536#define BUILTIN_TYPE(ID, SINGLETON_ID)
16537#define SIGNED_TYPE(ID, SINGLETON_ID) \
16538 case BuiltinType::ID: return GCCTypeClass::Integer;
16539#define FLOATING_TYPE(ID, SINGLETON_ID) \
16540 case BuiltinType::ID: return GCCTypeClass::RealFloat;
16541#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
16542 case BuiltinType::ID: break;
16543#include "clang/AST/BuiltinTypes.def"
16544 case BuiltinType::Void:
16545 return GCCTypeClass::Void;
16546
16547 case BuiltinType::Bool:
16548 return GCCTypeClass::Bool;
16549
16550 case BuiltinType::Char_U:
16551 case BuiltinType::UChar:
16552 case BuiltinType::WChar_U:
16553 case BuiltinType::Char8:
16554 case BuiltinType::Char16:
16555 case BuiltinType::Char32:
16556 case BuiltinType::UShort:
16557 case BuiltinType::UInt:
16558 case BuiltinType::ULong:
16559 case BuiltinType::ULongLong:
16560 case BuiltinType::UInt128:
16561 return GCCTypeClass::Integer;
16562
16563 case BuiltinType::UShortAccum:
16564 case BuiltinType::UAccum:
16565 case BuiltinType::ULongAccum:
16566 case BuiltinType::UShortFract:
16567 case BuiltinType::UFract:
16568 case BuiltinType::ULongFract:
16569 case BuiltinType::SatUShortAccum:
16570 case BuiltinType::SatUAccum:
16571 case BuiltinType::SatULongAccum:
16572 case BuiltinType::SatUShortFract:
16573 case BuiltinType::SatUFract:
16574 case BuiltinType::SatULongFract:
16575 return GCCTypeClass::None;
16576
16577 case BuiltinType::NullPtr:
16578
16579 case BuiltinType::ObjCId:
16580 case BuiltinType::ObjCClass:
16581 case BuiltinType::ObjCSel:
16582#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
16583 case BuiltinType::Id:
16584#include "clang/Basic/OpenCLImageTypes.def"
16585#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
16586 case BuiltinType::Id:
16587#include "clang/Basic/OpenCLExtensionTypes.def"
16588 case BuiltinType::OCLSampler:
16589 case BuiltinType::OCLEvent:
16590 case BuiltinType::OCLClkEvent:
16591 case BuiltinType::OCLQueue:
16592 case BuiltinType::OCLReserveID:
16593#define SVE_TYPE(Name, Id, SingletonId) \
16594 case BuiltinType::Id:
16595#include "clang/Basic/AArch64ACLETypes.def"
16596#define PPC_VECTOR_TYPE(Name, Id, Size) \
16597 case BuiltinType::Id:
16598#include "clang/Basic/PPCTypes.def"
16599#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
16600#include "clang/Basic/RISCVVTypes.def"
16601#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
16602#include "clang/Basic/WebAssemblyReferenceTypes.def"
16603#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
16604#include "clang/Basic/AMDGPUTypes.def"
16605#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
16606#include "clang/Basic/HLSLIntangibleTypes.def"
16607#define HLSL_PACKED_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
16608#include "clang/Basic/HLSLPackedTypes.def"
16609#define SPIRV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
16610#include "clang/Basic/SPIRVTypes.def"
16611 case BuiltinType::MetaInfo:
16612 return GCCTypeClass::None;
16613
16614 case BuiltinType::Dependent:
16615 llvm_unreachable("unexpected dependent type");
16616 };
16617 llvm_unreachable("unexpected placeholder type");
16618
16619 case Type::Enum:
16620 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
16621
16622 case Type::Pointer:
16623 case Type::ConstantArray:
16624 case Type::VariableArray:
16625 case Type::IncompleteArray:
16626 case Type::FunctionNoProto:
16627 case Type::FunctionProto:
16628 case Type::ArrayParameter:
16629 return GCCTypeClass::Pointer;
16630
16631 case Type::MemberPointer:
16632 return CanTy->isMemberDataPointerType()
16635
16636 case Type::Complex:
16637 return GCCTypeClass::Complex;
16638
16639 case Type::Record:
16640 return CanTy->isUnionType() ? GCCTypeClass::Union
16642
16643 case Type::Atomic:
16644 // GCC classifies _Atomic T the same as T.
16646 CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
16647
16648 case Type::Vector:
16649 case Type::ExtVector:
16650 return GCCTypeClass::Vector;
16651
16652 case Type::BlockPointer:
16653 case Type::ConstantMatrix:
16654 case Type::ObjCObject:
16655 case Type::ObjCInterface:
16656 case Type::ObjCObjectPointer:
16657 case Type::Pipe:
16658 case Type::HLSLAttributedResource:
16659 case Type::HLSLInlineSpirv:
16660 case Type::OverflowBehavior:
16661 // Classify all other types that don't fit into the regular
16662 // classification the same way.
16663 return GCCTypeClass::None;
16664
16665 case Type::BitInt:
16666 return GCCTypeClass::BitInt;
16667
16668 case Type::LValueReference:
16669 case Type::RValueReference:
16670 llvm_unreachable("invalid type for expression");
16671 }
16672
16673 llvm_unreachable("unexpected type class");
16674}
16675
16676/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
16677/// as GCC.
16678static GCCTypeClass
16680 // If no argument was supplied, default to None. This isn't
16681 // ideal, however it is what gcc does.
16682 if (E->getNumArgs() == 0)
16683 return GCCTypeClass::None;
16684
16685 // FIXME: Bizarrely, GCC treats a call with more than one argument as not
16686 // being an ICE, but still folds it to a constant using the type of the first
16687 // argument.
16688 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
16689}
16690
16691/// EvaluateBuiltinConstantPForLValue - Determine the result of
16692/// __builtin_constant_p when applied to the given pointer.
16693///
16694/// A pointer is only "constant" if it is null (or a pointer cast to integer)
16695/// or it points to the first character of a string literal.
16698 if (Base.isNull()) {
16699 // A null base is acceptable.
16700 return true;
16701 } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
16702 if (!isa<StringLiteral>(E))
16703 return false;
16704 return LV.getLValueOffset().isZero();
16705 } else if (Base.is<TypeInfoLValue>()) {
16706 // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
16707 // evaluate to true.
16708 return true;
16709 } else {
16710 // Any other base is not constant enough for GCC.
16711 return false;
16712 }
16713}
16714
16715/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
16716/// GCC as we can manage.
16717static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
16718 // This evaluation is not permitted to have side-effects, so evaluate it in
16719 // a speculative evaluation context.
16720 SpeculativeEvaluationRAII SpeculativeEval(Info);
16721
16722 // Constant-folding is always enabled for the operand of __builtin_constant_p
16723 // (even when the enclosing evaluation context otherwise requires a strict
16724 // language-specific constant expression).
16725 FoldConstant Fold(Info, true);
16726
16727 QualType ArgType = Arg->getType();
16728
16729 // __builtin_constant_p always has one operand. The rules which gcc follows
16730 // are not precisely documented, but are as follows:
16731 //
16732 // - If the operand is of integral, floating, complex or enumeration type,
16733 // and can be folded to a known value of that type, it returns 1.
16734 // - If the operand can be folded to a pointer to the first character
16735 // of a string literal (or such a pointer cast to an integral type)
16736 // or to a null pointer or an integer cast to a pointer, it returns 1.
16737 //
16738 // Otherwise, it returns 0.
16739 //
16740 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
16741 // its support for this did not work prior to GCC 9 and is not yet well
16742 // understood.
16743 if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
16744 ArgType->isAnyComplexType() || ArgType->isPointerType() ||
16745 ArgType->isNullPtrType()) {
16746 APValue V;
16747 if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) {
16748 Fold.keepDiagnostics();
16749 return false;
16750 }
16751
16752 // For a pointer (possibly cast to integer), there are special rules.
16753 if (V.getKind() == APValue::LValue)
16755
16756 // Otherwise, any constant value is good enough.
16757 return V.hasValue();
16758 }
16759
16760 // Anything else isn't considered to be sufficiently constant.
16761 return false;
16762}
16763
16764/// Retrieves the "underlying object type" of the given expression,
16765/// as used by __builtin_object_size.
16767 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
16768 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
16769 return VD->getType();
16770 } else if (const Expr *E = B.dyn_cast<const Expr*>()) {
16772 return E->getType();
16773 } else if (B.is<TypeInfoLValue>()) {
16774 return B.getTypeInfoType();
16775 } else if (B.is<DynamicAllocLValue>()) {
16776 return B.getDynamicAllocType();
16777 }
16778
16779 return QualType();
16780}
16781
16782/// A more selective version of E->IgnoreParenCasts for
16783/// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
16784/// to change the type of E.
16785/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
16786///
16787/// Always returns an RValue with a pointer representation.
16789 assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
16790
16791 const Expr *NoParens = E->IgnoreParens();
16792 const auto *Cast = dyn_cast<CastExpr>(NoParens);
16793 if (Cast == nullptr)
16794 return NoParens;
16795
16796 // We only conservatively allow a few kinds of casts, because this code is
16797 // inherently a simple solution that seeks to support the common case.
16798 auto CastKind = Cast->getCastKind();
16799 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
16800 CastKind != CK_AddressSpaceConversion)
16801 return NoParens;
16802
16803 const auto *SubExpr = Cast->getSubExpr();
16804 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isPRValue())
16805 return NoParens;
16806 return ignorePointerCastsAndParens(SubExpr);
16807}
16808
16809/// Checks to see if the given LValue's Designator is at the end of the LValue's
16810/// record layout. e.g.
16811/// struct { struct { int a, b; } fst, snd; } obj;
16812/// obj.fst // no
16813/// obj.snd // yes
16814/// obj.fst.a // no
16815/// obj.fst.b // no
16816/// obj.snd.a // no
16817/// obj.snd.b // yes
16818///
16819/// Please note: this function is specialized for how __builtin_object_size
16820/// views "objects".
16821///
16822/// If this encounters an invalid RecordDecl or otherwise cannot determine the
16823/// correct result, it will always return true.
16824static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
16825 assert(!LVal.Designator.Invalid);
16826
16827 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD) {
16828 const RecordDecl *Parent = FD->getParent();
16829 if (Parent->isInvalidDecl() || Parent->isUnion())
16830 return true;
16831 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
16832 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
16833 };
16834
16835 auto &Base = LVal.getLValueBase();
16836 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
16837 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
16838 if (!IsLastOrInvalidFieldDecl(FD))
16839 return false;
16840 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
16841 for (auto *FD : IFD->chain()) {
16842 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD)))
16843 return false;
16844 }
16845 }
16846 }
16847
16848 unsigned I = 0;
16849 QualType BaseType = getType(Base);
16850 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
16851 // If we don't know the array bound, conservatively assume we're looking at
16852 // the final array element.
16853 ++I;
16854 if (BaseType->isIncompleteArrayType())
16855 BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
16856 else
16857 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
16858 }
16859
16860 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
16861 const auto &Entry = LVal.Designator.Entries[I];
16862 if (BaseType->isArrayType()) {
16863 // Because __builtin_object_size treats arrays as objects, we can ignore
16864 // the index iff this is the last array in the Designator.
16865 if (I + 1 == E)
16866 return true;
16867 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
16868 uint64_t Index = Entry.getAsArrayIndex();
16869 if (Index + 1 != CAT->getZExtSize())
16870 return false;
16871 BaseType = CAT->getElementType();
16872 } else if (BaseType->isAnyComplexType()) {
16873 const auto *CT = BaseType->castAs<ComplexType>();
16874 uint64_t Index = Entry.getAsArrayIndex();
16875 if (Index != 1)
16876 return false;
16877 BaseType = CT->getElementType();
16878 } else if (auto *FD = getAsField(Entry)) {
16879 if (!IsLastOrInvalidFieldDecl(FD))
16880 return false;
16881 BaseType = FD->getType();
16882 } else {
16883 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
16884 return false;
16885 }
16886 }
16887 return true;
16888}
16889
16890/// Tests to see if the LValue has a user-specified designator (that isn't
16891/// necessarily valid). Note that this always returns 'true' if the LValue has
16892/// an unsized array as its first designator entry, because there's currently no
16893/// way to tell if the user typed *foo or foo[0].
16894static bool refersToCompleteObject(const LValue &LVal) {
16895 if (LVal.Designator.Invalid)
16896 return false;
16897
16898 if (!LVal.Designator.Entries.empty())
16899 return LVal.Designator.isMostDerivedAnUnsizedArray();
16900
16901 if (!LVal.InvalidBase)
16902 return true;
16903
16904 // If `E` is a MemberExpr, then the first part of the designator is hiding in
16905 // the LValueBase.
16906 const auto *E = LVal.Base.dyn_cast<const Expr *>();
16907 return !E || !isa<MemberExpr>(E);
16908}
16909
16910/// Attempts to detect a user writing into a piece of memory that's impossible
16911/// to figure out the size of by just using types.
16912static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
16913 const SubobjectDesignator &Designator = LVal.Designator;
16914 // Notes:
16915 // - Users can only write off of the end when we have an invalid base. Invalid
16916 // bases imply we don't know where the memory came from.
16917 // - We used to be a bit more aggressive here; we'd only be conservative if
16918 // the array at the end was flexible, or if it had 0 or 1 elements. This
16919 // broke some common standard library extensions (PR30346), but was
16920 // otherwise seemingly fine. It may be useful to reintroduce this behavior
16921 // with some sort of list. OTOH, it seems that GCC is always
16922 // conservative with the last element in structs (if it's an array), so our
16923 // current behavior is more compatible than an explicit list approach would
16924 // be.
16925 auto isFlexibleArrayMember = [&] {
16927 FAMKind StrictFlexArraysLevel =
16928 Ctx.getLangOpts().getStrictFlexArraysLevel();
16929
16930 if (Designator.isMostDerivedAnUnsizedArray())
16931 return true;
16932
16933 if (StrictFlexArraysLevel == FAMKind::Default)
16934 return true;
16935
16936 if (Designator.getMostDerivedArraySize() == 0 &&
16937 StrictFlexArraysLevel != FAMKind::IncompleteOnly)
16938 return true;
16939
16940 if (Designator.getMostDerivedArraySize() == 1 &&
16941 StrictFlexArraysLevel == FAMKind::OneZeroOrIncomplete)
16942 return true;
16943
16944 return false;
16945 };
16946
16947 return LVal.InvalidBase &&
16948 Designator.Entries.size() == Designator.MostDerivedPathLength &&
16949 Designator.MostDerivedIsArrayElement && isFlexibleArrayMember() &&
16950 isDesignatorAtObjectEnd(Ctx, LVal);
16951}
16952
16953/// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
16954/// Fails if the conversion would cause loss of precision.
16955static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
16956 CharUnits &Result) {
16957 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
16958 if (Int.ugt(CharUnitsMax))
16959 return false;
16960 Result = CharUnits::fromQuantity(Int.getZExtValue());
16961 return true;
16962}
16963
16964/// If we're evaluating the object size of an instance of a struct that
16965/// contains a flexible array member, add the size of the initializer.
16966static void addFlexibleArrayMemberInitSize(EvalInfo &Info, const QualType &T,
16967 const LValue &LV, CharUnits &Size) {
16968 if (!T.isNull() && T->isStructureType() &&
16969 T->castAsRecordDecl()->hasFlexibleArrayMember())
16970 if (const auto *V = LV.getLValueBase().dyn_cast<const ValueDecl *>())
16971 if (const auto *VD = dyn_cast<VarDecl>(V))
16972 if (VD->hasInit())
16973 Size += VD->getFlexibleArrayInitChars(Info.Ctx);
16974}
16975
16976/// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
16977/// determine how many bytes exist from the beginning of the object to either
16978/// the end of the current subobject, or the end of the object itself, depending
16979/// on what the LValue looks like + the value of Type.
16980///
16981/// If this returns false, the value of Result is undefined.
16982static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
16983 unsigned Type, const LValue &LVal,
16984 CharUnits &EndOffset) {
16985 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
16986
16987 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
16988 if (Ty.isNull())
16989 return false;
16990
16991 Ty = Ty.getNonReferenceType();
16992
16993 if (Ty->isIncompleteType() || Ty->isFunctionType())
16994 return false;
16995
16996 return HandleSizeof(Info, ExprLoc, Ty, Result);
16997 };
16998
16999 // We want to evaluate the size of the entire object. This is a valid fallback
17000 // for when Type=1 and the designator is invalid, because we're asked for an
17001 // upper-bound.
17002 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
17003 // Type=3 wants a lower bound, so we can't fall back to this.
17004 if (Type == 3 && !DetermineForCompleteObject)
17005 return false;
17006
17007 llvm::APInt APEndOffset;
17008 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
17009 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
17010 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
17011
17012 if (LVal.InvalidBase)
17013 return false;
17014
17015 QualType BaseTy = getObjectType(LVal.getLValueBase());
17016 const bool Ret = CheckedHandleSizeof(BaseTy, EndOffset);
17017 addFlexibleArrayMemberInitSize(Info, BaseTy, LVal, EndOffset);
17018 return Ret;
17019 }
17020
17021 // We want to evaluate the size of a subobject.
17022 const SubobjectDesignator &Designator = LVal.Designator;
17023
17024 // The following is a moderately common idiom in C:
17025 //
17026 // struct Foo { int a; char c[1]; };
17027 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
17028 // strcpy(&F->c[0], Bar);
17029 //
17030 // In order to not break too much legacy code, we need to support it.
17031 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
17032 // If we can resolve this to an alloc_size call, we can hand that back,
17033 // because we know for certain how many bytes there are to write to.
17034 llvm::APInt APEndOffset;
17035 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
17036 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
17037 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
17038
17039 // If we cannot determine the size of the initial allocation, then we can't
17040 // given an accurate upper-bound. However, we are still able to give
17041 // conservative lower-bounds for Type=3.
17042 if (Type == 1)
17043 return false;
17044 }
17045
17046 CharUnits BytesPerElem;
17047 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
17048 return false;
17049
17050 // According to the GCC documentation, we want the size of the subobject
17051 // denoted by the pointer. But that's not quite right -- what we actually
17052 // want is the size of the immediately-enclosing array, if there is one.
17053 int64_t ElemsRemaining;
17054 if (Designator.MostDerivedIsArrayElement &&
17055 Designator.Entries.size() == Designator.MostDerivedPathLength) {
17056 uint64_t ArraySize = Designator.getMostDerivedArraySize();
17057 uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
17058 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
17059 } else {
17060 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
17061 }
17062
17063 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
17064 return true;
17065}
17066
17067/// Tries to evaluate the __builtin_object_size for @p E.
17068///
17069/// If @p IsDynamic is true (i.e. we're evaluating
17070/// __builtin_dynamic_object_size) and the operand designates a flexible array
17071/// member annotated with 'counted_by', we refuse to fold so that IR generation
17072/// can emit the count-based runtime size computation.
17073static std::optional<uint64_t>
17074tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type, EvalInfo &Info,
17075 bool IsDynamic = false) {
17076
17077 // Determine the denoted object.
17078 LValue LVal;
17079 {
17080 // The operand of __builtin_object_size is never evaluated for side-effects.
17081 // If there are any, but we can determine the pointed-to object anyway, then
17082 // ignore the side-effects.
17083 SpeculativeEvaluationRAII SpeculativeEval(Info);
17084 IgnoreSideEffectsRAII Fold(Info);
17085
17086 if (E->isGLValue()) {
17087 // It's possible for us to be given GLValues if we're called via
17088 // Expr::tryEvaluateObjectSize.
17089 APValue RVal;
17090 if (!EvaluateAsRValue(Info, E, RVal))
17091 return std::nullopt;
17092 LVal.setFrom(Info.Ctx, RVal);
17093 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
17094 /*InvalidBaseOK=*/true))
17095 return std::nullopt;
17096 }
17097
17098 // If we point to before the start of the object, there are no accessible
17099 // bytes.
17100 if (LVal.getLValueOffset().isNegative())
17101 return 0;
17102
17103 // For __builtin_dynamic_object_size on a counted_by-annotated flexible
17104 // array member, defer to IR generation (emitCountedBySize in CGBuiltin):
17105 // its runtime computation uses the live 'count' field and is more accurate
17106 // than the layout/initializer-derived size we'd produce here. Use the same
17107 // findStructFieldAccess form-recognition CGBuiltin does, so we refuse to
17108 // fold on exactly the shapes that path handles (and, importantly, *not*
17109 // on '&af.fam' which designates the array-as-a-whole and stays on the
17110 // layout-derived path to match GCC). Checked after the negative-offset
17111 // early return above so that obviously out-of-bounds operands still fold
17112 // to 0, preserving existing behavior.
17113 if (IsDynamic) {
17114 const auto *ME = dyn_cast_or_null<MemberExpr>(findStructFieldAccess(E));
17115 const auto *FD = ME ? dyn_cast<FieldDecl>(ME->getMemberDecl()) : nullptr;
17116 if (FD && FD->getType()->isCountAttributedType())
17117 return std::nullopt;
17118 }
17119
17120 CharUnits EndOffset;
17121 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
17122 return std::nullopt;
17123
17124 // If we've fallen outside of the end offset, just pretend there's nothing to
17125 // write to/read from.
17126 if (EndOffset <= LVal.getLValueOffset())
17127 return 0;
17128 return (EndOffset - LVal.getLValueOffset()).getQuantity();
17129}
17130
17131bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
17132 if (!IsConstantEvaluatedBuiltinCall(E))
17133 return ExprEvaluatorBaseTy::VisitCallExpr(E);
17134 return VisitBuiltinCallExpr(E, ConvertBuiltinIDToX86BuiltinID(Info.Ctx, E));
17135}
17136
17137static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info,
17138 APValue &Val, APSInt &Alignment) {
17139 QualType SrcTy = E->getArg(0)->getType();
17140 if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment))
17141 return false;
17142 // Even though we are evaluating integer expressions we could get a pointer
17143 // argument for the __builtin_is_aligned() case.
17144 if (SrcTy->isPointerType()) {
17145 LValue Ptr;
17146 if (!EvaluatePointer(E->getArg(0), Ptr, Info))
17147 return false;
17148 Ptr.moveInto(Val);
17149 } else if (!SrcTy->isIntegralOrEnumerationType()) {
17150 Info.FFDiag(E->getArg(0));
17151 return false;
17152 } else {
17153 APSInt SrcInt;
17154 if (!EvaluateInteger(E->getArg(0), SrcInt, Info))
17155 return false;
17156 assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() &&
17157 "Bit widths must be the same");
17158 Val = APValue(SrcInt);
17159 }
17160 assert(Val.hasValue());
17161 return true;
17162}
17163
17164// Implements the C2y §7.18.21 stdc_load8_* family: reads N bytes from
17165// E->getArg(0) and assembles them per IsBE into a value of E's type. The
17166// aligned_* variants additionally require the pointer to be aligned to the
17167// natural alignment of E's type.
17168static bool EvaluateStdcLoad8(EvalInfo &Info, const CallExpr *E, bool IsBE,
17169 bool IsAligned, APSInt &Result) {
17170 LValue Ptr;
17171 if (!EvaluatePointer(E->getArg(0), Ptr, Info))
17172 return false;
17173
17174 if (!Ptr.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
17175 Ptr.Designator.Invalid)
17176 return false;
17177
17178 if (Ptr.Designator.isMostDerivedAnUnsizedArray())
17179 return false;
17180
17181 if (IsAligned) {
17182 CharUnits RequiredAlign = Info.Ctx.getTypeAlignInChars(E->getType());
17183 CharUnits BaseAlignment = getBaseAlignment(Info, Ptr);
17184 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset);
17185 if (PtrAlign < RequiredAlign) {
17186 Info.FFDiag(E, diag::note_constexpr_load8_unaligned)
17187 << Info.Ctx.BuiltinInfo.getQuotedName(E->getBuiltinCallee())
17188 << RequiredAlign.getQuantity() << PtrAlign.getQuantity();
17189 return false;
17190 }
17191 }
17192
17193 QualType CharTy = Ptr.Designator.getType(Info.Ctx);
17194 unsigned ByteWidth = Info.Ctx.getTypeSize(E->getType()) / 8;
17195 uint64_t RemainingElems = Ptr.Designator.validIndexAdjustments().second;
17196 if (ByteWidth > RemainingElems) {
17197 uint64_t ArrayIndex = Ptr.Designator.MostDerivedIsArrayElement
17198 ? Ptr.Designator.Entries.back().getAsArrayIndex()
17199 : (uint64_t)Ptr.Designator.IsOnePastTheEnd;
17200 APSInt Index = APSInt::get(ArrayIndex + ByteWidth - 1);
17201 Ptr.Designator.diagnosePointerArithmetic(Info, E, Index);
17202 return false;
17203 }
17204
17205 // Load the bytes and assemble them per C2y §7.18.21:
17206 // result = sum(b_index * 2^(8*index)) where b_index = ptr[index] (LE)
17207 // or ptr[N/8 - index - 1] (BE).
17208 uint64_t ResultBits = 0;
17209 LValue BytePtr = Ptr;
17210 for (unsigned I = 0; I < ByteWidth; ++I) {
17211 APValue ByteVal;
17212 if (!handleLValueToRValueConversion(Info, E, CharTy, BytePtr, ByteVal))
17213 return false;
17214 unsigned Shift = 8 * (IsBE ? ByteWidth - I - 1 : I);
17215 ResultBits |= ByteVal.getInt().getZExtValue() << Shift;
17216 if (I + 1 < ByteWidth)
17217 if (!HandleLValueArrayAdjustment(Info, E, BytePtr, CharTy, 1))
17218 return false;
17219 }
17220
17221 bool IsSigned = E->getType()->isSignedIntegerType();
17222 Result = APSInt(APInt(ByteWidth * 8, ResultBits), !IsSigned);
17223 return true;
17224}
17225
17226bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
17227 unsigned BuiltinOp) {
17228 if (Info.Ctx.BuiltinInfo.isReflectionMetafunctionBuiltin(BuiltinOp)) {
17230 if (!EvaluateReflectionMetafunctionBuiltin(Info, E, BuiltinOp, Result))
17231 return false;
17232 return Success(Result, E);
17233 }
17234
17235 auto EvalTestOp = [&](llvm::function_ref<bool(const APInt &, const APInt &)>
17236 Fn) {
17237 APValue SourceLHS, SourceRHS;
17238 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
17239 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
17240 return false;
17241
17242 unsigned SourceLen = SourceLHS.getVectorLength();
17243 const VectorType *VT = E->getArg(0)->getType()->castAs<VectorType>();
17244 QualType ElemQT = VT->getElementType();
17245 unsigned LaneWidth = Info.Ctx.getTypeSize(ElemQT);
17246
17247 APInt AWide(LaneWidth * SourceLen, 0);
17248 APInt BWide(LaneWidth * SourceLen, 0);
17249
17250 for (unsigned I = 0; I != SourceLen; ++I) {
17251 APInt ALane;
17252 APInt BLane;
17253 if (ElemQT->isIntegerType()) { // Get value.
17254 ALane = SourceLHS.getVectorElt(I).getInt();
17255 BLane = SourceRHS.getVectorElt(I).getInt();
17256 } else if (ElemQT->isFloatingType()) { // Get only sign bit.
17257 ALane =
17258 SourceLHS.getVectorElt(I).getFloat().bitcastToAPInt().isNegative();
17259 BLane =
17260 SourceRHS.getVectorElt(I).getFloat().bitcastToAPInt().isNegative();
17261 } else { // Must be integer or floating type.
17262 return false;
17263 }
17264 AWide.insertBits(ALane, I * LaneWidth);
17265 BWide.insertBits(BLane, I * LaneWidth);
17266 }
17267 return Success(Fn(AWide, BWide), E);
17268 };
17269
17270 auto HandleMaskBinOp =
17271 [&](llvm::function_ref<APSInt(const APSInt &, const APSInt &)> Fn)
17272 -> bool {
17273 APValue LHS, RHS;
17274 if (!Evaluate(LHS, Info, E->getArg(0)) ||
17275 !Evaluate(RHS, Info, E->getArg(1)))
17276 return false;
17277
17278 APSInt ResultInt = Fn(LHS.getInt(), RHS.getInt());
17279
17280 return Success(APValue(ResultInt), E);
17281 };
17282
17283 auto HandleCRC32 = [&](unsigned DataBytes) -> bool {
17284 APSInt CRC, Data;
17285 if (!EvaluateInteger(E->getArg(0), CRC, Info) ||
17286 !EvaluateInteger(E->getArg(1), Data, Info))
17287 return false;
17288
17289 uint64_t CRCVal = CRC.getZExtValue();
17290 uint64_t DataVal = Data.getZExtValue();
17291
17292 // CRC32C polynomial (iSCSI polynomial, bit-reversed)
17293 static const uint32_t CRC32C_POLY = 0x82F63B78;
17294
17295 uint32_t Result = llvm::calculateReflectedCRC32(
17296 static_cast<uint32_t>(CRCVal), DataVal, DataBytes, CRC32C_POLY);
17297
17298 return Success(Result, E);
17299 };
17300
17301 switch (BuiltinOp) {
17302 default:
17303 return false;
17304
17305 case X86::BI__builtin_ia32_crc32qi:
17306 return HandleCRC32(1);
17307 case X86::BI__builtin_ia32_crc32hi:
17308 return HandleCRC32(2);
17309 case X86::BI__builtin_ia32_crc32si:
17310 return HandleCRC32(4);
17311 case X86::BI__builtin_ia32_crc32di:
17312 return HandleCRC32(8);
17313
17314 case Builtin::BI__builtin_dynamic_object_size:
17315 case Builtin::BI__builtin_object_size: {
17316 APSInt TypeValue;
17317 if (!EvaluateInteger(E->getArg(1), TypeValue, Info))
17318 return false;
17319 if (TypeValue < 0 || TypeValue > 3) {
17320 Info.FFDiag(E->getArg(1), diag::note_constexpr_builtin_arg_out_of_range)
17321 << TypeValue << 0 << 3;
17322 return false;
17323 }
17324 unsigned Type = TypeValue.getZExtValue();
17325
17326 bool IsDynamic = BuiltinOp == Builtin::BI__builtin_dynamic_object_size;
17327 if (std::optional<uint64_t> Size =
17328 tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, IsDynamic))
17329 return Success(*Size, E);
17330
17331 if (E->getArg(0)->HasSideEffects(Info.Ctx))
17332 return Success((Type & 2) ? 0 : -1, E);
17333
17334 // Expression had no side effects, but we couldn't statically determine the
17335 // size of the referenced object.
17336 switch (Info.EvalMode) {
17337 case EvaluationMode::ConstantExpression:
17338 case EvaluationMode::ConstantFold:
17339 case EvaluationMode::IgnoreSideEffects:
17340 // Leave it to IR generation.
17341 return Error(E);
17342 case EvaluationMode::ConstantExpressionUnevaluated:
17343 // Reduce it to a constant now.
17344 return Success((Type & 2) ? 0 : -1, E);
17345 }
17346
17347 llvm_unreachable("unexpected EvalMode");
17348 }
17349
17350 case Builtin::BI__builtin_os_log_format_buffer_size: {
17351 analyze_os_log::OSLogBufferLayout Layout;
17352 analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
17353 return Success(Layout.size().getQuantity(), E);
17354 }
17355
17356 case Builtin::BI__builtin_is_aligned: {
17357 APValue Src;
17358 APSInt Alignment;
17359 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
17360 return false;
17361 if (Src.isLValue()) {
17362 // If we evaluated a pointer, check the minimum known alignment.
17363 LValue Ptr;
17364 Ptr.setFrom(Info.Ctx, Src);
17365 if (!Ptr.Base) {
17366 // Null pointers are always aligned.
17367 if (Ptr.Offset.isZero())
17368 return Success(1, E);
17369
17370 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute)
17371 << Alignment;
17372 // Reject non-null pointers without an underlying object.
17373 // Do not interpret the pointer offset as an integer address.
17374 return false;
17375 }
17376
17377 CharUnits BaseAlignment = getBaseAlignment(Info, Ptr);
17378 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset);
17379 // We can return true if the known alignment at the computed offset is
17380 // greater than the requested alignment.
17381 assert(PtrAlign.isPowerOfTwo());
17382 assert(Alignment.isPowerOf2());
17383 if (PtrAlign.getQuantity() >= Alignment)
17384 return Success(1, E);
17385 // If the alignment is not known to be sufficient, some cases could still
17386 // be aligned at run time. However, if the requested alignment is less or
17387 // equal to the base alignment and the offset is not aligned, we know that
17388 // the run-time value can never be aligned.
17389 if (BaseAlignment.getQuantity() >= Alignment &&
17390 PtrAlign.getQuantity() < Alignment)
17391 return Success(0, E);
17392 // Otherwise we can't infer whether the value is sufficiently aligned.
17393 // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N)
17394 // in cases where we can't fully evaluate the pointer.
17395 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute)
17396 << Alignment;
17397 return false;
17398 }
17399 assert(Src.isInt());
17400 return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E);
17401 }
17402 case Builtin::BI__builtin_align_up: {
17403 APValue Src;
17404 APSInt Alignment;
17405 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
17406 return false;
17407 if (!Src.isInt())
17408 return Error(E);
17409 APSInt AlignedVal =
17410 APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1),
17411 Src.getInt().isUnsigned());
17412 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
17413 return Success(AlignedVal, E);
17414 }
17415 case Builtin::BI__builtin_align_down: {
17416 APValue Src;
17417 APSInt Alignment;
17418 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
17419 return false;
17420 if (!Src.isInt())
17421 return Error(E);
17422 APSInt AlignedVal =
17423 APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned());
17424 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
17425 return Success(AlignedVal, E);
17426 }
17427
17428 case Builtin::BI__builtin_bitreverseg:
17429 case Builtin::BI__builtin_bitreverse8:
17430 case Builtin::BI__builtin_bitreverse16:
17431 case Builtin::BI__builtin_bitreverse32:
17432 case Builtin::BI__builtin_bitreverse64:
17433 case Builtin::BI__builtin_elementwise_bitreverse: {
17434 APSInt Val;
17435 if (!EvaluateInteger(E->getArg(0), Val, Info))
17436 return false;
17437
17438 return Success(Val.reverseBits(), E);
17439 }
17440 case Builtin::BI__builtin_bswapg:
17441 case Builtin::BI__builtin_bswap16:
17442 case Builtin::BI__builtin_bswap32:
17443 case Builtin::BI__builtin_bswap64:
17444 case Builtin::BIstdc_memreverse8u8:
17445 case Builtin::BIstdc_memreverse8u16:
17446 case Builtin::BIstdc_memreverse8u32:
17447 case Builtin::BIstdc_memreverse8u64: {
17448 APSInt Val;
17449 if (!EvaluateInteger(E->getArg(0), Val, Info))
17450 return false;
17451 if (Val.getBitWidth() == 8 || Val.getBitWidth() == 1)
17452 return Success(Val, E);
17453
17454 return Success(Val.byteSwap(), E);
17455 }
17456
17457 case Builtin::BIstdc_load8_leu8:
17458 case Builtin::BIstdc_load8_leu16:
17459 case Builtin::BIstdc_load8_leu32:
17460 case Builtin::BIstdc_load8_leu64:
17461 case Builtin::BIstdc_load8_les8:
17462 case Builtin::BIstdc_load8_les16:
17463 case Builtin::BIstdc_load8_les32:
17464 case Builtin::BIstdc_load8_les64: {
17465 APSInt Result;
17466 if (!EvaluateStdcLoad8(Info, E, /*IsBE=*/false, /*IsAligned=*/false,
17467 Result))
17468 return false;
17469 return Success(Result, E);
17470 }
17471
17472 case Builtin::BIstdc_load8_aligned_leu8:
17473 case Builtin::BIstdc_load8_aligned_leu16:
17474 case Builtin::BIstdc_load8_aligned_leu32:
17475 case Builtin::BIstdc_load8_aligned_leu64:
17476 case Builtin::BIstdc_load8_aligned_les8:
17477 case Builtin::BIstdc_load8_aligned_les16:
17478 case Builtin::BIstdc_load8_aligned_les32:
17479 case Builtin::BIstdc_load8_aligned_les64: {
17480 APSInt Result;
17481 if (!EvaluateStdcLoad8(Info, E, /*IsBE=*/false, /*IsAligned=*/true, Result))
17482 return false;
17483 return Success(Result, E);
17484 }
17485
17486 case Builtin::BIstdc_load8_beu8:
17487 case Builtin::BIstdc_load8_beu16:
17488 case Builtin::BIstdc_load8_beu32:
17489 case Builtin::BIstdc_load8_beu64:
17490 case Builtin::BIstdc_load8_bes8:
17491 case Builtin::BIstdc_load8_bes16:
17492 case Builtin::BIstdc_load8_bes32:
17493 case Builtin::BIstdc_load8_bes64: {
17494 APSInt Result;
17495 if (!EvaluateStdcLoad8(Info, E, /*IsBE=*/true, /*IsAligned=*/false, Result))
17496 return false;
17497 return Success(Result, E);
17498 }
17499
17500 case Builtin::BIstdc_load8_aligned_beu8:
17501 case Builtin::BIstdc_load8_aligned_beu16:
17502 case Builtin::BIstdc_load8_aligned_beu32:
17503 case Builtin::BIstdc_load8_aligned_beu64:
17504 case Builtin::BIstdc_load8_aligned_bes8:
17505 case Builtin::BIstdc_load8_aligned_bes16:
17506 case Builtin::BIstdc_load8_aligned_bes32:
17507 case Builtin::BIstdc_load8_aligned_bes64: {
17508 APSInt Result;
17509 if (!EvaluateStdcLoad8(Info, E, /*IsBE=*/true, /*IsAligned=*/true, Result))
17510 return false;
17511 return Success(Result, E);
17512 }
17513
17514 case Builtin::BI__builtin_classify_type:
17515 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
17516
17517 case Builtin::BI__builtin_clrsb:
17518 case Builtin::BI__builtin_clrsbl:
17519 case Builtin::BI__builtin_clrsbll: {
17520 APSInt Val;
17521 if (!EvaluateInteger(E->getArg(0), Val, Info))
17522 return false;
17523
17524 return Success(Val.getBitWidth() - Val.getSignificantBits(), E);
17525 }
17526
17527 case Builtin::BI__builtin_clz:
17528 case Builtin::BI__builtin_clzl:
17529 case Builtin::BI__builtin_clzll:
17530 case Builtin::BI__builtin_clzs:
17531 case Builtin::BI__builtin_clzg:
17532 case Builtin::BI__builtin_elementwise_clzg:
17533 case Builtin::BI__lzcnt16: // Microsoft variants of count leading-zeroes
17534 case Builtin::BI__lzcnt:
17535 case Builtin::BI__lzcnt64: {
17536 APSInt Val;
17537 if (E->getArg(0)->getType()->isExtVectorBoolType()) {
17538 APValue Vec;
17539 if (!EvaluateVector(E->getArg(0), Vec, Info))
17540 return false;
17541 Val = ConvertBoolVectorToInt(Vec);
17542 } else if (!EvaluateInteger(E->getArg(0), Val, Info)) {
17543 return false;
17544 }
17545
17546 std::optional<APSInt> Fallback;
17547 if ((BuiltinOp == Builtin::BI__builtin_clzg ||
17548 BuiltinOp == Builtin::BI__builtin_elementwise_clzg) &&
17549 E->getNumArgs() > 1) {
17550 APSInt FallbackTemp;
17551 if (!EvaluateInteger(E->getArg(1), FallbackTemp, Info))
17552 return false;
17553 Fallback = FallbackTemp;
17554 }
17555
17556 if (!Val) {
17557 if (Fallback)
17558 return Success(*Fallback, E);
17559
17560 // When the argument is 0, the result of GCC builtins is undefined,
17561 // whereas for Microsoft intrinsics, the result is the bit-width of the
17562 // argument.
17563 bool ZeroIsUndefined = BuiltinOp != Builtin::BI__lzcnt16 &&
17564 BuiltinOp != Builtin::BI__lzcnt &&
17565 BuiltinOp != Builtin::BI__lzcnt64;
17566
17567 if (BuiltinOp == Builtin::BI__builtin_elementwise_clzg) {
17568 Info.FFDiag(E, diag::note_constexpr_countzeroes_zero)
17569 << /*IsTrailing=*/false;
17570 }
17571
17572 if (ZeroIsUndefined)
17573 return Error(E);
17574 }
17575
17576 return Success(Val.countl_zero(), E);
17577 }
17578
17579 case Builtin::BI__builtin_constant_p: {
17580 const Expr *Arg = E->getArg(0);
17581 if (EvaluateBuiltinConstantP(Info, Arg))
17582 return Success(true, E);
17583 if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
17584 // Outside a constant context, eagerly evaluate to false in the presence
17585 // of side-effects in order to avoid -Wunsequenced false-positives in
17586 // a branch on __builtin_constant_p(expr).
17587 return Success(false, E);
17588 }
17589 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
17590 return false;
17591 }
17592
17593 case Builtin::BI__noop:
17594 // __noop always evaluates successfully and returns 0.
17595 return Success(0, E);
17596
17597 case Builtin::BI__builtin_is_constant_evaluated: {
17598 const auto *Callee = Info.CurrentCall->getCallee();
17599 if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression &&
17600 (Info.CallStackDepth == 1 ||
17601 (Info.CallStackDepth == 2 && Callee->isInStdNamespace() &&
17602 Callee->getIdentifier() &&
17603 Callee->getIdentifier()->isStr("is_constant_evaluated")))) {
17604 // FIXME: Find a better way to avoid duplicated diagnostics.
17605 if (Info.EvalStatus.Diag)
17606 Info.report((Info.CallStackDepth == 1)
17607 ? E->getExprLoc()
17608 : Info.CurrentCall->getCallRange().getBegin(),
17609 diag::warn_is_constant_evaluated_always_true_constexpr)
17610 << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated"
17611 : "std::is_constant_evaluated");
17612 }
17613
17614 return Success(Info.InConstantContext, E);
17615 }
17616
17617 case Builtin::BI__builtin_is_within_lifetime:
17618 if (auto result = EvaluateBuiltinIsWithinLifetime(*this, E))
17619 return Success(*result, E);
17620 return false;
17621
17622 case Builtin::BI__builtin_ctz:
17623 case Builtin::BI__builtin_ctzl:
17624 case Builtin::BI__builtin_ctzll:
17625 case Builtin::BI__builtin_ctzs:
17626 case Builtin::BI__builtin_ctzg:
17627 case Builtin::BI__builtin_elementwise_ctzg: {
17628 APSInt Val;
17629 if (E->getArg(0)->getType()->isExtVectorBoolType()) {
17630 APValue Vec;
17631 if (!EvaluateVector(E->getArg(0), Vec, Info))
17632 return false;
17633 Val = ConvertBoolVectorToInt(Vec);
17634 } else if (!EvaluateInteger(E->getArg(0), Val, Info)) {
17635 return false;
17636 }
17637
17638 std::optional<APSInt> Fallback;
17639 if ((BuiltinOp == Builtin::BI__builtin_ctzg ||
17640 BuiltinOp == Builtin::BI__builtin_elementwise_ctzg) &&
17641 E->getNumArgs() > 1) {
17642 APSInt FallbackTemp;
17643 if (!EvaluateInteger(E->getArg(1), FallbackTemp, Info))
17644 return false;
17645 Fallback = FallbackTemp;
17646 }
17647
17648 if (!Val) {
17649 if (Fallback)
17650 return Success(*Fallback, E);
17651
17652 if (BuiltinOp == Builtin::BI__builtin_elementwise_ctzg) {
17653 Info.FFDiag(E, diag::note_constexpr_countzeroes_zero)
17654 << /*IsTrailing=*/true;
17655 }
17656 return Error(E);
17657 }
17658
17659 return Success(Val.countr_zero(), E);
17660 }
17661
17662 case Builtin::BI__builtin_eh_return_data_regno: {
17663 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
17664 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
17665 return Success(Operand, E);
17666 }
17667
17668 case Builtin::BI__builtin_elementwise_abs: {
17669 APSInt Val;
17670 if (!EvaluateInteger(E->getArg(0), Val, Info))
17671 return false;
17672
17673 return Success(Val.abs(), E);
17674 }
17675
17676 case Builtin::BI__builtin_expect:
17677 case Builtin::BI__builtin_expect_with_probability:
17678 return Visit(E->getArg(0));
17679
17680 case Builtin::BI__builtin_ptrauth_string_discriminator: {
17681 const auto *Literal =
17683 uint64_t Result = getPointerAuthStableSipHash(Literal->getString());
17684 return Success(Result, E);
17685 }
17686
17687 case Builtin::BI__builtin_infer_alloc_token: {
17688 // If we fail to infer a type, this fails to be a constant expression; this
17689 // can be checked with __builtin_constant_p(...).
17690 QualType AllocType = infer_alloc::inferPossibleType(E, Info.Ctx, nullptr);
17691 if (AllocType.isNull())
17692 return Error(
17693 E, diag::note_constexpr_infer_alloc_token_type_inference_failed);
17694 auto ATMD = infer_alloc::getAllocTokenMetadata(AllocType, Info.Ctx);
17695 if (!ATMD)
17696 return Error(E, diag::note_constexpr_infer_alloc_token_no_metadata);
17697 auto Mode =
17698 Info.getLangOpts().AllocTokenMode.value_or(llvm::DefaultAllocTokenMode);
17699 uint64_t BitWidth = Info.Ctx.getTypeSize(Info.Ctx.getSizeType());
17700 auto MaxTokensOpt = Info.getLangOpts().AllocTokenMax;
17701 uint64_t MaxTokens =
17702 MaxTokensOpt.value_or(0) ? *MaxTokensOpt : (~0ULL >> (64 - BitWidth));
17703 auto MaybeToken = llvm::getAllocToken(Mode, *ATMD, MaxTokens);
17704 if (!MaybeToken)
17705 return Error(E, diag::note_constexpr_infer_alloc_token_unsupported_mode);
17706 return Success(llvm::APInt(BitWidth, *MaybeToken), E);
17707 }
17708
17709 case Builtin::BI__builtin_ffs:
17710 case Builtin::BI__builtin_ffsl:
17711 case Builtin::BI__builtin_ffsll: {
17712 APSInt Val;
17713 if (!EvaluateInteger(E->getArg(0), Val, Info))
17714 return false;
17715
17716 unsigned N = Val.countr_zero();
17717 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
17718 }
17719
17720 case Builtin::BI__builtin_fpclassify: {
17721 APFloat Val(0.0);
17722 if (!EvaluateFloat(E->getArg(5), Val, Info))
17723 return false;
17724 unsigned Arg;
17725 switch (Val.getCategory()) {
17726 case APFloat::fcNaN: Arg = 0; break;
17727 case APFloat::fcInfinity: Arg = 1; break;
17728 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
17729 case APFloat::fcZero: Arg = 4; break;
17730 }
17731 return Visit(E->getArg(Arg));
17732 }
17733
17734 case Builtin::BI__builtin_isinf_sign: {
17735 APFloat Val(0.0);
17736 return EvaluateFloat(E->getArg(0), Val, Info) &&
17737 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
17738 }
17739
17740 case Builtin::BI__builtin_isinf: {
17741 APFloat Val(0.0);
17742 return EvaluateFloat(E->getArg(0), Val, Info) &&
17743 Success(Val.isInfinity() ? 1 : 0, E);
17744 }
17745
17746 case Builtin::BI__builtin_isfinite: {
17747 APFloat Val(0.0);
17748 return EvaluateFloat(E->getArg(0), Val, Info) &&
17749 Success(Val.isFinite() ? 1 : 0, E);
17750 }
17751
17752 case Builtin::BI__builtin_isnan: {
17753 APFloat Val(0.0);
17754 return EvaluateFloat(E->getArg(0), Val, Info) &&
17755 Success(Val.isNaN() ? 1 : 0, E);
17756 }
17757
17758 case Builtin::BI__builtin_isnormal: {
17759 APFloat Val(0.0);
17760 return EvaluateFloat(E->getArg(0), Val, Info) &&
17761 Success(Val.isNormal() ? 1 : 0, E);
17762 }
17763
17764 case Builtin::BI__builtin_issubnormal: {
17765 APFloat Val(0.0);
17766 return EvaluateFloat(E->getArg(0), Val, Info) &&
17767 Success(Val.isDenormal() ? 1 : 0, E);
17768 }
17769
17770 case Builtin::BI__builtin_iszero: {
17771 APFloat Val(0.0);
17772 return EvaluateFloat(E->getArg(0), Val, Info) &&
17773 Success(Val.isZero() ? 1 : 0, E);
17774 }
17775
17776 case Builtin::BI__builtin_signbit:
17777 case Builtin::BI__builtin_signbitf:
17778 case Builtin::BI__builtin_signbitl: {
17779 APFloat Val(0.0);
17780 return EvaluateFloat(E->getArg(0), Val, Info) &&
17781 Success(Val.isNegative() ? 1 : 0, E);
17782 }
17783
17784 case Builtin::BI__builtin_isgreater:
17785 case Builtin::BI__builtin_isgreaterequal:
17786 case Builtin::BI__builtin_isless:
17787 case Builtin::BI__builtin_islessequal:
17788 case Builtin::BI__builtin_islessgreater:
17789 case Builtin::BI__builtin_isunordered: {
17790 APFloat LHS(0.0);
17791 APFloat RHS(0.0);
17792 if (!EvaluateFloat(E->getArg(0), LHS, Info) ||
17793 !EvaluateFloat(E->getArg(1), RHS, Info))
17794 return false;
17795
17796 return Success(
17797 [&] {
17798 switch (BuiltinOp) {
17799 case Builtin::BI__builtin_isgreater:
17800 return LHS > RHS;
17801 case Builtin::BI__builtin_isgreaterequal:
17802 return LHS >= RHS;
17803 case Builtin::BI__builtin_isless:
17804 return LHS < RHS;
17805 case Builtin::BI__builtin_islessequal:
17806 return LHS <= RHS;
17807 case Builtin::BI__builtin_islessgreater: {
17808 APFloat::cmpResult cmp = LHS.compare(RHS);
17809 return cmp == APFloat::cmpResult::cmpLessThan ||
17810 cmp == APFloat::cmpResult::cmpGreaterThan;
17811 }
17812 case Builtin::BI__builtin_isunordered:
17813 return LHS.compare(RHS) == APFloat::cmpResult::cmpUnordered;
17814 default:
17815 llvm_unreachable("Unexpected builtin ID: Should be a floating "
17816 "point comparison function");
17817 }
17818 }()
17819 ? 1
17820 : 0,
17821 E);
17822 }
17823
17824 case Builtin::BI__builtin_issignaling: {
17825 APFloat Val(0.0);
17826 return EvaluateFloat(E->getArg(0), Val, Info) &&
17827 Success(Val.isSignaling() ? 1 : 0, E);
17828 }
17829
17830 case Builtin::BI__builtin_isfpclass: {
17831 APSInt MaskVal;
17832 if (!EvaluateInteger(E->getArg(1), MaskVal, Info))
17833 return false;
17834 unsigned Test = static_cast<llvm::FPClassTest>(MaskVal.getZExtValue());
17835 APFloat Val(0.0);
17836 return EvaluateFloat(E->getArg(0), Val, Info) &&
17837 Success((Val.classify() & Test) ? 1 : 0, E);
17838 }
17839
17840 case Builtin::BI__builtin_parity:
17841 case Builtin::BI__builtin_parityl:
17842 case Builtin::BI__builtin_parityll: {
17843 APSInt Val;
17844 if (!EvaluateInteger(E->getArg(0), Val, Info))
17845 return false;
17846
17847 return Success(Val.popcount() % 2, E);
17848 }
17849
17850 case Builtin::BI__builtin_abs:
17851 case Builtin::BI__builtin_labs:
17852 case Builtin::BI__builtin_llabs: {
17853 APSInt Val;
17854 if (!EvaluateInteger(E->getArg(0), Val, Info))
17855 return false;
17856 if (Val == APSInt(APInt::getSignedMinValue(Val.getBitWidth()),
17857 /*IsUnsigned=*/false))
17858 return false;
17859 if (Val.isNegative())
17860 Val.negate();
17861 return Success(Val, E);
17862 }
17863
17864 case Builtin::BI__builtin_popcount:
17865 case Builtin::BI__builtin_popcountl:
17866 case Builtin::BI__builtin_popcountll:
17867 case Builtin::BI__builtin_popcountg:
17868 case Builtin::BI__builtin_elementwise_popcount:
17869 case Builtin::BI__popcnt16: // Microsoft variants of popcount
17870 case Builtin::BI__popcnt:
17871 case Builtin::BI__popcnt64: {
17872 APSInt Val;
17873 if (E->getArg(0)->getType()->isExtVectorBoolType()) {
17874 APValue Vec;
17875 if (!EvaluateVector(E->getArg(0), Vec, Info))
17876 return false;
17877 Val = ConvertBoolVectorToInt(Vec);
17878 } else if (!EvaluateInteger(E->getArg(0), Val, Info)) {
17879 return false;
17880 }
17881
17882 return Success(Val.popcount(), E);
17883 }
17884
17885 case Builtin::BI__builtin_rotateleft8:
17886 case Builtin::BI__builtin_rotateleft16:
17887 case Builtin::BI__builtin_rotateleft32:
17888 case Builtin::BI__builtin_rotateleft64:
17889 case Builtin::BI__builtin_rotateright8:
17890 case Builtin::BI__builtin_rotateright16:
17891 case Builtin::BI__builtin_rotateright32:
17892 case Builtin::BI__builtin_rotateright64:
17893 case Builtin::BI__builtin_stdc_rotate_left:
17894 case Builtin::BI__builtin_stdc_rotate_right:
17895 case Builtin::BIstdc_rotate_left_uc:
17896 case Builtin::BIstdc_rotate_left_us:
17897 case Builtin::BIstdc_rotate_left_ui:
17898 case Builtin::BIstdc_rotate_left_ul:
17899 case Builtin::BIstdc_rotate_left_ull:
17900 case Builtin::BIstdc_rotate_right_uc:
17901 case Builtin::BIstdc_rotate_right_us:
17902 case Builtin::BIstdc_rotate_right_ui:
17903 case Builtin::BIstdc_rotate_right_ul:
17904 case Builtin::BIstdc_rotate_right_ull:
17905 case Builtin::BI_rotl8: // Microsoft variants of rotate left
17906 case Builtin::BI_rotl16:
17907 case Builtin::BI_rotl:
17908 case Builtin::BI_lrotl:
17909 case Builtin::BI_rotl64:
17910 case Builtin::BI_rotr8: // Microsoft variants of rotate right
17911 case Builtin::BI_rotr16:
17912 case Builtin::BI_rotr:
17913 case Builtin::BI_lrotr:
17914 case Builtin::BI_rotr64: {
17915 APSInt Value, Amount;
17916 if (!EvaluateInteger(E->getArg(0), Value, Info) ||
17917 !EvaluateInteger(E->getArg(1), Amount, Info))
17918 return false;
17919
17920 Amount = NormalizeRotateAmount(Value, Amount);
17921
17922 switch (BuiltinOp) {
17923 case Builtin::BI__builtin_rotateright8:
17924 case Builtin::BI__builtin_rotateright16:
17925 case Builtin::BI__builtin_rotateright32:
17926 case Builtin::BI__builtin_rotateright64:
17927 case Builtin::BI__builtin_stdc_rotate_right:
17928 case Builtin::BIstdc_rotate_right_uc:
17929 case Builtin::BIstdc_rotate_right_us:
17930 case Builtin::BIstdc_rotate_right_ui:
17931 case Builtin::BIstdc_rotate_right_ul:
17932 case Builtin::BIstdc_rotate_right_ull:
17933 case Builtin::BI_rotr8:
17934 case Builtin::BI_rotr16:
17935 case Builtin::BI_rotr:
17936 case Builtin::BI_lrotr:
17937 case Builtin::BI_rotr64:
17938 return Success(
17939 APSInt(Value.rotr(Amount.getZExtValue()), Value.isUnsigned()), E);
17940 default:
17941 return Success(
17942 APSInt(Value.rotl(Amount.getZExtValue()), Value.isUnsigned()), E);
17943 }
17944 }
17945
17946 case Builtin::BIstdc_leading_zeros_uc:
17947 case Builtin::BIstdc_leading_zeros_us:
17948 case Builtin::BIstdc_leading_zeros_ui:
17949 case Builtin::BIstdc_leading_zeros_ul:
17950 case Builtin::BIstdc_leading_zeros_ull:
17951 case Builtin::BIstdc_leading_ones_uc:
17952 case Builtin::BIstdc_leading_ones_us:
17953 case Builtin::BIstdc_leading_ones_ui:
17954 case Builtin::BIstdc_leading_ones_ul:
17955 case Builtin::BIstdc_leading_ones_ull:
17956 case Builtin::BIstdc_trailing_zeros_uc:
17957 case Builtin::BIstdc_trailing_zeros_us:
17958 case Builtin::BIstdc_trailing_zeros_ui:
17959 case Builtin::BIstdc_trailing_zeros_ul:
17960 case Builtin::BIstdc_trailing_zeros_ull:
17961 case Builtin::BIstdc_trailing_ones_uc:
17962 case Builtin::BIstdc_trailing_ones_us:
17963 case Builtin::BIstdc_trailing_ones_ui:
17964 case Builtin::BIstdc_trailing_ones_ul:
17965 case Builtin::BIstdc_trailing_ones_ull:
17966 case Builtin::BIstdc_first_leading_zero_uc:
17967 case Builtin::BIstdc_first_leading_zero_us:
17968 case Builtin::BIstdc_first_leading_zero_ui:
17969 case Builtin::BIstdc_first_leading_zero_ul:
17970 case Builtin::BIstdc_first_leading_zero_ull:
17971 case Builtin::BIstdc_first_leading_one_uc:
17972 case Builtin::BIstdc_first_leading_one_us:
17973 case Builtin::BIstdc_first_leading_one_ui:
17974 case Builtin::BIstdc_first_leading_one_ul:
17975 case Builtin::BIstdc_first_leading_one_ull:
17976 case Builtin::BIstdc_first_trailing_zero_uc:
17977 case Builtin::BIstdc_first_trailing_zero_us:
17978 case Builtin::BIstdc_first_trailing_zero_ui:
17979 case Builtin::BIstdc_first_trailing_zero_ul:
17980 case Builtin::BIstdc_first_trailing_zero_ull:
17981 case Builtin::BIstdc_first_trailing_one_uc:
17982 case Builtin::BIstdc_first_trailing_one_us:
17983 case Builtin::BIstdc_first_trailing_one_ui:
17984 case Builtin::BIstdc_first_trailing_one_ul:
17985 case Builtin::BIstdc_first_trailing_one_ull:
17986 case Builtin::BIstdc_count_zeros_uc:
17987 case Builtin::BIstdc_count_zeros_us:
17988 case Builtin::BIstdc_count_zeros_ui:
17989 case Builtin::BIstdc_count_zeros_ul:
17990 case Builtin::BIstdc_count_zeros_ull:
17991 case Builtin::BIstdc_count_ones_uc:
17992 case Builtin::BIstdc_count_ones_us:
17993 case Builtin::BIstdc_count_ones_ui:
17994 case Builtin::BIstdc_count_ones_ul:
17995 case Builtin::BIstdc_count_ones_ull:
17996 case Builtin::BIstdc_has_single_bit_uc:
17997 case Builtin::BIstdc_has_single_bit_us:
17998 case Builtin::BIstdc_has_single_bit_ui:
17999 case Builtin::BIstdc_has_single_bit_ul:
18000 case Builtin::BIstdc_has_single_bit_ull:
18001 case Builtin::BIstdc_bit_width_uc:
18002 case Builtin::BIstdc_bit_width_us:
18003 case Builtin::BIstdc_bit_width_ui:
18004 case Builtin::BIstdc_bit_width_ul:
18005 case Builtin::BIstdc_bit_width_ull:
18006 case Builtin::BIstdc_bit_floor_uc:
18007 case Builtin::BIstdc_bit_floor_us:
18008 case Builtin::BIstdc_bit_floor_ui:
18009 case Builtin::BIstdc_bit_floor_ul:
18010 case Builtin::BIstdc_bit_floor_ull:
18011 case Builtin::BIstdc_bit_ceil_uc:
18012 case Builtin::BIstdc_bit_ceil_us:
18013 case Builtin::BIstdc_bit_ceil_ui:
18014 case Builtin::BIstdc_bit_ceil_ul:
18015 case Builtin::BIstdc_bit_ceil_ull:
18016 case Builtin::BI__builtin_stdc_leading_zeros:
18017 case Builtin::BI__builtin_stdc_leading_ones:
18018 case Builtin::BI__builtin_stdc_trailing_zeros:
18019 case Builtin::BI__builtin_stdc_trailing_ones:
18020 case Builtin::BI__builtin_stdc_first_leading_zero:
18021 case Builtin::BI__builtin_stdc_first_leading_one:
18022 case Builtin::BI__builtin_stdc_first_trailing_zero:
18023 case Builtin::BI__builtin_stdc_first_trailing_one:
18024 case Builtin::BI__builtin_stdc_count_zeros:
18025 case Builtin::BI__builtin_stdc_count_ones:
18026 case Builtin::BI__builtin_stdc_has_single_bit:
18027 case Builtin::BI__builtin_stdc_bit_width:
18028 case Builtin::BI__builtin_stdc_bit_floor:
18029 case Builtin::BI__builtin_stdc_bit_ceil: {
18030 APSInt Val;
18031 if (!EvaluateInteger(E->getArg(0), Val, Info))
18032 return false;
18033
18034 unsigned BitWidth = Val.getBitWidth();
18035 const unsigned ResBitWidth = Info.Ctx.getIntWidth(E->getType());
18036
18037 switch (BuiltinOp) {
18038 case Builtin::BIstdc_leading_zeros_uc:
18039 case Builtin::BIstdc_leading_zeros_us:
18040 case Builtin::BIstdc_leading_zeros_ui:
18041 case Builtin::BIstdc_leading_zeros_ul:
18042 case Builtin::BIstdc_leading_zeros_ull:
18043 case Builtin::BI__builtin_stdc_leading_zeros:
18044 return Success(APInt(ResBitWidth, Val.countl_zero()), E);
18045 case Builtin::BIstdc_leading_ones_uc:
18046 case Builtin::BIstdc_leading_ones_us:
18047 case Builtin::BIstdc_leading_ones_ui:
18048 case Builtin::BIstdc_leading_ones_ul:
18049 case Builtin::BIstdc_leading_ones_ull:
18050 case Builtin::BI__builtin_stdc_leading_ones:
18051 return Success(APInt(ResBitWidth, Val.countl_one()), E);
18052 case Builtin::BIstdc_trailing_zeros_uc:
18053 case Builtin::BIstdc_trailing_zeros_us:
18054 case Builtin::BIstdc_trailing_zeros_ui:
18055 case Builtin::BIstdc_trailing_zeros_ul:
18056 case Builtin::BIstdc_trailing_zeros_ull:
18057 case Builtin::BI__builtin_stdc_trailing_zeros:
18058 return Success(APInt(ResBitWidth, Val.countr_zero()), E);
18059 case Builtin::BIstdc_trailing_ones_uc:
18060 case Builtin::BIstdc_trailing_ones_us:
18061 case Builtin::BIstdc_trailing_ones_ui:
18062 case Builtin::BIstdc_trailing_ones_ul:
18063 case Builtin::BIstdc_trailing_ones_ull:
18064 case Builtin::BI__builtin_stdc_trailing_ones:
18065 return Success(APInt(ResBitWidth, Val.countr_one()), E);
18066 case Builtin::BIstdc_first_leading_zero_uc:
18067 case Builtin::BIstdc_first_leading_zero_us:
18068 case Builtin::BIstdc_first_leading_zero_ui:
18069 case Builtin::BIstdc_first_leading_zero_ul:
18070 case Builtin::BIstdc_first_leading_zero_ull:
18071 case Builtin::BI__builtin_stdc_first_leading_zero:
18072 return Success(
18073 APInt(ResBitWidth, Val.isAllOnes() ? 0 : Val.countl_one() + 1), E);
18074 case Builtin::BIstdc_first_leading_one_uc:
18075 case Builtin::BIstdc_first_leading_one_us:
18076 case Builtin::BIstdc_first_leading_one_ui:
18077 case Builtin::BIstdc_first_leading_one_ul:
18078 case Builtin::BIstdc_first_leading_one_ull:
18079 case Builtin::BI__builtin_stdc_first_leading_one:
18080 return Success(
18081 APInt(ResBitWidth, Val.isZero() ? 0 : Val.countl_zero() + 1), E);
18082 case Builtin::BIstdc_first_trailing_zero_uc:
18083 case Builtin::BIstdc_first_trailing_zero_us:
18084 case Builtin::BIstdc_first_trailing_zero_ui:
18085 case Builtin::BIstdc_first_trailing_zero_ul:
18086 case Builtin::BIstdc_first_trailing_zero_ull:
18087 case Builtin::BI__builtin_stdc_first_trailing_zero:
18088 return Success(
18089 APInt(ResBitWidth, Val.isAllOnes() ? 0 : Val.countr_one() + 1), E);
18090 case Builtin::BIstdc_first_trailing_one_uc:
18091 case Builtin::BIstdc_first_trailing_one_us:
18092 case Builtin::BIstdc_first_trailing_one_ui:
18093 case Builtin::BIstdc_first_trailing_one_ul:
18094 case Builtin::BIstdc_first_trailing_one_ull:
18095 case Builtin::BI__builtin_stdc_first_trailing_one:
18096 return Success(
18097 APInt(ResBitWidth, Val.isZero() ? 0 : Val.countr_zero() + 1), E);
18098 case Builtin::BIstdc_count_zeros_uc:
18099 case Builtin::BIstdc_count_zeros_us:
18100 case Builtin::BIstdc_count_zeros_ui:
18101 case Builtin::BIstdc_count_zeros_ul:
18102 case Builtin::BIstdc_count_zeros_ull:
18103 case Builtin::BI__builtin_stdc_count_zeros: {
18104 APInt Cnt(ResBitWidth, BitWidth - Val.popcount());
18105 return Success(APSInt(Cnt, /*IsUnsigned*/ true), E);
18106 }
18107 case Builtin::BIstdc_count_ones_uc:
18108 case Builtin::BIstdc_count_ones_us:
18109 case Builtin::BIstdc_count_ones_ui:
18110 case Builtin::BIstdc_count_ones_ul:
18111 case Builtin::BIstdc_count_ones_ull:
18112 case Builtin::BI__builtin_stdc_count_ones: {
18113 APInt Cnt(ResBitWidth, Val.popcount());
18114 return Success(APSInt(Cnt, /*IsUnsigned*/ true), E);
18115 }
18116 case Builtin::BIstdc_has_single_bit_uc:
18117 case Builtin::BIstdc_has_single_bit_us:
18118 case Builtin::BIstdc_has_single_bit_ui:
18119 case Builtin::BIstdc_has_single_bit_ul:
18120 case Builtin::BIstdc_has_single_bit_ull:
18121 case Builtin::BI__builtin_stdc_has_single_bit: {
18122 APInt Res(ResBitWidth, Val.popcount() == 1 ? 1 : 0);
18123 return Success(APSInt(Res, /*IsUnsigned*/ true), E);
18124 }
18125 case Builtin::BIstdc_bit_width_uc:
18126 case Builtin::BIstdc_bit_width_us:
18127 case Builtin::BIstdc_bit_width_ui:
18128 case Builtin::BIstdc_bit_width_ul:
18129 case Builtin::BIstdc_bit_width_ull:
18130 case Builtin::BI__builtin_stdc_bit_width:
18131 return Success(APInt(ResBitWidth, BitWidth - Val.countl_zero()), E);
18132 case Builtin::BIstdc_bit_floor_uc:
18133 case Builtin::BIstdc_bit_floor_us:
18134 case Builtin::BIstdc_bit_floor_ui:
18135 case Builtin::BIstdc_bit_floor_ul:
18136 case Builtin::BIstdc_bit_floor_ull:
18137 case Builtin::BI__builtin_stdc_bit_floor: {
18138 if (Val.isZero())
18139 return Success(APInt(BitWidth, 0), E);
18140 unsigned Exp = BitWidth - Val.countl_zero() - 1;
18141 return Success(
18142 APSInt(APInt::getOneBitSet(BitWidth, Exp), /*IsUnsigned*/ true), E);
18143 }
18144 case Builtin::BIstdc_bit_ceil_uc:
18145 case Builtin::BIstdc_bit_ceil_us:
18146 case Builtin::BIstdc_bit_ceil_ui:
18147 case Builtin::BIstdc_bit_ceil_ul:
18148 case Builtin::BIstdc_bit_ceil_ull:
18149 case Builtin::BI__builtin_stdc_bit_ceil: {
18150 if (Val.ule(1))
18151 return Success(APSInt(APInt(BitWidth, 1), /*IsUnsigned*/ true), E);
18152 APInt ValMinusOne = Val - 1;
18153 unsigned LZ = ValMinusOne.countl_zero();
18154 if (LZ == 0)
18155 return Success(APSInt(APInt(BitWidth, 0), /*IsUnsigned*/ true),
18156 E); // overflows; wrap to 0
18157 APInt Result = APInt::getOneBitSet(BitWidth, BitWidth - LZ);
18158 return Success(APSInt(Result, /*IsUnsigned*/ true), E);
18159 }
18160 default:
18161 llvm_unreachable("Unknown stdc builtin");
18162 }
18163 }
18164
18165 case Builtin::BI__builtin_elementwise_add_sat: {
18166 APSInt LHS, RHS;
18167 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
18168 !EvaluateInteger(E->getArg(1), RHS, Info))
18169 return false;
18170
18171 APInt Result = LHS.isSigned() ? LHS.sadd_sat(RHS) : LHS.uadd_sat(RHS);
18172 return Success(APSInt(Result, !LHS.isSigned()), E);
18173 }
18174 case Builtin::BI__builtin_elementwise_sub_sat: {
18175 APSInt LHS, RHS;
18176 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
18177 !EvaluateInteger(E->getArg(1), RHS, Info))
18178 return false;
18179
18180 APInt Result = LHS.isSigned() ? LHS.ssub_sat(RHS) : LHS.usub_sat(RHS);
18181 return Success(APSInt(Result, !LHS.isSigned()), E);
18182 }
18183 case Builtin::BI__builtin_elementwise_max: {
18184 APSInt LHS, RHS;
18185 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
18186 !EvaluateInteger(E->getArg(1), RHS, Info))
18187 return false;
18188
18189 APInt Result = std::max(LHS, RHS);
18190 return Success(APSInt(Result, !LHS.isSigned()), E);
18191 }
18192 case Builtin::BI__builtin_elementwise_min: {
18193 APSInt LHS, RHS;
18194 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
18195 !EvaluateInteger(E->getArg(1), RHS, Info))
18196 return false;
18197
18198 APInt Result = std::min(LHS, RHS);
18199 return Success(APSInt(Result, !LHS.isSigned()), E);
18200 }
18201 case Builtin::BI__builtin_elementwise_clmul: {
18202 APSInt LHS, RHS;
18203 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
18204 !EvaluateInteger(E->getArg(1), RHS, Info))
18205 return false;
18206
18207 APInt Result = llvm::APIntOps::clmul(LHS, RHS);
18208 return Success(APSInt(Result, LHS.isUnsigned()), E);
18209 }
18210 case Builtin::BI__builtin_elementwise_fshl:
18211 case Builtin::BI__builtin_elementwise_fshr: {
18212 APSInt Hi, Lo, Shift;
18213 if (!EvaluateInteger(E->getArg(0), Hi, Info) ||
18214 !EvaluateInteger(E->getArg(1), Lo, Info) ||
18215 !EvaluateInteger(E->getArg(2), Shift, Info))
18216 return false;
18217
18218 switch (BuiltinOp) {
18219 case Builtin::BI__builtin_elementwise_fshl: {
18220 APSInt Result(llvm::APIntOps::fshl(Hi, Lo, Shift), Hi.isUnsigned());
18221 return Success(Result, E);
18222 }
18223 case Builtin::BI__builtin_elementwise_fshr: {
18224 APSInt Result(llvm::APIntOps::fshr(Hi, Lo, Shift), Hi.isUnsigned());
18225 return Success(Result, E);
18226 }
18227 }
18228 llvm_unreachable("Fully covered switch above");
18229 }
18230 case Builtin::BIstrlen:
18231 case Builtin::BIwcslen:
18232 // A call to strlen is not a constant expression.
18233 if (Info.getLangOpts().CPlusPlus11)
18234 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
18235 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
18236 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
18237 else
18238 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
18239 [[fallthrough]];
18240 case Builtin::BI__builtin_strlen:
18241 case Builtin::BI__builtin_wcslen: {
18242 // As an extension, we support __builtin_strlen() as a constant expression,
18243 // and support folding strlen() to a constant.
18244 if (std::optional<uint64_t> StrLen =
18245 EvaluateBuiltinStrLen(E->getArg(0), Info))
18246 return Success(*StrLen, E);
18247 return false;
18248 }
18249
18250 case Builtin::BIstrcmp:
18251 case Builtin::BIwcscmp:
18252 case Builtin::BIstrncmp:
18253 case Builtin::BIwcsncmp:
18254 case Builtin::BImemcmp:
18255 case Builtin::BIbcmp:
18256 case Builtin::BIwmemcmp:
18257 // A call to strlen is not a constant expression.
18258 if (Info.getLangOpts().CPlusPlus11)
18259 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
18260 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
18261 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
18262 else
18263 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
18264 [[fallthrough]];
18265 case Builtin::BI__builtin_strcmp:
18266 case Builtin::BI__builtin_wcscmp:
18267 case Builtin::BI__builtin_strncmp:
18268 case Builtin::BI__builtin_wcsncmp:
18269 case Builtin::BI__builtin_memcmp:
18270 case Builtin::BI__builtin_bcmp:
18271 case Builtin::BI__builtin_wmemcmp: {
18272 LValue String1, String2;
18273 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
18274 !EvaluatePointer(E->getArg(1), String2, Info))
18275 return false;
18276
18277 uint64_t MaxLength = uint64_t(-1);
18278 if (BuiltinOp != Builtin::BIstrcmp &&
18279 BuiltinOp != Builtin::BIwcscmp &&
18280 BuiltinOp != Builtin::BI__builtin_strcmp &&
18281 BuiltinOp != Builtin::BI__builtin_wcscmp) {
18282 APSInt N;
18283 if (!EvaluateInteger(E->getArg(2), N, Info))
18284 return false;
18285 MaxLength = N.getZExtValue();
18286 }
18287
18288 // Empty substrings compare equal by definition.
18289 if (MaxLength == 0u)
18290 return Success(0, E);
18291
18292 if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
18293 !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
18294 String1.Designator.Invalid || String2.Designator.Invalid)
18295 return false;
18296
18297 QualType CharTy1 = String1.Designator.getType(Info.Ctx);
18298 QualType CharTy2 = String2.Designator.getType(Info.Ctx);
18299
18300 bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
18301 BuiltinOp == Builtin::BIbcmp ||
18302 BuiltinOp == Builtin::BI__builtin_memcmp ||
18303 BuiltinOp == Builtin::BI__builtin_bcmp;
18304
18305 assert(IsRawByte ||
18306 (Info.Ctx.hasSameUnqualifiedType(
18307 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
18308 Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
18309
18310 // For memcmp, allow comparing any arrays of '[[un]signed] char' or
18311 // 'char8_t', but no other types.
18312 if (IsRawByte &&
18313 !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) {
18314 // FIXME: Consider using our bit_cast implementation to support this.
18315 Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported)
18316 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp) << CharTy1
18317 << CharTy2;
18318 return false;
18319 }
18320
18321 const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
18322 return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
18323 handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
18324 Char1.isInt() && Char2.isInt();
18325 };
18326 const auto &AdvanceElems = [&] {
18327 return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
18328 HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
18329 };
18330
18331 bool StopAtNull =
18332 (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
18333 BuiltinOp != Builtin::BIwmemcmp &&
18334 BuiltinOp != Builtin::BI__builtin_memcmp &&
18335 BuiltinOp != Builtin::BI__builtin_bcmp &&
18336 BuiltinOp != Builtin::BI__builtin_wmemcmp);
18337 bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
18338 BuiltinOp == Builtin::BIwcsncmp ||
18339 BuiltinOp == Builtin::BIwmemcmp ||
18340 BuiltinOp == Builtin::BI__builtin_wcscmp ||
18341 BuiltinOp == Builtin::BI__builtin_wcsncmp ||
18342 BuiltinOp == Builtin::BI__builtin_wmemcmp;
18343
18344 for (; MaxLength; --MaxLength) {
18345 APValue Char1, Char2;
18346 if (!ReadCurElems(Char1, Char2))
18347 return false;
18348 if (Char1.getInt().ne(Char2.getInt())) {
18349 if (IsWide) // wmemcmp compares with wchar_t signedness.
18350 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
18351 // memcmp always compares unsigned chars.
18352 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
18353 }
18354 if (StopAtNull && !Char1.getInt())
18355 return Success(0, E);
18356 assert(!(StopAtNull && !Char2.getInt()));
18357 if (!AdvanceElems())
18358 return false;
18359 }
18360 // We hit the strncmp / memcmp limit.
18361 return Success(0, E);
18362 }
18363
18364 case Builtin::BI__atomic_always_lock_free:
18365 case Builtin::BI__atomic_is_lock_free:
18366 case Builtin::BI__c11_atomic_is_lock_free: {
18367 APSInt SizeVal;
18368 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
18369 return false;
18370
18371 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
18372 // of two less than or equal to the maximum inline atomic width, we know it
18373 // is lock-free. If the size isn't a power of two, or greater than the
18374 // maximum alignment where we promote atomics, we know it is not lock-free
18375 // (at least not in the sense of atomic_is_lock_free). Otherwise,
18376 // the answer can only be determined at runtime; for example, 16-byte
18377 // atomics have lock-free implementations on some, but not all,
18378 // x86-64 processors.
18379
18380 // Check power-of-two.
18381 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
18382 if (Size.isPowerOfTwo()) {
18383 // Check against inlining width.
18384 unsigned InlineWidthBits =
18385 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
18386 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
18387 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
18388 Size == CharUnits::One())
18389 return Success(1, E);
18390
18391 // If the pointer argument can be evaluated to a compile-time constant
18392 // integer (or nullptr), check if that value is appropriately aligned.
18393 const Expr *PtrArg = E->getArg(1);
18394 Expr::EvalResult ExprResult;
18395 APSInt IntResult;
18396 if (PtrArg->EvaluateAsRValue(ExprResult, Info.Ctx) &&
18397 ExprResult.Val.toIntegralConstant(IntResult, PtrArg->getType(),
18398 Info.Ctx) &&
18399 IntResult.isAligned(Size.getAsAlign()))
18400 return Success(1, E);
18401
18402 // Otherwise, check if the type's alignment against Size.
18403 if (auto *ICE = dyn_cast<ImplicitCastExpr>(PtrArg)) {
18404 // Drop the potential implicit-cast to 'const volatile void*', getting
18405 // the underlying type.
18406 if (ICE->getCastKind() == CK_BitCast)
18407 PtrArg = ICE->getSubExpr();
18408 }
18409
18410 if (auto PtrTy = PtrArg->getType()->getAs<PointerType>()) {
18411 QualType PointeeType = PtrTy->getPointeeType();
18412 if (!PointeeType->isIncompleteType() &&
18413 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
18414 // OK, we will inline operations on this object.
18415 return Success(1, E);
18416 }
18417 }
18418 }
18419 }
18420
18421 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
18422 Success(0, E) : Error(E);
18423 }
18424 case Builtin::BI__builtin_addcb:
18425 case Builtin::BI__builtin_addcs:
18426 case Builtin::BI__builtin_addc:
18427 case Builtin::BI__builtin_addcl:
18428 case Builtin::BI__builtin_addcll:
18429 case Builtin::BI__builtin_subcb:
18430 case Builtin::BI__builtin_subcs:
18431 case Builtin::BI__builtin_subc:
18432 case Builtin::BI__builtin_subcl:
18433 case Builtin::BI__builtin_subcll: {
18434 LValue CarryOutLValue;
18435 APSInt LHS, RHS, CarryIn, CarryOut, Result;
18436 QualType ResultType = E->getArg(0)->getType();
18437 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
18438 !EvaluateInteger(E->getArg(1), RHS, Info) ||
18439 !EvaluateInteger(E->getArg(2), CarryIn, Info) ||
18440 !EvaluatePointer(E->getArg(3), CarryOutLValue, Info))
18441 return false;
18442 // Copy the number of bits and sign.
18443 Result = LHS;
18444 CarryOut = LHS;
18445
18446 bool FirstOverflowed = false;
18447 bool SecondOverflowed = false;
18448 switch (BuiltinOp) {
18449 default:
18450 llvm_unreachable("Invalid value for BuiltinOp");
18451 case Builtin::BI__builtin_addcb:
18452 case Builtin::BI__builtin_addcs:
18453 case Builtin::BI__builtin_addc:
18454 case Builtin::BI__builtin_addcl:
18455 case Builtin::BI__builtin_addcll:
18456 Result =
18457 LHS.uadd_ov(RHS, FirstOverflowed).uadd_ov(CarryIn, SecondOverflowed);
18458 break;
18459 case Builtin::BI__builtin_subcb:
18460 case Builtin::BI__builtin_subcs:
18461 case Builtin::BI__builtin_subc:
18462 case Builtin::BI__builtin_subcl:
18463 case Builtin::BI__builtin_subcll:
18464 Result =
18465 LHS.usub_ov(RHS, FirstOverflowed).usub_ov(CarryIn, SecondOverflowed);
18466 break;
18467 }
18468
18469 // It is possible for both overflows to happen but CGBuiltin uses an OR so
18470 // this is consistent.
18471 CarryOut = (uint64_t)(FirstOverflowed | SecondOverflowed);
18472 APValue APV{CarryOut};
18473 if (!handleAssignment(Info, E, CarryOutLValue, ResultType, APV))
18474 return false;
18475 return Success(Result, E);
18476 }
18477 case Builtin::BI__builtin_add_overflow:
18478 case Builtin::BI__builtin_sub_overflow:
18479 case Builtin::BI__builtin_mul_overflow:
18480 case Builtin::BI__builtin_sadd_overflow:
18481 case Builtin::BI__builtin_uadd_overflow:
18482 case Builtin::BI__builtin_uaddl_overflow:
18483 case Builtin::BI__builtin_uaddll_overflow:
18484 case Builtin::BI__builtin_usub_overflow:
18485 case Builtin::BI__builtin_usubl_overflow:
18486 case Builtin::BI__builtin_usubll_overflow:
18487 case Builtin::BI__builtin_umul_overflow:
18488 case Builtin::BI__builtin_umull_overflow:
18489 case Builtin::BI__builtin_umulll_overflow:
18490 case Builtin::BI__builtin_saddl_overflow:
18491 case Builtin::BI__builtin_saddll_overflow:
18492 case Builtin::BI__builtin_ssub_overflow:
18493 case Builtin::BI__builtin_ssubl_overflow:
18494 case Builtin::BI__builtin_ssubll_overflow:
18495 case Builtin::BI__builtin_smul_overflow:
18496 case Builtin::BI__builtin_smull_overflow:
18497 case Builtin::BI__builtin_smulll_overflow: {
18498 LValue ResultLValue;
18499 APSInt LHS, RHS;
18500
18501 QualType ResultType = E->getArg(2)->getType()->getPointeeType();
18502 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
18503 !EvaluateInteger(E->getArg(1), RHS, Info) ||
18504 !EvaluatePointer(E->getArg(2), ResultLValue, Info))
18505 return false;
18506
18507 APSInt Result;
18508 bool DidOverflow = false;
18509
18510 // If the types don't have to match, enlarge all 3 to the largest of them.
18511 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
18512 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
18513 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
18514 bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
18516 bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
18518 uint64_t LHSSize = LHS.getBitWidth();
18519 uint64_t RHSSize = RHS.getBitWidth();
18520 uint64_t ResultSize = Info.Ctx.getIntWidth(ResultType);
18521 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
18522
18523 // Add an additional bit if the signedness isn't uniformly agreed to. We
18524 // could do this ONLY if there is a signed and an unsigned that both have
18525 // MaxBits, but the code to check that is pretty nasty. The issue will be
18526 // caught in the shrink-to-result later anyway.
18527 if (IsSigned && !AllSigned)
18528 ++MaxBits;
18529
18530 LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
18531 RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
18532 Result = APSInt(MaxBits, !IsSigned);
18533 }
18534
18535 // Find largest int.
18536 switch (BuiltinOp) {
18537 default:
18538 llvm_unreachable("Invalid value for BuiltinOp");
18539 case Builtin::BI__builtin_add_overflow:
18540 case Builtin::BI__builtin_sadd_overflow:
18541 case Builtin::BI__builtin_saddl_overflow:
18542 case Builtin::BI__builtin_saddll_overflow:
18543 case Builtin::BI__builtin_uadd_overflow:
18544 case Builtin::BI__builtin_uaddl_overflow:
18545 case Builtin::BI__builtin_uaddll_overflow:
18546 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
18547 : LHS.uadd_ov(RHS, DidOverflow);
18548 break;
18549 case Builtin::BI__builtin_sub_overflow:
18550 case Builtin::BI__builtin_ssub_overflow:
18551 case Builtin::BI__builtin_ssubl_overflow:
18552 case Builtin::BI__builtin_ssubll_overflow:
18553 case Builtin::BI__builtin_usub_overflow:
18554 case Builtin::BI__builtin_usubl_overflow:
18555 case Builtin::BI__builtin_usubll_overflow:
18556 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
18557 : LHS.usub_ov(RHS, DidOverflow);
18558 break;
18559 case Builtin::BI__builtin_mul_overflow:
18560 case Builtin::BI__builtin_smul_overflow:
18561 case Builtin::BI__builtin_smull_overflow:
18562 case Builtin::BI__builtin_smulll_overflow:
18563 case Builtin::BI__builtin_umul_overflow:
18564 case Builtin::BI__builtin_umull_overflow:
18565 case Builtin::BI__builtin_umulll_overflow:
18566 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
18567 : LHS.umul_ov(RHS, DidOverflow);
18568 break;
18569 }
18570
18571 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
18572 // since it will give us the behavior of a TruncOrSelf in the case where
18573 // its parameter <= its size. We previously set Result to be at least the
18574 // integer width of the result, so getIntWidth(ResultType) <=
18575 // Result.BitWidth will work exactly like TruncOrSelf.
18576 APSInt Temp = Result.extOrTrunc(Info.Ctx.getIntWidth(ResultType));
18577 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
18578
18579 // In the case where multiple sizes are allowed, truncate and see if
18580 // the values are the same.
18581 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
18582 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
18583 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
18584 if (!APSInt::isSameValue(Temp, Result))
18585 DidOverflow = true;
18586 }
18587 Result = Temp;
18588
18589 APValue APV{Result};
18590 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
18591 return false;
18592 return Success(DidOverflow, E);
18593 }
18594
18595 case Builtin::BI__builtin_reduce_add:
18596 case Builtin::BI__builtin_reduce_mul:
18597 case Builtin::BI__builtin_reduce_and:
18598 case Builtin::BI__builtin_reduce_or:
18599 case Builtin::BI__builtin_reduce_xor:
18600 case Builtin::BI__builtin_reduce_min:
18601 case Builtin::BI__builtin_reduce_max: {
18602 APValue Source;
18603 if (!EvaluateAsRValue(Info, E->getArg(0), Source))
18604 return false;
18605
18606 unsigned SourceLen = Source.getVectorLength();
18607 APSInt Reduced = Source.getVectorElt(0).getInt();
18608 for (unsigned EltNum = 1; EltNum < SourceLen; ++EltNum) {
18609 switch (BuiltinOp) {
18610 default:
18611 return false;
18612 case Builtin::BI__builtin_reduce_add: {
18614 Info, E, Reduced, Source.getVectorElt(EltNum).getInt(),
18615 Reduced.getBitWidth() + 1, std::plus<APSInt>(), Reduced))
18616 return false;
18617 break;
18618 }
18619 case Builtin::BI__builtin_reduce_mul: {
18621 Info, E, Reduced, Source.getVectorElt(EltNum).getInt(),
18622 Reduced.getBitWidth() * 2, std::multiplies<APSInt>(), Reduced))
18623 return false;
18624 break;
18625 }
18626 case Builtin::BI__builtin_reduce_and: {
18627 Reduced &= Source.getVectorElt(EltNum).getInt();
18628 break;
18629 }
18630 case Builtin::BI__builtin_reduce_or: {
18631 Reduced |= Source.getVectorElt(EltNum).getInt();
18632 break;
18633 }
18634 case Builtin::BI__builtin_reduce_xor: {
18635 Reduced ^= Source.getVectorElt(EltNum).getInt();
18636 break;
18637 }
18638 case Builtin::BI__builtin_reduce_min: {
18639 Reduced = std::min(Reduced, Source.getVectorElt(EltNum).getInt());
18640 break;
18641 }
18642 case Builtin::BI__builtin_reduce_max: {
18643 Reduced = std::max(Reduced, Source.getVectorElt(EltNum).getInt());
18644 break;
18645 }
18646 }
18647 }
18648
18649 return Success(Reduced, E);
18650 }
18651
18652 case clang::X86::BI__builtin_ia32_addcarryx_u32:
18653 case clang::X86::BI__builtin_ia32_addcarryx_u64:
18654 case clang::X86::BI__builtin_ia32_subborrow_u32:
18655 case clang::X86::BI__builtin_ia32_subborrow_u64: {
18656 LValue ResultLValue;
18657 APSInt CarryIn, LHS, RHS;
18658 QualType ResultType = E->getArg(3)->getType()->getPointeeType();
18659 if (!EvaluateInteger(E->getArg(0), CarryIn, Info) ||
18660 !EvaluateInteger(E->getArg(1), LHS, Info) ||
18661 !EvaluateInteger(E->getArg(2), RHS, Info) ||
18662 !EvaluatePointer(E->getArg(3), ResultLValue, Info))
18663 return false;
18664
18665 bool IsAdd = BuiltinOp == clang::X86::BI__builtin_ia32_addcarryx_u32 ||
18666 BuiltinOp == clang::X86::BI__builtin_ia32_addcarryx_u64;
18667
18668 unsigned BitWidth = LHS.getBitWidth();
18669 unsigned CarryInBit = CarryIn.ugt(0) ? 1 : 0;
18670 APInt ExResult =
18671 IsAdd
18672 ? (LHS.zext(BitWidth + 1) + (RHS.zext(BitWidth + 1) + CarryInBit))
18673 : (LHS.zext(BitWidth + 1) - (RHS.zext(BitWidth + 1) + CarryInBit));
18674
18675 APInt Result = ExResult.extractBits(BitWidth, 0);
18676 uint64_t CarryOut = ExResult.extractBitsAsZExtValue(1, BitWidth);
18677
18678 APValue APV{APSInt(Result, /*isUnsigned=*/true)};
18679 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
18680 return false;
18681 return Success(CarryOut, E);
18682 }
18683
18684 case clang::X86::BI__builtin_ia32_movmskps:
18685 case clang::X86::BI__builtin_ia32_movmskpd:
18686 case clang::X86::BI__builtin_ia32_pmovmskb128:
18687 case clang::X86::BI__builtin_ia32_pmovmskb256:
18688 case clang::X86::BI__builtin_ia32_movmskps256:
18689 case clang::X86::BI__builtin_ia32_movmskpd256: {
18690 APValue Source;
18691 if (!Evaluate(Source, Info, E->getArg(0)))
18692 return false;
18693 unsigned SourceLen = Source.getVectorLength();
18694 const VectorType *VT = E->getArg(0)->getType()->castAs<VectorType>();
18695 QualType ElemQT = VT->getElementType();
18696 unsigned ResultLen = Info.Ctx.getTypeSize(
18697 E->getCallReturnType(Info.Ctx)); // Always 32-bit integer.
18698 APInt Result(ResultLen, 0);
18699
18700 for (unsigned I = 0; I != SourceLen; ++I) {
18701 APInt Elem;
18702 if (ElemQT->isIntegerType()) {
18703 Elem = Source.getVectorElt(I).getInt();
18704 } else if (ElemQT->isRealFloatingType()) {
18705 Elem = Source.getVectorElt(I).getFloat().bitcastToAPInt();
18706 } else {
18707 return false;
18708 }
18709 Result.setBitVal(I, Elem.isNegative());
18710 }
18711 return Success(Result, E);
18712 }
18713
18714 case clang::X86::BI__builtin_ia32_bextr_u32:
18715 case clang::X86::BI__builtin_ia32_bextr_u64:
18716 case clang::X86::BI__builtin_ia32_bextri_u32:
18717 case clang::X86::BI__builtin_ia32_bextri_u64: {
18718 APSInt Val, Idx;
18719 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
18720 !EvaluateInteger(E->getArg(1), Idx, Info))
18721 return false;
18722
18723 unsigned BitWidth = Val.getBitWidth();
18724 uint64_t Shift = Idx.extractBitsAsZExtValue(8, 0);
18725 uint64_t Length = Idx.extractBitsAsZExtValue(8, 8);
18726 Length = Length > BitWidth ? BitWidth : Length;
18727
18728 // Handle out of bounds cases.
18729 if (Length == 0 || Shift >= BitWidth)
18730 return Success(0, E);
18731
18732 uint64_t Result = Val.getZExtValue() >> Shift;
18733 Result &= llvm::maskTrailingOnes<uint64_t>(Length);
18734 return Success(Result, E);
18735 }
18736
18737 case clang::X86::BI__builtin_ia32_bzhi_si:
18738 case clang::X86::BI__builtin_ia32_bzhi_di: {
18739 APSInt Val, Idx;
18740 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
18741 !EvaluateInteger(E->getArg(1), Idx, Info))
18742 return false;
18743
18744 unsigned BitWidth = Val.getBitWidth();
18745 unsigned Index = Idx.extractBitsAsZExtValue(8, 0);
18746 if (Index < BitWidth)
18747 Val.clearHighBits(BitWidth - Index);
18748 return Success(Val, E);
18749 }
18750
18751 case clang::X86::BI__builtin_ia32_ktestcqi:
18752 case clang::X86::BI__builtin_ia32_ktestchi:
18753 case clang::X86::BI__builtin_ia32_ktestcsi:
18754 case clang::X86::BI__builtin_ia32_ktestcdi: {
18755 APSInt A, B;
18756 if (!EvaluateInteger(E->getArg(0), A, Info) ||
18757 !EvaluateInteger(E->getArg(1), B, Info))
18758 return false;
18759
18760 return Success((~A & B) == 0, E);
18761 }
18762
18763 case clang::X86::BI__builtin_ia32_ktestzqi:
18764 case clang::X86::BI__builtin_ia32_ktestzhi:
18765 case clang::X86::BI__builtin_ia32_ktestzsi:
18766 case clang::X86::BI__builtin_ia32_ktestzdi: {
18767 APSInt A, B;
18768 if (!EvaluateInteger(E->getArg(0), A, Info) ||
18769 !EvaluateInteger(E->getArg(1), B, Info))
18770 return false;
18771
18772 return Success((A & B) == 0, E);
18773 }
18774
18775 case clang::X86::BI__builtin_ia32_kortestcqi:
18776 case clang::X86::BI__builtin_ia32_kortestchi:
18777 case clang::X86::BI__builtin_ia32_kortestcsi:
18778 case clang::X86::BI__builtin_ia32_kortestcdi: {
18779 APSInt A, B;
18780 if (!EvaluateInteger(E->getArg(0), A, Info) ||
18781 !EvaluateInteger(E->getArg(1), B, Info))
18782 return false;
18783
18784 return Success(~(A | B) == 0, E);
18785 }
18786
18787 case clang::X86::BI__builtin_ia32_kortestzqi:
18788 case clang::X86::BI__builtin_ia32_kortestzhi:
18789 case clang::X86::BI__builtin_ia32_kortestzsi:
18790 case clang::X86::BI__builtin_ia32_kortestzdi: {
18791 APSInt A, B;
18792 if (!EvaluateInteger(E->getArg(0), A, Info) ||
18793 !EvaluateInteger(E->getArg(1), B, Info))
18794 return false;
18795
18796 return Success((A | B) == 0, E);
18797 }
18798
18799 case clang::X86::BI__builtin_ia32_kunpckhi:
18800 case clang::X86::BI__builtin_ia32_kunpckdi:
18801 case clang::X86::BI__builtin_ia32_kunpcksi: {
18802 APSInt A, B;
18803 if (!EvaluateInteger(E->getArg(0), A, Info) ||
18804 !EvaluateInteger(E->getArg(1), B, Info))
18805 return false;
18806
18807 // Generic kunpack: extract lower half of each operand and concatenate
18808 // Result = A[HalfWidth-1:0] concat B[HalfWidth-1:0]
18809 unsigned BW = A.getBitWidth();
18810 APSInt Result(A.trunc(BW / 2).concat(B.trunc(BW / 2)), A.isUnsigned());
18811 return Success(Result, E);
18812 }
18813
18814 case clang::X86::BI__builtin_ia32_lzcnt_u16:
18815 case clang::X86::BI__builtin_ia32_lzcnt_u32:
18816 case clang::X86::BI__builtin_ia32_lzcnt_u64: {
18817 APSInt Val;
18818 if (!EvaluateInteger(E->getArg(0), Val, Info))
18819 return false;
18820 return Success(Val.countLeadingZeros(), E);
18821 }
18822
18823 case clang::X86::BI__builtin_ia32_tzcnt_u16:
18824 case clang::X86::BI__builtin_ia32_tzcnt_u32:
18825 case clang::X86::BI__builtin_ia32_tzcnt_u64: {
18826 APSInt Val;
18827 if (!EvaluateInteger(E->getArg(0), Val, Info))
18828 return false;
18829 return Success(Val.countTrailingZeros(), E);
18830 }
18831
18832 case Builtin::BI__builtin_elementwise_pdep: {
18833 APSInt Val, Msk;
18834 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
18835 !EvaluateInteger(E->getArg(1), Msk, Info))
18836 return false;
18837 return Success(llvm::APIntOps::pdep(Val, Msk), E);
18838 }
18839
18840 case Builtin::BI__builtin_elementwise_pext: {
18841 APSInt Val, Msk;
18842 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
18843 !EvaluateInteger(E->getArg(1), Msk, Info))
18844 return false;
18845 return Success(llvm::APIntOps::pext(Val, Msk), E);
18846 }
18847
18848 case X86::BI__builtin_ia32_ptestz128:
18849 case X86::BI__builtin_ia32_ptestz256:
18850 case X86::BI__builtin_ia32_vtestzps:
18851 case X86::BI__builtin_ia32_vtestzps256:
18852 case X86::BI__builtin_ia32_vtestzpd:
18853 case X86::BI__builtin_ia32_vtestzpd256: {
18854 return EvalTestOp(
18855 [](const APInt &A, const APInt &B) { return (A & B) == 0; });
18856 }
18857 case X86::BI__builtin_ia32_ptestc128:
18858 case X86::BI__builtin_ia32_ptestc256:
18859 case X86::BI__builtin_ia32_vtestcps:
18860 case X86::BI__builtin_ia32_vtestcps256:
18861 case X86::BI__builtin_ia32_vtestcpd:
18862 case X86::BI__builtin_ia32_vtestcpd256: {
18863 return EvalTestOp(
18864 [](const APInt &A, const APInt &B) { return (~A & B) == 0; });
18865 }
18866 case X86::BI__builtin_ia32_ptestnzc128:
18867 case X86::BI__builtin_ia32_ptestnzc256:
18868 case X86::BI__builtin_ia32_vtestnzcps:
18869 case X86::BI__builtin_ia32_vtestnzcps256:
18870 case X86::BI__builtin_ia32_vtestnzcpd:
18871 case X86::BI__builtin_ia32_vtestnzcpd256: {
18872 return EvalTestOp([](const APInt &A, const APInt &B) {
18873 return ((A & B) != 0) && ((~A & B) != 0);
18874 });
18875 }
18876 case X86::BI__builtin_ia32_kandqi:
18877 case X86::BI__builtin_ia32_kandhi:
18878 case X86::BI__builtin_ia32_kandsi:
18879 case X86::BI__builtin_ia32_kanddi: {
18880 return HandleMaskBinOp(
18881 [](const APSInt &LHS, const APSInt &RHS) { return LHS & RHS; });
18882 }
18883
18884 case X86::BI__builtin_ia32_kandnqi:
18885 case X86::BI__builtin_ia32_kandnhi:
18886 case X86::BI__builtin_ia32_kandnsi:
18887 case X86::BI__builtin_ia32_kandndi: {
18888 return HandleMaskBinOp(
18889 [](const APSInt &LHS, const APSInt &RHS) { return ~LHS & RHS; });
18890 }
18891
18892 case X86::BI__builtin_ia32_korqi:
18893 case X86::BI__builtin_ia32_korhi:
18894 case X86::BI__builtin_ia32_korsi:
18895 case X86::BI__builtin_ia32_kordi: {
18896 return HandleMaskBinOp(
18897 [](const APSInt &LHS, const APSInt &RHS) { return LHS | RHS; });
18898 }
18899
18900 case X86::BI__builtin_ia32_kxnorqi:
18901 case X86::BI__builtin_ia32_kxnorhi:
18902 case X86::BI__builtin_ia32_kxnorsi:
18903 case X86::BI__builtin_ia32_kxnordi: {
18904 return HandleMaskBinOp(
18905 [](const APSInt &LHS, const APSInt &RHS) { return ~(LHS ^ RHS); });
18906 }
18907
18908 case X86::BI__builtin_ia32_kxorqi:
18909 case X86::BI__builtin_ia32_kxorhi:
18910 case X86::BI__builtin_ia32_kxorsi:
18911 case X86::BI__builtin_ia32_kxordi: {
18912 return HandleMaskBinOp(
18913 [](const APSInt &LHS, const APSInt &RHS) { return LHS ^ RHS; });
18914 }
18915
18916 case X86::BI__builtin_ia32_knotqi:
18917 case X86::BI__builtin_ia32_knothi:
18918 case X86::BI__builtin_ia32_knotsi:
18919 case X86::BI__builtin_ia32_knotdi: {
18920 APSInt Val;
18921 if (!EvaluateInteger(E->getArg(0), Val, Info))
18922 return false;
18923 APSInt Result = ~Val;
18924 return Success(APValue(Result), E);
18925 }
18926
18927 case X86::BI__builtin_ia32_kaddqi:
18928 case X86::BI__builtin_ia32_kaddhi:
18929 case X86::BI__builtin_ia32_kaddsi:
18930 case X86::BI__builtin_ia32_kadddi: {
18931 return HandleMaskBinOp(
18932 [](const APSInt &LHS, const APSInt &RHS) { return LHS + RHS; });
18933 }
18934
18935 case X86::BI__builtin_ia32_kmovb:
18936 case X86::BI__builtin_ia32_kmovw:
18937 case X86::BI__builtin_ia32_kmovd:
18938 case X86::BI__builtin_ia32_kmovq: {
18939 APSInt Val;
18940 if (!EvaluateInteger(E->getArg(0), Val, Info))
18941 return false;
18942 return Success(Val, E);
18943 }
18944
18945 case X86::BI__builtin_ia32_kshiftliqi:
18946 case X86::BI__builtin_ia32_kshiftlihi:
18947 case X86::BI__builtin_ia32_kshiftlisi:
18948 case X86::BI__builtin_ia32_kshiftlidi: {
18949 return HandleMaskBinOp([](const APSInt &LHS, const APSInt &RHS) {
18950 unsigned Amt = RHS.getZExtValue() & 0xFF;
18951 if (Amt >= LHS.getBitWidth())
18952 return APSInt(APInt::getZero(LHS.getBitWidth()), LHS.isUnsigned());
18953 return APSInt(LHS.shl(Amt), LHS.isUnsigned());
18954 });
18955 }
18956
18957 case X86::BI__builtin_ia32_kshiftriqi:
18958 case X86::BI__builtin_ia32_kshiftrihi:
18959 case X86::BI__builtin_ia32_kshiftrisi:
18960 case X86::BI__builtin_ia32_kshiftridi: {
18961 return HandleMaskBinOp([](const APSInt &LHS, const APSInt &RHS) {
18962 unsigned Amt = RHS.getZExtValue() & 0xFF;
18963 if (Amt >= LHS.getBitWidth())
18964 return APSInt(APInt::getZero(LHS.getBitWidth()), LHS.isUnsigned());
18965 return APSInt(LHS.lshr(Amt), LHS.isUnsigned());
18966 });
18967 }
18968
18969 case clang::X86::BI__builtin_ia32_vec_ext_v4hi:
18970 case clang::X86::BI__builtin_ia32_vec_ext_v16qi:
18971 case clang::X86::BI__builtin_ia32_vec_ext_v8hi:
18972 case clang::X86::BI__builtin_ia32_vec_ext_v4si:
18973 case clang::X86::BI__builtin_ia32_vec_ext_v2di:
18974 case clang::X86::BI__builtin_ia32_vec_ext_v32qi:
18975 case clang::X86::BI__builtin_ia32_vec_ext_v16hi:
18976 case clang::X86::BI__builtin_ia32_vec_ext_v8si:
18977 case clang::X86::BI__builtin_ia32_vec_ext_v4di: {
18978 APValue Vec;
18979 APSInt IdxAPS;
18980 if (!EvaluateVector(E->getArg(0), Vec, Info) ||
18981 !EvaluateInteger(E->getArg(1), IdxAPS, Info))
18982 return false;
18983 unsigned N = Vec.getVectorLength();
18984 unsigned Idx = static_cast<unsigned>(IdxAPS.getZExtValue() & (N - 1));
18985 return Success(Vec.getVectorElt(Idx).getInt(), E);
18986 }
18987
18988 case clang::X86::BI__builtin_ia32_cvtb2mask128:
18989 case clang::X86::BI__builtin_ia32_cvtb2mask256:
18990 case clang::X86::BI__builtin_ia32_cvtb2mask512:
18991 case clang::X86::BI__builtin_ia32_cvtw2mask128:
18992 case clang::X86::BI__builtin_ia32_cvtw2mask256:
18993 case clang::X86::BI__builtin_ia32_cvtw2mask512:
18994 case clang::X86::BI__builtin_ia32_cvtd2mask128:
18995 case clang::X86::BI__builtin_ia32_cvtd2mask256:
18996 case clang::X86::BI__builtin_ia32_cvtd2mask512:
18997 case clang::X86::BI__builtin_ia32_cvtq2mask128:
18998 case clang::X86::BI__builtin_ia32_cvtq2mask256:
18999 case clang::X86::BI__builtin_ia32_cvtq2mask512: {
19000 assert(E->getNumArgs() == 1);
19001 APValue Vec;
19002 if (!EvaluateVector(E->getArg(0), Vec, Info))
19003 return false;
19004
19005 unsigned VectorLen = Vec.getVectorLength();
19006 unsigned RetWidth = Info.Ctx.getIntWidth(E->getType());
19007 llvm::APInt Bits(RetWidth, 0);
19008
19009 for (unsigned ElemNum = 0; ElemNum != VectorLen; ++ElemNum) {
19010 const APSInt &A = Vec.getVectorElt(ElemNum).getInt();
19011 unsigned MSB = A[A.getBitWidth() - 1];
19012 Bits.setBitVal(ElemNum, MSB);
19013 }
19014
19015 APSInt RetMask(Bits, /*isUnsigned=*/true);
19016 return Success(APValue(RetMask), E);
19017 }
19018
19019 case clang::X86::BI__builtin_ia32_cmpb128_mask:
19020 case clang::X86::BI__builtin_ia32_cmpw128_mask:
19021 case clang::X86::BI__builtin_ia32_cmpd128_mask:
19022 case clang::X86::BI__builtin_ia32_cmpq128_mask:
19023 case clang::X86::BI__builtin_ia32_cmpb256_mask:
19024 case clang::X86::BI__builtin_ia32_cmpw256_mask:
19025 case clang::X86::BI__builtin_ia32_cmpd256_mask:
19026 case clang::X86::BI__builtin_ia32_cmpq256_mask:
19027 case clang::X86::BI__builtin_ia32_cmpb512_mask:
19028 case clang::X86::BI__builtin_ia32_cmpw512_mask:
19029 case clang::X86::BI__builtin_ia32_cmpd512_mask:
19030 case clang::X86::BI__builtin_ia32_cmpq512_mask:
19031 case clang::X86::BI__builtin_ia32_ucmpb128_mask:
19032 case clang::X86::BI__builtin_ia32_ucmpw128_mask:
19033 case clang::X86::BI__builtin_ia32_ucmpd128_mask:
19034 case clang::X86::BI__builtin_ia32_ucmpq128_mask:
19035 case clang::X86::BI__builtin_ia32_ucmpb256_mask:
19036 case clang::X86::BI__builtin_ia32_ucmpw256_mask:
19037 case clang::X86::BI__builtin_ia32_ucmpd256_mask:
19038 case clang::X86::BI__builtin_ia32_ucmpq256_mask:
19039 case clang::X86::BI__builtin_ia32_ucmpb512_mask:
19040 case clang::X86::BI__builtin_ia32_ucmpw512_mask:
19041 case clang::X86::BI__builtin_ia32_ucmpd512_mask:
19042 case clang::X86::BI__builtin_ia32_ucmpq512_mask: {
19043 assert(E->getNumArgs() == 4);
19044
19045 bool IsUnsigned =
19046 (BuiltinOp >= clang::X86::BI__builtin_ia32_ucmpb128_mask &&
19047 BuiltinOp <= clang::X86::BI__builtin_ia32_ucmpw512_mask);
19048
19049 APValue LHS, RHS;
19050 APSInt Mask, Opcode;
19051 if (!EvaluateVector(E->getArg(0), LHS, Info) ||
19052 !EvaluateVector(E->getArg(1), RHS, Info) ||
19053 !EvaluateInteger(E->getArg(2), Opcode, Info) ||
19054 !EvaluateInteger(E->getArg(3), Mask, Info))
19055 return false;
19056
19057 assert(LHS.getVectorLength() == RHS.getVectorLength());
19058
19059 unsigned VectorLen = LHS.getVectorLength();
19060 unsigned RetWidth = Mask.getBitWidth();
19061
19062 APSInt RetMask(llvm::APInt(RetWidth, 0), /*isUnsigned=*/true);
19063
19064 for (unsigned ElemNum = 0; ElemNum < VectorLen; ++ElemNum) {
19065 const APSInt &A = LHS.getVectorElt(ElemNum).getInt();
19066 const APSInt &B = RHS.getVectorElt(ElemNum).getInt();
19067 bool Result = false;
19068
19069 switch (Opcode.getExtValue() & 0x7) {
19070 case 0: // _MM_CMPINT_EQ
19071 Result = (A == B);
19072 break;
19073 case 1: // _MM_CMPINT_LT
19074 Result = IsUnsigned ? A.ult(B) : A.slt(B);
19075 break;
19076 case 2: // _MM_CMPINT_LE
19077 Result = IsUnsigned ? A.ule(B) : A.sle(B);
19078 break;
19079 case 3: // _MM_CMPINT_FALSE
19080 Result = false;
19081 break;
19082 case 4: // _MM_CMPINT_NE
19083 Result = (A != B);
19084 break;
19085 case 5: // _MM_CMPINT_NLT (>=)
19086 Result = IsUnsigned ? A.uge(B) : A.sge(B);
19087 break;
19088 case 6: // _MM_CMPINT_NLE (>)
19089 Result = IsUnsigned ? A.ugt(B) : A.sgt(B);
19090 break;
19091 case 7: // _MM_CMPINT_TRUE
19092 Result = true;
19093 break;
19094 }
19095
19096 RetMask.setBitVal(ElemNum, Mask[ElemNum] && Result);
19097 }
19098
19099 return Success(APValue(RetMask), E);
19100 }
19101 case X86::BI__builtin_ia32_cvtss2si:
19102 case X86::BI__builtin_ia32_cvtsd2si:
19103 case X86::BI__builtin_ia32_cvttss2si:
19104 case X86::BI__builtin_ia32_cvttsd2si:
19105 case X86::BI__builtin_ia32_cvtss2si64:
19106 case X86::BI__builtin_ia32_cvtsd2si64:
19107 case X86::BI__builtin_ia32_cvttss2si64:
19108 case X86::BI__builtin_ia32_cvttsd2si64: {
19109 APValue ArgVal;
19110 if (!EvaluateAsRValue(Info, E->getArg(0), ArgVal))
19111 return false;
19112
19113 assert(ArgVal.isVector() && "Expected a vector argument");
19114 llvm::APFloat FloatElem = ArgVal.getVectorElt(0).getFloat();
19115 unsigned BitWidth = Info.Ctx.getIntWidth(E->getType());
19117
19118 llvm::APSInt IntResult(BitWidth, isUnsigned);
19119 bool IsExact = false;
19120 // We only allow exact conversions so rounding mode does not matter for cvt*
19121 // and cvtt* builtins
19122 FloatElem.convertToInteger(IntResult, llvm::APFloat::rmTowardZero,
19123 &IsExact);
19124 if (!IsExact)
19125 return false;
19126
19127 return Success(IntResult, E);
19128 }
19129 case X86::BI__builtin_ia32_vpshufbitqmb128_mask:
19130 case X86::BI__builtin_ia32_vpshufbitqmb256_mask:
19131 case X86::BI__builtin_ia32_vpshufbitqmb512_mask: {
19132 assert(E->getNumArgs() == 3);
19133
19134 APValue Source, ShuffleMask;
19135 APSInt ZeroMask;
19136 if (!EvaluateVector(E->getArg(0), Source, Info) ||
19137 !EvaluateVector(E->getArg(1), ShuffleMask, Info) ||
19138 !EvaluateInteger(E->getArg(2), ZeroMask, Info))
19139 return false;
19140
19141 assert(Source.getVectorLength() == ShuffleMask.getVectorLength());
19142 assert(ZeroMask.getBitWidth() == Source.getVectorLength());
19143
19144 unsigned NumBytesInQWord = 8;
19145 unsigned NumBitsInByte = 8;
19146 unsigned NumBytes = Source.getVectorLength();
19147 unsigned NumQWords = NumBytes / NumBytesInQWord;
19148 unsigned RetWidth = ZeroMask.getBitWidth();
19149 APSInt RetMask(llvm::APInt(RetWidth, 0), /*isUnsigned=*/true);
19150
19151 for (unsigned QWordId = 0; QWordId != NumQWords; ++QWordId) {
19152 APInt SourceQWord(64, 0);
19153 for (unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
19154 uint64_t Byte = Source.getVectorElt(QWordId * NumBytesInQWord + ByteIdx)
19155 .getInt()
19156 .getZExtValue();
19157 SourceQWord.insertBits(APInt(8, Byte & 0xFF), ByteIdx * NumBitsInByte);
19158 }
19159
19160 for (unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
19161 unsigned SelIdx = QWordId * NumBytesInQWord + ByteIdx;
19162 unsigned M =
19163 ShuffleMask.getVectorElt(SelIdx).getInt().getZExtValue() & 0x3F;
19164 if (ZeroMask[SelIdx]) {
19165 RetMask.setBitVal(SelIdx, SourceQWord[M]);
19166 }
19167 }
19168 }
19169 return Success(APValue(RetMask), E);
19170 }
19171 }
19172}
19173
19174/// Determine whether this is a pointer past the end of the complete
19175/// object referred to by the lvalue.
19177 const LValue &LV) {
19178 // A null pointer can be viewed as being "past the end" but we don't
19179 // choose to look at it that way here.
19180 if (!LV.getLValueBase())
19181 return false;
19182
19183 // If the designator is valid and refers to a subobject, we're not pointing
19184 // past the end.
19185 if (!LV.getLValueDesignator().Invalid &&
19186 !LV.getLValueDesignator().isOnePastTheEnd())
19187 return false;
19188
19189 // A pointer to an incomplete type might be past-the-end if the type's size is
19190 // zero. We cannot tell because the type is incomplete.
19191 QualType Ty = getType(LV.getLValueBase());
19192 if (Ty->isIncompleteType())
19193 return true;
19194
19195 // Can't be past the end of an invalid object.
19196 if (LV.getLValueDesignator().Invalid)
19197 return false;
19198
19199 // We're a past-the-end pointer if we point to the byte after the object,
19200 // no matter what our type or path is.
19201 auto Size = Ctx.getTypeSizeInChars(Ty);
19202 return LV.getLValueOffset() == Size;
19203}
19204
19205namespace {
19206
19207/// Data recursive integer evaluator of certain binary operators.
19208///
19209/// We use a data recursive algorithm for binary operators so that we are able
19210/// to handle extreme cases of chained binary operators without causing stack
19211/// overflow.
19212class DataRecursiveIntBinOpEvaluator {
19213 struct EvalResult {
19214 APValue Val;
19215 bool Failed = false;
19216
19217 EvalResult() = default;
19218
19219 void swap(EvalResult &RHS) {
19220 Val.swap(RHS.Val);
19221 Failed = RHS.Failed;
19222 RHS.Failed = false;
19223 }
19224 };
19225
19226 struct Job {
19227 const Expr *E;
19228 EvalResult LHSResult; // meaningful only for binary operator expression.
19229 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
19230
19231 Job() = default;
19232 Job(Job &&) = default;
19233
19234 void startSpeculativeEval(EvalInfo &Info) {
19235 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
19236 }
19237
19238 private:
19239 SpeculativeEvaluationRAII SpecEvalRAII;
19240 };
19241
19242 SmallVector<Job, 16> Queue;
19243
19244 IntExprEvaluator &IntEval;
19245 EvalInfo &Info;
19246 APValue &FinalResult;
19247
19248public:
19249 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
19250 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
19251
19252 /// True if \param E is a binary operator that we are going to handle
19253 /// data recursively.
19254 /// We handle binary operators that are comma, logical, or that have operands
19255 /// with integral or enumeration type.
19256 static bool shouldEnqueue(const BinaryOperator *E) {
19257 return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
19261 }
19262
19263 bool Traverse(const BinaryOperator *E) {
19264 enqueue(E);
19265 EvalResult PrevResult;
19266 while (!Queue.empty())
19267 process(PrevResult);
19268
19269 if (PrevResult.Failed) return false;
19270
19271 FinalResult.swap(PrevResult.Val);
19272 return true;
19273 }
19274
19275private:
19276 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
19277 return IntEval.Success(Value, E, Result);
19278 }
19279 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
19280 return IntEval.Success(Value, E, Result);
19281 }
19282 bool Error(const Expr *E) {
19283 return IntEval.Error(E);
19284 }
19285 bool Error(const Expr *E, diag::kind D) {
19286 return IntEval.Error(E, D);
19287 }
19288
19289 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
19290 return Info.CCEDiag(E, D);
19291 }
19292
19293 // Returns true if visiting the RHS is necessary, false otherwise.
19294 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
19295 bool &SuppressRHSDiags);
19296
19297 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
19298 const BinaryOperator *E, APValue &Result);
19299
19300 void EvaluateExpr(const Expr *E, EvalResult &Result) {
19301 Result.Failed = !Evaluate(Result.Val, Info, E);
19302 if (Result.Failed)
19303 Result.Val = APValue();
19304 }
19305
19306 void process(EvalResult &Result);
19307
19308 void enqueue(const Expr *E) {
19309 E = E->IgnoreParens();
19310 Queue.resize(Queue.size()+1);
19311 Queue.back().E = E;
19312 Queue.back().Kind = Job::AnyExprKind;
19313 }
19314};
19315
19316}
19317
19318bool DataRecursiveIntBinOpEvaluator::
19319 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
19320 bool &SuppressRHSDiags) {
19321 if (E->getOpcode() == BO_Comma) {
19322 // Ignore LHS but note if we could not evaluate it.
19323 if (LHSResult.Failed)
19324 return Info.noteSideEffect();
19325 return true;
19326 }
19327
19328 if (E->isLogicalOp()) {
19329 bool LHSAsBool;
19330 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
19331 // We were able to evaluate the LHS, see if we can get away with not
19332 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
19333 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
19334 Success(LHSAsBool, E, LHSResult.Val);
19335 return false; // Ignore RHS
19336 }
19337 } else {
19338 LHSResult.Failed = true;
19339
19340 // Since we weren't able to evaluate the left hand side, it
19341 // might have had side effects.
19342 if (!Info.noteSideEffect())
19343 return false;
19344
19345 // We can't evaluate the LHS; however, sometimes the result
19346 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
19347 // Don't ignore RHS and suppress diagnostics from this arm.
19348 SuppressRHSDiags = true;
19349 }
19350
19351 return true;
19352 }
19353
19354 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
19356
19357 if (LHSResult.Failed && !Info.noteFailure())
19358 return false; // Ignore RHS;
19359
19360 return true;
19361}
19362
19363static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
19364 bool IsSub) {
19365 // Compute the new offset in the appropriate width, wrapping at 64 bits.
19366 // FIXME: When compiling for a 32-bit target, we should use 32-bit
19367 // offsets.
19368 assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
19369 CharUnits &Offset = LVal.getLValueOffset();
19370 uint64_t Offset64 = Offset.getQuantity();
19371 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
19372 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
19373 : Offset64 + Index64);
19374}
19375
19376bool DataRecursiveIntBinOpEvaluator::
19377 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
19378 const BinaryOperator *E, APValue &Result) {
19379 if (E->getOpcode() == BO_Comma) {
19380 if (RHSResult.Failed)
19381 return false;
19382 Result = RHSResult.Val;
19383 return true;
19384 }
19385
19386 if (E->isLogicalOp()) {
19387 bool lhsResult, rhsResult;
19388 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
19389 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
19390
19391 if (LHSIsOK) {
19392 if (RHSIsOK) {
19393 if (E->getOpcode() == BO_LOr)
19394 return Success(lhsResult || rhsResult, E, Result);
19395 else
19396 return Success(lhsResult && rhsResult, E, Result);
19397 }
19398 } else {
19399 if (RHSIsOK) {
19400 // We can't evaluate the LHS; however, sometimes the result
19401 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
19402 if (rhsResult == (E->getOpcode() == BO_LOr))
19403 return Success(rhsResult, E, Result);
19404 }
19405 }
19406
19407 return false;
19408 }
19409
19410 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
19412
19413 if (LHSResult.Failed || RHSResult.Failed)
19414 return false;
19415
19416 const APValue &LHSVal = LHSResult.Val;
19417 const APValue &RHSVal = RHSResult.Val;
19418
19419 // Handle cases like (unsigned long)&a + 4.
19420 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
19421 Result = LHSVal;
19422 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
19423 return true;
19424 }
19425
19426 // Handle cases like 4 + (unsigned long)&a
19427 if (E->getOpcode() == BO_Add &&
19428 RHSVal.isLValue() && LHSVal.isInt()) {
19429 Result = RHSVal;
19430 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
19431 return true;
19432 }
19433
19434 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
19435 // Handle (intptr_t)&&A - (intptr_t)&&B.
19436 if (!LHSVal.getLValueOffset().isZero() ||
19437 !RHSVal.getLValueOffset().isZero())
19438 return false;
19439 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
19440 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
19441 if (!LHSExpr || !RHSExpr)
19442 return false;
19443 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
19444 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
19445 if (!LHSAddrExpr || !RHSAddrExpr)
19446 return false;
19447 // Make sure both labels come from the same function.
19448 if (LHSAddrExpr->getLabel()->getDeclContext() !=
19449 RHSAddrExpr->getLabel()->getDeclContext())
19450 return false;
19451 Result = APValue(LHSAddrExpr, RHSAddrExpr);
19452 return true;
19453 }
19454
19455 // All the remaining cases expect both operands to be an integer
19456 if (!LHSVal.isInt() || !RHSVal.isInt())
19457 return Error(E);
19458
19459 // Set up the width and signedness manually, in case it can't be deduced
19460 // from the operation we're performing.
19461 // FIXME: Don't do this in the cases where we can deduce it.
19462 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
19464 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
19465 RHSVal.getInt(), Value))
19466 return false;
19467 return Success(Value, E, Result);
19468}
19469
19470void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
19471 Job &job = Queue.back();
19472
19473 switch (job.Kind) {
19474 case Job::AnyExprKind: {
19475 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
19476 if (shouldEnqueue(Bop)) {
19477 job.Kind = Job::BinOpKind;
19478 enqueue(Bop->getLHS());
19479 return;
19480 }
19481 }
19482
19483 EvaluateExpr(job.E, Result);
19484 Queue.pop_back();
19485 return;
19486 }
19487
19488 case Job::BinOpKind: {
19489 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
19490 bool SuppressRHSDiags = false;
19491 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
19492 Queue.pop_back();
19493 return;
19494 }
19495 if (SuppressRHSDiags)
19496 job.startSpeculativeEval(Info);
19497 job.LHSResult.swap(Result);
19498 job.Kind = Job::BinOpVisitedLHSKind;
19499 enqueue(Bop->getRHS());
19500 return;
19501 }
19502
19503 case Job::BinOpVisitedLHSKind: {
19504 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
19505 EvalResult RHS;
19506 RHS.swap(Result);
19507 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
19508 Queue.pop_back();
19509 return;
19510 }
19511 }
19512
19513 llvm_unreachable("Invalid Job::Kind!");
19514}
19515
19516namespace {
19517enum class CmpResult {
19518 Unequal,
19519 Less,
19520 Equal,
19521 Greater,
19522 Unordered,
19523};
19524}
19525
19526template <class SuccessCB, class AfterCB>
19527static bool
19529 SuccessCB &&Success, AfterCB &&DoAfter) {
19530 assert(!E->isValueDependent());
19531 assert(E->isComparisonOp() && "expected comparison operator");
19532 assert((E->getOpcode() == BO_Cmp ||
19534 "unsupported binary expression evaluation");
19535 auto Error = [&](const Expr *E) {
19536 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
19537 return false;
19538 };
19539
19540 bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp;
19541 bool IsEquality = E->isEqualityOp();
19542
19543 QualType LHSTy = E->getLHS()->getType();
19544 QualType RHSTy = E->getRHS()->getType();
19545
19546 if (LHSTy->isIntegralOrEnumerationType() &&
19547 RHSTy->isIntegralOrEnumerationType()) {
19548 APSInt LHS, RHS;
19549 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
19550 if (!LHSOK && !Info.noteFailure())
19551 return false;
19552 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
19553 return false;
19554 if (LHS < RHS)
19555 return Success(CmpResult::Less, E);
19556 if (LHS > RHS)
19557 return Success(CmpResult::Greater, E);
19558 return Success(CmpResult::Equal, E);
19559 }
19560
19561 if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
19562 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
19563 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
19564
19565 bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
19566 if (!LHSOK && !Info.noteFailure())
19567 return false;
19568 if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
19569 return false;
19570 if (LHSFX < RHSFX)
19571 return Success(CmpResult::Less, E);
19572 if (LHSFX > RHSFX)
19573 return Success(CmpResult::Greater, E);
19574 return Success(CmpResult::Equal, E);
19575 }
19576
19577 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
19578 ComplexValue LHS, RHS;
19579 bool LHSOK;
19580 if (E->isAssignmentOp()) {
19581 LValue LV;
19582 EvaluateLValue(E->getLHS(), LV, Info);
19583 LHSOK = false;
19584 } else if (LHSTy->isRealFloatingType()) {
19585 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
19586 if (LHSOK) {
19587 LHS.makeComplexFloat();
19588 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
19589 }
19590 } else {
19591 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
19592 }
19593 if (!LHSOK && !Info.noteFailure())
19594 return false;
19595
19596 if (E->getRHS()->getType()->isRealFloatingType()) {
19597 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
19598 return false;
19599 RHS.makeComplexFloat();
19600 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
19601 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
19602 return false;
19603
19604 if (LHS.isComplexFloat()) {
19605 APFloat::cmpResult CR_r =
19606 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
19607 APFloat::cmpResult CR_i =
19608 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
19609 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
19610 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
19611 } else {
19612 assert(IsEquality && "invalid complex comparison");
19613 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
19614 LHS.getComplexIntImag() == RHS.getComplexIntImag();
19615 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
19616 }
19617 }
19618
19619 if (LHSTy->isRealFloatingType() &&
19620 RHSTy->isRealFloatingType()) {
19621 APFloat RHS(0.0), LHS(0.0);
19622
19623 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
19624 if (!LHSOK && !Info.noteFailure())
19625 return false;
19626
19627 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
19628 return false;
19629
19630 assert(E->isComparisonOp() && "Invalid binary operator!");
19631 llvm::APFloatBase::cmpResult APFloatCmpResult = LHS.compare(RHS);
19632 if (!Info.InConstantContext &&
19633 APFloatCmpResult == APFloat::cmpUnordered &&
19634 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained()) {
19635 // Note: Compares may raise invalid in some cases involving NaN or sNaN.
19636 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
19637 return false;
19638 }
19639 auto GetCmpRes = [&]() {
19640 switch (APFloatCmpResult) {
19641 case APFloat::cmpEqual:
19642 return CmpResult::Equal;
19643 case APFloat::cmpLessThan:
19644 return CmpResult::Less;
19645 case APFloat::cmpGreaterThan:
19646 return CmpResult::Greater;
19647 case APFloat::cmpUnordered:
19648 return CmpResult::Unordered;
19649 }
19650 llvm_unreachable("Unrecognised APFloat::cmpResult enum");
19651 };
19652 return Success(GetCmpRes(), E);
19653 }
19654
19655 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
19656 LValue LHSValue, RHSValue;
19657
19658 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
19659 if (!LHSOK && !Info.noteFailure())
19660 return false;
19661
19662 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
19663 return false;
19664
19665 // Reject differing bases from the normal codepath; we special-case
19666 // comparisons to null.
19667 if (!HasSameBase(LHSValue, RHSValue)) {
19668 // Bail out early if we're checking potential constant expression.
19669 // Otherwise, prefer to diagnose other issues.
19670 if (Info.checkingPotentialConstantExpression() &&
19671 (LHSValue.AllowConstexprUnknown || RHSValue.AllowConstexprUnknown))
19672 return false;
19673 auto DiagComparison = [&] (unsigned DiagID, bool Reversed = false) {
19674 std::string LHS = LHSValue.toString(Info.Ctx, E->getLHS()->getType());
19675 std::string RHS = RHSValue.toString(Info.Ctx, E->getRHS()->getType());
19676 Info.FFDiag(E, DiagID)
19677 << (Reversed ? RHS : LHS) << (Reversed ? LHS : RHS);
19678 return false;
19679 };
19680 // Inequalities and subtractions between unrelated pointers have
19681 // unspecified or undefined behavior.
19682 if (!IsEquality)
19683 return DiagComparison(
19684 diag::note_constexpr_pointer_comparison_unspecified);
19685 // A constant address may compare equal to the address of a symbol.
19686 // The one exception is that address of an object cannot compare equal
19687 // to a null pointer constant.
19688 // TODO: Should we restrict this to actual null pointers, and exclude the
19689 // case of zero cast to pointer type?
19690 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
19691 (!RHSValue.Base && !RHSValue.Offset.isZero()))
19692 return DiagComparison(diag::note_constexpr_pointer_constant_comparison,
19693 !RHSValue.Base);
19694 // C++2c [intro.object]/10:
19695 // Two objects [...] may have the same address if [...] they are both
19696 // potentially non-unique objects.
19697 // C++2c [intro.object]/9:
19698 // An object is potentially non-unique if it is a string literal object,
19699 // the backing array of an initializer list, or a subobject thereof.
19700 //
19701 // This makes the comparison result unspecified, so it's not a constant
19702 // expression.
19703 //
19704 // TODO: Do we need to handle the initializer list case here?
19705 if (ArePotentiallyOverlappingStringLiterals(Info, LHSValue, RHSValue))
19706 return DiagComparison(diag::note_constexpr_literal_comparison);
19707 if (IsOpaqueConstantCall(LHSValue) || IsOpaqueConstantCall(RHSValue))
19708 return DiagComparison(diag::note_constexpr_opaque_call_comparison,
19709 !IsOpaqueConstantCall(LHSValue));
19710 // We can't tell whether weak symbols will end up pointing to the same
19711 // object.
19712 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
19713 return DiagComparison(diag::note_constexpr_pointer_weak_comparison,
19714 !IsWeakLValue(LHSValue));
19715 // We can't compare the address of the start of one object with the
19716 // past-the-end address of another object, per C++ DR1652.
19717 if (LHSValue.Base && LHSValue.Offset.isZero() &&
19718 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue))
19719 return DiagComparison(diag::note_constexpr_pointer_comparison_past_end,
19720 true);
19721 if (RHSValue.Base && RHSValue.Offset.isZero() &&
19722 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue))
19723 return DiagComparison(diag::note_constexpr_pointer_comparison_past_end,
19724 false);
19725 // We can't tell whether an object is at the same address as another
19726 // zero sized object.
19727 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
19728 (LHSValue.Base && isZeroSized(RHSValue)))
19729 return DiagComparison(
19730 diag::note_constexpr_pointer_comparison_zero_sized);
19731 if (LHSValue.AllowConstexprUnknown || RHSValue.AllowConstexprUnknown)
19732 return DiagComparison(
19733 diag::note_constexpr_pointer_comparison_unspecified);
19734 // FIXME: Verify both variables are live.
19735 return Success(CmpResult::Unequal, E);
19736 }
19737
19738 CharUnits LHSOffset = LHSValue.getLValueOffset();
19739 CharUnits RHSOffset = RHSValue.getLValueOffset();
19740
19741 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
19742 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
19743
19744 // C++11 [expr.rel]p2:
19745 // - If two pointers point to non-static data members of the same object,
19746 // or to subobjects or array elements fo such members, recursively, the
19747 // pointer to the later declared member compares greater provided the
19748 // two members have the same access control and provided their class is
19749 // not a union.
19750 // [...]
19751 // - Otherwise pointer comparisons are unspecified.
19752 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
19753 bool WasArrayIndex;
19754 unsigned Mismatch = FindDesignatorMismatch(
19755 LHSValue.Base.isNull() ? QualType()
19756 : getType(LHSValue.Base).getNonReferenceType(),
19757 LHSDesignator, RHSDesignator, WasArrayIndex);
19758 // At the point where the designators diverge, the comparison has a
19759 // specified value if:
19760 // - we are comparing array indices
19761 // - we are comparing fields of a union, or fields with the same access
19762 // Otherwise, the result is unspecified and thus the comparison is not a
19763 // constant expression.
19764 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
19765 Mismatch < RHSDesignator.Entries.size()) {
19766 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
19767 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
19768 if (!LF && !RF)
19769 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
19770 else if (!LF)
19771 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
19772 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
19773 << RF->getParent() << RF;
19774 else if (!RF)
19775 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
19776 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
19777 << LF->getParent() << LF;
19778 else if (!LF->getParent()->isUnion() &&
19779 LF->getAccess() != RF->getAccess())
19780 Info.CCEDiag(E,
19781 diag::note_constexpr_pointer_comparison_differing_access)
19782 << LF << LF->getAccess() << RF << RF->getAccess()
19783 << LF->getParent();
19784 }
19785 }
19786
19787 // The comparison here must be unsigned, and performed with the same
19788 // width as the pointer.
19789 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
19790 uint64_t CompareLHS = LHSOffset.getQuantity();
19791 uint64_t CompareRHS = RHSOffset.getQuantity();
19792 assert(PtrSize <= 64 && "Unexpected pointer width");
19793 uint64_t Mask = ~0ULL >> (64 - PtrSize);
19794 CompareLHS &= Mask;
19795 CompareRHS &= Mask;
19796
19797 // If there is a base and this is a relational operator, we can only
19798 // compare pointers within the object in question; otherwise, the result
19799 // depends on where the object is located in memory.
19800 if (!LHSValue.Base.isNull() && IsRelational) {
19801 QualType BaseTy = getType(LHSValue.Base).getNonReferenceType();
19802 if (BaseTy->isIncompleteType())
19803 return Error(E);
19804 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
19805 uint64_t OffsetLimit = Size.getQuantity();
19806 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
19807 return Error(E);
19808 }
19809
19810 if (CompareLHS < CompareRHS)
19811 return Success(CmpResult::Less, E);
19812 if (CompareLHS > CompareRHS)
19813 return Success(CmpResult::Greater, E);
19814 return Success(CmpResult::Equal, E);
19815 }
19816
19817 if (LHSTy->isMemberPointerType()) {
19818 assert(IsEquality && "unexpected member pointer operation");
19819 assert(RHSTy->isMemberPointerType() && "invalid comparison");
19820
19821 MemberPtr LHSValue, RHSValue;
19822
19823 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
19824 if (!LHSOK && !Info.noteFailure())
19825 return false;
19826
19827 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
19828 return false;
19829
19830 // If either operand is a pointer to a weak function, the comparison is not
19831 // constant.
19832 if (LHSValue.getDecl() && LHSValue.getDecl()->isWeak()) {
19833 Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison)
19834 << LHSValue.getDecl();
19835 return false;
19836 }
19837 if (RHSValue.getDecl() && RHSValue.getDecl()->isWeak()) {
19838 Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison)
19839 << RHSValue.getDecl();
19840 return false;
19841 }
19842
19843 // C++11 [expr.eq]p2:
19844 // If both operands are null, they compare equal. Otherwise if only one is
19845 // null, they compare unequal.
19846 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
19847 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
19848 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
19849 }
19850
19851 // Otherwise if either is a pointer to a virtual member function, the
19852 // result is unspecified.
19853 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
19854 if (MD->isVirtual())
19855 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
19856 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
19857 if (MD->isVirtual())
19858 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
19859
19860 // Otherwise they compare equal if and only if they would refer to the
19861 // same member of the same most derived object or the same subobject if
19862 // they were dereferenced with a hypothetical object of the associated
19863 // class type.
19864 bool Equal = LHSValue == RHSValue;
19865 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
19866 }
19867
19868 if (LHSTy->isNullPtrType()) {
19869 assert(E->isComparisonOp() && "unexpected nullptr operation");
19870 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
19871 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
19872 // are compared, the result is true of the operator is <=, >= or ==, and
19873 // false otherwise.
19874 LValue Res;
19875 if (!EvaluatePointer(E->getLHS(), Res, Info) ||
19876 !EvaluatePointer(E->getRHS(), Res, Info))
19877 return false;
19878 return Success(CmpResult::Equal, E);
19879 }
19880
19881 if (LHSTy->isMetaInfoType() && RHSTy->isMetaInfoType()) {
19882 APValue LHSValue, RHSValue;
19883 llvm::FoldingSetNodeID LID, RID;
19884 if (!Evaluate(LHSValue, Info, E->getLHS()))
19885 return false;
19886 LHSValue.Profile(LID);
19887
19888 if (!Evaluate(RHSValue, Info, E->getRHS()))
19889 return false;
19890 RHSValue.Profile(RID);
19891
19892 if (LID == RID)
19893 return Success(CmpResult::Equal, E);
19894 else
19895 return Success(CmpResult::Unequal, E);
19896 }
19897
19898 return DoAfter();
19899}
19900
19901static bool EvaluateComparisonResult(EvalInfo &Info, const Expr *E,
19903 APValue &Result) {
19904 const ComparisonCategoryInfo &CmpInfo =
19905 Info.Ctx.CompCategories.getInfoForType(E->getType());
19906 const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD;
19907
19908 // Check and evaluate the result as a constant expression.
19909 LValue LV;
19910 LV.set(VD);
19911 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
19912 return false;
19913 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
19914 ConstantExprKind::Normal);
19915}
19916
19917bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
19918 if (!CheckLiteralType(Info, E))
19919 return false;
19920
19921 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
19923 switch (CR) {
19924 case CmpResult::Unequal:
19925 llvm_unreachable("should never produce Unequal for three-way comparison");
19926 case CmpResult::Less:
19927 CCR = ComparisonCategoryResult::Less;
19928 break;
19929 case CmpResult::Equal:
19930 CCR = ComparisonCategoryResult::Equal;
19931 break;
19932 case CmpResult::Greater:
19933 CCR = ComparisonCategoryResult::Greater;
19934 break;
19935 case CmpResult::Unordered:
19936 CCR = ComparisonCategoryResult::Unordered;
19937 break;
19938 }
19939 return EvaluateComparisonResult(Info, E, CCR, Result);
19940 };
19941 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
19942 return ExprEvaluatorBaseTy::VisitBinCmp(E);
19943 });
19944}
19945
19946bool RecordExprEvaluator::VisitTypeTraitExpr(const TypeTraitExpr *E) {
19947 if (!CheckLiteralType(Info, E))
19948 return false;
19949
19950 assert(E->isStoredAsComparisonResult() &&
19951 "expected a strong_ordering type trait with a stored value");
19952
19954 E->getAPValue().getInt().getZExtValue());
19955 return EvaluateComparisonResult(Info, E, CCR, Result);
19956}
19957
19958bool RecordExprEvaluator::VisitCXXParenListInitExpr(
19959 const CXXParenListInitExpr *E) {
19960 return VisitCXXParenListOrInitListExpr(E, E->getInitExprs());
19961}
19962
19963bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
19964 // We don't support assignment in C. C++ assignments don't get here because
19965 // assignment is an lvalue in C++.
19966 if (E->isAssignmentOp()) {
19967 Error(E);
19968 if (!Info.noteFailure())
19969 return false;
19970 }
19971
19972 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
19973 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
19974
19975 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
19977 "DataRecursiveIntBinOpEvaluator should have handled integral types");
19978
19979 if (E->isComparisonOp()) {
19980 // Evaluate builtin binary comparisons by evaluating them as three-way
19981 // comparisons and then translating the result.
19982 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
19983 assert((CR != CmpResult::Unequal || E->isEqualityOp()) &&
19984 "should only produce Unequal for equality comparisons");
19985 bool IsEqual = CR == CmpResult::Equal,
19986 IsLess = CR == CmpResult::Less,
19987 IsGreater = CR == CmpResult::Greater;
19988 auto Op = E->getOpcode();
19989 switch (Op) {
19990 default:
19991 llvm_unreachable("unsupported binary operator");
19992 case BO_EQ:
19993 case BO_NE:
19994 return Success(IsEqual == (Op == BO_EQ), E);
19995 case BO_LT:
19996 return Success(IsLess, E);
19997 case BO_GT:
19998 return Success(IsGreater, E);
19999 case BO_LE:
20000 return Success(IsEqual || IsLess, E);
20001 case BO_GE:
20002 return Success(IsEqual || IsGreater, E);
20003 }
20004 };
20005 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
20006 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
20007 });
20008 }
20009
20010 QualType LHSTy = E->getLHS()->getType();
20011 QualType RHSTy = E->getRHS()->getType();
20012
20013 if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
20014 E->getOpcode() == BO_Sub) {
20015 LValue LHSValue, RHSValue;
20016
20017 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
20018 if (!LHSOK && !Info.noteFailure())
20019 return false;
20020
20021 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
20022 return false;
20023
20024 // Reject differing bases from the normal codepath; we special-case
20025 // comparisons to null.
20026 if (!HasSameBase(LHSValue, RHSValue)) {
20027 if (Info.checkingPotentialConstantExpression() &&
20028 (LHSValue.AllowConstexprUnknown || RHSValue.AllowConstexprUnknown))
20029 return false;
20030
20031 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
20032 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
20033
20034 auto DiagArith = [&](unsigned DiagID) {
20035 std::string LHS = LHSValue.toString(Info.Ctx, E->getLHS()->getType());
20036 std::string RHS = RHSValue.toString(Info.Ctx, E->getRHS()->getType());
20037 Info.FFDiag(E, DiagID) << LHS << RHS;
20038 if (LHSExpr && LHSExpr == RHSExpr)
20039 Info.Note(LHSExpr->getExprLoc(),
20040 diag::note_constexpr_repeated_literal_eval)
20041 << LHSExpr->getSourceRange();
20042 return false;
20043 };
20044
20045 if (!LHSExpr || !RHSExpr)
20046 return DiagArith(diag::note_constexpr_pointer_arith_unspecified);
20047
20048 if (ArePotentiallyOverlappingStringLiterals(Info, LHSValue, RHSValue))
20049 return DiagArith(diag::note_constexpr_literal_arith);
20050
20051 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
20052 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
20053 if (!LHSAddrExpr || !RHSAddrExpr)
20054 return Error(E);
20055 // Make sure both labels come from the same function.
20056 if (LHSAddrExpr->getLabel()->getDeclContext() !=
20057 RHSAddrExpr->getLabel()->getDeclContext())
20058 return Error(E);
20059 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
20060 }
20061 CharUnits LHSOffset = LHSValue.getLValueOffset();
20062 CharUnits RHSOffset = RHSValue.getLValueOffset();
20063
20064 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
20065 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
20066
20067 // C++11 [expr.add]p6:
20068 // Unless both pointers point to elements of the same array object, or
20069 // one past the last element of the array object, the behavior is
20070 // undefined.
20071 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
20072 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
20073 RHSDesignator))
20074 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
20075
20076 QualType Type = E->getLHS()->getType();
20077 QualType ElementType = Type->castAs<PointerType>()->getPointeeType();
20078
20079 CharUnits ElementSize;
20080 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
20081 return false;
20082
20083 // As an extension, a type may have zero size (empty struct or union in
20084 // C, array of zero length). Pointer subtraction in such cases has
20085 // undefined behavior, so is not constant.
20086 if (ElementSize.isZero()) {
20087 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
20088 << ElementType;
20089 return false;
20090 }
20091
20092 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
20093 // and produce incorrect results when it overflows. Such behavior
20094 // appears to be non-conforming, but is common, so perhaps we should
20095 // assume the standard intended for such cases to be undefined behavior
20096 // and check for them.
20097
20098 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
20099 // overflow in the final conversion to ptrdiff_t.
20100 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
20101 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
20102 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
20103 false);
20104 APSInt TrueResult = (LHS - RHS) / ElemSize;
20105 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
20106
20107 if (Result.extend(65) != TrueResult &&
20108 !HandleOverflow(Info, E, TrueResult, E->getType()))
20109 return false;
20110 return Success(Result, E);
20111 }
20112
20113 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
20114}
20115
20116/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
20117/// a result as the expression's type.
20118bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
20119 const UnaryExprOrTypeTraitExpr *E) {
20120 switch(E->getKind()) {
20121 case UETT_PreferredAlignOf:
20122 case UETT_AlignOf: {
20123 if (E->isArgumentType())
20124 return Success(
20125 GetAlignOfType(Info.Ctx, E->getArgumentType(), E->getKind()), E);
20126 else
20127 return Success(
20128 GetAlignOfExpr(Info.Ctx, E->getArgumentExpr(), E->getKind()), E);
20129 }
20130
20131 case UETT_PtrAuthTypeDiscriminator: {
20132 if (E->getArgumentType()->isDependentType())
20133 return false;
20134 return Success(
20135 Info.Ctx.getPointerAuthTypeDiscriminator(E->getArgumentType()), E);
20136 }
20137 case UETT_VecStep: {
20138 QualType Ty = E->getTypeOfArgument();
20139
20140 if (Ty->isVectorType()) {
20141 unsigned n = Ty->castAs<VectorType>()->getNumElements();
20142
20143 // The vec_step built-in functions that take a 3-component
20144 // vector return 4. (OpenCL 1.1 spec 6.11.12)
20145 if (n == 3)
20146 n = 4;
20147
20148 return Success(n, E);
20149 } else
20150 return Success(1, E);
20151 }
20152
20153 case UETT_DataSizeOf:
20154 case UETT_SizeOf: {
20155 QualType SrcTy = E->getTypeOfArgument();
20156 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
20157 // the result is the size of the referenced type."
20158 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
20159 SrcTy = Ref->getPointeeType();
20160
20161 CharUnits Sizeof;
20162 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof,
20163 E->getKind() == UETT_DataSizeOf ? SizeOfType::DataSizeOf
20164 : SizeOfType::SizeOf)) {
20165 return false;
20166 }
20167 return Success(Sizeof, E);
20168 }
20169 case UETT_OpenMPRequiredSimdAlign:
20170 assert(E->isArgumentType());
20171 return Success(
20172 Info.Ctx.toCharUnitsFromBits(
20173 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
20174 .getQuantity(),
20175 E);
20176 case UETT_VectorElements: {
20177 QualType Ty = E->getTypeOfArgument();
20178 // If the vector has a fixed size, we can determine the number of elements
20179 // at compile time.
20180 if (const auto *VT = Ty->getAs<VectorType>())
20181 return Success(VT->getNumElements(), E);
20182
20183 assert(Ty->isSizelessVectorType());
20184 if (Info.InConstantContext)
20185 Info.CCEDiag(E, diag::note_constexpr_non_const_vectorelements)
20186 << E->getSourceRange();
20187
20188 return false;
20189 }
20190 case UETT_CountOf: {
20191 QualType Ty = E->getTypeOfArgument();
20192 assert(Ty->isArrayType());
20193
20194 // We don't need to worry about array element qualifiers, so getting the
20195 // unsafe array type is fine.
20196 if (const auto *CAT =
20197 dyn_cast<ConstantArrayType>(Ty->getAsArrayTypeUnsafe())) {
20198 return Success(CAT->getSize(), E);
20199 }
20200
20201 assert(!Ty->isConstantSizeType());
20202
20203 // If it's a variable-length array type, we need to check whether it is a
20204 // multidimensional array. If so, we need to check the size expression of
20205 // the VLA to see if it's a constant size. If so, we can return that value.
20206 const auto *VAT = Info.Ctx.getAsVariableArrayType(Ty);
20207 assert(VAT);
20208 if (VAT->getElementType()->isArrayType()) {
20209 // Variable array size expression could be missing (e.g. int a[*][10]) In
20210 // that case, it can't be a constant expression.
20211 if (!VAT->getSizeExpr()) {
20212 Info.FFDiag(E->getBeginLoc());
20213 return false;
20214 }
20215
20216 std::optional<APSInt> Res =
20217 VAT->getSizeExpr()->getIntegerConstantExpr(Info.Ctx);
20218 if (Res) {
20219 // The resulting value always has type size_t, so we need to make the
20220 // returned APInt have the correct sign and bit-width.
20221 APInt Val{
20222 static_cast<unsigned>(Info.Ctx.getTypeSize(Info.Ctx.getSizeType())),
20223 Res->getZExtValue()};
20224 return Success(Val, E);
20225 }
20226 }
20227
20228 // Definitely a variable-length type, which is not an ICE.
20229 // FIXME: Better diagnostic.
20230 Info.FFDiag(E->getBeginLoc());
20231 return false;
20232 }
20233 }
20234
20235 llvm_unreachable("unknown expr/type trait");
20236}
20237
20238bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
20239 Info.Ctx.recordOffsetOfEvaluation(OOE);
20240 CharUnits Result;
20241 unsigned n = OOE->getNumComponents();
20242 if (n == 0)
20243 return Error(OOE);
20244 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
20245 for (unsigned i = 0; i != n; ++i) {
20246 OffsetOfNode ON = OOE->getComponent(i);
20247 switch (ON.getKind()) {
20248 case OffsetOfNode::Array: {
20249 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
20250 APSInt IdxResult;
20251 if (!EvaluateInteger(Idx, IdxResult, Info))
20252 return false;
20253 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
20254 if (!AT)
20255 return Error(OOE);
20256 CurrentType = AT->getElementType();
20257 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
20258 // Reject negative indices, indices too large to fit in int64_t,
20259 // and overflow in the offset computation.
20260 if (IdxResult.isNegative() || IdxResult.getActiveBits() > 63)
20261 return Error(OOE);
20262 int64_t IdxVal = IdxResult.getExtValue();
20263 int64_t ElemSize = ElementSize.getQuantity();
20264 if (IdxVal != 0 &&
20265 ElemSize > std::numeric_limits<int64_t>::max() / IdxVal)
20266 return Error(OOE, diag::note_constexpr_offsetof_overflow);
20267 int64_t Offset = IdxVal * ElemSize;
20268 if (Result.getQuantity() > std::numeric_limits<int64_t>::max() - Offset)
20269 return Error(OOE, diag::note_constexpr_offsetof_overflow);
20271 break;
20272 }
20273
20274 case OffsetOfNode::Field: {
20275 FieldDecl *MemberDecl = ON.getField();
20276 const auto *RD = CurrentType->getAsRecordDecl();
20277 if (!RD)
20278 return Error(OOE);
20279 if (RD->isInvalidDecl()) return false;
20280 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
20281 unsigned i = MemberDecl->getFieldIndex();
20282 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
20283 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
20284 CurrentType = MemberDecl->getType().getNonReferenceType();
20285 break;
20286 }
20287
20289 llvm_unreachable("dependent __builtin_offsetof");
20290
20291 case OffsetOfNode::Base: {
20292 CXXBaseSpecifier *BaseSpec = ON.getBase();
20293 if (BaseSpec->isVirtual())
20294 return Error(OOE);
20295
20296 // Find the layout of the class whose base we are looking into.
20297 const auto *RD = CurrentType->getAsCXXRecordDecl();
20298 if (!RD)
20299 return Error(OOE);
20300 if (RD->isInvalidDecl()) return false;
20301 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
20302
20303 // Find the base class itself.
20304 CurrentType = BaseSpec->getType();
20305 const auto *BaseRD = CurrentType->getAsCXXRecordDecl();
20306 if (!BaseRD)
20307 return Error(OOE);
20308
20309 // Add the offset to the base.
20310 Result += RL.getBaseClassOffset(BaseRD);
20311 break;
20312 }
20313 }
20314 }
20315 return Success(Result, OOE);
20316}
20317
20318bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
20319 switch (E->getOpcode()) {
20320 default:
20321 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
20322 // See C99 6.6p3.
20323 return Error(E);
20324 case UO_Extension:
20325 // FIXME: Should extension allow i-c-e extension expressions in its scope?
20326 // If so, we could clear the diagnostic ID.
20327 return Visit(E->getSubExpr());
20328 case UO_Plus:
20329 // The result is just the value.
20330 return Visit(E->getSubExpr());
20331 case UO_Minus: {
20332 if (!Visit(E->getSubExpr()))
20333 return false;
20334 if (!Result.isInt()) return Error(E);
20335 const APSInt &Value = Result.getInt();
20336 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
20337 !E->getType().isWrapType()) {
20338 if (Info.checkingForUndefinedBehavior())
20339 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
20340 diag::warn_integer_constant_overflow)
20341 << toString(Value, 10, Value.isSigned(), /*formatAsCLiteral=*/false,
20342 /*UpperCase=*/true, /*InsertSeparators=*/true)
20343 << E->getType() << E->getSourceRange();
20344
20345 if (!HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
20346 E->getType()))
20347 return false;
20348 }
20349 return Success(-Value, E);
20350 }
20351 case UO_Not: {
20352 if (!Visit(E->getSubExpr()))
20353 return false;
20354 if (!Result.isInt()) return Error(E);
20355 return Success(~Result.getInt(), E);
20356 }
20357 case UO_LNot: {
20358 bool bres;
20359 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
20360 return false;
20361 return Success(!bres, E);
20362 }
20363 }
20364}
20365
20366/// HandleCast - This is used to evaluate implicit or explicit casts where the
20367/// result type is integer.
20368bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
20369 const Expr *SubExpr = E->getSubExpr();
20370 QualType DestType = E->getType();
20371 QualType SrcType = SubExpr->getType();
20372
20373 switch (E->getCastKind()) {
20374 case CK_BaseToDerived:
20375 case CK_DerivedToBase:
20376 case CK_UncheckedDerivedToBase:
20377 case CK_Dynamic:
20378 case CK_ToUnion:
20379 case CK_ArrayToPointerDecay:
20380 case CK_FunctionToPointerDecay:
20381 case CK_NullToPointer:
20382 case CK_NullToMemberPointer:
20383 case CK_BaseToDerivedMemberPointer:
20384 case CK_DerivedToBaseMemberPointer:
20385 case CK_ReinterpretMemberPointer:
20386 case CK_ConstructorConversion:
20387 case CK_IntegralToPointer:
20388 case CK_ToVoid:
20389 case CK_VectorSplat:
20390 case CK_IntegralToFloating:
20391 case CK_FloatingCast:
20392 case CK_CPointerToObjCPointerCast:
20393 case CK_BlockPointerToObjCPointerCast:
20394 case CK_AnyPointerToBlockPointerCast:
20395 case CK_ObjCObjectLValueCast:
20396 case CK_FloatingRealToComplex:
20397 case CK_FloatingComplexToReal:
20398 case CK_FloatingComplexCast:
20399 case CK_FloatingComplexToIntegralComplex:
20400 case CK_IntegralRealToComplex:
20401 case CK_IntegralComplexCast:
20402 case CK_IntegralComplexToFloatingComplex:
20403 case CK_BuiltinFnToFnPtr:
20404 case CK_ZeroToOCLOpaqueType:
20405 case CK_NonAtomicToAtomic:
20406 case CK_AddressSpaceConversion:
20407 case CK_IntToOCLSampler:
20408 case CK_FloatingToFixedPoint:
20409 case CK_FixedPointToFloating:
20410 case CK_FixedPointCast:
20411 case CK_IntegralToFixedPoint:
20412 case CK_MatrixCast:
20413 case CK_HLSLAggregateSplatCast:
20414 llvm_unreachable("invalid cast kind for integral value");
20415
20416 case CK_Dependent:
20417 case CK_LValueBitCast:
20418 case CK_ARCProduceObject:
20419 case CK_ARCConsumeObject:
20420 case CK_ARCReclaimReturnedObject:
20421 case CK_ARCExtendBlockObject:
20422 case CK_CopyAndAutoreleaseBlockObject:
20423 return Error(E);
20424
20425 case CK_UserDefinedConversion:
20426 case CK_LValueToRValue:
20427 case CK_AtomicToNonAtomic:
20428 case CK_NoOp:
20429 case CK_LValueToRValueBitCast:
20430 case CK_HLSLArrayRValue:
20431 return ExprEvaluatorBaseTy::VisitCastExpr(E);
20432
20433 case CK_BitCast: {
20434 APValue Src;
20435 if (!Evaluate(Src, Info, SubExpr))
20436 return false;
20437 APValue Dst;
20438 if (!handleRValueToRValueBitCast(Info, Dst, Src, E))
20439 return false;
20440 return Success(Dst, E);
20441 }
20442
20443 case CK_MemberPointerToBoolean:
20444 case CK_PointerToBoolean:
20445 case CK_IntegralToBoolean:
20446 case CK_FloatingToBoolean:
20447 case CK_BooleanToSignedIntegral:
20448 case CK_FloatingComplexToBoolean:
20449 case CK_IntegralComplexToBoolean: {
20450 bool BoolResult;
20451 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
20452 return false;
20453 uint64_t IntResult = BoolResult;
20454 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
20455 IntResult = (uint64_t)-1;
20456 return Success(IntResult, E);
20457 }
20458
20459 case CK_FixedPointToIntegral: {
20460 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
20461 if (!EvaluateFixedPoint(SubExpr, Src, Info))
20462 return false;
20463 bool Overflowed;
20464 llvm::APSInt Result = Src.convertToInt(
20465 Info.Ctx.getIntWidth(DestType),
20466 DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
20467 if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
20468 return false;
20469 return Success(Result, E);
20470 }
20471
20472 case CK_FixedPointToBoolean: {
20473 // Unsigned padding does not affect this.
20474 APValue Val;
20475 if (!Evaluate(Val, Info, SubExpr))
20476 return false;
20477 return Success(Val.getFixedPoint().getBoolValue(), E);
20478 }
20479
20480 case CK_IntegralCast: {
20481 if (!Visit(SubExpr))
20482 return false;
20483
20484 if (!Result.isInt()) {
20485 // Allow casts of address-of-label differences if they are no-ops
20486 // or narrowing, if the result is at least 32 bits wide.
20487 // (The narrowing case isn't actually guaranteed to
20488 // be constant-evaluatable except in some narrow cases which are hard
20489 // to detect here. We let it through on the assumption the user knows
20490 // what they are doing.)
20491 if (Result.isAddrLabelDiff()) {
20492 unsigned DestBits = Info.Ctx.getTypeSize(DestType);
20493 return DestBits >= 32 && DestBits <= Info.Ctx.getTypeSize(SrcType);
20494 }
20495 // Only allow casts of lvalues if they are lossless.
20496 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
20497 }
20498
20499 if (Info.Ctx.getLangOpts().CPlusPlus && DestType->isEnumeralType()) {
20500 const auto *ED = DestType->getAsEnumDecl();
20501 // Check that the value is within the range of the enumeration values.
20502 //
20503 // This corressponds to [expr.static.cast]p10 which says:
20504 // A value of integral or enumeration type can be explicitly converted
20505 // to a complete enumeration type ... If the enumeration type does not
20506 // have a fixed underlying type, the value is unchanged if the original
20507 // value is within the range of the enumeration values ([dcl.enum]), and
20508 // otherwise, the behavior is undefined.
20509 //
20510 // This was resolved as part of DR2338 which has CD5 status.
20511 if (!ED->isFixed()) {
20512 llvm::APInt Min;
20513 llvm::APInt Max;
20514
20515 ED->getValueRange(Max, Min);
20516 --Max;
20517
20518 if (ED->getNumNegativeBits() &&
20519 (Max.slt(Result.getInt().getSExtValue()) ||
20520 Min.sgt(Result.getInt().getSExtValue())))
20521 Info.CCEDiag(E, diag::note_constexpr_unscoped_enum_out_of_range)
20522 << llvm::toString(Result.getInt(), 10) << Min.getSExtValue()
20523 << Max.getSExtValue() << ED;
20524 else if (!ED->getNumNegativeBits() &&
20525 Max.ult(Result.getInt().getZExtValue()))
20526 Info.CCEDiag(E, diag::note_constexpr_unscoped_enum_out_of_range)
20527 << llvm::toString(Result.getInt(), 10) << Min.getZExtValue()
20528 << Max.getZExtValue() << ED;
20529 }
20530 }
20531
20532 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
20533 Result.getInt()), E);
20534 }
20535
20536 case CK_PointerToIntegral: {
20537 CCEDiag(E, diag::note_constexpr_invalid_cast_ptrtoint)
20538 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
20539 << Info.Ctx.getLangOpts().CPlusPlus << E->getSourceRange();
20540
20541 LValue LV;
20542 if (!EvaluatePointer(SubExpr, LV, Info))
20543 return false;
20544
20545 if (LV.getLValueBase()) {
20546 CCEDiag(E, diag::note_constexpr_has_lvalue) << E->getSourceRange();
20547 // Only allow based lvalue casts if they are lossless.
20548 // FIXME: Allow a larger integer size than the pointer size, and allow
20549 // narrowing back down to pointer width in subsequent integral casts.
20550 // FIXME: Check integer type's active bits, not its type size.
20551 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
20552 return Error(E);
20553
20554 LV.Designator.setInvalid();
20555 LV.moveInto(Result);
20556 return true;
20557 }
20558
20559 APSInt AsInt;
20560 APValue V;
20561 LV.moveInto(V);
20562 if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
20563 llvm_unreachable("Can't cast this!");
20564
20565 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
20566 }
20567
20568 case CK_IntegralComplexToReal: {
20569 ComplexValue C;
20570 if (!EvaluateComplex(SubExpr, C, Info))
20571 return false;
20572 return Success(C.getComplexIntReal(), E);
20573 }
20574
20575 case CK_FloatingToIntegral: {
20576 APFloat F(0.0);
20577 if (!EvaluateFloat(SubExpr, F, Info))
20578 return false;
20579
20580 APSInt Value;
20581 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
20582 return false;
20583 return Success(Value, E);
20584 }
20585 case CK_HLSLVectorTruncation: {
20586 APValue Val;
20587 if (!EvaluateVector(SubExpr, Val, Info))
20588 return Error(E);
20589 return Success(Val.getVectorElt(0), E);
20590 }
20591 case CK_HLSLMatrixTruncation: {
20592 APValue Val;
20593 if (!EvaluateMatrix(SubExpr, Val, Info))
20594 return Error(E);
20595 return Success(Val.getMatrixElt(0, 0), E);
20596 }
20597 case CK_HLSLElementwiseCast: {
20598 SmallVector<APValue> SrcVals;
20599 SmallVector<QualType> SrcTypes;
20600
20601 if (!hlslElementwiseCastHelper(Info, SubExpr, DestType, SrcVals, SrcTypes))
20602 return false;
20603
20604 // cast our single element
20605 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
20606 APValue ResultVal;
20607 if (!handleScalarCast(Info, FPO, E, SrcTypes[0], DestType, SrcVals[0],
20608 ResultVal))
20609 return false;
20610 return Success(ResultVal, E);
20611 }
20612 }
20613
20614 llvm_unreachable("unknown cast resulting in integral value");
20615}
20616
20617bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
20618 if (E->getSubExpr()->getType()->isAnyComplexType()) {
20619 ComplexValue LV;
20620 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
20621 return false;
20622 if (!LV.isComplexInt())
20623 return Error(E);
20624 return Success(LV.getComplexIntReal(), E);
20625 }
20626
20627 return Visit(E->getSubExpr());
20628}
20629
20630bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
20631 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
20632 ComplexValue LV;
20633 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
20634 return false;
20635 if (!LV.isComplexInt())
20636 return Error(E);
20637 return Success(LV.getComplexIntImag(), E);
20638 }
20639
20640 VisitIgnoredValue(E->getSubExpr());
20641 return Success(0, E);
20642}
20643
20644bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
20645 return Success(E->getPackLength(), E);
20646}
20647
20648bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
20649 return Success(E->getValue(), E);
20650}
20651
20652bool IntExprEvaluator::VisitConceptSpecializationExpr(
20653 const ConceptSpecializationExpr *E) {
20654 return Success(E->isSatisfied(), E);
20655}
20656
20657bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) {
20658 return Success(E->isSatisfied(), E);
20659}
20660
20661bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
20662 switch (E->getOpcode()) {
20663 default:
20664 // Invalid unary operators
20665 return Error(E);
20666 case UO_Plus:
20667 // The result is just the value.
20668 return Visit(E->getSubExpr());
20669 case UO_Minus: {
20670 if (!Visit(E->getSubExpr())) return false;
20671 if (!Result.isFixedPoint())
20672 return Error(E);
20673 bool Overflowed;
20674 APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
20675 if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
20676 return false;
20677 return Success(Negated, E);
20678 }
20679 case UO_LNot: {
20680 bool bres;
20681 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
20682 return false;
20683 return Success(!bres, E);
20684 }
20685 }
20686}
20687
20688bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
20689 const Expr *SubExpr = E->getSubExpr();
20690 QualType DestType = E->getType();
20691 assert(DestType->isFixedPointType() &&
20692 "Expected destination type to be a fixed point type");
20693 auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
20694
20695 switch (E->getCastKind()) {
20696 case CK_FixedPointCast: {
20697 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
20698 if (!EvaluateFixedPoint(SubExpr, Src, Info))
20699 return false;
20700 bool Overflowed;
20701 APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
20702 if (Overflowed) {
20703 if (Info.checkingForUndefinedBehavior())
20704 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
20705 diag::warn_fixedpoint_constant_overflow)
20706 << Result.toString() << E->getType();
20707 if (!HandleOverflow(Info, E, Result, E->getType()))
20708 return false;
20709 }
20710 return Success(Result, E);
20711 }
20712 case CK_IntegralToFixedPoint: {
20713 APSInt Src;
20714 if (!EvaluateInteger(SubExpr, Src, Info))
20715 return false;
20716
20717 bool Overflowed;
20718 APFixedPoint IntResult = APFixedPoint::getFromIntValue(
20719 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
20720
20721 if (Overflowed) {
20722 if (Info.checkingForUndefinedBehavior())
20723 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
20724 diag::warn_fixedpoint_constant_overflow)
20725 << IntResult.toString() << E->getType();
20726 if (!HandleOverflow(Info, E, IntResult, E->getType()))
20727 return false;
20728 }
20729
20730 return Success(IntResult, E);
20731 }
20732 case CK_FloatingToFixedPoint: {
20733 APFloat Src(0.0);
20734 if (!EvaluateFloat(SubExpr, Src, Info))
20735 return false;
20736
20737 bool Overflowed;
20738 APFixedPoint Result = APFixedPoint::getFromFloatValue(
20739 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
20740
20741 if (Overflowed) {
20742 if (Info.checkingForUndefinedBehavior())
20743 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
20744 diag::warn_fixedpoint_constant_overflow)
20745 << Result.toString() << E->getType();
20746 if (!HandleOverflow(Info, E, Result, E->getType()))
20747 return false;
20748 }
20749
20750 return Success(Result, E);
20751 }
20752 case CK_NoOp:
20753 case CK_LValueToRValue:
20754 return ExprEvaluatorBaseTy::VisitCastExpr(E);
20755 default:
20756 return Error(E);
20757 }
20758}
20759
20760bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
20761 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
20762 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
20763
20764 const Expr *LHS = E->getLHS();
20765 const Expr *RHS = E->getRHS();
20766 FixedPointSemantics ResultFXSema =
20767 Info.Ctx.getFixedPointSemantics(E->getType());
20768
20769 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
20770 if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
20771 return false;
20772 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
20773 if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
20774 return false;
20775
20776 bool OpOverflow = false, ConversionOverflow = false;
20777 APFixedPoint Result(LHSFX.getSemantics());
20778 switch (E->getOpcode()) {
20779 case BO_Add: {
20780 Result = LHSFX.add(RHSFX, &OpOverflow)
20781 .convert(ResultFXSema, &ConversionOverflow);
20782 break;
20783 }
20784 case BO_Sub: {
20785 Result = LHSFX.sub(RHSFX, &OpOverflow)
20786 .convert(ResultFXSema, &ConversionOverflow);
20787 break;
20788 }
20789 case BO_Mul: {
20790 Result = LHSFX.mul(RHSFX, &OpOverflow)
20791 .convert(ResultFXSema, &ConversionOverflow);
20792 break;
20793 }
20794 case BO_Div: {
20795 if (RHSFX.getValue() == 0) {
20796 Info.FFDiag(E, diag::note_expr_divide_by_zero);
20797 return false;
20798 }
20799 Result = LHSFX.div(RHSFX, &OpOverflow)
20800 .convert(ResultFXSema, &ConversionOverflow);
20801 break;
20802 }
20803 case BO_Shl:
20804 case BO_Shr: {
20805 FixedPointSemantics LHSSema = LHSFX.getSemantics();
20806 llvm::APSInt RHSVal = RHSFX.getValue();
20807
20808 unsigned ShiftBW =
20809 LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding();
20810 unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1);
20811 // Embedded-C 4.1.6.2.2:
20812 // The right operand must be nonnegative and less than the total number
20813 // of (nonpadding) bits of the fixed-point operand ...
20814 if (RHSVal.isNegative())
20815 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal;
20816 else if (Amt != RHSVal)
20817 Info.CCEDiag(E, diag::note_constexpr_large_shift)
20818 << RHSVal << E->getType() << ShiftBW;
20819
20820 if (E->getOpcode() == BO_Shl)
20821 Result = LHSFX.shl(Amt, &OpOverflow);
20822 else
20823 Result = LHSFX.shr(Amt, &OpOverflow);
20824 break;
20825 }
20826 default:
20827 return false;
20828 }
20829 if (OpOverflow || ConversionOverflow) {
20830 if (Info.checkingForUndefinedBehavior())
20831 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
20832 diag::warn_fixedpoint_constant_overflow)
20833 << Result.toString() << E->getType();
20834 if (!HandleOverflow(Info, E, Result, E->getType()))
20835 return false;
20836 }
20837 return Success(Result, E);
20838}
20839
20840//===----------------------------------------------------------------------===//
20841// Float Evaluation
20842//===----------------------------------------------------------------------===//
20843
20844namespace {
20845class FloatExprEvaluator
20846 : public ExprEvaluatorBase<FloatExprEvaluator> {
20847 APFloat &Result;
20848public:
20849 FloatExprEvaluator(EvalInfo &info, APFloat &result)
20850 : ExprEvaluatorBaseTy(info), Result(result) {}
20851
20852 bool Success(const APValue &V, const Expr *e) {
20853 Result = V.getFloat();
20854 return true;
20855 }
20856
20857 bool ZeroInitialization(const Expr *E) {
20858 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
20859 return true;
20860 }
20861
20862 bool VisitCallExpr(const CallExpr *E);
20863
20864 bool VisitUnaryOperator(const UnaryOperator *E);
20865 bool VisitBinaryOperator(const BinaryOperator *E);
20866 bool VisitFloatingLiteral(const FloatingLiteral *E);
20867 bool VisitCastExpr(const CastExpr *E);
20868
20869 bool VisitUnaryReal(const UnaryOperator *E);
20870 bool VisitUnaryImag(const UnaryOperator *E);
20871
20872 // FIXME: Missing: array subscript of vector, member of vector
20873};
20874} // end anonymous namespace
20875
20876static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
20877 assert(!E->isValueDependent());
20878 assert(E->isPRValue() && E->getType()->isRealFloatingType());
20879 return FloatExprEvaluator(Info, Result).Visit(E);
20880}
20881
20882static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
20883 QualType ResultTy,
20884 const Expr *Arg,
20885 bool SNaN,
20886 llvm::APFloat &Result) {
20887 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
20888 if (!S || !S->isOrdinary())
20889 return false;
20890
20891 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
20892
20893 llvm::APInt fill;
20894
20895 // Treat empty strings as if they were zero.
20896 if (S->getString().empty())
20897 fill = llvm::APInt(32, 0);
20898 else if (S->getString().getAsInteger(0, fill))
20899 return false;
20900
20901 if (Context.getTargetInfo().isNan2008()) {
20902 if (SNaN)
20903 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
20904 else
20905 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
20906 } else {
20907 // Prior to IEEE 754-2008, architectures were allowed to choose whether
20908 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
20909 // a different encoding to what became a standard in 2008, and for pre-
20910 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
20911 // sNaN. This is now known as "legacy NaN" encoding.
20912 if (SNaN)
20913 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
20914 else
20915 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
20916 }
20917
20918 return true;
20919}
20920
20921bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
20922 if (!IsConstantEvaluatedBuiltinCall(E))
20923 return ExprEvaluatorBaseTy::VisitCallExpr(E);
20924
20925 unsigned BuiltinOp = ConvertBuiltinIDToX86BuiltinID(Info.Ctx, E);
20926
20927 switch (BuiltinOp) {
20928 default:
20929 return false;
20930
20931 case Builtin::BI__builtin_huge_val:
20932 case Builtin::BI__builtin_huge_valf:
20933 case Builtin::BI__builtin_huge_vall:
20934 case Builtin::BI__builtin_huge_valf16:
20935 case Builtin::BI__builtin_huge_valf128:
20936 case Builtin::BI__builtin_inf:
20937 case Builtin::BI__builtin_inff:
20938 case Builtin::BI__builtin_infl:
20939 case Builtin::BI__builtin_inff16:
20940 case Builtin::BI__builtin_inff128: {
20941 const llvm::fltSemantics &Sem =
20942 Info.Ctx.getFloatTypeSemantics(E->getType());
20943 Result = llvm::APFloat::getInf(Sem);
20944 return true;
20945 }
20946
20947 case Builtin::BI__builtin_nans:
20948 case Builtin::BI__builtin_nansf:
20949 case Builtin::BI__builtin_nansl:
20950 case Builtin::BI__builtin_nansf16:
20951 case Builtin::BI__builtin_nansf128:
20952 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
20953 true, Result))
20954 return Error(E);
20955 return true;
20956
20957 case Builtin::BI__builtin_nan:
20958 case Builtin::BI__builtin_nanf:
20959 case Builtin::BI__builtin_nanl:
20960 case Builtin::BI__builtin_nanf16:
20961 case Builtin::BI__builtin_nanf128:
20962 // If this is __builtin_nan() turn this into a nan, otherwise we
20963 // can't constant fold it.
20964 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
20965 false, Result))
20966 return Error(E);
20967 return true;
20968
20969 case Builtin::BI__builtin_elementwise_abs:
20970 case Builtin::BI__builtin_fabs:
20971 case Builtin::BI__builtin_fabsf:
20972 case Builtin::BI__builtin_fabsl:
20973 case Builtin::BI__builtin_fabsf128:
20974 // The C standard says "fabs raises no floating-point exceptions,
20975 // even if x is a signaling NaN. The returned value is independent of
20976 // the current rounding direction mode." Therefore constant folding can
20977 // proceed without regard to the floating point settings.
20978 // Reference, WG14 N2478 F.10.4.3
20979 if (!EvaluateFloat(E->getArg(0), Result, Info))
20980 return false;
20981
20982 if (Result.isNegative())
20983 Result.changeSign();
20984 return true;
20985
20986 case Builtin::BI__arithmetic_fence:
20987 return EvaluateFloat(E->getArg(0), Result, Info);
20988
20989 // FIXME: Builtin::BI__builtin_powi
20990 // FIXME: Builtin::BI__builtin_powif
20991 // FIXME: Builtin::BI__builtin_powil
20992
20993 case Builtin::BI__builtin_copysign:
20994 case Builtin::BI__builtin_copysignf:
20995 case Builtin::BI__builtin_copysignl:
20996 case Builtin::BI__builtin_copysignf128: {
20997 APFloat RHS(0.);
20998 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
20999 !EvaluateFloat(E->getArg(1), RHS, Info))
21000 return false;
21001 Result.copySign(RHS);
21002 return true;
21003 }
21004
21005 case Builtin::BI__builtin_fmax:
21006 case Builtin::BI__builtin_fmaxf:
21007 case Builtin::BI__builtin_fmaxl:
21008 case Builtin::BI__builtin_fmaxf16:
21009 case Builtin::BI__builtin_fmaxf128: {
21010 APFloat RHS(0.);
21011 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
21012 !EvaluateFloat(E->getArg(1), RHS, Info))
21013 return false;
21014 Result = maxnum(Result, RHS);
21015 return true;
21016 }
21017
21018 case Builtin::BI__builtin_fmin:
21019 case Builtin::BI__builtin_fminf:
21020 case Builtin::BI__builtin_fminl:
21021 case Builtin::BI__builtin_fminf16:
21022 case Builtin::BI__builtin_fminf128: {
21023 APFloat RHS(0.);
21024 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
21025 !EvaluateFloat(E->getArg(1), RHS, Info))
21026 return false;
21027 Result = minnum(Result, RHS);
21028 return true;
21029 }
21030
21031 case Builtin::BI__builtin_fmaximum_num:
21032 case Builtin::BI__builtin_fmaximum_numf:
21033 case Builtin::BI__builtin_fmaximum_numl:
21034 case Builtin::BI__builtin_fmaximum_numf16:
21035 case Builtin::BI__builtin_fmaximum_numf128: {
21036 APFloat RHS(0.);
21037 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
21038 !EvaluateFloat(E->getArg(1), RHS, Info))
21039 return false;
21040 Result = maximumnum(Result, RHS);
21041 return true;
21042 }
21043
21044 case Builtin::BI__builtin_fminimum_num:
21045 case Builtin::BI__builtin_fminimum_numf:
21046 case Builtin::BI__builtin_fminimum_numl:
21047 case Builtin::BI__builtin_fminimum_numf16:
21048 case Builtin::BI__builtin_fminimum_numf128: {
21049 APFloat RHS(0.);
21050 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
21051 !EvaluateFloat(E->getArg(1), RHS, Info))
21052 return false;
21053 Result = minimumnum(Result, RHS);
21054 return true;
21055 }
21056
21057 case Builtin::BI__builtin_elementwise_fma: {
21058 if (!E->getArg(0)->isPRValue() || !E->getArg(1)->isPRValue() ||
21059 !E->getArg(2)->isPRValue()) {
21060 return false;
21061 }
21062 APFloat SourceY(0.), SourceZ(0.);
21063 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
21064 !EvaluateFloat(E->getArg(1), SourceY, Info) ||
21065 !EvaluateFloat(E->getArg(2), SourceZ, Info))
21066 return false;
21067 llvm::RoundingMode RM = getActiveRoundingMode(getEvalInfo(), E);
21068 (void)Result.fusedMultiplyAdd(SourceY, SourceZ, RM);
21069 return true;
21070 }
21071
21072 case clang::X86::BI__builtin_ia32_vec_ext_v4sf: {
21073 APValue Vec;
21074 APSInt IdxAPS;
21075 if (!EvaluateVector(E->getArg(0), Vec, Info) ||
21076 !EvaluateInteger(E->getArg(1), IdxAPS, Info))
21077 return false;
21078 unsigned N = Vec.getVectorLength();
21079 unsigned Idx = static_cast<unsigned>(IdxAPS.getZExtValue() & (N - 1));
21080 return Success(Vec.getVectorElt(Idx), E);
21081 }
21082 }
21083}
21084
21085bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
21086 if (E->getSubExpr()->getType()->isAnyComplexType()) {
21087 ComplexValue CV;
21088 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
21089 return false;
21090 Result = CV.FloatReal;
21091 return true;
21092 }
21093
21094 return Visit(E->getSubExpr());
21095}
21096
21097bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
21098 if (E->getSubExpr()->getType()->isAnyComplexType()) {
21099 ComplexValue CV;
21100 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
21101 return false;
21102 Result = CV.FloatImag;
21103 return true;
21104 }
21105
21106 VisitIgnoredValue(E->getSubExpr());
21107 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
21108 Result = llvm::APFloat::getZero(Sem);
21109 return true;
21110}
21111
21112bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
21113 switch (E->getOpcode()) {
21114 default: return Error(E);
21115 case UO_Plus:
21116 return EvaluateFloat(E->getSubExpr(), Result, Info);
21117 case UO_Minus:
21118 // In C standard, WG14 N2478 F.3 p4
21119 // "the unary - raises no floating point exceptions,
21120 // even if the operand is signalling."
21121 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
21122 return false;
21123 Result.changeSign();
21124 return true;
21125 }
21126}
21127
21128bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
21129 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
21130 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
21131
21132 APFloat RHS(0.0);
21133 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
21134 if (!LHSOK && !Info.noteFailure())
21135 return false;
21136 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
21137 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
21138}
21139
21140bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
21141 Result = E->getValue();
21142 return true;
21143}
21144
21145bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
21146 const Expr* SubExpr = E->getSubExpr();
21147
21148 switch (E->getCastKind()) {
21149 default:
21150 return ExprEvaluatorBaseTy::VisitCastExpr(E);
21151
21152 case CK_HLSLAggregateSplatCast:
21153 llvm_unreachable("invalid cast kind for floating value");
21154
21155 case CK_IntegralToFloating: {
21156 APSInt IntResult;
21157 const FPOptions FPO = E->getFPFeaturesInEffect(
21158 Info.Ctx.getLangOpts());
21159 return EvaluateInteger(SubExpr, IntResult, Info) &&
21160 HandleIntToFloatCast(Info, E, FPO, SubExpr->getType(),
21161 IntResult, E->getType(), Result);
21162 }
21163
21164 case CK_FixedPointToFloating: {
21165 APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
21166 if (!EvaluateFixedPoint(SubExpr, FixResult, Info))
21167 return false;
21168 Result =
21169 FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->getType()));
21170 return true;
21171 }
21172
21173 case CK_FloatingCast: {
21174 if (!Visit(SubExpr))
21175 return false;
21176 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
21177 Result);
21178 }
21179
21180 case CK_FloatingComplexToReal: {
21181 ComplexValue V;
21182 if (!EvaluateComplex(SubExpr, V, Info))
21183 return false;
21184 Result = V.getComplexFloatReal();
21185 return true;
21186 }
21187 case CK_HLSLVectorTruncation: {
21188 APValue Val;
21189 if (!EvaluateVector(SubExpr, Val, Info))
21190 return Error(E);
21191 return Success(Val.getVectorElt(0), E);
21192 }
21193 case CK_HLSLMatrixTruncation: {
21194 APValue Val;
21195 if (!EvaluateMatrix(SubExpr, Val, Info))
21196 return Error(E);
21197 return Success(Val.getMatrixElt(0, 0), E);
21198 }
21199 case CK_HLSLElementwiseCast: {
21200 SmallVector<APValue> SrcVals;
21201 SmallVector<QualType> SrcTypes;
21202
21203 if (!hlslElementwiseCastHelper(Info, SubExpr, E->getType(), SrcVals,
21204 SrcTypes))
21205 return false;
21206
21207 // Cast our single element.
21208 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
21209 APValue ResultVal;
21210 if (!handleScalarCast(Info, FPO, E, SrcTypes[0], E->getType(), SrcVals[0],
21211 ResultVal))
21212 return false;
21213 return Success(ResultVal, E);
21214 }
21215 }
21216}
21217
21218//===----------------------------------------------------------------------===//
21219// Complex Evaluation (for float and integer)
21220//===----------------------------------------------------------------------===//
21221
21222namespace {
21223class ComplexExprEvaluator
21224 : public ExprEvaluatorBase<ComplexExprEvaluator> {
21225 ComplexValue &Result;
21226
21227public:
21228 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
21229 : ExprEvaluatorBaseTy(info), Result(Result) {}
21230
21231 bool Success(const APValue &V, const Expr *e) {
21232 Result.setFrom(V);
21233 return true;
21234 }
21235
21236 bool ZeroInitialization(const Expr *E);
21237
21238 //===--------------------------------------------------------------------===//
21239 // Visitor Methods
21240 //===--------------------------------------------------------------------===//
21241
21242 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
21243 bool VisitCastExpr(const CastExpr *E);
21244 bool VisitBinaryOperator(const BinaryOperator *E);
21245 bool VisitUnaryOperator(const UnaryOperator *E);
21246 bool VisitInitListExpr(const InitListExpr *E);
21247 bool VisitCallExpr(const CallExpr *E);
21248};
21249} // end anonymous namespace
21250
21251static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
21252 EvalInfo &Info) {
21253 assert(!E->isValueDependent());
21254 assert(E->isPRValue() && E->getType()->isAnyComplexType());
21255 return ComplexExprEvaluator(Info, Result).Visit(E);
21256}
21257
21258bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
21259 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
21260 if (ElemTy->isRealFloatingType()) {
21261 Result.makeComplexFloat();
21262 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
21263 Result.FloatReal = Zero;
21264 Result.FloatImag = Zero;
21265 } else {
21266 Result.makeComplexInt();
21267 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
21268 Result.IntReal = Zero;
21269 Result.IntImag = Zero;
21270 }
21271 return true;
21272}
21273
21274bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
21275 const Expr* SubExpr = E->getSubExpr();
21276
21277 if (SubExpr->getType()->isRealFloatingType()) {
21278 Result.makeComplexFloat();
21279 APFloat &Imag = Result.FloatImag;
21280 if (!EvaluateFloat(SubExpr, Imag, Info))
21281 return false;
21282
21283 Result.FloatReal = APFloat(Imag.getSemantics());
21284 return true;
21285 } else {
21286 assert(SubExpr->getType()->isIntegerType() &&
21287 "Unexpected imaginary literal.");
21288
21289 Result.makeComplexInt();
21290 APSInt &Imag = Result.IntImag;
21291 if (!EvaluateInteger(SubExpr, Imag, Info))
21292 return false;
21293
21294 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
21295 return true;
21296 }
21297}
21298
21299bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
21300
21301 switch (E->getCastKind()) {
21302 case CK_BitCast:
21303 case CK_BaseToDerived:
21304 case CK_DerivedToBase:
21305 case CK_UncheckedDerivedToBase:
21306 case CK_Dynamic:
21307 case CK_ToUnion:
21308 case CK_ArrayToPointerDecay:
21309 case CK_FunctionToPointerDecay:
21310 case CK_NullToPointer:
21311 case CK_NullToMemberPointer:
21312 case CK_BaseToDerivedMemberPointer:
21313 case CK_DerivedToBaseMemberPointer:
21314 case CK_MemberPointerToBoolean:
21315 case CK_ReinterpretMemberPointer:
21316 case CK_ConstructorConversion:
21317 case CK_IntegralToPointer:
21318 case CK_PointerToIntegral:
21319 case CK_PointerToBoolean:
21320 case CK_ToVoid:
21321 case CK_VectorSplat:
21322 case CK_IntegralCast:
21323 case CK_BooleanToSignedIntegral:
21324 case CK_IntegralToBoolean:
21325 case CK_IntegralToFloating:
21326 case CK_FloatingToIntegral:
21327 case CK_FloatingToBoolean:
21328 case CK_FloatingCast:
21329 case CK_CPointerToObjCPointerCast:
21330 case CK_BlockPointerToObjCPointerCast:
21331 case CK_AnyPointerToBlockPointerCast:
21332 case CK_ObjCObjectLValueCast:
21333 case CK_FloatingComplexToReal:
21334 case CK_FloatingComplexToBoolean:
21335 case CK_IntegralComplexToReal:
21336 case CK_IntegralComplexToBoolean:
21337 case CK_ARCProduceObject:
21338 case CK_ARCConsumeObject:
21339 case CK_ARCReclaimReturnedObject:
21340 case CK_ARCExtendBlockObject:
21341 case CK_CopyAndAutoreleaseBlockObject:
21342 case CK_BuiltinFnToFnPtr:
21343 case CK_ZeroToOCLOpaqueType:
21344 case CK_NonAtomicToAtomic:
21345 case CK_AddressSpaceConversion:
21346 case CK_IntToOCLSampler:
21347 case CK_FloatingToFixedPoint:
21348 case CK_FixedPointToFloating:
21349 case CK_FixedPointCast:
21350 case CK_FixedPointToBoolean:
21351 case CK_FixedPointToIntegral:
21352 case CK_IntegralToFixedPoint:
21353 case CK_MatrixCast:
21354 case CK_HLSLVectorTruncation:
21355 case CK_HLSLMatrixTruncation:
21356 case CK_HLSLElementwiseCast:
21357 case CK_HLSLAggregateSplatCast:
21358 llvm_unreachable("invalid cast kind for complex value");
21359
21360 case CK_LValueToRValue:
21361 case CK_AtomicToNonAtomic:
21362 case CK_NoOp:
21363 case CK_LValueToRValueBitCast:
21364 case CK_HLSLArrayRValue:
21365 return ExprEvaluatorBaseTy::VisitCastExpr(E);
21366
21367 case CK_Dependent:
21368 case CK_LValueBitCast:
21369 case CK_UserDefinedConversion:
21370 return Error(E);
21371
21372 case CK_FloatingRealToComplex: {
21373 APFloat &Real = Result.FloatReal;
21374 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
21375 return false;
21376
21377 Result.makeComplexFloat();
21378 Result.FloatImag = APFloat(Real.getSemantics());
21379 return true;
21380 }
21381
21382 case CK_FloatingComplexCast: {
21383 if (!Visit(E->getSubExpr()))
21384 return false;
21385
21386 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
21387 QualType From
21388 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
21389
21390 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
21391 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
21392 }
21393
21394 case CK_FloatingComplexToIntegralComplex: {
21395 if (!Visit(E->getSubExpr()))
21396 return false;
21397
21398 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
21399 QualType From
21400 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
21401 Result.makeComplexInt();
21402 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
21403 To, Result.IntReal) &&
21404 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
21405 To, Result.IntImag);
21406 }
21407
21408 case CK_IntegralRealToComplex: {
21409 APSInt &Real = Result.IntReal;
21410 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
21411 return false;
21412
21413 Result.makeComplexInt();
21414 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
21415 return true;
21416 }
21417
21418 case CK_IntegralComplexCast: {
21419 if (!Visit(E->getSubExpr()))
21420 return false;
21421
21422 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
21423 QualType From
21424 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
21425
21426 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
21427 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
21428 return true;
21429 }
21430
21431 case CK_IntegralComplexToFloatingComplex: {
21432 if (!Visit(E->getSubExpr()))
21433 return false;
21434
21435 const FPOptions FPO = E->getFPFeaturesInEffect(
21436 Info.Ctx.getLangOpts());
21437 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
21438 QualType From
21439 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
21440 Result.makeComplexFloat();
21441 return HandleIntToFloatCast(Info, E, FPO, From, Result.IntReal,
21442 To, Result.FloatReal) &&
21443 HandleIntToFloatCast(Info, E, FPO, From, Result.IntImag,
21444 To, Result.FloatImag);
21445 }
21446 }
21447
21448 llvm_unreachable("unknown cast resulting in complex value");
21449}
21450
21452 // Lookup Table for Multiplicative Inverse in GF(2^8)
21453 const uint8_t GFInv[256] = {
21454 0x00, 0x01, 0x8d, 0xf6, 0xcb, 0x52, 0x7b, 0xd1, 0xe8, 0x4f, 0x29, 0xc0,
21455 0xb0, 0xe1, 0xe5, 0xc7, 0x74, 0xb4, 0xaa, 0x4b, 0x99, 0x2b, 0x60, 0x5f,
21456 0x58, 0x3f, 0xfd, 0xcc, 0xff, 0x40, 0xee, 0xb2, 0x3a, 0x6e, 0x5a, 0xf1,
21457 0x55, 0x4d, 0xa8, 0xc9, 0xc1, 0x0a, 0x98, 0x15, 0x30, 0x44, 0xa2, 0xc2,
21458 0x2c, 0x45, 0x92, 0x6c, 0xf3, 0x39, 0x66, 0x42, 0xf2, 0x35, 0x20, 0x6f,
21459 0x77, 0xbb, 0x59, 0x19, 0x1d, 0xfe, 0x37, 0x67, 0x2d, 0x31, 0xf5, 0x69,
21460 0xa7, 0x64, 0xab, 0x13, 0x54, 0x25, 0xe9, 0x09, 0xed, 0x5c, 0x05, 0xca,
21461 0x4c, 0x24, 0x87, 0xbf, 0x18, 0x3e, 0x22, 0xf0, 0x51, 0xec, 0x61, 0x17,
21462 0x16, 0x5e, 0xaf, 0xd3, 0x49, 0xa6, 0x36, 0x43, 0xf4, 0x47, 0x91, 0xdf,
21463 0x33, 0x93, 0x21, 0x3b, 0x79, 0xb7, 0x97, 0x85, 0x10, 0xb5, 0xba, 0x3c,
21464 0xb6, 0x70, 0xd0, 0x06, 0xa1, 0xfa, 0x81, 0x82, 0x83, 0x7e, 0x7f, 0x80,
21465 0x96, 0x73, 0xbe, 0x56, 0x9b, 0x9e, 0x95, 0xd9, 0xf7, 0x02, 0xb9, 0xa4,
21466 0xde, 0x6a, 0x32, 0x6d, 0xd8, 0x8a, 0x84, 0x72, 0x2a, 0x14, 0x9f, 0x88,
21467 0xf9, 0xdc, 0x89, 0x9a, 0xfb, 0x7c, 0x2e, 0xc3, 0x8f, 0xb8, 0x65, 0x48,
21468 0x26, 0xc8, 0x12, 0x4a, 0xce, 0xe7, 0xd2, 0x62, 0x0c, 0xe0, 0x1f, 0xef,
21469 0x11, 0x75, 0x78, 0x71, 0xa5, 0x8e, 0x76, 0x3d, 0xbd, 0xbc, 0x86, 0x57,
21470 0x0b, 0x28, 0x2f, 0xa3, 0xda, 0xd4, 0xe4, 0x0f, 0xa9, 0x27, 0x53, 0x04,
21471 0x1b, 0xfc, 0xac, 0xe6, 0x7a, 0x07, 0xae, 0x63, 0xc5, 0xdb, 0xe2, 0xea,
21472 0x94, 0x8b, 0xc4, 0xd5, 0x9d, 0xf8, 0x90, 0x6b, 0xb1, 0x0d, 0xd6, 0xeb,
21473 0xc6, 0x0e, 0xcf, 0xad, 0x08, 0x4e, 0xd7, 0xe3, 0x5d, 0x50, 0x1e, 0xb3,
21474 0x5b, 0x23, 0x38, 0x34, 0x68, 0x46, 0x03, 0x8c, 0xdd, 0x9c, 0x7d, 0xa0,
21475 0xcd, 0x1a, 0x41, 0x1c};
21476
21477 return GFInv[Byte];
21478}
21479
21480uint8_t GFNIAffine(uint8_t XByte, const APInt &AQword, const APSInt &Imm,
21481 bool Inverse) {
21482 unsigned NumBitsInByte = 8;
21483 // Computing the affine transformation
21484 uint8_t RetByte = 0;
21485 for (uint32_t BitIdx = 0; BitIdx != NumBitsInByte; ++BitIdx) {
21486 uint8_t AByte =
21487 AQword.lshr((7 - static_cast<int32_t>(BitIdx)) * NumBitsInByte)
21488 .getLoBits(8)
21489 .getZExtValue();
21490 uint8_t Product;
21491 if (Inverse) {
21492 Product = AByte & GFNIMultiplicativeInverse(XByte);
21493 } else {
21494 Product = AByte & XByte;
21495 }
21496 uint8_t Parity = 0;
21497
21498 // Dot product in GF(2) uses XOR instead of addition
21499 for (unsigned PBitIdx = 0; PBitIdx != NumBitsInByte; ++PBitIdx) {
21500 Parity = Parity ^ ((Product >> PBitIdx) & 0x1);
21501 }
21502
21503 uint8_t Temp = Imm[BitIdx] ? 1 : 0;
21504 RetByte |= (Temp ^ Parity) << BitIdx;
21505 }
21506 return RetByte;
21507}
21508
21510 // Multiplying two polynomials of degree 7
21511 // Polynomial of degree 7
21512 // x^7 + x^6 + x^5 + x^4 + x^3 + x^2 + x + 1
21513 uint16_t TWord = 0;
21514 unsigned NumBitsInByte = 8;
21515 for (unsigned BitIdx = 0; BitIdx != NumBitsInByte; ++BitIdx) {
21516 if ((BByte >> BitIdx) & 0x1) {
21517 TWord = TWord ^ (AByte << BitIdx);
21518 }
21519 }
21520
21521 // When multiplying two polynomials of degree 7
21522 // results in a polynomial of degree 14
21523 // so the result has to be reduced to 7
21524 // Reduction polynomial is x^8 + x^4 + x^3 + x + 1 i.e. 0x11B
21525 for (int32_t BitIdx = 14; BitIdx > 7; --BitIdx) {
21526 if ((TWord >> BitIdx) & 0x1) {
21527 TWord = TWord ^ (0x11B << (BitIdx - 8));
21528 }
21529 }
21530 return (TWord & 0xFF);
21531}
21532
21533void HandleComplexComplexMul(APFloat A, APFloat B, APFloat C, APFloat D,
21534 APFloat &ResR, APFloat &ResI) {
21535 // This is an implementation of complex multiplication according to the
21536 // constraints laid out in C11 Annex G. The implementation uses the
21537 // following naming scheme:
21538 // (a + ib) * (c + id)
21539
21540 APFloat AC = A * C;
21541 APFloat BD = B * D;
21542 APFloat AD = A * D;
21543 APFloat BC = B * C;
21544 ResR = AC - BD;
21545 ResI = AD + BC;
21546 if (ResR.isNaN() && ResI.isNaN()) {
21547 bool Recalc = false;
21548 if (A.isInfinity() || B.isInfinity()) {
21549 A = APFloat::copySign(APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0),
21550 A);
21551 B = APFloat::copySign(APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0),
21552 B);
21553 if (C.isNaN())
21554 C = APFloat::copySign(APFloat(C.getSemantics()), C);
21555 if (D.isNaN())
21556 D = APFloat::copySign(APFloat(D.getSemantics()), D);
21557 Recalc = true;
21558 }
21559 if (C.isInfinity() || D.isInfinity()) {
21560 C = APFloat::copySign(APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0),
21561 C);
21562 D = APFloat::copySign(APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0),
21563 D);
21564 if (A.isNaN())
21565 A = APFloat::copySign(APFloat(A.getSemantics()), A);
21566 if (B.isNaN())
21567 B = APFloat::copySign(APFloat(B.getSemantics()), B);
21568 Recalc = true;
21569 }
21570 if (!Recalc && (AC.isInfinity() || BD.isInfinity() || AD.isInfinity() ||
21571 BC.isInfinity())) {
21572 if (A.isNaN())
21573 A = APFloat::copySign(APFloat(A.getSemantics()), A);
21574 if (B.isNaN())
21575 B = APFloat::copySign(APFloat(B.getSemantics()), B);
21576 if (C.isNaN())
21577 C = APFloat::copySign(APFloat(C.getSemantics()), C);
21578 if (D.isNaN())
21579 D = APFloat::copySign(APFloat(D.getSemantics()), D);
21580 Recalc = true;
21581 }
21582 if (Recalc) {
21583 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
21584 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
21585 }
21586 }
21587}
21588
21589void HandleComplexComplexDiv(APFloat A, APFloat B, APFloat C, APFloat D,
21590 APFloat &ResR, APFloat &ResI) {
21591 // This is an implementation of complex division according to the
21592 // constraints laid out in C11 Annex G. The implementation uses the
21593 // following naming scheme:
21594 // (a + ib) / (c + id)
21595
21596 int DenomLogB = 0;
21597 APFloat MaxCD = maxnum(abs(C), abs(D));
21598 if (MaxCD.isFinite()) {
21599 DenomLogB = ilogb(MaxCD);
21600 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
21601 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
21602 }
21603 APFloat Denom = C * C + D * D;
21604 ResR =
21605 scalbn((A * C + B * D) / Denom, -DenomLogB, APFloat::rmNearestTiesToEven);
21606 ResI =
21607 scalbn((B * C - A * D) / Denom, -DenomLogB, APFloat::rmNearestTiesToEven);
21608 if (ResR.isNaN() && ResI.isNaN()) {
21609 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
21610 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
21611 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
21612 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
21613 D.isFinite()) {
21614 A = APFloat::copySign(APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0),
21615 A);
21616 B = APFloat::copySign(APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0),
21617 B);
21618 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
21619 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
21620 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
21621 C = APFloat::copySign(APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0),
21622 C);
21623 D = APFloat::copySign(APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0),
21624 D);
21625 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
21626 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
21627 }
21628 }
21629}
21630
21632 // Normalize shift amount to [0, BitWidth) range to match runtime behavior
21633 APSInt NormAmt = Amount;
21634 unsigned BitWidth = Value.getBitWidth();
21635 unsigned AmtBitWidth = NormAmt.getBitWidth();
21636 if (BitWidth == 1) {
21637 // Rotating a 1-bit value is always a no-op
21638 NormAmt = APSInt(APInt(AmtBitWidth, 0), NormAmt.isUnsigned());
21639 } else if (BitWidth == 2) {
21640 // For 2-bit values: rotation amount is 0 or 1 based on
21641 // whether the amount is even or odd. We can't use srem here because
21642 // the divisor (2) would be misinterpreted as -2 in 2-bit signed arithmetic.
21643 NormAmt =
21644 APSInt(APInt(AmtBitWidth, NormAmt[0] ? 1 : 0), NormAmt.isUnsigned());
21645 } else {
21646 APInt Divisor;
21647 if (AmtBitWidth > BitWidth) {
21648 Divisor = llvm::APInt(AmtBitWidth, BitWidth);
21649 } else {
21650 Divisor = llvm::APInt(BitWidth, BitWidth);
21651 if (AmtBitWidth < BitWidth) {
21652 NormAmt = NormAmt.extend(BitWidth);
21653 }
21654 }
21655
21656 // Normalize to [0, BitWidth)
21657 if (NormAmt.isSigned()) {
21658 NormAmt = APSInt(NormAmt.srem(Divisor), /*isUnsigned=*/false);
21659 if (NormAmt.isNegative()) {
21660 APSInt SignedDivisor(Divisor, /*isUnsigned=*/false);
21661 NormAmt += SignedDivisor;
21662 }
21663 } else {
21664 NormAmt = APSInt(NormAmt.urem(Divisor), /*isUnsigned=*/true);
21665 }
21666 }
21667
21668 return NormAmt;
21669}
21670
21671bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
21672 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
21673 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
21674
21675 // Track whether the LHS or RHS is real at the type system level. When this is
21676 // the case we can simplify our evaluation strategy.
21677 bool LHSReal = false, RHSReal = false;
21678
21679 bool LHSOK;
21680 if (E->getLHS()->getType()->isRealFloatingType()) {
21681 LHSReal = true;
21682 APFloat &Real = Result.FloatReal;
21683 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
21684 if (LHSOK) {
21685 Result.makeComplexFloat();
21686 Result.FloatImag = APFloat(Real.getSemantics());
21687 }
21688 } else {
21689 LHSOK = Visit(E->getLHS());
21690 }
21691 if (!LHSOK && !Info.noteFailure())
21692 return false;
21693
21694 ComplexValue RHS;
21695 if (E->getRHS()->getType()->isRealFloatingType()) {
21696 RHSReal = true;
21697 APFloat &Real = RHS.FloatReal;
21698 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
21699 return false;
21700 RHS.makeComplexFloat();
21701 RHS.FloatImag = APFloat(Real.getSemantics());
21702 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
21703 return false;
21704
21705 assert(!(LHSReal && RHSReal) &&
21706 "Cannot have both operands of a complex operation be real.");
21707 switch (E->getOpcode()) {
21708 default: return Error(E);
21709 case BO_Add:
21710 if (Result.isComplexFloat()) {
21711 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
21712 APFloat::rmNearestTiesToEven);
21713 if (LHSReal)
21714 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
21715 else if (!RHSReal)
21716 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
21717 APFloat::rmNearestTiesToEven);
21718 } else {
21719 Result.getComplexIntReal() += RHS.getComplexIntReal();
21720 Result.getComplexIntImag() += RHS.getComplexIntImag();
21721 }
21722 break;
21723 case BO_Sub:
21724 if (Result.isComplexFloat()) {
21725 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
21726 APFloat::rmNearestTiesToEven);
21727 if (LHSReal) {
21728 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
21729 Result.getComplexFloatImag().changeSign();
21730 } else if (!RHSReal) {
21731 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
21732 APFloat::rmNearestTiesToEven);
21733 }
21734 } else {
21735 Result.getComplexIntReal() -= RHS.getComplexIntReal();
21736 Result.getComplexIntImag() -= RHS.getComplexIntImag();
21737 }
21738 break;
21739 case BO_Mul:
21740 if (Result.isComplexFloat()) {
21741 // This is an implementation of complex multiplication according to the
21742 // constraints laid out in C11 Annex G. The implementation uses the
21743 // following naming scheme:
21744 // (a + ib) * (c + id)
21745 ComplexValue LHS = Result;
21746 APFloat &A = LHS.getComplexFloatReal();
21747 APFloat &B = LHS.getComplexFloatImag();
21748 APFloat &C = RHS.getComplexFloatReal();
21749 APFloat &D = RHS.getComplexFloatImag();
21750 APFloat &ResR = Result.getComplexFloatReal();
21751 APFloat &ResI = Result.getComplexFloatImag();
21752 if (LHSReal) {
21753 assert(!RHSReal && "Cannot have two real operands for a complex op!");
21754 ResR = A;
21755 ResI = A;
21756 // ResR = A * C;
21757 // ResI = A * D;
21758 if (!handleFloatFloatBinOp(Info, E, ResR, BO_Mul, C) ||
21759 !handleFloatFloatBinOp(Info, E, ResI, BO_Mul, D))
21760 return false;
21761 } else if (RHSReal) {
21762 // ResR = C * A;
21763 // ResI = C * B;
21764 ResR = C;
21765 ResI = C;
21766 if (!handleFloatFloatBinOp(Info, E, ResR, BO_Mul, A) ||
21767 !handleFloatFloatBinOp(Info, E, ResI, BO_Mul, B))
21768 return false;
21769 } else {
21770 HandleComplexComplexMul(A, B, C, D, ResR, ResI);
21771 }
21772 } else {
21773 ComplexValue LHS = Result;
21774 Result.getComplexIntReal() =
21775 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
21776 LHS.getComplexIntImag() * RHS.getComplexIntImag());
21777 Result.getComplexIntImag() =
21778 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
21779 LHS.getComplexIntImag() * RHS.getComplexIntReal());
21780 }
21781 break;
21782 case BO_Div:
21783 if (Result.isComplexFloat()) {
21784 // This is an implementation of complex division according to the
21785 // constraints laid out in C11 Annex G. The implementation uses the
21786 // following naming scheme:
21787 // (a + ib) / (c + id)
21788 ComplexValue LHS = Result;
21789 APFloat &A = LHS.getComplexFloatReal();
21790 APFloat &B = LHS.getComplexFloatImag();
21791 APFloat &C = RHS.getComplexFloatReal();
21792 APFloat &D = RHS.getComplexFloatImag();
21793 APFloat &ResR = Result.getComplexFloatReal();
21794 APFloat &ResI = Result.getComplexFloatImag();
21795 if (RHSReal) {
21796 ResR = A;
21797 ResI = B;
21798 // ResR = A / C;
21799 // ResI = B / C;
21800 if (!handleFloatFloatBinOp(Info, E, ResR, BO_Div, C) ||
21801 !handleFloatFloatBinOp(Info, E, ResI, BO_Div, C))
21802 return false;
21803 } else {
21804 if (LHSReal) {
21805 // No real optimizations we can do here, stub out with zero.
21806 B = APFloat::getZero(A.getSemantics());
21807 }
21808 HandleComplexComplexDiv(A, B, C, D, ResR, ResI);
21809 }
21810 } else {
21811 ComplexValue LHS = Result;
21812 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
21813 RHS.getComplexIntImag() * RHS.getComplexIntImag();
21814 if (Den.isZero())
21815 return Error(E, diag::note_expr_divide_by_zero);
21816
21817 Result.getComplexIntReal() =
21818 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
21819 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
21820 Result.getComplexIntImag() =
21821 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
21822 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
21823 }
21824 break;
21825 }
21826
21827 return true;
21828}
21829
21830bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
21831 // Get the operand value into 'Result'.
21832 if (!Visit(E->getSubExpr()))
21833 return false;
21834
21835 switch (E->getOpcode()) {
21836 default:
21837 return Error(E);
21838 case UO_Extension:
21839 return true;
21840 case UO_Plus:
21841 // The result is always just the subexpr.
21842 return true;
21843 case UO_Minus:
21844 if (Result.isComplexFloat()) {
21845 Result.getComplexFloatReal().changeSign();
21846 Result.getComplexFloatImag().changeSign();
21847 }
21848 else {
21849 Result.getComplexIntReal() = -Result.getComplexIntReal();
21850 Result.getComplexIntImag() = -Result.getComplexIntImag();
21851 }
21852 return true;
21853 case UO_Not:
21854 if (Result.isComplexFloat())
21855 Result.getComplexFloatImag().changeSign();
21856 else
21857 Result.getComplexIntImag() = -Result.getComplexIntImag();
21858 return true;
21859 }
21860}
21861
21862bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
21863 if (E->getNumInits() == 2) {
21864 if (E->getType()->isComplexType()) {
21865 Result.makeComplexFloat();
21866 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
21867 return false;
21868 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
21869 return false;
21870 } else {
21871 Result.makeComplexInt();
21872 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
21873 return false;
21874 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
21875 return false;
21876 }
21877 return true;
21878 }
21879 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
21880}
21881
21882bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) {
21883 if (!IsConstantEvaluatedBuiltinCall(E))
21884 return ExprEvaluatorBaseTy::VisitCallExpr(E);
21885
21886 switch (E->getBuiltinCallee()) {
21887 case Builtin::BI__builtin_complex:
21888 Result.makeComplexFloat();
21889 if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info))
21890 return false;
21891 if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info))
21892 return false;
21893 return true;
21894
21895 default:
21896 return false;
21897 }
21898}
21899
21900//===----------------------------------------------------------------------===//
21901// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
21902// implicit conversion.
21903//===----------------------------------------------------------------------===//
21904
21905namespace {
21906class AtomicExprEvaluator :
21907 public ExprEvaluatorBase<AtomicExprEvaluator> {
21908 const LValue *This;
21909 APValue &Result;
21910public:
21911 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
21912 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
21913
21914 bool Success(const APValue &V, const Expr *E) {
21915 Result = V;
21916 return true;
21917 }
21918
21919 bool ZeroInitialization(const Expr *E) {
21920 ImplicitValueInitExpr VIE(
21921 E->getType()->castAs<AtomicType>()->getValueType());
21922 // For atomic-qualified class (and array) types in C++, initialize the
21923 // _Atomic-wrapped subobject directly, in-place.
21924 return This ? EvaluateInPlace(Result, Info, *This, &VIE)
21925 : Evaluate(Result, Info, &VIE);
21926 }
21927
21928 bool VisitCastExpr(const CastExpr *E) {
21929 switch (E->getCastKind()) {
21930 default:
21931 return ExprEvaluatorBaseTy::VisitCastExpr(E);
21932 case CK_NullToPointer:
21933 VisitIgnoredValue(E->getSubExpr());
21934 return ZeroInitialization(E);
21935 case CK_NonAtomicToAtomic:
21936 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
21937 : Evaluate(Result, Info, E->getSubExpr());
21938 }
21939 }
21940};
21941} // end anonymous namespace
21942
21943static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
21944 EvalInfo &Info) {
21945 assert(!E->isValueDependent());
21946 assert(E->isPRValue() && E->getType()->isAtomicType());
21947 return AtomicExprEvaluator(Info, This, Result).Visit(E);
21948}
21949
21950//===----------------------------------------------------------------------===//
21951// Void expression evaluation, primarily for a cast to void on the LHS of a
21952// comma operator
21953//===----------------------------------------------------------------------===//
21954
21955namespace {
21956class VoidExprEvaluator
21957 : public ExprEvaluatorBase<VoidExprEvaluator> {
21958public:
21959 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
21960
21961 bool Success(const APValue &V, const Expr *e) { return true; }
21962
21963 bool ZeroInitialization(const Expr *E) { return true; }
21964
21965 bool VisitCastExpr(const CastExpr *E) {
21966 switch (E->getCastKind()) {
21967 default:
21968 return ExprEvaluatorBaseTy::VisitCastExpr(E);
21969 case CK_ToVoid:
21970 VisitIgnoredValue(E->getSubExpr());
21971 return true;
21972 }
21973 }
21974
21975 bool VisitCallExpr(const CallExpr *E) {
21976 if (!IsConstantEvaluatedBuiltinCall(E))
21977 return ExprEvaluatorBaseTy::VisitCallExpr(E);
21978
21979 switch (E->getBuiltinCallee()) {
21980 case Builtin::BI__assume:
21981 case Builtin::BI__builtin_assume:
21982 // The argument is not evaluated!
21983 return true;
21984
21985 case Builtin::BI__builtin_operator_delete:
21986 return HandleOperatorDeleteCall(Info, E);
21987
21988 case Builtin::BIstdc_memreverse8:
21989 case Builtin::BI__builtin_stdc_memreverse8: {
21990 APSInt N;
21991 if (!EvaluateInteger(E->getArg(0), N, Info))
21992 return false;
21993 uint64_t NElems = N.getZExtValue();
21994
21995 LValue Ptr;
21996 if (!EvaluatePointer(E->getArg(1), Ptr, Info))
21997 return false;
21998
21999 if (!Ptr.checkNullPointerForFoldAccess(Info, E, AK_Assign) ||
22000 Ptr.Designator.Invalid)
22001 return false;
22002
22003 QualType CharTy = Ptr.Designator.getType(Info.Ctx);
22004 uint64_t RemainingElems = Ptr.Designator.validIndexAdjustments().second;
22005 if (NElems > RemainingElems) {
22006 uint64_t ArrayIndex =
22007 Ptr.Designator.MostDerivedIsArrayElement
22008 ? Ptr.Designator.Entries.back().getAsArrayIndex()
22009 : (uint64_t)Ptr.Designator.IsOnePastTheEnd;
22010 APSInt Index =
22011 APSInt::getUnsigned(llvm::SaturatingAdd(ArrayIndex, NElems - 1));
22012 Ptr.Designator.diagnosePointerArithmetic(Info, E, Index);
22013 return false;
22014 }
22015
22016 if (NElems <= 1)
22017 return true;
22018
22019 LValue Lo = Ptr;
22020 LValue Hi = Ptr;
22021 if (!HandleLValueArrayAdjustment(Info, E, Hi, CharTy, NElems - 1))
22022 return false;
22023
22024 for (uint64_t I = 0, Half = NElems / 2; I < Half; ++I) {
22025 APValue LoVal, HiVal;
22026 if (!handleLValueToRValueConversion(Info, E, CharTy, Lo, LoVal) ||
22027 !handleLValueToRValueConversion(Info, E, CharTy, Hi, HiVal) ||
22028 !handleAssignment(Info, E, Lo, CharTy, HiVal) ||
22029 !handleAssignment(Info, E, Hi, CharTy, LoVal) ||
22030 !HandleLValueArrayAdjustment(Info, E, Lo, CharTy, 1) ||
22031 !HandleLValueArrayAdjustment(Info, E, Hi, CharTy, -1))
22032 return false;
22033 }
22034 return true;
22035 }
22036
22037 default:
22038 return false;
22039 }
22040 }
22041
22042 bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
22043};
22044} // end anonymous namespace
22045
22046bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
22047 // We cannot speculatively evaluate a delete expression.
22048 if (Info.SpeculativeEvaluationDepth)
22049 return false;
22050
22051 FunctionDecl *OperatorDelete = E->getOperatorDelete();
22052 if (!OperatorDelete
22053 ->isUsableAsGlobalAllocationFunctionInConstantEvaluation()) {
22054 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
22055 << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;
22056 return false;
22057 }
22058
22059 const Expr *Arg = E->getArgument();
22060
22061 LValue Pointer;
22062 if (!EvaluatePointer(Arg, Pointer, Info))
22063 return false;
22064 if (Pointer.Designator.Invalid)
22065 return false;
22066
22067 // Deleting a null pointer has no effect.
22068 if (Pointer.isNullPointer()) {
22069 // This is the only case where we need to produce an extension warning:
22070 // the only other way we can succeed is if we find a dynamic allocation,
22071 // and we will have warned when we allocated it in that case.
22072 if (!Info.getLangOpts().CPlusPlus20)
22073 Info.CCEDiag(E, diag::note_constexpr_new);
22074 return true;
22075 }
22076
22077 std::optional<DynAlloc *> Alloc = CheckDeleteKind(
22078 Info, E, Pointer,
22079 E->isArrayForm() ? DynAllocKind::ArrayNew : DynAllocKind::New);
22080 if (!Alloc)
22081 return false;
22082 QualType AllocType = Pointer.Base.getDynamicAllocType();
22083
22084 // For the non-array case, the designator must be empty if the static type
22085 // does not have a virtual destructor.
22086 if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 &&
22088 Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor)
22089 << Arg->getType()->getPointeeType() << AllocType;
22090 return false;
22091 }
22092
22093 // For a class type with a virtual destructor, the selected operator delete
22094 // is the one looked up when building the destructor.
22095 if (!E->isArrayForm() && !E->isGlobalDelete()) {
22096 const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType);
22097 if (VirtualDelete &&
22098 !VirtualDelete
22099 ->isUsableAsGlobalAllocationFunctionInConstantEvaluation()) {
22100 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
22101 << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete;
22102 return false;
22103 }
22104 }
22105
22106 if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(),
22107 (*Alloc)->Value, AllocType))
22108 return false;
22109
22110 if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) {
22111 // The element was already erased. This means the destructor call also
22112 // deleted the object.
22113 // FIXME: This probably results in undefined behavior before we get this
22114 // far, and should be diagnosed elsewhere first.
22115 Info.FFDiag(E, diag::note_constexpr_double_delete);
22116 return false;
22117 }
22118
22119 return true;
22120}
22121
22122static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
22123 assert(!E->isValueDependent());
22124 assert(E->isPRValue() && E->getType()->isVoidType());
22125 return VoidExprEvaluator(Info).Visit(E);
22126}
22127
22128//===----------------------------------------------------------------------===//
22129// Top level Expr::EvaluateAsRValue method.
22130//===----------------------------------------------------------------------===//
22131
22132static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
22133 assert(!E->isValueDependent());
22134 // In C, function designators are not lvalues, but we evaluate them as if they
22135 // are.
22136 QualType T = E->getType();
22137 if (E->isGLValue() || T->isFunctionType()) {
22138 LValue LV;
22139 if (!EvaluateLValue(E, LV, Info))
22140 return false;
22141 LV.moveInto(Result);
22142 } else if (T->isVectorType()) {
22143 if (!EvaluateVector(E, Result, Info))
22144 return false;
22145 } else if (T->isConstantMatrixType()) {
22146 if (!EvaluateMatrix(E, Result, Info))
22147 return false;
22148 } else if (T->isIntegralOrEnumerationType()) {
22149 if (!IntExprEvaluator(Info, Result).Visit(E))
22150 return false;
22151 } else if (T->isMetaInfoType()) {
22152 if (!EvaluateReflection(E, Result, Info))
22153 return false;
22154 } else if (T->hasPointerRepresentation()) {
22155 LValue LV;
22156 if (!EvaluatePointer(E, LV, Info))
22157 return false;
22158 LV.moveInto(Result);
22159 } else if (T->isRealFloatingType()) {
22160 llvm::APFloat F(0.0);
22161 if (!EvaluateFloat(E, F, Info))
22162 return false;
22163 Result = APValue(F);
22164 } else if (T->isAnyComplexType()) {
22165 ComplexValue C;
22166 if (!EvaluateComplex(E, C, Info))
22167 return false;
22168 C.moveInto(Result);
22169 } else if (T->isFixedPointType()) {
22170 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
22171 } else if (T->isMemberPointerType()) {
22172 MemberPtr P;
22173 if (!EvaluateMemberPointer(E, P, Info))
22174 return false;
22175 P.moveInto(Result);
22176 return true;
22177 } else if (T->isArrayType()) {
22178 LValue LV;
22179 APValue &Value =
22180 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
22181 if (!EvaluateArray(E, LV, Value, Info))
22182 return false;
22183 Result = Value;
22184 } else if (T->isRecordType()) {
22185 LValue LV;
22186 APValue &Value =
22187 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
22188 if (!EvaluateRecord(E, LV, Value, Info))
22189 return false;
22190 Result = Value;
22191 } else if (T->isVoidType()) {
22192 if (!Info.getLangOpts().CPlusPlus11)
22193 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
22194 << E->getType();
22195 if (!EvaluateVoid(E, Info))
22196 return false;
22197 } else if (T->isAtomicType()) {
22198 QualType Unqual = T.getAtomicUnqualifiedType();
22199 if (Unqual->isArrayType() || Unqual->isRecordType()) {
22200 LValue LV;
22201 APValue &Value = Info.CurrentCall->createTemporary(
22202 E, Unqual, ScopeKind::FullExpression, LV);
22203 if (!EvaluateAtomic(E, &LV, Value, Info))
22204 return false;
22205 Result = Value;
22206 } else {
22207 if (!EvaluateAtomic(E, nullptr, Result, Info))
22208 return false;
22209 }
22210 } else if (Info.getLangOpts().CPlusPlus11) {
22211 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
22212 return false;
22213 } else {
22214 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
22215 return false;
22216 }
22217
22218 return true;
22219}
22220
22221/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
22222/// cases, the in-place evaluation is essential, since later initializers for
22223/// an object can indirectly refer to subobjects which were initialized earlier.
22224static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
22225 const Expr *E, bool AllowNonLiteralTypes) {
22226 assert(!E->isValueDependent());
22227
22228 // Normally expressions passed to EvaluateInPlace have a type, but not when
22229 // a VarDecl initializer is evaluated before the untyped ParenListExpr is
22230 // replaced with a CXXConstructExpr. This can happen in LLDB.
22231 if (E->getType().isNull())
22232 return false;
22233
22234 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
22235 return false;
22236
22237 if (E->isPRValue()) {
22238 // Evaluate arrays and record types in-place, so that later initializers can
22239 // refer to earlier-initialized members of the object.
22240 QualType T = E->getType();
22241 if (T->isArrayType())
22242 return EvaluateArray(E, This, Result, Info);
22243 else if (T->isRecordType())
22244 return EvaluateRecord(E, This, Result, Info);
22245 else if (T->isAtomicType()) {
22246 QualType Unqual = T.getAtomicUnqualifiedType();
22247 if (Unqual->isArrayType() || Unqual->isRecordType())
22248 return EvaluateAtomic(E, &This, Result, Info);
22249 }
22250 }
22251
22252 // For any other type, in-place evaluation is unimportant.
22253 return Evaluate(Result, Info, E);
22254}
22255
22256/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
22257/// lvalue-to-rvalue cast if it is an lvalue.
22258static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
22259 assert(!E->isValueDependent());
22260 assert(!Info.Ctx.getLangOpts().EnableNewConstInterp);
22261
22262 if (E->getType().isNull())
22263 return false;
22264
22265 if (!CheckLiteralType(Info, E))
22266 return false;
22267
22268 if (!::Evaluate(Result, Info, E))
22269 return false;
22270
22271 // Implicit lvalue-to-rvalue cast.
22272 if (E->isGLValue()) {
22273 LValue LV;
22274 LV.setFrom(Info.Ctx, Result);
22275 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
22276 return false;
22277 }
22278
22279 // Check this core constant expression is a constant expression.
22280 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
22281 ConstantExprKind::Normal) &&
22282 CheckMemoryLeaks(Info);
22283}
22284
22285static bool FastEvaluateAsRValue(const Expr *Exp, APValue &Result,
22286 const ASTContext &Ctx, bool &IsConst) {
22287 // Fast-path evaluations of integer literals, since we sometimes see files
22288 // containing vast quantities of these.
22289 if (const auto *L = dyn_cast<IntegerLiteral>(Exp)) {
22290 Result =
22291 APValue(APSInt(L->getValue(), L->getType()->isUnsignedIntegerType()));
22292 IsConst = true;
22293 return true;
22294 }
22295
22296 if (const auto *L = dyn_cast<CXXBoolLiteralExpr>(Exp)) {
22297 Result = APValue(APSInt(APInt(1, L->getValue())));
22298 IsConst = true;
22299 return true;
22300 }
22301
22302 if (const auto *FL = dyn_cast<FloatingLiteral>(Exp)) {
22303 Result = APValue(FL->getValue());
22304 IsConst = true;
22305 return true;
22306 }
22307
22308 if (const auto *L = dyn_cast<CharacterLiteral>(Exp)) {
22309 Result = APValue(Ctx.MakeIntValue(L->getValue(), L->getType()));
22310 IsConst = true;
22311 return true;
22312 }
22313
22314 if (const auto *CE = dyn_cast<ConstantExpr>(Exp)) {
22315 if (CE->hasAPValueResult()) {
22316 APValue APV = CE->getAPValueResult();
22317 if (!APV.isLValue()) {
22318 Result = std::move(APV);
22319 IsConst = true;
22320 return true;
22321 }
22322 }
22323
22324 // The SubExpr is usually just an IntegerLiteral.
22325 return FastEvaluateAsRValue(CE->getSubExpr(), Result, Ctx, IsConst);
22326 }
22327
22328 // This case should be rare, but we need to check it before we check on
22329 // the type below.
22330 if (Exp->getType().isNull()) {
22331 IsConst = false;
22332 return true;
22333 }
22334
22335 return false;
22336}
22337
22340 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
22341 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
22342}
22343
22345 const ASTContext &Ctx, EvalInfo &Info) {
22346 assert(!E->isValueDependent());
22347 bool IsConst;
22348 if (FastEvaluateAsRValue(E, Result.Val, Ctx, IsConst))
22349 return IsConst;
22350
22351 return EvaluateAsRValue(Info, E, Result.Val);
22352}
22353
22355 const ASTContext &Ctx,
22356 Expr::SideEffectsKind AllowSideEffects,
22357 EvalInfo &Info) {
22358 assert(!E->isValueDependent());
22360 return false;
22361
22362 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
22363 !ExprResult.Val.isInt() ||
22364 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
22365 return false;
22366
22367 return true;
22368}
22369
22371 const ASTContext &Ctx,
22372 Expr::SideEffectsKind AllowSideEffects,
22373 EvalInfo &Info) {
22374 assert(!E->isValueDependent());
22375 if (!E->getType()->isFixedPointType())
22376 return false;
22377
22378 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
22379 return false;
22380
22381 if (!ExprResult.Val.isFixedPoint() ||
22382 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
22383 return false;
22384
22385 return true;
22386}
22387
22389 const ASTContext &Ctx, SemaProxy *SProxy,
22390 bool InConstantContext) {
22391 assert(!E->isValueDependent() &&
22392 "Expression evaluator can't be called on a dependent expression.");
22393
22394 bool IsConst;
22395 if (FastEvaluateAsRValue(E, Result.Val, Ctx, IsConst))
22396 return IsConst;
22397
22398 if (Ctx.getLangOpts().EnableNewConstInterp) {
22400 SProxy);
22401 Settings.InConstantContext = InConstantContext;
22402 return Ctx.getInterpContext().evaluateAsRValue(Settings, E, Result.Val);
22403 }
22404
22405 EvalInfo Info(Ctx, SProxy, Result, EvaluationMode::IgnoreSideEffects);
22406 Info.InConstantContext = InConstantContext;
22407 return ::EvaluateAsRValue(E, Result, Ctx, Info);
22408}
22409
22410/// EvaluateAsRValue - Return true if this is a constant which we can fold using
22411/// any crazy technique (that has nothing to do with language standards) that
22412/// we want to. If this function returns true, it returns the folded constant
22413/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
22414/// will be applied to the result.
22416 bool InConstantContext) const {
22417 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsRValue");
22418 return ::doEvaluateAsRValue(this, Result, Ctx, /*SProxy=*/nullptr,
22419 InConstantContext);
22420}
22421
22423 const ASTContext &Ctx,
22424 SemaProxy &SProxy) const {
22425 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsMandatedConstantRValue");
22426 return ::doEvaluateAsRValue(this, Result, Ctx, &SProxy,
22427 /*InConstantContext=*/true);
22428}
22429
22431 bool InConstantContext) const {
22432 assert(!isValueDependent() &&
22433 "Expression evaluator can't be called on a dependent expression.");
22434 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsBooleanCondition");
22435 EvalResult Scratch;
22436 return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
22437 HandleConversionToBool(Scratch.Val, Result);
22438}
22439
22441 SideEffectsKind AllowSideEffects,
22442 bool InConstantContext) const {
22443 assert(!isValueDependent() &&
22444 "Expression evaluator can't be called on a dependent expression.");
22445
22446 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsInt");
22447
22448 if (!getType()->isIntegralOrEnumerationType())
22449 return false;
22450
22451 bool IsConst;
22452 if (FastEvaluateAsRValue(this, Result.Val, Ctx, IsConst))
22453 return IsConst;
22454
22455 if (Ctx.getLangOpts().EnableNewConstInterp) {
22457 /*SProxy=*/nullptr);
22458 Settings.InConstantContext = InConstantContext;
22459 if (!Ctx.getInterpContext().evaluateAsRValue(Settings, this, Result.Val))
22460 return false;
22461
22462 if (!Result.Val.isInt() ||
22463 hasUnacceptableSideEffect(Result, AllowSideEffects))
22464 return false;
22465 return true;
22466 }
22467
22468 EvalInfo Info(Ctx, /*SProxy=*/nullptr, Result,
22470 Info.InConstantContext = InConstantContext;
22471 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
22472}
22473
22475 SideEffectsKind AllowSideEffects,
22476 bool InConstantContext) const {
22477 assert(!isValueDependent() &&
22478 "Expression evaluator can't be called on a dependent expression.");
22479 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFixedPoint");
22480
22481 if (!getType()->isFixedPointType())
22482 return false;
22483
22484 if (Ctx.getLangOpts().EnableNewConstInterp) {
22486 /*SProxy=*/nullptr);
22487 Settings.InConstantContext = InConstantContext;
22488
22489 if (!Ctx.getInterpContext().evaluateAsRValue(Settings, this, Result.Val))
22490 return false;
22491
22492 if (!Result.Val.isFixedPoint() ||
22493 hasUnacceptableSideEffect(Result, AllowSideEffects))
22494 return false;
22495
22496 return true;
22497 }
22498
22499 EvalInfo Info(Ctx, /*SProxy=*/nullptr, Result,
22501 Info.InConstantContext = InConstantContext;
22502 return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
22503}
22504
22505bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
22506 SideEffectsKind AllowSideEffects,
22507 bool InConstantContext) const {
22508 assert(!isValueDependent() &&
22509 "Expression evaluator can't be called on a dependent expression.");
22510
22511 if (!getType()->isRealFloatingType())
22512 return false;
22513
22514 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFloat");
22516 if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
22517 !ExprResult.Val.isFloat() ||
22518 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
22519 return false;
22520
22521 Result = ExprResult.Val.getFloat();
22522 return true;
22523}
22524
22526 bool InConstantContext) const {
22527 assert(!isValueDependent() &&
22528 "Expression evaluator can't be called on a dependent expression.");
22529
22530 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsLValue");
22531
22532 if (Ctx.getLangOpts().EnableNewConstInterp) {
22534 /*SProxy=*/nullptr);
22535 Settings.InConstantContext = InConstantContext;
22536 return Ctx.getInterpContext().evaluate(Settings, this, Result.Val);
22537 }
22538
22539 EvalInfo Info(Ctx, /*SProxy=*/nullptr, Result, EvaluationMode::ConstantFold);
22540 Info.InConstantContext = InConstantContext;
22541 LValue LV;
22542 CheckedTemporaries CheckedTemps;
22543
22544 if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() ||
22545 Result.HasSideEffects ||
22548 ConstantExprKind::Normal, CheckedTemps))
22549 return false;
22550
22551 LV.moveInto(Result.Val);
22552 return true;
22553}
22554
22555static bool EvaluateDestruction(const ASTContext &Ctx, SemaProxy *SProxy,
22557 APValue DestroyedValue, QualType Type,
22558 SourceLocation Loc, Expr::EvalStatus &EStatus,
22559 bool IsConstantDestruction) {
22560 EvalInfo Info(Ctx, SProxy, EStatus,
22561 IsConstantDestruction ? EvaluationMode::ConstantExpression
22563 Info.setEvaluatingDecl(Base, DestroyedValue,
22564 EvalInfo::EvaluatingDeclKind::Dtor);
22565 Info.InConstantContext = IsConstantDestruction;
22566
22567 LValue LVal;
22568 LVal.set(Base);
22569
22570 if (!HandleDestruction(Info, Loc, Base, DestroyedValue, Type) ||
22571 EStatus.HasSideEffects)
22572 return false;
22573
22574 if (!Info.discardCleanups())
22575 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
22576
22577 return true;
22578}
22579
22581 const ASTContext &Ctx, SemaProxy *SProxy,
22582 const Expr *E, ConstantExprKind Kind) {
22583 assert(!E->isValueDependent() &&
22584 "Expression evaluator can't be called on a dependent expression.");
22585
22586 bool IsConst;
22587 if (FastEvaluateAsRValue(E, Result.Val, Ctx, IsConst) &&
22588 Result.Val.hasValue())
22589 return true;
22590
22591 EvaluationMode EM = Kind == ConstantExprKind::Initializer
22594 if (Ctx.getLangOpts().EnableNewConstInterp) {
22595 interp::EvalSettings Settings(EM, Result, SProxy, Kind);
22596 Settings.InConstantContext = true;
22597 return Ctx.getInterpContext().evaluate(Settings, E, Result.Val) &&
22598 !Result.HasSideEffects;
22599 }
22600
22601 EvalInfo Info(Ctx, SProxy, Result, EM);
22602 Info.InConstantContext = true;
22603
22604 // The type of the object we're initializing is 'const T' for a class NTTP.
22605 QualType T = E->getType();
22606 if (Kind == ConstantExprKind::ClassTemplateArgument)
22607 T.addConst();
22608
22609 // If we're evaluating a prvalue, fake up a MaterializeTemporaryExpr to
22610 // represent the result of the evaluation. CheckConstantExpression ensures
22611 // this doesn't escape.
22612 MaterializeTemporaryExpr BaseMTE(T, const_cast<Expr *>(E), true);
22613 APValue::LValueBase Base(&BaseMTE);
22614 Info.setEvaluatingDecl(Base, Result.Val);
22615
22616 LValue LVal;
22617 LVal.set(Base);
22618 // C++23 [intro.execution]/p5
22619 // A full-expression is [...] a constant-expression
22620 // So we need to make sure temporary objects are destroyed after having
22621 // evaluating the expression (per C++23 [class.temporary]/p4).
22622 FullExpressionRAII Scope(Info);
22623 if (!::EvaluateInPlace(Result.Val, Info, LVal, E) || Result.HasSideEffects ||
22624 !Scope.destroy())
22625 return false;
22626
22627 if (!Info.discardCleanups())
22628 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
22629
22630 if (Result.HasSideEffects ||
22631 !CheckConstantExpression(Info, E->getExprLoc(), getStorageType(Ctx, E),
22632 Result.Val, Kind))
22633 return false;
22634 if (!CheckMemoryLeaks(Info))
22635 return false;
22636
22637 // If this is a class template argument, it's required to have constant
22638 // destruction too.
22639 if (Kind == ConstantExprKind::ClassTemplateArgument &&
22640 (!EvaluateDestruction(Ctx, Info.getSemaProxy(), Base, Result.Val, T,
22641 E->getBeginLoc(), Result, true) ||
22642 Result.HasSideEffects)) {
22643 // FIXME: Prefix a note to indicate that the problem is lack of constant
22644 // destruction.
22645 return false;
22646 }
22647
22648 return true;
22649}
22650
22652 ConstantExprKind Kind) const {
22653
22654 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsConstantExpr");
22655 return ::doEvaluateConstantExpr(Result, Ctx, /*SProxy=*/nullptr, this, Kind);
22656}
22657
22659 const ASTContext &Ctx,
22660 SemaProxy &SProxy,
22661 ConstantExprKind Kind) const {
22662 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsMandatedConstantExpr");
22663 return ::doEvaluateConstantExpr(Result, Ctx, &SProxy, this, Kind);
22664}
22665
22666static bool doEvaluateInitializer(const ASTContext &Ctx, SemaProxy *SProxy,
22667 const VarDecl *VD, const Expr *E,
22668 Expr::EvalResult &EStatus,
22669 bool IsConstantInitialization) {
22670 assert(!E->isValueDependent() &&
22671 "Expression evaluator can't be called on a dependent expression.");
22672 assert(VD && "Need a valid VarDecl");
22673
22674 EvaluationMode EvalMode =
22675 (IsConstantInitialization &&
22676 (Ctx.getLangOpts().CPlusPlus || Ctx.getLangOpts().C23))
22679
22680 if (Ctx.getLangOpts().EnableNewConstInterp) {
22681 interp::EvalSettings Settings(EvalMode, EStatus, SProxy);
22682 Settings.InConstantContext = IsConstantInitialization;
22683 return Ctx.getInterpContext().evaluateAsInitializer(Settings, VD, E,
22684 EStatus.Val);
22685 }
22686
22687 SourceLocation DeclLoc = VD->getLocation();
22688 QualType DeclTy = VD->getType();
22689
22690 EvalInfo Info(Ctx, SProxy, EStatus, EvalMode);
22691 Info.setEvaluatingDecl(VD, EStatus.Val);
22692 Info.InConstantContext = IsConstantInitialization;
22693
22694 LValue LVal;
22695 LVal.set(VD);
22696
22697 {
22698 // C++23 [intro.execution]/p5
22699 // A full-expression is ... an init-declarator ([dcl.decl]) or a
22700 // mem-initializer.
22701 // So we need to make sure temporary objects are destroyed after having
22702 // evaluated the expression (per C++23 [class.temporary]/p4).
22703 //
22704 // FIXME: Otherwise this may break test/Modules/pr68702.cpp because the
22705 // serialization code calls ParmVarDecl::getDefaultArg() which strips the
22706 // outermost FullExpr, such as ExprWithCleanups.
22707 FullExpressionRAII Scope(Info);
22708 if (!EvaluateInPlace(EStatus.Val, Info, LVal, E,
22709 /*AllowNonLiteralTypes=*/true) ||
22710 EStatus.HasSideEffects)
22711 return false;
22712 }
22713
22714 // At this point, any lifetime-extended temporaries are completely
22715 // initialized.
22716 Info.performLifetimeExtension();
22717
22718 if (!Info.discardCleanups())
22719 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
22720
22721 return CheckConstantExpression(Info, DeclLoc, DeclTy, EStatus.Val,
22722 ConstantExprKind::Normal) &&
22723 CheckMemoryLeaks(Info);
22724}
22725
22727 Expr::EvalResult &EStatus,
22728 bool IsConstantInitialization) const {
22729 llvm::TimeTraceScope TimeScope("EvaluateAsInitializer", [&] {
22730 std::string Name;
22731 llvm::raw_string_ostream OS(Name);
22732 VD->printQualifiedName(OS);
22733 return Name;
22734 });
22735
22736 return ::doEvaluateInitializer(Ctx, /*SProxy=*/nullptr, VD, this, EStatus,
22737 IsConstantInitialization);
22738}
22739
22741 const ASTContext &Ctx,
22742 SemaProxy &SProxy,
22743 const VarDecl *VD) const {
22744 llvm::TimeTraceScope TimeScope("EvaluateAsMandatedConstantInitializer", [&] {
22745 std::string Name;
22746 llvm::raw_string_ostream OS(Name);
22747 VD->printQualifiedName(OS);
22748 return Name;
22749 });
22750
22751 return ::doEvaluateInitializer(Ctx, &SProxy, VD, this, EStatus,
22752 /*IsConstantInitialization=*/true);
22753}
22754
22755static bool doEvaluateDestruction(const VarDecl *VD, SemaProxy *SProxy,
22756 bool IsConstantDestruction,
22758 ASTContext &Ctx = VD->getASTContext();
22759
22760 // This function is only meaningful for records and arrays of records.
22761 QualType VarTy = VD->getType();
22762 if (VarTy->isArrayType()) {
22763 QualType ElemTy = Ctx.getBaseElementType(VarTy);
22764 if (!ElemTy->isRecordType()) {
22766 return true;
22767 }
22768 } else if (!VarTy->isRecordType()) {
22770 return true;
22771 }
22772
22773 Expr::EvalStatus EStatus;
22774 EStatus.Diag = &Notes;
22775
22776 // Make a copy of the value for the destructor to mutate, if we know it.
22777 // Otherwise, treat the value as default-initialized; if the destructor works
22778 // anyway, then the destruction is constant (and must be essentially empty).
22779 APValue DestroyedValue;
22780 if (VD->getEvaluatedValue())
22781 DestroyedValue = *VD->getEvaluatedValue();
22782 else if (!handleDefaultInitValue(VarTy, DestroyedValue))
22783 return false;
22784
22785 if (Ctx.getLangOpts().EnableNewConstInterp) {
22786 interp::EvalSettings Settings(IsConstantDestruction
22789 EStatus, SProxy);
22790 Settings.InConstantContext = IsConstantDestruction;
22791 if (!Ctx.getInterpContext().evaluateDestruction(Settings, VD,
22792 std::move(DestroyedValue)))
22793 return false;
22795 return true;
22796 }
22797
22798 if (!EvaluateDestruction(Ctx, SProxy, VD, std::move(DestroyedValue), VarTy,
22799 VD->getLocation(), EStatus, IsConstantDestruction) ||
22800 EStatus.HasSideEffects)
22801 return false;
22802
22804 return true;
22805}
22806
22809 // Only treat the destruction as constant destruction if we formally have
22810 // constant initialization (or are usable in a constant expression).
22811 bool IsConstantDestruction = hasConstantInitialization();
22812
22813 return ::doEvaluateDestruction(this, /*SProxy=*/nullptr,
22814 IsConstantDestruction, Notes);
22815}
22816
22818 SmallVectorImpl<PartialDiagnosticAt> &Notes, SemaProxy &SProxy) const {
22819 // Only treat the destruction as constant destruction if we formally have
22820 // constant initialization (or are usable in a constant expression).
22821 bool IsConstantDestruction = hasConstantInitialization();
22822
22823 return ::doEvaluateDestruction(this, &SProxy, IsConstantDestruction, Notes);
22824}
22825
22826/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
22827/// constant folded, but discard the result.
22829 assert(!isValueDependent() &&
22830 "Expression evaluator can't be called on a dependent expression.");
22831
22833 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
22835}
22836
22837APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
22838 assert(!isValueDependent() &&
22839 "Expression evaluator can't be called on a dependent expression.");
22840
22841 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstInt");
22842 EvalResult EVResult;
22843
22844 bool IsConst;
22845 if (FastEvaluateAsRValue(this, EVResult.Val, Ctx, IsConst)) {
22846 assert(IsConst);
22847 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
22848 return EVResult.Val.getInt();
22849 }
22850
22851 if (Ctx.getLangOpts().EnableNewConstInterp) {
22853 /*SProxy=*/nullptr);
22854 Settings.InConstantContext = true;
22855 [[maybe_unused]] bool Result =
22856 Ctx.getInterpContext().evaluateAsRValue(Settings, this, EVResult.Val);
22857 assert(Result && "Could not evaluate expression");
22858 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
22859
22860 return EVResult.Val.getInt();
22861 }
22862
22863 EvalInfo Info(Ctx, /*SProxy=*/nullptr, EVResult,
22865 Info.InConstantContext = true;
22866
22867 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
22868 (void)Result;
22869 assert(Result && "Could not evaluate expression");
22870 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
22871
22872 return EVResult.Val.getInt();
22873}
22874
22877 assert(!isValueDependent() &&
22878 "Expression evaluator can't be called on a dependent expression.");
22879
22880 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstIntCheckOverflow");
22881 EvalResult EVResult;
22882 EVResult.Diag = Diag;
22883
22884 bool IsConst;
22885 if (FastEvaluateAsRValue(this, EVResult.Val, Ctx, IsConst)) {
22886 assert(IsConst);
22887 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
22888 return EVResult.Val.getInt();
22889 }
22890
22891 if (Ctx.getLangOpts().EnableNewConstInterp) {
22893 /*SProxy=*/nullptr);
22894 Settings.InConstantContext = true;
22895 Settings.CheckingForUndefinedBehavior = true;
22896 [[maybe_unused]] bool Result =
22897 Ctx.getInterpContext().evaluateAsRValue(Settings, this, EVResult.Val);
22898 assert(Result && "Could not evaluate expression");
22899 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
22900
22901 return EVResult.Val.getInt();
22902 }
22903
22904 EvalInfo Info(Ctx, /*SProxy=*/nullptr, EVResult,
22906 Info.InConstantContext = true;
22907 Info.CheckingForUndefinedBehavior = true;
22908
22909 bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
22910 (void)Result;
22911 assert(Result && "Could not evaluate expression");
22912 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
22913
22914 return EVResult.Val.getInt();
22915}
22916
22918 assert(!isValueDependent() &&
22919 "Expression evaluator can't be called on a dependent expression.");
22920
22921 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateForOverflow");
22922 bool IsConst;
22923 EvalResult EVResult;
22924 if (FastEvaluateAsRValue(this, EVResult.Val, Ctx, IsConst))
22925 return;
22926
22927 if (Ctx.getLangOpts().EnableNewConstInterp) {
22929 /*SProxy=*/nullptr);
22930 Settings.CheckingForUndefinedBehavior = true;
22931 (void)Ctx.getInterpContext().evaluateAsRValue(Settings, this, EVResult.Val);
22932 return;
22933 }
22934
22935 EvalInfo Info(Ctx, /*SProxy=*/nullptr, EVResult,
22937 Info.CheckingForUndefinedBehavior = true;
22938 (void)::EvaluateAsRValue(Info, this, EVResult.Val);
22939}
22940
22942 assert(Val.isLValue());
22943 return IsGlobalLValue(Val.getLValueBase());
22944}
22945
22946/// isIntegerConstantExpr - this recursive routine will test if an expression is
22947/// an integer constant expression.
22948
22949/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
22950/// comma, etc
22951
22952// CheckICE - This function does the fundamental ICE checking: the returned
22953// ICEDiag contains an ICEKind indicating whether the expression is an ICE.
22954//
22955// Note that to reduce code duplication, this helper does no evaluation
22956// itself; the caller checks whether the expression is evaluatable, and
22957// in the rare cases where CheckICE actually cares about the evaluated
22958// value, it calls into Evaluate.
22959
22960namespace {
22961
22962enum ICEKind {
22963 /// This expression is an ICE.
22964 IK_ICE,
22965 /// This expression is not an ICE, but if it isn't evaluated, it's
22966 /// a legal subexpression for an ICE. This return value is used to handle
22967 /// the comma operator in C99 mode, and non-constant subexpressions.
22968 IK_ICEIfUnevaluated,
22969 /// This expression is not an ICE, and is not a legal subexpression for one.
22970 IK_NotICE
22971};
22972
22973struct ICEDiag {
22974 ICEKind Kind;
22975 SourceLocation Loc;
22976
22977 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
22978};
22979
22980}
22981
22982static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
22983
22984static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
22985
22986static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
22987 Expr::EvalResult EVResult;
22988
22989 if (Ctx.getLangOpts().EnableNewConstInterp) {
22991 /*SProxy=*/nullptr);
22992 Settings.InConstantContext = true;
22993 if (!Ctx.getInterpContext().evaluateAsRValue(Settings, E, EVResult.Val) ||
22994 EVResult.HasSideEffects || !EVResult.Val.isInt())
22995 return ICEDiag(IK_NotICE, E->getBeginLoc());
22996 return NoDiag();
22997 }
22998
22999 Expr::EvalStatus Status;
23000 EvalInfo Info(Ctx, /*SProxy=*/nullptr, Status,
23002
23003 Info.InConstantContext = true;
23004 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
23005 !EVResult.Val.isInt())
23006 return ICEDiag(IK_NotICE, E->getBeginLoc());
23007
23008 return NoDiag();
23009}
23010
23011static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
23012 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
23014 return ICEDiag(IK_NotICE, E->getBeginLoc());
23015
23016 switch (E->getStmtClass()) {
23017#define ABSTRACT_STMT(Node)
23018#define STMT(Node, Base) case Expr::Node##Class:
23019#define EXPR(Node, Base)
23020#include "clang/AST/StmtNodes.inc"
23021 case Expr::PredefinedExprClass:
23022 case Expr::FloatingLiteralClass:
23023 case Expr::ImaginaryLiteralClass:
23024 case Expr::StringLiteralClass:
23025 case Expr::ArraySubscriptExprClass:
23026 case Expr::MatrixSingleSubscriptExprClass:
23027 case Expr::MatrixSubscriptExprClass:
23028 case Expr::ArraySectionExprClass:
23029 case Expr::OMPArrayShapingExprClass:
23030 case Expr::OMPIteratorExprClass:
23031 case Expr::CompoundAssignOperatorClass:
23032 case Expr::CompoundLiteralExprClass:
23033 case Expr::ExtVectorElementExprClass:
23034 case Expr::MatrixElementExprClass:
23035 case Expr::DesignatedInitExprClass:
23036 case Expr::ArrayInitLoopExprClass:
23037 case Expr::ArrayInitIndexExprClass:
23038 case Expr::NoInitExprClass:
23039 case Expr::DesignatedInitUpdateExprClass:
23040 case Expr::ImplicitValueInitExprClass:
23041 case Expr::ParenListExprClass:
23042 case Expr::VAArgExprClass:
23043 case Expr::AddrLabelExprClass:
23044 case Expr::StmtExprClass:
23045 case Expr::CXXMemberCallExprClass:
23046 case Expr::CUDAKernelCallExprClass:
23047 case Expr::CXXAddrspaceCastExprClass:
23048 case Expr::CXXDynamicCastExprClass:
23049 case Expr::CXXTypeidExprClass:
23050 case Expr::CXXUuidofExprClass:
23051 case Expr::MSPropertyRefExprClass:
23052 case Expr::MSPropertySubscriptExprClass:
23053 case Expr::CXXNullPtrLiteralExprClass:
23054 case Expr::UserDefinedLiteralClass:
23055 case Expr::CXXThisExprClass:
23056 case Expr::CXXThrowExprClass:
23057 case Expr::CXXNewExprClass:
23058 case Expr::CXXDeleteExprClass:
23059 case Expr::CXXPseudoDestructorExprClass:
23060 case Expr::UnresolvedLookupExprClass:
23061 case Expr::RecoveryExprClass:
23062 case Expr::DependentScopeDeclRefExprClass:
23063 case Expr::DependentTemplateIdExprClass:
23064 case Expr::CXXConstructExprClass:
23065 case Expr::CXXInheritedCtorInitExprClass:
23066 case Expr::CXXStdInitializerListExprClass:
23067 case Expr::CXXBindTemporaryExprClass:
23068 case Expr::ExprWithCleanupsClass:
23069 case Expr::CXXTemporaryObjectExprClass:
23070 case Expr::CXXUnresolvedConstructExprClass:
23071 case Expr::CXXDependentScopeMemberExprClass:
23072 case Expr::UnresolvedMemberExprClass:
23073 case Expr::ObjCStringLiteralClass:
23074 case Expr::ObjCBoxedExprClass:
23075 case Expr::ObjCArrayLiteralClass:
23076 case Expr::ObjCDictionaryLiteralClass:
23077 case Expr::ObjCEncodeExprClass:
23078 case Expr::ObjCMessageExprClass:
23079 case Expr::ObjCSelectorExprClass:
23080 case Expr::ObjCProtocolExprClass:
23081 case Expr::ObjCIvarRefExprClass:
23082 case Expr::ObjCPropertyRefExprClass:
23083 case Expr::ObjCSubscriptRefExprClass:
23084 case Expr::ObjCIsaExprClass:
23085 case Expr::ObjCAvailabilityCheckExprClass:
23086 case Expr::ShuffleVectorExprClass:
23087 case Expr::ConvertVectorExprClass:
23088 case Expr::BlockExprClass:
23089 case Expr::NoStmtClass:
23090 case Expr::OpaqueValueExprClass:
23091 case Expr::PackExpansionExprClass:
23092 case Expr::SubstNonTypeTemplateParmPackExprClass:
23093 case Expr::FunctionParmPackExprClass:
23094 case Expr::AsTypeExprClass:
23095 case Expr::ObjCIndirectCopyRestoreExprClass:
23096 case Expr::MaterializeTemporaryExprClass:
23097 case Expr::PseudoObjectExprClass:
23098 case Expr::AtomicExprClass:
23099 case Expr::LambdaExprClass:
23100 case Expr::CXXFoldExprClass:
23101 case Expr::CoawaitExprClass:
23102 case Expr::DependentCoawaitExprClass:
23103 case Expr::CoyieldExprClass:
23104 case Expr::SYCLUniqueStableNameExprClass:
23105 case Expr::CXXParenListInitExprClass:
23106 case Expr::HLSLOutArgExprClass:
23107 case Expr::CXXExpansionSelectExprClass:
23108 return ICEDiag(IK_NotICE, E->getBeginLoc());
23109
23110 case Expr::MemberExprClass: {
23111 if (Ctx.getLangOpts().C23) {
23112 const Expr *ME = E->IgnoreParenImpCasts();
23113 while (const auto *M = dyn_cast<MemberExpr>(ME)) {
23114 if (M->isArrow())
23115 return ICEDiag(IK_NotICE, E->getBeginLoc());
23116 ME = M->getBase()->IgnoreParenImpCasts();
23117 }
23118 const auto *DRE = dyn_cast<DeclRefExpr>(ME);
23119 if (DRE) {
23120 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
23121 VD && VD->isConstexpr())
23122 return CheckEvalInICE(E, Ctx);
23123 }
23124 }
23125 return ICEDiag(IK_NotICE, E->getBeginLoc());
23126 }
23127
23128 case Expr::InitListExprClass: {
23129 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
23130 // form "T x = { a };" is equivalent to "T x = a;".
23131 // Unless we're initializing a reference, T is a scalar as it is known to be
23132 // of integral or enumeration type.
23133 if (E->isPRValue())
23134 if (cast<InitListExpr>(E)->getNumInits() == 1)
23135 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
23136 return ICEDiag(IK_NotICE, E->getBeginLoc());
23137 }
23138
23139 case Expr::SizeOfPackExprClass:
23140 case Expr::GNUNullExprClass:
23141 case Expr::SourceLocExprClass:
23142 case Expr::EmbedExprClass:
23143 case Expr::OpenACCAsteriskSizeExprClass:
23144 return NoDiag();
23145
23146 case Expr::PackIndexingExprClass:
23147 return CheckICE(cast<PackIndexingExpr>(E)->getSelectedExpr(), Ctx);
23148
23149 case Expr::SubstNonTypeTemplateParmExprClass:
23150 return
23151 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
23152
23153 case Expr::ConstantExprClass:
23154 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
23155
23156 case Expr::ParenExprClass:
23157 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
23158 case Expr::GenericSelectionExprClass:
23159 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
23160 case Expr::IntegerLiteralClass:
23161 case Expr::FixedPointLiteralClass:
23162 case Expr::CharacterLiteralClass:
23163 case Expr::ObjCBoolLiteralExprClass:
23164 case Expr::CXXBoolLiteralExprClass:
23165 case Expr::CXXScalarValueInitExprClass:
23166 case Expr::TypeTraitExprClass:
23167 case Expr::ConceptSpecializationExprClass:
23168 case Expr::RequiresExprClass:
23169 case Expr::ArrayTypeTraitExprClass:
23170 case Expr::ExpressionTraitExprClass:
23171 case Expr::CXXNoexceptExprClass:
23172 case Expr::CXXReflectExprClass:
23173 return NoDiag();
23174 case Expr::CallExprClass:
23175 case Expr::CXXOperatorCallExprClass: {
23176 // C99 6.6/3 allows function calls within unevaluated subexpressions of
23177 // constant expressions, but they can never be ICEs because an ICE cannot
23178 // contain an operand of (pointer to) function type.
23179 const CallExpr *CE = cast<CallExpr>(E);
23180 if (CE->getBuiltinCallee())
23181 return CheckEvalInICE(E, Ctx);
23182 return ICEDiag(IK_NotICE, E->getBeginLoc());
23183 }
23184 case Expr::CXXRewrittenBinaryOperatorClass:
23185 return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(),
23186 Ctx);
23187 case Expr::DeclRefExprClass: {
23188 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
23189 if (isa<EnumConstantDecl>(D))
23190 return NoDiag();
23191
23192 // C++ and OpenCL (FIXME: spec reference?) allow reading const-qualified
23193 // integer variables in constant expressions:
23194 //
23195 // C++ 7.1.5.1p2
23196 // A variable of non-volatile const-qualified integral or enumeration
23197 // type initialized by an ICE can be used in ICEs.
23198 //
23199 // We sometimes use CheckICE to check the C++98 rules in C++11 mode. In
23200 // that mode, use of reference variables should not be allowed.
23201 const VarDecl *VD = dyn_cast<VarDecl>(D);
23202 if (VD && VD->isUsableInConstantExpressions(Ctx) &&
23203 !VD->getType()->isReferenceType())
23204 return NoDiag();
23205
23206 return ICEDiag(IK_NotICE, E->getBeginLoc());
23207 }
23208 case Expr::UnaryOperatorClass: {
23209 const UnaryOperator *Exp = cast<UnaryOperator>(E);
23210 switch (Exp->getOpcode()) {
23211 case UO_PostInc:
23212 case UO_PostDec:
23213 case UO_PreInc:
23214 case UO_PreDec:
23215 case UO_AddrOf:
23216 case UO_Deref:
23217 case UO_Coawait:
23218 // C99 6.6/3 allows increment and decrement within unevaluated
23219 // subexpressions of constant expressions, but they can never be ICEs
23220 // because an ICE cannot contain an lvalue operand.
23221 return ICEDiag(IK_NotICE, E->getBeginLoc());
23222 case UO_Extension:
23223 case UO_LNot:
23224 case UO_Plus:
23225 case UO_Minus:
23226 case UO_Not:
23227 case UO_Real:
23228 case UO_Imag:
23229 return CheckICE(Exp->getSubExpr(), Ctx);
23230 }
23231 llvm_unreachable("invalid unary operator class");
23232 }
23233 case Expr::OffsetOfExprClass: {
23234 // Note that per C99, offsetof must be an ICE. And AFAIK, using
23235 // EvaluateAsRValue matches the proposed gcc behavior for cases like
23236 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
23237 // compliance: we should warn earlier for offsetof expressions with
23238 // array subscripts that aren't ICEs, and if the array subscripts
23239 // are ICEs, the value of the offsetof must be an integer constant.
23240 return CheckEvalInICE(E, Ctx);
23241 }
23242 case Expr::UnaryExprOrTypeTraitExprClass: {
23244 if ((Exp->getKind() == UETT_SizeOf) &&
23246 return ICEDiag(IK_NotICE, E->getBeginLoc());
23247 if (Exp->getKind() == UETT_CountOf) {
23248 QualType ArgTy = Exp->getTypeOfArgument();
23249 if (ArgTy->isVariableArrayType()) {
23250 // We need to look whether the array is multidimensional. If it is,
23251 // then we want to check the size expression manually to see whether
23252 // it is an ICE or not.
23253 const auto *VAT = Ctx.getAsVariableArrayType(ArgTy);
23254 if (VAT->getElementType()->isArrayType())
23255 // Variable array size expression could be missing (e.g. int a[*][10])
23256 // In that case, it can't be a constant expression.
23257 return VAT->getSizeExpr() ? CheckICE(VAT->getSizeExpr(), Ctx)
23258 : ICEDiag(IK_NotICE, E->getBeginLoc());
23259
23260 // Otherwise, this is a regular VLA, which is definitely not an ICE.
23261 return ICEDiag(IK_NotICE, E->getBeginLoc());
23262 }
23263 }
23264 return NoDiag();
23265 }
23266 case Expr::BinaryOperatorClass: {
23267 const BinaryOperator *Exp = cast<BinaryOperator>(E);
23268 switch (Exp->getOpcode()) {
23269 case BO_PtrMemD:
23270 case BO_PtrMemI:
23271 case BO_Assign:
23272 case BO_MulAssign:
23273 case BO_DivAssign:
23274 case BO_RemAssign:
23275 case BO_AddAssign:
23276 case BO_SubAssign:
23277 case BO_ShlAssign:
23278 case BO_ShrAssign:
23279 case BO_AndAssign:
23280 case BO_XorAssign:
23281 case BO_OrAssign:
23282 // C99 6.6/3 allows assignments within unevaluated subexpressions of
23283 // constant expressions, but they can never be ICEs because an ICE cannot
23284 // contain an lvalue operand.
23285 return ICEDiag(IK_NotICE, E->getBeginLoc());
23286
23287 case BO_Mul:
23288 case BO_Div:
23289 case BO_Rem:
23290 case BO_Add:
23291 case BO_Sub:
23292 case BO_Shl:
23293 case BO_Shr:
23294 case BO_LT:
23295 case BO_GT:
23296 case BO_LE:
23297 case BO_GE:
23298 case BO_EQ:
23299 case BO_NE:
23300 case BO_And:
23301 case BO_Xor:
23302 case BO_Or:
23303 case BO_Comma:
23304 case BO_Cmp: {
23305 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
23306 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
23307 if (Exp->getOpcode() == BO_Div ||
23308 Exp->getOpcode() == BO_Rem) {
23309 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
23310 // we don't evaluate one.
23311 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
23312 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
23313 if (REval == 0)
23314 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
23315 if (REval.isSigned() && REval.isAllOnes()) {
23316 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
23317 if (LEval.isMinSignedValue())
23318 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
23319 }
23320 }
23321 }
23322 if (Exp->getOpcode() == BO_Comma) {
23323 if (Ctx.getLangOpts().C99) {
23324 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
23325 // if it isn't evaluated.
23326 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
23327 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
23328 } else {
23329 // In both C89 and C++, commas in ICEs are illegal.
23330 return ICEDiag(IK_NotICE, E->getBeginLoc());
23331 }
23332 }
23333 return Worst(LHSResult, RHSResult);
23334 }
23335 case BO_LAnd:
23336 case BO_LOr: {
23337 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
23338 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
23339 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
23340 // Rare case where the RHS has a comma "side-effect"; we need
23341 // to actually check the condition to see whether the side
23342 // with the comma is evaluated.
23343 if ((Exp->getOpcode() == BO_LAnd) !=
23344 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
23345 return RHSResult;
23346 return NoDiag();
23347 }
23348
23349 return Worst(LHSResult, RHSResult);
23350 }
23351 }
23352 llvm_unreachable("invalid binary operator kind");
23353 }
23354 case Expr::ImplicitCastExprClass:
23355 case Expr::CStyleCastExprClass:
23356 case Expr::CXXFunctionalCastExprClass:
23357 case Expr::CXXStaticCastExprClass:
23358 case Expr::CXXReinterpretCastExprClass:
23359 case Expr::CXXConstCastExprClass:
23360 case Expr::ObjCBridgedCastExprClass: {
23361 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
23362 if (isa<ExplicitCastExpr>(E)) {
23363 if (const FloatingLiteral *FL
23364 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
23365 unsigned DestWidth = Ctx.getIntWidth(E->getType());
23366 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
23367 APSInt IgnoredVal(DestWidth, !DestSigned);
23368 bool Ignored;
23369 // If the value does not fit in the destination type, the behavior is
23370 // undefined, so we are not required to treat it as a constant
23371 // expression.
23372 if (FL->getValue().convertToInteger(IgnoredVal,
23373 llvm::APFloat::rmTowardZero,
23374 &Ignored) & APFloat::opInvalidOp)
23375 return ICEDiag(IK_NotICE, E->getBeginLoc());
23376 return NoDiag();
23377 }
23378 }
23379 switch (cast<CastExpr>(E)->getCastKind()) {
23380 case CK_LValueToRValue:
23381 case CK_AtomicToNonAtomic:
23382 case CK_NonAtomicToAtomic:
23383 case CK_NoOp:
23384 case CK_IntegralToBoolean:
23385 case CK_IntegralCast:
23386 return CheckICE(SubExpr, Ctx);
23387 default:
23388 return ICEDiag(IK_NotICE, E->getBeginLoc());
23389 }
23390 }
23391 case Expr::BinaryConditionalOperatorClass: {
23393 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
23394 if (CommonResult.Kind == IK_NotICE) return CommonResult;
23395 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
23396 if (FalseResult.Kind == IK_NotICE) return FalseResult;
23397 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
23398 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
23399 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
23400 return FalseResult;
23401 }
23402 case Expr::ConditionalOperatorClass: {
23404 // If the condition (ignoring parens) is a __builtin_constant_p call,
23405 // then only the true side is actually considered in an integer constant
23406 // expression, and it is fully evaluated. This is an important GNU
23407 // extension. See GCC PR38377 for discussion.
23408 if (const CallExpr *CallCE
23409 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
23410 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
23411 return CheckEvalInICE(E, Ctx);
23412 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
23413 if (CondResult.Kind == IK_NotICE)
23414 return CondResult;
23415
23416 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
23417 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
23418
23419 if (TrueResult.Kind == IK_NotICE)
23420 return TrueResult;
23421 if (FalseResult.Kind == IK_NotICE)
23422 return FalseResult;
23423 if (CondResult.Kind == IK_ICEIfUnevaluated)
23424 return CondResult;
23425 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
23426 return NoDiag();
23427 // Rare case where the diagnostics depend on which side is evaluated
23428 // Note that if we get here, CondResult is 0, and at least one of
23429 // TrueResult and FalseResult is non-zero.
23430 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
23431 return FalseResult;
23432 return TrueResult;
23433 }
23434 case Expr::CXXDefaultArgExprClass:
23435 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
23436 case Expr::CXXDefaultInitExprClass:
23437 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
23438 case Expr::ChooseExprClass: {
23439 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
23440 }
23441 case Expr::BuiltinBitCastExprClass: {
23442 if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
23443 return ICEDiag(IK_NotICE, E->getBeginLoc());
23444 return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
23445 }
23446 }
23447
23448 llvm_unreachable("Invalid StmtClass!");
23449}
23450
23451/// Evaluate an expression as a C++11 integral constant expression.
23452static bool
23454 llvm::APSInt *Value,
23455 bool AllowRelaxedEval = false) {
23457 return false;
23458
23460 if (!E->isCXX11ConstantExpr(Ctx, Result, AllowRelaxedEval))
23461 return false;
23462
23463 if (!Result.isInt())
23464 return false;
23465
23466 if (Value) *Value = Result.getInt();
23467 return true;
23468}
23469
23471 assert(!isValueDependent() &&
23472 "Expression evaluator can't be called on a dependent expression.");
23473
23474 ExprTimeTraceScope TimeScope(this, Ctx, "isIntegerConstantExpr");
23475
23476 if (Ctx.getLangOpts().CPlusPlus11)
23477 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr);
23478
23479 ICEDiag D = CheckICE(this, Ctx);
23480 if (D.Kind != IK_ICE)
23481 return false;
23482 return true;
23483}
23484
23485std::optional<llvm::APSInt>
23487 bool AllowRelaxedEval) const {
23488 if (isValueDependent()) {
23489 // Expression evaluator can't succeed on a dependent expression.
23490 return std::nullopt;
23491 }
23492
23493 if (Ctx.getLangOpts().CPlusPlus11) {
23494 APSInt Value;
23496 AllowRelaxedEval))
23497 return Value;
23498 return std::nullopt;
23499 }
23500
23501 if (!isIntegerConstantExpr(Ctx))
23502 return std::nullopt;
23503
23504 // The only possible side-effects here are due to UB discovered in the
23505 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
23506 // required to treat the expression as an ICE, so we produce the folded
23507 // value.
23509
23510 if (Ctx.getLangOpts().EnableNewConstInterp) {
23512 /*SProxy=*/nullptr);
23513 Settings.InConstantContext = true;
23514 if (!Ctx.getInterpContext().evaluateAsRValue(Settings, this,
23515 ExprResult.Val))
23516 llvm_unreachable("ICE cannot be evaluated!");
23517 return ExprResult.Val.getInt();
23518 }
23519
23520 Expr::EvalStatus Status;
23521 EvalInfo Info(Ctx, /*SProxy=*/nullptr, Status,
23523 Info.InConstantContext = true;
23524
23525 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
23526 llvm_unreachable("ICE cannot be evaluated!");
23527
23528 return ExprResult.Val.getInt();
23529}
23530
23532 assert(!isValueDependent() &&
23533 "Expression evaluator can't be called on a dependent expression.");
23534
23535 return CheckICE(this, Ctx).Kind == IK_ICE;
23536}
23537
23539 bool AllowRelaxedEval) const {
23540 assert(!isValueDependent() &&
23541 "Expression evaluator can't be called on a dependent expression.");
23542
23543 // We support this checking in C++98 mode in order to diagnose compatibility
23544 // issues.
23545 assert(Ctx.getLangOpts().CPlusPlus);
23546
23547 bool IsConst;
23548 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst) && Result.hasValue())
23549 return true;
23550
23551 bool IsConstExpr;
23552 Expr::EvalStatus Status;
23554 Status.ExtendedDiag = AllowRelaxedEval ? &MSRelaxedDiag : nullptr;
23555
23556 if (Ctx.getLangOpts().EnableNewConstInterp) {
23558 /*SProxy=*/nullptr);
23559 IsConstExpr =
23560 Ctx.getInterpContext().evaluateAsRValue(Settings, this, Result);
23561 } else {
23562 // Build evaluation settings.
23563 EvalInfo Info(Ctx, /*SProxy=*/nullptr, Status,
23565 IsConstExpr =
23566 ::EvaluateAsRValue(Info, this, Result) &&
23567 // NOTE: We don't produce a diagnostic for this, but the callers that
23568 // call us on arbitrary full-expressions should generally not care.
23569 Info.discardCleanups() && !Status.HasSideEffects;
23570 }
23571 return IsConstExpr && !Status.DiagEmitted;
23572}
23573
23575 const FunctionDecl *Callee,
23577 const Expr *This) const {
23578 assert(!isValueDependent() &&
23579 "Expression evaluator can't be called on a dependent expression.");
23580
23581 llvm::TimeTraceScope TimeScope("EvaluateWithSubstitution", [&] {
23582 std::string Name;
23583 llvm::raw_string_ostream OS(Name);
23584 Callee->getNameForDiagnostic(OS, Ctx.getPrintingPolicy(),
23585 /*Qualified=*/true);
23586 return Name;
23587 });
23588
23589 Expr::EvalStatus Status;
23590
23591 if (Ctx.getLangOpts().EnableNewConstInterp) {
23593 Status, /*SProxy=*/nullptr);
23594 Settings.InConstantContext = true;
23595 if (std::optional<bool> BoolResult =
23596 Ctx.getInterpContext().evaluateWithSubstitution(Settings, Callee,
23597 Args, This, this)) {
23598 Value = APValue(APSInt(APInt(1, static_cast<uint64_t>(*BoolResult))));
23599 return true;
23600 }
23601 return false;
23602 }
23603
23604 EvalInfo Info(Ctx, /*SProxy=*/nullptr, Status,
23606 Info.InConstantContext = true;
23607
23608 LValue ThisVal;
23609 const LValue *ThisPtr = nullptr;
23610 if (This) {
23611#ifndef NDEBUG
23612 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
23613 assert(MD && "Don't provide `this` for non-methods.");
23614 assert(MD->isImplicitObjectMemberFunction() &&
23615 "Don't provide `this` for methods without an implicit object.");
23616#endif
23617 if (!This->isValueDependent() &&
23618 EvaluateObjectArgument(Info, This, ThisVal) &&
23619 !Info.EvalStatus.HasSideEffects)
23620 ThisPtr = &ThisVal;
23621
23622 // Ignore any side-effects from a failed evaluation. This is safe because
23623 // they can't interfere with any other argument evaluation.
23624 Info.EvalStatus.HasSideEffects = false;
23625 }
23626
23627 CallRef Call = Info.CurrentCall->createCall(Callee);
23628 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
23629 I != E; ++I) {
23630 unsigned Idx = I - Args.begin();
23631 if (Idx >= Callee->getNumParams())
23632 break;
23633 const ParmVarDecl *PVD = Callee->getParamDecl(Idx);
23634 if ((*I)->isValueDependent() ||
23635 !EvaluateCallArg(PVD, *I, Call, Info) ||
23636 Info.EvalStatus.HasSideEffects) {
23637 // If evaluation fails, throw away the argument entirely.
23638 if (APValue *Slot = Info.getParamSlot(Call, PVD))
23639 *Slot = APValue();
23640 }
23641
23642 // Ignore any side-effects from a failed evaluation. This is safe because
23643 // they can't interfere with any other argument evaluation.
23644 Info.EvalStatus.HasSideEffects = false;
23645 }
23646
23647 // Parameter cleanups happen in the caller and are not part of this
23648 // evaluation.
23649 Info.discardCleanups();
23650 Info.EvalStatus.HasSideEffects = false;
23651
23652 // Build fake call to Callee.
23653 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, This,
23654 Call);
23655 // FIXME: Missing ExprWithCleanups in enable_if conditions?
23656 FullExpressionRAII Scope(Info);
23657 return Evaluate(Value, Info, this) && Scope.destroy() &&
23658 !Info.EvalStatus.HasSideEffects;
23659}
23660
23663 PartialDiagnosticAt> &Diags) {
23664 // FIXME: It would be useful to check constexpr function templates, but at the
23665 // moment the constant expression evaluator cannot cope with the non-rigorous
23666 // ASTs which we build for dependent expressions.
23667 if (FD->isDependentContext())
23668 return true;
23669
23670 llvm::TimeTraceScope TimeScope("isPotentialConstantExpr", [&] {
23671 std::string Name;
23672 llvm::raw_string_ostream OS(Name);
23674 /*Qualified=*/true);
23675 return Name;
23676 });
23677
23678 const ASTContext &Ctx = FD->getASTContext();
23679 Expr::EvalStatus Status;
23680 Status.Diag = &Diags;
23681
23682 // The constexpr VM attempts to compile all methods to bytecode here.
23683 if (Ctx.getLangOpts().EnableNewConstInterp) {
23685 /*SProxy=*/nullptr);
23686 Settings.InConstantContext = true;
23688 Ctx.getInterpContext().isPotentialConstantExpr(Settings, FD);
23689 return Diags.empty();
23690 }
23691
23692 EvalInfo Info(Ctx, /*SProxy=*/nullptr, Status,
23694 Info.InConstantContext = true;
23695 Info.CheckingPotentialConstantExpression = true;
23696
23697 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
23698 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
23699
23700 // Fabricate an arbitrary expression on the stack and pretend that it
23701 // is a temporary being used as the 'this' pointer.
23702 LValue This;
23703 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getCanonicalTagType(RD)
23704 : Info.Ctx.IntTy);
23705 This.set({&VIE, Info.CurrentCall->Index});
23706
23708
23709 APValue Scratch;
23710 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
23711 // Evaluate the call as a constant initializer, to allow the construction
23712 // of objects of non-literal types.
23713 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
23714 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
23715 } else {
23716 SourceLocation Loc = FD->getLocation();
23718 Loc, FD, (MD && MD->isImplicitObjectMemberFunction()) ? &This : nullptr,
23719 &VIE, Args, CallRef(), FD->getBody(), Info, Scratch,
23720 /*ResultSlot=*/nullptr);
23721 }
23722
23723 return Diags.empty();
23724}
23725
23727 const FunctionDecl *FD,
23729 PartialDiagnosticAt> &Diags) {
23730 assert(!E->isValueDependent() &&
23731 "Expression evaluator can't be called on a dependent expression.");
23732
23733 const ASTContext &Ctx = FD->getASTContext();
23734 Expr::EvalStatus Status;
23735 Status.Diag = &Diags;
23736
23737 if (Ctx.getLangOpts().EnableNewConstInterp) {
23739 Status, /*SProxy=*/nullptr);
23740 Settings.InConstantContext = true;
23743 return Diags.empty();
23744 }
23745
23746 EvalInfo Info(Ctx, /*SProxy=*/nullptr, Status,
23748 Info.InConstantContext = true;
23749 Info.CheckingPotentialConstantExpression = true;
23750
23751 // Fabricate a call stack frame to give the arguments a plausible cover story.
23752 CallStackFrame Frame(Info, SourceLocation(), FD, /*This=*/nullptr,
23753 /*CallExpr=*/nullptr, CallRef());
23754
23755 APValue ResultScratch;
23756 Evaluate(ResultScratch, Info, E);
23757 return Diags.empty();
23758}
23759
23760std::optional<uint64_t> Expr::tryEvaluateObjectSize(const ASTContext &Ctx,
23761 unsigned Type) const {
23762 if (!getType()->isPointerType())
23763 return std::nullopt;
23764
23765 Expr::EvalStatus Status;
23766 if (Ctx.getLangOpts().EnableNewConstInterp) {
23768 /*SProxy=*/nullptr);
23769 return Ctx.getInterpContext().tryEvaluateObjectSize(Settings, this, Type,
23770 /*IsDynamic=*/false);
23771 }
23772
23773 EvalInfo Info(Ctx, /*SProxy=*/nullptr, Status, EvaluationMode::ConstantFold);
23774 return tryEvaluateBuiltinObjectSize(this, Type, Info);
23775}
23776
23777static std::optional<uint64_t>
23778EvaluateBuiltinStrLen(const Expr *E, EvalInfo &Info,
23779 std::string *StringResult) {
23780 if (!E->getType()->hasPointerRepresentation() || !E->isPRValue())
23781 return std::nullopt;
23782
23783 LValue String;
23784
23785 if (!EvaluatePointer(E, String, Info))
23786 return std::nullopt;
23787
23788 // Fast path: if it's a string literal, search the string value.
23789 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
23790 String.getLValueBase().dyn_cast<const Expr *>())) {
23791 StringRef Str = S->getBytes();
23792 int64_t Off = String.Offset.getQuantity();
23793 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size()) {
23794 UnsignedOrNone ZeroIndex = S->findZeroCodeUnit(Off);
23795 if (StringResult) {
23796 if (ZeroIndex)
23797 Str = Str.substr(Off, *ZeroIndex);
23798 *StringResult = Str;
23799 }
23800
23801 return ZeroIndex.value_or(Str.size());
23802 }
23803 // For an invalid index, fall through to the offset handling below.
23804 }
23805
23806 QualType CharTy = E->getType()->getPointeeType();
23807 // Slow path: scan the bytes of the string looking for the terminating 0.
23808 for (uint64_t Strlen = 0; /**/; ++Strlen) {
23809 APValue Char;
23810 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
23811 !Char.isInt())
23812 return std::nullopt;
23813 if (!Char.getInt())
23814 return Strlen;
23815 else if (StringResult)
23816 StringResult->push_back(Char.getInt().getExtValue());
23817 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
23818 return std::nullopt;
23819 }
23820}
23821
23822std::optional<std::string> Expr::tryEvaluateString(ASTContext &Ctx) const {
23823 Expr::EvalStatus Status;
23824 std::string StringResult;
23825
23826 if (Ctx.getLangOpts().EnableNewConstInterp) {
23828 /*SProxy=*/nullptr);
23829 if (!Ctx.getInterpContext().evaluateString(Settings, this, StringResult))
23830 return std::nullopt;
23831 return StringResult;
23832 }
23833
23834 EvalInfo Info(Ctx, /*SProxy=*/nullptr, Status, EvaluationMode::ConstantFold);
23835 if (EvaluateBuiltinStrLen(this, Info, &StringResult))
23836 return StringResult;
23837 return std::nullopt;
23838}
23839
23840template <typename T>
23842 const Expr *SizeExpression,
23843 const Expr *PtrExpression,
23844 ASTContext &Ctx, SemaProxy &SProxy,
23845 Expr::EvalResult &Status) {
23846 if (Ctx.getLangOpts().EnableNewConstInterp) {
23848 &SProxy);
23849 Settings.InConstantContext = true;
23850 return Ctx.getInterpContext().evaluateCharRange(Settings, SizeExpression,
23851 PtrExpression, Result);
23852 }
23853
23854 EvalInfo Info(Ctx, &SProxy, Status, EvaluationMode::ConstantExpression);
23855 Info.InConstantContext = true;
23856
23857 LValue String;
23858 FullExpressionRAII Scope(Info);
23859 APSInt SizeValue;
23860 if (!::EvaluateInteger(SizeExpression, SizeValue, Info))
23861 return false;
23862
23863 uint64_t Size = SizeValue.getZExtValue();
23864
23865 // FIXME: better protect against invalid or excessive sizes
23866 if constexpr (std::is_same_v<APValue, T>)
23867 Result = APValue(APValue::UninitArray{}, Size, Size);
23868 else {
23869 if (Size < Result.max_size())
23870 Result.reserve(Size);
23871 }
23872 if (!::EvaluatePointer(PtrExpression, String, Info))
23873 return false;
23874
23875 QualType CharTy = PtrExpression->getType()->getPointeeType();
23876 for (uint64_t I = 0; I < Size; ++I) {
23877 APValue Char;
23878 if (!handleLValueToRValueConversion(Info, PtrExpression, CharTy, String,
23879 Char))
23880 return false;
23881
23882 if constexpr (std::is_same_v<APValue, T>) {
23883 Result.getArrayInitializedElt(I) = std::move(Char);
23884 } else {
23885 APSInt C = Char.getInt();
23886
23887 assert(C.getBitWidth() <= 8 &&
23888 "string element not representable in char");
23889
23890 Result.push_back(static_cast<char>(C.getExtValue()));
23891 }
23892
23893 if (!HandleLValueArrayAdjustment(Info, PtrExpression, String, CharTy, 1))
23894 return false;
23895 }
23896
23897 return Scope.destroy() && CheckMemoryLeaks(Info);
23898}
23899
23901 const Expr *SizeExpression,
23902 const Expr *PtrExpression, ASTContext &Ctx,
23903 SemaProxy &SProxy,
23904 EvalResult &Status) const {
23905 return EvaluateCharRangeAsStringImpl(this, Result, SizeExpression,
23906 PtrExpression, Ctx, SProxy, Status);
23907}
23908
23910 const Expr *SizeExpression,
23911 const Expr *PtrExpression, ASTContext &Ctx,
23912 SemaProxy &SProxy,
23913 EvalResult &Status) const {
23914 return EvaluateCharRangeAsStringImpl(this, Result, SizeExpression,
23915 PtrExpression, Ctx, SProxy, Status);
23916}
23917
23918std::optional<uint64_t> Expr::tryEvaluateStrLen(const ASTContext &Ctx) const {
23919 Expr::EvalStatus Status;
23920
23921 if (Ctx.getLangOpts().EnableNewConstInterp) {
23923 /*SProxy=*/nullptr);
23924 return Ctx.getInterpContext().evaluateStrlen(Settings, this);
23925 }
23926 EvalInfo Info(Ctx, /*SProxy=*/nullptr, Status, EvaluationMode::ConstantFold);
23927 return EvaluateBuiltinStrLen(this, Info);
23928}
23929
23930namespace {
23931struct IsWithinLifetimeHandler {
23932 EvalInfo &Info;
23933 static constexpr AccessKinds AccessKind = AccessKinds::AK_IsWithinLifetime;
23934 using result_type = std::optional<bool>;
23935 std::optional<bool> failed() { return std::nullopt; }
23936 template <typename T>
23937 std::optional<bool> found(T &Subobj, QualType SubobjType,
23939 return true;
23940 }
23941 template <typename T>
23942 std::optional<bool> found(T &Subobj, QualType SubobjType) {
23943 return true;
23944 }
23945};
23946
23947std::optional<bool> EvaluateBuiltinIsWithinLifetime(IntExprEvaluator &IEE,
23948 const CallExpr *E) {
23949 EvalInfo &Info = IEE.Info;
23950 // Sometimes this is called during some sorts of constant folding / early
23951 // evaluation. These are meant for non-constant expressions and are not
23952 // necessary since this consteval builtin will never be evaluated at runtime.
23953 // Just fail to evaluate when not in a constant context.
23954 if (!Info.InConstantContext)
23955 return std::nullopt;
23956 assert(E->getBuiltinCallee() == Builtin::BI__builtin_is_within_lifetime);
23957 const Expr *Arg = E->getArg(0);
23958 if (Arg->isValueDependent())
23959 return std::nullopt;
23960 LValue Val;
23961 if (!EvaluatePointer(Arg, Val, Info))
23962 return std::nullopt;
23963
23964 if (Val.allowConstexprUnknown())
23965 return true;
23966
23967 auto Error = [&](int Diag) {
23968 bool CalledFromStd = false;
23969 const auto *Callee = Info.CurrentCall->getCallee();
23970 if (Callee && Callee->isInStdNamespace()) {
23971 const IdentifierInfo *Identifier = Callee->getIdentifier();
23972 CalledFromStd = Identifier && Identifier->isStr("is_within_lifetime");
23973 }
23974 Info.CCEDiag(CalledFromStd ? Info.CurrentCall->getCallRange().getBegin()
23975 : E->getExprLoc(),
23976 diag::err_invalid_is_within_lifetime)
23977 << (CalledFromStd ? "std::is_within_lifetime"
23978 : "__builtin_is_within_lifetime")
23979 << Diag;
23980 return std::nullopt;
23981 };
23982 // C++2c [meta.const.eval]p4:
23983 // During the evaluation of an expression E as a core constant expression, a
23984 // call to this function is ill-formed unless p points to an object that is
23985 // usable in constant expressions or whose complete object's lifetime began
23986 // within E.
23987
23988 // Make sure it points to an object
23989 // nullptr does not point to an object
23990 if (Val.isNullPointer() || Val.getLValueBase().isNull())
23991 return Error(0);
23992 QualType T = Val.getLValueBase().getType();
23993 assert(!T->isFunctionType() &&
23994 "Pointers to functions should have been typed as function pointers "
23995 "which would have been rejected earlier");
23996 assert(T->isObjectType());
23997 // Hypothetical array element is not an object
23998 if (Val.getLValueDesignator().isOnePastTheEnd())
23999 return Error(1);
24000 assert(Val.getLValueDesignator().isValidSubobject() &&
24001 "Unchecked case for valid subobject");
24002 // All other ill-formed values should have failed EvaluatePointer, so the
24003 // object should be a pointer to an object that is usable in a constant
24004 // expression or whose complete lifetime began within the expression
24005 CompleteObject CO =
24006 findCompleteObject(Info, E, AccessKinds::AK_IsWithinLifetime, Val, T);
24007 // The lifetime hasn't begun yet if we are still evaluating the
24008 // initializer ([basic.life]p(1.2))
24009 if (Info.EvaluatingDeclValue && CO.Value == Info.EvaluatingDeclValue)
24010 return Error(2);
24011
24012 if (!CO)
24013 return false;
24014 IsWithinLifetimeHandler handler{Info};
24015 return findSubobject(Info, E, CO, Val.getLValueDesignator(), handler);
24016}
24017} // 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:26
static Decl::Kind getKind(const Decl *D)
bool isTemplateArgument(ConstantExprKind Kind)
bool isOpaqueConstantCall(const CallExpr *E)
Should this call expression be treated as forming an opaque constant?
bool isForManglingOnly(ConstantExprKind Kind)
Determines whether the given kind of constant expression is only ever used for name mangling.
GCCTypeClass
Values returned by __builtin_classify_type, chosen to match the values produced by GCC's builtin.
static bool isRead(AccessKinds AK)
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)
const Expr * ignorePointerCastsAndParens(const Expr *E)
A more selective version of E->IgnoreParenCasts for tryEvaluateBuiltinObjectSize. This ignores some c...
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 EvaluateReflection(const Expr *E, APValue &Result, EvalInfo &Info)
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 bool doEvaluateAsRValue(const Expr *E, Expr::EvalResult &Result, const ASTContext &Ctx, SemaProxy *SProxy, bool InConstantContext)
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)
bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD)
Determine whether a type would actually be read by an lvalue-to-rvalue conversion.
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 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 std::optional< DynAlloc * > CheckDeleteKind(EvalInfo &Info, const Expr *E, const LValue &Pointer, DynAllocKind DeallocKind)
Check that the given object is a suitable pointer to a heap allocation that still exists and is of th...
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 bool doEvaluateDestruction(const VarDecl *VD, SemaProxy *SProxy, bool IsConstantDestruction, SmallVectorImpl< PartialDiagnosticAt > &Notes)
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 IsOpaqueConstantCall(const LValue &LVal)
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 void TryInstantiateFunctionBeforeCall(const FunctionDecl *FD, EvalInfo &Info, SourceLocation Loc)
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 doEvaluateInitializer(const ASTContext &Ctx, SemaProxy *SProxy, const VarDecl *VD, const Expr *E, Expr::EvalResult &EStatus, bool IsConstantInitialization)
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 EvaluateComparisonResult(EvalInfo &Info, const Expr *E, ComparisonCategoryResult CCR, APValue &Result)
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....
bool isGlobalLValue(const ValueDecl *D, const Expr *E)
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 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 EvaluateDestruction(const ASTContext &Ctx, SemaProxy *SProxy, APValue::LValueBase Base, APValue DestroyedValue, QualType Type, SourceLocation Loc, Expr::EvalStatus &EStatus, bool IsConstantDestruction)
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 EvaluateReflectionMetafunctionBuiltin(EvalInfo &Info, const CallExpr *E, unsigned BuiltinOp, APValue &Result)
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 doEvaluateConstantExpr(Expr::EvalResult &Result, const ASTContext &Ctx, SemaProxy *SProxy, const Expr *E, ConstantExprKind Kind)
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...
bool FunctionDefinitionCanBeLazilyInstantiated(const FunctionDecl *FD)
Whether we can instantiate FD during constant evaluation.
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 bool EvaluateCharRangeAsStringImpl(const Expr *, T &Result, const Expr *SizeExpression, const Expr *PtrExpression, ASTContext &Ctx, SemaProxy &SProxy, Expr::EvalResult &Status)
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 handleDefaultInitValue(QualType T, APValue &Result, bool IsCompleteClass=true)
Get the value to use for a default-initialized object of type T.
static bool EvaluateStdcLoad8(EvalInfo &Info, const CallExpr *E, bool IsBE, bool IsAligned, APSInt &Result)
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 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 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 isUserWritingOffTheEnd(const ASTContext &Ctx, const Pointer &Ptr, bool InvalidBase)
Does Ptr point to the last object AND to a flexible array member?
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.
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)
static bool hasLayout(const RecordDecl *D)
Whether layout (offset and size) information can be queried for D.
a trap message and trap category.
llvm::APInt getValue() const
QualType getType() const
Definition APValue.cpp:123
unsigned getVersion() const
Definition APValue.cpp:173
QualType getDynamicAllocType() const
Definition APValue.cpp:182
QualType getTypeInfoType() const
Definition APValue.cpp:177
static LValueBase getTypeInfo(TypeInfoLValue LV, QualType TypeInfo)
Definition APValue.cpp:115
static LValueBase getDynamicAlloc(DynamicAllocLValue LV, QualType Type)
Definition APValue.cpp:107
A non-discriminated union of a base, field, or array index.
Definition APValue.h:245
BaseOrMemberType getAsBaseOrMember() const
Definition APValue.h:259
static LValuePathEntry ArrayIndex(uint64_t Index)
Definition APValue.h:253
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:158
bool hasArrayFiller() const
Definition APValue.h:699
const LValueBase getLValueBase() const
Definition APValue.cpp:1126
APValue & getArrayInitializedElt(unsigned I)
Definition APValue.h:691
void swap(APValue &RHS)
Swaps the contents of this and the given APValue.
Definition APValue.cpp:539
APSInt & getInt()
Definition APValue.h:573
APValue & getStructField(unsigned i)
Definition APValue.h:736
unsigned getMatrixNumColumns() const
Definition APValue.h:664
const FieldDecl * getUnionField() const
Definition APValue.h:757
bool isVector() const
Definition APValue.h:555
APSInt & getComplexIntImag()
Definition APValue.h:611
bool isAbsent() const
Definition APValue.h:545
bool isComplexInt() const
Definition APValue.h:552
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:242
ValueKind getKind() const
Definition APValue.h:537
ReflectionKind getReflectionOperandKind() const
Definition APValue.h:782
APValue & getStructVirtualBase(unsigned i)
Definition APValue.h:741
unsigned getArrayInitializedElts() const
Definition APValue.h:710
static APValue IndeterminateValue()
Definition APValue.h:508
bool isFloat() const
Definition APValue.h:550
void Profile(llvm::FoldingSetNodeID &ID) const
profile this value.
Definition APValue.cpp:585
unsigned getStructNumBases() const
Definition APValue.h:719
APFixedPoint & getFixedPoint()
Definition APValue.h:595
bool hasValue() const
Definition APValue.h:547
bool hasLValuePath() const
Definition APValue.cpp:1141
const ValueDecl * getMemberPointerDecl() const
Definition APValue.cpp:1209
APValue & getUnionValue()
Definition APValue.h:761
CharUnits & getLValueOffset()
Definition APValue.cpp:1136
void printPretty(raw_ostream &OS, const ASTContext &Ctx, QualType Ty) const
Definition APValue.cpp:810
bool isComplexFloat() const
Definition APValue.h:553
APValue & getVectorElt(unsigned I)
Definition APValue.h:647
APValue & getArrayFiller()
Definition APValue.h:702
unsigned getVectorLength() const
Definition APValue.h:655
bool isLValue() const
Definition APValue.h:554
void setUnion(const FieldDecl *Field, const APValue &Value)
Definition APValue.cpp:1202
bool isIndeterminate() const
Definition APValue.h:546
unsigned getMatrixNumRows() const
Definition APValue.h:660
bool isInt() const
Definition APValue.h:549
unsigned getArraySize() const
Definition APValue.h:714
bool allowConstexprUnknown() const
Definition APValue.h:378
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition APValue.cpp:1099
bool isFixedPoint() const
Definition APValue.h:551
APValue & getMatrixElt(unsigned Idx)
Definition APValue.h:671
@ Indeterminate
This object has an indeterminate value (C++ [basic.indet]).
Definition APValue.h:167
@ None
There is no such object (it's outside its lifetime).
Definition APValue.h:165
bool isStruct() const
Definition APValue.h:558
APSInt & getComplexIntReal()
Definition APValue.h:603
APFloat & getComplexFloatImag()
Definition APValue.h:627
APFloat & getComplexFloatReal()
Definition APValue.h:619
APFloat & getFloat()
Definition APValue.h:587
APValue & getStructBase(unsigned i)
Definition APValue.h:731
bool isMatrix() const
Definition APValue.h:556
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:245
SourceManager & getSourceManager()
Definition ASTContext.h:913
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:854
const LangOptions & getLangOpts() const
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
const TargetInfo * getAuxTargetInfo() const
Definition ASTContext.h:972
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:905
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:971
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
CanQualType getCanonicalTagType(const TagDecl *TD) const
unsigned getTypeAlign(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in bits.
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:4642
OpaqueValueExpr * getCommonExpr() const
Get the common subexpression shared by all initializations (the source array).
Definition Expr.h:6069
Expr * getSubExpr() const
Get the initializer to use for each array element.
Definition Expr.h:6074
Expr * getLHS()
An array access can be written A[4] or 4[A] (both are equivalent).
Definition Expr.h:2819
uint64_t getValue() const
Definition ExprCXX.h:3059
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3820
QualType getElementType() const
Definition TypeBase.h:3832
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition TypeBase.h:8394
Attr - This represents one attribute.
Definition Attr.h:47
BinaryConditionalOperator - The GNU extension to the conditional operator which allows the middle ope...
Definition Expr.h:4522
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression which will be evaluated if the condition evaluates to false; ...
Definition Expr.h:4576
OpaqueValueExpr * getOpaqueValue() const
getOpaqueValue - Return the opaque value placeholder.
Definition Expr.h:4560
Expr * getCommon() const
getCommon - Return the common expression, written to the left of the condition.
Definition Expr.h:4557
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:4107
static bool isLogicalOp(Opcode Opc)
Definition Expr.h:4240
Expr * getLHS() const
Definition Expr.h:4157
static bool isRelationalOp(Opcode Opc)
Definition Expr.h:4201
static bool isComparisonOp(Opcode Opc)
Definition Expr.h:4207
static Opcode getOpForCompoundAssignment(Opcode Opc)
Definition Expr.h:4254
SourceLocation getExprLoc() const
Definition Expr.h:4148
Expr * getRHS() const
Definition Expr.h:4159
static bool isAdditiveOp(Opcode Opc)
Definition Expr.h:4193
static bool isPtrMemOp(Opcode Opc)
predicates to categorize the respective opcodes.
Definition Expr.h:4184
static bool isAssignmentOp(Opcode Opc)
Definition Expr.h:4243
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operator.
Definition Expr.h:4320
Opcode getOpcode() const
Definition Expr.h:4152
static bool isEqualityOp(Opcode Opc)
Definition Expr.h:4204
bool hasCaptures() const
True if this block (or its nested blocks) captures anything of local storage from its enclosing scope...
Definition Decl.h:4975
const BlockDecl * getBlockDecl() const
Definition Expr.h:6770
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:445
unsigned getAuxBuiltinID(unsigned ID) const
Return real builtin ID (i.e.
Definition Builtins.h:451
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:1520
bool getValue() const
Definition ExprCXX.h:745
Represents a call to a C++ constructor.
Definition ExprCXX.h:1553
bool isElidable() const
Whether this construction is elidable.
Definition ExprCXX.h:1622
Expr * getArg(unsigned Arg)
Return the specified argument.
Definition ExprCXX.h:1696
bool requiresZeroInitialization() const
Whether this construction first requires zero-initialization before the initializer is called.
Definition ExprCXX.h:1655
SourceLocation getBeginLoc() const LLVM_READONLY
Definition ExprCXX.cpp:605
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition ExprCXX.h:1616
unsigned getNumArgs() const
Return the number of arguments to the constructor call.
Definition ExprCXX.h:1693
Represents a C++ constructor within a class.
Definition DeclCXX.h:2645
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:2740
Expr * getExpr()
Get the initialization expression that will be used.
Definition ExprCXX.cpp:1137
FunctionDecl * getOperatorDelete() const
Definition ExprCXX.h:2670
bool isArrayForm() const
Definition ExprCXX.h:2657
bool isGlobalDelete() const
Definition ExprCXX.h:2656
Represents a C++ destructor within a class.
Definition DeclCXX.h:2915
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
SourceLocation getBeginLoc() const LLVM_READONLY
Definition ExprCXX.h:1810
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will call.
Definition ExprCXX.h:1793
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2153
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:2296
bool isInstance() const
Definition DeclCXX.h:2180
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:2469
QualType getAllocatedType() const
Definition ExprCXX.h:2439
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:2474
Expr * getPlacementArg(unsigned I)
Definition ExprCXX.h:2508
unsigned getNumPlacementArgs() const
Definition ExprCXX.h:2499
SourceRange getSourceRange() const
Definition ExprCXX.h:2615
FunctionDecl * getOperatorNew() const
Definition ExprCXX.h:2464
Expr * getInitializer()
The initializer of this new-expression.
Definition ExprCXX.h:2538
bool getValue() const
Definition ExprCXX.h:4386
MutableArrayRef< Expr * > getInitExprs()
Definition ExprCXX.h:5235
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:1243
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:1382
base_class_range bases()
Definition DeclCXX.h:609
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:603
base_class_range vbases()
Definition DeclCXX.h:626
capture_const_range captures() const
Definition DeclCXX.h:1107
bool isEmpty() const
Determine whether this is an empty class in the sense of (C++11 [meta.unary.prop]).
Definition DeclCXX.h:1196
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:523
unsigned getNumVBases() const
Retrieves the number of virtual base classes of this class.
Definition DeclCXX.h:624
bool isDerivedFrom(const CXXRecordDecl *Base) const
Determine whether this class is derived from the class Base.
ReflectionKind getKind() const
Definition ExprCXX.h:5599
const void * getOpaqueValue() const
Definition ExprCXX.h:5600
Expr * getSemanticForm()
Get an equivalent semantic form for this expression.
Definition ExprCXX.h:309
bool isImplicit() const
Definition ExprCXX.h:1182
bool isTypeOperand() const
Definition ExprCXX.h:889
QualType getTypeOperand(const ASTContext &Context) const
Retrieves the type operand of this typeid() expression after various required adjustments (removing r...
Definition ExprCXX.cpp:168
Expr * getExprOperand() const
Definition ExprCXX.h:900
bool isPotentiallyEvaluated() const
Determine whether this typeid has a type operand which is potentially evaluated, per C++11 [expr....
Definition ExprCXX.cpp:136
MSGuidDecl * getGuidDecl() const
Definition ExprCXX.h:1119
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:3012
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3216
SourceLocation getBeginLoc() const
Definition Expr.h:3346
const AllocSizeAttr * getCalleeAllocSizeAttr() const
Try to get the alloc_size attribute of the callee. May return null.
Definition Expr.cpp:3632
unsigned getBuiltinCallee() const
getBuiltinCallee - If this is a call to a builtin, return the builtin ID of the callee.
Definition Expr.cpp:1624
Expr * getCallee()
Definition Expr.h:3159
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition Expr.h:3203
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operator.
Definition Expr.h:3305
Expr ** getArgs()
Retrieve the call arguments.
Definition Expr.h:3206
Decl * getCalleeDecl()
Definition Expr.h:3189
QualType getCallReturnType(const ASTContext &Ctx) const
getCallReturnType - Get the return type of the call expr.
Definition Expr.cpp:1635
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
CaseStmt - Represent a case statement.
Definition Stmt.h:1931
Expr * getLHS()
Definition Stmt.h:2014
Expr * getRHS()
Definition Stmt.h:2026
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition Expr.h:3745
path_iterator path_begin()
Definition Expr.h:3815
unsigned path_size() const
Definition Expr.h:3814
CastKind getCastKind() const
Definition Expr.h:3789
const FieldDecl * getTargetUnionField() const
Definition Expr.h:3839
path_iterator path_end()
Definition Expr.h:3816
const CXXBaseSpecifier *const * path_const_iterator
Definition Expr.h:3812
bool path_empty() const
Definition Expr.h:3813
Expr * getSubExpr()
Definition Expr.h:3795
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operation.
Definition Expr.h:3859
This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
bool isPowerOfTwo() const
Test whether the quantity is a power of two.
Definition CharUnits.h:114
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:177
bool isZero() const
Test whether the quantity equals zero.
Definition CharUnits.h:101
QuantityType getQuantity() const
Get the raw integer representation of this quantity.
Definition CharUnits.h:155
static CharUnits One()
Construct a CharUnits quantity of one.
Definition CharUnits.h:55
static CharUnits fromQuantity(QuantityType Quantity)
Construct a CharUnits quantity from a raw integer type.
Definition CharUnits.h:58
unsigned getValue() const
Definition Expr.h:1674
Expr * getChosenSubExpr() const
getChosenSubExpr - Return the subexpression chosen according to the condition.
Definition Expr.h:4953
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:3362
QualType getElementType() const
Definition TypeBase.h:3372
CompoundAssignOperator - For compound assignments (e.g.
Definition Expr.h:4369
QualType getComputationLHSType() const
Definition Expr.h:4403
CompoundLiteralExpr - [C99 6.5.2.5].
Definition Expr.h:3674
bool hasStaticStorage() const
Definition Expr.h:3719
APValue & getOrCreateStaticValue(ASTContext &Ctx) const
Definition Expr.cpp:5742
bool isFileScope() const
Definition Expr.h:3706
const Expr * getInitializer() const
Definition Expr.h:3702
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition Stmt.h:1751
bool body_empty() const
Definition Stmt.h:1795
Stmt *const * const_body_iterator
Definition Stmt.h:1823
body_iterator body_end()
Definition Stmt.h:1816
body_range body()
Definition Stmt.h:1814
body_iterator body_begin()
Definition Stmt.h:1815
bool isSatisfied() const
Whether or not the concept with the given arguments was satisfied when the expression was created.
ConditionalOperator - The ?
Definition Expr.h:4460
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression representing the value of the expression if the condition eva...
Definition Expr.h:4492
Expr * getCond() const
getCond - Return the expression representing the condition for the ?
Definition Expr.h:4483
Expr * getTrueExpr() const
getTrueExpr - Return the subexpression representing the value of the expression if the condition eval...
Definition Expr.h:4487
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3858
unsigned getSizeBitWidth() const
Return the bit width of the size type.
Definition TypeBase.h:3921
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:336
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:376
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:3947
bool isZeroSize() const
Return true if the size is zero.
Definition TypeBase.h:3928
const Expr * getSizeExpr() const
Return a pointer to the size expression.
Definition TypeBase.h:3954
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3914
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition TypeBase.h:3934
APValue getAPValueResult() const
Definition Expr.cpp:419
bool hasAPValueResult() const
Definition Expr.h:1202
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4622
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operator.
Definition Expr.h:4865
Expr * getSrcExpr() const
getSrcExpr - Return the Expr to be converted.
Definition Expr.h:4878
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:1467
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2108
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition DeclBase.h:2261
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:1315
bool refersToEnclosingVariableOrCapture() const
Does this DeclRefExpr refer to an enclosing local or a captured variable?
Definition Expr.h:1519
ValueDecl * getDecl()
Definition Expr.h:1383
DeclStmt - Adaptor class for mixing declarations with statements and expressions.
Definition Stmt.h:1642
decl_range decls()
Definition Stmt.h:1690
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:597
SourceLocation getLocation() const
Definition DeclBase.h:448
DeclContext * getDeclContext()
Definition DeclBase.h:457
AccessSpecifier getAccess() const
Definition DeclBase.h:516
A decomposition declaration.
Definition DeclCXX.h:4287
auto flat_bindings() const
Definition DeclCXX.h:4332
InitListExpr * getUpdater() const
Definition Expr.h:6022
Designator - A designator in a C99 designated initializer.
Definition Designator.h:38
DoStmt - This represents a 'do/while' stmt.
Definition Stmt.h:2843
Stmt * getBody()
Definition Stmt.h:2868
Expr * getCond()
Definition Stmt.h:2861
Symbolic representation of a dynamic allocation.
Definition APValue.h:79
static uintptr_t getMaxIndex()
Definition APValue.h:120
unsigned getIndex() const
Definition APValue.h:100
DynAllocKind getAllocKind() const
Definition APValue.h:101
const Expr * getBase() const
Definition Expr.h:6667
ChildElementIter< false > begin()
Definition Expr.h:5310
ExplicitCastExpr - An explicit cast written in the source code.
Definition Expr.h:3997
QualType getTypeAsWritten() const
getTypeAsWritten - Returns the type that this expression is casting to, as written in the source code...
Definition Expr.h:4024
This represents one expression.
Definition Expr.h:114
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:289
SideEffectsKind
Definition Expr.h:699
@ SE_AllowSideEffects
Allow any unmodeled side effect.
Definition Expr.h:703
@ SE_AllowUndefinedBehavior
Allow UB that we can give a value, but not arbitrary unmodeled side effects.
Definition Expr.h:701
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:3134
bool EvaluateAsMandatedConstantInitializer(EvalResult &Result, const ASTContext &Ctx, SemaProxy &SProxy, const VarDecl *VD) const
Evaluate an expression that is required by the language to be a constant expression.
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:179
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
bool EvaluateAsMandatedConstantExpr(EvalResult &Result, const ASTContext &Ctx, SemaProxy &SProxy, ConstantExprKind Kind=ConstantExprKind::Normal) const
Evaluate an expression that is required by the language to be a constant expression.
bool isCXX11ConstantExpr(const ASTContext &Ctx, APValue &Result, bool AllowRelaxedEval=false) const
isCXX11ConstantExpr - Return true if this expression is a constant expression in C++11.
bool EvaluateAsMandatedConstantRValue(EvalResult &Result, const ASTContext &Ctx, SemaProxy &SProxy) const
Evaluate an expression that is required by the language to be a constant expression,...
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Returns the set of floating point options that apply to this expression.
Definition Expr.cpp:4031
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3129
bool containsErrors() const
Whether this expression contains subexpressions which had errors.
Definition Expr.h:248
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:3125
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:287
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition Expr.h:286
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:3728
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:3292
Expr()=delete
ConstantExprKind
Definition Expr.h:784
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
bool EvaluateCharRangeAsString(std::string &Result, const Expr *SizeExpression, const Expr *PtrExpression, ASTContext &Ctx, SemaProxy &SProxy, EvalResult &Status) const
QualType getType() const
Definition Expr.h:146
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...
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:4485
void getEncodedElementAccess(SmallVectorImpl< uint32_t > &Elts) const
getEncodedElementAccess - Encode the elements accessed into an llvm aggregate Constant of ConstantInt...
Definition Expr.cpp:4598
bool isFPConstrained() const
LangOptions::FPExceptionModeKind getExceptionMode() const
RoundingMode getRoundingMode() const
Represents a member of a struct/union/class.
Definition Decl.h:3341
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3444
unsigned getBitWidthValue() const
Computes the bit width of this field, if this is a bit field.
Definition Decl.cpp:4854
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition Decl.h:3426
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3577
FieldDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this field.
Definition Decl.h:3588
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition Diagnostic.h:103
llvm::APInt getValue() const
Returns an internal integer representation of the literal.
Definition Expr.h:1620
llvm::APFloat getValue() const
Definition Expr.h:1711
ForStmt - This represents a 'for (init;cond;inc)' stmt.
Definition Stmt.h:2899
Stmt * getInit()
Definition Stmt.h:2914
VarDecl * getConditionVariable() const
Retrieve the variable declared in this "for" statement, if any.
Definition Stmt.cpp:1120
Stmt * getBody()
Definition Stmt.h:2943
Expr * getInc()
Definition Stmt.h:2942
Expr * getCond()
Definition Stmt.h:2941
const Expr * getSubExpr() const
Definition Expr.h:1107
Represents a function declaration or definition.
Definition Decl.h:2082
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2974
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition Decl.cpp:3284
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition Decl.cpp:4280
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition Decl.cpp:4268
bool hasCXXExplicitFunctionObjectParameter() const
Definition Decl.cpp:3943
FunctionDecl * getTemplateInstantiationPattern(bool ForDefinition=true) const
Retrieve the function declaration from which this function could be instantiated, if it is an instant...
Definition Decl.cpp:4339
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition Decl.h:2546
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition Decl.cpp:4404
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition Decl.h:2639
bool isImplicitlyInstantiable() const
Determines whether this function is a function template specialization or a member of a class templat...
Definition Decl.cpp:4297
FunctionDecl * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
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:3499
bool isDefaulted() const
Whether this function is defaulted.
Definition Decl.h:2554
bool isDefined(const FunctionDecl *&Definition, bool CheckForPendingFriendDefinition=false) const
Returns true if the function has a definition that does not need to be instantiated.
Definition Decl.cpp:3251
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:3129
FunctionDecl * findSpecialization(ArrayRef< TemplateArgument > Args, llvm::FoldingSetInsertToken &InsertToken)
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:6554
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:2270
Stmt * getThen()
Definition Stmt.h:2359
Stmt * getInit()
Definition Stmt.h:2420
bool isNonNegatedConsteval() const
Definition Stmt.h:2455
Expr * getCond()
Definition Stmt.h:2347
Stmt * getElse()
Definition Stmt.h:2368
bool isConsteval() const
Definition Stmt.h:2450
VarDecl * getConditionVariable()
Retrieve the variable declared in this "if" statement, if any.
Definition Stmt.cpp:1068
const Expr * getSubExpr() const
Definition Expr.h:1788
Represents an implicitly-generated value initialization of an object of a given type.
Definition Expr.h:6143
Represents a field injected from an anonymous union/struct into the parent scope.
Definition Decl.h:3648
ArrayRef< NamedDecl * > chain() const
Definition Decl.h:3669
Describes an C or C++ initializer list.
Definition Expr.h:5377
bool isTransparent() const
Is this a transparent initializer list (that is, an InitListExpr that is purely syntactic,...
Definition Expr.cpp:2501
bool isStringLiteralInit() const
Is this an initializer for an array of characters, initialized by a string literal or an @encode?
Definition Expr.cpp:2487
unsigned getNumInits() const
Definition Expr.h:5410
Expr * getArrayFiller()
If this initializer list initializes an array with more elements than there are initializers in the l...
Definition Expr.h:5491
const Expr * getInit(unsigned Init) const
Definition Expr.h:5443
ArrayRef< Expr * > inits() const
Definition Expr.h:5441
capture_init_iterator capture_init_end()
Retrieve the iterator pointing one past the last initialization argument for this lambda expression.
Definition ExprCXX.h:2111
capture_init_iterator capture_init_begin()
Retrieve the first initialization argument for this lambda expression (which initializes the first ca...
Definition ExprCXX.h:2099
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:4974
StorageDuration getStorageDuration() const
Retrieve the storage duration for the materialized temporary.
Definition ExprCXX.h:4999
Expr * getSubExpr() const
Retrieve the temporary-generating subexpression whose value will be materialized into a glvalue.
Definition ExprCXX.h:4991
APValue * getOrCreateValue(bool MayCreate) const
Get the storage for the constant value of a materialized temporary of static storage duration.
Definition ExprCXX.h:5007
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3433
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3516
Expr * getBase() const
Definition Expr.h:3510
bool isArrow() const
Definition Expr.h:3617
This represents a decl that may have a name.
Definition Decl.h:276
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:297
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:303
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:342
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:67
Expr * getIndexExpr(unsigned Idx)
Definition Expr.h:2655
const OffsetOfNode & getComponent(unsigned Idx) const
Definition Expr.h:2643
TypeSourceInfo * getTypeSourceInfo() const
Definition Expr.h:2636
unsigned getNumComponents() const
Definition Expr.h:2651
unsigned getArrayExprIndex() const
For an array element node, returns the index into the array of expressions.
Definition Expr.h:2548
FieldDecl * getField() const
For a field offsetof node, returns the field.
Definition Expr.h:2554
@ Array
An index into an array.
Definition Expr.h:2495
@ Identifier
A field in a dependent type, known only by its name.
Definition Expr.h:2499
@ Field
A field.
Definition Expr.h:2497
@ Base
An implicit indirection through a C++ base class, when the field found is in a base class.
Definition Expr.h:2502
Kind getKind() const
Determine what kind of offsetof node this is.
Definition Expr.h:2544
CXXBaseSpecifier * getBase() const
For a base class node, returns the base specifier.
Definition Expr.h:2564
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition Expr.h:1223
Expr * getSourceExpr() const
The source expression of an opaque value expression is the expression which originally generated the ...
Definition Expr.h:1273
Expr * getSelectedExpr() const
Definition ExprCXX.h:4693
const Expr * getSubExpr() const
Definition Expr.h:2268
Represents a parameter to a function.
Definition Decl.h:1832
unsigned getFunctionScopeIndex() const
Returns the index of this parameter in its prototype or method scope.
Definition Decl.h:1892
bool isExplicitObjectParameter() const
Definition Decl.h:1920
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3403
StringLiteral * getFunctionName()
Definition Expr.h:2118
Expr * getResultExpr()
Return the result-bearing expression, or null if there is none.
Definition Expr.h:6938
ArrayRef< Expr * > semantics()
Definition Expr.h:6962
A (possibly-)qualified type.
Definition TypeBase.h:938
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8662
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:8578
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8618
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:8763
QualType getCanonicalType() const
Definition TypeBase.h:8630
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8672
void removeLocalVolatile()
Definition TypeBase.h:8694
void addVolatile()
Add the volatile type qualifier to this QualType.
Definition TypeBase.h:1180
void removeLocalConst()
Definition TypeBase.h:8686
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8651
QualType getAtomicUnqualifiedType() const
Remove all qualifiers including _Atomic.
Definition Type.cpp:1841
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:8624
bool isWrapType() const
Returns true if it is a OverflowBehaviorType of Wrap kind.
Definition Type.cpp:3182
Represents a struct/union/class.
Definition Decl.h:4506
unsigned getNumFields() const
Returns the number of fields (non-static data members) in this record.
Definition Decl.h:4722
field_iterator field_end() const
Definition Decl.h:4712
field_range fields() const
Definition Decl.h:4709
specific_decl_iterator< FieldDecl > field_iterator
Definition Decl.h:4706
bool isAnonymousStructOrUnion() const
Whether this is an anonymous struct or union.
Definition Decl.h:4558
bool field_empty() const
Definition Decl.h:4717
field_iterator field_begin() const
Definition Decl.cpp:5383
bool isSatisfied() const
Whether or not the requires clause is satisfied.
SourceLocation getLocation() const
Definition Expr.h:2224
std::string ComputeName(ASTContext &Context) const
Definition Expr.cpp:597
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
Classes implementing SemaProxy present a restricted view of the (possibly mutating) actions and queri...
Definition SemaProxy.h:29
virtual void instantiateFunctionDefinition(SourceLocation PointOfInstantiation, FunctionDecl *Function)=0
ShuffleVectorExpr - clang-specific builtin-in function __builtin_shufflevector.
Definition Expr.h:4712
llvm::APSInt getShuffleMaskIdx(unsigned N) const
Definition Expr.h:4764
unsigned getNumSubExprs() const
getNumSubExprs - Return the size of the SubExprs array.
Definition Expr.h:4745
Expr * getExpr(unsigned Index)
getExpr - Return the Expr at the specified index.
Definition Expr.h:4751
unsigned getPackLength() const
Retrieve the length of the parameter pack.
Definition ExprCXX.h:4569
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:2319
bool isIntType() const
Definition Expr.h:5119
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:4681
Stmt - This represents one statement.
Definition Stmt.h:85
@ NoStmtClass
Definition Stmt.h:88
StmtClass getStmtClass() const
Definition Stmt.h:1504
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:1844
UnsignedOrNone findZeroCodeUnit(unsigned StartIndex=0) const
Scan the string literal contents for a code unit with value 0.
Definition Expr.cpp:1414
unsigned getLength() const
Definition Expr.h:1969
uint32_t getCodeUnit(size_t I) const
Return the code unit at the given position.
Definition Expr.h:1931
StringRef getBytes() const
Allow access to clients that need the byte representation, such as ASTWriterStmt::VisitStringLiteral(...
Definition Expr.h:1920
StringRef getString() const
Definition Expr.h:1912
bool isOrdinary() const
Definition Expr.h:1977
const SwitchCase * getNextSwitchCase() const
Definition Stmt.h:1904
SwitchStmt - This represents a 'switch' stmt.
Definition Stmt.h:2520
Expr * getCond()
Definition Stmt.h:2583
Stmt * getBody()
Definition Stmt.h:2595
VarDecl * getConditionVariable()
Retrieve the variable declared in this "switch" statement, if any.
Definition Stmt.cpp:1186
Stmt * getInit()
Definition Stmt.h:2600
SwitchCase * getSwitchCaseList()
Definition Stmt.h:2651
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:3999
TagDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:5007
bool isUnion() const
Definition Decl.h:4109
Exposes information about the current target.
Definition TargetInfo.h:228
unsigned getNewAlign() const
Return the largest alignment for which a suitably-sized allocation with 'operator new(size_t)' is gua...
Definition TargetInfo.h:762
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
unsigned getLongLongAlign() const
Definition TargetInfo.h:549
unsigned getLongDoubleAlign() const
Definition TargetInfo.h:804
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:48
QualType getType() const
Return the type wrapped by this type source info.
Definition TypeBase.h:8560
bool getBoolValue() const
Definition ExprCXX.h:2962
bool isStoredAsComparisonResult() const
Definition ExprCXX.h:2958
const APValue & getAPValue() const
Definition ExprCXX.h:2967
bool isStoredAsBoolean() const
Definition ExprCXX.h:2954
The base class of the type hierarchy.
Definition TypeBase.h:1879
bool isVoidType() const
Definition TypeBase.h:9200
bool isBooleanType() const
Definition TypeBase.h:9341
bool isFunctionReferenceType() const
Definition TypeBase.h:8889
bool isMFloat8Type() const
Definition TypeBase.h:9229
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2415
bool isPackedVectorBoolType(const ASTContext &ctx) const
Definition Type.cpp:542
bool isLiteralType(const ASTContext &Ctx) const
Return true if this is a literal type (C++11 [basic.types]p10)
Definition Type.cpp:3239
bool isIncompleteArrayType() const
Definition TypeBase.h:8922
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2392
bool isComplexType() const
isComplexType() does not include complex integers (a GCC extension).
Definition Type.cpp:857
const ArrayType * castAsArrayTypeUnsafe() const
A variant of castAs<> for array type which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9507
bool isUnsignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is unsigned or an enumeration types whose underlying ...
Definition Type.cpp:2483
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition Type.cpp:2299
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:8918
bool isNothrowT() const
Definition Type.cpp:3430
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition Type.h:41
bool isVoidPointerType() const
Definition Type.cpp:845
bool isConstantSizeType() const
Return true if this is not a variable sized type, according to the rules of C99 6....
Definition Type.cpp:2645
bool isArrayType() const
Definition TypeBase.h:8914
bool isFunctionPointerType() const
Definition TypeBase.h:8882
bool isCountAttributedType() const
Definition Type.cpp:874
bool isConstantMatrixType() const
Definition TypeBase.h:8982
bool isPointerType() const
Definition TypeBase.h:8815
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9248
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9498
bool isReferenceType() const
Definition TypeBase.h:8839
bool isEnumeralType() const
Definition TypeBase.h:8946
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:2080
bool isVariableArrayType() const
Definition TypeBase.h:8926
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition Type.cpp:2829
const Type * getArrayElementTypeNoTypeQual() const
If this is an array type, return the element type of the array, potentially with type qualifiers miss...
Definition Type.cpp:595
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:885
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:9326
bool isExtVectorBoolType() const
Definition TypeBase.h:8962
bool isMemberDataPointerType() const
Definition TypeBase.h:8907
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition TypeBase.h:9169
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2863
RecordDecl * castAsRecordDecl() const
Definition Type.h:48
bool isAnyComplexType() const
Definition TypeBase.h:8950
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9264
bool isMemberPointerType() const
Definition TypeBase.h:8896
bool isAtomicType() const
Definition TypeBase.h:9007
bool isComplexIntegerType() const
Definition Type.cpp:863
bool isStdByteType() const
Definition Type.cpp:3449
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9484
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 isMetaInfoType() const
Definition TypeBase.h:9204
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2655
bool isFunctionType() const
Definition TypeBase.h:8811
bool isVectorType() const
Definition TypeBase.h:8954
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2533
bool isFloatingType() const
Definition Type.cpp:2517
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:2460
const T * castAsCanonical() const
Return this type's canonical type cast to the specified type.
Definition TypeBase.h:3009
bool isAnyPointerType() const
Definition TypeBase.h:8823
TypeClass getTypeClass() const
Definition TypeBase.h:2449
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9431
bool isNullPtrType() const
Definition TypeBase.h:9241
bool isRecordType() const
Definition TypeBase.h:8942
bool isUnionType() const
Definition Type.cpp:851
bool isSizelessVectorType() const
Returns true for all scalable vector types.
Definition Type.cpp:2791
bool hasPointerRepresentation() const
Whether this type is represented natively as a pointer.
Definition TypeBase.h:9375
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand.
Definition Expr.h:2694
QualType getArgumentType() const
Definition Expr.h:2737
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:2773
QualType getTypeOfArgument() const
Gets the argument type, or the type of the argument expression, whichever is appropriate.
Definition Expr.h:2763
UnaryExprOrTypeTrait getKind() const
Definition Expr.h:2726
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2313
SourceLocation getExprLoc() const
Definition Expr.h:2437
Expr * getSubExpr() const
Definition Expr.h:2354
Opcode getOpcode() const
Definition Expr.h:2349
static bool isIncrementOp(Opcode Op)
Definition Expr.h:2395
bool canOverflow() const
Returns true if the unary operator can cause an overflow.
Definition Expr.h:2367
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:714
QualType getType() const
Definition Decl.h:725
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr.
Definition Decl.cpp:5689
QualType getType() const
Definition Value.cpp:238
bool hasValue() const
Definition Value.h:135
Represents a variable declaration or definition.
Definition Decl.h:934
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition Decl.h:1606
bool hasInit() const
Definition Decl.cpp:2400
bool hasICEInitializer(const ASTContext &Context) const
Determine whether the initializer of this variable is an integer constant expression.
Definition Decl.cpp:2649
bool evaluateConstantDestruction(SmallVectorImpl< PartialDiagnosticAt > &Notes, SemaProxy &SProxy) const
Evaluate the destruction of a variable that is required by the language to have constant destruction.
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition Decl.h:1615
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:2641
CharUnits getFlexibleArrayInitChars(const ASTContext &Ctx) const
If hasFlexibleArrayInit is true, compute the number of additional bytes necessary to store those elem...
Definition Decl.cpp:2869
bool hasConstantInitialization() const
Determine whether this variable has constant initialization.
Definition Decl.cpp:2661
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
Definition Decl.cpp:2368
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:2479
EvaluatedStmt * ensureEvaluatedStmt() const
Convert the initializer for this declaration to the elaborated EvaluatedStmt form,...
Definition Decl.cpp:2550
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:1216
bool isCXXForRangeImplicitVar() const
Whether this variable is the implicit '__range' variable in C++ range-based for loops.
Definition Decl.h:1659
ThreadStorageClassSpecifier getTSCSpec() const
Definition Decl.h:1185
const Expr * getInit() const
Definition Decl.h:1393
const APValue * evaluateValue() const
Attempt to evaluate the value of the initializer attached to this declaration, and produce notes expl...
Definition Decl.cpp:2568
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition Decl.h:1192
DefinitionKind hasDefinition(ASTContext &) const
Check whether this variable is defined in this translation unit.
Definition Decl.cpp:2377
bool isLocalVarDecl() const
Returns true for local variable declarations other than parameters.
Definition Decl.h:1276
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:2521
const Expr * getAnyInitializer() const
Get the initializer for this variable, no matter which declaration it is attached to.
Definition Decl.h:1383
Expr * getSizeExpr() const
Definition TypeBase.h:4078
Represents a GCC generic vector type.
Definition TypeBase.h:4398
unsigned getNumElements() const
Definition TypeBase.h:4413
QualType getElementType() const
Definition TypeBase.h:4412
WhileStmt - This represents a 'while' stmt.
Definition Stmt.h:2708
Expr * getCond()
Definition Stmt.h:2760
VarDecl * getConditionVariable()
Retrieve the variable declared in this "while" statement, if any.
Definition Stmt.cpp:1247
Stmt * getBody()
Definition Stmt.h:2772
std::optional< uint64_t > tryEvaluateObjectSize(const EvalSettings &Settings, const Expr *E, unsigned Kind, bool IsDynamic)
If.
Definition Context.cpp:434
bool evaluateString(const EvalSettings &Settings, const Expr *E, std::string &Result)
Evaluate.
Definition Context.cpp:301
bool evaluateDestruction(const EvalSettings &Settings, const VarDecl *VD, APValue Value)
Evaluates the destruction of a variable.
Definition Context.cpp:167
std::optional< bool > evaluateWithSubstitution(const EvalSettings &Settings, const FunctionDecl *Callee, ArrayRef< const Expr * > Args, const Expr *This, const Expr *Condition)
Definition Context.cpp:464
bool evaluate(const EvalSettings &Settings, const Expr *E, APValue &Result)
Like evaluateAsRvalue(), but does no implicit lvalue-to-rvalue conversion.
Definition Context.cpp:103
bool evaluateAsInitializer(const EvalSettings &Settings, const VarDecl *VD, const Expr *Init, APValue &Result)
Evaluates a toplevel initializer.
Definition Context.cpp:134
bool evaluateAsRValue(const EvalSettings &Settings, const Expr *E, APValue &Result)
Evaluates a toplevel expression as an rvalue.
Definition Context.cpp:73
bool evaluateCharRange(const EvalSettings &Settings, const Expr *SizeExpr, const Expr *PtrExpr, APValue &Result)
Definition Context.cpp:283
std::optional< uint64_t > evaluateStrlen(const EvalSettings &Settings, const Expr *E)
Evalute.
Definition Context.cpp:366
void isPotentialConstantExprUnevaluated(const EvalSettings &Settings, const Expr *E, const FunctionDecl *FD)
Definition Context.cpp:60
Base class for stack frames, shared between VM and walker.
Definition Frame.h:28
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:4563
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:426
bool NE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1498
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:3920
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
DynAllocKind
Kind of source for a dynamic allocation.
Definition APValue.h:69
@ CPlusPlus
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:5807
bool hasSpecificAttr(const Container &container)
@ NonNull
Values of this type can never be null.
Definition Specifiers.h:352
@ Success
Annotation was successful.
Definition Parser.h:65
Expr::ConstantExprKind ConstantExprKind
Definition Expr.h:1087
@ 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:128
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:240
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:345
@ SD_FullExpression
Full-expression storage duration (for temporaries).
Definition Specifiers.h:342
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
@ TypeAlignment
Definition TypeBase.h:77
OptionalUnsigned< unsigned > UnsignedOrNone
const FunctionProtoType * T
@ Off
Never emit colors regardless of the output stream.
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:139
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:1306
U cast(CodeGen::Address addr)
Definition Address.h:327
@ ArrayBound
Array bound in array declarator or new-expression.
Definition Sema.h:837
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6157
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ Other
Other implicit parameter.
Definition Decl.h:1787
ActionResult< Stmt * > StmtResult
Definition Ownership.h:250
CharUnits GetAlignOfDynamicAlloc(const ASTContext &Ctx, QualType AllocType, DynAllocKind AllocKind)
unsigned long uint64_t
Diagnostic wrappers for TextAPI types for error reporting.
Definition Dominators.h:30
hash_code hash_value(const clang::dependencies::ModuleID &ID)
__UINTPTR_TYPE__ uintptr_t
An unsigned integer type with the property that any valid pointer to void can be converted to this ty...
__builtin_bitreverse32 uint32_t __builtin_riscv_aaddu_u32 __builtin_riscv_asubu_u32 __builtin_elementwise_add_sat __builtin_elementwise_sub_sat int32_t uint32_t uint32_t __builtin_riscv_mhacc_i32 __builtin_riscv_mhaccu_u32 __builtin_riscv_mhaccsu_i32 __builtin_riscv_mulq_i32 __builtin_riscv_mqwacc_i64 __packed_splat4 uint16_t
__builtin_bitreverse32 uint32_t __builtin_riscv_aaddu_u32 __builtin_riscv_asubu_u32 __builtin_elementwise_add_sat __builtin_elementwise_sub_sat int32_t uint32_t uint32_t __builtin_riscv_mhacc_i32 __builtin_riscv_mhaccu_u32 __builtin_riscv_mhaccsu_i32 __builtin_riscv_mulq_i32 int64_t
__builtin_bitreverse32 uint32_t __builtin_riscv_aaddu_u32 __builtin_riscv_asubu_u32 __builtin_elementwise_add_sat __builtin_elementwise_sub_sat int32_t uint32_t uint32_t __builtin_riscv_mhacc_i32 __builtin_riscv_mhaccu_u32 __builtin_riscv_mhaccsu_i32 __builtin_riscv_mulq_i32 __builtin_riscv_mqwacc_i64 uint8_t
__builtin_bitreverse32 uint32_t __builtin_riscv_aaddu_u32 __builtin_riscv_asubu_u32 __builtin_elementwise_add_sat __builtin_elementwise_sub_sat int32_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.
unsigned HasConstantDestruction
Whether this variable is known to have constant destruction.
Definition Decl.h:909
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:667
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:669
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:623
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:651
bool HasSideEffects
Whether the evaluated expression has side effects.
Definition Expr.h:626
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