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/Type.h"
55#include "clang/AST/TypeLoc.h"
60#include "llvm/ADT/APFixedPoint.h"
61#include "llvm/ADT/Sequence.h"
62#include "llvm/ADT/SmallBitVector.h"
63#include "llvm/ADT/StringExtras.h"
64#include "llvm/Support/Casting.h"
65#include "llvm/Support/Debug.h"
66#include "llvm/Support/SaveAndRestore.h"
67#include "llvm/Support/SipHash.h"
68#include "llvm/Support/TimeProfiler.h"
69#include "llvm/Support/raw_ostream.h"
70#include <cstring>
71#include <functional>
72#include <limits>
73#include <optional>
74
75#define DEBUG_TYPE "exprconstant"
76
77using namespace clang;
78using llvm::APFixedPoint;
79using llvm::APInt;
80using llvm::APSInt;
81using llvm::APFloat;
82using llvm::FixedPointSemantics;
83
84namespace {
85 struct LValue;
86 class CallStackFrame;
87 class EvalInfo;
88
89 using SourceLocExprScopeGuard =
91
93 return B.getType();
94 }
95
96 /// Get an LValue path entry, which is known to not be an array index, as a
97 /// field declaration.
98 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
99 return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer());
100 }
101 /// Get an LValue path entry, which is known to not be an array index, as a
102 /// base class declaration.
103 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
104 return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer());
105 }
106 /// Determine whether this LValue path entry for a base class names a virtual
107 /// base class.
108 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
109 return E.getAsBaseOrMember().getInt();
110 }
111
112 /// Given an expression, determine the type used to store the result of
113 /// evaluating that expression.
114 static QualType getStorageType(const ASTContext &Ctx, const Expr *E) {
115 if (E->isPRValue())
116 return E->getType();
117 return Ctx.getLValueReferenceType(E->getType());
118 }
119
120 static unsigned countNonVirtualBases(const CXXRecordDecl *RD) {
121 return llvm::count_if(RD->bases(), [](auto &B) { return !B.isVirtual(); });
122 }
123
124 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
125 /// This will look through a single cast.
126 ///
127 /// Returns null if we couldn't unwrap a function with alloc_size.
128 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
129 if (!E->getType()->isPointerType())
130 return nullptr;
131
132 E = E->IgnoreParens();
133 // If we're doing a variable assignment from e.g. malloc(N), there will
134 // probably be a cast of some kind. In exotic cases, we might also see a
135 // top-level ExprWithCleanups. Ignore them either way.
136 if (const auto *FE = dyn_cast<FullExpr>(E))
137 E = FE->getSubExpr()->IgnoreParens();
138
139 if (const auto *Cast = dyn_cast<CastExpr>(E))
140 E = Cast->getSubExpr()->IgnoreParens();
141
142 if (const auto *CE = dyn_cast<CallExpr>(E))
143 return CE->getCalleeAllocSizeAttr() ? CE : nullptr;
144 return nullptr;
145 }
146
147 /// Determines whether or not the given Base contains a call to a function
148 /// with the alloc_size attribute.
149 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
150 const auto *E = Base.dyn_cast<const Expr *>();
151 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
152 }
153
154 /// The bound to claim that an array of unknown bound has.
155 /// The value in MostDerivedArraySize is undefined in this case. So, set it
156 /// to an arbitrary value that's likely to loudly break things if it's used.
157 static const uint64_t AssumedSizeForUnsizedArray =
158 std::numeric_limits<uint64_t>::max() / 2;
159
160 /// Determines if an LValue with the given LValueBase will have an unsized
161 /// array in its designator.
162 /// Find the path length and type of the most-derived subobject in the given
163 /// path, and find the size of the containing array, if any.
164 static unsigned
165 findMostDerivedSubobject(const ASTContext &Ctx, APValue::LValueBase Base,
167 uint64_t &ArraySize, QualType &Type, bool &IsArray,
168 bool &FirstEntryIsUnsizedArray) {
169 // This only accepts LValueBases from APValues, and APValues don't support
170 // arrays that lack size info.
171 assert(!isBaseAnAllocSizeCall(Base) &&
172 "Unsized arrays shouldn't appear here");
173 unsigned MostDerivedLength = 0;
174 // The type of Base is a reference type if the base is a constexpr-unknown
175 // variable. In that case, look through the reference type.
176 Type = getType(Base).getNonReferenceType();
177
178 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
179 if (Type->isArrayType()) {
180 const ArrayType *AT = Ctx.getAsArrayType(Type);
181 Type = AT->getElementType();
182 MostDerivedLength = I + 1;
183 IsArray = true;
184
185 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
186 ArraySize = CAT->getZExtSize();
187 } else {
188 assert(I == 0 && "unexpected unsized array designator");
189 FirstEntryIsUnsizedArray = true;
190 ArraySize = AssumedSizeForUnsizedArray;
191 }
192 } else if (Type->isAnyComplexType()) {
193 const ComplexType *CT = Type->castAs<ComplexType>();
194 Type = CT->getElementType();
195 ArraySize = 2;
196 MostDerivedLength = I + 1;
197 IsArray = true;
198 } else if (const auto *VT = Type->getAs<VectorType>()) {
199 Type = VT->getElementType();
200 ArraySize = VT->getNumElements();
201 MostDerivedLength = I + 1;
202 IsArray = true;
203 } else if (const FieldDecl *FD = getAsField(Path[I])) {
204 Type = FD->getType();
205 ArraySize = 0;
206 MostDerivedLength = I + 1;
207 IsArray = false;
208 } else {
209 // Path[I] describes a base class.
210 ArraySize = 0;
211 IsArray = false;
212 }
213 }
214 return MostDerivedLength;
215 }
216
217 /// A path from a glvalue to a subobject of that glvalue.
218 struct SubobjectDesignator {
219 /// True if the subobject was named in a manner not supported by C++11. Such
220 /// lvalues can still be folded, but they are not core constant expressions
221 /// and we cannot perform lvalue-to-rvalue conversions on them.
222 LLVM_PREFERRED_TYPE(bool)
223 unsigned Invalid : 1;
224
225 /// Is this a pointer one past the end of an object?
226 LLVM_PREFERRED_TYPE(bool)
227 unsigned IsOnePastTheEnd : 1;
228
229 /// Indicator of whether the first entry is an unsized array.
230 LLVM_PREFERRED_TYPE(bool)
231 unsigned FirstEntryIsAnUnsizedArray : 1;
232
233 /// Indicator of whether the most-derived object is an array element.
234 LLVM_PREFERRED_TYPE(bool)
235 unsigned MostDerivedIsArrayElement : 1;
236
237 /// The length of the path to the most-derived object of which this is a
238 /// subobject.
239 unsigned MostDerivedPathLength : 28;
240
241 /// The size of the array of which the most-derived object is an element.
242 /// This will always be 0 if the most-derived object is not an array
243 /// element. 0 is not an indicator of whether or not the most-derived object
244 /// is an array, however, because 0-length arrays are allowed.
245 ///
246 /// If the current array is an unsized array, the value of this is
247 /// undefined.
248 uint64_t MostDerivedArraySize;
249 /// The type of the most derived object referred to by this address.
250 QualType MostDerivedType;
251
252 typedef APValue::LValuePathEntry PathEntry;
253
254 /// The entries on the path from the glvalue to the designated subobject.
256
257 SubobjectDesignator() : Invalid(true) {}
258
259 explicit SubobjectDesignator(QualType T)
260 : Invalid(false), IsOnePastTheEnd(false),
261 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
262 MostDerivedPathLength(0), MostDerivedArraySize(0),
263 MostDerivedType(T.isNull() ? QualType() : T.getNonReferenceType()) {}
264
265 SubobjectDesignator(const ASTContext &Ctx, const APValue &V)
266 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
267 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
268 MostDerivedPathLength(0), MostDerivedArraySize(0) {
269 assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
270 if (!Invalid) {
271 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
272 llvm::append_range(Entries, V.getLValuePath());
273 if (V.getLValueBase()) {
274 bool IsArray = false;
275 bool FirstIsUnsizedArray = false;
276 MostDerivedPathLength = findMostDerivedSubobject(
277 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
278 MostDerivedType, IsArray, FirstIsUnsizedArray);
279 MostDerivedIsArrayElement = IsArray;
280 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
281 }
282 }
283 }
284
285 void truncate(ASTContext &Ctx, APValue::LValueBase Base,
286 unsigned NewLength) {
287 if (Invalid)
288 return;
289
290 assert(Base && "cannot truncate path for null pointer");
291 assert(NewLength <= Entries.size() && "not a truncation");
292
293 if (NewLength == Entries.size())
294 return;
295 Entries.resize(NewLength);
296
297 bool IsArray = false;
298 bool FirstIsUnsizedArray = false;
299 MostDerivedPathLength = findMostDerivedSubobject(
300 Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray,
301 FirstIsUnsizedArray);
302 MostDerivedIsArrayElement = IsArray;
303 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
304 }
305
306 void setInvalid() {
307 Invalid = true;
308 Entries.clear();
309 }
310
311 /// Determine whether the most derived subobject is an array without a
312 /// known bound.
313 bool isMostDerivedAnUnsizedArray() const {
314 assert(!Invalid && "Calling this makes no sense on invalid designators");
315 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
316 }
317
318 /// Determine what the most derived array's size is. Results in an assertion
319 /// failure if the most derived array lacks a size.
320 uint64_t getMostDerivedArraySize() const {
321 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
322 return MostDerivedArraySize;
323 }
324
325 /// Determine whether this is a one-past-the-end pointer.
326 bool isOnePastTheEnd() const {
327 assert(!Invalid);
328 if (IsOnePastTheEnd)
329 return true;
330 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
331 Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==
332 MostDerivedArraySize)
333 return true;
334 return false;
335 }
336
337 /// Get the range of valid index adjustments in the form
338 /// {maximum value that can be subtracted from this pointer,
339 /// maximum value that can be added to this pointer}
340 std::pair<uint64_t, uint64_t> validIndexAdjustments() {
341 if (Invalid || isMostDerivedAnUnsizedArray())
342 return {0, 0};
343
344 // [expr.add]p4: For the purposes of these operators, a pointer to a
345 // nonarray object behaves the same as a pointer to the first element of
346 // an array of length one with the type of the object as its element type.
347 bool IsArray = MostDerivedPathLength == Entries.size() &&
348 MostDerivedIsArrayElement;
349 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
350 : (uint64_t)IsOnePastTheEnd;
351 uint64_t ArraySize =
352 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
353 return {ArrayIndex, ArraySize - ArrayIndex};
354 }
355
356 /// Check that this refers to a valid subobject.
357 bool isValidSubobject() const {
358 if (Invalid)
359 return false;
360 return !isOnePastTheEnd();
361 }
362 /// Check that this refers to a valid subobject, and if not, produce a
363 /// relevant diagnostic and set the designator as invalid.
364 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
365
366 /// Get the type of the designated object.
367 QualType getType(ASTContext &Ctx) const {
368 assert(!Invalid && "invalid designator has no subobject type");
369 return MostDerivedPathLength == Entries.size()
370 ? MostDerivedType
371 : Ctx.getCanonicalTagType(getAsBaseClass(Entries.back()));
372 }
373
374 /// Update this designator to refer to the first element within this array.
375 void addArrayUnchecked(const ConstantArrayType *CAT) {
376 Entries.push_back(PathEntry::ArrayIndex(0));
377
378 // This is a most-derived object.
379 MostDerivedType = CAT->getElementType();
380 MostDerivedIsArrayElement = true;
381 MostDerivedArraySize = CAT->getZExtSize();
382 MostDerivedPathLength = Entries.size();
383 }
384 /// Update this designator to refer to the first element within the array of
385 /// elements of type T. This is an array of unknown size.
386 void addUnsizedArrayUnchecked(QualType ElemTy) {
387 Entries.push_back(PathEntry::ArrayIndex(0));
388
389 MostDerivedType = ElemTy;
390 MostDerivedIsArrayElement = true;
391 // The value in MostDerivedArraySize is undefined in this case. So, set it
392 // to an arbitrary value that's likely to loudly break things if it's
393 // used.
394 MostDerivedArraySize = AssumedSizeForUnsizedArray;
395 MostDerivedPathLength = Entries.size();
396 }
397 /// Update this designator to refer to the given base or member of this
398 /// object.
399 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
400 Entries.push_back(APValue::BaseOrMemberType(D, Virtual));
401
402 // If this isn't a base class, it's a new most-derived object.
403 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
404 MostDerivedType = FD->getType();
405 MostDerivedIsArrayElement = false;
406 MostDerivedArraySize = 0;
407 MostDerivedPathLength = Entries.size();
408 }
409 }
410 /// Update this designator to refer to the given complex component.
411 void addComplexUnchecked(QualType EltTy, bool Imag) {
412 Entries.push_back(PathEntry::ArrayIndex(Imag));
413
414 // This is technically a most-derived object, though in practice this
415 // is unlikely to matter.
416 MostDerivedType = EltTy;
417 MostDerivedIsArrayElement = true;
418 MostDerivedArraySize = 2;
419 MostDerivedPathLength = Entries.size();
420 }
421
422 void addVectorElementUnchecked(QualType EltTy, uint64_t Size,
423 uint64_t Idx) {
424 Entries.push_back(PathEntry::ArrayIndex(Idx));
425 MostDerivedType = EltTy;
426 MostDerivedPathLength = Entries.size();
427 MostDerivedArraySize = 0;
428 MostDerivedIsArrayElement = false;
429 }
430
431 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
432 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
433 const APSInt &N);
434 /// Add N to the address of this subobject.
435 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N, const LValue &LV);
436 };
437
438 /// A scope at the end of which an object can need to be destroyed.
439 enum class ScopeKind {
440 Block,
441 FullExpression,
442 Call
443 };
444
445 /// A reference to a particular call and its arguments.
446 struct CallRef {
447 CallRef() : OrigCallee(), CallIndex(0), Version() {}
448 CallRef(const FunctionDecl *Callee, unsigned CallIndex, unsigned Version)
449 : OrigCallee(Callee), CallIndex(CallIndex), Version(Version) {}
450
451 explicit operator bool() const { return OrigCallee; }
452
453 /// Get the parameter that the caller initialized, corresponding to the
454 /// given parameter in the callee.
455 const ParmVarDecl *getOrigParam(const ParmVarDecl *PVD) const {
456 return OrigCallee ? OrigCallee->getParamDecl(PVD->getFunctionScopeIndex())
457 : PVD;
458 }
459
460 /// The callee at the point where the arguments were evaluated. This might
461 /// be different from the actual callee (a different redeclaration, or a
462 /// virtual override), but this function's parameters are the ones that
463 /// appear in the parameter map.
464 const FunctionDecl *OrigCallee;
465 /// The call index of the frame that holds the argument values.
466 unsigned CallIndex;
467 /// The version of the parameters corresponding to this call.
468 unsigned Version;
469 };
470
471 /// A stack frame in the constexpr call stack.
472 class CallStackFrame : public interp::Frame {
473 public:
474 EvalInfo &Info;
475
476 /// Parent - The caller of this stack frame.
477 CallStackFrame *Caller;
478
479 /// Callee - The function which was called.
480 const FunctionDecl *Callee;
481
482 /// This - The binding for the this pointer in this call, if any.
483 const LValue *This;
484
485 /// CallExpr - The syntactical structure of member function calls
486 const Expr *CallExpr;
487
488 /// Information on how to find the arguments to this call. Our arguments
489 /// are stored in our parent's CallStackFrame, using the ParmVarDecl* as a
490 /// key and this value as the version.
491 CallRef Arguments;
492
493 /// Source location information about the default argument or default
494 /// initializer expression we're evaluating, if any.
495 CurrentSourceLocExprScope CurSourceLocExprScope;
496
497 // Note that we intentionally use std::map here so that references to
498 // values are stable.
499 typedef std::pair<const void *, unsigned> MapKeyTy;
500 typedef std::map<MapKeyTy, APValue> MapTy;
501 /// Temporaries - Temporary lvalues materialized within this stack frame.
502 MapTy Temporaries;
503
504 /// CallRange - The source range of the call expression for this call.
505 SourceRange CallRange;
506
507 /// Index - The call index of this call.
508 unsigned Index;
509
510 /// The stack of integers for tracking version numbers for temporaries.
511 SmallVector<unsigned, 2> TempVersionStack = {1};
512 unsigned CurTempVersion = TempVersionStack.back();
513
514 unsigned getTempVersion() const { return TempVersionStack.back(); }
515
516 void pushTempVersion() {
517 TempVersionStack.push_back(++CurTempVersion);
518 }
519
520 void popTempVersion() {
521 TempVersionStack.pop_back();
522 }
523
524 CallRef createCall(const FunctionDecl *Callee) {
525 return {Callee, Index, ++CurTempVersion};
526 }
527
528 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
529 // on the overall stack usage of deeply-recursing constexpr evaluations.
530 // (We should cache this map rather than recomputing it repeatedly.)
531 // But let's try this and see how it goes; we can look into caching the map
532 // as a later change.
533
534 /// LambdaCaptureFields - Mapping from captured variables/this to
535 /// corresponding data members in the closure class.
536 llvm::DenseMap<const ValueDecl *, FieldDecl *> LambdaCaptureFields;
537 FieldDecl *LambdaThisCaptureField = nullptr;
538
539 CallStackFrame(EvalInfo &Info, SourceRange CallRange,
540 const FunctionDecl *Callee, const LValue *This,
541 const Expr *CallExpr, CallRef Arguments);
542 ~CallStackFrame();
543
544 // Return the temporary for Key whose version number is Version.
545 APValue *getTemporary(const void *Key, unsigned Version) {
546 MapKeyTy KV(Key, Version);
547 auto LB = Temporaries.lower_bound(KV);
548 if (LB != Temporaries.end() && LB->first == KV)
549 return &LB->second;
550 return nullptr;
551 }
552
553 // Return the current temporary for Key in the map.
554 APValue *getCurrentTemporary(const void *Key) {
555 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
556 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
557 return &std::prev(UB)->second;
558 return nullptr;
559 }
560
561 // Return the version number of the current temporary for Key.
562 unsigned getCurrentTemporaryVersion(const void *Key) const {
563 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
564 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
565 return std::prev(UB)->first.second;
566 return 0;
567 }
568
569 /// Allocate storage for an object of type T in this stack frame.
570 /// Populates LV with a handle to the created object. Key identifies
571 /// the temporary within the stack frame, and must not be reused without
572 /// bumping the temporary version number.
573 template<typename KeyT>
574 APValue &createTemporary(const KeyT *Key, QualType T,
575 ScopeKind Scope, LValue &LV);
576
577 /// Allocate storage for a parameter of a function call made in this frame.
578 APValue &createParam(CallRef Args, const ParmVarDecl *PVD, LValue &LV);
579
580 void describe(llvm::raw_ostream &OS) const override;
581
582 Frame *getCaller() const override { return Caller; }
583 SourceRange getCallRange() const override { return CallRange; }
584 const FunctionDecl *getCallee() const override { return Callee; }
585
586 bool isStdFunction() const {
587 for (const DeclContext *DC = Callee; DC; DC = DC->getParent())
588 if (DC->isStdNamespace())
589 return true;
590 return false;
591 }
592
593 /// Whether we're in a context where [[msvc::constexpr]] evaluation is
594 /// permitted. See MSConstexprDocs for description of permitted contexts.
595 bool CanEvalMSConstexpr = false;
596
597 private:
598 APValue &createLocal(APValue::LValueBase Base, const void *Key, QualType T,
599 ScopeKind Scope);
600 };
601
602 /// Temporarily override 'this'.
603 class ThisOverrideRAII {
604 public:
605 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
606 : Frame(Frame), OldThis(Frame.This) {
607 if (Enable)
608 Frame.This = NewThis;
609 }
610 ~ThisOverrideRAII() {
611 Frame.This = OldThis;
612 }
613 private:
614 CallStackFrame &Frame;
615 const LValue *OldThis;
616 };
617
618 // A shorthand time trace scope struct, prints source range, for example
619 // {"name":"EvaluateAsRValue","args":{"detail":"<test.cc:8:21, col:25>"}}}
620 class ExprTimeTraceScope {
621 public:
622 ExprTimeTraceScope(const Expr *E, const ASTContext &Ctx, StringRef Name)
623 : TimeScope(Name, [E, &Ctx] {
625 }) {}
626
627 private:
628 llvm::TimeTraceScope TimeScope;
629 };
630
631 /// RAII object used to change the current ability of
632 /// [[msvc::constexpr]] evaulation.
633 struct MSConstexprContextRAII {
634 CallStackFrame &Frame;
635 bool OldValue;
636 explicit MSConstexprContextRAII(CallStackFrame &Frame, bool Value)
637 : Frame(Frame), OldValue(Frame.CanEvalMSConstexpr) {
638 Frame.CanEvalMSConstexpr = Value;
639 }
640
641 ~MSConstexprContextRAII() { Frame.CanEvalMSConstexpr = OldValue; }
642 };
643}
644
645static bool HandleDestruction(EvalInfo &Info, const Expr *E,
646 const LValue &This, QualType ThisType);
647static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
649 QualType T);
650
651namespace {
652 /// A cleanup, and a flag indicating whether it is lifetime-extended.
653 class Cleanup {
654 llvm::PointerIntPair<APValue*, 2, ScopeKind> Value;
655 APValue::LValueBase Base;
656 QualType T;
657
658 public:
659 Cleanup(APValue *Val, APValue::LValueBase Base, QualType T,
660 ScopeKind Scope)
661 : Value(Val, Scope), Base(Base), T(T) {}
662
663 /// Determine whether this cleanup should be performed at the end of the
664 /// given kind of scope.
665 bool isDestroyedAtEndOf(ScopeKind K) const {
666 return (int)Value.getInt() >= (int)K;
667 }
668 bool endLifetime(EvalInfo &Info, bool RunDestructors) {
669 if (RunDestructors) {
670 SourceLocation Loc;
671 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>())
672 Loc = VD->getLocation();
673 else if (const Expr *E = Base.dyn_cast<const Expr*>())
674 Loc = E->getExprLoc();
675 return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T);
676 }
677 *Value.getPointer() = APValue();
678 return true;
679 }
680
681 bool hasSideEffect() {
682 return T.isDestructedType();
683 }
684 };
685
686 /// A reference to an object whose construction we are currently evaluating.
687 struct ObjectUnderConstruction {
688 APValue::LValueBase Base;
689 ArrayRef<APValue::LValuePathEntry> Path;
690 friend bool operator==(const ObjectUnderConstruction &LHS,
691 const ObjectUnderConstruction &RHS) {
692 return LHS.Base == RHS.Base && LHS.Path == RHS.Path;
693 }
694 friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {
695 return llvm::hash_combine(Obj.Base, Obj.Path);
696 }
697 };
698 enum class ConstructionPhase {
699 None,
700 Bases,
701 AfterBases,
702 AfterFields,
703 Destroying,
704 DestroyingBases
705 };
706}
707
708namespace llvm {
709template<> struct DenseMapInfo<ObjectUnderConstruction> {
710 using Base = DenseMapInfo<APValue::LValueBase>;
711 static unsigned getHashValue(const ObjectUnderConstruction &Object) {
712 return hash_value(Object);
713 }
714 static bool isEqual(const ObjectUnderConstruction &LHS,
715 const ObjectUnderConstruction &RHS) {
716 return LHS == RHS;
717 }
718};
719}
720
721namespace {
722 /// A dynamically-allocated heap object.
723 struct DynAlloc {
724 /// The value of this heap-allocated object.
725 APValue Value;
726 /// The allocating expression; used for diagnostics. Either a CXXNewExpr
727 /// or a CallExpr (the latter is for direct calls to operator new inside
728 /// std::allocator<T>::allocate).
729 const Expr *AllocExpr = nullptr;
730
731 enum Kind {
732 New,
733 ArrayNew,
734 StdAllocator
735 };
736
737 /// Get the kind of the allocation. This must match between allocation
738 /// and deallocation.
739 Kind getKind() const {
740 if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr))
741 return NE->isArray() ? ArrayNew : New;
742 assert(isa<CallExpr>(AllocExpr));
743 return StdAllocator;
744 }
745 };
746
747 struct DynAllocOrder {
748 bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const {
749 return L.getIndex() < R.getIndex();
750 }
751 };
752
753 /// EvalInfo - This is a private struct used by the evaluator to capture
754 /// information about a subexpression as it is folded. It retains information
755 /// about the AST context, but also maintains information about the folded
756 /// expression.
757 ///
758 /// If an expression could be evaluated, it is still possible it is not a C
759 /// "integer constant expression" or constant expression. If not, this struct
760 /// captures information about how and why not.
761 ///
762 /// One bit of information passed *into* the request for constant folding
763 /// indicates whether the subexpression is "evaluated" or not according to C
764 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
765 /// evaluate the expression regardless of what the RHS is, but C only allows
766 /// certain things in certain situations.
767 class EvalInfo final : public interp::State {
768 public:
769 /// CurrentCall - The top of the constexpr call stack.
770 CallStackFrame *CurrentCall;
771
772 /// CallStackDepth - The number of calls in the call stack right now.
773 unsigned CallStackDepth;
774
775 /// NextCallIndex - The next call index to assign.
776 unsigned NextCallIndex;
777
778 /// StepsLeft - The remaining number of evaluation steps we're permitted
779 /// to perform. This is essentially a limit for the number of statements
780 /// we will evaluate.
781 unsigned StepsLeft;
782
783 /// BottomFrame - The frame in which evaluation started. This must be
784 /// initialized after CurrentCall and CallStackDepth.
785 CallStackFrame BottomFrame;
786
787 /// A stack of values whose lifetimes end at the end of some surrounding
788 /// evaluation frame.
789 llvm::SmallVector<Cleanup, 16> CleanupStack;
790
791 /// EvaluatingDecl - This is the declaration whose initializer is being
792 /// evaluated, if any.
793 APValue::LValueBase EvaluatingDecl;
794
795 enum class EvaluatingDeclKind {
796 None,
797 /// We're evaluating the construction of EvaluatingDecl.
798 Ctor,
799 /// We're evaluating the destruction of EvaluatingDecl.
800 Dtor,
801 };
802 EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None;
803
804 /// EvaluatingDeclValue - This is the value being constructed for the
805 /// declaration whose initializer is being evaluated, if any.
806 APValue *EvaluatingDeclValue;
807
808 /// Stack of loops and 'switch' statements which we're currently
809 /// breaking/continuing; null entries are used to mark unlabeled
810 /// break/continue.
811 SmallVector<const Stmt *> BreakContinueStack;
812
813 /// Set of objects that are currently being constructed.
814 llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
815 ObjectsUnderConstruction;
816
817 /// Current heap allocations, along with the location where each was
818 /// allocated. We use std::map here because we need stable addresses
819 /// for the stored APValues.
820 std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs;
821
822 /// The number of heap allocations performed so far in this evaluation.
823 unsigned NumHeapAllocs = 0;
824
825 struct EvaluatingConstructorRAII {
826 EvalInfo &EI;
827 ObjectUnderConstruction Object;
828 bool DidInsert;
829 EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
830 bool HasBases)
831 : EI(EI), Object(Object) {
832 DidInsert =
833 EI.ObjectsUnderConstruction
834 .insert({Object, HasBases ? ConstructionPhase::Bases
835 : ConstructionPhase::AfterBases})
836 .second;
837 }
838 void finishedConstructingBases() {
839 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
840 }
841 void finishedConstructingFields() {
842 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields;
843 }
844 ~EvaluatingConstructorRAII() {
845 if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
846 }
847 };
848
849 struct EvaluatingDestructorRAII {
850 EvalInfo &EI;
851 ObjectUnderConstruction Object;
852 bool DidInsert;
853 EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object)
854 : EI(EI), Object(Object) {
855 DidInsert = EI.ObjectsUnderConstruction
856 .insert({Object, ConstructionPhase::Destroying})
857 .second;
858 }
859 void startedDestroyingBases() {
860 EI.ObjectsUnderConstruction[Object] =
861 ConstructionPhase::DestroyingBases;
862 }
863 ~EvaluatingDestructorRAII() {
864 if (DidInsert)
865 EI.ObjectsUnderConstruction.erase(Object);
866 }
867 };
868
869 ConstructionPhase
870 isEvaluatingCtorDtor(APValue::LValueBase Base,
871 ArrayRef<APValue::LValuePathEntry> Path) {
872 return ObjectsUnderConstruction.lookup({Base, Path});
873 }
874
875 /// If we're currently speculatively evaluating, the outermost call stack
876 /// depth at which we can mutate state, otherwise 0.
877 unsigned SpeculativeEvaluationDepth = 0;
878
879 /// The current array initialization index, if we're performing array
880 /// initialization.
881 uint64_t ArrayInitIndex = -1;
882
883 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
884 : State(const_cast<ASTContext &>(C), S), CurrentCall(nullptr),
885 CallStackDepth(0), NextCallIndex(1),
886 StepsLeft(C.getLangOpts().ConstexprStepLimit),
887 BottomFrame(*this, SourceLocation(), /*Callee=*/nullptr,
888 /*This=*/nullptr,
889 /*CallExpr=*/nullptr, CallRef()),
890 EvaluatingDecl((const ValueDecl *)nullptr),
891 EvaluatingDeclValue(nullptr) {
892 EvalMode = Mode;
893 }
894
895 ~EvalInfo() {
896 discardCleanups();
897 }
898
899 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value,
900 EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) {
901 EvaluatingDecl = Base;
902 IsEvaluatingDecl = EDK;
903 EvaluatingDeclValue = &Value;
904 }
905
906 bool CheckCallLimit(SourceLocation Loc) {
907 // Don't perform any constexpr calls (other than the call we're checking)
908 // when checking a potential constant expression.
909 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
910 return false;
911 if (NextCallIndex == 0) {
912 // NextCallIndex has wrapped around.
913 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
914 return false;
915 }
916 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
917 return true;
918 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
919 << getLangOpts().ConstexprCallDepth;
920 return false;
921 }
922
923 bool CheckArraySize(SourceLocation Loc, unsigned BitWidth,
924 uint64_t ElemCount, bool Diag) {
925 // FIXME: GH63562
926 // APValue stores array extents as unsigned,
927 // so anything that is greater that unsigned would overflow when
928 // constructing the array, we catch this here.
929 if (BitWidth > ConstantArrayType::getMaxSizeBits(Ctx) ||
930 ElemCount > uint64_t(std::numeric_limits<unsigned>::max())) {
931 if (Diag)
932 FFDiag(Loc, diag::note_constexpr_new_too_large) << ElemCount;
933 return false;
934 }
935
936 // FIXME: GH63562
937 // Arrays allocate an APValue per element.
938 // We use the number of constexpr steps as a proxy for the maximum size
939 // of arrays to avoid exhausting the system resources, as initialization
940 // of each element is likely to take some number of steps anyway.
941 uint64_t Limit = getLangOpts().ConstexprStepLimit;
942 if (Limit != 0 && ElemCount > Limit) {
943 if (Diag) {
944 FFDiag(Loc, diag::note_constexpr_new_exceeds_limits, 1)
945 << ElemCount << Limit;
946 Note(Loc, diag::note_constexpr_steps);
947 }
948 return false;
949 }
950 return true;
951 }
952
953 std::pair<CallStackFrame *, unsigned>
954 getCallFrameAndDepth(unsigned CallIndex) {
955 assert(CallIndex && "no call index in getCallFrameAndDepth");
956 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
957 // be null in this loop.
958 unsigned Depth = CallStackDepth;
959 CallStackFrame *Frame = CurrentCall;
960 while (Frame->Index > CallIndex) {
961 Frame = Frame->Caller;
962 --Depth;
963 }
964 if (Frame->Index == CallIndex)
965 return {Frame, Depth};
966 return {nullptr, 0};
967 }
968
969 bool nextStep(const Stmt *S) {
970 if (getLangOpts().ConstexprStepLimit == 0)
971 return true;
972
973 if (!StepsLeft) {
974 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded, 1)
975 << getLangOpts().ConstexprStepLimit;
976 Note(S->getBeginLoc(), diag::note_constexpr_steps);
977 return false;
978 }
979 --StepsLeft;
980 return true;
981 }
982
983 APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV);
984
985 std::optional<DynAlloc *> lookupDynamicAlloc(DynamicAllocLValue DA) {
986 std::optional<DynAlloc *> Result;
987 auto It = HeapAllocs.find(DA);
988 if (It != HeapAllocs.end())
989 Result = &It->second;
990 return Result;
991 }
992
993 /// Get the allocated storage for the given parameter of the given call.
994 APValue *getParamSlot(CallRef Call, const ParmVarDecl *PVD) {
995 CallStackFrame *Frame = getCallFrameAndDepth(Call.CallIndex).first;
996 return Frame ? Frame->getTemporary(Call.getOrigParam(PVD), Call.Version)
997 : nullptr;
998 }
999
1000 /// Information about a stack frame for std::allocator<T>::[de]allocate.
1001 struct StdAllocatorCaller {
1002 unsigned FrameIndex;
1003 QualType ElemType;
1004 const Expr *Call;
1005 explicit operator bool() const { return FrameIndex != 0; };
1006 };
1007
1008 StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const {
1009 for (const CallStackFrame *Call = CurrentCall; Call->Caller != nullptr;
1010 Call = Call->Caller) {
1011 const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee);
1012 if (!MD)
1013 continue;
1014 const IdentifierInfo *FnII = MD->getIdentifier();
1015 if (!FnII || !FnII->isStr(FnName))
1016 continue;
1017
1018 const auto *CTSD =
1019 dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent());
1020 if (!CTSD)
1021 continue;
1022
1023 const IdentifierInfo *ClassII = CTSD->getIdentifier();
1024 const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
1025 if (CTSD->isInStdNamespace() && ClassII &&
1026 ClassII->isStr("allocator") && TAL.size() >= 1 &&
1027 TAL[0].getKind() == TemplateArgument::Type)
1028 return {Call->Index, TAL[0].getAsType(), Call->CallExpr};
1029 }
1030
1031 return {};
1032 }
1033
1034 void performLifetimeExtension() {
1035 // Disable the cleanups for lifetime-extended temporaries.
1036 llvm::erase_if(CleanupStack, [](Cleanup &C) {
1037 return !C.isDestroyedAtEndOf(ScopeKind::FullExpression);
1038 });
1039 }
1040
1041 /// Throw away any remaining cleanups at the end of evaluation. If any
1042 /// cleanups would have had a side-effect, note that as an unmodeled
1043 /// side-effect and return false. Otherwise, return true.
1044 bool discardCleanups() {
1045 for (Cleanup &C : CleanupStack) {
1046 if (C.hasSideEffect() && !noteSideEffect()) {
1047 CleanupStack.clear();
1048 return false;
1049 }
1050 }
1051 CleanupStack.clear();
1052 return true;
1053 }
1054
1055 private:
1056 const interp::Frame *getCurrentFrame() override { return CurrentCall; }
1057
1058 unsigned getCallStackDepth() override { return CallStackDepth; }
1059 bool stepsLeft() const override { return StepsLeft > 0; }
1060
1061 public:
1062 /// Notes that we failed to evaluate an expression that other expressions
1063 /// directly depend on, and determine if we should keep evaluating. This
1064 /// should only be called if we actually intend to keep evaluating.
1065 ///
1066 /// Call noteSideEffect() instead if we may be able to ignore the value that
1067 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1068 ///
1069 /// (Foo(), 1) // use noteSideEffect
1070 /// (Foo() || true) // use noteSideEffect
1071 /// Foo() + 1 // use noteFailure
1072 [[nodiscard]] bool noteFailure() {
1073 // Failure when evaluating some expression often means there is some
1074 // subexpression whose evaluation was skipped. Therefore, (because we
1075 // don't track whether we skipped an expression when unwinding after an
1076 // evaluation failure) every evaluation failure that bubbles up from a
1077 // subexpression implies that a side-effect has potentially happened. We
1078 // skip setting the HasSideEffects flag to true until we decide to
1079 // continue evaluating after that point, which happens here.
1080 bool KeepGoing = keepEvaluatingAfterFailure();
1081 EvalStatus.HasSideEffects |= KeepGoing;
1082 return KeepGoing;
1083 }
1084
1085 class ArrayInitLoopIndex {
1086 EvalInfo &Info;
1087 uint64_t OuterIndex;
1088
1089 public:
1090 ArrayInitLoopIndex(EvalInfo &Info)
1091 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1092 Info.ArrayInitIndex = 0;
1093 }
1094 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1095
1096 operator uint64_t&() { return Info.ArrayInitIndex; }
1097 };
1098 };
1099
1100 /// Object used to treat all foldable expressions as constant expressions.
1101 struct FoldConstant {
1102 EvalInfo &Info;
1103 bool Enabled;
1104 bool HadNoPriorDiags;
1105 EvaluationMode OldMode;
1106
1107 explicit FoldConstant(EvalInfo &Info, bool Enabled)
1108 : Info(Info),
1109 Enabled(Enabled),
1110 HadNoPriorDiags(Info.EvalStatus.Diag &&
1111 Info.EvalStatus.Diag->empty() &&
1112 !Info.EvalStatus.HasSideEffects),
1113 OldMode(Info.EvalMode) {
1114 if (Enabled)
1115 Info.EvalMode = EvaluationMode::ConstantFold;
1116 }
1117 void keepDiagnostics() { Enabled = false; }
1118 ~FoldConstant() {
1119 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
1120 !Info.EvalStatus.HasSideEffects) {
1121 Info.EvalStatus.Diag->clear();
1122 Info.EvalStatus.DiagEmitted = false;
1123 }
1124 Info.EvalMode = OldMode;
1125 }
1126 };
1127
1128 /// RAII object used to set the current evaluation mode to ignore
1129 /// side-effects.
1130 struct IgnoreSideEffectsRAII {
1131 EvalInfo &Info;
1132 EvaluationMode OldMode;
1133 explicit IgnoreSideEffectsRAII(EvalInfo &Info)
1134 : Info(Info), OldMode(Info.EvalMode) {
1135 Info.EvalMode = EvaluationMode::IgnoreSideEffects;
1136 }
1137
1138 ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
1139 };
1140
1141 /// RAII object used to optionally suppress diagnostics and side-effects from
1142 /// a speculative evaluation.
1143 class SpeculativeEvaluationRAII {
1144 EvalInfo *Info = nullptr;
1145 Expr::EvalStatus OldStatus;
1146 unsigned OldSpeculativeEvaluationDepth = 0;
1147
1148 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1149 Info = Other.Info;
1150 OldStatus = Other.OldStatus;
1151 OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
1152 Other.Info = nullptr;
1153 }
1154
1155 void maybeRestoreState() {
1156 if (!Info)
1157 return;
1158
1159 Info->EvalStatus = OldStatus;
1160 Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
1161 }
1162
1163 public:
1164 SpeculativeEvaluationRAII() = default;
1165
1166 SpeculativeEvaluationRAII(
1167 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1168 : Info(&Info), OldStatus(Info.EvalStatus),
1169 OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
1170 Info.EvalStatus.Diag = NewDiag;
1171 Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
1172 }
1173
1174 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1175 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1176 moveFromAndCancel(std::move(Other));
1177 }
1178
1179 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1180 maybeRestoreState();
1181 moveFromAndCancel(std::move(Other));
1182 return *this;
1183 }
1184
1185 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1186 };
1187
1188 /// RAII object wrapping a full-expression or block scope, and handling
1189 /// the ending of the lifetime of temporaries created within it.
1190 template<ScopeKind Kind>
1191 class ScopeRAII {
1192 EvalInfo &Info;
1193 unsigned OldStackSize;
1194 public:
1195 ScopeRAII(EvalInfo &Info)
1196 : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1197 // Push a new temporary version. This is needed to distinguish between
1198 // temporaries created in different iterations of a loop.
1199 Info.CurrentCall->pushTempVersion();
1200 }
1201 bool destroy(bool RunDestructors = true) {
1202 bool OK = cleanup(Info, RunDestructors, OldStackSize);
1203 OldStackSize = std::numeric_limits<unsigned>::max();
1204 return OK;
1205 }
1206 ~ScopeRAII() {
1207 if (OldStackSize != std::numeric_limits<unsigned>::max())
1208 destroy(false);
1209 // Body moved to a static method to encourage the compiler to inline away
1210 // instances of this class.
1211 Info.CurrentCall->popTempVersion();
1212 }
1213 private:
1214 static bool cleanup(EvalInfo &Info, bool RunDestructors,
1215 unsigned OldStackSize) {
1216 assert(OldStackSize <= Info.CleanupStack.size() &&
1217 "running cleanups out of order?");
1218
1219 // Run all cleanups for a block scope, and non-lifetime-extended cleanups
1220 // for a full-expression scope.
1221 bool Success = true;
1222 for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) {
1223 if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) {
1224 if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) {
1225 Success = false;
1226 break;
1227 }
1228 }
1229 }
1230
1231 // Compact any retained cleanups.
1232 auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
1233 if (Kind != ScopeKind::Block)
1234 NewEnd =
1235 std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) {
1236 return C.isDestroyedAtEndOf(Kind);
1237 });
1238 Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
1239 return Success;
1240 }
1241 };
1242 typedef ScopeRAII<ScopeKind::Block> BlockScopeRAII;
1243 typedef ScopeRAII<ScopeKind::FullExpression> FullExpressionRAII;
1244 typedef ScopeRAII<ScopeKind::Call> CallScopeRAII;
1245}
1246
1247bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1248 CheckSubobjectKind CSK) {
1249 if (Invalid)
1250 return false;
1251 if (isOnePastTheEnd()) {
1252 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1253 << CSK;
1254 setInvalid();
1255 return false;
1256 }
1257 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1258 // must actually be at least one array element; even a VLA cannot have a
1259 // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1260 return true;
1261}
1262
1263void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1264 const Expr *E) {
1265 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1266 // Do not set the designator as invalid: we can represent this situation,
1267 // and correct handling of __builtin_object_size requires us to do so.
1268}
1269
1270void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1271 const Expr *E,
1272 const APSInt &N) {
1273 // If we're complaining, we must be able to statically determine the size of
1274 // the most derived array.
1275 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1276 Info.CCEDiag(E, diag::note_constexpr_array_index)
1277 << N << /*array*/ 0
1278 << static_cast<unsigned>(getMostDerivedArraySize());
1279 else
1280 Info.CCEDiag(E, diag::note_constexpr_array_index)
1281 << N << /*non-array*/ 1;
1282 setInvalid();
1283}
1284
1285CallStackFrame::CallStackFrame(EvalInfo &Info, SourceRange CallRange,
1286 const FunctionDecl *Callee, const LValue *This,
1287 const Expr *CallExpr, CallRef Call)
1288 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1289 CallExpr(CallExpr), Arguments(Call), CallRange(CallRange),
1290 Index(Info.NextCallIndex++) {
1291 Info.CurrentCall = this;
1292 ++Info.CallStackDepth;
1293}
1294
1295CallStackFrame::~CallStackFrame() {
1296 assert(Info.CurrentCall == this && "calls retired out of order");
1297 --Info.CallStackDepth;
1298 Info.CurrentCall = Caller;
1299}
1300
1301static bool isRead(AccessKinds AK) {
1302 return AK == AK_Read || AK == AK_ReadObjectRepresentation ||
1303 AK == AK_IsWithinLifetime || AK == AK_Dereference;
1304}
1305
1307 switch (AK) {
1308 case AK_Read:
1310 case AK_MemberCall:
1311 case AK_DynamicCast:
1312 case AK_TypeId:
1314 case AK_Dereference:
1315 return false;
1316 case AK_Assign:
1317 case AK_Increment:
1318 case AK_Decrement:
1319 case AK_Construct:
1320 case AK_Destroy:
1321 return true;
1322 }
1323 llvm_unreachable("unknown access kind");
1324}
1325
1326static bool isAnyAccess(AccessKinds AK) {
1327 return isRead(AK) || isModification(AK);
1328}
1329
1330/// Is this an access per the C++ definition?
1332 return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy &&
1333 AK != AK_IsWithinLifetime && AK != AK_Dereference;
1334}
1335
1336/// Is this kind of access valid on an indeterminate object value?
1338 switch (AK) {
1339 case AK_Read:
1340 case AK_Increment:
1341 case AK_Decrement:
1342 case AK_Dereference:
1343 // These need the object's value.
1344 return false;
1345
1348 case AK_Assign:
1349 case AK_Construct:
1350 case AK_Destroy:
1351 // Construction and destruction don't need the value.
1352 return true;
1353
1354 case AK_MemberCall:
1355 case AK_DynamicCast:
1356 case AK_TypeId:
1357 // These aren't really meaningful on scalars.
1358 return true;
1359 }
1360 llvm_unreachable("unknown access kind");
1361}
1362
1363namespace {
1364 struct ComplexValue {
1365 private:
1366 bool IsInt;
1367
1368 public:
1369 APSInt IntReal, IntImag;
1370 APFloat FloatReal, FloatImag;
1371
1372 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1373
1374 void makeComplexFloat() { IsInt = false; }
1375 bool isComplexFloat() const { return !IsInt; }
1376 APFloat &getComplexFloatReal() { return FloatReal; }
1377 APFloat &getComplexFloatImag() { return FloatImag; }
1378
1379 void makeComplexInt() { IsInt = true; }
1380 bool isComplexInt() const { return IsInt; }
1381 APSInt &getComplexIntReal() { return IntReal; }
1382 APSInt &getComplexIntImag() { return IntImag; }
1383
1384 void moveInto(APValue &v) const {
1385 if (isComplexFloat())
1386 v = APValue(FloatReal, FloatImag);
1387 else
1388 v = APValue(IntReal, IntImag);
1389 }
1390 void setFrom(const APValue &v) {
1391 assert(v.isComplexFloat() || v.isComplexInt());
1392 if (v.isComplexFloat()) {
1393 makeComplexFloat();
1394 FloatReal = v.getComplexFloatReal();
1395 FloatImag = v.getComplexFloatImag();
1396 } else {
1397 makeComplexInt();
1398 IntReal = v.getComplexIntReal();
1399 IntImag = v.getComplexIntImag();
1400 }
1401 }
1402 };
1403
1404 struct LValue {
1405 APValue::LValueBase Base;
1406 CharUnits Offset;
1407 SubobjectDesignator Designator;
1408 bool IsNullPtr : 1;
1409 bool InvalidBase : 1;
1410 // P2280R4 track if we have an unknown reference or pointer.
1411 bool AllowConstexprUnknown = false;
1412
1413 const APValue::LValueBase getLValueBase() const { return Base; }
1414 bool allowConstexprUnknown() const { return AllowConstexprUnknown; }
1415 CharUnits &getLValueOffset() { return Offset; }
1416 CharUnits getLValueOffset() const { return Offset; }
1417 SubobjectDesignator &getLValueDesignator() { return Designator; }
1418 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1419 bool isNullPointer() const { return IsNullPtr;}
1420
1421 unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1422 unsigned getLValueVersion() const { return Base.getVersion(); }
1423
1424 bool pointsToCompleteClass(const CXXRecordDecl *D) const {
1425 if (Designator.Entries.empty())
1426 return true;
1427
1428 return Designator.MostDerivedType->getAsCXXRecordDecl() == D;
1429 }
1430
1431 void moveInto(APValue &V) const {
1432 if (Designator.Invalid)
1433 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
1434 else {
1435 assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1436 V = APValue(Base, Offset, Designator.Entries,
1437 Designator.IsOnePastTheEnd, IsNullPtr);
1438 }
1439 if (AllowConstexprUnknown)
1440 V.setConstexprUnknown();
1441 }
1442 void setFrom(const ASTContext &Ctx, const APValue &V) {
1443 assert(V.isLValue() && "Setting LValue from a non-LValue?");
1444 Base = V.getLValueBase();
1445 Offset = V.getLValueOffset();
1446 InvalidBase = false;
1447 Designator = SubobjectDesignator(Ctx, V);
1448 IsNullPtr = V.isNullPointer();
1449 AllowConstexprUnknown = V.allowConstexprUnknown();
1450 }
1451
1452 void set(APValue::LValueBase B, bool BInvalid = false) {
1453#ifndef NDEBUG
1454 // We only allow a few types of invalid bases. Enforce that here.
1455 if (BInvalid) {
1456 const auto *E = B.get<const Expr *>();
1457 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1458 "Unexpected type of invalid base");
1459 }
1460#endif
1461
1462 Base = B;
1463 Offset = CharUnits::fromQuantity(0);
1464 InvalidBase = BInvalid;
1465 Designator = SubobjectDesignator(getType(B));
1466 IsNullPtr = false;
1467 AllowConstexprUnknown = false;
1468 }
1469
1470 void setNull(ASTContext &Ctx, QualType PointerTy) {
1471 Base = (const ValueDecl *)nullptr;
1472 Offset =
1474 InvalidBase = false;
1475 Designator = SubobjectDesignator(PointerTy->getPointeeType());
1476 IsNullPtr = true;
1477 AllowConstexprUnknown = false;
1478 }
1479
1480 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1481 set(B, true);
1482 }
1483
1484 std::string toString(ASTContext &Ctx, QualType T) const {
1485 APValue Printable;
1486 moveInto(Printable);
1487 return Printable.getAsString(Ctx, T);
1488 }
1489
1490 private:
1491 // Check that this LValue is not based on a null pointer. If it is, produce
1492 // a diagnostic and mark the designator as invalid.
1493 template <typename GenDiagType>
1494 bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
1495 if (Designator.Invalid)
1496 return false;
1497 if (IsNullPtr) {
1498 GenDiag();
1499 Designator.setInvalid();
1500 return false;
1501 }
1502 return true;
1503 }
1504
1505 public:
1506 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1507 CheckSubobjectKind CSK) {
1508 return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1509 Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1510 });
1511 }
1512
1513 bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1514 AccessKinds AK) {
1515 return checkNullPointerDiagnosingWith([&Info, E, AK] {
1516 if (AK == AccessKinds::AK_Dereference)
1517 Info.FFDiag(E, diag::note_constexpr_dereferencing_null);
1518 else
1519 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1520 });
1521 }
1522
1523 // Check this LValue refers to an object. If not, set the designator to be
1524 // invalid and emit a diagnostic.
1525 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1526 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1527 Designator.checkSubobject(Info, E, CSK);
1528 }
1529
1530 void addDecl(EvalInfo &Info, const Expr *E,
1531 const Decl *D, bool Virtual = false) {
1532 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1533 Designator.addDeclUnchecked(D, Virtual);
1534 }
1535 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1536 if (!Designator.Entries.empty()) {
1537 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1538 Designator.setInvalid();
1539 return;
1540 }
1541 if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1542 assert(!Base || getType(Base).getNonReferenceType()->isPointerType() ||
1543 getType(Base).getNonReferenceType()->isArrayType());
1544 Designator.FirstEntryIsAnUnsizedArray = true;
1545 Designator.addUnsizedArrayUnchecked(ElemTy);
1546 }
1547 }
1548 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1549 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1550 Designator.addArrayUnchecked(CAT);
1551 }
1552 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1553 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1554 Designator.addComplexUnchecked(EltTy, Imag);
1555 }
1556 void addVectorElement(EvalInfo &Info, const Expr *E, QualType EltTy,
1557 uint64_t Size, uint64_t Idx) {
1558 if (checkSubobject(Info, E, CSK_VectorElement))
1559 Designator.addVectorElementUnchecked(EltTy, Size, Idx);
1560 }
1561 void clearIsNullPointer() {
1562 IsNullPtr = false;
1563 }
1564 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1565 const APSInt &Index, CharUnits ElementSize) {
1566 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1567 // but we're not required to diagnose it and it's valid in C++.)
1568 if (!Index)
1569 return;
1570
1571 // Compute the new offset in the appropriate width, wrapping at 64 bits.
1572 // FIXME: When compiling for a 32-bit target, we should use 32-bit
1573 // offsets.
1574 uint64_t Offset64 = Offset.getQuantity();
1575 uint64_t ElemSize64 = ElementSize.getQuantity();
1576 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1577 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1578
1579 if (checkNullPointer(Info, E, CSK_ArrayIndex))
1580 Designator.adjustIndex(Info, E, Index, *this);
1581 clearIsNullPointer();
1582 }
1583 void adjustOffset(CharUnits N) {
1584 Offset += N;
1585 if (N.getQuantity())
1586 clearIsNullPointer();
1587 }
1588 };
1589
1590 struct MemberPtr {
1591 MemberPtr() {}
1592 explicit MemberPtr(const ValueDecl *Decl)
1593 : DeclAndIsDerivedMember(Decl, false) {}
1594
1595 /// The member or (direct or indirect) field referred to by this member
1596 /// pointer, or 0 if this is a null member pointer.
1597 const ValueDecl *getDecl() const {
1598 return DeclAndIsDerivedMember.getPointer();
1599 }
1600 /// Is this actually a member of some type derived from the relevant class?
1601 bool isDerivedMember() const {
1602 return DeclAndIsDerivedMember.getInt();
1603 }
1604 /// Get the class which the declaration actually lives in.
1605 const CXXRecordDecl *getContainingRecord() const {
1606 return cast<CXXRecordDecl>(
1607 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1608 }
1609
1610 void moveInto(APValue &V) const {
1611 V = APValue(getDecl(), isDerivedMember(), Path);
1612 }
1613 void setFrom(const APValue &V) {
1614 assert(V.isMemberPointer());
1615 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1616 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1617 Path.clear();
1618 llvm::append_range(Path, V.getMemberPointerPath());
1619 }
1620
1621 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1622 /// whether the member is a member of some class derived from the class type
1623 /// of the member pointer.
1624 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1625 /// Path - The path of base/derived classes from the member declaration's
1626 /// class (exclusive) to the class type of the member pointer (inclusive).
1627 SmallVector<const CXXRecordDecl*, 4> Path;
1628
1629 /// Perform a cast towards the class of the Decl (either up or down the
1630 /// hierarchy).
1631 bool castBack(const CXXRecordDecl *Class) {
1632 assert(!Path.empty());
1633 const CXXRecordDecl *Expected;
1634 if (Path.size() >= 2)
1635 Expected = Path[Path.size() - 2];
1636 else
1637 Expected = getContainingRecord();
1638 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1639 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1640 // if B does not contain the original member and is not a base or
1641 // derived class of the class containing the original member, the result
1642 // of the cast is undefined.
1643 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1644 // (D::*). We consider that to be a language defect.
1645 return false;
1646 }
1647 Path.pop_back();
1648 return true;
1649 }
1650 /// Perform a base-to-derived member pointer cast.
1651 bool castToDerived(const CXXRecordDecl *Derived) {
1652 if (!getDecl())
1653 return true;
1654 if (!isDerivedMember()) {
1655 Path.push_back(Derived);
1656 return true;
1657 }
1658 if (!castBack(Derived))
1659 return false;
1660 if (Path.empty())
1661 DeclAndIsDerivedMember.setInt(false);
1662 return true;
1663 }
1664 /// Perform a derived-to-base member pointer cast.
1665 bool castToBase(const CXXRecordDecl *Base) {
1666 if (!getDecl())
1667 return true;
1668 if (Path.empty())
1669 DeclAndIsDerivedMember.setInt(true);
1670 if (isDerivedMember()) {
1671 Path.push_back(Base);
1672 return true;
1673 }
1674 return castBack(Base);
1675 }
1676 };
1677
1678 /// Compare two member pointers, which are assumed to be of the same type.
1679 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1680 if (!LHS.getDecl() || !RHS.getDecl())
1681 return !LHS.getDecl() && !RHS.getDecl();
1682 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1683 return false;
1684 return LHS.Path == RHS.Path;
1685 }
1686}
1687
1688void SubobjectDesignator::adjustIndex(EvalInfo &Info, const Expr *E, APSInt N,
1689 const LValue &LV) {
1690 if (Invalid || !N)
1691 return;
1692 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
1693 if (isMostDerivedAnUnsizedArray()) {
1694 diagnoseUnsizedArrayPointerArithmetic(Info, E);
1695 // Can't verify -- trust that the user is doing the right thing (or if
1696 // not, trust that the caller will catch the bad behavior).
1697 // FIXME: Should we reject if this overflows, at least?
1698 Entries.back() =
1699 PathEntry::ArrayIndex(Entries.back().getAsArrayIndex() + TruncatedN);
1700 return;
1701 }
1702
1703 // [expr.add]p4: For the purposes of these operators, a pointer to a
1704 // nonarray object behaves the same as a pointer to the first element of
1705 // an array of length one with the type of the object as its element type.
1706 bool IsArray =
1707 MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement;
1708 uint64_t ArrayIndex =
1709 IsArray ? Entries.back().getAsArrayIndex() : (uint64_t)IsOnePastTheEnd;
1710 uint64_t ArraySize = IsArray ? getMostDerivedArraySize() : (uint64_t)1;
1711
1712 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
1713 if (!Info.checkingPotentialConstantExpression() ||
1714 !LV.AllowConstexprUnknown) {
1715 // Calculate the actual index in a wide enough type, so we can include
1716 // it in the note.
1717 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
1718 (llvm::APInt &)N += ArrayIndex;
1719 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
1720 diagnosePointerArithmetic(Info, E, N);
1721 }
1722 setInvalid();
1723 return;
1724 }
1725
1726 ArrayIndex += TruncatedN;
1727 assert(ArrayIndex <= ArraySize &&
1728 "bounds check succeeded for out-of-bounds index");
1729
1730 if (IsArray)
1731 Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
1732 else
1733 IsOnePastTheEnd = (ArrayIndex != 0);
1734}
1735
1736static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1737static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1738 const LValue &This, const Expr *E,
1739 bool AllowNonLiteralTypes = false);
1740static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1741 bool InvalidBaseOK = false);
1742static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1743 bool InvalidBaseOK = false);
1744static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1745 EvalInfo &Info);
1746static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1747static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1748static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1749 EvalInfo &Info);
1750static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1751static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1752static bool EvaluateMatrix(const Expr *E, APValue &Result, EvalInfo &Info);
1753static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1754 EvalInfo &Info);
1755static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1756static std::optional<uint64_t>
1757EvaluateBuiltinStrLen(const Expr *E, EvalInfo &Info,
1758 std::string *StringResult = nullptr);
1759
1760/// Evaluate an integer or fixed point expression into an APResult.
1761static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1762 EvalInfo &Info);
1763
1764/// Evaluate only a fixed point expression into an APResult.
1765static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1766 EvalInfo &Info);
1767
1768//===----------------------------------------------------------------------===//
1769// Misc utilities
1770//===----------------------------------------------------------------------===//
1771
1772/// Negate an APSInt in place, converting it to a signed form if necessary, and
1773/// preserving its value (by extending by up to one bit as needed).
1774static void negateAsSigned(APSInt &Int) {
1775 if (Int.isUnsigned() || Int.isMinSignedValue()) {
1776 Int = Int.extend(Int.getBitWidth() + 1);
1777 Int.setIsSigned(true);
1778 }
1779 Int = -Int;
1780}
1781
1782template<typename KeyT>
1783APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T,
1784 ScopeKind Scope, LValue &LV) {
1785 unsigned Version = getTempVersion();
1786 APValue::LValueBase Base(Key, Index, Version);
1787 LV.set(Base);
1788 return createLocal(Base, Key, T, Scope);
1789}
1790
1791/// Allocate storage for a parameter of a function call made in this frame.
1792APValue &CallStackFrame::createParam(CallRef Args, const ParmVarDecl *PVD,
1793 LValue &LV) {
1794 assert(Args.CallIndex == Index && "creating parameter in wrong frame");
1795 APValue::LValueBase Base(PVD, Index, Args.Version);
1796 LV.set(Base);
1797 // We always destroy parameters at the end of the call, even if we'd allow
1798 // them to live to the end of the full-expression at runtime, in order to
1799 // give portable results and match other compilers.
1800 return createLocal(Base, PVD, PVD->getType(), ScopeKind::Call);
1801}
1802
1803APValue &CallStackFrame::createLocal(APValue::LValueBase Base, const void *Key,
1804 QualType T, ScopeKind Scope) {
1805 assert(Base.getCallIndex() == Index && "lvalue for wrong frame");
1806 unsigned Version = Base.getVersion();
1807 APValue &Result = Temporaries[MapKeyTy(Key, Version)];
1808 assert(Result.isAbsent() && "local created multiple times");
1809
1810 // If we're creating a local immediately in the operand of a speculative
1811 // evaluation, don't register a cleanup to be run outside the speculative
1812 // evaluation context, since we won't actually be able to initialize this
1813 // object.
1814 if (Index <= Info.SpeculativeEvaluationDepth) {
1815 if (T.isDestructedType())
1816 Info.noteSideEffect();
1817 } else {
1818 Info.CleanupStack.push_back(Cleanup(&Result, Base, T, Scope));
1819 }
1820 return Result;
1821}
1822
1823APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) {
1824 if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) {
1825 FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded);
1826 return nullptr;
1827 }
1828
1829 DynamicAllocLValue DA(NumHeapAllocs++);
1831 auto Result = HeapAllocs.emplace(std::piecewise_construct,
1832 std::forward_as_tuple(DA), std::tuple<>());
1833 assert(Result.second && "reused a heap alloc index?");
1834 Result.first->second.AllocExpr = E;
1835 return &Result.first->second.Value;
1836}
1837
1838/// Produce a string describing the given constexpr call.
1839void CallStackFrame::describe(raw_ostream &Out) const {
1840 bool IsMemberCall = false;
1841 bool ExplicitInstanceParam = false;
1842 clang::PrintingPolicy PrintingPolicy = Info.Ctx.getPrintingPolicy();
1843 PrintingPolicy.SuppressLambdaBody = true;
1844
1845 if (const auto *MD = dyn_cast<CXXMethodDecl>(Callee)) {
1846 IsMemberCall = !isa<CXXConstructorDecl>(MD) && !MD->isStatic();
1847 ExplicitInstanceParam = MD->isExplicitObjectMemberFunction();
1848 }
1849
1850 if (!IsMemberCall)
1851 Callee->getNameForDiagnostic(Out, PrintingPolicy,
1852 /*Qualified=*/false);
1853
1854 if (This && IsMemberCall) {
1855 if (const auto *MCE = dyn_cast_if_present<CXXMemberCallExpr>(CallExpr)) {
1856 const Expr *Object = MCE->getImplicitObjectArgument();
1857 Object->printPretty(Out, /*Helper=*/nullptr, PrintingPolicy,
1858 /*Indentation=*/0);
1859 if (Object->getType()->isPointerType())
1860 Out << "->";
1861 else
1862 Out << ".";
1863 } else if (const auto *OCE =
1864 dyn_cast_if_present<CXXOperatorCallExpr>(CallExpr)) {
1865 OCE->getArg(0)->printPretty(Out, /*Helper=*/nullptr, PrintingPolicy,
1866 /*Indentation=*/0);
1867 Out << ".";
1868 } else {
1869 APValue Val;
1870 This->moveInto(Val);
1871 Val.printPretty(
1872 Out, Info.Ctx,
1873 Info.Ctx.getLValueReferenceType(This->Designator.MostDerivedType));
1874 Out << ".";
1875 }
1876 Callee->getNameForDiagnostic(Out, PrintingPolicy,
1877 /*Qualified=*/false);
1878 }
1879
1880 Out << '(';
1881
1882 llvm::ListSeparator Comma;
1883 for (const ParmVarDecl *Param :
1884 Callee->parameters().slice(ExplicitInstanceParam)) {
1885 Out << Comma;
1886 const APValue *V = Info.getParamSlot(Arguments, Param);
1887 if (V)
1888 V->printPretty(Out, Info.Ctx, Param->getType());
1889 else
1890 Out << "<...>";
1891 }
1892
1893 Out << ')';
1894}
1895
1896/// Evaluate an expression to see if it had side-effects, and discard its
1897/// result.
1898/// \return \c true if the caller should keep evaluating.
1899static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
1900 assert(!E->isValueDependent());
1901 APValue Scratch;
1902 if (!Evaluate(Scratch, Info, E))
1903 // We don't need the value, but we might have skipped a side effect here.
1904 return Info.noteSideEffect();
1905 return true;
1906}
1907
1908static bool IsOpaqueConstantCall(const LValue &LVal) {
1909 const auto *BaseExpr =
1910 llvm::dyn_cast_if_present<CallExpr>(LVal.Base.dyn_cast<const Expr *>());
1911 return BaseExpr && isOpaqueConstantCall(BaseExpr);
1912}
1913
1915 if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>())
1916 return true;
1917
1918 return isGlobalLValue(B.dyn_cast<const ValueDecl *>(),
1919 B.dyn_cast<const Expr *>());
1920}
1921
1922bool isGlobalLValue(const ValueDecl *D, const Expr *E) {
1923 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1924 // constant expression of pointer type that evaluates to...
1925
1926 // ... a null pointer value, or a prvalue core constant expression of type
1927 // std::nullptr_t.
1928 if (!D && !E)
1929 return true;
1930
1931 if (D) {
1932 // ... the address of an object with static storage duration,
1933 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1934 return VD->hasGlobalStorage();
1936 return true;
1937 // ... the address of a function,
1938 // ... the address of a GUID [MS extension],
1939 // ... the address of an unnamed global constant
1941 }
1942
1943 assert(E);
1944
1945 switch (E->getStmtClass()) {
1946 default:
1947 return false;
1948 case Expr::CompoundLiteralExprClass: {
1950 return CLE->isFileScope() && CLE->isLValue();
1951 }
1952 case Expr::MaterializeTemporaryExprClass:
1953 // A materialized temporary might have been lifetime-extended to static
1954 // storage duration.
1955 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
1956 // A string literal has static storage duration.
1957 case Expr::StringLiteralClass:
1958 case Expr::PredefinedExprClass:
1959 case Expr::ObjCStringLiteralClass:
1960 case Expr::ObjCEncodeExprClass:
1961 return true;
1962 case Expr::ObjCBoxedExprClass:
1963 case Expr::ObjCArrayLiteralClass:
1964 case Expr::ObjCDictionaryLiteralClass:
1965 return cast<ObjCObjectLiteral>(E)->isExpressibleAsConstantInitializer();
1966 case Expr::CallExprClass:
1968 // For GCC compatibility, &&label has static storage duration.
1969 case Expr::AddrLabelExprClass:
1970 return true;
1971 // A Block literal expression may be used as the initialization value for
1972 // Block variables at global or local static scope.
1973 case Expr::BlockExprClass:
1974 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
1975 // The APValue generated from a __builtin_source_location will be emitted as a
1976 // literal.
1977 case Expr::SourceLocExprClass:
1978 return true;
1979 case Expr::ImplicitValueInitExprClass:
1980 // FIXME:
1981 // We can never form an lvalue with an implicit value initialization as its
1982 // base through expression evaluation, so these only appear in one case: the
1983 // implicit variable declaration we invent when checking whether a constexpr
1984 // constructor can produce a constant expression. We must assume that such
1985 // an expression might be a global lvalue.
1986 return true;
1987 }
1988
1989 llvm_unreachable("Unhandled stmt kind in switch with default?");
1990}
1991
1992static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
1993 return LVal.Base.dyn_cast<const ValueDecl*>();
1994}
1995
1996// Information about an LValueBase that is some kind of string.
1999 StringRef Bytes;
2001};
2002
2003// Gets the lvalue base of LVal as a string.
2004static bool GetLValueBaseAsString(const EvalInfo &Info, const LValue &LVal,
2005 LValueBaseString &AsString) {
2006 const auto *BaseExpr = LVal.Base.dyn_cast<const Expr *>();
2007 if (!BaseExpr)
2008 return false;
2009
2010 // For ObjCEncodeExpr, we need to compute and store the string.
2011 if (const auto *EE = dyn_cast<ObjCEncodeExpr>(BaseExpr)) {
2012 Info.Ctx.getObjCEncodingForType(EE->getEncodedType(),
2013 AsString.ObjCEncodeStorage);
2014 AsString.Bytes = AsString.ObjCEncodeStorage;
2015 AsString.CharWidth = 1;
2016 return true;
2017 }
2018
2019 // Otherwise, we have a StringLiteral.
2020 const auto *Lit = dyn_cast<StringLiteral>(BaseExpr);
2021 if (const auto *PE = dyn_cast<PredefinedExpr>(BaseExpr))
2022 Lit = PE->getFunctionName();
2023
2024 if (!Lit)
2025 return false;
2026
2027 AsString.Bytes = Lit->getBytes();
2028 AsString.CharWidth = Lit->getCharByteWidth();
2029 return true;
2030}
2031
2032// Determine whether two string literals potentially overlap. This will be the
2033// case if they agree on the values of all the bytes on the overlapping region
2034// between them.
2035//
2036// The overlapping region is the portion of the two string literals that must
2037// overlap in memory if the pointers actually point to the same address at
2038// runtime. For example, if LHS is "abcdef" + 3 and RHS is "cdef\0gh" + 1 then
2039// the overlapping region is "cdef\0", which in this case does agree, so the
2040// strings are potentially overlapping. Conversely, for "foobar" + 3 versus
2041// "bazbar" + 3, the overlapping region contains all of both strings, so they
2042// are not potentially overlapping, even though they agree from the given
2043// addresses onwards.
2044//
2045// See open core issue CWG2765 which is discussing the desired rule here.
2046static bool ArePotentiallyOverlappingStringLiterals(const EvalInfo &Info,
2047 const LValue &LHS,
2048 const LValue &RHS) {
2049 LValueBaseString LHSString, RHSString;
2050 if (!GetLValueBaseAsString(Info, LHS, LHSString) ||
2051 !GetLValueBaseAsString(Info, RHS, RHSString))
2052 return false;
2053
2054 // This is the byte offset to the location of the first character of LHS
2055 // within RHS. We don't need to look at the characters of one string that
2056 // would appear before the start of the other string if they were merged.
2057 CharUnits Offset = RHS.Offset - LHS.Offset;
2058 if (Offset.isNegative()) {
2059 if (LHSString.Bytes.size() < (size_t)-Offset.getQuantity())
2060 return false;
2061 LHSString.Bytes = LHSString.Bytes.drop_front(-Offset.getQuantity());
2062 } else {
2063 if (RHSString.Bytes.size() < (size_t)Offset.getQuantity())
2064 return false;
2065 RHSString.Bytes = RHSString.Bytes.drop_front(Offset.getQuantity());
2066 }
2067
2068 bool LHSIsLonger = LHSString.Bytes.size() > RHSString.Bytes.size();
2069 StringRef Longer = LHSIsLonger ? LHSString.Bytes : RHSString.Bytes;
2070 StringRef Shorter = LHSIsLonger ? RHSString.Bytes : LHSString.Bytes;
2071 int ShorterCharWidth = (LHSIsLonger ? RHSString : LHSString).CharWidth;
2072
2073 // The null terminator isn't included in the string data, so check for it
2074 // manually. If the longer string doesn't have a null terminator where the
2075 // shorter string ends, they aren't potentially overlapping.
2076 for (int NullByte : llvm::seq(ShorterCharWidth)) {
2077 if (Shorter.size() + NullByte >= Longer.size())
2078 break;
2079 if (Longer[Shorter.size() + NullByte])
2080 return false;
2081 }
2082
2083 // Otherwise, they're potentially overlapping if and only if the overlapping
2084 // region is the same.
2085 return Shorter == Longer.take_front(Shorter.size());
2086}
2087
2088static bool IsWeakLValue(const LValue &Value) {
2090 return Decl && Decl->isWeak();
2091}
2092
2093static bool isZeroSized(const LValue &Value) {
2095 if (isa_and_nonnull<VarDecl>(Decl)) {
2096 QualType Ty = Decl->getType();
2097 if (Ty->isArrayType())
2098 return Ty->isIncompleteType() ||
2099 Decl->getASTContext().getTypeSize(Ty) == 0;
2100 }
2101 return false;
2102}
2103
2104static bool HasSameBase(const LValue &A, const LValue &B) {
2105 if (!A.getLValueBase())
2106 return !B.getLValueBase();
2107 if (!B.getLValueBase())
2108 return false;
2109
2110 if (A.getLValueBase().getOpaqueValue() !=
2111 B.getLValueBase().getOpaqueValue())
2112 return false;
2113
2114 return A.getLValueCallIndex() == B.getLValueCallIndex() &&
2115 A.getLValueVersion() == B.getLValueVersion();
2116}
2117
2118static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
2119 assert(Base && "no location for a null lvalue");
2120 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2121
2122 // For a parameter, find the corresponding call stack frame (if it still
2123 // exists), and point at the parameter of the function definition we actually
2124 // invoked.
2125 if (auto *PVD = dyn_cast_or_null<ParmVarDecl>(VD)) {
2126 unsigned Idx = PVD->getFunctionScopeIndex();
2127 for (CallStackFrame *F = Info.CurrentCall; F; F = F->Caller) {
2128 if (F->Arguments.CallIndex == Base.getCallIndex() &&
2129 F->Arguments.Version == Base.getVersion() && F->Callee &&
2130 Idx < F->Callee->getNumParams()) {
2131 VD = F->Callee->getParamDecl(Idx);
2132 break;
2133 }
2134 }
2135 }
2136
2137 if (VD)
2138 Info.Note(VD->getLocation(), diag::note_declared_at);
2139 else if (const Expr *E = Base.dyn_cast<const Expr*>())
2140 Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
2141 else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
2142 // FIXME: Produce a note for dangling pointers too.
2143 if (std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA))
2144 Info.Note((*Alloc)->AllocExpr->getExprLoc(),
2145 diag::note_constexpr_dynamic_alloc_here);
2146 }
2147
2148 // We have no information to show for a typeid(T) object.
2149}
2150
2155
2156/// Materialized temporaries that we've already checked to determine if they're
2157/// initializsed by a constant expression.
2160
2162 EvalInfo &Info, SourceLocation DiagLoc,
2163 QualType Type, const APValue &Value,
2164 ConstantExprKind Kind,
2165 const FieldDecl *SubobjectDecl,
2166 CheckedTemporaries &CheckedTemps,
2167 bool IsCompleteClass = true);
2168
2169/// Check that this reference or pointer core constant expression is a valid
2170/// value for an address or reference constant expression. Return true if we
2171/// can fold this expression, whether or not it's a constant expression.
2172static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
2173 QualType Type, const LValue &LVal,
2174 ConstantExprKind Kind,
2175 CheckedTemporaries &CheckedTemps) {
2176 bool IsReferenceType = Type->isReferenceType();
2177
2178 APValue::LValueBase Base = LVal.getLValueBase();
2179 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
2180
2181 const Expr *BaseE = Base.dyn_cast<const Expr *>();
2182 const ValueDecl *BaseVD = Base.dyn_cast<const ValueDecl*>();
2183
2184 // Additional restrictions apply in a template argument. We only enforce the
2185 // C++20 restrictions here; additional syntactic and semantic restrictions
2186 // are applied elsewhere.
2187 if (isTemplateArgument(Kind)) {
2188 int InvalidBaseKind = -1;
2189 StringRef Ident;
2190 if (Base.is<TypeInfoLValue>())
2191 InvalidBaseKind = 0;
2192 else if (isa_and_nonnull<StringLiteral>(BaseE))
2193 InvalidBaseKind = 1;
2194 else if (isa_and_nonnull<MaterializeTemporaryExpr>(BaseE) ||
2195 isa_and_nonnull<LifetimeExtendedTemporaryDecl>(BaseVD))
2196 InvalidBaseKind = 2;
2197 else if (auto *PE = dyn_cast_or_null<PredefinedExpr>(BaseE)) {
2198 InvalidBaseKind = 3;
2199 Ident = PE->getIdentKindName();
2200 }
2201
2202 if (InvalidBaseKind != -1) {
2203 Info.FFDiag(Loc, diag::note_constexpr_invalid_template_arg)
2204 << IsReferenceType << !Designator.Entries.empty() << InvalidBaseKind
2205 << Ident;
2206 return false;
2207 }
2208 }
2209
2210 if (auto *FD = dyn_cast_or_null<FunctionDecl>(BaseVD);
2211 FD && FD->isImmediateFunction()) {
2212 Info.FFDiag(Loc, diag::note_consteval_address_accessible)
2213 << !Type->isAnyPointerType();
2214 Info.Note(FD->getLocation(), diag::note_declared_at);
2215 return false;
2216 }
2217
2218 // Check that the object is a global. Note that the fake 'this' object we
2219 // manufacture when checking potential constant expressions is conservatively
2220 // assumed to be global here.
2221 if (!IsGlobalLValue(Base)) {
2222 if (Info.getLangOpts().CPlusPlus11) {
2223 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
2224 << IsReferenceType << !Designator.Entries.empty() << !!BaseVD
2225 << BaseVD;
2226 auto *VarD = dyn_cast_or_null<VarDecl>(BaseVD);
2227 if (VarD && VarD->isConstexpr()) {
2228 // Non-static local constexpr variables have unintuitive semantics:
2229 // constexpr int a = 1;
2230 // constexpr const int *p = &a;
2231 // ... is invalid because the address of 'a' is not constant. Suggest
2232 // adding a 'static' in this case.
2233 Info.Note(VarD->getLocation(), diag::note_constexpr_not_static)
2234 << VarD
2235 << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static ");
2236 } else {
2237 NoteLValueLocation(Info, Base);
2238 }
2239 } else {
2240 Info.FFDiag(Loc);
2241 }
2242 // Don't allow references to temporaries to escape.
2243 return false;
2244 }
2245 assert((Info.checkingPotentialConstantExpression() ||
2246 LVal.getLValueCallIndex() == 0) &&
2247 "have call index for global lvalue");
2248
2249 if (LVal.allowConstexprUnknown()) {
2250 if (BaseVD) {
2251 Info.FFDiag(Loc, diag::note_constexpr_var_init_non_constant, 1) << BaseVD;
2252 NoteLValueLocation(Info, Base);
2253 } else {
2254 Info.FFDiag(Loc);
2255 }
2256 return false;
2257 }
2258
2259 if (Base.is<DynamicAllocLValue>()) {
2260 Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc)
2261 << IsReferenceType << !Designator.Entries.empty();
2262 NoteLValueLocation(Info, Base);
2263 return false;
2264 }
2265
2266 if (BaseVD) {
2267 if (const VarDecl *Var = dyn_cast<const VarDecl>(BaseVD)) {
2268 // Check if this is a thread-local variable.
2269 if (Var->getTLSKind())
2270 // FIXME: Diagnostic!
2271 return false;
2272
2273 // A dllimport variable never acts like a constant, unless we're
2274 // evaluating a value for use only in name mangling, and unless it's a
2275 // static local. For the latter case, we'd still need to evaluate the
2276 // constant expression in case we're inside a (inlined) function.
2277 if (!isForManglingOnly(Kind) && Var->hasAttr<DLLImportAttr>() &&
2278 !Var->isStaticLocal())
2279 return false;
2280
2281 // Address of a managed variable is never a constant expression.
2282 if (Info.getLangOpts().CUDA && Var->hasAttr<HIPManagedAttr>())
2283 return false;
2284
2285 // In CUDA/HIP device compilation, only device side variables have
2286 // constant addresses.
2287 if (Info.getLangOpts().CUDA && Info.getLangOpts().CUDAIsDevice &&
2288 Info.Ctx.CUDAConstantEvalCtx.NoWrongSidedVars) {
2289 if ((!Var->hasAttr<CUDADeviceAttr>() &&
2290 !Var->hasAttr<CUDAConstantAttr>() &&
2291 !Var->getType()->isCUDADeviceBuiltinSurfaceType() &&
2292 !Var->getType()->isCUDADeviceBuiltinTextureType()))
2293 return false;
2294 }
2295 }
2296 if (const auto *FD = dyn_cast<const FunctionDecl>(BaseVD)) {
2297 // __declspec(dllimport) must be handled very carefully:
2298 // We must never initialize an expression with the thunk in C++.
2299 // Doing otherwise would allow the same id-expression to yield
2300 // different addresses for the same function in different translation
2301 // units. However, this means that we must dynamically initialize the
2302 // expression with the contents of the import address table at runtime.
2303 //
2304 // The C language has no notion of ODR; furthermore, it has no notion of
2305 // dynamic initialization. This means that we are permitted to
2306 // perform initialization with the address of the thunk.
2307 if (Info.getLangOpts().CPlusPlus && !isForManglingOnly(Kind) &&
2308 FD->hasAttr<DLLImportAttr>())
2309 // FIXME: Diagnostic!
2310 return false;
2311 }
2312 } else if (const auto *MTE =
2313 dyn_cast_or_null<MaterializeTemporaryExpr>(BaseE)) {
2314 if (CheckedTemps.insert(MTE).second) {
2315 QualType TempType = getType(Base);
2316 if (TempType.isDestructedType()) {
2317 Info.FFDiag(MTE->getExprLoc(),
2318 diag::note_constexpr_unsupported_temporary_nontrivial_dtor)
2319 << TempType;
2320 return false;
2321 }
2322
2323 APValue *V = MTE->getOrCreateValue(false);
2324 assert(V && "evasluation result refers to uninitialised temporary");
2326 Info, MTE->getExprLoc(), TempType, *V, Kind,
2327 /*SubobjectDecl=*/nullptr, CheckedTemps))
2328 return false;
2329 }
2330 }
2331
2332 // Allow address constant expressions to be past-the-end pointers. This is
2333 // an extension: the standard requires them to point to an object.
2334 if (!IsReferenceType)
2335 return true;
2336
2337 // A reference constant expression must refer to an object.
2338 if (!Base) {
2339 // FIXME: diagnostic
2340 Info.CCEDiag(Loc);
2341 return true;
2342 }
2343
2344 // Does this refer one past the end of some object?
2345 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
2346 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
2347 << !Designator.Entries.empty() << !!BaseVD << BaseVD;
2348 NoteLValueLocation(Info, Base);
2349 }
2350
2351 return true;
2352}
2353
2354/// Member pointers are constant expressions unless they point to a
2355/// non-virtual dllimport member function.
2356static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
2357 SourceLocation Loc,
2358 QualType Type,
2359 const APValue &Value,
2360 ConstantExprKind Kind) {
2361 const ValueDecl *Member = Value.getMemberPointerDecl();
2362 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
2363 if (!FD)
2364 return true;
2365 if (FD->isImmediateFunction()) {
2366 Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0;
2367 Info.Note(FD->getLocation(), diag::note_declared_at);
2368 return false;
2369 }
2370 return isForManglingOnly(Kind) || FD->isVirtual() ||
2371 !FD->hasAttr<DLLImportAttr>();
2372}
2373
2374/// Check that this core constant expression is of literal type, and if not,
2375/// produce an appropriate diagnostic.
2376static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
2377 const LValue *This = nullptr) {
2378 // The restriction to literal types does not exist in C++23 anymore.
2379 if (Info.getLangOpts().CPlusPlus23)
2380 return true;
2381
2382 if (!E->isPRValue() || E->getType()->isLiteralType(Info.Ctx))
2383 return true;
2384
2385 // C++1y: A constant initializer for an object o [...] may also invoke
2386 // constexpr constructors for o and its subobjects even if those objects
2387 // are of non-literal class types.
2388 //
2389 // C++11 missed this detail for aggregates, so classes like this:
2390 // struct foo_t { union { int i; volatile int j; } u; };
2391 // are not (obviously) initializable like so:
2392 // __attribute__((__require_constant_initialization__))
2393 // static const foo_t x = {{0}};
2394 // because "i" is a subobject with non-literal initialization (due to the
2395 // volatile member of the union). See:
2396 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2397 // Therefore, we use the C++1y behavior.
2398 if (This && Info.EvaluatingDecl == This->getLValueBase())
2399 return true;
2400
2401 // Prvalue constant expressions must be of literal types.
2402 if (Info.getLangOpts().CPlusPlus11)
2403 Info.FFDiag(E, diag::note_constexpr_nonliteral)
2404 << E->getType();
2405 else
2406 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2407 return false;
2408}
2409
2411 EvalInfo &Info, SourceLocation DiagLoc,
2412 QualType Type, const APValue &Value,
2413 ConstantExprKind Kind,
2414 const FieldDecl *SubobjectDecl,
2415 CheckedTemporaries &CheckedTemps,
2416 bool IsCompleteClass) {
2417 if (!Value.hasValue()) {
2418 if (SubobjectDecl) {
2419 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2420 << /*(name)*/ 1 << SubobjectDecl;
2421 Info.Note(SubobjectDecl->getLocation(),
2422 diag::note_constexpr_subobject_declared_here);
2423 } else {
2424 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2425 << /*of type*/ 0 << Type;
2426 }
2427 return false;
2428 }
2429
2430 // We allow _Atomic(T) to be initialized from anything that T can be
2431 // initialized from.
2432 if (const AtomicType *AT = Type->getAs<AtomicType>())
2433 Type = AT->getValueType();
2434
2435 // Core issue 1454: For a literal constant expression of array or class type,
2436 // each subobject of its value shall have been initialized by a constant
2437 // expression.
2438 if (Value.isArray()) {
2440 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
2441 if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2442 Value.getArrayInitializedElt(I), Kind,
2443 SubobjectDecl, CheckedTemps))
2444 return false;
2445 }
2446 if (!Value.hasArrayFiller())
2447 return true;
2448 return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2449 Value.getArrayFiller(), Kind, SubobjectDecl,
2450 CheckedTemps);
2451 }
2452 if (Value.isUnion() && Value.getUnionField()) {
2453 return CheckEvaluationResult(
2454 CERK, Info, DiagLoc, Value.getUnionField()->getType(),
2455 Value.getUnionValue(), Kind, Value.getUnionField(), CheckedTemps);
2456 }
2457 if (Value.isStruct()) {
2458 auto *RD = Type->castAsRecordDecl();
2459 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2460 unsigned BaseIndex = 0;
2461 for (const CXXBaseSpecifier &BS : CD->bases()) {
2462 if (BS.isVirtual())
2463 continue;
2464 const APValue &BaseValue = Value.getStructBase(BaseIndex);
2465 if (!BaseValue.hasValue()) {
2466 SourceLocation TypeBeginLoc = BS.getBaseTypeLoc();
2467 Info.FFDiag(TypeBeginLoc, diag::note_constexpr_uninitialized_base)
2468 << BS.getType() << SourceRange(TypeBeginLoc, BS.getEndLoc());
2469 return false;
2470 }
2471 if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(), BaseValue,
2472 Kind, /*SubobjectDecl=*/nullptr,
2473 CheckedTemps, /*IsCompleteClass=*/false))
2474 return false;
2475 ++BaseIndex;
2476 }
2477 }
2478 for (const auto *I : RD->fields()) {
2479 if (I->isUnnamedBitField())
2480 continue;
2481
2482 if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),
2483 Value.getStructField(I->getFieldIndex()), Kind,
2484 I, CheckedTemps))
2485 return false;
2486 }
2487
2488 if (IsCompleteClass) {
2489 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2490 unsigned BaseIndex = 0;
2491 for (const CXXBaseSpecifier &BS : CD->vbases()) {
2492 assert(BS.isVirtual());
2493 const APValue &BaseValue = Value.getStructVirtualBase(BaseIndex);
2494 if (!BaseValue.hasValue()) {
2495 SourceLocation TypeBeginLoc = BS.getBaseTypeLoc();
2496 Info.FFDiag(TypeBeginLoc, diag::note_constexpr_uninitialized_base)
2497 << BS.getType() << SourceRange(TypeBeginLoc, BS.getEndLoc());
2498 return false;
2499 }
2500 if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(),
2501 BaseValue, Kind, /*SubobjectDecl=*/nullptr,
2502 CheckedTemps, /*IsCompleteClass=*/false))
2503 return false;
2504 ++BaseIndex;
2505 }
2506 }
2507 }
2508 }
2509
2510 if (Value.isLValue() &&
2512 LValue LVal;
2513 LVal.setFrom(Info.Ctx, Value);
2514 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Kind,
2515 CheckedTemps);
2516 }
2517
2518 if (Value.isMemberPointer() &&
2520 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Kind);
2521
2522 // Everything else is fine.
2523 return true;
2524}
2525
2526/// Check that this core constant expression value is a valid value for a
2527/// constant expression. If not, report an appropriate diagnostic. Does not
2528/// check that the expression is of literal type.
2529static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
2530 QualType Type, const APValue &Value,
2531 ConstantExprKind Kind) {
2532 // Nothing to check for a constant expression of type 'cv void'.
2533 if (Type->isVoidType())
2534 return true;
2535
2536 CheckedTemporaries CheckedTemps;
2538 Info, DiagLoc, Type, Value, Kind,
2539 /*SubobjectDecl=*/nullptr, CheckedTemps);
2540}
2541
2542/// Check that this evaluated value is fully-initialized and can be loaded by
2543/// an lvalue-to-rvalue conversion.
2544static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,
2545 QualType Type, const APValue &Value) {
2546 CheckedTemporaries CheckedTemps;
2547 return CheckEvaluationResult(
2549 ConstantExprKind::Normal, /*SubobjectDecl=*/nullptr, CheckedTemps);
2550}
2551
2552/// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless
2553/// "the allocated storage is deallocated within the evaluation".
2554static bool CheckMemoryLeaks(EvalInfo &Info) {
2555 if (!Info.HeapAllocs.empty()) {
2556 // We can still fold to a constant despite a compile-time memory leak,
2557 // so long as the heap allocation isn't referenced in the result (we check
2558 // that in CheckConstantExpression).
2559 Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr,
2560 diag::note_constexpr_memory_leak)
2561 << unsigned(Info.HeapAllocs.size() - 1);
2562 }
2563 return true;
2564}
2565
2566static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
2567 // A null base expression indicates a null pointer. These are always
2568 // evaluatable, and they are false unless the offset is zero.
2569 if (!Value.getLValueBase()) {
2570 // TODO: Should a non-null pointer with an offset of zero evaluate to true?
2571 Result = !Value.getLValueOffset().isZero();
2572 return true;
2573 }
2574
2575 // We have a non-null base. These are generally known to be true, but if it's
2576 // a weak declaration it can be null at runtime.
2577 Result = true;
2578 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
2579 return !Decl || !Decl->isWeak();
2580}
2581
2582static bool HandleConversionToBool(const APValue &Val, bool &Result) {
2583 // TODO: This function should produce notes if it fails.
2584 switch (Val.getKind()) {
2585 case APValue::None:
2587 return false;
2588 case APValue::Int:
2589 Result = Val.getInt().getBoolValue();
2590 return true;
2592 Result = Val.getFixedPoint().getBoolValue();
2593 return true;
2594 case APValue::Float:
2595 Result = !Val.getFloat().isZero();
2596 return true;
2598 Result = Val.getComplexIntReal().getBoolValue() ||
2599 Val.getComplexIntImag().getBoolValue();
2600 return true;
2602 Result = !Val.getComplexFloatReal().isZero() ||
2603 !Val.getComplexFloatImag().isZero();
2604 return true;
2605 case APValue::LValue:
2606 return EvalPointerValueAsBool(Val, Result);
2608 if (Val.getMemberPointerDecl() && Val.getMemberPointerDecl()->isWeak()) {
2609 return false;
2610 }
2612 return true;
2613 case APValue::Vector:
2614 case APValue::Matrix:
2615 case APValue::Array:
2616 case APValue::Struct:
2617 case APValue::Union:
2619 return false;
2620 }
2621
2622 llvm_unreachable("unknown APValue kind");
2623}
2624
2625static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2626 EvalInfo &Info) {
2627 assert(!E->isValueDependent());
2628 assert(E->isPRValue() && "missing lvalue-to-rvalue conv in bool condition");
2629 APValue Val;
2630 if (!Evaluate(Val, Info, E))
2631 return false;
2632 return HandleConversionToBool(Val, Result);
2633}
2634
2635template<typename T>
2636static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2637 const T &SrcValue, QualType DestType) {
2638 Info.CCEDiag(E, diag::note_constexpr_overflow) << SrcValue << DestType;
2639 if (const auto *OBT = DestType->getAs<OverflowBehaviorType>();
2640 OBT && OBT->isTrapKind()) {
2641 return false;
2642 }
2643 return Info.noteUndefinedBehavior();
2644}
2645
2646static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2647 QualType SrcType, const APFloat &Value,
2648 QualType DestType, APSInt &Result) {
2649 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2650 // Determine whether we are converting to unsigned or signed.
2651 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2652
2653 Result = APSInt(DestWidth, !DestSigned);
2654 bool ignored;
2655 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2656 & APFloat::opInvalidOp)
2657 return HandleOverflow(Info, E, Value, DestType);
2658 return true;
2659}
2660
2661/// Get rounding mode to use in evaluation of the specified expression.
2662///
2663/// If rounding mode is unknown at compile time, still try to evaluate the
2664/// expression. If the result is exact, it does not depend on rounding mode.
2665/// So return "tonearest" mode instead of "dynamic".
2666static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E) {
2667 llvm::RoundingMode RM =
2668 E->getFPFeaturesInEffect(Info.getLangOpts()).getRoundingMode();
2669 if (RM == llvm::RoundingMode::Dynamic)
2670 RM = llvm::RoundingMode::NearestTiesToEven;
2671 return RM;
2672}
2673
2674/// Check if the given floating-point evaluation result is allowed for
2675/// compile-time constant folding during translation (as opposed to mandatory
2676/// constant expression evaluation).
2678 const Expr *E,
2679 APFloat::opStatus St) {
2680 // In a constant context, assume that any dynamic rounding mode or FP
2681 // exception state matches the default floating-point environment.
2682 if (Info.InConstantContext)
2683 return true;
2684
2685 FPOptions FPO = E->getFPFeaturesInEffect(Info.getLangOpts());
2686 if ((St & APFloat::opInexact) &&
2687 FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) {
2688 // Inexact result means that it depends on rounding mode. If the requested
2689 // mode is dynamic, the evaluation cannot be made in compile time.
2690 Info.FFDiag(E, diag::note_constexpr_dynamic_rounding);
2691 return false;
2692 }
2693
2694 if ((St != APFloat::opOK) &&
2695 (FPO.getRoundingMode() == llvm::RoundingMode::Dynamic ||
2697 FPO.getAllowFEnvAccess())) {
2698 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
2699 return false;
2700 }
2701
2702 if ((St & APFloat::opStatus::opInvalidOp) &&
2704 // There is no usefully definable result.
2705 Info.FFDiag(E);
2706 return false;
2707 }
2708
2709 // FIXME: if:
2710 // - evaluation triggered other FP exception, and
2711 // - exception mode is not "ignore", and
2712 // - the expression being evaluated is not a part of global variable
2713 // initializer,
2714 // the evaluation probably need to be rejected.
2715 return true;
2716}
2717
2718static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2719 QualType SrcType, QualType DestType,
2720 APFloat &Result) {
2721 assert((isa<CastExpr>(E) || isa<CompoundAssignOperator>(E) ||
2723 "HandleFloatToFloatCast has been checked with only CastExpr, "
2724 "CompoundAssignOperator and ConvertVectorExpr. Please either validate "
2725 "the new expression or address the root cause of this usage.");
2726 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2727 APFloat::opStatus St;
2728 APFloat Value = Result;
2729 bool ignored;
2730 St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored);
2732}
2733
2734static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2735 QualType DestType, QualType SrcType,
2736 const APSInt &Value) {
2737 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2738 // Figure out if this is a truncate, extend or noop cast.
2739 // If the input is signed, do a sign extend, noop, or truncate.
2740 APSInt Result = Value.extOrTrunc(DestWidth);
2741 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2742 if (DestType->isBooleanType())
2743 Result = Value.getBoolValue();
2744 return Result;
2745}
2746
2747static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2748 const FPOptions FPO,
2749 QualType SrcType, const APSInt &Value,
2750 QualType DestType, APFloat &Result) {
2751 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2752 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2753 APFloat::opStatus St = Result.convertFromAPInt(Value, Value.isSigned(), RM);
2755}
2756
2757static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2758 APValue &Value, const FieldDecl *FD) {
2759 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2760
2761 if (!Value.isInt()) {
2762 // Trying to store a pointer-cast-to-integer into a bitfield.
2763 // FIXME: In this case, we should provide the diagnostic for casting
2764 // a pointer to an integer.
2765 assert(Value.isLValue() && "integral value neither int nor lvalue?");
2766 Info.FFDiag(E);
2767 return false;
2768 }
2769
2770 APSInt &Int = Value.getInt();
2771 unsigned OldBitWidth = Int.getBitWidth();
2772 unsigned NewBitWidth = FD->getBitWidthValue();
2773 if (NewBitWidth < OldBitWidth)
2774 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2775 return true;
2776}
2777
2778/// Perform the given integer operation, which is known to need at most BitWidth
2779/// bits, and check for overflow in the original type (if that type was not an
2780/// unsigned type).
2781template<typename Operation>
2782static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2783 const APSInt &LHS, const APSInt &RHS,
2784 unsigned BitWidth, Operation Op,
2785 APSInt &Result) {
2786 if (LHS.isUnsigned()) {
2787 Result = Op(LHS, RHS);
2788 return true;
2789 }
2790
2791 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2792 Result = Value.trunc(LHS.getBitWidth());
2793 if (Result.extend(BitWidth) != Value && !E->getType().isWrapType()) {
2794 if (Info.checkingForUndefinedBehavior())
2795 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2796 diag::warn_integer_constant_overflow)
2797 << toString(Result, 10, Result.isSigned(), /*formatAsCLiteral=*/false,
2798 /*UpperCase=*/true, /*InsertSeparators=*/true)
2799 << E->getType() << E->getSourceRange();
2800 return HandleOverflow(Info, E, Value, E->getType());
2801 }
2802 return true;
2803}
2804
2805/// Perform the given binary integer operation.
2806static bool handleIntIntBinOp(EvalInfo &Info, const BinaryOperator *E,
2807 const APSInt &LHS, BinaryOperatorKind Opcode,
2808 APSInt RHS, APSInt &Result) {
2809 bool HandleOverflowResult = true;
2810 switch (Opcode) {
2811 default:
2812 Info.FFDiag(E);
2813 return false;
2814 case BO_Mul:
2815 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2816 std::multiplies<APSInt>(), Result);
2817 case BO_Add:
2818 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2819 std::plus<APSInt>(), Result);
2820 case BO_Sub:
2821 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2822 std::minus<APSInt>(), Result);
2823 case BO_And: Result = LHS & RHS; return true;
2824 case BO_Xor: Result = LHS ^ RHS; return true;
2825 case BO_Or: Result = LHS | RHS; return true;
2826 case BO_Div:
2827 case BO_Rem:
2828 if (RHS == 0) {
2829 Info.FFDiag(E, diag::note_expr_divide_by_zero)
2830 << E->getRHS()->getSourceRange();
2831 return false;
2832 }
2833 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2834 // this operation and gives the two's complement result.
2835 if (RHS.isNegative() && RHS.isAllOnes() && LHS.isSigned() &&
2836 LHS.isMinSignedValue())
2837 HandleOverflowResult = HandleOverflow(
2838 Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
2839 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2840 return HandleOverflowResult;
2841 case BO_Shl: {
2842 if (Info.getLangOpts().OpenCL)
2843 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2844 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2845 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2846 RHS.isUnsigned());
2847 else if (RHS.isSigned() && RHS.isNegative()) {
2848 // During constant-folding, a negative shift is an opposite shift. Such
2849 // a shift is not a constant expression.
2850 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2851 if (!Info.noteUndefinedBehavior())
2852 return false;
2853 RHS = -RHS;
2854 goto shift_right;
2855 }
2856 shift_left:
2857 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2858 // the shifted type.
2859 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2860 if (SA != RHS) {
2861 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2862 << RHS << E->getType() << LHS.getBitWidth();
2863 if (!Info.noteUndefinedBehavior())
2864 return false;
2865 } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) {
2866 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2867 // operand, and must not overflow the corresponding unsigned type.
2868 // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2869 // E1 x 2^E2 module 2^N.
2870 if (LHS.isNegative()) {
2871 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2872 if (!Info.noteUndefinedBehavior())
2873 return false;
2874 } else if (LHS.countl_zero() < SA) {
2875 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2876 if (!Info.noteUndefinedBehavior())
2877 return false;
2878 }
2879 }
2880 Result = LHS << SA;
2881 return true;
2882 }
2883 case BO_Shr: {
2884 if (Info.getLangOpts().OpenCL)
2885 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2886 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2887 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2888 RHS.isUnsigned());
2889 else if (RHS.isSigned() && RHS.isNegative()) {
2890 // During constant-folding, a negative shift is an opposite shift. Such a
2891 // shift is not a constant expression.
2892 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2893 if (!Info.noteUndefinedBehavior())
2894 return false;
2895 RHS = -RHS;
2896 goto shift_left;
2897 }
2898 shift_right:
2899 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2900 // shifted type.
2901 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2902 if (SA != RHS) {
2903 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2904 << RHS << E->getType() << LHS.getBitWidth();
2905 if (!Info.noteUndefinedBehavior())
2906 return false;
2907 }
2908
2909 Result = LHS >> SA;
2910 return true;
2911 }
2912
2913 case BO_LT: Result = LHS < RHS; return true;
2914 case BO_GT: Result = LHS > RHS; return true;
2915 case BO_LE: Result = LHS <= RHS; return true;
2916 case BO_GE: Result = LHS >= RHS; return true;
2917 case BO_EQ: Result = LHS == RHS; return true;
2918 case BO_NE: Result = LHS != RHS; return true;
2919 case BO_Cmp:
2920 llvm_unreachable("BO_Cmp should be handled elsewhere");
2921 }
2922}
2923
2924/// Perform the given binary floating-point operation, in-place, on LHS.
2925static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E,
2926 APFloat &LHS, BinaryOperatorKind Opcode,
2927 const APFloat &RHS) {
2928 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2929 APFloat::opStatus St;
2930 switch (Opcode) {
2931 default:
2932 Info.FFDiag(E);
2933 return false;
2934 case BO_Mul:
2935 St = LHS.multiply(RHS, RM);
2936 break;
2937 case BO_Add:
2938 St = LHS.add(RHS, RM);
2939 break;
2940 case BO_Sub:
2941 St = LHS.subtract(RHS, RM);
2942 break;
2943 case BO_Div:
2944 // [expr.mul]p4:
2945 // If the second operand of / or % is zero the behavior is undefined.
2946 if (RHS.isZero())
2947 Info.CCEDiag(E, diag::note_expr_divide_by_zero);
2948 St = LHS.divide(RHS, RM);
2949 break;
2950 }
2951
2952 // FIXME: The standard quote below is deleted by P3899R3.
2953 // [expr.pre]p4:
2954 // If during the evaluation of an expression, the result is not
2955 // mathematically defined [...], the behavior is undefined.
2956 // FIXME: C++ rules require us to not conform to IEEE 754 here.
2957 // FIXME: The NaN check should not be applied outside of "constant contexts"
2958 // because it prevents NaN propagation and the "invalid" status is the
2959 // responsibility of checkFloatingPointResultForConstantFolding.
2960 if (LHS.isNaN()) {
2961 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
2962 return Info.noteUndefinedBehavior();
2963 }
2964
2966}
2967
2968static bool handleLogicalOpForVector(const APInt &LHSValue,
2969 BinaryOperatorKind Opcode,
2970 const APInt &RHSValue, APInt &Result) {
2971 bool LHS = (LHSValue != 0);
2972 bool RHS = (RHSValue != 0);
2973
2974 if (Opcode == BO_LAnd)
2975 Result = LHS && RHS;
2976 else
2977 Result = LHS || RHS;
2978 return true;
2979}
2980static bool handleLogicalOpForVector(const APFloat &LHSValue,
2981 BinaryOperatorKind Opcode,
2982 const APFloat &RHSValue, APInt &Result) {
2983 bool LHS = !LHSValue.isZero();
2984 bool RHS = !RHSValue.isZero();
2985
2986 if (Opcode == BO_LAnd)
2987 Result = LHS && RHS;
2988 else
2989 Result = LHS || RHS;
2990 return true;
2991}
2992
2993static bool handleLogicalOpForVector(const APValue &LHSValue,
2994 BinaryOperatorKind Opcode,
2995 const APValue &RHSValue, APInt &Result) {
2996 // The result is always an int type, however operands match the first.
2997 if (LHSValue.getKind() == APValue::Int)
2998 return handleLogicalOpForVector(LHSValue.getInt(), Opcode,
2999 RHSValue.getInt(), Result);
3000 assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
3001 return handleLogicalOpForVector(LHSValue.getFloat(), Opcode,
3002 RHSValue.getFloat(), Result);
3003}
3004
3005template <typename APTy>
3006static bool
3008 const APTy &RHSValue, APInt &Result) {
3009 switch (Opcode) {
3010 default:
3011 llvm_unreachable("unsupported binary operator");
3012 case BO_EQ:
3013 Result = (LHSValue == RHSValue);
3014 break;
3015 case BO_NE:
3016 Result = (LHSValue != RHSValue);
3017 break;
3018 case BO_LT:
3019 Result = (LHSValue < RHSValue);
3020 break;
3021 case BO_GT:
3022 Result = (LHSValue > RHSValue);
3023 break;
3024 case BO_LE:
3025 Result = (LHSValue <= RHSValue);
3026 break;
3027 case BO_GE:
3028 Result = (LHSValue >= RHSValue);
3029 break;
3030 }
3031
3032 // The boolean operations on these vector types use an instruction that
3033 // results in a mask of '-1' for the 'truth' value. Ensure that we negate 1
3034 // to -1 to make sure that we produce the correct value.
3035 Result.negate();
3036
3037 return true;
3038}
3039
3040static bool handleCompareOpForVector(const APValue &LHSValue,
3041 BinaryOperatorKind Opcode,
3042 const APValue &RHSValue, APInt &Result) {
3043 // The result is always an int type, however operands match the first.
3044 if (LHSValue.getKind() == APValue::Int)
3045 return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode,
3046 RHSValue.getInt(), Result);
3047 assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
3048 return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode,
3049 RHSValue.getFloat(), Result);
3050}
3051
3052// Perform binary operations for vector types, in place on the LHS.
3053static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E,
3054 BinaryOperatorKind Opcode,
3055 APValue &LHSValue,
3056 const APValue &RHSValue) {
3057 assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI &&
3058 "Operation not supported on vector types");
3059
3060 const auto *VT = E->getType()->castAs<VectorType>();
3061 unsigned NumElements = VT->getNumElements();
3062 QualType EltTy = VT->getElementType();
3063
3064 // In the cases (typically C as I've observed) where we aren't evaluating
3065 // constexpr but are checking for cases where the LHS isn't yet evaluatable,
3066 // just give up.
3067 if (!LHSValue.isVector()) {
3068 assert(LHSValue.isLValue() &&
3069 "A vector result that isn't a vector OR uncalculated LValue");
3070 Info.FFDiag(E);
3071 return false;
3072 }
3073
3074 assert(LHSValue.getVectorLength() == NumElements &&
3075 RHSValue.getVectorLength() == NumElements && "Different vector sizes");
3076
3077 SmallVector<APValue, 4> ResultElements;
3078
3079 for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) {
3080 APValue LHSElt = LHSValue.getVectorElt(EltNum);
3081 APValue RHSElt = RHSValue.getVectorElt(EltNum);
3082
3083 if (EltTy->isIntegerType()) {
3084 APSInt EltResult{Info.Ctx.getIntWidth(EltTy),
3085 EltTy->isUnsignedIntegerType()};
3086 bool Success = true;
3087
3088 if (BinaryOperator::isLogicalOp(Opcode))
3089 Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3090 else if (BinaryOperator::isComparisonOp(Opcode))
3091 Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3092 else
3093 Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode,
3094 RHSElt.getInt(), EltResult);
3095
3096 if (!Success) {
3097 Info.FFDiag(E);
3098 return false;
3099 }
3100 ResultElements.emplace_back(EltResult);
3101
3102 } else if (EltTy->isFloatingType()) {
3103 assert(LHSElt.getKind() == APValue::Float &&
3104 RHSElt.getKind() == APValue::Float &&
3105 "Mismatched LHS/RHS/Result Type");
3106 APFloat LHSFloat = LHSElt.getFloat();
3107
3108 if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode,
3109 RHSElt.getFloat())) {
3110 Info.FFDiag(E);
3111 return false;
3112 }
3113
3114 ResultElements.emplace_back(LHSFloat);
3115 }
3116 }
3117
3118 LHSValue = APValue(ResultElements.data(), ResultElements.size());
3119 return true;
3120}
3121
3122/// Cast an lvalue referring to a base subobject to a derived class, by
3123/// truncating the lvalue's path to the given length.
3124static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
3125 const RecordDecl *TruncatedType,
3126 unsigned TruncatedElements) {
3127 SubobjectDesignator &D = Result.Designator;
3128
3129 // Check we actually point to a derived class object.
3130 if (TruncatedElements == D.Entries.size())
3131 return true;
3132 assert(TruncatedElements >= D.MostDerivedPathLength &&
3133 "not casting to a derived class");
3134 if (!Result.checkSubobject(Info, E, CSK_Derived))
3135 return false;
3136
3137 // Truncate the path to the subobject, and remove any derived-to-base offsets.
3138 const RecordDecl *RD = TruncatedType;
3139 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
3140 if (RD->isInvalidDecl()) return false;
3141 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3142 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
3143 if (isVirtualBaseClass(D.Entries[I]))
3144 Result.Offset -= Layout.getVBaseClassOffset(Base);
3145 else
3146 Result.Offset -= Layout.getBaseClassOffset(Base);
3147 RD = Base;
3148 }
3149 D.Entries.resize(TruncatedElements);
3150 return true;
3151}
3152
3153static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3154 const CXXRecordDecl *Derived,
3155 const CXXRecordDecl *Base,
3156 const ASTRecordLayout *RL = nullptr) {
3157 if (!RL) {
3158 if (Derived->isInvalidDecl()) return false;
3159 RL = &Info.Ctx.getASTRecordLayout(Derived);
3160 }
3161
3162 Obj.addDecl(Info, E, Base, /*Virtual=*/false);
3163 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
3164 return true;
3165}
3166
3167static bool HandleLValueDirectVirtualBase(EvalInfo &Info, const Expr *E,
3168 LValue &Obj,
3169 const CXXRecordDecl *Derived,
3170 const CXXRecordDecl *Base,
3171 const ASTRecordLayout *RL = nullptr) {
3172 if (!RL) {
3173 if (Derived->isInvalidDecl())
3174 return false;
3175 RL = &Info.Ctx.getASTRecordLayout(Derived);
3176 }
3177
3178 Obj.addDecl(Info, E, Base, /*Virtual=*/true);
3179 Obj.getLValueOffset() += RL->getVBaseClassOffset(Base);
3180 return true;
3181}
3182
3183static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3184 const CXXRecordDecl *DerivedDecl,
3185 const CXXBaseSpecifier *Base) {
3186 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
3187
3188 if (!Base->isVirtual())
3189 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
3190
3191 SubobjectDesignator &D = Obj.Designator;
3192 if (D.Invalid)
3193 return false;
3194
3195 // Extract most-derived object and corresponding type.
3196 // FIXME: After implementing P2280R4 it became possible to get references
3197 // here. We do MostDerivedType->getAsCXXRecordDecl() in several other
3198 // locations and if we see crashes in those locations in the future
3199 // it may make more sense to move this fix into Lvalue::set.
3200 DerivedDecl = D.MostDerivedType.getNonReferenceType()->getAsCXXRecordDecl();
3201 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
3202 return false;
3203
3204 // Find the virtual base class.
3205 if (DerivedDecl->isInvalidDecl()) return false;
3206 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
3207 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
3208 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
3209 return true;
3210}
3211
3212static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
3213 QualType Type, LValue &Result) {
3214 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3215 PathE = E->path_end();
3216 PathI != PathE; ++PathI) {
3218 *PathI))
3219 return false;
3220 Type = (*PathI)->getType();
3221 }
3222 return true;
3223}
3224
3225/// Cast an lvalue referring to a derived class to a known base subobject.
3226static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
3227 const CXXRecordDecl *DerivedRD,
3228 const CXXRecordDecl *BaseRD) {
3229 CXXBasePaths Paths(/*FindAmbiguities=*/false,
3230 /*RecordPaths=*/true, /*DetectVirtual=*/false);
3231 if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
3232 llvm_unreachable("Class must be derived from the passed in base class!");
3233
3234 for (CXXBasePathElement &Elem : Paths.front())
3235 if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
3236 return false;
3237 return true;
3238}
3239
3240/// Update LVal to refer to the given field, which must be a member of the type
3241/// currently described by LVal.
3242static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
3243 const FieldDecl *FD,
3244 const ASTRecordLayout *RL = nullptr) {
3245 if (!RL) {
3246 const RecordDecl *RD = FD->getParent();
3247 if (RD->isInvalidDecl())
3248 return false;
3249 // There are some cases where the base is not yet complete but we haven't
3250 // disagnosed (such as in a template instantation of an attribute that
3251 // references the expression, ala enable_if). These aren't necessarily
3252 // constant expressions so we return 'false', but they might be, so we don't
3253 // diagnose.
3254 if (!RD->isCompleteDefinition())
3255 return false;
3256 RL = &Info.Ctx.getASTRecordLayout(RD);
3257 }
3258
3259 unsigned I = FD->getFieldIndex();
3260 LVal.addDecl(Info, E, FD);
3261 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
3262 return true;
3263}
3264
3265/// Update LVal to refer to the given indirect field.
3266static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
3267 LValue &LVal,
3268 const IndirectFieldDecl *IFD) {
3269 for (const auto *C : IFD->chain())
3270 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
3271 return false;
3272 return true;
3273}
3274
3279
3280/// Get the size of the given type in char units.
3281static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, QualType Type,
3283 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
3284 // extension.
3285 if (Type->isVoidType() || Type->isFunctionType()) {
3286 Size = CharUnits::One();
3287 return true;
3288 }
3289
3290 if (Type->isDependentType()) {
3291 Info.FFDiag(Loc);
3292 return false;
3293 }
3294
3295 if (!Type->isConstantSizeType()) {
3296 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
3297 // FIXME: Better diagnostic.
3298 Info.FFDiag(Loc);
3299 return false;
3300 }
3301
3302 if (SOT == SizeOfType::SizeOf)
3303 Size = Info.Ctx.getTypeSizeInChars(Type);
3304 else
3305 Size = Info.Ctx.getTypeInfoDataSizeInChars(Type).Width;
3306 return true;
3307}
3308
3309/// Update a pointer value to model pointer arithmetic.
3310/// \param Info - Information about the ongoing evaluation.
3311/// \param E - The expression being evaluated, for diagnostic purposes.
3312/// \param LVal - The pointer value to be updated.
3313/// \param EltTy - The pointee type represented by LVal.
3314/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
3315static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3316 LValue &LVal, QualType EltTy,
3317 APSInt Adjustment) {
3318 CharUnits SizeOfPointee;
3319 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
3320 return false;
3321
3322 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
3323 return true;
3324}
3325
3326static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3327 LValue &LVal, QualType EltTy,
3328 int64_t Adjustment) {
3329 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
3330 APSInt::get(Adjustment));
3331}
3332
3333/// Update an lvalue to refer to a component of a complex number.
3334/// \param Info - Information about the ongoing evaluation.
3335/// \param LVal - The lvalue to be updated.
3336/// \param EltTy - The complex number's component type.
3337/// \param Imag - False for the real component, true for the imaginary.
3338static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
3339 LValue &LVal, QualType EltTy,
3340 bool Imag) {
3341 if (Imag) {
3342 CharUnits SizeOfComponent;
3343 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
3344 return false;
3345 LVal.Offset += SizeOfComponent;
3346 }
3347 LVal.addComplex(Info, E, EltTy, Imag);
3348 return true;
3349}
3350
3351static bool HandleLValueVectorElement(EvalInfo &Info, const Expr *E,
3352 LValue &LVal, QualType EltTy,
3353 uint64_t Size, uint64_t Idx) {
3354 if (Idx) {
3355 CharUnits SizeOfElement;
3356 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfElement))
3357 return false;
3358 LVal.Offset += SizeOfElement * Idx;
3359 }
3360 LVal.addVectorElement(Info, E, EltTy, Size, Idx);
3361 return true;
3362}
3363
3364/// Try to evaluate the initializer for a variable declaration.
3365///
3366/// \param Info Information about the ongoing evaluation.
3367/// \param E An expression to be used when printing diagnostics.
3368/// \param VD The variable whose initializer should be obtained.
3369/// \param Version The version of the variable within the frame.
3370/// \param Frame The frame in which the variable was created. Must be null
3371/// if this variable is not local to the evaluation.
3372/// \param Result Filled in with a pointer to the value of the variable.
3373static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
3374 const VarDecl *VD, CallStackFrame *Frame,
3375 unsigned Version, APValue *&Result) {
3376 // C++23 [expr.const]p8 If we have a reference type allow unknown references
3377 // and pointers.
3378 bool AllowConstexprUnknown =
3379 Info.getLangOpts().CPlusPlus23 && VD->getType()->isReferenceType();
3380
3381 APValue::LValueBase Base(VD, Frame ? Frame->Index : 0, Version);
3382
3383 auto CheckUninitReference = [&](bool IsLocalVariable) {
3384 if (!Result || (!Result->hasValue() && VD->getType()->isReferenceType())) {
3385 // C++23 [expr.const]p8
3386 // ... For such an object that is not usable in constant expressions, the
3387 // dynamic type of the object is constexpr-unknown. For such a reference
3388 // that is not usable in constant expressions, the reference is treated
3389 // as binding to an unspecified object of the referenced type whose
3390 // lifetime and that of all subobjects includes the entire constant
3391 // evaluation and whose dynamic type is constexpr-unknown.
3392 //
3393 // Variables that are part of the current evaluation are not
3394 // constexpr-unknown.
3395 if (!AllowConstexprUnknown || IsLocalVariable) {
3396 if (!Info.checkingPotentialConstantExpression())
3397 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
3398 return false;
3399 }
3400 Result = nullptr;
3401 }
3402 return true;
3403 };
3404
3405 // If this is a local variable, dig out its value.
3406 if (Frame) {
3407 Result = Frame->getTemporary(VD, Version);
3408 if (Result)
3409 return CheckUninitReference(/*IsLocalVariable=*/true);
3410
3411 if (!isa<ParmVarDecl>(VD)) {
3412 // Assume variables referenced within a lambda's call operator that were
3413 // not declared within the call operator are captures and during checking
3414 // of a potential constant expression, assume they are unknown constant
3415 // expressions.
3416 assert(isLambdaCallOperator(Frame->Callee) &&
3417 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
3418 "missing value for local variable");
3419 if (Info.checkingPotentialConstantExpression())
3420 return false;
3421
3422 llvm_unreachable(
3423 "A variable in a frame should either be a local or a parameter");
3424 }
3425 }
3426
3427 // If we're currently evaluating the initializer of this declaration, use that
3428 // in-flight value.
3429 if (Info.EvaluatingDecl == Base) {
3430 Result = Info.EvaluatingDeclValue;
3431 return CheckUninitReference(/*IsLocalVariable=*/false);
3432 }
3433
3434 // P2280R4 struck the restriction that variable of reference type lifetime
3435 // should begin within the evaluation of E
3436 // Used to be C++20 [expr.const]p5.12.2:
3437 // ... its lifetime began within the evaluation of E;
3438 if (isa<ParmVarDecl>(VD)) {
3439 if (AllowConstexprUnknown) {
3440 Result = nullptr;
3441 return true;
3442 }
3443
3444 // Assume parameters of a potential constant expression are usable in
3445 // constant expressions.
3446 if (!Info.checkingPotentialConstantExpression() ||
3447 !Info.CurrentCall->Callee ||
3448 !Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
3449 if (Info.getLangOpts().CPlusPlus11) {
3450 Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown)
3451 << VD;
3452 NoteLValueLocation(Info, Base);
3453 } else {
3454 Info.FFDiag(E);
3455 }
3456 }
3457 return false;
3458 }
3459
3460 if (E->isValueDependent())
3461 return false;
3462
3463 // Dig out the initializer, and use the declaration which it's attached to.
3464 // FIXME: We should eventually check whether the variable has a reachable
3465 // initializing declaration.
3466 const Expr *Init = VD->getAnyInitializer(VD);
3467 // P2280R4 struck the restriction that variable of reference type should have
3468 // a preceding initialization.
3469 // Used to be C++20 [expr.const]p5.12:
3470 // ... reference has a preceding initialization and either ...
3471 if (!Init && !AllowConstexprUnknown) {
3472 // Don't diagnose during potential constant expression checking; an
3473 // initializer might be added later.
3474 if (!Info.checkingPotentialConstantExpression()) {
3475 Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1)
3476 << VD;
3477 NoteLValueLocation(Info, Base);
3478 }
3479 return false;
3480 }
3481
3482 // P2280R4 struck the initialization requirement for variables of reference
3483 // type so we can no longer assume we have an Init.
3484 // Used to be C++20 [expr.const]p5.12:
3485 // ... reference has a preceding initialization and either ...
3486 if (Init && Init->isValueDependent()) {
3487 if (!Info.checkingPotentialConstantExpression()) {
3488 Info.FFDiag(E,
3489 Info.getLangOpts().CPlusPlus11
3490 ? diag::note_constexpr_ltor_non_constexpr
3491 : diag::note_constexpr_ltor_non_integral,
3492 1)
3493 << VD << VD->getType();
3494 NoteLValueLocation(Info, Base);
3495 }
3496
3497 // A recovery initializer can be value-dependent even when the expression
3498 // referring to the variable is not.
3499 if (Init->containsErrors())
3500 return false;
3501
3502 // The DeclRefExpr is not value-dependent, but the variable it refers to
3503 // has a value-dependent initializer. This should only happen in
3504 // constant-folding cases, where the variable is not actually of a suitable
3505 // type for use in a constant expression (otherwise the DeclRefExpr would
3506 // have been value-dependent too), so diagnose that.
3507 assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx));
3508 return false;
3509 }
3510
3511 // Check that we can fold the initializer. In C++, we will have already done
3512 // this in the cases where it matters for conformance.
3513 // P2280R4 struck the initialization requirement for variables of reference
3514 // type so we can no longer assume we have an Init.
3515 // Used to be C++20 [expr.const]p5.12:
3516 // ... reference has a preceding initialization and either ...
3517 if (Init && !VD->evaluateValue() && !AllowConstexprUnknown) {
3518 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3519 NoteLValueLocation(Info, Base);
3520 return false;
3521 }
3522
3523 // Check that the variable is actually usable in constant expressions. For a
3524 // const integral variable or a reference, we might have a non-constant
3525 // initializer that we can nonetheless evaluate the initializer for. Such
3526 // variables are not usable in constant expressions. In C++98, the
3527 // initializer also syntactically needs to be an ICE.
3528 //
3529 // FIXME: We don't diagnose cases that aren't potentially usable in constant
3530 // expressions here; doing so would regress diagnostics for things like
3531 // reading from a volatile constexpr variable.
3532 if ((Info.getLangOpts().CPlusPlus && !VD->hasConstantInitialization() &&
3533 VD->mightBeUsableInConstantExpressions(Info.Ctx) &&
3534 !AllowConstexprUnknown) ||
3535 ((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) &&
3536 !Info.getLangOpts().CPlusPlus11 && !VD->hasICEInitializer(Info.Ctx))) {
3537 if (Init) {
3538 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3539 NoteLValueLocation(Info, Base);
3540 } else {
3541 Info.CCEDiag(E);
3542 }
3543 }
3544
3545 // Never use the initializer of a weak variable, not even for constant
3546 // folding. We can't be sure that this is the definition that will be used.
3547 if (VD->isWeak()) {
3548 Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD;
3549 NoteLValueLocation(Info, Base);
3550 return false;
3551 }
3552
3553 Result = const_cast<APValue *>(VD->getEvaluatedValue());
3554
3555 if (!Result && !AllowConstexprUnknown)
3556 return false;
3557
3558 return CheckUninitReference(/*IsLocalVariable=*/false);
3559}
3560
3561/// Get the base index of the given base class within an APValue representing
3562/// the given derived class.
3563static unsigned getBaseIndex(const CXXRecordDecl *Derived,
3564 const CXXRecordDecl *Base) {
3565 Base = Base->getCanonicalDecl();
3566 unsigned Index = 0;
3567 for (const CXXBaseSpecifier &B : Derived->bases()) {
3568 if (B.isVirtual())
3569 continue;
3571 return Index;
3572 ++Index;
3573 }
3574
3575 for (const CXXBaseSpecifier &B : Derived->vbases()) {
3577 return Index;
3578 ++Index;
3579 }
3580
3581 llvm_unreachable("base class missing from derived class's bases list");
3582}
3583
3584/// Extract the value of a character from a string literal.
3585static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
3586 uint64_t Index) {
3587 assert(!isa<SourceLocExpr>(Lit) &&
3588 "SourceLocExpr should have already been converted to a StringLiteral");
3589
3590 // FIXME: Support MakeStringConstant
3591 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
3592 std::string Str;
3593 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
3594 assert(Index <= Str.size() && "Index too large");
3595 return APSInt::getUnsigned(Str.c_str()[Index]);
3596 }
3597
3598 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
3599 Lit = PE->getFunctionName();
3600 const StringLiteral *S = cast<StringLiteral>(Lit);
3601 const ConstantArrayType *CAT =
3602 Info.Ctx.getAsConstantArrayType(S->getType());
3603 assert(CAT && "string literal isn't an array");
3604 QualType CharType = CAT->getElementType();
3605 assert(CharType->isIntegerType() && "unexpected character type");
3606 APSInt Value(Info.Ctx.getTypeSize(CharType),
3607 CharType->isUnsignedIntegerType());
3608 if (Index < S->getLength())
3609 Value = S->getCodeUnit(Index);
3610 return Value;
3611}
3612
3613// Expand a string literal into an array of characters.
3614//
3615// FIXME: This is inefficient; we should probably introduce something similar
3616// to the LLVM ConstantDataArray to make this cheaper.
3617static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
3618 APValue &Result,
3619 QualType AllocType = QualType()) {
3620 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
3621 AllocType.isNull() ? S->getType() : AllocType);
3622 assert(CAT && "string literal isn't an array");
3623 QualType CharType = CAT->getElementType();
3624 assert(CharType->isIntegerType() && "unexpected character type");
3625
3626 unsigned Elts = CAT->getZExtSize();
3628 std::min(S->getLength(), Elts), Elts);
3629 APSInt Value(Info.Ctx.getTypeSize(CharType),
3630 CharType->isUnsignedIntegerType());
3631 if (Result.hasArrayFiller())
3632 Result.getArrayFiller() = APValue(Value);
3633 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
3634 Value = S->getCodeUnit(I);
3635 Result.getArrayInitializedElt(I) = APValue(Value);
3636 }
3637}
3638
3639// Expand an array so that it has more than Index filled elements.
3640static void expandArray(APValue &Array, unsigned Index) {
3641 unsigned Size = Array.getArraySize();
3642 assert(Index < Size);
3643
3644 // Always at least double the number of elements for which we store a value.
3645 unsigned OldElts = Array.getArrayInitializedElts();
3646 unsigned NewElts = std::max(Index+1, OldElts * 2);
3647 NewElts = std::min(Size, std::max(NewElts, 8u));
3648
3649 // Copy the data across.
3650 APValue NewValue(APValue::UninitArray(), NewElts, Size);
3651 for (unsigned I = 0; I != OldElts; ++I)
3652 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
3653 for (unsigned I = OldElts; I != NewElts; ++I)
3654 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
3655 if (NewValue.hasArrayFiller())
3656 NewValue.getArrayFiller() = Array.getArrayFiller();
3657 Array.swap(NewValue);
3658}
3659
3660// Expand an indeterminate vector to materialize all elements.
3661static void expandVector(APValue &Vec, unsigned NumElements) {
3662 assert(Vec.isIndeterminate());
3664 Vec = APValue(Elts.data(), Elts.size());
3665}
3666
3667/// Determine whether a type would actually be read by an lvalue-to-rvalue
3668/// conversion. If it's of class type, we may assume that the copy operation
3669/// is trivial. Note that this is never true for a union type with fields
3670/// (because the copy always "reads" the active member) and always true for
3671/// a non-class type.
3672bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD);
3674 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3675 return !RD || isReadByLvalueToRvalueConversion(RD);
3676}
3678 // FIXME: A trivial copy of a union copies the object representation, even if
3679 // the union is empty.
3680 if (RD->isUnion())
3681 return !RD->field_empty();
3682 if (RD->isEmpty())
3683 return false;
3684
3685 for (auto *Field : RD->fields())
3686 if (!Field->isUnnamedBitField() &&
3687 isReadByLvalueToRvalueConversion(Field->getType()))
3688 return true;
3689
3690 for (auto &BaseSpec : RD->bases())
3691 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
3692 return true;
3693
3694 return false;
3695}
3696
3697/// Diagnose an attempt to read from any unreadable field within the specified
3698/// type, which might be a class type.
3699static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK,
3700 QualType T) {
3701 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3702 if (!RD)
3703 return false;
3704
3705 if (!RD->hasMutableFields())
3706 return false;
3707
3708 for (auto *Field : RD->fields()) {
3709 // If we're actually going to read this field in some way, then it can't
3710 // be mutable. If we're in a union, then assigning to a mutable field
3711 // (even an empty one) can change the active member, so that's not OK.
3712 // FIXME: Add core issue number for the union case.
3713 if (Field->isMutable() &&
3714 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
3715 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field;
3716 Info.Note(Field->getLocation(), diag::note_declared_at);
3717 return true;
3718 }
3719
3720 if (diagnoseMutableFields(Info, E, AK, Field->getType()))
3721 return true;
3722 }
3723
3724 for (auto &BaseSpec : RD->bases())
3725 if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType()))
3726 return true;
3727
3728 // All mutable fields were empty, and thus not actually read.
3729 return false;
3730}
3731
3732static bool lifetimeStartedInEvaluation(EvalInfo &Info,
3734 bool MutableSubobject = false) {
3735 // A temporary or transient heap allocation we created.
3736 if (Base.getCallIndex() || Base.is<DynamicAllocLValue>())
3737 return true;
3738
3739 switch (Info.IsEvaluatingDecl) {
3740 case EvalInfo::EvaluatingDeclKind::None:
3741 return false;
3742
3743 case EvalInfo::EvaluatingDeclKind::Ctor:
3744 // The variable whose initializer we're evaluating.
3745 if (Info.EvaluatingDecl == Base)
3746 return true;
3747
3748 // A temporary lifetime-extended by the variable whose initializer we're
3749 // evaluating.
3750 if (auto *BaseE = Base.dyn_cast<const Expr *>())
3751 if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
3752 return Info.EvaluatingDecl == BaseMTE->getExtendingDecl();
3753 return false;
3754
3755 case EvalInfo::EvaluatingDeclKind::Dtor:
3756 // C++2a [expr.const]p6:
3757 // [during constant destruction] the lifetime of a and its non-mutable
3758 // subobjects (but not its mutable subobjects) [are] considered to start
3759 // within e.
3760 if (MutableSubobject || Base != Info.EvaluatingDecl)
3761 return false;
3762 // FIXME: We can meaningfully extend this to cover non-const objects, but
3763 // we will need special handling: we should be able to access only
3764 // subobjects of such objects that are themselves declared const.
3766 return T.isConstQualified() || T->isReferenceType();
3767 }
3768
3769 llvm_unreachable("unknown evaluating decl kind");
3770}
3771
3772static bool CheckArraySize(EvalInfo &Info, const ConstantArrayType *CAT,
3773 SourceLocation CallLoc = {}) {
3774 return Info.CheckArraySize(
3775 CAT->getSizeExpr() ? CAT->getSizeExpr()->getBeginLoc() : CallLoc,
3776 CAT->getNumAddressingBits(Info.Ctx), CAT->getZExtSize(),
3777 /*Diag=*/true);
3778}
3779
3780static bool handleScalarCast(EvalInfo &Info, const FPOptions FPO, const Expr *E,
3781 QualType SourceTy, QualType DestTy,
3782 APValue const &Original, APValue &Result) {
3783 // boolean must be checked before integer
3784 // since IsIntegerType() is true for bool
3785 if (SourceTy->isBooleanType()) {
3786 if (DestTy->isBooleanType()) {
3787 Result = Original;
3788 return true;
3789 }
3790 if (DestTy->isIntegerType() || DestTy->isRealFloatingType()) {
3791 bool BoolResult;
3792 if (!HandleConversionToBool(Original, BoolResult))
3793 return false;
3794 uint64_t IntResult = BoolResult;
3795 QualType IntType = DestTy->isIntegerType()
3796 ? DestTy
3797 : Info.Ctx.getIntTypeForBitwidth(64, false);
3798 Result = APValue(Info.Ctx.MakeIntValue(IntResult, IntType));
3799 }
3800 if (DestTy->isRealFloatingType()) {
3801 APValue Result2 = APValue(APFloat(0.0));
3802 if (!HandleIntToFloatCast(Info, E, FPO,
3803 Info.Ctx.getIntTypeForBitwidth(64, false),
3804 Result.getInt(), DestTy, Result2.getFloat()))
3805 return false;
3806 Result = std::move(Result2);
3807 }
3808 return true;
3809 }
3810 if (SourceTy->isIntegerType()) {
3811 if (DestTy->isRealFloatingType()) {
3812 Result = APValue(APFloat(0.0));
3813 return HandleIntToFloatCast(Info, E, FPO, SourceTy, Original.getInt(),
3814 DestTy, Result.getFloat());
3815 }
3816 if (DestTy->isBooleanType()) {
3817 bool BoolResult;
3818 if (!HandleConversionToBool(Original, BoolResult))
3819 return false;
3820 uint64_t IntResult = BoolResult;
3821 Result = APValue(Info.Ctx.MakeIntValue(IntResult, DestTy));
3822 return true;
3823 }
3824 if (DestTy->isIntegerType()) {
3825 Result = APValue(
3826 HandleIntToIntCast(Info, E, DestTy, SourceTy, Original.getInt()));
3827 return true;
3828 }
3829 } else if (SourceTy->isRealFloatingType()) {
3830 if (DestTy->isRealFloatingType()) {
3831 Result = Original;
3832 return HandleFloatToFloatCast(Info, E, SourceTy, DestTy,
3833 Result.getFloat());
3834 }
3835 if (DestTy->isBooleanType()) {
3836 bool BoolResult;
3837 if (!HandleConversionToBool(Original, BoolResult))
3838 return false;
3839 uint64_t IntResult = BoolResult;
3840 Result = APValue(Info.Ctx.MakeIntValue(IntResult, DestTy));
3841 return true;
3842 }
3843 if (DestTy->isIntegerType()) {
3844 Result = APValue(APSInt());
3845 return HandleFloatToIntCast(Info, E, SourceTy, Original.getFloat(),
3846 DestTy, Result.getInt());
3847 }
3848 }
3849
3850 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3851 return false;
3852}
3853
3854// do the heavy lifting for casting to aggregate types
3855// because we have to deal with bitfields specially
3856static bool constructAggregate(EvalInfo &Info, const FPOptions FPO,
3857 const Expr *E, APValue &Result,
3858 QualType ResultType,
3859 SmallVectorImpl<APValue> &Elements,
3860 SmallVectorImpl<QualType> &ElTypes) {
3861
3863 {&Result, ResultType, 0}};
3864
3865 unsigned ElI = 0;
3866 while (!WorkList.empty() && ElI < Elements.size()) {
3867 auto [Res, Type, BitWidth] = WorkList.pop_back_val();
3868
3869 if (Type->isRealFloatingType()) {
3870 if (!handleScalarCast(Info, FPO, E, ElTypes[ElI], Type, Elements[ElI],
3871 *Res))
3872 return false;
3873 ElI++;
3874 continue;
3875 }
3876 if (Type->isIntegerType()) {
3877 if (!handleScalarCast(Info, FPO, E, ElTypes[ElI], Type, Elements[ElI],
3878 *Res))
3879 return false;
3880 if (BitWidth > 0) {
3881 if (!Res->isInt())
3882 return false;
3883 APSInt &Int = Res->getInt();
3884 unsigned OldBitWidth = Int.getBitWidth();
3885 unsigned NewBitWidth = BitWidth;
3886 if (NewBitWidth < OldBitWidth)
3887 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
3888 }
3889 ElI++;
3890 continue;
3891 }
3892 if (Type->isVectorType()) {
3893 QualType ElTy = Type->castAs<VectorType>()->getElementType();
3894 unsigned NumEl = Type->castAs<VectorType>()->getNumElements();
3895 SmallVector<APValue> Vals(NumEl);
3896 for (unsigned I = 0; I < NumEl; ++I) {
3897 if (!handleScalarCast(Info, FPO, E, ElTypes[ElI], ElTy, Elements[ElI],
3898 Vals[I]))
3899 return false;
3900 ElI++;
3901 }
3902 *Res = APValue(Vals.data(), NumEl);
3903 continue;
3904 }
3905 if (Type->isConstantArrayType()) {
3906 QualType ElTy = cast<ConstantArrayType>(Info.Ctx.getAsArrayType(Type))
3907 ->getElementType();
3908 uint64_t Size =
3909 cast<ConstantArrayType>(Info.Ctx.getAsArrayType(Type))->getZExtSize();
3910 *Res = APValue(APValue::UninitArray(), Size, Size);
3911 for (int64_t I = Size - 1; I > -1; --I)
3912 WorkList.emplace_back(&Res->getArrayInitializedElt(I), ElTy, 0u);
3913 continue;
3914 }
3915 if (Type->isRecordType()) {
3916 const RecordDecl *RD = Type->getAsRecordDecl();
3917
3918 unsigned NumBases = 0;
3919 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
3920 NumBases = CXXRD->getNumBases();
3921
3922 *Res = APValue(APValue::UninitStruct(), NumBases, RD->getNumFields());
3923
3925 // we need to traverse backwards
3926 // Visit the base classes.
3927 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3928 if (CXXRD->getNumBases() > 0) {
3929 assert(CXXRD->getNumBases() == 1);
3930 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[0];
3931 ReverseList.emplace_back(&Res->getStructBase(0), BS.getType(), 0u);
3932 }
3933 }
3934
3935 // Visit the fields.
3936 for (FieldDecl *FD : RD->fields()) {
3937 unsigned FDBW = 0;
3938 if (FD->isUnnamedBitField())
3939 continue;
3940 if (FD->isBitField()) {
3941 FDBW = FD->getBitWidthValue();
3942 }
3943
3944 ReverseList.emplace_back(&Res->getStructField(FD->getFieldIndex()),
3945 FD->getType(), FDBW);
3946 }
3947
3948 std::reverse(ReverseList.begin(), ReverseList.end());
3949 llvm::append_range(WorkList, ReverseList);
3950 continue;
3951 }
3952 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3953 return false;
3954 }
3955 return true;
3956}
3957
3958static bool handleElementwiseCast(EvalInfo &Info, const Expr *E,
3959 const FPOptions FPO,
3960 SmallVectorImpl<APValue> &Elements,
3961 SmallVectorImpl<QualType> &SrcTypes,
3962 SmallVectorImpl<QualType> &DestTypes,
3963 SmallVectorImpl<APValue> &Results) {
3964
3965 assert((Elements.size() == SrcTypes.size()) &&
3966 (Elements.size() == DestTypes.size()));
3967
3968 for (unsigned I = 0, ESz = Elements.size(); I < ESz; ++I) {
3969 APValue Original = Elements[I];
3970 QualType SourceTy = SrcTypes[I];
3971 QualType DestTy = DestTypes[I];
3972
3973 if (!handleScalarCast(Info, FPO, E, SourceTy, DestTy, Original, Results[I]))
3974 return false;
3975 }
3976 return true;
3977}
3978
3979static unsigned elementwiseSize(EvalInfo &Info, QualType BaseTy) {
3980
3981 SmallVector<QualType> WorkList = {BaseTy};
3982
3983 unsigned Size = 0;
3984 while (!WorkList.empty()) {
3985 QualType Type = WorkList.pop_back_val();
3987 Type->isBooleanType()) {
3988 ++Size;
3989 continue;
3990 }
3991 if (Type->isVectorType()) {
3992 unsigned NumEl = Type->castAs<VectorType>()->getNumElements();
3993 Size += NumEl;
3994 continue;
3995 }
3996 if (Type->isConstantMatrixType()) {
3997 unsigned NumEl =
3998 Type->castAs<ConstantMatrixType>()->getNumElementsFlattened();
3999 Size += NumEl;
4000 continue;
4001 }
4002 if (Type->isConstantArrayType()) {
4003 QualType ElTy = cast<ConstantArrayType>(Info.Ctx.getAsArrayType(Type))
4004 ->getElementType();
4005 uint64_t ArrSize =
4006 cast<ConstantArrayType>(Info.Ctx.getAsArrayType(Type))->getZExtSize();
4007 for (uint64_t I = 0; I < ArrSize; ++I) {
4008 WorkList.push_back(ElTy);
4009 }
4010 continue;
4011 }
4012 if (Type->isRecordType()) {
4013 const RecordDecl *RD = Type->getAsRecordDecl();
4014
4015 // Visit the base classes.
4016 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
4017 if (CXXRD->getNumBases() > 0) {
4018 assert(CXXRD->getNumBases() == 1);
4019 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[0];
4020 WorkList.push_back(BS.getType());
4021 }
4022 }
4023
4024 // visit the fields.
4025 for (FieldDecl *FD : RD->fields()) {
4026 if (FD->isUnnamedBitField())
4027 continue;
4028 WorkList.push_back(FD->getType());
4029 }
4030 continue;
4031 }
4032 }
4033 return Size;
4034}
4035
4036static bool hlslAggSplatHelper(EvalInfo &Info, const Expr *E, APValue &SrcVal,
4037 QualType &SrcTy) {
4038 SrcTy = E->getType();
4039
4040 if (!Evaluate(SrcVal, Info, E))
4041 return false;
4042
4043 assert((SrcVal.isFloat() || SrcVal.isInt() ||
4044 (SrcVal.isVector() && SrcVal.getVectorLength() == 1)) &&
4045 "Not a valid HLSLAggregateSplatCast.");
4046
4047 if (SrcVal.isVector()) {
4048 assert(SrcTy->isVectorType() && "Type mismatch.");
4049 SrcTy = SrcTy->castAs<VectorType>()->getElementType();
4050 SrcVal = SrcVal.getVectorElt(0);
4051 }
4052 if (SrcVal.isMatrix()) {
4053 assert(SrcTy->isConstantMatrixType() && "Type mismatch.");
4054 SrcTy = SrcTy->castAs<ConstantMatrixType>()->getElementType();
4055 SrcVal = SrcVal.getMatrixElt(0, 0);
4056 }
4057 return true;
4058}
4059
4060static bool flattenAPValue(EvalInfo &Info, const Expr *E, APValue Value,
4061 QualType BaseTy, SmallVectorImpl<APValue> &Elements,
4062 SmallVectorImpl<QualType> &Types, unsigned Size) {
4063
4064 SmallVector<std::pair<APValue, QualType>> WorkList = {{Value, BaseTy}};
4065 unsigned Populated = 0;
4066 while (!WorkList.empty() && Populated < Size) {
4067 auto [Work, Type] = WorkList.pop_back_val();
4068
4069 if (Work.isFloat() || Work.isInt()) {
4070 Elements.push_back(Work);
4071 Types.push_back(Type);
4072 Populated++;
4073 continue;
4074 }
4075 if (Work.isVector()) {
4076 assert(Type->isVectorType() && "Type mismatch.");
4077 QualType ElTy = Type->castAs<VectorType>()->getElementType();
4078 for (unsigned I = 0; I < Work.getVectorLength() && Populated < Size;
4079 I++) {
4080 Elements.push_back(Work.getVectorElt(I));
4081 Types.push_back(ElTy);
4082 Populated++;
4083 }
4084 continue;
4085 }
4086 if (Work.isMatrix()) {
4087 assert(Type->isConstantMatrixType() && "Type mismatch.");
4088 const auto *MT = Type->castAs<ConstantMatrixType>();
4089 QualType ElTy = MT->getElementType();
4090 // Matrix elements are flattened in row-major order.
4091 for (unsigned Row = 0; Row < Work.getMatrixNumRows() && Populated < Size;
4092 Row++) {
4093 for (unsigned Col = 0;
4094 Col < Work.getMatrixNumColumns() && Populated < Size; Col++) {
4095 Elements.push_back(Work.getMatrixElt(Row, Col));
4096 Types.push_back(ElTy);
4097 Populated++;
4098 }
4099 }
4100 continue;
4101 }
4102 if (Work.isArray()) {
4103 assert(Type->isConstantArrayType() && "Type mismatch.");
4104 QualType ElTy = cast<ConstantArrayType>(Info.Ctx.getAsArrayType(Type))
4105 ->getElementType();
4106 for (int64_t I = Work.getArraySize() - 1; I > -1; --I) {
4107 WorkList.emplace_back(Work.getArrayInitializedElt(I), ElTy);
4108 }
4109 continue;
4110 }
4111
4112 if (Work.isStruct()) {
4113 assert(Type->isRecordType() && "Type mismatch.");
4114
4115 const RecordDecl *RD = Type->getAsRecordDecl();
4116
4118 // Visit the fields.
4119 for (FieldDecl *FD : RD->fields()) {
4120 if (FD->isUnnamedBitField())
4121 continue;
4122 ReverseList.emplace_back(Work.getStructField(FD->getFieldIndex()),
4123 FD->getType());
4124 }
4125
4126 std::reverse(ReverseList.begin(), ReverseList.end());
4127 llvm::append_range(WorkList, ReverseList);
4128
4129 // Visit the base classes.
4130 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
4131 if (CXXRD->getNumBases() > 0) {
4132 assert(CXXRD->getNumBases() == 1);
4133 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[0];
4134 const APValue &Base = Work.getStructBase(0);
4135
4136 // Can happen in error cases.
4137 if (!Base.isStruct())
4138 return false;
4139
4140 WorkList.emplace_back(Base, BS.getType());
4141 }
4142 }
4143 continue;
4144 }
4145 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
4146 return false;
4147 }
4148 return true;
4149}
4150
4151namespace {
4152/// A handle to a complete object (an object that is not a subobject of
4153/// another object).
4154struct CompleteObject {
4155 /// The identity of the object.
4156 APValue::LValueBase Base;
4157 /// The value of the complete object.
4158 APValue *Value;
4159 /// The type of the complete object.
4160 QualType Type;
4161
4162 CompleteObject() : Value(nullptr) {}
4163 CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
4164 : Base(Base), Value(Value), Type(Type) {}
4165
4166 bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const {
4167 // If this isn't a "real" access (eg, if it's just accessing the type
4168 // info), allow it. We assume the type doesn't change dynamically for
4169 // subobjects of constexpr objects (even though we'd hit UB here if it
4170 // did). FIXME: Is this right?
4171 if (!isAnyAccess(AK))
4172 return true;
4173
4174 // In C++14 onwards, it is permitted to read a mutable member whose
4175 // lifetime began within the evaluation.
4176 // FIXME: Should we also allow this in C++11?
4177 if (!Info.getLangOpts().CPlusPlus14 &&
4178 AK != AccessKinds::AK_IsWithinLifetime)
4179 return false;
4180 return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);
4181 }
4182
4183 explicit operator bool() const { return !Type.isNull(); }
4184};
4185} // end anonymous namespace
4186
4187static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
4188 bool IsMutable = false) {
4189 // C++ [basic.type.qualifier]p1:
4190 // - A const object is an object of type const T or a non-mutable subobject
4191 // of a const object.
4192 if (ObjType.isConstQualified() && !IsMutable)
4193 SubobjType.addConst();
4194 // - A volatile object is an object of type const T or a subobject of a
4195 // volatile object.
4196 if (ObjType.isVolatileQualified())
4197 SubobjType.addVolatile();
4198 return SubobjType;
4199}
4200
4201/// Find the designated sub-object of an rvalue.
4202template <typename SubobjectHandler>
4203static typename SubobjectHandler::result_type
4204findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
4205 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
4206 if (Sub.Invalid)
4207 // A diagnostic will have already been produced.
4208 return handler.failed();
4209 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
4210 if (Info.getLangOpts().CPlusPlus11)
4211 Info.FFDiag(E, Sub.isOnePastTheEnd()
4212 ? diag::note_constexpr_access_past_end
4213 : diag::note_constexpr_access_unsized_array)
4214 << handler.AccessKind;
4215 else
4216 Info.FFDiag(E);
4217 return handler.failed();
4218 }
4219
4220 APValue *O = Obj.Value;
4221 QualType ObjType = Obj.Type;
4222 const FieldDecl *LastField = nullptr;
4223 const FieldDecl *VolatileField = nullptr;
4224
4225 // Walk the designator's path to find the subobject.
4226 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
4227 // Reading an indeterminate value is undefined, but assigning over one is OK.
4228 if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) ||
4229 (O->isIndeterminate() &&
4230 !isValidIndeterminateAccess(handler.AccessKind))) {
4231 // Object has ended lifetime.
4232 // If I is non-zero, some subobject (member or array element) of a
4233 // complete object has ended its lifetime, so this is valid for
4234 // IsWithinLifetime, resulting in false.
4235 if (I != 0 && handler.AccessKind == AK_IsWithinLifetime)
4236 return false;
4237 if (!Info.checkingPotentialConstantExpression()) {
4238 Info.FFDiag(E, diag::note_constexpr_access_uninit)
4239 << handler.AccessKind << O->isIndeterminate()
4240 << E->getSourceRange();
4241 NoteLValueLocation(Info, Obj.Base);
4242 }
4243 return handler.failed();
4244 }
4245
4246 // C++ [class.ctor]p5, C++ [class.dtor]p5:
4247 // const and volatile semantics are not applied on an object under
4248 // {con,de}struction.
4249 if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
4250 ObjType->isRecordType() &&
4251 Info.isEvaluatingCtorDtor(
4252 Obj.Base, ArrayRef(Sub.Entries.begin(), Sub.Entries.begin() + I)) !=
4253 ConstructionPhase::None) {
4254 ObjType = Info.Ctx.getCanonicalType(ObjType);
4255 ObjType.removeLocalConst();
4256 ObjType.removeLocalVolatile();
4257 }
4258
4259 // If this is our last pass, check that the final object type is OK.
4260 if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
4261 // Accesses to volatile objects are prohibited.
4262 if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
4263 if (Info.getLangOpts().CPlusPlus) {
4264 int DiagKind;
4265 SourceLocation Loc;
4266 const NamedDecl *Decl = nullptr;
4267 if (VolatileField) {
4268 DiagKind = 2;
4269 Loc = VolatileField->getLocation();
4270 Decl = VolatileField;
4271 } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
4272 DiagKind = 1;
4273 Loc = VD->getLocation();
4274 Decl = VD;
4275 } else {
4276 DiagKind = 0;
4277 if (auto *E = Obj.Base.dyn_cast<const Expr *>())
4278 Loc = E->getExprLoc();
4279 }
4280 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
4281 << handler.AccessKind << DiagKind << Decl;
4282 Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
4283 } else {
4284 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
4285 }
4286 return handler.failed();
4287 }
4288
4289 // If we are reading an object of class type, there may still be more
4290 // things we need to check: if there are any mutable subobjects, we
4291 // cannot perform this read. (This only happens when performing a trivial
4292 // copy or assignment.)
4293 if (ObjType->isRecordType() &&
4294 !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
4295 diagnoseMutableFields(Info, E, handler.AccessKind, ObjType))
4296 return handler.failed();
4297 }
4298
4299 if (I == N) {
4300 if (!handler.found(*O, ObjType, Obj.Base))
4301 return false;
4302
4303 // If we modified a bit-field, truncate it to the right width.
4304 if (isModification(handler.AccessKind) &&
4305 LastField && LastField->isBitField() &&
4306 !truncateBitfieldValue(Info, E, *O, LastField))
4307 return false;
4308
4309 return true;
4310 }
4311
4312 LastField = nullptr;
4313
4314 // The value of an atomic object is represented like a value of the
4315 // underlying type, so look through the _Atomic wrapper.
4316 if (const AtomicType *AT = ObjType->getAs<AtomicType>())
4317 ObjType = Info.Ctx.getQualifiedType(AT->getValueType(),
4318 ObjType.getQualifiers());
4319
4320 if (ObjType->isArrayType()) {
4321 // Next subobject is an array element.
4322 const ArrayType *AT = Info.Ctx.getAsArrayType(ObjType);
4324 "vla in literal type?");
4325 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
4326 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT);
4327 CAT && CAT->getSize().ule(Index)) {
4328 // Note, it should not be possible to form a pointer with a valid
4329 // designator which points more than one past the end of the array.
4330 if (Info.getLangOpts().CPlusPlus11)
4331 Info.FFDiag(E, diag::note_constexpr_access_past_end)
4332 << handler.AccessKind;
4333 else
4334 Info.FFDiag(E);
4335 return handler.failed();
4336 }
4337
4338 ObjType = AT->getElementType();
4339
4340 if (O->getArrayInitializedElts() > Index)
4341 O = &O->getArrayInitializedElt(Index);
4342 else if (!isRead(handler.AccessKind)) {
4343 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT);
4344 CAT && !CheckArraySize(Info, CAT, E->getExprLoc()))
4345 return handler.failed();
4346
4347 expandArray(*O, Index);
4348 O = &O->getArrayInitializedElt(Index);
4349 } else
4350 O = &O->getArrayFiller();
4351 } else if (ObjType->isAnyComplexType()) {
4352 // Next subobject is a complex number.
4353 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
4354 if (Index > 1) {
4355 if (Info.getLangOpts().CPlusPlus11)
4356 Info.FFDiag(E, diag::note_constexpr_access_past_end)
4357 << handler.AccessKind;
4358 else
4359 Info.FFDiag(E);
4360 return handler.failed();
4361 }
4362
4363 ObjType = getSubobjectType(
4364 ObjType, ObjType->castAs<ComplexType>()->getElementType());
4365
4366 assert(I == N - 1 && "extracting subobject of scalar?");
4367 if (O->isComplexInt()) {
4368 return handler.found(Index ? O->getComplexIntImag()
4369 : O->getComplexIntReal(), ObjType);
4370 } else {
4371 assert(O->isComplexFloat());
4372 return handler.found(Index ? O->getComplexFloatImag()
4373 : O->getComplexFloatReal(), ObjType);
4374 }
4375 } else if (const auto *VT = ObjType->getAs<VectorType>()) {
4376 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
4377 unsigned NumElements = VT->getNumElements();
4378 if (Index == NumElements) {
4379 if (Info.getLangOpts().CPlusPlus11)
4380 Info.FFDiag(E, diag::note_constexpr_access_past_end)
4381 << handler.AccessKind;
4382 else
4383 Info.FFDiag(E);
4384 return handler.failed();
4385 }
4386
4387 if (Index > NumElements) {
4388 Info.CCEDiag(E, diag::note_constexpr_array_index)
4389 << Index << /*array*/ 0 << NumElements;
4390 return handler.failed();
4391 }
4392
4393 ObjType = VT->getElementType();
4394 assert(I == N - 1 && "extracting subobject of scalar?");
4395
4396 if (O->isIndeterminate()) {
4397 if (isRead(handler.AccessKind)) {
4398 Info.FFDiag(E);
4399 return handler.failed();
4400 }
4401 expandVector(*O, NumElements);
4402 }
4403 assert(O->isVector() && "unexpected object during vector element access");
4404 return handler.found(O->getVectorElt(Index), ObjType, Obj.Base);
4405 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
4406 if (Field->isMutable() &&
4407 !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) {
4408 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
4409 << handler.AccessKind << Field;
4410 Info.Note(Field->getLocation(), diag::note_declared_at);
4411 return handler.failed();
4412 }
4413
4414 // Next subobject is a class, struct or union field.
4415 RecordDecl *RD = ObjType->castAsCanonical<RecordType>()->getDecl();
4416 if (RD->isUnion()) {
4417 const FieldDecl *UnionField = O->getUnionField();
4418 if (!UnionField ||
4419 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
4420 if (I == N - 1 && handler.AccessKind == AK_Construct) {
4421 // Placement new onto an inactive union member makes it active.
4422 O->setUnion(Field, APValue());
4423 } else {
4424 // Pointer to/into inactive union member: Not within lifetime
4425 if (handler.AccessKind == AK_IsWithinLifetime)
4426 return false;
4427 // FIXME: If O->getUnionValue() is absent, report that there's no
4428 // active union member rather than reporting the prior active union
4429 // member. We'll need to fix nullptr_t to not use APValue() as its
4430 // representation first.
4431 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
4432 << handler.AccessKind << Field << !UnionField << UnionField;
4433 return handler.failed();
4434 }
4435 }
4436 O = &O->getUnionValue();
4437 } else
4438 O = &O->getStructField(Field->getFieldIndex());
4439
4440 ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
4441 LastField = Field;
4442 if (Field->getType().isVolatileQualified())
4443 VolatileField = Field;
4444 } else {
4445 // Next subobject is a base class.
4446 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
4447 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
4448
4449 unsigned BaseIndex = getBaseIndex(Derived, Base);
4450 unsigned NumNonVirtualBases = O->getStructNumBases();
4451 if (BaseIndex >= NumNonVirtualBases) {
4452 O = &O->getStructVirtualBase(BaseIndex - NumNonVirtualBases);
4453 } else
4454 O = &O->getStructBase(BaseIndex);
4455
4456 ObjType = getSubobjectType(ObjType, Info.Ctx.getCanonicalTagType(Base));
4457 }
4458 }
4459}
4460
4461namespace {
4462struct ExtractSubobjectHandler {
4463 EvalInfo &Info;
4464 const Expr *E;
4465 APValue &Result;
4466 const AccessKinds AccessKind;
4467
4468 typedef bool result_type;
4469 bool failed() { return false; }
4470 bool found(APValue &Subobj, QualType SubobjType, APValue::LValueBase Base) {
4471 Result = Subobj;
4472 if (AccessKind == AK_ReadObjectRepresentation)
4473 return true;
4474 return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
4475 }
4476 bool found(APSInt &Value, QualType SubobjType) {
4477 Result = APValue(Value);
4478 return true;
4479 }
4480 bool found(APFloat &Value, QualType SubobjType) {
4481 Result = APValue(Value);
4482 return true;
4483 }
4484};
4485} // end anonymous namespace
4486
4487/// Extract the designated sub-object of an rvalue.
4488static bool extractSubobject(EvalInfo &Info, const Expr *E,
4489 const CompleteObject &Obj,
4490 const SubobjectDesignator &Sub, APValue &Result,
4491 AccessKinds AK = AK_Read) {
4492 assert(AK == AK_Read || AK == AK_ReadObjectRepresentation);
4493 ExtractSubobjectHandler Handler = {Info, E, Result, AK};
4494 return findSubobject(Info, E, Obj, Sub, Handler);
4495}
4496
4497namespace {
4498struct ModifySubobjectHandler {
4499 EvalInfo &Info;
4500 APValue &NewVal;
4501 const Expr *E;
4502
4503 typedef bool result_type;
4504 static const AccessKinds AccessKind = AK_Assign;
4505
4506 bool checkConst(QualType QT) {
4507 // Assigning to a const object has undefined behavior.
4508 if (QT.isConstQualified()) {
4509 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4510 return false;
4511 }
4512 return true;
4513 }
4514
4515 bool failed() { return false; }
4516 bool found(APValue &Subobj, QualType SubobjType, APValue::LValueBase Base) {
4517 if (!checkConst(SubobjType))
4518 return false;
4519 // We've been given ownership of NewVal, so just swap it in.
4520 Subobj.swap(NewVal);
4521 return true;
4522 }
4523 bool found(APSInt &Value, QualType SubobjType) {
4524 if (!checkConst(SubobjType))
4525 return false;
4526 if (!NewVal.isInt()) {
4527 // Maybe trying to write a cast pointer value into a complex?
4528 Info.FFDiag(E);
4529 return false;
4530 }
4531 Value = NewVal.getInt();
4532 return true;
4533 }
4534 bool found(APFloat &Value, QualType SubobjType) {
4535 if (!checkConst(SubobjType))
4536 return false;
4537 Value = NewVal.getFloat();
4538 return true;
4539 }
4540};
4541} // end anonymous namespace
4542
4543const AccessKinds ModifySubobjectHandler::AccessKind;
4544
4545/// Update the designated sub-object of an rvalue to the given value.
4546static bool modifySubobject(EvalInfo &Info, const Expr *E,
4547 const CompleteObject &Obj,
4548 const SubobjectDesignator &Sub,
4549 APValue &NewVal) {
4550 ModifySubobjectHandler Handler = { Info, NewVal, E };
4551 return findSubobject(Info, E, Obj, Sub, Handler);
4552}
4553
4554/// Find the position where two subobject designators diverge, or equivalently
4555/// the length of the common initial subsequence.
4556static unsigned FindDesignatorMismatch(QualType ObjType,
4557 const SubobjectDesignator &A,
4558 const SubobjectDesignator &B,
4559 bool &WasArrayIndex) {
4560 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
4561 for (/**/; I != N; ++I) {
4562 if (!ObjType.isNull() &&
4563 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
4564 // Next subobject is an array element.
4565 if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
4566 WasArrayIndex = true;
4567 return I;
4568 }
4569 if (ObjType->isAnyComplexType())
4570 ObjType = ObjType->castAs<ComplexType>()->getElementType();
4571 else
4572 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
4573 } else {
4574 if (A.Entries[I].getAsBaseOrMember() !=
4575 B.Entries[I].getAsBaseOrMember()) {
4576 WasArrayIndex = false;
4577 return I;
4578 }
4579 if (const FieldDecl *FD = getAsField(A.Entries[I]))
4580 // Next subobject is a field.
4581 ObjType = FD->getType();
4582 else
4583 // Next subobject is a base class.
4584 ObjType = QualType();
4585 }
4586 }
4587 WasArrayIndex = false;
4588 return I;
4589}
4590
4591/// Determine whether the given subobject designators refer to elements of the
4592/// same array object.
4594 const SubobjectDesignator &A,
4595 const SubobjectDesignator &B) {
4596 if (A.Entries.size() != B.Entries.size())
4597 return false;
4598
4599 bool IsArray = A.MostDerivedIsArrayElement;
4600 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
4601 // A is a subobject of the array element.
4602 return false;
4603
4604 // If A (and B) designates an array element, the last entry will be the array
4605 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
4606 // of length 1' case, and the entire path must match.
4607 bool WasArrayIndex;
4608 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
4609 return CommonLength >= A.Entries.size() - IsArray;
4610}
4611
4612/// Find the complete object to which an LValue refers.
4613static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
4614 AccessKinds AK, const LValue &LVal,
4615 QualType LValType) {
4616 if (LVal.InvalidBase) {
4617 Info.FFDiag(E);
4618 return CompleteObject();
4619 }
4620
4621 if (!LVal.Base) {
4623 Info.FFDiag(E, diag::note_constexpr_dereferencing_null);
4624 else
4625 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
4626 return CompleteObject();
4627 }
4628
4629 CallStackFrame *Frame = nullptr;
4630 unsigned Depth = 0;
4631 if (LVal.getLValueCallIndex()) {
4632 std::tie(Frame, Depth) =
4633 Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
4634 if (!Frame) {
4635 Info.FFDiag(E, diag::note_constexpr_access_uninit, 1)
4636 << AK << /*Indeterminate=*/false << E->getSourceRange();
4637 NoteLValueLocation(Info, LVal.Base);
4638 return CompleteObject();
4639 }
4640 }
4641
4642 bool IsAccess = isAnyAccess(AK);
4643
4644 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
4645 // is not a constant expression (even if the object is non-volatile). We also
4646 // apply this rule to C++98, in order to conform to the expected 'volatile'
4647 // semantics.
4648 if (isFormalAccess(AK) && LValType.isVolatileQualified()) {
4649 if (Info.getLangOpts().CPlusPlus)
4650 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
4651 << AK << LValType;
4652 else
4653 Info.FFDiag(E);
4654 return CompleteObject();
4655 }
4656
4657 // Compute value storage location and type of base object.
4658 APValue *BaseVal = nullptr;
4659 QualType BaseType = getType(LVal.Base);
4660
4661 if (Info.getLangOpts().CPlusPlus14 && LVal.Base == Info.EvaluatingDecl &&
4662 lifetimeStartedInEvaluation(Info, LVal.Base)) {
4663 // This is the object whose initializer we're evaluating, so its lifetime
4664 // started in the current evaluation.
4665 BaseVal = Info.EvaluatingDeclValue;
4666 } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) {
4667 // Allow reading from a GUID declaration.
4668 if (auto *GD = dyn_cast<MSGuidDecl>(D)) {
4669 if (isModification(AK)) {
4670 // All the remaining cases do not permit modification of the object.
4671 Info.FFDiag(E, diag::note_constexpr_modify_global);
4672 return CompleteObject();
4673 }
4674 APValue &V = GD->getAsAPValue();
4675 if (V.isAbsent()) {
4676 Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
4677 << GD->getType();
4678 return CompleteObject();
4679 }
4680 return CompleteObject(LVal.Base, &V, GD->getType());
4681 }
4682
4683 // Allow reading the APValue from an UnnamedGlobalConstantDecl.
4684 if (auto *GCD = dyn_cast<UnnamedGlobalConstantDecl>(D)) {
4685 if (isModification(AK)) {
4686 Info.FFDiag(E, diag::note_constexpr_modify_global);
4687 return CompleteObject();
4688 }
4689 return CompleteObject(LVal.Base, const_cast<APValue *>(&GCD->getValue()),
4690 GCD->getType());
4691 }
4692
4693 // Allow reading from template parameter objects.
4694 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) {
4695 if (isModification(AK)) {
4696 Info.FFDiag(E, diag::note_constexpr_modify_global);
4697 return CompleteObject();
4698 }
4699 return CompleteObject(LVal.Base, const_cast<APValue *>(&TPO->getValue()),
4700 TPO->getType());
4701 }
4702
4703 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
4704 // In C++11, constexpr, non-volatile variables initialized with constant
4705 // expressions are constant expressions too. Inside constexpr functions,
4706 // parameters are constant expressions even if they're non-const.
4707 // In C++1y, objects local to a constant expression (those with a Frame) are
4708 // both readable and writable inside constant expressions.
4709 // In C, such things can also be folded, although they are not ICEs.
4710 const VarDecl *VD = dyn_cast<VarDecl>(D);
4711 if (VD) {
4712 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
4713 VD = VDef;
4714 }
4715 if (!VD || VD->isInvalidDecl()) {
4716 Info.FFDiag(E);
4717 return CompleteObject();
4718 }
4719
4720 bool IsConstant = BaseType.isConstant(Info.Ctx);
4721 bool ConstexprVar = false;
4722 if (const auto *VD = dyn_cast_if_present<VarDecl>(
4723 Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()))
4724 ConstexprVar = VD->isConstexpr();
4725
4726 // Unless we're looking at a local variable or argument in a constexpr call,
4727 // the variable we're reading must be const (unless we are binding to a
4728 // reference).
4729 if (AK != clang::AK_Dereference && !Frame) {
4730 if (IsAccess && isa<ParmVarDecl>(VD)) {
4731 // Access of a parameter that's not associated with a frame isn't going
4732 // to work out, but we can leave it to evaluateVarDeclInit to provide a
4733 // suitable diagnostic.
4734 } else if (Info.getLangOpts().CPlusPlus14 &&
4735 lifetimeStartedInEvaluation(Info, LVal.Base)) {
4736 // OK, we can read and modify an object if we're in the process of
4737 // evaluating its initializer, because its lifetime began in this
4738 // evaluation.
4739 } else if (isModification(AK)) {
4740 // All the remaining cases do not permit modification of the object.
4741 Info.FFDiag(E, diag::note_constexpr_modify_global);
4742 return CompleteObject();
4743 } else if (VD->isConstexpr()) {
4744 // OK, we can read this variable.
4745 } else if (Info.getLangOpts().C23 && ConstexprVar) {
4746 Info.FFDiag(E);
4747 return CompleteObject();
4748 } else if (VD->isCXXForRangeImplicitVar()) {
4749 if (!IsAccess)
4750 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4751 Info.FFDiag(E, diag::note_constexpr_ltor_for_range_var) << VD;
4752 return CompleteObject();
4753 } else if (BaseType->isIntegralOrEnumerationType()) {
4754 if (!IsConstant) {
4755 if (!IsAccess)
4756 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4757 if (Info.getLangOpts().CPlusPlus) {
4758 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
4759 Info.Note(VD->getLocation(), diag::note_declared_at);
4760 } else {
4761 Info.FFDiag(E);
4762 }
4763 return CompleteObject();
4764 }
4765 } else if (!IsAccess) {
4766 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4767 } else if ((IsConstant || BaseType->isReferenceType()) &&
4768 Info.checkingPotentialConstantExpression() &&
4769 BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) {
4770 // This variable might end up being constexpr. Don't diagnose it yet.
4771 } else if (IsConstant) {
4772 // Keep evaluating to see what we can do. In particular, we support
4773 // folding of const floating-point types, in order to make static const
4774 // data members of such types (supported as an extension) more useful.
4775 if (Info.getLangOpts().CPlusPlus) {
4776 Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11
4777 ? diag::note_constexpr_ltor_non_constexpr
4778 : diag::note_constexpr_ltor_non_integral, 1)
4779 << VD << BaseType;
4780 Info.Note(VD->getLocation(), diag::note_declared_at);
4781 } else {
4782 Info.CCEDiag(E);
4783 }
4784 } else {
4785 // Never allow reading a non-const value.
4786 if (Info.getLangOpts().CPlusPlus) {
4787 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
4788 ? diag::note_constexpr_ltor_non_constexpr
4789 : diag::note_constexpr_ltor_non_integral, 1)
4790 << VD << BaseType;
4791 Info.Note(VD->getLocation(), diag::note_declared_at);
4792 } else {
4793 Info.FFDiag(E);
4794 }
4795 return CompleteObject();
4796 }
4797 }
4798
4799 // When binding to a reference, the variable does not need to be constexpr
4800 // or have constant initalization.
4801 if (AK != clang::AK_Dereference &&
4802 !evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(),
4803 BaseVal))
4804 return CompleteObject();
4805 // If evaluateVarDeclInit sees a constexpr-unknown variable, it returns
4806 // a null BaseVal. Any constexpr-unknown variable seen here is an error:
4807 // we can't access a constexpr-unknown object.
4808 if (AK != clang::AK_Dereference && !BaseVal) {
4809 if (!Info.checkingPotentialConstantExpression()) {
4810 Info.FFDiag(E, diag::note_constexpr_access_unknown_variable, 1)
4811 << AK << VD;
4812 Info.Note(VD->getLocation(), diag::note_declared_at);
4813 }
4814 return CompleteObject();
4815 }
4816 } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) {
4817 std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
4818 if (!Alloc) {
4819 Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK;
4820 return CompleteObject();
4821 }
4822 return CompleteObject(LVal.Base, &(*Alloc)->Value,
4823 LVal.Base.getDynamicAllocType());
4824 }
4825 // When binding to a reference, the variable does not need to be
4826 // within its lifetime.
4827 else if (AK != clang::AK_Dereference) {
4828 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4829
4830 if (!Frame) {
4831 if (const MaterializeTemporaryExpr *MTE =
4832 dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
4833 assert(MTE->getStorageDuration() == SD_Static &&
4834 "should have a frame for a non-global materialized temporary");
4835
4836 // C++20 [expr.const]p4: [DR2126]
4837 // An object or reference is usable in constant expressions if it is
4838 // - a temporary object of non-volatile const-qualified literal type
4839 // whose lifetime is extended to that of a variable that is usable
4840 // in constant expressions
4841 //
4842 // C++20 [expr.const]p5:
4843 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
4844 // - a non-volatile glvalue that refers to an object that is usable
4845 // in constant expressions, or
4846 // - a non-volatile glvalue of literal type that refers to a
4847 // non-volatile object whose lifetime began within the evaluation
4848 // of E;
4849 //
4850 // C++11 misses the 'began within the evaluation of e' check and
4851 // instead allows all temporaries, including things like:
4852 // int &&r = 1;
4853 // int x = ++r;
4854 // constexpr int k = r;
4855 // Therefore we use the C++14-onwards rules in C++11 too.
4856 //
4857 // Note that temporaries whose lifetimes began while evaluating a
4858 // variable's constructor are not usable while evaluating the
4859 // corresponding destructor, not even if they're of const-qualified
4860 // types.
4861 if (!MTE->isUsableInConstantExpressions(Info.Ctx) &&
4862 !lifetimeStartedInEvaluation(Info, LVal.Base)) {
4863 if (!IsAccess)
4864 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4865 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
4866 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
4867 return CompleteObject();
4868 }
4869
4870 BaseVal = MTE->getOrCreateValue(false);
4871 assert(BaseVal && "got reference to unevaluated temporary");
4872 } else if (const CompoundLiteralExpr *CLE =
4873 dyn_cast_or_null<CompoundLiteralExpr>(Base)) {
4874 // According to GCC info page:
4875 //
4876 // 6.28 Compound Literals
4877 //
4878 // As an optimization, G++ sometimes gives array compound literals
4879 // longer lifetimes: when the array either appears outside a function or
4880 // has a const-qualified type. If foo and its initializer had elements
4881 // of type char *const rather than char *, or if foo were a global
4882 // variable, the array would have static storage duration. But it is
4883 // probably safest just to avoid the use of array compound literals in
4884 // C++ code.
4885 //
4886 // Obey that rule by checking constness for converted array types.
4887 if (QualType CLETy = CLE->getType(); CLETy->isArrayType() &&
4888 !LValType->isArrayType() &&
4889 !CLETy.isConstant(Info.Ctx)) {
4890 Info.FFDiag(E);
4891 Info.Note(CLE->getExprLoc(), diag::note_declared_at);
4892 return CompleteObject();
4893 }
4894
4895 BaseVal = &CLE->getStaticValue();
4896 } else {
4897 if (!IsAccess)
4898 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4899 APValue Val;
4900 LVal.moveInto(Val);
4901 Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
4902 << AK
4903 << Val.getAsString(Info.Ctx,
4904 Info.Ctx.getLValueReferenceType(LValType));
4905 NoteLValueLocation(Info, LVal.Base);
4906 return CompleteObject();
4907 }
4908 } else if (AK != clang::AK_Dereference) {
4909 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
4910 assert(BaseVal && "missing value for temporary");
4911 }
4912 }
4913
4914 // In C++14, we can't safely access any mutable state when we might be
4915 // evaluating after an unmodeled side effect. Parameters are modeled as state
4916 // in the caller, but aren't visible once the call returns, so they can be
4917 // modified in a speculatively-evaluated call.
4918 //
4919 // FIXME: Not all local state is mutable. Allow local constant subobjects
4920 // to be read here (but take care with 'mutable' fields).
4921 unsigned VisibleDepth = Depth;
4922 if (llvm::isa_and_nonnull<ParmVarDecl>(
4923 LVal.Base.dyn_cast<const ValueDecl *>()))
4924 ++VisibleDepth;
4925 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
4926 Info.EvalStatus.HasSideEffects) ||
4927 (isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth))
4928 return CompleteObject();
4929
4930 return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
4931}
4932
4933/// Perform an lvalue-to-rvalue conversion on the given glvalue. This
4934/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
4935/// glvalue referred to by an entity of reference type.
4936///
4937/// \param Info - Information about the ongoing evaluation.
4938/// \param Conv - The expression for which we are performing the conversion.
4939/// Used for diagnostics.
4940/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
4941/// case of a non-class type).
4942/// \param LVal - The glvalue on which we are attempting to perform this action.
4943/// \param RVal - The produced value will be placed here.
4944/// \param WantObjectRepresentation - If true, we're looking for the object
4945/// representation rather than the value, and in particular,
4946/// there is no requirement that the result be fully initialized.
4947static bool
4949 const LValue &LVal, APValue &RVal,
4950 bool WantObjectRepresentation = false) {
4951 if (LVal.Designator.Invalid)
4952 return false;
4953
4954 // Check for special cases where there is no existing APValue to look at.
4955 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4956
4957 AccessKinds AK =
4958 WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;
4959
4960 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
4962 // Special-case character extraction so we don't have to construct an
4963 // APValue for the whole string.
4964 assert(LVal.Designator.Entries.size() <= 1 &&
4965 "Can only read characters from string literals");
4966 if (LVal.Designator.Entries.empty()) {
4967 // Fail for now for LValue to RValue conversion of an array.
4968 // (This shouldn't show up in C/C++, but it could be triggered by a
4969 // weird EvaluateAsRValue call from a tool.)
4970 Info.FFDiag(Conv);
4971 return false;
4972 }
4973 if (LVal.Designator.isOnePastTheEnd()) {
4974 if (Info.getLangOpts().CPlusPlus11)
4975 Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
4976 else
4977 Info.FFDiag(Conv);
4978 return false;
4979 }
4980 uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
4981 RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
4982 return true;
4983 }
4984 }
4985
4986 CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
4987 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
4988}
4989
4990static bool hlslElementwiseCastHelper(EvalInfo &Info, const Expr *E,
4991 QualType DestTy,
4992 SmallVectorImpl<APValue> &SrcVals,
4993 SmallVectorImpl<QualType> &SrcTypes) {
4994 APValue Val;
4995 if (!Evaluate(Val, Info, E))
4996 return false;
4997
4998 // must be dealing with a record
4999 if (Val.isLValue()) {
5000 LValue LVal;
5001 LVal.setFrom(Info.Ctx, Val);
5002 if (!handleLValueToRValueConversion(Info, E, E->getType(), LVal, Val))
5003 return false;
5004 }
5005
5006 unsigned NEls = elementwiseSize(Info, DestTy);
5007 // flatten the source
5008 if (!flattenAPValue(Info, E, Val, E->getType(), SrcVals, SrcTypes, NEls))
5009 return false;
5010
5011 return true;
5012}
5013
5014/// Perform an assignment of Val to LVal. Takes ownership of Val.
5015static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
5016 QualType LValType, APValue &Val) {
5017 if (LVal.Designator.Invalid)
5018 return false;
5019
5020 if (!Info.getLangOpts().CPlusPlus14) {
5021 Info.FFDiag(E);
5022 return false;
5023 }
5024
5025 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
5026 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
5027}
5028
5029namespace {
5030struct CompoundAssignSubobjectHandler {
5031 EvalInfo &Info;
5032 const CompoundAssignOperator *E;
5033 QualType PromotedLHSType;
5035 const APValue &RHS;
5036
5037 static const AccessKinds AccessKind = AK_Assign;
5038
5039 typedef bool result_type;
5040
5041 bool checkConst(QualType QT) {
5042 // Assigning to a const object has undefined behavior.
5043 if (QT.isConstQualified()) {
5044 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
5045 return false;
5046 }
5047 return true;
5048 }
5049
5050 bool failed() { return false; }
5051 bool found(APValue &Subobj, QualType SubobjType, APValue::LValueBase Base) {
5052 switch (Subobj.getKind()) {
5053 case APValue::Int:
5054 return found(Subobj.getInt(), SubobjType);
5055 case APValue::Float:
5056 return found(Subobj.getFloat(), SubobjType);
5059 // FIXME: Implement complex compound assignment.
5060 Info.FFDiag(E);
5061 return false;
5062 case APValue::LValue:
5063 return foundPointer(Subobj, SubobjType);
5064 case APValue::Vector:
5065 return foundVector(Subobj, SubobjType);
5067 Info.FFDiag(E, diag::note_constexpr_access_uninit)
5068 << /*read of=*/0 << /*uninitialized object=*/1
5069 << E->getLHS()->getSourceRange();
5070 NoteLValueLocation(Info, Base);
5071 return false;
5072 default:
5073 // FIXME: can this happen?
5074 Info.FFDiag(E);
5075 return false;
5076 }
5077 }
5078
5079 bool foundVector(APValue &Value, QualType SubobjType) {
5080 if (!checkConst(SubobjType))
5081 return false;
5082
5083 if (!SubobjType->isVectorType()) {
5084 Info.FFDiag(E);
5085 return false;
5086 }
5087 return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS);
5088 }
5089
5090 bool found(APSInt &Value, QualType SubobjType) {
5091 if (!checkConst(SubobjType))
5092 return false;
5093
5094 if (!SubobjType->isIntegerType()) {
5095 // We don't support compound assignment on integer-cast-to-pointer
5096 // values.
5097 Info.FFDiag(E);
5098 return false;
5099 }
5100
5101 if (RHS.isInt()) {
5102 APSInt LHS =
5103 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
5104 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
5105 return false;
5106 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
5107 return true;
5108 } else if (RHS.isFloat()) {
5109 const FPOptions FPO = E->getFPFeaturesInEffect(
5110 Info.Ctx.getLangOpts());
5111 APFloat FValue(0.0);
5112 return HandleIntToFloatCast(Info, E, FPO, SubobjType, Value,
5113 PromotedLHSType, FValue) &&
5114 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
5115 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
5116 Value);
5117 }
5118
5119 Info.FFDiag(E);
5120 return false;
5121 }
5122 bool found(APFloat &Value, QualType SubobjType) {
5123 return checkConst(SubobjType) &&
5124 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
5125 Value) &&
5126 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
5127 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
5128 }
5129 bool foundPointer(APValue &Subobj, QualType SubobjType) {
5130 if (!checkConst(SubobjType))
5131 return false;
5132
5133 QualType PointeeType;
5134 if (const PointerType *PT = SubobjType->getAs<PointerType>())
5135 PointeeType = PT->getPointeeType();
5136
5137 if (PointeeType.isNull() || !RHS.isInt() ||
5138 (Opcode != BO_Add && Opcode != BO_Sub)) {
5139 Info.FFDiag(E);
5140 return false;
5141 }
5142
5143 APSInt Offset = RHS.getInt();
5144 if (Opcode == BO_Sub)
5145 negateAsSigned(Offset);
5146
5147 LValue LVal;
5148 LVal.setFrom(Info.Ctx, Subobj);
5149 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
5150 return false;
5151 LVal.moveInto(Subobj);
5152 return true;
5153 }
5154};
5155} // end anonymous namespace
5156
5157const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
5158
5159/// Perform a compound assignment of LVal <op>= RVal.
5160static bool handleCompoundAssignment(EvalInfo &Info,
5161 const CompoundAssignOperator *E,
5162 const LValue &LVal, QualType LValType,
5163 QualType PromotedLValType,
5164 BinaryOperatorKind Opcode,
5165 const APValue &RVal) {
5166 if (LVal.Designator.Invalid)
5167 return false;
5168
5169 if (!Info.getLangOpts().CPlusPlus14) {
5170 Info.FFDiag(E);
5171 return false;
5172 }
5173
5174 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
5175 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
5176 RVal };
5177 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
5178}
5179
5180namespace {
5181struct IncDecSubobjectHandler {
5182 EvalInfo &Info;
5183 const UnaryOperator *E;
5185 APValue *Old;
5186
5187 typedef bool result_type;
5188
5189 bool checkConst(QualType QT) {
5190 // Assigning to a const object has undefined behavior.
5191 if (QT.isConstQualified()) {
5192 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
5193 return false;
5194 }
5195 return true;
5196 }
5197
5198 bool failed() { return false; }
5199 bool found(APValue &Subobj, QualType SubobjType, APValue::LValueBase Base) {
5200 // Stash the old value. Also clear Old, so we don't clobber it later
5201 // if we're post-incrementing a complex.
5202 if (Old) {
5203 *Old = Subobj;
5204 Old = nullptr;
5205 }
5206
5207 switch (Subobj.getKind()) {
5208 case APValue::Int:
5209 return found(Subobj.getInt(), SubobjType);
5210 case APValue::Float:
5211 return found(Subobj.getFloat(), SubobjType);
5213 return found(Subobj.getComplexIntReal(),
5214 SubobjType->castAs<ComplexType>()->getElementType()
5215 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
5217 return found(Subobj.getComplexFloatReal(),
5218 SubobjType->castAs<ComplexType>()->getElementType()
5219 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
5220 case APValue::LValue:
5221 return foundPointer(Subobj, SubobjType);
5222 default:
5223 // FIXME: can this happen?
5224 Info.FFDiag(E);
5225 return false;
5226 }
5227 }
5228 bool found(APSInt &Value, QualType SubobjType) {
5229 if (!checkConst(SubobjType))
5230 return false;
5231
5232 if (!SubobjType->isIntegerType()) {
5233 // We don't support increment / decrement on integer-cast-to-pointer
5234 // values.
5235 Info.FFDiag(E);
5236 return false;
5237 }
5238
5239 if (Old) *Old = APValue(Value);
5240
5241 // bool arithmetic promotes to int, and the conversion back to bool
5242 // doesn't reduce mod 2^n, so special-case it.
5243 if (SubobjType->isBooleanType()) {
5244 if (AccessKind == AK_Increment)
5245 Value = 1;
5246 else
5247 Value = !Value;
5248 return true;
5249 }
5250
5251 bool WasNegative = Value.isNegative();
5252 if (AccessKind == AK_Increment) {
5253 ++Value;
5254
5255 if (!WasNegative && Value.isNegative() && E->canOverflow() &&
5256 !SubobjType.isWrapType()) {
5257 APSInt ActualValue(Value, /*IsUnsigned*/true);
5258 return HandleOverflow(Info, E, ActualValue, SubobjType);
5259 }
5260 } else {
5261 --Value;
5262
5263 if (WasNegative && !Value.isNegative() && E->canOverflow() &&
5264 !SubobjType.isWrapType()) {
5265 unsigned BitWidth = Value.getBitWidth();
5266 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
5267 ActualValue.setBit(BitWidth);
5268 return HandleOverflow(Info, E, ActualValue, SubobjType);
5269 }
5270 }
5271 return true;
5272 }
5273 bool found(APFloat &Value, QualType SubobjType) {
5274 if (!checkConst(SubobjType))
5275 return false;
5276
5277 if (Old) *Old = APValue(Value);
5278
5279 APFloat One(Value.getSemantics(), 1);
5280 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
5281 APFloat::opStatus St;
5282 if (AccessKind == AK_Increment)
5283 St = Value.add(One, RM);
5284 else
5285 St = Value.subtract(One, RM);
5287 }
5288 bool foundPointer(APValue &Subobj, QualType SubobjType) {
5289 if (!checkConst(SubobjType))
5290 return false;
5291
5292 QualType PointeeType;
5293 if (const PointerType *PT = SubobjType->getAs<PointerType>())
5294 PointeeType = PT->getPointeeType();
5295 else {
5296 Info.FFDiag(E);
5297 return false;
5298 }
5299
5300 LValue LVal;
5301 LVal.setFrom(Info.Ctx, Subobj);
5302 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
5303 AccessKind == AK_Increment ? 1 : -1))
5304 return false;
5305 LVal.moveInto(Subobj);
5306 return true;
5307 }
5308};
5309} // end anonymous namespace
5310
5311/// Perform an increment or decrement on LVal.
5312static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
5313 QualType LValType, bool IsIncrement, APValue *Old) {
5314 if (LVal.Designator.Invalid)
5315 return false;
5316
5317 if (!Info.getLangOpts().CPlusPlus14) {
5318 Info.FFDiag(E);
5319 return false;
5320 }
5321
5322 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
5323 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
5324 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
5325 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
5326}
5327
5328/// Build an lvalue for the object argument of a member function call.
5329static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
5330 LValue &This) {
5331 if (Object->getType()->isPointerType() && Object->isPRValue())
5332 return EvaluatePointer(Object, This, Info);
5333
5334 if (Object->isGLValue())
5335 return EvaluateLValue(Object, This, Info);
5336
5337 if (Object->getType()->isLiteralType(Info.Ctx))
5338 return EvaluateTemporary(Object, This, Info);
5339
5340 if (Object->getType()->isRecordType() && Object->isPRValue())
5341 return EvaluateTemporary(Object, This, Info);
5342
5343 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
5344 return false;
5345}
5346
5347/// HandleMemberPointerAccess - Evaluate a member access operation and build an
5348/// lvalue referring to the result.
5349///
5350/// \param Info - Information about the ongoing evaluation.
5351/// \param LV - An lvalue referring to the base of the member pointer.
5352/// \param RHS - The member pointer expression.
5353/// \param IncludeMember - Specifies whether the member itself is included in
5354/// the resulting LValue subobject designator. This is not possible when
5355/// creating a bound member function.
5356/// \return The field or method declaration to which the member pointer refers,
5357/// or 0 if evaluation fails.
5358static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
5359 QualType LVType,
5360 LValue &LV,
5361 const Expr *RHS,
5362 bool IncludeMember = true) {
5363 MemberPtr MemPtr;
5364 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
5365 return nullptr;
5366
5367 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
5368 // member value, the behavior is undefined.
5369 if (!MemPtr.getDecl()) {
5370 // FIXME: Specific diagnostic.
5371 Info.FFDiag(RHS);
5372 return nullptr;
5373 }
5374
5375 if (MemPtr.isDerivedMember()) {
5376 // This is a member of some derived class. Truncate LV appropriately.
5377 // The end of the derived-to-base path for the base object must match the
5378 // derived-to-base path for the member pointer.
5379 // C++23 [expr.mptr.oper]p4:
5380 // If the result of E1 is an object [...] whose most derived object does
5381 // not contain the member to which E2 refers, the behavior is undefined.
5382 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
5383 LV.Designator.Entries.size()) {
5384 Info.FFDiag(RHS);
5385 return nullptr;
5386 }
5387 unsigned PathLengthToMember =
5388 LV.Designator.Entries.size() - MemPtr.Path.size();
5389 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
5390 const CXXRecordDecl *LVDecl = getAsBaseClass(
5391 LV.Designator.Entries[PathLengthToMember + I]);
5392 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
5393 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
5394 Info.FFDiag(RHS);
5395 return nullptr;
5396 }
5397 }
5398 // MemPtr.Path only contains the base classes of the class directly
5399 // containing the member E2. It is still necessary to check that the class
5400 // directly containing the member E2 lies on the derived-to-base path of E1
5401 // to avoid incorrectly permitting member pointer access into a sibling
5402 // class of the class containing the member E2. If this class would
5403 // correspond to the most-derived class of E1, it either isn't contained in
5404 // LV.Designator.Entries or the corresponding entry refers to an array
5405 // element instead. Therefore get the most derived class directly in this
5406 // case. Otherwise the previous entry should correpond to this class.
5407 const CXXRecordDecl *LastLVDecl =
5408 (PathLengthToMember > LV.Designator.MostDerivedPathLength)
5409 ? getAsBaseClass(LV.Designator.Entries[PathLengthToMember - 1])
5410 : LV.Designator.MostDerivedType->getAsCXXRecordDecl();
5411 const CXXRecordDecl *LastMPDecl = MemPtr.getContainingRecord();
5412 if (LastLVDecl->getCanonicalDecl() != LastMPDecl->getCanonicalDecl()) {
5413 Info.FFDiag(RHS);
5414 return nullptr;
5415 }
5416
5417 // Truncate the lvalue to the appropriate derived class.
5418 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
5419 PathLengthToMember))
5420 return nullptr;
5421 } else if (!MemPtr.Path.empty()) {
5422 // Extend the LValue path with the member pointer's path.
5423 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
5424 MemPtr.Path.size() + IncludeMember);
5425
5426 // Walk down to the appropriate base class.
5427 if (const PointerType *PT = LVType->getAs<PointerType>())
5428 LVType = PT->getPointeeType();
5429 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
5430 assert(RD && "member pointer access on non-class-type expression");
5431 // The first class in the path is that of the lvalue.
5432 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
5433 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
5434 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
5435 return nullptr;
5436 RD = Base;
5437 }
5438 // Finally cast to the class containing the member.
5439 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
5440 MemPtr.getContainingRecord()))
5441 return nullptr;
5442 }
5443
5444 // Add the member. Note that we cannot build bound member functions here.
5445 if (IncludeMember) {
5446 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
5447 if (!HandleLValueMember(Info, RHS, LV, FD))
5448 return nullptr;
5449 } else if (const IndirectFieldDecl *IFD =
5450 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
5451 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
5452 return nullptr;
5453 } else {
5454 llvm_unreachable("can't construct reference to bound member function");
5455 }
5456 }
5457
5458 return MemPtr.getDecl();
5459}
5460
5461static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
5462 const BinaryOperator *BO,
5463 LValue &LV,
5464 bool IncludeMember = true) {
5465 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
5466
5467 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
5468 if (Info.noteFailure()) {
5469 MemberPtr MemPtr;
5470 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
5471 }
5472 return nullptr;
5473 }
5474
5475 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
5476 BO->getRHS(), IncludeMember);
5477}
5478
5479/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
5480/// the provided lvalue, which currently refers to the base object.
5481static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
5482 LValue &Result) {
5483 SubobjectDesignator &D = Result.Designator;
5484 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
5485 return false;
5486
5487 QualType TargetQT = E->getType();
5488 if (const PointerType *PT = TargetQT->getAs<PointerType>())
5489 TargetQT = PT->getPointeeType();
5490
5491 auto InvalidCast = [&]() {
5492 if (!Info.checkingPotentialConstantExpression() ||
5493 !Result.AllowConstexprUnknown) {
5494 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
5495 << D.MostDerivedType << TargetQT;
5496 }
5497 return false;
5498 };
5499
5500 // Check this cast lands within the final derived-to-base subobject path.
5501 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size())
5502 return InvalidCast();
5503
5504 // Check the type of the final cast. We don't need to check the path,
5505 // since a cast can only be formed if the path is unique.
5506 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
5507 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
5508 const CXXRecordDecl *FinalType;
5509 if (NewEntriesSize == D.MostDerivedPathLength)
5510 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
5511 else
5512 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
5513 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl())
5514 return InvalidCast();
5515
5516 // Truncate the lvalue to the appropriate derived class.
5517 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
5518}
5519
5520/// Get the value to use for a default-initialized object of type T.
5521/// Return false if it encounters something invalid.
5523 bool IsCompleteClass = true) {
5524 bool Success = true;
5525
5526 // If there is already a value present don't overwrite it.
5527 if (!Result.isAbsent())
5528 return true;
5529
5530 if (auto *RD = T->getAsCXXRecordDecl()) {
5531 if (RD->isInvalidDecl()) {
5532 Result = APValue();
5533 return false;
5534 }
5535 if (RD->isUnion()) {
5536 Result = APValue((const FieldDecl *)nullptr);
5537 return true;
5538 }
5539
5540 // bases() includes directly specified virtual bases as well.
5541 unsigned NonVirtualBases = countNonVirtualBases(RD);
5542 Result =
5543 APValue(APValue::UninitStruct(), NonVirtualBases, RD->getNumFields(),
5544 IsCompleteClass ? RD->getNumVBases() : 0);
5545
5546 unsigned Index = 0;
5547 for (const CXXBaseSpecifier &B : RD->bases()) {
5548 if (B.isVirtual())
5549 continue;
5551 B.getType(), Result.getStructBase(Index), /*IsCompleteClass=*/false);
5552 ++Index;
5553 }
5554
5555 for (const auto *I : RD->fields()) {
5556 if (I->isUnnamedBitField())
5557 continue;
5559 I->getType(), Result.getStructField(I->getFieldIndex()));
5560 }
5561
5562 if (IsCompleteClass) {
5563 Index = 0;
5564
5565 for (const auto &B : RD->vbases()) {
5567 Result.getStructVirtualBase(Index),
5568 /*IsCompleteClass=*/false);
5569 ++Index;
5570 }
5571 } else {
5572 // Virtual bases should only exist at the top level of an APValue.
5573 assert(Result.getStructNumVirtualBases() == 0);
5574 }
5575
5576 return Success;
5577 }
5578
5579 if (auto *AT =
5580 dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
5581 Result = APValue(APValue::UninitArray(), 0, AT->getZExtSize());
5582 if (Result.hasArrayFiller())
5583 Success &=
5584 handleDefaultInitValue(AT->getElementType(), Result.getArrayFiller());
5585 return Success;
5586 }
5587
5589 return true;
5590}
5591
5592namespace {
5593enum EvalStmtResult {
5594 /// Evaluation failed.
5595 ESR_Failed,
5596 /// Hit a 'return' statement.
5597 ESR_Returned,
5598 /// Evaluation succeeded.
5599 ESR_Succeeded,
5600 /// Hit a 'continue' statement.
5601 ESR_Continue,
5602 /// Hit a 'break' statement.
5603 ESR_Break,
5604 /// Still scanning for 'case' or 'default' statement.
5605 ESR_CaseNotFound
5606};
5607}
5608/// Evaluates the initializer of a reference.
5609static bool EvaluateInitForDeclOfReferenceType(EvalInfo &Info,
5610 const ValueDecl *D,
5611 const Expr *Init, LValue &Result,
5612 APValue &Val) {
5613 assert(Init->isGLValue() && D->getType()->isReferenceType());
5614 // A reference is an lvalue.
5615 if (!EvaluateLValue(Init, Result, Info))
5616 return false;
5617 // [C++26][decl.ref]
5618 // The object designated by such a glvalue can be outside its lifetime
5619 // Because a null pointer value or a pointer past the end of an object
5620 // does not point to an object, a reference in a well-defined program cannot
5621 // refer to such things;
5622 if (!Result.Designator.Invalid && Result.Designator.isOnePastTheEnd()) {
5623 Info.FFDiag(Init, diag::note_constexpr_access_past_end) << AK_Dereference;
5624 return false;
5625 }
5626
5627 // Save the result.
5628 Result.moveInto(Val);
5629 return true;
5630}
5631
5632static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
5633 if (VD->isInvalidDecl())
5634 return false;
5635 // We don't need to evaluate the initializer for a static local.
5636 if (!VD->hasLocalStorage())
5637 return true;
5638
5639 LValue Result;
5640 APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(),
5641 ScopeKind::Block, Result);
5642
5643 const Expr *InitE = VD->getInit();
5644 if (!InitE) {
5645 if (VD->getType()->isDependentType())
5646 return Info.noteSideEffect();
5647 return handleDefaultInitValue(VD->getType(), Val);
5648 }
5649 if (InitE->isValueDependent())
5650 return false;
5651
5652 // For references to objects, check they do not designate a one-past-the-end
5653 // object.
5654 if (VD->getType()->isReferenceType()) {
5655 return EvaluateInitForDeclOfReferenceType(Info, VD, InitE, Result, Val);
5656 } else if (!EvaluateInPlace(Val, Info, Result, InitE)) {
5657 // Wipe out any partially-computed value, to allow tracking that this
5658 // evaluation failed.
5659 Val = APValue();
5660 return false;
5661 }
5662
5663 return true;
5664}
5665
5666static bool EvaluateDecompositionDeclInit(EvalInfo &Info,
5667 const DecompositionDecl *DD);
5668
5669static bool EvaluateDecl(EvalInfo &Info, const Decl *D,
5670 bool EvaluateConditionDecl = false) {
5671 bool OK = true;
5672 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
5673 OK &= EvaluateVarDecl(Info, VD);
5674
5675 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D);
5676 EvaluateConditionDecl && DD)
5677 OK &= EvaluateDecompositionDeclInit(Info, DD);
5678
5679 return OK;
5680}
5681
5682static bool EvaluateDecompositionDeclInit(EvalInfo &Info,
5683 const DecompositionDecl *DD) {
5684 bool OK = true;
5685 for (auto *BD : DD->flat_bindings())
5686 if (auto *VD = BD->getHoldingVar())
5687 OK &= EvaluateDecl(Info, VD, /*EvaluateConditionDecl=*/true);
5688
5689 return OK;
5690}
5691
5692static bool MaybeEvaluateDeferredVarDeclInit(EvalInfo &Info,
5693 const VarDecl *VD) {
5694 if (auto *DD = dyn_cast_if_present<DecompositionDecl>(VD)) {
5695 if (!EvaluateDecompositionDeclInit(Info, DD))
5696 return false;
5697 }
5698 return true;
5699}
5700
5701static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info) {
5702 assert(E->isValueDependent());
5703 if (Info.noteSideEffect())
5704 return true;
5705 assert(E->containsErrors() && "valid value-dependent expression should never "
5706 "reach invalid code path.");
5707 return false;
5708}
5709
5710/// Evaluate a condition (either a variable declaration or an expression).
5711static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
5712 const Expr *Cond, bool &Result) {
5713 if (Cond->isValueDependent())
5714 return false;
5715 FullExpressionRAII Scope(Info);
5716 if (CondDecl && !EvaluateDecl(Info, CondDecl))
5717 return false;
5718 if (!EvaluateAsBooleanCondition(Cond, Result, Info))
5719 return false;
5720 if (!MaybeEvaluateDeferredVarDeclInit(Info, CondDecl))
5721 return false;
5722 return Scope.destroy();
5723}
5724
5725namespace {
5726/// A location where the result (returned value) of evaluating a
5727/// statement should be stored.
5728struct StmtResult {
5729 /// The APValue that should be filled in with the returned value.
5730 APValue &Value;
5731 /// The location containing the result, if any (used to support RVO).
5732 const LValue *Slot;
5733};
5734
5735struct TempVersionRAII {
5736 CallStackFrame &Frame;
5737
5738 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
5739 Frame.pushTempVersion();
5740 }
5741
5742 ~TempVersionRAII() {
5743 Frame.popTempVersion();
5744 }
5745};
5746
5747}
5748
5749static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
5750 const Stmt *S,
5751 const SwitchCase *SC = nullptr);
5752
5753/// Helper to implement named break/continue. Returns 'true' if the evaluation
5754/// result should be propagated up. Otherwise, it sets the evaluation result
5755/// to either Continue to continue the current loop, or Succeeded to break it.
5756static bool ShouldPropagateBreakContinue(EvalInfo &Info,
5757 const Stmt *LoopOrSwitch,
5759 EvalStmtResult &ESR) {
5760 bool IsSwitch = isa<SwitchStmt>(LoopOrSwitch);
5761
5762 // For loops, map Succeeded to Continue so we don't have to check for both.
5763 if (!IsSwitch && ESR == ESR_Succeeded) {
5764 ESR = ESR_Continue;
5765 return false;
5766 }
5767
5768 if (ESR != ESR_Break && ESR != ESR_Continue)
5769 return false;
5770
5771 // Are we breaking out of or continuing this statement?
5772 bool CanBreakOrContinue = !IsSwitch || ESR == ESR_Break;
5773 const Stmt *StackTop = Info.BreakContinueStack.back();
5774 if (CanBreakOrContinue && (StackTop == nullptr || StackTop == LoopOrSwitch)) {
5775 Info.BreakContinueStack.pop_back();
5776 if (ESR == ESR_Break)
5777 ESR = ESR_Succeeded;
5778 return false;
5779 }
5780
5781 // We're not. Propagate the result up.
5782 for (BlockScopeRAII *S : Scopes) {
5783 if (!S->destroy()) {
5784 ESR = ESR_Failed;
5785 break;
5786 }
5787 }
5788 return true;
5789}
5790
5791/// Evaluate the body of a loop, and translate the result as appropriate.
5792static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
5793 const Stmt *Body,
5794 const SwitchCase *Case = nullptr) {
5795 BlockScopeRAII Scope(Info);
5796
5797 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case);
5798 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
5799 ESR = ESR_Failed;
5800
5801 return ESR;
5802}
5803
5804/// Evaluate a switch statement.
5805static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
5806 const SwitchStmt *SS) {
5807 BlockScopeRAII Scope(Info);
5808
5809 // Evaluate the switch condition.
5810 APSInt Value;
5811 {
5812 if (const Stmt *Init = SS->getInit()) {
5813 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
5814 if (ESR != ESR_Succeeded) {
5815 if (ESR != ESR_Failed && !Scope.destroy())
5816 ESR = ESR_Failed;
5817 return ESR;
5818 }
5819 }
5820
5821 FullExpressionRAII CondScope(Info);
5822 if (SS->getConditionVariable() &&
5823 !EvaluateDecl(Info, SS->getConditionVariable()))
5824 return ESR_Failed;
5825 if (SS->getCond()->isValueDependent()) {
5826 // We don't know what the value is, and which branch should jump to.
5827 EvaluateDependentExpr(SS->getCond(), Info);
5828 return ESR_Failed;
5829 }
5830 if (!EvaluateInteger(SS->getCond(), Value, Info))
5831 return ESR_Failed;
5832
5834 return ESR_Failed;
5835
5836 if (!CondScope.destroy())
5837 return ESR_Failed;
5838 }
5839
5840 // Find the switch case corresponding to the value of the condition.
5841 // FIXME: Cache this lookup.
5842 const SwitchCase *Found = nullptr;
5843 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
5844 SC = SC->getNextSwitchCase()) {
5845 if (isa<DefaultStmt>(SC)) {
5846 Found = SC;
5847 continue;
5848 }
5849
5850 const CaseStmt *CS = cast<CaseStmt>(SC);
5851 const Expr *LHS = CS->getLHS();
5852 const Expr *RHS = CS->getRHS();
5853 if (LHS->isValueDependent() || (RHS && RHS->isValueDependent()))
5854 return ESR_Failed;
5855 APSInt LHSValue = LHS->EvaluateKnownConstInt(Info.Ctx);
5856 APSInt RHSValue = RHS ? RHS->EvaluateKnownConstInt(Info.Ctx) : LHSValue;
5857 if (LHSValue <= Value && Value <= RHSValue) {
5858 Found = SC;
5859 break;
5860 }
5861 }
5862
5863 if (!Found)
5864 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5865
5866 // Search the switch body for the switch case and evaluate it from there.
5867 EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found);
5868 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
5869 return ESR_Failed;
5870 if (ShouldPropagateBreakContinue(Info, SS, /*Scopes=*/{}, ESR))
5871 return ESR;
5872
5873 switch (ESR) {
5874 case ESR_Break:
5875 llvm_unreachable("Should have been converted to Succeeded");
5876 case ESR_Succeeded:
5877 case ESR_Continue:
5878 case ESR_Failed:
5879 case ESR_Returned:
5880 return ESR;
5881 case ESR_CaseNotFound:
5882 // This can only happen if the switch case is nested within a statement
5883 // expression. We have no intention of supporting that.
5884 Info.FFDiag(Found->getBeginLoc(),
5885 diag::note_constexpr_stmt_expr_unsupported);
5886 return ESR_Failed;
5887 }
5888 llvm_unreachable("Invalid EvalStmtResult!");
5889}
5890
5891static bool CheckLocalVariableDeclaration(EvalInfo &Info, const VarDecl *VD) {
5892 // An expression E is a core constant expression unless the evaluation of E
5893 // would evaluate one of the following: [C++23] - a control flow that passes
5894 // through a declaration of a variable with static or thread storage duration
5895 // unless that variable is usable in constant expressions.
5896 if (VD->isLocalVarDecl() && VD->isStaticLocal() &&
5897 !VD->isUsableInConstantExpressions(Info.Ctx)) {
5898 Info.CCEDiag(VD->getLocation(), diag::note_constexpr_static_local)
5899 << (VD->getTSCSpec() == TSCS_unspecified ? 0 : 1) << VD;
5900 return false;
5901 }
5902 return true;
5903}
5904
5905// Evaluate a statement.
5906static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
5907 const Stmt *S, const SwitchCase *Case) {
5908 if (!Info.nextStep(S))
5909 return ESR_Failed;
5910
5911 // If we're hunting down a 'case' or 'default' label, recurse through
5912 // substatements until we hit the label.
5913 if (Case) {
5914 switch (S->getStmtClass()) {
5915 case Stmt::CompoundStmtClass:
5916 // FIXME: Precompute which substatement of a compound statement we
5917 // would jump to, and go straight there rather than performing a
5918 // linear scan each time.
5919 case Stmt::LabelStmtClass:
5920 case Stmt::AttributedStmtClass:
5921 case Stmt::DoStmtClass:
5922 break;
5923
5924 case Stmt::CaseStmtClass:
5925 case Stmt::DefaultStmtClass:
5926 if (Case == S)
5927 Case = nullptr;
5928 break;
5929
5930 case Stmt::IfStmtClass: {
5931 // FIXME: Precompute which side of an 'if' we would jump to, and go
5932 // straight there rather than scanning both sides.
5933 const IfStmt *IS = cast<IfStmt>(S);
5934
5935 // Wrap the evaluation in a block scope, in case it's a DeclStmt
5936 // preceded by our switch label.
5937 BlockScopeRAII Scope(Info);
5938
5939 // Step into the init statement in case it brings an (uninitialized)
5940 // variable into scope.
5941 if (const Stmt *Init = IS->getInit()) {
5942 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5943 if (ESR != ESR_CaseNotFound) {
5944 assert(ESR != ESR_Succeeded);
5945 return ESR;
5946 }
5947 }
5948
5949 // Condition variable must be initialized if it exists.
5950 // FIXME: We can skip evaluating the body if there's a condition
5951 // variable, as there can't be any case labels within it.
5952 // (The same is true for 'for' statements.)
5953
5954 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
5955 if (ESR == ESR_Failed)
5956 return ESR;
5957 if (ESR != ESR_CaseNotFound)
5958 return Scope.destroy() ? ESR : ESR_Failed;
5959 if (!IS->getElse())
5960 return ESR_CaseNotFound;
5961
5962 ESR = EvaluateStmt(Result, Info, IS->getElse(), Case);
5963 if (ESR == ESR_Failed)
5964 return ESR;
5965 if (ESR != ESR_CaseNotFound)
5966 return Scope.destroy() ? ESR : ESR_Failed;
5967 return ESR_CaseNotFound;
5968 }
5969
5970 case Stmt::WhileStmtClass: {
5971 EvalStmtResult ESR =
5972 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
5973 if (ShouldPropagateBreakContinue(Info, S, /*Scopes=*/{}, ESR))
5974 return ESR;
5975 if (ESR != ESR_Continue)
5976 return ESR;
5977 break;
5978 }
5979
5980 case Stmt::ForStmtClass: {
5981 const ForStmt *FS = cast<ForStmt>(S);
5982 BlockScopeRAII Scope(Info);
5983
5984 // Step into the init statement in case it brings an (uninitialized)
5985 // variable into scope.
5986 if (const Stmt *Init = FS->getInit()) {
5987 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5988 if (ESR != ESR_CaseNotFound) {
5989 assert(ESR != ESR_Succeeded);
5990 return ESR;
5991 }
5992 }
5993
5994 EvalStmtResult ESR =
5995 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
5996 if (ShouldPropagateBreakContinue(Info, FS, /*Scopes=*/{}, ESR))
5997 return ESR;
5998 if (ESR != ESR_Continue)
5999 return ESR;
6000 if (const auto *Inc = FS->getInc()) {
6001 if (Inc->isValueDependent()) {
6002 if (!EvaluateDependentExpr(Inc, Info))
6003 return ESR_Failed;
6004 } else {
6005 FullExpressionRAII IncScope(Info);
6006 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
6007 return ESR_Failed;
6008 }
6009 }
6010 break;
6011 }
6012
6013 case Stmt::DeclStmtClass: {
6014 // Start the lifetime of any uninitialized variables we encounter. They
6015 // might be used by the selected branch of the switch.
6016 const DeclStmt *DS = cast<DeclStmt>(S);
6017 for (const auto *D : DS->decls()) {
6018 if (const auto *VD = dyn_cast<VarDecl>(D)) {
6019 if (!CheckLocalVariableDeclaration(Info, VD))
6020 return ESR_Failed;
6021 if (VD->hasLocalStorage() && !VD->getInit())
6022 if (!EvaluateVarDecl(Info, VD))
6023 return ESR_Failed;
6024 // FIXME: If the variable has initialization that can't be jumped
6025 // over, bail out of any immediately-surrounding compound-statement
6026 // too. There can't be any case labels here.
6027 }
6028 }
6029 return ESR_CaseNotFound;
6030 }
6031
6032 default:
6033 return ESR_CaseNotFound;
6034 }
6035 }
6036
6037 switch (S->getStmtClass()) {
6038 default:
6039 if (const Expr *E = dyn_cast<Expr>(S)) {
6040 if (E->isValueDependent()) {
6041 if (!EvaluateDependentExpr(E, Info))
6042 return ESR_Failed;
6043 } else {
6044 // Don't bother evaluating beyond an expression-statement which couldn't
6045 // be evaluated.
6046 // FIXME: Do we need the FullExpressionRAII object here?
6047 // VisitExprWithCleanups should create one when necessary.
6048 FullExpressionRAII Scope(Info);
6049 if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy())
6050 return ESR_Failed;
6051 }
6052 return ESR_Succeeded;
6053 }
6054
6055 Info.FFDiag(S->getBeginLoc()) << S->getSourceRange();
6056 return ESR_Failed;
6057
6058 case Stmt::NullStmtClass:
6059 return ESR_Succeeded;
6060
6061 case Stmt::DeclStmtClass: {
6062 const DeclStmt *DS = cast<DeclStmt>(S);
6063 for (const auto *D : DS->decls()) {
6064 const VarDecl *VD = dyn_cast_or_null<VarDecl>(D);
6065 if (VD && !CheckLocalVariableDeclaration(Info, VD))
6066 return ESR_Failed;
6067
6068 if (const auto *ESD = dyn_cast<CXXExpansionStmtDecl>(D)) {
6069 assert(ESD->getInstantiations() && "not expanded?");
6070 return EvaluateStmt(Result, Info, ESD->getInstantiations(), Case);
6071 }
6072
6073 // Each declaration initialization is its own full-expression.
6074 FullExpressionRAII Scope(Info);
6075 if (!EvaluateDecl(Info, D, /*EvaluateConditionDecl=*/true) &&
6076 !Info.noteFailure())
6077 return ESR_Failed;
6078 if (!Scope.destroy())
6079 return ESR_Failed;
6080 }
6081 return ESR_Succeeded;
6082 }
6083
6084 case Stmt::ReturnStmtClass: {
6085 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
6086 FullExpressionRAII Scope(Info);
6087 if (RetExpr && RetExpr->isValueDependent()) {
6088 EvaluateDependentExpr(RetExpr, Info);
6089 // We know we returned, but we don't know what the value is.
6090 return ESR_Failed;
6091 }
6092 if (RetExpr &&
6093 !(Result.Slot
6094 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
6095 : Evaluate(Result.Value, Info, RetExpr)))
6096 return ESR_Failed;
6097 return Scope.destroy() ? ESR_Returned : ESR_Failed;
6098 }
6099
6100 case Stmt::CompoundStmtClass: {
6101 BlockScopeRAII Scope(Info);
6102
6103 const CompoundStmt *CS = cast<CompoundStmt>(S);
6104 for (const auto *BI : CS->body()) {
6105 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
6106 if (ESR == ESR_Succeeded)
6107 Case = nullptr;
6108 else if (ESR != ESR_CaseNotFound) {
6109 if (ESR != ESR_Failed && !Scope.destroy())
6110 return ESR_Failed;
6111 return ESR;
6112 }
6113 }
6114 if (Case)
6115 return ESR_CaseNotFound;
6116 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
6117 }
6118
6119 case Stmt::IfStmtClass: {
6120 const IfStmt *IS = cast<IfStmt>(S);
6121
6122 // Evaluate the condition, as either a var decl or as an expression.
6123 BlockScopeRAII Scope(Info);
6124 if (const Stmt *Init = IS->getInit()) {
6125 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
6126 if (ESR != ESR_Succeeded) {
6127 if (ESR != ESR_Failed && !Scope.destroy())
6128 return ESR_Failed;
6129 return ESR;
6130 }
6131 }
6132 bool Cond;
6133 if (IS->isConsteval()) {
6134 Cond = IS->isNonNegatedConsteval();
6135 // If we are not in a constant context, if consteval should not evaluate
6136 // to true.
6137 if (!Info.InConstantContext)
6138 Cond = !Cond;
6139 } else if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(),
6140 Cond))
6141 return ESR_Failed;
6142
6143 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
6144 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
6145 if (ESR != ESR_Succeeded) {
6146 if (ESR != ESR_Failed && !Scope.destroy())
6147 return ESR_Failed;
6148 return ESR;
6149 }
6150 }
6151 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
6152 }
6153
6154 case Stmt::WhileStmtClass: {
6155 const WhileStmt *WS = cast<WhileStmt>(S);
6156 while (true) {
6157 BlockScopeRAII Scope(Info);
6158 bool Continue;
6159 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
6160 Continue))
6161 return ESR_Failed;
6162 if (!Continue)
6163 break;
6164
6165 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
6166 if (ShouldPropagateBreakContinue(Info, WS, &Scope, ESR))
6167 return ESR;
6168
6169 if (ESR != ESR_Continue) {
6170 if (ESR != ESR_Failed && !Scope.destroy())
6171 return ESR_Failed;
6172 return ESR;
6173 }
6174 if (!Scope.destroy())
6175 return ESR_Failed;
6176 }
6177 return ESR_Succeeded;
6178 }
6179
6180 case Stmt::DoStmtClass: {
6181 const DoStmt *DS = cast<DoStmt>(S);
6182 bool Continue;
6183 do {
6184 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
6185 if (ShouldPropagateBreakContinue(Info, DS, /*Scopes=*/{}, ESR))
6186 return ESR;
6187 if (ESR != ESR_Continue)
6188 return ESR;
6189 Case = nullptr;
6190
6191 if (DS->getCond()->isValueDependent()) {
6192 EvaluateDependentExpr(DS->getCond(), Info);
6193 // Bailout as we don't know whether to keep going or terminate the loop.
6194 return ESR_Failed;
6195 }
6196 FullExpressionRAII CondScope(Info);
6197 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) ||
6198 !CondScope.destroy())
6199 return ESR_Failed;
6200 } while (Continue);
6201 return ESR_Succeeded;
6202 }
6203
6204 case Stmt::ForStmtClass: {
6205 const ForStmt *FS = cast<ForStmt>(S);
6206 BlockScopeRAII ForScope(Info);
6207 if (FS->getInit()) {
6208 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
6209 if (ESR != ESR_Succeeded) {
6210 if (ESR != ESR_Failed && !ForScope.destroy())
6211 return ESR_Failed;
6212 return ESR;
6213 }
6214 }
6215 while (true) {
6216 BlockScopeRAII IterScope(Info);
6217 bool Continue = true;
6218 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
6219 FS->getCond(), Continue))
6220 return ESR_Failed;
6221
6222 if (!Continue) {
6223 if (!IterScope.destroy())
6224 return ESR_Failed;
6225 break;
6226 }
6227
6228 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
6229 if (ShouldPropagateBreakContinue(Info, FS, {&IterScope, &ForScope}, ESR))
6230 return ESR;
6231 if (ESR != ESR_Continue) {
6232 if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))
6233 return ESR_Failed;
6234 return ESR;
6235 }
6236
6237 if (const auto *Inc = FS->getInc()) {
6238 if (Inc->isValueDependent()) {
6239 if (!EvaluateDependentExpr(Inc, Info))
6240 return ESR_Failed;
6241 } else {
6242 FullExpressionRAII IncScope(Info);
6243 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
6244 return ESR_Failed;
6245 }
6246 }
6247
6248 if (!IterScope.destroy())
6249 return ESR_Failed;
6250 }
6251 return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;
6252 }
6253
6254 case Stmt::CXXForRangeStmtClass: {
6256 BlockScopeRAII Scope(Info);
6257
6258 // Evaluate the init-statement if present.
6259 if (FS->getInit()) {
6260 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
6261 if (ESR != ESR_Succeeded) {
6262 if (ESR != ESR_Failed && !Scope.destroy())
6263 return ESR_Failed;
6264 return ESR;
6265 }
6266 }
6267
6268 // Initialize the __range variable.
6269 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
6270 if (ESR != ESR_Succeeded) {
6271 if (ESR != ESR_Failed && !Scope.destroy())
6272 return ESR_Failed;
6273 return ESR;
6274 }
6275
6276 // In error-recovery cases it's possible to get here even if we failed to
6277 // synthesize the __begin and __end variables.
6278 if (!FS->getBeginStmt() || !FS->getEndStmt() || !FS->getCond())
6279 return ESR_Failed;
6280
6281 // Create the __begin and __end iterators.
6282 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
6283 if (ESR != ESR_Succeeded) {
6284 if (ESR != ESR_Failed && !Scope.destroy())
6285 return ESR_Failed;
6286 return ESR;
6287 }
6288 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
6289 if (ESR != ESR_Succeeded) {
6290 if (ESR != ESR_Failed && !Scope.destroy())
6291 return ESR_Failed;
6292 return ESR;
6293 }
6294
6295 while (true) {
6296 // Condition: __begin != __end.
6297 {
6298 if (FS->getCond()->isValueDependent()) {
6299 EvaluateDependentExpr(FS->getCond(), Info);
6300 // We don't know whether to keep going or terminate the loop.
6301 return ESR_Failed;
6302 }
6303 bool Continue = true;
6304 FullExpressionRAII CondExpr(Info);
6305 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
6306 return ESR_Failed;
6307 if (!Continue)
6308 break;
6309 }
6310
6311 // User's variable declaration, initialized by *__begin.
6312 BlockScopeRAII InnerScope(Info);
6313 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
6314 if (ESR != ESR_Succeeded) {
6315 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
6316 return ESR_Failed;
6317 return ESR;
6318 }
6319
6320 // Loop body.
6321 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
6322 if (ShouldPropagateBreakContinue(Info, FS, {&InnerScope, &Scope}, ESR))
6323 return ESR;
6324 if (ESR != ESR_Continue) {
6325 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
6326 return ESR_Failed;
6327 return ESR;
6328 }
6329 if (FS->getInc()->isValueDependent()) {
6330 if (!EvaluateDependentExpr(FS->getInc(), Info))
6331 return ESR_Failed;
6332 } else {
6333 // Increment: ++__begin
6334 if (!EvaluateIgnoredValue(Info, FS->getInc()))
6335 return ESR_Failed;
6336 }
6337
6338 if (!InnerScope.destroy())
6339 return ESR_Failed;
6340 }
6341
6342 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
6343 }
6344
6345 case Stmt::CXXExpansionStmtInstantiationClass: {
6346 BlockScopeRAII Scope(Info);
6347 const auto *Expansion = cast<CXXExpansionStmtInstantiation>(S);
6348 for (const Stmt *PreambleStmt : Expansion->getPreambleStmts()) {
6349 EvalStmtResult ESR = EvaluateStmt(Result, Info, PreambleStmt);
6350 if (ESR != ESR_Succeeded) {
6351 if (ESR != ESR_Failed && !Scope.destroy())
6352 return ESR_Failed;
6353 return ESR;
6354 }
6355 }
6356
6357 // No need to push an extra scope for these since they're already
6358 // CompoundStmts.
6359 EvalStmtResult ESR = ESR_Succeeded;
6360 for (const Stmt *Instantiation : Expansion->getInstantiations()) {
6361 ESR = EvaluateStmt(Result, Info, Instantiation);
6362 if (ESR == ESR_Failed ||
6363 ShouldPropagateBreakContinue(Info, Expansion, &Scope, ESR))
6364 return ESR;
6365 if (ESR != ESR_Continue) {
6366 // Succeeded here actually means we encountered a 'break'.
6367 assert(ESR == ESR_Succeeded || ESR == ESR_Returned);
6368 break;
6369 }
6370 }
6371
6372 // Map Continue back to Succeeded if we fell off the end of the loop.
6373 if (ESR == ESR_Continue)
6374 ESR = ESR_Succeeded;
6375
6376 return Scope.destroy() ? ESR : ESR_Failed;
6377 }
6378
6379 case Stmt::SwitchStmtClass:
6380 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
6381
6382 case Stmt::ContinueStmtClass:
6383 case Stmt::BreakStmtClass: {
6384 auto *B = cast<LoopControlStmt>(S);
6385 Info.BreakContinueStack.push_back(B->getNamedLoopOrSwitch());
6386 return isa<ContinueStmt>(S) ? ESR_Continue : ESR_Break;
6387 }
6388
6389 case Stmt::LabelStmtClass:
6390 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
6391
6392 case Stmt::AttributedStmtClass: {
6393 const auto *AS = cast<AttributedStmt>(S);
6394 const auto *SS = AS->getSubStmt();
6395 MSConstexprContextRAII ConstexprContext(
6396 *Info.CurrentCall, hasSpecificAttr<MSConstexprAttr>(AS->getAttrs()) &&
6397 isa<ReturnStmt>(SS));
6398
6399 auto LO = Info.Ctx.getLangOpts();
6400 if (LO.CXXAssumptions && !LO.MSVCCompat) {
6401 for (auto *Attr : AS->getAttrs()) {
6402 auto *AA = dyn_cast<CXXAssumeAttr>(Attr);
6403 if (!AA)
6404 continue;
6405
6406 auto *Assumption = AA->getAssumption();
6407 if (Assumption->isValueDependent())
6408 return ESR_Failed;
6409
6410 if (Assumption->HasSideEffects(Info.Ctx))
6411 continue;
6412
6413 bool Value;
6414 if (!EvaluateAsBooleanCondition(Assumption, Value, Info))
6415 return ESR_Failed;
6416 if (!Value) {
6417 Info.CCEDiag(Assumption->getExprLoc(),
6418 diag::note_constexpr_assumption_failed);
6419 return ESR_Failed;
6420 }
6421 }
6422 }
6423
6424 return EvaluateStmt(Result, Info, SS, Case);
6425 }
6426
6427 case Stmt::CaseStmtClass:
6428 case Stmt::DefaultStmtClass:
6429 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
6430 case Stmt::CXXTryStmtClass:
6431 // Evaluate try blocks by evaluating all sub statements.
6432 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
6433 }
6434}
6435
6436/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
6437/// default constructor. If so, we'll fold it whether or not it's marked as
6438/// constexpr. If it is marked as constexpr, we will never implicitly define it,
6439/// so we need special handling.
6440static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
6441 const CXXConstructorDecl *CD,
6442 bool IsValueInitialization) {
6443 if (!CD->isTrivial() || !CD->isDefaultConstructor())
6444 return false;
6445
6446 // Value-initialization does not call a trivial default constructor, so such a
6447 // call is a core constant expression whether or not the constructor is
6448 // constexpr.
6449 if (!CD->isConstexpr() && !IsValueInitialization) {
6450 if (Info.getLangOpts().CPlusPlus11) {
6451 // FIXME: If DiagDecl is an implicitly-declared special member function,
6452 // we should be much more explicit about why it's not constexpr.
6453 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
6454 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
6455 Info.Note(CD->getLocation(), diag::note_declared_at);
6456 } else {
6457 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
6458 }
6459 }
6460 return true;
6461}
6462
6463/// CheckConstexprFunction - Check that a function can be called in a constant
6464/// expression.
6465static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
6467 const FunctionDecl *Definition,
6468 const Stmt *Body) {
6469 // Potential constant expressions can contain calls to declared, but not yet
6470 // defined, constexpr functions.
6471 if (Info.checkingPotentialConstantExpression() && !Definition &&
6472 Declaration->isConstexpr())
6473 return false;
6474
6475 // Bail out if the function declaration itself is invalid. We will
6476 // have produced a relevant diagnostic while parsing it, so just
6477 // note the problematic sub-expression.
6478 if (Declaration->isInvalidDecl()) {
6479 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
6480 return false;
6481 }
6482
6483 // DR1872: An instantiated virtual constexpr function can't be called in a
6484 // constant expression (prior to C++20). We can still constant-fold such a
6485 // call.
6486 if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) &&
6487 cast<CXXMethodDecl>(Declaration)->isVirtual())
6488 Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
6489
6490 if (Definition && Definition->isInvalidDecl()) {
6491 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
6492 return false;
6493 }
6494
6495 // Can we evaluate this function call?
6496 if (Definition && Body &&
6497 (Definition->isConstexpr() || (Info.CurrentCall->CanEvalMSConstexpr &&
6498 Definition->hasAttr<MSConstexprAttr>())))
6499 return true;
6500
6501 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
6502 // Special note for the assert() macro, as the normal error message falsely
6503 // implies we cannot use an assertion during constant evaluation.
6504 if (CallLoc.isMacroID() && DiagDecl->getIdentifier()) {
6505 // FIXME: Instead of checking for an implementation-defined function,
6506 // check and evaluate the assert() macro.
6507 StringRef Name = DiagDecl->getName();
6508 bool AssertFailed =
6509 Name == "__assert_rtn" || Name == "__assert_fail" || Name == "_wassert";
6510 if (AssertFailed) {
6511 Info.FFDiag(CallLoc, diag::note_constexpr_assert_failed);
6512 return false;
6513 }
6514 }
6515
6516 if (Info.getLangOpts().CPlusPlus11) {
6517 // If this function is not constexpr because it is an inherited
6518 // non-constexpr constructor, diagnose that directly.
6519 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
6520 if (CD && CD->isInheritingConstructor()) {
6521 auto *Inherited = CD->getInheritedConstructor().getConstructor();
6522 if (!Inherited->isConstexpr())
6523 DiagDecl = CD = Inherited;
6524 }
6525
6526 // FIXME: If DiagDecl is an implicitly-declared special member function
6527 // or an inheriting constructor, we should be much more explicit about why
6528 // it's not constexpr.
6529 if (CD && CD->isInheritingConstructor())
6530 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
6531 << CD->getInheritedConstructor().getConstructor()->getParent();
6532 else
6533 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
6534 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
6535 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
6536 } else {
6537 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
6538 }
6539 return false;
6540}
6541
6542namespace {
6543struct CheckDynamicTypeHandler {
6545 typedef bool result_type;
6546 bool failed() { return false; }
6547 bool found(APValue &Subobj, QualType SubobjType, APValue::LValueBase Base) {
6548 return true;
6549 }
6550 bool found(APSInt &Value, QualType SubobjType) { return true; }
6551 bool found(APFloat &Value, QualType SubobjType) { return true; }
6552};
6553} // end anonymous namespace
6554
6555/// Check that we can access the notional vptr of an object / determine its
6556/// dynamic type.
6557static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
6558 AccessKinds AK, bool Polymorphic) {
6559 if (This.Designator.Invalid)
6560 return false;
6561
6562 CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
6563
6564 if (!Obj)
6565 return false;
6566
6567 if (!Obj.Value) {
6568 // The object is not usable in constant expressions, so we can't inspect
6569 // its value to see if it's in-lifetime or what the active union members
6570 // are. We can still check for a one-past-the-end lvalue.
6571 if (This.Designator.isOnePastTheEnd() ||
6572 This.Designator.isMostDerivedAnUnsizedArray()) {
6573 Info.FFDiag(E, This.Designator.isOnePastTheEnd()
6574 ? diag::note_constexpr_access_past_end
6575 : diag::note_constexpr_access_unsized_array)
6576 << AK;
6577 return false;
6578 } else if (Polymorphic) {
6579 // Conservatively refuse to perform a polymorphic operation if we would
6580 // not be able to read a notional 'vptr' value.
6581 if (!Info.checkingPotentialConstantExpression() ||
6582 !This.AllowConstexprUnknown) {
6583 APValue Val;
6584 This.moveInto(Val);
6585 QualType StarThisType =
6586 Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
6587 Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
6588 << AK << Val.getAsString(Info.Ctx, StarThisType);
6589 }
6590 return false;
6591 }
6592 return true;
6593 }
6594
6595 CheckDynamicTypeHandler Handler{AK};
6596 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
6597}
6598
6599/// Check that the pointee of the 'this' pointer in a member function call is
6600/// either within its lifetime or in its period of construction or destruction.
6601static bool
6603 const LValue &This,
6604 const CXXMethodDecl *NamedMember) {
6605 return checkDynamicType(
6606 Info, E, This,
6607 isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false);
6608}
6609
6611 /// The dynamic class type of the object.
6613 /// The corresponding path length in the lvalue.
6614 unsigned PathLength;
6615};
6616
6617static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
6618 unsigned PathLength) {
6619 assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
6620 Designator.Entries.size() && "invalid path length");
6621 return (PathLength == Designator.MostDerivedPathLength)
6622 ? Designator.MostDerivedType->getAsCXXRecordDecl()
6623 : getAsBaseClass(Designator.Entries[PathLength - 1]);
6624}
6625
6626/// Determine the dynamic type of an object.
6627static std::optional<DynamicType> ComputeDynamicType(EvalInfo &Info,
6628 const Expr *E,
6629 LValue &This,
6630 AccessKinds AK) {
6631 // If we don't have an lvalue denoting an object of class type, there is no
6632 // meaningful dynamic type. (We consider objects of non-class type to have no
6633 // dynamic type.)
6634 if (!checkDynamicType(Info, E, This, AK,
6635 AK != AK_TypeId || This.AllowConstexprUnknown))
6636 return std::nullopt;
6637
6638 if (This.Designator.Invalid)
6639 return std::nullopt;
6640
6641 // Refuse to compute a dynamic type in the presence of virtual bases
6642 // before C++26. This shouldn't happen other than in constant-folding
6643 // situations, since literal types can't have virtual bases.
6644 const CXXRecordDecl *Class =
6645 This.Designator.MostDerivedType->getAsCXXRecordDecl();
6646 if (!Class || (!Info.getLangOpts().CPlusPlus26 && Class->getNumVBases())) {
6647 Info.FFDiag(E);
6648 return std::nullopt;
6649 }
6650
6651 // FIXME: For very deep class hierarchies, it might be beneficial to use a
6652 // binary search here instead. But the overwhelmingly common case is that
6653 // we're not in the middle of a constructor, so it probably doesn't matter
6654 // in practice.
6655 ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
6656 for (unsigned PathLength = This.Designator.MostDerivedPathLength;
6657 PathLength <= Path.size(); ++PathLength) {
6658 switch (Info.isEvaluatingCtorDtor(This.getLValueBase(),
6659 Path.slice(0, PathLength))) {
6660 case ConstructionPhase::Bases:
6661 case ConstructionPhase::DestroyingBases:
6662 // We're constructing or destroying a base class. This is not the dynamic
6663 // type.
6664 break;
6665
6666 case ConstructionPhase::None:
6667 case ConstructionPhase::AfterBases:
6668 case ConstructionPhase::AfterFields:
6669 case ConstructionPhase::Destroying:
6670 // We've finished constructing the base classes and not yet started
6671 // destroying them again, so this is the dynamic type.
6672 return DynamicType{getBaseClassType(This.Designator, PathLength),
6673 PathLength};
6674 }
6675 }
6676
6677 // CWG issue 1517: we're constructing a base class of the object described by
6678 // 'This', so that object has not yet begun its period of construction and
6679 // any polymorphic operation on it results in undefined behavior.
6680 Info.FFDiag(E);
6681 return std::nullopt;
6682}
6683
6684/// Perform virtual dispatch.
6686 EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
6687 llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
6688 std::optional<DynamicType> DynType = ComputeDynamicType(
6689 Info, E, This,
6691 if (!DynType)
6692 return nullptr;
6693
6694 // Find the final overrider. It must be declared in one of the classes on the
6695 // path from the dynamic type to the static type.
6696 // FIXME: If we ever allow literal types to have virtual base classes, that
6697 // won't be true.
6698 const CXXMethodDecl *Callee = Found;
6699 unsigned PathLength = DynType->PathLength;
6700 for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
6701 const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
6702 const CXXMethodDecl *Overrider =
6703 Found->getCorrespondingMethodDeclaredInClass(Class, false);
6704 if (Overrider) {
6705 Callee = Overrider;
6706 break;
6707 }
6708 }
6709
6710 // C++2a [class.abstract]p6:
6711 // the effect of making a virtual call to a pure virtual function [...] is
6712 // undefined
6713 if (Callee->isPureVirtual()) {
6714 Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
6715 Info.Note(Callee->getLocation(), diag::note_declared_at);
6716 return nullptr;
6717 }
6718
6719 // If necessary, walk the rest of the path to determine the sequence of
6720 // covariant adjustment steps to apply.
6721 if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
6722 Found->getReturnType())) {
6723 CovariantAdjustmentPath.push_back(Callee->getReturnType());
6724 for (unsigned CovariantPathLength = PathLength + 1;
6725 CovariantPathLength != This.Designator.Entries.size();
6726 ++CovariantPathLength) {
6727 const CXXRecordDecl *NextClass =
6728 getBaseClassType(This.Designator, CovariantPathLength);
6729 const CXXMethodDecl *Next =
6730 Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
6731 if (Next && !Info.Ctx.hasSameUnqualifiedType(
6732 Next->getReturnType(), CovariantAdjustmentPath.back()))
6733 CovariantAdjustmentPath.push_back(Next->getReturnType());
6734 }
6735 if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
6736 CovariantAdjustmentPath.back()))
6737 CovariantAdjustmentPath.push_back(Found->getReturnType());
6738 }
6739
6740 // Perform 'this' adjustment.
6741 if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
6742 return nullptr;
6743
6744 return Callee;
6745}
6746
6747/// Perform the adjustment from a value returned by a virtual function to
6748/// a value of the statically expected type, which may be a pointer or
6749/// reference to a base class of the returned type.
6750static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
6751 APValue &Result,
6752 ArrayRef<QualType> Path) {
6753 assert(Result.isLValue() &&
6754 "unexpected kind of APValue for covariant return");
6755 if (Result.isNullPointer())
6756 return true;
6757
6758 LValue LVal;
6759 LVal.setFrom(Info.Ctx, Result);
6760
6761 const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
6762 for (unsigned I = 1; I != Path.size(); ++I) {
6763 const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
6764 assert(OldClass && NewClass && "unexpected kind of covariant return");
6765 if (OldClass != NewClass &&
6766 !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
6767 return false;
6768 OldClass = NewClass;
6769 }
6770
6771 LVal.moveInto(Result);
6772 return true;
6773}
6774
6775/// Determine whether \p Base, which is known to be a direct base class of
6776/// \p Derived, is a public base class.
6777static bool isBaseClassPublic(const CXXRecordDecl *Derived,
6778 const CXXRecordDecl *Base) {
6779 for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
6780 if (BaseSpec.isVirtual())
6781 continue;
6782 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
6783 if (BaseClass && declaresSameEntity(BaseClass, Base))
6784 return BaseSpec.getAccessSpecifier() == AS_public;
6785 }
6786 for (const CXXBaseSpecifier &BaseSpec : Derived->vbases()) {
6787 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
6788 if (BaseClass && declaresSameEntity(BaseClass, Base))
6789 return BaseSpec.getAccessSpecifier() == AS_public;
6790 }
6791
6792 llvm_unreachable("Base is not a direct base of Derived");
6793}
6794
6795/// Apply the given dynamic cast operation on the provided lvalue.
6796///
6797/// This implements the hard case of dynamic_cast, requiring a "runtime check"
6798/// to find a suitable target subobject.
6799static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
6800 LValue &Ptr) {
6801 // We can't do anything with a non-symbolic pointer value.
6802 SubobjectDesignator &D = Ptr.Designator;
6803 if (D.Invalid)
6804 return false;
6805
6806 // C++ [expr.dynamic.cast]p6:
6807 // If v is a null pointer value, the result is a null pointer value.
6808 if (Ptr.isNullPointer() && !E->isGLValue())
6809 return true;
6810
6811 // For all the other cases, we need the pointer to point to an object within
6812 // its lifetime / period of construction / destruction, and we need to know
6813 // its dynamic type.
6814 std::optional<DynamicType> DynType =
6815 ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
6816 if (!DynType)
6817 return false;
6818
6819 // C++ [expr.dynamic.cast]p7:
6820 // If T is "pointer to cv void", then the result is a pointer to the most
6821 // derived object
6822 if (E->getType()->isVoidPointerType())
6823 return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
6824
6826 assert(C && "dynamic_cast target is not void pointer nor class");
6827 CanQualType CQT = Info.Ctx.getCanonicalTagType(C);
6828
6829 auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
6830 // C++ [expr.dynamic.cast]p9:
6831 if (!E->isGLValue()) {
6832 // The value of a failed cast to pointer type is the null pointer value
6833 // of the required result type.
6834 Ptr.setNull(Info.Ctx, E->getType());
6835 return true;
6836 }
6837
6838 // A failed cast to reference type throws [...] std::bad_cast.
6839 unsigned DiagKind;
6840 if (!Paths && (declaresSameEntity(DynType->Type, C) ||
6841 DynType->Type->isDerivedFrom(C)))
6842 DiagKind = 0;
6843 else if (!Paths || Paths->begin() == Paths->end())
6844 DiagKind = 1;
6845 else if (Paths->isAmbiguous(CQT))
6846 DiagKind = 2;
6847 else {
6848 assert(Paths->front().Access != AS_public && "why did the cast fail?");
6849 DiagKind = 3;
6850 }
6851 Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
6852 << DiagKind << Ptr.Designator.getType(Info.Ctx)
6853 << Info.Ctx.getCanonicalTagType(DynType->Type)
6854 << E->getType().getUnqualifiedType();
6855 return false;
6856 };
6857
6858 // Runtime check, phase 1:
6859 // Walk from the base subobject towards the derived object looking for the
6860 // target type.
6861 for (int PathLength = Ptr.Designator.Entries.size();
6862 PathLength >= (int)DynType->PathLength; --PathLength) {
6863 const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
6864 if (declaresSameEntity(Class, C))
6865 return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
6866 // We can only walk across public inheritance edges.
6867 if (PathLength > (int)DynType->PathLength &&
6868 !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
6869 Class))
6870 return RuntimeCheckFailed(nullptr);
6871 }
6872
6873 // Runtime check, phase 2:
6874 // Search the dynamic type for an unambiguous public base of type C.
6875 CXXBasePaths Paths(/*FindAmbiguities=*/true,
6876 /*RecordPaths=*/true, /*DetectVirtual=*/false);
6877 if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
6878 Paths.front().Access == AS_public) {
6879 // Downcast to the dynamic type...
6880 if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
6881 return false;
6882 // ... then upcast to the chosen base class subobject.
6883 for (CXXBasePathElement &Elem : Paths.front())
6884 if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
6885 return false;
6886 return true;
6887 }
6888
6889 // Otherwise, the runtime check fails.
6890 return RuntimeCheckFailed(&Paths);
6891}
6892
6893namespace {
6894struct StartLifetimeOfUnionMemberHandler {
6895 EvalInfo &Info;
6896 const Expr *LHSExpr;
6897 const FieldDecl *Field;
6898 bool DuringInit;
6899 bool Failed = false;
6900 static const AccessKinds AccessKind = AK_Assign;
6901
6902 typedef bool result_type;
6903 bool failed() { return Failed; }
6904 bool found(APValue &Subobj, QualType SubobjType, APValue::LValueBase Base) {
6905 // We are supposed to perform no initialization but begin the lifetime of
6906 // the object. We interpret that as meaning to do what default
6907 // initialization of the object would do if all constructors involved were
6908 // trivial:
6909 // * All base, non-variant member, and array element subobjects' lifetimes
6910 // begin
6911 // * No variant members' lifetimes begin
6912 // * All scalar subobjects whose lifetimes begin have indeterminate values
6913 assert(SubobjType->isUnionType());
6914 if (declaresSameEntity(Subobj.getUnionField(), Field)) {
6915 // This union member is already active. If it's also in-lifetime, there's
6916 // nothing to do.
6917 if (Subobj.getUnionValue().hasValue())
6918 return true;
6919 } else if (DuringInit) {
6920 // We're currently in the process of initializing a different union
6921 // member. If we carried on, that initialization would attempt to
6922 // store to an inactive union member, resulting in undefined behavior.
6923 Info.FFDiag(LHSExpr,
6924 diag::note_constexpr_union_member_change_during_init);
6925 return false;
6926 }
6928 Failed = !handleDefaultInitValue(Field->getType(), Result);
6929 Subobj.setUnion(Field, Result);
6930 return true;
6931 }
6932 bool found(APSInt &Value, QualType SubobjType) {
6933 llvm_unreachable("wrong value kind for union object");
6934 }
6935 bool found(APFloat &Value, QualType SubobjType) {
6936 llvm_unreachable("wrong value kind for union object");
6937 }
6938};
6939} // end anonymous namespace
6940
6941const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
6942
6943/// Handle a builtin simple-assignment or a call to a trivial assignment
6944/// operator whose left-hand side might involve a union member access. If it
6945/// does, implicitly start the lifetime of any accessed union elements per
6946/// C++20 [class.union]5.
6947static bool MaybeHandleUnionActiveMemberChange(EvalInfo &Info,
6948 const Expr *LHSExpr,
6949 const LValue &LHS) {
6950 if (LHS.InvalidBase || LHS.Designator.Invalid)
6951 return false;
6952
6954 // C++ [class.union]p5:
6955 // define the set S(E) of subexpressions of E as follows:
6956 unsigned PathLength = LHS.Designator.Entries.size();
6957 for (const Expr *E = LHSExpr; E != nullptr;) {
6958 // -- If E is of the form A.B, S(E) contains the elements of S(A)...
6959 if (auto *ME = dyn_cast<MemberExpr>(E)) {
6960 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
6961 // Note that we can't implicitly start the lifetime of a reference,
6962 // so we don't need to proceed any further if we reach one.
6963 if (!FD || FD->getType()->isReferenceType())
6964 break;
6965
6966 // ... and also contains A.B if B names a union member ...
6967 if (FD->getParent()->isUnion()) {
6968 // ... of a non-class, non-array type, or of a class type with a
6969 // trivial default constructor that is not deleted, or an array of
6970 // such types.
6971 auto *RD =
6972 FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6973 if (!RD || RD->hasTrivialDefaultConstructor())
6974 UnionPathLengths.push_back({PathLength - 1, FD});
6975 }
6976
6977 E = ME->getBase();
6978 --PathLength;
6979 assert(declaresSameEntity(FD,
6980 LHS.Designator.Entries[PathLength]
6981 .getAsBaseOrMember().getPointer()));
6982
6983 // -- If E is of the form A[B] and is interpreted as a built-in array
6984 // subscripting operator, S(E) is [S(the array operand, if any)].
6985 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
6986 // Step over an ArrayToPointerDecay implicit cast.
6987 auto *Base = ASE->getBase()->IgnoreImplicit();
6988 if (!Base->getType()->isArrayType())
6989 break;
6990
6991 E = Base;
6992 --PathLength;
6993
6994 } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6995 // Step over a derived-to-base conversion.
6996 E = ICE->getSubExpr();
6997 if (ICE->getCastKind() == CK_NoOp)
6998 continue;
6999 if (ICE->getCastKind() != CK_DerivedToBase &&
7000 ICE->getCastKind() != CK_UncheckedDerivedToBase)
7001 break;
7002 // Walk path backwards as we walk up from the base to the derived class.
7003 for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
7004 if (Elt->isVirtual()) {
7005 // A class with virtual base classes never has a trivial default
7006 // constructor, so S(E) is empty in this case.
7007 E = nullptr;
7008 break;
7009 }
7010
7011 --PathLength;
7012 assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
7013 LHS.Designator.Entries[PathLength]
7014 .getAsBaseOrMember().getPointer()));
7015 }
7016
7017 // -- Otherwise, S(E) is empty.
7018 } else {
7019 break;
7020 }
7021 }
7022
7023 // Common case: no unions' lifetimes are started.
7024 if (UnionPathLengths.empty())
7025 return true;
7026
7027 // if modification of X [would access an inactive union member], an object
7028 // of the type of X is implicitly created
7029 CompleteObject Obj =
7030 findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
7031 if (!Obj)
7032 return false;
7033 for (std::pair<unsigned, const FieldDecl *> LengthAndField :
7034 llvm::reverse(UnionPathLengths)) {
7035 // Form a designator for the union object.
7036 SubobjectDesignator D = LHS.Designator;
7037 D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
7038
7039 bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) ==
7040 ConstructionPhase::AfterBases;
7041 StartLifetimeOfUnionMemberHandler StartLifetime{
7042 Info, LHSExpr, LengthAndField.second, DuringInit};
7043 if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
7044 return false;
7045 }
7046
7047 return true;
7048}
7049
7050static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg,
7051 CallRef Call, EvalInfo &Info, bool NonNull = false,
7052 APValue **EvaluatedArg = nullptr) {
7053 LValue LV;
7054 // Create the parameter slot and register its destruction. For a vararg
7055 // argument, create a temporary.
7056 // FIXME: For calling conventions that destroy parameters in the callee,
7057 // should we consider performing destruction when the function returns
7058 // instead?
7059 APValue &V = PVD ? Info.CurrentCall->createParam(Call, PVD, LV)
7060 : Info.CurrentCall->createTemporary(Arg, Arg->getType(),
7061 ScopeKind::Call, LV);
7062 if (!EvaluateInPlace(V, Info, LV, Arg))
7063 return false;
7064
7065 // Passing a null pointer to an __attribute__((nonnull)) parameter results in
7066 // undefined behavior, so is non-constant.
7067 if (NonNull && V.isLValue() && V.isNullPointer()) {
7068 Info.CCEDiag(Arg, diag::note_non_null_attribute_failed);
7069 return false;
7070 }
7071
7072 if (EvaluatedArg)
7073 *EvaluatedArg = &V;
7074
7075 return true;
7076}
7077
7078/// Evaluate the arguments to a function call.
7079static bool EvaluateArgs(ArrayRef<const Expr *> Args, CallRef Call,
7080 EvalInfo &Info, const FunctionDecl *Callee,
7081 bool RightToLeft = false,
7082 LValue *ObjectArg = nullptr) {
7083 bool Success = true;
7084 llvm::SmallBitVector ForbiddenNullArgs;
7085 if (Callee->hasAttr<NonNullAttr>()) {
7086 ForbiddenNullArgs.resize(Args.size());
7087 for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
7088 if (!Attr->args_size()) {
7089 ForbiddenNullArgs.set();
7090 break;
7091 } else
7092 for (auto Idx : Attr->args()) {
7093 unsigned ASTIdx = Idx.getASTIndex();
7094 if (ASTIdx >= Args.size())
7095 continue;
7096 ForbiddenNullArgs[ASTIdx] = true;
7097 }
7098 }
7099 }
7100 for (unsigned I = 0; I < Args.size(); I++) {
7101 unsigned Idx = RightToLeft ? Args.size() - I - 1 : I;
7102 const ParmVarDecl *PVD =
7103 Idx < Callee->getNumParams() ? Callee->getParamDecl(Idx) : nullptr;
7104 bool NonNull = !ForbiddenNullArgs.empty() && ForbiddenNullArgs[Idx];
7105 APValue *That = nullptr;
7106 if (!EvaluateCallArg(PVD, Args[Idx], Call, Info, NonNull, &That)) {
7107 // If we're checking for a potential constant expression, evaluate all
7108 // initializers even if some of them fail.
7109 if (!Info.noteFailure())
7110 return false;
7111 Success = false;
7112 }
7113 if (PVD && PVD->isExplicitObjectParameter() && That && That->isLValue())
7114 ObjectArg->setFrom(Info.Ctx, *That);
7115 }
7116 return Success;
7117}
7118
7119/// Perform a trivial copy from Param, which is the parameter of a copy or move
7120/// constructor or assignment operator.
7121static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param,
7122 const Expr *E, APValue &Result,
7123 bool CopyObjectRepresentation) {
7124 // Find the reference argument.
7125 CallStackFrame *Frame = Info.CurrentCall;
7126 APValue *RefValue = Info.getParamSlot(Frame->Arguments, Param);
7127 if (!RefValue) {
7128 Info.FFDiag(E);
7129 return false;
7130 }
7131
7132 // Copy out the contents of the RHS object.
7133 LValue RefLValue;
7134 RefLValue.setFrom(Info.Ctx, *RefValue);
7136 Info, E, Param->getType().getNonReferenceType(), RefLValue, Result,
7137 CopyObjectRepresentation);
7138}
7139
7140/// Evaluate a function call.
7142 const FunctionDecl *Callee,
7143 const LValue *ObjectArg, const Expr *E,
7144 ArrayRef<const Expr *> Args, CallRef Call,
7145 const Stmt *Body, EvalInfo &Info,
7146 APValue &Result, const LValue *ResultSlot) {
7147 if (!Info.CheckCallLimit(CallLoc))
7148 return false;
7149
7150 CallStackFrame Frame(Info, E->getSourceRange(), Callee, ObjectArg, E, Call);
7151
7152 // For a trivial copy or move assignment, perform an APValue copy. This is
7153 // essential for unions, where the operations performed by the assignment
7154 // operator cannot be represented as statements.
7155 //
7156 // Skip this for non-union classes with no fields; in that case, the defaulted
7157 // copy/move does not actually read the object.
7158 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
7159
7160 auto IsTrivialMemoryOperation = [&](const CXXMethodDecl *MD) {
7161 if (!MD || !MD->isDefaulted())
7162 return false;
7164 return false;
7165 return MD->getParent()->isUnion() ||
7166 (MD->isTrivial() &&
7168 };
7169
7170 if (IsTrivialMemoryOperation(MD)) {
7171 unsigned ExplicitOffset = MD->isExplicitObjectMemberFunction() ? 1 : 0;
7172 assert(ObjectArg);
7173 APValue RHSValue;
7174 if (!handleTrivialCopy(Info, MD->getParamDecl(0), Args[0], RHSValue,
7175 MD->getParent()->isUnion()))
7176 return false;
7177
7178 LValue Obj;
7179 if (!handleAssignment(Info, Args[ExplicitOffset], *ObjectArg,
7181 RHSValue))
7182 return false;
7183 ObjectArg->moveInto(Result);
7184 return true;
7185 } else if (MD && isLambdaCallOperator(MD)) {
7186 // We're in a lambda; determine the lambda capture field maps unless we're
7187 // just constexpr checking a lambda's call operator. constexpr checking is
7188 // done before the captures have been added to the closure object (unless
7189 // we're inferring constexpr-ness), so we don't have access to them in this
7190 // case. But since we don't need the captures to constexpr check, we can
7191 // just ignore them.
7192 if (!Info.checkingPotentialConstantExpression())
7193 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
7194 Frame.LambdaThisCaptureField);
7195 }
7196
7197 StmtResult Ret = {Result, ResultSlot};
7198 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
7199 if (ESR == ESR_Succeeded) {
7200 if (Callee->getReturnType()->isVoidType())
7201 return true;
7202 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
7203 }
7204 return ESR == ESR_Returned;
7205}
7206
7207static bool HandleConstructorCall(const Expr *E, const LValue &This,
7208 CallRef Call,
7209 const CXXConstructorDecl *Definition,
7210 EvalInfo &Info, APValue &Result,
7211 bool IsCompleteClass = true);
7212
7213static bool HandleConstructorCall(const Expr *E, const LValue &This,
7216 EvalInfo &Info, APValue &Result,
7217 bool IsCompleteClass = true) {
7218 CallScopeRAII CallScope(Info);
7219 CallRef Call = Info.CurrentCall->createCall(Definition);
7220 if (!EvaluateArgs(Args, Call, Info, Definition))
7221 return false;
7222
7223 return HandleConstructorCall(E, This, Call, Definition, Info, Result,
7224 IsCompleteClass) &&
7225 CallScope.destroy();
7226}
7227
7228/// Evaluate a constructor call.
7229static bool HandleConstructorCall(const Expr *E, const LValue &This,
7230 CallRef Call,
7232 EvalInfo &Info, APValue &Result,
7233 bool IsCompleteClass) {
7234
7235 SourceLocation CallLoc = E->getExprLoc();
7236 if (!Info.CheckCallLimit(CallLoc))
7237 return false;
7238
7239 const CXXRecordDecl *RD = Definition->getParent();
7240 if (!Info.getLangOpts().CPlusPlus26 && RD->getNumVBases()) {
7241 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
7242 return false;
7243 }
7244
7245 EvalInfo::EvaluatingConstructorRAII EvalObj(
7246 Info,
7247 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
7248 RD->getNumBases());
7249 CallStackFrame Frame(Info, E->getSourceRange(), Definition, &This, E, Call);
7250
7251 // FIXME: Creating an APValue just to hold a nonexistent return value is
7252 // wasteful.
7253 APValue RetVal;
7254 StmtResult Ret = {RetVal, nullptr};
7255
7256 // If it's a delegating constructor, delegate.
7257 if (Definition->isDelegatingConstructor()) {
7259 if ((*I)->getInit()->isValueDependent()) {
7260 if (!EvaluateDependentExpr((*I)->getInit(), Info))
7261 return false;
7262 } else {
7263 FullExpressionRAII InitScope(Info);
7264 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) ||
7265 !InitScope.destroy())
7266 return false;
7267 }
7268 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
7269 }
7270
7271 // For a trivial copy or move constructor, perform an APValue copy. This is
7272 // essential for unions (or classes with anonymous union members), where the
7273 // operations performed by the constructor cannot be represented by
7274 // ctor-initializers.
7275 //
7276 // Skip this for empty non-union classes; we should not perform an
7277 // lvalue-to-rvalue conversion on them because their copy constructor does not
7278 // actually read them.
7279 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
7280 (Definition->getParent()->isUnion() ||
7281 (Definition->isTrivial() &&
7283 return handleTrivialCopy(Info, Definition->getParamDecl(0), E, Result,
7284 Definition->getParent()->isUnion());
7285 }
7286
7287 // Reserve space for the struct members.
7288 if (!Result.hasValue()) {
7289 if (!RD->isUnion()) {
7290 unsigned NonVirtualBases = countNonVirtualBases(RD);
7291 Result = APValue(APValue::UninitStruct(), NonVirtualBases,
7292 RD->getNumFields(), RD->getNumVBases());
7293 } else
7294 // A union starts with no active member.
7295 Result = APValue((const FieldDecl*)nullptr);
7296 }
7297
7298 if (RD->isInvalidDecl()) return false;
7299 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7300
7301 // A scope for temporaries lifetime-extended by reference members.
7302 BlockScopeRAII LifetimeExtendedScope(Info);
7303
7304 bool Success = true;
7305 unsigned BasesSeen = 0;
7306 unsigned VirtualBasesSeen = 0;
7307 unsigned NonVirtualBases = countNonVirtualBases(RD);
7308
7310 auto SkipToField = [&](FieldDecl *FD, bool Indirect) {
7311 // We might be initializing the same field again if this is an indirect
7312 // field initialization.
7313 if (FieldIt == RD->field_end() ||
7314 FieldIt->getFieldIndex() > FD->getFieldIndex()) {
7315 assert(Indirect && "fields out of order?");
7316 return;
7317 }
7318
7319 // Default-initialize any fields with no explicit initializer.
7320 for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
7321 assert(FieldIt != RD->field_end() && "missing field?");
7322 if (!FieldIt->isUnnamedBitField())
7324 FieldIt->getType(),
7325 Result.getStructField(FieldIt->getFieldIndex()));
7326 }
7327 ++FieldIt;
7328 };
7329 for (const auto *I : Definition->inits()) {
7330 LValue Subobject = This;
7331 LValue SubobjectParent = This;
7332 APValue *Value = &Result;
7333
7334 // Determine the subobject to initialize.
7335 FieldDecl *FD = nullptr;
7336 if (I->isBaseInitializer()) {
7337 QualType BaseType(I->getBaseClass(), 0);
7338 if (I->isBaseVirtual()) {
7339 if (This.pointsToCompleteClass(RD)) {
7340 if (!HandleLValueDirectVirtualBase(Info, I->getInit(), Subobject, RD,
7341 BaseType->getAsCXXRecordDecl(),
7342 &Layout))
7343 return false;
7344 Value = &Result.getStructVirtualBase(VirtualBasesSeen++);
7345 } else {
7346 continue;
7347 }
7348
7349 } else {
7350 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
7351 BaseType->getAsCXXRecordDecl(), &Layout))
7352 return false;
7353 Value = &Result.getStructBase(BasesSeen++);
7354 }
7355 } else if ((FD = I->getMember())) {
7356 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
7357 return false;
7358 if (RD->isUnion()) {
7359 Result = APValue(FD);
7360 Value = &Result.getUnionValue();
7361 } else {
7362 SkipToField(FD, false);
7363 Value = &Result.getStructField(FD->getFieldIndex());
7364 }
7365 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
7366 // Walk the indirect field decl's chain to find the object to initialize,
7367 // and make sure we've initialized every step along it.
7368 auto IndirectFieldChain = IFD->chain();
7369 for (auto *C : IndirectFieldChain) {
7370 FD = cast<FieldDecl>(C);
7372 // Switch the union field if it differs. This happens if we had
7373 // preceding zero-initialization, and we're now initializing a union
7374 // subobject other than the first.
7375 // FIXME: In this case, the values of the other subobjects are
7376 // specified, since zero-initialization sets all padding bits to zero.
7377 if (!Value->hasValue() ||
7378 (Value->isUnion() &&
7379 !declaresSameEntity(Value->getUnionField(), FD))) {
7380 if (CD->isUnion())
7381 *Value = APValue(FD);
7382 else
7383 // FIXME: This immediately starts the lifetime of all members of
7384 // an anonymous struct. It would be preferable to strictly start
7385 // member lifetime in initialization order.
7386 Success &= handleDefaultInitValue(Info.Ctx.getCanonicalTagType(CD),
7387 *Value);
7388 }
7389 // Store Subobject as its parent before updating it for the last element
7390 // in the chain.
7391 if (C == IndirectFieldChain.back())
7392 SubobjectParent = Subobject;
7393 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
7394 return false;
7395 if (CD->isUnion())
7396 Value = &Value->getUnionValue();
7397 else {
7398 if (C == IndirectFieldChain.front() && !RD->isUnion())
7399 SkipToField(FD, true);
7400 Value = &Value->getStructField(FD->getFieldIndex());
7401 }
7402 }
7403 } else {
7404 llvm_unreachable("unknown base initializer kind");
7405 }
7406
7407 // Need to override This for implicit field initializers as in this case
7408 // This refers to innermost anonymous struct/union containing initializer,
7409 // not to currently constructed class.
7410 const Expr *Init = I->getInit();
7411 if (Init->isValueDependent()) {
7412 if (!EvaluateDependentExpr(Init, Info))
7413 return false;
7414 } else {
7415 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
7417 FullExpressionRAII InitScope(Info);
7418 if (FD && FD->getType()->isReferenceType() &&
7419 !FD->getType()->isFunctionReferenceType()) {
7420 LValue Result;
7422 *Value)) {
7423 if (!Info.noteFailure())
7424 return false;
7425 Success = false;
7426 }
7427 } else if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
7428 (FD && FD->isBitField() &&
7429 !truncateBitfieldValue(Info, Init, *Value, FD))) {
7430 // If we're checking for a potential constant expression, evaluate all
7431 // initializers even if some of them fail.
7432 if (!Info.noteFailure())
7433 return false;
7434 Success = false;
7435 }
7436 }
7437
7438 // This is the point at which the dynamic type of the object becomes this
7439 // class type.
7440 if (I->isBaseInitializer() && BasesSeen == NonVirtualBases)
7441 EvalObj.finishedConstructingBases();
7442 }
7443
7444 // Default-initialize any remaining fields.
7445 if (!RD->isUnion()) {
7446 for (; FieldIt != RD->field_end(); ++FieldIt) {
7447 if (!FieldIt->isUnnamedBitField())
7449 FieldIt->getType(),
7450 Result.getStructField(FieldIt->getFieldIndex()));
7451 }
7452 }
7453
7454 EvalObj.finishedConstructingFields();
7455
7456 return Success &&
7457 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed &&
7458 LifetimeExtendedScope.destroy();
7459}
7460
7461static bool HandleDestructionImpl(EvalInfo &Info, SourceRange CallRange,
7462 const LValue &This, APValue &Value,
7463 QualType T, bool IsCompleteClass = true) {
7464 // Objects can only be destroyed while they're within their lifetimes.
7465 // FIXME: We have no representation for whether an object of type nullptr_t
7466 // is in its lifetime; it usually doesn't matter. Perhaps we should model it
7467 // as indeterminate instead?
7468 if (Value.isAbsent() && !T->isNullPtrType()) {
7469 APValue Printable;
7470 This.moveInto(Printable);
7471 Info.FFDiag(CallRange.getBegin(),
7472 diag::note_constexpr_destroy_out_of_lifetime)
7473 << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T));
7474 return false;
7475 }
7476
7477 // Invent an expression for location purposes.
7478 // FIXME: We shouldn't need to do this.
7479 OpaqueValueExpr LocE(CallRange.getBegin(), Info.Ctx.IntTy, VK_PRValue);
7480
7481 // For arrays, destroy elements right-to-left.
7482 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) {
7483 uint64_t Size = CAT->getZExtSize();
7484 QualType ElemT = CAT->getElementType();
7485
7486 if (!CheckArraySize(Info, CAT, CallRange.getBegin()))
7487 return false;
7488
7489 LValue ElemLV = This;
7490 ElemLV.addArray(Info, &LocE, CAT);
7491 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size))
7492 return false;
7493
7494 // Ensure that we have actual array elements available to destroy; the
7495 // destructors might mutate the value, so we can't run them on the array
7496 // filler.
7497 if (Size && Size > Value.getArrayInitializedElts())
7498 expandArray(Value, Value.getArraySize() - 1);
7499
7500 // The size of the array might have been reduced by
7501 // a placement new.
7502 for (Size = Value.getArraySize(); Size != 0; --Size) {
7503 APValue &Elem = Value.getArrayInitializedElt(Size - 1);
7504 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) ||
7505 !HandleDestructionImpl(Info, CallRange, ElemLV, Elem, ElemT))
7506 return false;
7507 }
7508
7509 // End the lifetime of this array now.
7510 Value = APValue();
7511 return true;
7512 }
7513
7514 const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
7515 if (!RD) {
7516 if (T.isDestructedType()) {
7517 Info.FFDiag(CallRange.getBegin(),
7518 diag::note_constexpr_unsupported_destruction)
7519 << T;
7520 return false;
7521 }
7522
7523 Value = APValue();
7524 return true;
7525 }
7526
7527 if (!Info.getLangOpts().CPlusPlus26 && RD->getNumVBases()) {
7528 Info.FFDiag(CallRange.getBegin(), diag::note_constexpr_virtual_base) << RD;
7529 return false;
7530 }
7531
7532 // If an anonymous union would be destroyed, some enclosing destructor must
7533 // have been explicitly defined, and the anonymous union destruction should
7534 // have no effect.
7535 if (RD->isAnonymousStructOrUnion() && RD->isUnion()) {
7536 Value = APValue();
7537 return true;
7538 }
7539
7540 const CXXDestructorDecl *DD = RD->getDestructor();
7541 if (!DD && !RD->hasTrivialDestructor()) {
7542 Info.FFDiag(CallRange.getBegin());
7543 return false;
7544 }
7545
7546 if (!DD || DD->isTrivial()) {
7547 // A trivial destructor just ends the lifetime of the object. Check for
7548 // this case before checking for a body, because we might not bother
7549 // building a body for a trivial destructor. Note that it doesn't matter
7550 // whether the destructor is constexpr in this case; all trivial
7551 // destructors are constexpr.
7552 Value = APValue();
7553 return true;
7554 }
7555
7556 if (!Info.CheckCallLimit(CallRange.getBegin()))
7557 return false;
7558
7559 const FunctionDecl *Definition = nullptr;
7560 const Stmt *Body = DD->getBody(Definition);
7561
7562 if (!CheckConstexprFunction(Info, CallRange.getBegin(), DD, Definition, Body))
7563 return false;
7564
7565 CallStackFrame Frame(Info, CallRange, Definition, &This, /*CallExpr=*/nullptr,
7566 CallRef());
7567
7568 // We're now in the period of destruction of this object.
7569 EvalInfo::EvaluatingDestructorRAII EvalObj(
7570 Info,
7571 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries});
7572 unsigned NonVirtualBases = countNonVirtualBases(RD);
7573 unsigned NumVirtualBases = RD->getNumVBases();
7574 unsigned BasesLeft = NonVirtualBases;
7575 if (!EvalObj.DidInsert) {
7576 // C++2a [class.dtor]p19:
7577 // the behavior is undefined if the destructor is invoked for an object
7578 // whose lifetime has ended
7579 // (Note that formally the lifetime ends when the period of destruction
7580 // begins, even though certain uses of the object remain valid until the
7581 // period of destruction ends.)
7582 Info.FFDiag(CallRange.getBegin(), diag::note_constexpr_double_destroy);
7583 return false;
7584 }
7585
7586 // FIXME: Creating an APValue just to hold a nonexistent return value is
7587 // wasteful.
7588 APValue RetVal;
7589 StmtResult Ret = {RetVal, nullptr};
7590 if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed)
7591 return false;
7592
7593 // A union destructor does not implicitly destroy its members.
7594 if (RD->isUnion())
7595 return true;
7596
7597 if (!ASTContext::hasLayout(RD))
7598 return false;
7599 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7600
7601 // We don't have a good way to iterate fields in reverse, so collect all the
7602 // fields first and then walk them backwards.
7603 SmallVector<FieldDecl*, 16> Fields(RD->fields());
7604 for (const FieldDecl *FD : llvm::reverse(Fields)) {
7605 if (FD->isUnnamedBitField())
7606 continue;
7607
7608 LValue Subobject = This;
7609 if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout))
7610 return false;
7611
7612 APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex());
7613 if (!HandleDestructionImpl(Info, CallRange, Subobject, *SubobjectValue,
7614 FD->getType()))
7615 return false;
7616 }
7617
7618 if (BasesLeft != 0 || NumVirtualBases != 0)
7619 EvalObj.startedDestroyingBases();
7620
7621 // Destroy base classes in reverse order.
7622 for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) {
7623 if (Base.isVirtual())
7624 continue;
7625 --BasesLeft;
7626
7627 QualType BaseType = Base.getType();
7628 LValue Subobject = This;
7629 if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD,
7630 BaseType->getAsCXXRecordDecl(), &Layout))
7631 return false;
7632
7633 APValue *SubobjectValue = &Value.getStructBase(BasesLeft);
7634 if (!HandleDestructionImpl(Info, CallRange, Subobject, *SubobjectValue,
7635 BaseType, /*IsCompleteClass=*/false))
7636 return false;
7637 }
7638 assert(BasesLeft == 0 && "NumBases was wrong?");
7639
7640 // Virtual bases.
7641 if (IsCompleteClass) {
7642 unsigned VirtualBasesLeft = NumVirtualBases;
7643 for (const CXXBaseSpecifier &Base : llvm::reverse(RD->vbases())) {
7644 --VirtualBasesLeft;
7645
7646 QualType BaseType = Base.getType();
7647 LValue Subobject = This;
7648 if (!HandleLValueDirectVirtualBase(Info, &LocE, Subobject, RD,
7649 BaseType->getAsCXXRecordDecl(),
7650 &Layout))
7651 return false;
7652
7653 APValue *SubobjectValue = &Value.getStructVirtualBase(VirtualBasesLeft);
7654 if (!HandleDestructionImpl(Info, CallRange, Subobject, *SubobjectValue,
7655 BaseType, /*IsCompleteClass=*/false))
7656 return false;
7657 }
7658 assert(VirtualBasesLeft == 0 && "NumVirtualBases was wrong?");
7659 }
7660
7661 // The period of destruction ends now. The object is gone.
7662 Value = APValue();
7663 return true;
7664}
7665
7666namespace {
7667struct DestroyObjectHandler {
7668 EvalInfo &Info;
7669 const Expr *E;
7670 const LValue &This;
7671 const AccessKinds AccessKind;
7672
7673 typedef bool result_type;
7674 bool failed() { return false; }
7675 bool found(APValue &Subobj, QualType SubobjType, APValue::LValueBase Base) {
7676 return HandleDestructionImpl(Info, E->getSourceRange(), This, Subobj,
7677 SubobjType);
7678 }
7679 bool found(APSInt &Value, QualType SubobjType) {
7680 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
7681 return false;
7682 }
7683 bool found(APFloat &Value, QualType SubobjType) {
7684 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
7685 return false;
7686 }
7687};
7688}
7689
7690/// Perform a destructor or pseudo-destructor call on the given object, which
7691/// might in general not be a complete object.
7692static bool HandleDestruction(EvalInfo &Info, const Expr *E,
7693 const LValue &This, QualType ThisType) {
7694 CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType);
7695 DestroyObjectHandler Handler = {Info, E, This, AK_Destroy};
7696 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
7697}
7698
7699/// Destroy and end the lifetime of the given complete object.
7700static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
7702 QualType T) {
7703 // If we've had an unmodeled side-effect, we can't rely on mutable state
7704 // (such as the object we're about to destroy) being correct.
7705 if (Info.EvalStatus.HasSideEffects)
7706 return false;
7707
7708 LValue LV;
7709 LV.set({LVBase});
7710 return HandleDestructionImpl(Info, Loc, LV, Value, T);
7711}
7712
7713/// Perform a call to 'operator new' or to `__builtin_operator_new'.
7714static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E,
7715 LValue &Result) {
7716 if (Info.checkingPotentialConstantExpression() ||
7717 Info.SpeculativeEvaluationDepth)
7718 return false;
7719
7720 // This is permitted only within a call to std::allocator<T>::allocate.
7721 auto Caller = Info.getStdAllocatorCaller("allocate");
7722 if (!Caller) {
7723 Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20
7724 ? diag::note_constexpr_new_untyped
7725 : diag::note_constexpr_new);
7726 return false;
7727 }
7728
7729 QualType ElemType = Caller.ElemType;
7730 if (ElemType->isIncompleteType() || ElemType->isFunctionType()) {
7731 Info.FFDiag(E->getExprLoc(),
7732 diag::note_constexpr_new_not_complete_object_type)
7733 << (ElemType->isIncompleteType() ? 0 : 1) << ElemType;
7734 return false;
7735 }
7736
7737 APSInt ByteSize;
7738 if (!EvaluateInteger(E->getArg(0), ByteSize, Info))
7739 return false;
7740 bool IsNothrow = false;
7741 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) {
7742 EvaluateIgnoredValue(Info, E->getArg(I));
7743 IsNothrow |= E->getType()->isNothrowT();
7744 }
7745
7746 CharUnits ElemSize;
7747 if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize))
7748 return false;
7749 APInt Size, Remainder;
7750 APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity());
7751 APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder);
7752 if (Remainder != 0) {
7753 // This likely indicates a bug in the implementation of 'std::allocator'.
7754 Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size)
7755 << ByteSize << APSInt(ElemSizeAP, true) << ElemType;
7756 return false;
7757 }
7758
7759 if (!Info.CheckArraySize(E->getBeginLoc(), ByteSize.getActiveBits(),
7760 Size.getZExtValue(), /*Diag=*/!IsNothrow)) {
7761 if (IsNothrow) {
7762 Result.setNull(Info.Ctx, E->getType());
7763 return true;
7764 }
7765 return false;
7766 }
7767
7768 QualType AllocType = Info.Ctx.getConstantArrayType(
7769 ElemType, Size, nullptr, ArraySizeModifier::Normal, 0);
7770 APValue *Val = Info.createHeapAlloc(Caller.Call, AllocType, Result);
7771 *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue());
7772 Result.addArray(Info, E, cast<ConstantArrayType>(AllocType));
7773 return true;
7774}
7775
7777 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
7778 if (CXXDestructorDecl *DD = RD->getDestructor())
7779 return DD->isVirtual();
7780 return false;
7781}
7782
7784 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
7785 if (CXXDestructorDecl *DD = RD->getDestructor())
7786 return DD->isVirtual() ? DD->getOperatorDelete() : nullptr;
7787 return nullptr;
7788}
7789
7790/// Check that the given object is a suitable pointer to a heap allocation that
7791/// still exists and is of the right kind for the purpose of a deletion.
7792///
7793/// On success, returns the heap allocation to deallocate. On failure, produces
7794/// a diagnostic and returns std::nullopt.
7795static std::optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E,
7796 const LValue &Pointer,
7797 DynAlloc::Kind DeallocKind) {
7798 auto PointerAsString = [&] {
7799 return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy);
7800 };
7801
7802 DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>();
7803 if (!DA) {
7804 Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc)
7805 << PointerAsString();
7806 if (Pointer.Base)
7807 NoteLValueLocation(Info, Pointer.Base);
7808 return std::nullopt;
7809 }
7810
7811 std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
7812 if (!Alloc) {
7813 Info.FFDiag(E, diag::note_constexpr_double_delete);
7814 return std::nullopt;
7815 }
7816
7817 if (DeallocKind != (*Alloc)->getKind()) {
7818 QualType AllocType = Pointer.Base.getDynamicAllocType();
7819 Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch)
7820 << DeallocKind << (*Alloc)->getKind() << AllocType;
7821 NoteLValueLocation(Info, Pointer.Base);
7822 return std::nullopt;
7823 }
7824
7825 bool Subobject = false;
7826 if (DeallocKind == DynAlloc::New) {
7827 Subobject = Pointer.Designator.MostDerivedPathLength != 0 ||
7828 Pointer.Designator.isOnePastTheEnd();
7829 } else {
7830 Subobject = Pointer.Designator.Entries.size() != 1 ||
7831 Pointer.Designator.Entries[0].getAsArrayIndex() != 0;
7832 }
7833 if (Subobject) {
7834 Info.FFDiag(E, diag::note_constexpr_delete_subobject)
7835 << PointerAsString() << Pointer.Designator.isOnePastTheEnd();
7836 return std::nullopt;
7837 }
7838
7839 return Alloc;
7840}
7841
7842// Perform a call to 'operator delete' or '__builtin_operator_delete'.
7843static bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) {
7844 if (Info.checkingPotentialConstantExpression() ||
7845 Info.SpeculativeEvaluationDepth)
7846 return false;
7847
7848 // This is permitted only within a call to std::allocator<T>::deallocate.
7849 if (!Info.getStdAllocatorCaller("deallocate")) {
7850 Info.FFDiag(E->getExprLoc());
7851 return true;
7852 }
7853
7854 LValue Pointer;
7855 if (!EvaluatePointer(E->getArg(0), Pointer, Info))
7856 return false;
7857 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
7858 EvaluateIgnoredValue(Info, E->getArg(I));
7859
7860 if (Pointer.Designator.Invalid)
7861 return false;
7862
7863 // Deleting a null pointer would have no effect, but it's not permitted by
7864 // std::allocator<T>::deallocate's contract.
7865 if (Pointer.isNullPointer()) {
7866 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_deallocate_null);
7867 return true;
7868 }
7869
7870 if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator))
7871 return false;
7872
7873 Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>());
7874 return true;
7875}
7876
7877//===----------------------------------------------------------------------===//
7878// Generic Evaluation
7879//===----------------------------------------------------------------------===//
7880namespace {
7881
7882class BitCastBuffer {
7883 // FIXME: We're going to need bit-level granularity when we support
7884 // bit-fields.
7885 // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
7886 // we don't support a host or target where that is the case. Still, we should
7887 // use a more generic type in case we ever do.
7888 SmallVector<std::optional<unsigned char>, 32> Bytes;
7889
7890 static_assert(std::numeric_limits<unsigned char>::digits >= 8,
7891 "Need at least 8 bit unsigned char");
7892
7893 bool TargetIsLittleEndian;
7894
7895public:
7896 BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
7897 : Bytes(Width.getQuantity()),
7898 TargetIsLittleEndian(TargetIsLittleEndian) {}
7899
7900 [[nodiscard]] bool readObject(CharUnits Offset, CharUnits Width,
7901 SmallVectorImpl<unsigned char> &Output) const {
7902 for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
7903 // If a byte of an integer is uninitialized, then the whole integer is
7904 // uninitialized.
7905 if (!Bytes[I.getQuantity()])
7906 return false;
7907 Output.push_back(*Bytes[I.getQuantity()]);
7908 }
7909 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
7910 std::reverse(Output.begin(), Output.end());
7911 return true;
7912 }
7913
7914 void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
7915 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
7916 std::reverse(Input.begin(), Input.end());
7917
7918 size_t Index = 0;
7919 for (unsigned char Byte : Input) {
7920 assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
7921 Bytes[Offset.getQuantity() + Index] = Byte;
7922 ++Index;
7923 }
7924 }
7925
7926 size_t size() { return Bytes.size(); }
7927};
7928
7929/// Traverse an APValue to produce an BitCastBuffer, emulating how the current
7930/// target would represent the value at runtime.
7931class APValueToBufferConverter {
7932 EvalInfo &Info;
7933 BitCastBuffer Buffer;
7934 const CastExpr *BCE;
7935
7936 APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
7937 const CastExpr *BCE)
7938 : Info(Info),
7939 Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
7940 BCE(BCE) {}
7941
7942 bool visit(const APValue &Val, QualType Ty) {
7943 return visit(Val, Ty, CharUnits::fromQuantity(0));
7944 }
7945
7946 // Write out Val with type Ty into Buffer starting at Offset.
7947 bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
7948 assert((size_t)Offset.getQuantity() <= Buffer.size());
7949
7950 // As a special case, nullptr_t has an indeterminate value.
7951 if (Ty->isNullPtrType())
7952 return true;
7953
7954 // Dig through Src to find the byte at SrcOffset.
7955 switch (Val.getKind()) {
7957 case APValue::None:
7958 return true;
7959
7960 case APValue::Int:
7961 return visitInt(Val.getInt(), Ty, Offset);
7962 case APValue::Float:
7963 return visitFloat(Val.getFloat(), Ty, Offset);
7964 case APValue::Array:
7965 return visitArray(Val, Ty, Offset);
7966 case APValue::Struct:
7967 return visitRecord(Val, Ty, Offset);
7968 case APValue::Vector:
7969 return visitVector(Val, Ty, Offset);
7970
7973 return visitComplex(Val, Ty, Offset);
7975 // FIXME: We should support these.
7976
7977 case APValue::LValue:
7978 case APValue::Matrix:
7979 case APValue::Union:
7982 Info.FFDiag(BCE->getBeginLoc(),
7983 diag::note_constexpr_bit_cast_unsupported_type)
7984 << Ty;
7985 return false;
7986 }
7987 }
7988 llvm_unreachable("Unhandled APValue::ValueKind");
7989 }
7990
7991 bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
7992 const RecordDecl *RD = Ty->getAsRecordDecl();
7993 if (!ASTContext::hasLayout(RD))
7994 return false;
7995 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7996
7997 // Visit the base classes.
7998 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
7999 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
8000 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
8001 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
8002 const APValue &Base = Val.getStructBase(I);
8003
8004 // Can happen in error cases.
8005 if (!Base.isStruct())
8006 return false;
8007
8008 if (!visitRecord(Base, BS.getType(),
8009 Layout.getBaseClassOffset(BaseDecl) + Offset))
8010 return false;
8011 }
8012 }
8013
8014 // Visit the fields.
8015 unsigned FieldIdx = 0;
8016 for (FieldDecl *FD : RD->fields()) {
8017 if (FD->isBitField()) {
8018 Info.FFDiag(BCE->getBeginLoc(),
8019 diag::note_constexpr_bit_cast_unsupported_bitfield);
8020 return false;
8021 }
8022
8023 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
8024
8025 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
8026 "only bit-fields can have sub-char alignment");
8027 CharUnits FieldOffset =
8028 Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
8029 QualType FieldTy = FD->getType();
8030 if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
8031 return false;
8032 ++FieldIdx;
8033 }
8034
8035 return true;
8036 }
8037
8038 bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
8039 const auto *CAT =
8040 dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
8041 if (!CAT)
8042 return false;
8043
8044 CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
8045 unsigned NumInitializedElts = Val.getArrayInitializedElts();
8046 unsigned ArraySize = Val.getArraySize();
8047 // First, initialize the initialized elements.
8048 for (unsigned I = 0; I != NumInitializedElts; ++I) {
8049 const APValue &SubObj = Val.getArrayInitializedElt(I);
8050 if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
8051 return false;
8052 }
8053
8054 // Next, initialize the rest of the array using the filler.
8055 if (Val.hasArrayFiller()) {
8056 const APValue &Filler = Val.getArrayFiller();
8057 for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
8058 if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
8059 return false;
8060 }
8061 }
8062
8063 return true;
8064 }
8065
8066 bool visitComplex(const APValue &Val, QualType Ty, CharUnits Offset) {
8067 const ComplexType *ComplexTy = Ty->castAs<ComplexType>();
8068 QualType EltTy = ComplexTy->getElementType();
8069 CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
8070 bool IsInt = Val.isComplexInt();
8071
8072 if (IsInt) {
8073 if (!visitInt(Val.getComplexIntReal(), EltTy,
8074 Offset + (0 * EltSizeChars)))
8075 return false;
8076 if (!visitInt(Val.getComplexIntImag(), EltTy,
8077 Offset + (1 * EltSizeChars)))
8078 return false;
8079 } else {
8080 if (!visitFloat(Val.getComplexFloatReal(), EltTy,
8081 Offset + (0 * EltSizeChars)))
8082 return false;
8083 if (!visitFloat(Val.getComplexFloatImag(), EltTy,
8084 Offset + (1 * EltSizeChars)))
8085 return false;
8086 }
8087
8088 return true;
8089 }
8090
8091 bool visitVector(const APValue &Val, QualType Ty, CharUnits Offset) {
8092 const VectorType *VTy = Ty->castAs<VectorType>();
8093 QualType EltTy = VTy->getElementType();
8094 unsigned NElts = VTy->getNumElements();
8095
8096 if (VTy->isPackedVectorBoolType(Info.Ctx)) {
8097 // Special handling for OpenCL bool vectors:
8098 // Since these vectors are stored as packed bits, but we can't write
8099 // individual bits to the BitCastBuffer, we'll buffer all of the elements
8100 // together into an appropriately sized APInt and write them all out at
8101 // once. Because we don't accept vectors where NElts * EltSize isn't a
8102 // multiple of the char size, there will be no padding space, so we don't
8103 // have to worry about writing data which should have been left
8104 // uninitialized.
8105 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
8106
8107 llvm::APInt Res = llvm::APInt::getZero(NElts);
8108 for (unsigned I = 0; I < NElts; ++I) {
8109 const llvm::APSInt &EltAsInt = Val.getVectorElt(I).getInt();
8110 assert(EltAsInt.isUnsigned() && EltAsInt.getBitWidth() == 1 &&
8111 "bool vector element must be 1-bit unsigned integer!");
8112
8113 Res.insertBits(EltAsInt, BigEndian ? (NElts - I - 1) : I);
8114 }
8115
8116 SmallVector<uint8_t, 8> Bytes(NElts / 8);
8117 llvm::StoreIntToMemory(Res, &*Bytes.begin(), NElts / 8);
8118 Buffer.writeObject(Offset, Bytes);
8119 } else {
8120 // Iterate over each of the elements and write them out to the buffer at
8121 // the appropriate offset.
8122 CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
8123 for (unsigned I = 0; I < NElts; ++I) {
8124 if (!visit(Val.getVectorElt(I), EltTy, Offset + I * EltSizeChars))
8125 return false;
8126 }
8127 }
8128
8129 return true;
8130 }
8131
8132 bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
8133 APSInt AdjustedVal = Val;
8134 unsigned Width = AdjustedVal.getBitWidth();
8135 if (Ty->isBooleanType()) {
8136 Width = Info.Ctx.getTypeSize(Ty);
8137 AdjustedVal = AdjustedVal.extend(Width);
8138 }
8139
8140 SmallVector<uint8_t, 8> Bytes(Width / 8);
8141 llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8);
8142 Buffer.writeObject(Offset, Bytes);
8143 return true;
8144 }
8145
8146 bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
8147 APSInt AsInt(Val.bitcastToAPInt());
8148 return visitInt(AsInt, Ty, Offset);
8149 }
8150
8151public:
8152 static std::optional<BitCastBuffer>
8153 convert(EvalInfo &Info, const APValue &Src, const CastExpr *BCE) {
8154 CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
8155 APValueToBufferConverter Converter(Info, DstSize, BCE);
8156 if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
8157 return std::nullopt;
8158 return Converter.Buffer;
8159 }
8160};
8161
8162/// Write an BitCastBuffer into an APValue.
8163class BufferToAPValueConverter {
8164 EvalInfo &Info;
8165 const BitCastBuffer &Buffer;
8166 const CastExpr *BCE;
8167
8168 BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
8169 const CastExpr *BCE)
8170 : Info(Info), Buffer(Buffer), BCE(BCE) {}
8171
8172 // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
8173 // with an invalid type, so anything left is a deficiency on our part (FIXME).
8174 // Ideally this will be unreachable.
8175 std::nullopt_t unsupportedType(QualType Ty) {
8176 Info.FFDiag(BCE->getBeginLoc(),
8177 diag::note_constexpr_bit_cast_unsupported_type)
8178 << Ty;
8179 return std::nullopt;
8180 }
8181
8182 std::nullopt_t unrepresentableValue(QualType Ty, const APSInt &Val) {
8183 Info.FFDiag(BCE->getBeginLoc(),
8184 diag::note_constexpr_bit_cast_unrepresentable_value)
8185 << Ty << toString(Val, /*Radix=*/10);
8186 return std::nullopt;
8187 }
8188
8189 std::optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
8190 const EnumType *EnumSugar = nullptr) {
8191 if (T->isNullPtrType()) {
8192 uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
8193 return APValue((Expr *)nullptr,
8194 /*Offset=*/CharUnits::fromQuantity(NullValue),
8195 APValue::NoLValuePath{}, /*IsNullPtr=*/true);
8196 }
8197
8198 CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
8199
8200 // Work around floating point types that contain unused padding bytes. This
8201 // is really just `long double` on x86, which is the only fundamental type
8202 // with padding bytes.
8203 if (T->isRealFloatingType()) {
8204 const llvm::fltSemantics &Semantics =
8205 Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
8206 unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics);
8207 assert(NumBits % 8 == 0);
8208 CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8);
8209 if (NumBytes != SizeOf)
8210 SizeOf = NumBytes;
8211 }
8212
8213 SmallVector<uint8_t, 8> Bytes;
8214 if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
8215 // If this is std::byte or unsigned char, then its okay to store an
8216 // indeterminate value.
8217 bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
8218 bool IsUChar =
8219 !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
8220 T->isSpecificBuiltinType(BuiltinType::Char_U));
8221 if (!IsStdByte && !IsUChar) {
8222 QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
8223 Info.FFDiag(BCE->getExprLoc(),
8224 diag::note_constexpr_bit_cast_indet_dest)
8225 << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
8226 return std::nullopt;
8227 }
8228
8230 }
8231
8232 APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
8233 llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
8234
8236 Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
8237
8238 unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0));
8239 if (IntWidth != Val.getBitWidth()) {
8240 APSInt Truncated = Val.trunc(IntWidth);
8241 if (Truncated.extend(Val.getBitWidth()) != Val)
8242 return unrepresentableValue(QualType(T, 0), Val);
8243 Val = Truncated;
8244 }
8245
8246 return APValue(Val);
8247 }
8248
8249 if (T->isRealFloatingType()) {
8250 const llvm::fltSemantics &Semantics =
8251 Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
8252 return APValue(APFloat(Semantics, Val));
8253 }
8254
8255 return unsupportedType(QualType(T, 0));
8256 }
8257
8258 std::optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
8259 const RecordDecl *RD = RTy->getAsRecordDecl();
8260 if (RD->isInvalidDecl())
8261 return std::nullopt;
8262 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
8263
8264 unsigned NumBases = 0;
8265 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
8266 NumBases = CXXRD->getNumBases();
8267
8268 APValue ResultVal(APValue::UninitStruct(), NumBases, RD->getNumFields());
8269
8270 // Visit the base classes.
8271 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
8272 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
8273 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
8274 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
8275
8276 std::optional<APValue> SubObj = visitType(
8277 BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
8278 if (!SubObj)
8279 return std::nullopt;
8280 ResultVal.getStructBase(I) = *SubObj;
8281 }
8282 }
8283
8284 // Visit the fields.
8285 unsigned FieldIdx = 0;
8286 for (FieldDecl *FD : RD->fields()) {
8287 // FIXME: We don't currently support bit-fields. A lot of the logic for
8288 // this is in CodeGen, so we need to factor it around.
8289 if (FD->isBitField()) {
8290 Info.FFDiag(BCE->getBeginLoc(),
8291 diag::note_constexpr_bit_cast_unsupported_bitfield);
8292 return std::nullopt;
8293 }
8294
8295 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
8296 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
8297
8298 CharUnits FieldOffset =
8299 CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
8300 Offset;
8301 QualType FieldTy = FD->getType();
8302 std::optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
8303 if (!SubObj)
8304 return std::nullopt;
8305 ResultVal.getStructField(FieldIdx) = *SubObj;
8306 ++FieldIdx;
8307 }
8308
8309 return ResultVal;
8310 }
8311
8312 std::optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
8313 QualType RepresentationType =
8314 Ty->getDecl()->getDefinitionOrSelf()->getIntegerType();
8315 assert(!RepresentationType.isNull() &&
8316 "enum forward decl should be caught by Sema");
8317 const auto *AsBuiltin =
8318 RepresentationType.getCanonicalType()->castAs<BuiltinType>();
8319 // Recurse into the underlying type. Treat std::byte transparently as
8320 // unsigned char.
8321 return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
8322 }
8323
8324 std::optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
8325 size_t Size = Ty->getLimitedSize();
8326 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
8327
8328 APValue ArrayValue(APValue::UninitArray(), Size, Size);
8329 for (size_t I = 0; I != Size; ++I) {
8330 std::optional<APValue> ElementValue =
8331 visitType(Ty->getElementType(), Offset + I * ElementWidth);
8332 if (!ElementValue)
8333 return std::nullopt;
8334 ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
8335 }
8336
8337 return ArrayValue;
8338 }
8339
8340 std::optional<APValue> visit(const ComplexType *Ty, CharUnits Offset) {
8341 QualType ElementType = Ty->getElementType();
8342 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(ElementType);
8343 bool IsInt = ElementType->isIntegerType();
8344
8345 std::optional<APValue> Values[2];
8346 for (unsigned I = 0; I != 2; ++I) {
8347 Values[I] = visitType(Ty->getElementType(), Offset + I * ElementWidth);
8348 if (!Values[I])
8349 return std::nullopt;
8350 }
8351
8352 if (IsInt)
8353 return APValue(Values[0]->getInt(), Values[1]->getInt());
8354 return APValue(Values[0]->getFloat(), Values[1]->getFloat());
8355 }
8356
8357 std::optional<APValue> visit(const VectorType *VTy, CharUnits Offset) {
8358 QualType EltTy = VTy->getElementType();
8359 unsigned NElts = VTy->getNumElements();
8360 unsigned EltSize =
8361 VTy->isPackedVectorBoolType(Info.Ctx) ? 1 : Info.Ctx.getTypeSize(EltTy);
8362
8363 SmallVector<APValue, 4> Elts;
8364 Elts.reserve(NElts);
8365 if (VTy->isPackedVectorBoolType(Info.Ctx)) {
8366 // Special handling for OpenCL bool vectors:
8367 // Since these vectors are stored as packed bits, but we can't read
8368 // individual bits from the BitCastBuffer, we'll buffer all of the
8369 // elements together into an appropriately sized APInt and write them all
8370 // out at once. Because we don't accept vectors where NElts * EltSize
8371 // isn't a multiple of the char size, there will be no padding space, so
8372 // we don't have to worry about reading any padding data which didn't
8373 // actually need to be accessed.
8374 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
8375
8376 SmallVector<uint8_t, 8> Bytes;
8377 Bytes.reserve(NElts / 8);
8378 if (!Buffer.readObject(Offset, CharUnits::fromQuantity(NElts / 8), Bytes))
8379 return std::nullopt;
8380
8381 APSInt SValInt(NElts, true);
8382 llvm::LoadIntFromMemory(SValInt, &*Bytes.begin(), Bytes.size());
8383
8384 for (unsigned I = 0; I < NElts; ++I) {
8385 llvm::APInt Elt =
8386 SValInt.extractBits(1, (BigEndian ? NElts - I - 1 : I) * EltSize);
8387 Elts.emplace_back(
8388 APSInt(std::move(Elt), !EltTy->isSignedIntegerType()));
8389 }
8390 } else {
8391 // Iterate over each of the elements and read them from the buffer at
8392 // the appropriate offset.
8393 CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
8394 for (unsigned I = 0; I < NElts; ++I) {
8395 std::optional<APValue> EltValue =
8396 visitType(EltTy, Offset + I * EltSizeChars);
8397 if (!EltValue)
8398 return std::nullopt;
8399 Elts.push_back(std::move(*EltValue));
8400 }
8401 }
8402
8403 return APValue(Elts.data(), Elts.size());
8404 }
8405
8406 std::optional<APValue> visit(const Type *Ty, CharUnits Offset) {
8407 return unsupportedType(QualType(Ty, 0));
8408 }
8409
8410 std::optional<APValue> visitType(QualType Ty, CharUnits Offset) {
8411 QualType Can = Ty.getCanonicalType();
8412
8413 switch (Can->getTypeClass()) {
8414#define TYPE(Class, Base) \
8415 case Type::Class: \
8416 return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
8417#define ABSTRACT_TYPE(Class, Base)
8418#define NON_CANONICAL_TYPE(Class, Base) \
8419 case Type::Class: \
8420 llvm_unreachable("non-canonical type should be impossible!");
8421#define DEPENDENT_TYPE(Class, Base) \
8422 case Type::Class: \
8423 llvm_unreachable( \
8424 "dependent types aren't supported in the constant evaluator!");
8425#define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base) \
8426 case Type::Class: \
8427 llvm_unreachable("either dependent or not canonical!");
8428#include "clang/AST/TypeNodes.inc"
8429 }
8430 llvm_unreachable("Unhandled Type::TypeClass");
8431 }
8432
8433public:
8434 // Pull out a full value of type DstType.
8435 static std::optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
8436 const CastExpr *BCE) {
8437 BufferToAPValueConverter Converter(Info, Buffer, BCE);
8438 return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
8439 }
8440};
8441
8442static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
8443 QualType Ty, EvalInfo *Info,
8444 const ASTContext &Ctx,
8445 bool CheckingDest) {
8446 Ty = Ty.getCanonicalType();
8447
8448 auto diag = [&](int Reason) {
8449 if (Info)
8450 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
8451 << CheckingDest << (Reason == 4) << Reason;
8452 return false;
8453 };
8454 auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
8455 if (Info)
8456 Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
8457 << NoteTy << Construct << Ty;
8458 return false;
8459 };
8460
8461 if (Ty->isUnionType())
8462 return diag(0);
8463 if (Ty->isPointerType())
8464 return diag(1);
8465 if (Ty->isMemberPointerType())
8466 return diag(2);
8467 if (Ty.isVolatileQualified())
8468 return diag(3);
8469
8470 if (RecordDecl *Record = Ty->getAsRecordDecl()) {
8471 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
8472 for (CXXBaseSpecifier &BS : CXXRD->bases())
8473 if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
8474 CheckingDest))
8475 return note(1, BS.getType(), BS.getBeginLoc());
8476 }
8477 for (FieldDecl *FD : Record->fields()) {
8478 if (FD->getType()->isReferenceType())
8479 return diag(4);
8480 if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
8481 CheckingDest))
8482 return note(0, FD->getType(), FD->getBeginLoc());
8483 }
8484 }
8485
8486 if (Ty->isArrayType() &&
8487 !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
8488 Info, Ctx, CheckingDest))
8489 return false;
8490
8491 if (const auto *VTy = Ty->getAs<VectorType>()) {
8492 QualType EltTy = VTy->getElementType();
8493 unsigned NElts = VTy->getNumElements();
8494 unsigned EltSize =
8495 VTy->isPackedVectorBoolType(Ctx) ? 1 : Ctx.getTypeSize(EltTy);
8496
8497 if ((NElts * EltSize) % Ctx.getCharWidth() != 0) {
8498 // The vector's size in bits is not a multiple of the target's byte size,
8499 // so its layout is unspecified. For now, we'll simply treat these cases
8500 // as unsupported (this should only be possible with OpenCL bool vectors
8501 // whose element count isn't a multiple of the byte size).
8502 if (Info)
8503 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_vector)
8504 << QualType(VTy, 0) << EltSize << NElts << Ctx.getCharWidth();
8505 return false;
8506 }
8507
8508 if (EltTy->isRealFloatingType() &&
8509 &Ctx.getFloatTypeSemantics(EltTy) == &APFloat::x87DoubleExtended()) {
8510 // The layout for x86_fp80 vectors seems to be handled very inconsistently
8511 // by both clang and LLVM, so for now we won't allow bit_casts involving
8512 // it in a constexpr context.
8513 if (Info)
8514 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_unsupported_type)
8515 << EltTy;
8516 return false;
8517 }
8518 }
8519
8520 return true;
8521}
8522
8523static bool checkBitCastConstexprEligibility(EvalInfo *Info,
8524 const ASTContext &Ctx,
8525 const CastExpr *BCE) {
8526 bool DestOK = checkBitCastConstexprEligibilityType(
8527 BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
8528 bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
8529 BCE->getBeginLoc(),
8530 BCE->getSubExpr()->getType(), Info, Ctx, false);
8531 return SourceOK;
8532}
8533
8534static bool handleRValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
8535 const APValue &SourceRValue,
8536 const CastExpr *BCE) {
8537 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
8538 "no host or target supports non 8-bit chars");
8539
8540 if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
8541 return false;
8542
8543 // Read out SourceValue into a char buffer.
8544 std::optional<BitCastBuffer> Buffer =
8545 APValueToBufferConverter::convert(Info, SourceRValue, BCE);
8546 if (!Buffer)
8547 return false;
8548
8549 // Write out the buffer into a new APValue.
8550 std::optional<APValue> MaybeDestValue =
8551 BufferToAPValueConverter::convert(Info, *Buffer, BCE);
8552 if (!MaybeDestValue)
8553 return false;
8554
8555 DestValue = std::move(*MaybeDestValue);
8556 return true;
8557}
8558
8559static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
8560 APValue &SourceValue,
8561 const CastExpr *BCE) {
8562 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
8563 "no host or target supports non 8-bit chars");
8564 assert(SourceValue.isLValue() &&
8565 "LValueToRValueBitcast requires an lvalue operand!");
8566
8567 LValue SourceLValue;
8568 APValue SourceRValue;
8569 SourceLValue.setFrom(Info.Ctx, SourceValue);
8571 Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,
8572 SourceRValue, /*WantObjectRepresentation=*/true))
8573 return false;
8574
8575 return handleRValueToRValueBitCast(Info, DestValue, SourceRValue, BCE);
8576}
8577
8578template <class Derived>
8579class ExprEvaluatorBase
8580 : public ConstStmtVisitor<Derived, bool> {
8581private:
8582 Derived &getDerived() { return static_cast<Derived&>(*this); }
8583 bool DerivedSuccess(const APValue &V, const Expr *E) {
8584 return getDerived().Success(V, E);
8585 }
8586 bool DerivedZeroInitialization(const Expr *E) {
8587 return getDerived().ZeroInitialization(E);
8588 }
8589
8590 // Check whether a conditional operator with a non-constant condition is a
8591 // potential constant expression. If neither arm is a potential constant
8592 // expression, then the conditional operator is not either.
8593 template<typename ConditionalOperator>
8594 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
8595 assert(Info.checkingPotentialConstantExpression());
8596
8597 // Speculatively evaluate both arms.
8598 SmallVector<PartialDiagnosticAt, 8> Diag;
8599 {
8600 SpeculativeEvaluationRAII Speculate(Info, &Diag);
8601 StmtVisitorTy::Visit(E->getFalseExpr());
8602 if (Diag.empty())
8603 return;
8604 }
8605
8606 {
8607 SpeculativeEvaluationRAII Speculate(Info, &Diag);
8608 Diag.clear();
8609 Info.EvalStatus.DiagEmitted = false;
8610 StmtVisitorTy::Visit(E->getTrueExpr());
8611 if (Diag.empty())
8612 return;
8613 }
8614
8615 Error(E, diag::note_constexpr_conditional_never_const);
8616 }
8617
8618
8619 template<typename ConditionalOperator>
8620 bool HandleConditionalOperator(const ConditionalOperator *E) {
8621 bool BoolResult;
8622 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
8623 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
8624 CheckPotentialConstantConditional(E);
8625 return false;
8626 }
8627 if (Info.noteFailure()) {
8628 StmtVisitorTy::Visit(E->getTrueExpr());
8629 StmtVisitorTy::Visit(E->getFalseExpr());
8630 }
8631 return false;
8632 }
8633
8634 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
8635 return StmtVisitorTy::Visit(EvalExpr);
8636 }
8637
8638protected:
8639 EvalInfo &Info;
8640 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
8641 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
8642
8643 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
8644 return Info.CCEDiag(E, D);
8645 }
8646
8647 bool ZeroInitialization(const Expr *E) { return Error(E); }
8648
8649 bool IsConstantEvaluatedBuiltinCall(const CallExpr *E) {
8650 unsigned BuiltinOp = E->getBuiltinCallee();
8651 return BuiltinOp != 0 &&
8652 Info.Ctx.BuiltinInfo.isConstantEvaluated(BuiltinOp);
8653 }
8654
8655public:
8656 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
8657
8658 EvalInfo &getEvalInfo() { return Info; }
8659
8660 /// Report an evaluation error. This should only be called when an error is
8661 /// first discovered. When propagating an error, just return false.
8662 bool Error(const Expr *E, diag::kind D) {
8663 Info.FFDiag(E, D) << E->getSourceRange();
8664 return false;
8665 }
8666 bool Error(const Expr *E) {
8667 return Error(E, diag::note_invalid_subexpr_in_const_expr);
8668 }
8669
8670 bool VisitStmt(const Stmt *) {
8671 llvm_unreachable("Expression evaluator should not be called on stmts");
8672 }
8673 bool VisitExpr(const Expr *E) {
8674 return Error(E);
8675 }
8676
8677 bool VisitEmbedExpr(const EmbedExpr *E) {
8678 const auto It = E->begin();
8679 return StmtVisitorTy::Visit(*It);
8680 }
8681
8682 bool VisitPredefinedExpr(const PredefinedExpr *E) {
8683 return StmtVisitorTy::Visit(E->getFunctionName());
8684 }
8685 bool VisitConstantExpr(const ConstantExpr *E) {
8686 if (E->hasAPValueResult())
8687 return DerivedSuccess(E->getAPValueResult(), E);
8688
8689 return StmtVisitorTy::Visit(E->getSubExpr());
8690 }
8691
8692 bool VisitParenExpr(const ParenExpr *E)
8693 { return StmtVisitorTy::Visit(E->getSubExpr()); }
8694 bool VisitUnaryExtension(const UnaryOperator *E)
8695 { return StmtVisitorTy::Visit(E->getSubExpr()); }
8696 bool VisitUnaryPlus(const UnaryOperator *E)
8697 { return StmtVisitorTy::Visit(E->getSubExpr()); }
8698 bool VisitChooseExpr(const ChooseExpr *E)
8699 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
8700 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
8701 { return StmtVisitorTy::Visit(E->getResultExpr()); }
8702 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
8703 { return StmtVisitorTy::Visit(E->getReplacement()); }
8704 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
8705 TempVersionRAII RAII(*Info.CurrentCall);
8706 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
8707 return StmtVisitorTy::Visit(E->getExpr());
8708 }
8709 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
8710 TempVersionRAII RAII(*Info.CurrentCall);
8711 // The initializer may not have been parsed yet, or might be erroneous.
8712 if (!E->getExpr())
8713 return Error(E);
8714 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
8715 return StmtVisitorTy::Visit(E->getExpr());
8716 }
8717
8718 bool VisitExprWithCleanups(const ExprWithCleanups *E) {
8719 FullExpressionRAII Scope(Info);
8720 return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy();
8721 }
8722
8723 // Temporaries are registered when created, so we don't care about
8724 // CXXBindTemporaryExpr.
8725 bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
8726 return StmtVisitorTy::Visit(E->getSubExpr());
8727 }
8728
8729 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
8730 if (E->getCastKind() != CK_PointerToIntegral)
8731 CCEDiag(E, diag::note_constexpr_invalid_cast)
8732 << diag::ConstexprInvalidCastKind::Reinterpret;
8733 return static_cast<Derived*>(this)->VisitCastExpr(E);
8734 }
8735 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
8736 if (!Info.Ctx.getLangOpts().CPlusPlus20)
8737 CCEDiag(E, diag::note_constexpr_invalid_cast)
8738 << diag::ConstexprInvalidCastKind::Dynamic;
8739 return static_cast<Derived*>(this)->VisitCastExpr(E);
8740 }
8741 bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
8742 return static_cast<Derived*>(this)->VisitCastExpr(E);
8743 }
8744
8745 bool VisitBinaryOperator(const BinaryOperator *E) {
8746 switch (E->getOpcode()) {
8747 default:
8748 return Error(E);
8749
8750 case BO_Comma:
8751 VisitIgnoredValue(E->getLHS());
8752 return StmtVisitorTy::Visit(E->getRHS());
8753
8754 case BO_PtrMemD:
8755 case BO_PtrMemI: {
8756 LValue Obj;
8757 if (!HandleMemberPointerAccess(Info, E, Obj))
8758 return false;
8760 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
8761 return false;
8762 return DerivedSuccess(Result, E);
8763 }
8764 }
8765 }
8766
8767 bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) {
8768 return StmtVisitorTy::Visit(E->getSemanticForm());
8769 }
8770
8771 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
8772 // Evaluate and cache the common expression. We treat it as a temporary,
8773 // even though it's not quite the same thing.
8774 LValue CommonLV;
8775 if (!Evaluate(Info.CurrentCall->createTemporary(
8776 E->getOpaqueValue(),
8777 getStorageType(Info.Ctx, E->getOpaqueValue()),
8778 ScopeKind::FullExpression, CommonLV),
8779 Info, E->getCommon()))
8780 return false;
8781
8782 return HandleConditionalOperator(E);
8783 }
8784
8785 bool VisitConditionalOperator(const ConditionalOperator *E) {
8786 bool IsBcpCall = false;
8787 // If the condition (ignoring parens) is a __builtin_constant_p call,
8788 // the result is a constant expression if it can be folded without
8789 // side-effects. This is an important GNU extension. See GCC PR38377
8790 // for discussion.
8791 if (const CallExpr *CallCE =
8792 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
8793 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
8794 IsBcpCall = true;
8795
8796 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
8797 // constant expression; we can't check whether it's potentially foldable.
8798 // FIXME: We should instead treat __builtin_constant_p as non-constant if
8799 // it would return 'false' in this mode.
8800 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
8801 return false;
8802
8803 FoldConstant Fold(Info, IsBcpCall);
8804 if (!HandleConditionalOperator(E)) {
8805 Fold.keepDiagnostics();
8806 return false;
8807 }
8808
8809 return true;
8810 }
8811
8812 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
8813 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E);
8814 Value && !Value->isAbsent())
8815 return DerivedSuccess(*Value, E);
8816
8817 const Expr *Source = E->getSourceExpr();
8818 if (!Source)
8819 return Error(E);
8820 if (Source == E) {
8821 assert(0 && "OpaqueValueExpr recursively refers to itself");
8822 return Error(E);
8823 }
8824 return StmtVisitorTy::Visit(Source);
8825 }
8826
8827 bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
8828 for (const Expr *SemE : E->semantics()) {
8829 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
8830 // FIXME: We can't handle the case where an OpaqueValueExpr is also the
8831 // result expression: there could be two different LValues that would
8832 // refer to the same object in that case, and we can't model that.
8833 if (SemE == E->getResultExpr())
8834 return Error(E);
8835
8836 // Unique OVEs get evaluated if and when we encounter them when
8837 // emitting the rest of the semantic form, rather than eagerly.
8838 if (OVE->isUnique())
8839 continue;
8840
8841 LValue LV;
8842 if (!Evaluate(Info.CurrentCall->createTemporary(
8843 OVE, getStorageType(Info.Ctx, OVE),
8844 ScopeKind::FullExpression, LV),
8845 Info, OVE->getSourceExpr()))
8846 return false;
8847 } else if (SemE == E->getResultExpr()) {
8848 if (!StmtVisitorTy::Visit(SemE))
8849 return false;
8850 } else {
8851 if (!EvaluateIgnoredValue(Info, SemE))
8852 return false;
8853 }
8854 }
8855 return true;
8856 }
8857
8858 bool VisitCallExpr(const CallExpr *E) {
8860 if (!handleCallExpr(E, Result, nullptr))
8861 return false;
8862 return DerivedSuccess(Result, E);
8863 }
8864
8865 bool handleCallExpr(const CallExpr *E, APValue &Result,
8866 const LValue *ResultSlot) {
8867 CallScopeRAII CallScope(Info);
8868
8869 const Expr *Callee = E->getCallee()->IgnoreParens();
8870 QualType CalleeType = Callee->getType();
8871
8872 const FunctionDecl *FD = nullptr;
8873 LValue *This = nullptr, ObjectArg;
8874 auto Args = ArrayRef(E->getArgs(), E->getNumArgs());
8875 bool HasQualifier = false;
8876
8877 CallRef Call;
8878
8879 // Extract function decl and 'this' pointer from the callee.
8880 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
8881 const CXXMethodDecl *Member = nullptr;
8882 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
8883 // Explicit bound member calls, such as x.f() or p->g();
8884 if (!EvaluateObjectArgument(Info, ME->getBase(), ObjectArg))
8885 return false;
8886 Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
8887 if (!Member)
8888 return Error(Callee);
8889 This = &ObjectArg;
8890 HasQualifier = ME->hasQualifier();
8891 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
8892 // Indirect bound member calls ('.*' or '->*').
8893 const ValueDecl *D =
8894 HandleMemberPointerAccess(Info, BE, ObjectArg, false);
8895 if (!D)
8896 return false;
8897 Member = dyn_cast<CXXMethodDecl>(D);
8898 if (!Member)
8899 return Error(Callee);
8900 This = &ObjectArg;
8901 } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
8902 if (!Info.getLangOpts().CPlusPlus20)
8903 Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
8904 return EvaluateObjectArgument(Info, PDE->getBase(), ObjectArg) &&
8905 HandleDestruction(Info, PDE, ObjectArg, PDE->getDestroyedType());
8906 } else
8907 return Error(Callee);
8908 FD = Member;
8909 } else if (CalleeType->isFunctionPointerType()) {
8910 LValue CalleeLV;
8911 if (!EvaluatePointer(Callee, CalleeLV, Info))
8912 return false;
8913
8914 if (!CalleeLV.getLValueOffset().isZero())
8915 return Error(Callee);
8916 if (CalleeLV.isNullPointer()) {
8917 Info.FFDiag(Callee, diag::note_constexpr_null_callee)
8918 << const_cast<Expr *>(Callee);
8919 return false;
8920 }
8921 FD = dyn_cast_or_null<FunctionDecl>(
8922 CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>());
8923 if (!FD)
8924 return Error(Callee);
8925 // Don't call function pointers which have been cast to some other type.
8926 // Per DR (no number yet), the caller and callee can differ in noexcept.
8927 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
8928 CalleeType->getPointeeType(), FD->getType())) {
8929 return Error(E);
8930 }
8931
8932 // For an (overloaded) assignment expression, evaluate the RHS before the
8933 // LHS.
8934 auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
8935 if (OCE && OCE->isAssignmentOp()) {
8936 assert(Args.size() == 2 && "wrong number of arguments in assignment");
8937 Call = Info.CurrentCall->createCall(FD);
8938 bool HasThis = false;
8939 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
8940 HasThis = MD->isImplicitObjectMemberFunction();
8941 if (!EvaluateArgs(HasThis ? Args.slice(1) : Args, Call, Info, FD,
8942 /*RightToLeft=*/true, &ObjectArg))
8943 return false;
8944 }
8945
8946 // Overloaded operator calls to member functions are represented as normal
8947 // calls with '*this' as the first argument.
8948 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8949 if (MD &&
8950 (MD->isImplicitObjectMemberFunction() || (OCE && MD->isStatic()))) {
8951 // FIXME: When selecting an implicit conversion for an overloaded
8952 // operator delete, we sometimes try to evaluate calls to conversion
8953 // operators without a 'this' parameter!
8954 if (Args.empty())
8955 return Error(E);
8956
8957 if (!EvaluateObjectArgument(Info, Args[0], ObjectArg))
8958 return false;
8959
8960 // If we are calling a static operator, the 'this' argument needs to be
8961 // ignored after being evaluated.
8962 if (MD->isInstance())
8963 This = &ObjectArg;
8964
8965 // If this is syntactically a simple assignment using a trivial
8966 // assignment operator, start the lifetimes of union members as needed,
8967 // per C++20 [class.union]5.
8968 if (Info.getLangOpts().CPlusPlus20 && OCE &&
8969 OCE->getOperator() == OO_Equal && MD->isTrivial() &&
8970 !MaybeHandleUnionActiveMemberChange(Info, Args[0], ObjectArg))
8971 return false;
8972
8973 Args = Args.slice(1);
8974 } else if (MD && MD->isLambdaStaticInvoker()) {
8975 // Map the static invoker for the lambda back to the call operator.
8976 // Conveniently, we don't have to slice out the 'this' argument (as is
8977 // being done for the non-static case), since a static member function
8978 // doesn't have an implicit argument passed in.
8979 const CXXRecordDecl *ClosureClass = MD->getParent();
8980 assert(
8981 ClosureClass->captures().empty() &&
8982 "Number of captures must be zero for conversion to function-ptr");
8983
8984 const CXXMethodDecl *LambdaCallOp =
8985 ClosureClass->getLambdaCallOperator();
8986
8987 // Set 'FD', the function that will be called below, to the call
8988 // operator. If the closure object represents a generic lambda, find
8989 // the corresponding specialization of the call operator.
8990
8991 if (ClosureClass->isGenericLambda()) {
8992 assert(MD->isFunctionTemplateSpecialization() &&
8993 "A generic lambda's static-invoker function must be a "
8994 "template specialization");
8995 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
8996 FunctionTemplateDecl *CallOpTemplate =
8997 LambdaCallOp->getDescribedFunctionTemplate();
8998 llvm::FoldingSetInsertToken InsertToken;
8999 FunctionDecl *CorrespondingCallOpSpecialization =
9000 CallOpTemplate->findSpecialization(TAL->asArray(), InsertToken);
9001 assert(CorrespondingCallOpSpecialization &&
9002 "We must always have a function call operator specialization "
9003 "that corresponds to our static invoker specialization");
9004 assert(isa<CXXMethodDecl>(CorrespondingCallOpSpecialization));
9005 FD = CorrespondingCallOpSpecialization;
9006 } else
9007 FD = LambdaCallOp;
9009 if (FD->getDeclName().isAnyOperatorNew()) {
9010 LValue Ptr;
9011 if (!HandleOperatorNewCall(Info, E, Ptr))
9012 return false;
9013 Ptr.moveInto(Result);
9014 return CallScope.destroy();
9015 } else {
9016 return HandleOperatorDeleteCall(Info, E) && CallScope.destroy();
9017 }
9018 }
9019 } else
9020 return Error(E);
9021
9022 // Evaluate the arguments now if we've not already done so.
9023 if (!Call) {
9024 Call = Info.CurrentCall->createCall(FD);
9025 if (!EvaluateArgs(Args, Call, Info, FD, /*RightToLeft*/ false,
9026 &ObjectArg))
9027 return false;
9028 }
9029
9030 SmallVector<QualType, 4> CovariantAdjustmentPath;
9031 if (This) {
9032 auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
9033 if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
9034 // Perform virtual dispatch, if necessary.
9035 FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
9036 CovariantAdjustmentPath);
9037 if (!FD)
9038 return false;
9039 } else if (NamedMember && NamedMember->isImplicitObjectMemberFunction()) {
9040 // Check that the 'this' pointer points to an object of the right type.
9041 // FIXME: If this is an assignment operator call, we may need to change
9042 // the active union member before we check this.
9043 if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
9044 return false;
9045 }
9046 }
9047
9048 // Destructor calls are different enough that they have their own codepath.
9049 if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
9050 assert(This && "no 'this' pointer for destructor call");
9051 return HandleDestruction(Info, E, *This,
9052 Info.Ctx.getCanonicalTagType(DD->getParent())) &&
9053 CallScope.destroy();
9054 }
9055
9056 const FunctionDecl *Definition = nullptr;
9057 Stmt *Body = FD->getBody(Definition);
9058 SourceLocation Loc = E->getExprLoc();
9059
9060 // Treat the object argument as `this` when evaluating defaulted
9061 // special menmber functions
9063 This = &ObjectArg;
9064
9065 if (!CheckConstexprFunction(Info, Loc, FD, Definition, Body) ||
9066 !HandleFunctionCall(Loc, Definition, This, E, Args, Call, Body, Info,
9067 Result, ResultSlot))
9068 return false;
9069
9070 if (!CovariantAdjustmentPath.empty() &&
9072 CovariantAdjustmentPath))
9073 return false;
9074
9075 return CallScope.destroy();
9076 }
9077
9078 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
9079 return StmtVisitorTy::Visit(E->getInitializer());
9080 }
9081 bool VisitInitListExpr(const InitListExpr *E) {
9082 if (E->getNumInits() == 0)
9083 return DerivedZeroInitialization(E);
9084 if (E->getNumInits() == 1)
9085 return StmtVisitorTy::Visit(E->getInit(0));
9086 return Error(E);
9087 }
9088 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
9089 return DerivedZeroInitialization(E);
9090 }
9091 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
9092 return DerivedZeroInitialization(E);
9093 }
9094 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
9095 return DerivedZeroInitialization(E);
9096 }
9097
9098 /// A member expression where the object is a prvalue is itself a prvalue.
9099 bool VisitMemberExpr(const MemberExpr *E) {
9100 assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
9101 "missing temporary materialization conversion");
9102 assert(!E->isArrow() && "missing call to bound member function?");
9103
9104 APValue Val;
9105 if (!Evaluate(Val, Info, E->getBase()))
9106 return false;
9107
9108 QualType BaseTy = E->getBase()->getType();
9109
9110 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
9111 if (!FD) return Error(E);
9112 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
9113 assert(BaseTy->castAsCanonical<RecordType>()->getDecl() ==
9114 FD->getParent()->getCanonicalDecl() &&
9115 "record / field mismatch");
9116
9117 // Note: there is no lvalue base here. But this case should only ever
9118 // happen in C or in C++98, where we cannot be evaluating a constexpr
9119 // constructor, which is the only case the base matters.
9120 CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
9121 SubobjectDesignator Designator(BaseTy);
9122 Designator.addDeclUnchecked(FD);
9123
9125 return extractSubobject(Info, E, Obj, Designator, Result) &&
9126 DerivedSuccess(Result, E);
9127 }
9128
9129 bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) {
9130 APValue Val;
9131 if (!Evaluate(Val, Info, E->getBase()))
9132 return false;
9133
9134 if (Val.isVector()) {
9135 SmallVector<uint32_t, 4> Indices;
9136 E->getEncodedElementAccess(Indices);
9137 if (Indices.size() == 1) {
9138 // Return scalar.
9139 return DerivedSuccess(Val.getVectorElt(Indices[0]), E);
9140 } else {
9141 // Construct new APValue vector.
9142 SmallVector<APValue, 4> Elts;
9143 for (unsigned I = 0; I < Indices.size(); ++I) {
9144 Elts.push_back(Val.getVectorElt(Indices[I]));
9145 }
9146 APValue VecResult(Elts.data(), Indices.size());
9147 return DerivedSuccess(VecResult, E);
9148 }
9149 }
9150
9151 return false;
9152 }
9153
9154 bool VisitCastExpr(const CastExpr *E) {
9155 switch (E->getCastKind()) {
9156 default:
9157 break;
9158
9159 case CK_AtomicToNonAtomic: {
9160 APValue AtomicVal;
9161 // This does not need to be done in place even for class/array types:
9162 // atomic-to-non-atomic conversion implies copying the object
9163 // representation.
9164 if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
9165 return false;
9166 return DerivedSuccess(AtomicVal, E);
9167 }
9168
9169 case CK_NoOp:
9170 case CK_UserDefinedConversion:
9171 return StmtVisitorTy::Visit(E->getSubExpr());
9172
9173 case CK_HLSLArrayRValue: {
9174 const Expr *SubExpr = E->getSubExpr();
9175 if (!SubExpr->isGLValue()) {
9176 APValue Val;
9177 if (!Evaluate(Val, Info, SubExpr))
9178 return false;
9179 return DerivedSuccess(Val, E);
9180 }
9181
9182 LValue LVal;
9183 if (!EvaluateLValue(SubExpr, LVal, Info))
9184 return false;
9185 APValue RVal;
9186 // Note, we use the subexpression's type in order to retain cv-qualifiers.
9187 if (!handleLValueToRValueConversion(Info, E, SubExpr->getType(), LVal,
9188 RVal))
9189 return false;
9190 return DerivedSuccess(RVal, E);
9191 }
9192 case CK_LValueToRValue: {
9193 LValue LVal;
9194 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
9195 return false;
9196 APValue RVal;
9197 // Note, we use the subexpression's type in order to retain cv-qualifiers.
9199 LVal, RVal))
9200 return false;
9201 return DerivedSuccess(RVal, E);
9202 }
9203 case CK_LValueToRValueBitCast: {
9204 APValue DestValue, SourceValue;
9205 if (!Evaluate(SourceValue, Info, E->getSubExpr()))
9206 return false;
9207 if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
9208 return false;
9209 return DerivedSuccess(DestValue, E);
9210 }
9211
9212 case CK_AddressSpaceConversion: {
9213 APValue Value;
9214 if (!Evaluate(Value, Info, E->getSubExpr()))
9215 return false;
9216 return DerivedSuccess(Value, E);
9217 }
9218 }
9219
9220 return Error(E);
9221 }
9222
9223 bool VisitUnaryPostInc(const UnaryOperator *UO) {
9224 return VisitUnaryPostIncDec(UO);
9225 }
9226 bool VisitUnaryPostDec(const UnaryOperator *UO) {
9227 return VisitUnaryPostIncDec(UO);
9228 }
9229 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
9230 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9231 return Error(UO);
9232
9233 LValue LVal;
9234 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
9235 return false;
9236 APValue RVal;
9237 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
9238 UO->isIncrementOp(), &RVal))
9239 return false;
9240 return DerivedSuccess(RVal, UO);
9241 }
9242
9243 bool VisitStmtExpr(const StmtExpr *E) {
9244 // We will have checked the full-expressions inside the statement expression
9245 // when they were completed, and don't need to check them again now.
9246 llvm::SaveAndRestore NotCheckingForUB(Info.CheckingForUndefinedBehavior,
9247 false);
9248
9249 const CompoundStmt *CS = E->getSubStmt();
9250 if (CS->body_empty())
9251 return true;
9252
9253 BlockScopeRAII Scope(Info);
9255 BE = CS->body_end();
9256 /**/; ++BI) {
9257 if (BI + 1 == BE) {
9258 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
9259 if (!FinalExpr) {
9260 Info.FFDiag((*BI)->getBeginLoc(),
9261 diag::note_constexpr_stmt_expr_unsupported);
9262 return false;
9263 }
9264 return this->Visit(FinalExpr) && Scope.destroy();
9265 }
9266
9268 StmtResult Result = { ReturnValue, nullptr };
9269 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
9270 if (ESR != ESR_Succeeded) {
9271 // FIXME: If the statement-expression terminated due to 'return',
9272 // 'break', or 'continue', it would be nice to propagate that to
9273 // the outer statement evaluation rather than bailing out.
9274 if (ESR != ESR_Failed)
9275 Info.FFDiag((*BI)->getBeginLoc(),
9276 diag::note_constexpr_stmt_expr_unsupported);
9277 return false;
9278 }
9279 }
9280
9281 llvm_unreachable("Return from function from the loop above.");
9282 }
9283
9284 bool VisitPackIndexingExpr(const PackIndexingExpr *E) {
9285 return StmtVisitorTy::Visit(E->getSelectedExpr());
9286 }
9287
9288 /// Visit a value which is evaluated, but whose value is ignored.
9289 void VisitIgnoredValue(const Expr *E) {
9290 EvaluateIgnoredValue(Info, E);
9291 }
9292
9293 /// Potentially visit a MemberExpr's base expression.
9294 void VisitIgnoredBaseExpression(const Expr *E) {
9295 // While MSVC doesn't evaluate the base expression, it does diagnose the
9296 // presence of side-effecting behavior.
9297 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
9298 return;
9299 VisitIgnoredValue(E);
9300 }
9301};
9302
9303} // namespace
9304
9305//===----------------------------------------------------------------------===//
9306// Common base class for lvalue and temporary evaluation.
9307//===----------------------------------------------------------------------===//
9308namespace {
9309template<class Derived>
9310class LValueExprEvaluatorBase
9311 : public ExprEvaluatorBase<Derived> {
9312protected:
9313 LValue &Result;
9314 bool InvalidBaseOK;
9315 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
9316 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
9317
9318 bool Success(APValue::LValueBase B) {
9319 Result.set(B);
9320 return true;
9321 }
9322
9323 bool evaluatePointer(const Expr *E, LValue &Result) {
9324 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
9325 }
9326
9327public:
9328 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
9329 : ExprEvaluatorBaseTy(Info), Result(Result),
9330 InvalidBaseOK(InvalidBaseOK) {}
9331
9332 bool Success(const APValue &V, const Expr *E) {
9333 Result.setFrom(this->Info.Ctx, V);
9334 return true;
9335 }
9336
9337 bool VisitMemberExpr(const MemberExpr *E) {
9338 // Handle non-static data members.
9339 QualType BaseTy;
9340 bool EvalOK;
9341 if (E->isArrow()) {
9342 EvalOK = evaluatePointer(E->getBase(), Result);
9343 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
9344 } else if (E->getBase()->isPRValue()) {
9345 assert(E->getBase()->getType()->isRecordType());
9346 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
9347 BaseTy = E->getBase()->getType();
9348 } else {
9349 EvalOK = this->Visit(E->getBase());
9350 BaseTy = E->getBase()->getType();
9351 }
9352 if (!EvalOK) {
9353 if (!InvalidBaseOK)
9354 return false;
9355 Result.setInvalid(E);
9356 return true;
9357 }
9358
9359 const ValueDecl *MD = E->getMemberDecl();
9360 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
9361 assert(BaseTy->castAsCanonical<RecordType>()->getDecl() ==
9362 FD->getParent()->getCanonicalDecl() &&
9363 "record / field mismatch");
9364 (void)BaseTy;
9365 if (!HandleLValueMember(this->Info, E, Result, FD))
9366 return false;
9367 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
9368 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
9369 return false;
9370 } else
9371 return this->Error(E);
9372
9373 if (MD->getType()->isReferenceType()) {
9374 APValue RefValue;
9375 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
9376 RefValue))
9377 return false;
9378 return Success(RefValue, E);
9379 }
9380 return true;
9381 }
9382
9383 bool VisitBinaryOperator(const BinaryOperator *E) {
9384 switch (E->getOpcode()) {
9385 default:
9386 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9387
9388 case BO_PtrMemD:
9389 case BO_PtrMemI:
9390 return HandleMemberPointerAccess(this->Info, E, Result);
9391 }
9392 }
9393
9394 bool VisitCastExpr(const CastExpr *E) {
9395 switch (E->getCastKind()) {
9396 default:
9397 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9398
9399 case CK_DerivedToBase:
9400 case CK_UncheckedDerivedToBase:
9401 if (!this->Visit(E->getSubExpr()))
9402 return false;
9403
9404 // Now figure out the necessary offset to add to the base LV to get from
9405 // the derived class to the base class.
9406 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
9407 Result);
9408 }
9409 }
9410};
9411}
9412
9413//===----------------------------------------------------------------------===//
9414// LValue Evaluation
9415//
9416// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
9417// function designators (in C), decl references to void objects (in C), and
9418// temporaries (if building with -Wno-address-of-temporary).
9419//
9420// LValue evaluation produces values comprising a base expression of one of the
9421// following types:
9422// - Declarations
9423// * VarDecl
9424// * FunctionDecl
9425// - Literals
9426// * CompoundLiteralExpr in C (and in global scope in C++)
9427// * StringLiteral
9428// * PredefinedExpr
9429// * ObjCStringLiteralExpr
9430// * ObjCEncodeExpr
9431// * AddrLabelExpr
9432// * BlockExpr
9433// * CallExpr for a MakeStringConstant builtin
9434// - typeid(T) expressions, as TypeInfoLValues
9435// - Locals and temporaries
9436// * MaterializeTemporaryExpr
9437// * Any Expr, with a CallIndex indicating the function in which the temporary
9438// was evaluated, for cases where the MaterializeTemporaryExpr is missing
9439// from the AST (FIXME).
9440// * A MaterializeTemporaryExpr that has static storage duration, with no
9441// CallIndex, for a lifetime-extended temporary.
9442// * The ConstantExpr that is currently being evaluated during evaluation of an
9443// immediate invocation.
9444// plus an offset in bytes.
9445//===----------------------------------------------------------------------===//
9446namespace {
9447class LValueExprEvaluator
9448 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
9449public:
9450 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
9451 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
9452
9453 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
9454 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
9455
9456 bool VisitCallExpr(const CallExpr *E);
9457 bool VisitDeclRefExpr(const DeclRefExpr *E);
9458 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
9459 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
9460 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
9461 bool VisitMemberExpr(const MemberExpr *E);
9462 bool VisitStringLiteral(const StringLiteral *E) {
9463 return Success(
9464 APValue::LValueBase(E, 0, Info.Ctx.getNextStringLiteralVersion()));
9465 }
9466 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
9467 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
9468 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
9469 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
9470 bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E);
9471 bool VisitUnaryDeref(const UnaryOperator *E);
9472 bool VisitUnaryReal(const UnaryOperator *E);
9473 bool VisitUnaryImag(const UnaryOperator *E);
9474 bool VisitUnaryPreInc(const UnaryOperator *UO) {
9475 return VisitUnaryPreIncDec(UO);
9476 }
9477 bool VisitUnaryPreDec(const UnaryOperator *UO) {
9478 return VisitUnaryPreIncDec(UO);
9479 }
9480 bool VisitBinAssign(const BinaryOperator *BO);
9481 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
9482
9483 bool VisitCastExpr(const CastExpr *E) {
9484 switch (E->getCastKind()) {
9485 default:
9486 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
9487
9488 case CK_LValueBitCast:
9489 this->CCEDiag(E, diag::note_constexpr_invalid_cast)
9490 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
9491 << Info.Ctx.getLangOpts().CPlusPlus << E->getSourceRange();
9492 if (!Visit(E->getSubExpr()))
9493 return false;
9494 Result.Designator.setInvalid();
9495 return true;
9496
9497 case CK_BaseToDerived:
9498 if (!Visit(E->getSubExpr()))
9499 return false;
9500 return HandleBaseToDerivedCast(Info, E, Result);
9501
9502 case CK_Dynamic:
9503 if (!Visit(E->getSubExpr()))
9504 return false;
9506 }
9507 }
9508};
9509} // end anonymous namespace
9510
9511/// Get an lvalue to a field of a lambda's closure type.
9512static bool HandleLambdaCapture(EvalInfo &Info, const Expr *E, LValue &Result,
9513 const CXXMethodDecl *MD, const FieldDecl *FD,
9514 bool LValueToRValueConversion) {
9515 // Static lambda function call operators can't have captures. We already
9516 // diagnosed this, so bail out here.
9517 if (MD->isStatic()) {
9518 assert(Info.CurrentCall->This == nullptr &&
9519 "This should not be set for a static call operator");
9520 return false;
9521 }
9522
9523 // Start with 'Result' referring to the complete closure object...
9525 // Self may be passed by reference or by value.
9526 const ParmVarDecl *Self = MD->getParamDecl(0);
9527 if (Self->getType()->isReferenceType()) {
9528 APValue *RefValue = Info.getParamSlot(Info.CurrentCall->Arguments, Self);
9529 if (!RefValue->allowConstexprUnknown() || RefValue->hasValue())
9530 Result.setFrom(Info.Ctx, *RefValue);
9531 } else {
9532 const ParmVarDecl *VD = Info.CurrentCall->Arguments.getOrigParam(Self);
9533 CallStackFrame *Frame =
9534 Info.getCallFrameAndDepth(Info.CurrentCall->Arguments.CallIndex)
9535 .first;
9536 unsigned Version = Info.CurrentCall->Arguments.Version;
9537 Result.set({VD, Frame->Index, Version});
9538 }
9539 } else
9540 Result = *Info.CurrentCall->This;
9541
9542 // ... then update it to refer to the field of the closure object
9543 // that represents the capture.
9544 if (!HandleLValueMember(Info, E, Result, FD))
9545 return false;
9546
9547 // And if the field is of reference type (or if we captured '*this' by
9548 // reference), update 'Result' to refer to what
9549 // the field refers to.
9550 if (LValueToRValueConversion) {
9551 APValue RVal;
9552 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result, RVal))
9553 return false;
9554 Result.setFrom(Info.Ctx, RVal);
9555 }
9556 return true;
9557}
9558
9559/// Evaluate an expression as an lvalue. This can be legitimately called on
9560/// expressions which are not glvalues, in three cases:
9561/// * function designators in C, and
9562/// * "extern void" objects
9563/// * @selector() expressions in Objective-C
9564static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
9565 bool InvalidBaseOK) {
9566 assert(!E->isValueDependent());
9567 assert(E->isGLValue() || E->getType()->isFunctionType() ||
9569 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
9570}
9571
9572bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
9573 const ValueDecl *D = E->getDecl();
9574
9575 // If we are within a lambda's call operator, check whether the 'VD' referred
9576 // to within 'E' actually represents a lambda-capture that maps to a
9577 // data-member/field within the closure object, and if so, evaluate to the
9578 // field or what the field refers to.
9579 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
9581 // We don't always have a complete capture-map when checking or inferring if
9582 // the function call operator meets the requirements of a constexpr function
9583 // - but we don't need to evaluate the captures to determine constexprness
9584 // (dcl.constexpr C++17).
9585 if (Info.checkingPotentialConstantExpression())
9586 return false;
9587
9588 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(D)) {
9589 const auto *MD = cast<CXXMethodDecl>(Info.CurrentCall->Callee);
9590 return HandleLambdaCapture(Info, E, Result, MD, FD,
9591 FD->getType()->isReferenceType());
9592 }
9593 }
9594
9595 if (isa<FunctionDecl, MSGuidDecl, TemplateParamObjectDecl,
9596 UnnamedGlobalConstantDecl>(D))
9597 return Success(cast<ValueDecl>(D));
9598 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
9599 return VisitVarDecl(E, VD);
9600 if (const BindingDecl *BD = dyn_cast<BindingDecl>(D))
9601 return Visit(BD->getBinding());
9602 return Error(E);
9603}
9604
9605bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
9606 CallStackFrame *Frame = nullptr;
9607 unsigned Version = 0;
9608 if (VD->hasLocalStorage()) {
9609 // Only if a local variable was declared in the function currently being
9610 // evaluated, do we expect to be able to find its value in the current
9611 // frame. (Otherwise it was likely declared in an enclosing context and
9612 // could either have a valid evaluatable value (for e.g. a constexpr
9613 // variable) or be ill-formed (and trigger an appropriate evaluation
9614 // diagnostic)).
9615 CallStackFrame *CurrFrame = Info.CurrentCall;
9616 if (CurrFrame->Callee && CurrFrame->Callee->Equals(VD->getDeclContext())) {
9617 // Function parameters are stored in some caller's frame. (Usually the
9618 // immediate caller, but for an inherited constructor they may be more
9619 // distant.)
9620 if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) {
9621 if (CurrFrame->Arguments) {
9622 VD = CurrFrame->Arguments.getOrigParam(PVD);
9623 Frame =
9624 Info.getCallFrameAndDepth(CurrFrame->Arguments.CallIndex).first;
9625 Version = CurrFrame->Arguments.Version;
9626 }
9627 } else {
9628 Frame = CurrFrame;
9629 Version = CurrFrame->getCurrentTemporaryVersion(VD);
9630 }
9631 }
9632 }
9633
9634 if (!VD->getType()->isReferenceType()) {
9635 if (Frame) {
9636 Result.set({VD, Frame->Index, Version});
9637 return true;
9638 }
9639 return Success(VD);
9640 }
9641
9642 if (!Info.getLangOpts().CPlusPlus11) {
9643 Info.CCEDiag(E, diag::note_constexpr_ltor_non_integral, 1)
9644 << VD << VD->getType();
9645 Info.Note(VD->getLocation(), diag::note_declared_at);
9646 }
9647
9648 APValue *V;
9649 if (!evaluateVarDeclInit(Info, E, VD, Frame, Version, V))
9650 return false;
9651
9652 if (!V) {
9653 Result.set(VD);
9654 Result.AllowConstexprUnknown = true;
9655 return true;
9656 }
9657
9658 return Success(*V, E);
9659}
9660
9661bool LValueExprEvaluator::VisitCallExpr(const CallExpr *E) {
9662 if (!IsConstantEvaluatedBuiltinCall(E))
9663 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9664
9665 switch (E->getBuiltinCallee()) {
9666 default:
9667 return false;
9668 case Builtin::BIas_const:
9669 case Builtin::BIforward:
9670 case Builtin::BIforward_like:
9671 case Builtin::BImove:
9672 case Builtin::BImove_if_noexcept:
9673 if (cast<FunctionDecl>(E->getCalleeDecl())->isConstexpr())
9674 return Visit(E->getArg(0));
9675 break;
9676 }
9677
9678 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9679}
9680
9681bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
9682 const MaterializeTemporaryExpr *E) {
9683 // Walk through the expression to find the materialized temporary itself.
9686 const Expr *Inner =
9687 E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
9688
9689 // If we passed any comma operators, evaluate their LHSs.
9690 for (const Expr *E : CommaLHSs)
9691 if (!EvaluateIgnoredValue(Info, E))
9692 return false;
9693
9694 // A materialized temporary with static storage duration can appear within the
9695 // result of a constant expression evaluation, so we need to preserve its
9696 // value for use outside this evaluation.
9697 APValue *Value;
9698 if (E->getStorageDuration() == SD_Static) {
9699 if (Info.EvalMode == EvaluationMode::ConstantFold)
9700 return false;
9701 // FIXME: What about SD_Thread?
9702 Value = E->getOrCreateValue(true);
9703 *Value = APValue();
9704 Result.set(E);
9705 } else {
9706 Value = &Info.CurrentCall->createTemporary(
9707 E, Inner->getType(),
9708 E->getStorageDuration() == SD_FullExpression ? ScopeKind::FullExpression
9709 : ScopeKind::Block,
9710 Result);
9711 }
9712
9713 QualType Type = Inner->getType();
9714
9715 // Materialize the temporary itself.
9716 if (!EvaluateInPlace(*Value, Info, Result, Inner)) {
9717 *Value = APValue();
9718 return false;
9719 }
9720
9721 // Adjust our lvalue to refer to the desired subobject.
9722 for (unsigned I = Adjustments.size(); I != 0; /**/) {
9723 --I;
9724 switch (Adjustments[I].Kind) {
9726 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
9727 Type, Result))
9728 return false;
9729 Type = Adjustments[I].DerivedToBase.BasePath->getType();
9730 break;
9731
9733 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
9734 return false;
9735 Type = Adjustments[I].Field->getType();
9736 break;
9737
9739 if (!HandleMemberPointerAccess(this->Info, Type, Result,
9740 Adjustments[I].Ptr.RHS))
9741 return false;
9742 Type = Adjustments[I].Ptr.MPT->getPointeeType();
9743 break;
9744 }
9745 }
9746
9747 return true;
9748}
9749
9750bool
9751LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
9752 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
9753 "lvalue compound literal in c++?");
9754 APValue *Lit;
9755 // If CompountLiteral has static storage, its value can be used outside
9756 // this expression. So evaluate it once and store it in ASTContext.
9757 if (E->hasStaticStorage()) {
9758 Lit = &E->getOrCreateStaticValue(Info.Ctx);
9759 Result.set(E);
9760 // Reset any previously evaluated state, otherwise evaluation below might
9761 // fail.
9762 // FIXME: Should we just re-use the previously evaluated value instead?
9763 *Lit = APValue();
9764 } else {
9765 assert(!Info.getLangOpts().CPlusPlus);
9766 Lit = &Info.CurrentCall->createTemporary(E, E->getInitializer()->getType(),
9767 ScopeKind::Block, Result);
9768 }
9769 // FIXME: Evaluating in place isn't always right. We should figure out how to
9770 // use appropriate evaluation context here, see
9771 // clang/test/AST/static-compound-literals-reeval.cpp for a failure.
9772 if (!EvaluateInPlace(*Lit, Info, Result, E->getInitializer())) {
9773 *Lit = APValue();
9774 return false;
9775 }
9776 return true;
9777}
9778
9779bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
9780 TypeInfoLValue TypeInfo;
9781
9782 if (!E->isPotentiallyEvaluated()) {
9783 if (E->isTypeOperand())
9784 TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
9785 else
9786 TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
9787 } else {
9788 if (!Info.Ctx.getLangOpts().CPlusPlus20) {
9789 Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
9790 << E->getExprOperand()->getType()
9791 << E->getExprOperand()->getSourceRange();
9792 }
9793
9794 if (!Visit(E->getExprOperand()))
9795 return false;
9796
9797 std::optional<DynamicType> DynType =
9799 if (!DynType)
9800 return false;
9801
9802 TypeInfo = TypeInfoLValue(
9803 Info.Ctx.getCanonicalTagType(DynType->Type).getTypePtr());
9804 }
9805
9806 return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
9807}
9808
9809bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
9810 return Success(E->getGuidDecl());
9811}
9812
9813bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
9814 // Handle static data members.
9815 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
9816 VisitIgnoredBaseExpression(E->getBase());
9817 return VisitVarDecl(E, VD);
9818 }
9819
9820 // Handle static member functions.
9821 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
9822 if (MD->isStatic()) {
9823 VisitIgnoredBaseExpression(E->getBase());
9824 return Success(MD);
9825 }
9826 }
9827
9828 // Handle non-static data members.
9829 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
9830}
9831
9832bool LValueExprEvaluator::VisitExtVectorElementExpr(
9833 const ExtVectorElementExpr *E) {
9834 bool Success = true;
9835
9836 APValue Val;
9837 if (!Evaluate(Val, Info, E->getBase())) {
9838 if (!Info.noteFailure())
9839 return false;
9840 Success = false;
9841 }
9842
9844 E->getEncodedElementAccess(Indices);
9845 // FIXME: support accessing more than one element
9846 if (Indices.size() > 1)
9847 return false;
9848
9849 if (Success) {
9850 Result.setFrom(Info.Ctx, Val);
9851 QualType BaseType = E->getBase()->getType();
9852 if (E->isArrow())
9853 BaseType = BaseType->getPointeeType();
9854 const auto *VT = BaseType->castAs<VectorType>();
9855 HandleLValueVectorElement(Info, E, Result, VT->getElementType(),
9856 VT->getNumElements(), Indices[0]);
9857 }
9858
9859 return Success;
9860}
9861
9862bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
9863 if (E->getBase()->getType()->isSveVLSBuiltinType())
9864 return Error(E);
9865
9866 APSInt Index;
9867 bool Success = true;
9868
9869 if (const auto *VT = E->getBase()->getType()->getAs<VectorType>()) {
9870 APValue Val;
9871 if (!Evaluate(Val, Info, E->getBase())) {
9872 if (!Info.noteFailure())
9873 return false;
9874 Success = false;
9875 }
9876
9877 if (!EvaluateInteger(E->getIdx(), Index, Info)) {
9878 if (!Info.noteFailure())
9879 return false;
9880 Success = false;
9881 }
9882
9883 if (Success) {
9884 Result.setFrom(Info.Ctx, Val);
9885 HandleLValueVectorElement(Info, E, Result, VT->getElementType(),
9886 VT->getNumElements(), Index.getZExtValue());
9887 }
9888
9889 return Success;
9890 }
9891
9892 // C++17's rules require us to evaluate the LHS first, regardless of which
9893 // side is the base.
9894 for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) {
9895 if (SubExpr == E->getBase() ? !evaluatePointer(SubExpr, Result)
9896 : !EvaluateInteger(SubExpr, Index, Info)) {
9897 if (!Info.noteFailure())
9898 return false;
9899 Success = false;
9900 }
9901 }
9902
9903 return Success &&
9904 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
9905}
9906
9907bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
9908 bool Success = evaluatePointer(E->getSubExpr(), Result);
9909 // [C++26][expr.unary.op]
9910 // If the operand points to an object or function, the result
9911 // denotes that object or function; otherwise, the behavior is undefined.
9912 // Because &(*(type*)0) is a common pattern, we do not fail the evaluation
9913 // immediately.
9915 return Success;
9917 E->getType())) ||
9918 Info.noteUndefinedBehavior();
9919}
9920
9921bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
9922 if (!Visit(E->getSubExpr()))
9923 return false;
9924 // __real is a no-op on scalar lvalues.
9925 if (E->getSubExpr()->getType()->isAnyComplexType())
9926 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
9927 return true;
9928}
9929
9930bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
9931 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
9932 "lvalue __imag__ on scalar?");
9933 if (!Visit(E->getSubExpr()))
9934 return false;
9935 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
9936 return true;
9937}
9938
9939bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
9940 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9941 return Error(UO);
9942
9943 if (!this->Visit(UO->getSubExpr()))
9944 return false;
9945
9946 return handleIncDec(
9947 this->Info, UO, Result, UO->getSubExpr()->getType(),
9948 UO->isIncrementOp(), nullptr);
9949}
9950
9951bool LValueExprEvaluator::VisitCompoundAssignOperator(
9952 const CompoundAssignOperator *CAO) {
9953 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9954 return Error(CAO);
9955
9956 bool Success = true;
9957
9958 // C++17 onwards require that we evaluate the RHS first.
9959 APValue RHS;
9960 if (!Evaluate(RHS, this->Info, CAO->getRHS())) {
9961 if (!Info.noteFailure())
9962 return false;
9963 Success = false;
9964 }
9965
9966 // The overall lvalue result is the result of evaluating the LHS.
9967 if (!this->Visit(CAO->getLHS()) || !Success)
9968 return false;
9969
9971 this->Info, CAO,
9972 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
9973 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
9974}
9975
9976bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
9977 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9978 return Error(E);
9979
9980 bool Success = true;
9981
9982 // C++17 onwards require that we evaluate the RHS first.
9983 APValue NewVal;
9984 if (!Evaluate(NewVal, this->Info, E->getRHS())) {
9985 if (!Info.noteFailure())
9986 return false;
9987 Success = false;
9988 }
9989
9990 if (!this->Visit(E->getLHS()) || !Success)
9991 return false;
9992
9993 if (Info.getLangOpts().CPlusPlus20 &&
9995 return false;
9996
9997 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
9998 NewVal);
9999}
10000
10001//===----------------------------------------------------------------------===//
10002// Pointer Evaluation
10003//===----------------------------------------------------------------------===//
10004
10005/// Convenience function. LVal's base must be a call to an alloc_size
10006/// function.
10008 const LValue &LVal,
10009 llvm::APInt &Result) {
10010 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
10011 "Can't get the size of a non alloc_size function");
10012 const auto *Base = LVal.getLValueBase().get<const Expr *>();
10013 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
10014 std::optional<llvm::APInt> Size =
10015 CE->evaluateBytesReturnedByAllocSizeCall(Ctx);
10016 if (!Size)
10017 return false;
10018
10019 Result = std::move(*Size);
10020 return true;
10021}
10022
10023/// Attempts to evaluate the given LValueBase as the result of a call to
10024/// a function with the alloc_size attribute. If it was possible to do so, this
10025/// function will return true, make Result's Base point to said function call,
10026/// and mark Result's Base as invalid.
10028 LValue &Result) {
10029 if (Base.isNull())
10030 return false;
10031
10032 // Because we do no form of static analysis, we only support const variables.
10033 //
10034 // Additionally, we can't support parameters, nor can we support static
10035 // variables (in the latter case, use-before-assign isn't UB; in the former,
10036 // we have no clue what they'll be assigned to).
10037 const auto *VD =
10038 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
10039 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
10040 return false;
10041
10042 const Expr *Init = VD->getAnyInitializer();
10043 if (!Init || Init->getType().isNull())
10044 return false;
10045
10046 const Expr *E = Init->IgnoreParens();
10047 if (!tryUnwrapAllocSizeCall(E))
10048 return false;
10049
10050 // Store E instead of E unwrapped so that the type of the LValue's base is
10051 // what the user wanted.
10052 Result.setInvalid(E);
10053
10054 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
10055 Result.addUnsizedArray(Info, E, Pointee);
10056 return true;
10057}
10058
10059namespace {
10060class PointerExprEvaluator
10061 : public ExprEvaluatorBase<PointerExprEvaluator> {
10062 LValue &Result;
10063 bool InvalidBaseOK;
10064
10065 bool Success(const Expr *E) {
10066 Result.set(E);
10067 return true;
10068 }
10069
10070 bool evaluateLValue(const Expr *E, LValue &Result) {
10071 return EvaluateLValue(E, Result, Info, InvalidBaseOK);
10072 }
10073
10074 bool evaluatePointer(const Expr *E, LValue &Result) {
10075 return EvaluatePointer(E, Result, Info, InvalidBaseOK);
10076 }
10077
10078 bool visitNonBuiltinCallExpr(const CallExpr *E);
10079public:
10080
10081 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
10082 : ExprEvaluatorBaseTy(info), Result(Result),
10083 InvalidBaseOK(InvalidBaseOK) {}
10084
10085 bool Success(const APValue &V, const Expr *E) {
10086 Result.setFrom(Info.Ctx, V);
10087 return true;
10088 }
10089 bool ZeroInitialization(const Expr *E) {
10090 Result.setNull(Info.Ctx, E->getType());
10091 return true;
10092 }
10093
10094 bool VisitBinaryOperator(const BinaryOperator *E);
10095 bool VisitCastExpr(const CastExpr* E);
10096 bool VisitUnaryAddrOf(const UnaryOperator *E);
10097 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
10098 { return Success(E); }
10099 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
10101 return Success(E);
10102 if (Info.noteFailure())
10103 EvaluateIgnoredValue(Info, E->getSubExpr());
10104 return Error(E);
10105 }
10106 bool VisitObjCArrayLiteral(const ObjCArrayLiteral *E) {
10107 return E->isExpressibleAsConstantInitializer() ? Success(E) : Error(E);
10108 }
10109 bool VisitObjCDictionaryLiteral(const ObjCDictionaryLiteral *E) {
10110 return E->isExpressibleAsConstantInitializer() ? Success(E) : Error(E);
10111 }
10112 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
10113 { return Success(E); }
10114 bool VisitCallExpr(const CallExpr *E);
10115 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
10116 bool VisitBlockExpr(const BlockExpr *E) {
10117 if (!E->getBlockDecl()->hasCaptures())
10118 return Success(E);
10119 return Error(E);
10120 }
10121 bool VisitCXXThisExpr(const CXXThisExpr *E) {
10122 auto DiagnoseInvalidUseOfThis = [&] {
10123 if (Info.getLangOpts().CPlusPlus11)
10124 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
10125 else
10126 Info.FFDiag(E);
10127 };
10128
10129 // Can't look at 'this' when checking a potential constant expression.
10130 if (Info.checkingPotentialConstantExpression())
10131 return false;
10132
10133 bool IsExplicitLambda =
10134 isLambdaCallWithExplicitObjectParameter(Info.CurrentCall->Callee);
10135 if (!IsExplicitLambda) {
10136 if (!Info.CurrentCall->This) {
10137 DiagnoseInvalidUseOfThis();
10138 return false;
10139 }
10140
10141 Result = *Info.CurrentCall->This;
10142 }
10143
10144 if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
10145 // Ensure we actually have captured 'this'. If something was wrong with
10146 // 'this' capture, the error would have been previously reported.
10147 // Otherwise we can be inside of a default initialization of an object
10148 // declared by lambda's body, so no need to return false.
10149 if (!Info.CurrentCall->LambdaThisCaptureField) {
10150 if (IsExplicitLambda && !Info.CurrentCall->This) {
10151 DiagnoseInvalidUseOfThis();
10152 return false;
10153 }
10154
10155 return true;
10156 }
10157
10158 const auto *MD = cast<CXXMethodDecl>(Info.CurrentCall->Callee);
10159 return HandleLambdaCapture(
10160 Info, E, Result, MD, Info.CurrentCall->LambdaThisCaptureField,
10161 Info.CurrentCall->LambdaThisCaptureField->getType()->isPointerType());
10162 }
10163 return true;
10164 }
10165
10166 bool VisitCXXNewExpr(const CXXNewExpr *E);
10167
10168 bool VisitSourceLocExpr(const SourceLocExpr *E) {
10169 assert(!E->isIntType() && "SourceLocExpr isn't a pointer type?");
10170 APValue LValResult = E->EvaluateInContext(
10171 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
10172 Result.setFrom(Info.Ctx, LValResult);
10173 return true;
10174 }
10175
10176 bool VisitEmbedExpr(const EmbedExpr *E) {
10177 llvm::report_fatal_error("Not yet implemented for ExprConstant.cpp");
10178 return true;
10179 }
10180
10181 bool VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr *E) {
10182 std::string ResultStr = E->ComputeName(Info.Ctx);
10183
10184 QualType CharTy = Info.Ctx.CharTy.withConst();
10185 APInt Size(Info.Ctx.getTypeSize(Info.Ctx.getSizeType()),
10186 ResultStr.size() + 1);
10187 QualType ArrayTy = Info.Ctx.getConstantArrayType(
10188 CharTy, Size, nullptr, ArraySizeModifier::Normal, 0);
10189
10190 StringLiteral *SL =
10191 StringLiteral::Create(Info.Ctx, ResultStr, StringLiteralKind::Ordinary,
10192 /*Pascal*/ false, ArrayTy, E->getLocation());
10193
10194 evaluateLValue(SL, Result);
10195 Result.addArray(Info, E, cast<ConstantArrayType>(ArrayTy));
10196 return true;
10197 }
10198
10199 // FIXME: Missing: @protocol, @selector
10200};
10201} // end anonymous namespace
10202
10203static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
10204 bool InvalidBaseOK) {
10205 assert(!E->isValueDependent());
10206 assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
10207 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
10208}
10209
10210bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
10211 if (E->getOpcode() != BO_Add &&
10212 E->getOpcode() != BO_Sub)
10213 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10214
10215 const Expr *PExp = E->getLHS();
10216 const Expr *IExp = E->getRHS();
10217 if (IExp->getType()->isPointerType())
10218 std::swap(PExp, IExp);
10219
10220 bool EvalPtrOK = evaluatePointer(PExp, Result);
10221 if (!EvalPtrOK && !Info.noteFailure())
10222 return false;
10223
10224 llvm::APSInt Offset;
10225 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
10226 return false;
10227
10228 if (E->getOpcode() == BO_Sub)
10229 negateAsSigned(Offset);
10230
10231 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
10232 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
10233}
10234
10235bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
10236 // [C11 6.5.3.2p3]: if the operand of '&' is the result of a unary '*'
10237 // operator, neither operator is evaluated and the result is as if both were
10238 // omitted (except that the operators' constraints, already enforced by Sema,
10239 // still apply, and the result is not an lvalue). So '&*p' is just the pointer
10240 // value 'p' with no dereference, and forming it is therefore not undefined
10241 // behavior even when 'p' is null, e.g. '&*(int *)0'. Evaluate the pointer
10242 // operand directly so we don't spuriously diagnose a null dereference.
10243 if (!Info.getLangOpts().CPlusPlus) {
10244 const Expr *Sub = E->getSubExpr()->IgnoreParens();
10245 if (const auto *Deref = dyn_cast<UnaryOperator>(Sub);
10246 Deref && Deref->getOpcode() == UO_Deref)
10247 return evaluatePointer(Deref->getSubExpr(), Result);
10248 }
10249 return evaluateLValue(E->getSubExpr(), Result);
10250}
10251
10252// Is the provided decl 'std::source_location::current'?
10254 if (!FD)
10255 return false;
10256 const IdentifierInfo *FnII = FD->getIdentifier();
10257 if (!FnII || !FnII->isStr("current"))
10258 return false;
10259
10260 const auto *RD = dyn_cast<RecordDecl>(FD->getParent());
10261 if (!RD)
10262 return false;
10263
10264 const IdentifierInfo *ClassII = RD->getIdentifier();
10265 return RD->isInStdNamespace() && ClassII && ClassII->isStr("source_location");
10266}
10267
10268bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
10269 const Expr *SubExpr = E->getSubExpr();
10270
10271 switch (E->getCastKind()) {
10272 default:
10273 break;
10274 case CK_BitCast:
10275 case CK_CPointerToObjCPointerCast:
10276 case CK_BlockPointerToObjCPointerCast:
10277 case CK_AnyPointerToBlockPointerCast:
10278 case CK_AddressSpaceConversion:
10279 if (!Visit(SubExpr))
10280 return false;
10281 if (E->getType()->isFunctionPointerType() ||
10282 SubExpr->getType()->isFunctionPointerType()) {
10283 // Casting between two function pointer types, or between a function
10284 // pointer and an object pointer, is always a reinterpret_cast.
10285 CCEDiag(E, diag::note_constexpr_invalid_cast)
10286 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
10287 << Info.Ctx.getLangOpts().CPlusPlus;
10288 Result.Designator.setInvalid();
10289 } else if (!E->getType()->isVoidPointerType()) {
10290 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
10291 // permitted in constant expressions in C++11. Bitcasts from cv void* are
10292 // also static_casts, but we disallow them as a resolution to DR1312.
10293 //
10294 // In some circumstances, we permit casting from void* to cv1 T*, when the
10295 // actual pointee object is actually a cv2 T.
10296 bool HasValidResult = !Result.InvalidBase && !Result.Designator.Invalid &&
10297 !Result.IsNullPtr;
10298 bool VoidPtrCastMaybeOK =
10299 Result.IsNullPtr ||
10300 (HasValidResult &&
10301 Info.Ctx.hasSimilarType(Result.Designator.getType(Info.Ctx),
10302 E->getType()->getPointeeType()));
10303 // 1. We'll allow it in std::allocator::allocate, and anything which that
10304 // calls.
10305 // 2. HACK 2022-03-28: Work around an issue with libstdc++'s
10306 // <source_location> header. Fixed in GCC 12 and later (2022-04-??).
10307 // We'll allow it in the body of std::source_location::current. GCC's
10308 // implementation had a parameter of type `void*`, and casts from
10309 // that back to `const __impl*` in its body.
10310 if (VoidPtrCastMaybeOK &&
10311 (Info.getStdAllocatorCaller("allocate") ||
10312 IsDeclSourceLocationCurrent(Info.CurrentCall->Callee) ||
10313 Info.getLangOpts().CPlusPlus26)) {
10314 // Permitted.
10315 } else {
10316 if (SubExpr->getType()->isVoidPointerType() &&
10317 Info.getLangOpts().CPlusPlus) {
10318 if (HasValidResult)
10319 CCEDiag(E, diag::note_constexpr_invalid_void_star_cast)
10320 << SubExpr->getType() << Info.getLangOpts().CPlusPlus26
10321 << Result.Designator.getType(Info.Ctx).getCanonicalType()
10322 << E->getType()->getPointeeType();
10323 else
10324 CCEDiag(E, diag::note_constexpr_invalid_cast)
10325 << diag::ConstexprInvalidCastKind::CastFrom
10326 << SubExpr->getType();
10327 } else
10328 CCEDiag(E, diag::note_constexpr_invalid_cast)
10329 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
10330 << Info.Ctx.getLangOpts().CPlusPlus;
10331 Result.Designator.setInvalid();
10332 }
10333 }
10334 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
10335 ZeroInitialization(E);
10336 return true;
10337
10338 case CK_DerivedToBase:
10339 case CK_UncheckedDerivedToBase:
10340 if (!evaluatePointer(E->getSubExpr(), Result))
10341 return false;
10342 if (!Result.Base && Result.Offset.isZero())
10343 return true;
10344
10345 // Now figure out the necessary offset to add to the base LV to get from
10346 // the derived class to the base class.
10347 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
10348 castAs<PointerType>()->getPointeeType(),
10349 Result);
10350
10351 case CK_BaseToDerived:
10352 if (!Visit(E->getSubExpr()))
10353 return false;
10354 if (!Result.Base && Result.Offset.isZero())
10355 return true;
10356 return HandleBaseToDerivedCast(Info, E, Result);
10357
10358 case CK_Dynamic:
10359 if (!Visit(E->getSubExpr()))
10360 return false;
10362
10363 case CK_NullToPointer:
10364 VisitIgnoredValue(E->getSubExpr());
10365 return ZeroInitialization(E);
10366
10367 case CK_IntegralToPointer: {
10368 CCEDiag(E, diag::note_constexpr_invalid_cast)
10369 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
10370 << Info.Ctx.getLangOpts().CPlusPlus;
10371
10372 APValue Value;
10373 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
10374 break;
10375
10376 if (Value.isInt()) {
10377 unsigned Size = Info.Ctx.getTypeSize(E->getType());
10378 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
10379 if (N == Info.Ctx.getTargetNullPointerValue(E->getType())) {
10380 Result.setNull(Info.Ctx, E->getType());
10381 } else {
10382 Result.Base = (Expr *)nullptr;
10383 Result.InvalidBase = false;
10384 Result.Offset = CharUnits::fromQuantity(N);
10385 Result.Designator.setInvalid();
10386 Result.IsNullPtr = false;
10387 }
10388 return true;
10389 } else {
10390 // In rare instances, the value isn't an lvalue.
10391 // For example, when the value is the difference between the addresses of
10392 // two labels. We reject that as a constant expression because we can't
10393 // compute a valid offset to convert into a pointer.
10394 if (!Value.isLValue())
10395 return false;
10396
10397 // Cast is of an lvalue, no need to change value.
10398 Result.setFrom(Info.Ctx, Value);
10399 return true;
10400 }
10401 }
10402
10403 case CK_ArrayToPointerDecay: {
10404 if (SubExpr->isGLValue()) {
10405 if (!evaluateLValue(SubExpr, Result))
10406 return false;
10407 } else {
10408 APValue &Value = Info.CurrentCall->createTemporary(
10409 SubExpr, SubExpr->getType(), ScopeKind::FullExpression, Result);
10410 if (!EvaluateInPlace(Value, Info, Result, SubExpr))
10411 return false;
10412 }
10413 // The result is a pointer to the first element of the array.
10414 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
10415 if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
10416 Result.addArray(Info, E, CAT);
10417 else
10418 Result.addUnsizedArray(Info, E, AT->getElementType());
10419 return true;
10420 }
10421
10422 case CK_FunctionToPointerDecay:
10423 return evaluateLValue(SubExpr, Result);
10424
10425 case CK_LValueToRValue: {
10426 LValue LVal;
10427 if (!evaluateLValue(E->getSubExpr(), LVal))
10428 return false;
10429
10430 APValue RVal;
10431 // Note, we use the subexpression's type in order to retain cv-qualifiers.
10433 LVal, RVal))
10434 return InvalidBaseOK &&
10435 evaluateLValueAsAllocSize(Info, LVal.Base, Result);
10436 return Success(RVal, E);
10437 }
10438 }
10439
10440 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10441}
10442
10444 UnaryExprOrTypeTrait ExprKind) {
10445 // C++ [expr.alignof]p3:
10446 // When alignof is applied to a reference type, the result is the
10447 // alignment of the referenced type.
10448 T = T.getNonReferenceType();
10449
10450 if (T.getQualifiers().hasUnaligned())
10451 return CharUnits::One();
10452
10453 const bool AlignOfReturnsPreferred =
10454 Ctx.getLangOpts().isCompatibleWith(LangOptions::ClangABI::Ver7);
10455
10456 // __alignof is defined to return the preferred alignment.
10457 // Before 8, clang returned the preferred alignment for alignof and _Alignof
10458 // as well.
10459 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
10460 return Ctx.toCharUnitsFromBits(Ctx.getPreferredTypeAlign(T.getTypePtr()));
10461 // alignof and _Alignof are defined to return the ABI alignment.
10462 else if (ExprKind == UETT_AlignOf)
10463 return Ctx.getTypeAlignInChars(T.getTypePtr());
10464 else
10465 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
10466}
10467
10468// Convert a builtin ID to the canonical x86 builtin ID the constant evaluators
10469// dispatch on in their x86 target-specific cases, or 0 if \p BuiltinOp is a
10470// target builtin those cases should not handle.
10471//
10472// Target-independent builtins are returned unchanged. Target builtin IDs of
10473// different targets overlap (each target numbers its builtins from
10474// Builtin::FirstTSBuiltin), so a target builtin ID is only meaningful for the
10475// target that owns it. Determine the owning target (translating an auxiliary ID
10476// back to its canonical value) and only return the ID when x86 owns it;
10477// otherwise an overlapping ID could be misinterpreted as an unrelated x86
10478// builtin.
10480 unsigned BuiltinOp) {
10481 // Target-independent builtins have the same ID regardless of the target, so
10482 // they can be dispatched as-is. This is the common case and is intentionally
10483 // kept to a single comparison so callers can use this on hot paths (e.g. the
10484 // bytecode interpreter's builtin dispatch) without re-deriving the ID from
10485 // the call expression.
10486 if (BuiltinOp < Builtin::FirstTSBuiltin)
10487 return BuiltinOp;
10488
10489 // Determine the target that owns this builtin, translating an auxiliary ID
10490 // back to its canonical value.
10491 const TargetInfo *OwningTarget;
10492 if (Ctx.BuiltinInfo.isAuxBuiltinID(BuiltinOp)) {
10493 OwningTarget = Ctx.getAuxTargetInfo();
10494 BuiltinOp = Ctx.BuiltinInfo.getAuxBuiltinID(BuiltinOp);
10495 } else {
10496 OwningTarget = &Ctx.getTargetInfo();
10497 }
10498
10499 if (!OwningTarget)
10500 return 0;
10501
10502 // x86 and x86_64 share a single builtin set and are the only architectures
10503 // whose target-specific builtins the constant evaluators currently fold.
10504 switch (OwningTarget->getTriple().getArch()) {
10505 case llvm::Triple::x86:
10506 case llvm::Triple::x86_64:
10507 return BuiltinOp;
10508 default:
10509 return 0;
10510 }
10511}
10512
10514 const CallExpr *E) {
10516}
10517
10519 UnaryExprOrTypeTrait ExprKind) {
10520 E = E->IgnoreParens();
10521
10522 // The kinds of expressions that we have special-case logic here for
10523 // should be kept up to date with the special checks for those
10524 // expressions in Sema.
10525
10526 // alignof decl is always accepted, even if it doesn't make sense: we default
10527 // to 1 in those cases.
10528 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
10529 return Ctx.getDeclAlign(DRE->getDecl(),
10530 /*RefAsPointee*/ true);
10531
10532 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
10533 return Ctx.getDeclAlign(ME->getMemberDecl(),
10534 /*RefAsPointee*/ true);
10535
10536 return GetAlignOfType(Ctx, E->getType(), ExprKind);
10537}
10538
10539static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) {
10540 if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>())
10541 return Info.Ctx.getDeclAlign(VD);
10542 if (const auto *E = Value.Base.dyn_cast<const Expr *>())
10543 return GetAlignOfExpr(Info.Ctx, E, UETT_AlignOf);
10544 return GetAlignOfType(Info.Ctx, Value.Base.getTypeInfoType(), UETT_AlignOf);
10545}
10546
10547/// Evaluate the value of the alignment argument to __builtin_align_{up,down},
10548/// __builtin_is_aligned and __builtin_assume_aligned.
10549static bool getAlignmentArgument(const Expr *E, QualType ForType,
10550 EvalInfo &Info, APSInt &Alignment) {
10551 if (!EvaluateInteger(E, Alignment, Info))
10552 return false;
10553 if (Alignment < 0 || !Alignment.isPowerOf2()) {
10554 Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment;
10555 return false;
10556 }
10557 unsigned SrcWidth = Info.Ctx.getIntWidth(ForType);
10558 APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1));
10559 if (APSInt::compareValues(Alignment, MaxValue) > 0) {
10560 Info.FFDiag(E, diag::note_constexpr_alignment_too_big)
10561 << MaxValue << ForType << Alignment;
10562 return false;
10563 }
10564 // Ensure both alignment and source value have the same bit width so that we
10565 // don't assert when computing the resulting value.
10566 APSInt ExtAlignment =
10567 APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true);
10568 assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 &&
10569 "Alignment should not be changed by ext/trunc");
10570 Alignment = ExtAlignment;
10571 assert(Alignment.getBitWidth() == SrcWidth);
10572 return true;
10573}
10574
10575// To be clear: this happily visits unsupported builtins. Better name welcomed.
10576bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
10577 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
10578 return true;
10579
10580 if (!(InvalidBaseOK && E->getCalleeAllocSizeAttr()))
10581 return false;
10582
10583 Result.setInvalid(E);
10584 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
10585 Result.addUnsizedArray(Info, E, PointeeTy);
10586 return true;
10587}
10588
10589bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
10590 if (!IsConstantEvaluatedBuiltinCall(E))
10591 return visitNonBuiltinCallExpr(E);
10592 return VisitBuiltinCallExpr(E, ConvertBuiltinIDToX86BuiltinID(Info.Ctx, E));
10593}
10594
10595// Determine if T is a character type for which we guarantee that
10596// sizeof(T) == 1.
10598 return T->isCharType() || T->isChar8Type();
10599}
10600
10601bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
10602 unsigned BuiltinOp) {
10603 if (isOpaqueConstantCall(E))
10604 return Success(E);
10605
10606 switch (BuiltinOp) {
10607 case Builtin::BIaddressof:
10608 case Builtin::BI__addressof:
10609 case Builtin::BI__builtin_addressof:
10610 return evaluateLValue(E->getArg(0), Result);
10611 case Builtin::BI__builtin_assume_aligned: {
10612 // We need to be very careful here because: if the pointer does not have the
10613 // asserted alignment, then the behavior is undefined, and undefined
10614 // behavior is non-constant.
10615 if (!evaluatePointer(E->getArg(0), Result))
10616 return false;
10617
10618 LValue OffsetResult(Result);
10619 APSInt Alignment;
10620 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
10621 Alignment))
10622 return false;
10623 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
10624
10625 if (E->getNumArgs() > 2) {
10626 APSInt Offset;
10627 if (!EvaluateInteger(E->getArg(2), Offset, Info))
10628 return false;
10629
10630 int64_t AdditionalOffset = -Offset.getZExtValue();
10631 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
10632 }
10633
10634 // If there is a base object, then it must have the correct alignment.
10635 if (OffsetResult.Base) {
10636 CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult);
10637
10638 if (BaseAlignment < Align) {
10639 Result.Designator.setInvalid();
10640 CCEDiag(E->getArg(0), diag::note_constexpr_baa_insufficient_alignment)
10641 << 0 << BaseAlignment.getQuantity() << Align.getQuantity();
10642 return false;
10643 }
10644 }
10645
10646 // The offset must also have the correct alignment.
10647 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
10648 Result.Designator.setInvalid();
10649
10650 (OffsetResult.Base
10651 ? CCEDiag(E->getArg(0),
10652 diag::note_constexpr_baa_insufficient_alignment)
10653 << 1
10654 : CCEDiag(E->getArg(0),
10655 diag::note_constexpr_baa_value_insufficient_alignment))
10656 << OffsetResult.Offset.getQuantity() << Align.getQuantity();
10657 return false;
10658 }
10659
10660 return true;
10661 }
10662 case Builtin::BI__builtin_align_up:
10663 case Builtin::BI__builtin_align_down: {
10664 if (!evaluatePointer(E->getArg(0), Result))
10665 return false;
10666 APSInt Alignment;
10667 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
10668 Alignment))
10669 return false;
10670 CharUnits BaseAlignment = getBaseAlignment(Info, Result);
10671 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset);
10672 // For align_up/align_down, we can return the same value if the alignment
10673 // is known to be greater or equal to the requested value.
10674 if (PtrAlign.getQuantity() >= Alignment)
10675 return true;
10676
10677 // The alignment could be greater than the minimum at run-time, so we cannot
10678 // infer much about the resulting pointer value. One case is possible:
10679 // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we
10680 // can infer the correct index if the requested alignment is smaller than
10681 // the base alignment so we can perform the computation on the offset.
10682 if (BaseAlignment.getQuantity() >= Alignment) {
10683 assert(Alignment.getBitWidth() <= 64 &&
10684 "Cannot handle > 64-bit address-space");
10685 uint64_t Alignment64 = Alignment.getZExtValue();
10686 CharUnits NewOffset = CharUnits::fromQuantity(
10687 BuiltinOp == Builtin::BI__builtin_align_down
10688 ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64)
10689 : llvm::alignTo(Result.Offset.getQuantity(), Alignment64));
10690 Result.adjustOffset(NewOffset - Result.Offset);
10691 // TODO: diagnose out-of-bounds values/only allow for arrays?
10692 return true;
10693 }
10694 // Otherwise, we cannot constant-evaluate the result.
10695 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust)
10696 << Alignment;
10697 return false;
10698 }
10699 case Builtin::BI__builtin_operator_new:
10700 return HandleOperatorNewCall(Info, E, Result);
10701 case Builtin::BI__builtin_launder:
10702 return evaluatePointer(E->getArg(0), Result);
10703 case Builtin::BIstrchr:
10704 case Builtin::BIwcschr:
10705 case Builtin::BImemchr:
10706 case Builtin::BIwmemchr:
10707 if (Info.getLangOpts().CPlusPlus11)
10708 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
10709 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
10710 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
10711 else
10712 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
10713 [[fallthrough]];
10714 case Builtin::BI__builtin_strchr:
10715 case Builtin::BI__builtin_wcschr:
10716 case Builtin::BI__builtin_memchr:
10717 case Builtin::BI__builtin_char_memchr:
10718 case Builtin::BI__builtin_wmemchr: {
10719 if (!Visit(E->getArg(0)))
10720 return false;
10721 APSInt Desired;
10722 if (!EvaluateInteger(E->getArg(1), Desired, Info))
10723 return false;
10724 uint64_t MaxLength = uint64_t(-1);
10725 if (BuiltinOp != Builtin::BIstrchr &&
10726 BuiltinOp != Builtin::BIwcschr &&
10727 BuiltinOp != Builtin::BI__builtin_strchr &&
10728 BuiltinOp != Builtin::BI__builtin_wcschr) {
10729 APSInt N;
10730 if (!EvaluateInteger(E->getArg(2), N, Info))
10731 return false;
10732 MaxLength = N.getZExtValue();
10733 }
10734 // We cannot find the value if there are no candidates to match against.
10735 if (MaxLength == 0u)
10736 return ZeroInitialization(E);
10737 if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
10738 Result.Designator.Invalid)
10739 return false;
10740 QualType CharTy = Result.Designator.getType(Info.Ctx);
10741 bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
10742 BuiltinOp == Builtin::BI__builtin_memchr;
10743 assert(IsRawByte ||
10744 Info.Ctx.hasSameUnqualifiedType(
10745 CharTy, E->getArg(0)->getType()->getPointeeType()));
10746 // Pointers to const void may point to objects of incomplete type.
10747 if (IsRawByte && CharTy->isIncompleteType()) {
10748 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
10749 return false;
10750 }
10751 // Give up on byte-oriented matching against multibyte elements.
10752 // FIXME: We can compare the bytes in the correct order.
10753 if (IsRawByte && !isOneByteCharacterType(CharTy)) {
10754 Info.FFDiag(E, diag::note_constexpr_memchr_unsupported)
10755 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp) << CharTy;
10756 return false;
10757 }
10758 // Figure out what value we're actually looking for (after converting to
10759 // the corresponding unsigned type if necessary).
10760 uint64_t DesiredVal;
10761 bool StopAtNull = false;
10762 switch (BuiltinOp) {
10763 case Builtin::BIstrchr:
10764 case Builtin::BI__builtin_strchr:
10765 // strchr compares directly to the passed integer, and therefore
10766 // always fails if given an int that is not a char.
10767 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
10768 E->getArg(1)->getType(),
10769 Desired),
10770 Desired))
10771 return ZeroInitialization(E);
10772 StopAtNull = true;
10773 [[fallthrough]];
10774 case Builtin::BImemchr:
10775 case Builtin::BI__builtin_memchr:
10776 case Builtin::BI__builtin_char_memchr:
10777 // memchr compares by converting both sides to unsigned char. That's also
10778 // correct for strchr if we get this far (to cope with plain char being
10779 // unsigned in the strchr case).
10780 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
10781 break;
10782
10783 case Builtin::BIwcschr:
10784 case Builtin::BI__builtin_wcschr:
10785 StopAtNull = true;
10786 [[fallthrough]];
10787 case Builtin::BIwmemchr:
10788 case Builtin::BI__builtin_wmemchr:
10789 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
10790 DesiredVal = Desired.getZExtValue();
10791 break;
10792 }
10793
10794 for (; MaxLength; --MaxLength) {
10795 APValue Char;
10796 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
10797 !Char.isInt())
10798 return false;
10799 if (Char.getInt().getZExtValue() == DesiredVal)
10800 return true;
10801 if (StopAtNull && !Char.getInt())
10802 break;
10803 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
10804 return false;
10805 }
10806 // Not found: return nullptr.
10807 return ZeroInitialization(E);
10808 }
10809
10810 case Builtin::BImemcpy:
10811 case Builtin::BImemmove:
10812 case Builtin::BIwmemcpy:
10813 case Builtin::BIwmemmove:
10814 if (Info.getLangOpts().CPlusPlus11)
10815 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
10816 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
10817 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
10818 else
10819 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
10820 [[fallthrough]];
10821 case Builtin::BI__builtin_memcpy:
10822 case Builtin::BI__builtin_memmove:
10823 case Builtin::BI__builtin_wmemcpy:
10824 case Builtin::BI__builtin_wmemmove: {
10825 bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
10826 BuiltinOp == Builtin::BIwmemmove ||
10827 BuiltinOp == Builtin::BI__builtin_wmemcpy ||
10828 BuiltinOp == Builtin::BI__builtin_wmemmove;
10829 bool Move = BuiltinOp == Builtin::BImemmove ||
10830 BuiltinOp == Builtin::BIwmemmove ||
10831 BuiltinOp == Builtin::BI__builtin_memmove ||
10832 BuiltinOp == Builtin::BI__builtin_wmemmove;
10833
10834 // The result of mem* is the first argument.
10835 if (!Visit(E->getArg(0)))
10836 return false;
10837 LValue Dest = Result;
10838
10839 LValue Src;
10840 if (!EvaluatePointer(E->getArg(1), Src, Info))
10841 return false;
10842
10843 APSInt N;
10844 if (!EvaluateInteger(E->getArg(2), N, Info))
10845 return false;
10846 assert(!N.isSigned() && "memcpy and friends take an unsigned size");
10847
10848 // If the size is zero, we treat this as always being a valid no-op.
10849 // (Even if one of the src and dest pointers is null.)
10850 if (!N)
10851 return true;
10852
10853 // Otherwise, if either of the operands is null, we can't proceed. Don't
10854 // try to determine the type of the copied objects, because there aren't
10855 // any.
10856 if (!Src.Base || !Dest.Base) {
10857 APValue Val;
10858 (!Src.Base ? Src : Dest).moveInto(Val);
10859 Info.FFDiag(E, diag::note_constexpr_memcpy_null)
10860 << Move << WChar << !!Src.Base
10861 << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
10862 return false;
10863 }
10864 if (Src.Designator.Invalid || Dest.Designator.Invalid)
10865 return false;
10866
10867 // We require that Src and Dest are both pointers to arrays of
10868 // trivially-copyable type. (For the wide version, the designator will be
10869 // invalid if the designated object is not a wchar_t.)
10870 QualType T = Dest.Designator.getType(Info.Ctx);
10871 QualType SrcT = Src.Designator.getType(Info.Ctx);
10872 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
10873 // FIXME: Consider using our bit_cast implementation to support this.
10874 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
10875 return false;
10876 }
10877 if (T->isIncompleteType()) {
10878 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
10879 return false;
10880 }
10881 if (!T.isTriviallyCopyableType(Info.Ctx)) {
10882 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
10883 return false;
10884 }
10885
10886 // Figure out how many T's we're copying.
10887 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
10888 if (TSize == 0)
10889 return false;
10890 if (!WChar) {
10891 uint64_t Remainder;
10892 llvm::APInt OrigN = N;
10893 llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
10894 if (Remainder) {
10895 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
10896 << Move << WChar << 0 << T << toString(OrigN, 10, /*Signed*/false)
10897 << (unsigned)TSize;
10898 return false;
10899 }
10900 }
10901
10902 // Check that the copying will remain within the arrays, just so that we
10903 // can give a more meaningful diagnostic. This implicitly also checks that
10904 // N fits into 64 bits.
10905 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
10906 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
10907 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
10908 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
10909 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
10910 << toString(N, 10, /*Signed*/false);
10911 return false;
10912 }
10913 uint64_t NElems = N.getZExtValue();
10914 uint64_t NBytes = NElems * TSize;
10915
10916 // Check for overlap.
10917 int Direction = 1;
10918 if (HasSameBase(Src, Dest)) {
10919 uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
10920 uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
10921 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
10922 // Dest is inside the source region.
10923 if (!Move) {
10924 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
10925 return false;
10926 }
10927 // For memmove and friends, copy backwards.
10928 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
10929 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
10930 return false;
10931 Direction = -1;
10932 } else if (!Move && SrcOffset >= DestOffset &&
10933 SrcOffset - DestOffset < NBytes) {
10934 // Src is inside the destination region for memcpy: invalid.
10935 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
10936 return false;
10937 }
10938 }
10939
10940 while (true) {
10941 APValue Val;
10942 // FIXME: Set WantObjectRepresentation to true if we're copying a
10943 // char-like type?
10944 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
10945 !handleAssignment(Info, E, Dest, T, Val))
10946 return false;
10947 // Do not iterate past the last element; if we're copying backwards, that
10948 // might take us off the start of the array.
10949 if (--NElems == 0)
10950 return true;
10951 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
10952 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
10953 return false;
10954 }
10955 }
10956
10957 default:
10958 return false;
10959 }
10960}
10961
10962static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
10963 APValue &Result, const InitListExpr *ILE,
10964 QualType AllocType);
10965static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
10966 APValue &Result,
10967 const CXXConstructExpr *CCE,
10968 QualType AllocType);
10969
10970bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) {
10971 if (!Info.getLangOpts().CPlusPlus20)
10972 Info.CCEDiag(E, diag::note_constexpr_new);
10973
10974 // We cannot speculatively evaluate a delete expression.
10975 if (Info.SpeculativeEvaluationDepth)
10976 return false;
10977
10978 FunctionDecl *OperatorNew = E->getOperatorNew();
10979 QualType AllocType = E->getAllocatedType();
10980 QualType TargetType = AllocType;
10981
10982 bool IsNothrow = false;
10983 bool IsPlacement = false;
10984
10985 // The only new-placement list we support (other than the reserved placement
10986 // form) is of the form (std::nothrow).
10987 //
10988 // FIXME: There is no restriction on this, but it's not clear that any
10989 // other form makes any sense. We get here for cases such as:
10990 //
10991 // new (std::align_val_t{N}) X(int)
10992 //
10993 // (which should presumably be valid only if N is a multiple of
10994 // alignof(int), and in any case can't be deallocated unless N is
10995 // alignof(X) and X has new-extended alignment).
10996 bool HasNothrowArg = E->getNumPlacementArgs() == 1 &&
10998
10999 if (OperatorNew->isReservedGlobalPlacementOperator()) {
11000 if (Info.CurrentCall->isStdFunction() || Info.getLangOpts().CPlusPlus26 ||
11001 (Info.CurrentCall->CanEvalMSConstexpr &&
11002 OperatorNew->hasAttr<MSConstexprAttr>())) {
11003 if (!EvaluatePointer(E->getPlacementArg(0), Result, Info))
11004 return false;
11005 if (Result.Designator.Invalid)
11006 return false;
11007 TargetType = E->getPlacementArg(0)->getType();
11008 IsPlacement = true;
11009 } else {
11010 Info.FFDiag(E, diag::note_constexpr_new_placement)
11011 << /*C++26 feature*/ 1 << E->getSourceRange();
11012 return false;
11013 }
11014 } else if (E->getNumPlacementArgs() && !HasNothrowArg) {
11015 Info.FFDiag(E, diag::note_constexpr_new_placement)
11016 << /*Unsupported*/ 0 << E->getSourceRange();
11017 return false;
11018 } else if (!OperatorNew
11019 ->isUsableAsGlobalAllocationFunctionInConstantEvaluation()) {
11020 // [expr.const] only permits new-expressions that select a replaceable
11021 // global allocation function. Check this before evaluating a
11022 // (std::nothrow) placement argument.
11023 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
11024 << isa<CXXMethodDecl>(OperatorNew) << OperatorNew;
11025 return false;
11026 } else if (HasNothrowArg) {
11027 LValue Nothrow;
11028 if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info))
11029 return false;
11030 IsNothrow = true;
11031 }
11032
11033 const Expr *Init = E->getInitializer();
11034 const InitListExpr *ResizedArrayILE = nullptr;
11035 const CXXConstructExpr *ResizedArrayCCE = nullptr;
11036 bool ValueInit = false;
11037
11038 if (std::optional<const Expr *> ArraySize = E->getArraySize()) {
11039 const Expr *Stripped = *ArraySize;
11040 for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
11041 Stripped = ICE->getSubExpr())
11042 if (ICE->getCastKind() != CK_NoOp &&
11043 ICE->getCastKind() != CK_IntegralCast)
11044 break;
11045
11046 llvm::APSInt ArrayBound;
11047 if (!EvaluateInteger(Stripped, ArrayBound, Info))
11048 return false;
11049
11050 // C++ [expr.new]p9:
11051 // The expression is erroneous if:
11052 // -- [...] its value before converting to size_t [or] applying the
11053 // second standard conversion sequence is less than zero
11054 if (ArrayBound.isSigned() && ArrayBound.isNegative()) {
11055 if (IsNothrow)
11056 return ZeroInitialization(E);
11057
11058 Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative)
11059 << ArrayBound << (*ArraySize)->getSourceRange();
11060 return false;
11061 }
11062
11063 // -- its value is such that the size of the allocated object would
11064 // exceed the implementation-defined limit
11065 if (!Info.CheckArraySize(ArraySize.value()->getExprLoc(),
11067 Info.Ctx, AllocType, ArrayBound),
11068 ArrayBound.getZExtValue(), /*Diag=*/!IsNothrow)) {
11069 if (IsNothrow)
11070 return ZeroInitialization(E);
11071 return false;
11072 }
11073
11074 // -- the new-initializer is a braced-init-list and the number of
11075 // array elements for which initializers are provided [...]
11076 // exceeds the number of elements to initialize
11077 if (!Init) {
11078 // No initialization is performed.
11079 } else if (isa<CXXScalarValueInitExpr>(Init) ||
11081 ValueInit = true;
11082 } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) {
11083 ResizedArrayCCE = CCE;
11084 } else {
11085 auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType());
11086 assert(CAT && "unexpected type for array initializer");
11087
11088 unsigned Bits =
11089 std::max(CAT->getSizeBitWidth(), ArrayBound.getBitWidth());
11090 llvm::APInt InitBound = CAT->getSize().zext(Bits);
11091 llvm::APInt AllocBound = ArrayBound.zext(Bits);
11092 if (InitBound.ugt(AllocBound)) {
11093 if (IsNothrow)
11094 return ZeroInitialization(E);
11095
11096 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small)
11097 << toString(AllocBound, 10, /*Signed=*/false)
11098 << toString(InitBound, 10, /*Signed=*/false)
11099 << (*ArraySize)->getSourceRange();
11100 return false;
11101 }
11102
11103 // If the sizes differ, we must have an initializer list, and we need
11104 // special handling for this case when we initialize.
11105 if (InitBound != AllocBound)
11106 ResizedArrayILE = cast<InitListExpr>(Init);
11107 }
11108
11109 AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr,
11110 ArraySizeModifier::Normal, 0);
11111 } else if (E->isArray()) {
11112 // We have an array new-expression whose array size could not be
11113 // determined, e.g. 'new int[]()', where the bound is neither given nor
11114 // deducible from the initializer. This is ill-formed and already
11115 // diagnosed, so bail out rather than mis-evaluating a scalar allocation
11116 // as an array (which would later crash the evaluator).
11117 return false;
11118 } else {
11119 assert(!AllocType->isArrayType() &&
11120 "array allocation with non-array new");
11121 }
11122
11123 APValue *Val;
11124 if (IsPlacement) {
11126 struct FindObjectHandler {
11127 EvalInfo &Info;
11128 const Expr *E;
11129 QualType AllocType;
11130 const AccessKinds AccessKind;
11131 APValue *Value;
11132
11133 typedef bool result_type;
11134 bool failed() { return false; }
11135 bool checkConst(QualType QT) {
11136 if (QT.isConstQualified()) {
11137 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
11138 return false;
11139 }
11140 return true;
11141 }
11142 bool found(APValue &Subobj, QualType SubobjType,
11143 APValue::LValueBase Base) {
11144 if (!checkConst(SubobjType))
11145 return false;
11146 // FIXME: Reject the cases where [basic.life]p8 would not permit the
11147 // old name of the object to be used to name the new object.
11148 if (!Info.Ctx.hasSimilarType(SubobjType, AllocType)) {
11149 Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type)
11150 << SubobjType << AllocType;
11151 return false;
11152 }
11153 Value = &Subobj;
11154 return true;
11155 }
11156 bool found(APSInt &Value, QualType SubobjType) {
11157 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
11158 return false;
11159 }
11160 bool found(APFloat &Value, QualType SubobjType) {
11161 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
11162 return false;
11163 }
11164 } Handler = {Info, E, AllocType, AK, nullptr};
11165
11166 if (AllocType->isArrayType() &&
11167 Result.Designator.MostDerivedIsArrayElement &&
11168 Result.Designator.Entries.back().getAsArrayIndex() == 0) {
11169 // The destination of placement new is pointing to the first element
11170 // of an array. There's a special case in [expr.const]: "[...] if T is an
11171 // array type, to the first element of such an object [...]". Handle
11172 // that case here by dropping the last entry in the designator list.
11173 QualType AllocElementType =
11174 Info.Ctx.getAsArrayType(AllocType)->getElementType();
11175 if (Info.Ctx.hasSimilarType(AllocElementType,
11176 Result.Designator.MostDerivedType)) {
11177 Result.Designator.truncate(Info.Ctx, Result.Base,
11178 Result.Designator.MostDerivedPathLength - 1);
11179 }
11180 }
11181
11182 CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType);
11183 if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler))
11184 return false;
11185
11186 Val = Handler.Value;
11187
11188 // [basic.life]p1:
11189 // The lifetime of an object o of type T ends when [...] the storage
11190 // which the object occupies is [...] reused by an object that is not
11191 // nested within o (6.6.2).
11192 *Val = APValue();
11193 } else {
11194 // Perform the allocation and obtain a pointer to the resulting object.
11195 Val = Info.createHeapAlloc(E, AllocType, Result);
11196 if (!Val)
11197 return false;
11198 }
11199
11200 if (ValueInit) {
11201 ImplicitValueInitExpr VIE(AllocType);
11202 if (!EvaluateInPlace(*Val, Info, Result, &VIE))
11203 return false;
11204 } else if (ResizedArrayILE) {
11205 if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE,
11206 AllocType))
11207 return false;
11208 } else if (ResizedArrayCCE) {
11209 if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE,
11210 AllocType))
11211 return false;
11212 } else if (Init) {
11213 if (!EvaluateInPlace(*Val, Info, Result, Init))
11214 return false;
11215 } else if (!handleDefaultInitValue(AllocType, *Val)) {
11216 return false;
11217 }
11218
11219 // Array new returns a pointer to the first element, not a pointer to the
11220 // array.
11221 if (auto *AT = AllocType->getAsArrayTypeUnsafe())
11222 Result.addArray(Info, E, cast<ConstantArrayType>(AT));
11223
11224 return true;
11225}
11226//===----------------------------------------------------------------------===//
11227// Member Pointer Evaluation
11228//===----------------------------------------------------------------------===//
11229
11230namespace {
11231class MemberPointerExprEvaluator
11232 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
11233 MemberPtr &Result;
11234
11235 bool Success(const ValueDecl *D) {
11236 Result = MemberPtr(D);
11237 return true;
11238 }
11239public:
11240
11241 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
11242 : ExprEvaluatorBaseTy(Info), Result(Result) {}
11243
11244 bool Success(const APValue &V, const Expr *E) {
11245 Result.setFrom(V);
11246 return true;
11247 }
11248 bool ZeroInitialization(const Expr *E) {
11249 return Success((const ValueDecl*)nullptr);
11250 }
11251
11252 bool VisitCastExpr(const CastExpr *E);
11253 bool VisitUnaryAddrOf(const UnaryOperator *E);
11254};
11255} // end anonymous namespace
11256
11257static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
11258 EvalInfo &Info) {
11259 assert(!E->isValueDependent());
11260 assert(E->isPRValue() && E->getType()->isMemberPointerType());
11261 return MemberPointerExprEvaluator(Info, Result).Visit(E);
11262}
11263
11264bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
11265 switch (E->getCastKind()) {
11266 default:
11267 return ExprEvaluatorBaseTy::VisitCastExpr(E);
11268
11269 case CK_NullToMemberPointer:
11270 VisitIgnoredValue(E->getSubExpr());
11271 return ZeroInitialization(E);
11272
11273 case CK_BaseToDerivedMemberPointer: {
11274 if (!Visit(E->getSubExpr()))
11275 return false;
11276 if (E->path_empty())
11277 return true;
11278 // Base-to-derived member pointer casts store the path in derived-to-base
11279 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
11280 // the wrong end of the derived->base arc, so stagger the path by one class.
11281 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
11282 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
11283 PathI != PathE; ++PathI) {
11284 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
11285 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
11286 if (!Result.castToDerived(Derived))
11287 return Error(E);
11288 }
11289 if (!Result.castToDerived(E->getType()
11290 ->castAs<MemberPointerType>()
11291 ->getMostRecentCXXRecordDecl()))
11292 return Error(E);
11293 return true;
11294 }
11295
11296 case CK_DerivedToBaseMemberPointer:
11297 if (!Visit(E->getSubExpr()))
11298 return false;
11299 for (CastExpr::path_const_iterator PathI = E->path_begin(),
11300 PathE = E->path_end(); PathI != PathE; ++PathI) {
11301 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
11302 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
11303 if (!Result.castToBase(Base))
11304 return Error(E);
11305 }
11306 return true;
11307 }
11308}
11309
11310bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
11311 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
11312 // member can be formed.
11313 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
11314}
11315
11316//===----------------------------------------------------------------------===//
11317// Record Evaluation
11318//===----------------------------------------------------------------------===//
11319
11320namespace {
11321 class RecordExprEvaluator
11322 : public ExprEvaluatorBase<RecordExprEvaluator> {
11323 const LValue &This;
11324 APValue &Result;
11325 public:
11326
11327 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
11328 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
11329
11330 bool Success(const APValue &V, const Expr *E) {
11331 Result = V;
11332 return true;
11333 }
11334 bool ZeroInitialization(const Expr *E) {
11335 return ZeroInitialization(E, E->getType());
11336 }
11337 bool ZeroInitialization(const Expr *E, QualType T);
11338
11339 bool VisitCallExpr(const CallExpr *E) {
11340 return handleCallExpr(E, Result, &This);
11341 }
11342 bool VisitCastExpr(const CastExpr *E);
11343 bool VisitInitListExpr(const InitListExpr *E);
11344 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
11345 return VisitCXXConstructExpr(E, E->getType());
11346 }
11347 bool VisitLambdaExpr(const LambdaExpr *E);
11348 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
11349 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
11350 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
11351 bool VisitBinCmp(const BinaryOperator *E);
11352 bool VisitTypeTraitExpr(const TypeTraitExpr *E);
11353 bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E);
11354 bool VisitCXXParenListOrInitListExpr(const Expr *ExprToVisit,
11355 ArrayRef<Expr *> Args);
11356 bool VisitDesignatedInitUpdateExpr(const DesignatedInitUpdateExpr *E);
11357 };
11358}
11359
11360/// Perform zero-initialization on an object of non-union class type.
11361/// C++11 [dcl.init]p5:
11362/// To zero-initialize an object or reference of type T means:
11363/// [...]
11364/// -- if T is a (possibly cv-qualified) non-union class type,
11365/// each non-static data member and each base-class subobject is
11366/// zero-initialized
11367static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
11368 const RecordDecl *RD,
11369 const LValue &This, APValue &Result,
11370 bool IsCompleteClass = true) {
11371 assert(!RD->isUnion() && "Expected non-union class type");
11372 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
11373
11374 if (CD) {
11375 unsigned NonVirtualBases = countNonVirtualBases(CD);
11376 Result =
11377 APValue(APValue::UninitStruct(), NonVirtualBases, RD->getNumFields(),
11378 IsCompleteClass ? CD->getNumVBases() : 0);
11379 } else {
11381 }
11382
11383 if (RD->isInvalidDecl()) return false;
11384 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
11385
11386 if (CD) {
11387 unsigned Index = 0;
11388
11389 for (const auto &B : CD->bases()) {
11390 if (B.isVirtual())
11391 continue;
11393 LValue Subobject = This;
11394 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
11395 return false;
11396 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
11397 Result.getStructBase(Index),
11398 /*IsCompleteClass=*/false))
11399 return false;
11400 ++Index;
11401 }
11402 }
11403
11404 for (const auto *I : RD->fields()) {
11405 // -- if T is a reference type, no initialization is performed.
11406 if (I->isUnnamedBitField() || I->getType()->isReferenceType())
11407 continue;
11408
11409 LValue Subobject = This;
11410 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
11411 return false;
11412
11413 ImplicitValueInitExpr VIE(I->getType());
11414 if (!EvaluateInPlace(
11415 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
11416 return false;
11417 }
11418
11419 if (CD && This.pointsToCompleteClass(CD)) {
11420 unsigned Index = 0;
11421 for (const auto &B : CD->vbases()) {
11423 LValue Subobject = This;
11424 if (!HandleLValueDirectVirtualBase(Info, E, Subobject, CD, Base, &Layout))
11425 return false;
11426 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
11427 Result.getStructVirtualBase(Index),
11428 /*IsCompleteClass=*/false))
11429 return false;
11430 ++Index;
11431 }
11432 }
11433
11434 return true;
11435}
11436
11437bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
11438 const auto *RD = T->castAsRecordDecl();
11439 if (RD->isInvalidDecl()) return false;
11440 if (RD->isUnion()) {
11441 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
11442 // object's first non-static named data member is zero-initialized
11444 while (I != RD->field_end() && (*I)->isUnnamedBitField())
11445 ++I;
11446 if (I == RD->field_end()) {
11447 Result = APValue((const FieldDecl*)nullptr);
11448 return true;
11449 }
11450
11451 LValue Subobject = This;
11452 if (!HandleLValueMember(Info, E, Subobject, *I))
11453 return false;
11454 Result = APValue(*I);
11455 ImplicitValueInitExpr VIE(I->getType());
11456 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
11457 }
11458
11459 if (!Info.getLangOpts().CPlusPlus26) {
11460 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
11461 CXXRD && CXXRD->getNumVBases()) {
11462 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
11463 return false;
11464 }
11465 }
11466
11467 return HandleClassZeroInitialization(Info, E, RD, This, Result);
11468}
11469
11470bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
11471 switch (E->getCastKind()) {
11472 default:
11473 return ExprEvaluatorBaseTy::VisitCastExpr(E);
11474
11475 case CK_ConstructorConversion:
11476 return Visit(E->getSubExpr());
11477
11478 case CK_DerivedToBase:
11479 case CK_UncheckedDerivedToBase: {
11480 APValue DerivedObject;
11481 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
11482 return false;
11483 if (!DerivedObject.isStruct())
11484 return Error(E->getSubExpr());
11485
11486 // Derived-to-base rvalue conversion: just slice off the derived part.
11487 APValue *Value = &DerivedObject;
11488 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
11489 for (CastExpr::path_const_iterator PathI = E->path_begin(),
11490 PathE = E->path_end(); PathI != PathE; ++PathI) {
11491 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
11492 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
11493 Value = &Value->getStructBase(getBaseIndex(RD, Base));
11494 RD = Base;
11495 }
11496 Result = *Value;
11497 return true;
11498 }
11499 case CK_HLSLAggregateSplatCast: {
11500 APValue Val;
11501 QualType ValTy;
11502
11503 if (!hlslAggSplatHelper(Info, E->getSubExpr(), Val, ValTy))
11504 return false;
11505
11506 unsigned NEls = elementwiseSize(Info, E->getType());
11507 // splat our Val
11508 SmallVector<APValue> SplatEls(NEls, Val);
11509 SmallVector<QualType> SplatType(NEls, ValTy);
11510
11511 // cast the elements and construct our struct result
11512 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
11513 if (!constructAggregate(Info, FPO, E, Result, E->getType(), SplatEls,
11514 SplatType))
11515 return false;
11516
11517 return true;
11518 }
11519 case CK_HLSLElementwiseCast: {
11520 SmallVector<APValue> SrcEls;
11521 SmallVector<QualType> SrcTypes;
11522
11523 if (!hlslElementwiseCastHelper(Info, E->getSubExpr(), E->getType(), SrcEls,
11524 SrcTypes))
11525 return false;
11526
11527 // cast the elements and construct our struct result
11528 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
11529 if (!constructAggregate(Info, FPO, E, Result, E->getType(), SrcEls,
11530 SrcTypes))
11531 return false;
11532
11533 return true;
11534 }
11535 case CK_ToUnion: {
11536 const FieldDecl *Field = E->getTargetUnionField();
11537 LValue Subobject = This;
11538 if (!HandleLValueMember(Info, E, Subobject, Field))
11539 return false;
11540 Result = APValue(Field);
11541 if (!EvaluateInPlace(Result.getUnionValue(), Info, Subobject,
11542 E->getSubExpr()))
11543 return false;
11544 if (Field->isBitField()) {
11545 if (!truncateBitfieldValue(Info, E->getSubExpr(), Result.getUnionValue(),
11546 Field))
11547 return false;
11548 }
11549 return true;
11550 }
11551 }
11552}
11553
11554bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
11555 if (E->isTransparent())
11556 return Visit(E->getInit(0));
11557 return VisitCXXParenListOrInitListExpr(E, E->inits());
11558}
11559
11560bool RecordExprEvaluator::VisitCXXParenListOrInitListExpr(
11561 const Expr *ExprToVisit, ArrayRef<Expr *> Args) {
11562 const auto *RD = ExprToVisit->getType()->castAsRecordDecl();
11563 if (RD->isInvalidDecl()) return false;
11564 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
11565 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
11566
11567 EvalInfo::EvaluatingConstructorRAII EvalObj(
11568 Info,
11569 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
11570 CXXRD && CXXRD->getNumBases());
11571
11572 if (RD->isUnion()) {
11573 const FieldDecl *Field;
11574 if (auto *ILE = dyn_cast<InitListExpr>(ExprToVisit)) {
11575 Field = ILE->getInitializedFieldInUnion();
11576 } else if (auto *PLIE = dyn_cast<CXXParenListInitExpr>(ExprToVisit)) {
11577 Field = PLIE->getInitializedFieldInUnion();
11578 } else {
11579 llvm_unreachable(
11580 "Expression is neither an init list nor a C++ paren list");
11581 }
11582
11583 Result = APValue(Field);
11584 if (!Field)
11585 return true;
11586
11587 // If the initializer list for a union does not contain any elements, the
11588 // first element of the union is value-initialized.
11589 // FIXME: The element should be initialized from an initializer list.
11590 // Is this difference ever observable for initializer lists which
11591 // we don't build?
11592 ImplicitValueInitExpr VIE(Field->getType());
11593 const Expr *InitExpr = Args.empty() ? &VIE : Args[0];
11594
11595 LValue Subobject = This;
11596 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
11597 return false;
11598
11599 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
11600 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
11601 isa<CXXDefaultInitExpr>(InitExpr));
11602
11603 if (EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr)) {
11604 if (Field->isBitField())
11605 return truncateBitfieldValue(Info, InitExpr, Result.getUnionValue(),
11606 Field);
11607 return true;
11608 }
11609
11610 return false;
11611 }
11612
11613 if (!Result.hasValue())
11614 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
11615 RD->getNumFields());
11616 unsigned ElementNo = 0;
11617 bool Success = true;
11618
11619 // Initialize base classes.
11620 if (CXXRD && CXXRD->getNumBases()) {
11621 for (const auto &Base : CXXRD->bases()) {
11622 assert(ElementNo < Args.size() && "missing init for base class");
11623 const Expr *Init = Args[ElementNo];
11624
11625 LValue Subobject = This;
11626 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
11627 return false;
11628
11629 APValue &FieldVal = Result.getStructBase(ElementNo);
11630 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
11631 if (!Info.noteFailure())
11632 return false;
11633 Success = false;
11634 }
11635 ++ElementNo;
11636 }
11637
11638 EvalObj.finishedConstructingBases();
11639 }
11640
11641 // Initialize members.
11642 for (const auto *Field : RD->fields()) {
11643 // Anonymous bit-fields are not considered members of the class for
11644 // purposes of aggregate initialization.
11645 if (Field->isUnnamedBitField())
11646 continue;
11647
11648 LValue Subobject = This;
11649
11650 bool HaveInit = ElementNo < Args.size();
11651
11652 // FIXME: Diagnostics here should point to the end of the initializer
11653 // list, not the start.
11654 if (!HandleLValueMember(Info, HaveInit ? Args[ElementNo] : ExprToVisit,
11655 Subobject, Field, &Layout))
11656 return false;
11657
11658 // Perform an implicit value-initialization for members beyond the end of
11659 // the initializer list.
11660 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
11661 const Expr *Init = HaveInit ? Args[ElementNo++] : &VIE;
11662
11663 // If this is a child of a DesignatedInitUpdateExpr, skip elements which
11664 // aren't supposed to be modified.
11665 if (isa<NoInitExpr>(Init))
11666 continue;
11667
11668 if (Field->getType()->isIncompleteArrayType()) {
11669 if (auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType())) {
11670 if (!CAT->isZeroSize()) {
11671 // Bail out for now. This might sort of "work", but the rest of the
11672 // code isn't really prepared to handle it.
11673 Info.FFDiag(Init, diag::note_constexpr_unsupported_flexible_array);
11674 return false;
11675 }
11676 }
11677 }
11678
11679 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
11680 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
11682
11683 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
11684 if (Field->getType()->isReferenceType()) {
11685 LValue Result;
11687 FieldVal)) {
11688 if (!Info.noteFailure())
11689 return false;
11690 Success = false;
11691 }
11692 } else if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
11693 (Field->isBitField() &&
11694 !truncateBitfieldValue(Info, Init, FieldVal, Field))) {
11695 if (!Info.noteFailure())
11696 return false;
11697 Success = false;
11698 }
11699 }
11700
11701 EvalObj.finishedConstructingFields();
11702
11703 return Success;
11704}
11705
11706bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
11707 QualType T) {
11708 // Note that E's type is not necessarily the type of our class here; we might
11709 // be initializing an array element instead.
11710 const CXXConstructorDecl *FD = E->getConstructor();
11711 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
11712
11713 bool ZeroInit = E->requiresZeroInitialization();
11714 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
11715 if (ZeroInit)
11716 return ZeroInitialization(E, T);
11717
11719 }
11720
11721 const FunctionDecl *Definition = nullptr;
11722 auto Body = FD->getBody(Definition);
11723
11724 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
11725 return false;
11726
11727 // Avoid materializing a temporary for an elidable copy/move constructor.
11728 if (E->isElidable() && !ZeroInit) {
11729 // FIXME: This only handles the simplest case, where the source object
11730 // is passed directly as the first argument to the constructor.
11731 // This should also handle stepping though implicit casts and
11732 // and conversion sequences which involve two steps, with a
11733 // conversion operator followed by a converting constructor.
11734 const Expr *SrcObj = E->getArg(0);
11735 assert(SrcObj->isTemporaryObject(Info.Ctx, FD->getParent()));
11736 assert(Info.Ctx.hasSameUnqualifiedType(E->getType(), SrcObj->getType()));
11737 if (const MaterializeTemporaryExpr *ME =
11738 dyn_cast<MaterializeTemporaryExpr>(SrcObj))
11739 return Visit(ME->getSubExpr());
11740 }
11741
11742 if (ZeroInit && !ZeroInitialization(E, T))
11743 return false;
11744
11745 auto Args = ArrayRef(E->getArgs(), E->getNumArgs());
11746 return HandleConstructorCall(E, This, Args,
11748 Result);
11749}
11750
11751bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
11752 const CXXInheritedCtorInitExpr *E) {
11753 if (!Info.CurrentCall) {
11754 assert(Info.checkingPotentialConstantExpression());
11755 return false;
11756 }
11757
11758 const CXXConstructorDecl *FD = E->getConstructor();
11759 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
11760 return false;
11761
11762 const FunctionDecl *Definition = nullptr;
11763 auto Body = FD->getBody(Definition);
11764
11765 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
11766 return false;
11767
11768 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
11770 Result);
11771}
11772
11773bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
11774 const CXXStdInitializerListExpr *E) {
11775 const ConstantArrayType *ArrayType =
11776 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
11777
11778 LValue Array;
11779 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
11780 return false;
11781
11782 assert(ArrayType && "unexpected type for array initializer");
11783
11784 // Get a pointer to the first element of the array.
11785 Array.addArray(Info, E, ArrayType);
11786
11787 // FIXME: What if the initializer_list type has base classes, etc?
11788 Result = APValue(APValue::UninitStruct(), 0, 2);
11789 Array.moveInto(Result.getStructField(0));
11790
11791 auto *Record = E->getType()->castAsRecordDecl();
11792 RecordDecl::field_iterator Field = Record->field_begin();
11793 assert(Field != Record->field_end() &&
11794 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
11795 ArrayType->getElementType()) &&
11796 "Expected std::initializer_list first field to be const E *");
11797 ++Field;
11798 assert(Field != Record->field_end() &&
11799 "Expected std::initializer_list to have two fields");
11800
11801 if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType())) {
11802 // Length.
11803 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
11804 } else {
11805 // End pointer.
11806 assert(Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
11807 ArrayType->getElementType()) &&
11808 "Expected std::initializer_list second field to be const E *");
11809 if (!HandleLValueArrayAdjustment(Info, E, Array,
11810 ArrayType->getElementType(),
11811 ArrayType->getZExtSize()))
11812 return false;
11813 Array.moveInto(Result.getStructField(1));
11814 }
11815
11816 assert(++Field == Record->field_end() &&
11817 "Expected std::initializer_list to only have two fields");
11818
11819 return true;
11820}
11821
11822bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
11823 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
11824 if (ClosureClass->isInvalidDecl())
11825 return false;
11826
11827 const size_t NumFields = ClosureClass->getNumFields();
11828
11829 assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
11830 E->capture_init_end()) &&
11831 "The number of lambda capture initializers should equal the number of "
11832 "fields within the closure type");
11833
11834 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
11835 // Iterate through all the lambda's closure object's fields and initialize
11836 // them.
11837 auto *CaptureInitIt = E->capture_init_begin();
11838 bool Success = true;
11839 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(ClosureClass);
11840 for (const auto *Field : ClosureClass->fields()) {
11841 assert(CaptureInitIt != E->capture_init_end());
11842 // Get the initializer for this field
11843 Expr *const CurFieldInit = *CaptureInitIt++;
11844
11845 // If there is no initializer, either this is a VLA or an error has
11846 // occurred.
11847 if (!CurFieldInit || CurFieldInit->containsErrors())
11848 return Error(E);
11849
11850 LValue Subobject = This;
11851
11852 if (!HandleLValueMember(Info, E, Subobject, Field, &Layout))
11853 return false;
11854
11855 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
11856 if (!EvaluateInPlace(FieldVal, Info, Subobject, CurFieldInit)) {
11857 if (!Info.keepEvaluatingAfterFailure())
11858 return false;
11859 Success = false;
11860 }
11861 }
11862 return Success;
11863}
11864
11865bool RecordExprEvaluator::VisitDesignatedInitUpdateExpr(
11866 const DesignatedInitUpdateExpr *E) {
11867 if (!Visit(E->getBase()))
11868 return false;
11869 return Visit(E->getUpdater());
11870}
11871
11872static bool EvaluateRecord(const Expr *E, const LValue &This,
11873 APValue &Result, EvalInfo &Info) {
11874 assert(!E->isValueDependent());
11875 assert(E->isPRValue() && E->getType()->isRecordType() &&
11876 "can't evaluate expression as a record rvalue");
11877 return RecordExprEvaluator(Info, This, Result).Visit(E);
11878}
11879
11880//===----------------------------------------------------------------------===//
11881// Temporary Evaluation
11882//
11883// Temporaries are represented in the AST as rvalues, but generally behave like
11884// lvalues. The full-object of which the temporary is a subobject is implicitly
11885// materialized so that a reference can bind to it.
11886//===----------------------------------------------------------------------===//
11887namespace {
11888class TemporaryExprEvaluator
11889 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
11890public:
11891 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
11892 LValueExprEvaluatorBaseTy(Info, Result, false) {}
11893
11894 /// Visit an expression which constructs the value of this temporary.
11895 bool VisitConstructExpr(const Expr *E) {
11896 APValue &Value = Info.CurrentCall->createTemporary(
11897 E, E->getType(), ScopeKind::FullExpression, Result);
11898 return EvaluateInPlace(Value, Info, Result, E);
11899 }
11900
11901 bool VisitCastExpr(const CastExpr *E) {
11902 switch (E->getCastKind()) {
11903 default:
11904 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
11905
11906 case CK_ConstructorConversion:
11907 return VisitConstructExpr(E->getSubExpr());
11908 }
11909 }
11910 bool VisitInitListExpr(const InitListExpr *E) {
11911 return VisitConstructExpr(E);
11912 }
11913 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
11914 return VisitConstructExpr(E);
11915 }
11916 bool VisitCallExpr(const CallExpr *E) {
11917 return VisitConstructExpr(E);
11918 }
11919 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
11920 return VisitConstructExpr(E);
11921 }
11922 bool VisitLambdaExpr(const LambdaExpr *E) {
11923 return VisitConstructExpr(E);
11924 }
11925};
11926} // end anonymous namespace
11927
11928/// Evaluate an expression of record type as a temporary.
11929static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
11930 assert(!E->isValueDependent());
11931 assert(E->isPRValue() && E->getType()->isRecordType());
11932 return TemporaryExprEvaluator(Info, Result).Visit(E);
11933}
11934
11935//===----------------------------------------------------------------------===//
11936// Vector Evaluation
11937//===----------------------------------------------------------------------===//
11938
11939namespace {
11940 class VectorExprEvaluator
11941 : public ExprEvaluatorBase<VectorExprEvaluator> {
11942 APValue &Result;
11943 public:
11944
11945 VectorExprEvaluator(EvalInfo &info, APValue &Result)
11946 : ExprEvaluatorBaseTy(info), Result(Result) {}
11947
11948 bool Success(ArrayRef<APValue> V, const Expr *E) {
11949 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
11950 // FIXME: remove this APValue copy.
11951 Result = APValue(V.data(), V.size());
11952 return true;
11953 }
11954 bool Success(const APValue &V, const Expr *E) {
11955 assert(V.isVector());
11956 Result = V;
11957 return true;
11958 }
11959 bool ZeroInitialization(const Expr *E);
11960
11961 bool VisitUnaryReal(const UnaryOperator *E)
11962 { return Visit(E->getSubExpr()); }
11963 bool VisitCastExpr(const CastExpr* E);
11964 bool VisitInitListExpr(const InitListExpr *E);
11965 bool VisitUnaryImag(const UnaryOperator *E);
11966 bool VisitBinaryOperator(const BinaryOperator *E);
11967 bool VisitUnaryOperator(const UnaryOperator *E);
11968 bool VisitCallExpr(const CallExpr *E);
11969 bool VisitConvertVectorExpr(const ConvertVectorExpr *E);
11970 bool VisitShuffleVectorExpr(const ShuffleVectorExpr *E);
11971
11972 // FIXME: Missing: conditional operator (for GNU
11973 // conditional select), ExtVectorElementExpr
11974 };
11975} // end anonymous namespace
11976
11977static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
11978 assert(E->isPRValue() && E->getType()->isVectorType() &&
11979 "not a vector prvalue");
11980 return VectorExprEvaluator(Info, Result).Visit(E);
11981}
11982
11983static llvm::APInt ConvertBoolVectorToInt(const APValue &Val) {
11984 assert(Val.isVector() && "expected vector APValue");
11985 unsigned NumElts = Val.getVectorLength();
11986
11987 // Each element is one bit, so create an integer with NumElts bits.
11988 llvm::APInt Result(NumElts, 0);
11989
11990 for (unsigned I = 0; I < NumElts; ++I) {
11991 const APValue &Elt = Val.getVectorElt(I);
11992 assert(Elt.isInt() && "expected integer element in bool vector");
11993
11994 if (Elt.getInt().getBoolValue())
11995 Result.setBit(I);
11996 }
11997
11998 return Result;
11999}
12000
12001bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
12002 const VectorType *VTy = E->getType()->castAs<VectorType>();
12003 unsigned NElts = VTy->getNumElements();
12004
12005 const Expr *SE = E->getSubExpr();
12006 QualType SETy = SE->getType();
12007
12008 switch (E->getCastKind()) {
12009 case CK_VectorSplat: {
12010 APValue Val = APValue();
12011 if (SETy->isIntegerType()) {
12012 APSInt IntResult;
12013 if (!EvaluateInteger(SE, IntResult, Info))
12014 return false;
12015 Val = APValue(std::move(IntResult));
12016 } else if (SETy->isRealFloatingType()) {
12017 APFloat FloatResult(0.0);
12018 if (!EvaluateFloat(SE, FloatResult, Info))
12019 return false;
12020 Val = APValue(std::move(FloatResult));
12021 } else {
12022 return Error(E);
12023 }
12024
12025 // Splat and create vector APValue.
12026 SmallVector<APValue, 4> Elts(NElts, Val);
12027 return Success(Elts, E);
12028 }
12029 case CK_BitCast: {
12030 APValue SVal;
12031 if (!Evaluate(SVal, Info, SE))
12032 return false;
12033
12034 if (!SVal.isInt() && !SVal.isFloat() && !SVal.isVector()) {
12035 // Give up if the input isn't an int, float, or vector. For example, we
12036 // reject "(v4i16)(intptr_t)&a".
12037 Info.FFDiag(E, diag::note_constexpr_invalid_cast)
12038 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
12039 << Info.Ctx.getLangOpts().CPlusPlus;
12040 return false;
12041 }
12042
12043 if (!handleRValueToRValueBitCast(Info, Result, SVal, E))
12044 return false;
12045
12046 return true;
12047 }
12048 case CK_HLSLVectorTruncation: {
12049 APValue Val;
12050 SmallVector<APValue, 4> Elements;
12051 if (!EvaluateVector(SE, Val, Info))
12052 return Error(E);
12053 for (unsigned I = 0; I < NElts; I++)
12054 Elements.push_back(Val.getVectorElt(I));
12055 return Success(Elements, E);
12056 }
12057 case CK_HLSLMatrixTruncation: {
12058 // Matrix truncation occurs in row-major order.
12059 APValue Val;
12060 if (!EvaluateMatrix(SE, Val, Info))
12061 return Error(E);
12062 SmallVector<APValue, 16> Elements;
12063 for (unsigned Row = 0;
12064 Row < Val.getMatrixNumRows() && Elements.size() < NElts; Row++)
12065 for (unsigned Col = 0;
12066 Col < Val.getMatrixNumColumns() && Elements.size() < NElts; Col++)
12067 Elements.push_back(Val.getMatrixElt(Row, Col));
12068 return Success(Elements, E);
12069 }
12070 case CK_HLSLAggregateSplatCast: {
12071 APValue Val;
12072 QualType ValTy;
12073
12074 if (!hlslAggSplatHelper(Info, SE, Val, ValTy))
12075 return false;
12076
12077 // cast our Val once.
12079 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
12080 if (!handleScalarCast(Info, FPO, E, ValTy, VTy->getElementType(), Val,
12081 Result))
12082 return false;
12083
12084 SmallVector<APValue, 4> SplatEls(NElts, Result);
12085 return Success(SplatEls, E);
12086 }
12087 case CK_HLSLElementwiseCast: {
12088 SmallVector<APValue> SrcVals;
12089 SmallVector<QualType> SrcTypes;
12090
12091 if (!hlslElementwiseCastHelper(Info, SE, E->getType(), SrcVals, SrcTypes))
12092 return false;
12093
12094 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
12095 SmallVector<QualType, 4> DestTypes(NElts, VTy->getElementType());
12096 SmallVector<APValue, 4> ResultEls(NElts);
12097 if (!handleElementwiseCast(Info, E, FPO, SrcVals, SrcTypes, DestTypes,
12098 ResultEls))
12099 return false;
12100 return Success(ResultEls, E);
12101 }
12102 case CK_IntegralToFloating:
12103 case CK_FloatingToIntegral:
12104 case CK_IntegralCast:
12105 case CK_FloatingCast:
12106 case CK_FloatingToBoolean:
12107 case CK_IntegralToBoolean: {
12108 // These casts apply element-wise when the source is a vector type.
12109 assert(SETy->isVectorType() && "expected vector source type");
12110 APValue SrcVal;
12111 if (!EvaluateVector(SE, SrcVal, Info))
12112 return Error(E);
12113
12114 assert(SrcVal.getVectorLength() == NElts);
12115 QualType SrcEltTy = SETy->castAs<VectorType>()->getElementType();
12116 QualType DstEltTy = VTy->getElementType();
12117 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
12118
12119 SmallVector<APValue, 4> ResultEls(NElts);
12120 for (unsigned I = 0; I < NElts; ++I) {
12121 if (!handleScalarCast(Info, FPO, E, SrcEltTy, DstEltTy,
12122 SrcVal.getVectorElt(I), ResultEls[I]))
12123 return Error(E);
12124 }
12125 return Success(ResultEls, E);
12126 }
12127 default:
12128 return ExprEvaluatorBaseTy::VisitCastExpr(E);
12129 }
12130}
12131
12132bool
12133VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
12134 const VectorType *VT = E->getType()->castAs<VectorType>();
12135 unsigned NumInits = E->getNumInits();
12136 unsigned NumElements = VT->getNumElements();
12137
12138 QualType EltTy = VT->getElementType();
12139 SmallVector<APValue, 4> Elements;
12140
12141 // MFloat8 type doesn't have constants and thus constant folding
12142 // is impossible.
12143 if (EltTy->isMFloat8Type())
12144 return false;
12145
12146 // The number of initializers can be less than the number of
12147 // vector elements. For OpenCL, this can be due to nested vector
12148 // initialization. For GCC compatibility, missing trailing elements
12149 // should be initialized with zeroes.
12150 unsigned CountInits = 0, CountElts = 0;
12151 while (CountElts < NumElements) {
12152 // Handle nested vector initialization.
12153 if (CountInits < NumInits
12154 && E->getInit(CountInits)->getType()->isVectorType()) {
12155 APValue v;
12156 if (!EvaluateVector(E->getInit(CountInits), v, Info))
12157 return Error(E);
12158 unsigned vlen = v.getVectorLength();
12159 for (unsigned j = 0; j < vlen; j++)
12160 Elements.push_back(v.getVectorElt(j));
12161 CountElts += vlen;
12162 } else if (EltTy->isIntegerType()) {
12163 llvm::APSInt sInt(32);
12164 if (CountInits < NumInits) {
12165 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
12166 return false;
12167 } else // trailing integer zero.
12168 sInt = Info.Ctx.MakeIntValue(0, EltTy);
12169 Elements.push_back(APValue(sInt));
12170 CountElts++;
12171 } else {
12172 llvm::APFloat f(0.0);
12173 if (CountInits < NumInits) {
12174 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
12175 return false;
12176 } else // trailing float zero.
12177 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
12178 Elements.push_back(APValue(f));
12179 CountElts++;
12180 }
12181 CountInits++;
12182 }
12183 return Success(Elements, E);
12184}
12185
12186bool
12187VectorExprEvaluator::ZeroInitialization(const Expr *E) {
12188 const auto *VT = E->getType()->castAs<VectorType>();
12189 QualType EltTy = VT->getElementType();
12190 APValue ZeroElement;
12191 if (EltTy->isIntegerType())
12192 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
12193 else
12194 ZeroElement =
12195 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
12196
12197 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
12198 return Success(Elements, E);
12199}
12200
12201bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
12202 VisitIgnoredValue(E->getSubExpr());
12203 return ZeroInitialization(E);
12204}
12205
12206bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
12207 BinaryOperatorKind Op = E->getOpcode();
12208 assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp &&
12209 "Operation not supported on vector types");
12210
12211 if (Op == BO_Comma)
12212 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
12213
12214 Expr *LHS = E->getLHS();
12215 Expr *RHS = E->getRHS();
12216
12217 [[maybe_unused]] QualType LHSType = LHS->getType().getAtomicUnqualifiedType();
12218 [[maybe_unused]] QualType RHSType = RHS->getType().getAtomicUnqualifiedType();
12219 assert(LHSType->isVectorType() && RHSType->isVectorType() &&
12220 "Must both be vector types");
12221 // Checking JUST the types are the same would be fine, except shifts don't
12222 // need to have their types be the same (since you always shift by an int).
12223 assert(LHSType->castAs<VectorType>()->getNumElements() ==
12224 E->getType()->castAs<VectorType>()->getNumElements() &&
12225 RHSType->castAs<VectorType>()->getNumElements() ==
12226 E->getType()->castAs<VectorType>()->getNumElements() &&
12227 "All operands must be the same size.");
12228
12229 APValue LHSValue;
12230 APValue RHSValue;
12231 bool LHSOK = Evaluate(LHSValue, Info, LHS);
12232 if (!LHSOK && !Info.noteFailure())
12233 return false;
12234 if (!Evaluate(RHSValue, Info, RHS) || !LHSOK)
12235 return false;
12236
12237 if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue))
12238 return false;
12239
12240 return Success(LHSValue, E);
12241}
12242
12243static std::optional<APValue> handleVectorUnaryOperator(ASTContext &Ctx,
12244 QualType ResultTy,
12246 APValue Elt) {
12247 switch (Op) {
12248 case UO_Plus:
12249 // Nothing to do here.
12250 return Elt;
12251 case UO_Minus:
12252 if (Elt.getKind() == APValue::Int) {
12253 Elt.getInt().negate();
12254 } else {
12255 assert(Elt.getKind() == APValue::Float &&
12256 "Vector can only be int or float type");
12257 Elt.getFloat().changeSign();
12258 }
12259 return Elt;
12260 case UO_Not:
12261 // This is only valid for integral types anyway, so we don't have to handle
12262 // float here.
12263 assert(Elt.getKind() == APValue::Int &&
12264 "Vector operator ~ can only be int");
12265 Elt.getInt().flipAllBits();
12266 return Elt;
12267 case UO_LNot: {
12268 if (Elt.getKind() == APValue::Int) {
12269 Elt.getInt() = !Elt.getInt();
12270 // operator ! on vectors returns -1 for 'truth', so negate it.
12271 Elt.getInt().negate();
12272 return Elt;
12273 }
12274 assert(Elt.getKind() == APValue::Float &&
12275 "Vector can only be int or float type");
12276 // Float types result in an int of the same size, but -1 for true, or 0 for
12277 // false.
12278 APSInt EltResult{Ctx.getIntWidth(ResultTy),
12279 ResultTy->isUnsignedIntegerType()};
12280 if (Elt.getFloat().isZero())
12281 EltResult.setAllBits();
12282 else
12283 EltResult.clearAllBits();
12284
12285 return APValue{EltResult};
12286 }
12287 default:
12288 // FIXME: Implement the rest of the unary operators.
12289 return std::nullopt;
12290 }
12291}
12292
12293bool VectorExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
12294 Expr *SubExpr = E->getSubExpr();
12295 const auto *VD = SubExpr->getType()->castAs<VectorType>();
12296 // This result element type differs in the case of negating a floating point
12297 // vector, since the result type is the a vector of the equivilant sized
12298 // integer.
12299 const QualType ResultEltTy = VD->getElementType();
12300 UnaryOperatorKind Op = E->getOpcode();
12301
12302 APValue SubExprValue;
12303 if (!Evaluate(SubExprValue, Info, SubExpr))
12304 return false;
12305
12306 // FIXME: This vector evaluator someday needs to be changed to be LValue
12307 // aware/keep LValue information around, rather than dealing with just vector
12308 // types directly. Until then, we cannot handle cases where the operand to
12309 // these unary operators is an LValue. The only case I've been able to see
12310 // cause this is operator++ assigning to a member expression (only valid in
12311 // altivec compilations) in C mode, so this shouldn't limit us too much.
12312 if (SubExprValue.isLValue())
12313 return false;
12314
12315 assert(SubExprValue.getVectorLength() == VD->getNumElements() &&
12316 "Vector length doesn't match type?");
12317
12318 SmallVector<APValue, 4> ResultElements;
12319 for (unsigned EltNum = 0; EltNum < VD->getNumElements(); ++EltNum) {
12320 std::optional<APValue> Elt = handleVectorUnaryOperator(
12321 Info.Ctx, ResultEltTy, Op, SubExprValue.getVectorElt(EltNum));
12322 if (!Elt)
12323 return false;
12324 ResultElements.push_back(*Elt);
12325 }
12326 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12327}
12328
12329static bool handleVectorElementCast(EvalInfo &Info, const FPOptions FPO,
12330 const Expr *E, QualType SourceTy,
12331 QualType DestTy, APValue const &Original,
12332 APValue &Result) {
12333 if (SourceTy->isIntegerType()) {
12334 if (DestTy->isRealFloatingType()) {
12335 Result = APValue(APFloat(0.0));
12336 return HandleIntToFloatCast(Info, E, FPO, SourceTy, Original.getInt(),
12337 DestTy, Result.getFloat());
12338 }
12339 if (DestTy->isIntegerType()) {
12340 Result = APValue(
12341 HandleIntToIntCast(Info, E, DestTy, SourceTy, Original.getInt()));
12342 return true;
12343 }
12344 } else if (SourceTy->isRealFloatingType()) {
12345 if (DestTy->isRealFloatingType()) {
12346 Result = Original;
12347 return HandleFloatToFloatCast(Info, E, SourceTy, DestTy,
12348 Result.getFloat());
12349 }
12350 if (DestTy->isIntegerType()) {
12351 Result = APValue(APSInt());
12352 return HandleFloatToIntCast(Info, E, SourceTy, Original.getFloat(),
12353 DestTy, Result.getInt());
12354 }
12355 }
12356
12357 Info.FFDiag(E, diag::err_convertvector_constexpr_unsupported_vector_cast)
12358 << SourceTy << DestTy;
12359 return false;
12360}
12361
12362static bool evalPackBuiltin(const CallExpr *E, EvalInfo &Info, APValue &Result,
12363 llvm::function_ref<APInt(const APSInt &)> PackFn) {
12364 APValue LHS, RHS;
12365 if (!EvaluateAsRValue(Info, E->getArg(0), LHS) ||
12366 !EvaluateAsRValue(Info, E->getArg(1), RHS))
12367 return false;
12368
12369 unsigned LHSVecLen = LHS.getVectorLength();
12370 unsigned RHSVecLen = RHS.getVectorLength();
12371
12372 assert(LHSVecLen != 0 && LHSVecLen == RHSVecLen &&
12373 "pack builtin LHSVecLen must equal to RHSVecLen");
12374
12375 const VectorType *VT0 = E->getArg(0)->getType()->castAs<VectorType>();
12376 const unsigned SrcBits = Info.Ctx.getIntWidth(VT0->getElementType());
12377
12378 const VectorType *DstVT = E->getType()->castAs<VectorType>();
12379 QualType DstElemTy = DstVT->getElementType();
12380 const bool DstIsUnsigned = DstElemTy->isUnsignedIntegerType();
12381
12382 const unsigned SrcPerLane = 128 / SrcBits;
12383 const unsigned Lanes = LHSVecLen * SrcBits / 128;
12384
12386 Out.reserve(LHSVecLen + RHSVecLen);
12387
12388 for (unsigned Lane = 0; Lane != Lanes; ++Lane) {
12389 unsigned base = Lane * SrcPerLane;
12390 for (unsigned I = 0; I != SrcPerLane; ++I)
12391 Out.emplace_back(APValue(
12392 APSInt(PackFn(LHS.getVectorElt(base + I).getInt()), DstIsUnsigned)));
12393 for (unsigned I = 0; I != SrcPerLane; ++I)
12394 Out.emplace_back(APValue(
12395 APSInt(PackFn(RHS.getVectorElt(base + I).getInt()), DstIsUnsigned)));
12396 }
12397
12398 Result = APValue(Out.data(), Out.size());
12399 return true;
12400}
12401
12403 EvalInfo &Info, const CallExpr *Call, APValue &Out,
12404 llvm::function_ref<std::pair<unsigned, int>(unsigned, unsigned)>
12405 GetSourceIndex) {
12406
12407 const auto *VT = Call->getType()->getAs<VectorType>();
12408 if (!VT)
12409 return false;
12410
12411 unsigned ShuffleMask = 0;
12412 APValue A, MaskVector, B;
12413 bool IsVectorMask = false;
12414 bool IsSingleOperand = (Call->getNumArgs() == 2);
12415
12416 if (IsSingleOperand) {
12417 QualType MaskType = Call->getArg(1)->getType();
12418 if (MaskType->isVectorType()) {
12419 IsVectorMask = true;
12420 if (!EvaluateAsRValue(Info, Call->getArg(0), A) ||
12421 !EvaluateAsRValue(Info, Call->getArg(1), MaskVector))
12422 return false;
12423 B = A;
12424 } else if (MaskType->isIntegerType()) {
12425 APSInt MaskImm;
12426 if (!EvaluateInteger(Call->getArg(1), MaskImm, Info))
12427 return false;
12428 ShuffleMask = static_cast<unsigned>(MaskImm.getZExtValue());
12429 if (!EvaluateAsRValue(Info, Call->getArg(0), A))
12430 return false;
12431 B = A;
12432 } else {
12433 return false;
12434 }
12435 } else {
12436 QualType Arg2Type = Call->getArg(2)->getType();
12437 if (Arg2Type->isVectorType()) {
12438 IsVectorMask = true;
12439 if (!EvaluateAsRValue(Info, Call->getArg(0), A) ||
12440 !EvaluateAsRValue(Info, Call->getArg(1), MaskVector) ||
12441 !EvaluateAsRValue(Info, Call->getArg(2), B))
12442 return false;
12443 } else if (Arg2Type->isIntegerType()) {
12444 APSInt MaskImm;
12445 if (!EvaluateInteger(Call->getArg(2), MaskImm, Info))
12446 return false;
12447 ShuffleMask = static_cast<unsigned>(MaskImm.getZExtValue());
12448 if (!EvaluateAsRValue(Info, Call->getArg(0), A) ||
12449 !EvaluateAsRValue(Info, Call->getArg(1), B))
12450 return false;
12451 } else {
12452 return false;
12453 }
12454 }
12455
12456 unsigned NumElts = VT->getNumElements();
12457 SmallVector<APValue, 64> ResultElements;
12458 ResultElements.reserve(NumElts);
12459
12460 for (unsigned DstIdx = 0; DstIdx != NumElts; ++DstIdx) {
12461 if (IsVectorMask) {
12462 ShuffleMask = static_cast<unsigned>(
12463 MaskVector.getVectorElt(DstIdx).getInt().getZExtValue());
12464 }
12465 auto [SrcVecIdx, SrcIdx] = GetSourceIndex(DstIdx, ShuffleMask);
12466
12467 if (SrcIdx < 0) {
12468 // Zero out this element
12469 QualType ElemTy = VT->getElementType();
12470 if (ElemTy->isRealFloatingType()) {
12471 ResultElements.push_back(
12472 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy))));
12473 } else if (ElemTy->isIntegerType()) {
12474 APValue Zero(Info.Ctx.MakeIntValue(0, ElemTy));
12475 ResultElements.push_back(APValue(Zero));
12476 } else {
12477 // Other types of fallback logic
12478 ResultElements.push_back(APValue());
12479 }
12480 } else {
12481 const APValue &Src = (SrcVecIdx == 0) ? A : B;
12482 ResultElements.push_back(Src.getVectorElt(SrcIdx));
12483 }
12484 }
12485
12486 Out = APValue(ResultElements.data(), ResultElements.size());
12487 return true;
12488}
12489static bool ConvertDoubleToFloatStrict(EvalInfo &Info, const Expr *E,
12490 APFloat OrigVal, APValue &Result) {
12491
12492 if (OrigVal.isInfinity()) {
12493 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << 0;
12494 return false;
12495 }
12496 if (OrigVal.isNaN()) {
12497 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << 1;
12498 return false;
12499 }
12500
12501 APFloat Val = OrigVal;
12502 bool LosesInfo = false;
12503 APFloat::opStatus Status = Val.convert(
12504 APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, &LosesInfo);
12505
12506 if (LosesInfo || Val.isDenormal()) {
12507 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic_strict);
12508 return false;
12509 }
12510
12511 if (Status != APFloat::opOK) {
12512 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
12513 return false;
12514 }
12515
12516 Result = APValue(Val);
12517 return true;
12518}
12520 EvalInfo &Info, const CallExpr *Call, APValue &Out,
12521 llvm::function_ref<APInt(const APInt &, uint64_t)> ShiftOp,
12522 llvm::function_ref<APInt(const APInt &, unsigned)> OverflowOp) {
12523
12524 APValue Source, Count;
12525 if (!EvaluateAsRValue(Info, Call->getArg(0), Source) ||
12526 !EvaluateAsRValue(Info, Call->getArg(1), Count))
12527 return false;
12528
12529 assert(Call->getNumArgs() == 2);
12530
12531 QualType SourceTy = Call->getArg(0)->getType();
12532 assert(SourceTy->isVectorType() &&
12533 Call->getArg(1)->getType()->isVectorType());
12534
12535 QualType DestEltTy = SourceTy->castAs<VectorType>()->getElementType();
12536 unsigned DestEltWidth = Source.getVectorElt(0).getInt().getBitWidth();
12537 unsigned DestLen = Source.getVectorLength();
12538 bool IsDestUnsigned = DestEltTy->isUnsignedIntegerType();
12539 unsigned CountEltWidth = Count.getVectorElt(0).getInt().getBitWidth();
12540 unsigned NumBitsInQWord = 64;
12541 unsigned NumCountElts = NumBitsInQWord / CountEltWidth;
12543 Result.reserve(DestLen);
12544
12545 uint64_t CountLQWord = 0;
12546 for (unsigned EltIdx = 0; EltIdx != NumCountElts; ++EltIdx) {
12547 uint64_t Elt = Count.getVectorElt(EltIdx).getInt().getZExtValue();
12548 CountLQWord |= (Elt << (EltIdx * CountEltWidth));
12549 }
12550
12551 for (unsigned EltIdx = 0; EltIdx != DestLen; ++EltIdx) {
12552 APInt Elt = Source.getVectorElt(EltIdx).getInt();
12553 if (CountLQWord < DestEltWidth) {
12554 Result.push_back(
12555 APValue(APSInt(ShiftOp(Elt, CountLQWord), IsDestUnsigned)));
12556 } else {
12557 Result.push_back(
12558 APValue(APSInt(OverflowOp(Elt, DestEltWidth), IsDestUnsigned)));
12559 }
12560 }
12561 Out = APValue(Result.data(), Result.size());
12562 return true;
12563}
12564
12565std::optional<APFloat> EvalScalarMinMaxFp(const APFloat &A, const APFloat &B,
12566 std::optional<APSInt> RoundingMode,
12567 bool IsMin) {
12568 APSInt DefaultMode(APInt(32, 4), /*isUnsigned=*/true);
12569 if (RoundingMode.value_or(DefaultMode) != 4)
12570 return std::nullopt;
12571 if (A.isNaN() || A.isInfinity() || A.isDenormal() || B.isNaN() ||
12572 B.isInfinity() || B.isDenormal())
12573 return std::nullopt;
12574 if (A.isZero() && B.isZero())
12575 return B;
12576 return IsMin ? llvm::minimum(A, B) : llvm::maximum(A, B);
12577}
12578
12579bool VectorExprEvaluator::VisitCallExpr(const CallExpr *E) {
12580 if (!IsConstantEvaluatedBuiltinCall(E))
12581 return ExprEvaluatorBaseTy::VisitCallExpr(E);
12582
12583 unsigned BuiltinOp = ConvertBuiltinIDToX86BuiltinID(Info.Ctx, E);
12584
12585 auto EvaluateBinOpExpr =
12586 [&](llvm::function_ref<APInt(const APSInt &, const APSInt &)> Fn) {
12587 APValue SourceLHS, SourceRHS;
12588 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
12589 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
12590 return false;
12591
12592 auto *DestTy = E->getType()->castAs<VectorType>();
12593 QualType DestEltTy = DestTy->getElementType();
12594 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
12595 unsigned SourceLen = SourceLHS.getVectorLength();
12596 SmallVector<APValue, 4> ResultElements;
12597 ResultElements.reserve(SourceLen);
12598
12599 if (SourceRHS.isInt()) {
12600 const APSInt &RHS = SourceRHS.getInt();
12601 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12602 const APSInt &LHS = SourceLHS.getVectorElt(EltNum).getInt();
12603 ResultElements.push_back(
12604 APValue(APSInt(Fn(LHS, RHS), DestUnsigned)));
12605 }
12606 } else {
12607 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12608 const APSInt &LHS = SourceLHS.getVectorElt(EltNum).getInt();
12609 const APSInt &RHS = SourceRHS.getVectorElt(EltNum).getInt();
12610 ResultElements.push_back(
12611 APValue(APSInt(Fn(LHS, RHS), DestUnsigned)));
12612 }
12613 }
12614 return Success(APValue(ResultElements.data(), SourceLen), E);
12615 };
12616
12617 auto EvaluateFpBinOpExpr =
12618 [&](llvm::function_ref<std::optional<APFloat>(
12619 const APFloat &, const APFloat &, std::optional<APSInt>)>
12620 Fn,
12621 bool IsScalar = false) {
12622 assert(E->getNumArgs() == 2 || E->getNumArgs() == 3);
12623 APValue A, B;
12624 if (!EvaluateAsRValue(Info, E->getArg(0), A) ||
12625 !EvaluateAsRValue(Info, E->getArg(1), B))
12626 return false;
12627
12628 assert(A.isVector() && B.isVector());
12629 assert(A.getVectorLength() == B.getVectorLength());
12630
12631 std::optional<APSInt> RoundingMode;
12632 if (E->getNumArgs() == 3) {
12633 APSInt Imm;
12634 if (!EvaluateInteger(E->getArg(2), Imm, Info))
12635 return false;
12636 RoundingMode = Imm;
12637 }
12638
12639 unsigned NumElems = A.getVectorLength();
12640 SmallVector<APValue, 4> ResultElements;
12641 ResultElements.reserve(NumElems);
12642
12643 for (unsigned EltNum = 0; EltNum < NumElems; ++EltNum) {
12644 if (IsScalar && EltNum > 0) {
12645 ResultElements.push_back(A.getVectorElt(EltNum));
12646 continue;
12647 }
12648 const APFloat &EltA = A.getVectorElt(EltNum).getFloat();
12649 const APFloat &EltB = B.getVectorElt(EltNum).getFloat();
12650 std::optional<APFloat> Result = Fn(EltA, EltB, RoundingMode);
12651 if (!Result)
12652 return false;
12653 ResultElements.push_back(APValue(*Result));
12654 }
12655 return Success(APValue(ResultElements.data(), NumElems), E);
12656 };
12657
12658 auto EvaluateScalarFpRoundMaskBinOp =
12659 [&](llvm::function_ref<std::optional<APFloat>(
12660 const APFloat &, const APFloat &, std::optional<APSInt>)>
12661 Fn) {
12662 assert(E->getNumArgs() == 5);
12663 APValue VecA, VecB, VecSrc;
12664 APSInt MaskVal, Rounding;
12665
12666 if (!EvaluateAsRValue(Info, E->getArg(0), VecA) ||
12667 !EvaluateAsRValue(Info, E->getArg(1), VecB) ||
12668 !EvaluateAsRValue(Info, E->getArg(2), VecSrc) ||
12669 !EvaluateInteger(E->getArg(3), MaskVal, Info) ||
12670 !EvaluateInteger(E->getArg(4), Rounding, Info))
12671 return false;
12672
12673 unsigned NumElems = VecA.getVectorLength();
12674 SmallVector<APValue, 8> ResultElements;
12675 ResultElements.reserve(NumElems);
12676
12677 if (MaskVal.getZExtValue() & 1) {
12678 const APFloat &EltA = VecA.getVectorElt(0).getFloat();
12679 const APFloat &EltB = VecB.getVectorElt(0).getFloat();
12680 std::optional<APFloat> Result = Fn(EltA, EltB, Rounding);
12681 if (!Result)
12682 return false;
12683 ResultElements.push_back(APValue(*Result));
12684 } else {
12685 ResultElements.push_back(VecSrc.getVectorElt(0));
12686 }
12687
12688 for (unsigned I = 1; I < NumElems; ++I)
12689 ResultElements.push_back(VecA.getVectorElt(I));
12690
12691 return Success(APValue(ResultElements.data(), NumElems), E);
12692 };
12693
12694 auto EvalSelectScalar = [&](unsigned Len) -> bool {
12695 APSInt Mask;
12696 APValue AVal, WVal;
12697 if (!EvaluateInteger(E->getArg(0), Mask, Info) ||
12698 !EvaluateAsRValue(Info, E->getArg(1), AVal) ||
12699 !EvaluateAsRValue(Info, E->getArg(2), WVal))
12700 return false;
12701
12702 bool TakeA0 = (Mask.getZExtValue() & 1u) != 0;
12704 Res.reserve(Len);
12705 Res.push_back(TakeA0 ? AVal.getVectorElt(0) : WVal.getVectorElt(0));
12706 for (unsigned I = 1; I < Len; ++I)
12707 Res.push_back(WVal.getVectorElt(I));
12708 APValue V(Res.data(), Res.size());
12709 return Success(V, E);
12710 };
12711
12712 auto EvalVectorDotProduct = [&](bool IsSaturating) -> bool {
12713 APValue Source, OperandA, OperandB;
12714 if (!EvaluateVector(E->getArg(0), Source, Info) ||
12715 !EvaluateVector(E->getArg(1), OperandA, Info) ||
12716 !EvaluateVector(E->getArg(2), OperandB, Info)) {
12717 return false;
12718 }
12719
12720 unsigned NumSrcElems = Source.getVectorLength();
12721 unsigned NumOperandElems = OperandA.getVectorLength();
12722 unsigned ElemsPerLane = NumOperandElems / NumSrcElems;
12723
12724 assert(OperandA.getVectorLength() == OperandB.getVectorLength());
12725
12727 Result.reserve(NumSrcElems);
12728 for (unsigned I = 0; I != NumSrcElems; ++I) {
12729 APSInt DotProduct = Source.getVectorElt(I).getInt();
12730 DotProduct = DotProduct.extend(64);
12731 for (unsigned J = 0; J != ElemsPerLane; ++J) {
12732 APSInt OpA = APSInt(
12733 OperandA.getVectorElt(ElemsPerLane * I + J).getInt().extend(64),
12734 false);
12735 APSInt OpB = APSInt(
12736 OperandB.getVectorElt(ElemsPerLane * I + J).getInt().extend(64),
12737 false);
12738 DotProduct += OpA * OpB;
12739 }
12740 if (IsSaturating) {
12741 DotProduct = APSInt(DotProduct.truncSSat(32), false);
12742 } else {
12743 DotProduct = APSInt(DotProduct.trunc(32), false);
12744 }
12745 Result.push_back(APValue(DotProduct));
12746 }
12747
12748 return Success(APValue(Result.data(), Result.size()), E);
12749 };
12750
12751 switch (BuiltinOp) {
12752 default:
12753 return false;
12754 case Builtin::BI__builtin_elementwise_popcount:
12755 case Builtin::BI__builtin_elementwise_bitreverse: {
12756 APValue Source;
12757 if (!EvaluateAsRValue(Info, E->getArg(0), Source))
12758 return false;
12759
12760 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
12761 unsigned SourceLen = Source.getVectorLength();
12762 SmallVector<APValue, 4> ResultElements;
12763 ResultElements.reserve(SourceLen);
12764
12765 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12766 APSInt Elt = Source.getVectorElt(EltNum).getInt();
12767 switch (BuiltinOp) {
12768 case Builtin::BI__builtin_elementwise_popcount:
12769 ResultElements.push_back(APValue(
12770 APSInt(APInt(Info.Ctx.getIntWidth(DestEltTy), Elt.popcount()),
12771 DestEltTy->isUnsignedIntegerOrEnumerationType())));
12772 break;
12773 case Builtin::BI__builtin_elementwise_bitreverse:
12774 ResultElements.push_back(
12775 APValue(APSInt(Elt.reverseBits(),
12776 DestEltTy->isUnsignedIntegerOrEnumerationType())));
12777 break;
12778 }
12779 }
12780
12781 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12782 }
12783 case Builtin::BI__builtin_elementwise_abs: {
12784 APValue Source;
12785 if (!EvaluateAsRValue(Info, E->getArg(0), Source))
12786 return false;
12787
12788 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
12789 unsigned SourceLen = Source.getVectorLength();
12790 SmallVector<APValue, 4> ResultElements;
12791 ResultElements.reserve(SourceLen);
12792
12793 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12794 APValue CurrentEle = Source.getVectorElt(EltNum);
12795 APValue Val = DestEltTy->isFloatingType()
12796 ? APValue(llvm::abs(CurrentEle.getFloat()))
12797 : APValue(APSInt(
12798 CurrentEle.getInt().abs(),
12799 DestEltTy->isUnsignedIntegerOrEnumerationType()));
12800 ResultElements.push_back(Val);
12801 }
12802
12803 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12804 }
12805
12806 case Builtin::BI__builtin_elementwise_add_sat:
12807 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
12808 return LHS.isSigned() ? LHS.sadd_sat(RHS) : LHS.uadd_sat(RHS);
12809 });
12810
12811 case Builtin::BI__builtin_elementwise_sub_sat:
12812 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
12813 return LHS.isSigned() ? LHS.ssub_sat(RHS) : LHS.usub_sat(RHS);
12814 });
12815
12816 case X86::BI__builtin_ia32_extract128i256:
12817 case X86::BI__builtin_ia32_vextractf128_pd256:
12818 case X86::BI__builtin_ia32_vextractf128_ps256:
12819 case X86::BI__builtin_ia32_vextractf128_si256: {
12820 APValue SourceVec, SourceImm;
12821 if (!EvaluateAsRValue(Info, E->getArg(0), SourceVec) ||
12822 !EvaluateAsRValue(Info, E->getArg(1), SourceImm))
12823 return false;
12824
12825 if (!SourceVec.isVector())
12826 return false;
12827
12828 const auto *RetVT = E->getType()->castAs<VectorType>();
12829 unsigned RetLen = RetVT->getNumElements();
12830 unsigned Idx = SourceImm.getInt().getZExtValue() & 1;
12831
12832 SmallVector<APValue, 32> ResultElements;
12833 ResultElements.reserve(RetLen);
12834
12835 for (unsigned I = 0; I < RetLen; I++)
12836 ResultElements.push_back(SourceVec.getVectorElt(Idx * RetLen + I));
12837
12838 return Success(APValue(ResultElements.data(), RetLen), E);
12839 }
12840
12841 case clang::X86::BI__builtin_ia32_cvtmask2b128:
12842 case clang::X86::BI__builtin_ia32_cvtmask2b256:
12843 case clang::X86::BI__builtin_ia32_cvtmask2b512:
12844 case clang::X86::BI__builtin_ia32_cvtmask2w128:
12845 case clang::X86::BI__builtin_ia32_cvtmask2w256:
12846 case clang::X86::BI__builtin_ia32_cvtmask2w512:
12847 case clang::X86::BI__builtin_ia32_cvtmask2d128:
12848 case clang::X86::BI__builtin_ia32_cvtmask2d256:
12849 case clang::X86::BI__builtin_ia32_cvtmask2d512:
12850 case clang::X86::BI__builtin_ia32_cvtmask2q128:
12851 case clang::X86::BI__builtin_ia32_cvtmask2q256:
12852 case clang::X86::BI__builtin_ia32_cvtmask2q512: {
12853 assert(E->getNumArgs() == 1);
12854 APSInt Mask;
12855 if (!EvaluateInteger(E->getArg(0), Mask, Info))
12856 return false;
12857
12858 QualType VecTy = E->getType();
12859 const VectorType *VT = VecTy->castAs<VectorType>();
12860 unsigned VectorLen = VT->getNumElements();
12861 QualType ElemTy = VT->getElementType();
12862 unsigned ElemWidth = Info.Ctx.getTypeSize(ElemTy);
12863
12865 for (unsigned I = 0; I != VectorLen; ++I) {
12866 bool BitSet = Mask[I];
12867 APSInt ElemVal(ElemWidth, /*isUnsigned=*/false);
12868 if (BitSet) {
12869 ElemVal.setAllBits();
12870 }
12871 Elems.push_back(APValue(ElemVal));
12872 }
12873 return Success(APValue(Elems.data(), VectorLen), E);
12874 }
12875
12876 case X86::BI__builtin_ia32_extracti32x4_256_mask:
12877 case X86::BI__builtin_ia32_extractf32x4_256_mask:
12878 case X86::BI__builtin_ia32_extracti32x4_mask:
12879 case X86::BI__builtin_ia32_extractf32x4_mask:
12880 case X86::BI__builtin_ia32_extracti32x8_mask:
12881 case X86::BI__builtin_ia32_extractf32x8_mask:
12882 case X86::BI__builtin_ia32_extracti64x2_256_mask:
12883 case X86::BI__builtin_ia32_extractf64x2_256_mask:
12884 case X86::BI__builtin_ia32_extracti64x2_512_mask:
12885 case X86::BI__builtin_ia32_extractf64x2_512_mask:
12886 case X86::BI__builtin_ia32_extracti64x4_mask:
12887 case X86::BI__builtin_ia32_extractf64x4_mask: {
12888 APValue SourceVec, MergeVec;
12889 APSInt Imm, MaskImm;
12890
12891 if (!EvaluateAsRValue(Info, E->getArg(0), SourceVec) ||
12892 !EvaluateInteger(E->getArg(1), Imm, Info) ||
12893 !EvaluateAsRValue(Info, E->getArg(2), MergeVec) ||
12894 !EvaluateInteger(E->getArg(3), MaskImm, Info))
12895 return false;
12896
12897 const auto *RetVT = E->getType()->castAs<VectorType>();
12898 unsigned RetLen = RetVT->getNumElements();
12899
12900 if (!SourceVec.isVector() || !MergeVec.isVector())
12901 return false;
12902 unsigned SrcLen = SourceVec.getVectorLength();
12903 unsigned Lanes = SrcLen / RetLen;
12904 unsigned Lane = static_cast<unsigned>(Imm.getZExtValue() % Lanes);
12905 unsigned Base = Lane * RetLen;
12906
12907 SmallVector<APValue, 32> ResultElements;
12908 ResultElements.reserve(RetLen);
12909 for (unsigned I = 0; I < RetLen; ++I) {
12910 if (MaskImm[I])
12911 ResultElements.push_back(SourceVec.getVectorElt(Base + I));
12912 else
12913 ResultElements.push_back(MergeVec.getVectorElt(I));
12914 }
12915 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12916 }
12917
12918 case clang::X86::BI__builtin_ia32_pavgb128:
12919 case clang::X86::BI__builtin_ia32_pavgw128:
12920 case clang::X86::BI__builtin_ia32_pavgb256:
12921 case clang::X86::BI__builtin_ia32_pavgw256:
12922 case clang::X86::BI__builtin_ia32_pavgb512:
12923 case clang::X86::BI__builtin_ia32_pavgw512:
12924 return EvaluateBinOpExpr(llvm::APIntOps::avgCeilU);
12925
12926 case clang::X86::BI__builtin_ia32_pmulhrsw128:
12927 case clang::X86::BI__builtin_ia32_pmulhrsw256:
12928 case clang::X86::BI__builtin_ia32_pmulhrsw512:
12929 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
12930 return (llvm::APIntOps::mulsExtended(LHS, RHS).ashr(14) + 1)
12931 .extractBits(16, 1);
12932 });
12933
12934 case clang::X86::BI__builtin_ia32_psadbw128:
12935 case clang::X86::BI__builtin_ia32_psadbw256:
12936 case clang::X86::BI__builtin_ia32_psadbw512: {
12937 APValue SourceLHS, SourceRHS;
12938 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
12939 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
12940 return false;
12941
12942 assert(SourceLHS.isVector() && SourceRHS.isVector());
12943 unsigned SourceLen = SourceLHS.getVectorLength();
12944 assert(SourceLen == SourceRHS.getVectorLength());
12945 assert((SourceLen % 8) == 0);
12946
12947 auto *DestTy = E->getType()->castAs<VectorType>();
12948 QualType DestEltTy = DestTy->getElementType();
12949 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
12950 SmallVector<APValue, 8> ResultElements;
12951 ResultElements.reserve(SourceLen / 8);
12952
12953 for (unsigned Lane = 0; Lane != SourceLen; Lane += 8) {
12954 APInt Sum(64, 0);
12955 for (unsigned I = 0; I != 8; ++I) {
12956 APInt LHS = SourceLHS.getVectorElt(Lane + I).getInt().extOrTrunc(8);
12957 APInt RHS = SourceRHS.getVectorElt(Lane + I).getInt().extOrTrunc(8);
12958 Sum += llvm::APIntOps::abdu(LHS, RHS).zext(64);
12959 }
12960 ResultElements.push_back(APValue(APSInt(Sum, DestUnsigned)));
12961 }
12962
12963 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12964 }
12965
12966 case clang::X86::BI__builtin_ia32_pmaddubsw128:
12967 case clang::X86::BI__builtin_ia32_pmaddubsw256:
12968 case clang::X86::BI__builtin_ia32_pmaddubsw512:
12969 case clang::X86::BI__builtin_ia32_pmaddwd128:
12970 case clang::X86::BI__builtin_ia32_pmaddwd256:
12971 case clang::X86::BI__builtin_ia32_pmaddwd512: {
12972 APValue SourceLHS, SourceRHS;
12973 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
12974 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
12975 return false;
12976
12977 auto *DestTy = E->getType()->castAs<VectorType>();
12978 QualType DestEltTy = DestTy->getElementType();
12979 unsigned SourceLen = SourceLHS.getVectorLength();
12980 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
12981 SmallVector<APValue, 4> ResultElements;
12982 ResultElements.reserve(SourceLen / 2);
12983
12984 for (unsigned EltNum = 0; EltNum < SourceLen; EltNum += 2) {
12985 const APSInt &LoLHS = SourceLHS.getVectorElt(EltNum).getInt();
12986 const APSInt &HiLHS = SourceLHS.getVectorElt(EltNum + 1).getInt();
12987 const APSInt &LoRHS = SourceRHS.getVectorElt(EltNum).getInt();
12988 const APSInt &HiRHS = SourceRHS.getVectorElt(EltNum + 1).getInt();
12989 unsigned BitWidth = 2 * LoLHS.getBitWidth();
12990
12991 switch (BuiltinOp) {
12992 case clang::X86::BI__builtin_ia32_pmaddubsw128:
12993 case clang::X86::BI__builtin_ia32_pmaddubsw256:
12994 case clang::X86::BI__builtin_ia32_pmaddubsw512:
12995 ResultElements.push_back(APValue(
12996 APSInt((LoLHS.zext(BitWidth) * LoRHS.sext(BitWidth))
12997 .sadd_sat((HiLHS.zext(BitWidth) * HiRHS.sext(BitWidth))),
12998 DestUnsigned)));
12999 break;
13000 case clang::X86::BI__builtin_ia32_pmaddwd128:
13001 case clang::X86::BI__builtin_ia32_pmaddwd256:
13002 case clang::X86::BI__builtin_ia32_pmaddwd512:
13003 ResultElements.push_back(
13004 APValue(APSInt((LoLHS.sext(BitWidth) * LoRHS.sext(BitWidth)) +
13005 (HiLHS.sext(BitWidth) * HiRHS.sext(BitWidth)),
13006 DestUnsigned)));
13007 break;
13008 }
13009 }
13010
13011 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13012 }
13013
13014 case clang::X86::BI__builtin_ia32_bmacor16x16x16_v16hi:
13015 case clang::X86::BI__builtin_ia32_bmacor16x16x16_v32hi:
13016 case clang::X86::BI__builtin_ia32_bmacxor16x16x16_v16hi:
13017 case clang::X86::BI__builtin_ia32_bmacxor16x16x16_v32hi: {
13018 // Bit Matrix Multiply and Accumulate (AVX512BMM). Each 256-bit lane holds
13019 // a 16x16 bit matrix as 16 x i16 elements; element i is row i and bit j of
13020 // that element is entry [i][j]. The accumulator (third argument, src1 in
13021 // the AMD ISA) provides the initial value of each result bit, into which
13022 // the bit-matrix product of the first two arguments (src2 * src3) is
13023 // reduced with OR (vbmacor) or XOR (vbmacxor):
13024 // for i in 0..15, j in 0..15:
13025 // bit = C[16*i+j]
13026 // for k in 0..15: bit OP= A[16*i+k] & B[16*k+j]
13027 // dest[16*i+j] = bit
13028 APValue SourceA, SourceB, SourceC;
13029 if (!EvaluateAsRValue(Info, E->getArg(0), SourceA) ||
13030 !EvaluateAsRValue(Info, E->getArg(1), SourceB) ||
13031 !EvaluateAsRValue(Info, E->getArg(2), SourceC))
13032 return false;
13033
13034 bool IsXor = E->getBuiltinCallee() ==
13035 clang::X86::BI__builtin_ia32_bmacxor16x16x16_v16hi ||
13036 E->getBuiltinCallee() ==
13037 clang::X86::BI__builtin_ia32_bmacxor16x16x16_v32hi;
13038
13039 unsigned SourceLen = SourceA.getVectorLength();
13040 assert(SourceLen % 16 == 0 && "BMM operates on 256-bit lanes of 16 x i16");
13041 auto *DestTy = E->getType()->castAs<VectorType>();
13042 QualType DestEltTy = DestTy->getElementType();
13043 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
13044
13045 SmallVector<APValue, 32> ResultElements(SourceLen);
13046 for (unsigned Lane = 0; Lane != SourceLen; Lane += 16) {
13047 for (unsigned I = 0; I != 16; ++I) {
13048 uint16_t A =
13049 (uint16_t)SourceA.getVectorElt(Lane + I).getInt().getZExtValue();
13050 uint16_t Dst =
13051 (uint16_t)SourceC.getVectorElt(Lane + I).getInt().getZExtValue();
13052 for (unsigned J = 0; J != 16; ++J) {
13053 // Seed the reduction with the accumulator bit, then fold in each
13054 // product term with the same operator (OR for vbmacor, XOR for
13055 // vbmacxor).
13056 unsigned Bit = (Dst >> J) & 1u;
13057 for (unsigned K = 0; K != 16; ++K) {
13058 uint16_t B = (uint16_t)SourceB.getVectorElt(Lane + K)
13059 .getInt()
13060 .getZExtValue();
13061 unsigned Product = ((A >> K) & 1u) & ((B >> J) & 1u);
13062 Bit = IsXor ? (Bit ^ Product) : (Bit | Product);
13063 }
13064 Dst = (Dst & ~(uint16_t(1) << J)) | (uint16_t(Bit) << J);
13065 }
13066 ResultElements[Lane + I] =
13067 APValue(APSInt(APInt(16, Dst), DestUnsigned));
13068 }
13069 }
13070 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13071 }
13072
13073 case clang::X86::BI__builtin_ia32_dbpsadbw128:
13074 case clang::X86::BI__builtin_ia32_dbpsadbw256:
13075 case clang::X86::BI__builtin_ia32_dbpsadbw512: {
13076 APValue SourceA, SourceB, SourceImm;
13077 if (!EvaluateAsRValue(Info, E->getArg(0), SourceA) ||
13078 !EvaluateAsRValue(Info, E->getArg(1), SourceB) ||
13079 !EvaluateAsRValue(Info, E->getArg(2), SourceImm))
13080 return false;
13081
13082 unsigned SourceLen = SourceA.getVectorLength();
13083 constexpr unsigned LaneSize = 16; // 128-bit lane = 16 bytes
13084 unsigned Imm = SourceImm.getInt().getZExtValue();
13085
13086 auto *DestTy = E->getType()->castAs<VectorType>();
13087 QualType DestEltTy = DestTy->getElementType();
13088 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
13089 SmallVector<APValue, 32> ResultElements;
13090 ResultElements.reserve(SourceLen / 2);
13091
13092 // Phase 1: Shuffle SourceB using all four 2-bit fields of imm8.
13093 // Within each 128-bit lane, for group j (0..3), select a 4-byte block
13094 // from SourceB based on bits [2*j+1:2*j] of imm8.
13095 SmallVector<uint8_t, 64> Shuffled(SourceLen);
13096 for (unsigned I = 0; I < SourceLen; I += LaneSize) {
13097 for (unsigned J = 0; J < 4; ++J) {
13098 unsigned Part = (Imm >> (2 * J)) & 3;
13099 for (unsigned K = 0; K < 4; ++K) {
13100 Shuffled[I + 4 * J + K] = static_cast<uint8_t>(
13101 SourceB.getVectorElt(I + 4 * Part + K).getInt().getZExtValue());
13102 }
13103 }
13104 }
13105
13106 // Phase 2: Sliding SAD computation.
13107 // For every group of 4 output u16 values, compute absolute differences
13108 // using overlapping windows into SourceA and the shuffled array.
13109 unsigned Size = SourceLen / 2; // number of output u16 elements
13110 for (unsigned I = 0; I < Size; I += 4) {
13111 unsigned Sad[4] = {0, 0, 0, 0};
13112 for (unsigned J = 0; J < 4; ++J) {
13113 uint8_t A1 = static_cast<uint8_t>(
13114 SourceA.getVectorElt(2 * I + J).getInt().getZExtValue());
13115 uint8_t A2 = static_cast<uint8_t>(
13116 SourceA.getVectorElt(2 * I + J + 4).getInt().getZExtValue());
13117 uint8_t B0 = Shuffled[2 * I + J];
13118 uint8_t B1 = Shuffled[2 * I + J + 1];
13119 uint8_t B2 = Shuffled[2 * I + J + 2];
13120 uint8_t B3 = Shuffled[2 * I + J + 3];
13121 Sad[0] += (A1 > B0) ? (A1 - B0) : (B0 - A1);
13122 Sad[1] += (A1 > B1) ? (A1 - B1) : (B1 - A1);
13123 Sad[2] += (A2 > B2) ? (A2 - B2) : (B2 - A2);
13124 Sad[3] += (A2 > B3) ? (A2 - B3) : (B3 - A2);
13125 }
13126 for (unsigned R = 0; R < 4; ++R)
13127 ResultElements.push_back(
13128 APValue(APSInt(APInt(16, Sad[R]), DestUnsigned)));
13129 }
13130
13131 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13132 }
13133
13134 case clang::X86::BI__builtin_ia32_mpsadbw128:
13135 case clang::X86::BI__builtin_ia32_mpsadbw256: {
13136 APValue SourceA, SourceB;
13137 APSInt SourceImm;
13138 if (!EvaluateVector(E->getArg(0), SourceA, Info) ||
13139 !EvaluateVector(E->getArg(1), SourceB, Info) ||
13140 !EvaluateInteger(E->getArg(2), SourceImm, Info))
13141 return false;
13142 unsigned SourceLen = SourceA.getVectorLength();
13143 constexpr unsigned LaneSize = 16;
13144 assert((SourceLen == LaneSize || SourceLen == 2 * LaneSize) &&
13145 "MPSADBW operates on 128-bit or 256-bit vectors");
13146 unsigned NumLanes = SourceLen / LaneSize;
13147 unsigned Imm = SourceImm.getZExtValue();
13148
13149 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
13150 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
13151 SmallVector<APValue, 16> ResultElements;
13152 ResultElements.reserve(SourceLen / 2);
13153
13154 for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
13155 unsigned Ctrl = (Imm >> (3 * Lane)) & 0x7;
13156 unsigned AOff = ((Ctrl >> 2) & 1) * 4;
13157 unsigned BOff = (Ctrl & 3) * 4;
13158 for (unsigned J = 0; J != 8; ++J) {
13159 uint16_t Sad = 0;
13160 for (unsigned K = 0; K != 4; ++K) {
13161 uint8_t A = static_cast<uint8_t>(
13162 SourceA.getVectorElt(Lane * LaneSize + AOff + J + K)
13163 .getInt()
13164 .getZExtValue());
13165 uint8_t B = static_cast<uint8_t>(
13166 SourceB.getVectorElt(Lane * LaneSize + BOff + K)
13167 .getInt()
13168 .getZExtValue());
13169 Sad += (A > B) ? (A - B) : (B - A);
13170 }
13171 ResultElements.push_back(APValue(APSInt(APInt(16, Sad), DestUnsigned)));
13172 }
13173 }
13174 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13175 }
13176
13177 case clang::X86::BI__builtin_ia32_pmulhuw128:
13178 case clang::X86::BI__builtin_ia32_pmulhuw256:
13179 case clang::X86::BI__builtin_ia32_pmulhuw512:
13180 return EvaluateBinOpExpr(llvm::APIntOps::mulhu);
13181
13182 case clang::X86::BI__builtin_ia32_pmulhw128:
13183 case clang::X86::BI__builtin_ia32_pmulhw256:
13184 case clang::X86::BI__builtin_ia32_pmulhw512:
13185 return EvaluateBinOpExpr(llvm::APIntOps::mulhs);
13186
13187 case clang::X86::BI__builtin_ia32_psllv2di:
13188 case clang::X86::BI__builtin_ia32_psllv4di:
13189 case clang::X86::BI__builtin_ia32_psllv4si:
13190 case clang::X86::BI__builtin_ia32_psllv8di:
13191 case clang::X86::BI__builtin_ia32_psllv8hi:
13192 case clang::X86::BI__builtin_ia32_psllv8si:
13193 case clang::X86::BI__builtin_ia32_psllv16hi:
13194 case clang::X86::BI__builtin_ia32_psllv16si:
13195 case clang::X86::BI__builtin_ia32_psllv32hi:
13196 case clang::X86::BI__builtin_ia32_psllwi128:
13197 case clang::X86::BI__builtin_ia32_pslldi128:
13198 case clang::X86::BI__builtin_ia32_psllqi128:
13199 case clang::X86::BI__builtin_ia32_psllwi256:
13200 case clang::X86::BI__builtin_ia32_pslldi256:
13201 case clang::X86::BI__builtin_ia32_psllqi256:
13202 case clang::X86::BI__builtin_ia32_psllwi512:
13203 case clang::X86::BI__builtin_ia32_pslldi512:
13204 case clang::X86::BI__builtin_ia32_psllqi512:
13205 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
13206 if (RHS.uge(LHS.getBitWidth())) {
13207 return APInt::getZero(LHS.getBitWidth());
13208 }
13209 return LHS.shl(RHS.getZExtValue());
13210 });
13211
13212 case clang::X86::BI__builtin_ia32_psrav4si:
13213 case clang::X86::BI__builtin_ia32_psrav8di:
13214 case clang::X86::BI__builtin_ia32_psrav8hi:
13215 case clang::X86::BI__builtin_ia32_psrav8si:
13216 case clang::X86::BI__builtin_ia32_psrav16hi:
13217 case clang::X86::BI__builtin_ia32_psrav16si:
13218 case clang::X86::BI__builtin_ia32_psrav32hi:
13219 case clang::X86::BI__builtin_ia32_psravq128:
13220 case clang::X86::BI__builtin_ia32_psravq256:
13221 case clang::X86::BI__builtin_ia32_psrawi128:
13222 case clang::X86::BI__builtin_ia32_psradi128:
13223 case clang::X86::BI__builtin_ia32_psraqi128:
13224 case clang::X86::BI__builtin_ia32_psrawi256:
13225 case clang::X86::BI__builtin_ia32_psradi256:
13226 case clang::X86::BI__builtin_ia32_psraqi256:
13227 case clang::X86::BI__builtin_ia32_psrawi512:
13228 case clang::X86::BI__builtin_ia32_psradi512:
13229 case clang::X86::BI__builtin_ia32_psraqi512:
13230 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
13231 if (RHS.uge(LHS.getBitWidth())) {
13232 return LHS.ashr(LHS.getBitWidth() - 1);
13233 }
13234 return LHS.ashr(RHS.getZExtValue());
13235 });
13236
13237 case clang::X86::BI__builtin_ia32_psrlv2di:
13238 case clang::X86::BI__builtin_ia32_psrlv4di:
13239 case clang::X86::BI__builtin_ia32_psrlv4si:
13240 case clang::X86::BI__builtin_ia32_psrlv8di:
13241 case clang::X86::BI__builtin_ia32_psrlv8hi:
13242 case clang::X86::BI__builtin_ia32_psrlv8si:
13243 case clang::X86::BI__builtin_ia32_psrlv16hi:
13244 case clang::X86::BI__builtin_ia32_psrlv16si:
13245 case clang::X86::BI__builtin_ia32_psrlv32hi:
13246 case clang::X86::BI__builtin_ia32_psrlwi128:
13247 case clang::X86::BI__builtin_ia32_psrldi128:
13248 case clang::X86::BI__builtin_ia32_psrlqi128:
13249 case clang::X86::BI__builtin_ia32_psrlwi256:
13250 case clang::X86::BI__builtin_ia32_psrldi256:
13251 case clang::X86::BI__builtin_ia32_psrlqi256:
13252 case clang::X86::BI__builtin_ia32_psrlwi512:
13253 case clang::X86::BI__builtin_ia32_psrldi512:
13254 case clang::X86::BI__builtin_ia32_psrlqi512:
13255 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
13256 if (RHS.uge(LHS.getBitWidth())) {
13257 return APInt::getZero(LHS.getBitWidth());
13258 }
13259 return LHS.lshr(RHS.getZExtValue());
13260 });
13261 case X86::BI__builtin_ia32_packsswb128:
13262 case X86::BI__builtin_ia32_packsswb256:
13263 case X86::BI__builtin_ia32_packsswb512:
13264 case X86::BI__builtin_ia32_packssdw128:
13265 case X86::BI__builtin_ia32_packssdw256:
13266 case X86::BI__builtin_ia32_packssdw512:
13267 return evalPackBuiltin(E, Info, Result, [](const APSInt &Src) {
13268 return APSInt(Src).truncSSat(Src.getBitWidth() / 2);
13269 });
13270 case X86::BI__builtin_ia32_packusdw128:
13271 case X86::BI__builtin_ia32_packusdw256:
13272 case X86::BI__builtin_ia32_packusdw512:
13273 case X86::BI__builtin_ia32_packuswb128:
13274 case X86::BI__builtin_ia32_packuswb256:
13275 case X86::BI__builtin_ia32_packuswb512:
13276 return evalPackBuiltin(E, Info, Result, [](const APSInt &Src) {
13277 return APSInt(Src).truncSSatU(Src.getBitWidth() / 2);
13278 });
13279 case clang::X86::BI__builtin_ia32_selectss_128:
13280 return EvalSelectScalar(4);
13281 case clang::X86::BI__builtin_ia32_selectsd_128:
13282 return EvalSelectScalar(2);
13283 case clang::X86::BI__builtin_ia32_selectsh_128:
13284 case clang::X86::BI__builtin_ia32_selectsbf_128:
13285 return EvalSelectScalar(8);
13286 case clang::X86::BI__builtin_ia32_pmuldq128:
13287 case clang::X86::BI__builtin_ia32_pmuldq256:
13288 case clang::X86::BI__builtin_ia32_pmuldq512:
13289 case clang::X86::BI__builtin_ia32_pmuludq128:
13290 case clang::X86::BI__builtin_ia32_pmuludq256:
13291 case clang::X86::BI__builtin_ia32_pmuludq512: {
13292 APValue SourceLHS, SourceRHS;
13293 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
13294 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
13295 return false;
13296
13297 unsigned SourceLen = SourceLHS.getVectorLength();
13298 SmallVector<APValue, 4> ResultElements;
13299 ResultElements.reserve(SourceLen / 2);
13300
13301 for (unsigned EltNum = 0; EltNum < SourceLen; EltNum += 2) {
13302 APSInt LHS = SourceLHS.getVectorElt(EltNum).getInt();
13303 APSInt RHS = SourceRHS.getVectorElt(EltNum).getInt();
13304
13305 switch (BuiltinOp) {
13306 case clang::X86::BI__builtin_ia32_pmuludq128:
13307 case clang::X86::BI__builtin_ia32_pmuludq256:
13308 case clang::X86::BI__builtin_ia32_pmuludq512:
13309 ResultElements.push_back(
13310 APValue(APSInt(llvm::APIntOps::muluExtended(LHS, RHS), true)));
13311 break;
13312 case clang::X86::BI__builtin_ia32_pmuldq128:
13313 case clang::X86::BI__builtin_ia32_pmuldq256:
13314 case clang::X86::BI__builtin_ia32_pmuldq512:
13315 ResultElements.push_back(
13316 APValue(APSInt(llvm::APIntOps::mulsExtended(LHS, RHS), false)));
13317 break;
13318 }
13319 }
13320
13321 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13322 }
13323
13324 case X86::BI__builtin_ia32_vpmadd52luq128:
13325 case X86::BI__builtin_ia32_vpmadd52luq256:
13326 case X86::BI__builtin_ia32_vpmadd52luq512: {
13327 APValue A, B, C;
13328 if (!EvaluateAsRValue(Info, E->getArg(0), A) ||
13329 !EvaluateAsRValue(Info, E->getArg(1), B) ||
13330 !EvaluateAsRValue(Info, E->getArg(2), C))
13331 return false;
13332
13333 unsigned ALen = A.getVectorLength();
13334 SmallVector<APValue, 4> ResultElements;
13335 ResultElements.reserve(ALen);
13336
13337 for (unsigned EltNum = 0; EltNum < ALen; EltNum += 1) {
13338 APInt AElt = A.getVectorElt(EltNum).getInt();
13339 APInt BElt = B.getVectorElt(EltNum).getInt().trunc(52);
13340 APInt CElt = C.getVectorElt(EltNum).getInt().trunc(52);
13341 APSInt ResElt(AElt + (BElt * CElt).zext(64), false);
13342 ResultElements.push_back(APValue(ResElt));
13343 }
13344
13345 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13346 }
13347 case X86::BI__builtin_ia32_vpmadd52huq128:
13348 case X86::BI__builtin_ia32_vpmadd52huq256:
13349 case X86::BI__builtin_ia32_vpmadd52huq512: {
13350 APValue A, B, C;
13351 if (!EvaluateAsRValue(Info, E->getArg(0), A) ||
13352 !EvaluateAsRValue(Info, E->getArg(1), B) ||
13353 !EvaluateAsRValue(Info, E->getArg(2), C))
13354 return false;
13355
13356 unsigned ALen = A.getVectorLength();
13357 SmallVector<APValue, 4> ResultElements;
13358 ResultElements.reserve(ALen);
13359
13360 for (unsigned EltNum = 0; EltNum < ALen; EltNum += 1) {
13361 APInt AElt = A.getVectorElt(EltNum).getInt();
13362 APInt BElt = B.getVectorElt(EltNum).getInt().trunc(52);
13363 APInt CElt = C.getVectorElt(EltNum).getInt().trunc(52);
13364 APSInt ResElt(AElt + llvm::APIntOps::mulhu(BElt, CElt).zext(64), false);
13365 ResultElements.push_back(APValue(ResElt));
13366 }
13367
13368 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13369 }
13370
13371 case clang::X86::BI__builtin_ia32_vprotbi:
13372 case clang::X86::BI__builtin_ia32_vprotdi:
13373 case clang::X86::BI__builtin_ia32_vprotqi:
13374 case clang::X86::BI__builtin_ia32_vprotwi:
13375 case clang::X86::BI__builtin_ia32_prold128:
13376 case clang::X86::BI__builtin_ia32_prold256:
13377 case clang::X86::BI__builtin_ia32_prold512:
13378 case clang::X86::BI__builtin_ia32_prolq128:
13379 case clang::X86::BI__builtin_ia32_prolq256:
13380 case clang::X86::BI__builtin_ia32_prolq512:
13381 return EvaluateBinOpExpr(
13382 [](const APSInt &LHS, const APSInt &RHS) { return LHS.rotl(RHS); });
13383
13384 case clang::X86::BI__builtin_ia32_prord128:
13385 case clang::X86::BI__builtin_ia32_prord256:
13386 case clang::X86::BI__builtin_ia32_prord512:
13387 case clang::X86::BI__builtin_ia32_prorq128:
13388 case clang::X86::BI__builtin_ia32_prorq256:
13389 case clang::X86::BI__builtin_ia32_prorq512:
13390 return EvaluateBinOpExpr(
13391 [](const APSInt &LHS, const APSInt &RHS) { return LHS.rotr(RHS); });
13392
13393 case Builtin::BI__builtin_elementwise_max:
13394 case Builtin::BI__builtin_elementwise_min: {
13395 APValue SourceLHS, SourceRHS;
13396 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
13397 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
13398 return false;
13399
13400 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
13401
13402 if (!DestEltTy->isIntegerType())
13403 return false;
13404
13405 unsigned SourceLen = SourceLHS.getVectorLength();
13406 SmallVector<APValue, 4> ResultElements;
13407 ResultElements.reserve(SourceLen);
13408
13409 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
13410 APSInt LHS = SourceLHS.getVectorElt(EltNum).getInt();
13411 APSInt RHS = SourceRHS.getVectorElt(EltNum).getInt();
13412 switch (BuiltinOp) {
13413 case Builtin::BI__builtin_elementwise_max:
13414 ResultElements.push_back(
13415 APValue(APSInt(std::max(LHS, RHS),
13416 DestEltTy->isUnsignedIntegerOrEnumerationType())));
13417 break;
13418 case Builtin::BI__builtin_elementwise_min:
13419 ResultElements.push_back(
13420 APValue(APSInt(std::min(LHS, RHS),
13421 DestEltTy->isUnsignedIntegerOrEnumerationType())));
13422 break;
13423 }
13424 }
13425
13426 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13427 }
13428 case X86::BI__builtin_ia32_vpshldd128:
13429 case X86::BI__builtin_ia32_vpshldd256:
13430 case X86::BI__builtin_ia32_vpshldd512:
13431 case X86::BI__builtin_ia32_vpshldq128:
13432 case X86::BI__builtin_ia32_vpshldq256:
13433 case X86::BI__builtin_ia32_vpshldq512:
13434 case X86::BI__builtin_ia32_vpshldw128:
13435 case X86::BI__builtin_ia32_vpshldw256:
13436 case X86::BI__builtin_ia32_vpshldw512: {
13437 APValue SourceHi, SourceLo, SourceAmt;
13438 if (!EvaluateAsRValue(Info, E->getArg(0), SourceHi) ||
13439 !EvaluateAsRValue(Info, E->getArg(1), SourceLo) ||
13440 !EvaluateAsRValue(Info, E->getArg(2), SourceAmt))
13441 return false;
13442
13443 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
13444 unsigned SourceLen = SourceHi.getVectorLength();
13445 SmallVector<APValue, 32> ResultElements;
13446 ResultElements.reserve(SourceLen);
13447
13448 APInt Amt = SourceAmt.getInt();
13449 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
13450 APInt Hi = SourceHi.getVectorElt(EltNum).getInt();
13451 APInt Lo = SourceLo.getVectorElt(EltNum).getInt();
13452 APInt R = llvm::APIntOps::fshl(Hi, Lo, Amt);
13453 ResultElements.push_back(
13455 }
13456
13457 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13458 }
13459 case X86::BI__builtin_ia32_vpshrdd128:
13460 case X86::BI__builtin_ia32_vpshrdd256:
13461 case X86::BI__builtin_ia32_vpshrdd512:
13462 case X86::BI__builtin_ia32_vpshrdq128:
13463 case X86::BI__builtin_ia32_vpshrdq256:
13464 case X86::BI__builtin_ia32_vpshrdq512:
13465 case X86::BI__builtin_ia32_vpshrdw128:
13466 case X86::BI__builtin_ia32_vpshrdw256:
13467 case X86::BI__builtin_ia32_vpshrdw512: {
13468 // NOTE: Reversed Hi/Lo operands.
13469 APValue SourceHi, SourceLo, SourceAmt;
13470 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLo) ||
13471 !EvaluateAsRValue(Info, E->getArg(1), SourceHi) ||
13472 !EvaluateAsRValue(Info, E->getArg(2), SourceAmt))
13473 return false;
13474
13475 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
13476 unsigned SourceLen = SourceHi.getVectorLength();
13477 SmallVector<APValue, 32> ResultElements;
13478 ResultElements.reserve(SourceLen);
13479
13480 APInt Amt = SourceAmt.getInt();
13481 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
13482 APInt Hi = SourceHi.getVectorElt(EltNum).getInt();
13483 APInt Lo = SourceLo.getVectorElt(EltNum).getInt();
13484 APInt R = llvm::APIntOps::fshr(Hi, Lo, Amt);
13485 ResultElements.push_back(
13487 }
13488
13489 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13490 }
13491 case X86::BI__builtin_ia32_compressdf128_mask:
13492 case X86::BI__builtin_ia32_compressdf256_mask:
13493 case X86::BI__builtin_ia32_compressdf512_mask:
13494 case X86::BI__builtin_ia32_compressdi128_mask:
13495 case X86::BI__builtin_ia32_compressdi256_mask:
13496 case X86::BI__builtin_ia32_compressdi512_mask:
13497 case X86::BI__builtin_ia32_compresshi128_mask:
13498 case X86::BI__builtin_ia32_compresshi256_mask:
13499 case X86::BI__builtin_ia32_compresshi512_mask:
13500 case X86::BI__builtin_ia32_compressqi128_mask:
13501 case X86::BI__builtin_ia32_compressqi256_mask:
13502 case X86::BI__builtin_ia32_compressqi512_mask:
13503 case X86::BI__builtin_ia32_compresssf128_mask:
13504 case X86::BI__builtin_ia32_compresssf256_mask:
13505 case X86::BI__builtin_ia32_compresssf512_mask:
13506 case X86::BI__builtin_ia32_compresssi128_mask:
13507 case X86::BI__builtin_ia32_compresssi256_mask:
13508 case X86::BI__builtin_ia32_compresssi512_mask: {
13509 APValue Source, Passthru;
13510 if (!EvaluateAsRValue(Info, E->getArg(0), Source) ||
13511 !EvaluateAsRValue(Info, E->getArg(1), Passthru))
13512 return false;
13513 APSInt Mask;
13514 if (!EvaluateInteger(E->getArg(2), Mask, Info))
13515 return false;
13516
13517 unsigned NumElts = Source.getVectorLength();
13518 SmallVector<APValue, 64> ResultElements;
13519 ResultElements.reserve(NumElts);
13520
13521 for (unsigned I = 0; I != NumElts; ++I) {
13522 if (Mask[I])
13523 ResultElements.push_back(Source.getVectorElt(I));
13524 }
13525 for (unsigned I = ResultElements.size(); I != NumElts; ++I) {
13526 ResultElements.push_back(Passthru.getVectorElt(I));
13527 }
13528
13529 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13530 }
13531 case X86::BI__builtin_ia32_expanddf128_mask:
13532 case X86::BI__builtin_ia32_expanddf256_mask:
13533 case X86::BI__builtin_ia32_expanddf512_mask:
13534 case X86::BI__builtin_ia32_expanddi128_mask:
13535 case X86::BI__builtin_ia32_expanddi256_mask:
13536 case X86::BI__builtin_ia32_expanddi512_mask:
13537 case X86::BI__builtin_ia32_expandhi128_mask:
13538 case X86::BI__builtin_ia32_expandhi256_mask:
13539 case X86::BI__builtin_ia32_expandhi512_mask:
13540 case X86::BI__builtin_ia32_expandqi128_mask:
13541 case X86::BI__builtin_ia32_expandqi256_mask:
13542 case X86::BI__builtin_ia32_expandqi512_mask:
13543 case X86::BI__builtin_ia32_expandsf128_mask:
13544 case X86::BI__builtin_ia32_expandsf256_mask:
13545 case X86::BI__builtin_ia32_expandsf512_mask:
13546 case X86::BI__builtin_ia32_expandsi128_mask:
13547 case X86::BI__builtin_ia32_expandsi256_mask:
13548 case X86::BI__builtin_ia32_expandsi512_mask: {
13549 APValue Source, Passthru;
13550 if (!EvaluateAsRValue(Info, E->getArg(0), Source) ||
13551 !EvaluateAsRValue(Info, E->getArg(1), Passthru))
13552 return false;
13553 APSInt Mask;
13554 if (!EvaluateInteger(E->getArg(2), Mask, Info))
13555 return false;
13556
13557 unsigned NumElts = Source.getVectorLength();
13558 SmallVector<APValue, 64> ResultElements;
13559 ResultElements.reserve(NumElts);
13560
13561 unsigned SourceIdx = 0;
13562 for (unsigned I = 0; I != NumElts; ++I) {
13563 if (Mask[I])
13564 ResultElements.push_back(Source.getVectorElt(SourceIdx++));
13565 else
13566 ResultElements.push_back(Passthru.getVectorElt(I));
13567 }
13568 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13569 }
13570 case X86::BI__builtin_ia32_vpconflictsi_128:
13571 case X86::BI__builtin_ia32_vpconflictsi_256:
13572 case X86::BI__builtin_ia32_vpconflictsi_512:
13573 case X86::BI__builtin_ia32_vpconflictdi_128:
13574 case X86::BI__builtin_ia32_vpconflictdi_256:
13575 case X86::BI__builtin_ia32_vpconflictdi_512: {
13576 APValue Source;
13577
13578 if (!EvaluateAsRValue(Info, E->getArg(0), Source))
13579 return false;
13580
13581 unsigned SourceLen = Source.getVectorLength();
13582 SmallVector<APValue, 32> ResultElements;
13583 ResultElements.reserve(SourceLen);
13584
13585 const auto *VecT = E->getType()->castAs<VectorType>();
13586 bool DestUnsigned =
13587 VecT->getElementType()->isUnsignedIntegerOrEnumerationType();
13588
13589 for (unsigned I = 0; I != SourceLen; ++I) {
13590 const APValue &EltI = Source.getVectorElt(I);
13591
13592 APInt ConflictMask(EltI.getInt().getBitWidth(), 0);
13593 for (unsigned J = 0; J != I; ++J) {
13594 const APValue &EltJ = Source.getVectorElt(J);
13595 ConflictMask.setBitVal(J, EltI.getInt() == EltJ.getInt());
13596 }
13597 ResultElements.push_back(APValue(APSInt(ConflictMask, DestUnsigned)));
13598 }
13599 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13600 }
13601 case X86::BI__builtin_ia32_blendpd:
13602 case X86::BI__builtin_ia32_blendpd256:
13603 case X86::BI__builtin_ia32_blendps:
13604 case X86::BI__builtin_ia32_blendps256:
13605 case X86::BI__builtin_ia32_pblendw128:
13606 case X86::BI__builtin_ia32_pblendw256:
13607 case X86::BI__builtin_ia32_pblendd128:
13608 case X86::BI__builtin_ia32_pblendd256: {
13609 APValue SourceF, SourceT, SourceC;
13610 if (!EvaluateAsRValue(Info, E->getArg(0), SourceF) ||
13611 !EvaluateAsRValue(Info, E->getArg(1), SourceT) ||
13612 !EvaluateAsRValue(Info, E->getArg(2), SourceC))
13613 return false;
13614
13615 const APInt &C = SourceC.getInt();
13616 unsigned SourceLen = SourceF.getVectorLength();
13617 SmallVector<APValue, 32> ResultElements;
13618 ResultElements.reserve(SourceLen);
13619 for (unsigned EltNum = 0; EltNum != SourceLen; ++EltNum) {
13620 const APValue &F = SourceF.getVectorElt(EltNum);
13621 const APValue &T = SourceT.getVectorElt(EltNum);
13622 ResultElements.push_back(C[EltNum % 8] ? T : F);
13623 }
13624
13625 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13626 }
13627
13628 case X86::BI__builtin_ia32_psignb128:
13629 case X86::BI__builtin_ia32_psignb256:
13630 case X86::BI__builtin_ia32_psignw128:
13631 case X86::BI__builtin_ia32_psignw256:
13632 case X86::BI__builtin_ia32_psignd128:
13633 case X86::BI__builtin_ia32_psignd256:
13634 return EvaluateBinOpExpr([](const APInt &AElem, const APInt &BElem) {
13635 if (BElem.isZero())
13636 return APInt::getZero(AElem.getBitWidth());
13637 if (BElem.isNegative())
13638 return -AElem;
13639 return AElem;
13640 });
13641
13642 case X86::BI__builtin_ia32_blendvpd:
13643 case X86::BI__builtin_ia32_blendvpd256:
13644 case X86::BI__builtin_ia32_blendvps:
13645 case X86::BI__builtin_ia32_blendvps256:
13646 case X86::BI__builtin_ia32_pblendvb128:
13647 case X86::BI__builtin_ia32_pblendvb256: {
13648 // SSE blendv by mask signbit: "Result = C[] < 0 ? T[] : F[]".
13649 APValue SourceF, SourceT, SourceC;
13650 if (!EvaluateAsRValue(Info, E->getArg(0), SourceF) ||
13651 !EvaluateAsRValue(Info, E->getArg(1), SourceT) ||
13652 !EvaluateAsRValue(Info, E->getArg(2), SourceC))
13653 return false;
13654
13655 unsigned SourceLen = SourceF.getVectorLength();
13656 SmallVector<APValue, 32> ResultElements;
13657 ResultElements.reserve(SourceLen);
13658
13659 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
13660 const APValue &F = SourceF.getVectorElt(EltNum);
13661 const APValue &T = SourceT.getVectorElt(EltNum);
13662 const APValue &C = SourceC.getVectorElt(EltNum);
13663 APInt M = C.isInt() ? (APInt)C.getInt() : C.getFloat().bitcastToAPInt();
13664 ResultElements.push_back(M.isNegative() ? T : F);
13665 }
13666
13667 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13668 }
13669 case X86::BI__builtin_ia32_selectb_128:
13670 case X86::BI__builtin_ia32_selectb_256:
13671 case X86::BI__builtin_ia32_selectb_512:
13672 case X86::BI__builtin_ia32_selectw_128:
13673 case X86::BI__builtin_ia32_selectw_256:
13674 case X86::BI__builtin_ia32_selectw_512:
13675 case X86::BI__builtin_ia32_selectd_128:
13676 case X86::BI__builtin_ia32_selectd_256:
13677 case X86::BI__builtin_ia32_selectd_512:
13678 case X86::BI__builtin_ia32_selectq_128:
13679 case X86::BI__builtin_ia32_selectq_256:
13680 case X86::BI__builtin_ia32_selectq_512:
13681 case X86::BI__builtin_ia32_selectph_128:
13682 case X86::BI__builtin_ia32_selectph_256:
13683 case X86::BI__builtin_ia32_selectph_512:
13684 case X86::BI__builtin_ia32_selectpbf_128:
13685 case X86::BI__builtin_ia32_selectpbf_256:
13686 case X86::BI__builtin_ia32_selectpbf_512:
13687 case X86::BI__builtin_ia32_selectps_128:
13688 case X86::BI__builtin_ia32_selectps_256:
13689 case X86::BI__builtin_ia32_selectps_512:
13690 case X86::BI__builtin_ia32_selectpd_128:
13691 case X86::BI__builtin_ia32_selectpd_256:
13692 case X86::BI__builtin_ia32_selectpd_512: {
13693 // AVX512 predicated move: "Result = Mask[] ? LHS[] : RHS[]".
13694 APValue SourceMask, SourceLHS, SourceRHS;
13695 if (!EvaluateAsRValue(Info, E->getArg(0), SourceMask) ||
13696 !EvaluateAsRValue(Info, E->getArg(1), SourceLHS) ||
13697 !EvaluateAsRValue(Info, E->getArg(2), SourceRHS))
13698 return false;
13699
13700 APSInt Mask = SourceMask.getInt();
13701 unsigned SourceLen = SourceLHS.getVectorLength();
13702 SmallVector<APValue, 4> ResultElements;
13703 ResultElements.reserve(SourceLen);
13704
13705 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
13706 const APValue &LHS = SourceLHS.getVectorElt(EltNum);
13707 const APValue &RHS = SourceRHS.getVectorElt(EltNum);
13708 ResultElements.push_back(Mask[EltNum] ? LHS : RHS);
13709 }
13710
13711 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13712 }
13713
13714 case X86::BI__builtin_ia32_cvtsd2ss: {
13715 APValue VecA, VecB;
13716 if (!EvaluateAsRValue(Info, E->getArg(0), VecA) ||
13717 !EvaluateAsRValue(Info, E->getArg(1), VecB))
13718 return false;
13719
13720 SmallVector<APValue, 4> Elements;
13721
13722 APValue ResultVal;
13723 if (!ConvertDoubleToFloatStrict(Info, E, VecB.getVectorElt(0).getFloat(),
13724 ResultVal))
13725 return false;
13726
13727 Elements.push_back(ResultVal);
13728
13729 unsigned NumEltsA = VecA.getVectorLength();
13730 for (unsigned I = 1; I < NumEltsA; ++I) {
13731 Elements.push_back(VecA.getVectorElt(I));
13732 }
13733
13734 return Success(Elements, E);
13735 }
13736 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: {
13737 APValue VecA, VecB, VecSrc, MaskValue;
13738
13739 if (!EvaluateAsRValue(Info, E->getArg(0), VecA) ||
13740 !EvaluateAsRValue(Info, E->getArg(1), VecB) ||
13741 !EvaluateAsRValue(Info, E->getArg(2), VecSrc) ||
13742 !EvaluateAsRValue(Info, E->getArg(3), MaskValue))
13743 return false;
13744
13745 unsigned Mask = MaskValue.getInt().getZExtValue();
13746 SmallVector<APValue, 4> Elements;
13747
13748 if (Mask & 1) {
13749 APValue ResultVal;
13750 if (!ConvertDoubleToFloatStrict(Info, E, VecB.getVectorElt(0).getFloat(),
13751 ResultVal))
13752 return false;
13753 Elements.push_back(ResultVal);
13754 } else {
13755 Elements.push_back(VecSrc.getVectorElt(0));
13756 }
13757
13758 unsigned NumEltsA = VecA.getVectorLength();
13759 for (unsigned I = 1; I < NumEltsA; ++I) {
13760 Elements.push_back(VecA.getVectorElt(I));
13761 }
13762
13763 return Success(Elements, E);
13764 }
13765 case X86::BI__builtin_ia32_cvtpd2ps:
13766 case X86::BI__builtin_ia32_cvtpd2ps256:
13767 case X86::BI__builtin_ia32_cvtpd2ps_mask:
13768 case X86::BI__builtin_ia32_cvtpd2ps512_mask: {
13769
13770 const auto BuiltinID = BuiltinOp;
13771 bool IsMasked = (BuiltinID == X86::BI__builtin_ia32_cvtpd2ps_mask ||
13772 BuiltinID == X86::BI__builtin_ia32_cvtpd2ps512_mask);
13773
13774 APValue InputValue;
13775 if (!EvaluateAsRValue(Info, E->getArg(0), InputValue))
13776 return false;
13777
13778 APValue MergeValue;
13779 unsigned Mask = 0xFFFFFFFF;
13780 bool NeedsMerge = false;
13781 if (IsMasked) {
13782 APValue MaskValue;
13783 if (!EvaluateAsRValue(Info, E->getArg(2), MaskValue))
13784 return false;
13785 Mask = MaskValue.getInt().getZExtValue();
13786 auto NumEltsResult = E->getType()->getAs<VectorType>()->getNumElements();
13787 for (unsigned I = 0; I < NumEltsResult; ++I) {
13788 if (!((Mask >> I) & 1)) {
13789 NeedsMerge = true;
13790 break;
13791 }
13792 }
13793 if (NeedsMerge) {
13794 if (!EvaluateAsRValue(Info, E->getArg(1), MergeValue))
13795 return false;
13796 }
13797 }
13798
13799 unsigned NumEltsResult =
13800 E->getType()->getAs<VectorType>()->getNumElements();
13801 unsigned NumEltsInput = InputValue.getVectorLength();
13802 SmallVector<APValue, 8> Elements;
13803 for (unsigned I = 0; I < NumEltsResult; ++I) {
13804 if (IsMasked && !((Mask >> I) & 1)) {
13805 if (!NeedsMerge) {
13806 return false;
13807 }
13808 Elements.push_back(MergeValue.getVectorElt(I));
13809 continue;
13810 }
13811
13812 if (I >= NumEltsInput) {
13813 Elements.push_back(APValue(APFloat::getZero(APFloat::IEEEsingle())));
13814 continue;
13815 }
13816
13817 APValue ResultVal;
13819 Info, E, InputValue.getVectorElt(I).getFloat(), ResultVal))
13820 return false;
13821
13822 Elements.push_back(ResultVal);
13823 }
13824 return Success(Elements, E);
13825 }
13826
13827 case X86::BI__builtin_ia32_shufps:
13828 case X86::BI__builtin_ia32_shufps256:
13829 case X86::BI__builtin_ia32_shufps512: {
13830 APValue R;
13831 if (!evalShuffleGeneric(
13832 Info, E, R,
13833 [](unsigned DstIdx,
13834 unsigned ShuffleMask) -> std::pair<unsigned, int> {
13835 constexpr unsigned LaneBits = 128u;
13836 unsigned NumElemPerLane = LaneBits / 32;
13837 unsigned NumSelectableElems = NumElemPerLane / 2;
13838 unsigned BitsPerElem = 2;
13839 unsigned IndexMask = (1u << BitsPerElem) - 1;
13840 unsigned MaskBits = 8;
13841 unsigned Lane = DstIdx / NumElemPerLane;
13842 unsigned ElemInLane = DstIdx % NumElemPerLane;
13843 unsigned LaneOffset = Lane * NumElemPerLane;
13844 unsigned BitIndex = (DstIdx * BitsPerElem) % MaskBits;
13845 unsigned SrcIdx = (ElemInLane < NumSelectableElems) ? 0 : 1;
13846 unsigned Index = (ShuffleMask >> BitIndex) & IndexMask;
13847 return {SrcIdx, static_cast<int>(LaneOffset + Index)};
13848 }))
13849 return false;
13850 return Success(R, E);
13851 }
13852 case X86::BI__builtin_ia32_shufpd:
13853 case X86::BI__builtin_ia32_shufpd256:
13854 case X86::BI__builtin_ia32_shufpd512: {
13855 APValue R;
13856 if (!evalShuffleGeneric(
13857 Info, E, R,
13858 [](unsigned DstIdx,
13859 unsigned ShuffleMask) -> std::pair<unsigned, int> {
13860 constexpr unsigned LaneBits = 128u;
13861 unsigned NumElemPerLane = LaneBits / 64;
13862 unsigned NumSelectableElems = NumElemPerLane / 2;
13863 unsigned BitsPerElem = 1;
13864 unsigned IndexMask = (1u << BitsPerElem) - 1;
13865 unsigned MaskBits = 8;
13866 unsigned Lane = DstIdx / NumElemPerLane;
13867 unsigned ElemInLane = DstIdx % NumElemPerLane;
13868 unsigned LaneOffset = Lane * NumElemPerLane;
13869 unsigned BitIndex = (DstIdx * BitsPerElem) % MaskBits;
13870 unsigned SrcIdx = (ElemInLane < NumSelectableElems) ? 0 : 1;
13871 unsigned Index = (ShuffleMask >> BitIndex) & IndexMask;
13872 return {SrcIdx, static_cast<int>(LaneOffset + Index)};
13873 }))
13874 return false;
13875 return Success(R, E);
13876 }
13877 case X86::BI__builtin_ia32_insertps128: {
13878 APValue R;
13879 if (!evalShuffleGeneric(
13880 Info, E, R,
13881 [](unsigned DstIdx, unsigned Mask) -> std::pair<unsigned, int> {
13882 // Bits [3:0]: zero mask - if bit is set, zero this element
13883 if ((Mask & (1 << DstIdx)) != 0) {
13884 return {0, -1};
13885 }
13886 // Bits [7:6]: select element from source vector Y (0-3)
13887 // Bits [5:4]: select destination position (0-3)
13888 unsigned SrcElem = (Mask >> 6) & 0x3;
13889 unsigned DstElem = (Mask >> 4) & 0x3;
13890 if (DstIdx == DstElem) {
13891 // Insert element from source vector (B) at this position
13892 return {1, static_cast<int>(SrcElem)};
13893 } else {
13894 // Copy from destination vector (A)
13895 return {0, static_cast<int>(DstIdx)};
13896 }
13897 }))
13898 return false;
13899 return Success(R, E);
13900 }
13901 case X86::BI__builtin_ia32_pshufb128:
13902 case X86::BI__builtin_ia32_pshufb256:
13903 case X86::BI__builtin_ia32_pshufb512: {
13904 APValue R;
13905 if (!evalShuffleGeneric(
13906 Info, E, R,
13907 [](unsigned DstIdx,
13908 unsigned ShuffleMask) -> std::pair<unsigned, int> {
13909 uint8_t Ctlb = static_cast<uint8_t>(ShuffleMask);
13910 if (Ctlb & 0x80)
13911 return std::make_pair(0, -1);
13912
13913 unsigned LaneBase = (DstIdx / 16) * 16;
13914 unsigned SrcOffset = Ctlb & 0x0F;
13915 unsigned SrcIdx = LaneBase + SrcOffset;
13916 return std::make_pair(0, static_cast<int>(SrcIdx));
13917 }))
13918 return false;
13919 return Success(R, E);
13920 }
13921
13922 case X86::BI__builtin_ia32_pshuflw:
13923 case X86::BI__builtin_ia32_pshuflw256:
13924 case X86::BI__builtin_ia32_pshuflw512: {
13925 APValue R;
13926 if (!evalShuffleGeneric(
13927 Info, E, R,
13928 [](unsigned DstIdx, unsigned Mask) -> std::pair<unsigned, int> {
13929 constexpr unsigned LaneBits = 128u;
13930 constexpr unsigned ElemBits = 16u;
13931 constexpr unsigned LaneElts = LaneBits / ElemBits;
13932 constexpr unsigned HalfSize = 4;
13933 unsigned LaneBase = (DstIdx / LaneElts) * LaneElts;
13934 unsigned LaneIdx = DstIdx % LaneElts;
13935 if (LaneIdx < HalfSize) {
13936 unsigned Sel = (Mask >> (2 * LaneIdx)) & 0x3;
13937 return std::make_pair(0, static_cast<int>(LaneBase + Sel));
13938 }
13939 return std::make_pair(0, static_cast<int>(DstIdx));
13940 }))
13941 return false;
13942 return Success(R, E);
13943 }
13944
13945 case X86::BI__builtin_ia32_pshufhw:
13946 case X86::BI__builtin_ia32_pshufhw256:
13947 case X86::BI__builtin_ia32_pshufhw512: {
13948 APValue R;
13949 if (!evalShuffleGeneric(
13950 Info, E, R,
13951 [](unsigned DstIdx, unsigned Mask) -> std::pair<unsigned, int> {
13952 constexpr unsigned LaneBits = 128u;
13953 constexpr unsigned ElemBits = 16u;
13954 constexpr unsigned LaneElts = LaneBits / ElemBits;
13955 constexpr unsigned HalfSize = 4;
13956 unsigned LaneBase = (DstIdx / LaneElts) * LaneElts;
13957 unsigned LaneIdx = DstIdx % LaneElts;
13958 if (LaneIdx >= HalfSize) {
13959 unsigned Rel = LaneIdx - HalfSize;
13960 unsigned Sel = (Mask >> (2 * Rel)) & 0x3;
13961 return std::make_pair(
13962 0, static_cast<int>(LaneBase + HalfSize + Sel));
13963 }
13964 return std::make_pair(0, static_cast<int>(DstIdx));
13965 }))
13966 return false;
13967 return Success(R, E);
13968 }
13969
13970 case X86::BI__builtin_ia32_pshufd:
13971 case X86::BI__builtin_ia32_pshufd256:
13972 case X86::BI__builtin_ia32_pshufd512:
13973 case X86::BI__builtin_ia32_vpermilps:
13974 case X86::BI__builtin_ia32_vpermilps256:
13975 case X86::BI__builtin_ia32_vpermilps512: {
13976 APValue R;
13977 if (!evalShuffleGeneric(
13978 Info, E, R,
13979 [](unsigned DstIdx, unsigned Mask) -> std::pair<unsigned, int> {
13980 constexpr unsigned LaneBits = 128u;
13981 constexpr unsigned ElemBits = 32u;
13982 constexpr unsigned LaneElts = LaneBits / ElemBits;
13983 unsigned LaneBase = (DstIdx / LaneElts) * LaneElts;
13984 unsigned LaneIdx = DstIdx % LaneElts;
13985 unsigned Sel = (Mask >> (2 * LaneIdx)) & 0x3;
13986 return std::make_pair(0, static_cast<int>(LaneBase + Sel));
13987 }))
13988 return false;
13989 return Success(R, E);
13990 }
13991
13992 case X86::BI__builtin_ia32_vpermilvarpd:
13993 case X86::BI__builtin_ia32_vpermilvarpd256:
13994 case X86::BI__builtin_ia32_vpermilvarpd512: {
13995 APValue R;
13996 if (!evalShuffleGeneric(
13997 Info, E, R,
13998 [](unsigned DstIdx, unsigned Mask) -> std::pair<unsigned, int> {
13999 unsigned NumElemPerLane = 2;
14000 unsigned Lane = DstIdx / NumElemPerLane;
14001 unsigned Offset = Mask & 0b10 ? 1 : 0;
14002 return std::make_pair(
14003 0, static_cast<int>(Lane * NumElemPerLane + Offset));
14004 }))
14005 return false;
14006 return Success(R, E);
14007 }
14008
14009 case X86::BI__builtin_ia32_vpermilpd:
14010 case X86::BI__builtin_ia32_vpermilpd256:
14011 case X86::BI__builtin_ia32_vpermilpd512: {
14012 APValue R;
14013 if (!evalShuffleGeneric(Info, E, R, [](unsigned DstIdx, unsigned Control) {
14014 unsigned NumElemPerLane = 2;
14015 unsigned BitsPerElem = 1;
14016 unsigned MaskBits = 8;
14017 unsigned IndexMask = 0x1;
14018 unsigned Lane = DstIdx / NumElemPerLane;
14019 unsigned LaneOffset = Lane * NumElemPerLane;
14020 unsigned BitIndex = (DstIdx * BitsPerElem) % MaskBits;
14021 unsigned Index = (Control >> BitIndex) & IndexMask;
14022 return std::make_pair(0, static_cast<int>(LaneOffset + Index));
14023 }))
14024 return false;
14025 return Success(R, E);
14026 }
14027
14028 case X86::BI__builtin_ia32_permdf256:
14029 case X86::BI__builtin_ia32_permdi256: {
14030 APValue R;
14031 if (!evalShuffleGeneric(Info, E, R, [](unsigned DstIdx, unsigned Control) {
14032 // permute4x64 operates on 4 64-bit elements
14033 // For element i (0-3), extract bits [2*i+1:2*i] from Control
14034 unsigned Index = (Control >> (2 * DstIdx)) & 0x3;
14035 return std::make_pair(0, static_cast<int>(Index));
14036 }))
14037 return false;
14038 return Success(R, E);
14039 }
14040
14041 case X86::BI__builtin_ia32_vpermilvarps:
14042 case X86::BI__builtin_ia32_vpermilvarps256:
14043 case X86::BI__builtin_ia32_vpermilvarps512: {
14044 APValue R;
14045 if (!evalShuffleGeneric(
14046 Info, E, R,
14047 [](unsigned DstIdx, unsigned Mask) -> std::pair<unsigned, int> {
14048 unsigned NumElemPerLane = 4;
14049 unsigned Lane = DstIdx / NumElemPerLane;
14050 unsigned Offset = Mask & 0b11;
14051 return std::make_pair(
14052 0, static_cast<int>(Lane * NumElemPerLane + Offset));
14053 }))
14054 return false;
14055 return Success(R, E);
14056 }
14057
14058 case X86::BI__builtin_ia32_vpmultishiftqb128:
14059 case X86::BI__builtin_ia32_vpmultishiftqb256:
14060 case X86::BI__builtin_ia32_vpmultishiftqb512: {
14061 assert(E->getNumArgs() == 2);
14062
14063 APValue A, B;
14064 if (!Evaluate(A, Info, E->getArg(0)) || !Evaluate(B, Info, E->getArg(1)))
14065 return false;
14066
14067 assert(A.getVectorLength() == B.getVectorLength());
14068 unsigned NumBytesInQWord = 8;
14069 unsigned NumBitsInByte = 8;
14070 unsigned NumBytes = A.getVectorLength();
14071 unsigned NumQWords = NumBytes / NumBytesInQWord;
14073 Result.reserve(NumBytes);
14074
14075 for (unsigned QWordId = 0; QWordId != NumQWords; ++QWordId) {
14076 APInt BQWord(64, 0);
14077 for (unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
14078 unsigned Idx = QWordId * NumBytesInQWord + ByteIdx;
14079 uint64_t Byte = B.getVectorElt(Idx).getInt().getZExtValue();
14080 BQWord.insertBits(APInt(8, Byte & 0xFF), ByteIdx * NumBitsInByte);
14081 }
14082
14083 for (unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
14084 unsigned Idx = QWordId * NumBytesInQWord + ByteIdx;
14085 uint64_t Ctrl = A.getVectorElt(Idx).getInt().getZExtValue() & 0x3F;
14086
14087 APInt Byte(8, 0);
14088 for (unsigned BitIdx = 0; BitIdx != NumBitsInByte; ++BitIdx) {
14089 Byte.setBitVal(BitIdx, BQWord[(Ctrl + BitIdx) & 0x3F]);
14090 }
14091 Result.push_back(APValue(APSInt(Byte, /*isUnsigned*/ true)));
14092 }
14093 }
14094 return Success(APValue(Result.data(), Result.size()), E);
14095 }
14096
14097 case X86::BI__builtin_ia32_phminposuw128: {
14098 APValue Source;
14099 if (!Evaluate(Source, Info, E->getArg(0)))
14100 return false;
14101 unsigned SourceLen = Source.getVectorLength();
14102 const VectorType *VT = E->getArg(0)->getType()->castAs<VectorType>();
14103 QualType ElemQT = VT->getElementType();
14104 unsigned ElemBitWidth = Info.Ctx.getTypeSize(ElemQT);
14105
14106 APInt MinIndex(ElemBitWidth, 0);
14107 APInt MinVal = Source.getVectorElt(0).getInt();
14108 for (unsigned I = 1; I != SourceLen; ++I) {
14109 APInt Val = Source.getVectorElt(I).getInt();
14110 if (MinVal.ugt(Val)) {
14111 MinVal = Val;
14112 MinIndex = I;
14113 }
14114 }
14115
14116 bool ResultUnsigned = E->getCallReturnType(Info.Ctx)
14117 ->castAs<VectorType>()
14118 ->getElementType()
14119 ->isUnsignedIntegerOrEnumerationType();
14120
14122 Result.reserve(SourceLen);
14123 Result.emplace_back(APSInt(MinVal, ResultUnsigned));
14124 Result.emplace_back(APSInt(MinIndex, ResultUnsigned));
14125 for (unsigned I = 0; I != SourceLen - 2; ++I) {
14126 Result.emplace_back(APSInt(APInt(ElemBitWidth, 0), ResultUnsigned));
14127 }
14128 return Success(APValue(Result.data(), Result.size()), E);
14129 }
14130
14131 case X86::BI__builtin_ia32_psraq128:
14132 case X86::BI__builtin_ia32_psraq256:
14133 case X86::BI__builtin_ia32_psraq512:
14134 case X86::BI__builtin_ia32_psrad128:
14135 case X86::BI__builtin_ia32_psrad256:
14136 case X86::BI__builtin_ia32_psrad512:
14137 case X86::BI__builtin_ia32_psraw128:
14138 case X86::BI__builtin_ia32_psraw256:
14139 case X86::BI__builtin_ia32_psraw512: {
14140 APValue R;
14141 if (!evalShiftWithCount(
14142 Info, E, R,
14143 [](const APInt &Elt, uint64_t Count) { return Elt.ashr(Count); },
14144 [](const APInt &Elt, unsigned Width) {
14145 return Elt.ashr(Width - 1);
14146 }))
14147 return false;
14148 return Success(R, E);
14149 }
14150
14151 case X86::BI__builtin_ia32_psllq128:
14152 case X86::BI__builtin_ia32_psllq256:
14153 case X86::BI__builtin_ia32_psllq512:
14154 case X86::BI__builtin_ia32_pslld128:
14155 case X86::BI__builtin_ia32_pslld256:
14156 case X86::BI__builtin_ia32_pslld512:
14157 case X86::BI__builtin_ia32_psllw128:
14158 case X86::BI__builtin_ia32_psllw256:
14159 case X86::BI__builtin_ia32_psllw512: {
14160 APValue R;
14161 if (!evalShiftWithCount(
14162 Info, E, R,
14163 [](const APInt &Elt, uint64_t Count) { return Elt.shl(Count); },
14164 [](const APInt &Elt, unsigned Width) {
14165 return APInt::getZero(Width);
14166 }))
14167 return false;
14168 return Success(R, E);
14169 }
14170
14171 case X86::BI__builtin_ia32_psrlq128:
14172 case X86::BI__builtin_ia32_psrlq256:
14173 case X86::BI__builtin_ia32_psrlq512:
14174 case X86::BI__builtin_ia32_psrld128:
14175 case X86::BI__builtin_ia32_psrld256:
14176 case X86::BI__builtin_ia32_psrld512:
14177 case X86::BI__builtin_ia32_psrlw128:
14178 case X86::BI__builtin_ia32_psrlw256:
14179 case X86::BI__builtin_ia32_psrlw512: {
14180 APValue R;
14181 if (!evalShiftWithCount(
14182 Info, E, R,
14183 [](const APInt &Elt, uint64_t Count) { return Elt.lshr(Count); },
14184 [](const APInt &Elt, unsigned Width) {
14185 return APInt::getZero(Width);
14186 }))
14187 return false;
14188 return Success(R, E);
14189 }
14190
14191 case X86::BI__builtin_ia32_pternlogd128_mask:
14192 case X86::BI__builtin_ia32_pternlogd256_mask:
14193 case X86::BI__builtin_ia32_pternlogd512_mask:
14194 case X86::BI__builtin_ia32_pternlogq128_mask:
14195 case X86::BI__builtin_ia32_pternlogq256_mask:
14196 case X86::BI__builtin_ia32_pternlogq512_mask: {
14197 APValue AValue, BValue, CValue, ImmValue, UValue;
14198 if (!EvaluateAsRValue(Info, E->getArg(0), AValue) ||
14199 !EvaluateAsRValue(Info, E->getArg(1), BValue) ||
14200 !EvaluateAsRValue(Info, E->getArg(2), CValue) ||
14201 !EvaluateAsRValue(Info, E->getArg(3), ImmValue) ||
14202 !EvaluateAsRValue(Info, E->getArg(4), UValue))
14203 return false;
14204
14205 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
14206 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
14207 APInt Imm = ImmValue.getInt();
14208 APInt U = UValue.getInt();
14209 unsigned ResultLen = AValue.getVectorLength();
14210 SmallVector<APValue, 16> ResultElements;
14211 ResultElements.reserve(ResultLen);
14212
14213 for (unsigned EltNum = 0; EltNum < ResultLen; ++EltNum) {
14214 APInt ALane = AValue.getVectorElt(EltNum).getInt();
14215 APInt BLane = BValue.getVectorElt(EltNum).getInt();
14216 APInt CLane = CValue.getVectorElt(EltNum).getInt();
14217
14218 if (U[EltNum]) {
14219 unsigned BitWidth = ALane.getBitWidth();
14220 APInt ResLane(BitWidth, 0);
14221
14222 for (unsigned Bit = 0; Bit < BitWidth; ++Bit) {
14223 unsigned ABit = ALane[Bit];
14224 unsigned BBit = BLane[Bit];
14225 unsigned CBit = CLane[Bit];
14226
14227 unsigned Idx = (ABit << 2) | (BBit << 1) | CBit;
14228 ResLane.setBitVal(Bit, Imm[Idx]);
14229 }
14230 ResultElements.push_back(APValue(APSInt(ResLane, DestUnsigned)));
14231 } else {
14232 ResultElements.push_back(APValue(APSInt(ALane, DestUnsigned)));
14233 }
14234 }
14235 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
14236 }
14237 case X86::BI__builtin_ia32_pternlogd128_maskz:
14238 case X86::BI__builtin_ia32_pternlogd256_maskz:
14239 case X86::BI__builtin_ia32_pternlogd512_maskz:
14240 case X86::BI__builtin_ia32_pternlogq128_maskz:
14241 case X86::BI__builtin_ia32_pternlogq256_maskz:
14242 case X86::BI__builtin_ia32_pternlogq512_maskz: {
14243 APValue AValue, BValue, CValue, ImmValue, UValue;
14244 if (!EvaluateAsRValue(Info, E->getArg(0), AValue) ||
14245 !EvaluateAsRValue(Info, E->getArg(1), BValue) ||
14246 !EvaluateAsRValue(Info, E->getArg(2), CValue) ||
14247 !EvaluateAsRValue(Info, E->getArg(3), ImmValue) ||
14248 !EvaluateAsRValue(Info, E->getArg(4), UValue))
14249 return false;
14250
14251 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
14252 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
14253 APInt Imm = ImmValue.getInt();
14254 APInt U = UValue.getInt();
14255 unsigned ResultLen = AValue.getVectorLength();
14256 SmallVector<APValue, 16> ResultElements;
14257 ResultElements.reserve(ResultLen);
14258
14259 for (unsigned EltNum = 0; EltNum < ResultLen; ++EltNum) {
14260 APInt ALane = AValue.getVectorElt(EltNum).getInt();
14261 APInt BLane = BValue.getVectorElt(EltNum).getInt();
14262 APInt CLane = CValue.getVectorElt(EltNum).getInt();
14263
14264 unsigned BitWidth = ALane.getBitWidth();
14265 APInt ResLane(BitWidth, 0);
14266
14267 if (U[EltNum]) {
14268 for (unsigned Bit = 0; Bit < BitWidth; ++Bit) {
14269 unsigned ABit = ALane[Bit];
14270 unsigned BBit = BLane[Bit];
14271 unsigned CBit = CLane[Bit];
14272
14273 unsigned Idx = (ABit << 2) | (BBit << 1) | CBit;
14274 ResLane.setBitVal(Bit, Imm[Idx]);
14275 }
14276 }
14277 ResultElements.push_back(APValue(APSInt(ResLane, DestUnsigned)));
14278 }
14279 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
14280 }
14281
14282 case Builtin::BI__builtin_elementwise_clzg:
14283 case Builtin::BI__builtin_elementwise_ctzg: {
14284 APValue SourceLHS;
14285 std::optional<APValue> Fallback;
14286 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS))
14287 return false;
14288 if (E->getNumArgs() > 1) {
14289 APValue FallbackTmp;
14290 if (!EvaluateAsRValue(Info, E->getArg(1), FallbackTmp))
14291 return false;
14292 Fallback = FallbackTmp;
14293 }
14294
14295 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
14296 unsigned SourceLen = SourceLHS.getVectorLength();
14297 SmallVector<APValue, 4> ResultElements;
14298 ResultElements.reserve(SourceLen);
14299
14300 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
14301 APSInt LHS = SourceLHS.getVectorElt(EltNum).getInt();
14302 if (!LHS) {
14303 // Without a fallback, a zero element is undefined
14304 if (!Fallback) {
14305 Info.FFDiag(E, diag::note_constexpr_countzeroes_zero)
14306 << /*IsTrailing=*/(BuiltinOp ==
14307 Builtin::BI__builtin_elementwise_ctzg);
14308 return false;
14309 }
14310 ResultElements.push_back(Fallback->getVectorElt(EltNum));
14311 continue;
14312 }
14313 switch (BuiltinOp) {
14314 case Builtin::BI__builtin_elementwise_clzg:
14315 ResultElements.push_back(APValue(
14316 APSInt(APInt(Info.Ctx.getIntWidth(DestEltTy), LHS.countl_zero()),
14317 DestEltTy->isUnsignedIntegerOrEnumerationType())));
14318 break;
14319 case Builtin::BI__builtin_elementwise_ctzg:
14320 ResultElements.push_back(APValue(
14321 APSInt(APInt(Info.Ctx.getIntWidth(DestEltTy), LHS.countr_zero()),
14322 DestEltTy->isUnsignedIntegerOrEnumerationType())));
14323 break;
14324 }
14325 }
14326
14327 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
14328 }
14329
14330 case Builtin::BI__builtin_elementwise_fma: {
14331 APValue SourceX, SourceY, SourceZ;
14332 if (!EvaluateAsRValue(Info, E->getArg(0), SourceX) ||
14333 !EvaluateAsRValue(Info, E->getArg(1), SourceY) ||
14334 !EvaluateAsRValue(Info, E->getArg(2), SourceZ))
14335 return false;
14336
14337 unsigned SourceLen = SourceX.getVectorLength();
14338 SmallVector<APValue> ResultElements;
14339 ResultElements.reserve(SourceLen);
14340 llvm::RoundingMode RM = getActiveRoundingMode(getEvalInfo(), E);
14341 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
14342 const APFloat &X = SourceX.getVectorElt(EltNum).getFloat();
14343 const APFloat &Y = SourceY.getVectorElt(EltNum).getFloat();
14344 const APFloat &Z = SourceZ.getVectorElt(EltNum).getFloat();
14345 APFloat Result(X);
14346 (void)Result.fusedMultiplyAdd(Y, Z, RM);
14347 ResultElements.push_back(APValue(Result));
14348 }
14349 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
14350 }
14351
14352 case clang::X86::BI__builtin_ia32_phaddw128:
14353 case clang::X86::BI__builtin_ia32_phaddw256:
14354 case clang::X86::BI__builtin_ia32_phaddd128:
14355 case clang::X86::BI__builtin_ia32_phaddd256:
14356 case clang::X86::BI__builtin_ia32_phaddsw128:
14357 case clang::X86::BI__builtin_ia32_phaddsw256:
14358
14359 case clang::X86::BI__builtin_ia32_phsubw128:
14360 case clang::X86::BI__builtin_ia32_phsubw256:
14361 case clang::X86::BI__builtin_ia32_phsubd128:
14362 case clang::X86::BI__builtin_ia32_phsubd256:
14363 case clang::X86::BI__builtin_ia32_phsubsw128:
14364 case clang::X86::BI__builtin_ia32_phsubsw256: {
14365 APValue SourceLHS, SourceRHS;
14366 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
14367 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
14368 return false;
14369 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
14370 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
14371
14372 unsigned NumElts = SourceLHS.getVectorLength();
14373 unsigned EltBits = Info.Ctx.getIntWidth(DestEltTy);
14374 unsigned EltsPerLane = 128 / EltBits;
14375 SmallVector<APValue, 4> ResultElements;
14376 ResultElements.reserve(NumElts);
14377
14378 for (unsigned LaneStart = 0; LaneStart != NumElts;
14379 LaneStart += EltsPerLane) {
14380 for (unsigned I = 0; I != EltsPerLane; I += 2) {
14381 APSInt LHSA = SourceLHS.getVectorElt(LaneStart + I).getInt();
14382 APSInt LHSB = SourceLHS.getVectorElt(LaneStart + I + 1).getInt();
14383 switch (BuiltinOp) {
14384 case clang::X86::BI__builtin_ia32_phaddw128:
14385 case clang::X86::BI__builtin_ia32_phaddw256:
14386 case clang::X86::BI__builtin_ia32_phaddd128:
14387 case clang::X86::BI__builtin_ia32_phaddd256: {
14388 APSInt Res(LHSA + LHSB, DestUnsigned);
14389 ResultElements.push_back(APValue(Res));
14390 break;
14391 }
14392 case clang::X86::BI__builtin_ia32_phaddsw128:
14393 case clang::X86::BI__builtin_ia32_phaddsw256: {
14394 APSInt Res(LHSA.sadd_sat(LHSB));
14395 ResultElements.push_back(APValue(Res));
14396 break;
14397 }
14398 case clang::X86::BI__builtin_ia32_phsubw128:
14399 case clang::X86::BI__builtin_ia32_phsubw256:
14400 case clang::X86::BI__builtin_ia32_phsubd128:
14401 case clang::X86::BI__builtin_ia32_phsubd256: {
14402 APSInt Res(LHSA - LHSB, DestUnsigned);
14403 ResultElements.push_back(APValue(Res));
14404 break;
14405 }
14406 case clang::X86::BI__builtin_ia32_phsubsw128:
14407 case clang::X86::BI__builtin_ia32_phsubsw256: {
14408 APSInt Res(LHSA.ssub_sat(LHSB));
14409 ResultElements.push_back(APValue(Res));
14410 break;
14411 }
14412 }
14413 }
14414 for (unsigned I = 0; I != EltsPerLane; I += 2) {
14415 APSInt RHSA = SourceRHS.getVectorElt(LaneStart + I).getInt();
14416 APSInt RHSB = SourceRHS.getVectorElt(LaneStart + I + 1).getInt();
14417 switch (BuiltinOp) {
14418 case clang::X86::BI__builtin_ia32_phaddw128:
14419 case clang::X86::BI__builtin_ia32_phaddw256:
14420 case clang::X86::BI__builtin_ia32_phaddd128:
14421 case clang::X86::BI__builtin_ia32_phaddd256: {
14422 APSInt Res(RHSA + RHSB, DestUnsigned);
14423 ResultElements.push_back(APValue(Res));
14424 break;
14425 }
14426 case clang::X86::BI__builtin_ia32_phaddsw128:
14427 case clang::X86::BI__builtin_ia32_phaddsw256: {
14428 APSInt Res(RHSA.sadd_sat(RHSB));
14429 ResultElements.push_back(APValue(Res));
14430 break;
14431 }
14432 case clang::X86::BI__builtin_ia32_phsubw128:
14433 case clang::X86::BI__builtin_ia32_phsubw256:
14434 case clang::X86::BI__builtin_ia32_phsubd128:
14435 case clang::X86::BI__builtin_ia32_phsubd256: {
14436 APSInt Res(RHSA - RHSB, DestUnsigned);
14437 ResultElements.push_back(APValue(Res));
14438 break;
14439 }
14440 case clang::X86::BI__builtin_ia32_phsubsw128:
14441 case clang::X86::BI__builtin_ia32_phsubsw256: {
14442 APSInt Res(RHSA.ssub_sat(RHSB));
14443 ResultElements.push_back(APValue(Res));
14444 break;
14445 }
14446 }
14447 }
14448 }
14449 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
14450 }
14451 case clang::X86::BI__builtin_ia32_haddpd:
14452 case clang::X86::BI__builtin_ia32_haddps:
14453 case clang::X86::BI__builtin_ia32_haddps256:
14454 case clang::X86::BI__builtin_ia32_haddpd256:
14455 case clang::X86::BI__builtin_ia32_hsubpd:
14456 case clang::X86::BI__builtin_ia32_hsubps:
14457 case clang::X86::BI__builtin_ia32_hsubps256:
14458 case clang::X86::BI__builtin_ia32_hsubpd256: {
14459 APValue SourceLHS, SourceRHS;
14460 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
14461 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
14462 return false;
14463 unsigned NumElts = SourceLHS.getVectorLength();
14464 SmallVector<APValue, 4> ResultElements;
14465 ResultElements.reserve(NumElts);
14466 llvm::RoundingMode RM = getActiveRoundingMode(getEvalInfo(), E);
14467 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
14468 unsigned EltBits = Info.Ctx.getTypeSize(DestEltTy);
14469 unsigned NumLanes = NumElts * EltBits / 128;
14470 unsigned NumElemsPerLane = NumElts / NumLanes;
14471 unsigned HalfElemsPerLane = NumElemsPerLane / 2;
14472
14473 for (unsigned L = 0; L != NumElts; L += NumElemsPerLane) {
14474 for (unsigned I = 0; I != HalfElemsPerLane; ++I) {
14475 APFloat LHSA = SourceLHS.getVectorElt(L + (2 * I) + 0).getFloat();
14476 APFloat LHSB = SourceLHS.getVectorElt(L + (2 * I) + 1).getFloat();
14477 switch (BuiltinOp) {
14478 case clang::X86::BI__builtin_ia32_haddpd:
14479 case clang::X86::BI__builtin_ia32_haddps:
14480 case clang::X86::BI__builtin_ia32_haddps256:
14481 case clang::X86::BI__builtin_ia32_haddpd256:
14482 LHSA.add(LHSB, RM);
14483 break;
14484 case clang::X86::BI__builtin_ia32_hsubpd:
14485 case clang::X86::BI__builtin_ia32_hsubps:
14486 case clang::X86::BI__builtin_ia32_hsubps256:
14487 case clang::X86::BI__builtin_ia32_hsubpd256:
14488 LHSA.subtract(LHSB, RM);
14489 break;
14490 }
14491 ResultElements.push_back(APValue(LHSA));
14492 }
14493 for (unsigned I = 0; I != HalfElemsPerLane; ++I) {
14494 APFloat RHSA = SourceRHS.getVectorElt(L + (2 * I) + 0).getFloat();
14495 APFloat RHSB = SourceRHS.getVectorElt(L + (2 * I) + 1).getFloat();
14496 switch (BuiltinOp) {
14497 case clang::X86::BI__builtin_ia32_haddpd:
14498 case clang::X86::BI__builtin_ia32_haddps:
14499 case clang::X86::BI__builtin_ia32_haddps256:
14500 case clang::X86::BI__builtin_ia32_haddpd256:
14501 RHSA.add(RHSB, RM);
14502 break;
14503 case clang::X86::BI__builtin_ia32_hsubpd:
14504 case clang::X86::BI__builtin_ia32_hsubps:
14505 case clang::X86::BI__builtin_ia32_hsubps256:
14506 case clang::X86::BI__builtin_ia32_hsubpd256:
14507 RHSA.subtract(RHSB, RM);
14508 break;
14509 }
14510 ResultElements.push_back(APValue(RHSA));
14511 }
14512 }
14513 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
14514 }
14515 case clang::X86::BI__builtin_ia32_addsubpd:
14516 case clang::X86::BI__builtin_ia32_addsubps:
14517 case clang::X86::BI__builtin_ia32_addsubpd256:
14518 case clang::X86::BI__builtin_ia32_addsubps256: {
14519 // Addsub: alternates between subtraction and addition
14520 // Result[i] = (i % 2 == 0) ? (a[i] - b[i]) : (a[i] + b[i])
14521 APValue SourceLHS, SourceRHS;
14522 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
14523 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
14524 return false;
14525 unsigned NumElems = SourceLHS.getVectorLength();
14526 SmallVector<APValue, 8> ResultElements;
14527 ResultElements.reserve(NumElems);
14528 llvm::RoundingMode RM = getActiveRoundingMode(getEvalInfo(), E);
14529
14530 for (unsigned I = 0; I != NumElems; ++I) {
14531 APFloat LHS = SourceLHS.getVectorElt(I).getFloat();
14532 APFloat RHS = SourceRHS.getVectorElt(I).getFloat();
14533 if (I % 2 == 0) {
14534 // Even indices: subtract
14535 LHS.subtract(RHS, RM);
14536 } else {
14537 // Odd indices: add
14538 LHS.add(RHS, RM);
14539 }
14540 ResultElements.push_back(APValue(LHS));
14541 }
14542 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
14543 }
14544 case clang::X86::BI__builtin_ia32_pclmulqdq128:
14545 case clang::X86::BI__builtin_ia32_pclmulqdq256:
14546 case clang::X86::BI__builtin_ia32_pclmulqdq512: {
14547 // PCLMULQDQ: carry-less multiplication of selected 64-bit halves
14548 // imm8 bit 0: selects lower (0) or upper (1) 64 bits of first operand
14549 // imm8 bit 4: selects lower (0) or upper (1) 64 bits of second operand
14550 APValue SourceLHS, SourceRHS;
14551 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
14552 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
14553 return false;
14554
14555 APSInt Imm8;
14556 if (!EvaluateInteger(E->getArg(2), Imm8, Info))
14557 return false;
14558
14559 // Extract bits 0 and 4 from imm8
14560 bool SelectUpperA = (Imm8 & 0x01) != 0;
14561 bool SelectUpperB = (Imm8 & 0x10) != 0;
14562
14563 unsigned NumElems = SourceLHS.getVectorLength();
14564 SmallVector<APValue, 8> ResultElements;
14565 ResultElements.reserve(NumElems);
14566 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
14567 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
14568
14569 // Process each 128-bit lane
14570 for (unsigned Lane = 0; Lane < NumElems; Lane += 2) {
14571 // Get the two 64-bit halves of the first operand
14572 APSInt A0 = SourceLHS.getVectorElt(Lane + 0).getInt();
14573 APSInt A1 = SourceLHS.getVectorElt(Lane + 1).getInt();
14574 // Get the two 64-bit halves of the second operand
14575 APSInt B0 = SourceRHS.getVectorElt(Lane + 0).getInt();
14576 APSInt B1 = SourceRHS.getVectorElt(Lane + 1).getInt();
14577
14578 // Select the appropriate 64-bit values based on imm8
14579 APInt A = SelectUpperA ? A1 : A0;
14580 APInt B = SelectUpperB ? B1 : B0;
14581
14582 // Extend both operands to 128 bits for carry-less multiplication
14583 APInt A128 = A.zext(128);
14584 APInt B128 = B.zext(128);
14585
14586 // Use APIntOps::clmul for carry-less multiplication
14587 APInt Result = llvm::APIntOps::clmul(A128, B128);
14588
14589 // Split the 128-bit result into two 64-bit halves
14590 APSInt ResultLow(Result.extractBits(64, 0), DestUnsigned);
14591 APSInt ResultHigh(Result.extractBits(64, 64), DestUnsigned);
14592
14593 ResultElements.push_back(APValue(ResultLow));
14594 ResultElements.push_back(APValue(ResultHigh));
14595 }
14596
14597 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
14598 }
14599 case Builtin::BI__builtin_elementwise_clmul:
14600 return EvaluateBinOpExpr(llvm::APIntOps::clmul);
14601 case Builtin::BI__builtin_elementwise_pext:
14602 return EvaluateBinOpExpr(llvm::APIntOps::pext);
14603 case Builtin::BI__builtin_elementwise_pdep:
14604 return EvaluateBinOpExpr(llvm::APIntOps::pdep);
14605 case Builtin::BI__builtin_elementwise_fshl:
14606 case Builtin::BI__builtin_elementwise_fshr: {
14607 APValue SourceHi, SourceLo, SourceShift;
14608 if (!EvaluateAsRValue(Info, E->getArg(0), SourceHi) ||
14609 !EvaluateAsRValue(Info, E->getArg(1), SourceLo) ||
14610 !EvaluateAsRValue(Info, E->getArg(2), SourceShift))
14611 return false;
14612
14613 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
14614 if (!DestEltTy->isIntegerType())
14615 return false;
14616
14617 unsigned SourceLen = SourceHi.getVectorLength();
14618 SmallVector<APValue> ResultElements;
14619 ResultElements.reserve(SourceLen);
14620 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
14621 const APSInt &Hi = SourceHi.getVectorElt(EltNum).getInt();
14622 const APSInt &Lo = SourceLo.getVectorElt(EltNum).getInt();
14623 const APSInt &Shift = SourceShift.getVectorElt(EltNum).getInt();
14624 switch (BuiltinOp) {
14625 case Builtin::BI__builtin_elementwise_fshl:
14626 ResultElements.push_back(APValue(
14627 APSInt(llvm::APIntOps::fshl(Hi, Lo, Shift), Hi.isUnsigned())));
14628 break;
14629 case Builtin::BI__builtin_elementwise_fshr:
14630 ResultElements.push_back(APValue(
14631 APSInt(llvm::APIntOps::fshr(Hi, Lo, Shift), Hi.isUnsigned())));
14632 break;
14633 }
14634 }
14635
14636 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
14637 }
14638
14639 case X86::BI__builtin_ia32_shuf_f32x4_256:
14640 case X86::BI__builtin_ia32_shuf_i32x4_256:
14641 case X86::BI__builtin_ia32_shuf_f64x2_256:
14642 case X86::BI__builtin_ia32_shuf_i64x2_256:
14643 case X86::BI__builtin_ia32_shuf_f32x4:
14644 case X86::BI__builtin_ia32_shuf_i32x4:
14645 case X86::BI__builtin_ia32_shuf_f64x2:
14646 case X86::BI__builtin_ia32_shuf_i64x2: {
14647 APValue SourceA, SourceB;
14648 if (!EvaluateAsRValue(Info, E->getArg(0), SourceA) ||
14649 !EvaluateAsRValue(Info, E->getArg(1), SourceB))
14650 return false;
14651
14652 APSInt Imm;
14653 if (!EvaluateInteger(E->getArg(2), Imm, Info))
14654 return false;
14655
14656 // Destination and sources A, B all have the same type.
14657 unsigned NumElems = SourceA.getVectorLength();
14658 const VectorType *VT = E->getArg(0)->getType()->castAs<VectorType>();
14659 QualType ElemQT = VT->getElementType();
14660 unsigned ElemBits = Info.Ctx.getTypeSize(ElemQT);
14661 unsigned LaneBits = 128u;
14662 unsigned NumLanes = (NumElems * ElemBits) / LaneBits;
14663 unsigned NumElemsPerLane = LaneBits / ElemBits;
14664
14665 unsigned DstLen = SourceA.getVectorLength();
14666 SmallVector<APValue, 16> ResultElements;
14667 ResultElements.reserve(DstLen);
14668
14669 APValue R;
14670 if (!evalShuffleGeneric(
14671 Info, E, R,
14672 [NumLanes, NumElemsPerLane](unsigned DstIdx, unsigned ShuffleMask)
14673 -> std::pair<unsigned, int> {
14674 // DstIdx determines source. ShuffleMask selects lane in source.
14675 unsigned BitsPerElem = NumLanes / 2;
14676 unsigned IndexMask = (1u << BitsPerElem) - 1;
14677 unsigned Lane = DstIdx / NumElemsPerLane;
14678 unsigned SrcIdx = (Lane < NumLanes / 2) ? 0 : 1;
14679 unsigned BitIdx = BitsPerElem * Lane;
14680 unsigned SrcLaneIdx = (ShuffleMask >> BitIdx) & IndexMask;
14681 unsigned ElemInLane = DstIdx % NumElemsPerLane;
14682 unsigned IdxToPick = SrcLaneIdx * NumElemsPerLane + ElemInLane;
14683 return {SrcIdx, IdxToPick};
14684 }))
14685 return false;
14686 return Success(R, E);
14687 }
14688
14689 case X86::BI__builtin_ia32_vgf2p8affineinvqb_v16qi:
14690 case X86::BI__builtin_ia32_vgf2p8affineinvqb_v32qi:
14691 case X86::BI__builtin_ia32_vgf2p8affineinvqb_v64qi:
14692 case X86::BI__builtin_ia32_vgf2p8affineqb_v16qi:
14693 case X86::BI__builtin_ia32_vgf2p8affineqb_v32qi:
14694 case X86::BI__builtin_ia32_vgf2p8affineqb_v64qi: {
14695
14696 APValue X, A;
14697 APSInt Imm;
14698 if (!EvaluateAsRValue(Info, E->getArg(0), X) ||
14699 !EvaluateAsRValue(Info, E->getArg(1), A) ||
14700 !EvaluateInteger(E->getArg(2), Imm, Info))
14701 return false;
14702
14703 assert(X.isVector() && A.isVector());
14704 assert(X.getVectorLength() == A.getVectorLength());
14705
14706 bool IsInverse = false;
14707 switch (BuiltinOp) {
14708 case X86::BI__builtin_ia32_vgf2p8affineinvqb_v16qi:
14709 case X86::BI__builtin_ia32_vgf2p8affineinvqb_v32qi:
14710 case X86::BI__builtin_ia32_vgf2p8affineinvqb_v64qi: {
14711 IsInverse = true;
14712 }
14713 }
14714
14715 unsigned NumBitsInByte = 8;
14716 unsigned NumBytesInQWord = 8;
14717 unsigned NumBitsInQWord = 64;
14718 unsigned NumBytes = A.getVectorLength();
14719 unsigned NumQWords = NumBytes / NumBytesInQWord;
14721 Result.reserve(NumBytes);
14722
14723 // computing A*X + Imm
14724 for (unsigned QWordIdx = 0; QWordIdx != NumQWords; ++QWordIdx) {
14725 // Extract the QWords from X, A
14726 APInt XQWord(NumBitsInQWord, 0);
14727 APInt AQWord(NumBitsInQWord, 0);
14728 for (unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
14729 unsigned Idx = QWordIdx * NumBytesInQWord + ByteIdx;
14730 APInt XByte = X.getVectorElt(Idx).getInt();
14731 APInt AByte = A.getVectorElt(Idx).getInt();
14732 XQWord.insertBits(XByte, ByteIdx * NumBitsInByte);
14733 AQWord.insertBits(AByte, ByteIdx * NumBitsInByte);
14734 }
14735
14736 for (unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
14737 uint8_t XByte =
14738 XQWord.lshr(ByteIdx * NumBitsInByte).getLoBits(8).getZExtValue();
14739 Result.push_back(APValue(APSInt(
14740 APInt(8, GFNIAffine(XByte, AQWord, Imm, IsInverse)), false)));
14741 }
14742 }
14743
14744 return Success(APValue(Result.data(), Result.size()), E);
14745 }
14746
14747 case X86::BI__builtin_ia32_vgf2p8mulb_v16qi:
14748 case X86::BI__builtin_ia32_vgf2p8mulb_v32qi:
14749 case X86::BI__builtin_ia32_vgf2p8mulb_v64qi: {
14750 APValue A, B;
14751 if (!EvaluateAsRValue(Info, E->getArg(0), A) ||
14752 !EvaluateAsRValue(Info, E->getArg(1), B))
14753 return false;
14754
14755 assert(A.isVector() && B.isVector());
14756 assert(A.getVectorLength() == B.getVectorLength());
14757
14758 unsigned NumBytes = A.getVectorLength();
14760 Result.reserve(NumBytes);
14761
14762 for (unsigned ByteIdx = 0; ByteIdx != NumBytes; ++ByteIdx) {
14763 uint8_t AByte = A.getVectorElt(ByteIdx).getInt().getZExtValue();
14764 uint8_t BByte = B.getVectorElt(ByteIdx).getInt().getZExtValue();
14765 Result.push_back(APValue(
14766 APSInt(APInt(8, GFNIMul(AByte, BByte)), /*IsUnsigned=*/false)));
14767 }
14768
14769 return Success(APValue(Result.data(), Result.size()), E);
14770 }
14771
14772 case X86::BI__builtin_ia32_insertf32x4_256:
14773 case X86::BI__builtin_ia32_inserti32x4_256:
14774 case X86::BI__builtin_ia32_insertf64x2_256:
14775 case X86::BI__builtin_ia32_inserti64x2_256:
14776 case X86::BI__builtin_ia32_insertf32x4:
14777 case X86::BI__builtin_ia32_inserti32x4:
14778 case X86::BI__builtin_ia32_insertf64x2_512:
14779 case X86::BI__builtin_ia32_inserti64x2_512:
14780 case X86::BI__builtin_ia32_insertf32x8:
14781 case X86::BI__builtin_ia32_inserti32x8:
14782 case X86::BI__builtin_ia32_insertf64x4:
14783 case X86::BI__builtin_ia32_inserti64x4:
14784 case X86::BI__builtin_ia32_vinsertf128_ps256:
14785 case X86::BI__builtin_ia32_vinsertf128_pd256:
14786 case X86::BI__builtin_ia32_vinsertf128_si256:
14787 case X86::BI__builtin_ia32_insert128i256: {
14788 APValue SourceDst, SourceSub;
14789 if (!EvaluateAsRValue(Info, E->getArg(0), SourceDst) ||
14790 !EvaluateAsRValue(Info, E->getArg(1), SourceSub))
14791 return false;
14792
14793 APSInt Imm;
14794 if (!EvaluateInteger(E->getArg(2), Imm, Info))
14795 return false;
14796
14797 assert(SourceDst.isVector() && SourceSub.isVector());
14798 unsigned DstLen = SourceDst.getVectorLength();
14799 unsigned SubLen = SourceSub.getVectorLength();
14800 assert(SubLen != 0 && DstLen != 0 && (DstLen % SubLen) == 0);
14801 unsigned NumLanes = DstLen / SubLen;
14802 unsigned LaneIdx = (Imm.getZExtValue() % NumLanes) * SubLen;
14803
14804 SmallVector<APValue, 16> ResultElements;
14805 ResultElements.reserve(DstLen);
14806
14807 for (unsigned EltNum = 0; EltNum < DstLen; ++EltNum) {
14808 if (EltNum >= LaneIdx && EltNum < LaneIdx + SubLen)
14809 ResultElements.push_back(SourceSub.getVectorElt(EltNum - LaneIdx));
14810 else
14811 ResultElements.push_back(SourceDst.getVectorElt(EltNum));
14812 }
14813
14814 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
14815 }
14816
14817 case clang::X86::BI__builtin_ia32_vec_set_v4hi:
14818 case clang::X86::BI__builtin_ia32_vec_set_v16qi:
14819 case clang::X86::BI__builtin_ia32_vec_set_v8hi:
14820 case clang::X86::BI__builtin_ia32_vec_set_v4si:
14821 case clang::X86::BI__builtin_ia32_vec_set_v2di:
14822 case clang::X86::BI__builtin_ia32_vec_set_v32qi:
14823 case clang::X86::BI__builtin_ia32_vec_set_v16hi:
14824 case clang::X86::BI__builtin_ia32_vec_set_v8si:
14825 case clang::X86::BI__builtin_ia32_vec_set_v4di: {
14826 APValue VecVal;
14827 APSInt Scalar, IndexAPS;
14828 if (!EvaluateVector(E->getArg(0), VecVal, Info) ||
14829 !EvaluateInteger(E->getArg(1), Scalar, Info) ||
14830 !EvaluateInteger(E->getArg(2), IndexAPS, Info))
14831 return false;
14832
14833 QualType ElemTy = E->getType()->castAs<VectorType>()->getElementType();
14834 unsigned ElemWidth = Info.Ctx.getIntWidth(ElemTy);
14835 bool ElemUnsigned = ElemTy->isUnsignedIntegerOrEnumerationType();
14836 Scalar.setIsUnsigned(ElemUnsigned);
14837 APSInt ElemAPS = Scalar.extOrTrunc(ElemWidth);
14838 APValue ElemAV(ElemAPS);
14839
14840 unsigned NumElems = VecVal.getVectorLength();
14841 unsigned Index =
14842 static_cast<unsigned>(IndexAPS.getZExtValue() & (NumElems - 1));
14843
14845 Elems.reserve(NumElems);
14846 for (unsigned ElemNum = 0; ElemNum != NumElems; ++ElemNum)
14847 Elems.push_back(ElemNum == Index ? ElemAV : VecVal.getVectorElt(ElemNum));
14848
14849 return Success(APValue(Elems.data(), NumElems), E);
14850 }
14851
14852 case X86::BI__builtin_ia32_pslldqi128_byteshift:
14853 case X86::BI__builtin_ia32_pslldqi256_byteshift:
14854 case X86::BI__builtin_ia32_pslldqi512_byteshift: {
14855 APValue R;
14856 if (!evalShuffleGeneric(
14857 Info, E, R,
14858 [](unsigned DstIdx, unsigned Shift) -> std::pair<unsigned, int> {
14859 unsigned LaneBase = (DstIdx / 16) * 16;
14860 unsigned LaneIdx = DstIdx % 16;
14861 if (LaneIdx < Shift)
14862 return std::make_pair(0, -1);
14863
14864 return std::make_pair(
14865 0, static_cast<int>(LaneBase + LaneIdx - Shift));
14866 }))
14867 return false;
14868 return Success(R, E);
14869 }
14870
14871 case X86::BI__builtin_ia32_psrldqi128_byteshift:
14872 case X86::BI__builtin_ia32_psrldqi256_byteshift:
14873 case X86::BI__builtin_ia32_psrldqi512_byteshift: {
14874 APValue R;
14875 if (!evalShuffleGeneric(
14876 Info, E, R,
14877 [](unsigned DstIdx, unsigned Shift) -> std::pair<unsigned, int> {
14878 unsigned LaneBase = (DstIdx / 16) * 16;
14879 unsigned LaneIdx = DstIdx % 16;
14880 if (LaneIdx + Shift < 16)
14881 return std::make_pair(
14882 0, static_cast<int>(LaneBase + LaneIdx + Shift));
14883
14884 return std::make_pair(0, -1);
14885 }))
14886 return false;
14887 return Success(R, E);
14888 }
14889
14890 case X86::BI__builtin_ia32_palignr128:
14891 case X86::BI__builtin_ia32_palignr256:
14892 case X86::BI__builtin_ia32_palignr512: {
14893 APValue R;
14894 if (!evalShuffleGeneric(Info, E, R, [](unsigned DstIdx, unsigned Shift) {
14895 // Default to -1 → zero-fill this destination element
14896 unsigned VecIdx = 1;
14897 int ElemIdx = -1;
14898
14899 int Lane = DstIdx / 16;
14900 int Offset = DstIdx % 16;
14901
14902 // Elements come from VecB first, then VecA after the shift boundary
14903 unsigned ShiftedIdx = Offset + (Shift & 0xFF);
14904 if (ShiftedIdx < 16) { // from VecB
14905 ElemIdx = ShiftedIdx + (Lane * 16);
14906 } else if (ShiftedIdx < 32) { // from VecA
14907 VecIdx = 0;
14908 ElemIdx = (ShiftedIdx - 16) + (Lane * 16);
14909 }
14910
14911 return std::pair<unsigned, int>{VecIdx, ElemIdx};
14912 }))
14913 return false;
14914 return Success(R, E);
14915 }
14916 case X86::BI__builtin_ia32_alignd128:
14917 case X86::BI__builtin_ia32_alignd256:
14918 case X86::BI__builtin_ia32_alignd512:
14919 case X86::BI__builtin_ia32_alignq128:
14920 case X86::BI__builtin_ia32_alignq256:
14921 case X86::BI__builtin_ia32_alignq512: {
14922 APValue R;
14923 unsigned NumElems = E->getType()->castAs<VectorType>()->getNumElements();
14924 if (!evalShuffleGeneric(Info, E, R,
14925 [NumElems](unsigned DstIdx, unsigned Shift) {
14926 unsigned Imm = Shift & 0xFF;
14927 unsigned EffectiveShift = Imm & (NumElems - 1);
14928 unsigned SourcePos = DstIdx + EffectiveShift;
14929 unsigned VecIdx = SourcePos < NumElems ? 1 : 0;
14930 unsigned ElemIdx = SourcePos & (NumElems - 1);
14931
14932 return std::pair<unsigned, int>{
14933 VecIdx, static_cast<int>(ElemIdx)};
14934 }))
14935 return false;
14936 return Success(R, E);
14937 }
14938 case X86::BI__builtin_ia32_permvarsi256:
14939 case X86::BI__builtin_ia32_permvarsf256:
14940 case X86::BI__builtin_ia32_permvardf512:
14941 case X86::BI__builtin_ia32_permvardi512:
14942 case X86::BI__builtin_ia32_permvarhi128: {
14943 APValue R;
14944 if (!evalShuffleGeneric(Info, E, R,
14945 [](unsigned DstIdx, unsigned ShuffleMask) {
14946 int Offset = ShuffleMask & 0x7;
14947 return std::pair<unsigned, int>{0, Offset};
14948 }))
14949 return false;
14950 return Success(R, E);
14951 }
14952 case X86::BI__builtin_ia32_permvarqi128:
14953 case X86::BI__builtin_ia32_permvarhi256:
14954 case X86::BI__builtin_ia32_permvarsi512:
14955 case X86::BI__builtin_ia32_permvarsf512: {
14956 APValue R;
14957 if (!evalShuffleGeneric(Info, E, R,
14958 [](unsigned DstIdx, unsigned ShuffleMask) {
14959 int Offset = ShuffleMask & 0xF;
14960 return std::pair<unsigned, int>{0, Offset};
14961 }))
14962 return false;
14963 return Success(R, E);
14964 }
14965 case X86::BI__builtin_ia32_permvardi256:
14966 case X86::BI__builtin_ia32_permvardf256: {
14967 APValue R;
14968 if (!evalShuffleGeneric(Info, E, R,
14969 [](unsigned DstIdx, unsigned ShuffleMask) {
14970 int Offset = ShuffleMask & 0x3;
14971 return std::pair<unsigned, int>{0, Offset};
14972 }))
14973 return false;
14974 return Success(R, E);
14975 }
14976 case X86::BI__builtin_ia32_permvarqi256:
14977 case X86::BI__builtin_ia32_permvarhi512: {
14978 APValue R;
14979 if (!evalShuffleGeneric(Info, E, R,
14980 [](unsigned DstIdx, unsigned ShuffleMask) {
14981 int Offset = ShuffleMask & 0x1F;
14982 return std::pair<unsigned, int>{0, Offset};
14983 }))
14984 return false;
14985 return Success(R, E);
14986 }
14987 case X86::BI__builtin_ia32_permvarqi512: {
14988 APValue R;
14989 if (!evalShuffleGeneric(Info, E, R,
14990 [](unsigned DstIdx, unsigned ShuffleMask) {
14991 int Offset = ShuffleMask & 0x3F;
14992 return std::pair<unsigned, int>{0, Offset};
14993 }))
14994 return false;
14995 return Success(R, E);
14996 }
14997 case X86::BI__builtin_ia32_vpermi2varq128:
14998 case X86::BI__builtin_ia32_vpermi2varpd128: {
14999 APValue R;
15000 if (!evalShuffleGeneric(Info, E, R,
15001 [](unsigned DstIdx, unsigned ShuffleMask) {
15002 int Offset = ShuffleMask & 0x1;
15003 unsigned SrcIdx = (ShuffleMask >> 1) & 0x1;
15004 return std::pair<unsigned, int>{SrcIdx, Offset};
15005 }))
15006 return false;
15007 return Success(R, E);
15008 }
15009 case X86::BI__builtin_ia32_vpermi2vard128:
15010 case X86::BI__builtin_ia32_vpermi2varps128:
15011 case X86::BI__builtin_ia32_vpermi2varq256:
15012 case X86::BI__builtin_ia32_vpermi2varpd256: {
15013 APValue R;
15014 if (!evalShuffleGeneric(Info, E, R,
15015 [](unsigned DstIdx, unsigned ShuffleMask) {
15016 int Offset = ShuffleMask & 0x3;
15017 unsigned SrcIdx = (ShuffleMask >> 2) & 0x1;
15018 return std::pair<unsigned, int>{SrcIdx, Offset};
15019 }))
15020 return false;
15021 return Success(R, E);
15022 }
15023 case X86::BI__builtin_ia32_vpermi2varhi128:
15024 case X86::BI__builtin_ia32_vpermi2vard256:
15025 case X86::BI__builtin_ia32_vpermi2varps256:
15026 case X86::BI__builtin_ia32_vpermi2varq512:
15027 case X86::BI__builtin_ia32_vpermi2varpd512: {
15028 APValue R;
15029 if (!evalShuffleGeneric(Info, E, R,
15030 [](unsigned DstIdx, unsigned ShuffleMask) {
15031 int Offset = ShuffleMask & 0x7;
15032 unsigned SrcIdx = (ShuffleMask >> 3) & 0x1;
15033 return std::pair<unsigned, int>{SrcIdx, Offset};
15034 }))
15035 return false;
15036 return Success(R, E);
15037 }
15038 case X86::BI__builtin_ia32_vpermi2varqi128:
15039 case X86::BI__builtin_ia32_vpermi2varhi256:
15040 case X86::BI__builtin_ia32_vpermi2vard512:
15041 case X86::BI__builtin_ia32_vpermi2varps512: {
15042 APValue R;
15043 if (!evalShuffleGeneric(Info, E, R,
15044 [](unsigned DstIdx, unsigned ShuffleMask) {
15045 int Offset = ShuffleMask & 0xF;
15046 unsigned SrcIdx = (ShuffleMask >> 4) & 0x1;
15047 return std::pair<unsigned, int>{SrcIdx, Offset};
15048 }))
15049 return false;
15050 return Success(R, E);
15051 }
15052 case X86::BI__builtin_ia32_vpermi2varqi256:
15053 case X86::BI__builtin_ia32_vpermi2varhi512: {
15054 APValue R;
15055 if (!evalShuffleGeneric(Info, E, R,
15056 [](unsigned DstIdx, unsigned ShuffleMask) {
15057 int Offset = ShuffleMask & 0x1F;
15058 unsigned SrcIdx = (ShuffleMask >> 5) & 0x1;
15059 return std::pair<unsigned, int>{SrcIdx, Offset};
15060 }))
15061 return false;
15062 return Success(R, E);
15063 }
15064 case X86::BI__builtin_ia32_vpermi2varqi512: {
15065 APValue R;
15066 if (!evalShuffleGeneric(Info, E, R,
15067 [](unsigned DstIdx, unsigned ShuffleMask) {
15068 int Offset = ShuffleMask & 0x3F;
15069 unsigned SrcIdx = (ShuffleMask >> 6) & 0x1;
15070 return std::pair<unsigned, int>{SrcIdx, Offset};
15071 }))
15072 return false;
15073 return Success(R, E);
15074 }
15075
15076 case clang::X86::BI__builtin_ia32_minps:
15077 case clang::X86::BI__builtin_ia32_minpd:
15078 case clang::X86::BI__builtin_ia32_minps256:
15079 case clang::X86::BI__builtin_ia32_minpd256:
15080 case clang::X86::BI__builtin_ia32_minps512:
15081 case clang::X86::BI__builtin_ia32_minpd512:
15082 case clang::X86::BI__builtin_ia32_minph128:
15083 case clang::X86::BI__builtin_ia32_minph256:
15084 case clang::X86::BI__builtin_ia32_minph512:
15085 return EvaluateFpBinOpExpr(
15086 [](const APFloat &A, const APFloat &B,
15087 std::optional<APSInt>) -> std::optional<APFloat> {
15088 if (A.isNaN() || A.isInfinity() || A.isDenormal() || B.isNaN() ||
15089 B.isInfinity() || B.isDenormal())
15090 return std::nullopt;
15091 if (A.isZero() && B.isZero())
15092 return B;
15093 return llvm::minimum(A, B);
15094 });
15095
15096 case clang::X86::BI__builtin_ia32_minss:
15097 case clang::X86::BI__builtin_ia32_minsd:
15098 return EvaluateFpBinOpExpr(
15099 [](const APFloat &A, const APFloat &B,
15100 std::optional<APSInt> RoundingMode) -> std::optional<APFloat> {
15101 return EvalScalarMinMaxFp(A, B, RoundingMode, /*IsMin=*/true);
15102 },
15103 /*IsScalar=*/true);
15104
15105 case clang::X86::BI__builtin_ia32_minsd_round_mask:
15106 case clang::X86::BI__builtin_ia32_minss_round_mask:
15107 case clang::X86::BI__builtin_ia32_minsh_round_mask:
15108 case clang::X86::BI__builtin_ia32_maxsd_round_mask:
15109 case clang::X86::BI__builtin_ia32_maxss_round_mask:
15110 case clang::X86::BI__builtin_ia32_maxsh_round_mask: {
15111 bool IsMin = BuiltinOp == clang::X86::BI__builtin_ia32_minsd_round_mask ||
15112 BuiltinOp == clang::X86::BI__builtin_ia32_minss_round_mask ||
15113 BuiltinOp == clang::X86::BI__builtin_ia32_minsh_round_mask;
15114 return EvaluateScalarFpRoundMaskBinOp(
15115 [IsMin](const APFloat &A, const APFloat &B,
15116 std::optional<APSInt> RoundingMode) -> std::optional<APFloat> {
15117 return EvalScalarMinMaxFp(A, B, RoundingMode, IsMin);
15118 });
15119 }
15120
15121 case clang::X86::BI__builtin_ia32_maxps:
15122 case clang::X86::BI__builtin_ia32_maxpd:
15123 case clang::X86::BI__builtin_ia32_maxps256:
15124 case clang::X86::BI__builtin_ia32_maxpd256:
15125 case clang::X86::BI__builtin_ia32_maxps512:
15126 case clang::X86::BI__builtin_ia32_maxpd512:
15127 case clang::X86::BI__builtin_ia32_maxph128:
15128 case clang::X86::BI__builtin_ia32_maxph256:
15129 case clang::X86::BI__builtin_ia32_maxph512:
15130 return EvaluateFpBinOpExpr(
15131 [](const APFloat &A, const APFloat &B,
15132 std::optional<APSInt>) -> std::optional<APFloat> {
15133 if (A.isNaN() || A.isInfinity() || A.isDenormal() || B.isNaN() ||
15134 B.isInfinity() || B.isDenormal())
15135 return std::nullopt;
15136 if (A.isZero() && B.isZero())
15137 return B;
15138 return llvm::maximum(A, B);
15139 });
15140
15141 case clang::X86::BI__builtin_ia32_maxss:
15142 case clang::X86::BI__builtin_ia32_maxsd:
15143 return EvaluateFpBinOpExpr(
15144 [](const APFloat &A, const APFloat &B,
15145 std::optional<APSInt> RoundingMode) -> std::optional<APFloat> {
15146 return EvalScalarMinMaxFp(A, B, RoundingMode, /*IsMin=*/false);
15147 },
15148 /*IsScalar=*/true);
15149
15150 case clang::X86::BI__builtin_ia32_vcvtps2ph:
15151 case clang::X86::BI__builtin_ia32_vcvtps2ph256: {
15152 APValue SrcVec;
15153 if (!EvaluateAsRValue(Info, E->getArg(0), SrcVec))
15154 return false;
15155
15156 APSInt Imm;
15157 if (!EvaluateInteger(E->getArg(1), Imm, Info))
15158 return false;
15159
15160 const auto *SrcVTy = E->getArg(0)->getType()->castAs<VectorType>();
15161 unsigned SrcNumElems = SrcVTy->getNumElements();
15162 const auto *DstVTy = E->getType()->castAs<VectorType>();
15163 unsigned DstNumElems = DstVTy->getNumElements();
15164 QualType DstElemTy = DstVTy->getElementType();
15165
15166 const llvm::fltSemantics &HalfSem =
15167 Info.Ctx.getFloatTypeSemantics(Info.Ctx.HalfTy);
15168
15169 int ImmVal = Imm.getZExtValue();
15170 bool UseMXCSR = (ImmVal & 4) != 0;
15171 bool IsFPConstrained =
15172 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained();
15173
15174 llvm::RoundingMode RM;
15175 if (!UseMXCSR) {
15176 switch (ImmVal & 3) {
15177 case 0:
15178 RM = llvm::RoundingMode::NearestTiesToEven;
15179 break;
15180 case 1:
15181 RM = llvm::RoundingMode::TowardNegative;
15182 break;
15183 case 2:
15184 RM = llvm::RoundingMode::TowardPositive;
15185 break;
15186 case 3:
15187 RM = llvm::RoundingMode::TowardZero;
15188 break;
15189 default:
15190 llvm_unreachable("Invalid immediate rounding mode");
15191 }
15192 } else {
15193 RM = llvm::RoundingMode::NearestTiesToEven;
15194 }
15195
15196 SmallVector<APValue, 8> ResultElements;
15197 ResultElements.reserve(DstNumElems);
15198
15199 for (unsigned I = 0; I < SrcNumElems; ++I) {
15200 APFloat SrcVal = SrcVec.getVectorElt(I).getFloat();
15201
15202 bool LostInfo;
15203 APFloat::opStatus St = SrcVal.convert(HalfSem, RM, &LostInfo);
15204
15205 if (UseMXCSR && IsFPConstrained && St != APFloat::opOK) {
15206 Info.FFDiag(E, diag::note_constexpr_dynamic_rounding);
15207 return false;
15208 }
15209
15210 APSInt DstInt(SrcVal.bitcastToAPInt(),
15212 ResultElements.push_back(APValue(DstInt));
15213 }
15214
15215 if (DstNumElems > SrcNumElems) {
15216 APSInt Zero = Info.Ctx.MakeIntValue(0, DstElemTy);
15217 for (unsigned I = SrcNumElems; I < DstNumElems; ++I) {
15218 ResultElements.push_back(APValue(Zero));
15219 }
15220 }
15221
15222 return Success(ResultElements, E);
15223 }
15224 case X86::BI__builtin_ia32_vperm2f128_pd256:
15225 case X86::BI__builtin_ia32_vperm2f128_ps256:
15226 case X86::BI__builtin_ia32_vperm2f128_si256:
15227 case X86::BI__builtin_ia32_permti256: {
15228 unsigned NumElements =
15229 E->getArg(0)->getType()->getAs<VectorType>()->getNumElements();
15230 unsigned PreservedBitsCnt = NumElements >> 2;
15231 APValue R;
15232 if (!evalShuffleGeneric(
15233 Info, E, R,
15234 [PreservedBitsCnt](unsigned DstIdx, unsigned ShuffleMask) {
15235 unsigned ControlBitsCnt = DstIdx >> PreservedBitsCnt << 2;
15236 unsigned ControlBits = ShuffleMask >> ControlBitsCnt;
15237
15238 if (ControlBits & 0b1000)
15239 return std::make_pair(0u, -1);
15240
15241 unsigned SrcVecIdx = (ControlBits & 0b10) >> 1;
15242 unsigned PreservedBitsMask = (1 << PreservedBitsCnt) - 1;
15243 int SrcIdx = ((ControlBits & 0b1) << PreservedBitsCnt) |
15244 (DstIdx & PreservedBitsMask);
15245 return std::make_pair(SrcVecIdx, SrcIdx);
15246 }))
15247 return false;
15248 return Success(R, E);
15249 }
15250 case X86::BI__builtin_ia32_vpdpwssd128:
15251 case X86::BI__builtin_ia32_vpdpwssd256:
15252 case X86::BI__builtin_ia32_vpdpwssd512:
15253 case X86::BI__builtin_ia32_vpdpbusd128:
15254 case X86::BI__builtin_ia32_vpdpbusd256:
15255 case X86::BI__builtin_ia32_vpdpbusd512:
15256 return EvalVectorDotProduct(false);
15257 case X86::BI__builtin_ia32_vpdpwssds128:
15258 case X86::BI__builtin_ia32_vpdpwssds256:
15259 case X86::BI__builtin_ia32_vpdpwssds512:
15260 case X86::BI__builtin_ia32_vpdpbusds128:
15261 case X86::BI__builtin_ia32_vpdpbusds256:
15262 case X86::BI__builtin_ia32_vpdpbusds512:
15263 return EvalVectorDotProduct(true);
15264 case X86::BI__builtin_ia32_cvtpd2dq:
15265 case X86::BI__builtin_ia32_cvtps2dq:
15266 case X86::BI__builtin_ia32_cvttpd2dq:
15267 case X86::BI__builtin_ia32_cvttps2dq:
15268 case X86::BI__builtin_ia32_cvtpd2dq256:
15269 case X86::BI__builtin_ia32_cvtps2dq256:
15270 case X86::BI__builtin_ia32_cvttpd2dq256:
15271 case X86::BI__builtin_ia32_cvttps2dq256: {
15272 APValue SrcVec;
15273 if (!EvaluateAsRValue(Info, E->getArg(0), SrcVec) || !SrcVec.isVector())
15274 return false;
15275
15276 const auto *VT = E->getType()->castAs<VectorType>();
15277 QualType EltTy = VT->getElementType();
15278 bool isUnsigned = EltTy->isUnsignedIntegerType();
15279 unsigned BitWidth = Info.Ctx.getIntWidth(EltTy);
15280
15281 unsigned NumSrcElems = SrcVec.getVectorLength();
15282 unsigned NumDstElems = VT->getNumElements();
15283
15284 SmallVector<APValue, 8> ResultElts;
15285 for (unsigned i = 0; i != NumDstElems; ++i) {
15286 if (i < NumSrcElems) {
15287 llvm::APFloat FloatElem = SrcVec.getVectorElt(i).getFloat();
15288 llvm::APSInt IntResult(BitWidth, isUnsigned);
15289 bool IsExact = false;
15290 // We only allow exact conversions so rounding mode does not matter for
15291 // cvt* and cvtt* builtins
15292 FloatElem.convertToInteger(IntResult, llvm::APFloat::rmTowardZero,
15293 &IsExact);
15294 if (!IsExact)
15295 return false;
15296 ResultElts.push_back(APValue(IntResult));
15297 } else
15298 // Pad remaining lanes with zero
15299 ResultElts.push_back(APValue(llvm::APSInt(BitWidth, isUnsigned)));
15300 }
15301 return Success(ResultElts, E);
15302 }
15303 }
15304}
15305
15306bool VectorExprEvaluator::VisitConvertVectorExpr(const ConvertVectorExpr *E) {
15307 APValue Source;
15308 QualType SourceVecType = E->getSrcExpr()->getType();
15309 if (!EvaluateAsRValue(Info, E->getSrcExpr(), Source))
15310 return false;
15311
15312 QualType DestTy = E->getType()->castAs<VectorType>()->getElementType();
15313 QualType SourceTy = SourceVecType->castAs<VectorType>()->getElementType();
15314
15315 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
15316
15317 auto SourceLen = Source.getVectorLength();
15318 SmallVector<APValue, 4> ResultElements;
15319 ResultElements.reserve(SourceLen);
15320 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
15321 APValue Elt;
15322 if (!handleVectorElementCast(Info, FPO, E, SourceTy, DestTy,
15323 Source.getVectorElt(EltNum), Elt))
15324 return false;
15325 ResultElements.push_back(std::move(Elt));
15326 }
15327
15328 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
15329}
15330
15331static bool handleVectorShuffle(EvalInfo &Info, const ShuffleVectorExpr *E,
15332 QualType ElemType, APValue const &VecVal1,
15333 APValue const &VecVal2, unsigned EltNum,
15334 APValue &Result) {
15335 unsigned const TotalElementsInInputVector1 = VecVal1.getVectorLength();
15336 unsigned const TotalElementsInInputVector2 = VecVal2.getVectorLength();
15337
15338 APSInt IndexVal = E->getShuffleMaskIdx(EltNum);
15339 int64_t index = IndexVal.getExtValue();
15340 // The spec says that -1 should be treated as undef for optimizations,
15341 // but in constexpr we'd have to produce an APValue::Indeterminate,
15342 // which is prohibited from being a top-level constant value. Emit a
15343 // diagnostic instead.
15344 if (index == -1) {
15345 Info.FFDiag(
15346 E, diag::err_shufflevector_minus_one_is_undefined_behavior_constexpr)
15347 << EltNum;
15348 return false;
15349 }
15350
15351 if (index < 0 ||
15352 index >= TotalElementsInInputVector1 + TotalElementsInInputVector2)
15353 llvm_unreachable("Out of bounds shuffle index");
15354
15355 if (index >= TotalElementsInInputVector1)
15356 Result = VecVal2.getVectorElt(index - TotalElementsInInputVector1);
15357 else
15358 Result = VecVal1.getVectorElt(index);
15359 return true;
15360}
15361
15362bool VectorExprEvaluator::VisitShuffleVectorExpr(const ShuffleVectorExpr *E) {
15363 // FIXME: Unary shuffle with mask not currently supported.
15364 if (E->getNumSubExprs() == 2)
15365 return Error(E);
15366 APValue VecVal1;
15367 const Expr *Vec1 = E->getExpr(0);
15368 if (!EvaluateAsRValue(Info, Vec1, VecVal1))
15369 return false;
15370 APValue VecVal2;
15371 const Expr *Vec2 = E->getExpr(1);
15372 if (!EvaluateAsRValue(Info, Vec2, VecVal2))
15373 return false;
15374
15375 VectorType const *DestVecTy = E->getType()->castAs<VectorType>();
15376 QualType DestElTy = DestVecTy->getElementType();
15377
15378 auto TotalElementsInOutputVector = DestVecTy->getNumElements();
15379
15380 SmallVector<APValue, 4> ResultElements;
15381 ResultElements.reserve(TotalElementsInOutputVector);
15382 for (unsigned EltNum = 0; EltNum < TotalElementsInOutputVector; ++EltNum) {
15383 APValue Elt;
15384 if (!handleVectorShuffle(Info, E, DestElTy, VecVal1, VecVal2, EltNum, Elt))
15385 return false;
15386 ResultElements.push_back(std::move(Elt));
15387 }
15388
15389 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
15390}
15391
15392//===----------------------------------------------------------------------===//
15393// Matrix Evaluation
15394//===----------------------------------------------------------------------===//
15395
15396namespace {
15397class MatrixExprEvaluator : public ExprEvaluatorBase<MatrixExprEvaluator> {
15398 APValue &Result;
15399
15400public:
15401 MatrixExprEvaluator(EvalInfo &Info, APValue &Result)
15402 : ExprEvaluatorBaseTy(Info), Result(Result) {}
15403
15404 bool Success(ArrayRef<APValue> M, const Expr *E) {
15405 auto *CMTy = E->getType()->castAs<ConstantMatrixType>();
15406 assert(M.size() == CMTy->getNumElementsFlattened());
15407 // FIXME: remove this APValue copy.
15408 Result = APValue(M.data(), CMTy->getNumRows(), CMTy->getNumColumns());
15409 return true;
15410 }
15411 bool Success(const APValue &M, const Expr *E) {
15412 assert(M.isMatrix() && "expected matrix");
15413 Result = M;
15414 return true;
15415 }
15416
15417 bool VisitCastExpr(const CastExpr *E);
15418 bool VisitInitListExpr(const InitListExpr *E);
15419};
15420} // end anonymous namespace
15421
15422static bool EvaluateMatrix(const Expr *E, APValue &Result, EvalInfo &Info) {
15423 assert(E->isPRValue() && E->getType()->isConstantMatrixType() &&
15424 "not a matrix prvalue");
15425 return MatrixExprEvaluator(Info, Result).Visit(E);
15426}
15427
15428bool MatrixExprEvaluator::VisitCastExpr(const CastExpr *E) {
15429 const auto *MT = E->getType()->castAs<ConstantMatrixType>();
15430 unsigned NumRows = MT->getNumRows();
15431 unsigned NumCols = MT->getNumColumns();
15432 unsigned NElts = NumRows * NumCols;
15433 QualType EltTy = MT->getElementType();
15434 const Expr *SE = E->getSubExpr();
15435
15436 switch (E->getCastKind()) {
15437 case CK_HLSLAggregateSplatCast: {
15438 APValue Val;
15439 QualType ValTy;
15440
15441 if (!hlslAggSplatHelper(Info, SE, Val, ValTy))
15442 return false;
15443
15444 APValue CastedVal;
15445 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
15446 if (!handleScalarCast(Info, FPO, E, ValTy, EltTy, Val, CastedVal))
15447 return false;
15448
15449 SmallVector<APValue, 16> SplatEls(NElts, CastedVal);
15450 return Success(SplatEls, E);
15451 }
15452 case CK_HLSLElementwiseCast: {
15453 SmallVector<APValue> SrcVals;
15454 SmallVector<QualType> SrcTypes;
15455
15456 if (!hlslElementwiseCastHelper(Info, SE, E->getType(), SrcVals, SrcTypes))
15457 return false;
15458
15459 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
15460 SmallVector<QualType, 16> DestTypes(NElts, EltTy);
15461 SmallVector<APValue, 16> ResultEls(NElts);
15462 if (!handleElementwiseCast(Info, E, FPO, SrcVals, SrcTypes, DestTypes,
15463 ResultEls))
15464 return false;
15465 return Success(ResultEls, E);
15466 }
15467 default:
15468 return ExprEvaluatorBaseTy::VisitCastExpr(E);
15469 }
15470}
15471
15472bool MatrixExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
15473 const auto *MT = E->getType()->castAs<ConstantMatrixType>();
15474 QualType EltTy = MT->getElementType();
15475
15476 assert(E->getNumInits() == MT->getNumElementsFlattened() &&
15477 "Expected number of elements in initializer list to match the number "
15478 "of matrix elements");
15479
15480 SmallVector<APValue, 16> Elements;
15481 Elements.reserve(MT->getNumElementsFlattened());
15482
15483 // The following loop assumes the elements of the matrix InitListExpr are in
15484 // row-major order, which matches the row-major ordering assumption of the
15485 // matrix APValue.
15486 for (unsigned I = 0, N = MT->getNumElementsFlattened(); I < N; ++I) {
15487 if (EltTy->isIntegerType()) {
15488 llvm::APSInt IntVal;
15489 if (!EvaluateInteger(E->getInit(I), IntVal, Info))
15490 return false;
15491 Elements.push_back(APValue(IntVal));
15492 } else {
15493 llvm::APFloat FloatVal(0.0);
15494 if (!EvaluateFloat(E->getInit(I), FloatVal, Info))
15495 return false;
15496 Elements.push_back(APValue(FloatVal));
15497 }
15498 }
15499
15500 return Success(Elements, E);
15501}
15502
15503//===----------------------------------------------------------------------===//
15504// Array Evaluation
15505//===----------------------------------------------------------------------===//
15506
15507namespace {
15508 class ArrayExprEvaluator
15509 : public ExprEvaluatorBase<ArrayExprEvaluator> {
15510 const LValue &This;
15511 APValue &Result;
15512 public:
15513
15514 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
15515 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
15516
15517 bool Success(const APValue &V, const Expr *E) {
15518 assert(V.isArray() && "expected array");
15519 Result = V;
15520 return true;
15521 }
15522
15523 bool ZeroInitialization(const Expr *E) {
15524 const ConstantArrayType *CAT =
15525 Info.Ctx.getAsConstantArrayType(E->getType());
15526 if (!CAT) {
15527 if (E->getType()->isIncompleteArrayType()) {
15528 // We can be asked to zero-initialize a flexible array member; this
15529 // is represented as an ImplicitValueInitExpr of incomplete array
15530 // type. In this case, the array has zero elements.
15531 Result = APValue(APValue::UninitArray(), 0, 0);
15532 return true;
15533 }
15534 // FIXME: We could handle VLAs here.
15535 return Error(E);
15536 }
15537
15538 Result = APValue(APValue::UninitArray(), 0, CAT->getZExtSize());
15539 if (!Result.hasArrayFiller())
15540 return true;
15541
15542 // Zero-initialize all elements.
15543 LValue Subobject = This;
15544 Subobject.addArray(Info, E, CAT);
15545 ImplicitValueInitExpr VIE(CAT->getElementType());
15546 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
15547 }
15548
15549 bool VisitCallExpr(const CallExpr *E) {
15550 return handleCallExpr(E, Result, &This);
15551 }
15552 bool VisitCastExpr(const CastExpr *E);
15553 bool VisitInitListExpr(const InitListExpr *E,
15554 QualType AllocType = QualType());
15555 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
15556 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
15557 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
15558 const LValue &Subobject,
15559 APValue *Value, QualType Type);
15560 bool VisitStringLiteral(const StringLiteral *E,
15561 QualType AllocType = QualType()) {
15562 expandStringLiteral(Info, E, Result, AllocType);
15563 return true;
15564 }
15565 bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E);
15566 bool VisitCXXParenListOrInitListExpr(const Expr *ExprToVisit,
15567 ArrayRef<Expr *> Args,
15568 const Expr *ArrayFiller,
15569 QualType AllocType = QualType());
15570 bool VisitDesignatedInitUpdateExpr(const DesignatedInitUpdateExpr *E);
15571 };
15572} // end anonymous namespace
15573
15574static bool EvaluateArray(const Expr *E, const LValue &This,
15575 APValue &Result, EvalInfo &Info) {
15576 assert(!E->isValueDependent());
15577 assert(E->isPRValue() && E->getType()->isArrayType() &&
15578 "not an array prvalue");
15579 return ArrayExprEvaluator(Info, This, Result).Visit(E);
15580}
15581
15582static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
15583 APValue &Result, const InitListExpr *ILE,
15584 QualType AllocType) {
15585 assert(!ILE->isValueDependent());
15586 assert(ILE->isPRValue() && ILE->getType()->isArrayType() &&
15587 "not an array prvalue");
15588 return ArrayExprEvaluator(Info, This, Result)
15589 .VisitInitListExpr(ILE, AllocType);
15590}
15591
15592static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
15593 APValue &Result,
15594 const CXXConstructExpr *CCE,
15595 QualType AllocType) {
15596 assert(!CCE->isValueDependent());
15597 assert(CCE->isPRValue() && CCE->getType()->isArrayType() &&
15598 "not an array prvalue");
15599 return ArrayExprEvaluator(Info, This, Result)
15600 .VisitCXXConstructExpr(CCE, This, &Result, AllocType);
15601}
15602
15603// Return true iff the given array filler may depend on the element index.
15604static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
15605 // For now, just allow non-class value-initialization and initialization
15606 // lists comprised of them.
15607 if (isa<ImplicitValueInitExpr>(FillerExpr))
15608 return false;
15609 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
15610 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
15611 if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
15612 return true;
15613 }
15614
15615 if (ILE->hasArrayFiller() &&
15616 MaybeElementDependentArrayFiller(ILE->getArrayFiller()))
15617 return true;
15618
15619 return false;
15620 }
15621 return true;
15622}
15623
15624bool ArrayExprEvaluator::VisitCastExpr(const CastExpr *E) {
15625 const Expr *SE = E->getSubExpr();
15626
15627 switch (E->getCastKind()) {
15628 default:
15629 return ExprEvaluatorBaseTy::VisitCastExpr(E);
15630 case CK_HLSLAggregateSplatCast: {
15631 APValue Val;
15632 QualType ValTy;
15633
15634 if (!hlslAggSplatHelper(Info, SE, Val, ValTy))
15635 return false;
15636
15637 unsigned NEls = elementwiseSize(Info, E->getType());
15638
15639 SmallVector<APValue> SplatEls(NEls, Val);
15640 SmallVector<QualType> SplatType(NEls, ValTy);
15641
15642 // cast the elements
15643 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
15644 if (!constructAggregate(Info, FPO, E, Result, E->getType(), SplatEls,
15645 SplatType))
15646 return false;
15647
15648 return true;
15649 }
15650 case CK_HLSLElementwiseCast: {
15651 SmallVector<APValue> SrcEls;
15652 SmallVector<QualType> SrcTypes;
15653
15654 if (!hlslElementwiseCastHelper(Info, SE, E->getType(), SrcEls, SrcTypes))
15655 return false;
15656
15657 // cast the elements
15658 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
15659 if (!constructAggregate(Info, FPO, E, Result, E->getType(), SrcEls,
15660 SrcTypes))
15661 return false;
15662 return true;
15663 }
15664 }
15665}
15666
15667bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E,
15668 QualType AllocType) {
15669 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
15670 AllocType.isNull() ? E->getType() : AllocType);
15671 if (!CAT)
15672 return Error(E);
15673
15674 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
15675 // an appropriately-typed string literal enclosed in braces.
15676 if (E->isStringLiteralInit()) {
15677 auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParenImpCasts());
15678 // FIXME: Support ObjCEncodeExpr here once we support it in
15679 // ArrayExprEvaluator generally.
15680 if (!SL)
15681 return Error(E);
15682 return VisitStringLiteral(SL, AllocType);
15683 }
15684 // Any other transparent list init will need proper handling of the
15685 // AllocType; we can't just recurse to the inner initializer.
15686 assert(!E->isTransparent() &&
15687 "transparent array list initialization is not string literal init?");
15688
15689 return VisitCXXParenListOrInitListExpr(E, E->inits(), E->getArrayFiller(),
15690 AllocType);
15691}
15692
15693bool ArrayExprEvaluator::VisitCXXParenListOrInitListExpr(
15694 const Expr *ExprToVisit, ArrayRef<Expr *> Args, const Expr *ArrayFiller,
15695 QualType AllocType) {
15696 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
15697 AllocType.isNull() ? ExprToVisit->getType() : AllocType);
15698
15699 bool Success = true;
15700
15701 unsigned NumEltsToInit = Args.size();
15702 unsigned NumElts = CAT->getZExtSize();
15703
15704 // If the initializer might depend on the array index, run it for each
15705 // array element.
15706 if (NumEltsToInit != NumElts &&
15707 MaybeElementDependentArrayFiller(ArrayFiller)) {
15708 NumEltsToInit = NumElts;
15709 } else {
15710 // Add additional elements represented by EmbedExpr.
15711 for (auto *Init : Args) {
15712 if (auto *EmbedS = dyn_cast<EmbedExpr>(Init->IgnoreParenImpCasts()))
15713 NumEltsToInit += EmbedS->getDataElementCount() - 1;
15714 }
15715 // If we have extra elements in the list, they will be discarded.
15716 if (NumEltsToInit > NumElts)
15717 NumEltsToInit = NumElts;
15718 // If we're overwriting memory which already has an object, make sure we
15719 // don't reduce the number of non-filler elements. (It's possible to
15720 // optimize this in some cases, but the logic gets really complicated.)
15721 if (Result.hasValue() && NumEltsToInit < Result.getArrayInitializedElts())
15722 NumEltsToInit = Result.getArrayInitializedElts();
15723 }
15724
15725 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
15726 << NumEltsToInit << ".\n");
15727
15728 if (!Result.hasValue()) {
15729 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
15730 } else if (Result.getArrayInitializedElts() != NumEltsToInit) {
15731 // Number of inititalized elts changed. Recreate the APValue, and copy over
15732 // the relevant elements. (This is essentially just fixing the internal
15733 // representation of the value, because it's tied to the number of
15734 // non-filler elements.)
15735 //
15736 // This should be hit rarely, but there are some edge cases:
15737 //
15738 // - The array could be zero-initialized.
15739 // - There could be a DesignatedInitListExpr.
15740 // - operator new[] can be used to start the lifetime early.
15741 APValue NewResult = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
15742 // First copy existing elements.
15743 unsigned NumOldElts = Result.getArrayInitializedElts();
15744 for (unsigned I = 0; I < NumOldElts; ++I) {
15745 NewResult.getArrayInitializedElt(I) =
15746 std::move(Result.getArrayInitializedElt(I));
15747 }
15748 // Then copy the array filler over the remaining elements.
15749 for (unsigned I = Result.getArrayInitializedElts(); I < NumEltsToInit; ++I)
15751 if (NewResult.hasArrayFiller() && Result.hasArrayFiller())
15752 NewResult.getArrayFiller() = Result.getArrayFiller();
15753 Result = std::move(NewResult);
15754 }
15755
15756 LValue Subobject = This;
15757 Subobject.addArray(Info, ExprToVisit, CAT);
15758 auto Eval = [&](const Expr *Init, unsigned ArrayIndex) {
15759 if (Init->isValueDependent())
15760 return EvaluateDependentExpr(Init, Info);
15761
15762 // If this is a child of a DesignatedInitUpdateExpr, skip elements which
15763 // aren't supposed to be modified.
15764 if (isa<NoInitExpr>(Init))
15765 return true;
15766
15767 if (!EvaluateInPlace(Result.getArrayInitializedElt(ArrayIndex), Info,
15768 Subobject, Init) ||
15769 !HandleLValueArrayAdjustment(Info, Init, Subobject,
15770 CAT->getElementType(), 1)) {
15771 if (!Info.noteFailure())
15772 return false;
15773 Success = false;
15774 }
15775 return true;
15776 };
15777 unsigned ArrayIndex = 0;
15778 QualType DestTy = CAT->getElementType();
15779 APSInt Value(Info.Ctx.getTypeSize(DestTy), DestTy->isUnsignedIntegerType());
15780 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
15781 const Expr *Init = Index < Args.size() ? Args[Index] : ArrayFiller;
15782 if (ArrayIndex >= NumEltsToInit)
15783 break;
15784 if (auto *EmbedS = dyn_cast<EmbedExpr>(Init->IgnoreParenImpCasts())) {
15785 StringLiteral *SL = EmbedS->getDataStringLiteral();
15786 for (unsigned I = EmbedS->getStartingElementPos(),
15787 N = EmbedS->getDataElementCount();
15788 I != EmbedS->getStartingElementPos() + N; ++I) {
15789 Value = SL->getCodeUnit(I);
15790 if (DestTy->isIntegerType()) {
15791 Result.getArrayInitializedElt(ArrayIndex) = APValue(Value);
15792 } else {
15793 assert(DestTy->isFloatingType() && "unexpected type");
15794 const FPOptions FPO =
15795 Init->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
15796 APFloat FValue(0.0);
15797 if (!HandleIntToFloatCast(Info, Init, FPO, EmbedS->getType(), Value,
15798 DestTy, FValue))
15799 return false;
15800 Result.getArrayInitializedElt(ArrayIndex) = APValue(FValue);
15801 }
15802 ArrayIndex++;
15803 }
15804 } else {
15805 if (!Eval(Init, ArrayIndex))
15806 return false;
15807 ++ArrayIndex;
15808 }
15809 }
15810
15811 if (!Result.hasArrayFiller())
15812 return Success;
15813
15814 // If we get here, we have a trivial filler, which we can just evaluate
15815 // once and splat over the rest of the array elements.
15816 assert(ArrayFiller && "no array filler for incomplete init list");
15817 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
15818 ArrayFiller) &&
15819 Success;
15820}
15821
15822bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
15823 LValue CommonLV;
15824 if (E->getCommonExpr() &&
15825 !Evaluate(Info.CurrentCall->createTemporary(
15826 E->getCommonExpr(),
15827 getStorageType(Info.Ctx, E->getCommonExpr()),
15828 ScopeKind::FullExpression, CommonLV),
15829 Info, E->getCommonExpr()->getSourceExpr()))
15830 return false;
15831
15833
15834 uint64_t Elements = CAT->getZExtSize();
15835 Result = APValue(APValue::UninitArray(), Elements, Elements);
15836
15837 LValue Subobject = This;
15838 Subobject.addArray(Info, E, CAT);
15839
15840 bool Success = true;
15841 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
15842 // C++ [class.temporary]/5
15843 // There are four contexts in which temporaries are destroyed at a different
15844 // point than the end of the full-expression. [...] The second context is
15845 // when a copy constructor is called to copy an element of an array while
15846 // the entire array is copied [...]. In either case, if the constructor has
15847 // one or more default arguments, the destruction of every temporary created
15848 // in a default argument is sequenced before the construction of the next
15849 // array element, if any.
15850 FullExpressionRAII Scope(Info);
15851
15852 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
15853 Info, Subobject, E->getSubExpr()) ||
15854 !HandleLValueArrayAdjustment(Info, E, Subobject,
15855 CAT->getElementType(), 1)) {
15856 if (!Info.noteFailure())
15857 return false;
15858 Success = false;
15859 }
15860
15861 // Make sure we run the destructors too.
15862 Scope.destroy();
15863 }
15864
15865 return Success;
15866}
15867
15868bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
15869 return VisitCXXConstructExpr(E, This, &Result, E->getType());
15870}
15871
15872bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
15873 const LValue &Subobject,
15874 APValue *Value,
15875 QualType Type) {
15876 bool HadZeroInit = Value->hasValue();
15877
15878 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
15879 unsigned FinalSize = CAT->getZExtSize();
15880
15881 // Preserve the array filler if we had prior zero-initialization.
15882 APValue Filler =
15883 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
15884 : APValue();
15885
15886 *Value = APValue(APValue::UninitArray(), 0, FinalSize);
15887 if (FinalSize == 0)
15888 return true;
15889
15890 bool HasTrivialConstructor = CheckTrivialDefaultConstructor(
15891 Info, E->getExprLoc(), E->getConstructor(),
15893 LValue ArrayElt = Subobject;
15894 ArrayElt.addArray(Info, E, CAT);
15895 // We do the whole initialization in two passes, first for just one element,
15896 // then for the whole array. It's possible we may find out we can't do const
15897 // init in the first pass, in which case we avoid allocating a potentially
15898 // large array. We don't do more passes because expanding array requires
15899 // copying the data, which is wasteful.
15900 for (const unsigned N : {1u, FinalSize}) {
15901 unsigned OldElts = Value->getArrayInitializedElts();
15902 if (OldElts == N)
15903 break;
15904
15905 // Expand the array to appropriate size.
15906 APValue NewValue(APValue::UninitArray(), N, FinalSize);
15907 for (unsigned I = 0; I < OldElts; ++I)
15908 NewValue.getArrayInitializedElt(I).swap(
15909 Value->getArrayInitializedElt(I));
15910 Value->swap(NewValue);
15911
15912 if (HadZeroInit)
15913 for (unsigned I = OldElts; I < N; ++I)
15914 Value->getArrayInitializedElt(I) = Filler;
15915
15916 if (HasTrivialConstructor && N == FinalSize && FinalSize != 1) {
15917 // If we have a trivial constructor, only evaluate it once and copy
15918 // the result into all the array elements.
15919 APValue &FirstResult = Value->getArrayInitializedElt(0);
15920 for (unsigned I = OldElts; I < FinalSize; ++I)
15921 Value->getArrayInitializedElt(I) = FirstResult;
15922 } else {
15923 for (unsigned I = OldElts; I < N; ++I) {
15924 if (!VisitCXXConstructExpr(E, ArrayElt,
15925 &Value->getArrayInitializedElt(I),
15926 CAT->getElementType()) ||
15927 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
15928 CAT->getElementType(), 1))
15929 return false;
15930 // When checking for const initilization any diagnostic is considered
15931 // an error.
15932 if (Info.EvalStatus.Diag && !Info.EvalStatus.Diag->empty() &&
15933 !Info.keepEvaluatingAfterFailure())
15934 return false;
15935 }
15936 }
15937 }
15938
15939 return true;
15940 }
15941
15942 if (!Type->isRecordType())
15943 return Error(E);
15944
15945 return RecordExprEvaluator(Info, Subobject, *Value)
15946 .VisitCXXConstructExpr(E, Type);
15947}
15948
15949bool ArrayExprEvaluator::VisitCXXParenListInitExpr(
15950 const CXXParenListInitExpr *E) {
15951 assert(E->getType()->isConstantArrayType() &&
15952 "Expression result is not a constant array type");
15953
15954 return VisitCXXParenListOrInitListExpr(E, E->getInitExprs(),
15955 E->getArrayFiller());
15956}
15957
15958bool ArrayExprEvaluator::VisitDesignatedInitUpdateExpr(
15959 const DesignatedInitUpdateExpr *E) {
15960 if (!Visit(E->getBase()))
15961 return false;
15962 return Visit(E->getUpdater());
15963}
15964
15965//===----------------------------------------------------------------------===//
15966// Integer Evaluation
15967//
15968// As a GNU extension, we support casting pointers to sufficiently-wide integer
15969// types and back in constant folding. Integer values are thus represented
15970// either as an integer-valued APValue, or as an lvalue-valued APValue.
15971//===----------------------------------------------------------------------===//
15972
15973namespace {
15974class IntExprEvaluator
15975 : public ExprEvaluatorBase<IntExprEvaluator> {
15976 APValue &Result;
15977public:
15978 IntExprEvaluator(EvalInfo &info, APValue &result)
15979 : ExprEvaluatorBaseTy(info), Result(result) {}
15980
15981 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
15982 assert(E->getType()->isIntegralOrEnumerationType() &&
15983 "Invalid evaluation result.");
15984 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
15985 "Invalid evaluation result.");
15986 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
15987 "Invalid evaluation result.");
15988 Result = APValue(SI);
15989 return true;
15990 }
15991 bool Success(const llvm::APSInt &SI, const Expr *E) {
15992 return Success(SI, E, Result);
15993 }
15994
15995 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
15996 assert(E->getType()->isIntegralOrEnumerationType() &&
15997 "Invalid evaluation result.");
15998 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
15999 "Invalid evaluation result.");
16000 Result = APValue(APSInt(I));
16001 Result.getInt().setIsUnsigned(
16003 return true;
16004 }
16005 bool Success(const llvm::APInt &I, const Expr *E) {
16006 return Success(I, E, Result);
16007 }
16008
16009 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
16010 assert(E->getType()->isIntegralOrEnumerationType() &&
16011 "Invalid evaluation result.");
16012 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
16013 return true;
16014 }
16015 bool Success(uint64_t Value, const Expr *E) {
16016 return Success(Value, E, Result);
16017 }
16018
16019 bool Success(CharUnits Size, const Expr *E) {
16020 return Success(Size.getQuantity(), E);
16021 }
16022
16023 bool Success(const APValue &V, const Expr *E) {
16024 // C++23 [expr.const]p8 If we have a variable that is unknown reference or
16025 // pointer allow further evaluation of the value.
16026 if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate() ||
16027 V.allowConstexprUnknown()) {
16028 Result = V;
16029 return true;
16030 }
16031 return Success(V.getInt(), E);
16032 }
16033
16034 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
16035
16036 friend std::optional<bool> EvaluateBuiltinIsWithinLifetime(IntExprEvaluator &,
16037 const CallExpr *);
16038
16039 //===--------------------------------------------------------------------===//
16040 // Visitor Methods
16041 //===--------------------------------------------------------------------===//
16042
16043 bool VisitIntegerLiteral(const IntegerLiteral *E) {
16044 return Success(E->getValue(), E);
16045 }
16046 bool VisitCharacterLiteral(const CharacterLiteral *E) {
16047 return Success(E->getValue(), E);
16048 }
16049
16050 bool CheckReferencedDecl(const Expr *E, const Decl *D);
16051 bool VisitDeclRefExpr(const DeclRefExpr *E) {
16052 if (CheckReferencedDecl(E, E->getDecl()))
16053 return true;
16054
16055 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
16056 }
16057 bool VisitMemberExpr(const MemberExpr *E) {
16058 if (CheckReferencedDecl(E, E->getMemberDecl())) {
16059 VisitIgnoredBaseExpression(E->getBase());
16060 return true;
16061 }
16062
16063 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
16064 }
16065
16066 bool VisitCallExpr(const CallExpr *E);
16067 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
16068 bool VisitBinaryOperator(const BinaryOperator *E);
16069 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
16070 bool VisitUnaryOperator(const UnaryOperator *E);
16071
16072 bool VisitCastExpr(const CastExpr* E);
16073 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
16074
16075 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
16076 return Success(E->getValue(), E);
16077 }
16078
16079 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
16080 return Success(E->getValue(), E);
16081 }
16082
16083 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
16084 if (Info.ArrayInitIndex == uint64_t(-1)) {
16085 // We were asked to evaluate this subexpression independent of the
16086 // enclosing ArrayInitLoopExpr. We can't do that.
16087 Info.FFDiag(E);
16088 return false;
16089 }
16090 return Success(Info.ArrayInitIndex, E);
16091 }
16092
16093 // Note, GNU defines __null as an integer, not a pointer.
16094 bool VisitGNUNullExpr(const GNUNullExpr *E) {
16095 return ZeroInitialization(E);
16096 }
16097
16098 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
16099 if (E->isStoredAsBoolean())
16100 return Success(E->getBoolValue(), E);
16101 if (E->getAPValue().isAbsent())
16102 return false;
16103 assert(E->getAPValue().isInt() && "APValue type not supported");
16104 return Success(E->getAPValue().getInt(), E);
16105 }
16106
16107 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
16108 return Success(E->getValue(), E);
16109 }
16110
16111 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
16112 return Success(E->getValue(), E);
16113 }
16114
16115 bool VisitOpenACCAsteriskSizeExpr(const OpenACCAsteriskSizeExpr *E) {
16116 // This should not be evaluated during constant expr evaluation, as it
16117 // should always be in an unevaluated context (the args list of a 'gang' or
16118 // 'tile' clause).
16119 return Error(E);
16120 }
16121
16122 bool VisitUnaryReal(const UnaryOperator *E);
16123 bool VisitUnaryImag(const UnaryOperator *E);
16124
16125 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
16126 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
16127 bool VisitSourceLocExpr(const SourceLocExpr *E);
16128 bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E);
16129 bool VisitRequiresExpr(const RequiresExpr *E);
16130 // FIXME: Missing: array subscript of vector, member of vector
16131};
16132
16133class FixedPointExprEvaluator
16134 : public ExprEvaluatorBase<FixedPointExprEvaluator> {
16135 APValue &Result;
16136
16137 public:
16138 FixedPointExprEvaluator(EvalInfo &info, APValue &result)
16139 : ExprEvaluatorBaseTy(info), Result(result) {}
16140
16141 bool Success(const llvm::APInt &I, const Expr *E) {
16142 return Success(
16143 APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
16144 }
16145
16146 bool Success(uint64_t Value, const Expr *E) {
16147 return Success(
16148 APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
16149 }
16150
16151 bool Success(const APValue &V, const Expr *E) {
16152 return Success(V.getFixedPoint(), E);
16153 }
16154
16155 bool Success(const APFixedPoint &V, const Expr *E) {
16156 assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
16157 assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
16158 "Invalid evaluation result.");
16159 Result = APValue(V);
16160 return true;
16161 }
16162
16163 bool ZeroInitialization(const Expr *E) {
16164 return Success(0, E);
16165 }
16166
16167 //===--------------------------------------------------------------------===//
16168 // Visitor Methods
16169 //===--------------------------------------------------------------------===//
16170
16171 bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
16172 return Success(E->getValue(), E);
16173 }
16174
16175 bool VisitCastExpr(const CastExpr *E);
16176 bool VisitUnaryOperator(const UnaryOperator *E);
16177 bool VisitBinaryOperator(const BinaryOperator *E);
16178};
16179} // end anonymous namespace
16180
16181/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
16182/// produce either the integer value or a pointer.
16183///
16184/// GCC has a heinous extension which folds casts between pointer types and
16185/// pointer-sized integral types. We support this by allowing the evaluation of
16186/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
16187/// Some simple arithmetic on such values is supported (they are treated much
16188/// like char*).
16190 EvalInfo &Info) {
16191 assert(!E->isValueDependent());
16192 assert(E->isPRValue() && E->getType()->isIntegralOrEnumerationType());
16193 return IntExprEvaluator(Info, Result).Visit(E);
16194}
16195
16196static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
16197 assert(!E->isValueDependent());
16198 APValue Val;
16199 if (!EvaluateIntegerOrLValue(E, Val, Info))
16200 return false;
16201 if (!Val.isInt()) {
16202 // FIXME: It would be better to produce the diagnostic for casting
16203 // a pointer to an integer.
16204 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
16205 return false;
16206 }
16207 Result = Val.getInt();
16208 return true;
16209}
16210
16211bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
16213 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
16214 return Success(Evaluated, E);
16215}
16216
16217static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
16218 EvalInfo &Info) {
16219 assert(!E->isValueDependent());
16220 if (E->getType()->isFixedPointType()) {
16221 APValue Val;
16222 if (!FixedPointExprEvaluator(Info, Val).Visit(E))
16223 return false;
16224 if (!Val.isFixedPoint())
16225 return false;
16226
16227 Result = Val.getFixedPoint();
16228 return true;
16229 }
16230 return false;
16231}
16232
16233static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
16234 EvalInfo &Info) {
16235 assert(!E->isValueDependent());
16236 if (E->getType()->isIntegerType()) {
16237 auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
16238 APSInt Val;
16239 if (!EvaluateInteger(E, Val, Info))
16240 return false;
16241 Result = APFixedPoint(Val, FXSema);
16242 return true;
16243 } else if (E->getType()->isFixedPointType()) {
16244 return EvaluateFixedPoint(E, Result, Info);
16245 }
16246 return false;
16247}
16248
16249/// Check whether the given declaration can be directly converted to an integral
16250/// rvalue. If not, no diagnostic is produced; there are other things we can
16251/// try.
16252bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
16253 // Enums are integer constant exprs.
16254 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
16255 // Check for signedness/width mismatches between E type and ECD value.
16256 bool SameSign = (ECD->getInitVal().isSigned()
16258 bool SameWidth = (ECD->getInitVal().getBitWidth()
16259 == Info.Ctx.getIntWidth(E->getType()));
16260 if (SameSign && SameWidth)
16261 return Success(ECD->getInitVal(), E);
16262 else {
16263 // Get rid of mismatch (otherwise Success assertions will fail)
16264 // by computing a new value matching the type of E.
16265 llvm::APSInt Val = ECD->getInitVal();
16266 if (!SameSign)
16267 Val.setIsSigned(!ECD->getInitVal().isSigned());
16268 if (!SameWidth)
16269 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
16270 return Success(Val, E);
16271 }
16272 }
16273 return false;
16274}
16275
16276/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
16277/// as GCC.
16279 const LangOptions &LangOpts) {
16280 assert(!T->isDependentType() && "unexpected dependent type");
16281
16282 QualType CanTy = T.getCanonicalType();
16283
16284 switch (CanTy->getTypeClass()) {
16285#define TYPE(ID, BASE)
16286#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
16287#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
16288#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
16289#include "clang/AST/TypeNodes.inc"
16290 case Type::Auto:
16291 case Type::DeducedTemplateSpecialization:
16292 llvm_unreachable("unexpected non-canonical or dependent type");
16293
16294 case Type::Builtin:
16295 switch (cast<BuiltinType>(CanTy)->getKind()) {
16296#define BUILTIN_TYPE(ID, SINGLETON_ID)
16297#define SIGNED_TYPE(ID, SINGLETON_ID) \
16298 case BuiltinType::ID: return GCCTypeClass::Integer;
16299#define FLOATING_TYPE(ID, SINGLETON_ID) \
16300 case BuiltinType::ID: return GCCTypeClass::RealFloat;
16301#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
16302 case BuiltinType::ID: break;
16303#include "clang/AST/BuiltinTypes.def"
16304 case BuiltinType::Void:
16305 return GCCTypeClass::Void;
16306
16307 case BuiltinType::Bool:
16308 return GCCTypeClass::Bool;
16309
16310 case BuiltinType::Char_U:
16311 case BuiltinType::UChar:
16312 case BuiltinType::WChar_U:
16313 case BuiltinType::Char8:
16314 case BuiltinType::Char16:
16315 case BuiltinType::Char32:
16316 case BuiltinType::UShort:
16317 case BuiltinType::UInt:
16318 case BuiltinType::ULong:
16319 case BuiltinType::ULongLong:
16320 case BuiltinType::UInt128:
16321 return GCCTypeClass::Integer;
16322
16323 case BuiltinType::UShortAccum:
16324 case BuiltinType::UAccum:
16325 case BuiltinType::ULongAccum:
16326 case BuiltinType::UShortFract:
16327 case BuiltinType::UFract:
16328 case BuiltinType::ULongFract:
16329 case BuiltinType::SatUShortAccum:
16330 case BuiltinType::SatUAccum:
16331 case BuiltinType::SatULongAccum:
16332 case BuiltinType::SatUShortFract:
16333 case BuiltinType::SatUFract:
16334 case BuiltinType::SatULongFract:
16335 return GCCTypeClass::None;
16336
16337 case BuiltinType::NullPtr:
16338
16339 case BuiltinType::ObjCId:
16340 case BuiltinType::ObjCClass:
16341 case BuiltinType::ObjCSel:
16342#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
16343 case BuiltinType::Id:
16344#include "clang/Basic/OpenCLImageTypes.def"
16345#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
16346 case BuiltinType::Id:
16347#include "clang/Basic/OpenCLExtensionTypes.def"
16348 case BuiltinType::OCLSampler:
16349 case BuiltinType::OCLEvent:
16350 case BuiltinType::OCLClkEvent:
16351 case BuiltinType::OCLQueue:
16352 case BuiltinType::OCLReserveID:
16353#define SVE_TYPE(Name, Id, SingletonId) \
16354 case BuiltinType::Id:
16355#include "clang/Basic/AArch64ACLETypes.def"
16356#define PPC_VECTOR_TYPE(Name, Id, Size) \
16357 case BuiltinType::Id:
16358#include "clang/Basic/PPCTypes.def"
16359#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
16360#include "clang/Basic/RISCVVTypes.def"
16361#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
16362#include "clang/Basic/WebAssemblyReferenceTypes.def"
16363#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
16364#include "clang/Basic/AMDGPUTypes.def"
16365#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
16366#include "clang/Basic/HLSLIntangibleTypes.def"
16367#define SPIRV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
16368#include "clang/Basic/SPIRVTypes.def"
16369 return GCCTypeClass::None;
16370
16371 case BuiltinType::Dependent:
16372 llvm_unreachable("unexpected dependent type");
16373 };
16374 llvm_unreachable("unexpected placeholder type");
16375
16376 case Type::Enum:
16377 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
16378
16379 case Type::Pointer:
16380 case Type::ConstantArray:
16381 case Type::VariableArray:
16382 case Type::IncompleteArray:
16383 case Type::FunctionNoProto:
16384 case Type::FunctionProto:
16385 case Type::ArrayParameter:
16386 return GCCTypeClass::Pointer;
16387
16388 case Type::MemberPointer:
16389 return CanTy->isMemberDataPointerType()
16392
16393 case Type::Complex:
16394 return GCCTypeClass::Complex;
16395
16396 case Type::Record:
16397 return CanTy->isUnionType() ? GCCTypeClass::Union
16399
16400 case Type::Atomic:
16401 // GCC classifies _Atomic T the same as T.
16403 CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
16404
16405 case Type::Vector:
16406 case Type::ExtVector:
16407 return GCCTypeClass::Vector;
16408
16409 case Type::BlockPointer:
16410 case Type::ConstantMatrix:
16411 case Type::ObjCObject:
16412 case Type::ObjCInterface:
16413 case Type::ObjCObjectPointer:
16414 case Type::Pipe:
16415 case Type::HLSLAttributedResource:
16416 case Type::HLSLInlineSpirv:
16417 case Type::OverflowBehavior:
16418 // Classify all other types that don't fit into the regular
16419 // classification the same way.
16420 return GCCTypeClass::None;
16421
16422 case Type::BitInt:
16423 return GCCTypeClass::BitInt;
16424
16425 case Type::LValueReference:
16426 case Type::RValueReference:
16427 llvm_unreachable("invalid type for expression");
16428 }
16429
16430 llvm_unreachable("unexpected type class");
16431}
16432
16433/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
16434/// as GCC.
16435static GCCTypeClass
16437 // If no argument was supplied, default to None. This isn't
16438 // ideal, however it is what gcc does.
16439 if (E->getNumArgs() == 0)
16440 return GCCTypeClass::None;
16441
16442 // FIXME: Bizarrely, GCC treats a call with more than one argument as not
16443 // being an ICE, but still folds it to a constant using the type of the first
16444 // argument.
16445 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
16446}
16447
16448/// EvaluateBuiltinConstantPForLValue - Determine the result of
16449/// __builtin_constant_p when applied to the given pointer.
16450///
16451/// A pointer is only "constant" if it is null (or a pointer cast to integer)
16452/// or it points to the first character of a string literal.
16455 if (Base.isNull()) {
16456 // A null base is acceptable.
16457 return true;
16458 } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
16459 if (!isa<StringLiteral>(E))
16460 return false;
16461 return LV.getLValueOffset().isZero();
16462 } else if (Base.is<TypeInfoLValue>()) {
16463 // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
16464 // evaluate to true.
16465 return true;
16466 } else {
16467 // Any other base is not constant enough for GCC.
16468 return false;
16469 }
16470}
16471
16472/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
16473/// GCC as we can manage.
16474static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
16475 // This evaluation is not permitted to have side-effects, so evaluate it in
16476 // a speculative evaluation context.
16477 SpeculativeEvaluationRAII SpeculativeEval(Info);
16478
16479 // Constant-folding is always enabled for the operand of __builtin_constant_p
16480 // (even when the enclosing evaluation context otherwise requires a strict
16481 // language-specific constant expression).
16482 FoldConstant Fold(Info, true);
16483
16484 QualType ArgType = Arg->getType();
16485
16486 // __builtin_constant_p always has one operand. The rules which gcc follows
16487 // are not precisely documented, but are as follows:
16488 //
16489 // - If the operand is of integral, floating, complex or enumeration type,
16490 // and can be folded to a known value of that type, it returns 1.
16491 // - If the operand can be folded to a pointer to the first character
16492 // of a string literal (or such a pointer cast to an integral type)
16493 // or to a null pointer or an integer cast to a pointer, it returns 1.
16494 //
16495 // Otherwise, it returns 0.
16496 //
16497 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
16498 // its support for this did not work prior to GCC 9 and is not yet well
16499 // understood.
16500 if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
16501 ArgType->isAnyComplexType() || ArgType->isPointerType() ||
16502 ArgType->isNullPtrType()) {
16503 APValue V;
16504 if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) {
16505 Fold.keepDiagnostics();
16506 return false;
16507 }
16508
16509 // For a pointer (possibly cast to integer), there are special rules.
16510 if (V.getKind() == APValue::LValue)
16512
16513 // Otherwise, any constant value is good enough.
16514 return V.hasValue();
16515 }
16516
16517 // Anything else isn't considered to be sufficiently constant.
16518 return false;
16519}
16520
16521/// Retrieves the "underlying object type" of the given expression,
16522/// as used by __builtin_object_size.
16524 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
16525 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
16526 return VD->getType();
16527 } else if (const Expr *E = B.dyn_cast<const Expr*>()) {
16529 return E->getType();
16530 } else if (B.is<TypeInfoLValue>()) {
16531 return B.getTypeInfoType();
16532 } else if (B.is<DynamicAllocLValue>()) {
16533 return B.getDynamicAllocType();
16534 }
16535
16536 return QualType();
16537}
16538
16539/// A more selective version of E->IgnoreParenCasts for
16540/// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
16541/// to change the type of E.
16542/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
16543///
16544/// Always returns an RValue with a pointer representation.
16546 assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
16547
16548 const Expr *NoParens = E->IgnoreParens();
16549 const auto *Cast = dyn_cast<CastExpr>(NoParens);
16550 if (Cast == nullptr)
16551 return NoParens;
16552
16553 // We only conservatively allow a few kinds of casts, because this code is
16554 // inherently a simple solution that seeks to support the common case.
16555 auto CastKind = Cast->getCastKind();
16556 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
16557 CastKind != CK_AddressSpaceConversion)
16558 return NoParens;
16559
16560 const auto *SubExpr = Cast->getSubExpr();
16561 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isPRValue())
16562 return NoParens;
16563 return ignorePointerCastsAndParens(SubExpr);
16564}
16565
16566/// Checks to see if the given LValue's Designator is at the end of the LValue's
16567/// record layout. e.g.
16568/// struct { struct { int a, b; } fst, snd; } obj;
16569/// obj.fst // no
16570/// obj.snd // yes
16571/// obj.fst.a // no
16572/// obj.fst.b // no
16573/// obj.snd.a // no
16574/// obj.snd.b // yes
16575///
16576/// Please note: this function is specialized for how __builtin_object_size
16577/// views "objects".
16578///
16579/// If this encounters an invalid RecordDecl or otherwise cannot determine the
16580/// correct result, it will always return true.
16581static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
16582 assert(!LVal.Designator.Invalid);
16583
16584 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD) {
16585 const RecordDecl *Parent = FD->getParent();
16586 if (Parent->isInvalidDecl() || Parent->isUnion())
16587 return true;
16588 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
16589 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
16590 };
16591
16592 auto &Base = LVal.getLValueBase();
16593 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
16594 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
16595 if (!IsLastOrInvalidFieldDecl(FD))
16596 return false;
16597 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
16598 for (auto *FD : IFD->chain()) {
16599 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD)))
16600 return false;
16601 }
16602 }
16603 }
16604
16605 unsigned I = 0;
16606 QualType BaseType = getType(Base);
16607 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
16608 // If we don't know the array bound, conservatively assume we're looking at
16609 // the final array element.
16610 ++I;
16611 if (BaseType->isIncompleteArrayType())
16612 BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
16613 else
16614 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
16615 }
16616
16617 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
16618 const auto &Entry = LVal.Designator.Entries[I];
16619 if (BaseType->isArrayType()) {
16620 // Because __builtin_object_size treats arrays as objects, we can ignore
16621 // the index iff this is the last array in the Designator.
16622 if (I + 1 == E)
16623 return true;
16624 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
16625 uint64_t Index = Entry.getAsArrayIndex();
16626 if (Index + 1 != CAT->getZExtSize())
16627 return false;
16628 BaseType = CAT->getElementType();
16629 } else if (BaseType->isAnyComplexType()) {
16630 const auto *CT = BaseType->castAs<ComplexType>();
16631 uint64_t Index = Entry.getAsArrayIndex();
16632 if (Index != 1)
16633 return false;
16634 BaseType = CT->getElementType();
16635 } else if (auto *FD = getAsField(Entry)) {
16636 if (!IsLastOrInvalidFieldDecl(FD))
16637 return false;
16638 BaseType = FD->getType();
16639 } else {
16640 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
16641 return false;
16642 }
16643 }
16644 return true;
16645}
16646
16647/// Tests to see if the LValue has a user-specified designator (that isn't
16648/// necessarily valid). Note that this always returns 'true' if the LValue has
16649/// an unsized array as its first designator entry, because there's currently no
16650/// way to tell if the user typed *foo or foo[0].
16651static bool refersToCompleteObject(const LValue &LVal) {
16652 if (LVal.Designator.Invalid)
16653 return false;
16654
16655 if (!LVal.Designator.Entries.empty())
16656 return LVal.Designator.isMostDerivedAnUnsizedArray();
16657
16658 if (!LVal.InvalidBase)
16659 return true;
16660
16661 // If `E` is a MemberExpr, then the first part of the designator is hiding in
16662 // the LValueBase.
16663 const auto *E = LVal.Base.dyn_cast<const Expr *>();
16664 return !E || !isa<MemberExpr>(E);
16665}
16666
16667/// Attempts to detect a user writing into a piece of memory that's impossible
16668/// to figure out the size of by just using types.
16669static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
16670 const SubobjectDesignator &Designator = LVal.Designator;
16671 // Notes:
16672 // - Users can only write off of the end when we have an invalid base. Invalid
16673 // bases imply we don't know where the memory came from.
16674 // - We used to be a bit more aggressive here; we'd only be conservative if
16675 // the array at the end was flexible, or if it had 0 or 1 elements. This
16676 // broke some common standard library extensions (PR30346), but was
16677 // otherwise seemingly fine. It may be useful to reintroduce this behavior
16678 // with some sort of list. OTOH, it seems that GCC is always
16679 // conservative with the last element in structs (if it's an array), so our
16680 // current behavior is more compatible than an explicit list approach would
16681 // be.
16682 auto isFlexibleArrayMember = [&] {
16684 FAMKind StrictFlexArraysLevel =
16685 Ctx.getLangOpts().getStrictFlexArraysLevel();
16686
16687 if (Designator.isMostDerivedAnUnsizedArray())
16688 return true;
16689
16690 if (StrictFlexArraysLevel == FAMKind::Default)
16691 return true;
16692
16693 if (Designator.getMostDerivedArraySize() == 0 &&
16694 StrictFlexArraysLevel != FAMKind::IncompleteOnly)
16695 return true;
16696
16697 if (Designator.getMostDerivedArraySize() == 1 &&
16698 StrictFlexArraysLevel == FAMKind::OneZeroOrIncomplete)
16699 return true;
16700
16701 return false;
16702 };
16703
16704 return LVal.InvalidBase &&
16705 Designator.Entries.size() == Designator.MostDerivedPathLength &&
16706 Designator.MostDerivedIsArrayElement && isFlexibleArrayMember() &&
16707 isDesignatorAtObjectEnd(Ctx, LVal);
16708}
16709
16710/// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
16711/// Fails if the conversion would cause loss of precision.
16712static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
16713 CharUnits &Result) {
16714 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
16715 if (Int.ugt(CharUnitsMax))
16716 return false;
16717 Result = CharUnits::fromQuantity(Int.getZExtValue());
16718 return true;
16719}
16720
16721/// If we're evaluating the object size of an instance of a struct that
16722/// contains a flexible array member, add the size of the initializer.
16723static void addFlexibleArrayMemberInitSize(EvalInfo &Info, const QualType &T,
16724 const LValue &LV, CharUnits &Size) {
16725 if (!T.isNull() && T->isStructureType() &&
16726 T->castAsRecordDecl()->hasFlexibleArrayMember())
16727 if (const auto *V = LV.getLValueBase().dyn_cast<const ValueDecl *>())
16728 if (const auto *VD = dyn_cast<VarDecl>(V))
16729 if (VD->hasInit())
16730 Size += VD->getFlexibleArrayInitChars(Info.Ctx);
16731}
16732
16733/// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
16734/// determine how many bytes exist from the beginning of the object to either
16735/// the end of the current subobject, or the end of the object itself, depending
16736/// on what the LValue looks like + the value of Type.
16737///
16738/// If this returns false, the value of Result is undefined.
16739static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
16740 unsigned Type, const LValue &LVal,
16741 CharUnits &EndOffset) {
16742 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
16743
16744 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
16745 if (Ty.isNull())
16746 return false;
16747
16748 Ty = Ty.getNonReferenceType();
16749
16750 if (Ty->isIncompleteType() || Ty->isFunctionType())
16751 return false;
16752
16753 return HandleSizeof(Info, ExprLoc, Ty, Result);
16754 };
16755
16756 // We want to evaluate the size of the entire object. This is a valid fallback
16757 // for when Type=1 and the designator is invalid, because we're asked for an
16758 // upper-bound.
16759 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
16760 // Type=3 wants a lower bound, so we can't fall back to this.
16761 if (Type == 3 && !DetermineForCompleteObject)
16762 return false;
16763
16764 llvm::APInt APEndOffset;
16765 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
16766 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
16767 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
16768
16769 if (LVal.InvalidBase)
16770 return false;
16771
16772 QualType BaseTy = getObjectType(LVal.getLValueBase());
16773 const bool Ret = CheckedHandleSizeof(BaseTy, EndOffset);
16774 addFlexibleArrayMemberInitSize(Info, BaseTy, LVal, EndOffset);
16775 return Ret;
16776 }
16777
16778 // We want to evaluate the size of a subobject.
16779 const SubobjectDesignator &Designator = LVal.Designator;
16780
16781 // The following is a moderately common idiom in C:
16782 //
16783 // struct Foo { int a; char c[1]; };
16784 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
16785 // strcpy(&F->c[0], Bar);
16786 //
16787 // In order to not break too much legacy code, we need to support it.
16788 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
16789 // If we can resolve this to an alloc_size call, we can hand that back,
16790 // because we know for certain how many bytes there are to write to.
16791 llvm::APInt APEndOffset;
16792 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
16793 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
16794 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
16795
16796 // If we cannot determine the size of the initial allocation, then we can't
16797 // given an accurate upper-bound. However, we are still able to give
16798 // conservative lower-bounds for Type=3.
16799 if (Type == 1)
16800 return false;
16801 }
16802
16803 CharUnits BytesPerElem;
16804 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
16805 return false;
16806
16807 // According to the GCC documentation, we want the size of the subobject
16808 // denoted by the pointer. But that's not quite right -- what we actually
16809 // want is the size of the immediately-enclosing array, if there is one.
16810 int64_t ElemsRemaining;
16811 if (Designator.MostDerivedIsArrayElement &&
16812 Designator.Entries.size() == Designator.MostDerivedPathLength) {
16813 uint64_t ArraySize = Designator.getMostDerivedArraySize();
16814 uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
16815 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
16816 } else {
16817 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
16818 }
16819
16820 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
16821 return true;
16822}
16823
16824/// Tries to evaluate the __builtin_object_size for @p E.
16825///
16826/// If @p IsDynamic is true (i.e. we're evaluating
16827/// __builtin_dynamic_object_size) and the operand designates a flexible array
16828/// member annotated with 'counted_by', we refuse to fold so that IR generation
16829/// can emit the count-based runtime size computation.
16830static std::optional<uint64_t>
16831tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type, EvalInfo &Info,
16832 bool IsDynamic = false) {
16833
16834 // Determine the denoted object.
16835 LValue LVal;
16836 {
16837 // The operand of __builtin_object_size is never evaluated for side-effects.
16838 // If there are any, but we can determine the pointed-to object anyway, then
16839 // ignore the side-effects.
16840 SpeculativeEvaluationRAII SpeculativeEval(Info);
16841 IgnoreSideEffectsRAII Fold(Info);
16842
16843 if (E->isGLValue()) {
16844 // It's possible for us to be given GLValues if we're called via
16845 // Expr::tryEvaluateObjectSize.
16846 APValue RVal;
16847 if (!EvaluateAsRValue(Info, E, RVal))
16848 return std::nullopt;
16849 LVal.setFrom(Info.Ctx, RVal);
16850 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
16851 /*InvalidBaseOK=*/true))
16852 return std::nullopt;
16853 }
16854
16855 // If we point to before the start of the object, there are no accessible
16856 // bytes.
16857 if (LVal.getLValueOffset().isNegative())
16858 return 0;
16859
16860 // For __builtin_dynamic_object_size on a counted_by-annotated flexible
16861 // array member, defer to IR generation (emitCountedBySize in CGBuiltin):
16862 // its runtime computation uses the live 'count' field and is more accurate
16863 // than the layout/initializer-derived size we'd produce here. Use the same
16864 // findStructFieldAccess form-recognition CGBuiltin does, so we refuse to
16865 // fold on exactly the shapes that path handles (and, importantly, *not*
16866 // on '&af.fam' which designates the array-as-a-whole and stays on the
16867 // layout-derived path to match GCC). Checked after the negative-offset
16868 // early return above so that obviously out-of-bounds operands still fold
16869 // to 0, preserving existing behavior.
16870 if (IsDynamic) {
16871 const auto *ME = dyn_cast_or_null<MemberExpr>(findStructFieldAccess(E));
16872 const auto *FD = ME ? dyn_cast<FieldDecl>(ME->getMemberDecl()) : nullptr;
16873 if (FD && FD->getType()->isCountAttributedType())
16874 return std::nullopt;
16875 }
16876
16877 CharUnits EndOffset;
16878 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
16879 return std::nullopt;
16880
16881 // If we've fallen outside of the end offset, just pretend there's nothing to
16882 // write to/read from.
16883 if (EndOffset <= LVal.getLValueOffset())
16884 return 0;
16885 return (EndOffset - LVal.getLValueOffset()).getQuantity();
16886}
16887
16888bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
16889 if (!IsConstantEvaluatedBuiltinCall(E))
16890 return ExprEvaluatorBaseTy::VisitCallExpr(E);
16891 return VisitBuiltinCallExpr(E, ConvertBuiltinIDToX86BuiltinID(Info.Ctx, E));
16892}
16893
16894static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info,
16895 APValue &Val, APSInt &Alignment) {
16896 QualType SrcTy = E->getArg(0)->getType();
16897 if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment))
16898 return false;
16899 // Even though we are evaluating integer expressions we could get a pointer
16900 // argument for the __builtin_is_aligned() case.
16901 if (SrcTy->isPointerType()) {
16902 LValue Ptr;
16903 if (!EvaluatePointer(E->getArg(0), Ptr, Info))
16904 return false;
16905 Ptr.moveInto(Val);
16906 } else if (!SrcTy->isIntegralOrEnumerationType()) {
16907 Info.FFDiag(E->getArg(0));
16908 return false;
16909 } else {
16910 APSInt SrcInt;
16911 if (!EvaluateInteger(E->getArg(0), SrcInt, Info))
16912 return false;
16913 assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() &&
16914 "Bit widths must be the same");
16915 Val = APValue(SrcInt);
16916 }
16917 assert(Val.hasValue());
16918 return true;
16919}
16920
16921bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
16922 unsigned BuiltinOp) {
16923 auto EvalTestOp = [&](llvm::function_ref<bool(const APInt &, const APInt &)>
16924 Fn) {
16925 APValue SourceLHS, SourceRHS;
16926 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
16927 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
16928 return false;
16929
16930 unsigned SourceLen = SourceLHS.getVectorLength();
16931 const VectorType *VT = E->getArg(0)->getType()->castAs<VectorType>();
16932 QualType ElemQT = VT->getElementType();
16933 unsigned LaneWidth = Info.Ctx.getTypeSize(ElemQT);
16934
16935 APInt AWide(LaneWidth * SourceLen, 0);
16936 APInt BWide(LaneWidth * SourceLen, 0);
16937
16938 for (unsigned I = 0; I != SourceLen; ++I) {
16939 APInt ALane;
16940 APInt BLane;
16941 if (ElemQT->isIntegerType()) { // Get value.
16942 ALane = SourceLHS.getVectorElt(I).getInt();
16943 BLane = SourceRHS.getVectorElt(I).getInt();
16944 } else if (ElemQT->isFloatingType()) { // Get only sign bit.
16945 ALane =
16946 SourceLHS.getVectorElt(I).getFloat().bitcastToAPInt().isNegative();
16947 BLane =
16948 SourceRHS.getVectorElt(I).getFloat().bitcastToAPInt().isNegative();
16949 } else { // Must be integer or floating type.
16950 return false;
16951 }
16952 AWide.insertBits(ALane, I * LaneWidth);
16953 BWide.insertBits(BLane, I * LaneWidth);
16954 }
16955 return Success(Fn(AWide, BWide), E);
16956 };
16957
16958 auto HandleMaskBinOp =
16959 [&](llvm::function_ref<APSInt(const APSInt &, const APSInt &)> Fn)
16960 -> bool {
16961 APValue LHS, RHS;
16962 if (!Evaluate(LHS, Info, E->getArg(0)) ||
16963 !Evaluate(RHS, Info, E->getArg(1)))
16964 return false;
16965
16966 APSInt ResultInt = Fn(LHS.getInt(), RHS.getInt());
16967
16968 return Success(APValue(ResultInt), E);
16969 };
16970
16971 auto HandleCRC32 = [&](unsigned DataBytes) -> bool {
16972 APSInt CRC, Data;
16973 if (!EvaluateInteger(E->getArg(0), CRC, Info) ||
16974 !EvaluateInteger(E->getArg(1), Data, Info))
16975 return false;
16976
16977 uint64_t CRCVal = CRC.getZExtValue();
16978 uint64_t DataVal = Data.getZExtValue();
16979
16980 // CRC32C polynomial (iSCSI polynomial, bit-reversed)
16981 static const uint32_t CRC32C_POLY = 0x82F63B78;
16982
16983 // Process each byte
16984 uint32_t Result = static_cast<uint32_t>(CRCVal);
16985 for (unsigned I = 0; I != DataBytes; ++I) {
16986 uint8_t Byte = static_cast<uint8_t>((DataVal >> (I * 8)) & 0xFF);
16987 Result ^= Byte;
16988 for (int J = 0; J != 8; ++J) {
16989 Result = (Result >> 1) ^ ((Result & 1) ? CRC32C_POLY : 0);
16990 }
16991 }
16992
16993 return Success(Result, E);
16994 };
16995
16996 switch (BuiltinOp) {
16997 default:
16998 return false;
16999
17000 case X86::BI__builtin_ia32_crc32qi:
17001 return HandleCRC32(1);
17002 case X86::BI__builtin_ia32_crc32hi:
17003 return HandleCRC32(2);
17004 case X86::BI__builtin_ia32_crc32si:
17005 return HandleCRC32(4);
17006 case X86::BI__builtin_ia32_crc32di:
17007 return HandleCRC32(8);
17008
17009 case Builtin::BI__builtin_dynamic_object_size:
17010 case Builtin::BI__builtin_object_size: {
17011 // The type was checked when we built the expression.
17012 unsigned Type =
17013 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
17014 assert(Type <= 3 && "unexpected type");
17015
17016 bool IsDynamic = BuiltinOp == Builtin::BI__builtin_dynamic_object_size;
17017 if (std::optional<uint64_t> Size =
17018 tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, IsDynamic))
17019 return Success(*Size, E);
17020
17021 if (E->getArg(0)->HasSideEffects(Info.Ctx))
17022 return Success((Type & 2) ? 0 : -1, E);
17023
17024 // Expression had no side effects, but we couldn't statically determine the
17025 // size of the referenced object.
17026 switch (Info.EvalMode) {
17027 case EvaluationMode::ConstantExpression:
17028 case EvaluationMode::ConstantFold:
17029 case EvaluationMode::IgnoreSideEffects:
17030 // Leave it to IR generation.
17031 return Error(E);
17032 case EvaluationMode::ConstantExpressionUnevaluated:
17033 // Reduce it to a constant now.
17034 return Success((Type & 2) ? 0 : -1, E);
17035 }
17036
17037 llvm_unreachable("unexpected EvalMode");
17038 }
17039
17040 case Builtin::BI__builtin_os_log_format_buffer_size: {
17041 analyze_os_log::OSLogBufferLayout Layout;
17042 analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
17043 return Success(Layout.size().getQuantity(), E);
17044 }
17045
17046 case Builtin::BI__builtin_is_aligned: {
17047 APValue Src;
17048 APSInt Alignment;
17049 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
17050 return false;
17051 if (Src.isLValue()) {
17052 // If we evaluated a pointer, check the minimum known alignment.
17053 LValue Ptr;
17054 Ptr.setFrom(Info.Ctx, Src);
17055 CharUnits BaseAlignment = getBaseAlignment(Info, Ptr);
17056 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset);
17057 // We can return true if the known alignment at the computed offset is
17058 // greater than the requested alignment.
17059 assert(PtrAlign.isPowerOfTwo());
17060 assert(Alignment.isPowerOf2());
17061 if (PtrAlign.getQuantity() >= Alignment)
17062 return Success(1, E);
17063 // If the alignment is not known to be sufficient, some cases could still
17064 // be aligned at run time. However, if the requested alignment is less or
17065 // equal to the base alignment and the offset is not aligned, we know that
17066 // the run-time value can never be aligned.
17067 if (BaseAlignment.getQuantity() >= Alignment &&
17068 PtrAlign.getQuantity() < Alignment)
17069 return Success(0, E);
17070 // Otherwise we can't infer whether the value is sufficiently aligned.
17071 // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N)
17072 // in cases where we can't fully evaluate the pointer.
17073 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute)
17074 << Alignment;
17075 return false;
17076 }
17077 assert(Src.isInt());
17078 return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E);
17079 }
17080 case Builtin::BI__builtin_align_up: {
17081 APValue Src;
17082 APSInt Alignment;
17083 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
17084 return false;
17085 if (!Src.isInt())
17086 return Error(E);
17087 APSInt AlignedVal =
17088 APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1),
17089 Src.getInt().isUnsigned());
17090 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
17091 return Success(AlignedVal, E);
17092 }
17093 case Builtin::BI__builtin_align_down: {
17094 APValue Src;
17095 APSInt Alignment;
17096 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
17097 return false;
17098 if (!Src.isInt())
17099 return Error(E);
17100 APSInt AlignedVal =
17101 APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned());
17102 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
17103 return Success(AlignedVal, E);
17104 }
17105
17106 case Builtin::BI__builtin_bitreverseg:
17107 case Builtin::BI__builtin_bitreverse8:
17108 case Builtin::BI__builtin_bitreverse16:
17109 case Builtin::BI__builtin_bitreverse32:
17110 case Builtin::BI__builtin_bitreverse64:
17111 case Builtin::BI__builtin_elementwise_bitreverse: {
17112 APSInt Val;
17113 if (!EvaluateInteger(E->getArg(0), Val, Info))
17114 return false;
17115
17116 return Success(Val.reverseBits(), E);
17117 }
17118 case Builtin::BI__builtin_bswapg:
17119 case Builtin::BI__builtin_bswap16:
17120 case Builtin::BI__builtin_bswap32:
17121 case Builtin::BI__builtin_bswap64:
17122 case Builtin::BIstdc_memreverse8u8:
17123 case Builtin::BIstdc_memreverse8u16:
17124 case Builtin::BIstdc_memreverse8u32:
17125 case Builtin::BIstdc_memreverse8u64: {
17126 APSInt Val;
17127 if (!EvaluateInteger(E->getArg(0), Val, Info))
17128 return false;
17129 if (Val.getBitWidth() == 8 || Val.getBitWidth() == 1)
17130 return Success(Val, E);
17131
17132 return Success(Val.byteSwap(), E);
17133 }
17134
17135 case Builtin::BI__builtin_classify_type:
17136 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
17137
17138 case Builtin::BI__builtin_clrsb:
17139 case Builtin::BI__builtin_clrsbl:
17140 case Builtin::BI__builtin_clrsbll: {
17141 APSInt Val;
17142 if (!EvaluateInteger(E->getArg(0), Val, Info))
17143 return false;
17144
17145 return Success(Val.getBitWidth() - Val.getSignificantBits(), E);
17146 }
17147
17148 case Builtin::BI__builtin_clz:
17149 case Builtin::BI__builtin_clzl:
17150 case Builtin::BI__builtin_clzll:
17151 case Builtin::BI__builtin_clzs:
17152 case Builtin::BI__builtin_clzg:
17153 case Builtin::BI__builtin_elementwise_clzg:
17154 case Builtin::BI__lzcnt16: // Microsoft variants of count leading-zeroes
17155 case Builtin::BI__lzcnt:
17156 case Builtin::BI__lzcnt64: {
17157 APSInt Val;
17158 if (E->getArg(0)->getType()->isExtVectorBoolType()) {
17159 APValue Vec;
17160 if (!EvaluateVector(E->getArg(0), Vec, Info))
17161 return false;
17162 Val = ConvertBoolVectorToInt(Vec);
17163 } else if (!EvaluateInteger(E->getArg(0), Val, Info)) {
17164 return false;
17165 }
17166
17167 std::optional<APSInt> Fallback;
17168 if ((BuiltinOp == Builtin::BI__builtin_clzg ||
17169 BuiltinOp == Builtin::BI__builtin_elementwise_clzg) &&
17170 E->getNumArgs() > 1) {
17171 APSInt FallbackTemp;
17172 if (!EvaluateInteger(E->getArg(1), FallbackTemp, Info))
17173 return false;
17174 Fallback = FallbackTemp;
17175 }
17176
17177 if (!Val) {
17178 if (Fallback)
17179 return Success(*Fallback, E);
17180
17181 // When the argument is 0, the result of GCC builtins is undefined,
17182 // whereas for Microsoft intrinsics, the result is the bit-width of the
17183 // argument.
17184 bool ZeroIsUndefined = BuiltinOp != Builtin::BI__lzcnt16 &&
17185 BuiltinOp != Builtin::BI__lzcnt &&
17186 BuiltinOp != Builtin::BI__lzcnt64;
17187
17188 if (BuiltinOp == Builtin::BI__builtin_elementwise_clzg) {
17189 Info.FFDiag(E, diag::note_constexpr_countzeroes_zero)
17190 << /*IsTrailing=*/false;
17191 }
17192
17193 if (ZeroIsUndefined)
17194 return Error(E);
17195 }
17196
17197 return Success(Val.countl_zero(), E);
17198 }
17199
17200 case Builtin::BI__builtin_constant_p: {
17201 const Expr *Arg = E->getArg(0);
17202 if (EvaluateBuiltinConstantP(Info, Arg))
17203 return Success(true, E);
17204 if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
17205 // Outside a constant context, eagerly evaluate to false in the presence
17206 // of side-effects in order to avoid -Wunsequenced false-positives in
17207 // a branch on __builtin_constant_p(expr).
17208 return Success(false, E);
17209 }
17210 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
17211 return false;
17212 }
17213
17214 case Builtin::BI__noop:
17215 // __noop always evaluates successfully and returns 0.
17216 return Success(0, E);
17217
17218 case Builtin::BI__builtin_is_constant_evaluated: {
17219 const auto *Callee = Info.CurrentCall->getCallee();
17220 if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression &&
17221 (Info.CallStackDepth == 1 ||
17222 (Info.CallStackDepth == 2 && Callee->isInStdNamespace() &&
17223 Callee->getIdentifier() &&
17224 Callee->getIdentifier()->isStr("is_constant_evaluated")))) {
17225 // FIXME: Find a better way to avoid duplicated diagnostics.
17226 if (Info.EvalStatus.Diag)
17227 Info.report((Info.CallStackDepth == 1)
17228 ? E->getExprLoc()
17229 : Info.CurrentCall->getCallRange().getBegin(),
17230 diag::warn_is_constant_evaluated_always_true_constexpr)
17231 << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated"
17232 : "std::is_constant_evaluated");
17233 }
17234
17235 return Success(Info.InConstantContext, E);
17236 }
17237
17238 case Builtin::BI__builtin_is_within_lifetime:
17239 if (auto result = EvaluateBuiltinIsWithinLifetime(*this, E))
17240 return Success(*result, E);
17241 return false;
17242
17243 case Builtin::BI__builtin_ctz:
17244 case Builtin::BI__builtin_ctzl:
17245 case Builtin::BI__builtin_ctzll:
17246 case Builtin::BI__builtin_ctzs:
17247 case Builtin::BI__builtin_ctzg:
17248 case Builtin::BI__builtin_elementwise_ctzg: {
17249 APSInt Val;
17250 if (E->getArg(0)->getType()->isExtVectorBoolType()) {
17251 APValue Vec;
17252 if (!EvaluateVector(E->getArg(0), Vec, Info))
17253 return false;
17254 Val = ConvertBoolVectorToInt(Vec);
17255 } else if (!EvaluateInteger(E->getArg(0), Val, Info)) {
17256 return false;
17257 }
17258
17259 std::optional<APSInt> Fallback;
17260 if ((BuiltinOp == Builtin::BI__builtin_ctzg ||
17261 BuiltinOp == Builtin::BI__builtin_elementwise_ctzg) &&
17262 E->getNumArgs() > 1) {
17263 APSInt FallbackTemp;
17264 if (!EvaluateInteger(E->getArg(1), FallbackTemp, Info))
17265 return false;
17266 Fallback = FallbackTemp;
17267 }
17268
17269 if (!Val) {
17270 if (Fallback)
17271 return Success(*Fallback, E);
17272
17273 if (BuiltinOp == Builtin::BI__builtin_elementwise_ctzg) {
17274 Info.FFDiag(E, diag::note_constexpr_countzeroes_zero)
17275 << /*IsTrailing=*/true;
17276 }
17277 return Error(E);
17278 }
17279
17280 return Success(Val.countr_zero(), E);
17281 }
17282
17283 case Builtin::BI__builtin_eh_return_data_regno: {
17284 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
17285 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
17286 return Success(Operand, E);
17287 }
17288
17289 case Builtin::BI__builtin_elementwise_abs: {
17290 APSInt Val;
17291 if (!EvaluateInteger(E->getArg(0), Val, Info))
17292 return false;
17293
17294 return Success(Val.abs(), E);
17295 }
17296
17297 case Builtin::BI__builtin_expect:
17298 case Builtin::BI__builtin_expect_with_probability:
17299 return Visit(E->getArg(0));
17300
17301 case Builtin::BI__builtin_ptrauth_string_discriminator: {
17302 const auto *Literal =
17304 uint64_t Result = getPointerAuthStableSipHash(Literal->getString());
17305 return Success(Result, E);
17306 }
17307
17308 case Builtin::BI__builtin_infer_alloc_token: {
17309 // If we fail to infer a type, this fails to be a constant expression; this
17310 // can be checked with __builtin_constant_p(...).
17311 QualType AllocType = infer_alloc::inferPossibleType(E, Info.Ctx, nullptr);
17312 if (AllocType.isNull())
17313 return Error(
17314 E, diag::note_constexpr_infer_alloc_token_type_inference_failed);
17315 auto ATMD = infer_alloc::getAllocTokenMetadata(AllocType, Info.Ctx);
17316 if (!ATMD)
17317 return Error(E, diag::note_constexpr_infer_alloc_token_no_metadata);
17318 auto Mode =
17319 Info.getLangOpts().AllocTokenMode.value_or(llvm::DefaultAllocTokenMode);
17320 uint64_t BitWidth = Info.Ctx.getTypeSize(Info.Ctx.getSizeType());
17321 auto MaxTokensOpt = Info.getLangOpts().AllocTokenMax;
17322 uint64_t MaxTokens =
17323 MaxTokensOpt.value_or(0) ? *MaxTokensOpt : (~0ULL >> (64 - BitWidth));
17324 auto MaybeToken = llvm::getAllocToken(Mode, *ATMD, MaxTokens);
17325 if (!MaybeToken)
17326 return Error(E, diag::note_constexpr_infer_alloc_token_stateful_mode);
17327 return Success(llvm::APInt(BitWidth, *MaybeToken), E);
17328 }
17329
17330 case Builtin::BI__builtin_ffs:
17331 case Builtin::BI__builtin_ffsl:
17332 case Builtin::BI__builtin_ffsll: {
17333 APSInt Val;
17334 if (!EvaluateInteger(E->getArg(0), Val, Info))
17335 return false;
17336
17337 unsigned N = Val.countr_zero();
17338 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
17339 }
17340
17341 case Builtin::BI__builtin_fpclassify: {
17342 APFloat Val(0.0);
17343 if (!EvaluateFloat(E->getArg(5), Val, Info))
17344 return false;
17345 unsigned Arg;
17346 switch (Val.getCategory()) {
17347 case APFloat::fcNaN: Arg = 0; break;
17348 case APFloat::fcInfinity: Arg = 1; break;
17349 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
17350 case APFloat::fcZero: Arg = 4; break;
17351 }
17352 return Visit(E->getArg(Arg));
17353 }
17354
17355 case Builtin::BI__builtin_isinf_sign: {
17356 APFloat Val(0.0);
17357 return EvaluateFloat(E->getArg(0), Val, Info) &&
17358 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
17359 }
17360
17361 case Builtin::BI__builtin_isinf: {
17362 APFloat Val(0.0);
17363 return EvaluateFloat(E->getArg(0), Val, Info) &&
17364 Success(Val.isInfinity() ? 1 : 0, E);
17365 }
17366
17367 case Builtin::BI__builtin_isfinite: {
17368 APFloat Val(0.0);
17369 return EvaluateFloat(E->getArg(0), Val, Info) &&
17370 Success(Val.isFinite() ? 1 : 0, E);
17371 }
17372
17373 case Builtin::BI__builtin_isnan: {
17374 APFloat Val(0.0);
17375 return EvaluateFloat(E->getArg(0), Val, Info) &&
17376 Success(Val.isNaN() ? 1 : 0, E);
17377 }
17378
17379 case Builtin::BI__builtin_isnormal: {
17380 APFloat Val(0.0);
17381 return EvaluateFloat(E->getArg(0), Val, Info) &&
17382 Success(Val.isNormal() ? 1 : 0, E);
17383 }
17384
17385 case Builtin::BI__builtin_issubnormal: {
17386 APFloat Val(0.0);
17387 return EvaluateFloat(E->getArg(0), Val, Info) &&
17388 Success(Val.isDenormal() ? 1 : 0, E);
17389 }
17390
17391 case Builtin::BI__builtin_iszero: {
17392 APFloat Val(0.0);
17393 return EvaluateFloat(E->getArg(0), Val, Info) &&
17394 Success(Val.isZero() ? 1 : 0, E);
17395 }
17396
17397 case Builtin::BI__builtin_signbit:
17398 case Builtin::BI__builtin_signbitf:
17399 case Builtin::BI__builtin_signbitl: {
17400 APFloat Val(0.0);
17401 return EvaluateFloat(E->getArg(0), Val, Info) &&
17402 Success(Val.isNegative() ? 1 : 0, E);
17403 }
17404
17405 case Builtin::BI__builtin_isgreater:
17406 case Builtin::BI__builtin_isgreaterequal:
17407 case Builtin::BI__builtin_isless:
17408 case Builtin::BI__builtin_islessequal:
17409 case Builtin::BI__builtin_islessgreater:
17410 case Builtin::BI__builtin_isunordered: {
17411 APFloat LHS(0.0);
17412 APFloat RHS(0.0);
17413 if (!EvaluateFloat(E->getArg(0), LHS, Info) ||
17414 !EvaluateFloat(E->getArg(1), RHS, Info))
17415 return false;
17416
17417 return Success(
17418 [&] {
17419 switch (BuiltinOp) {
17420 case Builtin::BI__builtin_isgreater:
17421 return LHS > RHS;
17422 case Builtin::BI__builtin_isgreaterequal:
17423 return LHS >= RHS;
17424 case Builtin::BI__builtin_isless:
17425 return LHS < RHS;
17426 case Builtin::BI__builtin_islessequal:
17427 return LHS <= RHS;
17428 case Builtin::BI__builtin_islessgreater: {
17429 APFloat::cmpResult cmp = LHS.compare(RHS);
17430 return cmp == APFloat::cmpResult::cmpLessThan ||
17431 cmp == APFloat::cmpResult::cmpGreaterThan;
17432 }
17433 case Builtin::BI__builtin_isunordered:
17434 return LHS.compare(RHS) == APFloat::cmpResult::cmpUnordered;
17435 default:
17436 llvm_unreachable("Unexpected builtin ID: Should be a floating "
17437 "point comparison function");
17438 }
17439 }()
17440 ? 1
17441 : 0,
17442 E);
17443 }
17444
17445 case Builtin::BI__builtin_issignaling: {
17446 APFloat Val(0.0);
17447 return EvaluateFloat(E->getArg(0), Val, Info) &&
17448 Success(Val.isSignaling() ? 1 : 0, E);
17449 }
17450
17451 case Builtin::BI__builtin_isfpclass: {
17452 APSInt MaskVal;
17453 if (!EvaluateInteger(E->getArg(1), MaskVal, Info))
17454 return false;
17455 unsigned Test = static_cast<llvm::FPClassTest>(MaskVal.getZExtValue());
17456 APFloat Val(0.0);
17457 return EvaluateFloat(E->getArg(0), Val, Info) &&
17458 Success((Val.classify() & Test) ? 1 : 0, E);
17459 }
17460
17461 case Builtin::BI__builtin_parity:
17462 case Builtin::BI__builtin_parityl:
17463 case Builtin::BI__builtin_parityll: {
17464 APSInt Val;
17465 if (!EvaluateInteger(E->getArg(0), Val, Info))
17466 return false;
17467
17468 return Success(Val.popcount() % 2, E);
17469 }
17470
17471 case Builtin::BI__builtin_abs:
17472 case Builtin::BI__builtin_labs:
17473 case Builtin::BI__builtin_llabs: {
17474 APSInt Val;
17475 if (!EvaluateInteger(E->getArg(0), Val, Info))
17476 return false;
17477 if (Val == APSInt(APInt::getSignedMinValue(Val.getBitWidth()),
17478 /*IsUnsigned=*/false))
17479 return false;
17480 if (Val.isNegative())
17481 Val.negate();
17482 return Success(Val, E);
17483 }
17484
17485 case Builtin::BI__builtin_popcount:
17486 case Builtin::BI__builtin_popcountl:
17487 case Builtin::BI__builtin_popcountll:
17488 case Builtin::BI__builtin_popcountg:
17489 case Builtin::BI__builtin_elementwise_popcount:
17490 case Builtin::BI__popcnt16: // Microsoft variants of popcount
17491 case Builtin::BI__popcnt:
17492 case Builtin::BI__popcnt64: {
17493 APSInt Val;
17494 if (E->getArg(0)->getType()->isExtVectorBoolType()) {
17495 APValue Vec;
17496 if (!EvaluateVector(E->getArg(0), Vec, Info))
17497 return false;
17498 Val = ConvertBoolVectorToInt(Vec);
17499 } else if (!EvaluateInteger(E->getArg(0), Val, Info)) {
17500 return false;
17501 }
17502
17503 return Success(Val.popcount(), E);
17504 }
17505
17506 case Builtin::BI__builtin_rotateleft8:
17507 case Builtin::BI__builtin_rotateleft16:
17508 case Builtin::BI__builtin_rotateleft32:
17509 case Builtin::BI__builtin_rotateleft64:
17510 case Builtin::BI__builtin_rotateright8:
17511 case Builtin::BI__builtin_rotateright16:
17512 case Builtin::BI__builtin_rotateright32:
17513 case Builtin::BI__builtin_rotateright64:
17514 case Builtin::BI__builtin_stdc_rotate_left:
17515 case Builtin::BI__builtin_stdc_rotate_right:
17516 case Builtin::BIstdc_rotate_left_uc:
17517 case Builtin::BIstdc_rotate_left_us:
17518 case Builtin::BIstdc_rotate_left_ui:
17519 case Builtin::BIstdc_rotate_left_ul:
17520 case Builtin::BIstdc_rotate_left_ull:
17521 case Builtin::BIstdc_rotate_right_uc:
17522 case Builtin::BIstdc_rotate_right_us:
17523 case Builtin::BIstdc_rotate_right_ui:
17524 case Builtin::BIstdc_rotate_right_ul:
17525 case Builtin::BIstdc_rotate_right_ull:
17526 case Builtin::BI_rotl8: // Microsoft variants of rotate left
17527 case Builtin::BI_rotl16:
17528 case Builtin::BI_rotl:
17529 case Builtin::BI_lrotl:
17530 case Builtin::BI_rotl64:
17531 case Builtin::BI_rotr8: // Microsoft variants of rotate right
17532 case Builtin::BI_rotr16:
17533 case Builtin::BI_rotr:
17534 case Builtin::BI_lrotr:
17535 case Builtin::BI_rotr64: {
17536 APSInt Value, Amount;
17537 if (!EvaluateInteger(E->getArg(0), Value, Info) ||
17538 !EvaluateInteger(E->getArg(1), Amount, Info))
17539 return false;
17540
17541 Amount = NormalizeRotateAmount(Value, Amount);
17542
17543 switch (BuiltinOp) {
17544 case Builtin::BI__builtin_rotateright8:
17545 case Builtin::BI__builtin_rotateright16:
17546 case Builtin::BI__builtin_rotateright32:
17547 case Builtin::BI__builtin_rotateright64:
17548 case Builtin::BI__builtin_stdc_rotate_right:
17549 case Builtin::BIstdc_rotate_right_uc:
17550 case Builtin::BIstdc_rotate_right_us:
17551 case Builtin::BIstdc_rotate_right_ui:
17552 case Builtin::BIstdc_rotate_right_ul:
17553 case Builtin::BIstdc_rotate_right_ull:
17554 case Builtin::BI_rotr8:
17555 case Builtin::BI_rotr16:
17556 case Builtin::BI_rotr:
17557 case Builtin::BI_lrotr:
17558 case Builtin::BI_rotr64:
17559 return Success(
17560 APSInt(Value.rotr(Amount.getZExtValue()), Value.isUnsigned()), E);
17561 default:
17562 return Success(
17563 APSInt(Value.rotl(Amount.getZExtValue()), Value.isUnsigned()), E);
17564 }
17565 }
17566
17567 case Builtin::BIstdc_leading_zeros_uc:
17568 case Builtin::BIstdc_leading_zeros_us:
17569 case Builtin::BIstdc_leading_zeros_ui:
17570 case Builtin::BIstdc_leading_zeros_ul:
17571 case Builtin::BIstdc_leading_zeros_ull:
17572 case Builtin::BIstdc_leading_ones_uc:
17573 case Builtin::BIstdc_leading_ones_us:
17574 case Builtin::BIstdc_leading_ones_ui:
17575 case Builtin::BIstdc_leading_ones_ul:
17576 case Builtin::BIstdc_leading_ones_ull:
17577 case Builtin::BIstdc_trailing_zeros_uc:
17578 case Builtin::BIstdc_trailing_zeros_us:
17579 case Builtin::BIstdc_trailing_zeros_ui:
17580 case Builtin::BIstdc_trailing_zeros_ul:
17581 case Builtin::BIstdc_trailing_zeros_ull:
17582 case Builtin::BIstdc_trailing_ones_uc:
17583 case Builtin::BIstdc_trailing_ones_us:
17584 case Builtin::BIstdc_trailing_ones_ui:
17585 case Builtin::BIstdc_trailing_ones_ul:
17586 case Builtin::BIstdc_trailing_ones_ull:
17587 case Builtin::BIstdc_first_leading_zero_uc:
17588 case Builtin::BIstdc_first_leading_zero_us:
17589 case Builtin::BIstdc_first_leading_zero_ui:
17590 case Builtin::BIstdc_first_leading_zero_ul:
17591 case Builtin::BIstdc_first_leading_zero_ull:
17592 case Builtin::BIstdc_first_leading_one_uc:
17593 case Builtin::BIstdc_first_leading_one_us:
17594 case Builtin::BIstdc_first_leading_one_ui:
17595 case Builtin::BIstdc_first_leading_one_ul:
17596 case Builtin::BIstdc_first_leading_one_ull:
17597 case Builtin::BIstdc_first_trailing_zero_uc:
17598 case Builtin::BIstdc_first_trailing_zero_us:
17599 case Builtin::BIstdc_first_trailing_zero_ui:
17600 case Builtin::BIstdc_first_trailing_zero_ul:
17601 case Builtin::BIstdc_first_trailing_zero_ull:
17602 case Builtin::BIstdc_first_trailing_one_uc:
17603 case Builtin::BIstdc_first_trailing_one_us:
17604 case Builtin::BIstdc_first_trailing_one_ui:
17605 case Builtin::BIstdc_first_trailing_one_ul:
17606 case Builtin::BIstdc_first_trailing_one_ull:
17607 case Builtin::BIstdc_count_zeros_uc:
17608 case Builtin::BIstdc_count_zeros_us:
17609 case Builtin::BIstdc_count_zeros_ui:
17610 case Builtin::BIstdc_count_zeros_ul:
17611 case Builtin::BIstdc_count_zeros_ull:
17612 case Builtin::BIstdc_count_ones_uc:
17613 case Builtin::BIstdc_count_ones_us:
17614 case Builtin::BIstdc_count_ones_ui:
17615 case Builtin::BIstdc_count_ones_ul:
17616 case Builtin::BIstdc_count_ones_ull:
17617 case Builtin::BIstdc_has_single_bit_uc:
17618 case Builtin::BIstdc_has_single_bit_us:
17619 case Builtin::BIstdc_has_single_bit_ui:
17620 case Builtin::BIstdc_has_single_bit_ul:
17621 case Builtin::BIstdc_has_single_bit_ull:
17622 case Builtin::BIstdc_bit_width_uc:
17623 case Builtin::BIstdc_bit_width_us:
17624 case Builtin::BIstdc_bit_width_ui:
17625 case Builtin::BIstdc_bit_width_ul:
17626 case Builtin::BIstdc_bit_width_ull:
17627 case Builtin::BIstdc_bit_floor_uc:
17628 case Builtin::BIstdc_bit_floor_us:
17629 case Builtin::BIstdc_bit_floor_ui:
17630 case Builtin::BIstdc_bit_floor_ul:
17631 case Builtin::BIstdc_bit_floor_ull:
17632 case Builtin::BIstdc_bit_ceil_uc:
17633 case Builtin::BIstdc_bit_ceil_us:
17634 case Builtin::BIstdc_bit_ceil_ui:
17635 case Builtin::BIstdc_bit_ceil_ul:
17636 case Builtin::BIstdc_bit_ceil_ull:
17637 case Builtin::BI__builtin_stdc_leading_zeros:
17638 case Builtin::BI__builtin_stdc_leading_ones:
17639 case Builtin::BI__builtin_stdc_trailing_zeros:
17640 case Builtin::BI__builtin_stdc_trailing_ones:
17641 case Builtin::BI__builtin_stdc_first_leading_zero:
17642 case Builtin::BI__builtin_stdc_first_leading_one:
17643 case Builtin::BI__builtin_stdc_first_trailing_zero:
17644 case Builtin::BI__builtin_stdc_first_trailing_one:
17645 case Builtin::BI__builtin_stdc_count_zeros:
17646 case Builtin::BI__builtin_stdc_count_ones:
17647 case Builtin::BI__builtin_stdc_has_single_bit:
17648 case Builtin::BI__builtin_stdc_bit_width:
17649 case Builtin::BI__builtin_stdc_bit_floor:
17650 case Builtin::BI__builtin_stdc_bit_ceil: {
17651 APSInt Val;
17652 if (!EvaluateInteger(E->getArg(0), Val, Info))
17653 return false;
17654
17655 unsigned BitWidth = Val.getBitWidth();
17656 const unsigned ResBitWidth = Info.Ctx.getIntWidth(E->getType());
17657
17658 switch (BuiltinOp) {
17659 case Builtin::BIstdc_leading_zeros_uc:
17660 case Builtin::BIstdc_leading_zeros_us:
17661 case Builtin::BIstdc_leading_zeros_ui:
17662 case Builtin::BIstdc_leading_zeros_ul:
17663 case Builtin::BIstdc_leading_zeros_ull:
17664 case Builtin::BI__builtin_stdc_leading_zeros:
17665 return Success(APInt(ResBitWidth, Val.countl_zero()), E);
17666 case Builtin::BIstdc_leading_ones_uc:
17667 case Builtin::BIstdc_leading_ones_us:
17668 case Builtin::BIstdc_leading_ones_ui:
17669 case Builtin::BIstdc_leading_ones_ul:
17670 case Builtin::BIstdc_leading_ones_ull:
17671 case Builtin::BI__builtin_stdc_leading_ones:
17672 return Success(APInt(ResBitWidth, Val.countl_one()), E);
17673 case Builtin::BIstdc_trailing_zeros_uc:
17674 case Builtin::BIstdc_trailing_zeros_us:
17675 case Builtin::BIstdc_trailing_zeros_ui:
17676 case Builtin::BIstdc_trailing_zeros_ul:
17677 case Builtin::BIstdc_trailing_zeros_ull:
17678 case Builtin::BI__builtin_stdc_trailing_zeros:
17679 return Success(APInt(ResBitWidth, Val.countr_zero()), E);
17680 case Builtin::BIstdc_trailing_ones_uc:
17681 case Builtin::BIstdc_trailing_ones_us:
17682 case Builtin::BIstdc_trailing_ones_ui:
17683 case Builtin::BIstdc_trailing_ones_ul:
17684 case Builtin::BIstdc_trailing_ones_ull:
17685 case Builtin::BI__builtin_stdc_trailing_ones:
17686 return Success(APInt(ResBitWidth, Val.countr_one()), E);
17687 case Builtin::BIstdc_first_leading_zero_uc:
17688 case Builtin::BIstdc_first_leading_zero_us:
17689 case Builtin::BIstdc_first_leading_zero_ui:
17690 case Builtin::BIstdc_first_leading_zero_ul:
17691 case Builtin::BIstdc_first_leading_zero_ull:
17692 case Builtin::BI__builtin_stdc_first_leading_zero:
17693 return Success(
17694 APInt(ResBitWidth, Val.isAllOnes() ? 0 : Val.countl_one() + 1), E);
17695 case Builtin::BIstdc_first_leading_one_uc:
17696 case Builtin::BIstdc_first_leading_one_us:
17697 case Builtin::BIstdc_first_leading_one_ui:
17698 case Builtin::BIstdc_first_leading_one_ul:
17699 case Builtin::BIstdc_first_leading_one_ull:
17700 case Builtin::BI__builtin_stdc_first_leading_one:
17701 return Success(
17702 APInt(ResBitWidth, Val.isZero() ? 0 : Val.countl_zero() + 1), E);
17703 case Builtin::BIstdc_first_trailing_zero_uc:
17704 case Builtin::BIstdc_first_trailing_zero_us:
17705 case Builtin::BIstdc_first_trailing_zero_ui:
17706 case Builtin::BIstdc_first_trailing_zero_ul:
17707 case Builtin::BIstdc_first_trailing_zero_ull:
17708 case Builtin::BI__builtin_stdc_first_trailing_zero:
17709 return Success(
17710 APInt(ResBitWidth, Val.isAllOnes() ? 0 : Val.countr_one() + 1), E);
17711 case Builtin::BIstdc_first_trailing_one_uc:
17712 case Builtin::BIstdc_first_trailing_one_us:
17713 case Builtin::BIstdc_first_trailing_one_ui:
17714 case Builtin::BIstdc_first_trailing_one_ul:
17715 case Builtin::BIstdc_first_trailing_one_ull:
17716 case Builtin::BI__builtin_stdc_first_trailing_one:
17717 return Success(
17718 APInt(ResBitWidth, Val.isZero() ? 0 : Val.countr_zero() + 1), E);
17719 case Builtin::BIstdc_count_zeros_uc:
17720 case Builtin::BIstdc_count_zeros_us:
17721 case Builtin::BIstdc_count_zeros_ui:
17722 case Builtin::BIstdc_count_zeros_ul:
17723 case Builtin::BIstdc_count_zeros_ull:
17724 case Builtin::BI__builtin_stdc_count_zeros: {
17725 APInt Cnt(ResBitWidth, BitWidth - Val.popcount());
17726 return Success(APSInt(Cnt, /*IsUnsigned*/ true), E);
17727 }
17728 case Builtin::BIstdc_count_ones_uc:
17729 case Builtin::BIstdc_count_ones_us:
17730 case Builtin::BIstdc_count_ones_ui:
17731 case Builtin::BIstdc_count_ones_ul:
17732 case Builtin::BIstdc_count_ones_ull:
17733 case Builtin::BI__builtin_stdc_count_ones: {
17734 APInt Cnt(ResBitWidth, Val.popcount());
17735 return Success(APSInt(Cnt, /*IsUnsigned*/ true), E);
17736 }
17737 case Builtin::BIstdc_has_single_bit_uc:
17738 case Builtin::BIstdc_has_single_bit_us:
17739 case Builtin::BIstdc_has_single_bit_ui:
17740 case Builtin::BIstdc_has_single_bit_ul:
17741 case Builtin::BIstdc_has_single_bit_ull:
17742 case Builtin::BI__builtin_stdc_has_single_bit: {
17743 APInt Res(ResBitWidth, Val.popcount() == 1 ? 1 : 0);
17744 return Success(APSInt(Res, /*IsUnsigned*/ true), E);
17745 }
17746 case Builtin::BIstdc_bit_width_uc:
17747 case Builtin::BIstdc_bit_width_us:
17748 case Builtin::BIstdc_bit_width_ui:
17749 case Builtin::BIstdc_bit_width_ul:
17750 case Builtin::BIstdc_bit_width_ull:
17751 case Builtin::BI__builtin_stdc_bit_width:
17752 return Success(APInt(ResBitWidth, BitWidth - Val.countl_zero()), E);
17753 case Builtin::BIstdc_bit_floor_uc:
17754 case Builtin::BIstdc_bit_floor_us:
17755 case Builtin::BIstdc_bit_floor_ui:
17756 case Builtin::BIstdc_bit_floor_ul:
17757 case Builtin::BIstdc_bit_floor_ull:
17758 case Builtin::BI__builtin_stdc_bit_floor: {
17759 if (Val.isZero())
17760 return Success(APInt(BitWidth, 0), E);
17761 unsigned Exp = BitWidth - Val.countl_zero() - 1;
17762 return Success(
17763 APSInt(APInt::getOneBitSet(BitWidth, Exp), /*IsUnsigned*/ true), E);
17764 }
17765 case Builtin::BIstdc_bit_ceil_uc:
17766 case Builtin::BIstdc_bit_ceil_us:
17767 case Builtin::BIstdc_bit_ceil_ui:
17768 case Builtin::BIstdc_bit_ceil_ul:
17769 case Builtin::BIstdc_bit_ceil_ull:
17770 case Builtin::BI__builtin_stdc_bit_ceil: {
17771 if (Val.ule(1))
17772 return Success(APSInt(APInt(BitWidth, 1), /*IsUnsigned*/ true), E);
17773 APInt ValMinusOne = Val - 1;
17774 unsigned LZ = ValMinusOne.countl_zero();
17775 if (LZ == 0)
17776 return Success(APSInt(APInt(BitWidth, 0), /*IsUnsigned*/ true),
17777 E); // overflows; wrap to 0
17778 APInt Result = APInt::getOneBitSet(BitWidth, BitWidth - LZ);
17779 return Success(APSInt(Result, /*IsUnsigned*/ true), E);
17780 }
17781 default:
17782 llvm_unreachable("Unknown stdc builtin");
17783 }
17784 }
17785
17786 case Builtin::BI__builtin_elementwise_add_sat: {
17787 APSInt LHS, RHS;
17788 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
17789 !EvaluateInteger(E->getArg(1), RHS, Info))
17790 return false;
17791
17792 APInt Result = LHS.isSigned() ? LHS.sadd_sat(RHS) : LHS.uadd_sat(RHS);
17793 return Success(APSInt(Result, !LHS.isSigned()), E);
17794 }
17795 case Builtin::BI__builtin_elementwise_sub_sat: {
17796 APSInt LHS, RHS;
17797 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
17798 !EvaluateInteger(E->getArg(1), RHS, Info))
17799 return false;
17800
17801 APInt Result = LHS.isSigned() ? LHS.ssub_sat(RHS) : LHS.usub_sat(RHS);
17802 return Success(APSInt(Result, !LHS.isSigned()), E);
17803 }
17804 case Builtin::BI__builtin_elementwise_max: {
17805 APSInt LHS, RHS;
17806 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
17807 !EvaluateInteger(E->getArg(1), RHS, Info))
17808 return false;
17809
17810 APInt Result = std::max(LHS, RHS);
17811 return Success(APSInt(Result, !LHS.isSigned()), E);
17812 }
17813 case Builtin::BI__builtin_elementwise_min: {
17814 APSInt LHS, RHS;
17815 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
17816 !EvaluateInteger(E->getArg(1), RHS, Info))
17817 return false;
17818
17819 APInt Result = std::min(LHS, RHS);
17820 return Success(APSInt(Result, !LHS.isSigned()), E);
17821 }
17822 case Builtin::BI__builtin_elementwise_clmul: {
17823 APSInt LHS, RHS;
17824 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
17825 !EvaluateInteger(E->getArg(1), RHS, Info))
17826 return false;
17827
17828 APInt Result = llvm::APIntOps::clmul(LHS, RHS);
17829 return Success(APSInt(Result, LHS.isUnsigned()), E);
17830 }
17831 case Builtin::BI__builtin_elementwise_fshl:
17832 case Builtin::BI__builtin_elementwise_fshr: {
17833 APSInt Hi, Lo, Shift;
17834 if (!EvaluateInteger(E->getArg(0), Hi, Info) ||
17835 !EvaluateInteger(E->getArg(1), Lo, Info) ||
17836 !EvaluateInteger(E->getArg(2), Shift, Info))
17837 return false;
17838
17839 switch (BuiltinOp) {
17840 case Builtin::BI__builtin_elementwise_fshl: {
17841 APSInt Result(llvm::APIntOps::fshl(Hi, Lo, Shift), Hi.isUnsigned());
17842 return Success(Result, E);
17843 }
17844 case Builtin::BI__builtin_elementwise_fshr: {
17845 APSInt Result(llvm::APIntOps::fshr(Hi, Lo, Shift), Hi.isUnsigned());
17846 return Success(Result, E);
17847 }
17848 }
17849 llvm_unreachable("Fully covered switch above");
17850 }
17851 case Builtin::BIstrlen:
17852 case Builtin::BIwcslen:
17853 // A call to strlen is not a constant expression.
17854 if (Info.getLangOpts().CPlusPlus11)
17855 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
17856 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
17857 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
17858 else
17859 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
17860 [[fallthrough]];
17861 case Builtin::BI__builtin_strlen:
17862 case Builtin::BI__builtin_wcslen: {
17863 // As an extension, we support __builtin_strlen() as a constant expression,
17864 // and support folding strlen() to a constant.
17865 if (std::optional<uint64_t> StrLen =
17866 EvaluateBuiltinStrLen(E->getArg(0), Info))
17867 return Success(*StrLen, E);
17868 return false;
17869 }
17870
17871 case Builtin::BIstrcmp:
17872 case Builtin::BIwcscmp:
17873 case Builtin::BIstrncmp:
17874 case Builtin::BIwcsncmp:
17875 case Builtin::BImemcmp:
17876 case Builtin::BIbcmp:
17877 case Builtin::BIwmemcmp:
17878 // A call to strlen is not a constant expression.
17879 if (Info.getLangOpts().CPlusPlus11)
17880 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
17881 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
17882 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
17883 else
17884 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
17885 [[fallthrough]];
17886 case Builtin::BI__builtin_strcmp:
17887 case Builtin::BI__builtin_wcscmp:
17888 case Builtin::BI__builtin_strncmp:
17889 case Builtin::BI__builtin_wcsncmp:
17890 case Builtin::BI__builtin_memcmp:
17891 case Builtin::BI__builtin_bcmp:
17892 case Builtin::BI__builtin_wmemcmp: {
17893 LValue String1, String2;
17894 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
17895 !EvaluatePointer(E->getArg(1), String2, Info))
17896 return false;
17897
17898 uint64_t MaxLength = uint64_t(-1);
17899 if (BuiltinOp != Builtin::BIstrcmp &&
17900 BuiltinOp != Builtin::BIwcscmp &&
17901 BuiltinOp != Builtin::BI__builtin_strcmp &&
17902 BuiltinOp != Builtin::BI__builtin_wcscmp) {
17903 APSInt N;
17904 if (!EvaluateInteger(E->getArg(2), N, Info))
17905 return false;
17906 MaxLength = N.getZExtValue();
17907 }
17908
17909 // Empty substrings compare equal by definition.
17910 if (MaxLength == 0u)
17911 return Success(0, E);
17912
17913 if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
17914 !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
17915 String1.Designator.Invalid || String2.Designator.Invalid)
17916 return false;
17917
17918 QualType CharTy1 = String1.Designator.getType(Info.Ctx);
17919 QualType CharTy2 = String2.Designator.getType(Info.Ctx);
17920
17921 bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
17922 BuiltinOp == Builtin::BIbcmp ||
17923 BuiltinOp == Builtin::BI__builtin_memcmp ||
17924 BuiltinOp == Builtin::BI__builtin_bcmp;
17925
17926 assert(IsRawByte ||
17927 (Info.Ctx.hasSameUnqualifiedType(
17928 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
17929 Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
17930
17931 // For memcmp, allow comparing any arrays of '[[un]signed] char' or
17932 // 'char8_t', but no other types.
17933 if (IsRawByte &&
17934 !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) {
17935 // FIXME: Consider using our bit_cast implementation to support this.
17936 Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported)
17937 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp) << CharTy1
17938 << CharTy2;
17939 return false;
17940 }
17941
17942 const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
17943 return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
17944 handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
17945 Char1.isInt() && Char2.isInt();
17946 };
17947 const auto &AdvanceElems = [&] {
17948 return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
17949 HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
17950 };
17951
17952 bool StopAtNull =
17953 (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
17954 BuiltinOp != Builtin::BIwmemcmp &&
17955 BuiltinOp != Builtin::BI__builtin_memcmp &&
17956 BuiltinOp != Builtin::BI__builtin_bcmp &&
17957 BuiltinOp != Builtin::BI__builtin_wmemcmp);
17958 bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
17959 BuiltinOp == Builtin::BIwcsncmp ||
17960 BuiltinOp == Builtin::BIwmemcmp ||
17961 BuiltinOp == Builtin::BI__builtin_wcscmp ||
17962 BuiltinOp == Builtin::BI__builtin_wcsncmp ||
17963 BuiltinOp == Builtin::BI__builtin_wmemcmp;
17964
17965 for (; MaxLength; --MaxLength) {
17966 APValue Char1, Char2;
17967 if (!ReadCurElems(Char1, Char2))
17968 return false;
17969 if (Char1.getInt().ne(Char2.getInt())) {
17970 if (IsWide) // wmemcmp compares with wchar_t signedness.
17971 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
17972 // memcmp always compares unsigned chars.
17973 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
17974 }
17975 if (StopAtNull && !Char1.getInt())
17976 return Success(0, E);
17977 assert(!(StopAtNull && !Char2.getInt()));
17978 if (!AdvanceElems())
17979 return false;
17980 }
17981 // We hit the strncmp / memcmp limit.
17982 return Success(0, E);
17983 }
17984
17985 case Builtin::BI__atomic_always_lock_free:
17986 case Builtin::BI__atomic_is_lock_free:
17987 case Builtin::BI__c11_atomic_is_lock_free: {
17988 APSInt SizeVal;
17989 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
17990 return false;
17991
17992 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
17993 // of two less than or equal to the maximum inline atomic width, we know it
17994 // is lock-free. If the size isn't a power of two, or greater than the
17995 // maximum alignment where we promote atomics, we know it is not lock-free
17996 // (at least not in the sense of atomic_is_lock_free). Otherwise,
17997 // the answer can only be determined at runtime; for example, 16-byte
17998 // atomics have lock-free implementations on some, but not all,
17999 // x86-64 processors.
18000
18001 // Check power-of-two.
18002 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
18003 if (Size.isPowerOfTwo()) {
18004 // Check against inlining width.
18005 unsigned InlineWidthBits =
18006 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
18007 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
18008 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
18009 Size == CharUnits::One())
18010 return Success(1, E);
18011
18012 // If the pointer argument can be evaluated to a compile-time constant
18013 // integer (or nullptr), check if that value is appropriately aligned.
18014 const Expr *PtrArg = E->getArg(1);
18015 Expr::EvalResult ExprResult;
18016 APSInt IntResult;
18017 if (PtrArg->EvaluateAsRValue(ExprResult, Info.Ctx) &&
18018 ExprResult.Val.toIntegralConstant(IntResult, PtrArg->getType(),
18019 Info.Ctx) &&
18020 IntResult.isAligned(Size.getAsAlign()))
18021 return Success(1, E);
18022
18023 // Otherwise, check if the type's alignment against Size.
18024 if (auto *ICE = dyn_cast<ImplicitCastExpr>(PtrArg)) {
18025 // Drop the potential implicit-cast to 'const volatile void*', getting
18026 // the underlying type.
18027 if (ICE->getCastKind() == CK_BitCast)
18028 PtrArg = ICE->getSubExpr();
18029 }
18030
18031 if (auto PtrTy = PtrArg->getType()->getAs<PointerType>()) {
18032 QualType PointeeType = PtrTy->getPointeeType();
18033 if (!PointeeType->isIncompleteType() &&
18034 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
18035 // OK, we will inline operations on this object.
18036 return Success(1, E);
18037 }
18038 }
18039 }
18040 }
18041
18042 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
18043 Success(0, E) : Error(E);
18044 }
18045 case Builtin::BI__builtin_addcb:
18046 case Builtin::BI__builtin_addcs:
18047 case Builtin::BI__builtin_addc:
18048 case Builtin::BI__builtin_addcl:
18049 case Builtin::BI__builtin_addcll:
18050 case Builtin::BI__builtin_subcb:
18051 case Builtin::BI__builtin_subcs:
18052 case Builtin::BI__builtin_subc:
18053 case Builtin::BI__builtin_subcl:
18054 case Builtin::BI__builtin_subcll: {
18055 LValue CarryOutLValue;
18056 APSInt LHS, RHS, CarryIn, CarryOut, Result;
18057 QualType ResultType = E->getArg(0)->getType();
18058 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
18059 !EvaluateInteger(E->getArg(1), RHS, Info) ||
18060 !EvaluateInteger(E->getArg(2), CarryIn, Info) ||
18061 !EvaluatePointer(E->getArg(3), CarryOutLValue, Info))
18062 return false;
18063 // Copy the number of bits and sign.
18064 Result = LHS;
18065 CarryOut = LHS;
18066
18067 bool FirstOverflowed = false;
18068 bool SecondOverflowed = false;
18069 switch (BuiltinOp) {
18070 default:
18071 llvm_unreachable("Invalid value for BuiltinOp");
18072 case Builtin::BI__builtin_addcb:
18073 case Builtin::BI__builtin_addcs:
18074 case Builtin::BI__builtin_addc:
18075 case Builtin::BI__builtin_addcl:
18076 case Builtin::BI__builtin_addcll:
18077 Result =
18078 LHS.uadd_ov(RHS, FirstOverflowed).uadd_ov(CarryIn, SecondOverflowed);
18079 break;
18080 case Builtin::BI__builtin_subcb:
18081 case Builtin::BI__builtin_subcs:
18082 case Builtin::BI__builtin_subc:
18083 case Builtin::BI__builtin_subcl:
18084 case Builtin::BI__builtin_subcll:
18085 Result =
18086 LHS.usub_ov(RHS, FirstOverflowed).usub_ov(CarryIn, SecondOverflowed);
18087 break;
18088 }
18089
18090 // It is possible for both overflows to happen but CGBuiltin uses an OR so
18091 // this is consistent.
18092 CarryOut = (uint64_t)(FirstOverflowed | SecondOverflowed);
18093 APValue APV{CarryOut};
18094 if (!handleAssignment(Info, E, CarryOutLValue, ResultType, APV))
18095 return false;
18096 return Success(Result, E);
18097 }
18098 case Builtin::BI__builtin_add_overflow:
18099 case Builtin::BI__builtin_sub_overflow:
18100 case Builtin::BI__builtin_mul_overflow:
18101 case Builtin::BI__builtin_sadd_overflow:
18102 case Builtin::BI__builtin_uadd_overflow:
18103 case Builtin::BI__builtin_uaddl_overflow:
18104 case Builtin::BI__builtin_uaddll_overflow:
18105 case Builtin::BI__builtin_usub_overflow:
18106 case Builtin::BI__builtin_usubl_overflow:
18107 case Builtin::BI__builtin_usubll_overflow:
18108 case Builtin::BI__builtin_umul_overflow:
18109 case Builtin::BI__builtin_umull_overflow:
18110 case Builtin::BI__builtin_umulll_overflow:
18111 case Builtin::BI__builtin_saddl_overflow:
18112 case Builtin::BI__builtin_saddll_overflow:
18113 case Builtin::BI__builtin_ssub_overflow:
18114 case Builtin::BI__builtin_ssubl_overflow:
18115 case Builtin::BI__builtin_ssubll_overflow:
18116 case Builtin::BI__builtin_smul_overflow:
18117 case Builtin::BI__builtin_smull_overflow:
18118 case Builtin::BI__builtin_smulll_overflow: {
18119 LValue ResultLValue;
18120 APSInt LHS, RHS;
18121
18122 QualType ResultType = E->getArg(2)->getType()->getPointeeType();
18123 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
18124 !EvaluateInteger(E->getArg(1), RHS, Info) ||
18125 !EvaluatePointer(E->getArg(2), ResultLValue, Info))
18126 return false;
18127
18128 APSInt Result;
18129 bool DidOverflow = false;
18130
18131 // If the types don't have to match, enlarge all 3 to the largest of them.
18132 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
18133 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
18134 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
18135 bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
18137 bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
18139 uint64_t LHSSize = LHS.getBitWidth();
18140 uint64_t RHSSize = RHS.getBitWidth();
18141 uint64_t ResultSize = Info.Ctx.getIntWidth(ResultType);
18142 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
18143
18144 // Add an additional bit if the signedness isn't uniformly agreed to. We
18145 // could do this ONLY if there is a signed and an unsigned that both have
18146 // MaxBits, but the code to check that is pretty nasty. The issue will be
18147 // caught in the shrink-to-result later anyway.
18148 if (IsSigned && !AllSigned)
18149 ++MaxBits;
18150
18151 LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
18152 RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
18153 Result = APSInt(MaxBits, !IsSigned);
18154 }
18155
18156 // Find largest int.
18157 switch (BuiltinOp) {
18158 default:
18159 llvm_unreachable("Invalid value for BuiltinOp");
18160 case Builtin::BI__builtin_add_overflow:
18161 case Builtin::BI__builtin_sadd_overflow:
18162 case Builtin::BI__builtin_saddl_overflow:
18163 case Builtin::BI__builtin_saddll_overflow:
18164 case Builtin::BI__builtin_uadd_overflow:
18165 case Builtin::BI__builtin_uaddl_overflow:
18166 case Builtin::BI__builtin_uaddll_overflow:
18167 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
18168 : LHS.uadd_ov(RHS, DidOverflow);
18169 break;
18170 case Builtin::BI__builtin_sub_overflow:
18171 case Builtin::BI__builtin_ssub_overflow:
18172 case Builtin::BI__builtin_ssubl_overflow:
18173 case Builtin::BI__builtin_ssubll_overflow:
18174 case Builtin::BI__builtin_usub_overflow:
18175 case Builtin::BI__builtin_usubl_overflow:
18176 case Builtin::BI__builtin_usubll_overflow:
18177 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
18178 : LHS.usub_ov(RHS, DidOverflow);
18179 break;
18180 case Builtin::BI__builtin_mul_overflow:
18181 case Builtin::BI__builtin_smul_overflow:
18182 case Builtin::BI__builtin_smull_overflow:
18183 case Builtin::BI__builtin_smulll_overflow:
18184 case Builtin::BI__builtin_umul_overflow:
18185 case Builtin::BI__builtin_umull_overflow:
18186 case Builtin::BI__builtin_umulll_overflow:
18187 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
18188 : LHS.umul_ov(RHS, DidOverflow);
18189 break;
18190 }
18191
18192 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
18193 // since it will give us the behavior of a TruncOrSelf in the case where
18194 // its parameter <= its size. We previously set Result to be at least the
18195 // integer width of the result, so getIntWidth(ResultType) <=
18196 // Result.BitWidth will work exactly like TruncOrSelf.
18197 APSInt Temp = Result.extOrTrunc(Info.Ctx.getIntWidth(ResultType));
18198 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
18199
18200 // In the case where multiple sizes are allowed, truncate and see if
18201 // the values are the same.
18202 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
18203 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
18204 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
18205 if (!APSInt::isSameValue(Temp, Result))
18206 DidOverflow = true;
18207 }
18208 Result = Temp;
18209
18210 APValue APV{Result};
18211 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
18212 return false;
18213 return Success(DidOverflow, E);
18214 }
18215
18216 case Builtin::BI__builtin_reduce_add:
18217 case Builtin::BI__builtin_reduce_mul:
18218 case Builtin::BI__builtin_reduce_and:
18219 case Builtin::BI__builtin_reduce_or:
18220 case Builtin::BI__builtin_reduce_xor:
18221 case Builtin::BI__builtin_reduce_min:
18222 case Builtin::BI__builtin_reduce_max: {
18223 APValue Source;
18224 if (!EvaluateAsRValue(Info, E->getArg(0), Source))
18225 return false;
18226
18227 unsigned SourceLen = Source.getVectorLength();
18228 APSInt Reduced = Source.getVectorElt(0).getInt();
18229 for (unsigned EltNum = 1; EltNum < SourceLen; ++EltNum) {
18230 switch (BuiltinOp) {
18231 default:
18232 return false;
18233 case Builtin::BI__builtin_reduce_add: {
18235 Info, E, Reduced, Source.getVectorElt(EltNum).getInt(),
18236 Reduced.getBitWidth() + 1, std::plus<APSInt>(), Reduced))
18237 return false;
18238 break;
18239 }
18240 case Builtin::BI__builtin_reduce_mul: {
18242 Info, E, Reduced, Source.getVectorElt(EltNum).getInt(),
18243 Reduced.getBitWidth() * 2, std::multiplies<APSInt>(), Reduced))
18244 return false;
18245 break;
18246 }
18247 case Builtin::BI__builtin_reduce_and: {
18248 Reduced &= Source.getVectorElt(EltNum).getInt();
18249 break;
18250 }
18251 case Builtin::BI__builtin_reduce_or: {
18252 Reduced |= Source.getVectorElt(EltNum).getInt();
18253 break;
18254 }
18255 case Builtin::BI__builtin_reduce_xor: {
18256 Reduced ^= Source.getVectorElt(EltNum).getInt();
18257 break;
18258 }
18259 case Builtin::BI__builtin_reduce_min: {
18260 Reduced = std::min(Reduced, Source.getVectorElt(EltNum).getInt());
18261 break;
18262 }
18263 case Builtin::BI__builtin_reduce_max: {
18264 Reduced = std::max(Reduced, Source.getVectorElt(EltNum).getInt());
18265 break;
18266 }
18267 }
18268 }
18269
18270 return Success(Reduced, E);
18271 }
18272
18273 case clang::X86::BI__builtin_ia32_addcarryx_u32:
18274 case clang::X86::BI__builtin_ia32_addcarryx_u64:
18275 case clang::X86::BI__builtin_ia32_subborrow_u32:
18276 case clang::X86::BI__builtin_ia32_subborrow_u64: {
18277 LValue ResultLValue;
18278 APSInt CarryIn, LHS, RHS;
18279 QualType ResultType = E->getArg(3)->getType()->getPointeeType();
18280 if (!EvaluateInteger(E->getArg(0), CarryIn, Info) ||
18281 !EvaluateInteger(E->getArg(1), LHS, Info) ||
18282 !EvaluateInteger(E->getArg(2), RHS, Info) ||
18283 !EvaluatePointer(E->getArg(3), ResultLValue, Info))
18284 return false;
18285
18286 bool IsAdd = BuiltinOp == clang::X86::BI__builtin_ia32_addcarryx_u32 ||
18287 BuiltinOp == clang::X86::BI__builtin_ia32_addcarryx_u64;
18288
18289 unsigned BitWidth = LHS.getBitWidth();
18290 unsigned CarryInBit = CarryIn.ugt(0) ? 1 : 0;
18291 APInt ExResult =
18292 IsAdd
18293 ? (LHS.zext(BitWidth + 1) + (RHS.zext(BitWidth + 1) + CarryInBit))
18294 : (LHS.zext(BitWidth + 1) - (RHS.zext(BitWidth + 1) + CarryInBit));
18295
18296 APInt Result = ExResult.extractBits(BitWidth, 0);
18297 uint64_t CarryOut = ExResult.extractBitsAsZExtValue(1, BitWidth);
18298
18299 APValue APV{APSInt(Result, /*isUnsigned=*/true)};
18300 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
18301 return false;
18302 return Success(CarryOut, E);
18303 }
18304
18305 case clang::X86::BI__builtin_ia32_movmskps:
18306 case clang::X86::BI__builtin_ia32_movmskpd:
18307 case clang::X86::BI__builtin_ia32_pmovmskb128:
18308 case clang::X86::BI__builtin_ia32_pmovmskb256:
18309 case clang::X86::BI__builtin_ia32_movmskps256:
18310 case clang::X86::BI__builtin_ia32_movmskpd256: {
18311 APValue Source;
18312 if (!Evaluate(Source, Info, E->getArg(0)))
18313 return false;
18314 unsigned SourceLen = Source.getVectorLength();
18315 const VectorType *VT = E->getArg(0)->getType()->castAs<VectorType>();
18316 QualType ElemQT = VT->getElementType();
18317 unsigned ResultLen = Info.Ctx.getTypeSize(
18318 E->getCallReturnType(Info.Ctx)); // Always 32-bit integer.
18319 APInt Result(ResultLen, 0);
18320
18321 for (unsigned I = 0; I != SourceLen; ++I) {
18322 APInt Elem;
18323 if (ElemQT->isIntegerType()) {
18324 Elem = Source.getVectorElt(I).getInt();
18325 } else if (ElemQT->isRealFloatingType()) {
18326 Elem = Source.getVectorElt(I).getFloat().bitcastToAPInt();
18327 } else {
18328 return false;
18329 }
18330 Result.setBitVal(I, Elem.isNegative());
18331 }
18332 return Success(Result, E);
18333 }
18334
18335 case clang::X86::BI__builtin_ia32_bextr_u32:
18336 case clang::X86::BI__builtin_ia32_bextr_u64:
18337 case clang::X86::BI__builtin_ia32_bextri_u32:
18338 case clang::X86::BI__builtin_ia32_bextri_u64: {
18339 APSInt Val, Idx;
18340 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
18341 !EvaluateInteger(E->getArg(1), Idx, Info))
18342 return false;
18343
18344 unsigned BitWidth = Val.getBitWidth();
18345 uint64_t Shift = Idx.extractBitsAsZExtValue(8, 0);
18346 uint64_t Length = Idx.extractBitsAsZExtValue(8, 8);
18347 Length = Length > BitWidth ? BitWidth : Length;
18348
18349 // Handle out of bounds cases.
18350 if (Length == 0 || Shift >= BitWidth)
18351 return Success(0, E);
18352
18353 uint64_t Result = Val.getZExtValue() >> Shift;
18354 Result &= llvm::maskTrailingOnes<uint64_t>(Length);
18355 return Success(Result, E);
18356 }
18357
18358 case clang::X86::BI__builtin_ia32_bzhi_si:
18359 case clang::X86::BI__builtin_ia32_bzhi_di: {
18360 APSInt Val, Idx;
18361 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
18362 !EvaluateInteger(E->getArg(1), Idx, Info))
18363 return false;
18364
18365 unsigned BitWidth = Val.getBitWidth();
18366 unsigned Index = Idx.extractBitsAsZExtValue(8, 0);
18367 if (Index < BitWidth)
18368 Val.clearHighBits(BitWidth - Index);
18369 return Success(Val, E);
18370 }
18371
18372 case clang::X86::BI__builtin_ia32_ktestcqi:
18373 case clang::X86::BI__builtin_ia32_ktestchi:
18374 case clang::X86::BI__builtin_ia32_ktestcsi:
18375 case clang::X86::BI__builtin_ia32_ktestcdi: {
18376 APSInt A, B;
18377 if (!EvaluateInteger(E->getArg(0), A, Info) ||
18378 !EvaluateInteger(E->getArg(1), B, Info))
18379 return false;
18380
18381 return Success((~A & B) == 0, E);
18382 }
18383
18384 case clang::X86::BI__builtin_ia32_ktestzqi:
18385 case clang::X86::BI__builtin_ia32_ktestzhi:
18386 case clang::X86::BI__builtin_ia32_ktestzsi:
18387 case clang::X86::BI__builtin_ia32_ktestzdi: {
18388 APSInt A, B;
18389 if (!EvaluateInteger(E->getArg(0), A, Info) ||
18390 !EvaluateInteger(E->getArg(1), B, Info))
18391 return false;
18392
18393 return Success((A & B) == 0, E);
18394 }
18395
18396 case clang::X86::BI__builtin_ia32_kortestcqi:
18397 case clang::X86::BI__builtin_ia32_kortestchi:
18398 case clang::X86::BI__builtin_ia32_kortestcsi:
18399 case clang::X86::BI__builtin_ia32_kortestcdi: {
18400 APSInt A, B;
18401 if (!EvaluateInteger(E->getArg(0), A, Info) ||
18402 !EvaluateInteger(E->getArg(1), B, Info))
18403 return false;
18404
18405 return Success(~(A | B) == 0, E);
18406 }
18407
18408 case clang::X86::BI__builtin_ia32_kortestzqi:
18409 case clang::X86::BI__builtin_ia32_kortestzhi:
18410 case clang::X86::BI__builtin_ia32_kortestzsi:
18411 case clang::X86::BI__builtin_ia32_kortestzdi: {
18412 APSInt A, B;
18413 if (!EvaluateInteger(E->getArg(0), A, Info) ||
18414 !EvaluateInteger(E->getArg(1), B, Info))
18415 return false;
18416
18417 return Success((A | B) == 0, E);
18418 }
18419
18420 case clang::X86::BI__builtin_ia32_kunpckhi:
18421 case clang::X86::BI__builtin_ia32_kunpckdi:
18422 case clang::X86::BI__builtin_ia32_kunpcksi: {
18423 APSInt A, B;
18424 if (!EvaluateInteger(E->getArg(0), A, Info) ||
18425 !EvaluateInteger(E->getArg(1), B, Info))
18426 return false;
18427
18428 // Generic kunpack: extract lower half of each operand and concatenate
18429 // Result = A[HalfWidth-1:0] concat B[HalfWidth-1:0]
18430 unsigned BW = A.getBitWidth();
18431 APSInt Result(A.trunc(BW / 2).concat(B.trunc(BW / 2)), A.isUnsigned());
18432 return Success(Result, E);
18433 }
18434
18435 case clang::X86::BI__builtin_ia32_lzcnt_u16:
18436 case clang::X86::BI__builtin_ia32_lzcnt_u32:
18437 case clang::X86::BI__builtin_ia32_lzcnt_u64: {
18438 APSInt Val;
18439 if (!EvaluateInteger(E->getArg(0), Val, Info))
18440 return false;
18441 return Success(Val.countLeadingZeros(), E);
18442 }
18443
18444 case clang::X86::BI__builtin_ia32_tzcnt_u16:
18445 case clang::X86::BI__builtin_ia32_tzcnt_u32:
18446 case clang::X86::BI__builtin_ia32_tzcnt_u64: {
18447 APSInt Val;
18448 if (!EvaluateInteger(E->getArg(0), Val, Info))
18449 return false;
18450 return Success(Val.countTrailingZeros(), E);
18451 }
18452
18453 case Builtin::BI__builtin_elementwise_pdep: {
18454 APSInt Val, Msk;
18455 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
18456 !EvaluateInteger(E->getArg(1), Msk, Info))
18457 return false;
18458 return Success(llvm::APIntOps::pdep(Val, Msk), E);
18459 }
18460
18461 case Builtin::BI__builtin_elementwise_pext: {
18462 APSInt Val, Msk;
18463 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
18464 !EvaluateInteger(E->getArg(1), Msk, Info))
18465 return false;
18466 return Success(llvm::APIntOps::pext(Val, Msk), E);
18467 }
18468
18469 case X86::BI__builtin_ia32_ptestz128:
18470 case X86::BI__builtin_ia32_ptestz256:
18471 case X86::BI__builtin_ia32_vtestzps:
18472 case X86::BI__builtin_ia32_vtestzps256:
18473 case X86::BI__builtin_ia32_vtestzpd:
18474 case X86::BI__builtin_ia32_vtestzpd256: {
18475 return EvalTestOp(
18476 [](const APInt &A, const APInt &B) { return (A & B) == 0; });
18477 }
18478 case X86::BI__builtin_ia32_ptestc128:
18479 case X86::BI__builtin_ia32_ptestc256:
18480 case X86::BI__builtin_ia32_vtestcps:
18481 case X86::BI__builtin_ia32_vtestcps256:
18482 case X86::BI__builtin_ia32_vtestcpd:
18483 case X86::BI__builtin_ia32_vtestcpd256: {
18484 return EvalTestOp(
18485 [](const APInt &A, const APInt &B) { return (~A & B) == 0; });
18486 }
18487 case X86::BI__builtin_ia32_ptestnzc128:
18488 case X86::BI__builtin_ia32_ptestnzc256:
18489 case X86::BI__builtin_ia32_vtestnzcps:
18490 case X86::BI__builtin_ia32_vtestnzcps256:
18491 case X86::BI__builtin_ia32_vtestnzcpd:
18492 case X86::BI__builtin_ia32_vtestnzcpd256: {
18493 return EvalTestOp([](const APInt &A, const APInt &B) {
18494 return ((A & B) != 0) && ((~A & B) != 0);
18495 });
18496 }
18497 case X86::BI__builtin_ia32_kandqi:
18498 case X86::BI__builtin_ia32_kandhi:
18499 case X86::BI__builtin_ia32_kandsi:
18500 case X86::BI__builtin_ia32_kanddi: {
18501 return HandleMaskBinOp(
18502 [](const APSInt &LHS, const APSInt &RHS) { return LHS & RHS; });
18503 }
18504
18505 case X86::BI__builtin_ia32_kandnqi:
18506 case X86::BI__builtin_ia32_kandnhi:
18507 case X86::BI__builtin_ia32_kandnsi:
18508 case X86::BI__builtin_ia32_kandndi: {
18509 return HandleMaskBinOp(
18510 [](const APSInt &LHS, const APSInt &RHS) { return ~LHS & RHS; });
18511 }
18512
18513 case X86::BI__builtin_ia32_korqi:
18514 case X86::BI__builtin_ia32_korhi:
18515 case X86::BI__builtin_ia32_korsi:
18516 case X86::BI__builtin_ia32_kordi: {
18517 return HandleMaskBinOp(
18518 [](const APSInt &LHS, const APSInt &RHS) { return LHS | RHS; });
18519 }
18520
18521 case X86::BI__builtin_ia32_kxnorqi:
18522 case X86::BI__builtin_ia32_kxnorhi:
18523 case X86::BI__builtin_ia32_kxnorsi:
18524 case X86::BI__builtin_ia32_kxnordi: {
18525 return HandleMaskBinOp(
18526 [](const APSInt &LHS, const APSInt &RHS) { return ~(LHS ^ RHS); });
18527 }
18528
18529 case X86::BI__builtin_ia32_kxorqi:
18530 case X86::BI__builtin_ia32_kxorhi:
18531 case X86::BI__builtin_ia32_kxorsi:
18532 case X86::BI__builtin_ia32_kxordi: {
18533 return HandleMaskBinOp(
18534 [](const APSInt &LHS, const APSInt &RHS) { return LHS ^ RHS; });
18535 }
18536
18537 case X86::BI__builtin_ia32_knotqi:
18538 case X86::BI__builtin_ia32_knothi:
18539 case X86::BI__builtin_ia32_knotsi:
18540 case X86::BI__builtin_ia32_knotdi: {
18541 APSInt Val;
18542 if (!EvaluateInteger(E->getArg(0), Val, Info))
18543 return false;
18544 APSInt Result = ~Val;
18545 return Success(APValue(Result), E);
18546 }
18547
18548 case X86::BI__builtin_ia32_kaddqi:
18549 case X86::BI__builtin_ia32_kaddhi:
18550 case X86::BI__builtin_ia32_kaddsi:
18551 case X86::BI__builtin_ia32_kadddi: {
18552 return HandleMaskBinOp(
18553 [](const APSInt &LHS, const APSInt &RHS) { return LHS + RHS; });
18554 }
18555
18556 case X86::BI__builtin_ia32_kmovb:
18557 case X86::BI__builtin_ia32_kmovw:
18558 case X86::BI__builtin_ia32_kmovd:
18559 case X86::BI__builtin_ia32_kmovq: {
18560 APSInt Val;
18561 if (!EvaluateInteger(E->getArg(0), Val, Info))
18562 return false;
18563 return Success(Val, E);
18564 }
18565
18566 case X86::BI__builtin_ia32_kshiftliqi:
18567 case X86::BI__builtin_ia32_kshiftlihi:
18568 case X86::BI__builtin_ia32_kshiftlisi:
18569 case X86::BI__builtin_ia32_kshiftlidi: {
18570 return HandleMaskBinOp([](const APSInt &LHS, const APSInt &RHS) {
18571 unsigned Amt = RHS.getZExtValue() & 0xFF;
18572 if (Amt >= LHS.getBitWidth())
18573 return APSInt(APInt::getZero(LHS.getBitWidth()), LHS.isUnsigned());
18574 return APSInt(LHS.shl(Amt), LHS.isUnsigned());
18575 });
18576 }
18577
18578 case X86::BI__builtin_ia32_kshiftriqi:
18579 case X86::BI__builtin_ia32_kshiftrihi:
18580 case X86::BI__builtin_ia32_kshiftrisi:
18581 case X86::BI__builtin_ia32_kshiftridi: {
18582 return HandleMaskBinOp([](const APSInt &LHS, const APSInt &RHS) {
18583 unsigned Amt = RHS.getZExtValue() & 0xFF;
18584 if (Amt >= LHS.getBitWidth())
18585 return APSInt(APInt::getZero(LHS.getBitWidth()), LHS.isUnsigned());
18586 return APSInt(LHS.lshr(Amt), LHS.isUnsigned());
18587 });
18588 }
18589
18590 case clang::X86::BI__builtin_ia32_vec_ext_v4hi:
18591 case clang::X86::BI__builtin_ia32_vec_ext_v16qi:
18592 case clang::X86::BI__builtin_ia32_vec_ext_v8hi:
18593 case clang::X86::BI__builtin_ia32_vec_ext_v4si:
18594 case clang::X86::BI__builtin_ia32_vec_ext_v2di:
18595 case clang::X86::BI__builtin_ia32_vec_ext_v32qi:
18596 case clang::X86::BI__builtin_ia32_vec_ext_v16hi:
18597 case clang::X86::BI__builtin_ia32_vec_ext_v8si:
18598 case clang::X86::BI__builtin_ia32_vec_ext_v4di: {
18599 APValue Vec;
18600 APSInt IdxAPS;
18601 if (!EvaluateVector(E->getArg(0), Vec, Info) ||
18602 !EvaluateInteger(E->getArg(1), IdxAPS, Info))
18603 return false;
18604 unsigned N = Vec.getVectorLength();
18605 unsigned Idx = static_cast<unsigned>(IdxAPS.getZExtValue() & (N - 1));
18606 return Success(Vec.getVectorElt(Idx).getInt(), E);
18607 }
18608
18609 case clang::X86::BI__builtin_ia32_cvtb2mask128:
18610 case clang::X86::BI__builtin_ia32_cvtb2mask256:
18611 case clang::X86::BI__builtin_ia32_cvtb2mask512:
18612 case clang::X86::BI__builtin_ia32_cvtw2mask128:
18613 case clang::X86::BI__builtin_ia32_cvtw2mask256:
18614 case clang::X86::BI__builtin_ia32_cvtw2mask512:
18615 case clang::X86::BI__builtin_ia32_cvtd2mask128:
18616 case clang::X86::BI__builtin_ia32_cvtd2mask256:
18617 case clang::X86::BI__builtin_ia32_cvtd2mask512:
18618 case clang::X86::BI__builtin_ia32_cvtq2mask128:
18619 case clang::X86::BI__builtin_ia32_cvtq2mask256:
18620 case clang::X86::BI__builtin_ia32_cvtq2mask512: {
18621 assert(E->getNumArgs() == 1);
18622 APValue Vec;
18623 if (!EvaluateVector(E->getArg(0), Vec, Info))
18624 return false;
18625
18626 unsigned VectorLen = Vec.getVectorLength();
18627 unsigned RetWidth = Info.Ctx.getIntWidth(E->getType());
18628 llvm::APInt Bits(RetWidth, 0);
18629
18630 for (unsigned ElemNum = 0; ElemNum != VectorLen; ++ElemNum) {
18631 const APSInt &A = Vec.getVectorElt(ElemNum).getInt();
18632 unsigned MSB = A[A.getBitWidth() - 1];
18633 Bits.setBitVal(ElemNum, MSB);
18634 }
18635
18636 APSInt RetMask(Bits, /*isUnsigned=*/true);
18637 return Success(APValue(RetMask), E);
18638 }
18639
18640 case clang::X86::BI__builtin_ia32_cmpb128_mask:
18641 case clang::X86::BI__builtin_ia32_cmpw128_mask:
18642 case clang::X86::BI__builtin_ia32_cmpd128_mask:
18643 case clang::X86::BI__builtin_ia32_cmpq128_mask:
18644 case clang::X86::BI__builtin_ia32_cmpb256_mask:
18645 case clang::X86::BI__builtin_ia32_cmpw256_mask:
18646 case clang::X86::BI__builtin_ia32_cmpd256_mask:
18647 case clang::X86::BI__builtin_ia32_cmpq256_mask:
18648 case clang::X86::BI__builtin_ia32_cmpb512_mask:
18649 case clang::X86::BI__builtin_ia32_cmpw512_mask:
18650 case clang::X86::BI__builtin_ia32_cmpd512_mask:
18651 case clang::X86::BI__builtin_ia32_cmpq512_mask:
18652 case clang::X86::BI__builtin_ia32_ucmpb128_mask:
18653 case clang::X86::BI__builtin_ia32_ucmpw128_mask:
18654 case clang::X86::BI__builtin_ia32_ucmpd128_mask:
18655 case clang::X86::BI__builtin_ia32_ucmpq128_mask:
18656 case clang::X86::BI__builtin_ia32_ucmpb256_mask:
18657 case clang::X86::BI__builtin_ia32_ucmpw256_mask:
18658 case clang::X86::BI__builtin_ia32_ucmpd256_mask:
18659 case clang::X86::BI__builtin_ia32_ucmpq256_mask:
18660 case clang::X86::BI__builtin_ia32_ucmpb512_mask:
18661 case clang::X86::BI__builtin_ia32_ucmpw512_mask:
18662 case clang::X86::BI__builtin_ia32_ucmpd512_mask:
18663 case clang::X86::BI__builtin_ia32_ucmpq512_mask: {
18664 assert(E->getNumArgs() == 4);
18665
18666 bool IsUnsigned =
18667 (BuiltinOp >= clang::X86::BI__builtin_ia32_ucmpb128_mask &&
18668 BuiltinOp <= clang::X86::BI__builtin_ia32_ucmpw512_mask);
18669
18670 APValue LHS, RHS;
18671 APSInt Mask, Opcode;
18672 if (!EvaluateVector(E->getArg(0), LHS, Info) ||
18673 !EvaluateVector(E->getArg(1), RHS, Info) ||
18674 !EvaluateInteger(E->getArg(2), Opcode, Info) ||
18675 !EvaluateInteger(E->getArg(3), Mask, Info))
18676 return false;
18677
18678 assert(LHS.getVectorLength() == RHS.getVectorLength());
18679
18680 unsigned VectorLen = LHS.getVectorLength();
18681 unsigned RetWidth = Mask.getBitWidth();
18682
18683 APSInt RetMask(llvm::APInt(RetWidth, 0), /*isUnsigned=*/true);
18684
18685 for (unsigned ElemNum = 0; ElemNum < VectorLen; ++ElemNum) {
18686 const APSInt &A = LHS.getVectorElt(ElemNum).getInt();
18687 const APSInt &B = RHS.getVectorElt(ElemNum).getInt();
18688 bool Result = false;
18689
18690 switch (Opcode.getExtValue() & 0x7) {
18691 case 0: // _MM_CMPINT_EQ
18692 Result = (A == B);
18693 break;
18694 case 1: // _MM_CMPINT_LT
18695 Result = IsUnsigned ? A.ult(B) : A.slt(B);
18696 break;
18697 case 2: // _MM_CMPINT_LE
18698 Result = IsUnsigned ? A.ule(B) : A.sle(B);
18699 break;
18700 case 3: // _MM_CMPINT_FALSE
18701 Result = false;
18702 break;
18703 case 4: // _MM_CMPINT_NE
18704 Result = (A != B);
18705 break;
18706 case 5: // _MM_CMPINT_NLT (>=)
18707 Result = IsUnsigned ? A.uge(B) : A.sge(B);
18708 break;
18709 case 6: // _MM_CMPINT_NLE (>)
18710 Result = IsUnsigned ? A.ugt(B) : A.sgt(B);
18711 break;
18712 case 7: // _MM_CMPINT_TRUE
18713 Result = true;
18714 break;
18715 }
18716
18717 RetMask.setBitVal(ElemNum, Mask[ElemNum] && Result);
18718 }
18719
18720 return Success(APValue(RetMask), E);
18721 }
18722 case X86::BI__builtin_ia32_cvtss2si:
18723 case X86::BI__builtin_ia32_cvtsd2si:
18724 case X86::BI__builtin_ia32_cvttss2si:
18725 case X86::BI__builtin_ia32_cvttsd2si:
18726 case X86::BI__builtin_ia32_cvtss2si64:
18727 case X86::BI__builtin_ia32_cvtsd2si64:
18728 case X86::BI__builtin_ia32_cvttss2si64:
18729 case X86::BI__builtin_ia32_cvttsd2si64: {
18730 APValue ArgVal;
18731 if (!EvaluateAsRValue(Info, E->getArg(0), ArgVal))
18732 return false;
18733
18734 assert(ArgVal.isVector() && "Expected a vector argument");
18735 llvm::APFloat FloatElem = ArgVal.getVectorElt(0).getFloat();
18736 unsigned BitWidth = Info.Ctx.getIntWidth(E->getType());
18738
18739 llvm::APSInt IntResult(BitWidth, isUnsigned);
18740 bool IsExact = false;
18741 // We only allow exact conversions so rounding mode does not matter for cvt*
18742 // and cvtt* builtins
18743 FloatElem.convertToInteger(IntResult, llvm::APFloat::rmTowardZero,
18744 &IsExact);
18745 if (!IsExact)
18746 return false;
18747
18748 return Success(IntResult, E);
18749 }
18750 case X86::BI__builtin_ia32_vpshufbitqmb128_mask:
18751 case X86::BI__builtin_ia32_vpshufbitqmb256_mask:
18752 case X86::BI__builtin_ia32_vpshufbitqmb512_mask: {
18753 assert(E->getNumArgs() == 3);
18754
18755 APValue Source, ShuffleMask;
18756 APSInt ZeroMask;
18757 if (!EvaluateVector(E->getArg(0), Source, Info) ||
18758 !EvaluateVector(E->getArg(1), ShuffleMask, Info) ||
18759 !EvaluateInteger(E->getArg(2), ZeroMask, Info))
18760 return false;
18761
18762 assert(Source.getVectorLength() == ShuffleMask.getVectorLength());
18763 assert(ZeroMask.getBitWidth() == Source.getVectorLength());
18764
18765 unsigned NumBytesInQWord = 8;
18766 unsigned NumBitsInByte = 8;
18767 unsigned NumBytes = Source.getVectorLength();
18768 unsigned NumQWords = NumBytes / NumBytesInQWord;
18769 unsigned RetWidth = ZeroMask.getBitWidth();
18770 APSInt RetMask(llvm::APInt(RetWidth, 0), /*isUnsigned=*/true);
18771
18772 for (unsigned QWordId = 0; QWordId != NumQWords; ++QWordId) {
18773 APInt SourceQWord(64, 0);
18774 for (unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
18775 uint64_t Byte = Source.getVectorElt(QWordId * NumBytesInQWord + ByteIdx)
18776 .getInt()
18777 .getZExtValue();
18778 SourceQWord.insertBits(APInt(8, Byte & 0xFF), ByteIdx * NumBitsInByte);
18779 }
18780
18781 for (unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
18782 unsigned SelIdx = QWordId * NumBytesInQWord + ByteIdx;
18783 unsigned M =
18784 ShuffleMask.getVectorElt(SelIdx).getInt().getZExtValue() & 0x3F;
18785 if (ZeroMask[SelIdx]) {
18786 RetMask.setBitVal(SelIdx, SourceQWord[M]);
18787 }
18788 }
18789 }
18790 return Success(APValue(RetMask), E);
18791 }
18792 }
18793}
18794
18795/// Determine whether this is a pointer past the end of the complete
18796/// object referred to by the lvalue.
18798 const LValue &LV) {
18799 // A null pointer can be viewed as being "past the end" but we don't
18800 // choose to look at it that way here.
18801 if (!LV.getLValueBase())
18802 return false;
18803
18804 // If the designator is valid and refers to a subobject, we're not pointing
18805 // past the end.
18806 if (!LV.getLValueDesignator().Invalid &&
18807 !LV.getLValueDesignator().isOnePastTheEnd())
18808 return false;
18809
18810 // A pointer to an incomplete type might be past-the-end if the type's size is
18811 // zero. We cannot tell because the type is incomplete.
18812 QualType Ty = getType(LV.getLValueBase());
18813 if (Ty->isIncompleteType())
18814 return true;
18815
18816 // Can't be past the end of an invalid object.
18817 if (LV.getLValueDesignator().Invalid)
18818 return false;
18819
18820 // We're a past-the-end pointer if we point to the byte after the object,
18821 // no matter what our type or path is.
18822 auto Size = Ctx.getTypeSizeInChars(Ty);
18823 return LV.getLValueOffset() == Size;
18824}
18825
18826namespace {
18827
18828/// Data recursive integer evaluator of certain binary operators.
18829///
18830/// We use a data recursive algorithm for binary operators so that we are able
18831/// to handle extreme cases of chained binary operators without causing stack
18832/// overflow.
18833class DataRecursiveIntBinOpEvaluator {
18834 struct EvalResult {
18835 APValue Val;
18836 bool Failed = false;
18837
18838 EvalResult() = default;
18839
18840 void swap(EvalResult &RHS) {
18841 Val.swap(RHS.Val);
18842 Failed = RHS.Failed;
18843 RHS.Failed = false;
18844 }
18845 };
18846
18847 struct Job {
18848 const Expr *E;
18849 EvalResult LHSResult; // meaningful only for binary operator expression.
18850 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
18851
18852 Job() = default;
18853 Job(Job &&) = default;
18854
18855 void startSpeculativeEval(EvalInfo &Info) {
18856 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
18857 }
18858
18859 private:
18860 SpeculativeEvaluationRAII SpecEvalRAII;
18861 };
18862
18863 SmallVector<Job, 16> Queue;
18864
18865 IntExprEvaluator &IntEval;
18866 EvalInfo &Info;
18867 APValue &FinalResult;
18868
18869public:
18870 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
18871 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
18872
18873 /// True if \param E is a binary operator that we are going to handle
18874 /// data recursively.
18875 /// We handle binary operators that are comma, logical, or that have operands
18876 /// with integral or enumeration type.
18877 static bool shouldEnqueue(const BinaryOperator *E) {
18878 return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
18882 }
18883
18884 bool Traverse(const BinaryOperator *E) {
18885 enqueue(E);
18886 EvalResult PrevResult;
18887 while (!Queue.empty())
18888 process(PrevResult);
18889
18890 if (PrevResult.Failed) return false;
18891
18892 FinalResult.swap(PrevResult.Val);
18893 return true;
18894 }
18895
18896private:
18897 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
18898 return IntEval.Success(Value, E, Result);
18899 }
18900 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
18901 return IntEval.Success(Value, E, Result);
18902 }
18903 bool Error(const Expr *E) {
18904 return IntEval.Error(E);
18905 }
18906 bool Error(const Expr *E, diag::kind D) {
18907 return IntEval.Error(E, D);
18908 }
18909
18910 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
18911 return Info.CCEDiag(E, D);
18912 }
18913
18914 // Returns true if visiting the RHS is necessary, false otherwise.
18915 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
18916 bool &SuppressRHSDiags);
18917
18918 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
18919 const BinaryOperator *E, APValue &Result);
18920
18921 void EvaluateExpr(const Expr *E, EvalResult &Result) {
18922 Result.Failed = !Evaluate(Result.Val, Info, E);
18923 if (Result.Failed)
18924 Result.Val = APValue();
18925 }
18926
18927 void process(EvalResult &Result);
18928
18929 void enqueue(const Expr *E) {
18930 E = E->IgnoreParens();
18931 Queue.resize(Queue.size()+1);
18932 Queue.back().E = E;
18933 Queue.back().Kind = Job::AnyExprKind;
18934 }
18935};
18936
18937}
18938
18939bool DataRecursiveIntBinOpEvaluator::
18940 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
18941 bool &SuppressRHSDiags) {
18942 if (E->getOpcode() == BO_Comma) {
18943 // Ignore LHS but note if we could not evaluate it.
18944 if (LHSResult.Failed)
18945 return Info.noteSideEffect();
18946 return true;
18947 }
18948
18949 if (E->isLogicalOp()) {
18950 bool LHSAsBool;
18951 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
18952 // We were able to evaluate the LHS, see if we can get away with not
18953 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
18954 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
18955 Success(LHSAsBool, E, LHSResult.Val);
18956 return false; // Ignore RHS
18957 }
18958 } else {
18959 LHSResult.Failed = true;
18960
18961 // Since we weren't able to evaluate the left hand side, it
18962 // might have had side effects.
18963 if (!Info.noteSideEffect())
18964 return false;
18965
18966 // We can't evaluate the LHS; however, sometimes the result
18967 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
18968 // Don't ignore RHS and suppress diagnostics from this arm.
18969 SuppressRHSDiags = true;
18970 }
18971
18972 return true;
18973 }
18974
18975 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
18977
18978 if (LHSResult.Failed && !Info.noteFailure())
18979 return false; // Ignore RHS;
18980
18981 return true;
18982}
18983
18984static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
18985 bool IsSub) {
18986 // Compute the new offset in the appropriate width, wrapping at 64 bits.
18987 // FIXME: When compiling for a 32-bit target, we should use 32-bit
18988 // offsets.
18989 assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
18990 CharUnits &Offset = LVal.getLValueOffset();
18991 uint64_t Offset64 = Offset.getQuantity();
18992 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
18993 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
18994 : Offset64 + Index64);
18995}
18996
18997bool DataRecursiveIntBinOpEvaluator::
18998 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
18999 const BinaryOperator *E, APValue &Result) {
19000 if (E->getOpcode() == BO_Comma) {
19001 if (RHSResult.Failed)
19002 return false;
19003 Result = RHSResult.Val;
19004 return true;
19005 }
19006
19007 if (E->isLogicalOp()) {
19008 bool lhsResult, rhsResult;
19009 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
19010 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
19011
19012 if (LHSIsOK) {
19013 if (RHSIsOK) {
19014 if (E->getOpcode() == BO_LOr)
19015 return Success(lhsResult || rhsResult, E, Result);
19016 else
19017 return Success(lhsResult && rhsResult, E, Result);
19018 }
19019 } else {
19020 if (RHSIsOK) {
19021 // We can't evaluate the LHS; however, sometimes the result
19022 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
19023 if (rhsResult == (E->getOpcode() == BO_LOr))
19024 return Success(rhsResult, E, Result);
19025 }
19026 }
19027
19028 return false;
19029 }
19030
19031 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
19033
19034 if (LHSResult.Failed || RHSResult.Failed)
19035 return false;
19036
19037 const APValue &LHSVal = LHSResult.Val;
19038 const APValue &RHSVal = RHSResult.Val;
19039
19040 // Handle cases like (unsigned long)&a + 4.
19041 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
19042 Result = LHSVal;
19043 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
19044 return true;
19045 }
19046
19047 // Handle cases like 4 + (unsigned long)&a
19048 if (E->getOpcode() == BO_Add &&
19049 RHSVal.isLValue() && LHSVal.isInt()) {
19050 Result = RHSVal;
19051 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
19052 return true;
19053 }
19054
19055 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
19056 // Handle (intptr_t)&&A - (intptr_t)&&B.
19057 if (!LHSVal.getLValueOffset().isZero() ||
19058 !RHSVal.getLValueOffset().isZero())
19059 return false;
19060 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
19061 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
19062 if (!LHSExpr || !RHSExpr)
19063 return false;
19064 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
19065 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
19066 if (!LHSAddrExpr || !RHSAddrExpr)
19067 return false;
19068 // Make sure both labels come from the same function.
19069 if (LHSAddrExpr->getLabel()->getDeclContext() !=
19070 RHSAddrExpr->getLabel()->getDeclContext())
19071 return false;
19072 Result = APValue(LHSAddrExpr, RHSAddrExpr);
19073 return true;
19074 }
19075
19076 // All the remaining cases expect both operands to be an integer
19077 if (!LHSVal.isInt() || !RHSVal.isInt())
19078 return Error(E);
19079
19080 // Set up the width and signedness manually, in case it can't be deduced
19081 // from the operation we're performing.
19082 // FIXME: Don't do this in the cases where we can deduce it.
19083 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
19085 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
19086 RHSVal.getInt(), Value))
19087 return false;
19088 return Success(Value, E, Result);
19089}
19090
19091void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
19092 Job &job = Queue.back();
19093
19094 switch (job.Kind) {
19095 case Job::AnyExprKind: {
19096 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
19097 if (shouldEnqueue(Bop)) {
19098 job.Kind = Job::BinOpKind;
19099 enqueue(Bop->getLHS());
19100 return;
19101 }
19102 }
19103
19104 EvaluateExpr(job.E, Result);
19105 Queue.pop_back();
19106 return;
19107 }
19108
19109 case Job::BinOpKind: {
19110 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
19111 bool SuppressRHSDiags = false;
19112 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
19113 Queue.pop_back();
19114 return;
19115 }
19116 if (SuppressRHSDiags)
19117 job.startSpeculativeEval(Info);
19118 job.LHSResult.swap(Result);
19119 job.Kind = Job::BinOpVisitedLHSKind;
19120 enqueue(Bop->getRHS());
19121 return;
19122 }
19123
19124 case Job::BinOpVisitedLHSKind: {
19125 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
19126 EvalResult RHS;
19127 RHS.swap(Result);
19128 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
19129 Queue.pop_back();
19130 return;
19131 }
19132 }
19133
19134 llvm_unreachable("Invalid Job::Kind!");
19135}
19136
19137namespace {
19138enum class CmpResult {
19139 Unequal,
19140 Less,
19141 Equal,
19142 Greater,
19143 Unordered,
19144};
19145}
19146
19147template <class SuccessCB, class AfterCB>
19148static bool
19150 SuccessCB &&Success, AfterCB &&DoAfter) {
19151 assert(!E->isValueDependent());
19152 assert(E->isComparisonOp() && "expected comparison operator");
19153 assert((E->getOpcode() == BO_Cmp ||
19155 "unsupported binary expression evaluation");
19156 auto Error = [&](const Expr *E) {
19157 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
19158 return false;
19159 };
19160
19161 bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp;
19162 bool IsEquality = E->isEqualityOp();
19163
19164 QualType LHSTy = E->getLHS()->getType();
19165 QualType RHSTy = E->getRHS()->getType();
19166
19167 if (LHSTy->isIntegralOrEnumerationType() &&
19168 RHSTy->isIntegralOrEnumerationType()) {
19169 APSInt LHS, RHS;
19170 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
19171 if (!LHSOK && !Info.noteFailure())
19172 return false;
19173 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
19174 return false;
19175 if (LHS < RHS)
19176 return Success(CmpResult::Less, E);
19177 if (LHS > RHS)
19178 return Success(CmpResult::Greater, E);
19179 return Success(CmpResult::Equal, E);
19180 }
19181
19182 if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
19183 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
19184 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
19185
19186 bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
19187 if (!LHSOK && !Info.noteFailure())
19188 return false;
19189 if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
19190 return false;
19191 if (LHSFX < RHSFX)
19192 return Success(CmpResult::Less, E);
19193 if (LHSFX > RHSFX)
19194 return Success(CmpResult::Greater, E);
19195 return Success(CmpResult::Equal, E);
19196 }
19197
19198 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
19199 ComplexValue LHS, RHS;
19200 bool LHSOK;
19201 if (E->isAssignmentOp()) {
19202 LValue LV;
19203 EvaluateLValue(E->getLHS(), LV, Info);
19204 LHSOK = false;
19205 } else if (LHSTy->isRealFloatingType()) {
19206 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
19207 if (LHSOK) {
19208 LHS.makeComplexFloat();
19209 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
19210 }
19211 } else {
19212 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
19213 }
19214 if (!LHSOK && !Info.noteFailure())
19215 return false;
19216
19217 if (E->getRHS()->getType()->isRealFloatingType()) {
19218 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
19219 return false;
19220 RHS.makeComplexFloat();
19221 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
19222 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
19223 return false;
19224
19225 if (LHS.isComplexFloat()) {
19226 APFloat::cmpResult CR_r =
19227 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
19228 APFloat::cmpResult CR_i =
19229 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
19230 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
19231 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
19232 } else {
19233 assert(IsEquality && "invalid complex comparison");
19234 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
19235 LHS.getComplexIntImag() == RHS.getComplexIntImag();
19236 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
19237 }
19238 }
19239
19240 if (LHSTy->isRealFloatingType() &&
19241 RHSTy->isRealFloatingType()) {
19242 APFloat RHS(0.0), LHS(0.0);
19243
19244 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
19245 if (!LHSOK && !Info.noteFailure())
19246 return false;
19247
19248 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
19249 return false;
19250
19251 assert(E->isComparisonOp() && "Invalid binary operator!");
19252 llvm::APFloatBase::cmpResult APFloatCmpResult = LHS.compare(RHS);
19253 if (!Info.InConstantContext &&
19254 APFloatCmpResult == APFloat::cmpUnordered &&
19255 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained()) {
19256 // Note: Compares may raise invalid in some cases involving NaN or sNaN.
19257 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
19258 return false;
19259 }
19260 auto GetCmpRes = [&]() {
19261 switch (APFloatCmpResult) {
19262 case APFloat::cmpEqual:
19263 return CmpResult::Equal;
19264 case APFloat::cmpLessThan:
19265 return CmpResult::Less;
19266 case APFloat::cmpGreaterThan:
19267 return CmpResult::Greater;
19268 case APFloat::cmpUnordered:
19269 return CmpResult::Unordered;
19270 }
19271 llvm_unreachable("Unrecognised APFloat::cmpResult enum");
19272 };
19273 return Success(GetCmpRes(), E);
19274 }
19275
19276 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
19277 LValue LHSValue, RHSValue;
19278
19279 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
19280 if (!LHSOK && !Info.noteFailure())
19281 return false;
19282
19283 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
19284 return false;
19285
19286 // Reject differing bases from the normal codepath; we special-case
19287 // comparisons to null.
19288 if (!HasSameBase(LHSValue, RHSValue)) {
19289 // Bail out early if we're checking potential constant expression.
19290 // Otherwise, prefer to diagnose other issues.
19291 if (Info.checkingPotentialConstantExpression() &&
19292 (LHSValue.AllowConstexprUnknown || RHSValue.AllowConstexprUnknown))
19293 return false;
19294 auto DiagComparison = [&] (unsigned DiagID, bool Reversed = false) {
19295 std::string LHS = LHSValue.toString(Info.Ctx, E->getLHS()->getType());
19296 std::string RHS = RHSValue.toString(Info.Ctx, E->getRHS()->getType());
19297 Info.FFDiag(E, DiagID)
19298 << (Reversed ? RHS : LHS) << (Reversed ? LHS : RHS);
19299 return false;
19300 };
19301 // Inequalities and subtractions between unrelated pointers have
19302 // unspecified or undefined behavior.
19303 if (!IsEquality)
19304 return DiagComparison(
19305 diag::note_constexpr_pointer_comparison_unspecified);
19306 // A constant address may compare equal to the address of a symbol.
19307 // The one exception is that address of an object cannot compare equal
19308 // to a null pointer constant.
19309 // TODO: Should we restrict this to actual null pointers, and exclude the
19310 // case of zero cast to pointer type?
19311 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
19312 (!RHSValue.Base && !RHSValue.Offset.isZero()))
19313 return DiagComparison(diag::note_constexpr_pointer_constant_comparison,
19314 !RHSValue.Base);
19315 // C++2c [intro.object]/10:
19316 // Two objects [...] may have the same address if [...] they are both
19317 // potentially non-unique objects.
19318 // C++2c [intro.object]/9:
19319 // An object is potentially non-unique if it is a string literal object,
19320 // the backing array of an initializer list, or a subobject thereof.
19321 //
19322 // This makes the comparison result unspecified, so it's not a constant
19323 // expression.
19324 //
19325 // TODO: Do we need to handle the initializer list case here?
19326 if (ArePotentiallyOverlappingStringLiterals(Info, LHSValue, RHSValue))
19327 return DiagComparison(diag::note_constexpr_literal_comparison);
19328 if (IsOpaqueConstantCall(LHSValue) || IsOpaqueConstantCall(RHSValue))
19329 return DiagComparison(diag::note_constexpr_opaque_call_comparison,
19330 !IsOpaqueConstantCall(LHSValue));
19331 // We can't tell whether weak symbols will end up pointing to the same
19332 // object.
19333 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
19334 return DiagComparison(diag::note_constexpr_pointer_weak_comparison,
19335 !IsWeakLValue(LHSValue));
19336 // We can't compare the address of the start of one object with the
19337 // past-the-end address of another object, per C++ DR1652.
19338 if (LHSValue.Base && LHSValue.Offset.isZero() &&
19339 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue))
19340 return DiagComparison(diag::note_constexpr_pointer_comparison_past_end,
19341 true);
19342 if (RHSValue.Base && RHSValue.Offset.isZero() &&
19343 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue))
19344 return DiagComparison(diag::note_constexpr_pointer_comparison_past_end,
19345 false);
19346 // We can't tell whether an object is at the same address as another
19347 // zero sized object.
19348 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
19349 (LHSValue.Base && isZeroSized(RHSValue)))
19350 return DiagComparison(
19351 diag::note_constexpr_pointer_comparison_zero_sized);
19352 if (LHSValue.AllowConstexprUnknown || RHSValue.AllowConstexprUnknown)
19353 return DiagComparison(
19354 diag::note_constexpr_pointer_comparison_unspecified);
19355 // FIXME: Verify both variables are live.
19356 return Success(CmpResult::Unequal, E);
19357 }
19358
19359 CharUnits LHSOffset = LHSValue.getLValueOffset();
19360 CharUnits RHSOffset = RHSValue.getLValueOffset();
19361
19362 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
19363 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
19364
19365 // C++11 [expr.rel]p2:
19366 // - If two pointers point to non-static data members of the same object,
19367 // or to subobjects or array elements fo such members, recursively, the
19368 // pointer to the later declared member compares greater provided the
19369 // two members have the same access control and provided their class is
19370 // not a union.
19371 // [...]
19372 // - Otherwise pointer comparisons are unspecified.
19373 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
19374 bool WasArrayIndex;
19375 unsigned Mismatch = FindDesignatorMismatch(
19376 LHSValue.Base.isNull() ? QualType()
19377 : getType(LHSValue.Base).getNonReferenceType(),
19378 LHSDesignator, RHSDesignator, WasArrayIndex);
19379 // At the point where the designators diverge, the comparison has a
19380 // specified value if:
19381 // - we are comparing array indices
19382 // - we are comparing fields of a union, or fields with the same access
19383 // Otherwise, the result is unspecified and thus the comparison is not a
19384 // constant expression.
19385 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
19386 Mismatch < RHSDesignator.Entries.size()) {
19387 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
19388 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
19389 if (!LF && !RF)
19390 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
19391 else if (!LF)
19392 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
19393 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
19394 << RF->getParent() << RF;
19395 else if (!RF)
19396 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
19397 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
19398 << LF->getParent() << LF;
19399 else if (!LF->getParent()->isUnion() &&
19400 LF->getAccess() != RF->getAccess())
19401 Info.CCEDiag(E,
19402 diag::note_constexpr_pointer_comparison_differing_access)
19403 << LF << LF->getAccess() << RF << RF->getAccess()
19404 << LF->getParent();
19405 }
19406 }
19407
19408 // The comparison here must be unsigned, and performed with the same
19409 // width as the pointer.
19410 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
19411 uint64_t CompareLHS = LHSOffset.getQuantity();
19412 uint64_t CompareRHS = RHSOffset.getQuantity();
19413 assert(PtrSize <= 64 && "Unexpected pointer width");
19414 uint64_t Mask = ~0ULL >> (64 - PtrSize);
19415 CompareLHS &= Mask;
19416 CompareRHS &= Mask;
19417
19418 // If there is a base and this is a relational operator, we can only
19419 // compare pointers within the object in question; otherwise, the result
19420 // depends on where the object is located in memory.
19421 if (!LHSValue.Base.isNull() && IsRelational) {
19422 QualType BaseTy = getType(LHSValue.Base).getNonReferenceType();
19423 if (BaseTy->isIncompleteType())
19424 return Error(E);
19425 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
19426 uint64_t OffsetLimit = Size.getQuantity();
19427 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
19428 return Error(E);
19429 }
19430
19431 if (CompareLHS < CompareRHS)
19432 return Success(CmpResult::Less, E);
19433 if (CompareLHS > CompareRHS)
19434 return Success(CmpResult::Greater, E);
19435 return Success(CmpResult::Equal, E);
19436 }
19437
19438 if (LHSTy->isMemberPointerType()) {
19439 assert(IsEquality && "unexpected member pointer operation");
19440 assert(RHSTy->isMemberPointerType() && "invalid comparison");
19441
19442 MemberPtr LHSValue, RHSValue;
19443
19444 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
19445 if (!LHSOK && !Info.noteFailure())
19446 return false;
19447
19448 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
19449 return false;
19450
19451 // If either operand is a pointer to a weak function, the comparison is not
19452 // constant.
19453 if (LHSValue.getDecl() && LHSValue.getDecl()->isWeak()) {
19454 Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison)
19455 << LHSValue.getDecl();
19456 return false;
19457 }
19458 if (RHSValue.getDecl() && RHSValue.getDecl()->isWeak()) {
19459 Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison)
19460 << RHSValue.getDecl();
19461 return false;
19462 }
19463
19464 // C++11 [expr.eq]p2:
19465 // If both operands are null, they compare equal. Otherwise if only one is
19466 // null, they compare unequal.
19467 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
19468 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
19469 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
19470 }
19471
19472 // Otherwise if either is a pointer to a virtual member function, the
19473 // result is unspecified.
19474 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
19475 if (MD->isVirtual())
19476 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
19477 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
19478 if (MD->isVirtual())
19479 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
19480
19481 // Otherwise they compare equal if and only if they would refer to the
19482 // same member of the same most derived object or the same subobject if
19483 // they were dereferenced with a hypothetical object of the associated
19484 // class type.
19485 bool Equal = LHSValue == RHSValue;
19486 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
19487 }
19488
19489 if (LHSTy->isNullPtrType()) {
19490 assert(E->isComparisonOp() && "unexpected nullptr operation");
19491 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
19492 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
19493 // are compared, the result is true of the operator is <=, >= or ==, and
19494 // false otherwise.
19495 LValue Res;
19496 if (!EvaluatePointer(E->getLHS(), Res, Info) ||
19497 !EvaluatePointer(E->getRHS(), Res, Info))
19498 return false;
19499 return Success(CmpResult::Equal, E);
19500 }
19501
19502 return DoAfter();
19503}
19504
19505static bool EvaluateComparisonResult(EvalInfo &Info, const Expr *E,
19507 APValue &Result) {
19508 const ComparisonCategoryInfo &CmpInfo =
19509 Info.Ctx.CompCategories.getInfoForType(E->getType());
19510 const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD;
19511
19512 // Check and evaluate the result as a constant expression.
19513 LValue LV;
19514 LV.set(VD);
19515 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
19516 return false;
19517 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
19518 ConstantExprKind::Normal);
19519}
19520
19521bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
19522 if (!CheckLiteralType(Info, E))
19523 return false;
19524
19525 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
19527 switch (CR) {
19528 case CmpResult::Unequal:
19529 llvm_unreachable("should never produce Unequal for three-way comparison");
19530 case CmpResult::Less:
19531 CCR = ComparisonCategoryResult::Less;
19532 break;
19533 case CmpResult::Equal:
19534 CCR = ComparisonCategoryResult::Equal;
19535 break;
19536 case CmpResult::Greater:
19537 CCR = ComparisonCategoryResult::Greater;
19538 break;
19539 case CmpResult::Unordered:
19540 CCR = ComparisonCategoryResult::Unordered;
19541 break;
19542 }
19543 return EvaluateComparisonResult(Info, E, CCR, Result);
19544 };
19545 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
19546 return ExprEvaluatorBaseTy::VisitBinCmp(E);
19547 });
19548}
19549
19550bool RecordExprEvaluator::VisitTypeTraitExpr(const TypeTraitExpr *E) {
19551 if (!CheckLiteralType(Info, E))
19552 return false;
19553
19554 assert(E->isStoredAsComparisonResult() &&
19555 "expected a strong_ordering type trait with a stored value");
19556
19558 E->getAPValue().getInt().getZExtValue());
19559 return EvaluateComparisonResult(Info, E, CCR, Result);
19560}
19561
19562bool RecordExprEvaluator::VisitCXXParenListInitExpr(
19563 const CXXParenListInitExpr *E) {
19564 return VisitCXXParenListOrInitListExpr(E, E->getInitExprs());
19565}
19566
19567bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
19568 // We don't support assignment in C. C++ assignments don't get here because
19569 // assignment is an lvalue in C++.
19570 if (E->isAssignmentOp()) {
19571 Error(E);
19572 if (!Info.noteFailure())
19573 return false;
19574 }
19575
19576 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
19577 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
19578
19579 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
19581 "DataRecursiveIntBinOpEvaluator should have handled integral types");
19582
19583 if (E->isComparisonOp()) {
19584 // Evaluate builtin binary comparisons by evaluating them as three-way
19585 // comparisons and then translating the result.
19586 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
19587 assert((CR != CmpResult::Unequal || E->isEqualityOp()) &&
19588 "should only produce Unequal for equality comparisons");
19589 bool IsEqual = CR == CmpResult::Equal,
19590 IsLess = CR == CmpResult::Less,
19591 IsGreater = CR == CmpResult::Greater;
19592 auto Op = E->getOpcode();
19593 switch (Op) {
19594 default:
19595 llvm_unreachable("unsupported binary operator");
19596 case BO_EQ:
19597 case BO_NE:
19598 return Success(IsEqual == (Op == BO_EQ), E);
19599 case BO_LT:
19600 return Success(IsLess, E);
19601 case BO_GT:
19602 return Success(IsGreater, E);
19603 case BO_LE:
19604 return Success(IsEqual || IsLess, E);
19605 case BO_GE:
19606 return Success(IsEqual || IsGreater, E);
19607 }
19608 };
19609 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
19610 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
19611 });
19612 }
19613
19614 QualType LHSTy = E->getLHS()->getType();
19615 QualType RHSTy = E->getRHS()->getType();
19616
19617 if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
19618 E->getOpcode() == BO_Sub) {
19619 LValue LHSValue, RHSValue;
19620
19621 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
19622 if (!LHSOK && !Info.noteFailure())
19623 return false;
19624
19625 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
19626 return false;
19627
19628 // Reject differing bases from the normal codepath; we special-case
19629 // comparisons to null.
19630 if (!HasSameBase(LHSValue, RHSValue)) {
19631 if (Info.checkingPotentialConstantExpression() &&
19632 (LHSValue.AllowConstexprUnknown || RHSValue.AllowConstexprUnknown))
19633 return false;
19634
19635 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
19636 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
19637
19638 auto DiagArith = [&](unsigned DiagID) {
19639 std::string LHS = LHSValue.toString(Info.Ctx, E->getLHS()->getType());
19640 std::string RHS = RHSValue.toString(Info.Ctx, E->getRHS()->getType());
19641 Info.FFDiag(E, DiagID) << LHS << RHS;
19642 if (LHSExpr && LHSExpr == RHSExpr)
19643 Info.Note(LHSExpr->getExprLoc(),
19644 diag::note_constexpr_repeated_literal_eval)
19645 << LHSExpr->getSourceRange();
19646 return false;
19647 };
19648
19649 if (!LHSExpr || !RHSExpr)
19650 return DiagArith(diag::note_constexpr_pointer_arith_unspecified);
19651
19652 if (ArePotentiallyOverlappingStringLiterals(Info, LHSValue, RHSValue))
19653 return DiagArith(diag::note_constexpr_literal_arith);
19654
19655 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
19656 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
19657 if (!LHSAddrExpr || !RHSAddrExpr)
19658 return Error(E);
19659 // Make sure both labels come from the same function.
19660 if (LHSAddrExpr->getLabel()->getDeclContext() !=
19661 RHSAddrExpr->getLabel()->getDeclContext())
19662 return Error(E);
19663 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
19664 }
19665 CharUnits LHSOffset = LHSValue.getLValueOffset();
19666 CharUnits RHSOffset = RHSValue.getLValueOffset();
19667
19668 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
19669 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
19670
19671 // C++11 [expr.add]p6:
19672 // Unless both pointers point to elements of the same array object, or
19673 // one past the last element of the array object, the behavior is
19674 // undefined.
19675 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
19676 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
19677 RHSDesignator))
19678 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
19679
19680 QualType Type = E->getLHS()->getType();
19681 QualType ElementType = Type->castAs<PointerType>()->getPointeeType();
19682
19683 CharUnits ElementSize;
19684 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
19685 return false;
19686
19687 // As an extension, a type may have zero size (empty struct or union in
19688 // C, array of zero length). Pointer subtraction in such cases has
19689 // undefined behavior, so is not constant.
19690 if (ElementSize.isZero()) {
19691 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
19692 << ElementType;
19693 return false;
19694 }
19695
19696 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
19697 // and produce incorrect results when it overflows. Such behavior
19698 // appears to be non-conforming, but is common, so perhaps we should
19699 // assume the standard intended for such cases to be undefined behavior
19700 // and check for them.
19701
19702 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
19703 // overflow in the final conversion to ptrdiff_t.
19704 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
19705 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
19706 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
19707 false);
19708 APSInt TrueResult = (LHS - RHS) / ElemSize;
19709 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
19710
19711 if (Result.extend(65) != TrueResult &&
19712 !HandleOverflow(Info, E, TrueResult, E->getType()))
19713 return false;
19714 return Success(Result, E);
19715 }
19716
19717 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
19718}
19719
19720/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
19721/// a result as the expression's type.
19722bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
19723 const UnaryExprOrTypeTraitExpr *E) {
19724 switch(E->getKind()) {
19725 case UETT_PreferredAlignOf:
19726 case UETT_AlignOf: {
19727 if (E->isArgumentType())
19728 return Success(
19729 GetAlignOfType(Info.Ctx, E->getArgumentType(), E->getKind()), E);
19730 else
19731 return Success(
19732 GetAlignOfExpr(Info.Ctx, E->getArgumentExpr(), E->getKind()), E);
19733 }
19734
19735 case UETT_PtrAuthTypeDiscriminator: {
19736 if (E->getArgumentType()->isDependentType())
19737 return false;
19738 return Success(
19739 Info.Ctx.getPointerAuthTypeDiscriminator(E->getArgumentType()), E);
19740 }
19741 case UETT_VecStep: {
19742 QualType Ty = E->getTypeOfArgument();
19743
19744 if (Ty->isVectorType()) {
19745 unsigned n = Ty->castAs<VectorType>()->getNumElements();
19746
19747 // The vec_step built-in functions that take a 3-component
19748 // vector return 4. (OpenCL 1.1 spec 6.11.12)
19749 if (n == 3)
19750 n = 4;
19751
19752 return Success(n, E);
19753 } else
19754 return Success(1, E);
19755 }
19756
19757 case UETT_DataSizeOf:
19758 case UETT_SizeOf: {
19759 QualType SrcTy = E->getTypeOfArgument();
19760 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
19761 // the result is the size of the referenced type."
19762 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
19763 SrcTy = Ref->getPointeeType();
19764
19765 CharUnits Sizeof;
19766 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof,
19767 E->getKind() == UETT_DataSizeOf ? SizeOfType::DataSizeOf
19768 : SizeOfType::SizeOf)) {
19769 return false;
19770 }
19771 return Success(Sizeof, E);
19772 }
19773 case UETT_OpenMPRequiredSimdAlign:
19774 assert(E->isArgumentType());
19775 return Success(
19776 Info.Ctx.toCharUnitsFromBits(
19777 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
19778 .getQuantity(),
19779 E);
19780 case UETT_VectorElements: {
19781 QualType Ty = E->getTypeOfArgument();
19782 // If the vector has a fixed size, we can determine the number of elements
19783 // at compile time.
19784 if (const auto *VT = Ty->getAs<VectorType>())
19785 return Success(VT->getNumElements(), E);
19786
19787 assert(Ty->isSizelessVectorType());
19788 if (Info.InConstantContext)
19789 Info.CCEDiag(E, diag::note_constexpr_non_const_vectorelements)
19790 << E->getSourceRange();
19791
19792 return false;
19793 }
19794 case UETT_CountOf: {
19795 QualType Ty = E->getTypeOfArgument();
19796 assert(Ty->isArrayType());
19797
19798 // We don't need to worry about array element qualifiers, so getting the
19799 // unsafe array type is fine.
19800 if (const auto *CAT =
19801 dyn_cast<ConstantArrayType>(Ty->getAsArrayTypeUnsafe())) {
19802 return Success(CAT->getSize(), E);
19803 }
19804
19805 assert(!Ty->isConstantSizeType());
19806
19807 // If it's a variable-length array type, we need to check whether it is a
19808 // multidimensional array. If so, we need to check the size expression of
19809 // the VLA to see if it's a constant size. If so, we can return that value.
19810 const auto *VAT = Info.Ctx.getAsVariableArrayType(Ty);
19811 assert(VAT);
19812 if (VAT->getElementType()->isArrayType()) {
19813 // Variable array size expression could be missing (e.g. int a[*][10]) In
19814 // that case, it can't be a constant expression.
19815 if (!VAT->getSizeExpr()) {
19816 Info.FFDiag(E->getBeginLoc());
19817 return false;
19818 }
19819
19820 std::optional<APSInt> Res =
19821 VAT->getSizeExpr()->getIntegerConstantExpr(Info.Ctx);
19822 if (Res) {
19823 // The resulting value always has type size_t, so we need to make the
19824 // returned APInt have the correct sign and bit-width.
19825 APInt Val{
19826 static_cast<unsigned>(Info.Ctx.getTypeSize(Info.Ctx.getSizeType())),
19827 Res->getZExtValue()};
19828 return Success(Val, E);
19829 }
19830 }
19831
19832 // Definitely a variable-length type, which is not an ICE.
19833 // FIXME: Better diagnostic.
19834 Info.FFDiag(E->getBeginLoc());
19835 return false;
19836 }
19837 }
19838
19839 llvm_unreachable("unknown expr/type trait");
19840}
19841
19842bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
19843 Info.Ctx.recordOffsetOfEvaluation(OOE);
19844 CharUnits Result;
19845 unsigned n = OOE->getNumComponents();
19846 if (n == 0)
19847 return Error(OOE);
19848 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
19849 for (unsigned i = 0; i != n; ++i) {
19850 OffsetOfNode ON = OOE->getComponent(i);
19851 switch (ON.getKind()) {
19852 case OffsetOfNode::Array: {
19853 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
19854 APSInt IdxResult;
19855 if (!EvaluateInteger(Idx, IdxResult, Info))
19856 return false;
19857 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
19858 if (!AT)
19859 return Error(OOE);
19860 CurrentType = AT->getElementType();
19861 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
19862 // Reject negative indices, indices too large to fit in int64_t,
19863 // and overflow in the offset computation.
19864 if (IdxResult.isNegative() || IdxResult.getActiveBits() > 63)
19865 return Error(OOE);
19866 int64_t IdxVal = IdxResult.getExtValue();
19867 int64_t ElemSize = ElementSize.getQuantity();
19868 if (IdxVal != 0 &&
19869 ElemSize > std::numeric_limits<int64_t>::max() / IdxVal)
19870 return Error(OOE, diag::note_constexpr_offsetof_overflow);
19871 int64_t Offset = IdxVal * ElemSize;
19872 if (Result.getQuantity() > std::numeric_limits<int64_t>::max() - Offset)
19873 return Error(OOE, diag::note_constexpr_offsetof_overflow);
19875 break;
19876 }
19877
19878 case OffsetOfNode::Field: {
19879 FieldDecl *MemberDecl = ON.getField();
19880 const auto *RD = CurrentType->getAsRecordDecl();
19881 if (!RD)
19882 return Error(OOE);
19883 if (RD->isInvalidDecl()) return false;
19884 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
19885 unsigned i = MemberDecl->getFieldIndex();
19886 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
19887 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
19888 CurrentType = MemberDecl->getType().getNonReferenceType();
19889 break;
19890 }
19891
19893 llvm_unreachable("dependent __builtin_offsetof");
19894
19895 case OffsetOfNode::Base: {
19896 CXXBaseSpecifier *BaseSpec = ON.getBase();
19897 if (BaseSpec->isVirtual())
19898 return Error(OOE);
19899
19900 // Find the layout of the class whose base we are looking into.
19901 const auto *RD = CurrentType->getAsCXXRecordDecl();
19902 if (!RD)
19903 return Error(OOE);
19904 if (RD->isInvalidDecl()) return false;
19905 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
19906
19907 // Find the base class itself.
19908 CurrentType = BaseSpec->getType();
19909 const auto *BaseRD = CurrentType->getAsCXXRecordDecl();
19910 if (!BaseRD)
19911 return Error(OOE);
19912
19913 // Add the offset to the base.
19914 Result += RL.getBaseClassOffset(BaseRD);
19915 break;
19916 }
19917 }
19918 }
19919 return Success(Result, OOE);
19920}
19921
19922bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
19923 switch (E->getOpcode()) {
19924 default:
19925 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
19926 // See C99 6.6p3.
19927 return Error(E);
19928 case UO_Extension:
19929 // FIXME: Should extension allow i-c-e extension expressions in its scope?
19930 // If so, we could clear the diagnostic ID.
19931 return Visit(E->getSubExpr());
19932 case UO_Plus:
19933 // The result is just the value.
19934 return Visit(E->getSubExpr());
19935 case UO_Minus: {
19936 if (!Visit(E->getSubExpr()))
19937 return false;
19938 if (!Result.isInt()) return Error(E);
19939 const APSInt &Value = Result.getInt();
19940 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
19941 !E->getType().isWrapType()) {
19942 if (Info.checkingForUndefinedBehavior())
19943 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
19944 diag::warn_integer_constant_overflow)
19945 << toString(Value, 10, Value.isSigned(), /*formatAsCLiteral=*/false,
19946 /*UpperCase=*/true, /*InsertSeparators=*/true)
19947 << E->getType() << E->getSourceRange();
19948
19949 if (!HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
19950 E->getType()))
19951 return false;
19952 }
19953 return Success(-Value, E);
19954 }
19955 case UO_Not: {
19956 if (!Visit(E->getSubExpr()))
19957 return false;
19958 if (!Result.isInt()) return Error(E);
19959 return Success(~Result.getInt(), E);
19960 }
19961 case UO_LNot: {
19962 bool bres;
19963 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
19964 return false;
19965 return Success(!bres, E);
19966 }
19967 }
19968}
19969
19970/// HandleCast - This is used to evaluate implicit or explicit casts where the
19971/// result type is integer.
19972bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
19973 const Expr *SubExpr = E->getSubExpr();
19974 QualType DestType = E->getType();
19975 QualType SrcType = SubExpr->getType();
19976
19977 switch (E->getCastKind()) {
19978 case CK_BaseToDerived:
19979 case CK_DerivedToBase:
19980 case CK_UncheckedDerivedToBase:
19981 case CK_Dynamic:
19982 case CK_ToUnion:
19983 case CK_ArrayToPointerDecay:
19984 case CK_FunctionToPointerDecay:
19985 case CK_NullToPointer:
19986 case CK_NullToMemberPointer:
19987 case CK_BaseToDerivedMemberPointer:
19988 case CK_DerivedToBaseMemberPointer:
19989 case CK_ReinterpretMemberPointer:
19990 case CK_ConstructorConversion:
19991 case CK_IntegralToPointer:
19992 case CK_ToVoid:
19993 case CK_VectorSplat:
19994 case CK_IntegralToFloating:
19995 case CK_FloatingCast:
19996 case CK_CPointerToObjCPointerCast:
19997 case CK_BlockPointerToObjCPointerCast:
19998 case CK_AnyPointerToBlockPointerCast:
19999 case CK_ObjCObjectLValueCast:
20000 case CK_FloatingRealToComplex:
20001 case CK_FloatingComplexToReal:
20002 case CK_FloatingComplexCast:
20003 case CK_FloatingComplexToIntegralComplex:
20004 case CK_IntegralRealToComplex:
20005 case CK_IntegralComplexCast:
20006 case CK_IntegralComplexToFloatingComplex:
20007 case CK_BuiltinFnToFnPtr:
20008 case CK_ZeroToOCLOpaqueType:
20009 case CK_NonAtomicToAtomic:
20010 case CK_AddressSpaceConversion:
20011 case CK_IntToOCLSampler:
20012 case CK_FloatingToFixedPoint:
20013 case CK_FixedPointToFloating:
20014 case CK_FixedPointCast:
20015 case CK_IntegralToFixedPoint:
20016 case CK_MatrixCast:
20017 case CK_HLSLAggregateSplatCast:
20018 llvm_unreachable("invalid cast kind for integral value");
20019
20020 case CK_BitCast:
20021 case CK_Dependent:
20022 case CK_LValueBitCast:
20023 case CK_ARCProduceObject:
20024 case CK_ARCConsumeObject:
20025 case CK_ARCReclaimReturnedObject:
20026 case CK_ARCExtendBlockObject:
20027 case CK_CopyAndAutoreleaseBlockObject:
20028 return Error(E);
20029
20030 case CK_UserDefinedConversion:
20031 case CK_LValueToRValue:
20032 case CK_AtomicToNonAtomic:
20033 case CK_NoOp:
20034 case CK_LValueToRValueBitCast:
20035 case CK_HLSLArrayRValue:
20036 return ExprEvaluatorBaseTy::VisitCastExpr(E);
20037
20038 case CK_MemberPointerToBoolean:
20039 case CK_PointerToBoolean:
20040 case CK_IntegralToBoolean:
20041 case CK_FloatingToBoolean:
20042 case CK_BooleanToSignedIntegral:
20043 case CK_FloatingComplexToBoolean:
20044 case CK_IntegralComplexToBoolean: {
20045 bool BoolResult;
20046 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
20047 return false;
20048 uint64_t IntResult = BoolResult;
20049 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
20050 IntResult = (uint64_t)-1;
20051 return Success(IntResult, E);
20052 }
20053
20054 case CK_FixedPointToIntegral: {
20055 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
20056 if (!EvaluateFixedPoint(SubExpr, Src, Info))
20057 return false;
20058 bool Overflowed;
20059 llvm::APSInt Result = Src.convertToInt(
20060 Info.Ctx.getIntWidth(DestType),
20061 DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
20062 if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
20063 return false;
20064 return Success(Result, E);
20065 }
20066
20067 case CK_FixedPointToBoolean: {
20068 // Unsigned padding does not affect this.
20069 APValue Val;
20070 if (!Evaluate(Val, Info, SubExpr))
20071 return false;
20072 return Success(Val.getFixedPoint().getBoolValue(), E);
20073 }
20074
20075 case CK_IntegralCast: {
20076 if (!Visit(SubExpr))
20077 return false;
20078
20079 if (!Result.isInt()) {
20080 // Allow casts of address-of-label differences if they are no-ops
20081 // or narrowing, if the result is at least 32 bits wide.
20082 // (The narrowing case isn't actually guaranteed to
20083 // be constant-evaluatable except in some narrow cases which are hard
20084 // to detect here. We let it through on the assumption the user knows
20085 // what they are doing.)
20086 if (Result.isAddrLabelDiff()) {
20087 unsigned DestBits = Info.Ctx.getTypeSize(DestType);
20088 return DestBits >= 32 && DestBits <= Info.Ctx.getTypeSize(SrcType);
20089 }
20090 // Only allow casts of lvalues if they are lossless.
20091 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
20092 }
20093
20094 if (Info.Ctx.getLangOpts().CPlusPlus && DestType->isEnumeralType()) {
20095 const auto *ED = DestType->getAsEnumDecl();
20096 // Check that the value is within the range of the enumeration values.
20097 //
20098 // This corressponds to [expr.static.cast]p10 which says:
20099 // A value of integral or enumeration type can be explicitly converted
20100 // to a complete enumeration type ... If the enumeration type does not
20101 // have a fixed underlying type, the value is unchanged if the original
20102 // value is within the range of the enumeration values ([dcl.enum]), and
20103 // otherwise, the behavior is undefined.
20104 //
20105 // This was resolved as part of DR2338 which has CD5 status.
20106 if (!ED->isFixed()) {
20107 llvm::APInt Min;
20108 llvm::APInt Max;
20109
20110 ED->getValueRange(Max, Min);
20111 --Max;
20112
20113 if (ED->getNumNegativeBits() &&
20114 (Max.slt(Result.getInt().getSExtValue()) ||
20115 Min.sgt(Result.getInt().getSExtValue())))
20116 Info.CCEDiag(E, diag::note_constexpr_unscoped_enum_out_of_range)
20117 << llvm::toString(Result.getInt(), 10) << Min.getSExtValue()
20118 << Max.getSExtValue() << ED;
20119 else if (!ED->getNumNegativeBits() &&
20120 Max.ult(Result.getInt().getZExtValue()))
20121 Info.CCEDiag(E, diag::note_constexpr_unscoped_enum_out_of_range)
20122 << llvm::toString(Result.getInt(), 10) << Min.getZExtValue()
20123 << Max.getZExtValue() << ED;
20124 }
20125 }
20126
20127 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
20128 Result.getInt()), E);
20129 }
20130
20131 case CK_PointerToIntegral: {
20132 CCEDiag(E, diag::note_constexpr_invalid_cast_ptrtoint)
20133 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
20134 << Info.Ctx.getLangOpts().CPlusPlus << E->getSourceRange();
20135
20136 LValue LV;
20137 if (!EvaluatePointer(SubExpr, LV, Info))
20138 return false;
20139
20140 if (LV.getLValueBase()) {
20141 CCEDiag(E, diag::note_constexpr_has_lvalue) << E->getSourceRange();
20142 // Only allow based lvalue casts if they are lossless.
20143 // FIXME: Allow a larger integer size than the pointer size, and allow
20144 // narrowing back down to pointer width in subsequent integral casts.
20145 // FIXME: Check integer type's active bits, not its type size.
20146 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
20147 return Error(E);
20148
20149 LV.Designator.setInvalid();
20150 LV.moveInto(Result);
20151 return true;
20152 }
20153
20154 APSInt AsInt;
20155 APValue V;
20156 LV.moveInto(V);
20157 if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
20158 llvm_unreachable("Can't cast this!");
20159
20160 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
20161 }
20162
20163 case CK_IntegralComplexToReal: {
20164 ComplexValue C;
20165 if (!EvaluateComplex(SubExpr, C, Info))
20166 return false;
20167 return Success(C.getComplexIntReal(), E);
20168 }
20169
20170 case CK_FloatingToIntegral: {
20171 APFloat F(0.0);
20172 if (!EvaluateFloat(SubExpr, F, Info))
20173 return false;
20174
20175 APSInt Value;
20176 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
20177 return false;
20178 return Success(Value, E);
20179 }
20180 case CK_HLSLVectorTruncation: {
20181 APValue Val;
20182 if (!EvaluateVector(SubExpr, Val, Info))
20183 return Error(E);
20184 return Success(Val.getVectorElt(0), E);
20185 }
20186 case CK_HLSLMatrixTruncation: {
20187 APValue Val;
20188 if (!EvaluateMatrix(SubExpr, Val, Info))
20189 return Error(E);
20190 return Success(Val.getMatrixElt(0, 0), E);
20191 }
20192 case CK_HLSLElementwiseCast: {
20193 SmallVector<APValue> SrcVals;
20194 SmallVector<QualType> SrcTypes;
20195
20196 if (!hlslElementwiseCastHelper(Info, SubExpr, DestType, SrcVals, SrcTypes))
20197 return false;
20198
20199 // cast our single element
20200 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
20201 APValue ResultVal;
20202 if (!handleScalarCast(Info, FPO, E, SrcTypes[0], DestType, SrcVals[0],
20203 ResultVal))
20204 return false;
20205 return Success(ResultVal, E);
20206 }
20207 }
20208
20209 llvm_unreachable("unknown cast resulting in integral value");
20210}
20211
20212bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
20213 if (E->getSubExpr()->getType()->isAnyComplexType()) {
20214 ComplexValue LV;
20215 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
20216 return false;
20217 if (!LV.isComplexInt())
20218 return Error(E);
20219 return Success(LV.getComplexIntReal(), E);
20220 }
20221
20222 return Visit(E->getSubExpr());
20223}
20224
20225bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
20226 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
20227 ComplexValue LV;
20228 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
20229 return false;
20230 if (!LV.isComplexInt())
20231 return Error(E);
20232 return Success(LV.getComplexIntImag(), E);
20233 }
20234
20235 VisitIgnoredValue(E->getSubExpr());
20236 return Success(0, E);
20237}
20238
20239bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
20240 return Success(E->getPackLength(), E);
20241}
20242
20243bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
20244 return Success(E->getValue(), E);
20245}
20246
20247bool IntExprEvaluator::VisitConceptSpecializationExpr(
20248 const ConceptSpecializationExpr *E) {
20249 return Success(E->isSatisfied(), E);
20250}
20251
20252bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) {
20253 return Success(E->isSatisfied(), E);
20254}
20255
20256bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
20257 switch (E->getOpcode()) {
20258 default:
20259 // Invalid unary operators
20260 return Error(E);
20261 case UO_Plus:
20262 // The result is just the value.
20263 return Visit(E->getSubExpr());
20264 case UO_Minus: {
20265 if (!Visit(E->getSubExpr())) return false;
20266 if (!Result.isFixedPoint())
20267 return Error(E);
20268 bool Overflowed;
20269 APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
20270 if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
20271 return false;
20272 return Success(Negated, E);
20273 }
20274 case UO_LNot: {
20275 bool bres;
20276 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
20277 return false;
20278 return Success(!bres, E);
20279 }
20280 }
20281}
20282
20283bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
20284 const Expr *SubExpr = E->getSubExpr();
20285 QualType DestType = E->getType();
20286 assert(DestType->isFixedPointType() &&
20287 "Expected destination type to be a fixed point type");
20288 auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
20289
20290 switch (E->getCastKind()) {
20291 case CK_FixedPointCast: {
20292 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
20293 if (!EvaluateFixedPoint(SubExpr, Src, Info))
20294 return false;
20295 bool Overflowed;
20296 APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
20297 if (Overflowed) {
20298 if (Info.checkingForUndefinedBehavior())
20299 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
20300 diag::warn_fixedpoint_constant_overflow)
20301 << Result.toString() << E->getType();
20302 if (!HandleOverflow(Info, E, Result, E->getType()))
20303 return false;
20304 }
20305 return Success(Result, E);
20306 }
20307 case CK_IntegralToFixedPoint: {
20308 APSInt Src;
20309 if (!EvaluateInteger(SubExpr, Src, Info))
20310 return false;
20311
20312 bool Overflowed;
20313 APFixedPoint IntResult = APFixedPoint::getFromIntValue(
20314 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
20315
20316 if (Overflowed) {
20317 if (Info.checkingForUndefinedBehavior())
20318 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
20319 diag::warn_fixedpoint_constant_overflow)
20320 << IntResult.toString() << E->getType();
20321 if (!HandleOverflow(Info, E, IntResult, E->getType()))
20322 return false;
20323 }
20324
20325 return Success(IntResult, E);
20326 }
20327 case CK_FloatingToFixedPoint: {
20328 APFloat Src(0.0);
20329 if (!EvaluateFloat(SubExpr, Src, Info))
20330 return false;
20331
20332 bool Overflowed;
20333 APFixedPoint Result = APFixedPoint::getFromFloatValue(
20334 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
20335
20336 if (Overflowed) {
20337 if (Info.checkingForUndefinedBehavior())
20338 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
20339 diag::warn_fixedpoint_constant_overflow)
20340 << Result.toString() << E->getType();
20341 if (!HandleOverflow(Info, E, Result, E->getType()))
20342 return false;
20343 }
20344
20345 return Success(Result, E);
20346 }
20347 case CK_NoOp:
20348 case CK_LValueToRValue:
20349 return ExprEvaluatorBaseTy::VisitCastExpr(E);
20350 default:
20351 return Error(E);
20352 }
20353}
20354
20355bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
20356 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
20357 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
20358
20359 const Expr *LHS = E->getLHS();
20360 const Expr *RHS = E->getRHS();
20361 FixedPointSemantics ResultFXSema =
20362 Info.Ctx.getFixedPointSemantics(E->getType());
20363
20364 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
20365 if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
20366 return false;
20367 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
20368 if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
20369 return false;
20370
20371 bool OpOverflow = false, ConversionOverflow = false;
20372 APFixedPoint Result(LHSFX.getSemantics());
20373 switch (E->getOpcode()) {
20374 case BO_Add: {
20375 Result = LHSFX.add(RHSFX, &OpOverflow)
20376 .convert(ResultFXSema, &ConversionOverflow);
20377 break;
20378 }
20379 case BO_Sub: {
20380 Result = LHSFX.sub(RHSFX, &OpOverflow)
20381 .convert(ResultFXSema, &ConversionOverflow);
20382 break;
20383 }
20384 case BO_Mul: {
20385 Result = LHSFX.mul(RHSFX, &OpOverflow)
20386 .convert(ResultFXSema, &ConversionOverflow);
20387 break;
20388 }
20389 case BO_Div: {
20390 if (RHSFX.getValue() == 0) {
20391 Info.FFDiag(E, diag::note_expr_divide_by_zero);
20392 return false;
20393 }
20394 Result = LHSFX.div(RHSFX, &OpOverflow)
20395 .convert(ResultFXSema, &ConversionOverflow);
20396 break;
20397 }
20398 case BO_Shl:
20399 case BO_Shr: {
20400 FixedPointSemantics LHSSema = LHSFX.getSemantics();
20401 llvm::APSInt RHSVal = RHSFX.getValue();
20402
20403 unsigned ShiftBW =
20404 LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding();
20405 unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1);
20406 // Embedded-C 4.1.6.2.2:
20407 // The right operand must be nonnegative and less than the total number
20408 // of (nonpadding) bits of the fixed-point operand ...
20409 if (RHSVal.isNegative())
20410 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal;
20411 else if (Amt != RHSVal)
20412 Info.CCEDiag(E, diag::note_constexpr_large_shift)
20413 << RHSVal << E->getType() << ShiftBW;
20414
20415 if (E->getOpcode() == BO_Shl)
20416 Result = LHSFX.shl(Amt, &OpOverflow);
20417 else
20418 Result = LHSFX.shr(Amt, &OpOverflow);
20419 break;
20420 }
20421 default:
20422 return false;
20423 }
20424 if (OpOverflow || ConversionOverflow) {
20425 if (Info.checkingForUndefinedBehavior())
20426 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
20427 diag::warn_fixedpoint_constant_overflow)
20428 << Result.toString() << E->getType();
20429 if (!HandleOverflow(Info, E, Result, E->getType()))
20430 return false;
20431 }
20432 return Success(Result, E);
20433}
20434
20435//===----------------------------------------------------------------------===//
20436// Float Evaluation
20437//===----------------------------------------------------------------------===//
20438
20439namespace {
20440class FloatExprEvaluator
20441 : public ExprEvaluatorBase<FloatExprEvaluator> {
20442 APFloat &Result;
20443public:
20444 FloatExprEvaluator(EvalInfo &info, APFloat &result)
20445 : ExprEvaluatorBaseTy(info), Result(result) {}
20446
20447 bool Success(const APValue &V, const Expr *e) {
20448 Result = V.getFloat();
20449 return true;
20450 }
20451
20452 bool ZeroInitialization(const Expr *E) {
20453 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
20454 return true;
20455 }
20456
20457 bool VisitCallExpr(const CallExpr *E);
20458
20459 bool VisitUnaryOperator(const UnaryOperator *E);
20460 bool VisitBinaryOperator(const BinaryOperator *E);
20461 bool VisitFloatingLiteral(const FloatingLiteral *E);
20462 bool VisitCastExpr(const CastExpr *E);
20463
20464 bool VisitUnaryReal(const UnaryOperator *E);
20465 bool VisitUnaryImag(const UnaryOperator *E);
20466
20467 // FIXME: Missing: array subscript of vector, member of vector
20468};
20469} // end anonymous namespace
20470
20471static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
20472 assert(!E->isValueDependent());
20473 assert(E->isPRValue() && E->getType()->isRealFloatingType());
20474 return FloatExprEvaluator(Info, Result).Visit(E);
20475}
20476
20477static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
20478 QualType ResultTy,
20479 const Expr *Arg,
20480 bool SNaN,
20481 llvm::APFloat &Result) {
20482 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
20483 if (!S || !S->isOrdinary())
20484 return false;
20485
20486 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
20487
20488 llvm::APInt fill;
20489
20490 // Treat empty strings as if they were zero.
20491 if (S->getString().empty())
20492 fill = llvm::APInt(32, 0);
20493 else if (S->getString().getAsInteger(0, fill))
20494 return false;
20495
20496 if (Context.getTargetInfo().isNan2008()) {
20497 if (SNaN)
20498 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
20499 else
20500 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
20501 } else {
20502 // Prior to IEEE 754-2008, architectures were allowed to choose whether
20503 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
20504 // a different encoding to what became a standard in 2008, and for pre-
20505 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
20506 // sNaN. This is now known as "legacy NaN" encoding.
20507 if (SNaN)
20508 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
20509 else
20510 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
20511 }
20512
20513 return true;
20514}
20515
20516bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
20517 if (!IsConstantEvaluatedBuiltinCall(E))
20518 return ExprEvaluatorBaseTy::VisitCallExpr(E);
20519
20520 unsigned BuiltinOp = ConvertBuiltinIDToX86BuiltinID(Info.Ctx, E);
20521
20522 switch (BuiltinOp) {
20523 default:
20524 return false;
20525
20526 case Builtin::BI__builtin_huge_val:
20527 case Builtin::BI__builtin_huge_valf:
20528 case Builtin::BI__builtin_huge_vall:
20529 case Builtin::BI__builtin_huge_valf16:
20530 case Builtin::BI__builtin_huge_valf128:
20531 case Builtin::BI__builtin_inf:
20532 case Builtin::BI__builtin_inff:
20533 case Builtin::BI__builtin_infl:
20534 case Builtin::BI__builtin_inff16:
20535 case Builtin::BI__builtin_inff128: {
20536 const llvm::fltSemantics &Sem =
20537 Info.Ctx.getFloatTypeSemantics(E->getType());
20538 Result = llvm::APFloat::getInf(Sem);
20539 return true;
20540 }
20541
20542 case Builtin::BI__builtin_nans:
20543 case Builtin::BI__builtin_nansf:
20544 case Builtin::BI__builtin_nansl:
20545 case Builtin::BI__builtin_nansf16:
20546 case Builtin::BI__builtin_nansf128:
20547 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
20548 true, Result))
20549 return Error(E);
20550 return true;
20551
20552 case Builtin::BI__builtin_nan:
20553 case Builtin::BI__builtin_nanf:
20554 case Builtin::BI__builtin_nanl:
20555 case Builtin::BI__builtin_nanf16:
20556 case Builtin::BI__builtin_nanf128:
20557 // If this is __builtin_nan() turn this into a nan, otherwise we
20558 // can't constant fold it.
20559 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
20560 false, Result))
20561 return Error(E);
20562 return true;
20563
20564 case Builtin::BI__builtin_elementwise_abs:
20565 case Builtin::BI__builtin_fabs:
20566 case Builtin::BI__builtin_fabsf:
20567 case Builtin::BI__builtin_fabsl:
20568 case Builtin::BI__builtin_fabsf128:
20569 // The C standard says "fabs raises no floating-point exceptions,
20570 // even if x is a signaling NaN. The returned value is independent of
20571 // the current rounding direction mode." Therefore constant folding can
20572 // proceed without regard to the floating point settings.
20573 // Reference, WG14 N2478 F.10.4.3
20574 if (!EvaluateFloat(E->getArg(0), Result, Info))
20575 return false;
20576
20577 if (Result.isNegative())
20578 Result.changeSign();
20579 return true;
20580
20581 case Builtin::BI__arithmetic_fence:
20582 return EvaluateFloat(E->getArg(0), Result, Info);
20583
20584 // FIXME: Builtin::BI__builtin_powi
20585 // FIXME: Builtin::BI__builtin_powif
20586 // FIXME: Builtin::BI__builtin_powil
20587
20588 case Builtin::BI__builtin_copysign:
20589 case Builtin::BI__builtin_copysignf:
20590 case Builtin::BI__builtin_copysignl:
20591 case Builtin::BI__builtin_copysignf128: {
20592 APFloat RHS(0.);
20593 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
20594 !EvaluateFloat(E->getArg(1), RHS, Info))
20595 return false;
20596 Result.copySign(RHS);
20597 return true;
20598 }
20599
20600 case Builtin::BI__builtin_fmax:
20601 case Builtin::BI__builtin_fmaxf:
20602 case Builtin::BI__builtin_fmaxl:
20603 case Builtin::BI__builtin_fmaxf16:
20604 case Builtin::BI__builtin_fmaxf128: {
20605 APFloat RHS(0.);
20606 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
20607 !EvaluateFloat(E->getArg(1), RHS, Info))
20608 return false;
20609 Result = maxnum(Result, RHS);
20610 return true;
20611 }
20612
20613 case Builtin::BI__builtin_fmin:
20614 case Builtin::BI__builtin_fminf:
20615 case Builtin::BI__builtin_fminl:
20616 case Builtin::BI__builtin_fminf16:
20617 case Builtin::BI__builtin_fminf128: {
20618 APFloat RHS(0.);
20619 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
20620 !EvaluateFloat(E->getArg(1), RHS, Info))
20621 return false;
20622 Result = minnum(Result, RHS);
20623 return true;
20624 }
20625
20626 case Builtin::BI__builtin_fmaximum_num:
20627 case Builtin::BI__builtin_fmaximum_numf:
20628 case Builtin::BI__builtin_fmaximum_numl:
20629 case Builtin::BI__builtin_fmaximum_numf16:
20630 case Builtin::BI__builtin_fmaximum_numf128: {
20631 APFloat RHS(0.);
20632 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
20633 !EvaluateFloat(E->getArg(1), RHS, Info))
20634 return false;
20635 Result = maximumnum(Result, RHS);
20636 return true;
20637 }
20638
20639 case Builtin::BI__builtin_fminimum_num:
20640 case Builtin::BI__builtin_fminimum_numf:
20641 case Builtin::BI__builtin_fminimum_numl:
20642 case Builtin::BI__builtin_fminimum_numf16:
20643 case Builtin::BI__builtin_fminimum_numf128: {
20644 APFloat RHS(0.);
20645 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
20646 !EvaluateFloat(E->getArg(1), RHS, Info))
20647 return false;
20648 Result = minimumnum(Result, RHS);
20649 return true;
20650 }
20651
20652 case Builtin::BI__builtin_elementwise_fma: {
20653 if (!E->getArg(0)->isPRValue() || !E->getArg(1)->isPRValue() ||
20654 !E->getArg(2)->isPRValue()) {
20655 return false;
20656 }
20657 APFloat SourceY(0.), SourceZ(0.);
20658 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
20659 !EvaluateFloat(E->getArg(1), SourceY, Info) ||
20660 !EvaluateFloat(E->getArg(2), SourceZ, Info))
20661 return false;
20662 llvm::RoundingMode RM = getActiveRoundingMode(getEvalInfo(), E);
20663 (void)Result.fusedMultiplyAdd(SourceY, SourceZ, RM);
20664 return true;
20665 }
20666
20667 case clang::X86::BI__builtin_ia32_vec_ext_v4sf: {
20668 APValue Vec;
20669 APSInt IdxAPS;
20670 if (!EvaluateVector(E->getArg(0), Vec, Info) ||
20671 !EvaluateInteger(E->getArg(1), IdxAPS, Info))
20672 return false;
20673 unsigned N = Vec.getVectorLength();
20674 unsigned Idx = static_cast<unsigned>(IdxAPS.getZExtValue() & (N - 1));
20675 return Success(Vec.getVectorElt(Idx), E);
20676 }
20677 }
20678}
20679
20680bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
20681 if (E->getSubExpr()->getType()->isAnyComplexType()) {
20682 ComplexValue CV;
20683 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
20684 return false;
20685 Result = CV.FloatReal;
20686 return true;
20687 }
20688
20689 return Visit(E->getSubExpr());
20690}
20691
20692bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
20693 if (E->getSubExpr()->getType()->isAnyComplexType()) {
20694 ComplexValue CV;
20695 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
20696 return false;
20697 Result = CV.FloatImag;
20698 return true;
20699 }
20700
20701 VisitIgnoredValue(E->getSubExpr());
20702 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
20703 Result = llvm::APFloat::getZero(Sem);
20704 return true;
20705}
20706
20707bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
20708 switch (E->getOpcode()) {
20709 default: return Error(E);
20710 case UO_Plus:
20711 return EvaluateFloat(E->getSubExpr(), Result, Info);
20712 case UO_Minus:
20713 // In C standard, WG14 N2478 F.3 p4
20714 // "the unary - raises no floating point exceptions,
20715 // even if the operand is signalling."
20716 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
20717 return false;
20718 Result.changeSign();
20719 return true;
20720 }
20721}
20722
20723bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
20724 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
20725 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
20726
20727 APFloat RHS(0.0);
20728 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
20729 if (!LHSOK && !Info.noteFailure())
20730 return false;
20731 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
20732 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
20733}
20734
20735bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
20736 Result = E->getValue();
20737 return true;
20738}
20739
20740bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
20741 const Expr* SubExpr = E->getSubExpr();
20742
20743 switch (E->getCastKind()) {
20744 default:
20745 return ExprEvaluatorBaseTy::VisitCastExpr(E);
20746
20747 case CK_HLSLAggregateSplatCast:
20748 llvm_unreachable("invalid cast kind for floating value");
20749
20750 case CK_IntegralToFloating: {
20751 APSInt IntResult;
20752 const FPOptions FPO = E->getFPFeaturesInEffect(
20753 Info.Ctx.getLangOpts());
20754 return EvaluateInteger(SubExpr, IntResult, Info) &&
20755 HandleIntToFloatCast(Info, E, FPO, SubExpr->getType(),
20756 IntResult, E->getType(), Result);
20757 }
20758
20759 case CK_FixedPointToFloating: {
20760 APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
20761 if (!EvaluateFixedPoint(SubExpr, FixResult, Info))
20762 return false;
20763 Result =
20764 FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->getType()));
20765 return true;
20766 }
20767
20768 case CK_FloatingCast: {
20769 if (!Visit(SubExpr))
20770 return false;
20771 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
20772 Result);
20773 }
20774
20775 case CK_FloatingComplexToReal: {
20776 ComplexValue V;
20777 if (!EvaluateComplex(SubExpr, V, Info))
20778 return false;
20779 Result = V.getComplexFloatReal();
20780 return true;
20781 }
20782 case CK_HLSLVectorTruncation: {
20783 APValue Val;
20784 if (!EvaluateVector(SubExpr, Val, Info))
20785 return Error(E);
20786 return Success(Val.getVectorElt(0), E);
20787 }
20788 case CK_HLSLMatrixTruncation: {
20789 APValue Val;
20790 if (!EvaluateMatrix(SubExpr, Val, Info))
20791 return Error(E);
20792 return Success(Val.getMatrixElt(0, 0), E);
20793 }
20794 case CK_HLSLElementwiseCast: {
20795 SmallVector<APValue> SrcVals;
20796 SmallVector<QualType> SrcTypes;
20797
20798 if (!hlslElementwiseCastHelper(Info, SubExpr, E->getType(), SrcVals,
20799 SrcTypes))
20800 return false;
20801
20802 // Cast our single element.
20803 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
20804 APValue ResultVal;
20805 if (!handleScalarCast(Info, FPO, E, SrcTypes[0], E->getType(), SrcVals[0],
20806 ResultVal))
20807 return false;
20808 return Success(ResultVal, E);
20809 }
20810 }
20811}
20812
20813//===----------------------------------------------------------------------===//
20814// Complex Evaluation (for float and integer)
20815//===----------------------------------------------------------------------===//
20816
20817namespace {
20818class ComplexExprEvaluator
20819 : public ExprEvaluatorBase<ComplexExprEvaluator> {
20820 ComplexValue &Result;
20821
20822public:
20823 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
20824 : ExprEvaluatorBaseTy(info), Result(Result) {}
20825
20826 bool Success(const APValue &V, const Expr *e) {
20827 Result.setFrom(V);
20828 return true;
20829 }
20830
20831 bool ZeroInitialization(const Expr *E);
20832
20833 //===--------------------------------------------------------------------===//
20834 // Visitor Methods
20835 //===--------------------------------------------------------------------===//
20836
20837 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
20838 bool VisitCastExpr(const CastExpr *E);
20839 bool VisitBinaryOperator(const BinaryOperator *E);
20840 bool VisitUnaryOperator(const UnaryOperator *E);
20841 bool VisitInitListExpr(const InitListExpr *E);
20842 bool VisitCallExpr(const CallExpr *E);
20843};
20844} // end anonymous namespace
20845
20846static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
20847 EvalInfo &Info) {
20848 assert(!E->isValueDependent());
20849 assert(E->isPRValue() && E->getType()->isAnyComplexType());
20850 return ComplexExprEvaluator(Info, Result).Visit(E);
20851}
20852
20853bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
20854 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
20855 if (ElemTy->isRealFloatingType()) {
20856 Result.makeComplexFloat();
20857 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
20858 Result.FloatReal = Zero;
20859 Result.FloatImag = Zero;
20860 } else {
20861 Result.makeComplexInt();
20862 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
20863 Result.IntReal = Zero;
20864 Result.IntImag = Zero;
20865 }
20866 return true;
20867}
20868
20869bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
20870 const Expr* SubExpr = E->getSubExpr();
20871
20872 if (SubExpr->getType()->isRealFloatingType()) {
20873 Result.makeComplexFloat();
20874 APFloat &Imag = Result.FloatImag;
20875 if (!EvaluateFloat(SubExpr, Imag, Info))
20876 return false;
20877
20878 Result.FloatReal = APFloat(Imag.getSemantics());
20879 return true;
20880 } else {
20881 assert(SubExpr->getType()->isIntegerType() &&
20882 "Unexpected imaginary literal.");
20883
20884 Result.makeComplexInt();
20885 APSInt &Imag = Result.IntImag;
20886 if (!EvaluateInteger(SubExpr, Imag, Info))
20887 return false;
20888
20889 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
20890 return true;
20891 }
20892}
20893
20894bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
20895
20896 switch (E->getCastKind()) {
20897 case CK_BitCast:
20898 case CK_BaseToDerived:
20899 case CK_DerivedToBase:
20900 case CK_UncheckedDerivedToBase:
20901 case CK_Dynamic:
20902 case CK_ToUnion:
20903 case CK_ArrayToPointerDecay:
20904 case CK_FunctionToPointerDecay:
20905 case CK_NullToPointer:
20906 case CK_NullToMemberPointer:
20907 case CK_BaseToDerivedMemberPointer:
20908 case CK_DerivedToBaseMemberPointer:
20909 case CK_MemberPointerToBoolean:
20910 case CK_ReinterpretMemberPointer:
20911 case CK_ConstructorConversion:
20912 case CK_IntegralToPointer:
20913 case CK_PointerToIntegral:
20914 case CK_PointerToBoolean:
20915 case CK_ToVoid:
20916 case CK_VectorSplat:
20917 case CK_IntegralCast:
20918 case CK_BooleanToSignedIntegral:
20919 case CK_IntegralToBoolean:
20920 case CK_IntegralToFloating:
20921 case CK_FloatingToIntegral:
20922 case CK_FloatingToBoolean:
20923 case CK_FloatingCast:
20924 case CK_CPointerToObjCPointerCast:
20925 case CK_BlockPointerToObjCPointerCast:
20926 case CK_AnyPointerToBlockPointerCast:
20927 case CK_ObjCObjectLValueCast:
20928 case CK_FloatingComplexToReal:
20929 case CK_FloatingComplexToBoolean:
20930 case CK_IntegralComplexToReal:
20931 case CK_IntegralComplexToBoolean:
20932 case CK_ARCProduceObject:
20933 case CK_ARCConsumeObject:
20934 case CK_ARCReclaimReturnedObject:
20935 case CK_ARCExtendBlockObject:
20936 case CK_CopyAndAutoreleaseBlockObject:
20937 case CK_BuiltinFnToFnPtr:
20938 case CK_ZeroToOCLOpaqueType:
20939 case CK_NonAtomicToAtomic:
20940 case CK_AddressSpaceConversion:
20941 case CK_IntToOCLSampler:
20942 case CK_FloatingToFixedPoint:
20943 case CK_FixedPointToFloating:
20944 case CK_FixedPointCast:
20945 case CK_FixedPointToBoolean:
20946 case CK_FixedPointToIntegral:
20947 case CK_IntegralToFixedPoint:
20948 case CK_MatrixCast:
20949 case CK_HLSLVectorTruncation:
20950 case CK_HLSLMatrixTruncation:
20951 case CK_HLSLElementwiseCast:
20952 case CK_HLSLAggregateSplatCast:
20953 llvm_unreachable("invalid cast kind for complex value");
20954
20955 case CK_LValueToRValue:
20956 case CK_AtomicToNonAtomic:
20957 case CK_NoOp:
20958 case CK_LValueToRValueBitCast:
20959 case CK_HLSLArrayRValue:
20960 return ExprEvaluatorBaseTy::VisitCastExpr(E);
20961
20962 case CK_Dependent:
20963 case CK_LValueBitCast:
20964 case CK_UserDefinedConversion:
20965 return Error(E);
20966
20967 case CK_FloatingRealToComplex: {
20968 APFloat &Real = Result.FloatReal;
20969 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
20970 return false;
20971
20972 Result.makeComplexFloat();
20973 Result.FloatImag = APFloat(Real.getSemantics());
20974 return true;
20975 }
20976
20977 case CK_FloatingComplexCast: {
20978 if (!Visit(E->getSubExpr()))
20979 return false;
20980
20981 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
20982 QualType From
20983 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
20984
20985 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
20986 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
20987 }
20988
20989 case CK_FloatingComplexToIntegralComplex: {
20990 if (!Visit(E->getSubExpr()))
20991 return false;
20992
20993 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
20994 QualType From
20995 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
20996 Result.makeComplexInt();
20997 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
20998 To, Result.IntReal) &&
20999 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
21000 To, Result.IntImag);
21001 }
21002
21003 case CK_IntegralRealToComplex: {
21004 APSInt &Real = Result.IntReal;
21005 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
21006 return false;
21007
21008 Result.makeComplexInt();
21009 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
21010 return true;
21011 }
21012
21013 case CK_IntegralComplexCast: {
21014 if (!Visit(E->getSubExpr()))
21015 return false;
21016
21017 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
21018 QualType From
21019 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
21020
21021 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
21022 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
21023 return true;
21024 }
21025
21026 case CK_IntegralComplexToFloatingComplex: {
21027 if (!Visit(E->getSubExpr()))
21028 return false;
21029
21030 const FPOptions FPO = E->getFPFeaturesInEffect(
21031 Info.Ctx.getLangOpts());
21032 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
21033 QualType From
21034 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
21035 Result.makeComplexFloat();
21036 return HandleIntToFloatCast(Info, E, FPO, From, Result.IntReal,
21037 To, Result.FloatReal) &&
21038 HandleIntToFloatCast(Info, E, FPO, From, Result.IntImag,
21039 To, Result.FloatImag);
21040 }
21041 }
21042
21043 llvm_unreachable("unknown cast resulting in complex value");
21044}
21045
21047 // Lookup Table for Multiplicative Inverse in GF(2^8)
21048 const uint8_t GFInv[256] = {
21049 0x00, 0x01, 0x8d, 0xf6, 0xcb, 0x52, 0x7b, 0xd1, 0xe8, 0x4f, 0x29, 0xc0,
21050 0xb0, 0xe1, 0xe5, 0xc7, 0x74, 0xb4, 0xaa, 0x4b, 0x99, 0x2b, 0x60, 0x5f,
21051 0x58, 0x3f, 0xfd, 0xcc, 0xff, 0x40, 0xee, 0xb2, 0x3a, 0x6e, 0x5a, 0xf1,
21052 0x55, 0x4d, 0xa8, 0xc9, 0xc1, 0x0a, 0x98, 0x15, 0x30, 0x44, 0xa2, 0xc2,
21053 0x2c, 0x45, 0x92, 0x6c, 0xf3, 0x39, 0x66, 0x42, 0xf2, 0x35, 0x20, 0x6f,
21054 0x77, 0xbb, 0x59, 0x19, 0x1d, 0xfe, 0x37, 0x67, 0x2d, 0x31, 0xf5, 0x69,
21055 0xa7, 0x64, 0xab, 0x13, 0x54, 0x25, 0xe9, 0x09, 0xed, 0x5c, 0x05, 0xca,
21056 0x4c, 0x24, 0x87, 0xbf, 0x18, 0x3e, 0x22, 0xf0, 0x51, 0xec, 0x61, 0x17,
21057 0x16, 0x5e, 0xaf, 0xd3, 0x49, 0xa6, 0x36, 0x43, 0xf4, 0x47, 0x91, 0xdf,
21058 0x33, 0x93, 0x21, 0x3b, 0x79, 0xb7, 0x97, 0x85, 0x10, 0xb5, 0xba, 0x3c,
21059 0xb6, 0x70, 0xd0, 0x06, 0xa1, 0xfa, 0x81, 0x82, 0x83, 0x7e, 0x7f, 0x80,
21060 0x96, 0x73, 0xbe, 0x56, 0x9b, 0x9e, 0x95, 0xd9, 0xf7, 0x02, 0xb9, 0xa4,
21061 0xde, 0x6a, 0x32, 0x6d, 0xd8, 0x8a, 0x84, 0x72, 0x2a, 0x14, 0x9f, 0x88,
21062 0xf9, 0xdc, 0x89, 0x9a, 0xfb, 0x7c, 0x2e, 0xc3, 0x8f, 0xb8, 0x65, 0x48,
21063 0x26, 0xc8, 0x12, 0x4a, 0xce, 0xe7, 0xd2, 0x62, 0x0c, 0xe0, 0x1f, 0xef,
21064 0x11, 0x75, 0x78, 0x71, 0xa5, 0x8e, 0x76, 0x3d, 0xbd, 0xbc, 0x86, 0x57,
21065 0x0b, 0x28, 0x2f, 0xa3, 0xda, 0xd4, 0xe4, 0x0f, 0xa9, 0x27, 0x53, 0x04,
21066 0x1b, 0xfc, 0xac, 0xe6, 0x7a, 0x07, 0xae, 0x63, 0xc5, 0xdb, 0xe2, 0xea,
21067 0x94, 0x8b, 0xc4, 0xd5, 0x9d, 0xf8, 0x90, 0x6b, 0xb1, 0x0d, 0xd6, 0xeb,
21068 0xc6, 0x0e, 0xcf, 0xad, 0x08, 0x4e, 0xd7, 0xe3, 0x5d, 0x50, 0x1e, 0xb3,
21069 0x5b, 0x23, 0x38, 0x34, 0x68, 0x46, 0x03, 0x8c, 0xdd, 0x9c, 0x7d, 0xa0,
21070 0xcd, 0x1a, 0x41, 0x1c};
21071
21072 return GFInv[Byte];
21073}
21074
21075uint8_t GFNIAffine(uint8_t XByte, const APInt &AQword, const APSInt &Imm,
21076 bool Inverse) {
21077 unsigned NumBitsInByte = 8;
21078 // Computing the affine transformation
21079 uint8_t RetByte = 0;
21080 for (uint32_t BitIdx = 0; BitIdx != NumBitsInByte; ++BitIdx) {
21081 uint8_t AByte =
21082 AQword.lshr((7 - static_cast<int32_t>(BitIdx)) * NumBitsInByte)
21083 .getLoBits(8)
21084 .getZExtValue();
21085 uint8_t Product;
21086 if (Inverse) {
21087 Product = AByte & GFNIMultiplicativeInverse(XByte);
21088 } else {
21089 Product = AByte & XByte;
21090 }
21091 uint8_t Parity = 0;
21092
21093 // Dot product in GF(2) uses XOR instead of addition
21094 for (unsigned PBitIdx = 0; PBitIdx != NumBitsInByte; ++PBitIdx) {
21095 Parity = Parity ^ ((Product >> PBitIdx) & 0x1);
21096 }
21097
21098 uint8_t Temp = Imm[BitIdx] ? 1 : 0;
21099 RetByte |= (Temp ^ Parity) << BitIdx;
21100 }
21101 return RetByte;
21102}
21103
21105 // Multiplying two polynomials of degree 7
21106 // Polynomial of degree 7
21107 // x^7 + x^6 + x^5 + x^4 + x^3 + x^2 + x + 1
21108 uint16_t TWord = 0;
21109 unsigned NumBitsInByte = 8;
21110 for (unsigned BitIdx = 0; BitIdx != NumBitsInByte; ++BitIdx) {
21111 if ((BByte >> BitIdx) & 0x1) {
21112 TWord = TWord ^ (AByte << BitIdx);
21113 }
21114 }
21115
21116 // When multiplying two polynomials of degree 7
21117 // results in a polynomial of degree 14
21118 // so the result has to be reduced to 7
21119 // Reduction polynomial is x^8 + x^4 + x^3 + x + 1 i.e. 0x11B
21120 for (int32_t BitIdx = 14; BitIdx > 7; --BitIdx) {
21121 if ((TWord >> BitIdx) & 0x1) {
21122 TWord = TWord ^ (0x11B << (BitIdx - 8));
21123 }
21124 }
21125 return (TWord & 0xFF);
21126}
21127
21128void HandleComplexComplexMul(APFloat A, APFloat B, APFloat C, APFloat D,
21129 APFloat &ResR, APFloat &ResI) {
21130 // This is an implementation of complex multiplication according to the
21131 // constraints laid out in C11 Annex G. The implementation uses the
21132 // following naming scheme:
21133 // (a + ib) * (c + id)
21134
21135 APFloat AC = A * C;
21136 APFloat BD = B * D;
21137 APFloat AD = A * D;
21138 APFloat BC = B * C;
21139 ResR = AC - BD;
21140 ResI = AD + BC;
21141 if (ResR.isNaN() && ResI.isNaN()) {
21142 bool Recalc = false;
21143 if (A.isInfinity() || B.isInfinity()) {
21144 A = APFloat::copySign(APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0),
21145 A);
21146 B = APFloat::copySign(APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0),
21147 B);
21148 if (C.isNaN())
21149 C = APFloat::copySign(APFloat(C.getSemantics()), C);
21150 if (D.isNaN())
21151 D = APFloat::copySign(APFloat(D.getSemantics()), D);
21152 Recalc = true;
21153 }
21154 if (C.isInfinity() || D.isInfinity()) {
21155 C = APFloat::copySign(APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0),
21156 C);
21157 D = APFloat::copySign(APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0),
21158 D);
21159 if (A.isNaN())
21160 A = APFloat::copySign(APFloat(A.getSemantics()), A);
21161 if (B.isNaN())
21162 B = APFloat::copySign(APFloat(B.getSemantics()), B);
21163 Recalc = true;
21164 }
21165 if (!Recalc && (AC.isInfinity() || BD.isInfinity() || AD.isInfinity() ||
21166 BC.isInfinity())) {
21167 if (A.isNaN())
21168 A = APFloat::copySign(APFloat(A.getSemantics()), A);
21169 if (B.isNaN())
21170 B = APFloat::copySign(APFloat(B.getSemantics()), B);
21171 if (C.isNaN())
21172 C = APFloat::copySign(APFloat(C.getSemantics()), C);
21173 if (D.isNaN())
21174 D = APFloat::copySign(APFloat(D.getSemantics()), D);
21175 Recalc = true;
21176 }
21177 if (Recalc) {
21178 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
21179 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
21180 }
21181 }
21182}
21183
21184void HandleComplexComplexDiv(APFloat A, APFloat B, APFloat C, APFloat D,
21185 APFloat &ResR, APFloat &ResI) {
21186 // This is an implementation of complex division according to the
21187 // constraints laid out in C11 Annex G. The implementation uses the
21188 // following naming scheme:
21189 // (a + ib) / (c + id)
21190
21191 int DenomLogB = 0;
21192 APFloat MaxCD = maxnum(abs(C), abs(D));
21193 if (MaxCD.isFinite()) {
21194 DenomLogB = ilogb(MaxCD);
21195 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
21196 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
21197 }
21198 APFloat Denom = C * C + D * D;
21199 ResR =
21200 scalbn((A * C + B * D) / Denom, -DenomLogB, APFloat::rmNearestTiesToEven);
21201 ResI =
21202 scalbn((B * C - A * D) / Denom, -DenomLogB, APFloat::rmNearestTiesToEven);
21203 if (ResR.isNaN() && ResI.isNaN()) {
21204 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
21205 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
21206 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
21207 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
21208 D.isFinite()) {
21209 A = APFloat::copySign(APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0),
21210 A);
21211 B = APFloat::copySign(APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0),
21212 B);
21213 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
21214 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
21215 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
21216 C = APFloat::copySign(APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0),
21217 C);
21218 D = APFloat::copySign(APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0),
21219 D);
21220 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
21221 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
21222 }
21223 }
21224}
21225
21227 // Normalize shift amount to [0, BitWidth) range to match runtime behavior
21228 APSInt NormAmt = Amount;
21229 unsigned BitWidth = Value.getBitWidth();
21230 unsigned AmtBitWidth = NormAmt.getBitWidth();
21231 if (BitWidth == 1) {
21232 // Rotating a 1-bit value is always a no-op
21233 NormAmt = APSInt(APInt(AmtBitWidth, 0), NormAmt.isUnsigned());
21234 } else if (BitWidth == 2) {
21235 // For 2-bit values: rotation amount is 0 or 1 based on
21236 // whether the amount is even or odd. We can't use srem here because
21237 // the divisor (2) would be misinterpreted as -2 in 2-bit signed arithmetic.
21238 NormAmt =
21239 APSInt(APInt(AmtBitWidth, NormAmt[0] ? 1 : 0), NormAmt.isUnsigned());
21240 } else {
21241 APInt Divisor;
21242 if (AmtBitWidth > BitWidth) {
21243 Divisor = llvm::APInt(AmtBitWidth, BitWidth);
21244 } else {
21245 Divisor = llvm::APInt(BitWidth, BitWidth);
21246 if (AmtBitWidth < BitWidth) {
21247 NormAmt = NormAmt.extend(BitWidth);
21248 }
21249 }
21250
21251 // Normalize to [0, BitWidth)
21252 if (NormAmt.isSigned()) {
21253 NormAmt = APSInt(NormAmt.srem(Divisor), /*isUnsigned=*/false);
21254 if (NormAmt.isNegative()) {
21255 APSInt SignedDivisor(Divisor, /*isUnsigned=*/false);
21256 NormAmt += SignedDivisor;
21257 }
21258 } else {
21259 NormAmt = APSInt(NormAmt.urem(Divisor), /*isUnsigned=*/true);
21260 }
21261 }
21262
21263 return NormAmt;
21264}
21265
21266bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
21267 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
21268 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
21269
21270 // Track whether the LHS or RHS is real at the type system level. When this is
21271 // the case we can simplify our evaluation strategy.
21272 bool LHSReal = false, RHSReal = false;
21273
21274 bool LHSOK;
21275 if (E->getLHS()->getType()->isRealFloatingType()) {
21276 LHSReal = true;
21277 APFloat &Real = Result.FloatReal;
21278 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
21279 if (LHSOK) {
21280 Result.makeComplexFloat();
21281 Result.FloatImag = APFloat(Real.getSemantics());
21282 }
21283 } else {
21284 LHSOK = Visit(E->getLHS());
21285 }
21286 if (!LHSOK && !Info.noteFailure())
21287 return false;
21288
21289 ComplexValue RHS;
21290 if (E->getRHS()->getType()->isRealFloatingType()) {
21291 RHSReal = true;
21292 APFloat &Real = RHS.FloatReal;
21293 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
21294 return false;
21295 RHS.makeComplexFloat();
21296 RHS.FloatImag = APFloat(Real.getSemantics());
21297 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
21298 return false;
21299
21300 assert(!(LHSReal && RHSReal) &&
21301 "Cannot have both operands of a complex operation be real.");
21302 switch (E->getOpcode()) {
21303 default: return Error(E);
21304 case BO_Add:
21305 if (Result.isComplexFloat()) {
21306 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
21307 APFloat::rmNearestTiesToEven);
21308 if (LHSReal)
21309 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
21310 else if (!RHSReal)
21311 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
21312 APFloat::rmNearestTiesToEven);
21313 } else {
21314 Result.getComplexIntReal() += RHS.getComplexIntReal();
21315 Result.getComplexIntImag() += RHS.getComplexIntImag();
21316 }
21317 break;
21318 case BO_Sub:
21319 if (Result.isComplexFloat()) {
21320 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
21321 APFloat::rmNearestTiesToEven);
21322 if (LHSReal) {
21323 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
21324 Result.getComplexFloatImag().changeSign();
21325 } else if (!RHSReal) {
21326 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
21327 APFloat::rmNearestTiesToEven);
21328 }
21329 } else {
21330 Result.getComplexIntReal() -= RHS.getComplexIntReal();
21331 Result.getComplexIntImag() -= RHS.getComplexIntImag();
21332 }
21333 break;
21334 case BO_Mul:
21335 if (Result.isComplexFloat()) {
21336 // This is an implementation of complex multiplication according to the
21337 // constraints laid out in C11 Annex G. The implementation uses the
21338 // following naming scheme:
21339 // (a + ib) * (c + id)
21340 ComplexValue LHS = Result;
21341 APFloat &A = LHS.getComplexFloatReal();
21342 APFloat &B = LHS.getComplexFloatImag();
21343 APFloat &C = RHS.getComplexFloatReal();
21344 APFloat &D = RHS.getComplexFloatImag();
21345 APFloat &ResR = Result.getComplexFloatReal();
21346 APFloat &ResI = Result.getComplexFloatImag();
21347 if (LHSReal) {
21348 assert(!RHSReal && "Cannot have two real operands for a complex op!");
21349 ResR = A;
21350 ResI = A;
21351 // ResR = A * C;
21352 // ResI = A * D;
21353 if (!handleFloatFloatBinOp(Info, E, ResR, BO_Mul, C) ||
21354 !handleFloatFloatBinOp(Info, E, ResI, BO_Mul, D))
21355 return false;
21356 } else if (RHSReal) {
21357 // ResR = C * A;
21358 // ResI = C * B;
21359 ResR = C;
21360 ResI = C;
21361 if (!handleFloatFloatBinOp(Info, E, ResR, BO_Mul, A) ||
21362 !handleFloatFloatBinOp(Info, E, ResI, BO_Mul, B))
21363 return false;
21364 } else {
21365 HandleComplexComplexMul(A, B, C, D, ResR, ResI);
21366 }
21367 } else {
21368 ComplexValue LHS = Result;
21369 Result.getComplexIntReal() =
21370 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
21371 LHS.getComplexIntImag() * RHS.getComplexIntImag());
21372 Result.getComplexIntImag() =
21373 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
21374 LHS.getComplexIntImag() * RHS.getComplexIntReal());
21375 }
21376 break;
21377 case BO_Div:
21378 if (Result.isComplexFloat()) {
21379 // This is an implementation of complex division according to the
21380 // constraints laid out in C11 Annex G. The implementation uses the
21381 // following naming scheme:
21382 // (a + ib) / (c + id)
21383 ComplexValue LHS = Result;
21384 APFloat &A = LHS.getComplexFloatReal();
21385 APFloat &B = LHS.getComplexFloatImag();
21386 APFloat &C = RHS.getComplexFloatReal();
21387 APFloat &D = RHS.getComplexFloatImag();
21388 APFloat &ResR = Result.getComplexFloatReal();
21389 APFloat &ResI = Result.getComplexFloatImag();
21390 if (RHSReal) {
21391 ResR = A;
21392 ResI = B;
21393 // ResR = A / C;
21394 // ResI = B / C;
21395 if (!handleFloatFloatBinOp(Info, E, ResR, BO_Div, C) ||
21396 !handleFloatFloatBinOp(Info, E, ResI, BO_Div, C))
21397 return false;
21398 } else {
21399 if (LHSReal) {
21400 // No real optimizations we can do here, stub out with zero.
21401 B = APFloat::getZero(A.getSemantics());
21402 }
21403 HandleComplexComplexDiv(A, B, C, D, ResR, ResI);
21404 }
21405 } else {
21406 ComplexValue LHS = Result;
21407 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
21408 RHS.getComplexIntImag() * RHS.getComplexIntImag();
21409 if (Den.isZero())
21410 return Error(E, diag::note_expr_divide_by_zero);
21411
21412 Result.getComplexIntReal() =
21413 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
21414 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
21415 Result.getComplexIntImag() =
21416 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
21417 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
21418 }
21419 break;
21420 }
21421
21422 return true;
21423}
21424
21425bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
21426 // Get the operand value into 'Result'.
21427 if (!Visit(E->getSubExpr()))
21428 return false;
21429
21430 switch (E->getOpcode()) {
21431 default:
21432 return Error(E);
21433 case UO_Extension:
21434 return true;
21435 case UO_Plus:
21436 // The result is always just the subexpr.
21437 return true;
21438 case UO_Minus:
21439 if (Result.isComplexFloat()) {
21440 Result.getComplexFloatReal().changeSign();
21441 Result.getComplexFloatImag().changeSign();
21442 }
21443 else {
21444 Result.getComplexIntReal() = -Result.getComplexIntReal();
21445 Result.getComplexIntImag() = -Result.getComplexIntImag();
21446 }
21447 return true;
21448 case UO_Not:
21449 if (Result.isComplexFloat())
21450 Result.getComplexFloatImag().changeSign();
21451 else
21452 Result.getComplexIntImag() = -Result.getComplexIntImag();
21453 return true;
21454 }
21455}
21456
21457bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
21458 if (E->getNumInits() == 2) {
21459 if (E->getType()->isComplexType()) {
21460 Result.makeComplexFloat();
21461 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
21462 return false;
21463 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
21464 return false;
21465 } else {
21466 Result.makeComplexInt();
21467 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
21468 return false;
21469 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
21470 return false;
21471 }
21472 return true;
21473 }
21474 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
21475}
21476
21477bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) {
21478 if (!IsConstantEvaluatedBuiltinCall(E))
21479 return ExprEvaluatorBaseTy::VisitCallExpr(E);
21480
21481 switch (E->getBuiltinCallee()) {
21482 case Builtin::BI__builtin_complex:
21483 Result.makeComplexFloat();
21484 if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info))
21485 return false;
21486 if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info))
21487 return false;
21488 return true;
21489
21490 default:
21491 return false;
21492 }
21493}
21494
21495//===----------------------------------------------------------------------===//
21496// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
21497// implicit conversion.
21498//===----------------------------------------------------------------------===//
21499
21500namespace {
21501class AtomicExprEvaluator :
21502 public ExprEvaluatorBase<AtomicExprEvaluator> {
21503 const LValue *This;
21504 APValue &Result;
21505public:
21506 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
21507 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
21508
21509 bool Success(const APValue &V, const Expr *E) {
21510 Result = V;
21511 return true;
21512 }
21513
21514 bool ZeroInitialization(const Expr *E) {
21515 ImplicitValueInitExpr VIE(
21516 E->getType()->castAs<AtomicType>()->getValueType());
21517 // For atomic-qualified class (and array) types in C++, initialize the
21518 // _Atomic-wrapped subobject directly, in-place.
21519 return This ? EvaluateInPlace(Result, Info, *This, &VIE)
21520 : Evaluate(Result, Info, &VIE);
21521 }
21522
21523 bool VisitCastExpr(const CastExpr *E) {
21524 switch (E->getCastKind()) {
21525 default:
21526 return ExprEvaluatorBaseTy::VisitCastExpr(E);
21527 case CK_NullToPointer:
21528 VisitIgnoredValue(E->getSubExpr());
21529 return ZeroInitialization(E);
21530 case CK_NonAtomicToAtomic:
21531 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
21532 : Evaluate(Result, Info, E->getSubExpr());
21533 }
21534 }
21535};
21536} // end anonymous namespace
21537
21538static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
21539 EvalInfo &Info) {
21540 assert(!E->isValueDependent());
21541 assert(E->isPRValue() && E->getType()->isAtomicType());
21542 return AtomicExprEvaluator(Info, This, Result).Visit(E);
21543}
21544
21545//===----------------------------------------------------------------------===//
21546// Void expression evaluation, primarily for a cast to void on the LHS of a
21547// comma operator
21548//===----------------------------------------------------------------------===//
21549
21550namespace {
21551class VoidExprEvaluator
21552 : public ExprEvaluatorBase<VoidExprEvaluator> {
21553public:
21554 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
21555
21556 bool Success(const APValue &V, const Expr *e) { return true; }
21557
21558 bool ZeroInitialization(const Expr *E) { return true; }
21559
21560 bool VisitCastExpr(const CastExpr *E) {
21561 switch (E->getCastKind()) {
21562 default:
21563 return ExprEvaluatorBaseTy::VisitCastExpr(E);
21564 case CK_ToVoid:
21565 VisitIgnoredValue(E->getSubExpr());
21566 return true;
21567 }
21568 }
21569
21570 bool VisitCallExpr(const CallExpr *E) {
21571 if (!IsConstantEvaluatedBuiltinCall(E))
21572 return ExprEvaluatorBaseTy::VisitCallExpr(E);
21573
21574 switch (E->getBuiltinCallee()) {
21575 case Builtin::BI__assume:
21576 case Builtin::BI__builtin_assume:
21577 // The argument is not evaluated!
21578 return true;
21579
21580 case Builtin::BI__builtin_operator_delete:
21581 return HandleOperatorDeleteCall(Info, E);
21582
21583 default:
21584 return false;
21585 }
21586 }
21587
21588 bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
21589};
21590} // end anonymous namespace
21591
21592bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
21593 // We cannot speculatively evaluate a delete expression.
21594 if (Info.SpeculativeEvaluationDepth)
21595 return false;
21596
21597 FunctionDecl *OperatorDelete = E->getOperatorDelete();
21598 if (!OperatorDelete
21599 ->isUsableAsGlobalAllocationFunctionInConstantEvaluation()) {
21600 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
21601 << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;
21602 return false;
21603 }
21604
21605 const Expr *Arg = E->getArgument();
21606
21607 LValue Pointer;
21608 if (!EvaluatePointer(Arg, Pointer, Info))
21609 return false;
21610 if (Pointer.Designator.Invalid)
21611 return false;
21612
21613 // Deleting a null pointer has no effect.
21614 if (Pointer.isNullPointer()) {
21615 // This is the only case where we need to produce an extension warning:
21616 // the only other way we can succeed is if we find a dynamic allocation,
21617 // and we will have warned when we allocated it in that case.
21618 if (!Info.getLangOpts().CPlusPlus20)
21619 Info.CCEDiag(E, diag::note_constexpr_new);
21620 return true;
21621 }
21622
21623 std::optional<DynAlloc *> Alloc = CheckDeleteKind(
21624 Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New);
21625 if (!Alloc)
21626 return false;
21627 QualType AllocType = Pointer.Base.getDynamicAllocType();
21628
21629 // For the non-array case, the designator must be empty if the static type
21630 // does not have a virtual destructor.
21631 if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 &&
21633 Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor)
21634 << Arg->getType()->getPointeeType() << AllocType;
21635 return false;
21636 }
21637
21638 // For a class type with a virtual destructor, the selected operator delete
21639 // is the one looked up when building the destructor.
21640 if (!E->isArrayForm() && !E->isGlobalDelete()) {
21641 const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType);
21642 if (VirtualDelete &&
21643 !VirtualDelete
21644 ->isUsableAsGlobalAllocationFunctionInConstantEvaluation()) {
21645 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
21646 << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete;
21647 return false;
21648 }
21649 }
21650
21651 if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(),
21652 (*Alloc)->Value, AllocType))
21653 return false;
21654
21655 if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) {
21656 // The element was already erased. This means the destructor call also
21657 // deleted the object.
21658 // FIXME: This probably results in undefined behavior before we get this
21659 // far, and should be diagnosed elsewhere first.
21660 Info.FFDiag(E, diag::note_constexpr_double_delete);
21661 return false;
21662 }
21663
21664 return true;
21665}
21666
21667static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
21668 assert(!E->isValueDependent());
21669 assert(E->isPRValue() && E->getType()->isVoidType());
21670 return VoidExprEvaluator(Info).Visit(E);
21671}
21672
21673//===----------------------------------------------------------------------===//
21674// Top level Expr::EvaluateAsRValue method.
21675//===----------------------------------------------------------------------===//
21676
21677static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
21678 assert(!E->isValueDependent());
21679 // In C, function designators are not lvalues, but we evaluate them as if they
21680 // are.
21681 QualType T = E->getType();
21682 if (E->isGLValue() || T->isFunctionType()) {
21683 LValue LV;
21684 if (!EvaluateLValue(E, LV, Info))
21685 return false;
21686 LV.moveInto(Result);
21687 } else if (T->isVectorType()) {
21688 if (!EvaluateVector(E, Result, Info))
21689 return false;
21690 } else if (T->isConstantMatrixType()) {
21691 if (!EvaluateMatrix(E, Result, Info))
21692 return false;
21693 } else if (T->isIntegralOrEnumerationType()) {
21694 if (!IntExprEvaluator(Info, Result).Visit(E))
21695 return false;
21696 } else if (T->hasPointerRepresentation()) {
21697 LValue LV;
21698 if (!EvaluatePointer(E, LV, Info))
21699 return false;
21700 LV.moveInto(Result);
21701 } else if (T->isRealFloatingType()) {
21702 llvm::APFloat F(0.0);
21703 if (!EvaluateFloat(E, F, Info))
21704 return false;
21705 Result = APValue(F);
21706 } else if (T->isAnyComplexType()) {
21707 ComplexValue C;
21708 if (!EvaluateComplex(E, C, Info))
21709 return false;
21710 C.moveInto(Result);
21711 } else if (T->isFixedPointType()) {
21712 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
21713 } else if (T->isMemberPointerType()) {
21714 MemberPtr P;
21715 if (!EvaluateMemberPointer(E, P, Info))
21716 return false;
21717 P.moveInto(Result);
21718 return true;
21719 } else if (T->isArrayType()) {
21720 LValue LV;
21721 APValue &Value =
21722 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
21723 if (!EvaluateArray(E, LV, Value, Info))
21724 return false;
21725 Result = Value;
21726 } else if (T->isRecordType()) {
21727 LValue LV;
21728 APValue &Value =
21729 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
21730 if (!EvaluateRecord(E, LV, Value, Info))
21731 return false;
21732 Result = Value;
21733 } else if (T->isVoidType()) {
21734 if (!Info.getLangOpts().CPlusPlus11)
21735 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
21736 << E->getType();
21737 if (!EvaluateVoid(E, Info))
21738 return false;
21739 } else if (T->isAtomicType()) {
21740 QualType Unqual = T.getAtomicUnqualifiedType();
21741 if (Unqual->isArrayType() || Unqual->isRecordType()) {
21742 LValue LV;
21743 APValue &Value = Info.CurrentCall->createTemporary(
21744 E, Unqual, ScopeKind::FullExpression, LV);
21745 if (!EvaluateAtomic(E, &LV, Value, Info))
21746 return false;
21747 Result = Value;
21748 } else {
21749 if (!EvaluateAtomic(E, nullptr, Result, Info))
21750 return false;
21751 }
21752 } else if (Info.getLangOpts().CPlusPlus11) {
21753 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
21754 return false;
21755 } else {
21756 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
21757 return false;
21758 }
21759
21760 return true;
21761}
21762
21763/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
21764/// cases, the in-place evaluation is essential, since later initializers for
21765/// an object can indirectly refer to subobjects which were initialized earlier.
21766static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
21767 const Expr *E, bool AllowNonLiteralTypes) {
21768 assert(!E->isValueDependent());
21769
21770 // Normally expressions passed to EvaluateInPlace have a type, but not when
21771 // a VarDecl initializer is evaluated before the untyped ParenListExpr is
21772 // replaced with a CXXConstructExpr. This can happen in LLDB.
21773 if (E->getType().isNull())
21774 return false;
21775
21776 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
21777 return false;
21778
21779 if (E->isPRValue()) {
21780 // Evaluate arrays and record types in-place, so that later initializers can
21781 // refer to earlier-initialized members of the object.
21782 QualType T = E->getType();
21783 if (T->isArrayType())
21784 return EvaluateArray(E, This, Result, Info);
21785 else if (T->isRecordType())
21786 return EvaluateRecord(E, This, Result, Info);
21787 else if (T->isAtomicType()) {
21788 QualType Unqual = T.getAtomicUnqualifiedType();
21789 if (Unqual->isArrayType() || Unqual->isRecordType())
21790 return EvaluateAtomic(E, &This, Result, Info);
21791 }
21792 }
21793
21794 // For any other type, in-place evaluation is unimportant.
21795 return Evaluate(Result, Info, E);
21796}
21797
21798/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
21799/// lvalue-to-rvalue cast if it is an lvalue.
21800static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
21801 assert(!E->isValueDependent());
21802 assert(!Info.Ctx.getLangOpts().EnableNewConstInterp);
21803
21804 if (E->getType().isNull())
21805 return false;
21806
21807 if (!CheckLiteralType(Info, E))
21808 return false;
21809
21810 if (!::Evaluate(Result, Info, E))
21811 return false;
21812
21813 // Implicit lvalue-to-rvalue cast.
21814 if (E->isGLValue()) {
21815 LValue LV;
21816 LV.setFrom(Info.Ctx, Result);
21817 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
21818 return false;
21819 }
21820
21821 // Check this core constant expression is a constant expression.
21822 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
21823 ConstantExprKind::Normal) &&
21824 CheckMemoryLeaks(Info);
21825}
21826
21827static bool FastEvaluateAsRValue(const Expr *Exp, APValue &Result,
21828 const ASTContext &Ctx, bool &IsConst) {
21829 // Fast-path evaluations of integer literals, since we sometimes see files
21830 // containing vast quantities of these.
21831 if (const auto *L = dyn_cast<IntegerLiteral>(Exp)) {
21832 Result =
21833 APValue(APSInt(L->getValue(), L->getType()->isUnsignedIntegerType()));
21834 IsConst = true;
21835 return true;
21836 }
21837
21838 if (const auto *L = dyn_cast<CXXBoolLiteralExpr>(Exp)) {
21839 Result = APValue(APSInt(APInt(1, L->getValue())));
21840 IsConst = true;
21841 return true;
21842 }
21843
21844 if (const auto *FL = dyn_cast<FloatingLiteral>(Exp)) {
21845 Result = APValue(FL->getValue());
21846 IsConst = true;
21847 return true;
21848 }
21849
21850 if (const auto *L = dyn_cast<CharacterLiteral>(Exp)) {
21851 Result = APValue(Ctx.MakeIntValue(L->getValue(), L->getType()));
21852 IsConst = true;
21853 return true;
21854 }
21855
21856 if (const auto *CE = dyn_cast<ConstantExpr>(Exp)) {
21857 if (CE->hasAPValueResult()) {
21858 APValue APV = CE->getAPValueResult();
21859 if (!APV.isLValue()) {
21860 Result = std::move(APV);
21861 IsConst = true;
21862 return true;
21863 }
21864 }
21865
21866 // The SubExpr is usually just an IntegerLiteral.
21867 return FastEvaluateAsRValue(CE->getSubExpr(), Result, Ctx, IsConst);
21868 }
21869
21870 // This case should be rare, but we need to check it before we check on
21871 // the type below.
21872 if (Exp->getType().isNull()) {
21873 IsConst = false;
21874 return true;
21875 }
21876
21877 return false;
21878}
21879
21882 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
21883 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
21884}
21885
21887 const ASTContext &Ctx, EvalInfo &Info) {
21888 assert(!E->isValueDependent());
21889 bool IsConst;
21890 if (FastEvaluateAsRValue(E, Result.Val, Ctx, IsConst))
21891 return IsConst;
21892
21893 return EvaluateAsRValue(Info, E, Result.Val);
21894}
21895
21897 const ASTContext &Ctx,
21898 Expr::SideEffectsKind AllowSideEffects,
21899 EvalInfo &Info) {
21900 assert(!E->isValueDependent());
21902 return false;
21903
21904 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
21905 !ExprResult.Val.isInt() ||
21906 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
21907 return false;
21908
21909 return true;
21910}
21911
21913 const ASTContext &Ctx,
21914 Expr::SideEffectsKind AllowSideEffects,
21915 EvalInfo &Info) {
21916 assert(!E->isValueDependent());
21917 if (!E->getType()->isFixedPointType())
21918 return false;
21919
21920 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
21921 return false;
21922
21923 if (!ExprResult.Val.isFixedPoint() ||
21924 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
21925 return false;
21926
21927 return true;
21928}
21929
21930/// EvaluateAsRValue - Return true if this is a constant which we can fold using
21931/// any crazy technique (that has nothing to do with language standards) that
21932/// we want to. If this function returns true, it returns the folded constant
21933/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
21934/// will be applied to the result.
21936 bool InConstantContext) const {
21937 assert(!isValueDependent() &&
21938 "Expression evaluator can't be called on a dependent expression.");
21939 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsRValue");
21940
21941 bool IsConst;
21942 if (FastEvaluateAsRValue(this, Result.Val, Ctx, IsConst))
21943 return IsConst;
21944
21945 if (Ctx.getLangOpts().EnableNewConstInterp) {
21947 Settings.InConstantContext = InConstantContext;
21948 return Ctx.getInterpContext().evaluateAsRValue(Settings, this, Result.Val);
21949 }
21950
21951 EvalInfo Info(Ctx, Result, EvaluationMode::IgnoreSideEffects);
21952 Info.InConstantContext = InConstantContext;
21953 return ::EvaluateAsRValue(this, Result, Ctx, Info);
21954}
21955
21957 bool InConstantContext) const {
21958 assert(!isValueDependent() &&
21959 "Expression evaluator can't be called on a dependent expression.");
21960 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsBooleanCondition");
21961 EvalResult Scratch;
21962 return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
21963 HandleConversionToBool(Scratch.Val, Result);
21964}
21965
21967 SideEffectsKind AllowSideEffects,
21968 bool InConstantContext) const {
21969 assert(!isValueDependent() &&
21970 "Expression evaluator can't be called on a dependent expression.");
21971
21972 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsInt");
21973
21974 if (!getType()->isIntegralOrEnumerationType())
21975 return false;
21976
21977 bool IsConst;
21978 if (FastEvaluateAsRValue(this, Result.Val, Ctx, IsConst))
21979 return IsConst;
21980
21981 if (Ctx.getLangOpts().EnableNewConstInterp) {
21983 Settings.InConstantContext = InConstantContext;
21984 if (!Ctx.getInterpContext().evaluateAsRValue(Settings, this, Result.Val))
21985 return false;
21986
21987 if (!Result.Val.isInt() ||
21988 hasUnacceptableSideEffect(Result, AllowSideEffects))
21989 return false;
21990 return true;
21991 }
21992
21993 EvalInfo Info(Ctx, Result, EvaluationMode::IgnoreSideEffects);
21994 Info.InConstantContext = InConstantContext;
21995 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
21996}
21997
21999 SideEffectsKind AllowSideEffects,
22000 bool InConstantContext) const {
22001 assert(!isValueDependent() &&
22002 "Expression evaluator can't be called on a dependent expression.");
22003 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFixedPoint");
22004
22005 if (!getType()->isFixedPointType())
22006 return false;
22007
22008 if (Ctx.getLangOpts().EnableNewConstInterp) {
22010 Settings.InConstantContext = InConstantContext;
22011
22012 if (!Ctx.getInterpContext().evaluateAsRValue(Settings, this, Result.Val))
22013 return false;
22014
22015 if (!Result.Val.isFixedPoint() ||
22016 hasUnacceptableSideEffect(Result, AllowSideEffects))
22017 return false;
22018
22019 return true;
22020 }
22021
22022 EvalInfo Info(Ctx, Result, EvaluationMode::IgnoreSideEffects);
22023 Info.InConstantContext = InConstantContext;
22024 return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
22025}
22026
22027bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
22028 SideEffectsKind AllowSideEffects,
22029 bool InConstantContext) const {
22030 assert(!isValueDependent() &&
22031 "Expression evaluator can't be called on a dependent expression.");
22032
22033 if (!getType()->isRealFloatingType())
22034 return false;
22035
22036 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFloat");
22038 if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
22039 !ExprResult.Val.isFloat() ||
22040 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
22041 return false;
22042
22043 Result = ExprResult.Val.getFloat();
22044 return true;
22045}
22046
22048 bool InConstantContext) const {
22049 assert(!isValueDependent() &&
22050 "Expression evaluator can't be called on a dependent expression.");
22051
22052 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsLValue");
22053
22054 if (Ctx.getLangOpts().EnableNewConstInterp) {
22056 Settings.InConstantContext = InConstantContext;
22057 return Ctx.getInterpContext().evaluate(Settings, this, Result.Val);
22058 }
22059
22060 EvalInfo Info(Ctx, Result, EvaluationMode::ConstantFold);
22061 Info.InConstantContext = InConstantContext;
22062 LValue LV;
22063 CheckedTemporaries CheckedTemps;
22064
22065 if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() ||
22066 Result.HasSideEffects ||
22069 ConstantExprKind::Normal, CheckedTemps))
22070 return false;
22071
22072 LV.moveInto(Result.Val);
22073 return true;
22074}
22075
22077 APValue DestroyedValue, QualType Type,
22078 SourceLocation Loc, Expr::EvalStatus &EStatus,
22079 bool IsConstantDestruction) {
22080 EvalInfo Info(Ctx, EStatus,
22081 IsConstantDestruction ? EvaluationMode::ConstantExpression
22083 Info.setEvaluatingDecl(Base, DestroyedValue,
22084 EvalInfo::EvaluatingDeclKind::Dtor);
22085 Info.InConstantContext = IsConstantDestruction;
22086
22087 LValue LVal;
22088 LVal.set(Base);
22089
22090 if (!HandleDestruction(Info, Loc, Base, DestroyedValue, Type) ||
22091 EStatus.HasSideEffects)
22092 return false;
22093
22094 if (!Info.discardCleanups())
22095 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
22096
22097 return true;
22098}
22099
22101 ConstantExprKind Kind) const {
22102 assert(!isValueDependent() &&
22103 "Expression evaluator can't be called on a dependent expression.");
22104 bool IsConst;
22105 if (FastEvaluateAsRValue(this, Result.Val, Ctx, IsConst) &&
22106 Result.Val.hasValue())
22107 return true;
22108
22109 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsConstantExpr");
22110 if (Ctx.getLangOpts().EnableNewConstInterp) {
22112 Kind);
22113 Settings.InConstantContext = true;
22114 return Ctx.getInterpContext().evaluate(Settings, this, Result.Val);
22115 }
22116
22118 EvalInfo Info(Ctx, Result, EM);
22119 Info.InConstantContext = true;
22120
22121 // The type of the object we're initializing is 'const T' for a class NTTP.
22122 QualType T = getType();
22123 if (Kind == ConstantExprKind::ClassTemplateArgument)
22124 T.addConst();
22125
22126 // If we're evaluating a prvalue, fake up a MaterializeTemporaryExpr to
22127 // represent the result of the evaluation. CheckConstantExpression ensures
22128 // this doesn't escape.
22129 MaterializeTemporaryExpr BaseMTE(T, const_cast<Expr*>(this), true);
22130 APValue::LValueBase Base(&BaseMTE);
22131 Info.setEvaluatingDecl(Base, Result.Val);
22132
22133 LValue LVal;
22134 LVal.set(Base);
22135 // C++23 [intro.execution]/p5
22136 // A full-expression is [...] a constant-expression
22137 // So we need to make sure temporary objects are destroyed after having
22138 // evaluating the expression (per C++23 [class.temporary]/p4).
22139 FullExpressionRAII Scope(Info);
22140 if (!::EvaluateInPlace(Result.Val, Info, LVal, this) ||
22141 Result.HasSideEffects || !Scope.destroy())
22142 return false;
22143
22144 if (!Info.discardCleanups())
22145 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
22146
22147 if (!CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this),
22148 Result.Val, Kind))
22149 return false;
22150 if (!CheckMemoryLeaks(Info))
22151 return false;
22152
22153 // If this is a class template argument, it's required to have constant
22154 // destruction too.
22155 if (Kind == ConstantExprKind::ClassTemplateArgument &&
22157 true) ||
22158 Result.HasSideEffects)) {
22159 // FIXME: Prefix a note to indicate that the problem is lack of constant
22160 // destruction.
22161 return false;
22162 }
22163 return true;
22164}
22165
22167 Expr::EvalResult &EStatus,
22168 bool IsConstantInitialization) const {
22169 assert(!isValueDependent() &&
22170 "Expression evaluator can't be called on a dependent expression.");
22171 assert(VD && "Need a valid VarDecl");
22172
22173 llvm::TimeTraceScope TimeScope("EvaluateAsInitializer", [&] {
22174 std::string Name;
22175 llvm::raw_string_ostream OS(Name);
22176 VD->printQualifiedName(OS);
22177 return Name;
22178 });
22179
22180 EvaluationMode EvalMode =
22181 (IsConstantInitialization &&
22182 (Ctx.getLangOpts().CPlusPlus || Ctx.getLangOpts().C23))
22185
22186 if (Ctx.getLangOpts().EnableNewConstInterp) {
22187 interp::EvalSettings Settings(EvalMode, EStatus);
22188 Settings.InConstantContext = IsConstantInitialization;
22189 return Ctx.getInterpContext().evaluateAsInitializer(Settings, VD, this,
22190 EStatus.Val);
22191 }
22192
22193 SourceLocation DeclLoc = VD->getLocation();
22194 QualType DeclTy = VD->getType();
22195
22196 EvalInfo Info(Ctx, EStatus, EvalMode);
22197 Info.setEvaluatingDecl(VD, EStatus.Val);
22198 Info.InConstantContext = IsConstantInitialization;
22199
22200 LValue LVal;
22201 LVal.set(VD);
22202
22203 {
22204 // C++23 [intro.execution]/p5
22205 // A full-expression is ... an init-declarator ([dcl.decl]) or a
22206 // mem-initializer.
22207 // So we need to make sure temporary objects are destroyed after having
22208 // evaluated the expression (per C++23 [class.temporary]/p4).
22209 //
22210 // FIXME: Otherwise this may break test/Modules/pr68702.cpp because the
22211 // serialization code calls ParmVarDecl::getDefaultArg() which strips the
22212 // outermost FullExpr, such as ExprWithCleanups.
22213 FullExpressionRAII Scope(Info);
22214 if (!EvaluateInPlace(EStatus.Val, Info, LVal, this,
22215 /*AllowNonLiteralTypes=*/true) ||
22216 EStatus.HasSideEffects)
22217 return false;
22218 }
22219
22220 // At this point, any lifetime-extended temporaries are completely
22221 // initialized.
22222 Info.performLifetimeExtension();
22223
22224 if (!Info.discardCleanups())
22225 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
22226 return CheckConstantExpression(Info, DeclLoc, DeclTy, EStatus.Val,
22227 ConstantExprKind::Normal) &&
22228 CheckMemoryLeaks(Info);
22229}
22230
22233 // This function is only meaningful for records and arrays of records.
22234 QualType VarTy = getType();
22235 if (VarTy->isArrayType()) {
22236 QualType ElemTy = getASTContext().getBaseElementType(VarTy);
22237 if (!ElemTy->isRecordType()) {
22238 ensureEvaluatedStmt()->HasConstantDestruction = true;
22239 return true;
22240 }
22241 } else if (!VarTy->isRecordType()) {
22242 ensureEvaluatedStmt()->HasConstantDestruction = true;
22243 return true;
22244 }
22245
22246 Expr::EvalStatus EStatus;
22247 EStatus.Diag = &Notes;
22248
22249 // Only treat the destruction as constant destruction if we formally have
22250 // constant initialization (or are usable in a constant expression).
22251 bool IsConstantDestruction = hasConstantInitialization();
22252 ASTContext &Ctx = getASTContext();
22253
22254 // Make a copy of the value for the destructor to mutate, if we know it.
22255 // Otherwise, treat the value as default-initialized; if the destructor works
22256 // anyway, then the destruction is constant (and must be essentially empty).
22257 APValue DestroyedValue;
22258 if (getEvaluatedValue())
22259 DestroyedValue = *getEvaluatedValue();
22260 else if (!handleDefaultInitValue(VarTy, DestroyedValue))
22261 return false;
22262
22263 if (Ctx.getLangOpts().EnableNewConstInterp) {
22264 interp::EvalSettings Settings(IsConstantDestruction
22267 EStatus);
22268 Settings.InConstantContext = IsConstantDestruction;
22269 if (!Ctx.getInterpContext().evaluateDestruction(Settings, this,
22270 std::move(DestroyedValue)))
22271 return false;
22272 ensureEvaluatedStmt()->HasConstantDestruction = true;
22273 return true;
22274 }
22275
22276 if (!EvaluateDestruction(Ctx, this, std::move(DestroyedValue), VarTy,
22277 getLocation(), EStatus, IsConstantDestruction) ||
22278 EStatus.HasSideEffects)
22279 return false;
22280
22281 ensureEvaluatedStmt()->HasConstantDestruction = true;
22282 return true;
22283}
22284
22285/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
22286/// constant folded, but discard the result.
22288 assert(!isValueDependent() &&
22289 "Expression evaluator can't be called on a dependent expression.");
22290
22292 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
22294}
22295
22296APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
22297 assert(!isValueDependent() &&
22298 "Expression evaluator can't be called on a dependent expression.");
22299
22300 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstInt");
22301 EvalResult EVResult;
22302
22303 if (Ctx.getLangOpts().EnableNewConstInterp) {
22305 Settings.InConstantContext = true;
22306 [[maybe_unused]] bool Result =
22307 Ctx.getInterpContext().evaluateAsRValue(Settings, this, EVResult.Val);
22308 assert(Result && "Could not evaluate expression");
22309 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
22310
22311 return EVResult.Val.getInt();
22312 }
22313
22314 EvalInfo Info(Ctx, EVResult, EvaluationMode::IgnoreSideEffects);
22315 Info.InConstantContext = true;
22316
22317 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
22318 (void)Result;
22319 assert(Result && "Could not evaluate expression");
22320 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
22321
22322 return EVResult.Val.getInt();
22323}
22324
22327 assert(!isValueDependent() &&
22328 "Expression evaluator can't be called on a dependent expression.");
22329
22330 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstIntCheckOverflow");
22331 EvalResult EVResult;
22332 EVResult.Diag = Diag;
22333
22334 if (Ctx.getLangOpts().EnableNewConstInterp) {
22336 Settings.InConstantContext = true;
22337 Settings.CheckingForUndefinedBehavior = true;
22338 [[maybe_unused]] bool Result =
22339 Ctx.getInterpContext().evaluateAsRValue(Settings, this, EVResult.Val);
22340 assert(Result && "Could not evaluate expression");
22341 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
22342
22343 return EVResult.Val.getInt();
22344 }
22345
22346 EvalInfo Info(Ctx, EVResult, EvaluationMode::IgnoreSideEffects);
22347 Info.InConstantContext = true;
22348 Info.CheckingForUndefinedBehavior = true;
22349
22350 bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
22351 (void)Result;
22352 assert(Result && "Could not evaluate expression");
22353 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
22354
22355 return EVResult.Val.getInt();
22356}
22357
22359 assert(!isValueDependent() &&
22360 "Expression evaluator can't be called on a dependent expression.");
22361
22362 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateForOverflow");
22363 bool IsConst;
22364 EvalResult EVResult;
22365 if (FastEvaluateAsRValue(this, EVResult.Val, Ctx, IsConst))
22366 return;
22367
22368 if (Ctx.getLangOpts().EnableNewConstInterp) {
22370 Settings.CheckingForUndefinedBehavior = true;
22371 (void)Ctx.getInterpContext().evaluateAsRValue(Settings, this, EVResult.Val);
22372 return;
22373 }
22374
22375 EvalInfo Info(Ctx, EVResult, EvaluationMode::IgnoreSideEffects);
22376 Info.CheckingForUndefinedBehavior = true;
22377 (void)::EvaluateAsRValue(Info, this, EVResult.Val);
22378}
22379
22381 assert(Val.isLValue());
22382 return IsGlobalLValue(Val.getLValueBase());
22383}
22384
22385/// isIntegerConstantExpr - this recursive routine will test if an expression is
22386/// an integer constant expression.
22387
22388/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
22389/// comma, etc
22390
22391// CheckICE - This function does the fundamental ICE checking: the returned
22392// ICEDiag contains an ICEKind indicating whether the expression is an ICE.
22393//
22394// Note that to reduce code duplication, this helper does no evaluation
22395// itself; the caller checks whether the expression is evaluatable, and
22396// in the rare cases where CheckICE actually cares about the evaluated
22397// value, it calls into Evaluate.
22398
22399namespace {
22400
22401enum ICEKind {
22402 /// This expression is an ICE.
22403 IK_ICE,
22404 /// This expression is not an ICE, but if it isn't evaluated, it's
22405 /// a legal subexpression for an ICE. This return value is used to handle
22406 /// the comma operator in C99 mode, and non-constant subexpressions.
22407 IK_ICEIfUnevaluated,
22408 /// This expression is not an ICE, and is not a legal subexpression for one.
22409 IK_NotICE
22410};
22411
22412struct ICEDiag {
22413 ICEKind Kind;
22414 SourceLocation Loc;
22415
22416 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
22417};
22418
22419}
22420
22421static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
22422
22423static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
22424
22425static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
22426 Expr::EvalResult EVResult;
22427
22428 if (Ctx.getLangOpts().EnableNewConstInterp) {
22430 Settings.InConstantContext = true;
22431 if (!Ctx.getInterpContext().evaluateAsRValue(Settings, E, EVResult.Val) ||
22432 EVResult.HasSideEffects || !EVResult.Val.isInt())
22433 return ICEDiag(IK_NotICE, E->getBeginLoc());
22434 return NoDiag();
22435 }
22436
22437 Expr::EvalStatus Status;
22438 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantExpression);
22439
22440 Info.InConstantContext = true;
22441 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
22442 !EVResult.Val.isInt())
22443 return ICEDiag(IK_NotICE, E->getBeginLoc());
22444
22445 return NoDiag();
22446}
22447
22448static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
22449 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
22451 return ICEDiag(IK_NotICE, E->getBeginLoc());
22452
22453 switch (E->getStmtClass()) {
22454#define ABSTRACT_STMT(Node)
22455#define STMT(Node, Base) case Expr::Node##Class:
22456#define EXPR(Node, Base)
22457#include "clang/AST/StmtNodes.inc"
22458 case Expr::PredefinedExprClass:
22459 case Expr::FloatingLiteralClass:
22460 case Expr::ImaginaryLiteralClass:
22461 case Expr::StringLiteralClass:
22462 case Expr::ArraySubscriptExprClass:
22463 case Expr::MatrixSingleSubscriptExprClass:
22464 case Expr::MatrixSubscriptExprClass:
22465 case Expr::ArraySectionExprClass:
22466 case Expr::OMPArrayShapingExprClass:
22467 case Expr::OMPIteratorExprClass:
22468 case Expr::CompoundAssignOperatorClass:
22469 case Expr::CompoundLiteralExprClass:
22470 case Expr::ExtVectorElementExprClass:
22471 case Expr::MatrixElementExprClass:
22472 case Expr::DesignatedInitExprClass:
22473 case Expr::ArrayInitLoopExprClass:
22474 case Expr::ArrayInitIndexExprClass:
22475 case Expr::NoInitExprClass:
22476 case Expr::DesignatedInitUpdateExprClass:
22477 case Expr::ImplicitValueInitExprClass:
22478 case Expr::ParenListExprClass:
22479 case Expr::VAArgExprClass:
22480 case Expr::AddrLabelExprClass:
22481 case Expr::StmtExprClass:
22482 case Expr::CXXMemberCallExprClass:
22483 case Expr::CUDAKernelCallExprClass:
22484 case Expr::CXXAddrspaceCastExprClass:
22485 case Expr::CXXDynamicCastExprClass:
22486 case Expr::CXXTypeidExprClass:
22487 case Expr::CXXUuidofExprClass:
22488 case Expr::MSPropertyRefExprClass:
22489 case Expr::MSPropertySubscriptExprClass:
22490 case Expr::CXXNullPtrLiteralExprClass:
22491 case Expr::UserDefinedLiteralClass:
22492 case Expr::CXXThisExprClass:
22493 case Expr::CXXThrowExprClass:
22494 case Expr::CXXNewExprClass:
22495 case Expr::CXXDeleteExprClass:
22496 case Expr::CXXPseudoDestructorExprClass:
22497 case Expr::UnresolvedLookupExprClass:
22498 case Expr::RecoveryExprClass:
22499 case Expr::DependentScopeDeclRefExprClass:
22500 case Expr::DependentTemplateIdExprClass:
22501 case Expr::CXXConstructExprClass:
22502 case Expr::CXXInheritedCtorInitExprClass:
22503 case Expr::CXXStdInitializerListExprClass:
22504 case Expr::CXXBindTemporaryExprClass:
22505 case Expr::ExprWithCleanupsClass:
22506 case Expr::CXXTemporaryObjectExprClass:
22507 case Expr::CXXUnresolvedConstructExprClass:
22508 case Expr::CXXDependentScopeMemberExprClass:
22509 case Expr::UnresolvedMemberExprClass:
22510 case Expr::ObjCStringLiteralClass:
22511 case Expr::ObjCBoxedExprClass:
22512 case Expr::ObjCArrayLiteralClass:
22513 case Expr::ObjCDictionaryLiteralClass:
22514 case Expr::ObjCEncodeExprClass:
22515 case Expr::ObjCMessageExprClass:
22516 case Expr::ObjCSelectorExprClass:
22517 case Expr::ObjCProtocolExprClass:
22518 case Expr::ObjCIvarRefExprClass:
22519 case Expr::ObjCPropertyRefExprClass:
22520 case Expr::ObjCSubscriptRefExprClass:
22521 case Expr::ObjCIsaExprClass:
22522 case Expr::ObjCAvailabilityCheckExprClass:
22523 case Expr::ShuffleVectorExprClass:
22524 case Expr::ConvertVectorExprClass:
22525 case Expr::BlockExprClass:
22526 case Expr::NoStmtClass:
22527 case Expr::OpaqueValueExprClass:
22528 case Expr::PackExpansionExprClass:
22529 case Expr::SubstNonTypeTemplateParmPackExprClass:
22530 case Expr::FunctionParmPackExprClass:
22531 case Expr::AsTypeExprClass:
22532 case Expr::ObjCIndirectCopyRestoreExprClass:
22533 case Expr::MaterializeTemporaryExprClass:
22534 case Expr::PseudoObjectExprClass:
22535 case Expr::AtomicExprClass:
22536 case Expr::LambdaExprClass:
22537 case Expr::CXXFoldExprClass:
22538 case Expr::CoawaitExprClass:
22539 case Expr::DependentCoawaitExprClass:
22540 case Expr::CoyieldExprClass:
22541 case Expr::SYCLUniqueStableNameExprClass:
22542 case Expr::CXXParenListInitExprClass:
22543 case Expr::HLSLOutArgExprClass:
22544 case Expr::CXXExpansionSelectExprClass:
22545 return ICEDiag(IK_NotICE, E->getBeginLoc());
22546
22547 case Expr::MemberExprClass: {
22548 if (Ctx.getLangOpts().C23) {
22549 const Expr *ME = E->IgnoreParenImpCasts();
22550 while (const auto *M = dyn_cast<MemberExpr>(ME)) {
22551 if (M->isArrow())
22552 return ICEDiag(IK_NotICE, E->getBeginLoc());
22553 ME = M->getBase()->IgnoreParenImpCasts();
22554 }
22555 const auto *DRE = dyn_cast<DeclRefExpr>(ME);
22556 if (DRE) {
22557 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
22558 VD && VD->isConstexpr())
22559 return CheckEvalInICE(E, Ctx);
22560 }
22561 }
22562 return ICEDiag(IK_NotICE, E->getBeginLoc());
22563 }
22564
22565 case Expr::InitListExprClass: {
22566 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
22567 // form "T x = { a };" is equivalent to "T x = a;".
22568 // Unless we're initializing a reference, T is a scalar as it is known to be
22569 // of integral or enumeration type.
22570 if (E->isPRValue())
22571 if (cast<InitListExpr>(E)->getNumInits() == 1)
22572 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
22573 return ICEDiag(IK_NotICE, E->getBeginLoc());
22574 }
22575
22576 case Expr::SizeOfPackExprClass:
22577 case Expr::GNUNullExprClass:
22578 case Expr::SourceLocExprClass:
22579 case Expr::EmbedExprClass:
22580 case Expr::OpenACCAsteriskSizeExprClass:
22581 return NoDiag();
22582
22583 case Expr::PackIndexingExprClass:
22584 return CheckICE(cast<PackIndexingExpr>(E)->getSelectedExpr(), Ctx);
22585
22586 case Expr::SubstNonTypeTemplateParmExprClass:
22587 return
22588 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
22589
22590 case Expr::ConstantExprClass:
22591 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
22592
22593 case Expr::ParenExprClass:
22594 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
22595 case Expr::GenericSelectionExprClass:
22596 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
22597 case Expr::IntegerLiteralClass:
22598 case Expr::FixedPointLiteralClass:
22599 case Expr::CharacterLiteralClass:
22600 case Expr::ObjCBoolLiteralExprClass:
22601 case Expr::CXXBoolLiteralExprClass:
22602 case Expr::CXXScalarValueInitExprClass:
22603 case Expr::TypeTraitExprClass:
22604 case Expr::ConceptSpecializationExprClass:
22605 case Expr::RequiresExprClass:
22606 case Expr::ArrayTypeTraitExprClass:
22607 case Expr::ExpressionTraitExprClass:
22608 case Expr::CXXNoexceptExprClass:
22609 case Expr::CXXReflectExprClass:
22610 return NoDiag();
22611 case Expr::CallExprClass:
22612 case Expr::CXXOperatorCallExprClass: {
22613 // C99 6.6/3 allows function calls within unevaluated subexpressions of
22614 // constant expressions, but they can never be ICEs because an ICE cannot
22615 // contain an operand of (pointer to) function type.
22616 const CallExpr *CE = cast<CallExpr>(E);
22617 if (CE->getBuiltinCallee())
22618 return CheckEvalInICE(E, Ctx);
22619 return ICEDiag(IK_NotICE, E->getBeginLoc());
22620 }
22621 case Expr::CXXRewrittenBinaryOperatorClass:
22622 return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(),
22623 Ctx);
22624 case Expr::DeclRefExprClass: {
22625 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
22626 if (isa<EnumConstantDecl>(D))
22627 return NoDiag();
22628
22629 // C++ and OpenCL (FIXME: spec reference?) allow reading const-qualified
22630 // integer variables in constant expressions:
22631 //
22632 // C++ 7.1.5.1p2
22633 // A variable of non-volatile const-qualified integral or enumeration
22634 // type initialized by an ICE can be used in ICEs.
22635 //
22636 // We sometimes use CheckICE to check the C++98 rules in C++11 mode. In
22637 // that mode, use of reference variables should not be allowed.
22638 const VarDecl *VD = dyn_cast<VarDecl>(D);
22639 if (VD && VD->isUsableInConstantExpressions(Ctx) &&
22640 !VD->getType()->isReferenceType())
22641 return NoDiag();
22642
22643 return ICEDiag(IK_NotICE, E->getBeginLoc());
22644 }
22645 case Expr::UnaryOperatorClass: {
22646 const UnaryOperator *Exp = cast<UnaryOperator>(E);
22647 switch (Exp->getOpcode()) {
22648 case UO_PostInc:
22649 case UO_PostDec:
22650 case UO_PreInc:
22651 case UO_PreDec:
22652 case UO_AddrOf:
22653 case UO_Deref:
22654 case UO_Coawait:
22655 // C99 6.6/3 allows increment and decrement within unevaluated
22656 // subexpressions of constant expressions, but they can never be ICEs
22657 // because an ICE cannot contain an lvalue operand.
22658 return ICEDiag(IK_NotICE, E->getBeginLoc());
22659 case UO_Extension:
22660 case UO_LNot:
22661 case UO_Plus:
22662 case UO_Minus:
22663 case UO_Not:
22664 case UO_Real:
22665 case UO_Imag:
22666 return CheckICE(Exp->getSubExpr(), Ctx);
22667 }
22668 llvm_unreachable("invalid unary operator class");
22669 }
22670 case Expr::OffsetOfExprClass: {
22671 // Note that per C99, offsetof must be an ICE. And AFAIK, using
22672 // EvaluateAsRValue matches the proposed gcc behavior for cases like
22673 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
22674 // compliance: we should warn earlier for offsetof expressions with
22675 // array subscripts that aren't ICEs, and if the array subscripts
22676 // are ICEs, the value of the offsetof must be an integer constant.
22677 return CheckEvalInICE(E, Ctx);
22678 }
22679 case Expr::UnaryExprOrTypeTraitExprClass: {
22681 if ((Exp->getKind() == UETT_SizeOf) &&
22683 return ICEDiag(IK_NotICE, E->getBeginLoc());
22684 if (Exp->getKind() == UETT_CountOf) {
22685 QualType ArgTy = Exp->getTypeOfArgument();
22686 if (ArgTy->isVariableArrayType()) {
22687 // We need to look whether the array is multidimensional. If it is,
22688 // then we want to check the size expression manually to see whether
22689 // it is an ICE or not.
22690 const auto *VAT = Ctx.getAsVariableArrayType(ArgTy);
22691 if (VAT->getElementType()->isArrayType())
22692 // Variable array size expression could be missing (e.g. int a[*][10])
22693 // In that case, it can't be a constant expression.
22694 return VAT->getSizeExpr() ? CheckICE(VAT->getSizeExpr(), Ctx)
22695 : ICEDiag(IK_NotICE, E->getBeginLoc());
22696
22697 // Otherwise, this is a regular VLA, which is definitely not an ICE.
22698 return ICEDiag(IK_NotICE, E->getBeginLoc());
22699 }
22700 }
22701 return NoDiag();
22702 }
22703 case Expr::BinaryOperatorClass: {
22704 const BinaryOperator *Exp = cast<BinaryOperator>(E);
22705 switch (Exp->getOpcode()) {
22706 case BO_PtrMemD:
22707 case BO_PtrMemI:
22708 case BO_Assign:
22709 case BO_MulAssign:
22710 case BO_DivAssign:
22711 case BO_RemAssign:
22712 case BO_AddAssign:
22713 case BO_SubAssign:
22714 case BO_ShlAssign:
22715 case BO_ShrAssign:
22716 case BO_AndAssign:
22717 case BO_XorAssign:
22718 case BO_OrAssign:
22719 // C99 6.6/3 allows assignments within unevaluated subexpressions of
22720 // constant expressions, but they can never be ICEs because an ICE cannot
22721 // contain an lvalue operand.
22722 return ICEDiag(IK_NotICE, E->getBeginLoc());
22723
22724 case BO_Mul:
22725 case BO_Div:
22726 case BO_Rem:
22727 case BO_Add:
22728 case BO_Sub:
22729 case BO_Shl:
22730 case BO_Shr:
22731 case BO_LT:
22732 case BO_GT:
22733 case BO_LE:
22734 case BO_GE:
22735 case BO_EQ:
22736 case BO_NE:
22737 case BO_And:
22738 case BO_Xor:
22739 case BO_Or:
22740 case BO_Comma:
22741 case BO_Cmp: {
22742 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
22743 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
22744 if (Exp->getOpcode() == BO_Div ||
22745 Exp->getOpcode() == BO_Rem) {
22746 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
22747 // we don't evaluate one.
22748 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
22749 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
22750 if (REval == 0)
22751 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
22752 if (REval.isSigned() && REval.isAllOnes()) {
22753 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
22754 if (LEval.isMinSignedValue())
22755 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
22756 }
22757 }
22758 }
22759 if (Exp->getOpcode() == BO_Comma) {
22760 if (Ctx.getLangOpts().C99) {
22761 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
22762 // if it isn't evaluated.
22763 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
22764 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
22765 } else {
22766 // In both C89 and C++, commas in ICEs are illegal.
22767 return ICEDiag(IK_NotICE, E->getBeginLoc());
22768 }
22769 }
22770 return Worst(LHSResult, RHSResult);
22771 }
22772 case BO_LAnd:
22773 case BO_LOr: {
22774 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
22775 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
22776 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
22777 // Rare case where the RHS has a comma "side-effect"; we need
22778 // to actually check the condition to see whether the side
22779 // with the comma is evaluated.
22780 if ((Exp->getOpcode() == BO_LAnd) !=
22781 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
22782 return RHSResult;
22783 return NoDiag();
22784 }
22785
22786 return Worst(LHSResult, RHSResult);
22787 }
22788 }
22789 llvm_unreachable("invalid binary operator kind");
22790 }
22791 case Expr::ImplicitCastExprClass:
22792 case Expr::CStyleCastExprClass:
22793 case Expr::CXXFunctionalCastExprClass:
22794 case Expr::CXXStaticCastExprClass:
22795 case Expr::CXXReinterpretCastExprClass:
22796 case Expr::CXXConstCastExprClass:
22797 case Expr::ObjCBridgedCastExprClass: {
22798 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
22799 if (isa<ExplicitCastExpr>(E)) {
22800 if (const FloatingLiteral *FL
22801 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
22802 unsigned DestWidth = Ctx.getIntWidth(E->getType());
22803 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
22804 APSInt IgnoredVal(DestWidth, !DestSigned);
22805 bool Ignored;
22806 // If the value does not fit in the destination type, the behavior is
22807 // undefined, so we are not required to treat it as a constant
22808 // expression.
22809 if (FL->getValue().convertToInteger(IgnoredVal,
22810 llvm::APFloat::rmTowardZero,
22811 &Ignored) & APFloat::opInvalidOp)
22812 return ICEDiag(IK_NotICE, E->getBeginLoc());
22813 return NoDiag();
22814 }
22815 }
22816 switch (cast<CastExpr>(E)->getCastKind()) {
22817 case CK_LValueToRValue:
22818 case CK_AtomicToNonAtomic:
22819 case CK_NonAtomicToAtomic:
22820 case CK_NoOp:
22821 case CK_IntegralToBoolean:
22822 case CK_IntegralCast:
22823 return CheckICE(SubExpr, Ctx);
22824 default:
22825 return ICEDiag(IK_NotICE, E->getBeginLoc());
22826 }
22827 }
22828 case Expr::BinaryConditionalOperatorClass: {
22830 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
22831 if (CommonResult.Kind == IK_NotICE) return CommonResult;
22832 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
22833 if (FalseResult.Kind == IK_NotICE) return FalseResult;
22834 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
22835 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
22836 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
22837 return FalseResult;
22838 }
22839 case Expr::ConditionalOperatorClass: {
22841 // If the condition (ignoring parens) is a __builtin_constant_p call,
22842 // then only the true side is actually considered in an integer constant
22843 // expression, and it is fully evaluated. This is an important GNU
22844 // extension. See GCC PR38377 for discussion.
22845 if (const CallExpr *CallCE
22846 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
22847 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
22848 return CheckEvalInICE(E, Ctx);
22849 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
22850 if (CondResult.Kind == IK_NotICE)
22851 return CondResult;
22852
22853 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
22854 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
22855
22856 if (TrueResult.Kind == IK_NotICE)
22857 return TrueResult;
22858 if (FalseResult.Kind == IK_NotICE)
22859 return FalseResult;
22860 if (CondResult.Kind == IK_ICEIfUnevaluated)
22861 return CondResult;
22862 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
22863 return NoDiag();
22864 // Rare case where the diagnostics depend on which side is evaluated
22865 // Note that if we get here, CondResult is 0, and at least one of
22866 // TrueResult and FalseResult is non-zero.
22867 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
22868 return FalseResult;
22869 return TrueResult;
22870 }
22871 case Expr::CXXDefaultArgExprClass:
22872 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
22873 case Expr::CXXDefaultInitExprClass:
22874 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
22875 case Expr::ChooseExprClass: {
22876 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
22877 }
22878 case Expr::BuiltinBitCastExprClass: {
22879 if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
22880 return ICEDiag(IK_NotICE, E->getBeginLoc());
22881 return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
22882 }
22883 }
22884
22885 llvm_unreachable("Invalid StmtClass!");
22886}
22887
22888/// Evaluate an expression as a C++11 integral constant expression.
22889static bool
22891 llvm::APSInt *Value,
22892 bool AllowRelaxedEval = false) {
22894 return false;
22895
22897 if (!E->isCXX11ConstantExpr(Ctx, Result, AllowRelaxedEval))
22898 return false;
22899
22900 if (!Result.isInt())
22901 return false;
22902
22903 if (Value) *Value = Result.getInt();
22904 return true;
22905}
22906
22908 assert(!isValueDependent() &&
22909 "Expression evaluator can't be called on a dependent expression.");
22910
22911 ExprTimeTraceScope TimeScope(this, Ctx, "isIntegerConstantExpr");
22912
22913 if (Ctx.getLangOpts().CPlusPlus11)
22914 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr);
22915
22916 ICEDiag D = CheckICE(this, Ctx);
22917 if (D.Kind != IK_ICE)
22918 return false;
22919 return true;
22920}
22921
22922std::optional<llvm::APSInt>
22924 bool AllowRelaxedEval) const {
22925 if (isValueDependent()) {
22926 // Expression evaluator can't succeed on a dependent expression.
22927 return std::nullopt;
22928 }
22929
22930 if (Ctx.getLangOpts().CPlusPlus11) {
22931 APSInt Value;
22933 AllowRelaxedEval))
22934 return Value;
22935 return std::nullopt;
22936 }
22937
22938 if (!isIntegerConstantExpr(Ctx))
22939 return std::nullopt;
22940
22941 // The only possible side-effects here are due to UB discovered in the
22942 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
22943 // required to treat the expression as an ICE, so we produce the folded
22944 // value.
22946
22947 if (Ctx.getLangOpts().EnableNewConstInterp) {
22949 ExprResult);
22950 Settings.InConstantContext = true;
22951 if (!Ctx.getInterpContext().evaluateAsRValue(Settings, this,
22952 ExprResult.Val))
22953 llvm_unreachable("ICE cannot be evaluated!");
22954 return ExprResult.Val.getInt();
22955 }
22956
22957 Expr::EvalStatus Status;
22958 EvalInfo Info(Ctx, Status, EvaluationMode::IgnoreSideEffects);
22959 Info.InConstantContext = true;
22960
22961 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
22962 llvm_unreachable("ICE cannot be evaluated!");
22963
22964 return ExprResult.Val.getInt();
22965}
22966
22968 assert(!isValueDependent() &&
22969 "Expression evaluator can't be called on a dependent expression.");
22970
22971 return CheckICE(this, Ctx).Kind == IK_ICE;
22972}
22973
22975 bool AllowRelaxedEval) const {
22976 assert(!isValueDependent() &&
22977 "Expression evaluator can't be called on a dependent expression.");
22978
22979 // We support this checking in C++98 mode in order to diagnose compatibility
22980 // issues.
22981 assert(Ctx.getLangOpts().CPlusPlus);
22982
22983 bool IsConst;
22984 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst) && Result.hasValue())
22985 return true;
22986
22987 bool IsConstExpr;
22988 Expr::EvalStatus Status;
22990 Status.ExtendedDiag = AllowRelaxedEval ? &MSRelaxedDiag : nullptr;
22991
22992 if (Ctx.getLangOpts().EnableNewConstInterp) {
22994 IsConstExpr =
22995 Ctx.getInterpContext().evaluateAsRValue(Settings, this, Result);
22996 } else {
22997 // Build evaluation settings.
22998 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantExpression);
22999 IsConstExpr =
23000 ::EvaluateAsRValue(Info, this, Result) &&
23001 // NOTE: We don't produce a diagnostic for this, but the callers that
23002 // call us on arbitrary full-expressions should generally not care.
23003 Info.discardCleanups() && !Status.HasSideEffects;
23004 }
23005 return IsConstExpr && !Status.DiagEmitted;
23006}
23007
23009 const FunctionDecl *Callee,
23011 const Expr *This) const {
23012 assert(!isValueDependent() &&
23013 "Expression evaluator can't be called on a dependent expression.");
23014
23015 llvm::TimeTraceScope TimeScope("EvaluateWithSubstitution", [&] {
23016 std::string Name;
23017 llvm::raw_string_ostream OS(Name);
23018 Callee->getNameForDiagnostic(OS, Ctx.getPrintingPolicy(),
23019 /*Qualified=*/true);
23020 return Name;
23021 });
23022
23023 Expr::EvalStatus Status;
23024
23025 if (Ctx.getLangOpts().EnableNewConstInterp) {
23027 Status);
23028 Settings.InConstantContext = true;
23029 if (std::optional<bool> BoolResult =
23030 Ctx.getInterpContext().evaluateWithSubstitution(Settings, Callee,
23031 Args, This, this)) {
23032 Value = APValue(APSInt(APInt(1, static_cast<uint64_t>(*BoolResult))));
23033 return true;
23034 }
23035 return false;
23036 }
23037
23038 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantExpressionUnevaluated);
23039 Info.InConstantContext = true;
23040
23041 LValue ThisVal;
23042 const LValue *ThisPtr = nullptr;
23043 if (This) {
23044#ifndef NDEBUG
23045 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
23046 assert(MD && "Don't provide `this` for non-methods.");
23047 assert(MD->isImplicitObjectMemberFunction() &&
23048 "Don't provide `this` for methods without an implicit object.");
23049#endif
23050 if (!This->isValueDependent() &&
23051 EvaluateObjectArgument(Info, This, ThisVal) &&
23052 !Info.EvalStatus.HasSideEffects)
23053 ThisPtr = &ThisVal;
23054
23055 // Ignore any side-effects from a failed evaluation. This is safe because
23056 // they can't interfere with any other argument evaluation.
23057 Info.EvalStatus.HasSideEffects = false;
23058 }
23059
23060 CallRef Call = Info.CurrentCall->createCall(Callee);
23061 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
23062 I != E; ++I) {
23063 unsigned Idx = I - Args.begin();
23064 if (Idx >= Callee->getNumParams())
23065 break;
23066 const ParmVarDecl *PVD = Callee->getParamDecl(Idx);
23067 if ((*I)->isValueDependent() ||
23068 !EvaluateCallArg(PVD, *I, Call, Info) ||
23069 Info.EvalStatus.HasSideEffects) {
23070 // If evaluation fails, throw away the argument entirely.
23071 if (APValue *Slot = Info.getParamSlot(Call, PVD))
23072 *Slot = APValue();
23073 }
23074
23075 // Ignore any side-effects from a failed evaluation. This is safe because
23076 // they can't interfere with any other argument evaluation.
23077 Info.EvalStatus.HasSideEffects = false;
23078 }
23079
23080 // Parameter cleanups happen in the caller and are not part of this
23081 // evaluation.
23082 Info.discardCleanups();
23083 Info.EvalStatus.HasSideEffects = false;
23084
23085 // Build fake call to Callee.
23086 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, This,
23087 Call);
23088 // FIXME: Missing ExprWithCleanups in enable_if conditions?
23089 FullExpressionRAII Scope(Info);
23090 return Evaluate(Value, Info, this) && Scope.destroy() &&
23091 !Info.EvalStatus.HasSideEffects;
23092}
23093
23096 PartialDiagnosticAt> &Diags) {
23097 // FIXME: It would be useful to check constexpr function templates, but at the
23098 // moment the constant expression evaluator cannot cope with the non-rigorous
23099 // ASTs which we build for dependent expressions.
23100 if (FD->isDependentContext())
23101 return true;
23102
23103 llvm::TimeTraceScope TimeScope("isPotentialConstantExpr", [&] {
23104 std::string Name;
23105 llvm::raw_string_ostream OS(Name);
23107 /*Qualified=*/true);
23108 return Name;
23109 });
23110
23111 const ASTContext &Ctx = FD->getASTContext();
23112 Expr::EvalStatus Status;
23113 Status.Diag = &Diags;
23114
23115 // The constexpr VM attempts to compile all methods to bytecode here.
23116 if (Ctx.getLangOpts().EnableNewConstInterp) {
23118 Settings.InConstantContext = true;
23120 Ctx.getInterpContext().isPotentialConstantExpr(Settings, FD);
23121 return Diags.empty();
23122 }
23123
23124 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantExpression);
23125 Info.InConstantContext = true;
23126 Info.CheckingPotentialConstantExpression = true;
23127
23128 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
23129 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
23130
23131 // Fabricate an arbitrary expression on the stack and pretend that it
23132 // is a temporary being used as the 'this' pointer.
23133 LValue This;
23134 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getCanonicalTagType(RD)
23135 : Info.Ctx.IntTy);
23136 This.set({&VIE, Info.CurrentCall->Index});
23137
23139
23140 APValue Scratch;
23141 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
23142 // Evaluate the call as a constant initializer, to allow the construction
23143 // of objects of non-literal types.
23144 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
23145 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
23146 } else {
23147 SourceLocation Loc = FD->getLocation();
23149 Loc, FD, (MD && MD->isImplicitObjectMemberFunction()) ? &This : nullptr,
23150 &VIE, Args, CallRef(), FD->getBody(), Info, Scratch,
23151 /*ResultSlot=*/nullptr);
23152 }
23153
23154 return Diags.empty();
23155}
23156
23158 const FunctionDecl *FD,
23160 PartialDiagnosticAt> &Diags) {
23161 assert(!E->isValueDependent() &&
23162 "Expression evaluator can't be called on a dependent expression.");
23163
23164 const ASTContext &Ctx = FD->getASTContext();
23165 Expr::EvalStatus Status;
23166 Status.Diag = &Diags;
23167
23168 if (Ctx.getLangOpts().EnableNewConstInterp) {
23170 Status);
23171 Settings.InConstantContext = true;
23174 return Diags.empty();
23175 }
23176
23177 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantExpressionUnevaluated);
23178 Info.InConstantContext = true;
23179 Info.CheckingPotentialConstantExpression = true;
23180
23181 // Fabricate a call stack frame to give the arguments a plausible cover story.
23182 CallStackFrame Frame(Info, SourceLocation(), FD, /*This=*/nullptr,
23183 /*CallExpr=*/nullptr, CallRef());
23184
23185 APValue ResultScratch;
23186 Evaluate(ResultScratch, Info, E);
23187 return Diags.empty();
23188}
23189
23190std::optional<uint64_t> Expr::tryEvaluateObjectSize(const ASTContext &Ctx,
23191 unsigned Type) const {
23192 if (!getType()->isPointerType())
23193 return std::nullopt;
23194
23195 Expr::EvalStatus Status;
23196 if (Ctx.getLangOpts().EnableNewConstInterp) {
23198 return Ctx.getInterpContext().tryEvaluateObjectSize(Settings, this, Type,
23199 /*IsDynamic=*/false);
23200 }
23201
23202 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantFold);
23203 return tryEvaluateBuiltinObjectSize(this, Type, Info);
23204}
23205
23206static std::optional<uint64_t>
23207EvaluateBuiltinStrLen(const Expr *E, EvalInfo &Info,
23208 std::string *StringResult) {
23209 if (!E->getType()->hasPointerRepresentation() || !E->isPRValue())
23210 return std::nullopt;
23211
23212 LValue String;
23213
23214 if (!EvaluatePointer(E, String, Info))
23215 return std::nullopt;
23216
23217 // Fast path: if it's a string literal, search the string value.
23218 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
23219 String.getLValueBase().dyn_cast<const Expr *>())) {
23220 StringRef Str = S->getBytes();
23221 int64_t Off = String.Offset.getQuantity();
23222 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size()) {
23223 UnsignedOrNone ZeroIndex = S->findZeroCodeUnit(Off);
23224 if (StringResult) {
23225 if (ZeroIndex)
23226 Str = Str.substr(Off, *ZeroIndex);
23227 *StringResult = Str;
23228 }
23229
23230 return ZeroIndex.value_or(Str.size());
23231 }
23232 // For an invalid index, fall through to the offset handling below.
23233 }
23234
23235 QualType CharTy = E->getType()->getPointeeType();
23236 // Slow path: scan the bytes of the string looking for the terminating 0.
23237 for (uint64_t Strlen = 0; /**/; ++Strlen) {
23238 APValue Char;
23239 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
23240 !Char.isInt())
23241 return std::nullopt;
23242 if (!Char.getInt())
23243 return Strlen;
23244 else if (StringResult)
23245 StringResult->push_back(Char.getInt().getExtValue());
23246 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
23247 return std::nullopt;
23248 }
23249}
23250
23251std::optional<std::string> Expr::tryEvaluateString(ASTContext &Ctx) const {
23252 Expr::EvalStatus Status;
23253 std::string StringResult;
23254
23255 if (Ctx.getLangOpts().EnableNewConstInterp) {
23257 if (!Ctx.getInterpContext().evaluateString(Settings, this, StringResult))
23258 return std::nullopt;
23259 return StringResult;
23260 }
23261
23262 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantFold);
23263 if (EvaluateBuiltinStrLen(this, Info, &StringResult))
23264 return StringResult;
23265 return std::nullopt;
23266}
23267
23268template <typename T>
23270 const Expr *SizeExpression,
23271 const Expr *PtrExpression,
23272 ASTContext &Ctx,
23273 Expr::EvalResult &Status) {
23274 if (Ctx.getLangOpts().EnableNewConstInterp) {
23276 Settings.InConstantContext = true;
23277 return Ctx.getInterpContext().evaluateCharRange(Settings, SizeExpression,
23278 PtrExpression, Result);
23279 }
23280
23281 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantExpression);
23282 Info.InConstantContext = true;
23283
23284 LValue String;
23285 FullExpressionRAII Scope(Info);
23286 APSInt SizeValue;
23287 if (!::EvaluateInteger(SizeExpression, SizeValue, Info))
23288 return false;
23289
23290 uint64_t Size = SizeValue.getZExtValue();
23291
23292 // FIXME: better protect against invalid or excessive sizes
23293 if constexpr (std::is_same_v<APValue, T>)
23294 Result = APValue(APValue::UninitArray{}, Size, Size);
23295 else {
23296 if (Size < Result.max_size())
23297 Result.reserve(Size);
23298 }
23299 if (!::EvaluatePointer(PtrExpression, String, Info))
23300 return false;
23301
23302 QualType CharTy = PtrExpression->getType()->getPointeeType();
23303 for (uint64_t I = 0; I < Size; ++I) {
23304 APValue Char;
23305 if (!handleLValueToRValueConversion(Info, PtrExpression, CharTy, String,
23306 Char))
23307 return false;
23308
23309 if constexpr (std::is_same_v<APValue, T>) {
23310 Result.getArrayInitializedElt(I) = std::move(Char);
23311 } else {
23312 APSInt C = Char.getInt();
23313
23314 assert(C.getBitWidth() <= 8 &&
23315 "string element not representable in char");
23316
23317 Result.push_back(static_cast<char>(C.getExtValue()));
23318 }
23319
23320 if (!HandleLValueArrayAdjustment(Info, PtrExpression, String, CharTy, 1))
23321 return false;
23322 }
23323
23324 return Scope.destroy() && CheckMemoryLeaks(Info);
23325}
23326
23328 const Expr *SizeExpression,
23329 const Expr *PtrExpression, ASTContext &Ctx,
23330 EvalResult &Status) const {
23331 return EvaluateCharRangeAsStringImpl(this, Result, SizeExpression,
23332 PtrExpression, Ctx, Status);
23333}
23334
23336 const Expr *SizeExpression,
23337 const Expr *PtrExpression, ASTContext &Ctx,
23338 EvalResult &Status) const {
23339 return EvaluateCharRangeAsStringImpl(this, Result, SizeExpression,
23340 PtrExpression, Ctx, Status);
23341}
23342
23343std::optional<uint64_t> Expr::tryEvaluateStrLen(const ASTContext &Ctx) const {
23344 Expr::EvalStatus Status;
23345
23346 if (Ctx.getLangOpts().EnableNewConstInterp) {
23348 return Ctx.getInterpContext().evaluateStrlen(Settings, this);
23349 }
23350 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantFold);
23351 return EvaluateBuiltinStrLen(this, Info);
23352}
23353
23354namespace {
23355struct IsWithinLifetimeHandler {
23356 EvalInfo &Info;
23357 static constexpr AccessKinds AccessKind = AccessKinds::AK_IsWithinLifetime;
23358 using result_type = std::optional<bool>;
23359 std::optional<bool> failed() { return std::nullopt; }
23360 template <typename T>
23361 std::optional<bool> found(T &Subobj, QualType SubobjType,
23363 return true;
23364 }
23365 template <typename T>
23366 std::optional<bool> found(T &Subobj, QualType SubobjType) {
23367 return true;
23368 }
23369};
23370
23371std::optional<bool> EvaluateBuiltinIsWithinLifetime(IntExprEvaluator &IEE,
23372 const CallExpr *E) {
23373 EvalInfo &Info = IEE.Info;
23374 // Sometimes this is called during some sorts of constant folding / early
23375 // evaluation. These are meant for non-constant expressions and are not
23376 // necessary since this consteval builtin will never be evaluated at runtime.
23377 // Just fail to evaluate when not in a constant context.
23378 if (!Info.InConstantContext)
23379 return std::nullopt;
23380 assert(E->getBuiltinCallee() == Builtin::BI__builtin_is_within_lifetime);
23381 const Expr *Arg = E->getArg(0);
23382 if (Arg->isValueDependent())
23383 return std::nullopt;
23384 LValue Val;
23385 if (!EvaluatePointer(Arg, Val, Info))
23386 return std::nullopt;
23387
23388 if (Val.allowConstexprUnknown())
23389 return true;
23390
23391 auto Error = [&](int Diag) {
23392 bool CalledFromStd = false;
23393 const auto *Callee = Info.CurrentCall->getCallee();
23394 if (Callee && Callee->isInStdNamespace()) {
23395 const IdentifierInfo *Identifier = Callee->getIdentifier();
23396 CalledFromStd = Identifier && Identifier->isStr("is_within_lifetime");
23397 }
23398 Info.CCEDiag(CalledFromStd ? Info.CurrentCall->getCallRange().getBegin()
23399 : E->getExprLoc(),
23400 diag::err_invalid_is_within_lifetime)
23401 << (CalledFromStd ? "std::is_within_lifetime"
23402 : "__builtin_is_within_lifetime")
23403 << Diag;
23404 return std::nullopt;
23405 };
23406 // C++2c [meta.const.eval]p4:
23407 // During the evaluation of an expression E as a core constant expression, a
23408 // call to this function is ill-formed unless p points to an object that is
23409 // usable in constant expressions or whose complete object's lifetime began
23410 // within E.
23411
23412 // Make sure it points to an object
23413 // nullptr does not point to an object
23414 if (Val.isNullPointer() || Val.getLValueBase().isNull())
23415 return Error(0);
23416 QualType T = Val.getLValueBase().getType();
23417 assert(!T->isFunctionType() &&
23418 "Pointers to functions should have been typed as function pointers "
23419 "which would have been rejected earlier");
23420 assert(T->isObjectType());
23421 // Hypothetical array element is not an object
23422 if (Val.getLValueDesignator().isOnePastTheEnd())
23423 return Error(1);
23424 assert(Val.getLValueDesignator().isValidSubobject() &&
23425 "Unchecked case for valid subobject");
23426 // All other ill-formed values should have failed EvaluatePointer, so the
23427 // object should be a pointer to an object that is usable in a constant
23428 // expression or whose complete lifetime began within the expression
23429 CompleteObject CO =
23430 findCompleteObject(Info, E, AccessKinds::AK_IsWithinLifetime, Val, T);
23431 // The lifetime hasn't begun yet if we are still evaluating the
23432 // initializer ([basic.life]p(1.2))
23433 if (Info.EvaluatingDeclValue && CO.Value == Info.EvaluatingDeclValue)
23434 return Error(2);
23435
23436 if (!CO)
23437 return false;
23438 IsWithinLifetimeHandler handler{Info};
23439 return findSubobject(Info, E, CO, Val.getLValueDesignator(), handler);
23440}
23441} // 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 EvaluateCharRangeAsStringImpl(const Expr *, T &Result, const Expr *SizeExpression, const Expr *PtrExpression, ASTContext &Ctx, Expr::EvalResult &Status)
static bool isValidIndeterminateAccess(AccessKinds AK)
Is this kind of access valid on an indeterminate object value?
static unsigned elementwiseSize(EvalInfo &Info, QualType BaseTy)
static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, EvalInfo &Info)
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 HandleSizeof(EvalInfo &Info, SourceLocation Loc, QualType Type, CharUnits &Size, SizeOfType SOT=SizeOfType::SizeOf)
Get the size of the given type in char units.
static bool hlslElementwiseCastHelper(EvalInfo &Info, const Expr *E, QualType DestTy, SmallVectorImpl< APValue > &SrcVals, SmallVectorImpl< QualType > &SrcTypes)
static bool ShouldPropagateBreakContinue(EvalInfo &Info, const Stmt *LoopOrSwitch, ArrayRef< BlockScopeRAII * > Scopes, EvalStmtResult &ESR)
Helper to implement named break/continue.
static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info, const Stmt *Body, const SwitchCase *Case=nullptr)
Evaluate the body of a loop, and translate the result as appropriate.
static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info, bool InvalidBaseOK=false)
static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc, const CXXConstructorDecl *CD, bool IsValueInitialization)
CheckTrivialDefaultConstructor - Check whether a constructor is a trivial default constructor.
static bool EvaluateVector(const Expr *E, APValue &Result, EvalInfo &Info)
static const ValueDecl * GetLValueBaseDecl(const LValue &LVal)
SizeOfType
static bool TryEvaluateBuiltinNaN(const ASTContext &Context, QualType ResultTy, const Expr *Arg, bool SNaN, llvm::APFloat &Result)
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 bool handleElementwiseCast(EvalInfo &Info, const Expr *E, const FPOptions FPO, SmallVectorImpl< APValue > &Elements, SmallVectorImpl< QualType > &SrcTypes, SmallVectorImpl< QualType > &DestTypes, SmallVectorImpl< APValue > &Results)
static bool refersToCompleteObject(const LValue &LVal)
Tests to see if the LValue has a user-specified designator (that isn't necessarily valid)....
static bool AreElementsOfSameArray(QualType ObjType, const SubobjectDesignator &A, const SubobjectDesignator &B)
Determine whether the given subobject designators refer to elements of the same array object.
static bool EvaluateDecompositionDeclInit(EvalInfo &Info, const DecompositionDecl *DD)
static bool IsWeakLValue(const LValue &Value)
static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This, APValue &Result, const CXXConstructExpr *CCE, QualType AllocType)
static bool EvaluateRecord(const Expr *E, const LValue &This, APValue &Result, EvalInfo &Info)
static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal, QualType LValType, APValue &Val)
Perform an assignment of Val to LVal. Takes ownership of Val.
static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result, const RecordDecl *TruncatedType, unsigned TruncatedElements)
Cast an lvalue referring to a base subobject to a derived class, by truncating the lvalue's path to t...
static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E)
Evaluate an expression to see if it had side-effects, and discard its result.
static bool constructAggregate(EvalInfo &Info, const FPOptions FPO, const Expr *E, APValue &Result, QualType ResultType, SmallVectorImpl< APValue > &Elements, SmallVectorImpl< QualType > &ElTypes)
static void addFlexibleArrayMemberInitSize(EvalInfo &Info, const QualType &T, const LValue &LV, CharUnits &Size)
If we're evaluating the object size of an instance of a struct that contains a flexible array member,...
static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E, QualType Type, LValue &Result)
static bool evalShuffleGeneric(EvalInfo &Info, const CallExpr *Call, APValue &Out, llvm::function_ref< std::pair< unsigned, int >(unsigned, unsigned)> GetSourceIndex)
static QualType getSubobjectType(QualType ObjType, QualType SubobjType, bool IsMutable=false)
static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result, EvalInfo &Info)
Evaluate an integer or fixed point expression into an APResult.
static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E, const FPOptions FPO, QualType SrcType, const APSInt &Value, QualType DestType, APFloat &Result)
static const CXXRecordDecl * getBaseClassType(SubobjectDesignator &Designator, unsigned PathLength)
static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result, const CXXRecordDecl *DerivedRD, const CXXRecordDecl *BaseRD)
Cast an lvalue referring to a derived class to a known base subobject.
static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj, const CXXRecordDecl *DerivedDecl, const CXXBaseSpecifier *Base)
static bool HandleLValueDirectVirtualBase(EvalInfo &Info, const Expr *E, LValue &Obj, const CXXRecordDecl *Derived, const CXXRecordDecl *Base, const ASTRecordLayout *RL=nullptr)
static bool HandleConversionToBool(const APValue &Val, bool &Result)
static void expandVector(APValue &Vec, unsigned NumElements)
CharUnits GetAlignOfExpr(const ASTContext &Ctx, const Expr *E, UnaryExprOrTypeTrait ExprKind)
static bool handleCompareOpForVector(const APValue &LHSValue, BinaryOperatorKind Opcode, const APValue &RHSValue, APInt &Result)
static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr)
static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object, LValue &This)
Build an lvalue for the object argument of a member function call.
static bool CheckLiteralType(EvalInfo &Info, const Expr *E, const LValue *This=nullptr)
Check that this core constant expression is of literal type, and if not, produce an appropriate diagn...
static bool 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 bool EvaluateAsBooleanCondition(const Expr *E, bool &Result, EvalInfo &Info)
static std::optional< DynamicType > ComputeDynamicType(EvalInfo &Info, const Expr *E, LValue &This, AccessKinds AK)
Determine the dynamic type of an object.
static bool EvaluateDecl(EvalInfo &Info, const Decl *D, bool EvaluateConditionDecl=false)
static void expandArray(APValue &Array, unsigned Index)
static bool handleLogicalOpForVector(const APInt &LHSValue, BinaryOperatorKind Opcode, const APInt &RHSValue, APInt &Result)
static unsigned FindDesignatorMismatch(QualType ObjType, const SubobjectDesignator &A, const SubobjectDesignator &B, bool &WasArrayIndex)
Find the position where two subobject designators diverge, or equivalently the length of the common i...
static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx, const LValue &LV)
Determine whether this is a pointer past the end of the complete object referred to by the lvalue.
static unsigned getBaseIndex(const CXXRecordDecl *Derived, const CXXRecordDecl *Base)
Get the base index of the given base class within an APValue representing the given derived class.
static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result, EvalInfo &Info)
Evaluate only a fixed point expression into an APResult.
void HandleComplexComplexMul(APFloat A, APFloat B, APFloat C, APFloat D, APFloat &ResR, APFloat &ResI)
static bool HandleDestructionImpl(EvalInfo &Info, SourceRange CallRange, const LValue &This, APValue &Value, QualType T, bool IsCompleteClass=true)
static bool EvalPointerValueAsBool(const APValue &Value, bool &Result)
static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E, BinaryOperatorKind Opcode, APValue &LHSValue, const APValue &RHSValue)
static bool 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 std::optional< DynAlloc * > CheckDeleteKind(EvalInfo &Info, const Expr *E, const LValue &Pointer, DynAlloc::Kind DeallocKind)
Check that the given object is a suitable pointer to a heap allocation that still exists and is of th...
static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E, const RecordDecl *RD, const LValue &This, APValue &Result, bool IsCompleteClass=true)
Perform zero-initialization on an object of non-union class type. C++11 [dcl.init]p5: To zero-initial...
static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx, const Expr *E, llvm::APSInt *Value, bool AllowRelaxedEval=false)
Evaluate an expression as a C++11 integral constant expression.
static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, bool InvalidBaseOK=false)
Evaluate an expression as an lvalue. This can be legitimately called on expressions which are not glv...
static bool HandleConstructorCall(const Expr *E, const LValue &This, CallRef Call, const CXXConstructorDecl *Definition, EvalInfo &Info, APValue &Result, bool IsCompleteClass=true)
Evaluate a constructor call.
static bool FastEvaluateAsRValue(const Expr *Exp, APValue &Result, const ASTContext &Ctx, bool &IsConst)
static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E, APValue &Result, ArrayRef< QualType > Path)
Perform the adjustment from a value returned by a virtual function to a value of the statically expec...
static bool evalShiftWithCount(EvalInfo &Info, const CallExpr *Call, APValue &Out, llvm::function_ref< APInt(const APInt &, uint64_t)> ShiftOp, llvm::function_ref< APInt(const APInt &, unsigned)> OverflowOp)
static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info, const SwitchStmt *SS)
Evaluate a switch statement.
static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S, APValue &Result, QualType AllocType=QualType())
static bool EvaluateArgs(ArrayRef< const Expr * > Args, CallRef Call, EvalInfo &Info, const FunctionDecl *Callee, bool RightToLeft=false, LValue *ObjectArg=nullptr)
Evaluate the arguments to a function call.
static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, EvalInfo &Info)
static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, const LValue &LVal, llvm::APInt &Result)
Convenience function. LVal's base must be a call to an alloc_size function.
static bool handleIntIntBinOp(EvalInfo &Info, const BinaryOperator *E, const APSInt &LHS, BinaryOperatorKind Opcode, APSInt RHS, APSInt &Result)
Perform the given binary integer operation.
static bool EvaluateInitForDeclOfReferenceType(EvalInfo &Info, const ValueDecl *D, const Expr *Init, LValue &Result, APValue &Val)
Evaluates the initializer of a reference.
static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This, AccessKinds AK, bool Polymorphic)
Check that we can access the notional vptr of an object / determine its dynamic type.
static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E, QualType SrcType, const APFloat &Value, QualType DestType, APSInt &Result)
static bool getAlignmentArgument(const Expr *E, QualType ForType, EvalInfo &Info, APSInt &Alignment)
Evaluate the value of the alignment argument to __builtin_align_{up,down}, __builtin_is_aligned and _...
static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc, QualType Type, const APValue &Value)
Check that this evaluated value is fully-initialized and can be loaded by an lvalue-to-rvalue convers...
static SubobjectHandler::result_type findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj, const SubobjectDesignator &Sub, SubobjectHandler &handler)
Find the designated sub-object of an rvalue.
static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc, unsigned Type, const LValue &LVal, CharUnits &EndOffset)
Helper for tryEvaluateBuiltinObjectSize – Given an LValue, this will determine how many bytes exist f...
static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int, CharUnits &Result)
Converts the given APInt to CharUnits, assuming the APInt is unsigned. Fails if the conversion would ...
static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg, CallRef Call, EvalInfo &Info, bool NonNull=false, APValue **EvaluatedArg=nullptr)
llvm::SmallPtrSet< const MaterializeTemporaryExpr *, 8 > CheckedTemporaries
Materialized temporaries that we've already checked to determine if they're initializsed by a constan...
GCCTypeClass EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts)
EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way as GCC.
static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info)
static bool MaybeEvaluateDeferredVarDeclInit(EvalInfo &Info, const VarDecl *VD)
static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E, QualType DestType, QualType SrcType, const APSInt &Value)
static std::optional< APValue > handleVectorUnaryOperator(ASTContext &Ctx, QualType ResultTy, UnaryOperatorKind Op, APValue Elt)
static bool lifetimeStartedInEvaluation(EvalInfo &Info, APValue::LValueBase Base, bool MutableSubobject=false)
static bool isOneByteCharacterType(QualType T)
static bool HandleLambdaCapture(EvalInfo &Info, const Expr *E, LValue &Result, const CXXMethodDecl *MD, const FieldDecl *FD, bool LValueToRValueConversion)
Get an lvalue to a field of a lambda's closure type.
static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl, const Expr *Cond, bool &Result)
Evaluate a condition (either a variable declaration or an expression).
static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult, const ASTContext &Ctx, Expr::SideEffectsKind AllowSideEffects, EvalInfo &Info)
static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result)
EvaluateAsRValue - Try to evaluate this expression, performing an implicit lvalue-to-rvalue cast if i...
static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK, QualType T)
Diagnose an attempt to read from any unreadable field within the specified type, which might be a cla...
static ICEDiag CheckICE(const Expr *E, const ASTContext &Ctx)
static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc, const FunctionDecl *Declaration, const FunctionDecl *Definition, const Stmt *Body)
CheckConstexprFunction - Check that a function can be called in a constant expression.
static bool EvaluateDestruction(const ASTContext &Ctx, APValue::LValueBase Base, APValue DestroyedValue, QualType Type, SourceLocation Loc, Expr::EvalStatus &EStatus, bool IsConstantDestruction)
static bool handleDefaultInitValue(QualType T, APValue &Result, bool IsCompleteClass=true)
Get the value to use for a default-initialized object of type T.
static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, const Stmt *S, const SwitchCase *SC=nullptr)
static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This, APValue &Result, const InitListExpr *ILE, QualType AllocType)
static bool HasSameBase(const LValue &A, const LValue &B)
static bool CheckLocalVariableDeclaration(EvalInfo &Info, const VarDecl *VD)
static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj, const CXXRecordDecl *Derived, const CXXRecordDecl *Base, const ASTRecordLayout *RL=nullptr)
static bool IsGlobalLValue(APValue::LValueBase B)
static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E)
Get rounding mode to use in evaluation of the specified expression.
static QualType getObjectType(APValue::LValueBase B)
Retrieves the "underlying object type" of the given expression, as used by __builtin_object_size.
static bool handleCompareOpForVectorHelper(const APTy &LHSValue, BinaryOperatorKind Opcode, const APTy &RHSValue, APInt &Result)
static std::optional< uint64_t > tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type, EvalInfo &Info, bool IsDynamic=false)
Tries to evaluate the __builtin_object_size for E.
static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E)
static 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:173
#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:62
unsigned getVersion() const
Definition APValue.cpp:112
QualType getDynamicAllocType() const
Definition APValue.cpp:121
QualType getTypeInfoType() const
Definition APValue.cpp:116
static LValueBase getTypeInfo(TypeInfoLValue LV, QualType TypeInfo)
Definition APValue.cpp:54
static LValueBase getDynamicAlloc(DynamicAllocLValue LV, QualType Type)
Definition APValue.cpp:46
A non-discriminated union of a base, field, or array index.
Definition APValue.h:209
BaseOrMemberType getAsBaseOrMember() const
Definition APValue.h:223
static LValuePathEntry ArrayIndex(uint64_t Index)
Definition APValue.h:217
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:123
bool hasArrayFiller() const
Definition APValue.h:637
const LValueBase getLValueBase() const
Definition APValue.cpp:1011
APValue & getArrayInitializedElt(unsigned I)
Definition APValue.h:629
void swap(APValue &RHS)
Swaps the contents of this and the given APValue.
Definition APValue.cpp:471
APSInt & getInt()
Definition APValue.h:511
APValue & getStructField(unsigned i)
Definition APValue.h:674
unsigned getMatrixNumColumns() const
Definition APValue.h:602
const FieldDecl * getUnionField() const
Definition APValue.h:695
bool isVector() const
Definition APValue.h:494
APSInt & getComplexIntImag()
Definition APValue.h:549
bool isAbsent() const
Definition APValue.h:484
bool isComplexInt() const
Definition APValue.h:491
llvm::PointerIntPair< const Decl *, 1, bool > BaseOrMemberType
A FieldDecl or CXXRecordDecl, along with a flag indicating whether we mean a virtual or non-virtual b...
Definition APValue.h:206
ValueKind getKind() const
Definition APValue.h:482
APValue & getStructVirtualBase(unsigned i)
Definition APValue.h:679
unsigned getArrayInitializedElts() const
Definition APValue.h:648
static APValue IndeterminateValue()
Definition APValue.h:453
bool isFloat() const
Definition APValue.h:489
unsigned getStructNumBases() const
Definition APValue.h:657
APFixedPoint & getFixedPoint()
Definition APValue.h:533
bool hasValue() const
Definition APValue.h:486
bool hasLValuePath() const
Definition APValue.cpp:1026
const ValueDecl * getMemberPointerDecl() const
Definition APValue.cpp:1094
APValue & getUnionValue()
Definition APValue.h:699
CharUnits & getLValueOffset()
Definition APValue.cpp:1021
void printPretty(raw_ostream &OS, const ASTContext &Ctx, QualType Ty) const
Definition APValue.cpp:708
bool isComplexFloat() const
Definition APValue.h:492
APValue & getVectorElt(unsigned I)
Definition APValue.h:585
APValue & getArrayFiller()
Definition APValue.h:640
unsigned getVectorLength() const
Definition APValue.h:593
bool isLValue() const
Definition APValue.h:493
void setUnion(const FieldDecl *Field, const APValue &Value)
Definition APValue.cpp:1087
bool isIndeterminate() const
Definition APValue.h:485
unsigned getMatrixNumRows() const
Definition APValue.h:598
bool isInt() const
Definition APValue.h:488
unsigned getArraySize() const
Definition APValue.h:652
bool allowConstexprUnknown() const
Definition APValue.h:331
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition APValue.cpp:984
bool isFixedPoint() const
Definition APValue.h:490
APValue & getMatrixElt(unsigned Idx)
Definition APValue.h:609
@ Indeterminate
This object has an indeterminate value (C++ [basic.indet]).
Definition APValue.h:132
@ None
There is no such object (it's outside its lifetime).
Definition APValue.h:130
bool isStruct() const
Definition APValue.h:497
APSInt & getComplexIntReal()
Definition APValue.h:541
APFloat & getComplexFloatImag()
Definition APValue.h:565
APFloat & getComplexFloatReal()
Definition APValue.h:557
APFloat & getFloat()
Definition APValue.h:525
APValue & getStructBase(unsigned i)
Definition APValue.h:669
bool isMatrix() const
Definition APValue.h:495
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:239
SourceManager & getSourceManager()
Definition ASTContext.h:911
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:852
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:970
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:903
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:969
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
CanQualType getCanonicalTagType(const TagDecl *TD) const
uint64_t getCharWidth() const
Return the size of the character type, in bits.
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
unsigned getFieldCount() const
getFieldCount - Get the number of fields in the layout.
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
CharUnits getBaseClassOffset(const CXXRecordDecl *Base) const
getBaseClassOffset - Get the offset, in chars, for the given base class.
CharUnits getVBaseClassOffset(const CXXRecordDecl *VBase) const
getVBaseClassOffset - Get the offset, in chars, for the given base class.
LabelDecl * getLabel() const
Definition Expr.h:4617
OpaqueValueExpr * getCommonExpr() const
Get the common subexpression shared by all initializations (the source array).
Definition Expr.h:6033
Expr * getSubExpr() const
Get the initializer to use for each array element.
Definition Expr.h:6038
Expr * getLHS()
An array access can be written A[4] or 4[A] (both are equivalent).
Definition Expr.h:2794
uint64_t getValue() const
Definition ExprCXX.h:3058
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3813
QualType getElementType() const
Definition TypeBase.h:3825
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition TypeBase.h:8255
Attr - This represents one attribute.
Definition Attr.h:46
BinaryConditionalOperator - The GNU extension to the conditional operator which allows the middle ope...
Definition Expr.h:4497
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression which will be evaluated if the condition evaluates to false; ...
Definition Expr.h:4551
OpaqueValueExpr * getOpaqueValue() const
getOpaqueValue - Return the opaque value placeholder.
Definition Expr.h:4535
Expr * getCommon() const
getCommon - Return the common expression, written to the left of the condition.
Definition Expr.h:4532
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:4082
static bool isLogicalOp(Opcode Opc)
Definition Expr.h:4215
Expr * getLHS() const
Definition Expr.h:4132
static bool isRelationalOp(Opcode Opc)
Definition Expr.h:4176
static bool isComparisonOp(Opcode Opc)
Definition Expr.h:4182
static Opcode getOpForCompoundAssignment(Opcode Opc)
Definition Expr.h:4229
SourceLocation getExprLoc() const
Definition Expr.h:4123
Expr * getRHS() const
Definition Expr.h:4134
static bool isAdditiveOp(Opcode Opc)
Definition Expr.h:4168
static bool isPtrMemOp(Opcode Opc)
predicates to categorize the respective opcodes.
Definition Expr.h:4159
static bool isAssignmentOp(Opcode Opc)
Definition Expr.h:4218
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operator.
Definition Expr.h:4295
Opcode getOpcode() const
Definition Expr.h:4127
static bool isEqualityOp(Opcode Opc)
Definition Expr.h:4179
bool hasCaptures() const
True if this block (or its nested blocks) captures anything of local storage from its enclosing scope...
Definition Decl.h:4929
const BlockDecl * getBlockDecl() const
Definition Expr.h:6734
bool isAuxBuiltinID(unsigned ID) const
Return true if the builtin ID belongs exclusively to the AuxTarget, and false if it belongs to both p...
Definition Builtins.h:443
unsigned getAuxBuiltinID(unsigned ID) const
Return real builtin ID (i.e.
Definition Builtins.h:449
AccessSpecifier Access
The access along this inheritance path.
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
CXXBasePath & front()
bool isAmbiguous(CanQualType BaseType) const
Determine whether the path from the most-derived type to the given base type is ambiguous (i....
Represents a base class of a C++ class.
Definition DeclCXX.h:146
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclCXX.h:194
bool isVirtual() const
Determines whether the base class is a virtual base class (or not).
Definition DeclCXX.h:203
QualType getType() const
Retrieves the type of the base class.
Definition DeclCXX.h:249
const Expr * getSubExpr() const
Definition ExprCXX.h:1519
bool getValue() const
Definition ExprCXX.h:744
Represents a call to a C++ constructor.
Definition ExprCXX.h:1552
bool isElidable() const
Whether this construction is elidable.
Definition ExprCXX.h:1621
Expr * getArg(unsigned Arg)
Return the specified argument.
Definition ExprCXX.h:1695
bool requiresZeroInitialization() const
Whether this construction first requires zero-initialization before the initializer is called.
Definition ExprCXX.h:1654
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition ExprCXX.h:1615
unsigned getNumArgs() const
Return the number of arguments to the constructor call.
Definition ExprCXX.h:1692
Represents a C++ constructor within a class.
Definition DeclCXX.h:2642
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:2725
Expr * getExpr()
Get the initialization expression that will be used.
Definition ExprCXX.cpp:1138
FunctionDecl * getOperatorDelete() const
Definition ExprCXX.h:2669
bool isArrayForm() const
Definition ExprCXX.h:2656
bool isGlobalDelete() const
Definition ExprCXX.h:2655
Represents a C++ destructor within a class.
Definition DeclCXX.h:2907
CXXForRangeStmt - This represents C++0x [stmt.ranged]'s ranged for statement, represented as 'for (ra...
Definition StmtCXX.h:136
DeclStmt * getBeginStmt()
Definition StmtCXX.h:164
DeclStmt * getLoopVarStmt()
Definition StmtCXX.h:170
DeclStmt * getEndStmt()
Definition StmtCXX.h:167
DeclStmt * getRangeStmt()
Definition StmtCXX.h:163
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will call.
Definition ExprCXX.h:1792
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2150
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:2293
bool isInstance() const
Definition DeclCXX.h:2177
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:2468
QualType getAllocatedType() const
Definition ExprCXX.h:2438
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:2473
Expr * getPlacementArg(unsigned I)
Definition ExprCXX.h:2507
unsigned getNumPlacementArgs() const
Definition ExprCXX.h:2498
SourceRange getSourceRange() const
Definition ExprCXX.h:2614
FunctionDecl * getOperatorNew() const
Definition ExprCXX.h:2463
Expr * getInitializer()
The initializer of this new-expression.
Definition ExprCXX.h:2537
bool getValue() const
Definition ExprCXX.h:4385
MutableArrayRef< Expr * > getInitExprs()
Definition ExprCXX.h:5234
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.
Expr * getSemanticForm()
Get an equivalent semantic form for this expression.
Definition ExprCXX.h:308
bool isImplicit() const
Definition ExprCXX.h:1181
bool isTypeOperand() const
Definition ExprCXX.h:888
QualType getTypeOperand(const ASTContext &Context) const
Retrieves the type operand of this typeid() expression after various required adjustments (removing r...
Definition ExprCXX.cpp:167
Expr * getExprOperand() const
Definition ExprCXX.h:899
bool isPotentiallyEvaluated() const
Determine whether this typeid has a type operand which is potentially evaluated, per C++11 [expr....
Definition ExprCXX.cpp:135
MSGuidDecl * getGuidDecl() const
Definition ExprCXX.h:1118
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2987
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3191
SourceLocation getBeginLoc() const
Definition Expr.h:3321
const AllocSizeAttr * getCalleeAllocSizeAttr() const
Try to get the alloc_size attribute of the callee. May return null.
Definition Expr.cpp:3626
unsigned getBuiltinCallee() const
getBuiltinCallee - If this is a call to a builtin, return the builtin ID of the callee.
Definition Expr.cpp:1620
Expr * getCallee()
Definition Expr.h:3134
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition Expr.h:3178
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operator.
Definition Expr.h:3280
Expr ** getArgs()
Retrieve the call arguments.
Definition Expr.h:3181
Decl * getCalleeDecl()
Definition Expr.h:3164
QualType getCallReturnType(const ASTContext &Ctx) const
getCallReturnType - Get the return type of the call expr.
Definition Expr.cpp:1631
CaseStmt - Represent a case statement.
Definition Stmt.h:1932
Expr * getLHS()
Definition Stmt.h:2015
Expr * getRHS()
Definition Stmt.h:2027
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition Expr.h:3720
path_iterator path_begin()
Definition Expr.h:3790
unsigned path_size() const
Definition Expr.h:3789
CastKind getCastKind() const
Definition Expr.h:3764
const FieldDecl * getTargetUnionField() const
Definition Expr.h:3814
path_iterator path_end()
Definition Expr.h:3791
const CXXBaseSpecifier *const * path_const_iterator
Definition Expr.h:3787
bool path_empty() const
Definition Expr.h:3788
Expr * getSubExpr()
Definition Expr.h:3770
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operation.
Definition Expr.h:3834
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:175
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:153
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:1649
Expr * getChosenSubExpr() const
getChosenSubExpr - Return the subexpression chosen according to the condition.
Definition Expr.h:4928
const ValueInfo * getValueInfo(ComparisonCategoryResult ValueKind) const
ComparisonCategoryResult makeWeakResult(ComparisonCategoryResult Res) const
Converts the specified result kind into the correct result kind for this category.
Complex values, per C99 6.2.5p11.
Definition TypeBase.h:3355
QualType getElementType() const
Definition TypeBase.h:3365
CompoundAssignOperator - For compound assignments (e.g.
Definition Expr.h:4344
QualType getComputationLHSType() const
Definition Expr.h:4378
CompoundLiteralExpr - [C99 6.5.2.5].
Definition Expr.h:3649
bool hasStaticStorage() const
Definition Expr.h:3694
APValue & getOrCreateStaticValue(ASTContext &Ctx) const
Definition Expr.cpp:5736
bool isFileScope() const
Definition Expr.h:3681
const Expr * getInitializer() const
Definition Expr.h:3677
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition Stmt.h:1752
bool body_empty() const
Definition Stmt.h:1796
Stmt *const * const_body_iterator
Definition Stmt.h:1824
body_iterator body_end()
Definition Stmt.h:1817
body_range body()
Definition Stmt.h:1815
body_iterator body_begin()
Definition Stmt.h:1816
bool isSatisfied() const
Whether or not the concept with the given arguments was satisfied when the expression was created.
ConditionalOperator - The ?
Definition Expr.h:4435
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression representing the value of the expression if the condition eva...
Definition Expr.h:4467
Expr * getCond() const
getCond - Return the expression representing the condition for the ?
Definition Expr.h:4458
Expr * getTrueExpr() const
getTrueExpr - Return the subexpression representing the value of the expression if the condition eval...
Definition Expr.h:4462
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3851
unsigned getSizeBitWidth() const
Return the bit width of the size type.
Definition TypeBase.h:3914
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:334
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:374
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:3940
bool isZeroSize() const
Return true if the size is zero.
Definition TypeBase.h:3921
const Expr * getSizeExpr() const
Return a pointer to the size expression.
Definition TypeBase.h:3947
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3907
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition TypeBase.h:3927
APValue getAPValueResult() const
Definition Expr.cpp:419
bool hasAPValueResult() const
Definition Expr.h:1177
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4483
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operator.
Definition Expr.h:4840
Expr * getSrcExpr() const
getSrcExpr - Return the Expr to be converted.
Definition Expr.h:4853
Represents the current source location and context used to determine the value of the source location...
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1466
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2126
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition DeclBase.h:2279
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:1290
bool refersToEnclosingVariableOrCapture() const
Does this DeclRefExpr refer to an enclosing local or a captured variable?
Definition Expr.h:1494
ValueDecl * getDecl()
Definition Expr.h:1358
DeclStmt - Adaptor class for mixing declarations with statements and expressions.
Definition Stmt.h:1643
decl_range decls()
Definition Stmt.h:1691
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
bool isInStdNamespace() const
Definition DeclBase.cpp:453
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:550
bool isInvalidDecl() const
Definition DeclBase.h:596
SourceLocation getLocation() const
Definition DeclBase.h:447
DeclContext * getDeclContext()
Definition DeclBase.h:456
AccessSpecifier getAccess() const
Definition DeclBase.h:515
A decomposition declaration.
Definition DeclCXX.h:4279
auto flat_bindings() const
Definition DeclCXX.h:4324
InitListExpr * getUpdater() const
Definition Expr.h:5986
Designator - A designator in a C99 designated initializer.
Definition Designator.h:38
DoStmt - This represents a 'do/while' stmt.
Definition Stmt.h:2844
Stmt * getBody()
Definition Stmt.h:2869
Expr * getCond()
Definition Stmt.h:2862
Symbolic representation of a dynamic allocation.
Definition APValue.h:66
static unsigned getMaxIndex()
Definition APValue.h:86
const Expr * getBase() const
Definition Expr.h:6631
ChildElementIter< false > begin()
Definition Expr.h:5285
ExplicitCastExpr - An explicit cast written in the source code.
Definition Expr.h:3972
QualType getTypeAsWritten() const
getTypeAsWritten - Returns the type that this expression is casting to, as written in the source code...
Definition Expr.h:3999
This represents one expression.
Definition Expr.h:113
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:288
SideEffectsKind
Definition Expr.h:691
@ SE_AllowSideEffects
Allow any unmodeled side effect.
Definition Expr.h:695
@ SE_AllowUndefinedBehavior
Allow UB that we can give a value, but not arbitrary unmodeled side effects.
Definition Expr.h:693
bool EvaluateCharRangeAsString(std::string &Result, const Expr *SizeExpression, const Expr *PtrExpression, ASTContext &Ctx, EvalResult &Status) const
llvm::APSInt EvaluateKnownConstIntCheckOverflow(const ASTContext &Ctx, SmallVectorImpl< PartialDiagnosticAt > *Diag=nullptr) const
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition Expr.cpp:3128
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:178
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
bool isCXX11ConstantExpr(const ASTContext &Ctx, APValue &Result, bool AllowRelaxedEval=false) const
isCXX11ConstantExpr - Return true if this expression is a constant expression in C++11.
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Returns the set of floating point options that apply to this expression.
Definition Expr.cpp:4025
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3123
bool containsErrors() const
Whether this expression contains subexpressions which had errors.
Definition Expr.h:247
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:3119
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:286
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition Expr.h:285
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:3722
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:3286
Expr()=delete
ConstantExprKind
Definition Expr.h:769
std::optional< uint64_t > tryEvaluateObjectSize(const ASTContext &Ctx, unsigned Type) const
If the current Expr is a pointer, this will try to statically determine the number of bytes available...
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:283
QualType getType() const
Definition Expr.h:145
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:4479
void getEncodedElementAccess(SmallVectorImpl< uint32_t > &Elts) const
getEncodedElementAccess - Encode the elements accessed into an llvm aggregate Constant of ConstantInt...
Definition Expr.cpp:4592
bool isFPConstrained() const
LangOptions::FPExceptionModeKind getExceptionMode() const
RoundingMode getRoundingMode() const
Represents a member of a struct/union/class.
Definition Decl.h:3295
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3398
unsigned getBitWidthValue() const
Computes the bit width of this field, if this is a bit field.
Definition Decl.cpp:4817
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition Decl.h:3380
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3531
FieldDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this field.
Definition Decl.h:3542
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:1595
llvm::APFloat getValue() const
Definition Expr.h:1686
ForStmt - This represents a 'for (init;cond;inc)' stmt.
Definition Stmt.h:2900
Stmt * getInit()
Definition Stmt.h:2915
VarDecl * getConditionVariable() const
Retrieve the variable declared in this "for" statement, if any.
Definition Stmt.cpp:1120
Stmt * getBody()
Definition Stmt.h:2944
Expr * getInc()
Definition Stmt.h:2943
Expr * getCond()
Definition Stmt.h:2942
const Expr * getSubExpr() const
Definition Expr.h:1082
Represents a function declaration or definition.
Definition Decl.h:2059
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2928
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition Decl.cpp:3266
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition Decl.cpp:4244
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition Decl.cpp:4232
bool hasCXXExplicitFunctionObjectParameter() const
Definition Decl.cpp:3907
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition Decl.h:2504
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition Decl.cpp:4368
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition Decl.h:2597
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:3468
bool isDefaulted() const
Whether this function is defaulted.
Definition Decl.h:2512
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:3111
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:6518
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:2271
Stmt * getThen()
Definition Stmt.h:2360
Stmt * getInit()
Definition Stmt.h:2421
bool isNonNegatedConsteval() const
Definition Stmt.h:2456
Expr * getCond()
Definition Stmt.h:2348
Stmt * getElse()
Definition Stmt.h:2369
bool isConsteval() const
Definition Stmt.h:2451
VarDecl * getConditionVariable()
Retrieve the variable declared in this "if" statement, if any.
Definition Stmt.cpp:1068
const Expr * getSubExpr() const
Definition Expr.h:1763
Represents an implicitly-generated value initialization of an object of a given type.
Definition Expr.h:6107
Represents a field injected from an anonymous union/struct into the parent scope.
Definition Decl.h:3602
ArrayRef< NamedDecl * > chain() const
Definition Decl.h:3623
Describes an C or C++ initializer list.
Definition Expr.h:5352
bool isTransparent() const
Is this a transparent initializer list (that is, an InitListExpr that is purely syntactic,...
Definition Expr.cpp:2495
bool isStringLiteralInit() const
Is this an initializer for an array of characters, initialized by a string literal or an @encode?
Definition Expr.cpp:2481
unsigned getNumInits() const
Definition Expr.h:5385
Expr * getArrayFiller()
If this initializer list initializes an array with more elements than there are initializers in the l...
Definition Expr.h:5455
const Expr * getInit(unsigned Init) const
Definition Expr.h:5407
ArrayRef< Expr * > inits() const
Definition Expr.h:5405
capture_init_iterator capture_init_end()
Retrieve the iterator pointing one past the last initialization argument for this lambda expression.
Definition ExprCXX.h:2110
capture_init_iterator capture_init_begin()
Retrieve the first initialization argument for this lambda expression (which initializes the first ca...
Definition ExprCXX.h:2098
CXXRecordDecl * getLambdaClass() const
Retrieve the class that corresponds to the lambda.
Definition ExprCXX.cpp:1433
@ 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:4973
StorageDuration getStorageDuration() const
Retrieve the storage duration for the materialized temporary.
Definition ExprCXX.h:4998
Expr * getSubExpr() const
Retrieve the temporary-generating subexpression whose value will be materialized into a glvalue.
Definition ExprCXX.h:4990
APValue * getOrCreateValue(bool MayCreate) const
Get the storage for the constant value of a materialized temporary of static storage duration.
Definition ExprCXX.h:5006
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3408
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3491
Expr * getBase() const
Definition Expr.h:3485
bool isArrow() const
Definition Expr.h:3592
This represents a decl that may have a name.
Definition Decl.h:275
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:296
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:302
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:341
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:1689
bool isExpressibleAsConstantInitializer() const
Definition ExprObjC.h:67
Expr * getIndexExpr(unsigned Idx)
Definition Expr.h:2630
const OffsetOfNode & getComponent(unsigned Idx) const
Definition Expr.h:2618
TypeSourceInfo * getTypeSourceInfo() const
Definition Expr.h:2611
unsigned getNumComponents() const
Definition Expr.h:2626
unsigned getArrayExprIndex() const
For an array element node, returns the index into the array of expressions.
Definition Expr.h:2523
FieldDecl * getField() const
For a field offsetof node, returns the field.
Definition Expr.h:2529
@ Array
An index into an array.
Definition Expr.h:2470
@ Identifier
A field in a dependent type, known only by its name.
Definition Expr.h:2474
@ Field
A field.
Definition Expr.h:2472
@ Base
An implicit indirection through a C++ base class, when the field found is in a base class.
Definition Expr.h:2477
Kind getKind() const
Determine what kind of offsetof node this is.
Definition Expr.h:2519
CXXBaseSpecifier * getBase() const
For a base class node, returns the base specifier.
Definition Expr.h:2539
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition Expr.h:1198
Expr * getSourceExpr() const
The source expression of an opaque value expression is the expression which originally generated the ...
Definition Expr.h:1248
Expr * getSelectedExpr() const
Definition ExprCXX.h:4692
const Expr * getSubExpr() const
Definition Expr.h:2243
Represents a parameter to a function.
Definition Decl.h:1820
unsigned getFunctionScopeIndex() const
Returns the index of this parameter in its prototype or method scope.
Definition Decl.h:1880
bool isExplicitObjectParameter() const
Definition Decl.h:1908
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3396
StringLiteral * getFunctionName()
Definition Expr.h:2093
Expr * getResultExpr()
Return the result-bearing expression, or null if there is none.
Definition Expr.h:6902
ArrayRef< Expr * > semantics()
Definition Expr.h:6926
A (possibly-)qualified type.
Definition TypeBase.h:938
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8523
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:8439
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8479
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:8624
QualType getCanonicalType() const
Definition TypeBase.h:8491
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8533
void removeLocalVolatile()
Definition TypeBase.h:8555
void addVolatile()
Add the volatile type qualifier to this QualType.
Definition TypeBase.h:1180
void removeLocalConst()
Definition TypeBase.h:8547
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8512
QualType getAtomicUnqualifiedType() const
Remove all qualifiers including _Atomic.
Definition Type.cpp:1839
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:8485
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:4460
unsigned getNumFields() const
Returns the number of fields (non-static data members) in this record.
Definition Decl.h:4676
field_iterator field_end() const
Definition Decl.h:4666
field_range fields() const
Definition Decl.h:4663
specific_decl_iterator< FieldDecl > field_iterator
Definition Decl.h:4660
bool isAnonymousStructOrUnion() const
Whether this is an anonymous struct or union.
Definition Decl.h:4512
bool field_empty() const
Definition Decl.h:4671
field_iterator field_begin() const
Definition Decl.cpp:5340
bool isSatisfied() const
Whether or not the requires clause is satisfied.
SourceLocation getLocation() const
Definition Expr.h:2199
std::string ComputeName(ASTContext &Context) const
Definition Expr.cpp:593
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
ShuffleVectorExpr - clang-specific builtin-in function __builtin_shufflevector.
Definition Expr.h:4687
llvm::APSInt getShuffleMaskIdx(unsigned N) const
Definition Expr.h:4739
unsigned getNumSubExprs() const
getNumSubExprs - Return the size of the SubExprs array.
Definition Expr.h:4720
Expr * getExpr(unsigned Index)
getExpr - Return the Expr at the specified index.
Definition Expr.h:4726
unsigned getPackLength() const
Retrieve the length of the parameter pack.
Definition ExprCXX.h:4568
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:2313
bool isIntType() const
Definition Expr.h:5094
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:4656
Stmt - This represents one statement.
Definition Stmt.h:85
@ NoStmtClass
Definition Stmt.h:88
StmtClass getStmtClass() const
Definition Stmt.h:1505
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:1819
UnsignedOrNone findZeroCodeUnit(unsigned StartIndex=0) const
Scan the string literal contents for a code unit with value 0.
Definition Expr.cpp:1410
unsigned getLength() const
Definition Expr.h:1944
uint32_t getCodeUnit(size_t I) const
Return the code unit at the given position.
Definition Expr.h:1906
StringRef getBytes() const
Allow access to clients that need the byte representation, such as ASTWriterStmt::VisitStringLiteral(...
Definition Expr.h:1895
StringRef getString() const
Definition Expr.h:1887
bool isOrdinary() const
Definition Expr.h:1952
const SwitchCase * getNextSwitchCase() const
Definition Stmt.h:1905
SwitchStmt - This represents a 'switch' stmt.
Definition Stmt.h:2521
Expr * getCond()
Definition Stmt.h:2584
Stmt * getBody()
Definition Stmt.h:2596
VarDecl * getConditionVariable()
Retrieve the variable declared in this "switch" statement, if any.
Definition Stmt.cpp:1186
Stmt * getInit()
Definition Stmt.h:2601
SwitchCase * getSwitchCaseList()
Definition Stmt.h:2652
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:3953
TagDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:4964
bool isUnion() const
Definition Decl.h:4063
Exposes information about the current target.
Definition TargetInfo.h:226
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
unsigned size() const
Retrieve the number of template arguments in this template argument list.
ArrayRef< TemplateArgument > asArray() const
Produce this as an array ref.
@ Type
The template argument is a type.
Symbolic representation of typeid(T) for some type T.
Definition APValue.h:45
QualType getType() const
Return the type wrapped by this type source info.
Definition TypeBase.h:8421
bool getBoolValue() const
Definition ExprCXX.h:2961
bool isStoredAsComparisonResult() const
Definition ExprCXX.h:2957
const APValue & getAPValue() const
Definition ExprCXX.h:2966
bool isStoredAsBoolean() const
Definition ExprCXX.h:2953
The base class of the type hierarchy.
Definition TypeBase.h:1879
bool isVoidType() const
Definition TypeBase.h:9048
bool isBooleanType() const
Definition TypeBase.h:9185
bool isFunctionReferenceType() const
Definition TypeBase.h:8750
bool isMFloat8Type() const
Definition TypeBase.h:9073
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2413
bool isPackedVectorBoolType(const ASTContext &ctx) const
Definition Type.cpp:540
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:8783
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2390
bool isComplexType() const
isComplexType() does not include complex integers (a GCC extension).
Definition Type.cpp:855
const ArrayType * castAsArrayTypeUnsafe() const
A variant of castAs<> for array type which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9351
bool isUnsignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is unsigned or an enumeration types whose underlying ...
Definition Type.cpp:2481
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition Type.cpp:2297
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:8779
bool isNothrowT() const
Definition Type.cpp:3423
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition Type.h:41
bool isVoidPointerType() const
Definition Type.cpp:843
bool isConstantSizeType() const
Return true if this is not a variable sized type, according to the rules of C99 6....
Definition Type.cpp:2643
bool isArrayType() const
Definition TypeBase.h:8775
bool isFunctionPointerType() const
Definition TypeBase.h:8743
bool isCountAttributedType() const
Definition Type.cpp:872
bool isConstantMatrixType() const
Definition TypeBase.h:8843
bool isPointerType() const
Definition TypeBase.h:8676
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9092
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9342
bool isReferenceType() const
Definition TypeBase.h:8700
bool isEnumeralType() const
Definition TypeBase.h:8807
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:2078
bool isVariableArrayType() const
Definition TypeBase.h:8787
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition Type.cpp:2827
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:883
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:9170
bool isExtVectorBoolType() const
Definition TypeBase.h:8823
bool isMemberDataPointerType() const
Definition TypeBase.h:8768
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition TypeBase.h:9017
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2859
RecordDecl * castAsRecordDecl() const
Definition Type.h:48
bool isAnyComplexType() const
Definition TypeBase.h:8811
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9108
bool isMemberPointerType() const
Definition TypeBase.h:8757
bool isAtomicType() const
Definition TypeBase.h:8868
bool isComplexIntegerType() const
Definition Type.cpp:861
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9328
bool isObjectType() const
Determine whether this type is an object type.
Definition TypeBase.h:2574
EnumDecl * getAsEnumDecl() const
Retrieves the EnumDecl this type refers to.
Definition Type.h:53
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2653
bool isFunctionType() const
Definition TypeBase.h:8672
bool isVectorType() const
Definition TypeBase.h:8815
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2531
bool isFloatingType() const
Definition Type.cpp:2515
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:2458
const T * castAsCanonical() const
Return this type's canonical type cast to the specified type.
Definition TypeBase.h:3005
bool isAnyPointerType() const
Definition TypeBase.h:8684
TypeClass getTypeClass() const
Definition TypeBase.h:2449
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9275
bool isNullPtrType() const
Definition TypeBase.h:9085
bool isRecordType() const
Definition TypeBase.h:8803
bool isUnionType() const
Definition Type.cpp:849
bool isSizelessVectorType() const
Returns true for all scalable vector types.
Definition Type.cpp:2789
bool hasPointerRepresentation() const
Whether this type is represented natively as a pointer.
Definition TypeBase.h:9219
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand.
Definition Expr.h:2669
QualType getArgumentType() const
Definition Expr.h:2712
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:2748
QualType getTypeOfArgument() const
Gets the argument type, or the type of the argument expression, whichever is appropriate.
Definition Expr.h:2738
UnaryExprOrTypeTrait getKind() const
Definition Expr.h:2701
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2288
SourceLocation getExprLoc() const
Definition Expr.h:2412
Expr * getSubExpr() const
Definition Expr.h:2329
Opcode getOpcode() const
Definition Expr.h:2324
static bool isIncrementOp(Opcode Op)
Definition Expr.h:2370
bool canOverflow() const
Returns true if the unary operator can cause an overflow.
Definition Expr.h:2342
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:713
QualType getType() const
Definition Decl.h:724
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr.
Definition Decl.cpp:5646
QualType getType() const
Definition Value.cpp:238
bool hasValue() const
Definition Value.h:135
Represents a variable declaration or definition.
Definition Decl.h:933
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition Decl.h:1594
bool hasInit() const
Definition Decl.cpp:2378
bool hasICEInitializer(const ASTContext &Context) const
Determine whether the initializer of this variable is an integer constant expression.
Definition Decl.cpp:2627
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition Decl.h:1603
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:2619
CharUnits getFlexibleArrayInitChars(const ASTContext &Ctx) const
If hasFlexibleArrayInit is true, compute the number of additional bytes necessary to store those elem...
Definition Decl.cpp:2847
bool hasConstantInitialization() const
Determine whether this variable has constant initialization.
Definition Decl.cpp:2639
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
Definition Decl.cpp:2346
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:2466
EvaluatedStmt * ensureEvaluatedStmt() const
Convert the initializer for this declaration to the elaborated EvaluatedStmt form,...
Definition Decl.cpp:2537
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:1215
bool isCXXForRangeImplicitVar() const
Whether this variable is the implicit '__range' variable in C++ range-based for loops.
Definition Decl.h:1647
ThreadStorageClassSpecifier getTSCSpec() const
Definition Decl.h:1184
const Expr * getInit() const
Definition Decl.h:1392
const APValue * evaluateValue() const
Attempt to evaluate the value of the initializer attached to this declaration, and produce notes expl...
Definition Decl.cpp:2555
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition Decl.h:1191
DefinitionKind hasDefinition(ASTContext &) const
Check whether this variable is defined in this translation unit.
Definition Decl.cpp:2355
bool isLocalVarDecl() const
Returns true for local variable declarations other than parameters.
Definition Decl.h:1275
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:2508
const Expr * getAnyInitializer() const
Get the initializer for this variable, no matter which declaration it is attached to.
Definition Decl.h:1382
Expr * getSizeExpr() const
Definition TypeBase.h:4071
Represents a GCC generic vector type.
Definition TypeBase.h:4266
unsigned getNumElements() const
Definition TypeBase.h:4281
QualType getElementType() const
Definition TypeBase.h:4280
WhileStmt - This represents a 'while' stmt.
Definition Stmt.h:2709
Expr * getCond()
Definition Stmt.h:2761
VarDecl * getConditionVariable()
Retrieve the variable declared in this "while" statement, if any.
Definition Stmt.cpp:1247
Stmt * getBody()
Definition Stmt.h:2773
std::optional< uint64_t > tryEvaluateObjectSize(const EvalSettings &Settings, const Expr *E, unsigned Kind, bool IsDynamic)
If.
Definition Context.cpp:429
bool evaluateString(const EvalSettings &Settings, const Expr *E, std::string &Result)
Evaluate.
Definition Context.cpp:296
bool evaluateDestruction(const EvalSettings &Settings, const VarDecl *VD, APValue Value)
Evaluates the destruction of a variable.
Definition Context.cpp:168
std::optional< bool > evaluateWithSubstitution(const EvalSettings &Settings, const FunctionDecl *Callee, ArrayRef< const Expr * > Args, const Expr *This, const Expr *Condition)
Definition Context.cpp:459
bool evaluate(const EvalSettings &Settings, const Expr *E, APValue &Result)
Like evaluateAsRvalue(), but does no implicit lvalue-to-rvalue conversion.
Definition Context.cpp:106
bool evaluateAsInitializer(const EvalSettings &Settings, const VarDecl *VD, const Expr *Init, APValue &Result)
Evaluates a toplevel initializer.
Definition Context.cpp:135
bool evaluateAsRValue(const EvalSettings &Settings, const Expr *E, APValue &Result)
Evaluates a toplevel expression as an rvalue.
Definition Context.cpp:76
bool evaluateCharRange(const EvalSettings &Settings, const Expr *SizeExpr, const Expr *PtrExpr, APValue &Result)
Definition Context.cpp:278
std::optional< uint64_t > evaluateStrlen(const EvalSettings &Settings, const Expr *E)
Evalute.
Definition Context.cpp:361
void isPotentialConstantExprUnevaluated(const EvalSettings &Settings, const Expr *E, const FunctionDecl *FD)
Definition Context.cpp:62
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:79
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:4517
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:433
bool NE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1518
llvm::FixedPointSemantics FixedPointSemantics
Definition Interp.h:56
bool This(InterpState &S, CodePtr OpPC)
Definition Interp.h:3228
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:3961
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
@ 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:5801
bool hasSpecificAttr(const Container &container)
@ NonNull
Values of this type can never be null.
Definition Specifiers.h:349
@ Success
Annotation was successful.
Definition Parser.h:65
Expr::ConstantExprKind ConstantExprKind
Definition Expr.h:1062
@ Self
'self' clause, allowed on Compute and Combined Constructs, plus 'update'.
bool operator==(const CallGraphNode::CallRecord &LHS, const CallGraphNode::CallRecord &RHS)
Definition CallGraph.h:218
@ AS_public
Definition Specifiers.h:125
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
bool isLambdaCallWithExplicitObjectParameter(const DeclContext *DC)
Definition ASTLambda.h:45
@ TSCS_unspecified
Definition Specifiers.h:237
ComparisonCategoryResult
An enumeration representing the possible results of a three-way comparison.
CheckSubobjectKind
The order of this enum is important for diagnostics.
Definition State.h:42
@ CSK_ArrayToPointer
Definition State.h:46
@ CSK_Derived
Definition State.h:44
@ CSK_Base
Definition State.h:43
@ CSK_Real
Definition State.h:48
@ CSK_ArrayIndex
Definition State.h:47
@ CSK_Imag
Definition State.h:49
@ CSK_VectorElement
Definition State.h:50
@ CSK_Field
Definition State.h:45
@ SD_Static
Static storage duration.
Definition Specifiers.h:342
@ SD_FullExpression
Full-expression storage duration (for temporaries).
Definition Specifiers.h:339
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition ASTLambda.h:28
@ Result
The result type of a method or function.
Definition TypeBase.h:906
AccessKinds
Kinds of access we can perform on an object, for diagnostics.
Definition State.h:26
@ AK_TypeId
Definition State.h:34
@ AK_Construct
Definition State.h:35
@ AK_Increment
Definition State.h:30
@ AK_DynamicCast
Definition State.h:33
@ AK_Read
Definition State.h:27
@ AK_Assign
Definition State.h:29
@ AK_IsWithinLifetime
Definition State.h:37
@ AK_MemberCall
Definition State.h:32
@ AK_ReadObjectRepresentation
Definition State.h:28
@ AK_Dereference
Definition State.h:38
@ AK_Destroy
Definition State.h:36
@ AK_Decrement
Definition State.h:31
OptionalUnsigned< unsigned > UnsignedOrNone
const FunctionProtoType * T
@ Off
Never emit colors regardless of the output stream.
@ Type
The name was classified as a type.
Definition Sema.h:558
CastKind
CastKind - The kind of operation required for a conversion.
llvm::hash_code hash_value(const CustomizableOptional< T > &O)
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:136
EvaluationMode
Definition State.h:53
@ ConstantFold
Fold the expression to a constant.
Definition State.h:67
@ ConstantExpressionUnevaluated
Evaluate as a constant expression.
Definition State.h:63
@ ConstantExpression
Evaluate as a constant expression.
Definition State.h:56
@ IgnoreSideEffects
Evaluate in any way we know how.
Definition State.h:71
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition DeclBase.h:1305
U cast(CodeGen::Address addr)
Definition Address.h:327
@ None
The alignment was not explicit in code.
Definition ASTContext.h:176
@ ArrayBound
Array bound in array declarator or new-expression.
Definition Sema.h:838
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6018
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ Other
Other implicit parameter.
Definition Decl.h:1775
ActionResult< Stmt * > StmtResult
Definition Ownership.h:250
unsigned long uint64_t
long int64_t
Diagnostic wrappers for TextAPI types for error reporting.
Definition Dominators.h:30
hash_code hash_value(const clang::dependencies::ModuleID &ID)
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t __packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 __packed_splat2 uint8_t
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t __packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 __packed_splat2 __packed_splat4 uint16_t
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t __packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 __packed_splat2 __packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 uint32_t
#define false
Definition stdbool.h:26
unsigned PathLength
The corresponding path length in the lvalue.
const CXXRecordDecl * Type
The dynamic class type of the object.
std::string ObjCEncodeStorage
Represents an element in a path from a derived class to a base class.
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:666
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:668
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:622
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:650
bool HasSideEffects
Whether the evaluated expression has side effects.
Definition Expr.h:625
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