clang 23.0.0git
ExprConstant.cpp
Go to the documentation of this file.
1//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the Expr constant evaluator.
10//
11// Constant expression evaluation produces four main results:
12//
13// * A success/failure flag indicating whether constant folding was successful.
14// This is the 'bool' return value used by most of the code in this file. A
15// 'false' return value indicates that constant folding has failed, and any
16// appropriate diagnostic has already been produced.
17//
18// * An evaluated result, valid only if constant folding has not failed.
19//
20// * A flag indicating if evaluation encountered (unevaluated) side-effects.
21// These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
22// where it is possible to determine the evaluated result regardless.
23//
24// * A set of notes indicating why the evaluation was not a constant expression
25// (under the C++11 / C++1y rules only, at the moment), or, if folding failed
26// too, why the expression could not be folded.
27//
28// If we are checking for a potential constant expression, failure to constant
29// fold a potential constant sub-expression will be indicated by a 'false'
30// return value (the expression could not be folded) and no diagnostic (the
31// expression is not necessarily non-constant).
32//
33//===----------------------------------------------------------------------===//
34
35#include "ByteCode/Context.h"
36#include "ByteCode/Frame.h"
37#include "ByteCode/State.h"
38#include "ExprConstShared.h"
39#include "clang/AST/APValue.h"
41#include "clang/AST/ASTLambda.h"
42#include "clang/AST/Attr.h"
44#include "clang/AST/CharUnits.h"
46#include "clang/AST/Expr.h"
48#include "clang/AST/OSLog.h"
52#include "clang/AST/Type.h"
53#include "clang/AST/TypeLoc.h"
58#include "llvm/ADT/APFixedPoint.h"
59#include "llvm/ADT/Sequence.h"
60#include "llvm/ADT/SmallBitVector.h"
61#include "llvm/ADT/StringExtras.h"
62#include "llvm/Support/Casting.h"
63#include "llvm/Support/Debug.h"
64#include "llvm/Support/SaveAndRestore.h"
65#include "llvm/Support/SipHash.h"
66#include "llvm/Support/TimeProfiler.h"
67#include "llvm/Support/raw_ostream.h"
68#include <cstring>
69#include <functional>
70#include <limits>
71#include <optional>
72
73#define DEBUG_TYPE "exprconstant"
74
75using namespace clang;
76using llvm::APFixedPoint;
77using llvm::APInt;
78using llvm::APSInt;
79using llvm::APFloat;
80using llvm::FixedPointSemantics;
81
82namespace {
83 struct LValue;
84 class CallStackFrame;
85 class EvalInfo;
86
87 using SourceLocExprScopeGuard =
89
91 return B.getType();
92 }
93
94 /// Get an LValue path entry, which is known to not be an array index, as a
95 /// field declaration.
96 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
97 return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer());
98 }
99 /// Get an LValue path entry, which is known to not be an array index, as a
100 /// base class declaration.
101 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
102 return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer());
103 }
104 /// Determine whether this LValue path entry for a base class names a virtual
105 /// base class.
106 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
107 return E.getAsBaseOrMember().getInt();
108 }
109
110 /// Given an expression, determine the type used to store the result of
111 /// evaluating that expression.
112 static QualType getStorageType(const ASTContext &Ctx, const Expr *E) {
113 if (E->isPRValue())
114 return E->getType();
115 return Ctx.getLValueReferenceType(E->getType());
116 }
117
118 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
119 /// This will look through a single cast.
120 ///
121 /// Returns null if we couldn't unwrap a function with alloc_size.
122 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
123 if (!E->getType()->isPointerType())
124 return nullptr;
125
126 E = E->IgnoreParens();
127 // If we're doing a variable assignment from e.g. malloc(N), there will
128 // probably be a cast of some kind. In exotic cases, we might also see a
129 // top-level ExprWithCleanups. Ignore them either way.
130 if (const auto *FE = dyn_cast<FullExpr>(E))
131 E = FE->getSubExpr()->IgnoreParens();
132
133 if (const auto *Cast = dyn_cast<CastExpr>(E))
134 E = Cast->getSubExpr()->IgnoreParens();
135
136 if (const auto *CE = dyn_cast<CallExpr>(E))
137 return CE->getCalleeAllocSizeAttr() ? CE : nullptr;
138 return nullptr;
139 }
140
141 /// Determines whether or not the given Base contains a call to a function
142 /// with the alloc_size attribute.
143 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
144 const auto *E = Base.dyn_cast<const Expr *>();
145 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
146 }
147
148 /// Determines whether the given kind of constant expression is only ever
149 /// used for name mangling. If so, it's permitted to reference things that we
150 /// can't generate code for (in particular, dllimported functions).
151 static bool isForManglingOnly(ConstantExprKind Kind) {
152 switch (Kind) {
153 case ConstantExprKind::Normal:
154 case ConstantExprKind::ClassTemplateArgument:
155 case ConstantExprKind::ImmediateInvocation:
156 // Note that non-type template arguments of class type are emitted as
157 // template parameter objects.
158 return false;
159
160 case ConstantExprKind::NonClassTemplateArgument:
161 return true;
162 }
163 llvm_unreachable("unknown ConstantExprKind");
164 }
165
166 static bool isTemplateArgument(ConstantExprKind Kind) {
167 switch (Kind) {
168 case ConstantExprKind::Normal:
169 case ConstantExprKind::ImmediateInvocation:
170 return false;
171
172 case ConstantExprKind::ClassTemplateArgument:
173 case ConstantExprKind::NonClassTemplateArgument:
174 return true;
175 }
176 llvm_unreachable("unknown ConstantExprKind");
177 }
178
179 /// The bound to claim that an array of unknown bound has.
180 /// The value in MostDerivedArraySize is undefined in this case. So, set it
181 /// to an arbitrary value that's likely to loudly break things if it's used.
182 static const uint64_t AssumedSizeForUnsizedArray =
183 std::numeric_limits<uint64_t>::max() / 2;
184
185 /// Determines if an LValue with the given LValueBase will have an unsized
186 /// array in its designator.
187 /// Find the path length and type of the most-derived subobject in the given
188 /// path, and find the size of the containing array, if any.
189 static unsigned
190 findMostDerivedSubobject(const ASTContext &Ctx, APValue::LValueBase Base,
192 uint64_t &ArraySize, QualType &Type, bool &IsArray,
193 bool &FirstEntryIsUnsizedArray) {
194 // This only accepts LValueBases from APValues, and APValues don't support
195 // arrays that lack size info.
196 assert(!isBaseAnAllocSizeCall(Base) &&
197 "Unsized arrays shouldn't appear here");
198 unsigned MostDerivedLength = 0;
199 // The type of Base is a reference type if the base is a constexpr-unknown
200 // variable. In that case, look through the reference type.
201 Type = getType(Base).getNonReferenceType();
202
203 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
204 if (Type->isArrayType()) {
205 const ArrayType *AT = Ctx.getAsArrayType(Type);
206 Type = AT->getElementType();
207 MostDerivedLength = I + 1;
208 IsArray = true;
209
210 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
211 ArraySize = CAT->getZExtSize();
212 } else {
213 assert(I == 0 && "unexpected unsized array designator");
214 FirstEntryIsUnsizedArray = true;
215 ArraySize = AssumedSizeForUnsizedArray;
216 }
217 } else if (Type->isAnyComplexType()) {
218 const ComplexType *CT = Type->castAs<ComplexType>();
219 Type = CT->getElementType();
220 ArraySize = 2;
221 MostDerivedLength = I + 1;
222 IsArray = true;
223 } else if (const auto *VT = Type->getAs<VectorType>()) {
224 Type = VT->getElementType();
225 ArraySize = VT->getNumElements();
226 MostDerivedLength = I + 1;
227 IsArray = true;
228 } else if (const FieldDecl *FD = getAsField(Path[I])) {
229 Type = FD->getType();
230 ArraySize = 0;
231 MostDerivedLength = I + 1;
232 IsArray = false;
233 } else {
234 // Path[I] describes a base class.
235 ArraySize = 0;
236 IsArray = false;
237 }
238 }
239 return MostDerivedLength;
240 }
241
242 /// A path from a glvalue to a subobject of that glvalue.
243 struct SubobjectDesignator {
244 /// True if the subobject was named in a manner not supported by C++11. Such
245 /// lvalues can still be folded, but they are not core constant expressions
246 /// and we cannot perform lvalue-to-rvalue conversions on them.
247 LLVM_PREFERRED_TYPE(bool)
248 unsigned Invalid : 1;
249
250 /// Is this a pointer one past the end of an object?
251 LLVM_PREFERRED_TYPE(bool)
252 unsigned IsOnePastTheEnd : 1;
253
254 /// Indicator of whether the first entry is an unsized array.
255 LLVM_PREFERRED_TYPE(bool)
256 unsigned FirstEntryIsAnUnsizedArray : 1;
257
258 /// Indicator of whether the most-derived object is an array element.
259 LLVM_PREFERRED_TYPE(bool)
260 unsigned MostDerivedIsArrayElement : 1;
261
262 /// The length of the path to the most-derived object of which this is a
263 /// subobject.
264 unsigned MostDerivedPathLength : 28;
265
266 /// The size of the array of which the most-derived object is an element.
267 /// This will always be 0 if the most-derived object is not an array
268 /// element. 0 is not an indicator of whether or not the most-derived object
269 /// is an array, however, because 0-length arrays are allowed.
270 ///
271 /// If the current array is an unsized array, the value of this is
272 /// undefined.
273 uint64_t MostDerivedArraySize;
274 /// The type of the most derived object referred to by this address.
275 QualType MostDerivedType;
276
277 typedef APValue::LValuePathEntry PathEntry;
278
279 /// The entries on the path from the glvalue to the designated subobject.
281
282 SubobjectDesignator() : Invalid(true) {}
283
284 explicit SubobjectDesignator(QualType T)
285 : Invalid(false), IsOnePastTheEnd(false),
286 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
287 MostDerivedPathLength(0), MostDerivedArraySize(0),
288 MostDerivedType(T.isNull() ? QualType() : T.getNonReferenceType()) {}
289
290 SubobjectDesignator(const ASTContext &Ctx, const APValue &V)
291 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
292 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
293 MostDerivedPathLength(0), MostDerivedArraySize(0) {
294 assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
295 if (!Invalid) {
296 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
297 llvm::append_range(Entries, V.getLValuePath());
298 if (V.getLValueBase()) {
299 bool IsArray = false;
300 bool FirstIsUnsizedArray = false;
301 MostDerivedPathLength = findMostDerivedSubobject(
302 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
303 MostDerivedType, IsArray, FirstIsUnsizedArray);
304 MostDerivedIsArrayElement = IsArray;
305 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
306 }
307 }
308 }
309
310 void truncate(ASTContext &Ctx, APValue::LValueBase Base,
311 unsigned NewLength) {
312 if (Invalid)
313 return;
314
315 assert(Base && "cannot truncate path for null pointer");
316 assert(NewLength <= Entries.size() && "not a truncation");
317
318 if (NewLength == Entries.size())
319 return;
320 Entries.resize(NewLength);
321
322 bool IsArray = false;
323 bool FirstIsUnsizedArray = false;
324 MostDerivedPathLength = findMostDerivedSubobject(
325 Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray,
326 FirstIsUnsizedArray);
327 MostDerivedIsArrayElement = IsArray;
328 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
329 }
330
331 void setInvalid() {
332 Invalid = true;
333 Entries.clear();
334 }
335
336 /// Determine whether the most derived subobject is an array without a
337 /// known bound.
338 bool isMostDerivedAnUnsizedArray() const {
339 assert(!Invalid && "Calling this makes no sense on invalid designators");
340 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
341 }
342
343 /// Determine what the most derived array's size is. Results in an assertion
344 /// failure if the most derived array lacks a size.
345 uint64_t getMostDerivedArraySize() const {
346 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
347 return MostDerivedArraySize;
348 }
349
350 /// Determine whether this is a one-past-the-end pointer.
351 bool isOnePastTheEnd() const {
352 assert(!Invalid);
353 if (IsOnePastTheEnd)
354 return true;
355 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
356 Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==
357 MostDerivedArraySize)
358 return true;
359 return false;
360 }
361
362 /// Get the range of valid index adjustments in the form
363 /// {maximum value that can be subtracted from this pointer,
364 /// maximum value that can be added to this pointer}
365 std::pair<uint64_t, uint64_t> validIndexAdjustments() {
366 if (Invalid || isMostDerivedAnUnsizedArray())
367 return {0, 0};
368
369 // [expr.add]p4: For the purposes of these operators, a pointer to a
370 // nonarray object behaves the same as a pointer to the first element of
371 // an array of length one with the type of the object as its element type.
372 bool IsArray = MostDerivedPathLength == Entries.size() &&
373 MostDerivedIsArrayElement;
374 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
375 : (uint64_t)IsOnePastTheEnd;
376 uint64_t ArraySize =
377 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
378 return {ArrayIndex, ArraySize - ArrayIndex};
379 }
380
381 /// Check that this refers to a valid subobject.
382 bool isValidSubobject() const {
383 if (Invalid)
384 return false;
385 return !isOnePastTheEnd();
386 }
387 /// Check that this refers to a valid subobject, and if not, produce a
388 /// relevant diagnostic and set the designator as invalid.
389 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
390
391 /// Get the type of the designated object.
392 QualType getType(ASTContext &Ctx) const {
393 assert(!Invalid && "invalid designator has no subobject type");
394 return MostDerivedPathLength == Entries.size()
395 ? MostDerivedType
396 : Ctx.getCanonicalTagType(getAsBaseClass(Entries.back()));
397 }
398
399 /// Update this designator to refer to the first element within this array.
400 void addArrayUnchecked(const ConstantArrayType *CAT) {
401 Entries.push_back(PathEntry::ArrayIndex(0));
402
403 // This is a most-derived object.
404 MostDerivedType = CAT->getElementType();
405 MostDerivedIsArrayElement = true;
406 MostDerivedArraySize = CAT->getZExtSize();
407 MostDerivedPathLength = Entries.size();
408 }
409 /// Update this designator to refer to the first element within the array of
410 /// elements of type T. This is an array of unknown size.
411 void addUnsizedArrayUnchecked(QualType ElemTy) {
412 Entries.push_back(PathEntry::ArrayIndex(0));
413
414 MostDerivedType = ElemTy;
415 MostDerivedIsArrayElement = true;
416 // The value in MostDerivedArraySize is undefined in this case. So, set it
417 // to an arbitrary value that's likely to loudly break things if it's
418 // used.
419 MostDerivedArraySize = AssumedSizeForUnsizedArray;
420 MostDerivedPathLength = Entries.size();
421 }
422 /// Update this designator to refer to the given base or member of this
423 /// object.
424 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
425 Entries.push_back(APValue::BaseOrMemberType(D, Virtual));
426
427 // If this isn't a base class, it's a new most-derived object.
428 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
429 MostDerivedType = FD->getType();
430 MostDerivedIsArrayElement = false;
431 MostDerivedArraySize = 0;
432 MostDerivedPathLength = Entries.size();
433 }
434 }
435 /// Update this designator to refer to the given complex component.
436 void addComplexUnchecked(QualType EltTy, bool Imag) {
437 Entries.push_back(PathEntry::ArrayIndex(Imag));
438
439 // This is technically a most-derived object, though in practice this
440 // is unlikely to matter.
441 MostDerivedType = EltTy;
442 MostDerivedIsArrayElement = true;
443 MostDerivedArraySize = 2;
444 MostDerivedPathLength = Entries.size();
445 }
446
447 void addVectorElementUnchecked(QualType EltTy, uint64_t Size,
448 uint64_t Idx) {
449 Entries.push_back(PathEntry::ArrayIndex(Idx));
450 MostDerivedType = EltTy;
451 MostDerivedPathLength = Entries.size();
452 MostDerivedArraySize = 0;
453 MostDerivedIsArrayElement = false;
454 }
455
456 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
457 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
458 const APSInt &N);
459 /// Add N to the address of this subobject.
460 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N, const LValue &LV);
461 };
462
463 /// A scope at the end of which an object can need to be destroyed.
464 enum class ScopeKind {
465 Block,
466 FullExpression,
467 Call
468 };
469
470 /// A reference to a particular call and its arguments.
471 struct CallRef {
472 CallRef() : OrigCallee(), CallIndex(0), Version() {}
473 CallRef(const FunctionDecl *Callee, unsigned CallIndex, unsigned Version)
474 : OrigCallee(Callee), CallIndex(CallIndex), Version(Version) {}
475
476 explicit operator bool() const { return OrigCallee; }
477
478 /// Get the parameter that the caller initialized, corresponding to the
479 /// given parameter in the callee.
480 const ParmVarDecl *getOrigParam(const ParmVarDecl *PVD) const {
481 return OrigCallee ? OrigCallee->getParamDecl(PVD->getFunctionScopeIndex())
482 : PVD;
483 }
484
485 /// The callee at the point where the arguments were evaluated. This might
486 /// be different from the actual callee (a different redeclaration, or a
487 /// virtual override), but this function's parameters are the ones that
488 /// appear in the parameter map.
489 const FunctionDecl *OrigCallee;
490 /// The call index of the frame that holds the argument values.
491 unsigned CallIndex;
492 /// The version of the parameters corresponding to this call.
493 unsigned Version;
494 };
495
496 /// A stack frame in the constexpr call stack.
497 class CallStackFrame : public interp::Frame {
498 public:
499 EvalInfo &Info;
500
501 /// Parent - The caller of this stack frame.
502 CallStackFrame *Caller;
503
504 /// Callee - The function which was called.
505 const FunctionDecl *Callee;
506
507 /// This - The binding for the this pointer in this call, if any.
508 const LValue *This;
509
510 /// CallExpr - The syntactical structure of member function calls
511 const Expr *CallExpr;
512
513 /// Information on how to find the arguments to this call. Our arguments
514 /// are stored in our parent's CallStackFrame, using the ParmVarDecl* as a
515 /// key and this value as the version.
516 CallRef Arguments;
517
518 /// Source location information about the default argument or default
519 /// initializer expression we're evaluating, if any.
520 CurrentSourceLocExprScope CurSourceLocExprScope;
521
522 // Note that we intentionally use std::map here so that references to
523 // values are stable.
524 typedef std::pair<const void *, unsigned> MapKeyTy;
525 typedef std::map<MapKeyTy, APValue> MapTy;
526 /// Temporaries - Temporary lvalues materialized within this stack frame.
527 MapTy Temporaries;
528
529 /// CallRange - The source range of the call expression for this call.
530 SourceRange CallRange;
531
532 /// Index - The call index of this call.
533 unsigned Index;
534
535 /// The stack of integers for tracking version numbers for temporaries.
536 SmallVector<unsigned, 2> TempVersionStack = {1};
537 unsigned CurTempVersion = TempVersionStack.back();
538
539 unsigned getTempVersion() const { return TempVersionStack.back(); }
540
541 void pushTempVersion() {
542 TempVersionStack.push_back(++CurTempVersion);
543 }
544
545 void popTempVersion() {
546 TempVersionStack.pop_back();
547 }
548
549 CallRef createCall(const FunctionDecl *Callee) {
550 return {Callee, Index, ++CurTempVersion};
551 }
552
553 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
554 // on the overall stack usage of deeply-recursing constexpr evaluations.
555 // (We should cache this map rather than recomputing it repeatedly.)
556 // But let's try this and see how it goes; we can look into caching the map
557 // as a later change.
558
559 /// LambdaCaptureFields - Mapping from captured variables/this to
560 /// corresponding data members in the closure class.
561 llvm::DenseMap<const ValueDecl *, FieldDecl *> LambdaCaptureFields;
562 FieldDecl *LambdaThisCaptureField = nullptr;
563
564 CallStackFrame(EvalInfo &Info, SourceRange CallRange,
565 const FunctionDecl *Callee, const LValue *This,
566 const Expr *CallExpr, CallRef Arguments);
567 ~CallStackFrame();
568
569 // Return the temporary for Key whose version number is Version.
570 APValue *getTemporary(const void *Key, unsigned Version) {
571 MapKeyTy KV(Key, Version);
572 auto LB = Temporaries.lower_bound(KV);
573 if (LB != Temporaries.end() && LB->first == KV)
574 return &LB->second;
575 return nullptr;
576 }
577
578 // Return the current temporary for Key in the map.
579 APValue *getCurrentTemporary(const void *Key) {
580 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
581 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
582 return &std::prev(UB)->second;
583 return nullptr;
584 }
585
586 // Return the version number of the current temporary for Key.
587 unsigned getCurrentTemporaryVersion(const void *Key) const {
588 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
589 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
590 return std::prev(UB)->first.second;
591 return 0;
592 }
593
594 /// Allocate storage for an object of type T in this stack frame.
595 /// Populates LV with a handle to the created object. Key identifies
596 /// the temporary within the stack frame, and must not be reused without
597 /// bumping the temporary version number.
598 template<typename KeyT>
599 APValue &createTemporary(const KeyT *Key, QualType T,
600 ScopeKind Scope, LValue &LV);
601
602 /// Allocate storage for a parameter of a function call made in this frame.
603 APValue &createParam(CallRef Args, const ParmVarDecl *PVD, LValue &LV);
604
605 void describe(llvm::raw_ostream &OS) const override;
606
607 Frame *getCaller() const override { return Caller; }
608 SourceRange getCallRange() const override { return CallRange; }
609 const FunctionDecl *getCallee() const override { return Callee; }
610
611 bool isStdFunction() const {
612 for (const DeclContext *DC = Callee; DC; DC = DC->getParent())
613 if (DC->isStdNamespace())
614 return true;
615 return false;
616 }
617
618 /// Whether we're in a context where [[msvc::constexpr]] evaluation is
619 /// permitted. See MSConstexprDocs for description of permitted contexts.
620 bool CanEvalMSConstexpr = false;
621
622 private:
623 APValue &createLocal(APValue::LValueBase Base, const void *Key, QualType T,
624 ScopeKind Scope);
625 };
626
627 /// Temporarily override 'this'.
628 class ThisOverrideRAII {
629 public:
630 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
631 : Frame(Frame), OldThis(Frame.This) {
632 if (Enable)
633 Frame.This = NewThis;
634 }
635 ~ThisOverrideRAII() {
636 Frame.This = OldThis;
637 }
638 private:
639 CallStackFrame &Frame;
640 const LValue *OldThis;
641 };
642
643 // A shorthand time trace scope struct, prints source range, for example
644 // {"name":"EvaluateAsRValue","args":{"detail":"<test.cc:8:21, col:25>"}}}
645 class ExprTimeTraceScope {
646 public:
647 ExprTimeTraceScope(const Expr *E, const ASTContext &Ctx, StringRef Name)
648 : TimeScope(Name, [E, &Ctx] {
650 }) {}
651
652 private:
653 llvm::TimeTraceScope TimeScope;
654 };
655
656 /// RAII object used to change the current ability of
657 /// [[msvc::constexpr]] evaulation.
658 struct MSConstexprContextRAII {
659 CallStackFrame &Frame;
660 bool OldValue;
661 explicit MSConstexprContextRAII(CallStackFrame &Frame, bool Value)
662 : Frame(Frame), OldValue(Frame.CanEvalMSConstexpr) {
663 Frame.CanEvalMSConstexpr = Value;
664 }
665
666 ~MSConstexprContextRAII() { Frame.CanEvalMSConstexpr = OldValue; }
667 };
668}
669
670static bool HandleDestruction(EvalInfo &Info, const Expr *E,
671 const LValue &This, QualType ThisType);
672static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
674 QualType T);
675
676namespace {
677 /// A cleanup, and a flag indicating whether it is lifetime-extended.
678 class Cleanup {
679 llvm::PointerIntPair<APValue*, 2, ScopeKind> Value;
680 APValue::LValueBase Base;
681 QualType T;
682
683 public:
684 Cleanup(APValue *Val, APValue::LValueBase Base, QualType T,
685 ScopeKind Scope)
686 : Value(Val, Scope), Base(Base), T(T) {}
687
688 /// Determine whether this cleanup should be performed at the end of the
689 /// given kind of scope.
690 bool isDestroyedAtEndOf(ScopeKind K) const {
691 return (int)Value.getInt() >= (int)K;
692 }
693 bool endLifetime(EvalInfo &Info, bool RunDestructors) {
694 if (RunDestructors) {
695 SourceLocation Loc;
696 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>())
697 Loc = VD->getLocation();
698 else if (const Expr *E = Base.dyn_cast<const Expr*>())
699 Loc = E->getExprLoc();
700 return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T);
701 }
702 *Value.getPointer() = APValue();
703 return true;
704 }
705
706 bool hasSideEffect() {
707 return T.isDestructedType();
708 }
709 };
710
711 /// A reference to an object whose construction we are currently evaluating.
712 struct ObjectUnderConstruction {
713 APValue::LValueBase Base;
714 ArrayRef<APValue::LValuePathEntry> Path;
715 friend bool operator==(const ObjectUnderConstruction &LHS,
716 const ObjectUnderConstruction &RHS) {
717 return LHS.Base == RHS.Base && LHS.Path == RHS.Path;
718 }
719 friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {
720 return llvm::hash_combine(Obj.Base, Obj.Path);
721 }
722 };
723 enum class ConstructionPhase {
724 None,
725 Bases,
726 AfterBases,
727 AfterFields,
728 Destroying,
729 DestroyingBases
730 };
731}
732
733namespace llvm {
734template<> struct DenseMapInfo<ObjectUnderConstruction> {
735 using Base = DenseMapInfo<APValue::LValueBase>;
736 static ObjectUnderConstruction getEmptyKey() {
737 return {Base::getEmptyKey(), {}}; }
738 static ObjectUnderConstruction getTombstoneKey() {
739 return {Base::getTombstoneKey(), {}};
740 }
741 static unsigned getHashValue(const ObjectUnderConstruction &Object) {
742 return hash_value(Object);
743 }
744 static bool isEqual(const ObjectUnderConstruction &LHS,
745 const ObjectUnderConstruction &RHS) {
746 return LHS == RHS;
747 }
748};
749}
750
751namespace {
752 /// A dynamically-allocated heap object.
753 struct DynAlloc {
754 /// The value of this heap-allocated object.
755 APValue Value;
756 /// The allocating expression; used for diagnostics. Either a CXXNewExpr
757 /// or a CallExpr (the latter is for direct calls to operator new inside
758 /// std::allocator<T>::allocate).
759 const Expr *AllocExpr = nullptr;
760
761 enum Kind {
762 New,
763 ArrayNew,
764 StdAllocator
765 };
766
767 /// Get the kind of the allocation. This must match between allocation
768 /// and deallocation.
769 Kind getKind() const {
770 if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr))
771 return NE->isArray() ? ArrayNew : New;
772 assert(isa<CallExpr>(AllocExpr));
773 return StdAllocator;
774 }
775 };
776
777 struct DynAllocOrder {
778 bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const {
779 return L.getIndex() < R.getIndex();
780 }
781 };
782
783 /// EvalInfo - This is a private struct used by the evaluator to capture
784 /// information about a subexpression as it is folded. It retains information
785 /// about the AST context, but also maintains information about the folded
786 /// expression.
787 ///
788 /// If an expression could be evaluated, it is still possible it is not a C
789 /// "integer constant expression" or constant expression. If not, this struct
790 /// captures information about how and why not.
791 ///
792 /// One bit of information passed *into* the request for constant folding
793 /// indicates whether the subexpression is "evaluated" or not according to C
794 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
795 /// evaluate the expression regardless of what the RHS is, but C only allows
796 /// certain things in certain situations.
797 class EvalInfo final : public interp::State {
798 public:
799 /// CurrentCall - The top of the constexpr call stack.
800 CallStackFrame *CurrentCall;
801
802 /// CallStackDepth - The number of calls in the call stack right now.
803 unsigned CallStackDepth;
804
805 /// NextCallIndex - The next call index to assign.
806 unsigned NextCallIndex;
807
808 /// StepsLeft - The remaining number of evaluation steps we're permitted
809 /// to perform. This is essentially a limit for the number of statements
810 /// we will evaluate.
811 unsigned StepsLeft;
812
813 /// Enable the experimental new constant interpreter. If an expression is
814 /// not supported by the interpreter, an error is triggered.
815 bool EnableNewConstInterp;
816
817 /// BottomFrame - The frame in which evaluation started. This must be
818 /// initialized after CurrentCall and CallStackDepth.
819 CallStackFrame BottomFrame;
820
821 /// A stack of values whose lifetimes end at the end of some surrounding
822 /// evaluation frame.
823 llvm::SmallVector<Cleanup, 16> CleanupStack;
824
825 /// EvaluatingDecl - This is the declaration whose initializer is being
826 /// evaluated, if any.
827 APValue::LValueBase EvaluatingDecl;
828
829 enum class EvaluatingDeclKind {
830 None,
831 /// We're evaluating the construction of EvaluatingDecl.
832 Ctor,
833 /// We're evaluating the destruction of EvaluatingDecl.
834 Dtor,
835 };
836 EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None;
837
838 /// EvaluatingDeclValue - This is the value being constructed for the
839 /// declaration whose initializer is being evaluated, if any.
840 APValue *EvaluatingDeclValue;
841
842 /// Stack of loops and 'switch' statements which we're currently
843 /// breaking/continuing; null entries are used to mark unlabeled
844 /// break/continue.
845 SmallVector<const Stmt *> BreakContinueStack;
846
847 /// Set of objects that are currently being constructed.
848 llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
849 ObjectsUnderConstruction;
850
851 /// Current heap allocations, along with the location where each was
852 /// allocated. We use std::map here because we need stable addresses
853 /// for the stored APValues.
854 std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs;
855
856 /// The number of heap allocations performed so far in this evaluation.
857 unsigned NumHeapAllocs = 0;
858
859 struct EvaluatingConstructorRAII {
860 EvalInfo &EI;
861 ObjectUnderConstruction Object;
862 bool DidInsert;
863 EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
864 bool HasBases)
865 : EI(EI), Object(Object) {
866 DidInsert =
867 EI.ObjectsUnderConstruction
868 .insert({Object, HasBases ? ConstructionPhase::Bases
869 : ConstructionPhase::AfterBases})
870 .second;
871 }
872 void finishedConstructingBases() {
873 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
874 }
875 void finishedConstructingFields() {
876 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields;
877 }
878 ~EvaluatingConstructorRAII() {
879 if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
880 }
881 };
882
883 struct EvaluatingDestructorRAII {
884 EvalInfo &EI;
885 ObjectUnderConstruction Object;
886 bool DidInsert;
887 EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object)
888 : EI(EI), Object(Object) {
889 DidInsert = EI.ObjectsUnderConstruction
890 .insert({Object, ConstructionPhase::Destroying})
891 .second;
892 }
893 void startedDestroyingBases() {
894 EI.ObjectsUnderConstruction[Object] =
895 ConstructionPhase::DestroyingBases;
896 }
897 ~EvaluatingDestructorRAII() {
898 if (DidInsert)
899 EI.ObjectsUnderConstruction.erase(Object);
900 }
901 };
902
903 ConstructionPhase
904 isEvaluatingCtorDtor(APValue::LValueBase Base,
905 ArrayRef<APValue::LValuePathEntry> Path) {
906 return ObjectsUnderConstruction.lookup({Base, Path});
907 }
908
909 /// If we're currently speculatively evaluating, the outermost call stack
910 /// depth at which we can mutate state, otherwise 0.
911 unsigned SpeculativeEvaluationDepth = 0;
912
913 /// The current array initialization index, if we're performing array
914 /// initialization.
915 uint64_t ArrayInitIndex = -1;
916
917 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
918 : State(const_cast<ASTContext &>(C), S), CurrentCall(nullptr),
919 CallStackDepth(0), NextCallIndex(1),
920 StepsLeft(C.getLangOpts().ConstexprStepLimit),
921 EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp),
922 BottomFrame(*this, SourceLocation(), /*Callee=*/nullptr,
923 /*This=*/nullptr,
924 /*CallExpr=*/nullptr, CallRef()),
925 EvaluatingDecl((const ValueDecl *)nullptr),
926 EvaluatingDeclValue(nullptr) {
927 EvalMode = Mode;
928 }
929
930 ~EvalInfo() {
931 discardCleanups();
932 }
933
934 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value,
935 EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) {
936 EvaluatingDecl = Base;
937 IsEvaluatingDecl = EDK;
938 EvaluatingDeclValue = &Value;
939 }
940
941 bool CheckCallLimit(SourceLocation Loc) {
942 // Don't perform any constexpr calls (other than the call we're checking)
943 // when checking a potential constant expression.
944 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
945 return false;
946 if (NextCallIndex == 0) {
947 // NextCallIndex has wrapped around.
948 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
949 return false;
950 }
951 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
952 return true;
953 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
954 << getLangOpts().ConstexprCallDepth;
955 return false;
956 }
957
958 bool CheckArraySize(SourceLocation Loc, unsigned BitWidth,
959 uint64_t ElemCount, bool Diag) {
960 // FIXME: GH63562
961 // APValue stores array extents as unsigned,
962 // so anything that is greater that unsigned would overflow when
963 // constructing the array, we catch this here.
964 if (BitWidth > ConstantArrayType::getMaxSizeBits(Ctx) ||
965 ElemCount > uint64_t(std::numeric_limits<unsigned>::max())) {
966 if (Diag)
967 FFDiag(Loc, diag::note_constexpr_new_too_large) << ElemCount;
968 return false;
969 }
970
971 // FIXME: GH63562
972 // Arrays allocate an APValue per element.
973 // We use the number of constexpr steps as a proxy for the maximum size
974 // of arrays to avoid exhausting the system resources, as initialization
975 // of each element is likely to take some number of steps anyway.
976 uint64_t Limit = getLangOpts().ConstexprStepLimit;
977 if (Limit != 0 && ElemCount > Limit) {
978 if (Diag)
979 FFDiag(Loc, diag::note_constexpr_new_exceeds_limits)
980 << ElemCount << Limit;
981 return false;
982 }
983 return true;
984 }
985
986 std::pair<CallStackFrame *, unsigned>
987 getCallFrameAndDepth(unsigned CallIndex) {
988 assert(CallIndex && "no call index in getCallFrameAndDepth");
989 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
990 // be null in this loop.
991 unsigned Depth = CallStackDepth;
992 CallStackFrame *Frame = CurrentCall;
993 while (Frame->Index > CallIndex) {
994 Frame = Frame->Caller;
995 --Depth;
996 }
997 if (Frame->Index == CallIndex)
998 return {Frame, Depth};
999 return {nullptr, 0};
1000 }
1001
1002 bool nextStep(const Stmt *S) {
1003 if (getLangOpts().ConstexprStepLimit == 0)
1004 return true;
1005
1006 if (!StepsLeft) {
1007 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
1008 return false;
1009 }
1010 --StepsLeft;
1011 return true;
1012 }
1013
1014 APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV);
1015
1016 std::optional<DynAlloc *> lookupDynamicAlloc(DynamicAllocLValue DA) {
1017 std::optional<DynAlloc *> Result;
1018 auto It = HeapAllocs.find(DA);
1019 if (It != HeapAllocs.end())
1020 Result = &It->second;
1021 return Result;
1022 }
1023
1024 /// Get the allocated storage for the given parameter of the given call.
1025 APValue *getParamSlot(CallRef Call, const ParmVarDecl *PVD) {
1026 CallStackFrame *Frame = getCallFrameAndDepth(Call.CallIndex).first;
1027 return Frame ? Frame->getTemporary(Call.getOrigParam(PVD), Call.Version)
1028 : nullptr;
1029 }
1030
1031 /// Information about a stack frame for std::allocator<T>::[de]allocate.
1032 struct StdAllocatorCaller {
1033 unsigned FrameIndex;
1034 QualType ElemType;
1035 const Expr *Call;
1036 explicit operator bool() const { return FrameIndex != 0; };
1037 };
1038
1039 StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const {
1040 for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame;
1041 Call = Call->Caller) {
1042 const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee);
1043 if (!MD)
1044 continue;
1045 const IdentifierInfo *FnII = MD->getIdentifier();
1046 if (!FnII || !FnII->isStr(FnName))
1047 continue;
1048
1049 const auto *CTSD =
1050 dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent());
1051 if (!CTSD)
1052 continue;
1053
1054 const IdentifierInfo *ClassII = CTSD->getIdentifier();
1055 const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
1056 if (CTSD->isInStdNamespace() && ClassII &&
1057 ClassII->isStr("allocator") && TAL.size() >= 1 &&
1058 TAL[0].getKind() == TemplateArgument::Type)
1059 return {Call->Index, TAL[0].getAsType(), Call->CallExpr};
1060 }
1061
1062 return {};
1063 }
1064
1065 void performLifetimeExtension() {
1066 // Disable the cleanups for lifetime-extended temporaries.
1067 llvm::erase_if(CleanupStack, [](Cleanup &C) {
1068 return !C.isDestroyedAtEndOf(ScopeKind::FullExpression);
1069 });
1070 }
1071
1072 /// Throw away any remaining cleanups at the end of evaluation. If any
1073 /// cleanups would have had a side-effect, note that as an unmodeled
1074 /// side-effect and return false. Otherwise, return true.
1075 bool discardCleanups() {
1076 for (Cleanup &C : CleanupStack) {
1077 if (C.hasSideEffect() && !noteSideEffect()) {
1078 CleanupStack.clear();
1079 return false;
1080 }
1081 }
1082 CleanupStack.clear();
1083 return true;
1084 }
1085
1086 private:
1087 const interp::Frame *getCurrentFrame() override { return CurrentCall; }
1088 const interp::Frame *getBottomFrame() const override { return &BottomFrame; }
1089
1090 unsigned getCallStackDepth() override { return CallStackDepth; }
1091 bool stepsLeft() const override { return StepsLeft > 0; }
1092
1093 public:
1094 /// Notes that we failed to evaluate an expression that other expressions
1095 /// directly depend on, and determine if we should keep evaluating. This
1096 /// should only be called if we actually intend to keep evaluating.
1097 ///
1098 /// Call noteSideEffect() instead if we may be able to ignore the value that
1099 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1100 ///
1101 /// (Foo(), 1) // use noteSideEffect
1102 /// (Foo() || true) // use noteSideEffect
1103 /// Foo() + 1 // use noteFailure
1104 [[nodiscard]] bool noteFailure() {
1105 // Failure when evaluating some expression often means there is some
1106 // subexpression whose evaluation was skipped. Therefore, (because we
1107 // don't track whether we skipped an expression when unwinding after an
1108 // evaluation failure) every evaluation failure that bubbles up from a
1109 // subexpression implies that a side-effect has potentially happened. We
1110 // skip setting the HasSideEffects flag to true until we decide to
1111 // continue evaluating after that point, which happens here.
1112 bool KeepGoing = keepEvaluatingAfterFailure();
1113 EvalStatus.HasSideEffects |= KeepGoing;
1114 return KeepGoing;
1115 }
1116
1117 class ArrayInitLoopIndex {
1118 EvalInfo &Info;
1119 uint64_t OuterIndex;
1120
1121 public:
1122 ArrayInitLoopIndex(EvalInfo &Info)
1123 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1124 Info.ArrayInitIndex = 0;
1125 }
1126 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1127
1128 operator uint64_t&() { return Info.ArrayInitIndex; }
1129 };
1130 };
1131
1132 /// Object used to treat all foldable expressions as constant expressions.
1133 struct FoldConstant {
1134 EvalInfo &Info;
1135 bool Enabled;
1136 bool HadNoPriorDiags;
1137 EvaluationMode OldMode;
1138
1139 explicit FoldConstant(EvalInfo &Info, bool Enabled)
1140 : Info(Info),
1141 Enabled(Enabled),
1142 HadNoPriorDiags(Info.EvalStatus.Diag &&
1143 Info.EvalStatus.Diag->empty() &&
1144 !Info.EvalStatus.HasSideEffects),
1145 OldMode(Info.EvalMode) {
1146 if (Enabled)
1147 Info.EvalMode = EvaluationMode::ConstantFold;
1148 }
1149 void keepDiagnostics() { Enabled = false; }
1150 ~FoldConstant() {
1151 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
1152 !Info.EvalStatus.HasSideEffects)
1153 Info.EvalStatus.Diag->clear();
1154 Info.EvalMode = OldMode;
1155 }
1156 };
1157
1158 /// RAII object used to set the current evaluation mode to ignore
1159 /// side-effects.
1160 struct IgnoreSideEffectsRAII {
1161 EvalInfo &Info;
1162 EvaluationMode OldMode;
1163 explicit IgnoreSideEffectsRAII(EvalInfo &Info)
1164 : Info(Info), OldMode(Info.EvalMode) {
1165 Info.EvalMode = EvaluationMode::IgnoreSideEffects;
1166 }
1167
1168 ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
1169 };
1170
1171 /// RAII object used to optionally suppress diagnostics and side-effects from
1172 /// a speculative evaluation.
1173 class SpeculativeEvaluationRAII {
1174 EvalInfo *Info = nullptr;
1175 Expr::EvalStatus OldStatus;
1176 unsigned OldSpeculativeEvaluationDepth = 0;
1177
1178 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1179 Info = Other.Info;
1180 OldStatus = Other.OldStatus;
1181 OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
1182 Other.Info = nullptr;
1183 }
1184
1185 void maybeRestoreState() {
1186 if (!Info)
1187 return;
1188
1189 Info->EvalStatus = OldStatus;
1190 Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
1191 }
1192
1193 public:
1194 SpeculativeEvaluationRAII() = default;
1195
1196 SpeculativeEvaluationRAII(
1197 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1198 : Info(&Info), OldStatus(Info.EvalStatus),
1199 OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
1200 Info.EvalStatus.Diag = NewDiag;
1201 Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
1202 }
1203
1204 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1205 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1206 moveFromAndCancel(std::move(Other));
1207 }
1208
1209 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1210 maybeRestoreState();
1211 moveFromAndCancel(std::move(Other));
1212 return *this;
1213 }
1214
1215 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1216 };
1217
1218 /// RAII object wrapping a full-expression or block scope, and handling
1219 /// the ending of the lifetime of temporaries created within it.
1220 template<ScopeKind Kind>
1221 class ScopeRAII {
1222 EvalInfo &Info;
1223 unsigned OldStackSize;
1224 public:
1225 ScopeRAII(EvalInfo &Info)
1226 : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1227 // Push a new temporary version. This is needed to distinguish between
1228 // temporaries created in different iterations of a loop.
1229 Info.CurrentCall->pushTempVersion();
1230 }
1231 bool destroy(bool RunDestructors = true) {
1232 bool OK = cleanup(Info, RunDestructors, OldStackSize);
1233 OldStackSize = std::numeric_limits<unsigned>::max();
1234 return OK;
1235 }
1236 ~ScopeRAII() {
1237 if (OldStackSize != std::numeric_limits<unsigned>::max())
1238 destroy(false);
1239 // Body moved to a static method to encourage the compiler to inline away
1240 // instances of this class.
1241 Info.CurrentCall->popTempVersion();
1242 }
1243 private:
1244 static bool cleanup(EvalInfo &Info, bool RunDestructors,
1245 unsigned OldStackSize) {
1246 assert(OldStackSize <= Info.CleanupStack.size() &&
1247 "running cleanups out of order?");
1248
1249 // Run all cleanups for a block scope, and non-lifetime-extended cleanups
1250 // for a full-expression scope.
1251 bool Success = true;
1252 for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) {
1253 if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) {
1254 if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) {
1255 Success = false;
1256 break;
1257 }
1258 }
1259 }
1260
1261 // Compact any retained cleanups.
1262 auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
1263 if (Kind != ScopeKind::Block)
1264 NewEnd =
1265 std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) {
1266 return C.isDestroyedAtEndOf(Kind);
1267 });
1268 Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
1269 return Success;
1270 }
1271 };
1272 typedef ScopeRAII<ScopeKind::Block> BlockScopeRAII;
1273 typedef ScopeRAII<ScopeKind::FullExpression> FullExpressionRAII;
1274 typedef ScopeRAII<ScopeKind::Call> CallScopeRAII;
1275}
1276
1277bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1278 CheckSubobjectKind CSK) {
1279 if (Invalid)
1280 return false;
1281 if (isOnePastTheEnd()) {
1282 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1283 << CSK;
1284 setInvalid();
1285 return false;
1286 }
1287 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1288 // must actually be at least one array element; even a VLA cannot have a
1289 // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1290 return true;
1291}
1292
1293void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1294 const Expr *E) {
1295 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1296 // Do not set the designator as invalid: we can represent this situation,
1297 // and correct handling of __builtin_object_size requires us to do so.
1298}
1299
1300void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1301 const Expr *E,
1302 const APSInt &N) {
1303 // If we're complaining, we must be able to statically determine the size of
1304 // the most derived array.
1305 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1306 Info.CCEDiag(E, diag::note_constexpr_array_index)
1307 << N << /*array*/ 0
1308 << static_cast<unsigned>(getMostDerivedArraySize());
1309 else
1310 Info.CCEDiag(E, diag::note_constexpr_array_index)
1311 << N << /*non-array*/ 1;
1312 setInvalid();
1313}
1314
1315CallStackFrame::CallStackFrame(EvalInfo &Info, SourceRange CallRange,
1316 const FunctionDecl *Callee, const LValue *This,
1317 const Expr *CallExpr, CallRef Call)
1318 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1319 CallExpr(CallExpr), Arguments(Call), CallRange(CallRange),
1320 Index(Info.NextCallIndex++) {
1321 Info.CurrentCall = this;
1322 ++Info.CallStackDepth;
1323}
1324
1325CallStackFrame::~CallStackFrame() {
1326 assert(Info.CurrentCall == this && "calls retired out of order");
1327 --Info.CallStackDepth;
1328 Info.CurrentCall = Caller;
1329}
1330
1331static bool isRead(AccessKinds AK) {
1332 return AK == AK_Read || AK == AK_ReadObjectRepresentation ||
1333 AK == AK_IsWithinLifetime || AK == AK_Dereference;
1334}
1335
1337 switch (AK) {
1338 case AK_Read:
1340 case AK_MemberCall:
1341 case AK_DynamicCast:
1342 case AK_TypeId:
1344 case AK_Dereference:
1345 return false;
1346 case AK_Assign:
1347 case AK_Increment:
1348 case AK_Decrement:
1349 case AK_Construct:
1350 case AK_Destroy:
1351 return true;
1352 }
1353 llvm_unreachable("unknown access kind");
1354}
1355
1356static bool isAnyAccess(AccessKinds AK) {
1357 return isRead(AK) || isModification(AK);
1358}
1359
1360/// Is this an access per the C++ definition?
1362 return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy &&
1363 AK != AK_IsWithinLifetime && AK != AK_Dereference;
1364}
1365
1366/// Is this kind of access valid on an indeterminate object value?
1368 switch (AK) {
1369 case AK_Read:
1370 case AK_Increment:
1371 case AK_Decrement:
1372 case AK_Dereference:
1373 // These need the object's value.
1374 return false;
1375
1378 case AK_Assign:
1379 case AK_Construct:
1380 case AK_Destroy:
1381 // Construction and destruction don't need the value.
1382 return true;
1383
1384 case AK_MemberCall:
1385 case AK_DynamicCast:
1386 case AK_TypeId:
1387 // These aren't really meaningful on scalars.
1388 return true;
1389 }
1390 llvm_unreachable("unknown access kind");
1391}
1392
1393namespace {
1394 struct ComplexValue {
1395 private:
1396 bool IsInt;
1397
1398 public:
1399 APSInt IntReal, IntImag;
1400 APFloat FloatReal, FloatImag;
1401
1402 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1403
1404 void makeComplexFloat() { IsInt = false; }
1405 bool isComplexFloat() const { return !IsInt; }
1406 APFloat &getComplexFloatReal() { return FloatReal; }
1407 APFloat &getComplexFloatImag() { return FloatImag; }
1408
1409 void makeComplexInt() { IsInt = true; }
1410 bool isComplexInt() const { return IsInt; }
1411 APSInt &getComplexIntReal() { return IntReal; }
1412 APSInt &getComplexIntImag() { return IntImag; }
1413
1414 void moveInto(APValue &v) const {
1415 if (isComplexFloat())
1416 v = APValue(FloatReal, FloatImag);
1417 else
1418 v = APValue(IntReal, IntImag);
1419 }
1420 void setFrom(const APValue &v) {
1421 assert(v.isComplexFloat() || v.isComplexInt());
1422 if (v.isComplexFloat()) {
1423 makeComplexFloat();
1424 FloatReal = v.getComplexFloatReal();
1425 FloatImag = v.getComplexFloatImag();
1426 } else {
1427 makeComplexInt();
1428 IntReal = v.getComplexIntReal();
1429 IntImag = v.getComplexIntImag();
1430 }
1431 }
1432 };
1433
1434 struct LValue {
1435 APValue::LValueBase Base;
1436 CharUnits Offset;
1437 SubobjectDesignator Designator;
1438 bool IsNullPtr : 1;
1439 bool InvalidBase : 1;
1440 // P2280R4 track if we have an unknown reference or pointer.
1441 bool AllowConstexprUnknown = false;
1442
1443 const APValue::LValueBase getLValueBase() const { return Base; }
1444 bool allowConstexprUnknown() const { return AllowConstexprUnknown; }
1445 CharUnits &getLValueOffset() { return Offset; }
1446 const CharUnits &getLValueOffset() const { return Offset; }
1447 SubobjectDesignator &getLValueDesignator() { return Designator; }
1448 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1449 bool isNullPointer() const { return IsNullPtr;}
1450
1451 unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1452 unsigned getLValueVersion() const { return Base.getVersion(); }
1453
1454 void moveInto(APValue &V) const {
1455 if (Designator.Invalid)
1456 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
1457 else {
1458 assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1459 V = APValue(Base, Offset, Designator.Entries,
1460 Designator.IsOnePastTheEnd, IsNullPtr);
1461 }
1462 if (AllowConstexprUnknown)
1463 V.setConstexprUnknown();
1464 }
1465 void setFrom(const ASTContext &Ctx, const APValue &V) {
1466 assert(V.isLValue() && "Setting LValue from a non-LValue?");
1467 Base = V.getLValueBase();
1468 Offset = V.getLValueOffset();
1469 InvalidBase = false;
1470 Designator = SubobjectDesignator(Ctx, V);
1471 IsNullPtr = V.isNullPointer();
1472 AllowConstexprUnknown = V.allowConstexprUnknown();
1473 }
1474
1475 void set(APValue::LValueBase B, bool BInvalid = false) {
1476#ifndef NDEBUG
1477 // We only allow a few types of invalid bases. Enforce that here.
1478 if (BInvalid) {
1479 const auto *E = B.get<const Expr *>();
1480 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1481 "Unexpected type of invalid base");
1482 }
1483#endif
1484
1485 Base = B;
1486 Offset = CharUnits::fromQuantity(0);
1487 InvalidBase = BInvalid;
1488 Designator = SubobjectDesignator(getType(B));
1489 IsNullPtr = false;
1490 AllowConstexprUnknown = false;
1491 }
1492
1493 void setNull(ASTContext &Ctx, QualType PointerTy) {
1494 Base = (const ValueDecl *)nullptr;
1495 Offset =
1497 InvalidBase = false;
1498 Designator = SubobjectDesignator(PointerTy->getPointeeType());
1499 IsNullPtr = true;
1500 AllowConstexprUnknown = false;
1501 }
1502
1503 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1504 set(B, true);
1505 }
1506
1507 std::string toString(ASTContext &Ctx, QualType T) const {
1508 APValue Printable;
1509 moveInto(Printable);
1510 return Printable.getAsString(Ctx, T);
1511 }
1512
1513 private:
1514 // Check that this LValue is not based on a null pointer. If it is, produce
1515 // a diagnostic and mark the designator as invalid.
1516 template <typename GenDiagType>
1517 bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
1518 if (Designator.Invalid)
1519 return false;
1520 if (IsNullPtr) {
1521 GenDiag();
1522 Designator.setInvalid();
1523 return false;
1524 }
1525 return true;
1526 }
1527
1528 public:
1529 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1530 CheckSubobjectKind CSK) {
1531 return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1532 Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1533 });
1534 }
1535
1536 bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1537 AccessKinds AK) {
1538 return checkNullPointerDiagnosingWith([&Info, E, AK] {
1539 if (AK == AccessKinds::AK_Dereference)
1540 Info.FFDiag(E, diag::note_constexpr_dereferencing_null);
1541 else
1542 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1543 });
1544 }
1545
1546 // Check this LValue refers to an object. If not, set the designator to be
1547 // invalid and emit a diagnostic.
1548 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1549 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1550 Designator.checkSubobject(Info, E, CSK);
1551 }
1552
1553 void addDecl(EvalInfo &Info, const Expr *E,
1554 const Decl *D, bool Virtual = false) {
1555 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1556 Designator.addDeclUnchecked(D, Virtual);
1557 }
1558 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1559 if (!Designator.Entries.empty()) {
1560 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1561 Designator.setInvalid();
1562 return;
1563 }
1564 if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1565 assert(getType(Base).getNonReferenceType()->isPointerType() ||
1566 getType(Base).getNonReferenceType()->isArrayType());
1567 Designator.FirstEntryIsAnUnsizedArray = true;
1568 Designator.addUnsizedArrayUnchecked(ElemTy);
1569 }
1570 }
1571 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1572 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1573 Designator.addArrayUnchecked(CAT);
1574 }
1575 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1576 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1577 Designator.addComplexUnchecked(EltTy, Imag);
1578 }
1579 void addVectorElement(EvalInfo &Info, const Expr *E, QualType EltTy,
1580 uint64_t Size, uint64_t Idx) {
1581 if (checkSubobject(Info, E, CSK_VectorElement))
1582 Designator.addVectorElementUnchecked(EltTy, Size, Idx);
1583 }
1584 void clearIsNullPointer() {
1585 IsNullPtr = false;
1586 }
1587 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1588 const APSInt &Index, CharUnits ElementSize) {
1589 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1590 // but we're not required to diagnose it and it's valid in C++.)
1591 if (!Index)
1592 return;
1593
1594 // Compute the new offset in the appropriate width, wrapping at 64 bits.
1595 // FIXME: When compiling for a 32-bit target, we should use 32-bit
1596 // offsets.
1597 uint64_t Offset64 = Offset.getQuantity();
1598 uint64_t ElemSize64 = ElementSize.getQuantity();
1599 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1600 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1601
1602 if (checkNullPointer(Info, E, CSK_ArrayIndex))
1603 Designator.adjustIndex(Info, E, Index, *this);
1604 clearIsNullPointer();
1605 }
1606 void adjustOffset(CharUnits N) {
1607 Offset += N;
1608 if (N.getQuantity())
1609 clearIsNullPointer();
1610 }
1611 };
1612
1613 struct MemberPtr {
1614 MemberPtr() {}
1615 explicit MemberPtr(const ValueDecl *Decl)
1616 : DeclAndIsDerivedMember(Decl, false) {}
1617
1618 /// The member or (direct or indirect) field referred to by this member
1619 /// pointer, or 0 if this is a null member pointer.
1620 const ValueDecl *getDecl() const {
1621 return DeclAndIsDerivedMember.getPointer();
1622 }
1623 /// Is this actually a member of some type derived from the relevant class?
1624 bool isDerivedMember() const {
1625 return DeclAndIsDerivedMember.getInt();
1626 }
1627 /// Get the class which the declaration actually lives in.
1628 const CXXRecordDecl *getContainingRecord() const {
1629 return cast<CXXRecordDecl>(
1630 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1631 }
1632
1633 void moveInto(APValue &V) const {
1634 V = APValue(getDecl(), isDerivedMember(), Path);
1635 }
1636 void setFrom(const APValue &V) {
1637 assert(V.isMemberPointer());
1638 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1639 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1640 Path.clear();
1641 llvm::append_range(Path, V.getMemberPointerPath());
1642 }
1643
1644 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1645 /// whether the member is a member of some class derived from the class type
1646 /// of the member pointer.
1647 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1648 /// Path - The path of base/derived classes from the member declaration's
1649 /// class (exclusive) to the class type of the member pointer (inclusive).
1650 SmallVector<const CXXRecordDecl*, 4> Path;
1651
1652 /// Perform a cast towards the class of the Decl (either up or down the
1653 /// hierarchy).
1654 bool castBack(const CXXRecordDecl *Class) {
1655 assert(!Path.empty());
1656 const CXXRecordDecl *Expected;
1657 if (Path.size() >= 2)
1658 Expected = Path[Path.size() - 2];
1659 else
1660 Expected = getContainingRecord();
1661 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1662 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1663 // if B does not contain the original member and is not a base or
1664 // derived class of the class containing the original member, the result
1665 // of the cast is undefined.
1666 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1667 // (D::*). We consider that to be a language defect.
1668 return false;
1669 }
1670 Path.pop_back();
1671 return true;
1672 }
1673 /// Perform a base-to-derived member pointer cast.
1674 bool castToDerived(const CXXRecordDecl *Derived) {
1675 if (!getDecl())
1676 return true;
1677 if (!isDerivedMember()) {
1678 Path.push_back(Derived);
1679 return true;
1680 }
1681 if (!castBack(Derived))
1682 return false;
1683 if (Path.empty())
1684 DeclAndIsDerivedMember.setInt(false);
1685 return true;
1686 }
1687 /// Perform a derived-to-base member pointer cast.
1688 bool castToBase(const CXXRecordDecl *Base) {
1689 if (!getDecl())
1690 return true;
1691 if (Path.empty())
1692 DeclAndIsDerivedMember.setInt(true);
1693 if (isDerivedMember()) {
1694 Path.push_back(Base);
1695 return true;
1696 }
1697 return castBack(Base);
1698 }
1699 };
1700
1701 /// Compare two member pointers, which are assumed to be of the same type.
1702 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1703 if (!LHS.getDecl() || !RHS.getDecl())
1704 return !LHS.getDecl() && !RHS.getDecl();
1705 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1706 return false;
1707 return LHS.Path == RHS.Path;
1708 }
1709}
1710
1711void SubobjectDesignator::adjustIndex(EvalInfo &Info, const Expr *E, APSInt N,
1712 const LValue &LV) {
1713 if (Invalid || !N)
1714 return;
1715 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
1716 if (isMostDerivedAnUnsizedArray()) {
1717 diagnoseUnsizedArrayPointerArithmetic(Info, E);
1718 // Can't verify -- trust that the user is doing the right thing (or if
1719 // not, trust that the caller will catch the bad behavior).
1720 // FIXME: Should we reject if this overflows, at least?
1721 Entries.back() =
1722 PathEntry::ArrayIndex(Entries.back().getAsArrayIndex() + TruncatedN);
1723 return;
1724 }
1725
1726 // [expr.add]p4: For the purposes of these operators, a pointer to a
1727 // nonarray object behaves the same as a pointer to the first element of
1728 // an array of length one with the type of the object as its element type.
1729 bool IsArray =
1730 MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement;
1731 uint64_t ArrayIndex =
1732 IsArray ? Entries.back().getAsArrayIndex() : (uint64_t)IsOnePastTheEnd;
1733 uint64_t ArraySize = IsArray ? getMostDerivedArraySize() : (uint64_t)1;
1734
1735 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
1736 if (!Info.checkingPotentialConstantExpression() ||
1737 !LV.AllowConstexprUnknown) {
1738 // Calculate the actual index in a wide enough type, so we can include
1739 // it in the note.
1740 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
1741 (llvm::APInt &)N += ArrayIndex;
1742 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
1743 diagnosePointerArithmetic(Info, E, N);
1744 }
1745 setInvalid();
1746 return;
1747 }
1748
1749 ArrayIndex += TruncatedN;
1750 assert(ArrayIndex <= ArraySize &&
1751 "bounds check succeeded for out-of-bounds index");
1752
1753 if (IsArray)
1754 Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
1755 else
1756 IsOnePastTheEnd = (ArrayIndex != 0);
1757}
1758
1759static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1760static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1761 const LValue &This, const Expr *E,
1762 bool AllowNonLiteralTypes = false);
1763static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1764 bool InvalidBaseOK = false);
1765static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1766 bool InvalidBaseOK = false);
1767static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1768 EvalInfo &Info);
1769static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1770static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1771static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1772 EvalInfo &Info);
1773static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1774static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1775static bool EvaluateMatrix(const Expr *E, APValue &Result, EvalInfo &Info);
1776static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1777 EvalInfo &Info);
1778static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1779static std::optional<uint64_t>
1780EvaluateBuiltinStrLen(const Expr *E, EvalInfo &Info,
1781 std::string *StringResult = nullptr);
1782
1783/// Evaluate an integer or fixed point expression into an APResult.
1784static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1785 EvalInfo &Info);
1786
1787/// Evaluate only a fixed point expression into an APResult.
1788static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1789 EvalInfo &Info);
1790
1791//===----------------------------------------------------------------------===//
1792// Misc utilities
1793//===----------------------------------------------------------------------===//
1794
1795/// Negate an APSInt in place, converting it to a signed form if necessary, and
1796/// preserving its value (by extending by up to one bit as needed).
1797static void negateAsSigned(APSInt &Int) {
1798 if (Int.isUnsigned() || Int.isMinSignedValue()) {
1799 Int = Int.extend(Int.getBitWidth() + 1);
1800 Int.setIsSigned(true);
1801 }
1802 Int = -Int;
1803}
1804
1805template<typename KeyT>
1806APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T,
1807 ScopeKind Scope, LValue &LV) {
1808 unsigned Version = getTempVersion();
1809 APValue::LValueBase Base(Key, Index, Version);
1810 LV.set(Base);
1811 return createLocal(Base, Key, T, Scope);
1812}
1813
1814/// Allocate storage for a parameter of a function call made in this frame.
1815APValue &CallStackFrame::createParam(CallRef Args, const ParmVarDecl *PVD,
1816 LValue &LV) {
1817 assert(Args.CallIndex == Index && "creating parameter in wrong frame");
1818 APValue::LValueBase Base(PVD, Index, Args.Version);
1819 LV.set(Base);
1820 // We always destroy parameters at the end of the call, even if we'd allow
1821 // them to live to the end of the full-expression at runtime, in order to
1822 // give portable results and match other compilers.
1823 return createLocal(Base, PVD, PVD->getType(), ScopeKind::Call);
1824}
1825
1826APValue &CallStackFrame::createLocal(APValue::LValueBase Base, const void *Key,
1827 QualType T, ScopeKind Scope) {
1828 assert(Base.getCallIndex() == Index && "lvalue for wrong frame");
1829 unsigned Version = Base.getVersion();
1830 APValue &Result = Temporaries[MapKeyTy(Key, Version)];
1831 assert(Result.isAbsent() && "local created multiple times");
1832
1833 // If we're creating a local immediately in the operand of a speculative
1834 // evaluation, don't register a cleanup to be run outside the speculative
1835 // evaluation context, since we won't actually be able to initialize this
1836 // object.
1837 if (Index <= Info.SpeculativeEvaluationDepth) {
1838 if (T.isDestructedType())
1839 Info.noteSideEffect();
1840 } else {
1841 Info.CleanupStack.push_back(Cleanup(&Result, Base, T, Scope));
1842 }
1843 return Result;
1844}
1845
1846APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) {
1847 if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) {
1848 FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded);
1849 return nullptr;
1850 }
1851
1852 DynamicAllocLValue DA(NumHeapAllocs++);
1854 auto Result = HeapAllocs.emplace(std::piecewise_construct,
1855 std::forward_as_tuple(DA), std::tuple<>());
1856 assert(Result.second && "reused a heap alloc index?");
1857 Result.first->second.AllocExpr = E;
1858 return &Result.first->second.Value;
1859}
1860
1861/// Produce a string describing the given constexpr call.
1862void CallStackFrame::describe(raw_ostream &Out) const {
1863 bool IsMemberCall = false;
1864 bool ExplicitInstanceParam = false;
1865 clang::PrintingPolicy PrintingPolicy = Info.Ctx.getPrintingPolicy();
1866 PrintingPolicy.SuppressLambdaBody = true;
1867
1868 if (const auto *MD = dyn_cast<CXXMethodDecl>(Callee)) {
1869 IsMemberCall = !isa<CXXConstructorDecl>(MD) && !MD->isStatic();
1870 ExplicitInstanceParam = MD->isExplicitObjectMemberFunction();
1871 }
1872
1873 if (!IsMemberCall)
1874 Callee->getNameForDiagnostic(Out, PrintingPolicy,
1875 /*Qualified=*/false);
1876
1877 if (This && IsMemberCall) {
1878 if (const auto *MCE = dyn_cast_if_present<CXXMemberCallExpr>(CallExpr)) {
1879 const Expr *Object = MCE->getImplicitObjectArgument();
1880 Object->printPretty(Out, /*Helper=*/nullptr, PrintingPolicy,
1881 /*Indentation=*/0);
1882 if (Object->getType()->isPointerType())
1883 Out << "->";
1884 else
1885 Out << ".";
1886 } else if (const auto *OCE =
1887 dyn_cast_if_present<CXXOperatorCallExpr>(CallExpr)) {
1888 OCE->getArg(0)->printPretty(Out, /*Helper=*/nullptr, PrintingPolicy,
1889 /*Indentation=*/0);
1890 Out << ".";
1891 } else {
1892 APValue Val;
1893 This->moveInto(Val);
1894 Val.printPretty(
1895 Out, Info.Ctx,
1896 Info.Ctx.getLValueReferenceType(This->Designator.MostDerivedType));
1897 Out << ".";
1898 }
1899 Callee->getNameForDiagnostic(Out, PrintingPolicy,
1900 /*Qualified=*/false);
1901 }
1902
1903 Out << '(';
1904
1905 llvm::ListSeparator Comma;
1906 for (const ParmVarDecl *Param :
1907 Callee->parameters().slice(ExplicitInstanceParam)) {
1908 Out << Comma;
1909 const APValue *V = Info.getParamSlot(Arguments, Param);
1910 if (V)
1911 V->printPretty(Out, Info.Ctx, Param->getType());
1912 else
1913 Out << "<...>";
1914 }
1915
1916 Out << ')';
1917}
1918
1919/// Evaluate an expression to see if it had side-effects, and discard its
1920/// result.
1921/// \return \c true if the caller should keep evaluating.
1922static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
1923 assert(!E->isValueDependent());
1924 APValue Scratch;
1925 if (!Evaluate(Scratch, Info, E))
1926 // We don't need the value, but we might have skipped a side effect here.
1927 return Info.noteSideEffect();
1928 return true;
1929}
1930
1931/// Should this call expression be treated as forming an opaque constant?
1932static bool IsOpaqueConstantCall(const CallExpr *E) {
1933 unsigned Builtin = E->getBuiltinCallee();
1934 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1935 Builtin == Builtin::BI__builtin___NSStringMakeConstantString ||
1936 Builtin == Builtin::BI__builtin_ptrauth_sign_constant ||
1937 Builtin == Builtin::BI__builtin_function_start);
1938}
1939
1940static bool IsOpaqueConstantCall(const LValue &LVal) {
1941 const auto *BaseExpr =
1942 llvm::dyn_cast_if_present<CallExpr>(LVal.Base.dyn_cast<const Expr *>());
1943 return BaseExpr && IsOpaqueConstantCall(BaseExpr);
1944}
1945
1947 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1948 // constant expression of pointer type that evaluates to...
1949
1950 // ... a null pointer value, or a prvalue core constant expression of type
1951 // std::nullptr_t.
1952 if (!B)
1953 return true;
1954
1955 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1956 // ... the address of an object with static storage duration,
1957 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1958 return VD->hasGlobalStorage();
1960 return true;
1961 // ... the address of a function,
1962 // ... the address of a GUID [MS extension],
1963 // ... the address of an unnamed global constant
1965 }
1966
1967 if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>())
1968 return true;
1969
1970 const Expr *E = B.get<const Expr*>();
1971 switch (E->getStmtClass()) {
1972 default:
1973 return false;
1974 case Expr::CompoundLiteralExprClass: {
1976 return CLE->isFileScope() && CLE->isLValue();
1977 }
1978 case Expr::MaterializeTemporaryExprClass:
1979 // A materialized temporary might have been lifetime-extended to static
1980 // storage duration.
1981 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
1982 // A string literal has static storage duration.
1983 case Expr::StringLiteralClass:
1984 case Expr::PredefinedExprClass:
1985 case Expr::ObjCStringLiteralClass:
1986 case Expr::ObjCEncodeExprClass:
1987 return true;
1988 case Expr::ObjCBoxedExprClass:
1989 case Expr::ObjCArrayLiteralClass:
1990 case Expr::ObjCDictionaryLiteralClass:
1991 return cast<ObjCObjectLiteral>(E)->isExpressibleAsConstantInitializer();
1992 case Expr::CallExprClass:
1994 // For GCC compatibility, &&label has static storage duration.
1995 case Expr::AddrLabelExprClass:
1996 return true;
1997 // A Block literal expression may be used as the initialization value for
1998 // Block variables at global or local static scope.
1999 case Expr::BlockExprClass:
2000 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
2001 // The APValue generated from a __builtin_source_location will be emitted as a
2002 // literal.
2003 case Expr::SourceLocExprClass:
2004 return true;
2005 case Expr::ImplicitValueInitExprClass:
2006 // FIXME:
2007 // We can never form an lvalue with an implicit value initialization as its
2008 // base through expression evaluation, so these only appear in one case: the
2009 // implicit variable declaration we invent when checking whether a constexpr
2010 // constructor can produce a constant expression. We must assume that such
2011 // an expression might be a global lvalue.
2012 return true;
2013 }
2014}
2015
2016static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
2017 return LVal.Base.dyn_cast<const ValueDecl*>();
2018}
2019
2020// Information about an LValueBase that is some kind of string.
2023 StringRef Bytes;
2025};
2026
2027// Gets the lvalue base of LVal as a string.
2028static bool GetLValueBaseAsString(const EvalInfo &Info, const LValue &LVal,
2029 LValueBaseString &AsString) {
2030 const auto *BaseExpr = LVal.Base.dyn_cast<const Expr *>();
2031 if (!BaseExpr)
2032 return false;
2033
2034 // For ObjCEncodeExpr, we need to compute and store the string.
2035 if (const auto *EE = dyn_cast<ObjCEncodeExpr>(BaseExpr)) {
2036 Info.Ctx.getObjCEncodingForType(EE->getEncodedType(),
2037 AsString.ObjCEncodeStorage);
2038 AsString.Bytes = AsString.ObjCEncodeStorage;
2039 AsString.CharWidth = 1;
2040 return true;
2041 }
2042
2043 // Otherwise, we have a StringLiteral.
2044 const auto *Lit = dyn_cast<StringLiteral>(BaseExpr);
2045 if (const auto *PE = dyn_cast<PredefinedExpr>(BaseExpr))
2046 Lit = PE->getFunctionName();
2047
2048 if (!Lit)
2049 return false;
2050
2051 AsString.Bytes = Lit->getBytes();
2052 AsString.CharWidth = Lit->getCharByteWidth();
2053 return true;
2054}
2055
2056// Determine whether two string literals potentially overlap. This will be the
2057// case if they agree on the values of all the bytes on the overlapping region
2058// between them.
2059//
2060// The overlapping region is the portion of the two string literals that must
2061// overlap in memory if the pointers actually point to the same address at
2062// runtime. For example, if LHS is "abcdef" + 3 and RHS is "cdef\0gh" + 1 then
2063// the overlapping region is "cdef\0", which in this case does agree, so the
2064// strings are potentially overlapping. Conversely, for "foobar" + 3 versus
2065// "bazbar" + 3, the overlapping region contains all of both strings, so they
2066// are not potentially overlapping, even though they agree from the given
2067// addresses onwards.
2068//
2069// See open core issue CWG2765 which is discussing the desired rule here.
2070static bool ArePotentiallyOverlappingStringLiterals(const EvalInfo &Info,
2071 const LValue &LHS,
2072 const LValue &RHS) {
2073 LValueBaseString LHSString, RHSString;
2074 if (!GetLValueBaseAsString(Info, LHS, LHSString) ||
2075 !GetLValueBaseAsString(Info, RHS, RHSString))
2076 return false;
2077
2078 // This is the byte offset to the location of the first character of LHS
2079 // within RHS. We don't need to look at the characters of one string that
2080 // would appear before the start of the other string if they were merged.
2081 CharUnits Offset = RHS.Offset - LHS.Offset;
2082 if (Offset.isNegative()) {
2083 if (LHSString.Bytes.size() < (size_t)-Offset.getQuantity())
2084 return false;
2085 LHSString.Bytes = LHSString.Bytes.drop_front(-Offset.getQuantity());
2086 } else {
2087 if (RHSString.Bytes.size() < (size_t)Offset.getQuantity())
2088 return false;
2089 RHSString.Bytes = RHSString.Bytes.drop_front(Offset.getQuantity());
2090 }
2091
2092 bool LHSIsLonger = LHSString.Bytes.size() > RHSString.Bytes.size();
2093 StringRef Longer = LHSIsLonger ? LHSString.Bytes : RHSString.Bytes;
2094 StringRef Shorter = LHSIsLonger ? RHSString.Bytes : LHSString.Bytes;
2095 int ShorterCharWidth = (LHSIsLonger ? RHSString : LHSString).CharWidth;
2096
2097 // The null terminator isn't included in the string data, so check for it
2098 // manually. If the longer string doesn't have a null terminator where the
2099 // shorter string ends, they aren't potentially overlapping.
2100 for (int NullByte : llvm::seq(ShorterCharWidth)) {
2101 if (Shorter.size() + NullByte >= Longer.size())
2102 break;
2103 if (Longer[Shorter.size() + NullByte])
2104 return false;
2105 }
2106
2107 // Otherwise, they're potentially overlapping if and only if the overlapping
2108 // region is the same.
2109 return Shorter == Longer.take_front(Shorter.size());
2110}
2111
2112static bool IsWeakLValue(const LValue &Value) {
2114 return Decl && Decl->isWeak();
2115}
2116
2117static bool isZeroSized(const LValue &Value) {
2119 if (isa_and_nonnull<VarDecl>(Decl)) {
2120 QualType Ty = Decl->getType();
2121 if (Ty->isArrayType())
2122 return Ty->isIncompleteType() ||
2123 Decl->getASTContext().getTypeSize(Ty) == 0;
2124 }
2125 return false;
2126}
2127
2128static bool HasSameBase(const LValue &A, const LValue &B) {
2129 if (!A.getLValueBase())
2130 return !B.getLValueBase();
2131 if (!B.getLValueBase())
2132 return false;
2133
2134 if (A.getLValueBase().getOpaqueValue() !=
2135 B.getLValueBase().getOpaqueValue())
2136 return false;
2137
2138 return A.getLValueCallIndex() == B.getLValueCallIndex() &&
2139 A.getLValueVersion() == B.getLValueVersion();
2140}
2141
2142static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
2143 assert(Base && "no location for a null lvalue");
2144 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2145
2146 // For a parameter, find the corresponding call stack frame (if it still
2147 // exists), and point at the parameter of the function definition we actually
2148 // invoked.
2149 if (auto *PVD = dyn_cast_or_null<ParmVarDecl>(VD)) {
2150 unsigned Idx = PVD->getFunctionScopeIndex();
2151 for (CallStackFrame *F = Info.CurrentCall; F; F = F->Caller) {
2152 if (F->Arguments.CallIndex == Base.getCallIndex() &&
2153 F->Arguments.Version == Base.getVersion() && F->Callee &&
2154 Idx < F->Callee->getNumParams()) {
2155 VD = F->Callee->getParamDecl(Idx);
2156 break;
2157 }
2158 }
2159 }
2160
2161 if (VD)
2162 Info.Note(VD->getLocation(), diag::note_declared_at);
2163 else if (const Expr *E = Base.dyn_cast<const Expr*>())
2164 Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
2165 else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
2166 // FIXME: Produce a note for dangling pointers too.
2167 if (std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA))
2168 Info.Note((*Alloc)->AllocExpr->getExprLoc(),
2169 diag::note_constexpr_dynamic_alloc_here);
2170 }
2171
2172 // We have no information to show for a typeid(T) object.
2173}
2174
2179
2180/// Materialized temporaries that we've already checked to determine if they're
2181/// initializsed by a constant expression.
2184
2186 EvalInfo &Info, SourceLocation DiagLoc,
2187 QualType Type, const APValue &Value,
2188 ConstantExprKind Kind,
2189 const FieldDecl *SubobjectDecl,
2190 CheckedTemporaries &CheckedTemps);
2191
2192/// Check that this reference or pointer core constant expression is a valid
2193/// value for an address or reference constant expression. Return true if we
2194/// can fold this expression, whether or not it's a constant expression.
2195static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
2196 QualType Type, const LValue &LVal,
2197 ConstantExprKind Kind,
2198 CheckedTemporaries &CheckedTemps) {
2199 bool IsReferenceType = Type->isReferenceType();
2200
2201 APValue::LValueBase Base = LVal.getLValueBase();
2202 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
2203
2204 const Expr *BaseE = Base.dyn_cast<const Expr *>();
2205 const ValueDecl *BaseVD = Base.dyn_cast<const ValueDecl*>();
2206
2207 // Additional restrictions apply in a template argument. We only enforce the
2208 // C++20 restrictions here; additional syntactic and semantic restrictions
2209 // are applied elsewhere.
2210 if (isTemplateArgument(Kind)) {
2211 int InvalidBaseKind = -1;
2212 StringRef Ident;
2213 if (Base.is<TypeInfoLValue>())
2214 InvalidBaseKind = 0;
2215 else if (isa_and_nonnull<StringLiteral>(BaseE))
2216 InvalidBaseKind = 1;
2217 else if (isa_and_nonnull<MaterializeTemporaryExpr>(BaseE) ||
2218 isa_and_nonnull<LifetimeExtendedTemporaryDecl>(BaseVD))
2219 InvalidBaseKind = 2;
2220 else if (auto *PE = dyn_cast_or_null<PredefinedExpr>(BaseE)) {
2221 InvalidBaseKind = 3;
2222 Ident = PE->getIdentKindName();
2223 }
2224
2225 if (InvalidBaseKind != -1) {
2226 Info.FFDiag(Loc, diag::note_constexpr_invalid_template_arg)
2227 << IsReferenceType << !Designator.Entries.empty() << InvalidBaseKind
2228 << Ident;
2229 return false;
2230 }
2231 }
2232
2233 if (auto *FD = dyn_cast_or_null<FunctionDecl>(BaseVD);
2234 FD && FD->isImmediateFunction()) {
2235 Info.FFDiag(Loc, diag::note_consteval_address_accessible)
2236 << !Type->isAnyPointerType();
2237 Info.Note(FD->getLocation(), diag::note_declared_at);
2238 return false;
2239 }
2240
2241 // Check that the object is a global. Note that the fake 'this' object we
2242 // manufacture when checking potential constant expressions is conservatively
2243 // assumed to be global here.
2244 if (!IsGlobalLValue(Base)) {
2245 if (Info.getLangOpts().CPlusPlus11) {
2246 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
2247 << IsReferenceType << !Designator.Entries.empty() << !!BaseVD
2248 << BaseVD;
2249 auto *VarD = dyn_cast_or_null<VarDecl>(BaseVD);
2250 if (VarD && VarD->isConstexpr()) {
2251 // Non-static local constexpr variables have unintuitive semantics:
2252 // constexpr int a = 1;
2253 // constexpr const int *p = &a;
2254 // ... is invalid because the address of 'a' is not constant. Suggest
2255 // adding a 'static' in this case.
2256 Info.Note(VarD->getLocation(), diag::note_constexpr_not_static)
2257 << VarD
2258 << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static ");
2259 } else {
2260 NoteLValueLocation(Info, Base);
2261 }
2262 } else {
2263 Info.FFDiag(Loc);
2264 }
2265 // Don't allow references to temporaries to escape.
2266 return false;
2267 }
2268 assert((Info.checkingPotentialConstantExpression() ||
2269 LVal.getLValueCallIndex() == 0) &&
2270 "have call index for global lvalue");
2271
2272 if (LVal.allowConstexprUnknown()) {
2273 if (BaseVD) {
2274 Info.FFDiag(Loc, diag::note_constexpr_var_init_non_constant, 1) << BaseVD;
2275 NoteLValueLocation(Info, Base);
2276 } else {
2277 Info.FFDiag(Loc);
2278 }
2279 return false;
2280 }
2281
2282 if (Base.is<DynamicAllocLValue>()) {
2283 Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc)
2284 << IsReferenceType << !Designator.Entries.empty();
2285 NoteLValueLocation(Info, Base);
2286 return false;
2287 }
2288
2289 if (BaseVD) {
2290 if (const VarDecl *Var = dyn_cast<const VarDecl>(BaseVD)) {
2291 // Check if this is a thread-local variable.
2292 if (Var->getTLSKind())
2293 // FIXME: Diagnostic!
2294 return false;
2295
2296 // A dllimport variable never acts like a constant, unless we're
2297 // evaluating a value for use only in name mangling, and unless it's a
2298 // static local. For the latter case, we'd still need to evaluate the
2299 // constant expression in case we're inside a (inlined) function.
2300 if (!isForManglingOnly(Kind) && Var->hasAttr<DLLImportAttr>() &&
2301 !Var->isStaticLocal())
2302 return false;
2303
2304 // In CUDA/HIP device compilation, only device side variables have
2305 // constant addresses.
2306 if (Info.getLangOpts().CUDA && Info.getLangOpts().CUDAIsDevice &&
2307 Info.Ctx.CUDAConstantEvalCtx.NoWrongSidedVars) {
2308 if ((!Var->hasAttr<CUDADeviceAttr>() &&
2309 !Var->hasAttr<CUDAConstantAttr>() &&
2310 !Var->getType()->isCUDADeviceBuiltinSurfaceType() &&
2311 !Var->getType()->isCUDADeviceBuiltinTextureType()) ||
2312 Var->hasAttr<HIPManagedAttr>())
2313 return false;
2314 }
2315 }
2316 if (const auto *FD = dyn_cast<const FunctionDecl>(BaseVD)) {
2317 // __declspec(dllimport) must be handled very carefully:
2318 // We must never initialize an expression with the thunk in C++.
2319 // Doing otherwise would allow the same id-expression to yield
2320 // different addresses for the same function in different translation
2321 // units. However, this means that we must dynamically initialize the
2322 // expression with the contents of the import address table at runtime.
2323 //
2324 // The C language has no notion of ODR; furthermore, it has no notion of
2325 // dynamic initialization. This means that we are permitted to
2326 // perform initialization with the address of the thunk.
2327 if (Info.getLangOpts().CPlusPlus && !isForManglingOnly(Kind) &&
2328 FD->hasAttr<DLLImportAttr>())
2329 // FIXME: Diagnostic!
2330 return false;
2331 }
2332 } else if (const auto *MTE =
2333 dyn_cast_or_null<MaterializeTemporaryExpr>(BaseE)) {
2334 if (CheckedTemps.insert(MTE).second) {
2335 QualType TempType = getType(Base);
2336 if (TempType.isDestructedType()) {
2337 Info.FFDiag(MTE->getExprLoc(),
2338 diag::note_constexpr_unsupported_temporary_nontrivial_dtor)
2339 << TempType;
2340 return false;
2341 }
2342
2343 APValue *V = MTE->getOrCreateValue(false);
2344 assert(V && "evasluation result refers to uninitialised temporary");
2346 Info, MTE->getExprLoc(), TempType, *V, Kind,
2347 /*SubobjectDecl=*/nullptr, CheckedTemps))
2348 return false;
2349 }
2350 }
2351
2352 // Allow address constant expressions to be past-the-end pointers. This is
2353 // an extension: the standard requires them to point to an object.
2354 if (!IsReferenceType)
2355 return true;
2356
2357 // A reference constant expression must refer to an object.
2358 if (!Base) {
2359 // FIXME: diagnostic
2360 Info.CCEDiag(Loc);
2361 return true;
2362 }
2363
2364 // Does this refer one past the end of some object?
2365 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
2366 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
2367 << !Designator.Entries.empty() << !!BaseVD << BaseVD;
2368 NoteLValueLocation(Info, Base);
2369 }
2370
2371 return true;
2372}
2373
2374/// Member pointers are constant expressions unless they point to a
2375/// non-virtual dllimport member function.
2376static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
2377 SourceLocation Loc,
2378 QualType Type,
2379 const APValue &Value,
2380 ConstantExprKind Kind) {
2381 const ValueDecl *Member = Value.getMemberPointerDecl();
2382 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
2383 if (!FD)
2384 return true;
2385 if (FD->isImmediateFunction()) {
2386 Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0;
2387 Info.Note(FD->getLocation(), diag::note_declared_at);
2388 return false;
2389 }
2390 return isForManglingOnly(Kind) || FD->isVirtual() ||
2391 !FD->hasAttr<DLLImportAttr>();
2392}
2393
2394/// Check that this core constant expression is of literal type, and if not,
2395/// produce an appropriate diagnostic.
2396static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
2397 const LValue *This = nullptr) {
2398 // The restriction to literal types does not exist in C++23 anymore.
2399 if (Info.getLangOpts().CPlusPlus23)
2400 return true;
2401
2402 if (!E->isPRValue() || E->getType()->isLiteralType(Info.Ctx))
2403 return true;
2404
2405 // C++1y: A constant initializer for an object o [...] may also invoke
2406 // constexpr constructors for o and its subobjects even if those objects
2407 // are of non-literal class types.
2408 //
2409 // C++11 missed this detail for aggregates, so classes like this:
2410 // struct foo_t { union { int i; volatile int j; } u; };
2411 // are not (obviously) initializable like so:
2412 // __attribute__((__require_constant_initialization__))
2413 // static const foo_t x = {{0}};
2414 // because "i" is a subobject with non-literal initialization (due to the
2415 // volatile member of the union). See:
2416 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2417 // Therefore, we use the C++1y behavior.
2418 if (This && Info.EvaluatingDecl == This->getLValueBase())
2419 return true;
2420
2421 // Prvalue constant expressions must be of literal types.
2422 if (Info.getLangOpts().CPlusPlus11)
2423 Info.FFDiag(E, diag::note_constexpr_nonliteral)
2424 << E->getType();
2425 else
2426 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2427 return false;
2428}
2429
2431 EvalInfo &Info, SourceLocation DiagLoc,
2432 QualType Type, const APValue &Value,
2433 ConstantExprKind Kind,
2434 const FieldDecl *SubobjectDecl,
2435 CheckedTemporaries &CheckedTemps) {
2436 if (!Value.hasValue()) {
2437 if (SubobjectDecl) {
2438 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2439 << /*(name)*/ 1 << SubobjectDecl;
2440 Info.Note(SubobjectDecl->getLocation(),
2441 diag::note_constexpr_subobject_declared_here);
2442 } else {
2443 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2444 << /*of type*/ 0 << Type;
2445 }
2446 return false;
2447 }
2448
2449 // We allow _Atomic(T) to be initialized from anything that T can be
2450 // initialized from.
2451 if (const AtomicType *AT = Type->getAs<AtomicType>())
2452 Type = AT->getValueType();
2453
2454 // Core issue 1454: For a literal constant expression of array or class type,
2455 // each subobject of its value shall have been initialized by a constant
2456 // expression.
2457 if (Value.isArray()) {
2459 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
2460 if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2461 Value.getArrayInitializedElt(I), Kind,
2462 SubobjectDecl, CheckedTemps))
2463 return false;
2464 }
2465 if (!Value.hasArrayFiller())
2466 return true;
2467 return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2468 Value.getArrayFiller(), Kind, SubobjectDecl,
2469 CheckedTemps);
2470 }
2471 if (Value.isUnion() && Value.getUnionField()) {
2472 return CheckEvaluationResult(
2473 CERK, Info, DiagLoc, Value.getUnionField()->getType(),
2474 Value.getUnionValue(), Kind, Value.getUnionField(), CheckedTemps);
2475 }
2476 if (Value.isStruct()) {
2477 auto *RD = Type->castAsRecordDecl();
2478 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2479 unsigned BaseIndex = 0;
2480 for (const CXXBaseSpecifier &BS : CD->bases()) {
2481 const APValue &BaseValue = Value.getStructBase(BaseIndex);
2482 if (!BaseValue.hasValue()) {
2483 SourceLocation TypeBeginLoc = BS.getBaseTypeLoc();
2484 Info.FFDiag(TypeBeginLoc, diag::note_constexpr_uninitialized_base)
2485 << BS.getType() << SourceRange(TypeBeginLoc, BS.getEndLoc());
2486 return false;
2487 }
2488 if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(), BaseValue,
2489 Kind, /*SubobjectDecl=*/nullptr,
2490 CheckedTemps))
2491 return false;
2492 ++BaseIndex;
2493 }
2494 }
2495 for (const auto *I : RD->fields()) {
2496 if (I->isUnnamedBitField())
2497 continue;
2498
2499 if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),
2500 Value.getStructField(I->getFieldIndex()), Kind,
2501 I, CheckedTemps))
2502 return false;
2503 }
2504 }
2505
2506 if (Value.isLValue() &&
2508 LValue LVal;
2509 LVal.setFrom(Info.Ctx, Value);
2510 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Kind,
2511 CheckedTemps);
2512 }
2513
2514 if (Value.isMemberPointer() &&
2516 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Kind);
2517
2518 // Everything else is fine.
2519 return true;
2520}
2521
2522/// Check that this core constant expression value is a valid value for a
2523/// constant expression. If not, report an appropriate diagnostic. Does not
2524/// check that the expression is of literal type.
2525static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
2526 QualType Type, const APValue &Value,
2527 ConstantExprKind Kind) {
2528 // Nothing to check for a constant expression of type 'cv void'.
2529 if (Type->isVoidType())
2530 return true;
2531
2532 CheckedTemporaries CheckedTemps;
2534 Info, DiagLoc, Type, Value, Kind,
2535 /*SubobjectDecl=*/nullptr, CheckedTemps);
2536}
2537
2538/// Check that this evaluated value is fully-initialized and can be loaded by
2539/// an lvalue-to-rvalue conversion.
2540static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,
2541 QualType Type, const APValue &Value) {
2542 CheckedTemporaries CheckedTemps;
2543 return CheckEvaluationResult(
2545 ConstantExprKind::Normal, /*SubobjectDecl=*/nullptr, CheckedTemps);
2546}
2547
2548/// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless
2549/// "the allocated storage is deallocated within the evaluation".
2550static bool CheckMemoryLeaks(EvalInfo &Info) {
2551 if (!Info.HeapAllocs.empty()) {
2552 // We can still fold to a constant despite a compile-time memory leak,
2553 // so long as the heap allocation isn't referenced in the result (we check
2554 // that in CheckConstantExpression).
2555 Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr,
2556 diag::note_constexpr_memory_leak)
2557 << unsigned(Info.HeapAllocs.size() - 1);
2558 }
2559 return true;
2560}
2561
2562static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
2563 // A null base expression indicates a null pointer. These are always
2564 // evaluatable, and they are false unless the offset is zero.
2565 if (!Value.getLValueBase()) {
2566 // TODO: Should a non-null pointer with an offset of zero evaluate to true?
2567 Result = !Value.getLValueOffset().isZero();
2568 return true;
2569 }
2570
2571 // We have a non-null base. These are generally known to be true, but if it's
2572 // a weak declaration it can be null at runtime.
2573 Result = true;
2574 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
2575 return !Decl || !Decl->isWeak();
2576}
2577
2578static bool HandleConversionToBool(const APValue &Val, bool &Result) {
2579 // TODO: This function should produce notes if it fails.
2580 switch (Val.getKind()) {
2581 case APValue::None:
2583 return false;
2584 case APValue::Int:
2585 Result = Val.getInt().getBoolValue();
2586 return true;
2588 Result = Val.getFixedPoint().getBoolValue();
2589 return true;
2590 case APValue::Float:
2591 Result = !Val.getFloat().isZero();
2592 return true;
2594 Result = Val.getComplexIntReal().getBoolValue() ||
2595 Val.getComplexIntImag().getBoolValue();
2596 return true;
2598 Result = !Val.getComplexFloatReal().isZero() ||
2599 !Val.getComplexFloatImag().isZero();
2600 return true;
2601 case APValue::LValue:
2602 return EvalPointerValueAsBool(Val, Result);
2604 if (Val.getMemberPointerDecl() && Val.getMemberPointerDecl()->isWeak()) {
2605 return false;
2606 }
2608 return true;
2609 case APValue::Vector:
2610 case APValue::Matrix:
2611 case APValue::Array:
2612 case APValue::Struct:
2613 case APValue::Union:
2615 return false;
2616 }
2617
2618 llvm_unreachable("unknown APValue kind");
2619}
2620
2621static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2622 EvalInfo &Info) {
2623 assert(!E->isValueDependent());
2624 assert(E->isPRValue() && "missing lvalue-to-rvalue conv in bool condition");
2625 APValue Val;
2626 if (!Evaluate(Val, Info, E))
2627 return false;
2628 return HandleConversionToBool(Val, Result);
2629}
2630
2631template<typename T>
2632static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2633 const T &SrcValue, QualType DestType) {
2634 Info.CCEDiag(E, diag::note_constexpr_overflow) << SrcValue << DestType;
2635 if (const auto *OBT = DestType->getAs<OverflowBehaviorType>();
2636 OBT && OBT->isTrapKind()) {
2637 return false;
2638 }
2639 return Info.noteUndefinedBehavior();
2640}
2641
2642static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2643 QualType SrcType, const APFloat &Value,
2644 QualType DestType, APSInt &Result) {
2645 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2646 // Determine whether we are converting to unsigned or signed.
2647 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2648
2649 Result = APSInt(DestWidth, !DestSigned);
2650 bool ignored;
2651 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2652 & APFloat::opInvalidOp)
2653 return HandleOverflow(Info, E, Value, DestType);
2654 return true;
2655}
2656
2657/// Get rounding mode to use in evaluation of the specified expression.
2658///
2659/// If rounding mode is unknown at compile time, still try to evaluate the
2660/// expression. If the result is exact, it does not depend on rounding mode.
2661/// So return "tonearest" mode instead of "dynamic".
2662static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E) {
2663 llvm::RoundingMode RM =
2664 E->getFPFeaturesInEffect(Info.getLangOpts()).getRoundingMode();
2665 if (RM == llvm::RoundingMode::Dynamic)
2666 RM = llvm::RoundingMode::NearestTiesToEven;
2667 return RM;
2668}
2669
2670/// Check if the given evaluation result is allowed for constant evaluation.
2671static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E,
2672 APFloat::opStatus St) {
2673 // In a constant context, assume that any dynamic rounding mode or FP
2674 // exception state matches the default floating-point environment.
2675 if (Info.InConstantContext)
2676 return true;
2677
2678 FPOptions FPO = E->getFPFeaturesInEffect(Info.getLangOpts());
2679 if ((St & APFloat::opInexact) &&
2680 FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) {
2681 // Inexact result means that it depends on rounding mode. If the requested
2682 // mode is dynamic, the evaluation cannot be made in compile time.
2683 Info.FFDiag(E, diag::note_constexpr_dynamic_rounding);
2684 return false;
2685 }
2686
2687 if ((St != APFloat::opOK) &&
2688 (FPO.getRoundingMode() == llvm::RoundingMode::Dynamic ||
2690 FPO.getAllowFEnvAccess())) {
2691 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
2692 return false;
2693 }
2694
2695 if ((St & APFloat::opStatus::opInvalidOp) &&
2697 // There is no usefully definable result.
2698 Info.FFDiag(E);
2699 return false;
2700 }
2701
2702 // FIXME: if:
2703 // - evaluation triggered other FP exception, and
2704 // - exception mode is not "ignore", and
2705 // - the expression being evaluated is not a part of global variable
2706 // initializer,
2707 // the evaluation probably need to be rejected.
2708 return true;
2709}
2710
2711static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2712 QualType SrcType, QualType DestType,
2713 APFloat &Result) {
2714 assert((isa<CastExpr>(E) || isa<CompoundAssignOperator>(E) ||
2716 "HandleFloatToFloatCast has been checked with only CastExpr, "
2717 "CompoundAssignOperator and ConvertVectorExpr. Please either validate "
2718 "the new expression or address the root cause of this usage.");
2719 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2720 APFloat::opStatus St;
2721 APFloat Value = Result;
2722 bool ignored;
2723 St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored);
2724 return checkFloatingPointResult(Info, E, St);
2725}
2726
2727static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2728 QualType DestType, QualType SrcType,
2729 const APSInt &Value) {
2730 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2731 // Figure out if this is a truncate, extend or noop cast.
2732 // If the input is signed, do a sign extend, noop, or truncate.
2733 APSInt Result = Value.extOrTrunc(DestWidth);
2734 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2735 if (DestType->isBooleanType())
2736 Result = Value.getBoolValue();
2737 return Result;
2738}
2739
2740static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2741 const FPOptions FPO,
2742 QualType SrcType, const APSInt &Value,
2743 QualType DestType, APFloat &Result) {
2744 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2745 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2746 APFloat::opStatus St = Result.convertFromAPInt(Value, Value.isSigned(), RM);
2747 return checkFloatingPointResult(Info, E, St);
2748}
2749
2750static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2751 APValue &Value, const FieldDecl *FD) {
2752 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2753
2754 if (!Value.isInt()) {
2755 // Trying to store a pointer-cast-to-integer into a bitfield.
2756 // FIXME: In this case, we should provide the diagnostic for casting
2757 // a pointer to an integer.
2758 assert(Value.isLValue() && "integral value neither int nor lvalue?");
2759 Info.FFDiag(E);
2760 return false;
2761 }
2762
2763 APSInt &Int = Value.getInt();
2764 unsigned OldBitWidth = Int.getBitWidth();
2765 unsigned NewBitWidth = FD->getBitWidthValue();
2766 if (NewBitWidth < OldBitWidth)
2767 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2768 return true;
2769}
2770
2771/// Perform the given integer operation, which is known to need at most BitWidth
2772/// bits, and check for overflow in the original type (if that type was not an
2773/// unsigned type).
2774template<typename Operation>
2775static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2776 const APSInt &LHS, const APSInt &RHS,
2777 unsigned BitWidth, Operation Op,
2778 APSInt &Result) {
2779 if (LHS.isUnsigned()) {
2780 Result = Op(LHS, RHS);
2781 return true;
2782 }
2783
2784 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2785 Result = Value.trunc(LHS.getBitWidth());
2786 if (Result.extend(BitWidth) != Value && !E->getType().isWrapType()) {
2787 if (Info.checkingForUndefinedBehavior())
2788 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2789 diag::warn_integer_constant_overflow)
2790 << toString(Result, 10, Result.isSigned(), /*formatAsCLiteral=*/false,
2791 /*UpperCase=*/true, /*InsertSeparators=*/true)
2792 << E->getType() << E->getSourceRange();
2793 return HandleOverflow(Info, E, Value, E->getType());
2794 }
2795 return true;
2796}
2797
2798/// Perform the given binary integer operation.
2799static bool handleIntIntBinOp(EvalInfo &Info, const BinaryOperator *E,
2800 const APSInt &LHS, BinaryOperatorKind Opcode,
2801 APSInt RHS, APSInt &Result) {
2802 bool HandleOverflowResult = true;
2803 switch (Opcode) {
2804 default:
2805 Info.FFDiag(E);
2806 return false;
2807 case BO_Mul:
2808 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2809 std::multiplies<APSInt>(), Result);
2810 case BO_Add:
2811 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2812 std::plus<APSInt>(), Result);
2813 case BO_Sub:
2814 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2815 std::minus<APSInt>(), Result);
2816 case BO_And: Result = LHS & RHS; return true;
2817 case BO_Xor: Result = LHS ^ RHS; return true;
2818 case BO_Or: Result = LHS | RHS; return true;
2819 case BO_Div:
2820 case BO_Rem:
2821 if (RHS == 0) {
2822 Info.FFDiag(E, diag::note_expr_divide_by_zero)
2823 << E->getRHS()->getSourceRange();
2824 return false;
2825 }
2826 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2827 // this operation and gives the two's complement result.
2828 if (RHS.isNegative() && RHS.isAllOnes() && LHS.isSigned() &&
2829 LHS.isMinSignedValue())
2830 HandleOverflowResult = HandleOverflow(
2831 Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
2832 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2833 return HandleOverflowResult;
2834 case BO_Shl: {
2835 if (Info.getLangOpts().OpenCL)
2836 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2837 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2838 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2839 RHS.isUnsigned());
2840 else if (RHS.isSigned() && RHS.isNegative()) {
2841 // During constant-folding, a negative shift is an opposite shift. Such
2842 // a shift is not a constant expression.
2843 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2844 if (!Info.noteUndefinedBehavior())
2845 return false;
2846 RHS = -RHS;
2847 goto shift_right;
2848 }
2849 shift_left:
2850 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2851 // the shifted type.
2852 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2853 if (SA != RHS) {
2854 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2855 << RHS << E->getType() << LHS.getBitWidth();
2856 if (!Info.noteUndefinedBehavior())
2857 return false;
2858 } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) {
2859 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2860 // operand, and must not overflow the corresponding unsigned type.
2861 // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2862 // E1 x 2^E2 module 2^N.
2863 if (LHS.isNegative()) {
2864 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2865 if (!Info.noteUndefinedBehavior())
2866 return false;
2867 } else if (LHS.countl_zero() < SA) {
2868 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2869 if (!Info.noteUndefinedBehavior())
2870 return false;
2871 }
2872 }
2873 Result = LHS << SA;
2874 return true;
2875 }
2876 case BO_Shr: {
2877 if (Info.getLangOpts().OpenCL)
2878 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2879 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2880 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2881 RHS.isUnsigned());
2882 else if (RHS.isSigned() && RHS.isNegative()) {
2883 // During constant-folding, a negative shift is an opposite shift. Such a
2884 // shift is not a constant expression.
2885 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2886 if (!Info.noteUndefinedBehavior())
2887 return false;
2888 RHS = -RHS;
2889 goto shift_left;
2890 }
2891 shift_right:
2892 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2893 // shifted type.
2894 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2895 if (SA != RHS) {
2896 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2897 << RHS << E->getType() << LHS.getBitWidth();
2898 if (!Info.noteUndefinedBehavior())
2899 return false;
2900 }
2901
2902 Result = LHS >> SA;
2903 return true;
2904 }
2905
2906 case BO_LT: Result = LHS < RHS; return true;
2907 case BO_GT: Result = LHS > RHS; return true;
2908 case BO_LE: Result = LHS <= RHS; return true;
2909 case BO_GE: Result = LHS >= RHS; return true;
2910 case BO_EQ: Result = LHS == RHS; return true;
2911 case BO_NE: Result = LHS != RHS; return true;
2912 case BO_Cmp:
2913 llvm_unreachable("BO_Cmp should be handled elsewhere");
2914 }
2915}
2916
2917/// Perform the given binary floating-point operation, in-place, on LHS.
2918static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E,
2919 APFloat &LHS, BinaryOperatorKind Opcode,
2920 const APFloat &RHS) {
2921 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2922 APFloat::opStatus St;
2923 switch (Opcode) {
2924 default:
2925 Info.FFDiag(E);
2926 return false;
2927 case BO_Mul:
2928 St = LHS.multiply(RHS, RM);
2929 break;
2930 case BO_Add:
2931 St = LHS.add(RHS, RM);
2932 break;
2933 case BO_Sub:
2934 St = LHS.subtract(RHS, RM);
2935 break;
2936 case BO_Div:
2937 // [expr.mul]p4:
2938 // If the second operand of / or % is zero the behavior is undefined.
2939 if (RHS.isZero())
2940 Info.CCEDiag(E, diag::note_expr_divide_by_zero);
2941 St = LHS.divide(RHS, RM);
2942 break;
2943 }
2944
2945 // [expr.pre]p4:
2946 // If during the evaluation of an expression, the result is not
2947 // mathematically defined [...], the behavior is undefined.
2948 // FIXME: C++ rules require us to not conform to IEEE 754 here.
2949 if (LHS.isNaN()) {
2950 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
2951 return Info.noteUndefinedBehavior();
2952 }
2953
2954 return checkFloatingPointResult(Info, E, St);
2955}
2956
2957static bool handleLogicalOpForVector(const APInt &LHSValue,
2958 BinaryOperatorKind Opcode,
2959 const APInt &RHSValue, APInt &Result) {
2960 bool LHS = (LHSValue != 0);
2961 bool RHS = (RHSValue != 0);
2962
2963 if (Opcode == BO_LAnd)
2964 Result = LHS && RHS;
2965 else
2966 Result = LHS || RHS;
2967 return true;
2968}
2969static bool handleLogicalOpForVector(const APFloat &LHSValue,
2970 BinaryOperatorKind Opcode,
2971 const APFloat &RHSValue, APInt &Result) {
2972 bool LHS = !LHSValue.isZero();
2973 bool RHS = !RHSValue.isZero();
2974
2975 if (Opcode == BO_LAnd)
2976 Result = LHS && RHS;
2977 else
2978 Result = LHS || RHS;
2979 return true;
2980}
2981
2982static bool handleLogicalOpForVector(const APValue &LHSValue,
2983 BinaryOperatorKind Opcode,
2984 const APValue &RHSValue, APInt &Result) {
2985 // The result is always an int type, however operands match the first.
2986 if (LHSValue.getKind() == APValue::Int)
2987 return handleLogicalOpForVector(LHSValue.getInt(), Opcode,
2988 RHSValue.getInt(), Result);
2989 assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
2990 return handleLogicalOpForVector(LHSValue.getFloat(), Opcode,
2991 RHSValue.getFloat(), Result);
2992}
2993
2994template <typename APTy>
2995static bool
2997 const APTy &RHSValue, APInt &Result) {
2998 switch (Opcode) {
2999 default:
3000 llvm_unreachable("unsupported binary operator");
3001 case BO_EQ:
3002 Result = (LHSValue == RHSValue);
3003 break;
3004 case BO_NE:
3005 Result = (LHSValue != RHSValue);
3006 break;
3007 case BO_LT:
3008 Result = (LHSValue < RHSValue);
3009 break;
3010 case BO_GT:
3011 Result = (LHSValue > RHSValue);
3012 break;
3013 case BO_LE:
3014 Result = (LHSValue <= RHSValue);
3015 break;
3016 case BO_GE:
3017 Result = (LHSValue >= RHSValue);
3018 break;
3019 }
3020
3021 // The boolean operations on these vector types use an instruction that
3022 // results in a mask of '-1' for the 'truth' value. Ensure that we negate 1
3023 // to -1 to make sure that we produce the correct value.
3024 Result.negate();
3025
3026 return true;
3027}
3028
3029static bool handleCompareOpForVector(const APValue &LHSValue,
3030 BinaryOperatorKind Opcode,
3031 const APValue &RHSValue, APInt &Result) {
3032 // The result is always an int type, however operands match the first.
3033 if (LHSValue.getKind() == APValue::Int)
3034 return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode,
3035 RHSValue.getInt(), Result);
3036 assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
3037 return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode,
3038 RHSValue.getFloat(), Result);
3039}
3040
3041// Perform binary operations for vector types, in place on the LHS.
3042static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E,
3043 BinaryOperatorKind Opcode,
3044 APValue &LHSValue,
3045 const APValue &RHSValue) {
3046 assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI &&
3047 "Operation not supported on vector types");
3048
3049 const auto *VT = E->getType()->castAs<VectorType>();
3050 unsigned NumElements = VT->getNumElements();
3051 QualType EltTy = VT->getElementType();
3052
3053 // In the cases (typically C as I've observed) where we aren't evaluating
3054 // constexpr but are checking for cases where the LHS isn't yet evaluatable,
3055 // just give up.
3056 if (!LHSValue.isVector()) {
3057 assert(LHSValue.isLValue() &&
3058 "A vector result that isn't a vector OR uncalculated LValue");
3059 Info.FFDiag(E);
3060 return false;
3061 }
3062
3063 assert(LHSValue.getVectorLength() == NumElements &&
3064 RHSValue.getVectorLength() == NumElements && "Different vector sizes");
3065
3066 SmallVector<APValue, 4> ResultElements;
3067
3068 for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) {
3069 APValue LHSElt = LHSValue.getVectorElt(EltNum);
3070 APValue RHSElt = RHSValue.getVectorElt(EltNum);
3071
3072 if (EltTy->isIntegerType()) {
3073 APSInt EltResult{Info.Ctx.getIntWidth(EltTy),
3074 EltTy->isUnsignedIntegerType()};
3075 bool Success = true;
3076
3077 if (BinaryOperator::isLogicalOp(Opcode))
3078 Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3079 else if (BinaryOperator::isComparisonOp(Opcode))
3080 Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3081 else
3082 Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode,
3083 RHSElt.getInt(), EltResult);
3084
3085 if (!Success) {
3086 Info.FFDiag(E);
3087 return false;
3088 }
3089 ResultElements.emplace_back(EltResult);
3090
3091 } else if (EltTy->isFloatingType()) {
3092 assert(LHSElt.getKind() == APValue::Float &&
3093 RHSElt.getKind() == APValue::Float &&
3094 "Mismatched LHS/RHS/Result Type");
3095 APFloat LHSFloat = LHSElt.getFloat();
3096
3097 if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode,
3098 RHSElt.getFloat())) {
3099 Info.FFDiag(E);
3100 return false;
3101 }
3102
3103 ResultElements.emplace_back(LHSFloat);
3104 }
3105 }
3106
3107 LHSValue = APValue(ResultElements.data(), ResultElements.size());
3108 return true;
3109}
3110
3111/// Cast an lvalue referring to a base subobject to a derived class, by
3112/// truncating the lvalue's path to the given length.
3113static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
3114 const RecordDecl *TruncatedType,
3115 unsigned TruncatedElements) {
3116 SubobjectDesignator &D = Result.Designator;
3117
3118 // Check we actually point to a derived class object.
3119 if (TruncatedElements == D.Entries.size())
3120 return true;
3121 assert(TruncatedElements >= D.MostDerivedPathLength &&
3122 "not casting to a derived class");
3123 if (!Result.checkSubobject(Info, E, CSK_Derived))
3124 return false;
3125
3126 // Truncate the path to the subobject, and remove any derived-to-base offsets.
3127 const RecordDecl *RD = TruncatedType;
3128 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
3129 if (RD->isInvalidDecl()) return false;
3130 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3131 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
3132 if (isVirtualBaseClass(D.Entries[I]))
3133 Result.Offset -= Layout.getVBaseClassOffset(Base);
3134 else
3135 Result.Offset -= Layout.getBaseClassOffset(Base);
3136 RD = Base;
3137 }
3138 D.Entries.resize(TruncatedElements);
3139 return true;
3140}
3141
3142static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3143 const CXXRecordDecl *Derived,
3144 const CXXRecordDecl *Base,
3145 const ASTRecordLayout *RL = nullptr) {
3146 if (!RL) {
3147 if (Derived->isInvalidDecl()) return false;
3148 RL = &Info.Ctx.getASTRecordLayout(Derived);
3149 }
3150
3151 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
3152 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
3153 return true;
3154}
3155
3156static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3157 const CXXRecordDecl *DerivedDecl,
3158 const CXXBaseSpecifier *Base) {
3159 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
3160
3161 if (!Base->isVirtual())
3162 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
3163
3164 SubobjectDesignator &D = Obj.Designator;
3165 if (D.Invalid)
3166 return false;
3167
3168 // Extract most-derived object and corresponding type.
3169 // FIXME: After implementing P2280R4 it became possible to get references
3170 // here. We do MostDerivedType->getAsCXXRecordDecl() in several other
3171 // locations and if we see crashes in those locations in the future
3172 // it may make more sense to move this fix into Lvalue::set.
3173 DerivedDecl = D.MostDerivedType.getNonReferenceType()->getAsCXXRecordDecl();
3174 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
3175 return false;
3176
3177 // Find the virtual base class.
3178 if (DerivedDecl->isInvalidDecl()) return false;
3179 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
3180 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
3181 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
3182 return true;
3183}
3184
3185static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
3186 QualType Type, LValue &Result) {
3187 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3188 PathE = E->path_end();
3189 PathI != PathE; ++PathI) {
3191 *PathI))
3192 return false;
3193 Type = (*PathI)->getType();
3194 }
3195 return true;
3196}
3197
3198/// Cast an lvalue referring to a derived class to a known base subobject.
3199static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
3200 const CXXRecordDecl *DerivedRD,
3201 const CXXRecordDecl *BaseRD) {
3202 CXXBasePaths Paths(/*FindAmbiguities=*/false,
3203 /*RecordPaths=*/true, /*DetectVirtual=*/false);
3204 if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
3205 llvm_unreachable("Class must be derived from the passed in base class!");
3206
3207 for (CXXBasePathElement &Elem : Paths.front())
3208 if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
3209 return false;
3210 return true;
3211}
3212
3213/// Update LVal to refer to the given field, which must be a member of the type
3214/// currently described by LVal.
3215static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
3216 const FieldDecl *FD,
3217 const ASTRecordLayout *RL = nullptr) {
3218 if (!RL) {
3219 if (FD->getParent()->isInvalidDecl()) return false;
3220 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
3221 }
3222
3223 unsigned I = FD->getFieldIndex();
3224 LVal.addDecl(Info, E, FD);
3225 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
3226 return true;
3227}
3228
3229/// Update LVal to refer to the given indirect field.
3230static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
3231 LValue &LVal,
3232 const IndirectFieldDecl *IFD) {
3233 for (const auto *C : IFD->chain())
3234 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
3235 return false;
3236 return true;
3237}
3238
3243
3244/// Get the size of the given type in char units.
3245static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, QualType Type,
3247 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
3248 // extension.
3249 if (Type->isVoidType() || Type->isFunctionType()) {
3250 Size = CharUnits::One();
3251 return true;
3252 }
3253
3254 if (Type->isDependentType()) {
3255 Info.FFDiag(Loc);
3256 return false;
3257 }
3258
3259 if (!Type->isConstantSizeType()) {
3260 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
3261 // FIXME: Better diagnostic.
3262 Info.FFDiag(Loc);
3263 return false;
3264 }
3265
3266 if (SOT == SizeOfType::SizeOf)
3267 Size = Info.Ctx.getTypeSizeInChars(Type);
3268 else
3269 Size = Info.Ctx.getTypeInfoDataSizeInChars(Type).Width;
3270 return true;
3271}
3272
3273/// Update a pointer value to model pointer arithmetic.
3274/// \param Info - Information about the ongoing evaluation.
3275/// \param E - The expression being evaluated, for diagnostic purposes.
3276/// \param LVal - The pointer value to be updated.
3277/// \param EltTy - The pointee type represented by LVal.
3278/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
3279static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3280 LValue &LVal, QualType EltTy,
3281 APSInt Adjustment) {
3282 CharUnits SizeOfPointee;
3283 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
3284 return false;
3285
3286 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
3287 return true;
3288}
3289
3290static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3291 LValue &LVal, QualType EltTy,
3292 int64_t Adjustment) {
3293 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
3294 APSInt::get(Adjustment));
3295}
3296
3297/// Update an lvalue to refer to a component of a complex number.
3298/// \param Info - Information about the ongoing evaluation.
3299/// \param LVal - The lvalue to be updated.
3300/// \param EltTy - The complex number's component type.
3301/// \param Imag - False for the real component, true for the imaginary.
3302static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
3303 LValue &LVal, QualType EltTy,
3304 bool Imag) {
3305 if (Imag) {
3306 CharUnits SizeOfComponent;
3307 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
3308 return false;
3309 LVal.Offset += SizeOfComponent;
3310 }
3311 LVal.addComplex(Info, E, EltTy, Imag);
3312 return true;
3313}
3314
3315static bool HandleLValueVectorElement(EvalInfo &Info, const Expr *E,
3316 LValue &LVal, QualType EltTy,
3317 uint64_t Size, uint64_t Idx) {
3318 if (Idx) {
3319 CharUnits SizeOfElement;
3320 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfElement))
3321 return false;
3322 LVal.Offset += SizeOfElement * Idx;
3323 }
3324 LVal.addVectorElement(Info, E, EltTy, Size, Idx);
3325 return true;
3326}
3327
3328/// Try to evaluate the initializer for a variable declaration.
3329///
3330/// \param Info Information about the ongoing evaluation.
3331/// \param E An expression to be used when printing diagnostics.
3332/// \param VD The variable whose initializer should be obtained.
3333/// \param Version The version of the variable within the frame.
3334/// \param Frame The frame in which the variable was created. Must be null
3335/// if this variable is not local to the evaluation.
3336/// \param Result Filled in with a pointer to the value of the variable.
3337static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
3338 const VarDecl *VD, CallStackFrame *Frame,
3339 unsigned Version, APValue *&Result) {
3340 // C++23 [expr.const]p8 If we have a reference type allow unknown references
3341 // and pointers.
3342 bool AllowConstexprUnknown =
3343 Info.getLangOpts().CPlusPlus23 && VD->getType()->isReferenceType();
3344
3345 APValue::LValueBase Base(VD, Frame ? Frame->Index : 0, Version);
3346
3347 auto CheckUninitReference = [&](bool IsLocalVariable) {
3348 if (!Result || (!Result->hasValue() && VD->getType()->isReferenceType())) {
3349 // C++23 [expr.const]p8
3350 // ... For such an object that is not usable in constant expressions, the
3351 // dynamic type of the object is constexpr-unknown. For such a reference
3352 // that is not usable in constant expressions, the reference is treated
3353 // as binding to an unspecified object of the referenced type whose
3354 // lifetime and that of all subobjects includes the entire constant
3355 // evaluation and whose dynamic type is constexpr-unknown.
3356 //
3357 // Variables that are part of the current evaluation are not
3358 // constexpr-unknown.
3359 if (!AllowConstexprUnknown || IsLocalVariable) {
3360 if (!Info.checkingPotentialConstantExpression())
3361 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
3362 return false;
3363 }
3364 Result = nullptr;
3365 }
3366 return true;
3367 };
3368
3369 // If this is a local variable, dig out its value.
3370 if (Frame) {
3371 Result = Frame->getTemporary(VD, Version);
3372 if (Result)
3373 return CheckUninitReference(/*IsLocalVariable=*/true);
3374
3375 if (!isa<ParmVarDecl>(VD)) {
3376 // Assume variables referenced within a lambda's call operator that were
3377 // not declared within the call operator are captures and during checking
3378 // of a potential constant expression, assume they are unknown constant
3379 // expressions.
3380 assert(isLambdaCallOperator(Frame->Callee) &&
3381 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
3382 "missing value for local variable");
3383 if (Info.checkingPotentialConstantExpression())
3384 return false;
3385
3386 llvm_unreachable(
3387 "A variable in a frame should either be a local or a parameter");
3388 }
3389 }
3390
3391 // If we're currently evaluating the initializer of this declaration, use that
3392 // in-flight value.
3393 if (Info.EvaluatingDecl == Base) {
3394 Result = Info.EvaluatingDeclValue;
3395 return CheckUninitReference(/*IsLocalVariable=*/false);
3396 }
3397
3398 // P2280R4 struck the restriction that variable of reference type lifetime
3399 // should begin within the evaluation of E
3400 // Used to be C++20 [expr.const]p5.12.2:
3401 // ... its lifetime began within the evaluation of E;
3402 if (isa<ParmVarDecl>(VD)) {
3403 if (AllowConstexprUnknown) {
3404 Result = nullptr;
3405 return true;
3406 }
3407
3408 // Assume parameters of a potential constant expression are usable in
3409 // constant expressions.
3410 if (!Info.checkingPotentialConstantExpression() ||
3411 !Info.CurrentCall->Callee ||
3412 !Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
3413 if (Info.getLangOpts().CPlusPlus11) {
3414 Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown)
3415 << VD;
3416 NoteLValueLocation(Info, Base);
3417 } else {
3418 Info.FFDiag(E);
3419 }
3420 }
3421 return false;
3422 }
3423
3424 if (E->isValueDependent())
3425 return false;
3426
3427 // Dig out the initializer, and use the declaration which it's attached to.
3428 // FIXME: We should eventually check whether the variable has a reachable
3429 // initializing declaration.
3430 const Expr *Init = VD->getAnyInitializer(VD);
3431 // P2280R4 struck the restriction that variable of reference type should have
3432 // a preceding initialization.
3433 // Used to be C++20 [expr.const]p5.12:
3434 // ... reference has a preceding initialization and either ...
3435 if (!Init && !AllowConstexprUnknown) {
3436 // Don't diagnose during potential constant expression checking; an
3437 // initializer might be added later.
3438 if (!Info.checkingPotentialConstantExpression()) {
3439 Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1)
3440 << VD;
3441 NoteLValueLocation(Info, Base);
3442 }
3443 return false;
3444 }
3445
3446 // P2280R4 struck the initialization requirement for variables of reference
3447 // type so we can no longer assume we have an Init.
3448 // Used to be C++20 [expr.const]p5.12:
3449 // ... reference has a preceding initialization and either ...
3450 if (Init && Init->isValueDependent()) {
3451 // The DeclRefExpr is not value-dependent, but the variable it refers to
3452 // has a value-dependent initializer. This should only happen in
3453 // constant-folding cases, where the variable is not actually of a suitable
3454 // type for use in a constant expression (otherwise the DeclRefExpr would
3455 // have been value-dependent too), so diagnose that.
3456 assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx));
3457 if (!Info.checkingPotentialConstantExpression()) {
3458 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
3459 ? diag::note_constexpr_ltor_non_constexpr
3460 : diag::note_constexpr_ltor_non_integral, 1)
3461 << VD << VD->getType();
3462 NoteLValueLocation(Info, Base);
3463 }
3464 return false;
3465 }
3466
3467 // Check that we can fold the initializer. In C++, we will have already done
3468 // this in the cases where it matters for conformance.
3469 // P2280R4 struck the initialization requirement for variables of reference
3470 // type so we can no longer assume we have an Init.
3471 // Used to be C++20 [expr.const]p5.12:
3472 // ... reference has a preceding initialization and either ...
3473 if (Init && !VD->evaluateValue() && !AllowConstexprUnknown) {
3474 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3475 NoteLValueLocation(Info, Base);
3476 return false;
3477 }
3478
3479 // Check that the variable is actually usable in constant expressions. For a
3480 // const integral variable or a reference, we might have a non-constant
3481 // initializer that we can nonetheless evaluate the initializer for. Such
3482 // variables are not usable in constant expressions. In C++98, the
3483 // initializer also syntactically needs to be an ICE.
3484 //
3485 // FIXME: We don't diagnose cases that aren't potentially usable in constant
3486 // expressions here; doing so would regress diagnostics for things like
3487 // reading from a volatile constexpr variable.
3488 if ((Info.getLangOpts().CPlusPlus && !VD->hasConstantInitialization() &&
3489 VD->mightBeUsableInConstantExpressions(Info.Ctx) &&
3490 !AllowConstexprUnknown) ||
3491 ((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) &&
3492 !Info.getLangOpts().CPlusPlus11 && !VD->hasICEInitializer(Info.Ctx))) {
3493 if (Init) {
3494 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3495 NoteLValueLocation(Info, Base);
3496 } else {
3497 Info.CCEDiag(E);
3498 }
3499 }
3500
3501 // Never use the initializer of a weak variable, not even for constant
3502 // folding. We can't be sure that this is the definition that will be used.
3503 if (VD->isWeak()) {
3504 Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD;
3505 NoteLValueLocation(Info, Base);
3506 return false;
3507 }
3508
3509 Result = VD->getEvaluatedValue();
3510
3511 if (!Result && !AllowConstexprUnknown)
3512 return false;
3513
3514 return CheckUninitReference(/*IsLocalVariable=*/false);
3515}
3516
3517/// Get the base index of the given base class within an APValue representing
3518/// the given derived class.
3519static unsigned getBaseIndex(const CXXRecordDecl *Derived,
3520 const CXXRecordDecl *Base) {
3521 Base = Base->getCanonicalDecl();
3522 unsigned Index = 0;
3524 E = Derived->bases_end(); I != E; ++I, ++Index) {
3525 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
3526 return Index;
3527 }
3528
3529 llvm_unreachable("base class missing from derived class's bases list");
3530}
3531
3532/// Extract the value of a character from a string literal.
3533static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
3534 uint64_t Index) {
3535 assert(!isa<SourceLocExpr>(Lit) &&
3536 "SourceLocExpr should have already been converted to a StringLiteral");
3537
3538 // FIXME: Support MakeStringConstant
3539 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
3540 std::string Str;
3541 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
3542 assert(Index <= Str.size() && "Index too large");
3543 return APSInt::getUnsigned(Str.c_str()[Index]);
3544 }
3545
3546 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
3547 Lit = PE->getFunctionName();
3548 const StringLiteral *S = cast<StringLiteral>(Lit);
3549 const ConstantArrayType *CAT =
3550 Info.Ctx.getAsConstantArrayType(S->getType());
3551 assert(CAT && "string literal isn't an array");
3552 QualType CharType = CAT->getElementType();
3553 assert(CharType->isIntegerType() && "unexpected character type");
3554 APSInt Value(Info.Ctx.getTypeSize(CharType),
3555 CharType->isUnsignedIntegerType());
3556 if (Index < S->getLength())
3557 Value = S->getCodeUnit(Index);
3558 return Value;
3559}
3560
3561// Expand a string literal into an array of characters.
3562//
3563// FIXME: This is inefficient; we should probably introduce something similar
3564// to the LLVM ConstantDataArray to make this cheaper.
3565static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
3566 APValue &Result,
3567 QualType AllocType = QualType()) {
3568 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
3569 AllocType.isNull() ? S->getType() : AllocType);
3570 assert(CAT && "string literal isn't an array");
3571 QualType CharType = CAT->getElementType();
3572 assert(CharType->isIntegerType() && "unexpected character type");
3573
3574 unsigned Elts = CAT->getZExtSize();
3576 std::min(S->getLength(), Elts), Elts);
3577 APSInt Value(Info.Ctx.getTypeSize(CharType),
3578 CharType->isUnsignedIntegerType());
3579 if (Result.hasArrayFiller())
3580 Result.getArrayFiller() = APValue(Value);
3581 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
3582 Value = S->getCodeUnit(I);
3583 Result.getArrayInitializedElt(I) = APValue(Value);
3584 }
3585}
3586
3587// Expand an array so that it has more than Index filled elements.
3588static void expandArray(APValue &Array, unsigned Index) {
3589 unsigned Size = Array.getArraySize();
3590 assert(Index < Size);
3591
3592 // Always at least double the number of elements for which we store a value.
3593 unsigned OldElts = Array.getArrayInitializedElts();
3594 unsigned NewElts = std::max(Index+1, OldElts * 2);
3595 NewElts = std::min(Size, std::max(NewElts, 8u));
3596
3597 // Copy the data across.
3598 APValue NewValue(APValue::UninitArray(), NewElts, Size);
3599 for (unsigned I = 0; I != OldElts; ++I)
3600 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
3601 for (unsigned I = OldElts; I != NewElts; ++I)
3602 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
3603 if (NewValue.hasArrayFiller())
3604 NewValue.getArrayFiller() = Array.getArrayFiller();
3605 Array.swap(NewValue);
3606}
3607
3608// Expand an indeterminate vector to materialize all elements.
3609static void expandVector(APValue &Vec, unsigned NumElements) {
3610 assert(Vec.isIndeterminate());
3612 Vec = APValue(Elts.data(), Elts.size());
3613}
3614
3615/// Determine whether a type would actually be read by an lvalue-to-rvalue
3616/// conversion. If it's of class type, we may assume that the copy operation
3617/// is trivial. Note that this is never true for a union type with fields
3618/// (because the copy always "reads" the active member) and always true for
3619/// a non-class type.
3620static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD);
3622 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3623 return !RD || isReadByLvalueToRvalueConversion(RD);
3624}
3626 // FIXME: A trivial copy of a union copies the object representation, even if
3627 // the union is empty.
3628 if (RD->isUnion())
3629 return !RD->field_empty();
3630 if (RD->isEmpty())
3631 return false;
3632
3633 for (auto *Field : RD->fields())
3634 if (!Field->isUnnamedBitField() &&
3635 isReadByLvalueToRvalueConversion(Field->getType()))
3636 return true;
3637
3638 for (auto &BaseSpec : RD->bases())
3639 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
3640 return true;
3641
3642 return false;
3643}
3644
3645/// Diagnose an attempt to read from any unreadable field within the specified
3646/// type, which might be a class type.
3647static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK,
3648 QualType T) {
3649 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3650 if (!RD)
3651 return false;
3652
3653 if (!RD->hasMutableFields())
3654 return false;
3655
3656 for (auto *Field : RD->fields()) {
3657 // If we're actually going to read this field in some way, then it can't
3658 // be mutable. If we're in a union, then assigning to a mutable field
3659 // (even an empty one) can change the active member, so that's not OK.
3660 // FIXME: Add core issue number for the union case.
3661 if (Field->isMutable() &&
3662 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
3663 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field;
3664 Info.Note(Field->getLocation(), diag::note_declared_at);
3665 return true;
3666 }
3667
3668 if (diagnoseMutableFields(Info, E, AK, Field->getType()))
3669 return true;
3670 }
3671
3672 for (auto &BaseSpec : RD->bases())
3673 if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType()))
3674 return true;
3675
3676 // All mutable fields were empty, and thus not actually read.
3677 return false;
3678}
3679
3680static bool lifetimeStartedInEvaluation(EvalInfo &Info,
3682 bool MutableSubobject = false) {
3683 // A temporary or transient heap allocation we created.
3684 if (Base.getCallIndex() || Base.is<DynamicAllocLValue>())
3685 return true;
3686
3687 switch (Info.IsEvaluatingDecl) {
3688 case EvalInfo::EvaluatingDeclKind::None:
3689 return false;
3690
3691 case EvalInfo::EvaluatingDeclKind::Ctor:
3692 // The variable whose initializer we're evaluating.
3693 if (Info.EvaluatingDecl == Base)
3694 return true;
3695
3696 // A temporary lifetime-extended by the variable whose initializer we're
3697 // evaluating.
3698 if (auto *BaseE = Base.dyn_cast<const Expr *>())
3699 if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
3700 return Info.EvaluatingDecl == BaseMTE->getExtendingDecl();
3701 return false;
3702
3703 case EvalInfo::EvaluatingDeclKind::Dtor:
3704 // C++2a [expr.const]p6:
3705 // [during constant destruction] the lifetime of a and its non-mutable
3706 // subobjects (but not its mutable subobjects) [are] considered to start
3707 // within e.
3708 if (MutableSubobject || Base != Info.EvaluatingDecl)
3709 return false;
3710 // FIXME: We can meaningfully extend this to cover non-const objects, but
3711 // we will need special handling: we should be able to access only
3712 // subobjects of such objects that are themselves declared const.
3713 QualType T = getType(Base);
3714 return T.isConstQualified() || T->isReferenceType();
3715 }
3716
3717 llvm_unreachable("unknown evaluating decl kind");
3718}
3719
3720static bool CheckArraySize(EvalInfo &Info, const ConstantArrayType *CAT,
3721 SourceLocation CallLoc = {}) {
3722 return Info.CheckArraySize(
3723 CAT->getSizeExpr() ? CAT->getSizeExpr()->getBeginLoc() : CallLoc,
3724 CAT->getNumAddressingBits(Info.Ctx), CAT->getZExtSize(),
3725 /*Diag=*/true);
3726}
3727
3728static bool handleScalarCast(EvalInfo &Info, const FPOptions FPO, const Expr *E,
3729 QualType SourceTy, QualType DestTy,
3730 APValue const &Original, APValue &Result) {
3731 // boolean must be checked before integer
3732 // since IsIntegerType() is true for bool
3733 if (SourceTy->isBooleanType()) {
3734 if (DestTy->isBooleanType()) {
3735 Result = Original;
3736 return true;
3737 }
3738 if (DestTy->isIntegerType() || DestTy->isRealFloatingType()) {
3739 bool BoolResult;
3740 if (!HandleConversionToBool(Original, BoolResult))
3741 return false;
3742 uint64_t IntResult = BoolResult;
3743 QualType IntType = DestTy->isIntegerType()
3744 ? DestTy
3745 : Info.Ctx.getIntTypeForBitwidth(64, false);
3746 Result = APValue(Info.Ctx.MakeIntValue(IntResult, IntType));
3747 }
3748 if (DestTy->isRealFloatingType()) {
3749 APValue Result2 = APValue(APFloat(0.0));
3750 if (!HandleIntToFloatCast(Info, E, FPO,
3751 Info.Ctx.getIntTypeForBitwidth(64, false),
3752 Result.getInt(), DestTy, Result2.getFloat()))
3753 return false;
3754 Result = std::move(Result2);
3755 }
3756 return true;
3757 }
3758 if (SourceTy->isIntegerType()) {
3759 if (DestTy->isRealFloatingType()) {
3760 Result = APValue(APFloat(0.0));
3761 return HandleIntToFloatCast(Info, E, FPO, SourceTy, Original.getInt(),
3762 DestTy, Result.getFloat());
3763 }
3764 if (DestTy->isBooleanType()) {
3765 bool BoolResult;
3766 if (!HandleConversionToBool(Original, BoolResult))
3767 return false;
3768 uint64_t IntResult = BoolResult;
3769 Result = APValue(Info.Ctx.MakeIntValue(IntResult, DestTy));
3770 return true;
3771 }
3772 if (DestTy->isIntegerType()) {
3773 Result = APValue(
3774 HandleIntToIntCast(Info, E, DestTy, SourceTy, Original.getInt()));
3775 return true;
3776 }
3777 } else if (SourceTy->isRealFloatingType()) {
3778 if (DestTy->isRealFloatingType()) {
3779 Result = Original;
3780 return HandleFloatToFloatCast(Info, E, SourceTy, DestTy,
3781 Result.getFloat());
3782 }
3783 if (DestTy->isBooleanType()) {
3784 bool BoolResult;
3785 if (!HandleConversionToBool(Original, BoolResult))
3786 return false;
3787 uint64_t IntResult = BoolResult;
3788 Result = APValue(Info.Ctx.MakeIntValue(IntResult, DestTy));
3789 return true;
3790 }
3791 if (DestTy->isIntegerType()) {
3792 Result = APValue(APSInt());
3793 return HandleFloatToIntCast(Info, E, SourceTy, Original.getFloat(),
3794 DestTy, Result.getInt());
3795 }
3796 }
3797
3798 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3799 return false;
3800}
3801
3802// do the heavy lifting for casting to aggregate types
3803// because we have to deal with bitfields specially
3804static bool constructAggregate(EvalInfo &Info, const FPOptions FPO,
3805 const Expr *E, APValue &Result,
3806 QualType ResultType,
3807 SmallVectorImpl<APValue> &Elements,
3808 SmallVectorImpl<QualType> &ElTypes) {
3809
3811 {&Result, ResultType, 0}};
3812
3813 unsigned ElI = 0;
3814 while (!WorkList.empty() && ElI < Elements.size()) {
3815 auto [Res, Type, BitWidth] = WorkList.pop_back_val();
3816
3817 if (Type->isRealFloatingType()) {
3818 if (!handleScalarCast(Info, FPO, E, ElTypes[ElI], Type, Elements[ElI],
3819 *Res))
3820 return false;
3821 ElI++;
3822 continue;
3823 }
3824 if (Type->isIntegerType()) {
3825 if (!handleScalarCast(Info, FPO, E, ElTypes[ElI], Type, Elements[ElI],
3826 *Res))
3827 return false;
3828 if (BitWidth > 0) {
3829 if (!Res->isInt())
3830 return false;
3831 APSInt &Int = Res->getInt();
3832 unsigned OldBitWidth = Int.getBitWidth();
3833 unsigned NewBitWidth = BitWidth;
3834 if (NewBitWidth < OldBitWidth)
3835 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
3836 }
3837 ElI++;
3838 continue;
3839 }
3840 if (Type->isVectorType()) {
3841 QualType ElTy = Type->castAs<VectorType>()->getElementType();
3842 unsigned NumEl = Type->castAs<VectorType>()->getNumElements();
3843 SmallVector<APValue> Vals(NumEl);
3844 for (unsigned I = 0; I < NumEl; ++I) {
3845 if (!handleScalarCast(Info, FPO, E, ElTypes[ElI], ElTy, Elements[ElI],
3846 Vals[I]))
3847 return false;
3848 ElI++;
3849 }
3850 *Res = APValue(Vals.data(), NumEl);
3851 continue;
3852 }
3853 if (Type->isConstantArrayType()) {
3854 QualType ElTy = cast<ConstantArrayType>(Info.Ctx.getAsArrayType(Type))
3855 ->getElementType();
3856 uint64_t Size =
3857 cast<ConstantArrayType>(Info.Ctx.getAsArrayType(Type))->getZExtSize();
3858 *Res = APValue(APValue::UninitArray(), Size, Size);
3859 for (int64_t I = Size - 1; I > -1; --I)
3860 WorkList.emplace_back(&Res->getArrayInitializedElt(I), ElTy, 0u);
3861 continue;
3862 }
3863 if (Type->isRecordType()) {
3864 const RecordDecl *RD = Type->getAsRecordDecl();
3865
3866 unsigned NumBases = 0;
3867 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
3868 NumBases = CXXRD->getNumBases();
3869
3870 *Res = APValue(APValue::UninitStruct(), NumBases, RD->getNumFields());
3871
3873 // we need to traverse backwards
3874 // Visit the base classes.
3875 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3876 if (CXXRD->getNumBases() > 0) {
3877 assert(CXXRD->getNumBases() == 1);
3878 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[0];
3879 ReverseList.emplace_back(&Res->getStructBase(0), BS.getType(), 0u);
3880 }
3881 }
3882
3883 // Visit the fields.
3884 for (FieldDecl *FD : RD->fields()) {
3885 unsigned FDBW = 0;
3886 if (FD->isUnnamedBitField())
3887 continue;
3888 if (FD->isBitField()) {
3889 FDBW = FD->getBitWidthValue();
3890 }
3891
3892 ReverseList.emplace_back(&Res->getStructField(FD->getFieldIndex()),
3893 FD->getType(), FDBW);
3894 }
3895
3896 std::reverse(ReverseList.begin(), ReverseList.end());
3897 llvm::append_range(WorkList, ReverseList);
3898 continue;
3899 }
3900 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3901 return false;
3902 }
3903 return true;
3904}
3905
3906static bool handleElementwiseCast(EvalInfo &Info, const Expr *E,
3907 const FPOptions FPO,
3908 SmallVectorImpl<APValue> &Elements,
3909 SmallVectorImpl<QualType> &SrcTypes,
3910 SmallVectorImpl<QualType> &DestTypes,
3911 SmallVectorImpl<APValue> &Results) {
3912
3913 assert((Elements.size() == SrcTypes.size()) &&
3914 (Elements.size() == DestTypes.size()));
3915
3916 for (unsigned I = 0, ESz = Elements.size(); I < ESz; ++I) {
3917 APValue Original = Elements[I];
3918 QualType SourceTy = SrcTypes[I];
3919 QualType DestTy = DestTypes[I];
3920
3921 if (!handleScalarCast(Info, FPO, E, SourceTy, DestTy, Original, Results[I]))
3922 return false;
3923 }
3924 return true;
3925}
3926
3927static unsigned elementwiseSize(EvalInfo &Info, QualType BaseTy) {
3928
3929 SmallVector<QualType> WorkList = {BaseTy};
3930
3931 unsigned Size = 0;
3932 while (!WorkList.empty()) {
3933 QualType Type = WorkList.pop_back_val();
3935 Type->isBooleanType()) {
3936 ++Size;
3937 continue;
3938 }
3939 if (Type->isVectorType()) {
3940 unsigned NumEl = Type->castAs<VectorType>()->getNumElements();
3941 Size += NumEl;
3942 continue;
3943 }
3944 if (Type->isConstantMatrixType()) {
3945 unsigned NumEl =
3946 Type->castAs<ConstantMatrixType>()->getNumElementsFlattened();
3947 Size += NumEl;
3948 continue;
3949 }
3950 if (Type->isConstantArrayType()) {
3951 QualType ElTy = cast<ConstantArrayType>(Info.Ctx.getAsArrayType(Type))
3952 ->getElementType();
3953 uint64_t ArrSize =
3954 cast<ConstantArrayType>(Info.Ctx.getAsArrayType(Type))->getZExtSize();
3955 for (uint64_t I = 0; I < ArrSize; ++I) {
3956 WorkList.push_back(ElTy);
3957 }
3958 continue;
3959 }
3960 if (Type->isRecordType()) {
3961 const RecordDecl *RD = Type->getAsRecordDecl();
3962
3963 // Visit the base classes.
3964 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3965 if (CXXRD->getNumBases() > 0) {
3966 assert(CXXRD->getNumBases() == 1);
3967 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[0];
3968 WorkList.push_back(BS.getType());
3969 }
3970 }
3971
3972 // visit the fields.
3973 for (FieldDecl *FD : RD->fields()) {
3974 if (FD->isUnnamedBitField())
3975 continue;
3976 WorkList.push_back(FD->getType());
3977 }
3978 continue;
3979 }
3980 }
3981 return Size;
3982}
3983
3984static bool hlslAggSplatHelper(EvalInfo &Info, const Expr *E, APValue &SrcVal,
3985 QualType &SrcTy) {
3986 SrcTy = E->getType();
3987
3988 if (!Evaluate(SrcVal, Info, E))
3989 return false;
3990
3991 assert((SrcVal.isFloat() || SrcVal.isInt() ||
3992 (SrcVal.isVector() && SrcVal.getVectorLength() == 1)) &&
3993 "Not a valid HLSLAggregateSplatCast.");
3994
3995 if (SrcVal.isVector()) {
3996 assert(SrcTy->isVectorType() && "Type mismatch.");
3997 SrcTy = SrcTy->castAs<VectorType>()->getElementType();
3998 SrcVal = SrcVal.getVectorElt(0);
3999 }
4000 if (SrcVal.isMatrix()) {
4001 assert(SrcTy->isConstantMatrixType() && "Type mismatch.");
4002 SrcTy = SrcTy->castAs<ConstantMatrixType>()->getElementType();
4003 SrcVal = SrcVal.getMatrixElt(0, 0);
4004 }
4005 return true;
4006}
4007
4008static bool flattenAPValue(EvalInfo &Info, const Expr *E, APValue Value,
4009 QualType BaseTy, SmallVectorImpl<APValue> &Elements,
4010 SmallVectorImpl<QualType> &Types, unsigned Size) {
4011
4012 SmallVector<std::pair<APValue, QualType>> WorkList = {{Value, BaseTy}};
4013 unsigned Populated = 0;
4014 while (!WorkList.empty() && Populated < Size) {
4015 auto [Work, Type] = WorkList.pop_back_val();
4016
4017 if (Work.isFloat() || Work.isInt()) {
4018 Elements.push_back(Work);
4019 Types.push_back(Type);
4020 Populated++;
4021 continue;
4022 }
4023 if (Work.isVector()) {
4024 assert(Type->isVectorType() && "Type mismatch.");
4025 QualType ElTy = Type->castAs<VectorType>()->getElementType();
4026 for (unsigned I = 0; I < Work.getVectorLength() && Populated < Size;
4027 I++) {
4028 Elements.push_back(Work.getVectorElt(I));
4029 Types.push_back(ElTy);
4030 Populated++;
4031 }
4032 continue;
4033 }
4034 if (Work.isMatrix()) {
4035 assert(Type->isConstantMatrixType() && "Type mismatch.");
4036 const auto *MT = Type->castAs<ConstantMatrixType>();
4037 QualType ElTy = MT->getElementType();
4038 // Matrix elements are flattened in row-major order.
4039 for (unsigned Row = 0; Row < Work.getMatrixNumRows() && Populated < Size;
4040 Row++) {
4041 for (unsigned Col = 0;
4042 Col < Work.getMatrixNumColumns() && Populated < Size; Col++) {
4043 Elements.push_back(Work.getMatrixElt(Row, Col));
4044 Types.push_back(ElTy);
4045 Populated++;
4046 }
4047 }
4048 continue;
4049 }
4050 if (Work.isArray()) {
4051 assert(Type->isConstantArrayType() && "Type mismatch.");
4052 QualType ElTy = cast<ConstantArrayType>(Info.Ctx.getAsArrayType(Type))
4053 ->getElementType();
4054 for (int64_t I = Work.getArraySize() - 1; I > -1; --I) {
4055 WorkList.emplace_back(Work.getArrayInitializedElt(I), ElTy);
4056 }
4057 continue;
4058 }
4059
4060 if (Work.isStruct()) {
4061 assert(Type->isRecordType() && "Type mismatch.");
4062
4063 const RecordDecl *RD = Type->getAsRecordDecl();
4064
4066 // Visit the fields.
4067 for (FieldDecl *FD : RD->fields()) {
4068 if (FD->isUnnamedBitField())
4069 continue;
4070 ReverseList.emplace_back(Work.getStructField(FD->getFieldIndex()),
4071 FD->getType());
4072 }
4073
4074 std::reverse(ReverseList.begin(), ReverseList.end());
4075 llvm::append_range(WorkList, ReverseList);
4076
4077 // Visit the base classes.
4078 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
4079 if (CXXRD->getNumBases() > 0) {
4080 assert(CXXRD->getNumBases() == 1);
4081 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[0];
4082 const APValue &Base = Work.getStructBase(0);
4083
4084 // Can happen in error cases.
4085 if (!Base.isStruct())
4086 return false;
4087
4088 WorkList.emplace_back(Base, BS.getType());
4089 }
4090 }
4091 continue;
4092 }
4093 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
4094 return false;
4095 }
4096 return true;
4097}
4098
4099namespace {
4100/// A handle to a complete object (an object that is not a subobject of
4101/// another object).
4102struct CompleteObject {
4103 /// The identity of the object.
4104 APValue::LValueBase Base;
4105 /// The value of the complete object.
4106 APValue *Value;
4107 /// The type of the complete object.
4108 QualType Type;
4109
4110 CompleteObject() : Value(nullptr) {}
4111 CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
4112 : Base(Base), Value(Value), Type(Type) {}
4113
4114 bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const {
4115 // If this isn't a "real" access (eg, if it's just accessing the type
4116 // info), allow it. We assume the type doesn't change dynamically for
4117 // subobjects of constexpr objects (even though we'd hit UB here if it
4118 // did). FIXME: Is this right?
4119 if (!isAnyAccess(AK))
4120 return true;
4121
4122 // In C++14 onwards, it is permitted to read a mutable member whose
4123 // lifetime began within the evaluation.
4124 // FIXME: Should we also allow this in C++11?
4125 if (!Info.getLangOpts().CPlusPlus14 &&
4126 AK != AccessKinds::AK_IsWithinLifetime)
4127 return false;
4128 return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);
4129 }
4130
4131 explicit operator bool() const { return !Type.isNull(); }
4132};
4133} // end anonymous namespace
4134
4135static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
4136 bool IsMutable = false) {
4137 // C++ [basic.type.qualifier]p1:
4138 // - A const object is an object of type const T or a non-mutable subobject
4139 // of a const object.
4140 if (ObjType.isConstQualified() && !IsMutable)
4141 SubobjType.addConst();
4142 // - A volatile object is an object of type const T or a subobject of a
4143 // volatile object.
4144 if (ObjType.isVolatileQualified())
4145 SubobjType.addVolatile();
4146 return SubobjType;
4147}
4148
4149/// Find the designated sub-object of an rvalue.
4150template <typename SubobjectHandler>
4151static typename SubobjectHandler::result_type
4152findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
4153 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
4154 if (Sub.Invalid)
4155 // A diagnostic will have already been produced.
4156 return handler.failed();
4157 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
4158 if (Info.getLangOpts().CPlusPlus11)
4159 Info.FFDiag(E, Sub.isOnePastTheEnd()
4160 ? diag::note_constexpr_access_past_end
4161 : diag::note_constexpr_access_unsized_array)
4162 << handler.AccessKind;
4163 else
4164 Info.FFDiag(E);
4165 return handler.failed();
4166 }
4167
4168 APValue *O = Obj.Value;
4169 QualType ObjType = Obj.Type;
4170 const FieldDecl *LastField = nullptr;
4171 const FieldDecl *VolatileField = nullptr;
4172
4173 // Walk the designator's path to find the subobject.
4174 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
4175 // Reading an indeterminate value is undefined, but assigning over one is OK.
4176 if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) ||
4177 (O->isIndeterminate() &&
4178 !isValidIndeterminateAccess(handler.AccessKind))) {
4179 // Object has ended lifetime.
4180 // If I is non-zero, some subobject (member or array element) of a
4181 // complete object has ended its lifetime, so this is valid for
4182 // IsWithinLifetime, resulting in false.
4183 if (I != 0 && handler.AccessKind == AK_IsWithinLifetime)
4184 return false;
4185 if (!Info.checkingPotentialConstantExpression()) {
4186 Info.FFDiag(E, diag::note_constexpr_access_uninit)
4187 << handler.AccessKind << O->isIndeterminate()
4188 << E->getSourceRange();
4189 NoteLValueLocation(Info, Obj.Base);
4190 }
4191 return handler.failed();
4192 }
4193
4194 // C++ [class.ctor]p5, C++ [class.dtor]p5:
4195 // const and volatile semantics are not applied on an object under
4196 // {con,de}struction.
4197 if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
4198 ObjType->isRecordType() &&
4199 Info.isEvaluatingCtorDtor(
4200 Obj.Base, ArrayRef(Sub.Entries.begin(), Sub.Entries.begin() + I)) !=
4201 ConstructionPhase::None) {
4202 ObjType = Info.Ctx.getCanonicalType(ObjType);
4203 ObjType.removeLocalConst();
4204 ObjType.removeLocalVolatile();
4205 }
4206
4207 // If this is our last pass, check that the final object type is OK.
4208 if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
4209 // Accesses to volatile objects are prohibited.
4210 if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
4211 if (Info.getLangOpts().CPlusPlus) {
4212 int DiagKind;
4213 SourceLocation Loc;
4214 const NamedDecl *Decl = nullptr;
4215 if (VolatileField) {
4216 DiagKind = 2;
4217 Loc = VolatileField->getLocation();
4218 Decl = VolatileField;
4219 } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
4220 DiagKind = 1;
4221 Loc = VD->getLocation();
4222 Decl = VD;
4223 } else {
4224 DiagKind = 0;
4225 if (auto *E = Obj.Base.dyn_cast<const Expr *>())
4226 Loc = E->getExprLoc();
4227 }
4228 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
4229 << handler.AccessKind << DiagKind << Decl;
4230 Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
4231 } else {
4232 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
4233 }
4234 return handler.failed();
4235 }
4236
4237 // If we are reading an object of class type, there may still be more
4238 // things we need to check: if there are any mutable subobjects, we
4239 // cannot perform this read. (This only happens when performing a trivial
4240 // copy or assignment.)
4241 if (ObjType->isRecordType() &&
4242 !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
4243 diagnoseMutableFields(Info, E, handler.AccessKind, ObjType))
4244 return handler.failed();
4245 }
4246
4247 if (I == N) {
4248 if (!handler.found(*O, ObjType, Obj.Base))
4249 return false;
4250
4251 // If we modified a bit-field, truncate it to the right width.
4252 if (isModification(handler.AccessKind) &&
4253 LastField && LastField->isBitField() &&
4254 !truncateBitfieldValue(Info, E, *O, LastField))
4255 return false;
4256
4257 return true;
4258 }
4259
4260 LastField = nullptr;
4261 if (ObjType->isArrayType()) {
4262 // Next subobject is an array element.
4263 const ArrayType *AT = Info.Ctx.getAsArrayType(ObjType);
4265 "vla in literal type?");
4266 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
4267 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT);
4268 CAT && CAT->getSize().ule(Index)) {
4269 // Note, it should not be possible to form a pointer with a valid
4270 // designator which points more than one past the end of the array.
4271 if (Info.getLangOpts().CPlusPlus11)
4272 Info.FFDiag(E, diag::note_constexpr_access_past_end)
4273 << handler.AccessKind;
4274 else
4275 Info.FFDiag(E);
4276 return handler.failed();
4277 }
4278
4279 ObjType = AT->getElementType();
4280
4281 if (O->getArrayInitializedElts() > Index)
4282 O = &O->getArrayInitializedElt(Index);
4283 else if (!isRead(handler.AccessKind)) {
4284 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT);
4285 CAT && !CheckArraySize(Info, CAT, E->getExprLoc()))
4286 return handler.failed();
4287
4288 expandArray(*O, Index);
4289 O = &O->getArrayInitializedElt(Index);
4290 } else
4291 O = &O->getArrayFiller();
4292 } else if (ObjType->isAnyComplexType()) {
4293 // Next subobject is a complex number.
4294 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
4295 if (Index > 1) {
4296 if (Info.getLangOpts().CPlusPlus11)
4297 Info.FFDiag(E, diag::note_constexpr_access_past_end)
4298 << handler.AccessKind;
4299 else
4300 Info.FFDiag(E);
4301 return handler.failed();
4302 }
4303
4304 ObjType = getSubobjectType(
4305 ObjType, ObjType->castAs<ComplexType>()->getElementType());
4306
4307 assert(I == N - 1 && "extracting subobject of scalar?");
4308 if (O->isComplexInt()) {
4309 return handler.found(Index ? O->getComplexIntImag()
4310 : O->getComplexIntReal(), ObjType);
4311 } else {
4312 assert(O->isComplexFloat());
4313 return handler.found(Index ? O->getComplexFloatImag()
4314 : O->getComplexFloatReal(), ObjType);
4315 }
4316 } else if (const auto *VT = ObjType->getAs<VectorType>()) {
4317 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
4318 unsigned NumElements = VT->getNumElements();
4319 if (Index == NumElements) {
4320 if (Info.getLangOpts().CPlusPlus11)
4321 Info.FFDiag(E, diag::note_constexpr_access_past_end)
4322 << handler.AccessKind;
4323 else
4324 Info.FFDiag(E);
4325 return handler.failed();
4326 }
4327
4328 if (Index > NumElements) {
4329 Info.CCEDiag(E, diag::note_constexpr_array_index)
4330 << Index << /*array*/ 0 << NumElements;
4331 return handler.failed();
4332 }
4333
4334 ObjType = VT->getElementType();
4335 assert(I == N - 1 && "extracting subobject of scalar?");
4336
4337 if (O->isIndeterminate()) {
4338 if (isRead(handler.AccessKind)) {
4339 Info.FFDiag(E);
4340 return handler.failed();
4341 }
4342 expandVector(*O, NumElements);
4343 }
4344 assert(O->isVector() && "unexpected object during vector element access");
4345 return handler.found(O->getVectorElt(Index), ObjType, Obj.Base);
4346 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
4347 if (Field->isMutable() &&
4348 !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) {
4349 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
4350 << handler.AccessKind << Field;
4351 Info.Note(Field->getLocation(), diag::note_declared_at);
4352 return handler.failed();
4353 }
4354
4355 // Next subobject is a class, struct or union field.
4356 RecordDecl *RD = ObjType->castAsCanonical<RecordType>()->getDecl();
4357 if (RD->isUnion()) {
4358 const FieldDecl *UnionField = O->getUnionField();
4359 if (!UnionField ||
4360 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
4361 if (I == N - 1 && handler.AccessKind == AK_Construct) {
4362 // Placement new onto an inactive union member makes it active.
4363 O->setUnion(Field, APValue());
4364 } else {
4365 // Pointer to/into inactive union member: Not within lifetime
4366 if (handler.AccessKind == AK_IsWithinLifetime)
4367 return false;
4368 // FIXME: If O->getUnionValue() is absent, report that there's no
4369 // active union member rather than reporting the prior active union
4370 // member. We'll need to fix nullptr_t to not use APValue() as its
4371 // representation first.
4372 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
4373 << handler.AccessKind << Field << !UnionField << UnionField;
4374 return handler.failed();
4375 }
4376 }
4377 O = &O->getUnionValue();
4378 } else
4379 O = &O->getStructField(Field->getFieldIndex());
4380
4381 ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
4382 LastField = Field;
4383 if (Field->getType().isVolatileQualified())
4384 VolatileField = Field;
4385 } else {
4386 // Next subobject is a base class.
4387 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
4388 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
4389 O = &O->getStructBase(getBaseIndex(Derived, Base));
4390
4391 ObjType = getSubobjectType(ObjType, Info.Ctx.getCanonicalTagType(Base));
4392 }
4393 }
4394}
4395
4396namespace {
4397struct ExtractSubobjectHandler {
4398 EvalInfo &Info;
4399 const Expr *E;
4400 APValue &Result;
4401 const AccessKinds AccessKind;
4402
4403 typedef bool result_type;
4404 bool failed() { return false; }
4405 bool found(APValue &Subobj, QualType SubobjType, APValue::LValueBase Base) {
4406 Result = Subobj;
4407 if (AccessKind == AK_ReadObjectRepresentation)
4408 return true;
4409 return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
4410 }
4411 bool found(APSInt &Value, QualType SubobjType) {
4412 Result = APValue(Value);
4413 return true;
4414 }
4415 bool found(APFloat &Value, QualType SubobjType) {
4416 Result = APValue(Value);
4417 return true;
4418 }
4419};
4420} // end anonymous namespace
4421
4422/// Extract the designated sub-object of an rvalue.
4423static bool extractSubobject(EvalInfo &Info, const Expr *E,
4424 const CompleteObject &Obj,
4425 const SubobjectDesignator &Sub, APValue &Result,
4426 AccessKinds AK = AK_Read) {
4427 assert(AK == AK_Read || AK == AK_ReadObjectRepresentation);
4428 ExtractSubobjectHandler Handler = {Info, E, Result, AK};
4429 return findSubobject(Info, E, Obj, Sub, Handler);
4430}
4431
4432namespace {
4433struct ModifySubobjectHandler {
4434 EvalInfo &Info;
4435 APValue &NewVal;
4436 const Expr *E;
4437
4438 typedef bool result_type;
4439 static const AccessKinds AccessKind = AK_Assign;
4440
4441 bool checkConst(QualType QT) {
4442 // Assigning to a const object has undefined behavior.
4443 if (QT.isConstQualified()) {
4444 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4445 return false;
4446 }
4447 return true;
4448 }
4449
4450 bool failed() { return false; }
4451 bool found(APValue &Subobj, QualType SubobjType, APValue::LValueBase Base) {
4452 if (!checkConst(SubobjType))
4453 return false;
4454 // We've been given ownership of NewVal, so just swap it in.
4455 Subobj.swap(NewVal);
4456 return true;
4457 }
4458 bool found(APSInt &Value, QualType SubobjType) {
4459 if (!checkConst(SubobjType))
4460 return false;
4461 if (!NewVal.isInt()) {
4462 // Maybe trying to write a cast pointer value into a complex?
4463 Info.FFDiag(E);
4464 return false;
4465 }
4466 Value = NewVal.getInt();
4467 return true;
4468 }
4469 bool found(APFloat &Value, QualType SubobjType) {
4470 if (!checkConst(SubobjType))
4471 return false;
4472 Value = NewVal.getFloat();
4473 return true;
4474 }
4475};
4476} // end anonymous namespace
4477
4478const AccessKinds ModifySubobjectHandler::AccessKind;
4479
4480/// Update the designated sub-object of an rvalue to the given value.
4481static bool modifySubobject(EvalInfo &Info, const Expr *E,
4482 const CompleteObject &Obj,
4483 const SubobjectDesignator &Sub,
4484 APValue &NewVal) {
4485 ModifySubobjectHandler Handler = { Info, NewVal, E };
4486 return findSubobject(Info, E, Obj, Sub, Handler);
4487}
4488
4489/// Find the position where two subobject designators diverge, or equivalently
4490/// the length of the common initial subsequence.
4491static unsigned FindDesignatorMismatch(QualType ObjType,
4492 const SubobjectDesignator &A,
4493 const SubobjectDesignator &B,
4494 bool &WasArrayIndex) {
4495 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
4496 for (/**/; I != N; ++I) {
4497 if (!ObjType.isNull() &&
4498 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
4499 // Next subobject is an array element.
4500 if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
4501 WasArrayIndex = true;
4502 return I;
4503 }
4504 if (ObjType->isAnyComplexType())
4505 ObjType = ObjType->castAs<ComplexType>()->getElementType();
4506 else
4507 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
4508 } else {
4509 if (A.Entries[I].getAsBaseOrMember() !=
4510 B.Entries[I].getAsBaseOrMember()) {
4511 WasArrayIndex = false;
4512 return I;
4513 }
4514 if (const FieldDecl *FD = getAsField(A.Entries[I]))
4515 // Next subobject is a field.
4516 ObjType = FD->getType();
4517 else
4518 // Next subobject is a base class.
4519 ObjType = QualType();
4520 }
4521 }
4522 WasArrayIndex = false;
4523 return I;
4524}
4525
4526/// Determine whether the given subobject designators refer to elements of the
4527/// same array object.
4529 const SubobjectDesignator &A,
4530 const SubobjectDesignator &B) {
4531 if (A.Entries.size() != B.Entries.size())
4532 return false;
4533
4534 bool IsArray = A.MostDerivedIsArrayElement;
4535 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
4536 // A is a subobject of the array element.
4537 return false;
4538
4539 // If A (and B) designates an array element, the last entry will be the array
4540 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
4541 // of length 1' case, and the entire path must match.
4542 bool WasArrayIndex;
4543 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
4544 return CommonLength >= A.Entries.size() - IsArray;
4545}
4546
4547/// Find the complete object to which an LValue refers.
4548static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
4549 AccessKinds AK, const LValue &LVal,
4550 QualType LValType) {
4551 if (LVal.InvalidBase) {
4552 Info.FFDiag(E);
4553 return CompleteObject();
4554 }
4555
4556 if (!LVal.Base) {
4558 Info.FFDiag(E, diag::note_constexpr_dereferencing_null);
4559 else
4560 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
4561 return CompleteObject();
4562 }
4563
4564 CallStackFrame *Frame = nullptr;
4565 unsigned Depth = 0;
4566 if (LVal.getLValueCallIndex()) {
4567 std::tie(Frame, Depth) =
4568 Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
4569 if (!Frame) {
4570 Info.FFDiag(E, diag::note_constexpr_access_uninit, 1)
4571 << AK << /*Indeterminate=*/false << E->getSourceRange();
4572 NoteLValueLocation(Info, LVal.Base);
4573 return CompleteObject();
4574 }
4575 }
4576
4577 bool IsAccess = isAnyAccess(AK);
4578
4579 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
4580 // is not a constant expression (even if the object is non-volatile). We also
4581 // apply this rule to C++98, in order to conform to the expected 'volatile'
4582 // semantics.
4583 if (isFormalAccess(AK) && LValType.isVolatileQualified()) {
4584 if (Info.getLangOpts().CPlusPlus)
4585 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
4586 << AK << LValType;
4587 else
4588 Info.FFDiag(E);
4589 return CompleteObject();
4590 }
4591
4592 // Compute value storage location and type of base object.
4593 APValue *BaseVal = nullptr;
4594 QualType BaseType = getType(LVal.Base);
4595
4596 if (Info.getLangOpts().CPlusPlus14 && LVal.Base == Info.EvaluatingDecl &&
4597 lifetimeStartedInEvaluation(Info, LVal.Base)) {
4598 // This is the object whose initializer we're evaluating, so its lifetime
4599 // started in the current evaluation.
4600 BaseVal = Info.EvaluatingDeclValue;
4601 } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) {
4602 // Allow reading from a GUID declaration.
4603 if (auto *GD = dyn_cast<MSGuidDecl>(D)) {
4604 if (isModification(AK)) {
4605 // All the remaining cases do not permit modification of the object.
4606 Info.FFDiag(E, diag::note_constexpr_modify_global);
4607 return CompleteObject();
4608 }
4609 APValue &V = GD->getAsAPValue();
4610 if (V.isAbsent()) {
4611 Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
4612 << GD->getType();
4613 return CompleteObject();
4614 }
4615 return CompleteObject(LVal.Base, &V, GD->getType());
4616 }
4617
4618 // Allow reading the APValue from an UnnamedGlobalConstantDecl.
4619 if (auto *GCD = dyn_cast<UnnamedGlobalConstantDecl>(D)) {
4620 if (isModification(AK)) {
4621 Info.FFDiag(E, diag::note_constexpr_modify_global);
4622 return CompleteObject();
4623 }
4624 return CompleteObject(LVal.Base, const_cast<APValue *>(&GCD->getValue()),
4625 GCD->getType());
4626 }
4627
4628 // Allow reading from template parameter objects.
4629 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) {
4630 if (isModification(AK)) {
4631 Info.FFDiag(E, diag::note_constexpr_modify_global);
4632 return CompleteObject();
4633 }
4634 return CompleteObject(LVal.Base, const_cast<APValue *>(&TPO->getValue()),
4635 TPO->getType());
4636 }
4637
4638 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
4639 // In C++11, constexpr, non-volatile variables initialized with constant
4640 // expressions are constant expressions too. Inside constexpr functions,
4641 // parameters are constant expressions even if they're non-const.
4642 // In C++1y, objects local to a constant expression (those with a Frame) are
4643 // both readable and writable inside constant expressions.
4644 // In C, such things can also be folded, although they are not ICEs.
4645 const VarDecl *VD = dyn_cast<VarDecl>(D);
4646 if (VD) {
4647 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
4648 VD = VDef;
4649 }
4650 if (!VD || VD->isInvalidDecl()) {
4651 Info.FFDiag(E);
4652 return CompleteObject();
4653 }
4654
4655 bool IsConstant = BaseType.isConstant(Info.Ctx);
4656 bool ConstexprVar = false;
4657 if (const auto *VD = dyn_cast_if_present<VarDecl>(
4658 Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()))
4659 ConstexprVar = VD->isConstexpr();
4660
4661 // Unless we're looking at a local variable or argument in a constexpr call,
4662 // the variable we're reading must be const (unless we are binding to a
4663 // reference).
4664 if (AK != clang::AK_Dereference && !Frame) {
4665 if (IsAccess && isa<ParmVarDecl>(VD)) {
4666 // Access of a parameter that's not associated with a frame isn't going
4667 // to work out, but we can leave it to evaluateVarDeclInit to provide a
4668 // suitable diagnostic.
4669 } else if (Info.getLangOpts().CPlusPlus14 &&
4670 lifetimeStartedInEvaluation(Info, LVal.Base)) {
4671 // OK, we can read and modify an object if we're in the process of
4672 // evaluating its initializer, because its lifetime began in this
4673 // evaluation.
4674 } else if (isModification(AK)) {
4675 // All the remaining cases do not permit modification of the object.
4676 Info.FFDiag(E, diag::note_constexpr_modify_global);
4677 return CompleteObject();
4678 } else if (VD->isConstexpr()) {
4679 // OK, we can read this variable.
4680 } else if (Info.getLangOpts().C23 && ConstexprVar) {
4681 Info.FFDiag(E);
4682 return CompleteObject();
4683 } else if (BaseType->isIntegralOrEnumerationType()) {
4684 if (!IsConstant) {
4685 if (!IsAccess)
4686 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4687 if (Info.getLangOpts().CPlusPlus) {
4688 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
4689 Info.Note(VD->getLocation(), diag::note_declared_at);
4690 } else {
4691 Info.FFDiag(E);
4692 }
4693 return CompleteObject();
4694 }
4695 } else if (!IsAccess) {
4696 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4697 } else if ((IsConstant || BaseType->isReferenceType()) &&
4698 Info.checkingPotentialConstantExpression() &&
4699 BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) {
4700 // This variable might end up being constexpr. Don't diagnose it yet.
4701 } else if (IsConstant) {
4702 // Keep evaluating to see what we can do. In particular, we support
4703 // folding of const floating-point types, in order to make static const
4704 // data members of such types (supported as an extension) more useful.
4705 if (Info.getLangOpts().CPlusPlus) {
4706 Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11
4707 ? diag::note_constexpr_ltor_non_constexpr
4708 : diag::note_constexpr_ltor_non_integral, 1)
4709 << VD << BaseType;
4710 Info.Note(VD->getLocation(), diag::note_declared_at);
4711 } else {
4712 Info.CCEDiag(E);
4713 }
4714 } else {
4715 // Never allow reading a non-const value.
4716 if (Info.getLangOpts().CPlusPlus) {
4717 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
4718 ? diag::note_constexpr_ltor_non_constexpr
4719 : diag::note_constexpr_ltor_non_integral, 1)
4720 << VD << BaseType;
4721 Info.Note(VD->getLocation(), diag::note_declared_at);
4722 } else {
4723 Info.FFDiag(E);
4724 }
4725 return CompleteObject();
4726 }
4727 }
4728
4729 // When binding to a reference, the variable does not need to be constexpr
4730 // or have constant initalization.
4731 if (AK != clang::AK_Dereference &&
4732 !evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(),
4733 BaseVal))
4734 return CompleteObject();
4735 // If evaluateVarDeclInit sees a constexpr-unknown variable, it returns
4736 // a null BaseVal. Any constexpr-unknown variable seen here is an error:
4737 // we can't access a constexpr-unknown object.
4738 if (AK != clang::AK_Dereference && !BaseVal) {
4739 if (!Info.checkingPotentialConstantExpression()) {
4740 Info.FFDiag(E, diag::note_constexpr_access_unknown_variable, 1)
4741 << AK << VD;
4742 Info.Note(VD->getLocation(), diag::note_declared_at);
4743 }
4744 return CompleteObject();
4745 }
4746 } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) {
4747 std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
4748 if (!Alloc) {
4749 Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK;
4750 return CompleteObject();
4751 }
4752 return CompleteObject(LVal.Base, &(*Alloc)->Value,
4753 LVal.Base.getDynamicAllocType());
4754 }
4755 // When binding to a reference, the variable does not need to be
4756 // within its lifetime.
4757 else if (AK != clang::AK_Dereference) {
4758 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4759
4760 if (!Frame) {
4761 if (const MaterializeTemporaryExpr *MTE =
4762 dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
4763 assert(MTE->getStorageDuration() == SD_Static &&
4764 "should have a frame for a non-global materialized temporary");
4765
4766 // C++20 [expr.const]p4: [DR2126]
4767 // An object or reference is usable in constant expressions if it is
4768 // - a temporary object of non-volatile const-qualified literal type
4769 // whose lifetime is extended to that of a variable that is usable
4770 // in constant expressions
4771 //
4772 // C++20 [expr.const]p5:
4773 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
4774 // - a non-volatile glvalue that refers to an object that is usable
4775 // in constant expressions, or
4776 // - a non-volatile glvalue of literal type that refers to a
4777 // non-volatile object whose lifetime began within the evaluation
4778 // of E;
4779 //
4780 // C++11 misses the 'began within the evaluation of e' check and
4781 // instead allows all temporaries, including things like:
4782 // int &&r = 1;
4783 // int x = ++r;
4784 // constexpr int k = r;
4785 // Therefore we use the C++14-onwards rules in C++11 too.
4786 //
4787 // Note that temporaries whose lifetimes began while evaluating a
4788 // variable's constructor are not usable while evaluating the
4789 // corresponding destructor, not even if they're of const-qualified
4790 // types.
4791 if (!MTE->isUsableInConstantExpressions(Info.Ctx) &&
4792 !lifetimeStartedInEvaluation(Info, LVal.Base)) {
4793 if (!IsAccess)
4794 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4795 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
4796 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
4797 return CompleteObject();
4798 }
4799
4800 BaseVal = MTE->getOrCreateValue(false);
4801 assert(BaseVal && "got reference to unevaluated temporary");
4802 } else if (const CompoundLiteralExpr *CLE =
4803 dyn_cast_or_null<CompoundLiteralExpr>(Base)) {
4804 // According to GCC info page:
4805 //
4806 // 6.28 Compound Literals
4807 //
4808 // As an optimization, G++ sometimes gives array compound literals
4809 // longer lifetimes: when the array either appears outside a function or
4810 // has a const-qualified type. If foo and its initializer had elements
4811 // of type char *const rather than char *, or if foo were a global
4812 // variable, the array would have static storage duration. But it is
4813 // probably safest just to avoid the use of array compound literals in
4814 // C++ code.
4815 //
4816 // Obey that rule by checking constness for converted array types.
4817 if (QualType CLETy = CLE->getType(); CLETy->isArrayType() &&
4818 !LValType->isArrayType() &&
4819 !CLETy.isConstant(Info.Ctx)) {
4820 Info.FFDiag(E);
4821 Info.Note(CLE->getExprLoc(), diag::note_declared_at);
4822 return CompleteObject();
4823 }
4824
4825 BaseVal = &CLE->getStaticValue();
4826 } else {
4827 if (!IsAccess)
4828 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4829 APValue Val;
4830 LVal.moveInto(Val);
4831 Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
4832 << AK
4833 << Val.getAsString(Info.Ctx,
4834 Info.Ctx.getLValueReferenceType(LValType));
4835 NoteLValueLocation(Info, LVal.Base);
4836 return CompleteObject();
4837 }
4838 } else if (AK != clang::AK_Dereference) {
4839 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
4840 assert(BaseVal && "missing value for temporary");
4841 }
4842 }
4843
4844 // In C++14, we can't safely access any mutable state when we might be
4845 // evaluating after an unmodeled side effect. Parameters are modeled as state
4846 // in the caller, but aren't visible once the call returns, so they can be
4847 // modified in a speculatively-evaluated call.
4848 //
4849 // FIXME: Not all local state is mutable. Allow local constant subobjects
4850 // to be read here (but take care with 'mutable' fields).
4851 unsigned VisibleDepth = Depth;
4852 if (llvm::isa_and_nonnull<ParmVarDecl>(
4853 LVal.Base.dyn_cast<const ValueDecl *>()))
4854 ++VisibleDepth;
4855 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
4856 Info.EvalStatus.HasSideEffects) ||
4857 (isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth))
4858 return CompleteObject();
4859
4860 return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
4861}
4862
4863/// Perform an lvalue-to-rvalue conversion on the given glvalue. This
4864/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
4865/// glvalue referred to by an entity of reference type.
4866///
4867/// \param Info - Information about the ongoing evaluation.
4868/// \param Conv - The expression for which we are performing the conversion.
4869/// Used for diagnostics.
4870/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
4871/// case of a non-class type).
4872/// \param LVal - The glvalue on which we are attempting to perform this action.
4873/// \param RVal - The produced value will be placed here.
4874/// \param WantObjectRepresentation - If true, we're looking for the object
4875/// representation rather than the value, and in particular,
4876/// there is no requirement that the result be fully initialized.
4877static bool
4879 const LValue &LVal, APValue &RVal,
4880 bool WantObjectRepresentation = false) {
4881 if (LVal.Designator.Invalid)
4882 return false;
4883
4884 // Check for special cases where there is no existing APValue to look at.
4885 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4886
4887 AccessKinds AK =
4888 WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;
4889
4890 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
4892 // Special-case character extraction so we don't have to construct an
4893 // APValue for the whole string.
4894 assert(LVal.Designator.Entries.size() <= 1 &&
4895 "Can only read characters from string literals");
4896 if (LVal.Designator.Entries.empty()) {
4897 // Fail for now for LValue to RValue conversion of an array.
4898 // (This shouldn't show up in C/C++, but it could be triggered by a
4899 // weird EvaluateAsRValue call from a tool.)
4900 Info.FFDiag(Conv);
4901 return false;
4902 }
4903 if (LVal.Designator.isOnePastTheEnd()) {
4904 if (Info.getLangOpts().CPlusPlus11)
4905 Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
4906 else
4907 Info.FFDiag(Conv);
4908 return false;
4909 }
4910 uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
4911 RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
4912 return true;
4913 }
4914 }
4915
4916 CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
4917 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
4918}
4919
4920static bool hlslElementwiseCastHelper(EvalInfo &Info, const Expr *E,
4921 QualType DestTy,
4922 SmallVectorImpl<APValue> &SrcVals,
4923 SmallVectorImpl<QualType> &SrcTypes) {
4924 APValue Val;
4925 if (!Evaluate(Val, Info, E))
4926 return false;
4927
4928 // must be dealing with a record
4929 if (Val.isLValue()) {
4930 LValue LVal;
4931 LVal.setFrom(Info.Ctx, Val);
4932 if (!handleLValueToRValueConversion(Info, E, E->getType(), LVal, Val))
4933 return false;
4934 }
4935
4936 unsigned NEls = elementwiseSize(Info, DestTy);
4937 // flatten the source
4938 if (!flattenAPValue(Info, E, Val, E->getType(), SrcVals, SrcTypes, NEls))
4939 return false;
4940
4941 return true;
4942}
4943
4944/// Perform an assignment of Val to LVal. Takes ownership of Val.
4945static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
4946 QualType LValType, APValue &Val) {
4947 if (LVal.Designator.Invalid)
4948 return false;
4949
4950 if (!Info.getLangOpts().CPlusPlus14) {
4951 Info.FFDiag(E);
4952 return false;
4953 }
4954
4955 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4956 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
4957}
4958
4959namespace {
4960struct CompoundAssignSubobjectHandler {
4961 EvalInfo &Info;
4962 const CompoundAssignOperator *E;
4963 QualType PromotedLHSType;
4965 const APValue &RHS;
4966
4967 static const AccessKinds AccessKind = AK_Assign;
4968
4969 typedef bool result_type;
4970
4971 bool checkConst(QualType QT) {
4972 // Assigning to a const object has undefined behavior.
4973 if (QT.isConstQualified()) {
4974 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4975 return false;
4976 }
4977 return true;
4978 }
4979
4980 bool failed() { return false; }
4981 bool found(APValue &Subobj, QualType SubobjType, APValue::LValueBase Base) {
4982 switch (Subobj.getKind()) {
4983 case APValue::Int:
4984 return found(Subobj.getInt(), SubobjType);
4985 case APValue::Float:
4986 return found(Subobj.getFloat(), SubobjType);
4989 // FIXME: Implement complex compound assignment.
4990 Info.FFDiag(E);
4991 return false;
4992 case APValue::LValue:
4993 return foundPointer(Subobj, SubobjType);
4994 case APValue::Vector:
4995 return foundVector(Subobj, SubobjType);
4997 Info.FFDiag(E, diag::note_constexpr_access_uninit)
4998 << /*read of=*/0 << /*uninitialized object=*/1
4999 << E->getLHS()->getSourceRange();
5000 NoteLValueLocation(Info, Base);
5001 return false;
5002 default:
5003 // FIXME: can this happen?
5004 Info.FFDiag(E);
5005 return false;
5006 }
5007 }
5008
5009 bool foundVector(APValue &Value, QualType SubobjType) {
5010 if (!checkConst(SubobjType))
5011 return false;
5012
5013 if (!SubobjType->isVectorType()) {
5014 Info.FFDiag(E);
5015 return false;
5016 }
5017 return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS);
5018 }
5019
5020 bool found(APSInt &Value, QualType SubobjType) {
5021 if (!checkConst(SubobjType))
5022 return false;
5023
5024 if (!SubobjType->isIntegerType()) {
5025 // We don't support compound assignment on integer-cast-to-pointer
5026 // values.
5027 Info.FFDiag(E);
5028 return false;
5029 }
5030
5031 if (RHS.isInt()) {
5032 APSInt LHS =
5033 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
5034 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
5035 return false;
5036 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
5037 return true;
5038 } else if (RHS.isFloat()) {
5039 const FPOptions FPO = E->getFPFeaturesInEffect(
5040 Info.Ctx.getLangOpts());
5041 APFloat FValue(0.0);
5042 return HandleIntToFloatCast(Info, E, FPO, SubobjType, Value,
5043 PromotedLHSType, FValue) &&
5044 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
5045 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
5046 Value);
5047 }
5048
5049 Info.FFDiag(E);
5050 return false;
5051 }
5052 bool found(APFloat &Value, QualType SubobjType) {
5053 return checkConst(SubobjType) &&
5054 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
5055 Value) &&
5056 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
5057 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
5058 }
5059 bool foundPointer(APValue &Subobj, QualType SubobjType) {
5060 if (!checkConst(SubobjType))
5061 return false;
5062
5063 QualType PointeeType;
5064 if (const PointerType *PT = SubobjType->getAs<PointerType>())
5065 PointeeType = PT->getPointeeType();
5066
5067 if (PointeeType.isNull() || !RHS.isInt() ||
5068 (Opcode != BO_Add && Opcode != BO_Sub)) {
5069 Info.FFDiag(E);
5070 return false;
5071 }
5072
5073 APSInt Offset = RHS.getInt();
5074 if (Opcode == BO_Sub)
5075 negateAsSigned(Offset);
5076
5077 LValue LVal;
5078 LVal.setFrom(Info.Ctx, Subobj);
5079 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
5080 return false;
5081 LVal.moveInto(Subobj);
5082 return true;
5083 }
5084};
5085} // end anonymous namespace
5086
5087const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
5088
5089/// Perform a compound assignment of LVal <op>= RVal.
5090static bool handleCompoundAssignment(EvalInfo &Info,
5091 const CompoundAssignOperator *E,
5092 const LValue &LVal, QualType LValType,
5093 QualType PromotedLValType,
5094 BinaryOperatorKind Opcode,
5095 const APValue &RVal) {
5096 if (LVal.Designator.Invalid)
5097 return false;
5098
5099 if (!Info.getLangOpts().CPlusPlus14) {
5100 Info.FFDiag(E);
5101 return false;
5102 }
5103
5104 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
5105 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
5106 RVal };
5107 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
5108}
5109
5110namespace {
5111struct IncDecSubobjectHandler {
5112 EvalInfo &Info;
5113 const UnaryOperator *E;
5115 APValue *Old;
5116
5117 typedef bool result_type;
5118
5119 bool checkConst(QualType QT) {
5120 // Assigning to a const object has undefined behavior.
5121 if (QT.isConstQualified()) {
5122 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
5123 return false;
5124 }
5125 return true;
5126 }
5127
5128 bool failed() { return false; }
5129 bool found(APValue &Subobj, QualType SubobjType, APValue::LValueBase Base) {
5130 // Stash the old value. Also clear Old, so we don't clobber it later
5131 // if we're post-incrementing a complex.
5132 if (Old) {
5133 *Old = Subobj;
5134 Old = nullptr;
5135 }
5136
5137 switch (Subobj.getKind()) {
5138 case APValue::Int:
5139 return found(Subobj.getInt(), SubobjType);
5140 case APValue::Float:
5141 return found(Subobj.getFloat(), SubobjType);
5143 return found(Subobj.getComplexIntReal(),
5144 SubobjType->castAs<ComplexType>()->getElementType()
5145 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
5147 return found(Subobj.getComplexFloatReal(),
5148 SubobjType->castAs<ComplexType>()->getElementType()
5149 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
5150 case APValue::LValue:
5151 return foundPointer(Subobj, SubobjType);
5152 default:
5153 // FIXME: can this happen?
5154 Info.FFDiag(E);
5155 return false;
5156 }
5157 }
5158 bool found(APSInt &Value, QualType SubobjType) {
5159 if (!checkConst(SubobjType))
5160 return false;
5161
5162 if (!SubobjType->isIntegerType()) {
5163 // We don't support increment / decrement on integer-cast-to-pointer
5164 // values.
5165 Info.FFDiag(E);
5166 return false;
5167 }
5168
5169 if (Old) *Old = APValue(Value);
5170
5171 // bool arithmetic promotes to int, and the conversion back to bool
5172 // doesn't reduce mod 2^n, so special-case it.
5173 if (SubobjType->isBooleanType()) {
5174 if (AccessKind == AK_Increment)
5175 Value = 1;
5176 else
5177 Value = !Value;
5178 return true;
5179 }
5180
5181 bool WasNegative = Value.isNegative();
5182 if (AccessKind == AK_Increment) {
5183 ++Value;
5184
5185 if (!WasNegative && Value.isNegative() && E->canOverflow() &&
5186 !SubobjType.isWrapType()) {
5187 APSInt ActualValue(Value, /*IsUnsigned*/true);
5188 return HandleOverflow(Info, E, ActualValue, SubobjType);
5189 }
5190 } else {
5191 --Value;
5192
5193 if (WasNegative && !Value.isNegative() && E->canOverflow() &&
5194 !SubobjType.isWrapType()) {
5195 unsigned BitWidth = Value.getBitWidth();
5196 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
5197 ActualValue.setBit(BitWidth);
5198 return HandleOverflow(Info, E, ActualValue, SubobjType);
5199 }
5200 }
5201 return true;
5202 }
5203 bool found(APFloat &Value, QualType SubobjType) {
5204 if (!checkConst(SubobjType))
5205 return false;
5206
5207 if (Old) *Old = APValue(Value);
5208
5209 APFloat One(Value.getSemantics(), 1);
5210 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
5211 APFloat::opStatus St;
5212 if (AccessKind == AK_Increment)
5213 St = Value.add(One, RM);
5214 else
5215 St = Value.subtract(One, RM);
5216 return checkFloatingPointResult(Info, E, St);
5217 }
5218 bool foundPointer(APValue &Subobj, QualType SubobjType) {
5219 if (!checkConst(SubobjType))
5220 return false;
5221
5222 QualType PointeeType;
5223 if (const PointerType *PT = SubobjType->getAs<PointerType>())
5224 PointeeType = PT->getPointeeType();
5225 else {
5226 Info.FFDiag(E);
5227 return false;
5228 }
5229
5230 LValue LVal;
5231 LVal.setFrom(Info.Ctx, Subobj);
5232 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
5233 AccessKind == AK_Increment ? 1 : -1))
5234 return false;
5235 LVal.moveInto(Subobj);
5236 return true;
5237 }
5238};
5239} // end anonymous namespace
5240
5241/// Perform an increment or decrement on LVal.
5242static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
5243 QualType LValType, bool IsIncrement, APValue *Old) {
5244 if (LVal.Designator.Invalid)
5245 return false;
5246
5247 if (!Info.getLangOpts().CPlusPlus14) {
5248 Info.FFDiag(E);
5249 return false;
5250 }
5251
5252 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
5253 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
5254 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
5255 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
5256}
5257
5258/// Build an lvalue for the object argument of a member function call.
5259static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
5260 LValue &This) {
5261 if (Object->getType()->isPointerType() && Object->isPRValue())
5262 return EvaluatePointer(Object, This, Info);
5263
5264 if (Object->isGLValue())
5265 return EvaluateLValue(Object, This, Info);
5266
5267 if (Object->getType()->isLiteralType(Info.Ctx))
5268 return EvaluateTemporary(Object, This, Info);
5269
5270 if (Object->getType()->isRecordType() && Object->isPRValue())
5271 return EvaluateTemporary(Object, This, Info);
5272
5273 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
5274 return false;
5275}
5276
5277/// HandleMemberPointerAccess - Evaluate a member access operation and build an
5278/// lvalue referring to the result.
5279///
5280/// \param Info - Information about the ongoing evaluation.
5281/// \param LV - An lvalue referring to the base of the member pointer.
5282/// \param RHS - The member pointer expression.
5283/// \param IncludeMember - Specifies whether the member itself is included in
5284/// the resulting LValue subobject designator. This is not possible when
5285/// creating a bound member function.
5286/// \return The field or method declaration to which the member pointer refers,
5287/// or 0 if evaluation fails.
5288static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
5289 QualType LVType,
5290 LValue &LV,
5291 const Expr *RHS,
5292 bool IncludeMember = true) {
5293 MemberPtr MemPtr;
5294 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
5295 return nullptr;
5296
5297 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
5298 // member value, the behavior is undefined.
5299 if (!MemPtr.getDecl()) {
5300 // FIXME: Specific diagnostic.
5301 Info.FFDiag(RHS);
5302 return nullptr;
5303 }
5304
5305 if (MemPtr.isDerivedMember()) {
5306 // This is a member of some derived class. Truncate LV appropriately.
5307 // The end of the derived-to-base path for the base object must match the
5308 // derived-to-base path for the member pointer.
5309 // C++23 [expr.mptr.oper]p4:
5310 // If the result of E1 is an object [...] whose most derived object does
5311 // not contain the member to which E2 refers, the behavior is undefined.
5312 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
5313 LV.Designator.Entries.size()) {
5314 Info.FFDiag(RHS);
5315 return nullptr;
5316 }
5317 unsigned PathLengthToMember =
5318 LV.Designator.Entries.size() - MemPtr.Path.size();
5319 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
5320 const CXXRecordDecl *LVDecl = getAsBaseClass(
5321 LV.Designator.Entries[PathLengthToMember + I]);
5322 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
5323 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
5324 Info.FFDiag(RHS);
5325 return nullptr;
5326 }
5327 }
5328 // MemPtr.Path only contains the base classes of the class directly
5329 // containing the member E2. It is still necessary to check that the class
5330 // directly containing the member E2 lies on the derived-to-base path of E1
5331 // to avoid incorrectly permitting member pointer access into a sibling
5332 // class of the class containing the member E2. If this class would
5333 // correspond to the most-derived class of E1, it either isn't contained in
5334 // LV.Designator.Entries or the corresponding entry refers to an array
5335 // element instead. Therefore get the most derived class directly in this
5336 // case. Otherwise the previous entry should correpond to this class.
5337 const CXXRecordDecl *LastLVDecl =
5338 (PathLengthToMember > LV.Designator.MostDerivedPathLength)
5339 ? getAsBaseClass(LV.Designator.Entries[PathLengthToMember - 1])
5340 : LV.Designator.MostDerivedType->getAsCXXRecordDecl();
5341 const CXXRecordDecl *LastMPDecl = MemPtr.getContainingRecord();
5342 if (LastLVDecl->getCanonicalDecl() != LastMPDecl->getCanonicalDecl()) {
5343 Info.FFDiag(RHS);
5344 return nullptr;
5345 }
5346
5347 // Truncate the lvalue to the appropriate derived class.
5348 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
5349 PathLengthToMember))
5350 return nullptr;
5351 } else if (!MemPtr.Path.empty()) {
5352 // Extend the LValue path with the member pointer's path.
5353 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
5354 MemPtr.Path.size() + IncludeMember);
5355
5356 // Walk down to the appropriate base class.
5357 if (const PointerType *PT = LVType->getAs<PointerType>())
5358 LVType = PT->getPointeeType();
5359 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
5360 assert(RD && "member pointer access on non-class-type expression");
5361 // The first class in the path is that of the lvalue.
5362 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
5363 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
5364 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
5365 return nullptr;
5366 RD = Base;
5367 }
5368 // Finally cast to the class containing the member.
5369 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
5370 MemPtr.getContainingRecord()))
5371 return nullptr;
5372 }
5373
5374 // Add the member. Note that we cannot build bound member functions here.
5375 if (IncludeMember) {
5376 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
5377 if (!HandleLValueMember(Info, RHS, LV, FD))
5378 return nullptr;
5379 } else if (const IndirectFieldDecl *IFD =
5380 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
5381 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
5382 return nullptr;
5383 } else {
5384 llvm_unreachable("can't construct reference to bound member function");
5385 }
5386 }
5387
5388 return MemPtr.getDecl();
5389}
5390
5391static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
5392 const BinaryOperator *BO,
5393 LValue &LV,
5394 bool IncludeMember = true) {
5395 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
5396
5397 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
5398 if (Info.noteFailure()) {
5399 MemberPtr MemPtr;
5400 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
5401 }
5402 return nullptr;
5403 }
5404
5405 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
5406 BO->getRHS(), IncludeMember);
5407}
5408
5409/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
5410/// the provided lvalue, which currently refers to the base object.
5411static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
5412 LValue &Result) {
5413 SubobjectDesignator &D = Result.Designator;
5414 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
5415 return false;
5416
5417 QualType TargetQT = E->getType();
5418 if (const PointerType *PT = TargetQT->getAs<PointerType>())
5419 TargetQT = PT->getPointeeType();
5420
5421 auto InvalidCast = [&]() {
5422 if (!Info.checkingPotentialConstantExpression() ||
5423 !Result.AllowConstexprUnknown) {
5424 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
5425 << D.MostDerivedType << TargetQT;
5426 }
5427 return false;
5428 };
5429
5430 // Check this cast lands within the final derived-to-base subobject path.
5431 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size())
5432 return InvalidCast();
5433
5434 // Check the type of the final cast. We don't need to check the path,
5435 // since a cast can only be formed if the path is unique.
5436 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
5437 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
5438 const CXXRecordDecl *FinalType;
5439 if (NewEntriesSize == D.MostDerivedPathLength)
5440 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
5441 else
5442 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
5443 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl())
5444 return InvalidCast();
5445
5446 // Truncate the lvalue to the appropriate derived class.
5447 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
5448}
5449
5450/// Get the value to use for a default-initialized object of type T.
5451/// Return false if it encounters something invalid.
5453 bool Success = true;
5454
5455 // If there is already a value present don't overwrite it.
5456 if (!Result.isAbsent())
5457 return true;
5458
5459 if (auto *RD = T->getAsCXXRecordDecl()) {
5460 if (RD->isInvalidDecl()) {
5461 Result = APValue();
5462 return false;
5463 }
5464 if (RD->isUnion()) {
5465 Result = APValue((const FieldDecl *)nullptr);
5466 return true;
5467 }
5468 Result =
5469 APValue(APValue::UninitStruct(), RD->getNumBases(), RD->getNumFields());
5470
5471 unsigned Index = 0;
5472 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
5473 End = RD->bases_end();
5474 I != End; ++I, ++Index)
5475 Success &=
5476 handleDefaultInitValue(I->getType(), Result.getStructBase(Index));
5477
5478 for (const auto *I : RD->fields()) {
5479 if (I->isUnnamedBitField())
5480 continue;
5482 I->getType(), Result.getStructField(I->getFieldIndex()));
5483 }
5484 return Success;
5485 }
5486
5487 if (auto *AT =
5488 dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
5489 Result = APValue(APValue::UninitArray(), 0, AT->getZExtSize());
5490 if (Result.hasArrayFiller())
5491 Success &=
5492 handleDefaultInitValue(AT->getElementType(), Result.getArrayFiller());
5493
5494 return Success;
5495 }
5496
5498 return true;
5499}
5500
5501namespace {
5502enum EvalStmtResult {
5503 /// Evaluation failed.
5504 ESR_Failed,
5505 /// Hit a 'return' statement.
5506 ESR_Returned,
5507 /// Evaluation succeeded.
5508 ESR_Succeeded,
5509 /// Hit a 'continue' statement.
5510 ESR_Continue,
5511 /// Hit a 'break' statement.
5512 ESR_Break,
5513 /// Still scanning for 'case' or 'default' statement.
5514 ESR_CaseNotFound
5515};
5516}
5517/// Evaluates the initializer of a reference.
5518static bool EvaluateInitForDeclOfReferenceType(EvalInfo &Info,
5519 const ValueDecl *D,
5520 const Expr *Init, LValue &Result,
5521 APValue &Val) {
5522 assert(Init->isGLValue() && D->getType()->isReferenceType());
5523 // A reference is an lvalue.
5524 if (!EvaluateLValue(Init, Result, Info))
5525 return false;
5526 // [C++26][decl.ref]
5527 // The object designated by such a glvalue can be outside its lifetime
5528 // Because a null pointer value or a pointer past the end of an object
5529 // does not point to an object, a reference in a well-defined program cannot
5530 // refer to such things;
5531 if (!Result.Designator.Invalid && Result.Designator.isOnePastTheEnd()) {
5532 Info.FFDiag(Init, diag::note_constexpr_access_past_end) << AK_Dereference;
5533 return false;
5534 }
5535
5536 // Save the result.
5537 Result.moveInto(Val);
5538 return true;
5539}
5540
5541static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
5542 if (VD->isInvalidDecl())
5543 return false;
5544 // We don't need to evaluate the initializer for a static local.
5545 if (!VD->hasLocalStorage())
5546 return true;
5547
5548 LValue Result;
5549 APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(),
5550 ScopeKind::Block, Result);
5551
5552 const Expr *InitE = VD->getInit();
5553 if (!InitE) {
5554 if (VD->getType()->isDependentType())
5555 return Info.noteSideEffect();
5556 return handleDefaultInitValue(VD->getType(), Val);
5557 }
5558 if (InitE->isValueDependent())
5559 return false;
5560
5561 // For references to objects, check they do not designate a one-past-the-end
5562 // object.
5563 if (VD->getType()->isReferenceType()) {
5564 return EvaluateInitForDeclOfReferenceType(Info, VD, InitE, Result, Val);
5565 } else if (!EvaluateInPlace(Val, Info, Result, InitE)) {
5566 // Wipe out any partially-computed value, to allow tracking that this
5567 // evaluation failed.
5568 Val = APValue();
5569 return false;
5570 }
5571
5572 return true;
5573}
5574
5575static bool EvaluateDecompositionDeclInit(EvalInfo &Info,
5576 const DecompositionDecl *DD);
5577
5578static bool EvaluateDecl(EvalInfo &Info, const Decl *D,
5579 bool EvaluateConditionDecl = false) {
5580 bool OK = true;
5581 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
5582 OK &= EvaluateVarDecl(Info, VD);
5583
5584 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D);
5585 EvaluateConditionDecl && DD)
5586 OK &= EvaluateDecompositionDeclInit(Info, DD);
5587
5588 return OK;
5589}
5590
5591static bool EvaluateDecompositionDeclInit(EvalInfo &Info,
5592 const DecompositionDecl *DD) {
5593 bool OK = true;
5594 for (auto *BD : DD->flat_bindings())
5595 if (auto *VD = BD->getHoldingVar())
5596 OK &= EvaluateDecl(Info, VD, /*EvaluateConditionDecl=*/true);
5597
5598 return OK;
5599}
5600
5601static bool MaybeEvaluateDeferredVarDeclInit(EvalInfo &Info,
5602 const VarDecl *VD) {
5603 if (auto *DD = dyn_cast_if_present<DecompositionDecl>(VD)) {
5604 if (!EvaluateDecompositionDeclInit(Info, DD))
5605 return false;
5606 }
5607 return true;
5608}
5609
5610static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info) {
5611 assert(E->isValueDependent());
5612 if (Info.noteSideEffect())
5613 return true;
5614 assert(E->containsErrors() && "valid value-dependent expression should never "
5615 "reach invalid code path.");
5616 return false;
5617}
5618
5619/// Evaluate a condition (either a variable declaration or an expression).
5620static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
5621 const Expr *Cond, bool &Result) {
5622 if (Cond->isValueDependent())
5623 return false;
5624 FullExpressionRAII Scope(Info);
5625 if (CondDecl && !EvaluateDecl(Info, CondDecl))
5626 return false;
5628 return false;
5629 if (!MaybeEvaluateDeferredVarDeclInit(Info, CondDecl))
5630 return false;
5631 return Scope.destroy();
5632}
5633
5634namespace {
5635/// A location where the result (returned value) of evaluating a
5636/// statement should be stored.
5637struct StmtResult {
5638 /// The APValue that should be filled in with the returned value.
5639 APValue &Value;
5640 /// The location containing the result, if any (used to support RVO).
5641 const LValue *Slot;
5642};
5643
5644struct TempVersionRAII {
5645 CallStackFrame &Frame;
5646
5647 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
5648 Frame.pushTempVersion();
5649 }
5650
5651 ~TempVersionRAII() {
5652 Frame.popTempVersion();
5653 }
5654};
5655
5656}
5657
5658static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
5659 const Stmt *S,
5660 const SwitchCase *SC = nullptr);
5661
5662/// Helper to implement named break/continue. Returns 'true' if the evaluation
5663/// result should be propagated up. Otherwise, it sets the evaluation result
5664/// to either Continue to continue the current loop, or Succeeded to break it.
5665static bool ShouldPropagateBreakContinue(EvalInfo &Info,
5666 const Stmt *LoopOrSwitch,
5668 EvalStmtResult &ESR) {
5669 bool IsSwitch = isa<SwitchStmt>(LoopOrSwitch);
5670
5671 // For loops, map Succeeded to Continue so we don't have to check for both.
5672 if (!IsSwitch && ESR == ESR_Succeeded) {
5673 ESR = ESR_Continue;
5674 return false;
5675 }
5676
5677 if (ESR != ESR_Break && ESR != ESR_Continue)
5678 return false;
5679
5680 // Are we breaking out of or continuing this statement?
5681 bool CanBreakOrContinue = !IsSwitch || ESR == ESR_Break;
5682 const Stmt *StackTop = Info.BreakContinueStack.back();
5683 if (CanBreakOrContinue && (StackTop == nullptr || StackTop == LoopOrSwitch)) {
5684 Info.BreakContinueStack.pop_back();
5685 if (ESR == ESR_Break)
5686 ESR = ESR_Succeeded;
5687 return false;
5688 }
5689
5690 // We're not. Propagate the result up.
5691 for (BlockScopeRAII *S : Scopes) {
5692 if (!S->destroy()) {
5693 ESR = ESR_Failed;
5694 break;
5695 }
5696 }
5697 return true;
5698}
5699
5700/// Evaluate the body of a loop, and translate the result as appropriate.
5701static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
5702 const Stmt *Body,
5703 const SwitchCase *Case = nullptr) {
5704 BlockScopeRAII Scope(Info);
5705
5706 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case);
5707 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
5708 ESR = ESR_Failed;
5709
5710 return ESR;
5711}
5712
5713/// Evaluate a switch statement.
5714static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
5715 const SwitchStmt *SS) {
5716 BlockScopeRAII Scope(Info);
5717
5718 // Evaluate the switch condition.
5719 APSInt Value;
5720 {
5721 if (const Stmt *Init = SS->getInit()) {
5722 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
5723 if (ESR != ESR_Succeeded) {
5724 if (ESR != ESR_Failed && !Scope.destroy())
5725 ESR = ESR_Failed;
5726 return ESR;
5727 }
5728 }
5729
5730 FullExpressionRAII CondScope(Info);
5731 if (SS->getConditionVariable() &&
5732 !EvaluateDecl(Info, SS->getConditionVariable()))
5733 return ESR_Failed;
5734 if (SS->getCond()->isValueDependent()) {
5735 // We don't know what the value is, and which branch should jump to.
5736 EvaluateDependentExpr(SS->getCond(), Info);
5737 return ESR_Failed;
5738 }
5739 if (!EvaluateInteger(SS->getCond(), Value, Info))
5740 return ESR_Failed;
5741
5743 return ESR_Failed;
5744
5745 if (!CondScope.destroy())
5746 return ESR_Failed;
5747 }
5748
5749 // Find the switch case corresponding to the value of the condition.
5750 // FIXME: Cache this lookup.
5751 const SwitchCase *Found = nullptr;
5752 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
5753 SC = SC->getNextSwitchCase()) {
5754 if (isa<DefaultStmt>(SC)) {
5755 Found = SC;
5756 continue;
5757 }
5758
5759 const CaseStmt *CS = cast<CaseStmt>(SC);
5760 const Expr *LHS = CS->getLHS();
5761 const Expr *RHS = CS->getRHS();
5762 if (LHS->isValueDependent() || (RHS && RHS->isValueDependent()))
5763 return ESR_Failed;
5764 APSInt LHSValue = LHS->EvaluateKnownConstInt(Info.Ctx);
5765 APSInt RHSValue = RHS ? RHS->EvaluateKnownConstInt(Info.Ctx) : LHSValue;
5766 if (LHSValue <= Value && Value <= RHSValue) {
5767 Found = SC;
5768 break;
5769 }
5770 }
5771
5772 if (!Found)
5773 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5774
5775 // Search the switch body for the switch case and evaluate it from there.
5776 EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found);
5777 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
5778 return ESR_Failed;
5779 if (ShouldPropagateBreakContinue(Info, SS, /*Scopes=*/{}, ESR))
5780 return ESR;
5781
5782 switch (ESR) {
5783 case ESR_Break:
5784 llvm_unreachable("Should have been converted to Succeeded");
5785 case ESR_Succeeded:
5786 case ESR_Continue:
5787 case ESR_Failed:
5788 case ESR_Returned:
5789 return ESR;
5790 case ESR_CaseNotFound:
5791 // This can only happen if the switch case is nested within a statement
5792 // expression. We have no intention of supporting that.
5793 Info.FFDiag(Found->getBeginLoc(),
5794 diag::note_constexpr_stmt_expr_unsupported);
5795 return ESR_Failed;
5796 }
5797 llvm_unreachable("Invalid EvalStmtResult!");
5798}
5799
5800static bool CheckLocalVariableDeclaration(EvalInfo &Info, const VarDecl *VD) {
5801 // An expression E is a core constant expression unless the evaluation of E
5802 // would evaluate one of the following: [C++23] - a control flow that passes
5803 // through a declaration of a variable with static or thread storage duration
5804 // unless that variable is usable in constant expressions.
5805 if (VD->isLocalVarDecl() && VD->isStaticLocal() &&
5806 !VD->isUsableInConstantExpressions(Info.Ctx)) {
5807 Info.CCEDiag(VD->getLocation(), diag::note_constexpr_static_local)
5808 << (VD->getTSCSpec() == TSCS_unspecified ? 0 : 1) << VD;
5809 return false;
5810 }
5811 return true;
5812}
5813
5814// Evaluate a statement.
5815static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
5816 const Stmt *S, const SwitchCase *Case) {
5817 if (!Info.nextStep(S))
5818 return ESR_Failed;
5819
5820 // If we're hunting down a 'case' or 'default' label, recurse through
5821 // substatements until we hit the label.
5822 if (Case) {
5823 switch (S->getStmtClass()) {
5824 case Stmt::CompoundStmtClass:
5825 // FIXME: Precompute which substatement of a compound statement we
5826 // would jump to, and go straight there rather than performing a
5827 // linear scan each time.
5828 case Stmt::LabelStmtClass:
5829 case Stmt::AttributedStmtClass:
5830 case Stmt::DoStmtClass:
5831 break;
5832
5833 case Stmt::CaseStmtClass:
5834 case Stmt::DefaultStmtClass:
5835 if (Case == S)
5836 Case = nullptr;
5837 break;
5838
5839 case Stmt::IfStmtClass: {
5840 // FIXME: Precompute which side of an 'if' we would jump to, and go
5841 // straight there rather than scanning both sides.
5842 const IfStmt *IS = cast<IfStmt>(S);
5843
5844 // Wrap the evaluation in a block scope, in case it's a DeclStmt
5845 // preceded by our switch label.
5846 BlockScopeRAII Scope(Info);
5847
5848 // Step into the init statement in case it brings an (uninitialized)
5849 // variable into scope.
5850 if (const Stmt *Init = IS->getInit()) {
5851 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5852 if (ESR != ESR_CaseNotFound) {
5853 assert(ESR != ESR_Succeeded);
5854 return ESR;
5855 }
5856 }
5857
5858 // Condition variable must be initialized if it exists.
5859 // FIXME: We can skip evaluating the body if there's a condition
5860 // variable, as there can't be any case labels within it.
5861 // (The same is true for 'for' statements.)
5862
5863 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
5864 if (ESR == ESR_Failed)
5865 return ESR;
5866 if (ESR != ESR_CaseNotFound)
5867 return Scope.destroy() ? ESR : ESR_Failed;
5868 if (!IS->getElse())
5869 return ESR_CaseNotFound;
5870
5871 ESR = EvaluateStmt(Result, Info, IS->getElse(), Case);
5872 if (ESR == ESR_Failed)
5873 return ESR;
5874 if (ESR != ESR_CaseNotFound)
5875 return Scope.destroy() ? ESR : ESR_Failed;
5876 return ESR_CaseNotFound;
5877 }
5878
5879 case Stmt::WhileStmtClass: {
5880 EvalStmtResult ESR =
5881 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
5882 if (ShouldPropagateBreakContinue(Info, S, /*Scopes=*/{}, ESR))
5883 return ESR;
5884 if (ESR != ESR_Continue)
5885 return ESR;
5886 break;
5887 }
5888
5889 case Stmt::ForStmtClass: {
5890 const ForStmt *FS = cast<ForStmt>(S);
5891 BlockScopeRAII Scope(Info);
5892
5893 // Step into the init statement in case it brings an (uninitialized)
5894 // variable into scope.
5895 if (const Stmt *Init = FS->getInit()) {
5896 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5897 if (ESR != ESR_CaseNotFound) {
5898 assert(ESR != ESR_Succeeded);
5899 return ESR;
5900 }
5901 }
5902
5903 EvalStmtResult ESR =
5904 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
5905 if (ShouldPropagateBreakContinue(Info, FS, /*Scopes=*/{}, ESR))
5906 return ESR;
5907 if (ESR != ESR_Continue)
5908 return ESR;
5909 if (const auto *Inc = FS->getInc()) {
5910 if (Inc->isValueDependent()) {
5911 if (!EvaluateDependentExpr(Inc, Info))
5912 return ESR_Failed;
5913 } else {
5914 FullExpressionRAII IncScope(Info);
5915 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5916 return ESR_Failed;
5917 }
5918 }
5919 break;
5920 }
5921
5922 case Stmt::DeclStmtClass: {
5923 // Start the lifetime of any uninitialized variables we encounter. They
5924 // might be used by the selected branch of the switch.
5925 const DeclStmt *DS = cast<DeclStmt>(S);
5926 for (const auto *D : DS->decls()) {
5927 if (const auto *VD = dyn_cast<VarDecl>(D)) {
5928 if (!CheckLocalVariableDeclaration(Info, VD))
5929 return ESR_Failed;
5930 if (VD->hasLocalStorage() && !VD->getInit())
5931 if (!EvaluateVarDecl(Info, VD))
5932 return ESR_Failed;
5933 // FIXME: If the variable has initialization that can't be jumped
5934 // over, bail out of any immediately-surrounding compound-statement
5935 // too. There can't be any case labels here.
5936 }
5937 }
5938 return ESR_CaseNotFound;
5939 }
5940
5941 default:
5942 return ESR_CaseNotFound;
5943 }
5944 }
5945
5946 switch (S->getStmtClass()) {
5947 default:
5948 if (const Expr *E = dyn_cast<Expr>(S)) {
5949 if (E->isValueDependent()) {
5950 if (!EvaluateDependentExpr(E, Info))
5951 return ESR_Failed;
5952 } else {
5953 // Don't bother evaluating beyond an expression-statement which couldn't
5954 // be evaluated.
5955 // FIXME: Do we need the FullExpressionRAII object here?
5956 // VisitExprWithCleanups should create one when necessary.
5957 FullExpressionRAII Scope(Info);
5958 if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy())
5959 return ESR_Failed;
5960 }
5961 return ESR_Succeeded;
5962 }
5963
5964 Info.FFDiag(S->getBeginLoc()) << S->getSourceRange();
5965 return ESR_Failed;
5966
5967 case Stmt::NullStmtClass:
5968 return ESR_Succeeded;
5969
5970 case Stmt::DeclStmtClass: {
5971 const DeclStmt *DS = cast<DeclStmt>(S);
5972 for (const auto *D : DS->decls()) {
5973 const VarDecl *VD = dyn_cast_or_null<VarDecl>(D);
5974 if (VD && !CheckLocalVariableDeclaration(Info, VD))
5975 return ESR_Failed;
5976 // Each declaration initialization is its own full-expression.
5977 FullExpressionRAII Scope(Info);
5978 if (!EvaluateDecl(Info, D, /*EvaluateConditionDecl=*/true) &&
5979 !Info.noteFailure())
5980 return ESR_Failed;
5981 if (!Scope.destroy())
5982 return ESR_Failed;
5983 }
5984 return ESR_Succeeded;
5985 }
5986
5987 case Stmt::ReturnStmtClass: {
5988 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
5989 FullExpressionRAII Scope(Info);
5990 if (RetExpr && RetExpr->isValueDependent()) {
5991 EvaluateDependentExpr(RetExpr, Info);
5992 // We know we returned, but we don't know what the value is.
5993 return ESR_Failed;
5994 }
5995 if (RetExpr &&
5996 !(Result.Slot
5997 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
5998 : Evaluate(Result.Value, Info, RetExpr)))
5999 return ESR_Failed;
6000 return Scope.destroy() ? ESR_Returned : ESR_Failed;
6001 }
6002
6003 case Stmt::CompoundStmtClass: {
6004 BlockScopeRAII Scope(Info);
6005
6006 const CompoundStmt *CS = cast<CompoundStmt>(S);
6007 for (const auto *BI : CS->body()) {
6008 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
6009 if (ESR == ESR_Succeeded)
6010 Case = nullptr;
6011 else if (ESR != ESR_CaseNotFound) {
6012 if (ESR != ESR_Failed && !Scope.destroy())
6013 return ESR_Failed;
6014 return ESR;
6015 }
6016 }
6017 if (Case)
6018 return ESR_CaseNotFound;
6019 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
6020 }
6021
6022 case Stmt::IfStmtClass: {
6023 const IfStmt *IS = cast<IfStmt>(S);
6024
6025 // Evaluate the condition, as either a var decl or as an expression.
6026 BlockScopeRAII Scope(Info);
6027 if (const Stmt *Init = IS->getInit()) {
6028 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
6029 if (ESR != ESR_Succeeded) {
6030 if (ESR != ESR_Failed && !Scope.destroy())
6031 return ESR_Failed;
6032 return ESR;
6033 }
6034 }
6035 bool Cond;
6036 if (IS->isConsteval()) {
6038 // If we are not in a constant context, if consteval should not evaluate
6039 // to true.
6040 if (!Info.InConstantContext)
6041 Cond = !Cond;
6042 } else if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(),
6043 Cond))
6044 return ESR_Failed;
6045
6046 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
6047 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
6048 if (ESR != ESR_Succeeded) {
6049 if (ESR != ESR_Failed && !Scope.destroy())
6050 return ESR_Failed;
6051 return ESR;
6052 }
6053 }
6054 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
6055 }
6056
6057 case Stmt::WhileStmtClass: {
6058 const WhileStmt *WS = cast<WhileStmt>(S);
6059 while (true) {
6060 BlockScopeRAII Scope(Info);
6061 bool Continue;
6062 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
6063 Continue))
6064 return ESR_Failed;
6065 if (!Continue)
6066 break;
6067
6068 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
6069 if (ShouldPropagateBreakContinue(Info, WS, &Scope, ESR))
6070 return ESR;
6071
6072 if (ESR != ESR_Continue) {
6073 if (ESR != ESR_Failed && !Scope.destroy())
6074 return ESR_Failed;
6075 return ESR;
6076 }
6077 if (!Scope.destroy())
6078 return ESR_Failed;
6079 }
6080 return ESR_Succeeded;
6081 }
6082
6083 case Stmt::DoStmtClass: {
6084 const DoStmt *DS = cast<DoStmt>(S);
6085 bool Continue;
6086 do {
6087 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
6088 if (ShouldPropagateBreakContinue(Info, DS, /*Scopes=*/{}, ESR))
6089 return ESR;
6090 if (ESR != ESR_Continue)
6091 return ESR;
6092 Case = nullptr;
6093
6094 if (DS->getCond()->isValueDependent()) {
6095 EvaluateDependentExpr(DS->getCond(), Info);
6096 // Bailout as we don't know whether to keep going or terminate the loop.
6097 return ESR_Failed;
6098 }
6099 FullExpressionRAII CondScope(Info);
6100 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) ||
6101 !CondScope.destroy())
6102 return ESR_Failed;
6103 } while (Continue);
6104 return ESR_Succeeded;
6105 }
6106
6107 case Stmt::ForStmtClass: {
6108 const ForStmt *FS = cast<ForStmt>(S);
6109 BlockScopeRAII ForScope(Info);
6110 if (FS->getInit()) {
6111 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
6112 if (ESR != ESR_Succeeded) {
6113 if (ESR != ESR_Failed && !ForScope.destroy())
6114 return ESR_Failed;
6115 return ESR;
6116 }
6117 }
6118 while (true) {
6119 BlockScopeRAII IterScope(Info);
6120 bool Continue = true;
6121 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
6122 FS->getCond(), Continue))
6123 return ESR_Failed;
6124
6125 if (!Continue) {
6126 if (!IterScope.destroy())
6127 return ESR_Failed;
6128 break;
6129 }
6130
6131 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
6132 if (ShouldPropagateBreakContinue(Info, FS, {&IterScope, &ForScope}, ESR))
6133 return ESR;
6134 if (ESR != ESR_Continue) {
6135 if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))
6136 return ESR_Failed;
6137 return ESR;
6138 }
6139
6140 if (const auto *Inc = FS->getInc()) {
6141 if (Inc->isValueDependent()) {
6142 if (!EvaluateDependentExpr(Inc, Info))
6143 return ESR_Failed;
6144 } else {
6145 FullExpressionRAII IncScope(Info);
6146 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
6147 return ESR_Failed;
6148 }
6149 }
6150
6151 if (!IterScope.destroy())
6152 return ESR_Failed;
6153 }
6154 return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;
6155 }
6156
6157 case Stmt::CXXForRangeStmtClass: {
6159 BlockScopeRAII Scope(Info);
6160
6161 // Evaluate the init-statement if present.
6162 if (FS->getInit()) {
6163 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
6164 if (ESR != ESR_Succeeded) {
6165 if (ESR != ESR_Failed && !Scope.destroy())
6166 return ESR_Failed;
6167 return ESR;
6168 }
6169 }
6170
6171 // Initialize the __range variable.
6172 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
6173 if (ESR != ESR_Succeeded) {
6174 if (ESR != ESR_Failed && !Scope.destroy())
6175 return ESR_Failed;
6176 return ESR;
6177 }
6178
6179 // In error-recovery cases it's possible to get here even if we failed to
6180 // synthesize the __begin and __end variables.
6181 if (!FS->getBeginStmt() || !FS->getEndStmt() || !FS->getCond())
6182 return ESR_Failed;
6183
6184 // Create the __begin and __end iterators.
6185 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
6186 if (ESR != ESR_Succeeded) {
6187 if (ESR != ESR_Failed && !Scope.destroy())
6188 return ESR_Failed;
6189 return ESR;
6190 }
6191 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
6192 if (ESR != ESR_Succeeded) {
6193 if (ESR != ESR_Failed && !Scope.destroy())
6194 return ESR_Failed;
6195 return ESR;
6196 }
6197
6198 while (true) {
6199 // Condition: __begin != __end.
6200 {
6201 if (FS->getCond()->isValueDependent()) {
6202 EvaluateDependentExpr(FS->getCond(), Info);
6203 // We don't know whether to keep going or terminate the loop.
6204 return ESR_Failed;
6205 }
6206 bool Continue = true;
6207 FullExpressionRAII CondExpr(Info);
6208 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
6209 return ESR_Failed;
6210 if (!Continue)
6211 break;
6212 }
6213
6214 // User's variable declaration, initialized by *__begin.
6215 BlockScopeRAII InnerScope(Info);
6216 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
6217 if (ESR != ESR_Succeeded) {
6218 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
6219 return ESR_Failed;
6220 return ESR;
6221 }
6222
6223 // Loop body.
6224 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
6225 if (ShouldPropagateBreakContinue(Info, FS, {&InnerScope, &Scope}, ESR))
6226 return ESR;
6227 if (ESR != ESR_Continue) {
6228 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
6229 return ESR_Failed;
6230 return ESR;
6231 }
6232 if (FS->getInc()->isValueDependent()) {
6233 if (!EvaluateDependentExpr(FS->getInc(), Info))
6234 return ESR_Failed;
6235 } else {
6236 // Increment: ++__begin
6237 if (!EvaluateIgnoredValue(Info, FS->getInc()))
6238 return ESR_Failed;
6239 }
6240
6241 if (!InnerScope.destroy())
6242 return ESR_Failed;
6243 }
6244
6245 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
6246 }
6247
6248 case Stmt::SwitchStmtClass:
6249 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
6250
6251 case Stmt::ContinueStmtClass:
6252 case Stmt::BreakStmtClass: {
6253 auto *B = cast<LoopControlStmt>(S);
6254 Info.BreakContinueStack.push_back(B->getNamedLoopOrSwitch());
6255 return isa<ContinueStmt>(S) ? ESR_Continue : ESR_Break;
6256 }
6257
6258 case Stmt::LabelStmtClass:
6259 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
6260
6261 case Stmt::AttributedStmtClass: {
6262 const auto *AS = cast<AttributedStmt>(S);
6263 const auto *SS = AS->getSubStmt();
6264 MSConstexprContextRAII ConstexprContext(
6265 *Info.CurrentCall, hasSpecificAttr<MSConstexprAttr>(AS->getAttrs()) &&
6266 isa<ReturnStmt>(SS));
6267
6268 auto LO = Info.Ctx.getLangOpts();
6269 if (LO.CXXAssumptions && !LO.MSVCCompat) {
6270 for (auto *Attr : AS->getAttrs()) {
6271 auto *AA = dyn_cast<CXXAssumeAttr>(Attr);
6272 if (!AA)
6273 continue;
6274
6275 auto *Assumption = AA->getAssumption();
6276 if (Assumption->isValueDependent())
6277 return ESR_Failed;
6278
6279 if (Assumption->HasSideEffects(Info.Ctx))
6280 continue;
6281
6282 bool Value;
6283 if (!EvaluateAsBooleanCondition(Assumption, Value, Info))
6284 return ESR_Failed;
6285 if (!Value) {
6286 Info.CCEDiag(Assumption->getExprLoc(),
6287 diag::note_constexpr_assumption_failed);
6288 return ESR_Failed;
6289 }
6290 }
6291 }
6292
6293 return EvaluateStmt(Result, Info, SS, Case);
6294 }
6295
6296 case Stmt::CaseStmtClass:
6297 case Stmt::DefaultStmtClass:
6298 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
6299 case Stmt::CXXTryStmtClass:
6300 // Evaluate try blocks by evaluating all sub statements.
6301 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
6302 }
6303}
6304
6305/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
6306/// default constructor. If so, we'll fold it whether or not it's marked as
6307/// constexpr. If it is marked as constexpr, we will never implicitly define it,
6308/// so we need special handling.
6309static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
6310 const CXXConstructorDecl *CD,
6311 bool IsValueInitialization) {
6312 if (!CD->isTrivial() || !CD->isDefaultConstructor())
6313 return false;
6314
6315 // Value-initialization does not call a trivial default constructor, so such a
6316 // call is a core constant expression whether or not the constructor is
6317 // constexpr.
6318 if (!CD->isConstexpr() && !IsValueInitialization) {
6319 if (Info.getLangOpts().CPlusPlus11) {
6320 // FIXME: If DiagDecl is an implicitly-declared special member function,
6321 // we should be much more explicit about why it's not constexpr.
6322 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
6323 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
6324 Info.Note(CD->getLocation(), diag::note_declared_at);
6325 } else {
6326 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
6327 }
6328 }
6329 return true;
6330}
6331
6332/// CheckConstexprFunction - Check that a function can be called in a constant
6333/// expression.
6334static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
6336 const FunctionDecl *Definition,
6337 const Stmt *Body) {
6338 // Potential constant expressions can contain calls to declared, but not yet
6339 // defined, constexpr functions.
6340 if (Info.checkingPotentialConstantExpression() && !Definition &&
6341 Declaration->isConstexpr())
6342 return false;
6343
6344 // Bail out if the function declaration itself is invalid. We will
6345 // have produced a relevant diagnostic while parsing it, so just
6346 // note the problematic sub-expression.
6347 if (Declaration->isInvalidDecl()) {
6348 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
6349 return false;
6350 }
6351
6352 // DR1872: An instantiated virtual constexpr function can't be called in a
6353 // constant expression (prior to C++20). We can still constant-fold such a
6354 // call.
6355 if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) &&
6356 cast<CXXMethodDecl>(Declaration)->isVirtual())
6357 Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
6358
6359 if (Definition && Definition->isInvalidDecl()) {
6360 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
6361 return false;
6362 }
6363
6364 // Can we evaluate this function call?
6365 if (Definition && Body &&
6366 (Definition->isConstexpr() || (Info.CurrentCall->CanEvalMSConstexpr &&
6367 Definition->hasAttr<MSConstexprAttr>())))
6368 return true;
6369
6370 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
6371 // Special note for the assert() macro, as the normal error message falsely
6372 // implies we cannot use an assertion during constant evaluation.
6373 if (CallLoc.isMacroID() && DiagDecl->getIdentifier()) {
6374 // FIXME: Instead of checking for an implementation-defined function,
6375 // check and evaluate the assert() macro.
6376 StringRef Name = DiagDecl->getName();
6377 bool AssertFailed =
6378 Name == "__assert_rtn" || Name == "__assert_fail" || Name == "_wassert";
6379 if (AssertFailed) {
6380 Info.FFDiag(CallLoc, diag::note_constexpr_assert_failed);
6381 return false;
6382 }
6383 }
6384
6385 if (Info.getLangOpts().CPlusPlus11) {
6386 // If this function is not constexpr because it is an inherited
6387 // non-constexpr constructor, diagnose that directly.
6388 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
6389 if (CD && CD->isInheritingConstructor()) {
6390 auto *Inherited = CD->getInheritedConstructor().getConstructor();
6391 if (!Inherited->isConstexpr())
6392 DiagDecl = CD = Inherited;
6393 }
6394
6395 // FIXME: If DiagDecl is an implicitly-declared special member function
6396 // or an inheriting constructor, we should be much more explicit about why
6397 // it's not constexpr.
6398 if (CD && CD->isInheritingConstructor())
6399 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
6400 << CD->getInheritedConstructor().getConstructor()->getParent();
6401 else
6402 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
6403 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
6404 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
6405 } else {
6406 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
6407 }
6408 return false;
6409}
6410
6411namespace {
6412struct CheckDynamicTypeHandler {
6414 typedef bool result_type;
6415 bool failed() { return false; }
6416 bool found(APValue &Subobj, QualType SubobjType, APValue::LValueBase Base) {
6417 return true;
6418 }
6419 bool found(APSInt &Value, QualType SubobjType) { return true; }
6420 bool found(APFloat &Value, QualType SubobjType) { return true; }
6421};
6422} // end anonymous namespace
6423
6424/// Check that we can access the notional vptr of an object / determine its
6425/// dynamic type.
6426static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
6427 AccessKinds AK, bool Polymorphic) {
6428 if (This.Designator.Invalid)
6429 return false;
6430
6431 CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
6432
6433 if (!Obj)
6434 return false;
6435
6436 if (!Obj.Value) {
6437 // The object is not usable in constant expressions, so we can't inspect
6438 // its value to see if it's in-lifetime or what the active union members
6439 // are. We can still check for a one-past-the-end lvalue.
6440 if (This.Designator.isOnePastTheEnd() ||
6441 This.Designator.isMostDerivedAnUnsizedArray()) {
6442 Info.FFDiag(E, This.Designator.isOnePastTheEnd()
6443 ? diag::note_constexpr_access_past_end
6444 : diag::note_constexpr_access_unsized_array)
6445 << AK;
6446 return false;
6447 } else if (Polymorphic) {
6448 // Conservatively refuse to perform a polymorphic operation if we would
6449 // not be able to read a notional 'vptr' value.
6450 if (!Info.checkingPotentialConstantExpression() ||
6451 !This.AllowConstexprUnknown) {
6452 APValue Val;
6453 This.moveInto(Val);
6454 QualType StarThisType =
6455 Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
6456 Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
6457 << AK << Val.getAsString(Info.Ctx, StarThisType);
6458 }
6459 return false;
6460 }
6461 return true;
6462 }
6463
6464 CheckDynamicTypeHandler Handler{AK};
6465 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
6466}
6467
6468/// Check that the pointee of the 'this' pointer in a member function call is
6469/// either within its lifetime or in its period of construction or destruction.
6470static bool
6472 const LValue &This,
6473 const CXXMethodDecl *NamedMember) {
6474 return checkDynamicType(
6475 Info, E, This,
6476 isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false);
6477}
6478
6480 /// The dynamic class type of the object.
6482 /// The corresponding path length in the lvalue.
6483 unsigned PathLength;
6484};
6485
6486static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
6487 unsigned PathLength) {
6488 assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
6489 Designator.Entries.size() && "invalid path length");
6490 return (PathLength == Designator.MostDerivedPathLength)
6491 ? Designator.MostDerivedType->getAsCXXRecordDecl()
6492 : getAsBaseClass(Designator.Entries[PathLength - 1]);
6493}
6494
6495/// Determine the dynamic type of an object.
6496static std::optional<DynamicType> ComputeDynamicType(EvalInfo &Info,
6497 const Expr *E,
6498 LValue &This,
6499 AccessKinds AK) {
6500 // If we don't have an lvalue denoting an object of class type, there is no
6501 // meaningful dynamic type. (We consider objects of non-class type to have no
6502 // dynamic type.)
6503 if (!checkDynamicType(Info, E, This, AK,
6504 AK != AK_TypeId || This.AllowConstexprUnknown))
6505 return std::nullopt;
6506
6507 if (This.Designator.Invalid)
6508 return std::nullopt;
6509
6510 // Refuse to compute a dynamic type in the presence of virtual bases. This
6511 // shouldn't happen other than in constant-folding situations, since literal
6512 // types can't have virtual bases.
6513 //
6514 // Note that consumers of DynamicType assume that the type has no virtual
6515 // bases, and will need modifications if this restriction is relaxed.
6516 const CXXRecordDecl *Class =
6517 This.Designator.MostDerivedType->getAsCXXRecordDecl();
6518 if (!Class || Class->getNumVBases()) {
6519 Info.FFDiag(E);
6520 return std::nullopt;
6521 }
6522
6523 // FIXME: For very deep class hierarchies, it might be beneficial to use a
6524 // binary search here instead. But the overwhelmingly common case is that
6525 // we're not in the middle of a constructor, so it probably doesn't matter
6526 // in practice.
6527 ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
6528 for (unsigned PathLength = This.Designator.MostDerivedPathLength;
6529 PathLength <= Path.size(); ++PathLength) {
6530 switch (Info.isEvaluatingCtorDtor(This.getLValueBase(),
6531 Path.slice(0, PathLength))) {
6532 case ConstructionPhase::Bases:
6533 case ConstructionPhase::DestroyingBases:
6534 // We're constructing or destroying a base class. This is not the dynamic
6535 // type.
6536 break;
6537
6538 case ConstructionPhase::None:
6539 case ConstructionPhase::AfterBases:
6540 case ConstructionPhase::AfterFields:
6541 case ConstructionPhase::Destroying:
6542 // We've finished constructing the base classes and not yet started
6543 // destroying them again, so this is the dynamic type.
6544 return DynamicType{getBaseClassType(This.Designator, PathLength),
6545 PathLength};
6546 }
6547 }
6548
6549 // CWG issue 1517: we're constructing a base class of the object described by
6550 // 'This', so that object has not yet begun its period of construction and
6551 // any polymorphic operation on it results in undefined behavior.
6552 Info.FFDiag(E);
6553 return std::nullopt;
6554}
6555
6556/// Perform virtual dispatch.
6558 EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
6559 llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
6560 std::optional<DynamicType> DynType = ComputeDynamicType(
6561 Info, E, This,
6563 if (!DynType)
6564 return nullptr;
6565
6566 // Find the final overrider. It must be declared in one of the classes on the
6567 // path from the dynamic type to the static type.
6568 // FIXME: If we ever allow literal types to have virtual base classes, that
6569 // won't be true.
6570 const CXXMethodDecl *Callee = Found;
6571 unsigned PathLength = DynType->PathLength;
6572 for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
6573 const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
6574 const CXXMethodDecl *Overrider =
6575 Found->getCorrespondingMethodDeclaredInClass(Class, false);
6576 if (Overrider) {
6577 Callee = Overrider;
6578 break;
6579 }
6580 }
6581
6582 // C++2a [class.abstract]p6:
6583 // the effect of making a virtual call to a pure virtual function [...] is
6584 // undefined
6585 if (Callee->isPureVirtual()) {
6586 Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
6587 Info.Note(Callee->getLocation(), diag::note_declared_at);
6588 return nullptr;
6589 }
6590
6591 // If necessary, walk the rest of the path to determine the sequence of
6592 // covariant adjustment steps to apply.
6593 if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
6594 Found->getReturnType())) {
6595 CovariantAdjustmentPath.push_back(Callee->getReturnType());
6596 for (unsigned CovariantPathLength = PathLength + 1;
6597 CovariantPathLength != This.Designator.Entries.size();
6598 ++CovariantPathLength) {
6599 const CXXRecordDecl *NextClass =
6600 getBaseClassType(This.Designator, CovariantPathLength);
6601 const CXXMethodDecl *Next =
6602 Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
6603 if (Next && !Info.Ctx.hasSameUnqualifiedType(
6604 Next->getReturnType(), CovariantAdjustmentPath.back()))
6605 CovariantAdjustmentPath.push_back(Next->getReturnType());
6606 }
6607 if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
6608 CovariantAdjustmentPath.back()))
6609 CovariantAdjustmentPath.push_back(Found->getReturnType());
6610 }
6611
6612 // Perform 'this' adjustment.
6613 if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
6614 return nullptr;
6615
6616 return Callee;
6617}
6618
6619/// Perform the adjustment from a value returned by a virtual function to
6620/// a value of the statically expected type, which may be a pointer or
6621/// reference to a base class of the returned type.
6622static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
6623 APValue &Result,
6624 ArrayRef<QualType> Path) {
6625 assert(Result.isLValue() &&
6626 "unexpected kind of APValue for covariant return");
6627 if (Result.isNullPointer())
6628 return true;
6629
6630 LValue LVal;
6631 LVal.setFrom(Info.Ctx, Result);
6632
6633 const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
6634 for (unsigned I = 1; I != Path.size(); ++I) {
6635 const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
6636 assert(OldClass && NewClass && "unexpected kind of covariant return");
6637 if (OldClass != NewClass &&
6638 !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
6639 return false;
6640 OldClass = NewClass;
6641 }
6642
6643 LVal.moveInto(Result);
6644 return true;
6645}
6646
6647/// Determine whether \p Base, which is known to be a direct base class of
6648/// \p Derived, is a public base class.
6649static bool isBaseClassPublic(const CXXRecordDecl *Derived,
6650 const CXXRecordDecl *Base) {
6651 for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
6652 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
6653 if (BaseClass && declaresSameEntity(BaseClass, Base))
6654 return BaseSpec.getAccessSpecifier() == AS_public;
6655 }
6656 llvm_unreachable("Base is not a direct base of Derived");
6657}
6658
6659/// Apply the given dynamic cast operation on the provided lvalue.
6660///
6661/// This implements the hard case of dynamic_cast, requiring a "runtime check"
6662/// to find a suitable target subobject.
6663static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
6664 LValue &Ptr) {
6665 // We can't do anything with a non-symbolic pointer value.
6666 SubobjectDesignator &D = Ptr.Designator;
6667 if (D.Invalid)
6668 return false;
6669
6670 // C++ [expr.dynamic.cast]p6:
6671 // If v is a null pointer value, the result is a null pointer value.
6672 if (Ptr.isNullPointer() && !E->isGLValue())
6673 return true;
6674
6675 // For all the other cases, we need the pointer to point to an object within
6676 // its lifetime / period of construction / destruction, and we need to know
6677 // its dynamic type.
6678 std::optional<DynamicType> DynType =
6679 ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
6680 if (!DynType)
6681 return false;
6682
6683 // C++ [expr.dynamic.cast]p7:
6684 // If T is "pointer to cv void", then the result is a pointer to the most
6685 // derived object
6686 if (E->getType()->isVoidPointerType())
6687 return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
6688
6690 assert(C && "dynamic_cast target is not void pointer nor class");
6691 CanQualType CQT = Info.Ctx.getCanonicalTagType(C);
6692
6693 auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
6694 // C++ [expr.dynamic.cast]p9:
6695 if (!E->isGLValue()) {
6696 // The value of a failed cast to pointer type is the null pointer value
6697 // of the required result type.
6698 Ptr.setNull(Info.Ctx, E->getType());
6699 return true;
6700 }
6701
6702 // A failed cast to reference type throws [...] std::bad_cast.
6703 unsigned DiagKind;
6704 if (!Paths && (declaresSameEntity(DynType->Type, C) ||
6705 DynType->Type->isDerivedFrom(C)))
6706 DiagKind = 0;
6707 else if (!Paths || Paths->begin() == Paths->end())
6708 DiagKind = 1;
6709 else if (Paths->isAmbiguous(CQT))
6710 DiagKind = 2;
6711 else {
6712 assert(Paths->front().Access != AS_public && "why did the cast fail?");
6713 DiagKind = 3;
6714 }
6715 Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
6716 << DiagKind << Ptr.Designator.getType(Info.Ctx)
6717 << Info.Ctx.getCanonicalTagType(DynType->Type)
6718 << E->getType().getUnqualifiedType();
6719 return false;
6720 };
6721
6722 // Runtime check, phase 1:
6723 // Walk from the base subobject towards the derived object looking for the
6724 // target type.
6725 for (int PathLength = Ptr.Designator.Entries.size();
6726 PathLength >= (int)DynType->PathLength; --PathLength) {
6727 const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
6728 if (declaresSameEntity(Class, C))
6729 return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
6730 // We can only walk across public inheritance edges.
6731 if (PathLength > (int)DynType->PathLength &&
6732 !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
6733 Class))
6734 return RuntimeCheckFailed(nullptr);
6735 }
6736
6737 // Runtime check, phase 2:
6738 // Search the dynamic type for an unambiguous public base of type C.
6739 CXXBasePaths Paths(/*FindAmbiguities=*/true,
6740 /*RecordPaths=*/true, /*DetectVirtual=*/false);
6741 if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
6742 Paths.front().Access == AS_public) {
6743 // Downcast to the dynamic type...
6744 if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
6745 return false;
6746 // ... then upcast to the chosen base class subobject.
6747 for (CXXBasePathElement &Elem : Paths.front())
6748 if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
6749 return false;
6750 return true;
6751 }
6752
6753 // Otherwise, the runtime check fails.
6754 return RuntimeCheckFailed(&Paths);
6755}
6756
6757namespace {
6758struct StartLifetimeOfUnionMemberHandler {
6759 EvalInfo &Info;
6760 const Expr *LHSExpr;
6761 const FieldDecl *Field;
6762 bool DuringInit;
6763 bool Failed = false;
6764 static const AccessKinds AccessKind = AK_Assign;
6765
6766 typedef bool result_type;
6767 bool failed() { return Failed; }
6768 bool found(APValue &Subobj, QualType SubobjType, APValue::LValueBase Base) {
6769 // We are supposed to perform no initialization but begin the lifetime of
6770 // the object. We interpret that as meaning to do what default
6771 // initialization of the object would do if all constructors involved were
6772 // trivial:
6773 // * All base, non-variant member, and array element subobjects' lifetimes
6774 // begin
6775 // * No variant members' lifetimes begin
6776 // * All scalar subobjects whose lifetimes begin have indeterminate values
6777 assert(SubobjType->isUnionType());
6778 if (declaresSameEntity(Subobj.getUnionField(), Field)) {
6779 // This union member is already active. If it's also in-lifetime, there's
6780 // nothing to do.
6781 if (Subobj.getUnionValue().hasValue())
6782 return true;
6783 } else if (DuringInit) {
6784 // We're currently in the process of initializing a different union
6785 // member. If we carried on, that initialization would attempt to
6786 // store to an inactive union member, resulting in undefined behavior.
6787 Info.FFDiag(LHSExpr,
6788 diag::note_constexpr_union_member_change_during_init);
6789 return false;
6790 }
6792 Failed = !handleDefaultInitValue(Field->getType(), Result);
6793 Subobj.setUnion(Field, Result);
6794 return true;
6795 }
6796 bool found(APSInt &Value, QualType SubobjType) {
6797 llvm_unreachable("wrong value kind for union object");
6798 }
6799 bool found(APFloat &Value, QualType SubobjType) {
6800 llvm_unreachable("wrong value kind for union object");
6801 }
6802};
6803} // end anonymous namespace
6804
6805const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
6806
6807/// Handle a builtin simple-assignment or a call to a trivial assignment
6808/// operator whose left-hand side might involve a union member access. If it
6809/// does, implicitly start the lifetime of any accessed union elements per
6810/// C++20 [class.union]5.
6811static bool MaybeHandleUnionActiveMemberChange(EvalInfo &Info,
6812 const Expr *LHSExpr,
6813 const LValue &LHS) {
6814 if (LHS.InvalidBase || LHS.Designator.Invalid)
6815 return false;
6816
6818 // C++ [class.union]p5:
6819 // define the set S(E) of subexpressions of E as follows:
6820 unsigned PathLength = LHS.Designator.Entries.size();
6821 for (const Expr *E = LHSExpr; E != nullptr;) {
6822 // -- If E is of the form A.B, S(E) contains the elements of S(A)...
6823 if (auto *ME = dyn_cast<MemberExpr>(E)) {
6824 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
6825 // Note that we can't implicitly start the lifetime of a reference,
6826 // so we don't need to proceed any further if we reach one.
6827 if (!FD || FD->getType()->isReferenceType())
6828 break;
6829
6830 // ... and also contains A.B if B names a union member ...
6831 if (FD->getParent()->isUnion()) {
6832 // ... of a non-class, non-array type, or of a class type with a
6833 // trivial default constructor that is not deleted, or an array of
6834 // such types.
6835 auto *RD =
6836 FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6837 if (!RD || RD->hasTrivialDefaultConstructor())
6838 UnionPathLengths.push_back({PathLength - 1, FD});
6839 }
6840
6841 E = ME->getBase();
6842 --PathLength;
6843 assert(declaresSameEntity(FD,
6844 LHS.Designator.Entries[PathLength]
6845 .getAsBaseOrMember().getPointer()));
6846
6847 // -- If E is of the form A[B] and is interpreted as a built-in array
6848 // subscripting operator, S(E) is [S(the array operand, if any)].
6849 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
6850 // Step over an ArrayToPointerDecay implicit cast.
6851 auto *Base = ASE->getBase()->IgnoreImplicit();
6852 if (!Base->getType()->isArrayType())
6853 break;
6854
6855 E = Base;
6856 --PathLength;
6857
6858 } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6859 // Step over a derived-to-base conversion.
6860 E = ICE->getSubExpr();
6861 if (ICE->getCastKind() == CK_NoOp)
6862 continue;
6863 if (ICE->getCastKind() != CK_DerivedToBase &&
6864 ICE->getCastKind() != CK_UncheckedDerivedToBase)
6865 break;
6866 // Walk path backwards as we walk up from the base to the derived class.
6867 for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
6868 if (Elt->isVirtual()) {
6869 // A class with virtual base classes never has a trivial default
6870 // constructor, so S(E) is empty in this case.
6871 E = nullptr;
6872 break;
6873 }
6874
6875 --PathLength;
6876 assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
6877 LHS.Designator.Entries[PathLength]
6878 .getAsBaseOrMember().getPointer()));
6879 }
6880
6881 // -- Otherwise, S(E) is empty.
6882 } else {
6883 break;
6884 }
6885 }
6886
6887 // Common case: no unions' lifetimes are started.
6888 if (UnionPathLengths.empty())
6889 return true;
6890
6891 // if modification of X [would access an inactive union member], an object
6892 // of the type of X is implicitly created
6893 CompleteObject Obj =
6894 findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
6895 if (!Obj)
6896 return false;
6897 for (std::pair<unsigned, const FieldDecl *> LengthAndField :
6898 llvm::reverse(UnionPathLengths)) {
6899 // Form a designator for the union object.
6900 SubobjectDesignator D = LHS.Designator;
6901 D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
6902
6903 bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) ==
6904 ConstructionPhase::AfterBases;
6905 StartLifetimeOfUnionMemberHandler StartLifetime{
6906 Info, LHSExpr, LengthAndField.second, DuringInit};
6907 if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
6908 return false;
6909 }
6910
6911 return true;
6912}
6913
6914static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg,
6915 CallRef Call, EvalInfo &Info, bool NonNull = false,
6916 APValue **EvaluatedArg = nullptr) {
6917 LValue LV;
6918 // Create the parameter slot and register its destruction. For a vararg
6919 // argument, create a temporary.
6920 // FIXME: For calling conventions that destroy parameters in the callee,
6921 // should we consider performing destruction when the function returns
6922 // instead?
6923 APValue &V = PVD ? Info.CurrentCall->createParam(Call, PVD, LV)
6924 : Info.CurrentCall->createTemporary(Arg, Arg->getType(),
6925 ScopeKind::Call, LV);
6926 if (!EvaluateInPlace(V, Info, LV, Arg))
6927 return false;
6928
6929 // Passing a null pointer to an __attribute__((nonnull)) parameter results in
6930 // undefined behavior, so is non-constant.
6931 if (NonNull && V.isLValue() && V.isNullPointer()) {
6932 Info.CCEDiag(Arg, diag::note_non_null_attribute_failed);
6933 return false;
6934 }
6935
6936 if (EvaluatedArg)
6937 *EvaluatedArg = &V;
6938
6939 return true;
6940}
6941
6942/// Evaluate the arguments to a function call.
6943static bool EvaluateArgs(ArrayRef<const Expr *> Args, CallRef Call,
6944 EvalInfo &Info, const FunctionDecl *Callee,
6945 bool RightToLeft = false,
6946 LValue *ObjectArg = nullptr) {
6947 bool Success = true;
6948 llvm::SmallBitVector ForbiddenNullArgs;
6949 if (Callee->hasAttr<NonNullAttr>()) {
6950 ForbiddenNullArgs.resize(Args.size());
6951 for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
6952 if (!Attr->args_size()) {
6953 ForbiddenNullArgs.set();
6954 break;
6955 } else
6956 for (auto Idx : Attr->args()) {
6957 unsigned ASTIdx = Idx.getASTIndex();
6958 if (ASTIdx >= Args.size())
6959 continue;
6960 ForbiddenNullArgs[ASTIdx] = true;
6961 }
6962 }
6963 }
6964 for (unsigned I = 0; I < Args.size(); I++) {
6965 unsigned Idx = RightToLeft ? Args.size() - I - 1 : I;
6966 const ParmVarDecl *PVD =
6967 Idx < Callee->getNumParams() ? Callee->getParamDecl(Idx) : nullptr;
6968 bool NonNull = !ForbiddenNullArgs.empty() && ForbiddenNullArgs[Idx];
6969 APValue *That = nullptr;
6970 if (!EvaluateCallArg(PVD, Args[Idx], Call, Info, NonNull, &That)) {
6971 // If we're checking for a potential constant expression, evaluate all
6972 // initializers even if some of them fail.
6973 if (!Info.noteFailure())
6974 return false;
6975 Success = false;
6976 }
6977 if (PVD && PVD->isExplicitObjectParameter() && That && That->isLValue())
6978 ObjectArg->setFrom(Info.Ctx, *That);
6979 }
6980 return Success;
6981}
6982
6983/// Perform a trivial copy from Param, which is the parameter of a copy or move
6984/// constructor or assignment operator.
6985static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param,
6986 const Expr *E, APValue &Result,
6987 bool CopyObjectRepresentation) {
6988 // Find the reference argument.
6989 CallStackFrame *Frame = Info.CurrentCall;
6990 APValue *RefValue = Info.getParamSlot(Frame->Arguments, Param);
6991 if (!RefValue) {
6992 Info.FFDiag(E);
6993 return false;
6994 }
6995
6996 // Copy out the contents of the RHS object.
6997 LValue RefLValue;
6998 RefLValue.setFrom(Info.Ctx, *RefValue);
7000 Info, E, Param->getType().getNonReferenceType(), RefLValue, Result,
7001 CopyObjectRepresentation);
7002}
7003
7004/// Evaluate a function call.
7006 const FunctionDecl *Callee,
7007 const LValue *ObjectArg, const Expr *E,
7008 ArrayRef<const Expr *> Args, CallRef Call,
7009 const Stmt *Body, EvalInfo &Info,
7010 APValue &Result, const LValue *ResultSlot) {
7011 if (!Info.CheckCallLimit(CallLoc))
7012 return false;
7013
7014 CallStackFrame Frame(Info, E->getSourceRange(), Callee, ObjectArg, E, Call);
7015
7016 // For a trivial copy or move assignment, perform an APValue copy. This is
7017 // essential for unions, where the operations performed by the assignment
7018 // operator cannot be represented as statements.
7019 //
7020 // Skip this for non-union classes with no fields; in that case, the defaulted
7021 // copy/move does not actually read the object.
7022 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
7023 if (MD && MD->isDefaulted() &&
7024 (MD->getParent()->isUnion() ||
7025 (MD->isTrivial() &&
7027 unsigned ExplicitOffset = MD->isExplicitObjectMemberFunction() ? 1 : 0;
7028 assert(ObjectArg &&
7030 APValue RHSValue;
7031 if (!handleTrivialCopy(Info, MD->getParamDecl(0), Args[0], RHSValue,
7032 MD->getParent()->isUnion()))
7033 return false;
7034
7035 LValue Obj;
7036 if (!handleAssignment(Info, Args[ExplicitOffset], *ObjectArg,
7038 RHSValue))
7039 return false;
7040 ObjectArg->moveInto(Result);
7041 return true;
7042 } else if (MD && isLambdaCallOperator(MD)) {
7043 // We're in a lambda; determine the lambda capture field maps unless we're
7044 // just constexpr checking a lambda's call operator. constexpr checking is
7045 // done before the captures have been added to the closure object (unless
7046 // we're inferring constexpr-ness), so we don't have access to them in this
7047 // case. But since we don't need the captures to constexpr check, we can
7048 // just ignore them.
7049 if (!Info.checkingPotentialConstantExpression())
7050 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
7051 Frame.LambdaThisCaptureField);
7052 }
7053
7054 StmtResult Ret = {Result, ResultSlot};
7055 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
7056 if (ESR == ESR_Succeeded) {
7057 if (Callee->getReturnType()->isVoidType())
7058 return true;
7059 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
7060 }
7061 return ESR == ESR_Returned;
7062}
7063
7064/// Evaluate a constructor call.
7065static bool HandleConstructorCall(const Expr *E, const LValue &This,
7066 CallRef Call,
7068 EvalInfo &Info, APValue &Result) {
7069 SourceLocation CallLoc = E->getExprLoc();
7070 if (!Info.CheckCallLimit(CallLoc))
7071 return false;
7072
7073 const CXXRecordDecl *RD = Definition->getParent();
7074 if (RD->getNumVBases()) {
7075 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
7076 return false;
7077 }
7078
7079 EvalInfo::EvaluatingConstructorRAII EvalObj(
7080 Info,
7081 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
7082 RD->getNumBases());
7083 CallStackFrame Frame(Info, E->getSourceRange(), Definition, &This, E, Call);
7084
7085 // FIXME: Creating an APValue just to hold a nonexistent return value is
7086 // wasteful.
7087 APValue RetVal;
7088 StmtResult Ret = {RetVal, nullptr};
7089
7090 // If it's a delegating constructor, delegate.
7091 if (Definition->isDelegatingConstructor()) {
7093 if ((*I)->getInit()->isValueDependent()) {
7094 if (!EvaluateDependentExpr((*I)->getInit(), Info))
7095 return false;
7096 } else {
7097 FullExpressionRAII InitScope(Info);
7098 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) ||
7099 !InitScope.destroy())
7100 return false;
7101 }
7102 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
7103 }
7104
7105 // For a trivial copy or move constructor, perform an APValue copy. This is
7106 // essential for unions (or classes with anonymous union members), where the
7107 // operations performed by the constructor cannot be represented by
7108 // ctor-initializers.
7109 //
7110 // Skip this for empty non-union classes; we should not perform an
7111 // lvalue-to-rvalue conversion on them because their copy constructor does not
7112 // actually read them.
7113 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
7114 (Definition->getParent()->isUnion() ||
7115 (Definition->isTrivial() &&
7117 return handleTrivialCopy(Info, Definition->getParamDecl(0), E, Result,
7118 Definition->getParent()->isUnion());
7119 }
7120
7121 // Reserve space for the struct members.
7122 if (!Result.hasValue()) {
7123 if (!RD->isUnion())
7125 RD->getNumFields());
7126 else
7127 // A union starts with no active member.
7128 Result = APValue((const FieldDecl*)nullptr);
7129 }
7130
7131 if (RD->isInvalidDecl()) return false;
7132 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7133
7134 // A scope for temporaries lifetime-extended by reference members.
7135 BlockScopeRAII LifetimeExtendedScope(Info);
7136
7137 bool Success = true;
7138 unsigned BasesSeen = 0;
7139#ifndef NDEBUG
7141#endif
7143 auto SkipToField = [&](FieldDecl *FD, bool Indirect) {
7144 // We might be initializing the same field again if this is an indirect
7145 // field initialization.
7146 if (FieldIt == RD->field_end() ||
7147 FieldIt->getFieldIndex() > FD->getFieldIndex()) {
7148 assert(Indirect && "fields out of order?");
7149 return;
7150 }
7151
7152 // Default-initialize any fields with no explicit initializer.
7153 for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
7154 assert(FieldIt != RD->field_end() && "missing field?");
7155 if (!FieldIt->isUnnamedBitField())
7157 FieldIt->getType(),
7158 Result.getStructField(FieldIt->getFieldIndex()));
7159 }
7160 ++FieldIt;
7161 };
7162 for (const auto *I : Definition->inits()) {
7163 LValue Subobject = This;
7164 LValue SubobjectParent = This;
7165 APValue *Value = &Result;
7166
7167 // Determine the subobject to initialize.
7168 FieldDecl *FD = nullptr;
7169 if (I->isBaseInitializer()) {
7170 QualType BaseType(I->getBaseClass(), 0);
7171#ifndef NDEBUG
7172 // Non-virtual base classes are initialized in the order in the class
7173 // definition. We have already checked for virtual base classes.
7174 assert(!BaseIt->isVirtual() && "virtual base for literal type");
7175 assert(Info.Ctx.hasSameUnqualifiedType(BaseIt->getType(), BaseType) &&
7176 "base class initializers not in expected order");
7177 ++BaseIt;
7178#endif
7179 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
7180 BaseType->getAsCXXRecordDecl(), &Layout))
7181 return false;
7182 Value = &Result.getStructBase(BasesSeen++);
7183 } else if ((FD = I->getMember())) {
7184 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
7185 return false;
7186 if (RD->isUnion()) {
7187 Result = APValue(FD);
7188 Value = &Result.getUnionValue();
7189 } else {
7190 SkipToField(FD, false);
7191 Value = &Result.getStructField(FD->getFieldIndex());
7192 }
7193 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
7194 // Walk the indirect field decl's chain to find the object to initialize,
7195 // and make sure we've initialized every step along it.
7196 auto IndirectFieldChain = IFD->chain();
7197 for (auto *C : IndirectFieldChain) {
7198 FD = cast<FieldDecl>(C);
7200 // Switch the union field if it differs. This happens if we had
7201 // preceding zero-initialization, and we're now initializing a union
7202 // subobject other than the first.
7203 // FIXME: In this case, the values of the other subobjects are
7204 // specified, since zero-initialization sets all padding bits to zero.
7205 if (!Value->hasValue() ||
7206 (Value->isUnion() &&
7207 !declaresSameEntity(Value->getUnionField(), FD))) {
7208 if (CD->isUnion())
7209 *Value = APValue(FD);
7210 else
7211 // FIXME: This immediately starts the lifetime of all members of
7212 // an anonymous struct. It would be preferable to strictly start
7213 // member lifetime in initialization order.
7214 Success &= handleDefaultInitValue(Info.Ctx.getCanonicalTagType(CD),
7215 *Value);
7216 }
7217 // Store Subobject as its parent before updating it for the last element
7218 // in the chain.
7219 if (C == IndirectFieldChain.back())
7220 SubobjectParent = Subobject;
7221 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
7222 return false;
7223 if (CD->isUnion())
7224 Value = &Value->getUnionValue();
7225 else {
7226 if (C == IndirectFieldChain.front() && !RD->isUnion())
7227 SkipToField(FD, true);
7228 Value = &Value->getStructField(FD->getFieldIndex());
7229 }
7230 }
7231 } else {
7232 llvm_unreachable("unknown base initializer kind");
7233 }
7234
7235 // Need to override This for implicit field initializers as in this case
7236 // This refers to innermost anonymous struct/union containing initializer,
7237 // not to currently constructed class.
7238 const Expr *Init = I->getInit();
7239 if (Init->isValueDependent()) {
7240 if (!EvaluateDependentExpr(Init, Info))
7241 return false;
7242 } else {
7243 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
7245 FullExpressionRAII InitScope(Info);
7246 if (FD && FD->getType()->isReferenceType() &&
7247 !FD->getType()->isFunctionReferenceType()) {
7248 LValue Result;
7250 *Value)) {
7251 if (!Info.noteFailure())
7252 return false;
7253 Success = false;
7254 }
7255 } else if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
7256 (FD && FD->isBitField() &&
7257 !truncateBitfieldValue(Info, Init, *Value, FD))) {
7258 // If we're checking for a potential constant expression, evaluate all
7259 // initializers even if some of them fail.
7260 if (!Info.noteFailure())
7261 return false;
7262 Success = false;
7263 }
7264 }
7265
7266 // This is the point at which the dynamic type of the object becomes this
7267 // class type.
7268 if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
7269 EvalObj.finishedConstructingBases();
7270 }
7271
7272 // Default-initialize any remaining fields.
7273 if (!RD->isUnion()) {
7274 for (; FieldIt != RD->field_end(); ++FieldIt) {
7275 if (!FieldIt->isUnnamedBitField())
7277 FieldIt->getType(),
7278 Result.getStructField(FieldIt->getFieldIndex()));
7279 }
7280 }
7281
7282 EvalObj.finishedConstructingFields();
7283
7284 return Success &&
7285 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed &&
7286 LifetimeExtendedScope.destroy();
7287}
7288
7289static bool HandleConstructorCall(const Expr *E, const LValue &This,
7292 EvalInfo &Info, APValue &Result) {
7293 CallScopeRAII CallScope(Info);
7294 CallRef Call = Info.CurrentCall->createCall(Definition);
7295 if (!EvaluateArgs(Args, Call, Info, Definition))
7296 return false;
7297
7298 return HandleConstructorCall(E, This, Call, Definition, Info, Result) &&
7299 CallScope.destroy();
7300}
7301
7302static bool HandleDestructionImpl(EvalInfo &Info, SourceRange CallRange,
7303 const LValue &This, APValue &Value,
7304 QualType T) {
7305 // Objects can only be destroyed while they're within their lifetimes.
7306 // FIXME: We have no representation for whether an object of type nullptr_t
7307 // is in its lifetime; it usually doesn't matter. Perhaps we should model it
7308 // as indeterminate instead?
7309 if (Value.isAbsent() && !T->isNullPtrType()) {
7310 APValue Printable;
7311 This.moveInto(Printable);
7312 Info.FFDiag(CallRange.getBegin(),
7313 diag::note_constexpr_destroy_out_of_lifetime)
7314 << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T));
7315 return false;
7316 }
7317
7318 // Invent an expression for location purposes.
7319 // FIXME: We shouldn't need to do this.
7320 OpaqueValueExpr LocE(CallRange.getBegin(), Info.Ctx.IntTy, VK_PRValue);
7321
7322 // For arrays, destroy elements right-to-left.
7323 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) {
7324 uint64_t Size = CAT->getZExtSize();
7325 QualType ElemT = CAT->getElementType();
7326
7327 if (!CheckArraySize(Info, CAT, CallRange.getBegin()))
7328 return false;
7329
7330 LValue ElemLV = This;
7331 ElemLV.addArray(Info, &LocE, CAT);
7332 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size))
7333 return false;
7334
7335 // Ensure that we have actual array elements available to destroy; the
7336 // destructors might mutate the value, so we can't run them on the array
7337 // filler.
7338 if (Size && Size > Value.getArrayInitializedElts())
7339 expandArray(Value, Value.getArraySize() - 1);
7340
7341 // The size of the array might have been reduced by
7342 // a placement new.
7343 for (Size = Value.getArraySize(); Size != 0; --Size) {
7344 APValue &Elem = Value.getArrayInitializedElt(Size - 1);
7345 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) ||
7346 !HandleDestructionImpl(Info, CallRange, ElemLV, Elem, ElemT))
7347 return false;
7348 }
7349
7350 // End the lifetime of this array now.
7351 Value = APValue();
7352 return true;
7353 }
7354
7355 const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
7356 if (!RD) {
7357 if (T.isDestructedType()) {
7358 Info.FFDiag(CallRange.getBegin(),
7359 diag::note_constexpr_unsupported_destruction)
7360 << T;
7361 return false;
7362 }
7363
7364 Value = APValue();
7365 return true;
7366 }
7367
7368 if (RD->getNumVBases()) {
7369 Info.FFDiag(CallRange.getBegin(), diag::note_constexpr_virtual_base) << RD;
7370 return false;
7371 }
7372
7373 const CXXDestructorDecl *DD = RD->getDestructor();
7374 if (!DD && !RD->hasTrivialDestructor()) {
7375 Info.FFDiag(CallRange.getBegin());
7376 return false;
7377 }
7378
7379 if (!DD || DD->isTrivial() ||
7380 (RD->isAnonymousStructOrUnion() && RD->isUnion())) {
7381 // A trivial destructor just ends the lifetime of the object. Check for
7382 // this case before checking for a body, because we might not bother
7383 // building a body for a trivial destructor. Note that it doesn't matter
7384 // whether the destructor is constexpr in this case; all trivial
7385 // destructors are constexpr.
7386 //
7387 // If an anonymous union would be destroyed, some enclosing destructor must
7388 // have been explicitly defined, and the anonymous union destruction should
7389 // have no effect.
7390 Value = APValue();
7391 return true;
7392 }
7393
7394 if (!Info.CheckCallLimit(CallRange.getBegin()))
7395 return false;
7396
7397 const FunctionDecl *Definition = nullptr;
7398 const Stmt *Body = DD->getBody(Definition);
7399
7400 if (!CheckConstexprFunction(Info, CallRange.getBegin(), DD, Definition, Body))
7401 return false;
7402
7403 CallStackFrame Frame(Info, CallRange, Definition, &This, /*CallExpr=*/nullptr,
7404 CallRef());
7405
7406 // We're now in the period of destruction of this object.
7407 unsigned BasesLeft = RD->getNumBases();
7408 EvalInfo::EvaluatingDestructorRAII EvalObj(
7409 Info,
7410 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries});
7411 if (!EvalObj.DidInsert) {
7412 // C++2a [class.dtor]p19:
7413 // the behavior is undefined if the destructor is invoked for an object
7414 // whose lifetime has ended
7415 // (Note that formally the lifetime ends when the period of destruction
7416 // begins, even though certain uses of the object remain valid until the
7417 // period of destruction ends.)
7418 Info.FFDiag(CallRange.getBegin(), diag::note_constexpr_double_destroy);
7419 return false;
7420 }
7421
7422 // FIXME: Creating an APValue just to hold a nonexistent return value is
7423 // wasteful.
7424 APValue RetVal;
7425 StmtResult Ret = {RetVal, nullptr};
7426 if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed)
7427 return false;
7428
7429 // A union destructor does not implicitly destroy its members.
7430 if (RD->isUnion())
7431 return true;
7432
7433 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7434
7435 // We don't have a good way to iterate fields in reverse, so collect all the
7436 // fields first and then walk them backwards.
7437 SmallVector<FieldDecl*, 16> Fields(RD->fields());
7438 for (const FieldDecl *FD : llvm::reverse(Fields)) {
7439 if (FD->isUnnamedBitField())
7440 continue;
7441
7442 LValue Subobject = This;
7443 if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout))
7444 return false;
7445
7446 APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex());
7447 if (!HandleDestructionImpl(Info, CallRange, Subobject, *SubobjectValue,
7448 FD->getType()))
7449 return false;
7450 }
7451
7452 if (BasesLeft != 0)
7453 EvalObj.startedDestroyingBases();
7454
7455 // Destroy base classes in reverse order.
7456 for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) {
7457 --BasesLeft;
7458
7459 QualType BaseType = Base.getType();
7460 LValue Subobject = This;
7461 if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD,
7462 BaseType->getAsCXXRecordDecl(), &Layout))
7463 return false;
7464
7465 APValue *SubobjectValue = &Value.getStructBase(BasesLeft);
7466 if (!HandleDestructionImpl(Info, CallRange, Subobject, *SubobjectValue,
7467 BaseType))
7468 return false;
7469 }
7470 assert(BasesLeft == 0 && "NumBases was wrong?");
7471
7472 // The period of destruction ends now. The object is gone.
7473 Value = APValue();
7474 return true;
7475}
7476
7477namespace {
7478struct DestroyObjectHandler {
7479 EvalInfo &Info;
7480 const Expr *E;
7481 const LValue &This;
7482 const AccessKinds AccessKind;
7483
7484 typedef bool result_type;
7485 bool failed() { return false; }
7486 bool found(APValue &Subobj, QualType SubobjType, APValue::LValueBase Base) {
7487 return HandleDestructionImpl(Info, E->getSourceRange(), This, Subobj,
7488 SubobjType);
7489 }
7490 bool found(APSInt &Value, QualType SubobjType) {
7491 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
7492 return false;
7493 }
7494 bool found(APFloat &Value, QualType SubobjType) {
7495 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
7496 return false;
7497 }
7498};
7499}
7500
7501/// Perform a destructor or pseudo-destructor call on the given object, which
7502/// might in general not be a complete object.
7503static bool HandleDestruction(EvalInfo &Info, const Expr *E,
7504 const LValue &This, QualType ThisType) {
7505 CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType);
7506 DestroyObjectHandler Handler = {Info, E, This, AK_Destroy};
7507 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
7508}
7509
7510/// Destroy and end the lifetime of the given complete object.
7511static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
7513 QualType T) {
7514 // If we've had an unmodeled side-effect, we can't rely on mutable state
7515 // (such as the object we're about to destroy) being correct.
7516 if (Info.EvalStatus.HasSideEffects)
7517 return false;
7518
7519 LValue LV;
7520 LV.set({LVBase});
7521 return HandleDestructionImpl(Info, Loc, LV, Value, T);
7522}
7523
7524/// Perform a call to 'operator new' or to `__builtin_operator_new'.
7525static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E,
7526 LValue &Result) {
7527 if (Info.checkingPotentialConstantExpression() ||
7528 Info.SpeculativeEvaluationDepth)
7529 return false;
7530
7531 // This is permitted only within a call to std::allocator<T>::allocate.
7532 auto Caller = Info.getStdAllocatorCaller("allocate");
7533 if (!Caller) {
7534 Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20
7535 ? diag::note_constexpr_new_untyped
7536 : diag::note_constexpr_new);
7537 return false;
7538 }
7539
7540 QualType ElemType = Caller.ElemType;
7541 if (ElemType->isIncompleteType() || ElemType->isFunctionType()) {
7542 Info.FFDiag(E->getExprLoc(),
7543 diag::note_constexpr_new_not_complete_object_type)
7544 << (ElemType->isIncompleteType() ? 0 : 1) << ElemType;
7545 return false;
7546 }
7547
7548 APSInt ByteSize;
7549 if (!EvaluateInteger(E->getArg(0), ByteSize, Info))
7550 return false;
7551 bool IsNothrow = false;
7552 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) {
7553 EvaluateIgnoredValue(Info, E->getArg(I));
7554 IsNothrow |= E->getType()->isNothrowT();
7555 }
7556
7557 CharUnits ElemSize;
7558 if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize))
7559 return false;
7560 APInt Size, Remainder;
7561 APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity());
7562 APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder);
7563 if (Remainder != 0) {
7564 // This likely indicates a bug in the implementation of 'std::allocator'.
7565 Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size)
7566 << ByteSize << APSInt(ElemSizeAP, true) << ElemType;
7567 return false;
7568 }
7569
7570 if (!Info.CheckArraySize(E->getBeginLoc(), ByteSize.getActiveBits(),
7571 Size.getZExtValue(), /*Diag=*/!IsNothrow)) {
7572 if (IsNothrow) {
7573 Result.setNull(Info.Ctx, E->getType());
7574 return true;
7575 }
7576 return false;
7577 }
7578
7579 QualType AllocType = Info.Ctx.getConstantArrayType(
7580 ElemType, Size, nullptr, ArraySizeModifier::Normal, 0);
7581 APValue *Val = Info.createHeapAlloc(Caller.Call, AllocType, Result);
7582 *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue());
7583 Result.addArray(Info, E, cast<ConstantArrayType>(AllocType));
7584 return true;
7585}
7586
7588 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
7589 if (CXXDestructorDecl *DD = RD->getDestructor())
7590 return DD->isVirtual();
7591 return false;
7592}
7593
7595 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
7596 if (CXXDestructorDecl *DD = RD->getDestructor())
7597 return DD->isVirtual() ? DD->getOperatorDelete() : nullptr;
7598 return nullptr;
7599}
7600
7601/// Check that the given object is a suitable pointer to a heap allocation that
7602/// still exists and is of the right kind for the purpose of a deletion.
7603///
7604/// On success, returns the heap allocation to deallocate. On failure, produces
7605/// a diagnostic and returns std::nullopt.
7606static std::optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E,
7607 const LValue &Pointer,
7608 DynAlloc::Kind DeallocKind) {
7609 auto PointerAsString = [&] {
7610 return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy);
7611 };
7612
7613 DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>();
7614 if (!DA) {
7615 Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc)
7616 << PointerAsString();
7617 if (Pointer.Base)
7618 NoteLValueLocation(Info, Pointer.Base);
7619 return std::nullopt;
7620 }
7621
7622 std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
7623 if (!Alloc) {
7624 Info.FFDiag(E, diag::note_constexpr_double_delete);
7625 return std::nullopt;
7626 }
7627
7628 if (DeallocKind != (*Alloc)->getKind()) {
7629 QualType AllocType = Pointer.Base.getDynamicAllocType();
7630 Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch)
7631 << DeallocKind << (*Alloc)->getKind() << AllocType;
7632 NoteLValueLocation(Info, Pointer.Base);
7633 return std::nullopt;
7634 }
7635
7636 bool Subobject = false;
7637 if (DeallocKind == DynAlloc::New) {
7638 Subobject = Pointer.Designator.MostDerivedPathLength != 0 ||
7639 Pointer.Designator.isOnePastTheEnd();
7640 } else {
7641 Subobject = Pointer.Designator.Entries.size() != 1 ||
7642 Pointer.Designator.Entries[0].getAsArrayIndex() != 0;
7643 }
7644 if (Subobject) {
7645 Info.FFDiag(E, diag::note_constexpr_delete_subobject)
7646 << PointerAsString() << Pointer.Designator.isOnePastTheEnd();
7647 return std::nullopt;
7648 }
7649
7650 return Alloc;
7651}
7652
7653// Perform a call to 'operator delete' or '__builtin_operator_delete'.
7654static bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) {
7655 if (Info.checkingPotentialConstantExpression() ||
7656 Info.SpeculativeEvaluationDepth)
7657 return false;
7658
7659 // This is permitted only within a call to std::allocator<T>::deallocate.
7660 if (!Info.getStdAllocatorCaller("deallocate")) {
7661 Info.FFDiag(E->getExprLoc());
7662 return true;
7663 }
7664
7665 LValue Pointer;
7666 if (!EvaluatePointer(E->getArg(0), Pointer, Info))
7667 return false;
7668 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
7669 EvaluateIgnoredValue(Info, E->getArg(I));
7670
7671 if (Pointer.Designator.Invalid)
7672 return false;
7673
7674 // Deleting a null pointer would have no effect, but it's not permitted by
7675 // std::allocator<T>::deallocate's contract.
7676 if (Pointer.isNullPointer()) {
7677 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_deallocate_null);
7678 return true;
7679 }
7680
7681 if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator))
7682 return false;
7683
7684 Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>());
7685 return true;
7686}
7687
7688//===----------------------------------------------------------------------===//
7689// Generic Evaluation
7690//===----------------------------------------------------------------------===//
7691namespace {
7692
7693class BitCastBuffer {
7694 // FIXME: We're going to need bit-level granularity when we support
7695 // bit-fields.
7696 // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
7697 // we don't support a host or target where that is the case. Still, we should
7698 // use a more generic type in case we ever do.
7699 SmallVector<std::optional<unsigned char>, 32> Bytes;
7700
7701 static_assert(std::numeric_limits<unsigned char>::digits >= 8,
7702 "Need at least 8 bit unsigned char");
7703
7704 bool TargetIsLittleEndian;
7705
7706public:
7707 BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
7708 : Bytes(Width.getQuantity()),
7709 TargetIsLittleEndian(TargetIsLittleEndian) {}
7710
7711 [[nodiscard]] bool readObject(CharUnits Offset, CharUnits Width,
7712 SmallVectorImpl<unsigned char> &Output) const {
7713 for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
7714 // If a byte of an integer is uninitialized, then the whole integer is
7715 // uninitialized.
7716 if (!Bytes[I.getQuantity()])
7717 return false;
7718 Output.push_back(*Bytes[I.getQuantity()]);
7719 }
7720 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
7721 std::reverse(Output.begin(), Output.end());
7722 return true;
7723 }
7724
7725 void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
7726 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
7727 std::reverse(Input.begin(), Input.end());
7728
7729 size_t Index = 0;
7730 for (unsigned char Byte : Input) {
7731 assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
7732 Bytes[Offset.getQuantity() + Index] = Byte;
7733 ++Index;
7734 }
7735 }
7736
7737 size_t size() { return Bytes.size(); }
7738};
7739
7740/// Traverse an APValue to produce an BitCastBuffer, emulating how the current
7741/// target would represent the value at runtime.
7742class APValueToBufferConverter {
7743 EvalInfo &Info;
7744 BitCastBuffer Buffer;
7745 const CastExpr *BCE;
7746
7747 APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
7748 const CastExpr *BCE)
7749 : Info(Info),
7750 Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
7751 BCE(BCE) {}
7752
7753 bool visit(const APValue &Val, QualType Ty) {
7754 return visit(Val, Ty, CharUnits::fromQuantity(0));
7755 }
7756
7757 // Write out Val with type Ty into Buffer starting at Offset.
7758 bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
7759 assert((size_t)Offset.getQuantity() <= Buffer.size());
7760
7761 // As a special case, nullptr_t has an indeterminate value.
7762 if (Ty->isNullPtrType())
7763 return true;
7764
7765 // Dig through Src to find the byte at SrcOffset.
7766 switch (Val.getKind()) {
7768 case APValue::None:
7769 return true;
7770
7771 case APValue::Int:
7772 return visitInt(Val.getInt(), Ty, Offset);
7773 case APValue::Float:
7774 return visitFloat(Val.getFloat(), Ty, Offset);
7775 case APValue::Array:
7776 return visitArray(Val, Ty, Offset);
7777 case APValue::Struct:
7778 return visitRecord(Val, Ty, Offset);
7779 case APValue::Vector:
7780 return visitVector(Val, Ty, Offset);
7781
7784 return visitComplex(Val, Ty, Offset);
7786 // FIXME: We should support these.
7787
7788 case APValue::LValue:
7789 case APValue::Matrix:
7790 case APValue::Union:
7793 Info.FFDiag(BCE->getBeginLoc(),
7794 diag::note_constexpr_bit_cast_unsupported_type)
7795 << Ty;
7796 return false;
7797 }
7798 }
7799 llvm_unreachable("Unhandled APValue::ValueKind");
7800 }
7801
7802 bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
7803 const RecordDecl *RD = Ty->getAsRecordDecl();
7804 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7805
7806 // Visit the base classes.
7807 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
7808 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
7809 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
7810 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
7811 const APValue &Base = Val.getStructBase(I);
7812
7813 // Can happen in error cases.
7814 if (!Base.isStruct())
7815 return false;
7816
7817 if (!visitRecord(Base, BS.getType(),
7818 Layout.getBaseClassOffset(BaseDecl) + Offset))
7819 return false;
7820 }
7821 }
7822
7823 // Visit the fields.
7824 unsigned FieldIdx = 0;
7825 for (FieldDecl *FD : RD->fields()) {
7826 if (FD->isBitField()) {
7827 Info.FFDiag(BCE->getBeginLoc(),
7828 diag::note_constexpr_bit_cast_unsupported_bitfield);
7829 return false;
7830 }
7831
7832 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
7833
7834 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
7835 "only bit-fields can have sub-char alignment");
7836 CharUnits FieldOffset =
7837 Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
7838 QualType FieldTy = FD->getType();
7839 if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
7840 return false;
7841 ++FieldIdx;
7842 }
7843
7844 return true;
7845 }
7846
7847 bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
7848 const auto *CAT =
7849 dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
7850 if (!CAT)
7851 return false;
7852
7853 CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
7854 unsigned NumInitializedElts = Val.getArrayInitializedElts();
7855 unsigned ArraySize = Val.getArraySize();
7856 // First, initialize the initialized elements.
7857 for (unsigned I = 0; I != NumInitializedElts; ++I) {
7858 const APValue &SubObj = Val.getArrayInitializedElt(I);
7859 if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
7860 return false;
7861 }
7862
7863 // Next, initialize the rest of the array using the filler.
7864 if (Val.hasArrayFiller()) {
7865 const APValue &Filler = Val.getArrayFiller();
7866 for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
7867 if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
7868 return false;
7869 }
7870 }
7871
7872 return true;
7873 }
7874
7875 bool visitComplex(const APValue &Val, QualType Ty, CharUnits Offset) {
7876 const ComplexType *ComplexTy = Ty->castAs<ComplexType>();
7877 QualType EltTy = ComplexTy->getElementType();
7878 CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
7879 bool IsInt = Val.isComplexInt();
7880
7881 if (IsInt) {
7882 if (!visitInt(Val.getComplexIntReal(), EltTy,
7883 Offset + (0 * EltSizeChars)))
7884 return false;
7885 if (!visitInt(Val.getComplexIntImag(), EltTy,
7886 Offset + (1 * EltSizeChars)))
7887 return false;
7888 } else {
7889 if (!visitFloat(Val.getComplexFloatReal(), EltTy,
7890 Offset + (0 * EltSizeChars)))
7891 return false;
7892 if (!visitFloat(Val.getComplexFloatImag(), EltTy,
7893 Offset + (1 * EltSizeChars)))
7894 return false;
7895 }
7896
7897 return true;
7898 }
7899
7900 bool visitVector(const APValue &Val, QualType Ty, CharUnits Offset) {
7901 const VectorType *VTy = Ty->castAs<VectorType>();
7902 QualType EltTy = VTy->getElementType();
7903 unsigned NElts = VTy->getNumElements();
7904
7905 if (VTy->isPackedVectorBoolType(Info.Ctx)) {
7906 // Special handling for OpenCL bool vectors:
7907 // Since these vectors are stored as packed bits, but we can't write
7908 // individual bits to the BitCastBuffer, we'll buffer all of the elements
7909 // together into an appropriately sized APInt and write them all out at
7910 // once. Because we don't accept vectors where NElts * EltSize isn't a
7911 // multiple of the char size, there will be no padding space, so we don't
7912 // have to worry about writing data which should have been left
7913 // uninitialized.
7914 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
7915
7916 llvm::APInt Res = llvm::APInt::getZero(NElts);
7917 for (unsigned I = 0; I < NElts; ++I) {
7918 const llvm::APSInt &EltAsInt = Val.getVectorElt(I).getInt();
7919 assert(EltAsInt.isUnsigned() && EltAsInt.getBitWidth() == 1 &&
7920 "bool vector element must be 1-bit unsigned integer!");
7921
7922 Res.insertBits(EltAsInt, BigEndian ? (NElts - I - 1) : I);
7923 }
7924
7925 SmallVector<uint8_t, 8> Bytes(NElts / 8);
7926 llvm::StoreIntToMemory(Res, &*Bytes.begin(), NElts / 8);
7927 Buffer.writeObject(Offset, Bytes);
7928 } else {
7929 // Iterate over each of the elements and write them out to the buffer at
7930 // the appropriate offset.
7931 CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
7932 for (unsigned I = 0; I < NElts; ++I) {
7933 if (!visit(Val.getVectorElt(I), EltTy, Offset + I * EltSizeChars))
7934 return false;
7935 }
7936 }
7937
7938 return true;
7939 }
7940
7941 bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
7942 APSInt AdjustedVal = Val;
7943 unsigned Width = AdjustedVal.getBitWidth();
7944 if (Ty->isBooleanType()) {
7945 Width = Info.Ctx.getTypeSize(Ty);
7946 AdjustedVal = AdjustedVal.extend(Width);
7947 }
7948
7949 SmallVector<uint8_t, 8> Bytes(Width / 8);
7950 llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8);
7951 Buffer.writeObject(Offset, Bytes);
7952 return true;
7953 }
7954
7955 bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
7956 APSInt AsInt(Val.bitcastToAPInt());
7957 return visitInt(AsInt, Ty, Offset);
7958 }
7959
7960public:
7961 static std::optional<BitCastBuffer>
7962 convert(EvalInfo &Info, const APValue &Src, const CastExpr *BCE) {
7963 CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
7964 APValueToBufferConverter Converter(Info, DstSize, BCE);
7965 if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
7966 return std::nullopt;
7967 return Converter.Buffer;
7968 }
7969};
7970
7971/// Write an BitCastBuffer into an APValue.
7972class BufferToAPValueConverter {
7973 EvalInfo &Info;
7974 const BitCastBuffer &Buffer;
7975 const CastExpr *BCE;
7976
7977 BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
7978 const CastExpr *BCE)
7979 : Info(Info), Buffer(Buffer), BCE(BCE) {}
7980
7981 // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
7982 // with an invalid type, so anything left is a deficiency on our part (FIXME).
7983 // Ideally this will be unreachable.
7984 std::nullopt_t unsupportedType(QualType Ty) {
7985 Info.FFDiag(BCE->getBeginLoc(),
7986 diag::note_constexpr_bit_cast_unsupported_type)
7987 << Ty;
7988 return std::nullopt;
7989 }
7990
7991 std::nullopt_t unrepresentableValue(QualType Ty, const APSInt &Val) {
7992 Info.FFDiag(BCE->getBeginLoc(),
7993 diag::note_constexpr_bit_cast_unrepresentable_value)
7994 << Ty << toString(Val, /*Radix=*/10);
7995 return std::nullopt;
7996 }
7997
7998 std::optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
7999 const EnumType *EnumSugar = nullptr) {
8000 if (T->isNullPtrType()) {
8001 uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
8002 return APValue((Expr *)nullptr,
8003 /*Offset=*/CharUnits::fromQuantity(NullValue),
8004 APValue::NoLValuePath{}, /*IsNullPtr=*/true);
8005 }
8006
8007 CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
8008
8009 // Work around floating point types that contain unused padding bytes. This
8010 // is really just `long double` on x86, which is the only fundamental type
8011 // with padding bytes.
8012 if (T->isRealFloatingType()) {
8013 const llvm::fltSemantics &Semantics =
8014 Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
8015 unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics);
8016 assert(NumBits % 8 == 0);
8017 CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8);
8018 if (NumBytes != SizeOf)
8019 SizeOf = NumBytes;
8020 }
8021
8022 SmallVector<uint8_t, 8> Bytes;
8023 if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
8024 // If this is std::byte or unsigned char, then its okay to store an
8025 // indeterminate value.
8026 bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
8027 bool IsUChar =
8028 !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
8029 T->isSpecificBuiltinType(BuiltinType::Char_U));
8030 if (!IsStdByte && !IsUChar) {
8031 QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
8032 Info.FFDiag(BCE->getExprLoc(),
8033 diag::note_constexpr_bit_cast_indet_dest)
8034 << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
8035 return std::nullopt;
8036 }
8037
8039 }
8040
8041 APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
8042 llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
8043
8044 if (T->isIntegralOrEnumerationType()) {
8045 Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
8046
8047 unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0));
8048 if (IntWidth != Val.getBitWidth()) {
8049 APSInt Truncated = Val.trunc(IntWidth);
8050 if (Truncated.extend(Val.getBitWidth()) != Val)
8051 return unrepresentableValue(QualType(T, 0), Val);
8052 Val = Truncated;
8053 }
8054
8055 return APValue(Val);
8056 }
8057
8058 if (T->isRealFloatingType()) {
8059 const llvm::fltSemantics &Semantics =
8060 Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
8061 return APValue(APFloat(Semantics, Val));
8062 }
8063
8064 return unsupportedType(QualType(T, 0));
8065 }
8066
8067 std::optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
8068 const RecordDecl *RD = RTy->getAsRecordDecl();
8069 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
8070
8071 unsigned NumBases = 0;
8072 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
8073 NumBases = CXXRD->getNumBases();
8074
8075 APValue ResultVal(APValue::UninitStruct(), NumBases, RD->getNumFields());
8076
8077 // Visit the base classes.
8078 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
8079 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
8080 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
8081 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
8082
8083 std::optional<APValue> SubObj = visitType(
8084 BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
8085 if (!SubObj)
8086 return std::nullopt;
8087 ResultVal.getStructBase(I) = *SubObj;
8088 }
8089 }
8090
8091 // Visit the fields.
8092 unsigned FieldIdx = 0;
8093 for (FieldDecl *FD : RD->fields()) {
8094 // FIXME: We don't currently support bit-fields. A lot of the logic for
8095 // this is in CodeGen, so we need to factor it around.
8096 if (FD->isBitField()) {
8097 Info.FFDiag(BCE->getBeginLoc(),
8098 diag::note_constexpr_bit_cast_unsupported_bitfield);
8099 return std::nullopt;
8100 }
8101
8102 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
8103 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
8104
8105 CharUnits FieldOffset =
8106 CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
8107 Offset;
8108 QualType FieldTy = FD->getType();
8109 std::optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
8110 if (!SubObj)
8111 return std::nullopt;
8112 ResultVal.getStructField(FieldIdx) = *SubObj;
8113 ++FieldIdx;
8114 }
8115
8116 return ResultVal;
8117 }
8118
8119 std::optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
8120 QualType RepresentationType =
8121 Ty->getDecl()->getDefinitionOrSelf()->getIntegerType();
8122 assert(!RepresentationType.isNull() &&
8123 "enum forward decl should be caught by Sema");
8124 const auto *AsBuiltin =
8125 RepresentationType.getCanonicalType()->castAs<BuiltinType>();
8126 // Recurse into the underlying type. Treat std::byte transparently as
8127 // unsigned char.
8128 return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
8129 }
8130
8131 std::optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
8132 size_t Size = Ty->getLimitedSize();
8133 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
8134
8135 APValue ArrayValue(APValue::UninitArray(), Size, Size);
8136 for (size_t I = 0; I != Size; ++I) {
8137 std::optional<APValue> ElementValue =
8138 visitType(Ty->getElementType(), Offset + I * ElementWidth);
8139 if (!ElementValue)
8140 return std::nullopt;
8141 ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
8142 }
8143
8144 return ArrayValue;
8145 }
8146
8147 std::optional<APValue> visit(const ComplexType *Ty, CharUnits Offset) {
8148 QualType ElementType = Ty->getElementType();
8149 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(ElementType);
8150 bool IsInt = ElementType->isIntegerType();
8151
8152 std::optional<APValue> Values[2];
8153 for (unsigned I = 0; I != 2; ++I) {
8154 Values[I] = visitType(Ty->getElementType(), Offset + I * ElementWidth);
8155 if (!Values[I])
8156 return std::nullopt;
8157 }
8158
8159 if (IsInt)
8160 return APValue(Values[0]->getInt(), Values[1]->getInt());
8161 return APValue(Values[0]->getFloat(), Values[1]->getFloat());
8162 }
8163
8164 std::optional<APValue> visit(const VectorType *VTy, CharUnits Offset) {
8165 QualType EltTy = VTy->getElementType();
8166 unsigned NElts = VTy->getNumElements();
8167 unsigned EltSize =
8168 VTy->isPackedVectorBoolType(Info.Ctx) ? 1 : Info.Ctx.getTypeSize(EltTy);
8169
8170 SmallVector<APValue, 4> Elts;
8171 Elts.reserve(NElts);
8172 if (VTy->isPackedVectorBoolType(Info.Ctx)) {
8173 // Special handling for OpenCL bool vectors:
8174 // Since these vectors are stored as packed bits, but we can't read
8175 // individual bits from the BitCastBuffer, we'll buffer all of the
8176 // elements together into an appropriately sized APInt and write them all
8177 // out at once. Because we don't accept vectors where NElts * EltSize
8178 // isn't a multiple of the char size, there will be no padding space, so
8179 // we don't have to worry about reading any padding data which didn't
8180 // actually need to be accessed.
8181 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
8182
8183 SmallVector<uint8_t, 8> Bytes;
8184 Bytes.reserve(NElts / 8);
8185 if (!Buffer.readObject(Offset, CharUnits::fromQuantity(NElts / 8), Bytes))
8186 return std::nullopt;
8187
8188 APSInt SValInt(NElts, true);
8189 llvm::LoadIntFromMemory(SValInt, &*Bytes.begin(), Bytes.size());
8190
8191 for (unsigned I = 0; I < NElts; ++I) {
8192 llvm::APInt Elt =
8193 SValInt.extractBits(1, (BigEndian ? NElts - I - 1 : I) * EltSize);
8194 Elts.emplace_back(
8195 APSInt(std::move(Elt), !EltTy->isSignedIntegerType()));
8196 }
8197 } else {
8198 // Iterate over each of the elements and read them from the buffer at
8199 // the appropriate offset.
8200 CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
8201 for (unsigned I = 0; I < NElts; ++I) {
8202 std::optional<APValue> EltValue =
8203 visitType(EltTy, Offset + I * EltSizeChars);
8204 if (!EltValue)
8205 return std::nullopt;
8206 Elts.push_back(std::move(*EltValue));
8207 }
8208 }
8209
8210 return APValue(Elts.data(), Elts.size());
8211 }
8212
8213 std::optional<APValue> visit(const Type *Ty, CharUnits Offset) {
8214 return unsupportedType(QualType(Ty, 0));
8215 }
8216
8217 std::optional<APValue> visitType(QualType Ty, CharUnits Offset) {
8218 QualType Can = Ty.getCanonicalType();
8219
8220 switch (Can->getTypeClass()) {
8221#define TYPE(Class, Base) \
8222 case Type::Class: \
8223 return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
8224#define ABSTRACT_TYPE(Class, Base)
8225#define NON_CANONICAL_TYPE(Class, Base) \
8226 case Type::Class: \
8227 llvm_unreachable("non-canonical type should be impossible!");
8228#define DEPENDENT_TYPE(Class, Base) \
8229 case Type::Class: \
8230 llvm_unreachable( \
8231 "dependent types aren't supported in the constant evaluator!");
8232#define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base) \
8233 case Type::Class: \
8234 llvm_unreachable("either dependent or not canonical!");
8235#include "clang/AST/TypeNodes.inc"
8236 }
8237 llvm_unreachable("Unhandled Type::TypeClass");
8238 }
8239
8240public:
8241 // Pull out a full value of type DstType.
8242 static std::optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
8243 const CastExpr *BCE) {
8244 BufferToAPValueConverter Converter(Info, Buffer, BCE);
8245 return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
8246 }
8247};
8248
8249static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
8250 QualType Ty, EvalInfo *Info,
8251 const ASTContext &Ctx,
8252 bool CheckingDest) {
8253 Ty = Ty.getCanonicalType();
8254
8255 auto diag = [&](int Reason) {
8256 if (Info)
8257 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
8258 << CheckingDest << (Reason == 4) << Reason;
8259 return false;
8260 };
8261 auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
8262 if (Info)
8263 Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
8264 << NoteTy << Construct << Ty;
8265 return false;
8266 };
8267
8268 if (Ty->isUnionType())
8269 return diag(0);
8270 if (Ty->isPointerType())
8271 return diag(1);
8272 if (Ty->isMemberPointerType())
8273 return diag(2);
8274 if (Ty.isVolatileQualified())
8275 return diag(3);
8276
8277 if (RecordDecl *Record = Ty->getAsRecordDecl()) {
8278 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
8279 for (CXXBaseSpecifier &BS : CXXRD->bases())
8280 if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
8281 CheckingDest))
8282 return note(1, BS.getType(), BS.getBeginLoc());
8283 }
8284 for (FieldDecl *FD : Record->fields()) {
8285 if (FD->getType()->isReferenceType())
8286 return diag(4);
8287 if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
8288 CheckingDest))
8289 return note(0, FD->getType(), FD->getBeginLoc());
8290 }
8291 }
8292
8293 if (Ty->isArrayType() &&
8294 !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
8295 Info, Ctx, CheckingDest))
8296 return false;
8297
8298 if (const auto *VTy = Ty->getAs<VectorType>()) {
8299 QualType EltTy = VTy->getElementType();
8300 unsigned NElts = VTy->getNumElements();
8301 unsigned EltSize =
8302 VTy->isPackedVectorBoolType(Ctx) ? 1 : Ctx.getTypeSize(EltTy);
8303
8304 if ((NElts * EltSize) % Ctx.getCharWidth() != 0) {
8305 // The vector's size in bits is not a multiple of the target's byte size,
8306 // so its layout is unspecified. For now, we'll simply treat these cases
8307 // as unsupported (this should only be possible with OpenCL bool vectors
8308 // whose element count isn't a multiple of the byte size).
8309 if (Info)
8310 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_vector)
8311 << QualType(VTy, 0) << EltSize << NElts << Ctx.getCharWidth();
8312 return false;
8313 }
8314
8315 if (EltTy->isRealFloatingType() &&
8316 &Ctx.getFloatTypeSemantics(EltTy) == &APFloat::x87DoubleExtended()) {
8317 // The layout for x86_fp80 vectors seems to be handled very inconsistently
8318 // by both clang and LLVM, so for now we won't allow bit_casts involving
8319 // it in a constexpr context.
8320 if (Info)
8321 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_unsupported_type)
8322 << EltTy;
8323 return false;
8324 }
8325 }
8326
8327 return true;
8328}
8329
8330static bool checkBitCastConstexprEligibility(EvalInfo *Info,
8331 const ASTContext &Ctx,
8332 const CastExpr *BCE) {
8333 bool DestOK = checkBitCastConstexprEligibilityType(
8334 BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
8335 bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
8336 BCE->getBeginLoc(),
8337 BCE->getSubExpr()->getType(), Info, Ctx, false);
8338 return SourceOK;
8339}
8340
8341static bool handleRValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
8342 const APValue &SourceRValue,
8343 const CastExpr *BCE) {
8344 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
8345 "no host or target supports non 8-bit chars");
8346
8347 if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
8348 return false;
8349
8350 // Read out SourceValue into a char buffer.
8351 std::optional<BitCastBuffer> Buffer =
8352 APValueToBufferConverter::convert(Info, SourceRValue, BCE);
8353 if (!Buffer)
8354 return false;
8355
8356 // Write out the buffer into a new APValue.
8357 std::optional<APValue> MaybeDestValue =
8358 BufferToAPValueConverter::convert(Info, *Buffer, BCE);
8359 if (!MaybeDestValue)
8360 return false;
8361
8362 DestValue = std::move(*MaybeDestValue);
8363 return true;
8364}
8365
8366static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
8367 APValue &SourceValue,
8368 const CastExpr *BCE) {
8369 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
8370 "no host or target supports non 8-bit chars");
8371 assert(SourceValue.isLValue() &&
8372 "LValueToRValueBitcast requires an lvalue operand!");
8373
8374 LValue SourceLValue;
8375 APValue SourceRValue;
8376 SourceLValue.setFrom(Info.Ctx, SourceValue);
8378 Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,
8379 SourceRValue, /*WantObjectRepresentation=*/true))
8380 return false;
8381
8382 return handleRValueToRValueBitCast(Info, DestValue, SourceRValue, BCE);
8383}
8384
8385template <class Derived>
8386class ExprEvaluatorBase
8387 : public ConstStmtVisitor<Derived, bool> {
8388private:
8389 Derived &getDerived() { return static_cast<Derived&>(*this); }
8390 bool DerivedSuccess(const APValue &V, const Expr *E) {
8391 return getDerived().Success(V, E);
8392 }
8393 bool DerivedZeroInitialization(const Expr *E) {
8394 return getDerived().ZeroInitialization(E);
8395 }
8396
8397 // Check whether a conditional operator with a non-constant condition is a
8398 // potential constant expression. If neither arm is a potential constant
8399 // expression, then the conditional operator is not either.
8400 template<typename ConditionalOperator>
8401 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
8402 assert(Info.checkingPotentialConstantExpression());
8403
8404 // Speculatively evaluate both arms.
8405 SmallVector<PartialDiagnosticAt, 8> Diag;
8406 {
8407 SpeculativeEvaluationRAII Speculate(Info, &Diag);
8408 StmtVisitorTy::Visit(E->getFalseExpr());
8409 if (Diag.empty())
8410 return;
8411 }
8412
8413 {
8414 SpeculativeEvaluationRAII Speculate(Info, &Diag);
8415 Diag.clear();
8416 StmtVisitorTy::Visit(E->getTrueExpr());
8417 if (Diag.empty())
8418 return;
8419 }
8420
8421 Error(E, diag::note_constexpr_conditional_never_const);
8422 }
8423
8424
8425 template<typename ConditionalOperator>
8426 bool HandleConditionalOperator(const ConditionalOperator *E) {
8427 bool BoolResult;
8428 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
8429 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
8430 CheckPotentialConstantConditional(E);
8431 return false;
8432 }
8433 if (Info.noteFailure()) {
8434 StmtVisitorTy::Visit(E->getTrueExpr());
8435 StmtVisitorTy::Visit(E->getFalseExpr());
8436 }
8437 return false;
8438 }
8439
8440 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
8441 return StmtVisitorTy::Visit(EvalExpr);
8442 }
8443
8444protected:
8445 EvalInfo &Info;
8446 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
8447 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
8448
8449 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
8450 return Info.CCEDiag(E, D);
8451 }
8452
8453 bool ZeroInitialization(const Expr *E) { return Error(E); }
8454
8455 bool IsConstantEvaluatedBuiltinCall(const CallExpr *E) {
8456 unsigned BuiltinOp = E->getBuiltinCallee();
8457 return BuiltinOp != 0 &&
8458 Info.Ctx.BuiltinInfo.isConstantEvaluated(BuiltinOp);
8459 }
8460
8461public:
8462 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
8463
8464 EvalInfo &getEvalInfo() { return Info; }
8465
8466 /// Report an evaluation error. This should only be called when an error is
8467 /// first discovered. When propagating an error, just return false.
8468 bool Error(const Expr *E, diag::kind D) {
8469 Info.FFDiag(E, D) << E->getSourceRange();
8470 return false;
8471 }
8472 bool Error(const Expr *E) {
8473 return Error(E, diag::note_invalid_subexpr_in_const_expr);
8474 }
8475
8476 bool VisitStmt(const Stmt *) {
8477 llvm_unreachable("Expression evaluator should not be called on stmts");
8478 }
8479 bool VisitExpr(const Expr *E) {
8480 return Error(E);
8481 }
8482
8483 bool VisitEmbedExpr(const EmbedExpr *E) {
8484 const auto It = E->begin();
8485 return StmtVisitorTy::Visit(*It);
8486 }
8487
8488 bool VisitPredefinedExpr(const PredefinedExpr *E) {
8489 return StmtVisitorTy::Visit(E->getFunctionName());
8490 }
8491 bool VisitConstantExpr(const ConstantExpr *E) {
8492 if (E->hasAPValueResult())
8493 return DerivedSuccess(E->getAPValueResult(), E);
8494
8495 return StmtVisitorTy::Visit(E->getSubExpr());
8496 }
8497
8498 bool VisitParenExpr(const ParenExpr *E)
8499 { return StmtVisitorTy::Visit(E->getSubExpr()); }
8500 bool VisitUnaryExtension(const UnaryOperator *E)
8501 { return StmtVisitorTy::Visit(E->getSubExpr()); }
8502 bool VisitUnaryPlus(const UnaryOperator *E)
8503 { return StmtVisitorTy::Visit(E->getSubExpr()); }
8504 bool VisitChooseExpr(const ChooseExpr *E)
8505 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
8506 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
8507 { return StmtVisitorTy::Visit(E->getResultExpr()); }
8508 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
8509 { return StmtVisitorTy::Visit(E->getReplacement()); }
8510 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
8511 TempVersionRAII RAII(*Info.CurrentCall);
8512 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
8513 return StmtVisitorTy::Visit(E->getExpr());
8514 }
8515 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
8516 TempVersionRAII RAII(*Info.CurrentCall);
8517 // The initializer may not have been parsed yet, or might be erroneous.
8518 if (!E->getExpr())
8519 return Error(E);
8520 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
8521 return StmtVisitorTy::Visit(E->getExpr());
8522 }
8523
8524 bool VisitExprWithCleanups(const ExprWithCleanups *E) {
8525 FullExpressionRAII Scope(Info);
8526 return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy();
8527 }
8528
8529 // Temporaries are registered when created, so we don't care about
8530 // CXXBindTemporaryExpr.
8531 bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
8532 return StmtVisitorTy::Visit(E->getSubExpr());
8533 }
8534
8535 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
8536 CCEDiag(E, diag::note_constexpr_invalid_cast)
8537 << diag::ConstexprInvalidCastKind::Reinterpret;
8538 return static_cast<Derived*>(this)->VisitCastExpr(E);
8539 }
8540 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
8541 if (!Info.Ctx.getLangOpts().CPlusPlus20)
8542 CCEDiag(E, diag::note_constexpr_invalid_cast)
8543 << diag::ConstexprInvalidCastKind::Dynamic;
8544 return static_cast<Derived*>(this)->VisitCastExpr(E);
8545 }
8546 bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
8547 return static_cast<Derived*>(this)->VisitCastExpr(E);
8548 }
8549
8550 bool VisitBinaryOperator(const BinaryOperator *E) {
8551 switch (E->getOpcode()) {
8552 default:
8553 return Error(E);
8554
8555 case BO_Comma:
8556 VisitIgnoredValue(E->getLHS());
8557 return StmtVisitorTy::Visit(E->getRHS());
8558
8559 case BO_PtrMemD:
8560 case BO_PtrMemI: {
8561 LValue Obj;
8562 if (!HandleMemberPointerAccess(Info, E, Obj))
8563 return false;
8565 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
8566 return false;
8567 return DerivedSuccess(Result, E);
8568 }
8569 }
8570 }
8571
8572 bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) {
8573 return StmtVisitorTy::Visit(E->getSemanticForm());
8574 }
8575
8576 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
8577 // Evaluate and cache the common expression. We treat it as a temporary,
8578 // even though it's not quite the same thing.
8579 LValue CommonLV;
8580 if (!Evaluate(Info.CurrentCall->createTemporary(
8581 E->getOpaqueValue(),
8582 getStorageType(Info.Ctx, E->getOpaqueValue()),
8583 ScopeKind::FullExpression, CommonLV),
8584 Info, E->getCommon()))
8585 return false;
8586
8587 return HandleConditionalOperator(E);
8588 }
8589
8590 bool VisitConditionalOperator(const ConditionalOperator *E) {
8591 bool IsBcpCall = false;
8592 // If the condition (ignoring parens) is a __builtin_constant_p call,
8593 // the result is a constant expression if it can be folded without
8594 // side-effects. This is an important GNU extension. See GCC PR38377
8595 // for discussion.
8596 if (const CallExpr *CallCE =
8597 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
8598 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
8599 IsBcpCall = true;
8600
8601 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
8602 // constant expression; we can't check whether it's potentially foldable.
8603 // FIXME: We should instead treat __builtin_constant_p as non-constant if
8604 // it would return 'false' in this mode.
8605 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
8606 return false;
8607
8608 FoldConstant Fold(Info, IsBcpCall);
8609 if (!HandleConditionalOperator(E)) {
8610 Fold.keepDiagnostics();
8611 return false;
8612 }
8613
8614 return true;
8615 }
8616
8617 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
8618 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E);
8619 Value && !Value->isAbsent())
8620 return DerivedSuccess(*Value, E);
8621
8622 const Expr *Source = E->getSourceExpr();
8623 if (!Source)
8624 return Error(E);
8625 if (Source == E) {
8626 assert(0 && "OpaqueValueExpr recursively refers to itself");
8627 return Error(E);
8628 }
8629 return StmtVisitorTy::Visit(Source);
8630 }
8631
8632 bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
8633 for (const Expr *SemE : E->semantics()) {
8634 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
8635 // FIXME: We can't handle the case where an OpaqueValueExpr is also the
8636 // result expression: there could be two different LValues that would
8637 // refer to the same object in that case, and we can't model that.
8638 if (SemE == E->getResultExpr())
8639 return Error(E);
8640
8641 // Unique OVEs get evaluated if and when we encounter them when
8642 // emitting the rest of the semantic form, rather than eagerly.
8643 if (OVE->isUnique())
8644 continue;
8645
8646 LValue LV;
8647 if (!Evaluate(Info.CurrentCall->createTemporary(
8648 OVE, getStorageType(Info.Ctx, OVE),
8649 ScopeKind::FullExpression, LV),
8650 Info, OVE->getSourceExpr()))
8651 return false;
8652 } else if (SemE == E->getResultExpr()) {
8653 if (!StmtVisitorTy::Visit(SemE))
8654 return false;
8655 } else {
8656 if (!EvaluateIgnoredValue(Info, SemE))
8657 return false;
8658 }
8659 }
8660 return true;
8661 }
8662
8663 bool VisitCallExpr(const CallExpr *E) {
8665 if (!handleCallExpr(E, Result, nullptr))
8666 return false;
8667 return DerivedSuccess(Result, E);
8668 }
8669
8670 bool handleCallExpr(const CallExpr *E, APValue &Result,
8671 const LValue *ResultSlot) {
8672 CallScopeRAII CallScope(Info);
8673
8674 const Expr *Callee = E->getCallee()->IgnoreParens();
8675 QualType CalleeType = Callee->getType();
8676
8677 const FunctionDecl *FD = nullptr;
8678 LValue *This = nullptr, ObjectArg;
8679 auto Args = ArrayRef(E->getArgs(), E->getNumArgs());
8680 bool HasQualifier = false;
8681
8682 CallRef Call;
8683
8684 // Extract function decl and 'this' pointer from the callee.
8685 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
8686 const CXXMethodDecl *Member = nullptr;
8687 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
8688 // Explicit bound member calls, such as x.f() or p->g();
8689 if (!EvaluateObjectArgument(Info, ME->getBase(), ObjectArg))
8690 return false;
8691 Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
8692 if (!Member)
8693 return Error(Callee);
8694 This = &ObjectArg;
8695 HasQualifier = ME->hasQualifier();
8696 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
8697 // Indirect bound member calls ('.*' or '->*').
8698 const ValueDecl *D =
8699 HandleMemberPointerAccess(Info, BE, ObjectArg, false);
8700 if (!D)
8701 return false;
8702 Member = dyn_cast<CXXMethodDecl>(D);
8703 if (!Member)
8704 return Error(Callee);
8705 This = &ObjectArg;
8706 } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
8707 if (!Info.getLangOpts().CPlusPlus20)
8708 Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
8709 return EvaluateObjectArgument(Info, PDE->getBase(), ObjectArg) &&
8710 HandleDestruction(Info, PDE, ObjectArg, PDE->getDestroyedType());
8711 } else
8712 return Error(Callee);
8713 FD = Member;
8714 } else if (CalleeType->isFunctionPointerType()) {
8715 LValue CalleeLV;
8716 if (!EvaluatePointer(Callee, CalleeLV, Info))
8717 return false;
8718
8719 if (!CalleeLV.getLValueOffset().isZero())
8720 return Error(Callee);
8721 if (CalleeLV.isNullPointer()) {
8722 Info.FFDiag(Callee, diag::note_constexpr_null_callee)
8723 << const_cast<Expr *>(Callee);
8724 return false;
8725 }
8726 FD = dyn_cast_or_null<FunctionDecl>(
8727 CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>());
8728 if (!FD)
8729 return Error(Callee);
8730 // Don't call function pointers which have been cast to some other type.
8731 // Per DR (no number yet), the caller and callee can differ in noexcept.
8732 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
8733 CalleeType->getPointeeType(), FD->getType())) {
8734 return Error(E);
8735 }
8736
8737 // For an (overloaded) assignment expression, evaluate the RHS before the
8738 // LHS.
8739 auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
8740 if (OCE && OCE->isAssignmentOp()) {
8741 assert(Args.size() == 2 && "wrong number of arguments in assignment");
8742 Call = Info.CurrentCall->createCall(FD);
8743 bool HasThis = false;
8744 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
8745 HasThis = MD->isImplicitObjectMemberFunction();
8746 if (!EvaluateArgs(HasThis ? Args.slice(1) : Args, Call, Info, FD,
8747 /*RightToLeft=*/true, &ObjectArg))
8748 return false;
8749 }
8750
8751 // Overloaded operator calls to member functions are represented as normal
8752 // calls with '*this' as the first argument.
8753 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8754 if (MD &&
8755 (MD->isImplicitObjectMemberFunction() || (OCE && MD->isStatic()))) {
8756 // FIXME: When selecting an implicit conversion for an overloaded
8757 // operator delete, we sometimes try to evaluate calls to conversion
8758 // operators without a 'this' parameter!
8759 if (Args.empty())
8760 return Error(E);
8761
8762 if (!EvaluateObjectArgument(Info, Args[0], ObjectArg))
8763 return false;
8764
8765 // If we are calling a static operator, the 'this' argument needs to be
8766 // ignored after being evaluated.
8767 if (MD->isInstance())
8768 This = &ObjectArg;
8769
8770 // If this is syntactically a simple assignment using a trivial
8771 // assignment operator, start the lifetimes of union members as needed,
8772 // per C++20 [class.union]5.
8773 if (Info.getLangOpts().CPlusPlus20 && OCE &&
8774 OCE->getOperator() == OO_Equal && MD->isTrivial() &&
8775 !MaybeHandleUnionActiveMemberChange(Info, Args[0], ObjectArg))
8776 return false;
8777
8778 Args = Args.slice(1);
8779 } else if (MD && MD->isLambdaStaticInvoker()) {
8780 // Map the static invoker for the lambda back to the call operator.
8781 // Conveniently, we don't have to slice out the 'this' argument (as is
8782 // being done for the non-static case), since a static member function
8783 // doesn't have an implicit argument passed in.
8784 const CXXRecordDecl *ClosureClass = MD->getParent();
8785 assert(
8786 ClosureClass->captures().empty() &&
8787 "Number of captures must be zero for conversion to function-ptr");
8788
8789 const CXXMethodDecl *LambdaCallOp =
8790 ClosureClass->getLambdaCallOperator();
8791
8792 // Set 'FD', the function that will be called below, to the call
8793 // operator. If the closure object represents a generic lambda, find
8794 // the corresponding specialization of the call operator.
8795
8796 if (ClosureClass->isGenericLambda()) {
8797 assert(MD->isFunctionTemplateSpecialization() &&
8798 "A generic lambda's static-invoker function must be a "
8799 "template specialization");
8800 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
8801 FunctionTemplateDecl *CallOpTemplate =
8802 LambdaCallOp->getDescribedFunctionTemplate();
8803 void *InsertPos = nullptr;
8804 FunctionDecl *CorrespondingCallOpSpecialization =
8805 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
8806 assert(CorrespondingCallOpSpecialization &&
8807 "We must always have a function call operator specialization "
8808 "that corresponds to our static invoker specialization");
8809 assert(isa<CXXMethodDecl>(CorrespondingCallOpSpecialization));
8810 FD = CorrespondingCallOpSpecialization;
8811 } else
8812 FD = LambdaCallOp;
8814 if (FD->getDeclName().isAnyOperatorNew()) {
8815 LValue Ptr;
8816 if (!HandleOperatorNewCall(Info, E, Ptr))
8817 return false;
8818 Ptr.moveInto(Result);
8819 return CallScope.destroy();
8820 } else {
8821 return HandleOperatorDeleteCall(Info, E) && CallScope.destroy();
8822 }
8823 }
8824 } else
8825 return Error(E);
8826
8827 // Evaluate the arguments now if we've not already done so.
8828 if (!Call) {
8829 Call = Info.CurrentCall->createCall(FD);
8830 if (!EvaluateArgs(Args, Call, Info, FD, /*RightToLeft*/ false,
8831 &ObjectArg))
8832 return false;
8833 }
8834
8835 SmallVector<QualType, 4> CovariantAdjustmentPath;
8836 if (This) {
8837 auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
8838 if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
8839 // Perform virtual dispatch, if necessary.
8840 FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
8841 CovariantAdjustmentPath);
8842 if (!FD)
8843 return false;
8844 } else if (NamedMember && NamedMember->isImplicitObjectMemberFunction()) {
8845 // Check that the 'this' pointer points to an object of the right type.
8846 // FIXME: If this is an assignment operator call, we may need to change
8847 // the active union member before we check this.
8848 if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
8849 return false;
8850 }
8851 }
8852
8853 // Destructor calls are different enough that they have their own codepath.
8854 if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
8855 assert(This && "no 'this' pointer for destructor call");
8856 return HandleDestruction(Info, E, *This,
8857 Info.Ctx.getCanonicalTagType(DD->getParent())) &&
8858 CallScope.destroy();
8859 }
8860
8861 const FunctionDecl *Definition = nullptr;
8862 Stmt *Body = FD->getBody(Definition);
8863 SourceLocation Loc = E->getExprLoc();
8864
8865 // Treat the object argument as `this` when evaluating defaulted
8866 // special menmber functions
8868 This = &ObjectArg;
8869
8870 if (!CheckConstexprFunction(Info, Loc, FD, Definition, Body) ||
8871 !HandleFunctionCall(Loc, Definition, This, E, Args, Call, Body, Info,
8872 Result, ResultSlot))
8873 return false;
8874
8875 if (!CovariantAdjustmentPath.empty() &&
8877 CovariantAdjustmentPath))
8878 return false;
8879
8880 return CallScope.destroy();
8881 }
8882
8883 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
8884 return StmtVisitorTy::Visit(E->getInitializer());
8885 }
8886 bool VisitInitListExpr(const InitListExpr *E) {
8887 if (E->getNumInits() == 0)
8888 return DerivedZeroInitialization(E);
8889 if (E->getNumInits() == 1)
8890 return StmtVisitorTy::Visit(E->getInit(0));
8891 return Error(E);
8892 }
8893 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
8894 return DerivedZeroInitialization(E);
8895 }
8896 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
8897 return DerivedZeroInitialization(E);
8898 }
8899 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
8900 return DerivedZeroInitialization(E);
8901 }
8902
8903 /// A member expression where the object is a prvalue is itself a prvalue.
8904 bool VisitMemberExpr(const MemberExpr *E) {
8905 assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
8906 "missing temporary materialization conversion");
8907 assert(!E->isArrow() && "missing call to bound member function?");
8908
8909 APValue Val;
8910 if (!Evaluate(Val, Info, E->getBase()))
8911 return false;
8912
8913 QualType BaseTy = E->getBase()->getType();
8914
8915 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
8916 if (!FD) return Error(E);
8917 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
8918 assert(BaseTy->castAsCanonical<RecordType>()->getDecl() ==
8919 FD->getParent()->getCanonicalDecl() &&
8920 "record / field mismatch");
8921
8922 // Note: there is no lvalue base here. But this case should only ever
8923 // happen in C or in C++98, where we cannot be evaluating a constexpr
8924 // constructor, which is the only case the base matters.
8925 CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
8926 SubobjectDesignator Designator(BaseTy);
8927 Designator.addDeclUnchecked(FD);
8928
8930 return extractSubobject(Info, E, Obj, Designator, Result) &&
8931 DerivedSuccess(Result, E);
8932 }
8933
8934 bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) {
8935 APValue Val;
8936 if (!Evaluate(Val, Info, E->getBase()))
8937 return false;
8938
8939 if (Val.isVector()) {
8940 SmallVector<uint32_t, 4> Indices;
8941 E->getEncodedElementAccess(Indices);
8942 if (Indices.size() == 1) {
8943 // Return scalar.
8944 return DerivedSuccess(Val.getVectorElt(Indices[0]), E);
8945 } else {
8946 // Construct new APValue vector.
8947 SmallVector<APValue, 4> Elts;
8948 for (unsigned I = 0; I < Indices.size(); ++I) {
8949 Elts.push_back(Val.getVectorElt(Indices[I]));
8950 }
8951 APValue VecResult(Elts.data(), Indices.size());
8952 return DerivedSuccess(VecResult, E);
8953 }
8954 }
8955
8956 return false;
8957 }
8958
8959 bool VisitCastExpr(const CastExpr *E) {
8960 switch (E->getCastKind()) {
8961 default:
8962 break;
8963
8964 case CK_AtomicToNonAtomic: {
8965 APValue AtomicVal;
8966 // This does not need to be done in place even for class/array types:
8967 // atomic-to-non-atomic conversion implies copying the object
8968 // representation.
8969 if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
8970 return false;
8971 return DerivedSuccess(AtomicVal, E);
8972 }
8973
8974 case CK_NoOp:
8975 case CK_UserDefinedConversion:
8976 return StmtVisitorTy::Visit(E->getSubExpr());
8977
8978 case CK_HLSLArrayRValue: {
8979 const Expr *SubExpr = E->getSubExpr();
8980 if (!SubExpr->isGLValue()) {
8981 APValue Val;
8982 if (!Evaluate(Val, Info, SubExpr))
8983 return false;
8984 return DerivedSuccess(Val, E);
8985 }
8986
8987 LValue LVal;
8988 if (!EvaluateLValue(SubExpr, LVal, Info))
8989 return false;
8990 APValue RVal;
8991 // Note, we use the subexpression's type in order to retain cv-qualifiers.
8992 if (!handleLValueToRValueConversion(Info, E, SubExpr->getType(), LVal,
8993 RVal))
8994 return false;
8995 return DerivedSuccess(RVal, E);
8996 }
8997 case CK_LValueToRValue: {
8998 LValue LVal;
8999 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
9000 return false;
9001 APValue RVal;
9002 // Note, we use the subexpression's type in order to retain cv-qualifiers.
9004 LVal, RVal))
9005 return false;
9006 return DerivedSuccess(RVal, E);
9007 }
9008 case CK_LValueToRValueBitCast: {
9009 APValue DestValue, SourceValue;
9010 if (!Evaluate(SourceValue, Info, E->getSubExpr()))
9011 return false;
9012 if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
9013 return false;
9014 return DerivedSuccess(DestValue, E);
9015 }
9016
9017 case CK_AddressSpaceConversion: {
9018 APValue Value;
9019 if (!Evaluate(Value, Info, E->getSubExpr()))
9020 return false;
9021 return DerivedSuccess(Value, E);
9022 }
9023 }
9024
9025 return Error(E);
9026 }
9027
9028 bool VisitUnaryPostInc(const UnaryOperator *UO) {
9029 return VisitUnaryPostIncDec(UO);
9030 }
9031 bool VisitUnaryPostDec(const UnaryOperator *UO) {
9032 return VisitUnaryPostIncDec(UO);
9033 }
9034 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
9035 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9036 return Error(UO);
9037
9038 LValue LVal;
9039 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
9040 return false;
9041 APValue RVal;
9042 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
9043 UO->isIncrementOp(), &RVal))
9044 return false;
9045 return DerivedSuccess(RVal, UO);
9046 }
9047
9048 bool VisitStmtExpr(const StmtExpr *E) {
9049 // We will have checked the full-expressions inside the statement expression
9050 // when they were completed, and don't need to check them again now.
9051 llvm::SaveAndRestore NotCheckingForUB(Info.CheckingForUndefinedBehavior,
9052 false);
9053
9054 const CompoundStmt *CS = E->getSubStmt();
9055 if (CS->body_empty())
9056 return true;
9057
9058 BlockScopeRAII Scope(Info);
9060 BE = CS->body_end();
9061 /**/; ++BI) {
9062 if (BI + 1 == BE) {
9063 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
9064 if (!FinalExpr) {
9065 Info.FFDiag((*BI)->getBeginLoc(),
9066 diag::note_constexpr_stmt_expr_unsupported);
9067 return false;
9068 }
9069 return this->Visit(FinalExpr) && Scope.destroy();
9070 }
9071
9073 StmtResult Result = { ReturnValue, nullptr };
9074 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
9075 if (ESR != ESR_Succeeded) {
9076 // FIXME: If the statement-expression terminated due to 'return',
9077 // 'break', or 'continue', it would be nice to propagate that to
9078 // the outer statement evaluation rather than bailing out.
9079 if (ESR != ESR_Failed)
9080 Info.FFDiag((*BI)->getBeginLoc(),
9081 diag::note_constexpr_stmt_expr_unsupported);
9082 return false;
9083 }
9084 }
9085
9086 llvm_unreachable("Return from function from the loop above.");
9087 }
9088
9089 bool VisitPackIndexingExpr(const PackIndexingExpr *E) {
9090 return StmtVisitorTy::Visit(E->getSelectedExpr());
9091 }
9092
9093 /// Visit a value which is evaluated, but whose value is ignored.
9094 void VisitIgnoredValue(const Expr *E) {
9095 EvaluateIgnoredValue(Info, E);
9096 }
9097
9098 /// Potentially visit a MemberExpr's base expression.
9099 void VisitIgnoredBaseExpression(const Expr *E) {
9100 // While MSVC doesn't evaluate the base expression, it does diagnose the
9101 // presence of side-effecting behavior.
9102 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
9103 return;
9104 VisitIgnoredValue(E);
9105 }
9106};
9107
9108} // namespace
9109
9110//===----------------------------------------------------------------------===//
9111// Common base class for lvalue and temporary evaluation.
9112//===----------------------------------------------------------------------===//
9113namespace {
9114template<class Derived>
9115class LValueExprEvaluatorBase
9116 : public ExprEvaluatorBase<Derived> {
9117protected:
9118 LValue &Result;
9119 bool InvalidBaseOK;
9120 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
9121 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
9122
9123 bool Success(APValue::LValueBase B) {
9124 Result.set(B);
9125 return true;
9126 }
9127
9128 bool evaluatePointer(const Expr *E, LValue &Result) {
9129 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
9130 }
9131
9132public:
9133 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
9134 : ExprEvaluatorBaseTy(Info), Result(Result),
9135 InvalidBaseOK(InvalidBaseOK) {}
9136
9137 bool Success(const APValue &V, const Expr *E) {
9138 Result.setFrom(this->Info.Ctx, V);
9139 return true;
9140 }
9141
9142 bool VisitMemberExpr(const MemberExpr *E) {
9143 // Handle non-static data members.
9144 QualType BaseTy;
9145 bool EvalOK;
9146 if (E->isArrow()) {
9147 EvalOK = evaluatePointer(E->getBase(), Result);
9148 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
9149 } else if (E->getBase()->isPRValue()) {
9150 assert(E->getBase()->getType()->isRecordType());
9151 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
9152 BaseTy = E->getBase()->getType();
9153 } else {
9154 EvalOK = this->Visit(E->getBase());
9155 BaseTy = E->getBase()->getType();
9156 }
9157 if (!EvalOK) {
9158 if (!InvalidBaseOK)
9159 return false;
9160 Result.setInvalid(E);
9161 return true;
9162 }
9163
9164 const ValueDecl *MD = E->getMemberDecl();
9165 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
9166 assert(BaseTy->castAsCanonical<RecordType>()->getDecl() ==
9167 FD->getParent()->getCanonicalDecl() &&
9168 "record / field mismatch");
9169 (void)BaseTy;
9170 if (!HandleLValueMember(this->Info, E, Result, FD))
9171 return false;
9172 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
9173 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
9174 return false;
9175 } else
9176 return this->Error(E);
9177
9178 if (MD->getType()->isReferenceType()) {
9179 APValue RefValue;
9180 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
9181 RefValue))
9182 return false;
9183 return Success(RefValue, E);
9184 }
9185 return true;
9186 }
9187
9188 bool VisitBinaryOperator(const BinaryOperator *E) {
9189 switch (E->getOpcode()) {
9190 default:
9191 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9192
9193 case BO_PtrMemD:
9194 case BO_PtrMemI:
9195 return HandleMemberPointerAccess(this->Info, E, Result);
9196 }
9197 }
9198
9199 bool VisitCastExpr(const CastExpr *E) {
9200 switch (E->getCastKind()) {
9201 default:
9202 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9203
9204 case CK_DerivedToBase:
9205 case CK_UncheckedDerivedToBase:
9206 if (!this->Visit(E->getSubExpr()))
9207 return false;
9208
9209 // Now figure out the necessary offset to add to the base LV to get from
9210 // the derived class to the base class.
9211 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
9212 Result);
9213 }
9214 }
9215};
9216}
9217
9218//===----------------------------------------------------------------------===//
9219// LValue Evaluation
9220//
9221// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
9222// function designators (in C), decl references to void objects (in C), and
9223// temporaries (if building with -Wno-address-of-temporary).
9224//
9225// LValue evaluation produces values comprising a base expression of one of the
9226// following types:
9227// - Declarations
9228// * VarDecl
9229// * FunctionDecl
9230// - Literals
9231// * CompoundLiteralExpr in C (and in global scope in C++)
9232// * StringLiteral
9233// * PredefinedExpr
9234// * ObjCStringLiteralExpr
9235// * ObjCEncodeExpr
9236// * AddrLabelExpr
9237// * BlockExpr
9238// * CallExpr for a MakeStringConstant builtin
9239// - typeid(T) expressions, as TypeInfoLValues
9240// - Locals and temporaries
9241// * MaterializeTemporaryExpr
9242// * Any Expr, with a CallIndex indicating the function in which the temporary
9243// was evaluated, for cases where the MaterializeTemporaryExpr is missing
9244// from the AST (FIXME).
9245// * A MaterializeTemporaryExpr that has static storage duration, with no
9246// CallIndex, for a lifetime-extended temporary.
9247// * The ConstantExpr that is currently being evaluated during evaluation of an
9248// immediate invocation.
9249// plus an offset in bytes.
9250//===----------------------------------------------------------------------===//
9251namespace {
9252class LValueExprEvaluator
9253 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
9254public:
9255 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
9256 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
9257
9258 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
9259 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
9260
9261 bool VisitCallExpr(const CallExpr *E);
9262 bool VisitDeclRefExpr(const DeclRefExpr *E);
9263 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
9264 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
9265 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
9266 bool VisitMemberExpr(const MemberExpr *E);
9267 bool VisitStringLiteral(const StringLiteral *E) {
9268 return Success(
9269 APValue::LValueBase(E, 0, Info.Ctx.getNextStringLiteralVersion()));
9270 }
9271 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
9272 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
9273 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
9274 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
9275 bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E);
9276 bool VisitUnaryDeref(const UnaryOperator *E);
9277 bool VisitUnaryReal(const UnaryOperator *E);
9278 bool VisitUnaryImag(const UnaryOperator *E);
9279 bool VisitUnaryPreInc(const UnaryOperator *UO) {
9280 return VisitUnaryPreIncDec(UO);
9281 }
9282 bool VisitUnaryPreDec(const UnaryOperator *UO) {
9283 return VisitUnaryPreIncDec(UO);
9284 }
9285 bool VisitBinAssign(const BinaryOperator *BO);
9286 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
9287
9288 bool VisitCastExpr(const CastExpr *E) {
9289 switch (E->getCastKind()) {
9290 default:
9291 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
9292
9293 case CK_LValueBitCast:
9294 this->CCEDiag(E, diag::note_constexpr_invalid_cast)
9295 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
9296 << Info.Ctx.getLangOpts().CPlusPlus;
9297 if (!Visit(E->getSubExpr()))
9298 return false;
9299 Result.Designator.setInvalid();
9300 return true;
9301
9302 case CK_BaseToDerived:
9303 if (!Visit(E->getSubExpr()))
9304 return false;
9305 return HandleBaseToDerivedCast(Info, E, Result);
9306
9307 case CK_Dynamic:
9308 if (!Visit(E->getSubExpr()))
9309 return false;
9311 }
9312 }
9313};
9314} // end anonymous namespace
9315
9316/// Get an lvalue to a field of a lambda's closure type.
9317static bool HandleLambdaCapture(EvalInfo &Info, const Expr *E, LValue &Result,
9318 const CXXMethodDecl *MD, const FieldDecl *FD,
9319 bool LValueToRValueConversion) {
9320 // Static lambda function call operators can't have captures. We already
9321 // diagnosed this, so bail out here.
9322 if (MD->isStatic()) {
9323 assert(Info.CurrentCall->This == nullptr &&
9324 "This should not be set for a static call operator");
9325 return false;
9326 }
9327
9328 // Start with 'Result' referring to the complete closure object...
9330 // Self may be passed by reference or by value.
9331 const ParmVarDecl *Self = MD->getParamDecl(0);
9332 if (Self->getType()->isReferenceType()) {
9333 APValue *RefValue = Info.getParamSlot(Info.CurrentCall->Arguments, Self);
9334 if (!RefValue->allowConstexprUnknown() || RefValue->hasValue())
9335 Result.setFrom(Info.Ctx, *RefValue);
9336 } else {
9337 const ParmVarDecl *VD = Info.CurrentCall->Arguments.getOrigParam(Self);
9338 CallStackFrame *Frame =
9339 Info.getCallFrameAndDepth(Info.CurrentCall->Arguments.CallIndex)
9340 .first;
9341 unsigned Version = Info.CurrentCall->Arguments.Version;
9342 Result.set({VD, Frame->Index, Version});
9343 }
9344 } else
9345 Result = *Info.CurrentCall->This;
9346
9347 // ... then update it to refer to the field of the closure object
9348 // that represents the capture.
9349 if (!HandleLValueMember(Info, E, Result, FD))
9350 return false;
9351
9352 // And if the field is of reference type (or if we captured '*this' by
9353 // reference), update 'Result' to refer to what
9354 // the field refers to.
9355 if (LValueToRValueConversion) {
9356 APValue RVal;
9357 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result, RVal))
9358 return false;
9359 Result.setFrom(Info.Ctx, RVal);
9360 }
9361 return true;
9362}
9363
9364/// Evaluate an expression as an lvalue. This can be legitimately called on
9365/// expressions which are not glvalues, in three cases:
9366/// * function designators in C, and
9367/// * "extern void" objects
9368/// * @selector() expressions in Objective-C
9369static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
9370 bool InvalidBaseOK) {
9371 assert(!E->isValueDependent());
9372 assert(E->isGLValue() || E->getType()->isFunctionType() ||
9374 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
9375}
9376
9377bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
9378 const ValueDecl *D = E->getDecl();
9379
9380 // If we are within a lambda's call operator, check whether the 'VD' referred
9381 // to within 'E' actually represents a lambda-capture that maps to a
9382 // data-member/field within the closure object, and if so, evaluate to the
9383 // field or what the field refers to.
9384 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
9386 // We don't always have a complete capture-map when checking or inferring if
9387 // the function call operator meets the requirements of a constexpr function
9388 // - but we don't need to evaluate the captures to determine constexprness
9389 // (dcl.constexpr C++17).
9390 if (Info.checkingPotentialConstantExpression())
9391 return false;
9392
9393 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(D)) {
9394 const auto *MD = cast<CXXMethodDecl>(Info.CurrentCall->Callee);
9395 return HandleLambdaCapture(Info, E, Result, MD, FD,
9396 FD->getType()->isReferenceType());
9397 }
9398 }
9399
9400 if (isa<FunctionDecl, MSGuidDecl, TemplateParamObjectDecl,
9401 UnnamedGlobalConstantDecl>(D))
9402 return Success(cast<ValueDecl>(D));
9403 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
9404 return VisitVarDecl(E, VD);
9405 if (const BindingDecl *BD = dyn_cast<BindingDecl>(D))
9406 return Visit(BD->getBinding());
9407 return Error(E);
9408}
9409
9410bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
9411 CallStackFrame *Frame = nullptr;
9412 unsigned Version = 0;
9413 if (VD->hasLocalStorage()) {
9414 // Only if a local variable was declared in the function currently being
9415 // evaluated, do we expect to be able to find its value in the current
9416 // frame. (Otherwise it was likely declared in an enclosing context and
9417 // could either have a valid evaluatable value (for e.g. a constexpr
9418 // variable) or be ill-formed (and trigger an appropriate evaluation
9419 // diagnostic)).
9420 CallStackFrame *CurrFrame = Info.CurrentCall;
9421 if (CurrFrame->Callee && CurrFrame->Callee->Equals(VD->getDeclContext())) {
9422 // Function parameters are stored in some caller's frame. (Usually the
9423 // immediate caller, but for an inherited constructor they may be more
9424 // distant.)
9425 if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) {
9426 if (CurrFrame->Arguments) {
9427 VD = CurrFrame->Arguments.getOrigParam(PVD);
9428 Frame =
9429 Info.getCallFrameAndDepth(CurrFrame->Arguments.CallIndex).first;
9430 Version = CurrFrame->Arguments.Version;
9431 }
9432 } else {
9433 Frame = CurrFrame;
9434 Version = CurrFrame->getCurrentTemporaryVersion(VD);
9435 }
9436 }
9437 }
9438
9439 if (!VD->getType()->isReferenceType()) {
9440 if (Frame) {
9441 Result.set({VD, Frame->Index, Version});
9442 return true;
9443 }
9444 return Success(VD);
9445 }
9446
9447 if (!Info.getLangOpts().CPlusPlus11) {
9448 Info.CCEDiag(E, diag::note_constexpr_ltor_non_integral, 1)
9449 << VD << VD->getType();
9450 Info.Note(VD->getLocation(), diag::note_declared_at);
9451 }
9452
9453 APValue *V;
9454 if (!evaluateVarDeclInit(Info, E, VD, Frame, Version, V))
9455 return false;
9456
9457 if (!V) {
9458 Result.set(VD);
9459 Result.AllowConstexprUnknown = true;
9460 return true;
9461 }
9462
9463 return Success(*V, E);
9464}
9465
9466bool LValueExprEvaluator::VisitCallExpr(const CallExpr *E) {
9467 if (!IsConstantEvaluatedBuiltinCall(E))
9468 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9469
9470 switch (E->getBuiltinCallee()) {
9471 default:
9472 return false;
9473 case Builtin::BIas_const:
9474 case Builtin::BIforward:
9475 case Builtin::BIforward_like:
9476 case Builtin::BImove:
9477 case Builtin::BImove_if_noexcept:
9478 if (cast<FunctionDecl>(E->getCalleeDecl())->isConstexpr())
9479 return Visit(E->getArg(0));
9480 break;
9481 }
9482
9483 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9484}
9485
9486bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
9487 const MaterializeTemporaryExpr *E) {
9488 // Walk through the expression to find the materialized temporary itself.
9491 const Expr *Inner =
9492 E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
9493
9494 // If we passed any comma operators, evaluate their LHSs.
9495 for (const Expr *E : CommaLHSs)
9496 if (!EvaluateIgnoredValue(Info, E))
9497 return false;
9498
9499 // A materialized temporary with static storage duration can appear within the
9500 // result of a constant expression evaluation, so we need to preserve its
9501 // value for use outside this evaluation.
9502 APValue *Value;
9503 if (E->getStorageDuration() == SD_Static) {
9504 if (Info.EvalMode == EvaluationMode::ConstantFold)
9505 return false;
9506 // FIXME: What about SD_Thread?
9507 Value = E->getOrCreateValue(true);
9508 *Value = APValue();
9509 Result.set(E);
9510 } else {
9511 Value = &Info.CurrentCall->createTemporary(
9512 E, Inner->getType(),
9513 E->getStorageDuration() == SD_FullExpression ? ScopeKind::FullExpression
9514 : ScopeKind::Block,
9515 Result);
9516 }
9517
9518 QualType Type = Inner->getType();
9519
9520 // Materialize the temporary itself.
9521 if (!EvaluateInPlace(*Value, Info, Result, Inner)) {
9522 *Value = APValue();
9523 return false;
9524 }
9525
9526 // Adjust our lvalue to refer to the desired subobject.
9527 for (unsigned I = Adjustments.size(); I != 0; /**/) {
9528 --I;
9529 switch (Adjustments[I].Kind) {
9531 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
9532 Type, Result))
9533 return false;
9534 Type = Adjustments[I].DerivedToBase.BasePath->getType();
9535 break;
9536
9538 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
9539 return false;
9540 Type = Adjustments[I].Field->getType();
9541 break;
9542
9544 if (!HandleMemberPointerAccess(this->Info, Type, Result,
9545 Adjustments[I].Ptr.RHS))
9546 return false;
9547 Type = Adjustments[I].Ptr.MPT->getPointeeType();
9548 break;
9549 }
9550 }
9551
9552 return true;
9553}
9554
9555bool
9556LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
9557 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
9558 "lvalue compound literal in c++?");
9559 APValue *Lit;
9560 // If CompountLiteral has static storage, its value can be used outside
9561 // this expression. So evaluate it once and store it in ASTContext.
9562 if (E->hasStaticStorage()) {
9563 Lit = &E->getOrCreateStaticValue(Info.Ctx);
9564 Result.set(E);
9565 // Reset any previously evaluated state, otherwise evaluation below might
9566 // fail.
9567 // FIXME: Should we just re-use the previously evaluated value instead?
9568 *Lit = APValue();
9569 } else {
9570 assert(!Info.getLangOpts().CPlusPlus);
9571 Lit = &Info.CurrentCall->createTemporary(E, E->getInitializer()->getType(),
9572 ScopeKind::Block, Result);
9573 }
9574 // FIXME: Evaluating in place isn't always right. We should figure out how to
9575 // use appropriate evaluation context here, see
9576 // clang/test/AST/static-compound-literals-reeval.cpp for a failure.
9577 if (!EvaluateInPlace(*Lit, Info, Result, E->getInitializer())) {
9578 *Lit = APValue();
9579 return false;
9580 }
9581 return true;
9582}
9583
9584bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
9585 TypeInfoLValue TypeInfo;
9586
9587 if (!E->isPotentiallyEvaluated()) {
9588 if (E->isTypeOperand())
9589 TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
9590 else
9591 TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
9592 } else {
9593 if (!Info.Ctx.getLangOpts().CPlusPlus20) {
9594 Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
9595 << E->getExprOperand()->getType()
9596 << E->getExprOperand()->getSourceRange();
9597 }
9598
9599 if (!Visit(E->getExprOperand()))
9600 return false;
9601
9602 std::optional<DynamicType> DynType =
9604 if (!DynType)
9605 return false;
9606
9607 TypeInfo = TypeInfoLValue(
9608 Info.Ctx.getCanonicalTagType(DynType->Type).getTypePtr());
9609 }
9610
9611 return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
9612}
9613
9614bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
9615 return Success(E->getGuidDecl());
9616}
9617
9618bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
9619 // Handle static data members.
9620 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
9621 VisitIgnoredBaseExpression(E->getBase());
9622 return VisitVarDecl(E, VD);
9623 }
9624
9625 // Handle static member functions.
9626 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
9627 if (MD->isStatic()) {
9628 VisitIgnoredBaseExpression(E->getBase());
9629 return Success(MD);
9630 }
9631 }
9632
9633 // Handle non-static data members.
9634 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
9635}
9636
9637bool LValueExprEvaluator::VisitExtVectorElementExpr(
9638 const ExtVectorElementExpr *E) {
9639 bool Success = true;
9640
9641 APValue Val;
9642 if (!Evaluate(Val, Info, E->getBase())) {
9643 if (!Info.noteFailure())
9644 return false;
9645 Success = false;
9646 }
9647
9649 E->getEncodedElementAccess(Indices);
9650 // FIXME: support accessing more than one element
9651 if (Indices.size() > 1)
9652 return false;
9653
9654 if (Success) {
9655 Result.setFrom(Info.Ctx, Val);
9656 QualType BaseType = E->getBase()->getType();
9657 if (E->isArrow())
9658 BaseType = BaseType->getPointeeType();
9659 const auto *VT = BaseType->castAs<VectorType>();
9660 HandleLValueVectorElement(Info, E, Result, VT->getElementType(),
9661 VT->getNumElements(), Indices[0]);
9662 }
9663
9664 return Success;
9665}
9666
9667bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
9668 if (E->getBase()->getType()->isSveVLSBuiltinType())
9669 return Error(E);
9670
9671 APSInt Index;
9672 bool Success = true;
9673
9674 if (const auto *VT = E->getBase()->getType()->getAs<VectorType>()) {
9675 APValue Val;
9676 if (!Evaluate(Val, Info, E->getBase())) {
9677 if (!Info.noteFailure())
9678 return false;
9679 Success = false;
9680 }
9681
9682 if (!EvaluateInteger(E->getIdx(), Index, Info)) {
9683 if (!Info.noteFailure())
9684 return false;
9685 Success = false;
9686 }
9687
9688 if (Success) {
9689 Result.setFrom(Info.Ctx, Val);
9690 HandleLValueVectorElement(Info, E, Result, VT->getElementType(),
9691 VT->getNumElements(), Index.getZExtValue());
9692 }
9693
9694 return Success;
9695 }
9696
9697 // C++17's rules require us to evaluate the LHS first, regardless of which
9698 // side is the base.
9699 for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) {
9700 if (SubExpr == E->getBase() ? !evaluatePointer(SubExpr, Result)
9701 : !EvaluateInteger(SubExpr, Index, Info)) {
9702 if (!Info.noteFailure())
9703 return false;
9704 Success = false;
9705 }
9706 }
9707
9708 return Success &&
9709 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
9710}
9711
9712bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
9713 bool Success = evaluatePointer(E->getSubExpr(), Result);
9714 // [C++26][expr.unary.op]
9715 // If the operand points to an object or function, the result
9716 // denotes that object or function; otherwise, the behavior is undefined.
9717 // Because &(*(type*)0) is a common pattern, we do not fail the evaluation
9718 // immediately.
9720 return Success;
9722 E->getType())) ||
9723 Info.noteUndefinedBehavior();
9724}
9725
9726bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
9727 if (!Visit(E->getSubExpr()))
9728 return false;
9729 // __real is a no-op on scalar lvalues.
9730 if (E->getSubExpr()->getType()->isAnyComplexType())
9731 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
9732 return true;
9733}
9734
9735bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
9736 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
9737 "lvalue __imag__ on scalar?");
9738 if (!Visit(E->getSubExpr()))
9739 return false;
9740 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
9741 return true;
9742}
9743
9744bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
9745 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9746 return Error(UO);
9747
9748 if (!this->Visit(UO->getSubExpr()))
9749 return false;
9750
9751 return handleIncDec(
9752 this->Info, UO, Result, UO->getSubExpr()->getType(),
9753 UO->isIncrementOp(), nullptr);
9754}
9755
9756bool LValueExprEvaluator::VisitCompoundAssignOperator(
9757 const CompoundAssignOperator *CAO) {
9758 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9759 return Error(CAO);
9760
9761 bool Success = true;
9762
9763 // C++17 onwards require that we evaluate the RHS first.
9764 APValue RHS;
9765 if (!Evaluate(RHS, this->Info, CAO->getRHS())) {
9766 if (!Info.noteFailure())
9767 return false;
9768 Success = false;
9769 }
9770
9771 // The overall lvalue result is the result of evaluating the LHS.
9772 if (!this->Visit(CAO->getLHS()) || !Success)
9773 return false;
9774
9776 this->Info, CAO,
9777 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
9778 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
9779}
9780
9781bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
9782 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9783 return Error(E);
9784
9785 bool Success = true;
9786
9787 // C++17 onwards require that we evaluate the RHS first.
9788 APValue NewVal;
9789 if (!Evaluate(NewVal, this->Info, E->getRHS())) {
9790 if (!Info.noteFailure())
9791 return false;
9792 Success = false;
9793 }
9794
9795 if (!this->Visit(E->getLHS()) || !Success)
9796 return false;
9797
9798 if (Info.getLangOpts().CPlusPlus20 &&
9800 return false;
9801
9802 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
9803 NewVal);
9804}
9805
9806//===----------------------------------------------------------------------===//
9807// Pointer Evaluation
9808//===----------------------------------------------------------------------===//
9809
9810/// Convenience function. LVal's base must be a call to an alloc_size
9811/// function.
9813 const LValue &LVal,
9814 llvm::APInt &Result) {
9815 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
9816 "Can't get the size of a non alloc_size function");
9817 const auto *Base = LVal.getLValueBase().get<const Expr *>();
9818 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
9819 std::optional<llvm::APInt> Size =
9820 CE->evaluateBytesReturnedByAllocSizeCall(Ctx);
9821 if (!Size)
9822 return false;
9823
9824 Result = std::move(*Size);
9825 return true;
9826}
9827
9828/// Attempts to evaluate the given LValueBase as the result of a call to
9829/// a function with the alloc_size attribute. If it was possible to do so, this
9830/// function will return true, make Result's Base point to said function call,
9831/// and mark Result's Base as invalid.
9833 LValue &Result) {
9834 if (Base.isNull())
9835 return false;
9836
9837 // Because we do no form of static analysis, we only support const variables.
9838 //
9839 // Additionally, we can't support parameters, nor can we support static
9840 // variables (in the latter case, use-before-assign isn't UB; in the former,
9841 // we have no clue what they'll be assigned to).
9842 const auto *VD =
9843 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
9844 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
9845 return false;
9846
9847 const Expr *Init = VD->getAnyInitializer();
9848 if (!Init || Init->getType().isNull())
9849 return false;
9850
9851 const Expr *E = Init->IgnoreParens();
9852 if (!tryUnwrapAllocSizeCall(E))
9853 return false;
9854
9855 // Store E instead of E unwrapped so that the type of the LValue's base is
9856 // what the user wanted.
9857 Result.setInvalid(E);
9858
9859 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
9860 Result.addUnsizedArray(Info, E, Pointee);
9861 return true;
9862}
9863
9864namespace {
9865class PointerExprEvaluator
9866 : public ExprEvaluatorBase<PointerExprEvaluator> {
9867 LValue &Result;
9868 bool InvalidBaseOK;
9869
9870 bool Success(const Expr *E) {
9871 Result.set(E);
9872 return true;
9873 }
9874
9875 bool evaluateLValue(const Expr *E, LValue &Result) {
9876 return EvaluateLValue(E, Result, Info, InvalidBaseOK);
9877 }
9878
9879 bool evaluatePointer(const Expr *E, LValue &Result) {
9880 return EvaluatePointer(E, Result, Info, InvalidBaseOK);
9881 }
9882
9883 bool visitNonBuiltinCallExpr(const CallExpr *E);
9884public:
9885
9886 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
9887 : ExprEvaluatorBaseTy(info), Result(Result),
9888 InvalidBaseOK(InvalidBaseOK) {}
9889
9890 bool Success(const APValue &V, const Expr *E) {
9891 Result.setFrom(Info.Ctx, V);
9892 return true;
9893 }
9894 bool ZeroInitialization(const Expr *E) {
9895 Result.setNull(Info.Ctx, E->getType());
9896 return true;
9897 }
9898
9899 bool VisitBinaryOperator(const BinaryOperator *E);
9900 bool VisitCastExpr(const CastExpr* E);
9901 bool VisitUnaryAddrOf(const UnaryOperator *E);
9902 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
9903 { return Success(E); }
9904 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
9906 return Success(E);
9907 if (Info.noteFailure())
9908 EvaluateIgnoredValue(Info, E->getSubExpr());
9909 return Error(E);
9910 }
9911 bool VisitObjCArrayLiteral(const ObjCArrayLiteral *E) {
9912 return E->isExpressibleAsConstantInitializer() ? Success(E) : Error(E);
9913 }
9914 bool VisitObjCDictionaryLiteral(const ObjCDictionaryLiteral *E) {
9915 return E->isExpressibleAsConstantInitializer() ? Success(E) : Error(E);
9916 }
9917 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
9918 { return Success(E); }
9919 bool VisitCallExpr(const CallExpr *E);
9920 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
9921 bool VisitBlockExpr(const BlockExpr *E) {
9922 if (!E->getBlockDecl()->hasCaptures())
9923 return Success(E);
9924 return Error(E);
9925 }
9926 bool VisitCXXThisExpr(const CXXThisExpr *E) {
9927 auto DiagnoseInvalidUseOfThis = [&] {
9928 if (Info.getLangOpts().CPlusPlus11)
9929 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
9930 else
9931 Info.FFDiag(E);
9932 };
9933
9934 // Can't look at 'this' when checking a potential constant expression.
9935 if (Info.checkingPotentialConstantExpression())
9936 return false;
9937
9938 bool IsExplicitLambda =
9939 isLambdaCallWithExplicitObjectParameter(Info.CurrentCall->Callee);
9940 if (!IsExplicitLambda) {
9941 if (!Info.CurrentCall->This) {
9942 DiagnoseInvalidUseOfThis();
9943 return false;
9944 }
9945
9946 Result = *Info.CurrentCall->This;
9947 }
9948
9949 if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
9950 // Ensure we actually have captured 'this'. If something was wrong with
9951 // 'this' capture, the error would have been previously reported.
9952 // Otherwise we can be inside of a default initialization of an object
9953 // declared by lambda's body, so no need to return false.
9954 if (!Info.CurrentCall->LambdaThisCaptureField) {
9955 if (IsExplicitLambda && !Info.CurrentCall->This) {
9956 DiagnoseInvalidUseOfThis();
9957 return false;
9958 }
9959
9960 return true;
9961 }
9962
9963 const auto *MD = cast<CXXMethodDecl>(Info.CurrentCall->Callee);
9964 return HandleLambdaCapture(
9965 Info, E, Result, MD, Info.CurrentCall->LambdaThisCaptureField,
9966 Info.CurrentCall->LambdaThisCaptureField->getType()->isPointerType());
9967 }
9968 return true;
9969 }
9970
9971 bool VisitCXXNewExpr(const CXXNewExpr *E);
9972
9973 bool VisitSourceLocExpr(const SourceLocExpr *E) {
9974 assert(!E->isIntType() && "SourceLocExpr isn't a pointer type?");
9975 APValue LValResult = E->EvaluateInContext(
9976 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
9977 Result.setFrom(Info.Ctx, LValResult);
9978 return true;
9979 }
9980
9981 bool VisitEmbedExpr(const EmbedExpr *E) {
9982 llvm::report_fatal_error("Not yet implemented for ExprConstant.cpp");
9983 return true;
9984 }
9985
9986 bool VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr *E) {
9987 std::string ResultStr = E->ComputeName(Info.Ctx);
9988
9989 QualType CharTy = Info.Ctx.CharTy.withConst();
9990 APInt Size(Info.Ctx.getTypeSize(Info.Ctx.getSizeType()),
9991 ResultStr.size() + 1);
9992 QualType ArrayTy = Info.Ctx.getConstantArrayType(
9993 CharTy, Size, nullptr, ArraySizeModifier::Normal, 0);
9994
9995 StringLiteral *SL =
9996 StringLiteral::Create(Info.Ctx, ResultStr, StringLiteralKind::Ordinary,
9997 /*Pascal*/ false, ArrayTy, E->getLocation());
9998
9999 evaluateLValue(SL, Result);
10000 Result.addArray(Info, E, cast<ConstantArrayType>(ArrayTy));
10001 return true;
10002 }
10003
10004 // FIXME: Missing: @protocol, @selector
10005};
10006} // end anonymous namespace
10007
10008static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
10009 bool InvalidBaseOK) {
10010 assert(!E->isValueDependent());
10011 assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
10012 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
10013}
10014
10015bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
10016 if (E->getOpcode() != BO_Add &&
10017 E->getOpcode() != BO_Sub)
10018 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10019
10020 const Expr *PExp = E->getLHS();
10021 const Expr *IExp = E->getRHS();
10022 if (IExp->getType()->isPointerType())
10023 std::swap(PExp, IExp);
10024
10025 bool EvalPtrOK = evaluatePointer(PExp, Result);
10026 if (!EvalPtrOK && !Info.noteFailure())
10027 return false;
10028
10029 llvm::APSInt Offset;
10030 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
10031 return false;
10032
10033 if (E->getOpcode() == BO_Sub)
10034 negateAsSigned(Offset);
10035
10036 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
10037 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
10038}
10039
10040bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
10041 return evaluateLValue(E->getSubExpr(), Result);
10042}
10043
10044// Is the provided decl 'std::source_location::current'?
10046 if (!FD)
10047 return false;
10048 const IdentifierInfo *FnII = FD->getIdentifier();
10049 if (!FnII || !FnII->isStr("current"))
10050 return false;
10051
10052 const auto *RD = dyn_cast<RecordDecl>(FD->getParent());
10053 if (!RD)
10054 return false;
10055
10056 const IdentifierInfo *ClassII = RD->getIdentifier();
10057 return RD->isInStdNamespace() && ClassII && ClassII->isStr("source_location");
10058}
10059
10060bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
10061 const Expr *SubExpr = E->getSubExpr();
10062
10063 switch (E->getCastKind()) {
10064 default:
10065 break;
10066 case CK_BitCast:
10067 case CK_CPointerToObjCPointerCast:
10068 case CK_BlockPointerToObjCPointerCast:
10069 case CK_AnyPointerToBlockPointerCast:
10070 case CK_AddressSpaceConversion:
10071 if (!Visit(SubExpr))
10072 return false;
10073 if (E->getType()->isFunctionPointerType() ||
10074 SubExpr->getType()->isFunctionPointerType()) {
10075 // Casting between two function pointer types, or between a function
10076 // pointer and an object pointer, is always a reinterpret_cast.
10077 CCEDiag(E, diag::note_constexpr_invalid_cast)
10078 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
10079 << Info.Ctx.getLangOpts().CPlusPlus;
10080 Result.Designator.setInvalid();
10081 } else if (!E->getType()->isVoidPointerType()) {
10082 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
10083 // permitted in constant expressions in C++11. Bitcasts from cv void* are
10084 // also static_casts, but we disallow them as a resolution to DR1312.
10085 //
10086 // In some circumstances, we permit casting from void* to cv1 T*, when the
10087 // actual pointee object is actually a cv2 T.
10088 bool HasValidResult = !Result.InvalidBase && !Result.Designator.Invalid &&
10089 !Result.IsNullPtr;
10090 bool VoidPtrCastMaybeOK =
10091 Result.IsNullPtr ||
10092 (HasValidResult &&
10093 Info.Ctx.hasSimilarType(Result.Designator.getType(Info.Ctx),
10094 E->getType()->getPointeeType()));
10095 // 1. We'll allow it in std::allocator::allocate, and anything which that
10096 // calls.
10097 // 2. HACK 2022-03-28: Work around an issue with libstdc++'s
10098 // <source_location> header. Fixed in GCC 12 and later (2022-04-??).
10099 // We'll allow it in the body of std::source_location::current. GCC's
10100 // implementation had a parameter of type `void*`, and casts from
10101 // that back to `const __impl*` in its body.
10102 if (VoidPtrCastMaybeOK &&
10103 (Info.getStdAllocatorCaller("allocate") ||
10104 IsDeclSourceLocationCurrent(Info.CurrentCall->Callee) ||
10105 Info.getLangOpts().CPlusPlus26)) {
10106 // Permitted.
10107 } else {
10108 if (SubExpr->getType()->isVoidPointerType() &&
10109 Info.getLangOpts().CPlusPlus) {
10110 if (HasValidResult)
10111 CCEDiag(E, diag::note_constexpr_invalid_void_star_cast)
10112 << SubExpr->getType() << Info.getLangOpts().CPlusPlus26
10113 << Result.Designator.getType(Info.Ctx).getCanonicalType()
10114 << E->getType()->getPointeeType();
10115 else
10116 CCEDiag(E, diag::note_constexpr_invalid_cast)
10117 << diag::ConstexprInvalidCastKind::CastFrom
10118 << SubExpr->getType();
10119 } else
10120 CCEDiag(E, diag::note_constexpr_invalid_cast)
10121 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
10122 << Info.Ctx.getLangOpts().CPlusPlus;
10123 Result.Designator.setInvalid();
10124 }
10125 }
10126 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
10127 ZeroInitialization(E);
10128 return true;
10129
10130 case CK_DerivedToBase:
10131 case CK_UncheckedDerivedToBase:
10132 if (!evaluatePointer(E->getSubExpr(), Result))
10133 return false;
10134 if (!Result.Base && Result.Offset.isZero())
10135 return true;
10136
10137 // Now figure out the necessary offset to add to the base LV to get from
10138 // the derived class to the base class.
10139 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
10140 castAs<PointerType>()->getPointeeType(),
10141 Result);
10142
10143 case CK_BaseToDerived:
10144 if (!Visit(E->getSubExpr()))
10145 return false;
10146 if (!Result.Base && Result.Offset.isZero())
10147 return true;
10148 return HandleBaseToDerivedCast(Info, E, Result);
10149
10150 case CK_Dynamic:
10151 if (!Visit(E->getSubExpr()))
10152 return false;
10154
10155 case CK_NullToPointer:
10156 VisitIgnoredValue(E->getSubExpr());
10157 return ZeroInitialization(E);
10158
10159 case CK_IntegralToPointer: {
10160 CCEDiag(E, diag::note_constexpr_invalid_cast)
10161 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
10162 << Info.Ctx.getLangOpts().CPlusPlus;
10163
10164 APValue Value;
10165 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
10166 break;
10167
10168 if (Value.isInt()) {
10169 unsigned Size = Info.Ctx.getTypeSize(E->getType());
10170 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
10171 if (N == Info.Ctx.getTargetNullPointerValue(E->getType())) {
10172 Result.setNull(Info.Ctx, E->getType());
10173 } else {
10174 Result.Base = (Expr *)nullptr;
10175 Result.InvalidBase = false;
10176 Result.Offset = CharUnits::fromQuantity(N);
10177 Result.Designator.setInvalid();
10178 Result.IsNullPtr = false;
10179 }
10180 return true;
10181 } else {
10182 // In rare instances, the value isn't an lvalue.
10183 // For example, when the value is the difference between the addresses of
10184 // two labels. We reject that as a constant expression because we can't
10185 // compute a valid offset to convert into a pointer.
10186 if (!Value.isLValue())
10187 return false;
10188
10189 // Cast is of an lvalue, no need to change value.
10190 Result.setFrom(Info.Ctx, Value);
10191 return true;
10192 }
10193 }
10194
10195 case CK_ArrayToPointerDecay: {
10196 if (SubExpr->isGLValue()) {
10197 if (!evaluateLValue(SubExpr, Result))
10198 return false;
10199 } else {
10200 APValue &Value = Info.CurrentCall->createTemporary(
10201 SubExpr, SubExpr->getType(), ScopeKind::FullExpression, Result);
10202 if (!EvaluateInPlace(Value, Info, Result, SubExpr))
10203 return false;
10204 }
10205 // The result is a pointer to the first element of the array.
10206 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
10207 if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
10208 Result.addArray(Info, E, CAT);
10209 else
10210 Result.addUnsizedArray(Info, E, AT->getElementType());
10211 return true;
10212 }
10213
10214 case CK_FunctionToPointerDecay:
10215 return evaluateLValue(SubExpr, Result);
10216
10217 case CK_LValueToRValue: {
10218 LValue LVal;
10219 if (!evaluateLValue(E->getSubExpr(), LVal))
10220 return false;
10221
10222 APValue RVal;
10223 // Note, we use the subexpression's type in order to retain cv-qualifiers.
10225 LVal, RVal))
10226 return InvalidBaseOK &&
10227 evaluateLValueAsAllocSize(Info, LVal.Base, Result);
10228 return Success(RVal, E);
10229 }
10230 }
10231
10232 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10233}
10234
10236 UnaryExprOrTypeTrait ExprKind) {
10237 // C++ [expr.alignof]p3:
10238 // When alignof is applied to a reference type, the result is the
10239 // alignment of the referenced type.
10240 T = T.getNonReferenceType();
10241
10242 if (T.getQualifiers().hasUnaligned())
10243 return CharUnits::One();
10244
10245 const bool AlignOfReturnsPreferred =
10246 Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
10247
10248 // __alignof is defined to return the preferred alignment.
10249 // Before 8, clang returned the preferred alignment for alignof and _Alignof
10250 // as well.
10251 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
10252 return Ctx.toCharUnitsFromBits(Ctx.getPreferredTypeAlign(T.getTypePtr()));
10253 // alignof and _Alignof are defined to return the ABI alignment.
10254 else if (ExprKind == UETT_AlignOf)
10255 return Ctx.getTypeAlignInChars(T.getTypePtr());
10256 else
10257 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
10258}
10259
10261 UnaryExprOrTypeTrait ExprKind) {
10262 E = E->IgnoreParens();
10263
10264 // The kinds of expressions that we have special-case logic here for
10265 // should be kept up to date with the special checks for those
10266 // expressions in Sema.
10267
10268 // alignof decl is always accepted, even if it doesn't make sense: we default
10269 // to 1 in those cases.
10270 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
10271 return Ctx.getDeclAlign(DRE->getDecl(),
10272 /*RefAsPointee*/ true);
10273
10274 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
10275 return Ctx.getDeclAlign(ME->getMemberDecl(),
10276 /*RefAsPointee*/ true);
10277
10278 return GetAlignOfType(Ctx, E->getType(), ExprKind);
10279}
10280
10281static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) {
10282 if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>())
10283 return Info.Ctx.getDeclAlign(VD);
10284 if (const auto *E = Value.Base.dyn_cast<const Expr *>())
10285 return GetAlignOfExpr(Info.Ctx, E, UETT_AlignOf);
10286 return GetAlignOfType(Info.Ctx, Value.Base.getTypeInfoType(), UETT_AlignOf);
10287}
10288
10289/// Evaluate the value of the alignment argument to __builtin_align_{up,down},
10290/// __builtin_is_aligned and __builtin_assume_aligned.
10291static bool getAlignmentArgument(const Expr *E, QualType ForType,
10292 EvalInfo &Info, APSInt &Alignment) {
10293 if (!EvaluateInteger(E, Alignment, Info))
10294 return false;
10295 if (Alignment < 0 || !Alignment.isPowerOf2()) {
10296 Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment;
10297 return false;
10298 }
10299 unsigned SrcWidth = Info.Ctx.getIntWidth(ForType);
10300 APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1));
10301 if (APSInt::compareValues(Alignment, MaxValue) > 0) {
10302 Info.FFDiag(E, diag::note_constexpr_alignment_too_big)
10303 << MaxValue << ForType << Alignment;
10304 return false;
10305 }
10306 // Ensure both alignment and source value have the same bit width so that we
10307 // don't assert when computing the resulting value.
10308 APSInt ExtAlignment =
10309 APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true);
10310 assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 &&
10311 "Alignment should not be changed by ext/trunc");
10312 Alignment = ExtAlignment;
10313 assert(Alignment.getBitWidth() == SrcWidth);
10314 return true;
10315}
10316
10317// To be clear: this happily visits unsupported builtins. Better name welcomed.
10318bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
10319 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
10320 return true;
10321
10322 if (!(InvalidBaseOK && E->getCalleeAllocSizeAttr()))
10323 return false;
10324
10325 Result.setInvalid(E);
10326 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
10327 Result.addUnsizedArray(Info, E, PointeeTy);
10328 return true;
10329}
10330
10331bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
10332 if (!IsConstantEvaluatedBuiltinCall(E))
10333 return visitNonBuiltinCallExpr(E);
10334 return VisitBuiltinCallExpr(E, E->getBuiltinCallee());
10335}
10336
10337// Determine if T is a character type for which we guarantee that
10338// sizeof(T) == 1.
10340 return T->isCharType() || T->isChar8Type();
10341}
10342
10343bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
10344 unsigned BuiltinOp) {
10345 if (IsOpaqueConstantCall(E))
10346 return Success(E);
10347
10348 switch (BuiltinOp) {
10349 case Builtin::BIaddressof:
10350 case Builtin::BI__addressof:
10351 case Builtin::BI__builtin_addressof:
10352 return evaluateLValue(E->getArg(0), Result);
10353 case Builtin::BI__builtin_assume_aligned: {
10354 // We need to be very careful here because: if the pointer does not have the
10355 // asserted alignment, then the behavior is undefined, and undefined
10356 // behavior is non-constant.
10357 if (!evaluatePointer(E->getArg(0), Result))
10358 return false;
10359
10360 LValue OffsetResult(Result);
10361 APSInt Alignment;
10362 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
10363 Alignment))
10364 return false;
10365 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
10366
10367 if (E->getNumArgs() > 2) {
10368 APSInt Offset;
10369 if (!EvaluateInteger(E->getArg(2), Offset, Info))
10370 return false;
10371
10372 int64_t AdditionalOffset = -Offset.getZExtValue();
10373 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
10374 }
10375
10376 // If there is a base object, then it must have the correct alignment.
10377 if (OffsetResult.Base) {
10378 CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult);
10379
10380 if (BaseAlignment < Align) {
10381 Result.Designator.setInvalid();
10382 CCEDiag(E->getArg(0), diag::note_constexpr_baa_insufficient_alignment)
10383 << 0 << BaseAlignment.getQuantity() << Align.getQuantity();
10384 return false;
10385 }
10386 }
10387
10388 // The offset must also have the correct alignment.
10389 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
10390 Result.Designator.setInvalid();
10391
10392 (OffsetResult.Base
10393 ? CCEDiag(E->getArg(0),
10394 diag::note_constexpr_baa_insufficient_alignment)
10395 << 1
10396 : CCEDiag(E->getArg(0),
10397 diag::note_constexpr_baa_value_insufficient_alignment))
10398 << OffsetResult.Offset.getQuantity() << Align.getQuantity();
10399 return false;
10400 }
10401
10402 return true;
10403 }
10404 case Builtin::BI__builtin_align_up:
10405 case Builtin::BI__builtin_align_down: {
10406 if (!evaluatePointer(E->getArg(0), Result))
10407 return false;
10408 APSInt Alignment;
10409 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
10410 Alignment))
10411 return false;
10412 CharUnits BaseAlignment = getBaseAlignment(Info, Result);
10413 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset);
10414 // For align_up/align_down, we can return the same value if the alignment
10415 // is known to be greater or equal to the requested value.
10416 if (PtrAlign.getQuantity() >= Alignment)
10417 return true;
10418
10419 // The alignment could be greater than the minimum at run-time, so we cannot
10420 // infer much about the resulting pointer value. One case is possible:
10421 // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we
10422 // can infer the correct index if the requested alignment is smaller than
10423 // the base alignment so we can perform the computation on the offset.
10424 if (BaseAlignment.getQuantity() >= Alignment) {
10425 assert(Alignment.getBitWidth() <= 64 &&
10426 "Cannot handle > 64-bit address-space");
10427 uint64_t Alignment64 = Alignment.getZExtValue();
10428 CharUnits NewOffset = CharUnits::fromQuantity(
10429 BuiltinOp == Builtin::BI__builtin_align_down
10430 ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64)
10431 : llvm::alignTo(Result.Offset.getQuantity(), Alignment64));
10432 Result.adjustOffset(NewOffset - Result.Offset);
10433 // TODO: diagnose out-of-bounds values/only allow for arrays?
10434 return true;
10435 }
10436 // Otherwise, we cannot constant-evaluate the result.
10437 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust)
10438 << Alignment;
10439 return false;
10440 }
10441 case Builtin::BI__builtin_operator_new:
10442 return HandleOperatorNewCall(Info, E, Result);
10443 case Builtin::BI__builtin_launder:
10444 return evaluatePointer(E->getArg(0), Result);
10445 case Builtin::BIstrchr:
10446 case Builtin::BIwcschr:
10447 case Builtin::BImemchr:
10448 case Builtin::BIwmemchr:
10449 if (Info.getLangOpts().CPlusPlus11)
10450 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
10451 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
10452 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
10453 else
10454 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
10455 [[fallthrough]];
10456 case Builtin::BI__builtin_strchr:
10457 case Builtin::BI__builtin_wcschr:
10458 case Builtin::BI__builtin_memchr:
10459 case Builtin::BI__builtin_char_memchr:
10460 case Builtin::BI__builtin_wmemchr: {
10461 if (!Visit(E->getArg(0)))
10462 return false;
10463 APSInt Desired;
10464 if (!EvaluateInteger(E->getArg(1), Desired, Info))
10465 return false;
10466 uint64_t MaxLength = uint64_t(-1);
10467 if (BuiltinOp != Builtin::BIstrchr &&
10468 BuiltinOp != Builtin::BIwcschr &&
10469 BuiltinOp != Builtin::BI__builtin_strchr &&
10470 BuiltinOp != Builtin::BI__builtin_wcschr) {
10471 APSInt N;
10472 if (!EvaluateInteger(E->getArg(2), N, Info))
10473 return false;
10474 MaxLength = N.getZExtValue();
10475 }
10476 // We cannot find the value if there are no candidates to match against.
10477 if (MaxLength == 0u)
10478 return ZeroInitialization(E);
10479 if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
10480 Result.Designator.Invalid)
10481 return false;
10482 QualType CharTy = Result.Designator.getType(Info.Ctx);
10483 bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
10484 BuiltinOp == Builtin::BI__builtin_memchr;
10485 assert(IsRawByte ||
10486 Info.Ctx.hasSameUnqualifiedType(
10487 CharTy, E->getArg(0)->getType()->getPointeeType()));
10488 // Pointers to const void may point to objects of incomplete type.
10489 if (IsRawByte && CharTy->isIncompleteType()) {
10490 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
10491 return false;
10492 }
10493 // Give up on byte-oriented matching against multibyte elements.
10494 // FIXME: We can compare the bytes in the correct order.
10495 if (IsRawByte && !isOneByteCharacterType(CharTy)) {
10496 Info.FFDiag(E, diag::note_constexpr_memchr_unsupported)
10497 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp) << CharTy;
10498 return false;
10499 }
10500 // Figure out what value we're actually looking for (after converting to
10501 // the corresponding unsigned type if necessary).
10502 uint64_t DesiredVal;
10503 bool StopAtNull = false;
10504 switch (BuiltinOp) {
10505 case Builtin::BIstrchr:
10506 case Builtin::BI__builtin_strchr:
10507 // strchr compares directly to the passed integer, and therefore
10508 // always fails if given an int that is not a char.
10509 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
10510 E->getArg(1)->getType(),
10511 Desired),
10512 Desired))
10513 return ZeroInitialization(E);
10514 StopAtNull = true;
10515 [[fallthrough]];
10516 case Builtin::BImemchr:
10517 case Builtin::BI__builtin_memchr:
10518 case Builtin::BI__builtin_char_memchr:
10519 // memchr compares by converting both sides to unsigned char. That's also
10520 // correct for strchr if we get this far (to cope with plain char being
10521 // unsigned in the strchr case).
10522 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
10523 break;
10524
10525 case Builtin::BIwcschr:
10526 case Builtin::BI__builtin_wcschr:
10527 StopAtNull = true;
10528 [[fallthrough]];
10529 case Builtin::BIwmemchr:
10530 case Builtin::BI__builtin_wmemchr:
10531 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
10532 DesiredVal = Desired.getZExtValue();
10533 break;
10534 }
10535
10536 for (; MaxLength; --MaxLength) {
10537 APValue Char;
10538 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
10539 !Char.isInt())
10540 return false;
10541 if (Char.getInt().getZExtValue() == DesiredVal)
10542 return true;
10543 if (StopAtNull && !Char.getInt())
10544 break;
10545 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
10546 return false;
10547 }
10548 // Not found: return nullptr.
10549 return ZeroInitialization(E);
10550 }
10551
10552 case Builtin::BImemcpy:
10553 case Builtin::BImemmove:
10554 case Builtin::BIwmemcpy:
10555 case Builtin::BIwmemmove:
10556 if (Info.getLangOpts().CPlusPlus11)
10557 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
10558 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
10559 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
10560 else
10561 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
10562 [[fallthrough]];
10563 case Builtin::BI__builtin_memcpy:
10564 case Builtin::BI__builtin_memmove:
10565 case Builtin::BI__builtin_wmemcpy:
10566 case Builtin::BI__builtin_wmemmove: {
10567 bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
10568 BuiltinOp == Builtin::BIwmemmove ||
10569 BuiltinOp == Builtin::BI__builtin_wmemcpy ||
10570 BuiltinOp == Builtin::BI__builtin_wmemmove;
10571 bool Move = BuiltinOp == Builtin::BImemmove ||
10572 BuiltinOp == Builtin::BIwmemmove ||
10573 BuiltinOp == Builtin::BI__builtin_memmove ||
10574 BuiltinOp == Builtin::BI__builtin_wmemmove;
10575
10576 // The result of mem* is the first argument.
10577 if (!Visit(E->getArg(0)))
10578 return false;
10579 LValue Dest = Result;
10580
10581 LValue Src;
10582 if (!EvaluatePointer(E->getArg(1), Src, Info))
10583 return false;
10584
10585 APSInt N;
10586 if (!EvaluateInteger(E->getArg(2), N, Info))
10587 return false;
10588 assert(!N.isSigned() && "memcpy and friends take an unsigned size");
10589
10590 // If the size is zero, we treat this as always being a valid no-op.
10591 // (Even if one of the src and dest pointers is null.)
10592 if (!N)
10593 return true;
10594
10595 // Otherwise, if either of the operands is null, we can't proceed. Don't
10596 // try to determine the type of the copied objects, because there aren't
10597 // any.
10598 if (!Src.Base || !Dest.Base) {
10599 APValue Val;
10600 (!Src.Base ? Src : Dest).moveInto(Val);
10601 Info.FFDiag(E, diag::note_constexpr_memcpy_null)
10602 << Move << WChar << !!Src.Base
10603 << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
10604 return false;
10605 }
10606 if (Src.Designator.Invalid || Dest.Designator.Invalid)
10607 return false;
10608
10609 // We require that Src and Dest are both pointers to arrays of
10610 // trivially-copyable type. (For the wide version, the designator will be
10611 // invalid if the designated object is not a wchar_t.)
10612 QualType T = Dest.Designator.getType(Info.Ctx);
10613 QualType SrcT = Src.Designator.getType(Info.Ctx);
10614 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
10615 // FIXME: Consider using our bit_cast implementation to support this.
10616 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
10617 return false;
10618 }
10619 if (T->isIncompleteType()) {
10620 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
10621 return false;
10622 }
10623 if (!T.isTriviallyCopyableType(Info.Ctx)) {
10624 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
10625 return false;
10626 }
10627
10628 // Figure out how many T's we're copying.
10629 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
10630 if (TSize == 0)
10631 return false;
10632 if (!WChar) {
10633 uint64_t Remainder;
10634 llvm::APInt OrigN = N;
10635 llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
10636 if (Remainder) {
10637 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
10638 << Move << WChar << 0 << T << toString(OrigN, 10, /*Signed*/false)
10639 << (unsigned)TSize;
10640 return false;
10641 }
10642 }
10643
10644 // Check that the copying will remain within the arrays, just so that we
10645 // can give a more meaningful diagnostic. This implicitly also checks that
10646 // N fits into 64 bits.
10647 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
10648 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
10649 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
10650 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
10651 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
10652 << toString(N, 10, /*Signed*/false);
10653 return false;
10654 }
10655 uint64_t NElems = N.getZExtValue();
10656 uint64_t NBytes = NElems * TSize;
10657
10658 // Check for overlap.
10659 int Direction = 1;
10660 if (HasSameBase(Src, Dest)) {
10661 uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
10662 uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
10663 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
10664 // Dest is inside the source region.
10665 if (!Move) {
10666 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
10667 return false;
10668 }
10669 // For memmove and friends, copy backwards.
10670 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
10671 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
10672 return false;
10673 Direction = -1;
10674 } else if (!Move && SrcOffset >= DestOffset &&
10675 SrcOffset - DestOffset < NBytes) {
10676 // Src is inside the destination region for memcpy: invalid.
10677 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
10678 return false;
10679 }
10680 }
10681
10682 while (true) {
10683 APValue Val;
10684 // FIXME: Set WantObjectRepresentation to true if we're copying a
10685 // char-like type?
10686 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
10687 !handleAssignment(Info, E, Dest, T, Val))
10688 return false;
10689 // Do not iterate past the last element; if we're copying backwards, that
10690 // might take us off the start of the array.
10691 if (--NElems == 0)
10692 return true;
10693 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
10694 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
10695 return false;
10696 }
10697 }
10698
10699 default:
10700 return false;
10701 }
10702}
10703
10704static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
10705 APValue &Result, const InitListExpr *ILE,
10706 QualType AllocType);
10707static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
10708 APValue &Result,
10709 const CXXConstructExpr *CCE,
10710 QualType AllocType);
10711
10712bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) {
10713 if (!Info.getLangOpts().CPlusPlus20)
10714 Info.CCEDiag(E, diag::note_constexpr_new);
10715
10716 // We cannot speculatively evaluate a delete expression.
10717 if (Info.SpeculativeEvaluationDepth)
10718 return false;
10719
10720 FunctionDecl *OperatorNew = E->getOperatorNew();
10721 QualType AllocType = E->getAllocatedType();
10722 QualType TargetType = AllocType;
10723
10724 bool IsNothrow = false;
10725 bool IsPlacement = false;
10726
10727 if (E->getNumPlacementArgs() == 1 &&
10728 E->getPlacementArg(0)->getType()->isNothrowT()) {
10729 // The only new-placement list we support is of the form (std::nothrow).
10730 //
10731 // FIXME: There is no restriction on this, but it's not clear that any
10732 // other form makes any sense. We get here for cases such as:
10733 //
10734 // new (std::align_val_t{N}) X(int)
10735 //
10736 // (which should presumably be valid only if N is a multiple of
10737 // alignof(int), and in any case can't be deallocated unless N is
10738 // alignof(X) and X has new-extended alignment).
10739 LValue Nothrow;
10740 if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info))
10741 return false;
10742 IsNothrow = true;
10743 } else if (OperatorNew->isReservedGlobalPlacementOperator()) {
10744 if (Info.CurrentCall->isStdFunction() || Info.getLangOpts().CPlusPlus26 ||
10745 (Info.CurrentCall->CanEvalMSConstexpr &&
10746 OperatorNew->hasAttr<MSConstexprAttr>())) {
10747 if (!EvaluatePointer(E->getPlacementArg(0), Result, Info))
10748 return false;
10749 if (Result.Designator.Invalid)
10750 return false;
10751 TargetType = E->getPlacementArg(0)->getType();
10752 IsPlacement = true;
10753 } else {
10754 Info.FFDiag(E, diag::note_constexpr_new_placement)
10755 << /*C++26 feature*/ 1 << E->getSourceRange();
10756 return false;
10757 }
10758 } else if (E->getNumPlacementArgs()) {
10759 Info.FFDiag(E, diag::note_constexpr_new_placement)
10760 << /*Unsupported*/ 0 << E->getSourceRange();
10761 return false;
10762 } else if (!OperatorNew
10763 ->isUsableAsGlobalAllocationFunctionInConstantEvaluation()) {
10764 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
10765 << isa<CXXMethodDecl>(OperatorNew) << OperatorNew;
10766 return false;
10767 }
10768
10769 const Expr *Init = E->getInitializer();
10770 const InitListExpr *ResizedArrayILE = nullptr;
10771 const CXXConstructExpr *ResizedArrayCCE = nullptr;
10772 bool ValueInit = false;
10773
10774 if (std::optional<const Expr *> ArraySize = E->getArraySize()) {
10775 const Expr *Stripped = *ArraySize;
10776 for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
10777 Stripped = ICE->getSubExpr())
10778 if (ICE->getCastKind() != CK_NoOp &&
10779 ICE->getCastKind() != CK_IntegralCast)
10780 break;
10781
10782 llvm::APSInt ArrayBound;
10783 if (!EvaluateInteger(Stripped, ArrayBound, Info))
10784 return false;
10785
10786 // C++ [expr.new]p9:
10787 // The expression is erroneous if:
10788 // -- [...] its value before converting to size_t [or] applying the
10789 // second standard conversion sequence is less than zero
10790 if (ArrayBound.isSigned() && ArrayBound.isNegative()) {
10791 if (IsNothrow)
10792 return ZeroInitialization(E);
10793
10794 Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative)
10795 << ArrayBound << (*ArraySize)->getSourceRange();
10796 return false;
10797 }
10798
10799 // -- its value is such that the size of the allocated object would
10800 // exceed the implementation-defined limit
10801 if (!Info.CheckArraySize(ArraySize.value()->getExprLoc(),
10803 Info.Ctx, AllocType, ArrayBound),
10804 ArrayBound.getZExtValue(), /*Diag=*/!IsNothrow)) {
10805 if (IsNothrow)
10806 return ZeroInitialization(E);
10807 return false;
10808 }
10809
10810 // -- the new-initializer is a braced-init-list and the number of
10811 // array elements for which initializers are provided [...]
10812 // exceeds the number of elements to initialize
10813 if (!Init) {
10814 // No initialization is performed.
10815 } else if (isa<CXXScalarValueInitExpr>(Init) ||
10817 ValueInit = true;
10818 } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) {
10819 ResizedArrayCCE = CCE;
10820 } else {
10821 auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType());
10822 assert(CAT && "unexpected type for array initializer");
10823
10824 unsigned Bits =
10825 std::max(CAT->getSizeBitWidth(), ArrayBound.getBitWidth());
10826 llvm::APInt InitBound = CAT->getSize().zext(Bits);
10827 llvm::APInt AllocBound = ArrayBound.zext(Bits);
10828 if (InitBound.ugt(AllocBound)) {
10829 if (IsNothrow)
10830 return ZeroInitialization(E);
10831
10832 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small)
10833 << toString(AllocBound, 10, /*Signed=*/false)
10834 << toString(InitBound, 10, /*Signed=*/false)
10835 << (*ArraySize)->getSourceRange();
10836 return false;
10837 }
10838
10839 // If the sizes differ, we must have an initializer list, and we need
10840 // special handling for this case when we initialize.
10841 if (InitBound != AllocBound)
10842 ResizedArrayILE = cast<InitListExpr>(Init);
10843 }
10844
10845 AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr,
10846 ArraySizeModifier::Normal, 0);
10847 } else {
10848 assert(!AllocType->isArrayType() &&
10849 "array allocation with non-array new");
10850 }
10851
10852 APValue *Val;
10853 if (IsPlacement) {
10855 struct FindObjectHandler {
10856 EvalInfo &Info;
10857 const Expr *E;
10858 QualType AllocType;
10859 const AccessKinds AccessKind;
10860 APValue *Value;
10861
10862 typedef bool result_type;
10863 bool failed() { return false; }
10864 bool checkConst(QualType QT) {
10865 if (QT.isConstQualified()) {
10866 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
10867 return false;
10868 }
10869 return true;
10870 }
10871 bool found(APValue &Subobj, QualType SubobjType,
10872 APValue::LValueBase Base) {
10873 if (!checkConst(SubobjType))
10874 return false;
10875 // FIXME: Reject the cases where [basic.life]p8 would not permit the
10876 // old name of the object to be used to name the new object.
10877 unsigned SubobjectSize = 1;
10878 unsigned AllocSize = 1;
10879 if (auto *CAT = dyn_cast<ConstantArrayType>(AllocType))
10880 AllocSize = CAT->getZExtSize();
10881 if (auto *CAT = dyn_cast<ConstantArrayType>(SubobjType))
10882 SubobjectSize = CAT->getZExtSize();
10883 if (SubobjectSize < AllocSize ||
10884 !Info.Ctx.hasSimilarType(Info.Ctx.getBaseElementType(SubobjType),
10885 Info.Ctx.getBaseElementType(AllocType))) {
10886 Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type)
10887 << SubobjType << AllocType;
10888 return false;
10889 }
10890 Value = &Subobj;
10891 return true;
10892 }
10893 bool found(APSInt &Value, QualType SubobjType) {
10894 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
10895 return false;
10896 }
10897 bool found(APFloat &Value, QualType SubobjType) {
10898 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
10899 return false;
10900 }
10901 } Handler = {Info, E, AllocType, AK, nullptr};
10902
10903 CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType);
10904 if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler))
10905 return false;
10906
10907 Val = Handler.Value;
10908
10909 // [basic.life]p1:
10910 // The lifetime of an object o of type T ends when [...] the storage
10911 // which the object occupies is [...] reused by an object that is not
10912 // nested within o (6.6.2).
10913 *Val = APValue();
10914 } else {
10915 // Perform the allocation and obtain a pointer to the resulting object.
10916 Val = Info.createHeapAlloc(E, AllocType, Result);
10917 if (!Val)
10918 return false;
10919 }
10920
10921 if (ValueInit) {
10922 ImplicitValueInitExpr VIE(AllocType);
10923 if (!EvaluateInPlace(*Val, Info, Result, &VIE))
10924 return false;
10925 } else if (ResizedArrayILE) {
10926 if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE,
10927 AllocType))
10928 return false;
10929 } else if (ResizedArrayCCE) {
10930 if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE,
10931 AllocType))
10932 return false;
10933 } else if (Init) {
10934 if (!EvaluateInPlace(*Val, Info, Result, Init))
10935 return false;
10936 } else if (!handleDefaultInitValue(AllocType, *Val)) {
10937 return false;
10938 }
10939
10940 // Array new returns a pointer to the first element, not a pointer to the
10941 // array.
10942 if (auto *AT = AllocType->getAsArrayTypeUnsafe())
10943 Result.addArray(Info, E, cast<ConstantArrayType>(AT));
10944
10945 return true;
10946}
10947//===----------------------------------------------------------------------===//
10948// Member Pointer Evaluation
10949//===----------------------------------------------------------------------===//
10950
10951namespace {
10952class MemberPointerExprEvaluator
10953 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
10954 MemberPtr &Result;
10955
10956 bool Success(const ValueDecl *D) {
10957 Result = MemberPtr(D);
10958 return true;
10959 }
10960public:
10961
10962 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
10963 : ExprEvaluatorBaseTy(Info), Result(Result) {}
10964
10965 bool Success(const APValue &V, const Expr *E) {
10966 Result.setFrom(V);
10967 return true;
10968 }
10969 bool ZeroInitialization(const Expr *E) {
10970 return Success((const ValueDecl*)nullptr);
10971 }
10972
10973 bool VisitCastExpr(const CastExpr *E);
10974 bool VisitUnaryAddrOf(const UnaryOperator *E);
10975};
10976} // end anonymous namespace
10977
10978static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
10979 EvalInfo &Info) {
10980 assert(!E->isValueDependent());
10981 assert(E->isPRValue() && E->getType()->isMemberPointerType());
10982 return MemberPointerExprEvaluator(Info, Result).Visit(E);
10983}
10984
10985bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
10986 switch (E->getCastKind()) {
10987 default:
10988 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10989
10990 case CK_NullToMemberPointer:
10991 VisitIgnoredValue(E->getSubExpr());
10992 return ZeroInitialization(E);
10993
10994 case CK_BaseToDerivedMemberPointer: {
10995 if (!Visit(E->getSubExpr()))
10996 return false;
10997 if (E->path_empty())
10998 return true;
10999 // Base-to-derived member pointer casts store the path in derived-to-base
11000 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
11001 // the wrong end of the derived->base arc, so stagger the path by one class.
11002 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
11003 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
11004 PathI != PathE; ++PathI) {
11005 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
11006 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
11007 if (!Result.castToDerived(Derived))
11008 return Error(E);
11009 }
11010 if (!Result.castToDerived(E->getType()
11011 ->castAs<MemberPointerType>()
11012 ->getMostRecentCXXRecordDecl()))
11013 return Error(E);
11014 return true;
11015 }
11016
11017 case CK_DerivedToBaseMemberPointer:
11018 if (!Visit(E->getSubExpr()))
11019 return false;
11020 for (CastExpr::path_const_iterator PathI = E->path_begin(),
11021 PathE = E->path_end(); PathI != PathE; ++PathI) {
11022 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
11023 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
11024 if (!Result.castToBase(Base))
11025 return Error(E);
11026 }
11027 return true;
11028 }
11029}
11030
11031bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
11032 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
11033 // member can be formed.
11034 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
11035}
11036
11037//===----------------------------------------------------------------------===//
11038// Record Evaluation
11039//===----------------------------------------------------------------------===//
11040
11041namespace {
11042 class RecordExprEvaluator
11043 : public ExprEvaluatorBase<RecordExprEvaluator> {
11044 const LValue &This;
11045 APValue &Result;
11046 public:
11047
11048 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
11049 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
11050
11051 bool Success(const APValue &V, const Expr *E) {
11052 Result = V;
11053 return true;
11054 }
11055 bool ZeroInitialization(const Expr *E) {
11056 return ZeroInitialization(E, E->getType());
11057 }
11058 bool ZeroInitialization(const Expr *E, QualType T);
11059
11060 bool VisitCallExpr(const CallExpr *E) {
11061 return handleCallExpr(E, Result, &This);
11062 }
11063 bool VisitCastExpr(const CastExpr *E);
11064 bool VisitInitListExpr(const InitListExpr *E);
11065 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
11066 return VisitCXXConstructExpr(E, E->getType());
11067 }
11068 bool VisitLambdaExpr(const LambdaExpr *E);
11069 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
11070 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
11071 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
11072 bool VisitBinCmp(const BinaryOperator *E);
11073 bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E);
11074 bool VisitCXXParenListOrInitListExpr(const Expr *ExprToVisit,
11075 ArrayRef<Expr *> Args);
11076 bool VisitDesignatedInitUpdateExpr(const DesignatedInitUpdateExpr *E);
11077 };
11078}
11079
11080/// Perform zero-initialization on an object of non-union class type.
11081/// C++11 [dcl.init]p5:
11082/// To zero-initialize an object or reference of type T means:
11083/// [...]
11084/// -- if T is a (possibly cv-qualified) non-union class type,
11085/// each non-static data member and each base-class subobject is
11086/// zero-initialized
11087static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
11088 const RecordDecl *RD,
11089 const LValue &This, APValue &Result) {
11090 assert(!RD->isUnion() && "Expected non-union class type");
11091 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
11092 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
11093 RD->getNumFields());
11094
11095 if (RD->isInvalidDecl()) return false;
11096 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
11097
11098 if (CD) {
11099 unsigned Index = 0;
11101 End = CD->bases_end(); I != End; ++I, ++Index) {
11102 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
11103 LValue Subobject = This;
11104 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
11105 return false;
11106 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
11107 Result.getStructBase(Index)))
11108 return false;
11109 }
11110 }
11111
11112 for (const auto *I : RD->fields()) {
11113 // -- if T is a reference type, no initialization is performed.
11114 if (I->isUnnamedBitField() || I->getType()->isReferenceType())
11115 continue;
11116
11117 LValue Subobject = This;
11118 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
11119 return false;
11120
11121 ImplicitValueInitExpr VIE(I->getType());
11122 if (!EvaluateInPlace(
11123 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
11124 return false;
11125 }
11126
11127 return true;
11128}
11129
11130bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
11131 const auto *RD = T->castAsRecordDecl();
11132 if (RD->isInvalidDecl()) return false;
11133 if (RD->isUnion()) {
11134 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
11135 // object's first non-static named data member is zero-initialized
11137 while (I != RD->field_end() && (*I)->isUnnamedBitField())
11138 ++I;
11139 if (I == RD->field_end()) {
11140 Result = APValue((const FieldDecl*)nullptr);
11141 return true;
11142 }
11143
11144 LValue Subobject = This;
11145 if (!HandleLValueMember(Info, E, Subobject, *I))
11146 return false;
11147 Result = APValue(*I);
11148 ImplicitValueInitExpr VIE(I->getType());
11149 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
11150 }
11151
11152 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
11153 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
11154 return false;
11155 }
11156
11157 return HandleClassZeroInitialization(Info, E, RD, This, Result);
11158}
11159
11160bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
11161 switch (E->getCastKind()) {
11162 default:
11163 return ExprEvaluatorBaseTy::VisitCastExpr(E);
11164
11165 case CK_ConstructorConversion:
11166 return Visit(E->getSubExpr());
11167
11168 case CK_DerivedToBase:
11169 case CK_UncheckedDerivedToBase: {
11170 APValue DerivedObject;
11171 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
11172 return false;
11173 if (!DerivedObject.isStruct())
11174 return Error(E->getSubExpr());
11175
11176 // Derived-to-base rvalue conversion: just slice off the derived part.
11177 APValue *Value = &DerivedObject;
11178 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
11179 for (CastExpr::path_const_iterator PathI = E->path_begin(),
11180 PathE = E->path_end(); PathI != PathE; ++PathI) {
11181 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
11182 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
11183 Value = &Value->getStructBase(getBaseIndex(RD, Base));
11184 RD = Base;
11185 }
11186 Result = *Value;
11187 return true;
11188 }
11189 case CK_HLSLAggregateSplatCast: {
11190 APValue Val;
11191 QualType ValTy;
11192
11193 if (!hlslAggSplatHelper(Info, E->getSubExpr(), Val, ValTy))
11194 return false;
11195
11196 unsigned NEls = elementwiseSize(Info, E->getType());
11197 // splat our Val
11198 SmallVector<APValue> SplatEls(NEls, Val);
11199 SmallVector<QualType> SplatType(NEls, ValTy);
11200
11201 // cast the elements and construct our struct result
11202 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
11203 if (!constructAggregate(Info, FPO, E, Result, E->getType(), SplatEls,
11204 SplatType))
11205 return false;
11206
11207 return true;
11208 }
11209 case CK_HLSLElementwiseCast: {
11210 SmallVector<APValue> SrcEls;
11211 SmallVector<QualType> SrcTypes;
11212
11213 if (!hlslElementwiseCastHelper(Info, E->getSubExpr(), E->getType(), SrcEls,
11214 SrcTypes))
11215 return false;
11216
11217 // cast the elements and construct our struct result
11218 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
11219 if (!constructAggregate(Info, FPO, E, Result, E->getType(), SrcEls,
11220 SrcTypes))
11221 return false;
11222
11223 return true;
11224 }
11225 case CK_ToUnion: {
11226 const FieldDecl *Field = E->getTargetUnionField();
11227 LValue Subobject = This;
11228 if (!HandleLValueMember(Info, E, Subobject, Field))
11229 return false;
11230 Result = APValue(Field);
11231 if (!EvaluateInPlace(Result.getUnionValue(), Info, Subobject,
11232 E->getSubExpr()))
11233 return false;
11234 if (Field->isBitField()) {
11235 if (!truncateBitfieldValue(Info, E->getSubExpr(), Result.getUnionValue(),
11236 Field))
11237 return false;
11238 }
11239 return true;
11240 }
11241 }
11242}
11243
11244bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
11245 if (E->isTransparent())
11246 return Visit(E->getInit(0));
11247 return VisitCXXParenListOrInitListExpr(E, E->inits());
11248}
11249
11250bool RecordExprEvaluator::VisitCXXParenListOrInitListExpr(
11251 const Expr *ExprToVisit, ArrayRef<Expr *> Args) {
11252 const auto *RD = ExprToVisit->getType()->castAsRecordDecl();
11253 if (RD->isInvalidDecl()) return false;
11254 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
11255 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
11256
11257 EvalInfo::EvaluatingConstructorRAII EvalObj(
11258 Info,
11259 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
11260 CXXRD && CXXRD->getNumBases());
11261
11262 if (RD->isUnion()) {
11263 const FieldDecl *Field;
11264 if (auto *ILE = dyn_cast<InitListExpr>(ExprToVisit)) {
11265 Field = ILE->getInitializedFieldInUnion();
11266 } else if (auto *PLIE = dyn_cast<CXXParenListInitExpr>(ExprToVisit)) {
11267 Field = PLIE->getInitializedFieldInUnion();
11268 } else {
11269 llvm_unreachable(
11270 "Expression is neither an init list nor a C++ paren list");
11271 }
11272
11273 Result = APValue(Field);
11274 if (!Field)
11275 return true;
11276
11277 // If the initializer list for a union does not contain any elements, the
11278 // first element of the union is value-initialized.
11279 // FIXME: The element should be initialized from an initializer list.
11280 // Is this difference ever observable for initializer lists which
11281 // we don't build?
11282 ImplicitValueInitExpr VIE(Field->getType());
11283 const Expr *InitExpr = Args.empty() ? &VIE : Args[0];
11284
11285 LValue Subobject = This;
11286 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
11287 return false;
11288
11289 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
11290 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
11291 isa<CXXDefaultInitExpr>(InitExpr));
11292
11293 if (EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr)) {
11294 if (Field->isBitField())
11295 return truncateBitfieldValue(Info, InitExpr, Result.getUnionValue(),
11296 Field);
11297 return true;
11298 }
11299
11300 return false;
11301 }
11302
11303 if (!Result.hasValue())
11304 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
11305 RD->getNumFields());
11306 unsigned ElementNo = 0;
11307 bool Success = true;
11308
11309 // Initialize base classes.
11310 if (CXXRD && CXXRD->getNumBases()) {
11311 for (const auto &Base : CXXRD->bases()) {
11312 assert(ElementNo < Args.size() && "missing init for base class");
11313 const Expr *Init = Args[ElementNo];
11314
11315 LValue Subobject = This;
11316 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
11317 return false;
11318
11319 APValue &FieldVal = Result.getStructBase(ElementNo);
11320 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
11321 if (!Info.noteFailure())
11322 return false;
11323 Success = false;
11324 }
11325 ++ElementNo;
11326 }
11327
11328 EvalObj.finishedConstructingBases();
11329 }
11330
11331 // Initialize members.
11332 for (const auto *Field : RD->fields()) {
11333 // Anonymous bit-fields are not considered members of the class for
11334 // purposes of aggregate initialization.
11335 if (Field->isUnnamedBitField())
11336 continue;
11337
11338 LValue Subobject = This;
11339
11340 bool HaveInit = ElementNo < Args.size();
11341
11342 // FIXME: Diagnostics here should point to the end of the initializer
11343 // list, not the start.
11344 if (!HandleLValueMember(Info, HaveInit ? Args[ElementNo] : ExprToVisit,
11345 Subobject, Field, &Layout))
11346 return false;
11347
11348 // Perform an implicit value-initialization for members beyond the end of
11349 // the initializer list.
11350 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
11351 const Expr *Init = HaveInit ? Args[ElementNo++] : &VIE;
11352
11353 // If this is a child of a DesignatedInitUpdateExpr, skip elements which
11354 // aren't supposed to be modified.
11355 if (isa<NoInitExpr>(Init))
11356 continue;
11357
11358 if (Field->getType()->isIncompleteArrayType()) {
11359 if (auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType())) {
11360 if (!CAT->isZeroSize()) {
11361 // Bail out for now. This might sort of "work", but the rest of the
11362 // code isn't really prepared to handle it.
11363 Info.FFDiag(Init, diag::note_constexpr_unsupported_flexible_array);
11364 return false;
11365 }
11366 }
11367 }
11368
11369 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
11370 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
11372
11373 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
11374 if (Field->getType()->isReferenceType()) {
11375 LValue Result;
11377 FieldVal)) {
11378 if (!Info.noteFailure())
11379 return false;
11380 Success = false;
11381 }
11382 } else if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
11383 (Field->isBitField() &&
11384 !truncateBitfieldValue(Info, Init, FieldVal, Field))) {
11385 if (!Info.noteFailure())
11386 return false;
11387 Success = false;
11388 }
11389 }
11390
11391 EvalObj.finishedConstructingFields();
11392
11393 return Success;
11394}
11395
11396bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
11397 QualType T) {
11398 // Note that E's type is not necessarily the type of our class here; we might
11399 // be initializing an array element instead.
11400 const CXXConstructorDecl *FD = E->getConstructor();
11401 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
11402
11403 bool ZeroInit = E->requiresZeroInitialization();
11404 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
11405 if (ZeroInit)
11406 return ZeroInitialization(E, T);
11407
11408 return handleDefaultInitValue(T, Result);
11409 }
11410
11411 const FunctionDecl *Definition = nullptr;
11412 auto Body = FD->getBody(Definition);
11413
11414 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
11415 return false;
11416
11417 // Avoid materializing a temporary for an elidable copy/move constructor.
11418 if (E->isElidable() && !ZeroInit) {
11419 // FIXME: This only handles the simplest case, where the source object
11420 // is passed directly as the first argument to the constructor.
11421 // This should also handle stepping though implicit casts and
11422 // and conversion sequences which involve two steps, with a
11423 // conversion operator followed by a converting constructor.
11424 const Expr *SrcObj = E->getArg(0);
11425 assert(SrcObj->isTemporaryObject(Info.Ctx, FD->getParent()));
11426 assert(Info.Ctx.hasSameUnqualifiedType(E->getType(), SrcObj->getType()));
11427 if (const MaterializeTemporaryExpr *ME =
11428 dyn_cast<MaterializeTemporaryExpr>(SrcObj))
11429 return Visit(ME->getSubExpr());
11430 }
11431
11432 if (ZeroInit && !ZeroInitialization(E, T))
11433 return false;
11434
11435 auto Args = ArrayRef(E->getArgs(), E->getNumArgs());
11436 return HandleConstructorCall(E, This, Args,
11438 Result);
11439}
11440
11441bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
11442 const CXXInheritedCtorInitExpr *E) {
11443 if (!Info.CurrentCall) {
11444 assert(Info.checkingPotentialConstantExpression());
11445 return false;
11446 }
11447
11448 const CXXConstructorDecl *FD = E->getConstructor();
11449 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
11450 return false;
11451
11452 const FunctionDecl *Definition = nullptr;
11453 auto Body = FD->getBody(Definition);
11454
11455 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
11456 return false;
11457
11458 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
11460 Result);
11461}
11462
11463bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
11464 const CXXStdInitializerListExpr *E) {
11465 const ConstantArrayType *ArrayType =
11466 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
11467
11468 LValue Array;
11469 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
11470 return false;
11471
11472 assert(ArrayType && "unexpected type for array initializer");
11473
11474 // Get a pointer to the first element of the array.
11475 Array.addArray(Info, E, ArrayType);
11476
11477 // FIXME: What if the initializer_list type has base classes, etc?
11478 Result = APValue(APValue::UninitStruct(), 0, 2);
11479 Array.moveInto(Result.getStructField(0));
11480
11481 auto *Record = E->getType()->castAsRecordDecl();
11482 RecordDecl::field_iterator Field = Record->field_begin();
11483 assert(Field != Record->field_end() &&
11484 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
11485 ArrayType->getElementType()) &&
11486 "Expected std::initializer_list first field to be const E *");
11487 ++Field;
11488 assert(Field != Record->field_end() &&
11489 "Expected std::initializer_list to have two fields");
11490
11491 if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType())) {
11492 // Length.
11493 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
11494 } else {
11495 // End pointer.
11496 assert(Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
11497 ArrayType->getElementType()) &&
11498 "Expected std::initializer_list second field to be const E *");
11499 if (!HandleLValueArrayAdjustment(Info, E, Array,
11500 ArrayType->getElementType(),
11501 ArrayType->getZExtSize()))
11502 return false;
11503 Array.moveInto(Result.getStructField(1));
11504 }
11505
11506 assert(++Field == Record->field_end() &&
11507 "Expected std::initializer_list to only have two fields");
11508
11509 return true;
11510}
11511
11512bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
11513 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
11514 if (ClosureClass->isInvalidDecl())
11515 return false;
11516
11517 const size_t NumFields = ClosureClass->getNumFields();
11518
11519 assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
11520 E->capture_init_end()) &&
11521 "The number of lambda capture initializers should equal the number of "
11522 "fields within the closure type");
11523
11524 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
11525 // Iterate through all the lambda's closure object's fields and initialize
11526 // them.
11527 auto *CaptureInitIt = E->capture_init_begin();
11528 bool Success = true;
11529 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(ClosureClass);
11530 for (const auto *Field : ClosureClass->fields()) {
11531 assert(CaptureInitIt != E->capture_init_end());
11532 // Get the initializer for this field
11533 Expr *const CurFieldInit = *CaptureInitIt++;
11534
11535 // If there is no initializer, either this is a VLA or an error has
11536 // occurred.
11537 if (!CurFieldInit || CurFieldInit->containsErrors())
11538 return Error(E);
11539
11540 LValue Subobject = This;
11541
11542 if (!HandleLValueMember(Info, E, Subobject, Field, &Layout))
11543 return false;
11544
11545 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
11546 if (!EvaluateInPlace(FieldVal, Info, Subobject, CurFieldInit)) {
11547 if (!Info.keepEvaluatingAfterFailure())
11548 return false;
11549 Success = false;
11550 }
11551 }
11552 return Success;
11553}
11554
11555bool RecordExprEvaluator::VisitDesignatedInitUpdateExpr(
11556 const DesignatedInitUpdateExpr *E) {
11557 if (!Visit(E->getBase()))
11558 return false;
11559 return Visit(E->getUpdater());
11560}
11561
11562static bool EvaluateRecord(const Expr *E, const LValue &This,
11563 APValue &Result, EvalInfo &Info) {
11564 assert(!E->isValueDependent());
11565 assert(E->isPRValue() && E->getType()->isRecordType() &&
11566 "can't evaluate expression as a record rvalue");
11567 return RecordExprEvaluator(Info, This, Result).Visit(E);
11568}
11569
11570//===----------------------------------------------------------------------===//
11571// Temporary Evaluation
11572//
11573// Temporaries are represented in the AST as rvalues, but generally behave like
11574// lvalues. The full-object of which the temporary is a subobject is implicitly
11575// materialized so that a reference can bind to it.
11576//===----------------------------------------------------------------------===//
11577namespace {
11578class TemporaryExprEvaluator
11579 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
11580public:
11581 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
11582 LValueExprEvaluatorBaseTy(Info, Result, false) {}
11583
11584 /// Visit an expression which constructs the value of this temporary.
11585 bool VisitConstructExpr(const Expr *E) {
11586 APValue &Value = Info.CurrentCall->createTemporary(
11587 E, E->getType(), ScopeKind::FullExpression, Result);
11588 return EvaluateInPlace(Value, Info, Result, E);
11589 }
11590
11591 bool VisitCastExpr(const CastExpr *E) {
11592 switch (E->getCastKind()) {
11593 default:
11594 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
11595
11596 case CK_ConstructorConversion:
11597 return VisitConstructExpr(E->getSubExpr());
11598 }
11599 }
11600 bool VisitInitListExpr(const InitListExpr *E) {
11601 return VisitConstructExpr(E);
11602 }
11603 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
11604 return VisitConstructExpr(E);
11605 }
11606 bool VisitCallExpr(const CallExpr *E) {
11607 return VisitConstructExpr(E);
11608 }
11609 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
11610 return VisitConstructExpr(E);
11611 }
11612 bool VisitLambdaExpr(const LambdaExpr *E) {
11613 return VisitConstructExpr(E);
11614 }
11615};
11616} // end anonymous namespace
11617
11618/// Evaluate an expression of record type as a temporary.
11619static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
11620 assert(!E->isValueDependent());
11621 assert(E->isPRValue() && E->getType()->isRecordType());
11622 return TemporaryExprEvaluator(Info, Result).Visit(E);
11623}
11624
11625//===----------------------------------------------------------------------===//
11626// Vector Evaluation
11627//===----------------------------------------------------------------------===//
11628
11629namespace {
11630 class VectorExprEvaluator
11631 : public ExprEvaluatorBase<VectorExprEvaluator> {
11632 APValue &Result;
11633 public:
11634
11635 VectorExprEvaluator(EvalInfo &info, APValue &Result)
11636 : ExprEvaluatorBaseTy(info), Result(Result) {}
11637
11638 bool Success(ArrayRef<APValue> V, const Expr *E) {
11639 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
11640 // FIXME: remove this APValue copy.
11641 Result = APValue(V.data(), V.size());
11642 return true;
11643 }
11644 bool Success(const APValue &V, const Expr *E) {
11645 assert(V.isVector());
11646 Result = V;
11647 return true;
11648 }
11649 bool ZeroInitialization(const Expr *E);
11650
11651 bool VisitUnaryReal(const UnaryOperator *E)
11652 { return Visit(E->getSubExpr()); }
11653 bool VisitCastExpr(const CastExpr* E);
11654 bool VisitInitListExpr(const InitListExpr *E);
11655 bool VisitUnaryImag(const UnaryOperator *E);
11656 bool VisitBinaryOperator(const BinaryOperator *E);
11657 bool VisitUnaryOperator(const UnaryOperator *E);
11658 bool VisitCallExpr(const CallExpr *E);
11659 bool VisitConvertVectorExpr(const ConvertVectorExpr *E);
11660 bool VisitShuffleVectorExpr(const ShuffleVectorExpr *E);
11661
11662 // FIXME: Missing: conditional operator (for GNU
11663 // conditional select), ExtVectorElementExpr
11664 };
11665} // end anonymous namespace
11666
11667static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
11668 assert(E->isPRValue() && E->getType()->isVectorType() &&
11669 "not a vector prvalue");
11670 return VectorExprEvaluator(Info, Result).Visit(E);
11671}
11672
11673static llvm::APInt ConvertBoolVectorToInt(const APValue &Val) {
11674 assert(Val.isVector() && "expected vector APValue");
11675 unsigned NumElts = Val.getVectorLength();
11676
11677 // Each element is one bit, so create an integer with NumElts bits.
11678 llvm::APInt Result(NumElts, 0);
11679
11680 for (unsigned I = 0; I < NumElts; ++I) {
11681 const APValue &Elt = Val.getVectorElt(I);
11682 assert(Elt.isInt() && "expected integer element in bool vector");
11683
11684 if (Elt.getInt().getBoolValue())
11685 Result.setBit(I);
11686 }
11687
11688 return Result;
11689}
11690
11691bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
11692 const VectorType *VTy = E->getType()->castAs<VectorType>();
11693 unsigned NElts = VTy->getNumElements();
11694
11695 const Expr *SE = E->getSubExpr();
11696 QualType SETy = SE->getType();
11697
11698 switch (E->getCastKind()) {
11699 case CK_VectorSplat: {
11700 APValue Val = APValue();
11701 if (SETy->isIntegerType()) {
11702 APSInt IntResult;
11703 if (!EvaluateInteger(SE, IntResult, Info))
11704 return false;
11705 Val = APValue(std::move(IntResult));
11706 } else if (SETy->isRealFloatingType()) {
11707 APFloat FloatResult(0.0);
11708 if (!EvaluateFloat(SE, FloatResult, Info))
11709 return false;
11710 Val = APValue(std::move(FloatResult));
11711 } else {
11712 return Error(E);
11713 }
11714
11715 // Splat and create vector APValue.
11716 SmallVector<APValue, 4> Elts(NElts, Val);
11717 return Success(Elts, E);
11718 }
11719 case CK_BitCast: {
11720 APValue SVal;
11721 if (!Evaluate(SVal, Info, SE))
11722 return false;
11723
11724 if (!SVal.isInt() && !SVal.isFloat() && !SVal.isVector()) {
11725 // Give up if the input isn't an int, float, or vector. For example, we
11726 // reject "(v4i16)(intptr_t)&a".
11727 Info.FFDiag(E, diag::note_constexpr_invalid_cast)
11728 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
11729 << Info.Ctx.getLangOpts().CPlusPlus;
11730 return false;
11731 }
11732
11733 if (!handleRValueToRValueBitCast(Info, Result, SVal, E))
11734 return false;
11735
11736 return true;
11737 }
11738 case CK_HLSLVectorTruncation: {
11739 APValue Val;
11740 SmallVector<APValue, 4> Elements;
11741 if (!EvaluateVector(SE, Val, Info))
11742 return Error(E);
11743 for (unsigned I = 0; I < NElts; I++)
11744 Elements.push_back(Val.getVectorElt(I));
11745 return Success(Elements, E);
11746 }
11747 case CK_HLSLMatrixTruncation: {
11748 // Matrix truncation occurs in row-major order.
11749 APValue Val;
11750 if (!EvaluateMatrix(SE, Val, Info))
11751 return Error(E);
11752 SmallVector<APValue, 16> Elements;
11753 for (unsigned Row = 0;
11754 Row < Val.getMatrixNumRows() && Elements.size() < NElts; Row++)
11755 for (unsigned Col = 0;
11756 Col < Val.getMatrixNumColumns() && Elements.size() < NElts; Col++)
11757 Elements.push_back(Val.getMatrixElt(Row, Col));
11758 return Success(Elements, E);
11759 }
11760 case CK_HLSLAggregateSplatCast: {
11761 APValue Val;
11762 QualType ValTy;
11763
11764 if (!hlslAggSplatHelper(Info, SE, Val, ValTy))
11765 return false;
11766
11767 // cast our Val once.
11769 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
11770 if (!handleScalarCast(Info, FPO, E, ValTy, VTy->getElementType(), Val,
11771 Result))
11772 return false;
11773
11774 SmallVector<APValue, 4> SplatEls(NElts, Result);
11775 return Success(SplatEls, E);
11776 }
11777 case CK_HLSLElementwiseCast: {
11778 SmallVector<APValue> SrcVals;
11779 SmallVector<QualType> SrcTypes;
11780
11781 if (!hlslElementwiseCastHelper(Info, SE, E->getType(), SrcVals, SrcTypes))
11782 return false;
11783
11784 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
11785 SmallVector<QualType, 4> DestTypes(NElts, VTy->getElementType());
11786 SmallVector<APValue, 4> ResultEls(NElts);
11787 if (!handleElementwiseCast(Info, E, FPO, SrcVals, SrcTypes, DestTypes,
11788 ResultEls))
11789 return false;
11790 return Success(ResultEls, E);
11791 }
11792 case CK_IntegralToFloating:
11793 case CK_FloatingToIntegral:
11794 case CK_IntegralCast:
11795 case CK_FloatingCast:
11796 case CK_FloatingToBoolean:
11797 case CK_IntegralToBoolean: {
11798 // These casts apply element-wise when the source is a vector type.
11799 assert(SETy->isVectorType() && "expected vector source type");
11800 APValue SrcVal;
11801 if (!EvaluateVector(SE, SrcVal, Info))
11802 return Error(E);
11803
11804 assert(SrcVal.getVectorLength() == NElts);
11805 QualType SrcEltTy = SETy->castAs<VectorType>()->getElementType();
11806 QualType DstEltTy = VTy->getElementType();
11807 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
11808
11809 SmallVector<APValue, 4> ResultEls(NElts);
11810 for (unsigned I = 0; I < NElts; ++I) {
11811 if (!handleScalarCast(Info, FPO, E, SrcEltTy, DstEltTy,
11812 SrcVal.getVectorElt(I), ResultEls[I]))
11813 return Error(E);
11814 }
11815 return Success(ResultEls, E);
11816 }
11817 default:
11818 return ExprEvaluatorBaseTy::VisitCastExpr(E);
11819 }
11820}
11821
11822bool
11823VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
11824 const VectorType *VT = E->getType()->castAs<VectorType>();
11825 unsigned NumInits = E->getNumInits();
11826 unsigned NumElements = VT->getNumElements();
11827
11828 QualType EltTy = VT->getElementType();
11829 SmallVector<APValue, 4> Elements;
11830
11831 // MFloat8 type doesn't have constants and thus constant folding
11832 // is impossible.
11833 if (EltTy->isMFloat8Type())
11834 return false;
11835
11836 // The number of initializers can be less than the number of
11837 // vector elements. For OpenCL, this can be due to nested vector
11838 // initialization. For GCC compatibility, missing trailing elements
11839 // should be initialized with zeroes.
11840 unsigned CountInits = 0, CountElts = 0;
11841 while (CountElts < NumElements) {
11842 // Handle nested vector initialization.
11843 if (CountInits < NumInits
11844 && E->getInit(CountInits)->getType()->isVectorType()) {
11845 APValue v;
11846 if (!EvaluateVector(E->getInit(CountInits), v, Info))
11847 return Error(E);
11848 unsigned vlen = v.getVectorLength();
11849 for (unsigned j = 0; j < vlen; j++)
11850 Elements.push_back(v.getVectorElt(j));
11851 CountElts += vlen;
11852 } else if (EltTy->isIntegerType()) {
11853 llvm::APSInt sInt(32);
11854 if (CountInits < NumInits) {
11855 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
11856 return false;
11857 } else // trailing integer zero.
11858 sInt = Info.Ctx.MakeIntValue(0, EltTy);
11859 Elements.push_back(APValue(sInt));
11860 CountElts++;
11861 } else {
11862 llvm::APFloat f(0.0);
11863 if (CountInits < NumInits) {
11864 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
11865 return false;
11866 } else // trailing float zero.
11867 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
11868 Elements.push_back(APValue(f));
11869 CountElts++;
11870 }
11871 CountInits++;
11872 }
11873 return Success(Elements, E);
11874}
11875
11876bool
11877VectorExprEvaluator::ZeroInitialization(const Expr *E) {
11878 const auto *VT = E->getType()->castAs<VectorType>();
11879 QualType EltTy = VT->getElementType();
11880 APValue ZeroElement;
11881 if (EltTy->isIntegerType())
11882 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
11883 else
11884 ZeroElement =
11885 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
11886
11887 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
11888 return Success(Elements, E);
11889}
11890
11891bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
11892 VisitIgnoredValue(E->getSubExpr());
11893 return ZeroInitialization(E);
11894}
11895
11896bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
11897 BinaryOperatorKind Op = E->getOpcode();
11898 assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp &&
11899 "Operation not supported on vector types");
11900
11901 if (Op == BO_Comma)
11902 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
11903
11904 Expr *LHS = E->getLHS();
11905 Expr *RHS = E->getRHS();
11906
11907 assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() &&
11908 "Must both be vector types");
11909 // Checking JUST the types are the same would be fine, except shifts don't
11910 // need to have their types be the same (since you always shift by an int).
11911 assert(LHS->getType()->castAs<VectorType>()->getNumElements() ==
11912 E->getType()->castAs<VectorType>()->getNumElements() &&
11913 RHS->getType()->castAs<VectorType>()->getNumElements() ==
11914 E->getType()->castAs<VectorType>()->getNumElements() &&
11915 "All operands must be the same size.");
11916
11917 APValue LHSValue;
11918 APValue RHSValue;
11919 bool LHSOK = Evaluate(LHSValue, Info, LHS);
11920 if (!LHSOK && !Info.noteFailure())
11921 return false;
11922 if (!Evaluate(RHSValue, Info, RHS) || !LHSOK)
11923 return false;
11924
11925 if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue))
11926 return false;
11927
11928 return Success(LHSValue, E);
11929}
11930
11931static std::optional<APValue> handleVectorUnaryOperator(ASTContext &Ctx,
11932 QualType ResultTy,
11934 APValue Elt) {
11935 switch (Op) {
11936 case UO_Plus:
11937 // Nothing to do here.
11938 return Elt;
11939 case UO_Minus:
11940 if (Elt.getKind() == APValue::Int) {
11941 Elt.getInt().negate();
11942 } else {
11943 assert(Elt.getKind() == APValue::Float &&
11944 "Vector can only be int or float type");
11945 Elt.getFloat().changeSign();
11946 }
11947 return Elt;
11948 case UO_Not:
11949 // This is only valid for integral types anyway, so we don't have to handle
11950 // float here.
11951 assert(Elt.getKind() == APValue::Int &&
11952 "Vector operator ~ can only be int");
11953 Elt.getInt().flipAllBits();
11954 return Elt;
11955 case UO_LNot: {
11956 if (Elt.getKind() == APValue::Int) {
11957 Elt.getInt() = !Elt.getInt();
11958 // operator ! on vectors returns -1 for 'truth', so negate it.
11959 Elt.getInt().negate();
11960 return Elt;
11961 }
11962 assert(Elt.getKind() == APValue::Float &&
11963 "Vector can only be int or float type");
11964 // Float types result in an int of the same size, but -1 for true, or 0 for
11965 // false.
11966 APSInt EltResult{Ctx.getIntWidth(ResultTy),
11967 ResultTy->isUnsignedIntegerType()};
11968 if (Elt.getFloat().isZero())
11969 EltResult.setAllBits();
11970 else
11971 EltResult.clearAllBits();
11972
11973 return APValue{EltResult};
11974 }
11975 default:
11976 // FIXME: Implement the rest of the unary operators.
11977 return std::nullopt;
11978 }
11979}
11980
11981bool VectorExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
11982 Expr *SubExpr = E->getSubExpr();
11983 const auto *VD = SubExpr->getType()->castAs<VectorType>();
11984 // This result element type differs in the case of negating a floating point
11985 // vector, since the result type is the a vector of the equivilant sized
11986 // integer.
11987 const QualType ResultEltTy = VD->getElementType();
11988 UnaryOperatorKind Op = E->getOpcode();
11989
11990 APValue SubExprValue;
11991 if (!Evaluate(SubExprValue, Info, SubExpr))
11992 return false;
11993
11994 // FIXME: This vector evaluator someday needs to be changed to be LValue
11995 // aware/keep LValue information around, rather than dealing with just vector
11996 // types directly. Until then, we cannot handle cases where the operand to
11997 // these unary operators is an LValue. The only case I've been able to see
11998 // cause this is operator++ assigning to a member expression (only valid in
11999 // altivec compilations) in C mode, so this shouldn't limit us too much.
12000 if (SubExprValue.isLValue())
12001 return false;
12002
12003 assert(SubExprValue.getVectorLength() == VD->getNumElements() &&
12004 "Vector length doesn't match type?");
12005
12006 SmallVector<APValue, 4> ResultElements;
12007 for (unsigned EltNum = 0; EltNum < VD->getNumElements(); ++EltNum) {
12008 std::optional<APValue> Elt = handleVectorUnaryOperator(
12009 Info.Ctx, ResultEltTy, Op, SubExprValue.getVectorElt(EltNum));
12010 if (!Elt)
12011 return false;
12012 ResultElements.push_back(*Elt);
12013 }
12014 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12015}
12016
12017static bool handleVectorElementCast(EvalInfo &Info, const FPOptions FPO,
12018 const Expr *E, QualType SourceTy,
12019 QualType DestTy, APValue const &Original,
12020 APValue &Result) {
12021 if (SourceTy->isIntegerType()) {
12022 if (DestTy->isRealFloatingType()) {
12023 Result = APValue(APFloat(0.0));
12024 return HandleIntToFloatCast(Info, E, FPO, SourceTy, Original.getInt(),
12025 DestTy, Result.getFloat());
12026 }
12027 if (DestTy->isIntegerType()) {
12028 Result = APValue(
12029 HandleIntToIntCast(Info, E, DestTy, SourceTy, Original.getInt()));
12030 return true;
12031 }
12032 } else if (SourceTy->isRealFloatingType()) {
12033 if (DestTy->isRealFloatingType()) {
12034 Result = Original;
12035 return HandleFloatToFloatCast(Info, E, SourceTy, DestTy,
12036 Result.getFloat());
12037 }
12038 if (DestTy->isIntegerType()) {
12039 Result = APValue(APSInt());
12040 return HandleFloatToIntCast(Info, E, SourceTy, Original.getFloat(),
12041 DestTy, Result.getInt());
12042 }
12043 }
12044
12045 Info.FFDiag(E, diag::err_convertvector_constexpr_unsupported_vector_cast)
12046 << SourceTy << DestTy;
12047 return false;
12048}
12049
12050static bool evalPackBuiltin(const CallExpr *E, EvalInfo &Info, APValue &Result,
12051 llvm::function_ref<APInt(const APSInt &)> PackFn) {
12052 APValue LHS, RHS;
12053 if (!EvaluateAsRValue(Info, E->getArg(0), LHS) ||
12054 !EvaluateAsRValue(Info, E->getArg(1), RHS))
12055 return false;
12056
12057 unsigned LHSVecLen = LHS.getVectorLength();
12058 unsigned RHSVecLen = RHS.getVectorLength();
12059
12060 assert(LHSVecLen != 0 && LHSVecLen == RHSVecLen &&
12061 "pack builtin LHSVecLen must equal to RHSVecLen");
12062
12063 const VectorType *VT0 = E->getArg(0)->getType()->castAs<VectorType>();
12064 const unsigned SrcBits = Info.Ctx.getIntWidth(VT0->getElementType());
12065
12066 const VectorType *DstVT = E->getType()->castAs<VectorType>();
12067 QualType DstElemTy = DstVT->getElementType();
12068 const bool DstIsUnsigned = DstElemTy->isUnsignedIntegerType();
12069
12070 const unsigned SrcPerLane = 128 / SrcBits;
12071 const unsigned Lanes = LHSVecLen * SrcBits / 128;
12072
12074 Out.reserve(LHSVecLen + RHSVecLen);
12075
12076 for (unsigned Lane = 0; Lane != Lanes; ++Lane) {
12077 unsigned base = Lane * SrcPerLane;
12078 for (unsigned I = 0; I != SrcPerLane; ++I)
12079 Out.emplace_back(APValue(
12080 APSInt(PackFn(LHS.getVectorElt(base + I).getInt()), DstIsUnsigned)));
12081 for (unsigned I = 0; I != SrcPerLane; ++I)
12082 Out.emplace_back(APValue(
12083 APSInt(PackFn(RHS.getVectorElt(base + I).getInt()), DstIsUnsigned)));
12084 }
12085
12086 Result = APValue(Out.data(), Out.size());
12087 return true;
12088}
12089
12091 EvalInfo &Info, const CallExpr *Call, APValue &Out,
12092 llvm::function_ref<std::pair<unsigned, int>(unsigned, unsigned)>
12093 GetSourceIndex) {
12094
12095 const auto *VT = Call->getType()->getAs<VectorType>();
12096 if (!VT)
12097 return false;
12098
12099 unsigned ShuffleMask = 0;
12100 APValue A, MaskVector, B;
12101 bool IsVectorMask = false;
12102 bool IsSingleOperand = (Call->getNumArgs() == 2);
12103
12104 if (IsSingleOperand) {
12105 QualType MaskType = Call->getArg(1)->getType();
12106 if (MaskType->isVectorType()) {
12107 IsVectorMask = true;
12108 if (!EvaluateAsRValue(Info, Call->getArg(0), A) ||
12109 !EvaluateAsRValue(Info, Call->getArg(1), MaskVector))
12110 return false;
12111 B = A;
12112 } else if (MaskType->isIntegerType()) {
12113 APSInt MaskImm;
12114 if (!EvaluateInteger(Call->getArg(1), MaskImm, Info))
12115 return false;
12116 ShuffleMask = static_cast<unsigned>(MaskImm.getZExtValue());
12117 if (!EvaluateAsRValue(Info, Call->getArg(0), A))
12118 return false;
12119 B = A;
12120 } else {
12121 return false;
12122 }
12123 } else {
12124 QualType Arg2Type = Call->getArg(2)->getType();
12125 if (Arg2Type->isVectorType()) {
12126 IsVectorMask = true;
12127 if (!EvaluateAsRValue(Info, Call->getArg(0), A) ||
12128 !EvaluateAsRValue(Info, Call->getArg(1), MaskVector) ||
12129 !EvaluateAsRValue(Info, Call->getArg(2), B))
12130 return false;
12131 } else if (Arg2Type->isIntegerType()) {
12132 APSInt MaskImm;
12133 if (!EvaluateInteger(Call->getArg(2), MaskImm, Info))
12134 return false;
12135 ShuffleMask = static_cast<unsigned>(MaskImm.getZExtValue());
12136 if (!EvaluateAsRValue(Info, Call->getArg(0), A) ||
12137 !EvaluateAsRValue(Info, Call->getArg(1), B))
12138 return false;
12139 } else {
12140 return false;
12141 }
12142 }
12143
12144 unsigned NumElts = VT->getNumElements();
12145 SmallVector<APValue, 64> ResultElements;
12146 ResultElements.reserve(NumElts);
12147
12148 for (unsigned DstIdx = 0; DstIdx != NumElts; ++DstIdx) {
12149 if (IsVectorMask) {
12150 ShuffleMask = static_cast<unsigned>(
12151 MaskVector.getVectorElt(DstIdx).getInt().getZExtValue());
12152 }
12153 auto [SrcVecIdx, SrcIdx] = GetSourceIndex(DstIdx, ShuffleMask);
12154
12155 if (SrcIdx < 0) {
12156 // Zero out this element
12157 QualType ElemTy = VT->getElementType();
12158 if (ElemTy->isRealFloatingType()) {
12159 ResultElements.push_back(
12160 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy))));
12161 } else if (ElemTy->isIntegerType()) {
12162 APValue Zero(Info.Ctx.MakeIntValue(0, ElemTy));
12163 ResultElements.push_back(APValue(Zero));
12164 } else {
12165 // Other types of fallback logic
12166 ResultElements.push_back(APValue());
12167 }
12168 } else {
12169 const APValue &Src = (SrcVecIdx == 0) ? A : B;
12170 ResultElements.push_back(Src.getVectorElt(SrcIdx));
12171 }
12172 }
12173
12174 Out = APValue(ResultElements.data(), ResultElements.size());
12175 return true;
12176}
12177static bool ConvertDoubleToFloatStrict(EvalInfo &Info, const Expr *E,
12178 APFloat OrigVal, APValue &Result) {
12179
12180 if (OrigVal.isInfinity()) {
12181 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << 0;
12182 return false;
12183 }
12184 if (OrigVal.isNaN()) {
12185 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << 1;
12186 return false;
12187 }
12188
12189 APFloat Val = OrigVal;
12190 bool LosesInfo = false;
12191 APFloat::opStatus Status = Val.convert(
12192 APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, &LosesInfo);
12193
12194 if (LosesInfo || Val.isDenormal()) {
12195 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic_strict);
12196 return false;
12197 }
12198
12199 if (Status != APFloat::opOK) {
12200 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
12201 return false;
12202 }
12203
12204 Result = APValue(Val);
12205 return true;
12206}
12208 EvalInfo &Info, const CallExpr *Call, APValue &Out,
12209 llvm::function_ref<APInt(const APInt &, uint64_t)> ShiftOp,
12210 llvm::function_ref<APInt(const APInt &, unsigned)> OverflowOp) {
12211
12212 APValue Source, Count;
12213 if (!EvaluateAsRValue(Info, Call->getArg(0), Source) ||
12214 !EvaluateAsRValue(Info, Call->getArg(1), Count))
12215 return false;
12216
12217 assert(Call->getNumArgs() == 2);
12218
12219 QualType SourceTy = Call->getArg(0)->getType();
12220 assert(SourceTy->isVectorType() &&
12221 Call->getArg(1)->getType()->isVectorType());
12222
12223 QualType DestEltTy = SourceTy->castAs<VectorType>()->getElementType();
12224 unsigned DestEltWidth = Source.getVectorElt(0).getInt().getBitWidth();
12225 unsigned DestLen = Source.getVectorLength();
12226 bool IsDestUnsigned = DestEltTy->isUnsignedIntegerType();
12227 unsigned CountEltWidth = Count.getVectorElt(0).getInt().getBitWidth();
12228 unsigned NumBitsInQWord = 64;
12229 unsigned NumCountElts = NumBitsInQWord / CountEltWidth;
12231 Result.reserve(DestLen);
12232
12233 uint64_t CountLQWord = 0;
12234 for (unsigned EltIdx = 0; EltIdx != NumCountElts; ++EltIdx) {
12235 uint64_t Elt = Count.getVectorElt(EltIdx).getInt().getZExtValue();
12236 CountLQWord |= (Elt << (EltIdx * CountEltWidth));
12237 }
12238
12239 for (unsigned EltIdx = 0; EltIdx != DestLen; ++EltIdx) {
12240 APInt Elt = Source.getVectorElt(EltIdx).getInt();
12241 if (CountLQWord < DestEltWidth) {
12242 Result.push_back(
12243 APValue(APSInt(ShiftOp(Elt, CountLQWord), IsDestUnsigned)));
12244 } else {
12245 Result.push_back(
12246 APValue(APSInt(OverflowOp(Elt, DestEltWidth), IsDestUnsigned)));
12247 }
12248 }
12249 Out = APValue(Result.data(), Result.size());
12250 return true;
12251}
12252
12253std::optional<APFloat> EvalScalarMinMaxFp(const APFloat &A, const APFloat &B,
12254 std::optional<APSInt> RoundingMode,
12255 bool IsMin) {
12256 APSInt DefaultMode(APInt(32, 4), /*isUnsigned=*/true);
12257 if (RoundingMode.value_or(DefaultMode) != 4)
12258 return std::nullopt;
12259 if (A.isNaN() || A.isInfinity() || A.isDenormal() || B.isNaN() ||
12260 B.isInfinity() || B.isDenormal())
12261 return std::nullopt;
12262 if (A.isZero() && B.isZero())
12263 return B;
12264 return IsMin ? llvm::minimum(A, B) : llvm::maximum(A, B);
12265}
12266
12267bool VectorExprEvaluator::VisitCallExpr(const CallExpr *E) {
12268 if (!IsConstantEvaluatedBuiltinCall(E))
12269 return ExprEvaluatorBaseTy::VisitCallExpr(E);
12270
12271 auto EvaluateBinOpExpr =
12272 [&](llvm::function_ref<APInt(const APSInt &, const APSInt &)> Fn) {
12273 APValue SourceLHS, SourceRHS;
12274 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
12275 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
12276 return false;
12277
12278 auto *DestTy = E->getType()->castAs<VectorType>();
12279 QualType DestEltTy = DestTy->getElementType();
12280 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
12281 unsigned SourceLen = SourceLHS.getVectorLength();
12282 SmallVector<APValue, 4> ResultElements;
12283 ResultElements.reserve(SourceLen);
12284
12285 if (SourceRHS.isInt()) {
12286 const APSInt &RHS = SourceRHS.getInt();
12287 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12288 const APSInt &LHS = SourceLHS.getVectorElt(EltNum).getInt();
12289 ResultElements.push_back(
12290 APValue(APSInt(Fn(LHS, RHS), DestUnsigned)));
12291 }
12292 } else {
12293 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12294 const APSInt &LHS = SourceLHS.getVectorElt(EltNum).getInt();
12295 const APSInt &RHS = SourceRHS.getVectorElt(EltNum).getInt();
12296 ResultElements.push_back(
12297 APValue(APSInt(Fn(LHS, RHS), DestUnsigned)));
12298 }
12299 }
12300 return Success(APValue(ResultElements.data(), SourceLen), E);
12301 };
12302
12303 auto EvaluateFpBinOpExpr =
12304 [&](llvm::function_ref<std::optional<APFloat>(
12305 const APFloat &, const APFloat &, std::optional<APSInt>)>
12306 Fn,
12307 bool IsScalar = false) {
12308 assert(E->getNumArgs() == 2 || E->getNumArgs() == 3);
12309 APValue A, B;
12310 if (!EvaluateAsRValue(Info, E->getArg(0), A) ||
12311 !EvaluateAsRValue(Info, E->getArg(1), B))
12312 return false;
12313
12314 assert(A.isVector() && B.isVector());
12315 assert(A.getVectorLength() == B.getVectorLength());
12316
12317 std::optional<APSInt> RoundingMode;
12318 if (E->getNumArgs() == 3) {
12319 APSInt Imm;
12320 if (!EvaluateInteger(E->getArg(2), Imm, Info))
12321 return false;
12322 RoundingMode = Imm;
12323 }
12324
12325 unsigned NumElems = A.getVectorLength();
12326 SmallVector<APValue, 4> ResultElements;
12327 ResultElements.reserve(NumElems);
12328
12329 for (unsigned EltNum = 0; EltNum < NumElems; ++EltNum) {
12330 if (IsScalar && EltNum > 0) {
12331 ResultElements.push_back(A.getVectorElt(EltNum));
12332 continue;
12333 }
12334 const APFloat &EltA = A.getVectorElt(EltNum).getFloat();
12335 const APFloat &EltB = B.getVectorElt(EltNum).getFloat();
12336 std::optional<APFloat> Result = Fn(EltA, EltB, RoundingMode);
12337 if (!Result)
12338 return false;
12339 ResultElements.push_back(APValue(*Result));
12340 }
12341 return Success(APValue(ResultElements.data(), NumElems), E);
12342 };
12343
12344 auto EvaluateScalarFpRoundMaskBinOp =
12345 [&](llvm::function_ref<std::optional<APFloat>(
12346 const APFloat &, const APFloat &, std::optional<APSInt>)>
12347 Fn) {
12348 assert(E->getNumArgs() == 5);
12349 APValue VecA, VecB, VecSrc;
12350 APSInt MaskVal, Rounding;
12351
12352 if (!EvaluateAsRValue(Info, E->getArg(0), VecA) ||
12353 !EvaluateAsRValue(Info, E->getArg(1), VecB) ||
12354 !EvaluateAsRValue(Info, E->getArg(2), VecSrc) ||
12355 !EvaluateInteger(E->getArg(3), MaskVal, Info) ||
12356 !EvaluateInteger(E->getArg(4), Rounding, Info))
12357 return false;
12358
12359 unsigned NumElems = VecA.getVectorLength();
12360 SmallVector<APValue, 8> ResultElements;
12361 ResultElements.reserve(NumElems);
12362
12363 if (MaskVal.getZExtValue() & 1) {
12364 const APFloat &EltA = VecA.getVectorElt(0).getFloat();
12365 const APFloat &EltB = VecB.getVectorElt(0).getFloat();
12366 std::optional<APFloat> Result = Fn(EltA, EltB, Rounding);
12367 if (!Result)
12368 return false;
12369 ResultElements.push_back(APValue(*Result));
12370 } else {
12371 ResultElements.push_back(VecSrc.getVectorElt(0));
12372 }
12373
12374 for (unsigned I = 1; I < NumElems; ++I)
12375 ResultElements.push_back(VecA.getVectorElt(I));
12376
12377 return Success(APValue(ResultElements.data(), NumElems), E);
12378 };
12379
12380 auto EvalSelectScalar = [&](unsigned Len) -> bool {
12381 APSInt Mask;
12382 APValue AVal, WVal;
12383 if (!EvaluateInteger(E->getArg(0), Mask, Info) ||
12384 !EvaluateAsRValue(Info, E->getArg(1), AVal) ||
12385 !EvaluateAsRValue(Info, E->getArg(2), WVal))
12386 return false;
12387
12388 bool TakeA0 = (Mask.getZExtValue() & 1u) != 0;
12390 Res.reserve(Len);
12391 Res.push_back(TakeA0 ? AVal.getVectorElt(0) : WVal.getVectorElt(0));
12392 for (unsigned I = 1; I < Len; ++I)
12393 Res.push_back(WVal.getVectorElt(I));
12394 APValue V(Res.data(), Res.size());
12395 return Success(V, E);
12396 };
12397
12398 switch (E->getBuiltinCallee()) {
12399 default:
12400 return false;
12401 case Builtin::BI__builtin_elementwise_popcount:
12402 case Builtin::BI__builtin_elementwise_bitreverse: {
12403 APValue Source;
12404 if (!EvaluateAsRValue(Info, E->getArg(0), Source))
12405 return false;
12406
12407 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
12408 unsigned SourceLen = Source.getVectorLength();
12409 SmallVector<APValue, 4> ResultElements;
12410 ResultElements.reserve(SourceLen);
12411
12412 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12413 APSInt Elt = Source.getVectorElt(EltNum).getInt();
12414 switch (E->getBuiltinCallee()) {
12415 case Builtin::BI__builtin_elementwise_popcount:
12416 ResultElements.push_back(APValue(
12417 APSInt(APInt(Info.Ctx.getIntWidth(DestEltTy), Elt.popcount()),
12418 DestEltTy->isUnsignedIntegerOrEnumerationType())));
12419 break;
12420 case Builtin::BI__builtin_elementwise_bitreverse:
12421 ResultElements.push_back(
12422 APValue(APSInt(Elt.reverseBits(),
12423 DestEltTy->isUnsignedIntegerOrEnumerationType())));
12424 break;
12425 }
12426 }
12427
12428 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12429 }
12430 case Builtin::BI__builtin_elementwise_abs: {
12431 APValue Source;
12432 if (!EvaluateAsRValue(Info, E->getArg(0), Source))
12433 return false;
12434
12435 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
12436 unsigned SourceLen = Source.getVectorLength();
12437 SmallVector<APValue, 4> ResultElements;
12438 ResultElements.reserve(SourceLen);
12439
12440 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12441 APValue CurrentEle = Source.getVectorElt(EltNum);
12442 APValue Val = DestEltTy->isFloatingType()
12443 ? APValue(llvm::abs(CurrentEle.getFloat()))
12444 : APValue(APSInt(
12445 CurrentEle.getInt().abs(),
12446 DestEltTy->isUnsignedIntegerOrEnumerationType()));
12447 ResultElements.push_back(Val);
12448 }
12449
12450 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12451 }
12452
12453 case Builtin::BI__builtin_elementwise_add_sat:
12454 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
12455 return LHS.isSigned() ? LHS.sadd_sat(RHS) : LHS.uadd_sat(RHS);
12456 });
12457
12458 case Builtin::BI__builtin_elementwise_sub_sat:
12459 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
12460 return LHS.isSigned() ? LHS.ssub_sat(RHS) : LHS.usub_sat(RHS);
12461 });
12462
12463 case X86::BI__builtin_ia32_extract128i256:
12464 case X86::BI__builtin_ia32_vextractf128_pd256:
12465 case X86::BI__builtin_ia32_vextractf128_ps256:
12466 case X86::BI__builtin_ia32_vextractf128_si256: {
12467 APValue SourceVec, SourceImm;
12468 if (!EvaluateAsRValue(Info, E->getArg(0), SourceVec) ||
12469 !EvaluateAsRValue(Info, E->getArg(1), SourceImm))
12470 return false;
12471
12472 if (!SourceVec.isVector())
12473 return false;
12474
12475 const auto *RetVT = E->getType()->castAs<VectorType>();
12476 unsigned RetLen = RetVT->getNumElements();
12477 unsigned Idx = SourceImm.getInt().getZExtValue() & 1;
12478
12479 SmallVector<APValue, 32> ResultElements;
12480 ResultElements.reserve(RetLen);
12481
12482 for (unsigned I = 0; I < RetLen; I++)
12483 ResultElements.push_back(SourceVec.getVectorElt(Idx * RetLen + I));
12484
12485 return Success(APValue(ResultElements.data(), RetLen), E);
12486 }
12487
12488 case clang::X86::BI__builtin_ia32_cvtmask2b128:
12489 case clang::X86::BI__builtin_ia32_cvtmask2b256:
12490 case clang::X86::BI__builtin_ia32_cvtmask2b512:
12491 case clang::X86::BI__builtin_ia32_cvtmask2w128:
12492 case clang::X86::BI__builtin_ia32_cvtmask2w256:
12493 case clang::X86::BI__builtin_ia32_cvtmask2w512:
12494 case clang::X86::BI__builtin_ia32_cvtmask2d128:
12495 case clang::X86::BI__builtin_ia32_cvtmask2d256:
12496 case clang::X86::BI__builtin_ia32_cvtmask2d512:
12497 case clang::X86::BI__builtin_ia32_cvtmask2q128:
12498 case clang::X86::BI__builtin_ia32_cvtmask2q256:
12499 case clang::X86::BI__builtin_ia32_cvtmask2q512: {
12500 assert(E->getNumArgs() == 1);
12501 APSInt Mask;
12502 if (!EvaluateInteger(E->getArg(0), Mask, Info))
12503 return false;
12504
12505 QualType VecTy = E->getType();
12506 const VectorType *VT = VecTy->castAs<VectorType>();
12507 unsigned VectorLen = VT->getNumElements();
12508 QualType ElemTy = VT->getElementType();
12509 unsigned ElemWidth = Info.Ctx.getTypeSize(ElemTy);
12510
12512 for (unsigned I = 0; I != VectorLen; ++I) {
12513 bool BitSet = Mask[I];
12514 APSInt ElemVal(ElemWidth, /*isUnsigned=*/false);
12515 if (BitSet) {
12516 ElemVal.setAllBits();
12517 }
12518 Elems.push_back(APValue(ElemVal));
12519 }
12520 return Success(APValue(Elems.data(), VectorLen), E);
12521 }
12522
12523 case X86::BI__builtin_ia32_extracti32x4_256_mask:
12524 case X86::BI__builtin_ia32_extractf32x4_256_mask:
12525 case X86::BI__builtin_ia32_extracti32x4_mask:
12526 case X86::BI__builtin_ia32_extractf32x4_mask:
12527 case X86::BI__builtin_ia32_extracti32x8_mask:
12528 case X86::BI__builtin_ia32_extractf32x8_mask:
12529 case X86::BI__builtin_ia32_extracti64x2_256_mask:
12530 case X86::BI__builtin_ia32_extractf64x2_256_mask:
12531 case X86::BI__builtin_ia32_extracti64x2_512_mask:
12532 case X86::BI__builtin_ia32_extractf64x2_512_mask:
12533 case X86::BI__builtin_ia32_extracti64x4_mask:
12534 case X86::BI__builtin_ia32_extractf64x4_mask: {
12535 APValue SourceVec, MergeVec;
12536 APSInt Imm, MaskImm;
12537
12538 if (!EvaluateAsRValue(Info, E->getArg(0), SourceVec) ||
12539 !EvaluateInteger(E->getArg(1), Imm, Info) ||
12540 !EvaluateAsRValue(Info, E->getArg(2), MergeVec) ||
12541 !EvaluateInteger(E->getArg(3), MaskImm, Info))
12542 return false;
12543
12544 const auto *RetVT = E->getType()->castAs<VectorType>();
12545 unsigned RetLen = RetVT->getNumElements();
12546
12547 if (!SourceVec.isVector() || !MergeVec.isVector())
12548 return false;
12549 unsigned SrcLen = SourceVec.getVectorLength();
12550 unsigned Lanes = SrcLen / RetLen;
12551 unsigned Lane = static_cast<unsigned>(Imm.getZExtValue() % Lanes);
12552 unsigned Base = Lane * RetLen;
12553
12554 SmallVector<APValue, 32> ResultElements;
12555 ResultElements.reserve(RetLen);
12556 for (unsigned I = 0; I < RetLen; ++I) {
12557 if (MaskImm[I])
12558 ResultElements.push_back(SourceVec.getVectorElt(Base + I));
12559 else
12560 ResultElements.push_back(MergeVec.getVectorElt(I));
12561 }
12562 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12563 }
12564
12565 case clang::X86::BI__builtin_ia32_pavgb128:
12566 case clang::X86::BI__builtin_ia32_pavgw128:
12567 case clang::X86::BI__builtin_ia32_pavgb256:
12568 case clang::X86::BI__builtin_ia32_pavgw256:
12569 case clang::X86::BI__builtin_ia32_pavgb512:
12570 case clang::X86::BI__builtin_ia32_pavgw512:
12571 return EvaluateBinOpExpr(llvm::APIntOps::avgCeilU);
12572
12573 case clang::X86::BI__builtin_ia32_pmulhrsw128:
12574 case clang::X86::BI__builtin_ia32_pmulhrsw256:
12575 case clang::X86::BI__builtin_ia32_pmulhrsw512:
12576 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
12577 return (llvm::APIntOps::mulsExtended(LHS, RHS).ashr(14) + 1)
12578 .extractBits(16, 1);
12579 });
12580
12581 case clang::X86::BI__builtin_ia32_pmaddubsw128:
12582 case clang::X86::BI__builtin_ia32_pmaddubsw256:
12583 case clang::X86::BI__builtin_ia32_pmaddubsw512:
12584 case clang::X86::BI__builtin_ia32_pmaddwd128:
12585 case clang::X86::BI__builtin_ia32_pmaddwd256:
12586 case clang::X86::BI__builtin_ia32_pmaddwd512: {
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 unsigned SourceLen = SourceLHS.getVectorLength();
12595 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
12596 SmallVector<APValue, 4> ResultElements;
12597 ResultElements.reserve(SourceLen / 2);
12598
12599 for (unsigned EltNum = 0; EltNum < SourceLen; EltNum += 2) {
12600 const APSInt &LoLHS = SourceLHS.getVectorElt(EltNum).getInt();
12601 const APSInt &HiLHS = SourceLHS.getVectorElt(EltNum + 1).getInt();
12602 const APSInt &LoRHS = SourceRHS.getVectorElt(EltNum).getInt();
12603 const APSInt &HiRHS = SourceRHS.getVectorElt(EltNum + 1).getInt();
12604 unsigned BitWidth = 2 * LoLHS.getBitWidth();
12605
12606 switch (E->getBuiltinCallee()) {
12607 case clang::X86::BI__builtin_ia32_pmaddubsw128:
12608 case clang::X86::BI__builtin_ia32_pmaddubsw256:
12609 case clang::X86::BI__builtin_ia32_pmaddubsw512:
12610 ResultElements.push_back(APValue(
12611 APSInt((LoLHS.zext(BitWidth) * LoRHS.sext(BitWidth))
12612 .sadd_sat((HiLHS.zext(BitWidth) * HiRHS.sext(BitWidth))),
12613 DestUnsigned)));
12614 break;
12615 case clang::X86::BI__builtin_ia32_pmaddwd128:
12616 case clang::X86::BI__builtin_ia32_pmaddwd256:
12617 case clang::X86::BI__builtin_ia32_pmaddwd512:
12618 ResultElements.push_back(
12619 APValue(APSInt((LoLHS.sext(BitWidth) * LoRHS.sext(BitWidth)) +
12620 (HiLHS.sext(BitWidth) * HiRHS.sext(BitWidth)),
12621 DestUnsigned)));
12622 break;
12623 }
12624 }
12625
12626 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12627 }
12628
12629 case clang::X86::BI__builtin_ia32_dbpsadbw128:
12630 case clang::X86::BI__builtin_ia32_dbpsadbw256:
12631 case clang::X86::BI__builtin_ia32_dbpsadbw512: {
12632 APValue SourceA, SourceB, SourceImm;
12633 if (!EvaluateAsRValue(Info, E->getArg(0), SourceA) ||
12634 !EvaluateAsRValue(Info, E->getArg(1), SourceB) ||
12635 !EvaluateAsRValue(Info, E->getArg(2), SourceImm))
12636 return false;
12637
12638 unsigned SourceLen = SourceA.getVectorLength();
12639 constexpr unsigned LaneSize = 16; // 128-bit lane = 16 bytes
12640 unsigned Imm = SourceImm.getInt().getZExtValue();
12641
12642 auto *DestTy = E->getType()->castAs<VectorType>();
12643 QualType DestEltTy = DestTy->getElementType();
12644 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
12645 SmallVector<APValue, 32> ResultElements;
12646 ResultElements.reserve(SourceLen / 2);
12647
12648 // Phase 1: Shuffle SourceB using all four 2-bit fields of imm8.
12649 // Within each 128-bit lane, for group j (0..3), select a 4-byte block
12650 // from SourceB based on bits [2*j+1:2*j] of imm8.
12651 SmallVector<uint8_t, 64> Shuffled(SourceLen);
12652 for (unsigned I = 0; I < SourceLen; I += LaneSize) {
12653 for (unsigned J = 0; J < 4; ++J) {
12654 unsigned Part = (Imm >> (2 * J)) & 3;
12655 for (unsigned K = 0; K < 4; ++K) {
12656 Shuffled[I + 4 * J + K] = static_cast<uint8_t>(
12657 SourceB.getVectorElt(I + 4 * Part + K).getInt().getZExtValue());
12658 }
12659 }
12660 }
12661
12662 // Phase 2: Sliding SAD computation.
12663 // For every group of 4 output u16 values, compute absolute differences
12664 // using overlapping windows into SourceA and the shuffled array.
12665 unsigned Size = SourceLen / 2; // number of output u16 elements
12666 for (unsigned I = 0; I < Size; I += 4) {
12667 unsigned Sad[4] = {0, 0, 0, 0};
12668 for (unsigned J = 0; J < 4; ++J) {
12669 uint8_t A1 = static_cast<uint8_t>(
12670 SourceA.getVectorElt(2 * I + J).getInt().getZExtValue());
12671 uint8_t A2 = static_cast<uint8_t>(
12672 SourceA.getVectorElt(2 * I + J + 4).getInt().getZExtValue());
12673 uint8_t B0 = Shuffled[2 * I + J];
12674 uint8_t B1 = Shuffled[2 * I + J + 1];
12675 uint8_t B2 = Shuffled[2 * I + J + 2];
12676 uint8_t B3 = Shuffled[2 * I + J + 3];
12677 Sad[0] += (A1 > B0) ? (A1 - B0) : (B0 - A1);
12678 Sad[1] += (A1 > B1) ? (A1 - B1) : (B1 - A1);
12679 Sad[2] += (A2 > B2) ? (A2 - B2) : (B2 - A2);
12680 Sad[3] += (A2 > B3) ? (A2 - B3) : (B3 - A2);
12681 }
12682 for (unsigned R = 0; R < 4; ++R)
12683 ResultElements.push_back(
12684 APValue(APSInt(APInt(16, Sad[R]), DestUnsigned)));
12685 }
12686
12687 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12688 }
12689
12690 case clang::X86::BI__builtin_ia32_pmulhuw128:
12691 case clang::X86::BI__builtin_ia32_pmulhuw256:
12692 case clang::X86::BI__builtin_ia32_pmulhuw512:
12693 return EvaluateBinOpExpr(llvm::APIntOps::mulhu);
12694
12695 case clang::X86::BI__builtin_ia32_pmulhw128:
12696 case clang::X86::BI__builtin_ia32_pmulhw256:
12697 case clang::X86::BI__builtin_ia32_pmulhw512:
12698 return EvaluateBinOpExpr(llvm::APIntOps::mulhs);
12699
12700 case clang::X86::BI__builtin_ia32_psllv2di:
12701 case clang::X86::BI__builtin_ia32_psllv4di:
12702 case clang::X86::BI__builtin_ia32_psllv4si:
12703 case clang::X86::BI__builtin_ia32_psllv8di:
12704 case clang::X86::BI__builtin_ia32_psllv8hi:
12705 case clang::X86::BI__builtin_ia32_psllv8si:
12706 case clang::X86::BI__builtin_ia32_psllv16hi:
12707 case clang::X86::BI__builtin_ia32_psllv16si:
12708 case clang::X86::BI__builtin_ia32_psllv32hi:
12709 case clang::X86::BI__builtin_ia32_psllwi128:
12710 case clang::X86::BI__builtin_ia32_pslldi128:
12711 case clang::X86::BI__builtin_ia32_psllqi128:
12712 case clang::X86::BI__builtin_ia32_psllwi256:
12713 case clang::X86::BI__builtin_ia32_pslldi256:
12714 case clang::X86::BI__builtin_ia32_psllqi256:
12715 case clang::X86::BI__builtin_ia32_psllwi512:
12716 case clang::X86::BI__builtin_ia32_pslldi512:
12717 case clang::X86::BI__builtin_ia32_psllqi512:
12718 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
12719 if (RHS.uge(LHS.getBitWidth())) {
12720 return APInt::getZero(LHS.getBitWidth());
12721 }
12722 return LHS.shl(RHS.getZExtValue());
12723 });
12724
12725 case clang::X86::BI__builtin_ia32_psrav4si:
12726 case clang::X86::BI__builtin_ia32_psrav8di:
12727 case clang::X86::BI__builtin_ia32_psrav8hi:
12728 case clang::X86::BI__builtin_ia32_psrav8si:
12729 case clang::X86::BI__builtin_ia32_psrav16hi:
12730 case clang::X86::BI__builtin_ia32_psrav16si:
12731 case clang::X86::BI__builtin_ia32_psrav32hi:
12732 case clang::X86::BI__builtin_ia32_psravq128:
12733 case clang::X86::BI__builtin_ia32_psravq256:
12734 case clang::X86::BI__builtin_ia32_psrawi128:
12735 case clang::X86::BI__builtin_ia32_psradi128:
12736 case clang::X86::BI__builtin_ia32_psraqi128:
12737 case clang::X86::BI__builtin_ia32_psrawi256:
12738 case clang::X86::BI__builtin_ia32_psradi256:
12739 case clang::X86::BI__builtin_ia32_psraqi256:
12740 case clang::X86::BI__builtin_ia32_psrawi512:
12741 case clang::X86::BI__builtin_ia32_psradi512:
12742 case clang::X86::BI__builtin_ia32_psraqi512:
12743 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
12744 if (RHS.uge(LHS.getBitWidth())) {
12745 return LHS.ashr(LHS.getBitWidth() - 1);
12746 }
12747 return LHS.ashr(RHS.getZExtValue());
12748 });
12749
12750 case clang::X86::BI__builtin_ia32_psrlv2di:
12751 case clang::X86::BI__builtin_ia32_psrlv4di:
12752 case clang::X86::BI__builtin_ia32_psrlv4si:
12753 case clang::X86::BI__builtin_ia32_psrlv8di:
12754 case clang::X86::BI__builtin_ia32_psrlv8hi:
12755 case clang::X86::BI__builtin_ia32_psrlv8si:
12756 case clang::X86::BI__builtin_ia32_psrlv16hi:
12757 case clang::X86::BI__builtin_ia32_psrlv16si:
12758 case clang::X86::BI__builtin_ia32_psrlv32hi:
12759 case clang::X86::BI__builtin_ia32_psrlwi128:
12760 case clang::X86::BI__builtin_ia32_psrldi128:
12761 case clang::X86::BI__builtin_ia32_psrlqi128:
12762 case clang::X86::BI__builtin_ia32_psrlwi256:
12763 case clang::X86::BI__builtin_ia32_psrldi256:
12764 case clang::X86::BI__builtin_ia32_psrlqi256:
12765 case clang::X86::BI__builtin_ia32_psrlwi512:
12766 case clang::X86::BI__builtin_ia32_psrldi512:
12767 case clang::X86::BI__builtin_ia32_psrlqi512:
12768 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
12769 if (RHS.uge(LHS.getBitWidth())) {
12770 return APInt::getZero(LHS.getBitWidth());
12771 }
12772 return LHS.lshr(RHS.getZExtValue());
12773 });
12774 case X86::BI__builtin_ia32_packsswb128:
12775 case X86::BI__builtin_ia32_packsswb256:
12776 case X86::BI__builtin_ia32_packsswb512:
12777 case X86::BI__builtin_ia32_packssdw128:
12778 case X86::BI__builtin_ia32_packssdw256:
12779 case X86::BI__builtin_ia32_packssdw512:
12780 return evalPackBuiltin(E, Info, Result, [](const APSInt &Src) {
12781 return APSInt(Src).truncSSat(Src.getBitWidth() / 2);
12782 });
12783 case X86::BI__builtin_ia32_packusdw128:
12784 case X86::BI__builtin_ia32_packusdw256:
12785 case X86::BI__builtin_ia32_packusdw512:
12786 case X86::BI__builtin_ia32_packuswb128:
12787 case X86::BI__builtin_ia32_packuswb256:
12788 case X86::BI__builtin_ia32_packuswb512:
12789 return evalPackBuiltin(E, Info, Result, [](const APSInt &Src) {
12790 return APSInt(Src).truncSSatU(Src.getBitWidth() / 2);
12791 });
12792 case clang::X86::BI__builtin_ia32_selectss_128:
12793 return EvalSelectScalar(4);
12794 case clang::X86::BI__builtin_ia32_selectsd_128:
12795 return EvalSelectScalar(2);
12796 case clang::X86::BI__builtin_ia32_selectsh_128:
12797 case clang::X86::BI__builtin_ia32_selectsbf_128:
12798 return EvalSelectScalar(8);
12799 case clang::X86::BI__builtin_ia32_pmuldq128:
12800 case clang::X86::BI__builtin_ia32_pmuldq256:
12801 case clang::X86::BI__builtin_ia32_pmuldq512:
12802 case clang::X86::BI__builtin_ia32_pmuludq128:
12803 case clang::X86::BI__builtin_ia32_pmuludq256:
12804 case clang::X86::BI__builtin_ia32_pmuludq512: {
12805 APValue SourceLHS, SourceRHS;
12806 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
12807 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
12808 return false;
12809
12810 unsigned SourceLen = SourceLHS.getVectorLength();
12811 SmallVector<APValue, 4> ResultElements;
12812 ResultElements.reserve(SourceLen / 2);
12813
12814 for (unsigned EltNum = 0; EltNum < SourceLen; EltNum += 2) {
12815 APSInt LHS = SourceLHS.getVectorElt(EltNum).getInt();
12816 APSInt RHS = SourceRHS.getVectorElt(EltNum).getInt();
12817
12818 switch (E->getBuiltinCallee()) {
12819 case clang::X86::BI__builtin_ia32_pmuludq128:
12820 case clang::X86::BI__builtin_ia32_pmuludq256:
12821 case clang::X86::BI__builtin_ia32_pmuludq512:
12822 ResultElements.push_back(
12823 APValue(APSInt(llvm::APIntOps::muluExtended(LHS, RHS), true)));
12824 break;
12825 case clang::X86::BI__builtin_ia32_pmuldq128:
12826 case clang::X86::BI__builtin_ia32_pmuldq256:
12827 case clang::X86::BI__builtin_ia32_pmuldq512:
12828 ResultElements.push_back(
12829 APValue(APSInt(llvm::APIntOps::mulsExtended(LHS, RHS), false)));
12830 break;
12831 }
12832 }
12833
12834 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12835 }
12836
12837 case X86::BI__builtin_ia32_vpmadd52luq128:
12838 case X86::BI__builtin_ia32_vpmadd52luq256:
12839 case X86::BI__builtin_ia32_vpmadd52luq512: {
12840 APValue A, B, C;
12841 if (!EvaluateAsRValue(Info, E->getArg(0), A) ||
12842 !EvaluateAsRValue(Info, E->getArg(1), B) ||
12843 !EvaluateAsRValue(Info, E->getArg(2), C))
12844 return false;
12845
12846 unsigned ALen = A.getVectorLength();
12847 SmallVector<APValue, 4> ResultElements;
12848 ResultElements.reserve(ALen);
12849
12850 for (unsigned EltNum = 0; EltNum < ALen; EltNum += 1) {
12851 APInt AElt = A.getVectorElt(EltNum).getInt();
12852 APInt BElt = B.getVectorElt(EltNum).getInt().trunc(52);
12853 APInt CElt = C.getVectorElt(EltNum).getInt().trunc(52);
12854 APSInt ResElt(AElt + (BElt * CElt).zext(64), false);
12855 ResultElements.push_back(APValue(ResElt));
12856 }
12857
12858 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12859 }
12860 case X86::BI__builtin_ia32_vpmadd52huq128:
12861 case X86::BI__builtin_ia32_vpmadd52huq256:
12862 case X86::BI__builtin_ia32_vpmadd52huq512: {
12863 APValue A, B, C;
12864 if (!EvaluateAsRValue(Info, E->getArg(0), A) ||
12865 !EvaluateAsRValue(Info, E->getArg(1), B) ||
12866 !EvaluateAsRValue(Info, E->getArg(2), C))
12867 return false;
12868
12869 unsigned ALen = A.getVectorLength();
12870 SmallVector<APValue, 4> ResultElements;
12871 ResultElements.reserve(ALen);
12872
12873 for (unsigned EltNum = 0; EltNum < ALen; EltNum += 1) {
12874 APInt AElt = A.getVectorElt(EltNum).getInt();
12875 APInt BElt = B.getVectorElt(EltNum).getInt().trunc(52);
12876 APInt CElt = C.getVectorElt(EltNum).getInt().trunc(52);
12877 APSInt ResElt(AElt + llvm::APIntOps::mulhu(BElt, CElt).zext(64), false);
12878 ResultElements.push_back(APValue(ResElt));
12879 }
12880
12881 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12882 }
12883
12884 case clang::X86::BI__builtin_ia32_vprotbi:
12885 case clang::X86::BI__builtin_ia32_vprotdi:
12886 case clang::X86::BI__builtin_ia32_vprotqi:
12887 case clang::X86::BI__builtin_ia32_vprotwi:
12888 case clang::X86::BI__builtin_ia32_prold128:
12889 case clang::X86::BI__builtin_ia32_prold256:
12890 case clang::X86::BI__builtin_ia32_prold512:
12891 case clang::X86::BI__builtin_ia32_prolq128:
12892 case clang::X86::BI__builtin_ia32_prolq256:
12893 case clang::X86::BI__builtin_ia32_prolq512:
12894 return EvaluateBinOpExpr(
12895 [](const APSInt &LHS, const APSInt &RHS) { return LHS.rotl(RHS); });
12896
12897 case clang::X86::BI__builtin_ia32_prord128:
12898 case clang::X86::BI__builtin_ia32_prord256:
12899 case clang::X86::BI__builtin_ia32_prord512:
12900 case clang::X86::BI__builtin_ia32_prorq128:
12901 case clang::X86::BI__builtin_ia32_prorq256:
12902 case clang::X86::BI__builtin_ia32_prorq512:
12903 return EvaluateBinOpExpr(
12904 [](const APSInt &LHS, const APSInt &RHS) { return LHS.rotr(RHS); });
12905
12906 case Builtin::BI__builtin_elementwise_max:
12907 case Builtin::BI__builtin_elementwise_min: {
12908 APValue SourceLHS, SourceRHS;
12909 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
12910 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
12911 return false;
12912
12913 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
12914
12915 if (!DestEltTy->isIntegerType())
12916 return false;
12917
12918 unsigned SourceLen = SourceLHS.getVectorLength();
12919 SmallVector<APValue, 4> ResultElements;
12920 ResultElements.reserve(SourceLen);
12921
12922 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12923 APSInt LHS = SourceLHS.getVectorElt(EltNum).getInt();
12924 APSInt RHS = SourceRHS.getVectorElt(EltNum).getInt();
12925 switch (E->getBuiltinCallee()) {
12926 case Builtin::BI__builtin_elementwise_max:
12927 ResultElements.push_back(
12928 APValue(APSInt(std::max(LHS, RHS),
12929 DestEltTy->isUnsignedIntegerOrEnumerationType())));
12930 break;
12931 case Builtin::BI__builtin_elementwise_min:
12932 ResultElements.push_back(
12933 APValue(APSInt(std::min(LHS, RHS),
12934 DestEltTy->isUnsignedIntegerOrEnumerationType())));
12935 break;
12936 }
12937 }
12938
12939 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12940 }
12941 case X86::BI__builtin_ia32_vpshldd128:
12942 case X86::BI__builtin_ia32_vpshldd256:
12943 case X86::BI__builtin_ia32_vpshldd512:
12944 case X86::BI__builtin_ia32_vpshldq128:
12945 case X86::BI__builtin_ia32_vpshldq256:
12946 case X86::BI__builtin_ia32_vpshldq512:
12947 case X86::BI__builtin_ia32_vpshldw128:
12948 case X86::BI__builtin_ia32_vpshldw256:
12949 case X86::BI__builtin_ia32_vpshldw512: {
12950 APValue SourceHi, SourceLo, SourceAmt;
12951 if (!EvaluateAsRValue(Info, E->getArg(0), SourceHi) ||
12952 !EvaluateAsRValue(Info, E->getArg(1), SourceLo) ||
12953 !EvaluateAsRValue(Info, E->getArg(2), SourceAmt))
12954 return false;
12955
12956 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
12957 unsigned SourceLen = SourceHi.getVectorLength();
12958 SmallVector<APValue, 32> ResultElements;
12959 ResultElements.reserve(SourceLen);
12960
12961 APInt Amt = SourceAmt.getInt();
12962 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12963 APInt Hi = SourceHi.getVectorElt(EltNum).getInt();
12964 APInt Lo = SourceLo.getVectorElt(EltNum).getInt();
12965 APInt R = llvm::APIntOps::fshl(Hi, Lo, Amt);
12966 ResultElements.push_back(
12968 }
12969
12970 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12971 }
12972 case X86::BI__builtin_ia32_vpshrdd128:
12973 case X86::BI__builtin_ia32_vpshrdd256:
12974 case X86::BI__builtin_ia32_vpshrdd512:
12975 case X86::BI__builtin_ia32_vpshrdq128:
12976 case X86::BI__builtin_ia32_vpshrdq256:
12977 case X86::BI__builtin_ia32_vpshrdq512:
12978 case X86::BI__builtin_ia32_vpshrdw128:
12979 case X86::BI__builtin_ia32_vpshrdw256:
12980 case X86::BI__builtin_ia32_vpshrdw512: {
12981 // NOTE: Reversed Hi/Lo operands.
12982 APValue SourceHi, SourceLo, SourceAmt;
12983 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLo) ||
12984 !EvaluateAsRValue(Info, E->getArg(1), SourceHi) ||
12985 !EvaluateAsRValue(Info, E->getArg(2), SourceAmt))
12986 return false;
12987
12988 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
12989 unsigned SourceLen = SourceHi.getVectorLength();
12990 SmallVector<APValue, 32> ResultElements;
12991 ResultElements.reserve(SourceLen);
12992
12993 APInt Amt = SourceAmt.getInt();
12994 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12995 APInt Hi = SourceHi.getVectorElt(EltNum).getInt();
12996 APInt Lo = SourceLo.getVectorElt(EltNum).getInt();
12997 APInt R = llvm::APIntOps::fshr(Hi, Lo, Amt);
12998 ResultElements.push_back(
13000 }
13001
13002 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13003 }
13004 case X86::BI__builtin_ia32_compressdf128_mask:
13005 case X86::BI__builtin_ia32_compressdf256_mask:
13006 case X86::BI__builtin_ia32_compressdf512_mask:
13007 case X86::BI__builtin_ia32_compressdi128_mask:
13008 case X86::BI__builtin_ia32_compressdi256_mask:
13009 case X86::BI__builtin_ia32_compressdi512_mask:
13010 case X86::BI__builtin_ia32_compresshi128_mask:
13011 case X86::BI__builtin_ia32_compresshi256_mask:
13012 case X86::BI__builtin_ia32_compresshi512_mask:
13013 case X86::BI__builtin_ia32_compressqi128_mask:
13014 case X86::BI__builtin_ia32_compressqi256_mask:
13015 case X86::BI__builtin_ia32_compressqi512_mask:
13016 case X86::BI__builtin_ia32_compresssf128_mask:
13017 case X86::BI__builtin_ia32_compresssf256_mask:
13018 case X86::BI__builtin_ia32_compresssf512_mask:
13019 case X86::BI__builtin_ia32_compresssi128_mask:
13020 case X86::BI__builtin_ia32_compresssi256_mask:
13021 case X86::BI__builtin_ia32_compresssi512_mask: {
13022 APValue Source, Passthru;
13023 if (!EvaluateAsRValue(Info, E->getArg(0), Source) ||
13024 !EvaluateAsRValue(Info, E->getArg(1), Passthru))
13025 return false;
13026 APSInt Mask;
13027 if (!EvaluateInteger(E->getArg(2), Mask, Info))
13028 return false;
13029
13030 unsigned NumElts = Source.getVectorLength();
13031 SmallVector<APValue, 64> ResultElements;
13032 ResultElements.reserve(NumElts);
13033
13034 for (unsigned I = 0; I != NumElts; ++I) {
13035 if (Mask[I])
13036 ResultElements.push_back(Source.getVectorElt(I));
13037 }
13038 for (unsigned I = ResultElements.size(); I != NumElts; ++I) {
13039 ResultElements.push_back(Passthru.getVectorElt(I));
13040 }
13041
13042 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13043 }
13044 case X86::BI__builtin_ia32_expanddf128_mask:
13045 case X86::BI__builtin_ia32_expanddf256_mask:
13046 case X86::BI__builtin_ia32_expanddf512_mask:
13047 case X86::BI__builtin_ia32_expanddi128_mask:
13048 case X86::BI__builtin_ia32_expanddi256_mask:
13049 case X86::BI__builtin_ia32_expanddi512_mask:
13050 case X86::BI__builtin_ia32_expandhi128_mask:
13051 case X86::BI__builtin_ia32_expandhi256_mask:
13052 case X86::BI__builtin_ia32_expandhi512_mask:
13053 case X86::BI__builtin_ia32_expandqi128_mask:
13054 case X86::BI__builtin_ia32_expandqi256_mask:
13055 case X86::BI__builtin_ia32_expandqi512_mask:
13056 case X86::BI__builtin_ia32_expandsf128_mask:
13057 case X86::BI__builtin_ia32_expandsf256_mask:
13058 case X86::BI__builtin_ia32_expandsf512_mask:
13059 case X86::BI__builtin_ia32_expandsi128_mask:
13060 case X86::BI__builtin_ia32_expandsi256_mask:
13061 case X86::BI__builtin_ia32_expandsi512_mask: {
13062 APValue Source, Passthru;
13063 if (!EvaluateAsRValue(Info, E->getArg(0), Source) ||
13064 !EvaluateAsRValue(Info, E->getArg(1), Passthru))
13065 return false;
13066 APSInt Mask;
13067 if (!EvaluateInteger(E->getArg(2), Mask, Info))
13068 return false;
13069
13070 unsigned NumElts = Source.getVectorLength();
13071 SmallVector<APValue, 64> ResultElements;
13072 ResultElements.reserve(NumElts);
13073
13074 unsigned SourceIdx = 0;
13075 for (unsigned I = 0; I != NumElts; ++I) {
13076 if (Mask[I])
13077 ResultElements.push_back(Source.getVectorElt(SourceIdx++));
13078 else
13079 ResultElements.push_back(Passthru.getVectorElt(I));
13080 }
13081 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13082 }
13083 case X86::BI__builtin_ia32_vpconflictsi_128:
13084 case X86::BI__builtin_ia32_vpconflictsi_256:
13085 case X86::BI__builtin_ia32_vpconflictsi_512:
13086 case X86::BI__builtin_ia32_vpconflictdi_128:
13087 case X86::BI__builtin_ia32_vpconflictdi_256:
13088 case X86::BI__builtin_ia32_vpconflictdi_512: {
13089 APValue Source;
13090
13091 if (!EvaluateAsRValue(Info, E->getArg(0), Source))
13092 return false;
13093
13094 unsigned SourceLen = Source.getVectorLength();
13095 SmallVector<APValue, 32> ResultElements;
13096 ResultElements.reserve(SourceLen);
13097
13098 const auto *VecT = E->getType()->castAs<VectorType>();
13099 bool DestUnsigned =
13100 VecT->getElementType()->isUnsignedIntegerOrEnumerationType();
13101
13102 for (unsigned I = 0; I != SourceLen; ++I) {
13103 const APValue &EltI = Source.getVectorElt(I);
13104
13105 APInt ConflictMask(EltI.getInt().getBitWidth(), 0);
13106 for (unsigned J = 0; J != I; ++J) {
13107 const APValue &EltJ = Source.getVectorElt(J);
13108 ConflictMask.setBitVal(J, EltI.getInt() == EltJ.getInt());
13109 }
13110 ResultElements.push_back(APValue(APSInt(ConflictMask, DestUnsigned)));
13111 }
13112 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13113 }
13114 case X86::BI__builtin_ia32_blendpd:
13115 case X86::BI__builtin_ia32_blendpd256:
13116 case X86::BI__builtin_ia32_blendps:
13117 case X86::BI__builtin_ia32_blendps256:
13118 case X86::BI__builtin_ia32_pblendw128:
13119 case X86::BI__builtin_ia32_pblendw256:
13120 case X86::BI__builtin_ia32_pblendd128:
13121 case X86::BI__builtin_ia32_pblendd256: {
13122 APValue SourceF, SourceT, SourceC;
13123 if (!EvaluateAsRValue(Info, E->getArg(0), SourceF) ||
13124 !EvaluateAsRValue(Info, E->getArg(1), SourceT) ||
13125 !EvaluateAsRValue(Info, E->getArg(2), SourceC))
13126 return false;
13127
13128 const APInt &C = SourceC.getInt();
13129 unsigned SourceLen = SourceF.getVectorLength();
13130 SmallVector<APValue, 32> ResultElements;
13131 ResultElements.reserve(SourceLen);
13132 for (unsigned EltNum = 0; EltNum != SourceLen; ++EltNum) {
13133 const APValue &F = SourceF.getVectorElt(EltNum);
13134 const APValue &T = SourceT.getVectorElt(EltNum);
13135 ResultElements.push_back(C[EltNum % 8] ? T : F);
13136 }
13137
13138 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13139 }
13140
13141 case X86::BI__builtin_ia32_psignb128:
13142 case X86::BI__builtin_ia32_psignb256:
13143 case X86::BI__builtin_ia32_psignw128:
13144 case X86::BI__builtin_ia32_psignw256:
13145 case X86::BI__builtin_ia32_psignd128:
13146 case X86::BI__builtin_ia32_psignd256:
13147 return EvaluateBinOpExpr([](const APInt &AElem, const APInt &BElem) {
13148 if (BElem.isZero())
13149 return APInt::getZero(AElem.getBitWidth());
13150 if (BElem.isNegative())
13151 return -AElem;
13152 return AElem;
13153 });
13154
13155 case X86::BI__builtin_ia32_blendvpd:
13156 case X86::BI__builtin_ia32_blendvpd256:
13157 case X86::BI__builtin_ia32_blendvps:
13158 case X86::BI__builtin_ia32_blendvps256:
13159 case X86::BI__builtin_ia32_pblendvb128:
13160 case X86::BI__builtin_ia32_pblendvb256: {
13161 // SSE blendv by mask signbit: "Result = C[] < 0 ? T[] : F[]".
13162 APValue SourceF, SourceT, SourceC;
13163 if (!EvaluateAsRValue(Info, E->getArg(0), SourceF) ||
13164 !EvaluateAsRValue(Info, E->getArg(1), SourceT) ||
13165 !EvaluateAsRValue(Info, E->getArg(2), SourceC))
13166 return false;
13167
13168 unsigned SourceLen = SourceF.getVectorLength();
13169 SmallVector<APValue, 32> ResultElements;
13170 ResultElements.reserve(SourceLen);
13171
13172 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
13173 const APValue &F = SourceF.getVectorElt(EltNum);
13174 const APValue &T = SourceT.getVectorElt(EltNum);
13175 const APValue &C = SourceC.getVectorElt(EltNum);
13176 APInt M = C.isInt() ? (APInt)C.getInt() : C.getFloat().bitcastToAPInt();
13177 ResultElements.push_back(M.isNegative() ? T : F);
13178 }
13179
13180 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13181 }
13182 case X86::BI__builtin_ia32_selectb_128:
13183 case X86::BI__builtin_ia32_selectb_256:
13184 case X86::BI__builtin_ia32_selectb_512:
13185 case X86::BI__builtin_ia32_selectw_128:
13186 case X86::BI__builtin_ia32_selectw_256:
13187 case X86::BI__builtin_ia32_selectw_512:
13188 case X86::BI__builtin_ia32_selectd_128:
13189 case X86::BI__builtin_ia32_selectd_256:
13190 case X86::BI__builtin_ia32_selectd_512:
13191 case X86::BI__builtin_ia32_selectq_128:
13192 case X86::BI__builtin_ia32_selectq_256:
13193 case X86::BI__builtin_ia32_selectq_512:
13194 case X86::BI__builtin_ia32_selectph_128:
13195 case X86::BI__builtin_ia32_selectph_256:
13196 case X86::BI__builtin_ia32_selectph_512:
13197 case X86::BI__builtin_ia32_selectpbf_128:
13198 case X86::BI__builtin_ia32_selectpbf_256:
13199 case X86::BI__builtin_ia32_selectpbf_512:
13200 case X86::BI__builtin_ia32_selectps_128:
13201 case X86::BI__builtin_ia32_selectps_256:
13202 case X86::BI__builtin_ia32_selectps_512:
13203 case X86::BI__builtin_ia32_selectpd_128:
13204 case X86::BI__builtin_ia32_selectpd_256:
13205 case X86::BI__builtin_ia32_selectpd_512: {
13206 // AVX512 predicated move: "Result = Mask[] ? LHS[] : RHS[]".
13207 APValue SourceMask, SourceLHS, SourceRHS;
13208 if (!EvaluateAsRValue(Info, E->getArg(0), SourceMask) ||
13209 !EvaluateAsRValue(Info, E->getArg(1), SourceLHS) ||
13210 !EvaluateAsRValue(Info, E->getArg(2), SourceRHS))
13211 return false;
13212
13213 APSInt Mask = SourceMask.getInt();
13214 unsigned SourceLen = SourceLHS.getVectorLength();
13215 SmallVector<APValue, 4> ResultElements;
13216 ResultElements.reserve(SourceLen);
13217
13218 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
13219 const APValue &LHS = SourceLHS.getVectorElt(EltNum);
13220 const APValue &RHS = SourceRHS.getVectorElt(EltNum);
13221 ResultElements.push_back(Mask[EltNum] ? LHS : RHS);
13222 }
13223
13224 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13225 }
13226
13227 case X86::BI__builtin_ia32_cvtsd2ss: {
13228 APValue VecA, VecB;
13229 if (!EvaluateAsRValue(Info, E->getArg(0), VecA) ||
13230 !EvaluateAsRValue(Info, E->getArg(1), VecB))
13231 return false;
13232
13233 SmallVector<APValue, 4> Elements;
13234
13235 APValue ResultVal;
13236 if (!ConvertDoubleToFloatStrict(Info, E, VecB.getVectorElt(0).getFloat(),
13237 ResultVal))
13238 return false;
13239
13240 Elements.push_back(ResultVal);
13241
13242 unsigned NumEltsA = VecA.getVectorLength();
13243 for (unsigned I = 1; I < NumEltsA; ++I) {
13244 Elements.push_back(VecA.getVectorElt(I));
13245 }
13246
13247 return Success(Elements, E);
13248 }
13249 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: {
13250 APValue VecA, VecB, VecSrc, MaskValue;
13251
13252 if (!EvaluateAsRValue(Info, E->getArg(0), VecA) ||
13253 !EvaluateAsRValue(Info, E->getArg(1), VecB) ||
13254 !EvaluateAsRValue(Info, E->getArg(2), VecSrc) ||
13255 !EvaluateAsRValue(Info, E->getArg(3), MaskValue))
13256 return false;
13257
13258 unsigned Mask = MaskValue.getInt().getZExtValue();
13259 SmallVector<APValue, 4> Elements;
13260
13261 if (Mask & 1) {
13262 APValue ResultVal;
13263 if (!ConvertDoubleToFloatStrict(Info, E, VecB.getVectorElt(0).getFloat(),
13264 ResultVal))
13265 return false;
13266 Elements.push_back(ResultVal);
13267 } else {
13268 Elements.push_back(VecSrc.getVectorElt(0));
13269 }
13270
13271 unsigned NumEltsA = VecA.getVectorLength();
13272 for (unsigned I = 1; I < NumEltsA; ++I) {
13273 Elements.push_back(VecA.getVectorElt(I));
13274 }
13275
13276 return Success(Elements, E);
13277 }
13278 case X86::BI__builtin_ia32_cvtpd2ps:
13279 case X86::BI__builtin_ia32_cvtpd2ps256:
13280 case X86::BI__builtin_ia32_cvtpd2ps_mask:
13281 case X86::BI__builtin_ia32_cvtpd2ps512_mask: {
13282
13283 const auto BuiltinID = E->getBuiltinCallee();
13284 bool IsMasked = (BuiltinID == X86::BI__builtin_ia32_cvtpd2ps_mask ||
13285 BuiltinID == X86::BI__builtin_ia32_cvtpd2ps512_mask);
13286
13287 APValue InputValue;
13288 if (!EvaluateAsRValue(Info, E->getArg(0), InputValue))
13289 return false;
13290
13291 APValue MergeValue;
13292 unsigned Mask = 0xFFFFFFFF;
13293 bool NeedsMerge = false;
13294 if (IsMasked) {
13295 APValue MaskValue;
13296 if (!EvaluateAsRValue(Info, E->getArg(2), MaskValue))
13297 return false;
13298 Mask = MaskValue.getInt().getZExtValue();
13299 auto NumEltsResult = E->getType()->getAs<VectorType>()->getNumElements();
13300 for (unsigned I = 0; I < NumEltsResult; ++I) {
13301 if (!((Mask >> I) & 1)) {
13302 NeedsMerge = true;
13303 break;
13304 }
13305 }
13306 if (NeedsMerge) {
13307 if (!EvaluateAsRValue(Info, E->getArg(1), MergeValue))
13308 return false;
13309 }
13310 }
13311
13312 unsigned NumEltsResult =
13313 E->getType()->getAs<VectorType>()->getNumElements();
13314 unsigned NumEltsInput = InputValue.getVectorLength();
13315 SmallVector<APValue, 8> Elements;
13316 for (unsigned I = 0; I < NumEltsResult; ++I) {
13317 if (IsMasked && !((Mask >> I) & 1)) {
13318 if (!NeedsMerge) {
13319 return false;
13320 }
13321 Elements.push_back(MergeValue.getVectorElt(I));
13322 continue;
13323 }
13324
13325 if (I >= NumEltsInput) {
13326 Elements.push_back(APValue(APFloat::getZero(APFloat::IEEEsingle())));
13327 continue;
13328 }
13329
13330 APValue ResultVal;
13332 Info, E, InputValue.getVectorElt(I).getFloat(), ResultVal))
13333 return false;
13334
13335 Elements.push_back(ResultVal);
13336 }
13337 return Success(Elements, E);
13338 }
13339
13340 case X86::BI__builtin_ia32_shufps:
13341 case X86::BI__builtin_ia32_shufps256:
13342 case X86::BI__builtin_ia32_shufps512: {
13343 APValue R;
13344 if (!evalShuffleGeneric(
13345 Info, E, R,
13346 [](unsigned DstIdx,
13347 unsigned ShuffleMask) -> std::pair<unsigned, int> {
13348 constexpr unsigned LaneBits = 128u;
13349 unsigned NumElemPerLane = LaneBits / 32;
13350 unsigned NumSelectableElems = NumElemPerLane / 2;
13351 unsigned BitsPerElem = 2;
13352 unsigned IndexMask = (1u << BitsPerElem) - 1;
13353 unsigned MaskBits = 8;
13354 unsigned Lane = DstIdx / NumElemPerLane;
13355 unsigned ElemInLane = DstIdx % NumElemPerLane;
13356 unsigned LaneOffset = Lane * NumElemPerLane;
13357 unsigned BitIndex = (DstIdx * BitsPerElem) % MaskBits;
13358 unsigned SrcIdx = (ElemInLane < NumSelectableElems) ? 0 : 1;
13359 unsigned Index = (ShuffleMask >> BitIndex) & IndexMask;
13360 return {SrcIdx, static_cast<int>(LaneOffset + Index)};
13361 }))
13362 return false;
13363 return Success(R, E);
13364 }
13365 case X86::BI__builtin_ia32_shufpd:
13366 case X86::BI__builtin_ia32_shufpd256:
13367 case X86::BI__builtin_ia32_shufpd512: {
13368 APValue R;
13369 if (!evalShuffleGeneric(
13370 Info, E, R,
13371 [](unsigned DstIdx,
13372 unsigned ShuffleMask) -> std::pair<unsigned, int> {
13373 constexpr unsigned LaneBits = 128u;
13374 unsigned NumElemPerLane = LaneBits / 64;
13375 unsigned NumSelectableElems = NumElemPerLane / 2;
13376 unsigned BitsPerElem = 1;
13377 unsigned IndexMask = (1u << BitsPerElem) - 1;
13378 unsigned MaskBits = 8;
13379 unsigned Lane = DstIdx / NumElemPerLane;
13380 unsigned ElemInLane = DstIdx % NumElemPerLane;
13381 unsigned LaneOffset = Lane * NumElemPerLane;
13382 unsigned BitIndex = (DstIdx * BitsPerElem) % MaskBits;
13383 unsigned SrcIdx = (ElemInLane < NumSelectableElems) ? 0 : 1;
13384 unsigned Index = (ShuffleMask >> BitIndex) & IndexMask;
13385 return {SrcIdx, static_cast<int>(LaneOffset + Index)};
13386 }))
13387 return false;
13388 return Success(R, E);
13389 }
13390 case X86::BI__builtin_ia32_insertps128: {
13391 APValue R;
13392 if (!evalShuffleGeneric(
13393 Info, E, R,
13394 [](unsigned DstIdx, unsigned Mask) -> std::pair<unsigned, int> {
13395 // Bits [3:0]: zero mask - if bit is set, zero this element
13396 if ((Mask & (1 << DstIdx)) != 0) {
13397 return {0, -1};
13398 }
13399 // Bits [7:6]: select element from source vector Y (0-3)
13400 // Bits [5:4]: select destination position (0-3)
13401 unsigned SrcElem = (Mask >> 6) & 0x3;
13402 unsigned DstElem = (Mask >> 4) & 0x3;
13403 if (DstIdx == DstElem) {
13404 // Insert element from source vector (B) at this position
13405 return {1, static_cast<int>(SrcElem)};
13406 } else {
13407 // Copy from destination vector (A)
13408 return {0, static_cast<int>(DstIdx)};
13409 }
13410 }))
13411 return false;
13412 return Success(R, E);
13413 }
13414 case X86::BI__builtin_ia32_pshufb128:
13415 case X86::BI__builtin_ia32_pshufb256:
13416 case X86::BI__builtin_ia32_pshufb512: {
13417 APValue R;
13418 if (!evalShuffleGeneric(
13419 Info, E, R,
13420 [](unsigned DstIdx,
13421 unsigned ShuffleMask) -> std::pair<unsigned, int> {
13422 uint8_t Ctlb = static_cast<uint8_t>(ShuffleMask);
13423 if (Ctlb & 0x80)
13424 return std::make_pair(0, -1);
13425
13426 unsigned LaneBase = (DstIdx / 16) * 16;
13427 unsigned SrcOffset = Ctlb & 0x0F;
13428 unsigned SrcIdx = LaneBase + SrcOffset;
13429 return std::make_pair(0, static_cast<int>(SrcIdx));
13430 }))
13431 return false;
13432 return Success(R, E);
13433 }
13434
13435 case X86::BI__builtin_ia32_pshuflw:
13436 case X86::BI__builtin_ia32_pshuflw256:
13437 case X86::BI__builtin_ia32_pshuflw512: {
13438 APValue R;
13439 if (!evalShuffleGeneric(
13440 Info, E, R,
13441 [](unsigned DstIdx, unsigned Mask) -> std::pair<unsigned, int> {
13442 constexpr unsigned LaneBits = 128u;
13443 constexpr unsigned ElemBits = 16u;
13444 constexpr unsigned LaneElts = LaneBits / ElemBits;
13445 constexpr unsigned HalfSize = 4;
13446 unsigned LaneBase = (DstIdx / LaneElts) * LaneElts;
13447 unsigned LaneIdx = DstIdx % LaneElts;
13448 if (LaneIdx < HalfSize) {
13449 unsigned Sel = (Mask >> (2 * LaneIdx)) & 0x3;
13450 return std::make_pair(0, static_cast<int>(LaneBase + Sel));
13451 }
13452 return std::make_pair(0, static_cast<int>(DstIdx));
13453 }))
13454 return false;
13455 return Success(R, E);
13456 }
13457
13458 case X86::BI__builtin_ia32_pshufhw:
13459 case X86::BI__builtin_ia32_pshufhw256:
13460 case X86::BI__builtin_ia32_pshufhw512: {
13461 APValue R;
13462 if (!evalShuffleGeneric(
13463 Info, E, R,
13464 [](unsigned DstIdx, unsigned Mask) -> std::pair<unsigned, int> {
13465 constexpr unsigned LaneBits = 128u;
13466 constexpr unsigned ElemBits = 16u;
13467 constexpr unsigned LaneElts = LaneBits / ElemBits;
13468 constexpr unsigned HalfSize = 4;
13469 unsigned LaneBase = (DstIdx / LaneElts) * LaneElts;
13470 unsigned LaneIdx = DstIdx % LaneElts;
13471 if (LaneIdx >= HalfSize) {
13472 unsigned Rel = LaneIdx - HalfSize;
13473 unsigned Sel = (Mask >> (2 * Rel)) & 0x3;
13474 return std::make_pair(
13475 0, static_cast<int>(LaneBase + HalfSize + Sel));
13476 }
13477 return std::make_pair(0, static_cast<int>(DstIdx));
13478 }))
13479 return false;
13480 return Success(R, E);
13481 }
13482
13483 case X86::BI__builtin_ia32_pshufd:
13484 case X86::BI__builtin_ia32_pshufd256:
13485 case X86::BI__builtin_ia32_pshufd512:
13486 case X86::BI__builtin_ia32_vpermilps:
13487 case X86::BI__builtin_ia32_vpermilps256:
13488 case X86::BI__builtin_ia32_vpermilps512: {
13489 APValue R;
13490 if (!evalShuffleGeneric(
13491 Info, E, R,
13492 [](unsigned DstIdx, unsigned Mask) -> std::pair<unsigned, int> {
13493 constexpr unsigned LaneBits = 128u;
13494 constexpr unsigned ElemBits = 32u;
13495 constexpr unsigned LaneElts = LaneBits / ElemBits;
13496 unsigned LaneBase = (DstIdx / LaneElts) * LaneElts;
13497 unsigned LaneIdx = DstIdx % LaneElts;
13498 unsigned Sel = (Mask >> (2 * LaneIdx)) & 0x3;
13499 return std::make_pair(0, static_cast<int>(LaneBase + Sel));
13500 }))
13501 return false;
13502 return Success(R, E);
13503 }
13504
13505 case X86::BI__builtin_ia32_vpermilvarpd:
13506 case X86::BI__builtin_ia32_vpermilvarpd256:
13507 case X86::BI__builtin_ia32_vpermilvarpd512: {
13508 APValue R;
13509 if (!evalShuffleGeneric(
13510 Info, E, R,
13511 [](unsigned DstIdx, unsigned Mask) -> std::pair<unsigned, int> {
13512 unsigned NumElemPerLane = 2;
13513 unsigned Lane = DstIdx / NumElemPerLane;
13514 unsigned Offset = Mask & 0b10 ? 1 : 0;
13515 return std::make_pair(
13516 0, static_cast<int>(Lane * NumElemPerLane + Offset));
13517 }))
13518 return false;
13519 return Success(R, E);
13520 }
13521
13522 case X86::BI__builtin_ia32_vpermilpd:
13523 case X86::BI__builtin_ia32_vpermilpd256:
13524 case X86::BI__builtin_ia32_vpermilpd512: {
13525 APValue R;
13526 if (!evalShuffleGeneric(Info, E, R, [](unsigned DstIdx, unsigned Control) {
13527 unsigned NumElemPerLane = 2;
13528 unsigned BitsPerElem = 1;
13529 unsigned MaskBits = 8;
13530 unsigned IndexMask = 0x1;
13531 unsigned Lane = DstIdx / NumElemPerLane;
13532 unsigned LaneOffset = Lane * NumElemPerLane;
13533 unsigned BitIndex = (DstIdx * BitsPerElem) % MaskBits;
13534 unsigned Index = (Control >> BitIndex) & IndexMask;
13535 return std::make_pair(0, static_cast<int>(LaneOffset + Index));
13536 }))
13537 return false;
13538 return Success(R, E);
13539 }
13540
13541 case X86::BI__builtin_ia32_permdf256:
13542 case X86::BI__builtin_ia32_permdi256: {
13543 APValue R;
13544 if (!evalShuffleGeneric(Info, E, R, [](unsigned DstIdx, unsigned Control) {
13545 // permute4x64 operates on 4 64-bit elements
13546 // For element i (0-3), extract bits [2*i+1:2*i] from Control
13547 unsigned Index = (Control >> (2 * DstIdx)) & 0x3;
13548 return std::make_pair(0, static_cast<int>(Index));
13549 }))
13550 return false;
13551 return Success(R, E);
13552 }
13553
13554 case X86::BI__builtin_ia32_vpermilvarps:
13555 case X86::BI__builtin_ia32_vpermilvarps256:
13556 case X86::BI__builtin_ia32_vpermilvarps512: {
13557 APValue R;
13558 if (!evalShuffleGeneric(
13559 Info, E, R,
13560 [](unsigned DstIdx, unsigned Mask) -> std::pair<unsigned, int> {
13561 unsigned NumElemPerLane = 4;
13562 unsigned Lane = DstIdx / NumElemPerLane;
13563 unsigned Offset = Mask & 0b11;
13564 return std::make_pair(
13565 0, static_cast<int>(Lane * NumElemPerLane + Offset));
13566 }))
13567 return false;
13568 return Success(R, E);
13569 }
13570
13571 case X86::BI__builtin_ia32_vpmultishiftqb128:
13572 case X86::BI__builtin_ia32_vpmultishiftqb256:
13573 case X86::BI__builtin_ia32_vpmultishiftqb512: {
13574 assert(E->getNumArgs() == 2);
13575
13576 APValue A, B;
13577 if (!Evaluate(A, Info, E->getArg(0)) || !Evaluate(B, Info, E->getArg(1)))
13578 return false;
13579
13580 assert(A.getVectorLength() == B.getVectorLength());
13581 unsigned NumBytesInQWord = 8;
13582 unsigned NumBitsInByte = 8;
13583 unsigned NumBytes = A.getVectorLength();
13584 unsigned NumQWords = NumBytes / NumBytesInQWord;
13586 Result.reserve(NumBytes);
13587
13588 for (unsigned QWordId = 0; QWordId != NumQWords; ++QWordId) {
13589 APInt BQWord(64, 0);
13590 for (unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
13591 unsigned Idx = QWordId * NumBytesInQWord + ByteIdx;
13592 uint64_t Byte = B.getVectorElt(Idx).getInt().getZExtValue();
13593 BQWord.insertBits(APInt(8, Byte & 0xFF), ByteIdx * NumBitsInByte);
13594 }
13595
13596 for (unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
13597 unsigned Idx = QWordId * NumBytesInQWord + ByteIdx;
13598 uint64_t Ctrl = A.getVectorElt(Idx).getInt().getZExtValue() & 0x3F;
13599
13600 APInt Byte(8, 0);
13601 for (unsigned BitIdx = 0; BitIdx != NumBitsInByte; ++BitIdx) {
13602 Byte.setBitVal(BitIdx, BQWord[(Ctrl + BitIdx) & 0x3F]);
13603 }
13604 Result.push_back(APValue(APSInt(Byte, /*isUnsigned*/ true)));
13605 }
13606 }
13607 return Success(APValue(Result.data(), Result.size()), E);
13608 }
13609
13610 case X86::BI__builtin_ia32_phminposuw128: {
13611 APValue Source;
13612 if (!Evaluate(Source, Info, E->getArg(0)))
13613 return false;
13614 unsigned SourceLen = Source.getVectorLength();
13615 const VectorType *VT = E->getArg(0)->getType()->castAs<VectorType>();
13616 QualType ElemQT = VT->getElementType();
13617 unsigned ElemBitWidth = Info.Ctx.getTypeSize(ElemQT);
13618
13619 APInt MinIndex(ElemBitWidth, 0);
13620 APInt MinVal = Source.getVectorElt(0).getInt();
13621 for (unsigned I = 1; I != SourceLen; ++I) {
13622 APInt Val = Source.getVectorElt(I).getInt();
13623 if (MinVal.ugt(Val)) {
13624 MinVal = Val;
13625 MinIndex = I;
13626 }
13627 }
13628
13629 bool ResultUnsigned = E->getCallReturnType(Info.Ctx)
13630 ->castAs<VectorType>()
13631 ->getElementType()
13632 ->isUnsignedIntegerOrEnumerationType();
13633
13635 Result.reserve(SourceLen);
13636 Result.emplace_back(APSInt(MinVal, ResultUnsigned));
13637 Result.emplace_back(APSInt(MinIndex, ResultUnsigned));
13638 for (unsigned I = 0; I != SourceLen - 2; ++I) {
13639 Result.emplace_back(APSInt(APInt(ElemBitWidth, 0), ResultUnsigned));
13640 }
13641 return Success(APValue(Result.data(), Result.size()), E);
13642 }
13643
13644 case X86::BI__builtin_ia32_psraq128:
13645 case X86::BI__builtin_ia32_psraq256:
13646 case X86::BI__builtin_ia32_psraq512:
13647 case X86::BI__builtin_ia32_psrad128:
13648 case X86::BI__builtin_ia32_psrad256:
13649 case X86::BI__builtin_ia32_psrad512:
13650 case X86::BI__builtin_ia32_psraw128:
13651 case X86::BI__builtin_ia32_psraw256:
13652 case X86::BI__builtin_ia32_psraw512: {
13653 APValue R;
13654 if (!evalShiftWithCount(
13655 Info, E, R,
13656 [](const APInt &Elt, uint64_t Count) { return Elt.ashr(Count); },
13657 [](const APInt &Elt, unsigned Width) {
13658 return Elt.ashr(Width - 1);
13659 }))
13660 return false;
13661 return Success(R, E);
13662 }
13663
13664 case X86::BI__builtin_ia32_psllq128:
13665 case X86::BI__builtin_ia32_psllq256:
13666 case X86::BI__builtin_ia32_psllq512:
13667 case X86::BI__builtin_ia32_pslld128:
13668 case X86::BI__builtin_ia32_pslld256:
13669 case X86::BI__builtin_ia32_pslld512:
13670 case X86::BI__builtin_ia32_psllw128:
13671 case X86::BI__builtin_ia32_psllw256:
13672 case X86::BI__builtin_ia32_psllw512: {
13673 APValue R;
13674 if (!evalShiftWithCount(
13675 Info, E, R,
13676 [](const APInt &Elt, uint64_t Count) { return Elt.shl(Count); },
13677 [](const APInt &Elt, unsigned Width) {
13678 return APInt::getZero(Width);
13679 }))
13680 return false;
13681 return Success(R, E);
13682 }
13683
13684 case X86::BI__builtin_ia32_psrlq128:
13685 case X86::BI__builtin_ia32_psrlq256:
13686 case X86::BI__builtin_ia32_psrlq512:
13687 case X86::BI__builtin_ia32_psrld128:
13688 case X86::BI__builtin_ia32_psrld256:
13689 case X86::BI__builtin_ia32_psrld512:
13690 case X86::BI__builtin_ia32_psrlw128:
13691 case X86::BI__builtin_ia32_psrlw256:
13692 case X86::BI__builtin_ia32_psrlw512: {
13693 APValue R;
13694 if (!evalShiftWithCount(
13695 Info, E, R,
13696 [](const APInt &Elt, uint64_t Count) { return Elt.lshr(Count); },
13697 [](const APInt &Elt, unsigned Width) {
13698 return APInt::getZero(Width);
13699 }))
13700 return false;
13701 return Success(R, E);
13702 }
13703
13704 case X86::BI__builtin_ia32_pternlogd128_mask:
13705 case X86::BI__builtin_ia32_pternlogd256_mask:
13706 case X86::BI__builtin_ia32_pternlogd512_mask:
13707 case X86::BI__builtin_ia32_pternlogq128_mask:
13708 case X86::BI__builtin_ia32_pternlogq256_mask:
13709 case X86::BI__builtin_ia32_pternlogq512_mask: {
13710 APValue AValue, BValue, CValue, ImmValue, UValue;
13711 if (!EvaluateAsRValue(Info, E->getArg(0), AValue) ||
13712 !EvaluateAsRValue(Info, E->getArg(1), BValue) ||
13713 !EvaluateAsRValue(Info, E->getArg(2), CValue) ||
13714 !EvaluateAsRValue(Info, E->getArg(3), ImmValue) ||
13715 !EvaluateAsRValue(Info, E->getArg(4), UValue))
13716 return false;
13717
13718 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
13719 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
13720 APInt Imm = ImmValue.getInt();
13721 APInt U = UValue.getInt();
13722 unsigned ResultLen = AValue.getVectorLength();
13723 SmallVector<APValue, 16> ResultElements;
13724 ResultElements.reserve(ResultLen);
13725
13726 for (unsigned EltNum = 0; EltNum < ResultLen; ++EltNum) {
13727 APInt ALane = AValue.getVectorElt(EltNum).getInt();
13728 APInt BLane = BValue.getVectorElt(EltNum).getInt();
13729 APInt CLane = CValue.getVectorElt(EltNum).getInt();
13730
13731 if (U[EltNum]) {
13732 unsigned BitWidth = ALane.getBitWidth();
13733 APInt ResLane(BitWidth, 0);
13734
13735 for (unsigned Bit = 0; Bit < BitWidth; ++Bit) {
13736 unsigned ABit = ALane[Bit];
13737 unsigned BBit = BLane[Bit];
13738 unsigned CBit = CLane[Bit];
13739
13740 unsigned Idx = (ABit << 2) | (BBit << 1) | CBit;
13741 ResLane.setBitVal(Bit, Imm[Idx]);
13742 }
13743 ResultElements.push_back(APValue(APSInt(ResLane, DestUnsigned)));
13744 } else {
13745 ResultElements.push_back(APValue(APSInt(ALane, DestUnsigned)));
13746 }
13747 }
13748 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13749 }
13750 case X86::BI__builtin_ia32_pternlogd128_maskz:
13751 case X86::BI__builtin_ia32_pternlogd256_maskz:
13752 case X86::BI__builtin_ia32_pternlogd512_maskz:
13753 case X86::BI__builtin_ia32_pternlogq128_maskz:
13754 case X86::BI__builtin_ia32_pternlogq256_maskz:
13755 case X86::BI__builtin_ia32_pternlogq512_maskz: {
13756 APValue AValue, BValue, CValue, ImmValue, UValue;
13757 if (!EvaluateAsRValue(Info, E->getArg(0), AValue) ||
13758 !EvaluateAsRValue(Info, E->getArg(1), BValue) ||
13759 !EvaluateAsRValue(Info, E->getArg(2), CValue) ||
13760 !EvaluateAsRValue(Info, E->getArg(3), ImmValue) ||
13761 !EvaluateAsRValue(Info, E->getArg(4), UValue))
13762 return false;
13763
13764 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
13765 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
13766 APInt Imm = ImmValue.getInt();
13767 APInt U = UValue.getInt();
13768 unsigned ResultLen = AValue.getVectorLength();
13769 SmallVector<APValue, 16> ResultElements;
13770 ResultElements.reserve(ResultLen);
13771
13772 for (unsigned EltNum = 0; EltNum < ResultLen; ++EltNum) {
13773 APInt ALane = AValue.getVectorElt(EltNum).getInt();
13774 APInt BLane = BValue.getVectorElt(EltNum).getInt();
13775 APInt CLane = CValue.getVectorElt(EltNum).getInt();
13776
13777 unsigned BitWidth = ALane.getBitWidth();
13778 APInt ResLane(BitWidth, 0);
13779
13780 if (U[EltNum]) {
13781 for (unsigned Bit = 0; Bit < BitWidth; ++Bit) {
13782 unsigned ABit = ALane[Bit];
13783 unsigned BBit = BLane[Bit];
13784 unsigned CBit = CLane[Bit];
13785
13786 unsigned Idx = (ABit << 2) | (BBit << 1) | CBit;
13787 ResLane.setBitVal(Bit, Imm[Idx]);
13788 }
13789 }
13790 ResultElements.push_back(APValue(APSInt(ResLane, DestUnsigned)));
13791 }
13792 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13793 }
13794
13795 case Builtin::BI__builtin_elementwise_clzg:
13796 case Builtin::BI__builtin_elementwise_ctzg: {
13797 APValue SourceLHS;
13798 std::optional<APValue> Fallback;
13799 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS))
13800 return false;
13801 if (E->getNumArgs() > 1) {
13802 APValue FallbackTmp;
13803 if (!EvaluateAsRValue(Info, E->getArg(1), FallbackTmp))
13804 return false;
13805 Fallback = FallbackTmp;
13806 }
13807
13808 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
13809 unsigned SourceLen = SourceLHS.getVectorLength();
13810 SmallVector<APValue, 4> ResultElements;
13811 ResultElements.reserve(SourceLen);
13812
13813 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
13814 APSInt LHS = SourceLHS.getVectorElt(EltNum).getInt();
13815 if (!LHS) {
13816 // Without a fallback, a zero element is undefined
13817 if (!Fallback) {
13818 Info.FFDiag(E, diag::note_constexpr_countzeroes_zero)
13819 << /*IsTrailing=*/(E->getBuiltinCallee() ==
13820 Builtin::BI__builtin_elementwise_ctzg);
13821 return false;
13822 }
13823 ResultElements.push_back(Fallback->getVectorElt(EltNum));
13824 continue;
13825 }
13826 switch (E->getBuiltinCallee()) {
13827 case Builtin::BI__builtin_elementwise_clzg:
13828 ResultElements.push_back(APValue(
13829 APSInt(APInt(Info.Ctx.getIntWidth(DestEltTy), LHS.countl_zero()),
13830 DestEltTy->isUnsignedIntegerOrEnumerationType())));
13831 break;
13832 case Builtin::BI__builtin_elementwise_ctzg:
13833 ResultElements.push_back(APValue(
13834 APSInt(APInt(Info.Ctx.getIntWidth(DestEltTy), LHS.countr_zero()),
13835 DestEltTy->isUnsignedIntegerOrEnumerationType())));
13836 break;
13837 }
13838 }
13839
13840 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13841 }
13842
13843 case Builtin::BI__builtin_elementwise_fma: {
13844 APValue SourceX, SourceY, SourceZ;
13845 if (!EvaluateAsRValue(Info, E->getArg(0), SourceX) ||
13846 !EvaluateAsRValue(Info, E->getArg(1), SourceY) ||
13847 !EvaluateAsRValue(Info, E->getArg(2), SourceZ))
13848 return false;
13849
13850 unsigned SourceLen = SourceX.getVectorLength();
13851 SmallVector<APValue> ResultElements;
13852 ResultElements.reserve(SourceLen);
13853 llvm::RoundingMode RM = getActiveRoundingMode(getEvalInfo(), E);
13854 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
13855 const APFloat &X = SourceX.getVectorElt(EltNum).getFloat();
13856 const APFloat &Y = SourceY.getVectorElt(EltNum).getFloat();
13857 const APFloat &Z = SourceZ.getVectorElt(EltNum).getFloat();
13858 APFloat Result(X);
13859 (void)Result.fusedMultiplyAdd(Y, Z, RM);
13860 ResultElements.push_back(APValue(Result));
13861 }
13862 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13863 }
13864
13865 case clang::X86::BI__builtin_ia32_phaddw128:
13866 case clang::X86::BI__builtin_ia32_phaddw256:
13867 case clang::X86::BI__builtin_ia32_phaddd128:
13868 case clang::X86::BI__builtin_ia32_phaddd256:
13869 case clang::X86::BI__builtin_ia32_phaddsw128:
13870 case clang::X86::BI__builtin_ia32_phaddsw256:
13871
13872 case clang::X86::BI__builtin_ia32_phsubw128:
13873 case clang::X86::BI__builtin_ia32_phsubw256:
13874 case clang::X86::BI__builtin_ia32_phsubd128:
13875 case clang::X86::BI__builtin_ia32_phsubd256:
13876 case clang::X86::BI__builtin_ia32_phsubsw128:
13877 case clang::X86::BI__builtin_ia32_phsubsw256: {
13878 APValue SourceLHS, SourceRHS;
13879 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
13880 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
13881 return false;
13882 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
13883 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
13884
13885 unsigned NumElts = SourceLHS.getVectorLength();
13886 unsigned EltBits = Info.Ctx.getIntWidth(DestEltTy);
13887 unsigned EltsPerLane = 128 / EltBits;
13888 SmallVector<APValue, 4> ResultElements;
13889 ResultElements.reserve(NumElts);
13890
13891 for (unsigned LaneStart = 0; LaneStart != NumElts;
13892 LaneStart += EltsPerLane) {
13893 for (unsigned I = 0; I != EltsPerLane; I += 2) {
13894 APSInt LHSA = SourceLHS.getVectorElt(LaneStart + I).getInt();
13895 APSInt LHSB = SourceLHS.getVectorElt(LaneStart + I + 1).getInt();
13896 switch (E->getBuiltinCallee()) {
13897 case clang::X86::BI__builtin_ia32_phaddw128:
13898 case clang::X86::BI__builtin_ia32_phaddw256:
13899 case clang::X86::BI__builtin_ia32_phaddd128:
13900 case clang::X86::BI__builtin_ia32_phaddd256: {
13901 APSInt Res(LHSA + LHSB, DestUnsigned);
13902 ResultElements.push_back(APValue(Res));
13903 break;
13904 }
13905 case clang::X86::BI__builtin_ia32_phaddsw128:
13906 case clang::X86::BI__builtin_ia32_phaddsw256: {
13907 APSInt Res(LHSA.sadd_sat(LHSB));
13908 ResultElements.push_back(APValue(Res));
13909 break;
13910 }
13911 case clang::X86::BI__builtin_ia32_phsubw128:
13912 case clang::X86::BI__builtin_ia32_phsubw256:
13913 case clang::X86::BI__builtin_ia32_phsubd128:
13914 case clang::X86::BI__builtin_ia32_phsubd256: {
13915 APSInt Res(LHSA - LHSB, DestUnsigned);
13916 ResultElements.push_back(APValue(Res));
13917 break;
13918 }
13919 case clang::X86::BI__builtin_ia32_phsubsw128:
13920 case clang::X86::BI__builtin_ia32_phsubsw256: {
13921 APSInt Res(LHSA.ssub_sat(LHSB));
13922 ResultElements.push_back(APValue(Res));
13923 break;
13924 }
13925 }
13926 }
13927 for (unsigned I = 0; I != EltsPerLane; I += 2) {
13928 APSInt RHSA = SourceRHS.getVectorElt(LaneStart + I).getInt();
13929 APSInt RHSB = SourceRHS.getVectorElt(LaneStart + I + 1).getInt();
13930 switch (E->getBuiltinCallee()) {
13931 case clang::X86::BI__builtin_ia32_phaddw128:
13932 case clang::X86::BI__builtin_ia32_phaddw256:
13933 case clang::X86::BI__builtin_ia32_phaddd128:
13934 case clang::X86::BI__builtin_ia32_phaddd256: {
13935 APSInt Res(RHSA + RHSB, DestUnsigned);
13936 ResultElements.push_back(APValue(Res));
13937 break;
13938 }
13939 case clang::X86::BI__builtin_ia32_phaddsw128:
13940 case clang::X86::BI__builtin_ia32_phaddsw256: {
13941 APSInt Res(RHSA.sadd_sat(RHSB));
13942 ResultElements.push_back(APValue(Res));
13943 break;
13944 }
13945 case clang::X86::BI__builtin_ia32_phsubw128:
13946 case clang::X86::BI__builtin_ia32_phsubw256:
13947 case clang::X86::BI__builtin_ia32_phsubd128:
13948 case clang::X86::BI__builtin_ia32_phsubd256: {
13949 APSInt Res(RHSA - RHSB, DestUnsigned);
13950 ResultElements.push_back(APValue(Res));
13951 break;
13952 }
13953 case clang::X86::BI__builtin_ia32_phsubsw128:
13954 case clang::X86::BI__builtin_ia32_phsubsw256: {
13955 APSInt Res(RHSA.ssub_sat(RHSB));
13956 ResultElements.push_back(APValue(Res));
13957 break;
13958 }
13959 }
13960 }
13961 }
13962 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13963 }
13964 case clang::X86::BI__builtin_ia32_haddpd:
13965 case clang::X86::BI__builtin_ia32_haddps:
13966 case clang::X86::BI__builtin_ia32_haddps256:
13967 case clang::X86::BI__builtin_ia32_haddpd256:
13968 case clang::X86::BI__builtin_ia32_hsubpd:
13969 case clang::X86::BI__builtin_ia32_hsubps:
13970 case clang::X86::BI__builtin_ia32_hsubps256:
13971 case clang::X86::BI__builtin_ia32_hsubpd256: {
13972 APValue SourceLHS, SourceRHS;
13973 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
13974 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
13975 return false;
13976 unsigned NumElts = SourceLHS.getVectorLength();
13977 SmallVector<APValue, 4> ResultElements;
13978 ResultElements.reserve(NumElts);
13979 llvm::RoundingMode RM = getActiveRoundingMode(getEvalInfo(), E);
13980 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
13981 unsigned EltBits = Info.Ctx.getTypeSize(DestEltTy);
13982 unsigned NumLanes = NumElts * EltBits / 128;
13983 unsigned NumElemsPerLane = NumElts / NumLanes;
13984 unsigned HalfElemsPerLane = NumElemsPerLane / 2;
13985
13986 for (unsigned L = 0; L != NumElts; L += NumElemsPerLane) {
13987 for (unsigned I = 0; I != HalfElemsPerLane; ++I) {
13988 APFloat LHSA = SourceLHS.getVectorElt(L + (2 * I) + 0).getFloat();
13989 APFloat LHSB = SourceLHS.getVectorElt(L + (2 * I) + 1).getFloat();
13990 switch (E->getBuiltinCallee()) {
13991 case clang::X86::BI__builtin_ia32_haddpd:
13992 case clang::X86::BI__builtin_ia32_haddps:
13993 case clang::X86::BI__builtin_ia32_haddps256:
13994 case clang::X86::BI__builtin_ia32_haddpd256:
13995 LHSA.add(LHSB, RM);
13996 break;
13997 case clang::X86::BI__builtin_ia32_hsubpd:
13998 case clang::X86::BI__builtin_ia32_hsubps:
13999 case clang::X86::BI__builtin_ia32_hsubps256:
14000 case clang::X86::BI__builtin_ia32_hsubpd256:
14001 LHSA.subtract(LHSB, RM);
14002 break;
14003 }
14004 ResultElements.push_back(APValue(LHSA));
14005 }
14006 for (unsigned I = 0; I != HalfElemsPerLane; ++I) {
14007 APFloat RHSA = SourceRHS.getVectorElt(L + (2 * I) + 0).getFloat();
14008 APFloat RHSB = SourceRHS.getVectorElt(L + (2 * I) + 1).getFloat();
14009 switch (E->getBuiltinCallee()) {
14010 case clang::X86::BI__builtin_ia32_haddpd:
14011 case clang::X86::BI__builtin_ia32_haddps:
14012 case clang::X86::BI__builtin_ia32_haddps256:
14013 case clang::X86::BI__builtin_ia32_haddpd256:
14014 RHSA.add(RHSB, RM);
14015 break;
14016 case clang::X86::BI__builtin_ia32_hsubpd:
14017 case clang::X86::BI__builtin_ia32_hsubps:
14018 case clang::X86::BI__builtin_ia32_hsubps256:
14019 case clang::X86::BI__builtin_ia32_hsubpd256:
14020 RHSA.subtract(RHSB, RM);
14021 break;
14022 }
14023 ResultElements.push_back(APValue(RHSA));
14024 }
14025 }
14026 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
14027 }
14028 case clang::X86::BI__builtin_ia32_addsubpd:
14029 case clang::X86::BI__builtin_ia32_addsubps:
14030 case clang::X86::BI__builtin_ia32_addsubpd256:
14031 case clang::X86::BI__builtin_ia32_addsubps256: {
14032 // Addsub: alternates between subtraction and addition
14033 // Result[i] = (i % 2 == 0) ? (a[i] - b[i]) : (a[i] + b[i])
14034 APValue SourceLHS, SourceRHS;
14035 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
14036 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
14037 return false;
14038 unsigned NumElems = SourceLHS.getVectorLength();
14039 SmallVector<APValue, 8> ResultElements;
14040 ResultElements.reserve(NumElems);
14041 llvm::RoundingMode RM = getActiveRoundingMode(getEvalInfo(), E);
14042
14043 for (unsigned I = 0; I != NumElems; ++I) {
14044 APFloat LHS = SourceLHS.getVectorElt(I).getFloat();
14045 APFloat RHS = SourceRHS.getVectorElt(I).getFloat();
14046 if (I % 2 == 0) {
14047 // Even indices: subtract
14048 LHS.subtract(RHS, RM);
14049 } else {
14050 // Odd indices: add
14051 LHS.add(RHS, RM);
14052 }
14053 ResultElements.push_back(APValue(LHS));
14054 }
14055 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
14056 }
14057 case clang::X86::BI__builtin_ia32_pclmulqdq128:
14058 case clang::X86::BI__builtin_ia32_pclmulqdq256:
14059 case clang::X86::BI__builtin_ia32_pclmulqdq512: {
14060 // PCLMULQDQ: carry-less multiplication of selected 64-bit halves
14061 // imm8 bit 0: selects lower (0) or upper (1) 64 bits of first operand
14062 // imm8 bit 4: selects lower (0) or upper (1) 64 bits of second operand
14063 APValue SourceLHS, SourceRHS;
14064 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
14065 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
14066 return false;
14067
14068 APSInt Imm8;
14069 if (!EvaluateInteger(E->getArg(2), Imm8, Info))
14070 return false;
14071
14072 // Extract bits 0 and 4 from imm8
14073 bool SelectUpperA = (Imm8 & 0x01) != 0;
14074 bool SelectUpperB = (Imm8 & 0x10) != 0;
14075
14076 unsigned NumElems = SourceLHS.getVectorLength();
14077 SmallVector<APValue, 8> ResultElements;
14078 ResultElements.reserve(NumElems);
14079 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
14080 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
14081
14082 // Process each 128-bit lane
14083 for (unsigned Lane = 0; Lane < NumElems; Lane += 2) {
14084 // Get the two 64-bit halves of the first operand
14085 APSInt A0 = SourceLHS.getVectorElt(Lane + 0).getInt();
14086 APSInt A1 = SourceLHS.getVectorElt(Lane + 1).getInt();
14087 // Get the two 64-bit halves of the second operand
14088 APSInt B0 = SourceRHS.getVectorElt(Lane + 0).getInt();
14089 APSInt B1 = SourceRHS.getVectorElt(Lane + 1).getInt();
14090
14091 // Select the appropriate 64-bit values based on imm8
14092 APInt A = SelectUpperA ? A1 : A0;
14093 APInt B = SelectUpperB ? B1 : B0;
14094
14095 // Extend both operands to 128 bits for carry-less multiplication
14096 APInt A128 = A.zext(128);
14097 APInt B128 = B.zext(128);
14098
14099 // Use APIntOps::clmul for carry-less multiplication
14100 APInt Result = llvm::APIntOps::clmul(A128, B128);
14101
14102 // Split the 128-bit result into two 64-bit halves
14103 APSInt ResultLow(Result.extractBits(64, 0), DestUnsigned);
14104 APSInt ResultHigh(Result.extractBits(64, 64), DestUnsigned);
14105
14106 ResultElements.push_back(APValue(ResultLow));
14107 ResultElements.push_back(APValue(ResultHigh));
14108 }
14109
14110 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
14111 }
14112 case Builtin::BI__builtin_elementwise_clmul:
14113 return EvaluateBinOpExpr(llvm::APIntOps::clmul);
14114 case Builtin::BI__builtin_elementwise_fshl:
14115 case Builtin::BI__builtin_elementwise_fshr: {
14116 APValue SourceHi, SourceLo, SourceShift;
14117 if (!EvaluateAsRValue(Info, E->getArg(0), SourceHi) ||
14118 !EvaluateAsRValue(Info, E->getArg(1), SourceLo) ||
14119 !EvaluateAsRValue(Info, E->getArg(2), SourceShift))
14120 return false;
14121
14122 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
14123 if (!DestEltTy->isIntegerType())
14124 return false;
14125
14126 unsigned SourceLen = SourceHi.getVectorLength();
14127 SmallVector<APValue> ResultElements;
14128 ResultElements.reserve(SourceLen);
14129 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
14130 const APSInt &Hi = SourceHi.getVectorElt(EltNum).getInt();
14131 const APSInt &Lo = SourceLo.getVectorElt(EltNum).getInt();
14132 const APSInt &Shift = SourceShift.getVectorElt(EltNum).getInt();
14133 switch (E->getBuiltinCallee()) {
14134 case Builtin::BI__builtin_elementwise_fshl:
14135 ResultElements.push_back(APValue(
14136 APSInt(llvm::APIntOps::fshl(Hi, Lo, Shift), Hi.isUnsigned())));
14137 break;
14138 case Builtin::BI__builtin_elementwise_fshr:
14139 ResultElements.push_back(APValue(
14140 APSInt(llvm::APIntOps::fshr(Hi, Lo, Shift), Hi.isUnsigned())));
14141 break;
14142 }
14143 }
14144
14145 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
14146 }
14147
14148 case X86::BI__builtin_ia32_shuf_f32x4_256:
14149 case X86::BI__builtin_ia32_shuf_i32x4_256:
14150 case X86::BI__builtin_ia32_shuf_f64x2_256:
14151 case X86::BI__builtin_ia32_shuf_i64x2_256:
14152 case X86::BI__builtin_ia32_shuf_f32x4:
14153 case X86::BI__builtin_ia32_shuf_i32x4:
14154 case X86::BI__builtin_ia32_shuf_f64x2:
14155 case X86::BI__builtin_ia32_shuf_i64x2: {
14156 APValue SourceA, SourceB;
14157 if (!EvaluateAsRValue(Info, E->getArg(0), SourceA) ||
14158 !EvaluateAsRValue(Info, E->getArg(1), SourceB))
14159 return false;
14160
14161 APSInt Imm;
14162 if (!EvaluateInteger(E->getArg(2), Imm, Info))
14163 return false;
14164
14165 // Destination and sources A, B all have the same type.
14166 unsigned NumElems = SourceA.getVectorLength();
14167 const VectorType *VT = E->getArg(0)->getType()->castAs<VectorType>();
14168 QualType ElemQT = VT->getElementType();
14169 unsigned ElemBits = Info.Ctx.getTypeSize(ElemQT);
14170 unsigned LaneBits = 128u;
14171 unsigned NumLanes = (NumElems * ElemBits) / LaneBits;
14172 unsigned NumElemsPerLane = LaneBits / ElemBits;
14173
14174 unsigned DstLen = SourceA.getVectorLength();
14175 SmallVector<APValue, 16> ResultElements;
14176 ResultElements.reserve(DstLen);
14177
14178 APValue R;
14179 if (!evalShuffleGeneric(
14180 Info, E, R,
14181 [NumLanes, NumElemsPerLane](unsigned DstIdx, unsigned ShuffleMask)
14182 -> std::pair<unsigned, int> {
14183 // DstIdx determines source. ShuffleMask selects lane in source.
14184 unsigned BitsPerElem = NumLanes / 2;
14185 unsigned IndexMask = (1u << BitsPerElem) - 1;
14186 unsigned Lane = DstIdx / NumElemsPerLane;
14187 unsigned SrcIdx = (Lane < NumLanes / 2) ? 0 : 1;
14188 unsigned BitIdx = BitsPerElem * Lane;
14189 unsigned SrcLaneIdx = (ShuffleMask >> BitIdx) & IndexMask;
14190 unsigned ElemInLane = DstIdx % NumElemsPerLane;
14191 unsigned IdxToPick = SrcLaneIdx * NumElemsPerLane + ElemInLane;
14192 return {SrcIdx, IdxToPick};
14193 }))
14194 return false;
14195 return Success(R, E);
14196 }
14197
14198 case X86::BI__builtin_ia32_vgf2p8affineinvqb_v16qi:
14199 case X86::BI__builtin_ia32_vgf2p8affineinvqb_v32qi:
14200 case X86::BI__builtin_ia32_vgf2p8affineinvqb_v64qi:
14201 case X86::BI__builtin_ia32_vgf2p8affineqb_v16qi:
14202 case X86::BI__builtin_ia32_vgf2p8affineqb_v32qi:
14203 case X86::BI__builtin_ia32_vgf2p8affineqb_v64qi: {
14204
14205 APValue X, A;
14206 APSInt Imm;
14207 if (!EvaluateAsRValue(Info, E->getArg(0), X) ||
14208 !EvaluateAsRValue(Info, E->getArg(1), A) ||
14209 !EvaluateInteger(E->getArg(2), Imm, Info))
14210 return false;
14211
14212 assert(X.isVector() && A.isVector());
14213 assert(X.getVectorLength() == A.getVectorLength());
14214
14215 bool IsInverse = false;
14216 switch (E->getBuiltinCallee()) {
14217 case X86::BI__builtin_ia32_vgf2p8affineinvqb_v16qi:
14218 case X86::BI__builtin_ia32_vgf2p8affineinvqb_v32qi:
14219 case X86::BI__builtin_ia32_vgf2p8affineinvqb_v64qi: {
14220 IsInverse = true;
14221 }
14222 }
14223
14224 unsigned NumBitsInByte = 8;
14225 unsigned NumBytesInQWord = 8;
14226 unsigned NumBitsInQWord = 64;
14227 unsigned NumBytes = A.getVectorLength();
14228 unsigned NumQWords = NumBytes / NumBytesInQWord;
14230 Result.reserve(NumBytes);
14231
14232 // computing A*X + Imm
14233 for (unsigned QWordIdx = 0; QWordIdx != NumQWords; ++QWordIdx) {
14234 // Extract the QWords from X, A
14235 APInt XQWord(NumBitsInQWord, 0);
14236 APInt AQWord(NumBitsInQWord, 0);
14237 for (unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
14238 unsigned Idx = QWordIdx * NumBytesInQWord + ByteIdx;
14239 APInt XByte = X.getVectorElt(Idx).getInt();
14240 APInt AByte = A.getVectorElt(Idx).getInt();
14241 XQWord.insertBits(XByte, ByteIdx * NumBitsInByte);
14242 AQWord.insertBits(AByte, ByteIdx * NumBitsInByte);
14243 }
14244
14245 for (unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
14246 uint8_t XByte =
14247 XQWord.lshr(ByteIdx * NumBitsInByte).getLoBits(8).getZExtValue();
14248 Result.push_back(APValue(APSInt(
14249 APInt(8, GFNIAffine(XByte, AQWord, Imm, IsInverse)), false)));
14250 }
14251 }
14252
14253 return Success(APValue(Result.data(), Result.size()), E);
14254 }
14255
14256 case X86::BI__builtin_ia32_vgf2p8mulb_v16qi:
14257 case X86::BI__builtin_ia32_vgf2p8mulb_v32qi:
14258 case X86::BI__builtin_ia32_vgf2p8mulb_v64qi: {
14259 APValue A, B;
14260 if (!EvaluateAsRValue(Info, E->getArg(0), A) ||
14261 !EvaluateAsRValue(Info, E->getArg(1), B))
14262 return false;
14263
14264 assert(A.isVector() && B.isVector());
14265 assert(A.getVectorLength() == B.getVectorLength());
14266
14267 unsigned NumBytes = A.getVectorLength();
14269 Result.reserve(NumBytes);
14270
14271 for (unsigned ByteIdx = 0; ByteIdx != NumBytes; ++ByteIdx) {
14272 uint8_t AByte = A.getVectorElt(ByteIdx).getInt().getZExtValue();
14273 uint8_t BByte = B.getVectorElt(ByteIdx).getInt().getZExtValue();
14274 Result.push_back(APValue(
14275 APSInt(APInt(8, GFNIMul(AByte, BByte)), /*IsUnsigned=*/false)));
14276 }
14277
14278 return Success(APValue(Result.data(), Result.size()), E);
14279 }
14280
14281 case X86::BI__builtin_ia32_insertf32x4_256:
14282 case X86::BI__builtin_ia32_inserti32x4_256:
14283 case X86::BI__builtin_ia32_insertf64x2_256:
14284 case X86::BI__builtin_ia32_inserti64x2_256:
14285 case X86::BI__builtin_ia32_insertf32x4:
14286 case X86::BI__builtin_ia32_inserti32x4:
14287 case X86::BI__builtin_ia32_insertf64x2_512:
14288 case X86::BI__builtin_ia32_inserti64x2_512:
14289 case X86::BI__builtin_ia32_insertf32x8:
14290 case X86::BI__builtin_ia32_inserti32x8:
14291 case X86::BI__builtin_ia32_insertf64x4:
14292 case X86::BI__builtin_ia32_inserti64x4:
14293 case X86::BI__builtin_ia32_vinsertf128_ps256:
14294 case X86::BI__builtin_ia32_vinsertf128_pd256:
14295 case X86::BI__builtin_ia32_vinsertf128_si256:
14296 case X86::BI__builtin_ia32_insert128i256: {
14297 APValue SourceDst, SourceSub;
14298 if (!EvaluateAsRValue(Info, E->getArg(0), SourceDst) ||
14299 !EvaluateAsRValue(Info, E->getArg(1), SourceSub))
14300 return false;
14301
14302 APSInt Imm;
14303 if (!EvaluateInteger(E->getArg(2), Imm, Info))
14304 return false;
14305
14306 assert(SourceDst.isVector() && SourceSub.isVector());
14307 unsigned DstLen = SourceDst.getVectorLength();
14308 unsigned SubLen = SourceSub.getVectorLength();
14309 assert(SubLen != 0 && DstLen != 0 && (DstLen % SubLen) == 0);
14310 unsigned NumLanes = DstLen / SubLen;
14311 unsigned LaneIdx = (Imm.getZExtValue() % NumLanes) * SubLen;
14312
14313 SmallVector<APValue, 16> ResultElements;
14314 ResultElements.reserve(DstLen);
14315
14316 for (unsigned EltNum = 0; EltNum < DstLen; ++EltNum) {
14317 if (EltNum >= LaneIdx && EltNum < LaneIdx + SubLen)
14318 ResultElements.push_back(SourceSub.getVectorElt(EltNum - LaneIdx));
14319 else
14320 ResultElements.push_back(SourceDst.getVectorElt(EltNum));
14321 }
14322
14323 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
14324 }
14325
14326 case clang::X86::BI__builtin_ia32_vec_set_v4hi:
14327 case clang::X86::BI__builtin_ia32_vec_set_v16qi:
14328 case clang::X86::BI__builtin_ia32_vec_set_v8hi:
14329 case clang::X86::BI__builtin_ia32_vec_set_v4si:
14330 case clang::X86::BI__builtin_ia32_vec_set_v2di:
14331 case clang::X86::BI__builtin_ia32_vec_set_v32qi:
14332 case clang::X86::BI__builtin_ia32_vec_set_v16hi:
14333 case clang::X86::BI__builtin_ia32_vec_set_v8si:
14334 case clang::X86::BI__builtin_ia32_vec_set_v4di: {
14335 APValue VecVal;
14336 APSInt Scalar, IndexAPS;
14337 if (!EvaluateVector(E->getArg(0), VecVal, Info) ||
14338 !EvaluateInteger(E->getArg(1), Scalar, Info) ||
14339 !EvaluateInteger(E->getArg(2), IndexAPS, Info))
14340 return false;
14341
14342 QualType ElemTy = E->getType()->castAs<VectorType>()->getElementType();
14343 unsigned ElemWidth = Info.Ctx.getIntWidth(ElemTy);
14344 bool ElemUnsigned = ElemTy->isUnsignedIntegerOrEnumerationType();
14345 Scalar.setIsUnsigned(ElemUnsigned);
14346 APSInt ElemAPS = Scalar.extOrTrunc(ElemWidth);
14347 APValue ElemAV(ElemAPS);
14348
14349 unsigned NumElems = VecVal.getVectorLength();
14350 unsigned Index =
14351 static_cast<unsigned>(IndexAPS.getZExtValue() & (NumElems - 1));
14352
14354 Elems.reserve(NumElems);
14355 for (unsigned ElemNum = 0; ElemNum != NumElems; ++ElemNum)
14356 Elems.push_back(ElemNum == Index ? ElemAV : VecVal.getVectorElt(ElemNum));
14357
14358 return Success(APValue(Elems.data(), NumElems), E);
14359 }
14360
14361 case X86::BI__builtin_ia32_pslldqi128_byteshift:
14362 case X86::BI__builtin_ia32_pslldqi256_byteshift:
14363 case X86::BI__builtin_ia32_pslldqi512_byteshift: {
14364 APValue R;
14365 if (!evalShuffleGeneric(
14366 Info, E, R,
14367 [](unsigned DstIdx, unsigned Shift) -> std::pair<unsigned, int> {
14368 unsigned LaneBase = (DstIdx / 16) * 16;
14369 unsigned LaneIdx = DstIdx % 16;
14370 if (LaneIdx < Shift)
14371 return std::make_pair(0, -1);
14372
14373 return std::make_pair(
14374 0, static_cast<int>(LaneBase + LaneIdx - Shift));
14375 }))
14376 return false;
14377 return Success(R, E);
14378 }
14379
14380 case X86::BI__builtin_ia32_psrldqi128_byteshift:
14381 case X86::BI__builtin_ia32_psrldqi256_byteshift:
14382 case X86::BI__builtin_ia32_psrldqi512_byteshift: {
14383 APValue R;
14384 if (!evalShuffleGeneric(
14385 Info, E, R,
14386 [](unsigned DstIdx, unsigned Shift) -> std::pair<unsigned, int> {
14387 unsigned LaneBase = (DstIdx / 16) * 16;
14388 unsigned LaneIdx = DstIdx % 16;
14389 if (LaneIdx + Shift < 16)
14390 return std::make_pair(
14391 0, static_cast<int>(LaneBase + LaneIdx + Shift));
14392
14393 return std::make_pair(0, -1);
14394 }))
14395 return false;
14396 return Success(R, E);
14397 }
14398
14399 case X86::BI__builtin_ia32_palignr128:
14400 case X86::BI__builtin_ia32_palignr256:
14401 case X86::BI__builtin_ia32_palignr512: {
14402 APValue R;
14403 if (!evalShuffleGeneric(Info, E, R, [](unsigned DstIdx, unsigned Shift) {
14404 // Default to -1 → zero-fill this destination element
14405 unsigned VecIdx = 1;
14406 int ElemIdx = -1;
14407
14408 int Lane = DstIdx / 16;
14409 int Offset = DstIdx % 16;
14410
14411 // Elements come from VecB first, then VecA after the shift boundary
14412 unsigned ShiftedIdx = Offset + (Shift & 0xFF);
14413 if (ShiftedIdx < 16) { // from VecB
14414 ElemIdx = ShiftedIdx + (Lane * 16);
14415 } else if (ShiftedIdx < 32) { // from VecA
14416 VecIdx = 0;
14417 ElemIdx = (ShiftedIdx - 16) + (Lane * 16);
14418 }
14419
14420 return std::pair<unsigned, int>{VecIdx, ElemIdx};
14421 }))
14422 return false;
14423 return Success(R, E);
14424 }
14425 case X86::BI__builtin_ia32_alignd128:
14426 case X86::BI__builtin_ia32_alignd256:
14427 case X86::BI__builtin_ia32_alignd512:
14428 case X86::BI__builtin_ia32_alignq128:
14429 case X86::BI__builtin_ia32_alignq256:
14430 case X86::BI__builtin_ia32_alignq512: {
14431 APValue R;
14432 unsigned NumElems = E->getType()->castAs<VectorType>()->getNumElements();
14433 if (!evalShuffleGeneric(Info, E, R,
14434 [NumElems](unsigned DstIdx, unsigned Shift) {
14435 unsigned Imm = Shift & 0xFF;
14436 unsigned EffectiveShift = Imm & (NumElems - 1);
14437 unsigned SourcePos = DstIdx + EffectiveShift;
14438 unsigned VecIdx = SourcePos < NumElems ? 1 : 0;
14439 unsigned ElemIdx = SourcePos & (NumElems - 1);
14440
14441 return std::pair<unsigned, int>{
14442 VecIdx, static_cast<int>(ElemIdx)};
14443 }))
14444 return false;
14445 return Success(R, E);
14446 }
14447 case X86::BI__builtin_ia32_permvarsi256:
14448 case X86::BI__builtin_ia32_permvarsf256:
14449 case X86::BI__builtin_ia32_permvardf512:
14450 case X86::BI__builtin_ia32_permvardi512:
14451 case X86::BI__builtin_ia32_permvarhi128: {
14452 APValue R;
14453 if (!evalShuffleGeneric(Info, E, R,
14454 [](unsigned DstIdx, unsigned ShuffleMask) {
14455 int Offset = ShuffleMask & 0x7;
14456 return std::pair<unsigned, int>{0, Offset};
14457 }))
14458 return false;
14459 return Success(R, E);
14460 }
14461 case X86::BI__builtin_ia32_permvarqi128:
14462 case X86::BI__builtin_ia32_permvarhi256:
14463 case X86::BI__builtin_ia32_permvarsi512:
14464 case X86::BI__builtin_ia32_permvarsf512: {
14465 APValue R;
14466 if (!evalShuffleGeneric(Info, E, R,
14467 [](unsigned DstIdx, unsigned ShuffleMask) {
14468 int Offset = ShuffleMask & 0xF;
14469 return std::pair<unsigned, int>{0, Offset};
14470 }))
14471 return false;
14472 return Success(R, E);
14473 }
14474 case X86::BI__builtin_ia32_permvardi256:
14475 case X86::BI__builtin_ia32_permvardf256: {
14476 APValue R;
14477 if (!evalShuffleGeneric(Info, E, R,
14478 [](unsigned DstIdx, unsigned ShuffleMask) {
14479 int Offset = ShuffleMask & 0x3;
14480 return std::pair<unsigned, int>{0, Offset};
14481 }))
14482 return false;
14483 return Success(R, E);
14484 }
14485 case X86::BI__builtin_ia32_permvarqi256:
14486 case X86::BI__builtin_ia32_permvarhi512: {
14487 APValue R;
14488 if (!evalShuffleGeneric(Info, E, R,
14489 [](unsigned DstIdx, unsigned ShuffleMask) {
14490 int Offset = ShuffleMask & 0x1F;
14491 return std::pair<unsigned, int>{0, Offset};
14492 }))
14493 return false;
14494 return Success(R, E);
14495 }
14496 case X86::BI__builtin_ia32_permvarqi512: {
14497 APValue R;
14498 if (!evalShuffleGeneric(Info, E, R,
14499 [](unsigned DstIdx, unsigned ShuffleMask) {
14500 int Offset = ShuffleMask & 0x3F;
14501 return std::pair<unsigned, int>{0, Offset};
14502 }))
14503 return false;
14504 return Success(R, E);
14505 }
14506 case X86::BI__builtin_ia32_vpermi2varq128:
14507 case X86::BI__builtin_ia32_vpermi2varpd128: {
14508 APValue R;
14509 if (!evalShuffleGeneric(Info, E, R,
14510 [](unsigned DstIdx, unsigned ShuffleMask) {
14511 int Offset = ShuffleMask & 0x1;
14512 unsigned SrcIdx = (ShuffleMask >> 1) & 0x1;
14513 return std::pair<unsigned, int>{SrcIdx, Offset};
14514 }))
14515 return false;
14516 return Success(R, E);
14517 }
14518 case X86::BI__builtin_ia32_vpermi2vard128:
14519 case X86::BI__builtin_ia32_vpermi2varps128:
14520 case X86::BI__builtin_ia32_vpermi2varq256:
14521 case X86::BI__builtin_ia32_vpermi2varpd256: {
14522 APValue R;
14523 if (!evalShuffleGeneric(Info, E, R,
14524 [](unsigned DstIdx, unsigned ShuffleMask) {
14525 int Offset = ShuffleMask & 0x3;
14526 unsigned SrcIdx = (ShuffleMask >> 2) & 0x1;
14527 return std::pair<unsigned, int>{SrcIdx, Offset};
14528 }))
14529 return false;
14530 return Success(R, E);
14531 }
14532 case X86::BI__builtin_ia32_vpermi2varhi128:
14533 case X86::BI__builtin_ia32_vpermi2vard256:
14534 case X86::BI__builtin_ia32_vpermi2varps256:
14535 case X86::BI__builtin_ia32_vpermi2varq512:
14536 case X86::BI__builtin_ia32_vpermi2varpd512: {
14537 APValue R;
14538 if (!evalShuffleGeneric(Info, E, R,
14539 [](unsigned DstIdx, unsigned ShuffleMask) {
14540 int Offset = ShuffleMask & 0x7;
14541 unsigned SrcIdx = (ShuffleMask >> 3) & 0x1;
14542 return std::pair<unsigned, int>{SrcIdx, Offset};
14543 }))
14544 return false;
14545 return Success(R, E);
14546 }
14547 case X86::BI__builtin_ia32_vpermi2varqi128:
14548 case X86::BI__builtin_ia32_vpermi2varhi256:
14549 case X86::BI__builtin_ia32_vpermi2vard512:
14550 case X86::BI__builtin_ia32_vpermi2varps512: {
14551 APValue R;
14552 if (!evalShuffleGeneric(Info, E, R,
14553 [](unsigned DstIdx, unsigned ShuffleMask) {
14554 int Offset = ShuffleMask & 0xF;
14555 unsigned SrcIdx = (ShuffleMask >> 4) & 0x1;
14556 return std::pair<unsigned, int>{SrcIdx, Offset};
14557 }))
14558 return false;
14559 return Success(R, E);
14560 }
14561 case X86::BI__builtin_ia32_vpermi2varqi256:
14562 case X86::BI__builtin_ia32_vpermi2varhi512: {
14563 APValue R;
14564 if (!evalShuffleGeneric(Info, E, R,
14565 [](unsigned DstIdx, unsigned ShuffleMask) {
14566 int Offset = ShuffleMask & 0x1F;
14567 unsigned SrcIdx = (ShuffleMask >> 5) & 0x1;
14568 return std::pair<unsigned, int>{SrcIdx, Offset};
14569 }))
14570 return false;
14571 return Success(R, E);
14572 }
14573 case X86::BI__builtin_ia32_vpermi2varqi512: {
14574 APValue R;
14575 if (!evalShuffleGeneric(Info, E, R,
14576 [](unsigned DstIdx, unsigned ShuffleMask) {
14577 int Offset = ShuffleMask & 0x3F;
14578 unsigned SrcIdx = (ShuffleMask >> 6) & 0x1;
14579 return std::pair<unsigned, int>{SrcIdx, Offset};
14580 }))
14581 return false;
14582 return Success(R, E);
14583 }
14584
14585 case clang::X86::BI__builtin_ia32_minps:
14586 case clang::X86::BI__builtin_ia32_minpd:
14587 case clang::X86::BI__builtin_ia32_minps256:
14588 case clang::X86::BI__builtin_ia32_minpd256:
14589 case clang::X86::BI__builtin_ia32_minps512:
14590 case clang::X86::BI__builtin_ia32_minpd512:
14591 case clang::X86::BI__builtin_ia32_minph128:
14592 case clang::X86::BI__builtin_ia32_minph256:
14593 case clang::X86::BI__builtin_ia32_minph512:
14594 return EvaluateFpBinOpExpr(
14595 [](const APFloat &A, const APFloat &B,
14596 std::optional<APSInt>) -> std::optional<APFloat> {
14597 if (A.isNaN() || A.isInfinity() || A.isDenormal() || B.isNaN() ||
14598 B.isInfinity() || B.isDenormal())
14599 return std::nullopt;
14600 if (A.isZero() && B.isZero())
14601 return B;
14602 return llvm::minimum(A, B);
14603 });
14604
14605 case clang::X86::BI__builtin_ia32_minss:
14606 case clang::X86::BI__builtin_ia32_minsd:
14607 return EvaluateFpBinOpExpr(
14608 [](const APFloat &A, const APFloat &B,
14609 std::optional<APSInt> RoundingMode) -> std::optional<APFloat> {
14610 return EvalScalarMinMaxFp(A, B, RoundingMode, /*IsMin=*/true);
14611 },
14612 /*IsScalar=*/true);
14613
14614 case clang::X86::BI__builtin_ia32_minsd_round_mask:
14615 case clang::X86::BI__builtin_ia32_minss_round_mask:
14616 case clang::X86::BI__builtin_ia32_minsh_round_mask:
14617 case clang::X86::BI__builtin_ia32_maxsd_round_mask:
14618 case clang::X86::BI__builtin_ia32_maxss_round_mask:
14619 case clang::X86::BI__builtin_ia32_maxsh_round_mask: {
14620 bool IsMin =
14621 E->getBuiltinCallee() ==
14622 clang::X86::BI__builtin_ia32_minsd_round_mask ||
14623 E->getBuiltinCallee() ==
14624 clang::X86::BI__builtin_ia32_minss_round_mask ||
14625 E->getBuiltinCallee() == clang::X86::BI__builtin_ia32_minsh_round_mask;
14626 return EvaluateScalarFpRoundMaskBinOp(
14627 [IsMin](const APFloat &A, const APFloat &B,
14628 std::optional<APSInt> RoundingMode) -> std::optional<APFloat> {
14629 return EvalScalarMinMaxFp(A, B, RoundingMode, IsMin);
14630 });
14631 }
14632
14633 case clang::X86::BI__builtin_ia32_maxps:
14634 case clang::X86::BI__builtin_ia32_maxpd:
14635 case clang::X86::BI__builtin_ia32_maxps256:
14636 case clang::X86::BI__builtin_ia32_maxpd256:
14637 case clang::X86::BI__builtin_ia32_maxps512:
14638 case clang::X86::BI__builtin_ia32_maxpd512:
14639 case clang::X86::BI__builtin_ia32_maxph128:
14640 case clang::X86::BI__builtin_ia32_maxph256:
14641 case clang::X86::BI__builtin_ia32_maxph512:
14642 return EvaluateFpBinOpExpr(
14643 [](const APFloat &A, const APFloat &B,
14644 std::optional<APSInt>) -> std::optional<APFloat> {
14645 if (A.isNaN() || A.isInfinity() || A.isDenormal() || B.isNaN() ||
14646 B.isInfinity() || B.isDenormal())
14647 return std::nullopt;
14648 if (A.isZero() && B.isZero())
14649 return B;
14650 return llvm::maximum(A, B);
14651 });
14652
14653 case clang::X86::BI__builtin_ia32_maxss:
14654 case clang::X86::BI__builtin_ia32_maxsd:
14655 return EvaluateFpBinOpExpr(
14656 [](const APFloat &A, const APFloat &B,
14657 std::optional<APSInt> RoundingMode) -> std::optional<APFloat> {
14658 return EvalScalarMinMaxFp(A, B, RoundingMode, /*IsMin=*/false);
14659 },
14660 /*IsScalar=*/true);
14661
14662 case clang::X86::BI__builtin_ia32_vcvtps2ph:
14663 case clang::X86::BI__builtin_ia32_vcvtps2ph256: {
14664 APValue SrcVec;
14665 if (!EvaluateAsRValue(Info, E->getArg(0), SrcVec))
14666 return false;
14667
14668 APSInt Imm;
14669 if (!EvaluateInteger(E->getArg(1), Imm, Info))
14670 return false;
14671
14672 const auto *SrcVTy = E->getArg(0)->getType()->castAs<VectorType>();
14673 unsigned SrcNumElems = SrcVTy->getNumElements();
14674 const auto *DstVTy = E->getType()->castAs<VectorType>();
14675 unsigned DstNumElems = DstVTy->getNumElements();
14676 QualType DstElemTy = DstVTy->getElementType();
14677
14678 const llvm::fltSemantics &HalfSem =
14679 Info.Ctx.getFloatTypeSemantics(Info.Ctx.HalfTy);
14680
14681 int ImmVal = Imm.getZExtValue();
14682 bool UseMXCSR = (ImmVal & 4) != 0;
14683 bool IsFPConstrained =
14684 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained();
14685
14686 llvm::RoundingMode RM;
14687 if (!UseMXCSR) {
14688 switch (ImmVal & 3) {
14689 case 0:
14690 RM = llvm::RoundingMode::NearestTiesToEven;
14691 break;
14692 case 1:
14693 RM = llvm::RoundingMode::TowardNegative;
14694 break;
14695 case 2:
14696 RM = llvm::RoundingMode::TowardPositive;
14697 break;
14698 case 3:
14699 RM = llvm::RoundingMode::TowardZero;
14700 break;
14701 default:
14702 llvm_unreachable("Invalid immediate rounding mode");
14703 }
14704 } else {
14705 RM = llvm::RoundingMode::NearestTiesToEven;
14706 }
14707
14708 SmallVector<APValue, 8> ResultElements;
14709 ResultElements.reserve(DstNumElems);
14710
14711 for (unsigned I = 0; I < SrcNumElems; ++I) {
14712 APFloat SrcVal = SrcVec.getVectorElt(I).getFloat();
14713
14714 bool LostInfo;
14715 APFloat::opStatus St = SrcVal.convert(HalfSem, RM, &LostInfo);
14716
14717 if (UseMXCSR && IsFPConstrained && St != APFloat::opOK) {
14718 Info.FFDiag(E, diag::note_constexpr_dynamic_rounding);
14719 return false;
14720 }
14721
14722 APSInt DstInt(SrcVal.bitcastToAPInt(),
14724 ResultElements.push_back(APValue(DstInt));
14725 }
14726
14727 if (DstNumElems > SrcNumElems) {
14728 APSInt Zero = Info.Ctx.MakeIntValue(0, DstElemTy);
14729 for (unsigned I = SrcNumElems; I < DstNumElems; ++I) {
14730 ResultElements.push_back(APValue(Zero));
14731 }
14732 }
14733
14734 return Success(ResultElements, E);
14735 }
14736 case X86::BI__builtin_ia32_vperm2f128_pd256:
14737 case X86::BI__builtin_ia32_vperm2f128_ps256:
14738 case X86::BI__builtin_ia32_vperm2f128_si256:
14739 case X86::BI__builtin_ia32_permti256: {
14740 unsigned NumElements =
14741 E->getArg(0)->getType()->getAs<VectorType>()->getNumElements();
14742 unsigned PreservedBitsCnt = NumElements >> 2;
14743 APValue R;
14744 if (!evalShuffleGeneric(
14745 Info, E, R,
14746 [PreservedBitsCnt](unsigned DstIdx, unsigned ShuffleMask) {
14747 unsigned ControlBitsCnt = DstIdx >> PreservedBitsCnt << 2;
14748 unsigned ControlBits = ShuffleMask >> ControlBitsCnt;
14749
14750 if (ControlBits & 0b1000)
14751 return std::make_pair(0u, -1);
14752
14753 unsigned SrcVecIdx = (ControlBits & 0b10) >> 1;
14754 unsigned PreservedBitsMask = (1 << PreservedBitsCnt) - 1;
14755 int SrcIdx = ((ControlBits & 0b1) << PreservedBitsCnt) |
14756 (DstIdx & PreservedBitsMask);
14757 return std::make_pair(SrcVecIdx, SrcIdx);
14758 }))
14759 return false;
14760 return Success(R, E);
14761 }
14762 }
14763}
14764
14765bool VectorExprEvaluator::VisitConvertVectorExpr(const ConvertVectorExpr *E) {
14766 APValue Source;
14767 QualType SourceVecType = E->getSrcExpr()->getType();
14768 if (!EvaluateAsRValue(Info, E->getSrcExpr(), Source))
14769 return false;
14770
14771 QualType DestTy = E->getType()->castAs<VectorType>()->getElementType();
14772 QualType SourceTy = SourceVecType->castAs<VectorType>()->getElementType();
14773
14774 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
14775
14776 auto SourceLen = Source.getVectorLength();
14777 SmallVector<APValue, 4> ResultElements;
14778 ResultElements.reserve(SourceLen);
14779 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
14780 APValue Elt;
14781 if (!handleVectorElementCast(Info, FPO, E, SourceTy, DestTy,
14782 Source.getVectorElt(EltNum), Elt))
14783 return false;
14784 ResultElements.push_back(std::move(Elt));
14785 }
14786
14787 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
14788}
14789
14790static bool handleVectorShuffle(EvalInfo &Info, const ShuffleVectorExpr *E,
14791 QualType ElemType, APValue const &VecVal1,
14792 APValue const &VecVal2, unsigned EltNum,
14793 APValue &Result) {
14794 unsigned const TotalElementsInInputVector1 = VecVal1.getVectorLength();
14795 unsigned const TotalElementsInInputVector2 = VecVal2.getVectorLength();
14796
14797 APSInt IndexVal = E->getShuffleMaskIdx(EltNum);
14798 int64_t index = IndexVal.getExtValue();
14799 // The spec says that -1 should be treated as undef for optimizations,
14800 // but in constexpr we'd have to produce an APValue::Indeterminate,
14801 // which is prohibited from being a top-level constant value. Emit a
14802 // diagnostic instead.
14803 if (index == -1) {
14804 Info.FFDiag(
14805 E, diag::err_shufflevector_minus_one_is_undefined_behavior_constexpr)
14806 << EltNum;
14807 return false;
14808 }
14809
14810 if (index < 0 ||
14811 index >= TotalElementsInInputVector1 + TotalElementsInInputVector2)
14812 llvm_unreachable("Out of bounds shuffle index");
14813
14814 if (index >= TotalElementsInInputVector1)
14815 Result = VecVal2.getVectorElt(index - TotalElementsInInputVector1);
14816 else
14817 Result = VecVal1.getVectorElt(index);
14818 return true;
14819}
14820
14821bool VectorExprEvaluator::VisitShuffleVectorExpr(const ShuffleVectorExpr *E) {
14822 // FIXME: Unary shuffle with mask not currently supported.
14823 if (E->getNumSubExprs() == 2)
14824 return Error(E);
14825 APValue VecVal1;
14826 const Expr *Vec1 = E->getExpr(0);
14827 if (!EvaluateAsRValue(Info, Vec1, VecVal1))
14828 return false;
14829 APValue VecVal2;
14830 const Expr *Vec2 = E->getExpr(1);
14831 if (!EvaluateAsRValue(Info, Vec2, VecVal2))
14832 return false;
14833
14834 VectorType const *DestVecTy = E->getType()->castAs<VectorType>();
14835 QualType DestElTy = DestVecTy->getElementType();
14836
14837 auto TotalElementsInOutputVector = DestVecTy->getNumElements();
14838
14839 SmallVector<APValue, 4> ResultElements;
14840 ResultElements.reserve(TotalElementsInOutputVector);
14841 for (unsigned EltNum = 0; EltNum < TotalElementsInOutputVector; ++EltNum) {
14842 APValue Elt;
14843 if (!handleVectorShuffle(Info, E, DestElTy, VecVal1, VecVal2, EltNum, Elt))
14844 return false;
14845 ResultElements.push_back(std::move(Elt));
14846 }
14847
14848 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
14849}
14850
14851//===----------------------------------------------------------------------===//
14852// Matrix Evaluation
14853//===----------------------------------------------------------------------===//
14854
14855namespace {
14856class MatrixExprEvaluator : public ExprEvaluatorBase<MatrixExprEvaluator> {
14857 APValue &Result;
14858
14859public:
14860 MatrixExprEvaluator(EvalInfo &Info, APValue &Result)
14861 : ExprEvaluatorBaseTy(Info), Result(Result) {}
14862
14863 bool Success(ArrayRef<APValue> M, const Expr *E) {
14864 auto *CMTy = E->getType()->castAs<ConstantMatrixType>();
14865 assert(M.size() == CMTy->getNumElementsFlattened());
14866 // FIXME: remove this APValue copy.
14867 Result = APValue(M.data(), CMTy->getNumRows(), CMTy->getNumColumns());
14868 return true;
14869 }
14870 bool Success(const APValue &M, const Expr *E) {
14871 assert(M.isMatrix() && "expected matrix");
14872 Result = M;
14873 return true;
14874 }
14875
14876 bool VisitCastExpr(const CastExpr *E);
14877 bool VisitInitListExpr(const InitListExpr *E);
14878};
14879} // end anonymous namespace
14880
14881static bool EvaluateMatrix(const Expr *E, APValue &Result, EvalInfo &Info) {
14882 assert(E->isPRValue() && E->getType()->isConstantMatrixType() &&
14883 "not a matrix prvalue");
14884 return MatrixExprEvaluator(Info, Result).Visit(E);
14885}
14886
14887bool MatrixExprEvaluator::VisitCastExpr(const CastExpr *E) {
14888 const auto *MT = E->getType()->castAs<ConstantMatrixType>();
14889 unsigned NumRows = MT->getNumRows();
14890 unsigned NumCols = MT->getNumColumns();
14891 unsigned NElts = NumRows * NumCols;
14892 QualType EltTy = MT->getElementType();
14893 const Expr *SE = E->getSubExpr();
14894
14895 switch (E->getCastKind()) {
14896 case CK_HLSLAggregateSplatCast: {
14897 APValue Val;
14898 QualType ValTy;
14899
14900 if (!hlslAggSplatHelper(Info, SE, Val, ValTy))
14901 return false;
14902
14903 APValue CastedVal;
14904 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
14905 if (!handleScalarCast(Info, FPO, E, ValTy, EltTy, Val, CastedVal))
14906 return false;
14907
14908 SmallVector<APValue, 16> SplatEls(NElts, CastedVal);
14909 return Success(SplatEls, E);
14910 }
14911 case CK_HLSLElementwiseCast: {
14912 SmallVector<APValue> SrcVals;
14913 SmallVector<QualType> SrcTypes;
14914
14915 if (!hlslElementwiseCastHelper(Info, SE, E->getType(), SrcVals, SrcTypes))
14916 return false;
14917
14918 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
14919 SmallVector<QualType, 16> DestTypes(NElts, EltTy);
14920 SmallVector<APValue, 16> ResultEls(NElts);
14921 if (!handleElementwiseCast(Info, E, FPO, SrcVals, SrcTypes, DestTypes,
14922 ResultEls))
14923 return false;
14924 return Success(ResultEls, E);
14925 }
14926 default:
14927 return ExprEvaluatorBaseTy::VisitCastExpr(E);
14928 }
14929}
14930
14931bool MatrixExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
14932 const auto *MT = E->getType()->castAs<ConstantMatrixType>();
14933 QualType EltTy = MT->getElementType();
14934
14935 assert(E->getNumInits() == MT->getNumElementsFlattened() &&
14936 "Expected number of elements in initializer list to match the number "
14937 "of matrix elements");
14938
14939 SmallVector<APValue, 16> Elements;
14940 Elements.reserve(MT->getNumElementsFlattened());
14941
14942 // The following loop assumes the elements of the matrix InitListExpr are in
14943 // row-major order, which matches the row-major ordering assumption of the
14944 // matrix APValue.
14945 for (unsigned I = 0, N = MT->getNumElementsFlattened(); I < N; ++I) {
14946 if (EltTy->isIntegerType()) {
14947 llvm::APSInt IntVal;
14948 if (!EvaluateInteger(E->getInit(I), IntVal, Info))
14949 return false;
14950 Elements.push_back(APValue(IntVal));
14951 } else {
14952 llvm::APFloat FloatVal(0.0);
14953 if (!EvaluateFloat(E->getInit(I), FloatVal, Info))
14954 return false;
14955 Elements.push_back(APValue(FloatVal));
14956 }
14957 }
14958
14959 return Success(Elements, E);
14960}
14961
14962//===----------------------------------------------------------------------===//
14963// Array Evaluation
14964//===----------------------------------------------------------------------===//
14965
14966namespace {
14967 class ArrayExprEvaluator
14968 : public ExprEvaluatorBase<ArrayExprEvaluator> {
14969 const LValue &This;
14970 APValue &Result;
14971 public:
14972
14973 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
14974 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
14975
14976 bool Success(const APValue &V, const Expr *E) {
14977 assert(V.isArray() && "expected array");
14978 Result = V;
14979 return true;
14980 }
14981
14982 bool ZeroInitialization(const Expr *E) {
14983 const ConstantArrayType *CAT =
14984 Info.Ctx.getAsConstantArrayType(E->getType());
14985 if (!CAT) {
14986 if (E->getType()->isIncompleteArrayType()) {
14987 // We can be asked to zero-initialize a flexible array member; this
14988 // is represented as an ImplicitValueInitExpr of incomplete array
14989 // type. In this case, the array has zero elements.
14990 Result = APValue(APValue::UninitArray(), 0, 0);
14991 return true;
14992 }
14993 // FIXME: We could handle VLAs here.
14994 return Error(E);
14995 }
14996
14997 Result = APValue(APValue::UninitArray(), 0, CAT->getZExtSize());
14998 if (!Result.hasArrayFiller())
14999 return true;
15000
15001 // Zero-initialize all elements.
15002 LValue Subobject = This;
15003 Subobject.addArray(Info, E, CAT);
15004 ImplicitValueInitExpr VIE(CAT->getElementType());
15005 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
15006 }
15007
15008 bool VisitCallExpr(const CallExpr *E) {
15009 return handleCallExpr(E, Result, &This);
15010 }
15011 bool VisitCastExpr(const CastExpr *E);
15012 bool VisitInitListExpr(const InitListExpr *E,
15013 QualType AllocType = QualType());
15014 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
15015 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
15016 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
15017 const LValue &Subobject,
15018 APValue *Value, QualType Type);
15019 bool VisitStringLiteral(const StringLiteral *E,
15020 QualType AllocType = QualType()) {
15021 expandStringLiteral(Info, E, Result, AllocType);
15022 return true;
15023 }
15024 bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E);
15025 bool VisitCXXParenListOrInitListExpr(const Expr *ExprToVisit,
15026 ArrayRef<Expr *> Args,
15027 const Expr *ArrayFiller,
15028 QualType AllocType = QualType());
15029 };
15030} // end anonymous namespace
15031
15032static bool EvaluateArray(const Expr *E, const LValue &This,
15033 APValue &Result, EvalInfo &Info) {
15034 assert(!E->isValueDependent());
15035 assert(E->isPRValue() && E->getType()->isArrayType() &&
15036 "not an array prvalue");
15037 return ArrayExprEvaluator(Info, This, Result).Visit(E);
15038}
15039
15040static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
15041 APValue &Result, const InitListExpr *ILE,
15042 QualType AllocType) {
15043 assert(!ILE->isValueDependent());
15044 assert(ILE->isPRValue() && ILE->getType()->isArrayType() &&
15045 "not an array prvalue");
15046 return ArrayExprEvaluator(Info, This, Result)
15047 .VisitInitListExpr(ILE, AllocType);
15048}
15049
15050static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
15051 APValue &Result,
15052 const CXXConstructExpr *CCE,
15053 QualType AllocType) {
15054 assert(!CCE->isValueDependent());
15055 assert(CCE->isPRValue() && CCE->getType()->isArrayType() &&
15056 "not an array prvalue");
15057 return ArrayExprEvaluator(Info, This, Result)
15058 .VisitCXXConstructExpr(CCE, This, &Result, AllocType);
15059}
15060
15061// Return true iff the given array filler may depend on the element index.
15062static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
15063 // For now, just allow non-class value-initialization and initialization
15064 // lists comprised of them.
15065 if (isa<ImplicitValueInitExpr>(FillerExpr))
15066 return false;
15067 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
15068 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
15069 if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
15070 return true;
15071 }
15072
15073 if (ILE->hasArrayFiller() &&
15074 MaybeElementDependentArrayFiller(ILE->getArrayFiller()))
15075 return true;
15076
15077 return false;
15078 }
15079 return true;
15080}
15081
15082bool ArrayExprEvaluator::VisitCastExpr(const CastExpr *E) {
15083 const Expr *SE = E->getSubExpr();
15084
15085 switch (E->getCastKind()) {
15086 default:
15087 return ExprEvaluatorBaseTy::VisitCastExpr(E);
15088 case CK_HLSLAggregateSplatCast: {
15089 APValue Val;
15090 QualType ValTy;
15091
15092 if (!hlslAggSplatHelper(Info, SE, Val, ValTy))
15093 return false;
15094
15095 unsigned NEls = elementwiseSize(Info, E->getType());
15096
15097 SmallVector<APValue> SplatEls(NEls, Val);
15098 SmallVector<QualType> SplatType(NEls, ValTy);
15099
15100 // cast the elements
15101 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
15102 if (!constructAggregate(Info, FPO, E, Result, E->getType(), SplatEls,
15103 SplatType))
15104 return false;
15105
15106 return true;
15107 }
15108 case CK_HLSLElementwiseCast: {
15109 SmallVector<APValue> SrcEls;
15110 SmallVector<QualType> SrcTypes;
15111
15112 if (!hlslElementwiseCastHelper(Info, SE, E->getType(), SrcEls, SrcTypes))
15113 return false;
15114
15115 // cast the elements
15116 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
15117 if (!constructAggregate(Info, FPO, E, Result, E->getType(), SrcEls,
15118 SrcTypes))
15119 return false;
15120 return true;
15121 }
15122 }
15123}
15124
15125bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E,
15126 QualType AllocType) {
15127 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
15128 AllocType.isNull() ? E->getType() : AllocType);
15129 if (!CAT)
15130 return Error(E);
15131
15132 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
15133 // an appropriately-typed string literal enclosed in braces.
15134 if (E->isStringLiteralInit()) {
15135 auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParenImpCasts());
15136 // FIXME: Support ObjCEncodeExpr here once we support it in
15137 // ArrayExprEvaluator generally.
15138 if (!SL)
15139 return Error(E);
15140 return VisitStringLiteral(SL, AllocType);
15141 }
15142 // Any other transparent list init will need proper handling of the
15143 // AllocType; we can't just recurse to the inner initializer.
15144 assert(!E->isTransparent() &&
15145 "transparent array list initialization is not string literal init?");
15146
15147 return VisitCXXParenListOrInitListExpr(E, E->inits(), E->getArrayFiller(),
15148 AllocType);
15149}
15150
15151bool ArrayExprEvaluator::VisitCXXParenListOrInitListExpr(
15152 const Expr *ExprToVisit, ArrayRef<Expr *> Args, const Expr *ArrayFiller,
15153 QualType AllocType) {
15154 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
15155 AllocType.isNull() ? ExprToVisit->getType() : AllocType);
15156
15157 bool Success = true;
15158
15159 unsigned NumEltsToInit = Args.size();
15160 unsigned NumElts = CAT->getZExtSize();
15161
15162 // If the initializer might depend on the array index, run it for each
15163 // array element.
15164 if (NumEltsToInit != NumElts &&
15165 MaybeElementDependentArrayFiller(ArrayFiller)) {
15166 NumEltsToInit = NumElts;
15167 } else {
15168 // Add additional elements represented by EmbedExpr.
15169 for (auto *Init : Args) {
15170 if (auto *EmbedS = dyn_cast<EmbedExpr>(Init->IgnoreParenImpCasts()))
15171 NumEltsToInit += EmbedS->getDataElementCount() - 1;
15172 }
15173 // If we have extra elements in the list, they will be discarded.
15174 if (NumEltsToInit > NumElts)
15175 NumEltsToInit = NumElts;
15176 // If we're overwriting memory which already has an object, make sure we
15177 // don't reduce the number of non-filler elements. (It's possible to
15178 // optimize this in some cases, but the logic gets really complicated.)
15179 if (Result.hasValue() && NumEltsToInit < Result.getArrayInitializedElts())
15180 NumEltsToInit = Result.getArrayInitializedElts();
15181 }
15182
15183 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
15184 << NumEltsToInit << ".\n");
15185
15186 if (!Result.hasValue()) {
15187 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
15188 } else if (Result.getArrayInitializedElts() != NumEltsToInit) {
15189 // Number of inititalized elts changed. Recreate the APValue, and copy over
15190 // the relevant elements. (This is essentially just fixing the internal
15191 // representation of the value, because it's tied to the number of
15192 // non-filler elements.)
15193 //
15194 // This should be hit rarely, but there are some edge cases:
15195 //
15196 // - The array could be zero-initialized.
15197 // - There could be a DesignatedInitListExpr.
15198 // - operator new[] can be used to start the lifetime early.
15199 APValue NewResult = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
15200 // First copy existing elements.
15201 unsigned NumOldElts = Result.getArrayInitializedElts();
15202 for (unsigned I = 0; I < NumOldElts; ++I) {
15203 NewResult.getArrayInitializedElt(I) =
15204 std::move(Result.getArrayInitializedElt(I));
15205 }
15206 // Then copy the array filler over the remaining elements.
15207 for (unsigned I = Result.getArrayInitializedElts(); I < NumEltsToInit; ++I)
15209 if (NewResult.hasArrayFiller() && Result.hasArrayFiller())
15210 NewResult.getArrayFiller() = Result.getArrayFiller();
15211 Result = std::move(NewResult);
15212 }
15213
15214 LValue Subobject = This;
15215 Subobject.addArray(Info, ExprToVisit, CAT);
15216 auto Eval = [&](const Expr *Init, unsigned ArrayIndex) {
15217 if (Init->isValueDependent())
15218 return EvaluateDependentExpr(Init, Info);
15219
15220 // If this is a child of a DesignatedInitUpdateExpr, skip elements which
15221 // aren't supposed to be modified.
15222 if (isa<NoInitExpr>(Init))
15223 return true;
15224
15225 if (!EvaluateInPlace(Result.getArrayInitializedElt(ArrayIndex), Info,
15226 Subobject, Init) ||
15227 !HandleLValueArrayAdjustment(Info, Init, Subobject,
15228 CAT->getElementType(), 1)) {
15229 if (!Info.noteFailure())
15230 return false;
15231 Success = false;
15232 }
15233 return true;
15234 };
15235 unsigned ArrayIndex = 0;
15236 QualType DestTy = CAT->getElementType();
15237 APSInt Value(Info.Ctx.getTypeSize(DestTy), DestTy->isUnsignedIntegerType());
15238 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
15239 const Expr *Init = Index < Args.size() ? Args[Index] : ArrayFiller;
15240 if (ArrayIndex >= NumEltsToInit)
15241 break;
15242 if (auto *EmbedS = dyn_cast<EmbedExpr>(Init->IgnoreParenImpCasts())) {
15243 StringLiteral *SL = EmbedS->getDataStringLiteral();
15244 for (unsigned I = EmbedS->getStartingElementPos(),
15245 N = EmbedS->getDataElementCount();
15246 I != EmbedS->getStartingElementPos() + N; ++I) {
15247 Value = SL->getCodeUnit(I);
15248 if (DestTy->isIntegerType()) {
15249 Result.getArrayInitializedElt(ArrayIndex) = APValue(Value);
15250 } else {
15251 assert(DestTy->isFloatingType() && "unexpected type");
15252 const FPOptions FPO =
15253 Init->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
15254 APFloat FValue(0.0);
15255 if (!HandleIntToFloatCast(Info, Init, FPO, EmbedS->getType(), Value,
15256 DestTy, FValue))
15257 return false;
15258 Result.getArrayInitializedElt(ArrayIndex) = APValue(FValue);
15259 }
15260 ArrayIndex++;
15261 }
15262 } else {
15263 if (!Eval(Init, ArrayIndex))
15264 return false;
15265 ++ArrayIndex;
15266 }
15267 }
15268
15269 if (!Result.hasArrayFiller())
15270 return Success;
15271
15272 // If we get here, we have a trivial filler, which we can just evaluate
15273 // once and splat over the rest of the array elements.
15274 assert(ArrayFiller && "no array filler for incomplete init list");
15275 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
15276 ArrayFiller) &&
15277 Success;
15278}
15279
15280bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
15281 LValue CommonLV;
15282 if (E->getCommonExpr() &&
15283 !Evaluate(Info.CurrentCall->createTemporary(
15284 E->getCommonExpr(),
15285 getStorageType(Info.Ctx, E->getCommonExpr()),
15286 ScopeKind::FullExpression, CommonLV),
15287 Info, E->getCommonExpr()->getSourceExpr()))
15288 return false;
15289
15291
15292 uint64_t Elements = CAT->getZExtSize();
15293 Result = APValue(APValue::UninitArray(), Elements, Elements);
15294
15295 LValue Subobject = This;
15296 Subobject.addArray(Info, E, CAT);
15297
15298 bool Success = true;
15299 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
15300 // C++ [class.temporary]/5
15301 // There are four contexts in which temporaries are destroyed at a different
15302 // point than the end of the full-expression. [...] The second context is
15303 // when a copy constructor is called to copy an element of an array while
15304 // the entire array is copied [...]. In either case, if the constructor has
15305 // one or more default arguments, the destruction of every temporary created
15306 // in a default argument is sequenced before the construction of the next
15307 // array element, if any.
15308 FullExpressionRAII Scope(Info);
15309
15310 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
15311 Info, Subobject, E->getSubExpr()) ||
15312 !HandleLValueArrayAdjustment(Info, E, Subobject,
15313 CAT->getElementType(), 1)) {
15314 if (!Info.noteFailure())
15315 return false;
15316 Success = false;
15317 }
15318
15319 // Make sure we run the destructors too.
15320 Scope.destroy();
15321 }
15322
15323 return Success;
15324}
15325
15326bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
15327 return VisitCXXConstructExpr(E, This, &Result, E->getType());
15328}
15329
15330bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
15331 const LValue &Subobject,
15332 APValue *Value,
15333 QualType Type) {
15334 bool HadZeroInit = Value->hasValue();
15335
15336 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
15337 unsigned FinalSize = CAT->getZExtSize();
15338
15339 // Preserve the array filler if we had prior zero-initialization.
15340 APValue Filler =
15341 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
15342 : APValue();
15343
15344 *Value = APValue(APValue::UninitArray(), 0, FinalSize);
15345 if (FinalSize == 0)
15346 return true;
15347
15348 bool HasTrivialConstructor = CheckTrivialDefaultConstructor(
15349 Info, E->getExprLoc(), E->getConstructor(),
15351 LValue ArrayElt = Subobject;
15352 ArrayElt.addArray(Info, E, CAT);
15353 // We do the whole initialization in two passes, first for just one element,
15354 // then for the whole array. It's possible we may find out we can't do const
15355 // init in the first pass, in which case we avoid allocating a potentially
15356 // large array. We don't do more passes because expanding array requires
15357 // copying the data, which is wasteful.
15358 for (const unsigned N : {1u, FinalSize}) {
15359 unsigned OldElts = Value->getArrayInitializedElts();
15360 if (OldElts == N)
15361 break;
15362
15363 // Expand the array to appropriate size.
15364 APValue NewValue(APValue::UninitArray(), N, FinalSize);
15365 for (unsigned I = 0; I < OldElts; ++I)
15366 NewValue.getArrayInitializedElt(I).swap(
15367 Value->getArrayInitializedElt(I));
15368 Value->swap(NewValue);
15369
15370 if (HadZeroInit)
15371 for (unsigned I = OldElts; I < N; ++I)
15372 Value->getArrayInitializedElt(I) = Filler;
15373
15374 if (HasTrivialConstructor && N == FinalSize && FinalSize != 1) {
15375 // If we have a trivial constructor, only evaluate it once and copy
15376 // the result into all the array elements.
15377 APValue &FirstResult = Value->getArrayInitializedElt(0);
15378 for (unsigned I = OldElts; I < FinalSize; ++I)
15379 Value->getArrayInitializedElt(I) = FirstResult;
15380 } else {
15381 for (unsigned I = OldElts; I < N; ++I) {
15382 if (!VisitCXXConstructExpr(E, ArrayElt,
15383 &Value->getArrayInitializedElt(I),
15384 CAT->getElementType()) ||
15385 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
15386 CAT->getElementType(), 1))
15387 return false;
15388 // When checking for const initilization any diagnostic is considered
15389 // an error.
15390 if (Info.EvalStatus.Diag && !Info.EvalStatus.Diag->empty() &&
15391 !Info.keepEvaluatingAfterFailure())
15392 return false;
15393 }
15394 }
15395 }
15396
15397 return true;
15398 }
15399
15400 if (!Type->isRecordType())
15401 return Error(E);
15402
15403 return RecordExprEvaluator(Info, Subobject, *Value)
15404 .VisitCXXConstructExpr(E, Type);
15405}
15406
15407bool ArrayExprEvaluator::VisitCXXParenListInitExpr(
15408 const CXXParenListInitExpr *E) {
15409 assert(E->getType()->isConstantArrayType() &&
15410 "Expression result is not a constant array type");
15411
15412 return VisitCXXParenListOrInitListExpr(E, E->getInitExprs(),
15413 E->getArrayFiller());
15414}
15415
15416//===----------------------------------------------------------------------===//
15417// Integer Evaluation
15418//
15419// As a GNU extension, we support casting pointers to sufficiently-wide integer
15420// types and back in constant folding. Integer values are thus represented
15421// either as an integer-valued APValue, or as an lvalue-valued APValue.
15422//===----------------------------------------------------------------------===//
15423
15424namespace {
15425class IntExprEvaluator
15426 : public ExprEvaluatorBase<IntExprEvaluator> {
15427 APValue &Result;
15428public:
15429 IntExprEvaluator(EvalInfo &info, APValue &result)
15430 : ExprEvaluatorBaseTy(info), Result(result) {}
15431
15432 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
15433 assert(E->getType()->isIntegralOrEnumerationType() &&
15434 "Invalid evaluation result.");
15435 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
15436 "Invalid evaluation result.");
15437 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
15438 "Invalid evaluation result.");
15439 Result = APValue(SI);
15440 return true;
15441 }
15442 bool Success(const llvm::APSInt &SI, const Expr *E) {
15443 return Success(SI, E, Result);
15444 }
15445
15446 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
15447 assert(E->getType()->isIntegralOrEnumerationType() &&
15448 "Invalid evaluation result.");
15449 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
15450 "Invalid evaluation result.");
15451 Result = APValue(APSInt(I));
15452 Result.getInt().setIsUnsigned(
15454 return true;
15455 }
15456 bool Success(const llvm::APInt &I, const Expr *E) {
15457 return Success(I, E, Result);
15458 }
15459
15460 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
15461 assert(E->getType()->isIntegralOrEnumerationType() &&
15462 "Invalid evaluation result.");
15463 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
15464 return true;
15465 }
15466 bool Success(uint64_t Value, const Expr *E) {
15467 return Success(Value, E, Result);
15468 }
15469
15470 bool Success(CharUnits Size, const Expr *E) {
15471 return Success(Size.getQuantity(), E);
15472 }
15473
15474 bool Success(const APValue &V, const Expr *E) {
15475 // C++23 [expr.const]p8 If we have a variable that is unknown reference or
15476 // pointer allow further evaluation of the value.
15477 if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate() ||
15478 V.allowConstexprUnknown()) {
15479 Result = V;
15480 return true;
15481 }
15482 return Success(V.getInt(), E);
15483 }
15484
15485 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
15486
15487 friend std::optional<bool> EvaluateBuiltinIsWithinLifetime(IntExprEvaluator &,
15488 const CallExpr *);
15489
15490 //===--------------------------------------------------------------------===//
15491 // Visitor Methods
15492 //===--------------------------------------------------------------------===//
15493
15494 bool VisitIntegerLiteral(const IntegerLiteral *E) {
15495 return Success(E->getValue(), E);
15496 }
15497 bool VisitCharacterLiteral(const CharacterLiteral *E) {
15498 return Success(E->getValue(), E);
15499 }
15500
15501 bool CheckReferencedDecl(const Expr *E, const Decl *D);
15502 bool VisitDeclRefExpr(const DeclRefExpr *E) {
15503 if (CheckReferencedDecl(E, E->getDecl()))
15504 return true;
15505
15506 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
15507 }
15508 bool VisitMemberExpr(const MemberExpr *E) {
15509 if (CheckReferencedDecl(E, E->getMemberDecl())) {
15510 VisitIgnoredBaseExpression(E->getBase());
15511 return true;
15512 }
15513
15514 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
15515 }
15516
15517 bool VisitCallExpr(const CallExpr *E);
15518 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
15519 bool VisitBinaryOperator(const BinaryOperator *E);
15520 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
15521 bool VisitUnaryOperator(const UnaryOperator *E);
15522
15523 bool VisitCastExpr(const CastExpr* E);
15524 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
15525
15526 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
15527 return Success(E->getValue(), E);
15528 }
15529
15530 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
15531 return Success(E->getValue(), E);
15532 }
15533
15534 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
15535 if (Info.ArrayInitIndex == uint64_t(-1)) {
15536 // We were asked to evaluate this subexpression independent of the
15537 // enclosing ArrayInitLoopExpr. We can't do that.
15538 Info.FFDiag(E);
15539 return false;
15540 }
15541 return Success(Info.ArrayInitIndex, E);
15542 }
15543
15544 // Note, GNU defines __null as an integer, not a pointer.
15545 bool VisitGNUNullExpr(const GNUNullExpr *E) {
15546 return ZeroInitialization(E);
15547 }
15548
15549 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
15550 if (E->isStoredAsBoolean())
15551 return Success(E->getBoolValue(), E);
15552 if (E->getAPValue().isAbsent())
15553 return false;
15554 assert(E->getAPValue().isInt() && "APValue type not supported");
15555 return Success(E->getAPValue().getInt(), E);
15556 }
15557
15558 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
15559 return Success(E->getValue(), E);
15560 }
15561
15562 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
15563 return Success(E->getValue(), E);
15564 }
15565
15566 bool VisitOpenACCAsteriskSizeExpr(const OpenACCAsteriskSizeExpr *E) {
15567 // This should not be evaluated during constant expr evaluation, as it
15568 // should always be in an unevaluated context (the args list of a 'gang' or
15569 // 'tile' clause).
15570 return Error(E);
15571 }
15572
15573 bool VisitUnaryReal(const UnaryOperator *E);
15574 bool VisitUnaryImag(const UnaryOperator *E);
15575
15576 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
15577 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
15578 bool VisitSourceLocExpr(const SourceLocExpr *E);
15579 bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E);
15580 bool VisitRequiresExpr(const RequiresExpr *E);
15581 // FIXME: Missing: array subscript of vector, member of vector
15582};
15583
15584class FixedPointExprEvaluator
15585 : public ExprEvaluatorBase<FixedPointExprEvaluator> {
15586 APValue &Result;
15587
15588 public:
15589 FixedPointExprEvaluator(EvalInfo &info, APValue &result)
15590 : ExprEvaluatorBaseTy(info), Result(result) {}
15591
15592 bool Success(const llvm::APInt &I, const Expr *E) {
15593 return Success(
15594 APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
15595 }
15596
15597 bool Success(uint64_t Value, const Expr *E) {
15598 return Success(
15599 APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
15600 }
15601
15602 bool Success(const APValue &V, const Expr *E) {
15603 return Success(V.getFixedPoint(), E);
15604 }
15605
15606 bool Success(const APFixedPoint &V, const Expr *E) {
15607 assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
15608 assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
15609 "Invalid evaluation result.");
15610 Result = APValue(V);
15611 return true;
15612 }
15613
15614 bool ZeroInitialization(const Expr *E) {
15615 return Success(0, E);
15616 }
15617
15618 //===--------------------------------------------------------------------===//
15619 // Visitor Methods
15620 //===--------------------------------------------------------------------===//
15621
15622 bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
15623 return Success(E->getValue(), E);
15624 }
15625
15626 bool VisitCastExpr(const CastExpr *E);
15627 bool VisitUnaryOperator(const UnaryOperator *E);
15628 bool VisitBinaryOperator(const BinaryOperator *E);
15629};
15630} // end anonymous namespace
15631
15632/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
15633/// produce either the integer value or a pointer.
15634///
15635/// GCC has a heinous extension which folds casts between pointer types and
15636/// pointer-sized integral types. We support this by allowing the evaluation of
15637/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
15638/// Some simple arithmetic on such values is supported (they are treated much
15639/// like char*).
15641 EvalInfo &Info) {
15642 assert(!E->isValueDependent());
15643 assert(E->isPRValue() && E->getType()->isIntegralOrEnumerationType());
15644 return IntExprEvaluator(Info, Result).Visit(E);
15645}
15646
15647static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
15648 assert(!E->isValueDependent());
15649 APValue Val;
15650 if (!EvaluateIntegerOrLValue(E, Val, Info))
15651 return false;
15652 if (!Val.isInt()) {
15653 // FIXME: It would be better to produce the diagnostic for casting
15654 // a pointer to an integer.
15655 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
15656 return false;
15657 }
15658 Result = Val.getInt();
15659 return true;
15660}
15661
15662bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
15664 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
15665 return Success(Evaluated, E);
15666}
15667
15668static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
15669 EvalInfo &Info) {
15670 assert(!E->isValueDependent());
15671 if (E->getType()->isFixedPointType()) {
15672 APValue Val;
15673 if (!FixedPointExprEvaluator(Info, Val).Visit(E))
15674 return false;
15675 if (!Val.isFixedPoint())
15676 return false;
15677
15678 Result = Val.getFixedPoint();
15679 return true;
15680 }
15681 return false;
15682}
15683
15684static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
15685 EvalInfo &Info) {
15686 assert(!E->isValueDependent());
15687 if (E->getType()->isIntegerType()) {
15688 auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
15689 APSInt Val;
15690 if (!EvaluateInteger(E, Val, Info))
15691 return false;
15692 Result = APFixedPoint(Val, FXSema);
15693 return true;
15694 } else if (E->getType()->isFixedPointType()) {
15695 return EvaluateFixedPoint(E, Result, Info);
15696 }
15697 return false;
15698}
15699
15700/// Check whether the given declaration can be directly converted to an integral
15701/// rvalue. If not, no diagnostic is produced; there are other things we can
15702/// try.
15703bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
15704 // Enums are integer constant exprs.
15705 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
15706 // Check for signedness/width mismatches between E type and ECD value.
15707 bool SameSign = (ECD->getInitVal().isSigned()
15709 bool SameWidth = (ECD->getInitVal().getBitWidth()
15710 == Info.Ctx.getIntWidth(E->getType()));
15711 if (SameSign && SameWidth)
15712 return Success(ECD->getInitVal(), E);
15713 else {
15714 // Get rid of mismatch (otherwise Success assertions will fail)
15715 // by computing a new value matching the type of E.
15716 llvm::APSInt Val = ECD->getInitVal();
15717 if (!SameSign)
15718 Val.setIsSigned(!ECD->getInitVal().isSigned());
15719 if (!SameWidth)
15720 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
15721 return Success(Val, E);
15722 }
15723 }
15724 return false;
15725}
15726
15727/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
15728/// as GCC.
15730 const LangOptions &LangOpts) {
15731 assert(!T->isDependentType() && "unexpected dependent type");
15732
15733 QualType CanTy = T.getCanonicalType();
15734
15735 switch (CanTy->getTypeClass()) {
15736#define TYPE(ID, BASE)
15737#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
15738#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
15739#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
15740#include "clang/AST/TypeNodes.inc"
15741 case Type::Auto:
15742 case Type::DeducedTemplateSpecialization:
15743 llvm_unreachable("unexpected non-canonical or dependent type");
15744
15745 case Type::Builtin:
15746 switch (cast<BuiltinType>(CanTy)->getKind()) {
15747#define BUILTIN_TYPE(ID, SINGLETON_ID)
15748#define SIGNED_TYPE(ID, SINGLETON_ID) \
15749 case BuiltinType::ID: return GCCTypeClass::Integer;
15750#define FLOATING_TYPE(ID, SINGLETON_ID) \
15751 case BuiltinType::ID: return GCCTypeClass::RealFloat;
15752#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
15753 case BuiltinType::ID: break;
15754#include "clang/AST/BuiltinTypes.def"
15755 case BuiltinType::Void:
15756 return GCCTypeClass::Void;
15757
15758 case BuiltinType::Bool:
15759 return GCCTypeClass::Bool;
15760
15761 case BuiltinType::Char_U:
15762 case BuiltinType::UChar:
15763 case BuiltinType::WChar_U:
15764 case BuiltinType::Char8:
15765 case BuiltinType::Char16:
15766 case BuiltinType::Char32:
15767 case BuiltinType::UShort:
15768 case BuiltinType::UInt:
15769 case BuiltinType::ULong:
15770 case BuiltinType::ULongLong:
15771 case BuiltinType::UInt128:
15772 return GCCTypeClass::Integer;
15773
15774 case BuiltinType::UShortAccum:
15775 case BuiltinType::UAccum:
15776 case BuiltinType::ULongAccum:
15777 case BuiltinType::UShortFract:
15778 case BuiltinType::UFract:
15779 case BuiltinType::ULongFract:
15780 case BuiltinType::SatUShortAccum:
15781 case BuiltinType::SatUAccum:
15782 case BuiltinType::SatULongAccum:
15783 case BuiltinType::SatUShortFract:
15784 case BuiltinType::SatUFract:
15785 case BuiltinType::SatULongFract:
15786 return GCCTypeClass::None;
15787
15788 case BuiltinType::NullPtr:
15789
15790 case BuiltinType::ObjCId:
15791 case BuiltinType::ObjCClass:
15792 case BuiltinType::ObjCSel:
15793#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
15794 case BuiltinType::Id:
15795#include "clang/Basic/OpenCLImageTypes.def"
15796#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
15797 case BuiltinType::Id:
15798#include "clang/Basic/OpenCLExtensionTypes.def"
15799 case BuiltinType::OCLSampler:
15800 case BuiltinType::OCLEvent:
15801 case BuiltinType::OCLClkEvent:
15802 case BuiltinType::OCLQueue:
15803 case BuiltinType::OCLReserveID:
15804#define SVE_TYPE(Name, Id, SingletonId) \
15805 case BuiltinType::Id:
15806#include "clang/Basic/AArch64ACLETypes.def"
15807#define PPC_VECTOR_TYPE(Name, Id, Size) \
15808 case BuiltinType::Id:
15809#include "clang/Basic/PPCTypes.def"
15810#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
15811#include "clang/Basic/RISCVVTypes.def"
15812#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
15813#include "clang/Basic/WebAssemblyReferenceTypes.def"
15814#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
15815#include "clang/Basic/AMDGPUTypes.def"
15816#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
15817#include "clang/Basic/HLSLIntangibleTypes.def"
15818 return GCCTypeClass::None;
15819
15820 case BuiltinType::Dependent:
15821 llvm_unreachable("unexpected dependent type");
15822 };
15823 llvm_unreachable("unexpected placeholder type");
15824
15825 case Type::Enum:
15826 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
15827
15828 case Type::Pointer:
15829 case Type::ConstantArray:
15830 case Type::VariableArray:
15831 case Type::IncompleteArray:
15832 case Type::FunctionNoProto:
15833 case Type::FunctionProto:
15834 case Type::ArrayParameter:
15835 return GCCTypeClass::Pointer;
15836
15837 case Type::MemberPointer:
15838 return CanTy->isMemberDataPointerType()
15841
15842 case Type::Complex:
15843 return GCCTypeClass::Complex;
15844
15845 case Type::Record:
15846 return CanTy->isUnionType() ? GCCTypeClass::Union
15848
15849 case Type::Atomic:
15850 // GCC classifies _Atomic T the same as T.
15852 CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
15853
15854 case Type::Vector:
15855 case Type::ExtVector:
15856 return GCCTypeClass::Vector;
15857
15858 case Type::BlockPointer:
15859 case Type::ConstantMatrix:
15860 case Type::ObjCObject:
15861 case Type::ObjCInterface:
15862 case Type::ObjCObjectPointer:
15863 case Type::Pipe:
15864 case Type::HLSLAttributedResource:
15865 case Type::HLSLInlineSpirv:
15866 case Type::OverflowBehavior:
15867 // Classify all other types that don't fit into the regular
15868 // classification the same way.
15869 return GCCTypeClass::None;
15870
15871 case Type::BitInt:
15872 return GCCTypeClass::BitInt;
15873
15874 case Type::LValueReference:
15875 case Type::RValueReference:
15876 llvm_unreachable("invalid type for expression");
15877 }
15878
15879 llvm_unreachable("unexpected type class");
15880}
15881
15882/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
15883/// as GCC.
15884static GCCTypeClass
15886 // If no argument was supplied, default to None. This isn't
15887 // ideal, however it is what gcc does.
15888 if (E->getNumArgs() == 0)
15889 return GCCTypeClass::None;
15890
15891 // FIXME: Bizarrely, GCC treats a call with more than one argument as not
15892 // being an ICE, but still folds it to a constant using the type of the first
15893 // argument.
15894 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
15895}
15896
15897/// EvaluateBuiltinConstantPForLValue - Determine the result of
15898/// __builtin_constant_p when applied to the given pointer.
15899///
15900/// A pointer is only "constant" if it is null (or a pointer cast to integer)
15901/// or it points to the first character of a string literal.
15904 if (Base.isNull()) {
15905 // A null base is acceptable.
15906 return true;
15907 } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
15908 if (!isa<StringLiteral>(E))
15909 return false;
15910 return LV.getLValueOffset().isZero();
15911 } else if (Base.is<TypeInfoLValue>()) {
15912 // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
15913 // evaluate to true.
15914 return true;
15915 } else {
15916 // Any other base is not constant enough for GCC.
15917 return false;
15918 }
15919}
15920
15921/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
15922/// GCC as we can manage.
15923static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
15924 // This evaluation is not permitted to have side-effects, so evaluate it in
15925 // a speculative evaluation context.
15926 SpeculativeEvaluationRAII SpeculativeEval(Info);
15927
15928 // Constant-folding is always enabled for the operand of __builtin_constant_p
15929 // (even when the enclosing evaluation context otherwise requires a strict
15930 // language-specific constant expression).
15931 FoldConstant Fold(Info, true);
15932
15933 QualType ArgType = Arg->getType();
15934
15935 // __builtin_constant_p always has one operand. The rules which gcc follows
15936 // are not precisely documented, but are as follows:
15937 //
15938 // - If the operand is of integral, floating, complex or enumeration type,
15939 // and can be folded to a known value of that type, it returns 1.
15940 // - If the operand can be folded to a pointer to the first character
15941 // of a string literal (or such a pointer cast to an integral type)
15942 // or to a null pointer or an integer cast to a pointer, it returns 1.
15943 //
15944 // Otherwise, it returns 0.
15945 //
15946 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
15947 // its support for this did not work prior to GCC 9 and is not yet well
15948 // understood.
15949 if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
15950 ArgType->isAnyComplexType() || ArgType->isPointerType() ||
15951 ArgType->isNullPtrType()) {
15952 APValue V;
15953 if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) {
15954 Fold.keepDiagnostics();
15955 return false;
15956 }
15957
15958 // For a pointer (possibly cast to integer), there are special rules.
15959 if (V.getKind() == APValue::LValue)
15961
15962 // Otherwise, any constant value is good enough.
15963 return V.hasValue();
15964 }
15965
15966 // Anything else isn't considered to be sufficiently constant.
15967 return false;
15968}
15969
15970/// Retrieves the "underlying object type" of the given expression,
15971/// as used by __builtin_object_size.
15973 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
15974 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
15975 return VD->getType();
15976 } else if (const Expr *E = B.dyn_cast<const Expr*>()) {
15978 return E->getType();
15979 } else if (B.is<TypeInfoLValue>()) {
15980 return B.getTypeInfoType();
15981 } else if (B.is<DynamicAllocLValue>()) {
15982 return B.getDynamicAllocType();
15983 }
15984
15985 return QualType();
15986}
15987
15988/// A more selective version of E->IgnoreParenCasts for
15989/// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
15990/// to change the type of E.
15991/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
15992///
15993/// Always returns an RValue with a pointer representation.
15994static const Expr *ignorePointerCastsAndParens(const Expr *E) {
15995 assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
15996
15997 const Expr *NoParens = E->IgnoreParens();
15998 const auto *Cast = dyn_cast<CastExpr>(NoParens);
15999 if (Cast == nullptr)
16000 return NoParens;
16001
16002 // We only conservatively allow a few kinds of casts, because this code is
16003 // inherently a simple solution that seeks to support the common case.
16004 auto CastKind = Cast->getCastKind();
16005 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
16006 CastKind != CK_AddressSpaceConversion)
16007 return NoParens;
16008
16009 const auto *SubExpr = Cast->getSubExpr();
16010 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isPRValue())
16011 return NoParens;
16012 return ignorePointerCastsAndParens(SubExpr);
16013}
16014
16015/// Checks to see if the given LValue's Designator is at the end of the LValue's
16016/// record layout. e.g.
16017/// struct { struct { int a, b; } fst, snd; } obj;
16018/// obj.fst // no
16019/// obj.snd // yes
16020/// obj.fst.a // no
16021/// obj.fst.b // no
16022/// obj.snd.a // no
16023/// obj.snd.b // yes
16024///
16025/// Please note: this function is specialized for how __builtin_object_size
16026/// views "objects".
16027///
16028/// If this encounters an invalid RecordDecl or otherwise cannot determine the
16029/// correct result, it will always return true.
16030static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
16031 assert(!LVal.Designator.Invalid);
16032
16033 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD) {
16034 const RecordDecl *Parent = FD->getParent();
16035 if (Parent->isInvalidDecl() || Parent->isUnion())
16036 return true;
16037 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
16038 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
16039 };
16040
16041 auto &Base = LVal.getLValueBase();
16042 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
16043 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
16044 if (!IsLastOrInvalidFieldDecl(FD))
16045 return false;
16046 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
16047 for (auto *FD : IFD->chain()) {
16048 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD)))
16049 return false;
16050 }
16051 }
16052 }
16053
16054 unsigned I = 0;
16055 QualType BaseType = getType(Base);
16056 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
16057 // If we don't know the array bound, conservatively assume we're looking at
16058 // the final array element.
16059 ++I;
16060 if (BaseType->isIncompleteArrayType())
16061 BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
16062 else
16063 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
16064 }
16065
16066 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
16067 const auto &Entry = LVal.Designator.Entries[I];
16068 if (BaseType->isArrayType()) {
16069 // Because __builtin_object_size treats arrays as objects, we can ignore
16070 // the index iff this is the last array in the Designator.
16071 if (I + 1 == E)
16072 return true;
16073 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
16074 uint64_t Index = Entry.getAsArrayIndex();
16075 if (Index + 1 != CAT->getZExtSize())
16076 return false;
16077 BaseType = CAT->getElementType();
16078 } else if (BaseType->isAnyComplexType()) {
16079 const auto *CT = BaseType->castAs<ComplexType>();
16080 uint64_t Index = Entry.getAsArrayIndex();
16081 if (Index != 1)
16082 return false;
16083 BaseType = CT->getElementType();
16084 } else if (auto *FD = getAsField(Entry)) {
16085 if (!IsLastOrInvalidFieldDecl(FD))
16086 return false;
16087 BaseType = FD->getType();
16088 } else {
16089 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
16090 return false;
16091 }
16092 }
16093 return true;
16094}
16095
16096/// Tests to see if the LValue has a user-specified designator (that isn't
16097/// necessarily valid). Note that this always returns 'true' if the LValue has
16098/// an unsized array as its first designator entry, because there's currently no
16099/// way to tell if the user typed *foo or foo[0].
16100static bool refersToCompleteObject(const LValue &LVal) {
16101 if (LVal.Designator.Invalid)
16102 return false;
16103
16104 if (!LVal.Designator.Entries.empty())
16105 return LVal.Designator.isMostDerivedAnUnsizedArray();
16106
16107 if (!LVal.InvalidBase)
16108 return true;
16109
16110 // If `E` is a MemberExpr, then the first part of the designator is hiding in
16111 // the LValueBase.
16112 const auto *E = LVal.Base.dyn_cast<const Expr *>();
16113 return !E || !isa<MemberExpr>(E);
16114}
16115
16116/// Attempts to detect a user writing into a piece of memory that's impossible
16117/// to figure out the size of by just using types.
16118static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
16119 const SubobjectDesignator &Designator = LVal.Designator;
16120 // Notes:
16121 // - Users can only write off of the end when we have an invalid base. Invalid
16122 // bases imply we don't know where the memory came from.
16123 // - We used to be a bit more aggressive here; we'd only be conservative if
16124 // the array at the end was flexible, or if it had 0 or 1 elements. This
16125 // broke some common standard library extensions (PR30346), but was
16126 // otherwise seemingly fine. It may be useful to reintroduce this behavior
16127 // with some sort of list. OTOH, it seems that GCC is always
16128 // conservative with the last element in structs (if it's an array), so our
16129 // current behavior is more compatible than an explicit list approach would
16130 // be.
16131 auto isFlexibleArrayMember = [&] {
16133 FAMKind StrictFlexArraysLevel =
16134 Ctx.getLangOpts().getStrictFlexArraysLevel();
16135
16136 if (Designator.isMostDerivedAnUnsizedArray())
16137 return true;
16138
16139 if (StrictFlexArraysLevel == FAMKind::Default)
16140 return true;
16141
16142 if (Designator.getMostDerivedArraySize() == 0 &&
16143 StrictFlexArraysLevel != FAMKind::IncompleteOnly)
16144 return true;
16145
16146 if (Designator.getMostDerivedArraySize() == 1 &&
16147 StrictFlexArraysLevel == FAMKind::OneZeroOrIncomplete)
16148 return true;
16149
16150 return false;
16151 };
16152
16153 return LVal.InvalidBase &&
16154 Designator.Entries.size() == Designator.MostDerivedPathLength &&
16155 Designator.MostDerivedIsArrayElement && isFlexibleArrayMember() &&
16156 isDesignatorAtObjectEnd(Ctx, LVal);
16157}
16158
16159/// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
16160/// Fails if the conversion would cause loss of precision.
16161static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
16162 CharUnits &Result) {
16163 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
16164 if (Int.ugt(CharUnitsMax))
16165 return false;
16166 Result = CharUnits::fromQuantity(Int.getZExtValue());
16167 return true;
16168}
16169
16170/// If we're evaluating the object size of an instance of a struct that
16171/// contains a flexible array member, add the size of the initializer.
16172static void addFlexibleArrayMemberInitSize(EvalInfo &Info, const QualType &T,
16173 const LValue &LV, CharUnits &Size) {
16174 if (!T.isNull() && T->isStructureType() &&
16175 T->castAsRecordDecl()->hasFlexibleArrayMember())
16176 if (const auto *V = LV.getLValueBase().dyn_cast<const ValueDecl *>())
16177 if (const auto *VD = dyn_cast<VarDecl>(V))
16178 if (VD->hasInit())
16179 Size += VD->getFlexibleArrayInitChars(Info.Ctx);
16180}
16181
16182/// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
16183/// determine how many bytes exist from the beginning of the object to either
16184/// the end of the current subobject, or the end of the object itself, depending
16185/// on what the LValue looks like + the value of Type.
16186///
16187/// If this returns false, the value of Result is undefined.
16188static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
16189 unsigned Type, const LValue &LVal,
16190 CharUnits &EndOffset) {
16191 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
16192
16193 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
16194 if (Ty.isNull())
16195 return false;
16196
16197 Ty = Ty.getNonReferenceType();
16198
16199 if (Ty->isIncompleteType() || Ty->isFunctionType())
16200 return false;
16201
16202 return HandleSizeof(Info, ExprLoc, Ty, Result);
16203 };
16204
16205 // We want to evaluate the size of the entire object. This is a valid fallback
16206 // for when Type=1 and the designator is invalid, because we're asked for an
16207 // upper-bound.
16208 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
16209 // Type=3 wants a lower bound, so we can't fall back to this.
16210 if (Type == 3 && !DetermineForCompleteObject)
16211 return false;
16212
16213 llvm::APInt APEndOffset;
16214 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
16215 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
16216 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
16217
16218 if (LVal.InvalidBase)
16219 return false;
16220
16221 QualType BaseTy = getObjectType(LVal.getLValueBase());
16222 const bool Ret = CheckedHandleSizeof(BaseTy, EndOffset);
16223 addFlexibleArrayMemberInitSize(Info, BaseTy, LVal, EndOffset);
16224 return Ret;
16225 }
16226
16227 // We want to evaluate the size of a subobject.
16228 const SubobjectDesignator &Designator = LVal.Designator;
16229
16230 // The following is a moderately common idiom in C:
16231 //
16232 // struct Foo { int a; char c[1]; };
16233 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
16234 // strcpy(&F->c[0], Bar);
16235 //
16236 // In order to not break too much legacy code, we need to support it.
16237 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
16238 // If we can resolve this to an alloc_size call, we can hand that back,
16239 // because we know for certain how many bytes there are to write to.
16240 llvm::APInt APEndOffset;
16241 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
16242 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
16243 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
16244
16245 // If we cannot determine the size of the initial allocation, then we can't
16246 // given an accurate upper-bound. However, we are still able to give
16247 // conservative lower-bounds for Type=3.
16248 if (Type == 1)
16249 return false;
16250 }
16251
16252 CharUnits BytesPerElem;
16253 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
16254 return false;
16255
16256 // According to the GCC documentation, we want the size of the subobject
16257 // denoted by the pointer. But that's not quite right -- what we actually
16258 // want is the size of the immediately-enclosing array, if there is one.
16259 int64_t ElemsRemaining;
16260 if (Designator.MostDerivedIsArrayElement &&
16261 Designator.Entries.size() == Designator.MostDerivedPathLength) {
16262 uint64_t ArraySize = Designator.getMostDerivedArraySize();
16263 uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
16264 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
16265 } else {
16266 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
16267 }
16268
16269 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
16270 return true;
16271}
16272
16273/// Tries to evaluate the __builtin_object_size for @p E. If successful,
16274/// returns true and stores the result in @p Size.
16275///
16276/// If @p WasError is non-null, this will report whether the failure to evaluate
16277/// is to be treated as an Error in IntExprEvaluator.
16278static std::optional<uint64_t>
16279tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type, EvalInfo &Info) {
16280 // Determine the denoted object.
16281 LValue LVal;
16282 {
16283 // The operand of __builtin_object_size is never evaluated for side-effects.
16284 // If there are any, but we can determine the pointed-to object anyway, then
16285 // ignore the side-effects.
16286 SpeculativeEvaluationRAII SpeculativeEval(Info);
16287 IgnoreSideEffectsRAII Fold(Info);
16288
16289 if (E->isGLValue()) {
16290 // It's possible for us to be given GLValues if we're called via
16291 // Expr::tryEvaluateObjectSize.
16292 APValue RVal;
16293 if (!EvaluateAsRValue(Info, E, RVal))
16294 return std::nullopt;
16295 LVal.setFrom(Info.Ctx, RVal);
16296 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
16297 /*InvalidBaseOK=*/true))
16298 return std::nullopt;
16299 }
16300
16301 // If we point to before the start of the object, there are no accessible
16302 // bytes.
16303 if (LVal.getLValueOffset().isNegative())
16304 return 0;
16305
16306 CharUnits EndOffset;
16307 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
16308 return std::nullopt;
16309
16310 // If we've fallen outside of the end offset, just pretend there's nothing to
16311 // write to/read from.
16312 if (EndOffset <= LVal.getLValueOffset())
16313 return 0;
16314 return (EndOffset - LVal.getLValueOffset()).getQuantity();
16315}
16316
16317bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
16318 if (!IsConstantEvaluatedBuiltinCall(E))
16319 return ExprEvaluatorBaseTy::VisitCallExpr(E);
16320 return VisitBuiltinCallExpr(E, E->getBuiltinCallee());
16321}
16322
16323static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info,
16324 APValue &Val, APSInt &Alignment) {
16325 QualType SrcTy = E->getArg(0)->getType();
16326 if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment))
16327 return false;
16328 // Even though we are evaluating integer expressions we could get a pointer
16329 // argument for the __builtin_is_aligned() case.
16330 if (SrcTy->isPointerType()) {
16331 LValue Ptr;
16332 if (!EvaluatePointer(E->getArg(0), Ptr, Info))
16333 return false;
16334 Ptr.moveInto(Val);
16335 } else if (!SrcTy->isIntegralOrEnumerationType()) {
16336 Info.FFDiag(E->getArg(0));
16337 return false;
16338 } else {
16339 APSInt SrcInt;
16340 if (!EvaluateInteger(E->getArg(0), SrcInt, Info))
16341 return false;
16342 assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() &&
16343 "Bit widths must be the same");
16344 Val = APValue(SrcInt);
16345 }
16346 assert(Val.hasValue());
16347 return true;
16348}
16349
16350bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
16351 unsigned BuiltinOp) {
16352 auto EvalTestOp = [&](llvm::function_ref<bool(const APInt &, const APInt &)>
16353 Fn) {
16354 APValue SourceLHS, SourceRHS;
16355 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
16356 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
16357 return false;
16358
16359 unsigned SourceLen = SourceLHS.getVectorLength();
16360 const VectorType *VT = E->getArg(0)->getType()->castAs<VectorType>();
16361 QualType ElemQT = VT->getElementType();
16362 unsigned LaneWidth = Info.Ctx.getTypeSize(ElemQT);
16363
16364 APInt AWide(LaneWidth * SourceLen, 0);
16365 APInt BWide(LaneWidth * SourceLen, 0);
16366
16367 for (unsigned I = 0; I != SourceLen; ++I) {
16368 APInt ALane;
16369 APInt BLane;
16370 if (ElemQT->isIntegerType()) { // Get value.
16371 ALane = SourceLHS.getVectorElt(I).getInt();
16372 BLane = SourceRHS.getVectorElt(I).getInt();
16373 } else if (ElemQT->isFloatingType()) { // Get only sign bit.
16374 ALane =
16375 SourceLHS.getVectorElt(I).getFloat().bitcastToAPInt().isNegative();
16376 BLane =
16377 SourceRHS.getVectorElt(I).getFloat().bitcastToAPInt().isNegative();
16378 } else { // Must be integer or floating type.
16379 return false;
16380 }
16381 AWide.insertBits(ALane, I * LaneWidth);
16382 BWide.insertBits(BLane, I * LaneWidth);
16383 }
16384 return Success(Fn(AWide, BWide), E);
16385 };
16386
16387 auto HandleMaskBinOp =
16388 [&](llvm::function_ref<APSInt(const APSInt &, const APSInt &)> Fn)
16389 -> bool {
16390 APValue LHS, RHS;
16391 if (!Evaluate(LHS, Info, E->getArg(0)) ||
16392 !Evaluate(RHS, Info, E->getArg(1)))
16393 return false;
16394
16395 APSInt ResultInt = Fn(LHS.getInt(), RHS.getInt());
16396
16397 return Success(APValue(ResultInt), E);
16398 };
16399
16400 auto HandleCRC32 = [&](unsigned DataBytes) -> bool {
16401 APSInt CRC, Data;
16402 if (!EvaluateInteger(E->getArg(0), CRC, Info) ||
16403 !EvaluateInteger(E->getArg(1), Data, Info))
16404 return false;
16405
16406 uint64_t CRCVal = CRC.getZExtValue();
16407 uint64_t DataVal = Data.getZExtValue();
16408
16409 // CRC32C polynomial (iSCSI polynomial, bit-reversed)
16410 static const uint32_t CRC32C_POLY = 0x82F63B78;
16411
16412 // Process each byte
16413 uint32_t Result = static_cast<uint32_t>(CRCVal);
16414 for (unsigned I = 0; I != DataBytes; ++I) {
16415 uint8_t Byte = static_cast<uint8_t>((DataVal >> (I * 8)) & 0xFF);
16416 Result ^= Byte;
16417 for (int J = 0; J != 8; ++J) {
16418 Result = (Result >> 1) ^ ((Result & 1) ? CRC32C_POLY : 0);
16419 }
16420 }
16421
16422 return Success(Result, E);
16423 };
16424
16425 switch (BuiltinOp) {
16426 default:
16427 return false;
16428
16429 case X86::BI__builtin_ia32_crc32qi:
16430 return HandleCRC32(1);
16431 case X86::BI__builtin_ia32_crc32hi:
16432 return HandleCRC32(2);
16433 case X86::BI__builtin_ia32_crc32si:
16434 return HandleCRC32(4);
16435 case X86::BI__builtin_ia32_crc32di:
16436 return HandleCRC32(8);
16437
16438 case Builtin::BI__builtin_dynamic_object_size:
16439 case Builtin::BI__builtin_object_size: {
16440 // The type was checked when we built the expression.
16441 unsigned Type =
16442 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
16443 assert(Type <= 3 && "unexpected type");
16444
16445 if (std::optional<uint64_t> Size =
16447 return Success(*Size, E);
16448
16449 if (E->getArg(0)->HasSideEffects(Info.Ctx))
16450 return Success((Type & 2) ? 0 : -1, E);
16451
16452 // Expression had no side effects, but we couldn't statically determine the
16453 // size of the referenced object.
16454 switch (Info.EvalMode) {
16455 case EvaluationMode::ConstantExpression:
16456 case EvaluationMode::ConstantFold:
16457 case EvaluationMode::IgnoreSideEffects:
16458 // Leave it to IR generation.
16459 return Error(E);
16460 case EvaluationMode::ConstantExpressionUnevaluated:
16461 // Reduce it to a constant now.
16462 return Success((Type & 2) ? 0 : -1, E);
16463 }
16464
16465 llvm_unreachable("unexpected EvalMode");
16466 }
16467
16468 case Builtin::BI__builtin_os_log_format_buffer_size: {
16469 analyze_os_log::OSLogBufferLayout Layout;
16470 analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
16471 return Success(Layout.size().getQuantity(), E);
16472 }
16473
16474 case Builtin::BI__builtin_is_aligned: {
16475 APValue Src;
16476 APSInt Alignment;
16477 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
16478 return false;
16479 if (Src.isLValue()) {
16480 // If we evaluated a pointer, check the minimum known alignment.
16481 LValue Ptr;
16482 Ptr.setFrom(Info.Ctx, Src);
16483 CharUnits BaseAlignment = getBaseAlignment(Info, Ptr);
16484 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset);
16485 // We can return true if the known alignment at the computed offset is
16486 // greater than the requested alignment.
16487 assert(PtrAlign.isPowerOfTwo());
16488 assert(Alignment.isPowerOf2());
16489 if (PtrAlign.getQuantity() >= Alignment)
16490 return Success(1, E);
16491 // If the alignment is not known to be sufficient, some cases could still
16492 // be aligned at run time. However, if the requested alignment is less or
16493 // equal to the base alignment and the offset is not aligned, we know that
16494 // the run-time value can never be aligned.
16495 if (BaseAlignment.getQuantity() >= Alignment &&
16496 PtrAlign.getQuantity() < Alignment)
16497 return Success(0, E);
16498 // Otherwise we can't infer whether the value is sufficiently aligned.
16499 // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N)
16500 // in cases where we can't fully evaluate the pointer.
16501 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute)
16502 << Alignment;
16503 return false;
16504 }
16505 assert(Src.isInt());
16506 return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E);
16507 }
16508 case Builtin::BI__builtin_align_up: {
16509 APValue Src;
16510 APSInt Alignment;
16511 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
16512 return false;
16513 if (!Src.isInt())
16514 return Error(E);
16515 APSInt AlignedVal =
16516 APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1),
16517 Src.getInt().isUnsigned());
16518 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
16519 return Success(AlignedVal, E);
16520 }
16521 case Builtin::BI__builtin_align_down: {
16522 APValue Src;
16523 APSInt Alignment;
16524 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
16525 return false;
16526 if (!Src.isInt())
16527 return Error(E);
16528 APSInt AlignedVal =
16529 APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned());
16530 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
16531 return Success(AlignedVal, E);
16532 }
16533
16534 case Builtin::BI__builtin_bitreverseg:
16535 case Builtin::BI__builtin_bitreverse8:
16536 case Builtin::BI__builtin_bitreverse16:
16537 case Builtin::BI__builtin_bitreverse32:
16538 case Builtin::BI__builtin_bitreverse64:
16539 case Builtin::BI__builtin_elementwise_bitreverse: {
16540 APSInt Val;
16541 if (!EvaluateInteger(E->getArg(0), Val, Info))
16542 return false;
16543
16544 return Success(Val.reverseBits(), E);
16545 }
16546 case Builtin::BI__builtin_bswapg:
16547 case Builtin::BI__builtin_bswap16:
16548 case Builtin::BI__builtin_bswap32:
16549 case Builtin::BI__builtin_bswap64: {
16550 APSInt Val;
16551 if (!EvaluateInteger(E->getArg(0), Val, Info))
16552 return false;
16553 if (Val.getBitWidth() == 8 || Val.getBitWidth() == 1)
16554 return Success(Val, E);
16555
16556 return Success(Val.byteSwap(), E);
16557 }
16558
16559 case Builtin::BI__builtin_classify_type:
16560 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
16561
16562 case Builtin::BI__builtin_clrsb:
16563 case Builtin::BI__builtin_clrsbl:
16564 case Builtin::BI__builtin_clrsbll: {
16565 APSInt Val;
16566 if (!EvaluateInteger(E->getArg(0), Val, Info))
16567 return false;
16568
16569 return Success(Val.getBitWidth() - Val.getSignificantBits(), E);
16570 }
16571
16572 case Builtin::BI__builtin_clz:
16573 case Builtin::BI__builtin_clzl:
16574 case Builtin::BI__builtin_clzll:
16575 case Builtin::BI__builtin_clzs:
16576 case Builtin::BI__builtin_clzg:
16577 case Builtin::BI__builtin_elementwise_clzg:
16578 case Builtin::BI__lzcnt16: // Microsoft variants of count leading-zeroes
16579 case Builtin::BI__lzcnt:
16580 case Builtin::BI__lzcnt64: {
16581 APSInt Val;
16582 if (E->getArg(0)->getType()->isExtVectorBoolType()) {
16583 APValue Vec;
16584 if (!EvaluateVector(E->getArg(0), Vec, Info))
16585 return false;
16586 Val = ConvertBoolVectorToInt(Vec);
16587 } else if (!EvaluateInteger(E->getArg(0), Val, Info)) {
16588 return false;
16589 }
16590
16591 std::optional<APSInt> Fallback;
16592 if ((BuiltinOp == Builtin::BI__builtin_clzg ||
16593 BuiltinOp == Builtin::BI__builtin_elementwise_clzg) &&
16594 E->getNumArgs() > 1) {
16595 APSInt FallbackTemp;
16596 if (!EvaluateInteger(E->getArg(1), FallbackTemp, Info))
16597 return false;
16598 Fallback = FallbackTemp;
16599 }
16600
16601 if (!Val) {
16602 if (Fallback)
16603 return Success(*Fallback, E);
16604
16605 // When the argument is 0, the result of GCC builtins is undefined,
16606 // whereas for Microsoft intrinsics, the result is the bit-width of the
16607 // argument.
16608 bool ZeroIsUndefined = BuiltinOp != Builtin::BI__lzcnt16 &&
16609 BuiltinOp != Builtin::BI__lzcnt &&
16610 BuiltinOp != Builtin::BI__lzcnt64;
16611
16612 if (BuiltinOp == Builtin::BI__builtin_elementwise_clzg) {
16613 Info.FFDiag(E, diag::note_constexpr_countzeroes_zero)
16614 << /*IsTrailing=*/false;
16615 }
16616
16617 if (ZeroIsUndefined)
16618 return Error(E);
16619 }
16620
16621 return Success(Val.countl_zero(), E);
16622 }
16623
16624 case Builtin::BI__builtin_constant_p: {
16625 const Expr *Arg = E->getArg(0);
16626 if (EvaluateBuiltinConstantP(Info, Arg))
16627 return Success(true, E);
16628 if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
16629 // Outside a constant context, eagerly evaluate to false in the presence
16630 // of side-effects in order to avoid -Wunsequenced false-positives in
16631 // a branch on __builtin_constant_p(expr).
16632 return Success(false, E);
16633 }
16634 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
16635 return false;
16636 }
16637
16638 case Builtin::BI__noop:
16639 // __noop always evaluates successfully and returns 0.
16640 return Success(0, E);
16641
16642 case Builtin::BI__builtin_is_constant_evaluated: {
16643 const auto *Callee = Info.CurrentCall->getCallee();
16644 if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression &&
16645 (Info.CallStackDepth == 1 ||
16646 (Info.CallStackDepth == 2 && Callee->isInStdNamespace() &&
16647 Callee->getIdentifier() &&
16648 Callee->getIdentifier()->isStr("is_constant_evaluated")))) {
16649 // FIXME: Find a better way to avoid duplicated diagnostics.
16650 if (Info.EvalStatus.Diag)
16651 Info.report((Info.CallStackDepth == 1)
16652 ? E->getExprLoc()
16653 : Info.CurrentCall->getCallRange().getBegin(),
16654 diag::warn_is_constant_evaluated_always_true_constexpr)
16655 << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated"
16656 : "std::is_constant_evaluated");
16657 }
16658
16659 return Success(Info.InConstantContext, E);
16660 }
16661
16662 case Builtin::BI__builtin_is_within_lifetime:
16663 if (auto result = EvaluateBuiltinIsWithinLifetime(*this, E))
16664 return Success(*result, E);
16665 return false;
16666
16667 case Builtin::BI__builtin_ctz:
16668 case Builtin::BI__builtin_ctzl:
16669 case Builtin::BI__builtin_ctzll:
16670 case Builtin::BI__builtin_ctzs:
16671 case Builtin::BI__builtin_ctzg:
16672 case Builtin::BI__builtin_elementwise_ctzg: {
16673 APSInt Val;
16674 if (E->getArg(0)->getType()->isExtVectorBoolType()) {
16675 APValue Vec;
16676 if (!EvaluateVector(E->getArg(0), Vec, Info))
16677 return false;
16678 Val = ConvertBoolVectorToInt(Vec);
16679 } else if (!EvaluateInteger(E->getArg(0), Val, Info)) {
16680 return false;
16681 }
16682
16683 std::optional<APSInt> Fallback;
16684 if ((BuiltinOp == Builtin::BI__builtin_ctzg ||
16685 BuiltinOp == Builtin::BI__builtin_elementwise_ctzg) &&
16686 E->getNumArgs() > 1) {
16687 APSInt FallbackTemp;
16688 if (!EvaluateInteger(E->getArg(1), FallbackTemp, Info))
16689 return false;
16690 Fallback = FallbackTemp;
16691 }
16692
16693 if (!Val) {
16694 if (Fallback)
16695 return Success(*Fallback, E);
16696
16697 if (BuiltinOp == Builtin::BI__builtin_elementwise_ctzg) {
16698 Info.FFDiag(E, diag::note_constexpr_countzeroes_zero)
16699 << /*IsTrailing=*/true;
16700 }
16701 return Error(E);
16702 }
16703
16704 return Success(Val.countr_zero(), E);
16705 }
16706
16707 case Builtin::BI__builtin_eh_return_data_regno: {
16708 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
16709 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
16710 return Success(Operand, E);
16711 }
16712
16713 case Builtin::BI__builtin_elementwise_abs: {
16714 APSInt Val;
16715 if (!EvaluateInteger(E->getArg(0), Val, Info))
16716 return false;
16717
16718 return Success(Val.abs(), E);
16719 }
16720
16721 case Builtin::BI__builtin_expect:
16722 case Builtin::BI__builtin_expect_with_probability:
16723 return Visit(E->getArg(0));
16724
16725 case Builtin::BI__builtin_ptrauth_string_discriminator: {
16726 const auto *Literal =
16728 uint64_t Result = getPointerAuthStableSipHash(Literal->getString());
16729 return Success(Result, E);
16730 }
16731
16732 case Builtin::BI__builtin_infer_alloc_token: {
16733 // If we fail to infer a type, this fails to be a constant expression; this
16734 // can be checked with __builtin_constant_p(...).
16735 QualType AllocType = infer_alloc::inferPossibleType(E, Info.Ctx, nullptr);
16736 if (AllocType.isNull())
16737 return Error(
16738 E, diag::note_constexpr_infer_alloc_token_type_inference_failed);
16739 auto ATMD = infer_alloc::getAllocTokenMetadata(AllocType, Info.Ctx);
16740 if (!ATMD)
16741 return Error(E, diag::note_constexpr_infer_alloc_token_no_metadata);
16742 auto Mode =
16743 Info.getLangOpts().AllocTokenMode.value_or(llvm::DefaultAllocTokenMode);
16744 uint64_t BitWidth = Info.Ctx.getTypeSize(Info.Ctx.getSizeType());
16745 auto MaxTokensOpt = Info.getLangOpts().AllocTokenMax;
16746 uint64_t MaxTokens =
16747 MaxTokensOpt.value_or(0) ? *MaxTokensOpt : (~0ULL >> (64 - BitWidth));
16748 auto MaybeToken = llvm::getAllocToken(Mode, *ATMD, MaxTokens);
16749 if (!MaybeToken)
16750 return Error(E, diag::note_constexpr_infer_alloc_token_stateful_mode);
16751 return Success(llvm::APInt(BitWidth, *MaybeToken), E);
16752 }
16753
16754 case Builtin::BI__builtin_ffs:
16755 case Builtin::BI__builtin_ffsl:
16756 case Builtin::BI__builtin_ffsll: {
16757 APSInt Val;
16758 if (!EvaluateInteger(E->getArg(0), Val, Info))
16759 return false;
16760
16761 unsigned N = Val.countr_zero();
16762 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
16763 }
16764
16765 case Builtin::BI__builtin_fpclassify: {
16766 APFloat Val(0.0);
16767 if (!EvaluateFloat(E->getArg(5), Val, Info))
16768 return false;
16769 unsigned Arg;
16770 switch (Val.getCategory()) {
16771 case APFloat::fcNaN: Arg = 0; break;
16772 case APFloat::fcInfinity: Arg = 1; break;
16773 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
16774 case APFloat::fcZero: Arg = 4; break;
16775 }
16776 return Visit(E->getArg(Arg));
16777 }
16778
16779 case Builtin::BI__builtin_isinf_sign: {
16780 APFloat Val(0.0);
16781 return EvaluateFloat(E->getArg(0), Val, Info) &&
16782 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
16783 }
16784
16785 case Builtin::BI__builtin_isinf: {
16786 APFloat Val(0.0);
16787 return EvaluateFloat(E->getArg(0), Val, Info) &&
16788 Success(Val.isInfinity() ? 1 : 0, E);
16789 }
16790
16791 case Builtin::BI__builtin_isfinite: {
16792 APFloat Val(0.0);
16793 return EvaluateFloat(E->getArg(0), Val, Info) &&
16794 Success(Val.isFinite() ? 1 : 0, E);
16795 }
16796
16797 case Builtin::BI__builtin_isnan: {
16798 APFloat Val(0.0);
16799 return EvaluateFloat(E->getArg(0), Val, Info) &&
16800 Success(Val.isNaN() ? 1 : 0, E);
16801 }
16802
16803 case Builtin::BI__builtin_isnormal: {
16804 APFloat Val(0.0);
16805 return EvaluateFloat(E->getArg(0), Val, Info) &&
16806 Success(Val.isNormal() ? 1 : 0, E);
16807 }
16808
16809 case Builtin::BI__builtin_issubnormal: {
16810 APFloat Val(0.0);
16811 return EvaluateFloat(E->getArg(0), Val, Info) &&
16812 Success(Val.isDenormal() ? 1 : 0, E);
16813 }
16814
16815 case Builtin::BI__builtin_iszero: {
16816 APFloat Val(0.0);
16817 return EvaluateFloat(E->getArg(0), Val, Info) &&
16818 Success(Val.isZero() ? 1 : 0, E);
16819 }
16820
16821 case Builtin::BI__builtin_signbit:
16822 case Builtin::BI__builtin_signbitf:
16823 case Builtin::BI__builtin_signbitl: {
16824 APFloat Val(0.0);
16825 return EvaluateFloat(E->getArg(0), Val, Info) &&
16826 Success(Val.isNegative() ? 1 : 0, E);
16827 }
16828
16829 case Builtin::BI__builtin_isgreater:
16830 case Builtin::BI__builtin_isgreaterequal:
16831 case Builtin::BI__builtin_isless:
16832 case Builtin::BI__builtin_islessequal:
16833 case Builtin::BI__builtin_islessgreater:
16834 case Builtin::BI__builtin_isunordered: {
16835 APFloat LHS(0.0);
16836 APFloat RHS(0.0);
16837 if (!EvaluateFloat(E->getArg(0), LHS, Info) ||
16838 !EvaluateFloat(E->getArg(1), RHS, Info))
16839 return false;
16840
16841 return Success(
16842 [&] {
16843 switch (BuiltinOp) {
16844 case Builtin::BI__builtin_isgreater:
16845 return LHS > RHS;
16846 case Builtin::BI__builtin_isgreaterequal:
16847 return LHS >= RHS;
16848 case Builtin::BI__builtin_isless:
16849 return LHS < RHS;
16850 case Builtin::BI__builtin_islessequal:
16851 return LHS <= RHS;
16852 case Builtin::BI__builtin_islessgreater: {
16853 APFloat::cmpResult cmp = LHS.compare(RHS);
16854 return cmp == APFloat::cmpResult::cmpLessThan ||
16855 cmp == APFloat::cmpResult::cmpGreaterThan;
16856 }
16857 case Builtin::BI__builtin_isunordered:
16858 return LHS.compare(RHS) == APFloat::cmpResult::cmpUnordered;
16859 default:
16860 llvm_unreachable("Unexpected builtin ID: Should be a floating "
16861 "point comparison function");
16862 }
16863 }()
16864 ? 1
16865 : 0,
16866 E);
16867 }
16868
16869 case Builtin::BI__builtin_issignaling: {
16870 APFloat Val(0.0);
16871 return EvaluateFloat(E->getArg(0), Val, Info) &&
16872 Success(Val.isSignaling() ? 1 : 0, E);
16873 }
16874
16875 case Builtin::BI__builtin_isfpclass: {
16876 APSInt MaskVal;
16877 if (!EvaluateInteger(E->getArg(1), MaskVal, Info))
16878 return false;
16879 unsigned Test = static_cast<llvm::FPClassTest>(MaskVal.getZExtValue());
16880 APFloat Val(0.0);
16881 return EvaluateFloat(E->getArg(0), Val, Info) &&
16882 Success((Val.classify() & Test) ? 1 : 0, E);
16883 }
16884
16885 case Builtin::BI__builtin_parity:
16886 case Builtin::BI__builtin_parityl:
16887 case Builtin::BI__builtin_parityll: {
16888 APSInt Val;
16889 if (!EvaluateInteger(E->getArg(0), Val, Info))
16890 return false;
16891
16892 return Success(Val.popcount() % 2, E);
16893 }
16894
16895 case Builtin::BI__builtin_abs:
16896 case Builtin::BI__builtin_labs:
16897 case Builtin::BI__builtin_llabs: {
16898 APSInt Val;
16899 if (!EvaluateInteger(E->getArg(0), Val, Info))
16900 return false;
16901 if (Val == APSInt(APInt::getSignedMinValue(Val.getBitWidth()),
16902 /*IsUnsigned=*/false))
16903 return false;
16904 if (Val.isNegative())
16905 Val.negate();
16906 return Success(Val, E);
16907 }
16908
16909 case Builtin::BI__builtin_popcount:
16910 case Builtin::BI__builtin_popcountl:
16911 case Builtin::BI__builtin_popcountll:
16912 case Builtin::BI__builtin_popcountg:
16913 case Builtin::BI__builtin_elementwise_popcount:
16914 case Builtin::BI__popcnt16: // Microsoft variants of popcount
16915 case Builtin::BI__popcnt:
16916 case Builtin::BI__popcnt64: {
16917 APSInt Val;
16918 if (E->getArg(0)->getType()->isExtVectorBoolType()) {
16919 APValue Vec;
16920 if (!EvaluateVector(E->getArg(0), Vec, Info))
16921 return false;
16922 Val = ConvertBoolVectorToInt(Vec);
16923 } else if (!EvaluateInteger(E->getArg(0), Val, Info)) {
16924 return false;
16925 }
16926
16927 return Success(Val.popcount(), E);
16928 }
16929
16930 case Builtin::BI__builtin_rotateleft8:
16931 case Builtin::BI__builtin_rotateleft16:
16932 case Builtin::BI__builtin_rotateleft32:
16933 case Builtin::BI__builtin_rotateleft64:
16934 case Builtin::BI__builtin_rotateright8:
16935 case Builtin::BI__builtin_rotateright16:
16936 case Builtin::BI__builtin_rotateright32:
16937 case Builtin::BI__builtin_rotateright64:
16938 case Builtin::BI__builtin_stdc_rotate_left:
16939 case Builtin::BI__builtin_stdc_rotate_right:
16940 case Builtin::BIstdc_rotate_left_uc:
16941 case Builtin::BIstdc_rotate_left_us:
16942 case Builtin::BIstdc_rotate_left_ui:
16943 case Builtin::BIstdc_rotate_left_ul:
16944 case Builtin::BIstdc_rotate_left_ull:
16945 case Builtin::BIstdc_rotate_right_uc:
16946 case Builtin::BIstdc_rotate_right_us:
16947 case Builtin::BIstdc_rotate_right_ui:
16948 case Builtin::BIstdc_rotate_right_ul:
16949 case Builtin::BIstdc_rotate_right_ull:
16950 case Builtin::BI_rotl8: // Microsoft variants of rotate left
16951 case Builtin::BI_rotl16:
16952 case Builtin::BI_rotl:
16953 case Builtin::BI_lrotl:
16954 case Builtin::BI_rotl64:
16955 case Builtin::BI_rotr8: // Microsoft variants of rotate right
16956 case Builtin::BI_rotr16:
16957 case Builtin::BI_rotr:
16958 case Builtin::BI_lrotr:
16959 case Builtin::BI_rotr64: {
16960 APSInt Value, Amount;
16961 if (!EvaluateInteger(E->getArg(0), Value, Info) ||
16962 !EvaluateInteger(E->getArg(1), Amount, Info))
16963 return false;
16964
16965 Amount = NormalizeRotateAmount(Value, Amount);
16966
16967 switch (BuiltinOp) {
16968 case Builtin::BI__builtin_rotateright8:
16969 case Builtin::BI__builtin_rotateright16:
16970 case Builtin::BI__builtin_rotateright32:
16971 case Builtin::BI__builtin_rotateright64:
16972 case Builtin::BI__builtin_stdc_rotate_right:
16973 case Builtin::BIstdc_rotate_right_uc:
16974 case Builtin::BIstdc_rotate_right_us:
16975 case Builtin::BIstdc_rotate_right_ui:
16976 case Builtin::BIstdc_rotate_right_ul:
16977 case Builtin::BIstdc_rotate_right_ull:
16978 case Builtin::BI_rotr8:
16979 case Builtin::BI_rotr16:
16980 case Builtin::BI_rotr:
16981 case Builtin::BI_lrotr:
16982 case Builtin::BI_rotr64:
16983 return Success(
16984 APSInt(Value.rotr(Amount.getZExtValue()), Value.isUnsigned()), E);
16985 default:
16986 return Success(
16987 APSInt(Value.rotl(Amount.getZExtValue()), Value.isUnsigned()), E);
16988 }
16989 }
16990
16991 case Builtin::BIstdc_leading_zeros_uc:
16992 case Builtin::BIstdc_leading_zeros_us:
16993 case Builtin::BIstdc_leading_zeros_ui:
16994 case Builtin::BIstdc_leading_zeros_ul:
16995 case Builtin::BIstdc_leading_zeros_ull:
16996 case Builtin::BIstdc_leading_ones_uc:
16997 case Builtin::BIstdc_leading_ones_us:
16998 case Builtin::BIstdc_leading_ones_ui:
16999 case Builtin::BIstdc_leading_ones_ul:
17000 case Builtin::BIstdc_leading_ones_ull:
17001 case Builtin::BIstdc_trailing_zeros_uc:
17002 case Builtin::BIstdc_trailing_zeros_us:
17003 case Builtin::BIstdc_trailing_zeros_ui:
17004 case Builtin::BIstdc_trailing_zeros_ul:
17005 case Builtin::BIstdc_trailing_zeros_ull:
17006 case Builtin::BIstdc_trailing_ones_uc:
17007 case Builtin::BIstdc_trailing_ones_us:
17008 case Builtin::BIstdc_trailing_ones_ui:
17009 case Builtin::BIstdc_trailing_ones_ul:
17010 case Builtin::BIstdc_trailing_ones_ull:
17011 case Builtin::BIstdc_first_leading_zero_uc:
17012 case Builtin::BIstdc_first_leading_zero_us:
17013 case Builtin::BIstdc_first_leading_zero_ui:
17014 case Builtin::BIstdc_first_leading_zero_ul:
17015 case Builtin::BIstdc_first_leading_zero_ull:
17016 case Builtin::BIstdc_first_leading_one_uc:
17017 case Builtin::BIstdc_first_leading_one_us:
17018 case Builtin::BIstdc_first_leading_one_ui:
17019 case Builtin::BIstdc_first_leading_one_ul:
17020 case Builtin::BIstdc_first_leading_one_ull:
17021 case Builtin::BIstdc_first_trailing_zero_uc:
17022 case Builtin::BIstdc_first_trailing_zero_us:
17023 case Builtin::BIstdc_first_trailing_zero_ui:
17024 case Builtin::BIstdc_first_trailing_zero_ul:
17025 case Builtin::BIstdc_first_trailing_zero_ull:
17026 case Builtin::BIstdc_first_trailing_one_uc:
17027 case Builtin::BIstdc_first_trailing_one_us:
17028 case Builtin::BIstdc_first_trailing_one_ui:
17029 case Builtin::BIstdc_first_trailing_one_ul:
17030 case Builtin::BIstdc_first_trailing_one_ull:
17031 case Builtin::BIstdc_count_zeros_uc:
17032 case Builtin::BIstdc_count_zeros_us:
17033 case Builtin::BIstdc_count_zeros_ui:
17034 case Builtin::BIstdc_count_zeros_ul:
17035 case Builtin::BIstdc_count_zeros_ull:
17036 case Builtin::BIstdc_count_ones_uc:
17037 case Builtin::BIstdc_count_ones_us:
17038 case Builtin::BIstdc_count_ones_ui:
17039 case Builtin::BIstdc_count_ones_ul:
17040 case Builtin::BIstdc_count_ones_ull:
17041 case Builtin::BIstdc_has_single_bit_uc:
17042 case Builtin::BIstdc_has_single_bit_us:
17043 case Builtin::BIstdc_has_single_bit_ui:
17044 case Builtin::BIstdc_has_single_bit_ul:
17045 case Builtin::BIstdc_has_single_bit_ull:
17046 case Builtin::BIstdc_bit_width_uc:
17047 case Builtin::BIstdc_bit_width_us:
17048 case Builtin::BIstdc_bit_width_ui:
17049 case Builtin::BIstdc_bit_width_ul:
17050 case Builtin::BIstdc_bit_width_ull:
17051 case Builtin::BIstdc_bit_floor_uc:
17052 case Builtin::BIstdc_bit_floor_us:
17053 case Builtin::BIstdc_bit_floor_ui:
17054 case Builtin::BIstdc_bit_floor_ul:
17055 case Builtin::BIstdc_bit_floor_ull:
17056 case Builtin::BIstdc_bit_ceil_uc:
17057 case Builtin::BIstdc_bit_ceil_us:
17058 case Builtin::BIstdc_bit_ceil_ui:
17059 case Builtin::BIstdc_bit_ceil_ul:
17060 case Builtin::BIstdc_bit_ceil_ull:
17061 case Builtin::BI__builtin_stdc_leading_zeros:
17062 case Builtin::BI__builtin_stdc_leading_ones:
17063 case Builtin::BI__builtin_stdc_trailing_zeros:
17064 case Builtin::BI__builtin_stdc_trailing_ones:
17065 case Builtin::BI__builtin_stdc_first_leading_zero:
17066 case Builtin::BI__builtin_stdc_first_leading_one:
17067 case Builtin::BI__builtin_stdc_first_trailing_zero:
17068 case Builtin::BI__builtin_stdc_first_trailing_one:
17069 case Builtin::BI__builtin_stdc_count_zeros:
17070 case Builtin::BI__builtin_stdc_count_ones:
17071 case Builtin::BI__builtin_stdc_has_single_bit:
17072 case Builtin::BI__builtin_stdc_bit_width:
17073 case Builtin::BI__builtin_stdc_bit_floor:
17074 case Builtin::BI__builtin_stdc_bit_ceil: {
17075 APSInt Val;
17076 if (!EvaluateInteger(E->getArg(0), Val, Info))
17077 return false;
17078
17079 unsigned BitWidth = Val.getBitWidth();
17080 const unsigned ResBitWidth = Info.Ctx.getIntWidth(E->getType());
17081
17082 switch (BuiltinOp) {
17083 case Builtin::BIstdc_leading_zeros_uc:
17084 case Builtin::BIstdc_leading_zeros_us:
17085 case Builtin::BIstdc_leading_zeros_ui:
17086 case Builtin::BIstdc_leading_zeros_ul:
17087 case Builtin::BIstdc_leading_zeros_ull:
17088 case Builtin::BI__builtin_stdc_leading_zeros:
17089 return Success(APInt(ResBitWidth, Val.countl_zero()), E);
17090 case Builtin::BIstdc_leading_ones_uc:
17091 case Builtin::BIstdc_leading_ones_us:
17092 case Builtin::BIstdc_leading_ones_ui:
17093 case Builtin::BIstdc_leading_ones_ul:
17094 case Builtin::BIstdc_leading_ones_ull:
17095 case Builtin::BI__builtin_stdc_leading_ones:
17096 return Success(APInt(ResBitWidth, Val.countl_one()), E);
17097 case Builtin::BIstdc_trailing_zeros_uc:
17098 case Builtin::BIstdc_trailing_zeros_us:
17099 case Builtin::BIstdc_trailing_zeros_ui:
17100 case Builtin::BIstdc_trailing_zeros_ul:
17101 case Builtin::BIstdc_trailing_zeros_ull:
17102 case Builtin::BI__builtin_stdc_trailing_zeros:
17103 return Success(APInt(ResBitWidth, Val.countr_zero()), E);
17104 case Builtin::BIstdc_trailing_ones_uc:
17105 case Builtin::BIstdc_trailing_ones_us:
17106 case Builtin::BIstdc_trailing_ones_ui:
17107 case Builtin::BIstdc_trailing_ones_ul:
17108 case Builtin::BIstdc_trailing_ones_ull:
17109 case Builtin::BI__builtin_stdc_trailing_ones:
17110 return Success(APInt(ResBitWidth, Val.countr_one()), E);
17111 case Builtin::BIstdc_first_leading_zero_uc:
17112 case Builtin::BIstdc_first_leading_zero_us:
17113 case Builtin::BIstdc_first_leading_zero_ui:
17114 case Builtin::BIstdc_first_leading_zero_ul:
17115 case Builtin::BIstdc_first_leading_zero_ull:
17116 case Builtin::BI__builtin_stdc_first_leading_zero:
17117 return Success(
17118 APInt(ResBitWidth, Val.isAllOnes() ? 0 : Val.countl_one() + 1), E);
17119 case Builtin::BIstdc_first_leading_one_uc:
17120 case Builtin::BIstdc_first_leading_one_us:
17121 case Builtin::BIstdc_first_leading_one_ui:
17122 case Builtin::BIstdc_first_leading_one_ul:
17123 case Builtin::BIstdc_first_leading_one_ull:
17124 case Builtin::BI__builtin_stdc_first_leading_one:
17125 return Success(
17126 APInt(ResBitWidth, Val.isZero() ? 0 : Val.countl_zero() + 1), E);
17127 case Builtin::BIstdc_first_trailing_zero_uc:
17128 case Builtin::BIstdc_first_trailing_zero_us:
17129 case Builtin::BIstdc_first_trailing_zero_ui:
17130 case Builtin::BIstdc_first_trailing_zero_ul:
17131 case Builtin::BIstdc_first_trailing_zero_ull:
17132 case Builtin::BI__builtin_stdc_first_trailing_zero:
17133 return Success(
17134 APInt(ResBitWidth, Val.isAllOnes() ? 0 : Val.countr_one() + 1), E);
17135 case Builtin::BIstdc_first_trailing_one_uc:
17136 case Builtin::BIstdc_first_trailing_one_us:
17137 case Builtin::BIstdc_first_trailing_one_ui:
17138 case Builtin::BIstdc_first_trailing_one_ul:
17139 case Builtin::BIstdc_first_trailing_one_ull:
17140 case Builtin::BI__builtin_stdc_first_trailing_one:
17141 return Success(
17142 APInt(ResBitWidth, Val.isZero() ? 0 : Val.countr_zero() + 1), E);
17143 case Builtin::BIstdc_count_zeros_uc:
17144 case Builtin::BIstdc_count_zeros_us:
17145 case Builtin::BIstdc_count_zeros_ui:
17146 case Builtin::BIstdc_count_zeros_ul:
17147 case Builtin::BIstdc_count_zeros_ull:
17148 case Builtin::BI__builtin_stdc_count_zeros: {
17149 APInt Cnt(ResBitWidth, BitWidth - Val.popcount());
17150 return Success(APSInt(Cnt, /*IsUnsigned*/ true), E);
17151 }
17152 case Builtin::BIstdc_count_ones_uc:
17153 case Builtin::BIstdc_count_ones_us:
17154 case Builtin::BIstdc_count_ones_ui:
17155 case Builtin::BIstdc_count_ones_ul:
17156 case Builtin::BIstdc_count_ones_ull:
17157 case Builtin::BI__builtin_stdc_count_ones: {
17158 APInt Cnt(ResBitWidth, Val.popcount());
17159 return Success(APSInt(Cnt, /*IsUnsigned*/ true), E);
17160 }
17161 case Builtin::BIstdc_has_single_bit_uc:
17162 case Builtin::BIstdc_has_single_bit_us:
17163 case Builtin::BIstdc_has_single_bit_ui:
17164 case Builtin::BIstdc_has_single_bit_ul:
17165 case Builtin::BIstdc_has_single_bit_ull:
17166 case Builtin::BI__builtin_stdc_has_single_bit: {
17167 APInt Res(ResBitWidth, Val.popcount() == 1 ? 1 : 0);
17168 return Success(APSInt(Res, /*IsUnsigned*/ true), E);
17169 }
17170 case Builtin::BIstdc_bit_width_uc:
17171 case Builtin::BIstdc_bit_width_us:
17172 case Builtin::BIstdc_bit_width_ui:
17173 case Builtin::BIstdc_bit_width_ul:
17174 case Builtin::BIstdc_bit_width_ull:
17175 case Builtin::BI__builtin_stdc_bit_width:
17176 return Success(APInt(ResBitWidth, BitWidth - Val.countl_zero()), E);
17177 case Builtin::BIstdc_bit_floor_uc:
17178 case Builtin::BIstdc_bit_floor_us:
17179 case Builtin::BIstdc_bit_floor_ui:
17180 case Builtin::BIstdc_bit_floor_ul:
17181 case Builtin::BIstdc_bit_floor_ull:
17182 case Builtin::BI__builtin_stdc_bit_floor: {
17183 if (Val.isZero())
17184 return Success(APInt(BitWidth, 0), E);
17185 unsigned Exp = BitWidth - Val.countl_zero() - 1;
17186 return Success(
17187 APSInt(APInt::getOneBitSet(BitWidth, Exp), /*IsUnsigned*/ true), E);
17188 }
17189 case Builtin::BIstdc_bit_ceil_uc:
17190 case Builtin::BIstdc_bit_ceil_us:
17191 case Builtin::BIstdc_bit_ceil_ui:
17192 case Builtin::BIstdc_bit_ceil_ul:
17193 case Builtin::BIstdc_bit_ceil_ull:
17194 case Builtin::BI__builtin_stdc_bit_ceil: {
17195 if (Val.ule(1))
17196 return Success(APSInt(APInt(BitWidth, 1), /*IsUnsigned*/ true), E);
17197 APInt ValMinusOne = Val - 1;
17198 unsigned LZ = ValMinusOne.countl_zero();
17199 if (LZ == 0)
17200 return Success(APSInt(APInt(BitWidth, 0), /*IsUnsigned*/ true),
17201 E); // overflows; wrap to 0
17202 APInt Result = APInt::getOneBitSet(BitWidth, BitWidth - LZ);
17203 return Success(APSInt(Result, /*IsUnsigned*/ true), E);
17204 }
17205 default:
17206 llvm_unreachable("Unknown stdc builtin");
17207 }
17208 }
17209
17210 case Builtin::BI__builtin_elementwise_add_sat: {
17211 APSInt LHS, RHS;
17212 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
17213 !EvaluateInteger(E->getArg(1), RHS, Info))
17214 return false;
17215
17216 APInt Result = LHS.isSigned() ? LHS.sadd_sat(RHS) : LHS.uadd_sat(RHS);
17217 return Success(APSInt(Result, !LHS.isSigned()), E);
17218 }
17219 case Builtin::BI__builtin_elementwise_sub_sat: {
17220 APSInt LHS, RHS;
17221 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
17222 !EvaluateInteger(E->getArg(1), RHS, Info))
17223 return false;
17224
17225 APInt Result = LHS.isSigned() ? LHS.ssub_sat(RHS) : LHS.usub_sat(RHS);
17226 return Success(APSInt(Result, !LHS.isSigned()), E);
17227 }
17228 case Builtin::BI__builtin_elementwise_max: {
17229 APSInt LHS, RHS;
17230 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
17231 !EvaluateInteger(E->getArg(1), RHS, Info))
17232 return false;
17233
17234 APInt Result = std::max(LHS, RHS);
17235 return Success(APSInt(Result, !LHS.isSigned()), E);
17236 }
17237 case Builtin::BI__builtin_elementwise_min: {
17238 APSInt LHS, RHS;
17239 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
17240 !EvaluateInteger(E->getArg(1), RHS, Info))
17241 return false;
17242
17243 APInt Result = std::min(LHS, RHS);
17244 return Success(APSInt(Result, !LHS.isSigned()), E);
17245 }
17246 case Builtin::BI__builtin_elementwise_clmul: {
17247 APSInt LHS, RHS;
17248 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
17249 !EvaluateInteger(E->getArg(1), RHS, Info))
17250 return false;
17251
17252 APInt Result = llvm::APIntOps::clmul(LHS, RHS);
17253 return Success(APSInt(Result, LHS.isUnsigned()), E);
17254 }
17255 case Builtin::BI__builtin_elementwise_fshl:
17256 case Builtin::BI__builtin_elementwise_fshr: {
17257 APSInt Hi, Lo, Shift;
17258 if (!EvaluateInteger(E->getArg(0), Hi, Info) ||
17259 !EvaluateInteger(E->getArg(1), Lo, Info) ||
17260 !EvaluateInteger(E->getArg(2), Shift, Info))
17261 return false;
17262
17263 switch (BuiltinOp) {
17264 case Builtin::BI__builtin_elementwise_fshl: {
17265 APSInt Result(llvm::APIntOps::fshl(Hi, Lo, Shift), Hi.isUnsigned());
17266 return Success(Result, E);
17267 }
17268 case Builtin::BI__builtin_elementwise_fshr: {
17269 APSInt Result(llvm::APIntOps::fshr(Hi, Lo, Shift), Hi.isUnsigned());
17270 return Success(Result, E);
17271 }
17272 }
17273 llvm_unreachable("Fully covered switch above");
17274 }
17275 case Builtin::BIstrlen:
17276 case Builtin::BIwcslen:
17277 // A call to strlen is not a constant expression.
17278 if (Info.getLangOpts().CPlusPlus11)
17279 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
17280 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
17281 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
17282 else
17283 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
17284 [[fallthrough]];
17285 case Builtin::BI__builtin_strlen:
17286 case Builtin::BI__builtin_wcslen: {
17287 // As an extension, we support __builtin_strlen() as a constant expression,
17288 // and support folding strlen() to a constant.
17289 if (std::optional<uint64_t> StrLen =
17290 EvaluateBuiltinStrLen(E->getArg(0), Info))
17291 return Success(*StrLen, E);
17292 return false;
17293 }
17294
17295 case Builtin::BIstrcmp:
17296 case Builtin::BIwcscmp:
17297 case Builtin::BIstrncmp:
17298 case Builtin::BIwcsncmp:
17299 case Builtin::BImemcmp:
17300 case Builtin::BIbcmp:
17301 case Builtin::BIwmemcmp:
17302 // A call to strlen is not a constant expression.
17303 if (Info.getLangOpts().CPlusPlus11)
17304 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
17305 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
17306 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
17307 else
17308 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
17309 [[fallthrough]];
17310 case Builtin::BI__builtin_strcmp:
17311 case Builtin::BI__builtin_wcscmp:
17312 case Builtin::BI__builtin_strncmp:
17313 case Builtin::BI__builtin_wcsncmp:
17314 case Builtin::BI__builtin_memcmp:
17315 case Builtin::BI__builtin_bcmp:
17316 case Builtin::BI__builtin_wmemcmp: {
17317 LValue String1, String2;
17318 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
17319 !EvaluatePointer(E->getArg(1), String2, Info))
17320 return false;
17321
17322 uint64_t MaxLength = uint64_t(-1);
17323 if (BuiltinOp != Builtin::BIstrcmp &&
17324 BuiltinOp != Builtin::BIwcscmp &&
17325 BuiltinOp != Builtin::BI__builtin_strcmp &&
17326 BuiltinOp != Builtin::BI__builtin_wcscmp) {
17327 APSInt N;
17328 if (!EvaluateInteger(E->getArg(2), N, Info))
17329 return false;
17330 MaxLength = N.getZExtValue();
17331 }
17332
17333 // Empty substrings compare equal by definition.
17334 if (MaxLength == 0u)
17335 return Success(0, E);
17336
17337 if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
17338 !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
17339 String1.Designator.Invalid || String2.Designator.Invalid)
17340 return false;
17341
17342 QualType CharTy1 = String1.Designator.getType(Info.Ctx);
17343 QualType CharTy2 = String2.Designator.getType(Info.Ctx);
17344
17345 bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
17346 BuiltinOp == Builtin::BIbcmp ||
17347 BuiltinOp == Builtin::BI__builtin_memcmp ||
17348 BuiltinOp == Builtin::BI__builtin_bcmp;
17349
17350 assert(IsRawByte ||
17351 (Info.Ctx.hasSameUnqualifiedType(
17352 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
17353 Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
17354
17355 // For memcmp, allow comparing any arrays of '[[un]signed] char' or
17356 // 'char8_t', but no other types.
17357 if (IsRawByte &&
17358 !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) {
17359 // FIXME: Consider using our bit_cast implementation to support this.
17360 Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported)
17361 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp) << CharTy1
17362 << CharTy2;
17363 return false;
17364 }
17365
17366 const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
17367 return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
17368 handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
17369 Char1.isInt() && Char2.isInt();
17370 };
17371 const auto &AdvanceElems = [&] {
17372 return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
17373 HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
17374 };
17375
17376 bool StopAtNull =
17377 (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
17378 BuiltinOp != Builtin::BIwmemcmp &&
17379 BuiltinOp != Builtin::BI__builtin_memcmp &&
17380 BuiltinOp != Builtin::BI__builtin_bcmp &&
17381 BuiltinOp != Builtin::BI__builtin_wmemcmp);
17382 bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
17383 BuiltinOp == Builtin::BIwcsncmp ||
17384 BuiltinOp == Builtin::BIwmemcmp ||
17385 BuiltinOp == Builtin::BI__builtin_wcscmp ||
17386 BuiltinOp == Builtin::BI__builtin_wcsncmp ||
17387 BuiltinOp == Builtin::BI__builtin_wmemcmp;
17388
17389 for (; MaxLength; --MaxLength) {
17390 APValue Char1, Char2;
17391 if (!ReadCurElems(Char1, Char2))
17392 return false;
17393 if (Char1.getInt().ne(Char2.getInt())) {
17394 if (IsWide) // wmemcmp compares with wchar_t signedness.
17395 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
17396 // memcmp always compares unsigned chars.
17397 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
17398 }
17399 if (StopAtNull && !Char1.getInt())
17400 return Success(0, E);
17401 assert(!(StopAtNull && !Char2.getInt()));
17402 if (!AdvanceElems())
17403 return false;
17404 }
17405 // We hit the strncmp / memcmp limit.
17406 return Success(0, E);
17407 }
17408
17409 case Builtin::BI__atomic_always_lock_free:
17410 case Builtin::BI__atomic_is_lock_free:
17411 case Builtin::BI__c11_atomic_is_lock_free: {
17412 APSInt SizeVal;
17413 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
17414 return false;
17415
17416 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
17417 // of two less than or equal to the maximum inline atomic width, we know it
17418 // is lock-free. If the size isn't a power of two, or greater than the
17419 // maximum alignment where we promote atomics, we know it is not lock-free
17420 // (at least not in the sense of atomic_is_lock_free). Otherwise,
17421 // the answer can only be determined at runtime; for example, 16-byte
17422 // atomics have lock-free implementations on some, but not all,
17423 // x86-64 processors.
17424
17425 // Check power-of-two.
17426 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
17427 if (Size.isPowerOfTwo()) {
17428 // Check against inlining width.
17429 unsigned InlineWidthBits =
17430 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
17431 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
17432 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
17433 Size == CharUnits::One())
17434 return Success(1, E);
17435
17436 // If the pointer argument can be evaluated to a compile-time constant
17437 // integer (or nullptr), check if that value is appropriately aligned.
17438 const Expr *PtrArg = E->getArg(1);
17439 Expr::EvalResult ExprResult;
17440 APSInt IntResult;
17441 if (PtrArg->EvaluateAsRValue(ExprResult, Info.Ctx) &&
17442 ExprResult.Val.toIntegralConstant(IntResult, PtrArg->getType(),
17443 Info.Ctx) &&
17444 IntResult.isAligned(Size.getAsAlign()))
17445 return Success(1, E);
17446
17447 // Otherwise, check if the type's alignment against Size.
17448 if (auto *ICE = dyn_cast<ImplicitCastExpr>(PtrArg)) {
17449 // Drop the potential implicit-cast to 'const volatile void*', getting
17450 // the underlying type.
17451 if (ICE->getCastKind() == CK_BitCast)
17452 PtrArg = ICE->getSubExpr();
17453 }
17454
17455 if (auto PtrTy = PtrArg->getType()->getAs<PointerType>()) {
17456 QualType PointeeType = PtrTy->getPointeeType();
17457 if (!PointeeType->isIncompleteType() &&
17458 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
17459 // OK, we will inline operations on this object.
17460 return Success(1, E);
17461 }
17462 }
17463 }
17464 }
17465
17466 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
17467 Success(0, E) : Error(E);
17468 }
17469 case Builtin::BI__builtin_addcb:
17470 case Builtin::BI__builtin_addcs:
17471 case Builtin::BI__builtin_addc:
17472 case Builtin::BI__builtin_addcl:
17473 case Builtin::BI__builtin_addcll:
17474 case Builtin::BI__builtin_subcb:
17475 case Builtin::BI__builtin_subcs:
17476 case Builtin::BI__builtin_subc:
17477 case Builtin::BI__builtin_subcl:
17478 case Builtin::BI__builtin_subcll: {
17479 LValue CarryOutLValue;
17480 APSInt LHS, RHS, CarryIn, CarryOut, Result;
17481 QualType ResultType = E->getArg(0)->getType();
17482 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
17483 !EvaluateInteger(E->getArg(1), RHS, Info) ||
17484 !EvaluateInteger(E->getArg(2), CarryIn, Info) ||
17485 !EvaluatePointer(E->getArg(3), CarryOutLValue, Info))
17486 return false;
17487 // Copy the number of bits and sign.
17488 Result = LHS;
17489 CarryOut = LHS;
17490
17491 bool FirstOverflowed = false;
17492 bool SecondOverflowed = false;
17493 switch (BuiltinOp) {
17494 default:
17495 llvm_unreachable("Invalid value for BuiltinOp");
17496 case Builtin::BI__builtin_addcb:
17497 case Builtin::BI__builtin_addcs:
17498 case Builtin::BI__builtin_addc:
17499 case Builtin::BI__builtin_addcl:
17500 case Builtin::BI__builtin_addcll:
17501 Result =
17502 LHS.uadd_ov(RHS, FirstOverflowed).uadd_ov(CarryIn, SecondOverflowed);
17503 break;
17504 case Builtin::BI__builtin_subcb:
17505 case Builtin::BI__builtin_subcs:
17506 case Builtin::BI__builtin_subc:
17507 case Builtin::BI__builtin_subcl:
17508 case Builtin::BI__builtin_subcll:
17509 Result =
17510 LHS.usub_ov(RHS, FirstOverflowed).usub_ov(CarryIn, SecondOverflowed);
17511 break;
17512 }
17513
17514 // It is possible for both overflows to happen but CGBuiltin uses an OR so
17515 // this is consistent.
17516 CarryOut = (uint64_t)(FirstOverflowed | SecondOverflowed);
17517 APValue APV{CarryOut};
17518 if (!handleAssignment(Info, E, CarryOutLValue, ResultType, APV))
17519 return false;
17520 return Success(Result, E);
17521 }
17522 case Builtin::BI__builtin_add_overflow:
17523 case Builtin::BI__builtin_sub_overflow:
17524 case Builtin::BI__builtin_mul_overflow:
17525 case Builtin::BI__builtin_sadd_overflow:
17526 case Builtin::BI__builtin_uadd_overflow:
17527 case Builtin::BI__builtin_uaddl_overflow:
17528 case Builtin::BI__builtin_uaddll_overflow:
17529 case Builtin::BI__builtin_usub_overflow:
17530 case Builtin::BI__builtin_usubl_overflow:
17531 case Builtin::BI__builtin_usubll_overflow:
17532 case Builtin::BI__builtin_umul_overflow:
17533 case Builtin::BI__builtin_umull_overflow:
17534 case Builtin::BI__builtin_umulll_overflow:
17535 case Builtin::BI__builtin_saddl_overflow:
17536 case Builtin::BI__builtin_saddll_overflow:
17537 case Builtin::BI__builtin_ssub_overflow:
17538 case Builtin::BI__builtin_ssubl_overflow:
17539 case Builtin::BI__builtin_ssubll_overflow:
17540 case Builtin::BI__builtin_smul_overflow:
17541 case Builtin::BI__builtin_smull_overflow:
17542 case Builtin::BI__builtin_smulll_overflow: {
17543 LValue ResultLValue;
17544 APSInt LHS, RHS;
17545
17546 QualType ResultType = E->getArg(2)->getType()->getPointeeType();
17547 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
17548 !EvaluateInteger(E->getArg(1), RHS, Info) ||
17549 !EvaluatePointer(E->getArg(2), ResultLValue, Info))
17550 return false;
17551
17552 APSInt Result;
17553 bool DidOverflow = false;
17554
17555 // If the types don't have to match, enlarge all 3 to the largest of them.
17556 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
17557 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
17558 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
17559 bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
17561 bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
17563 uint64_t LHSSize = LHS.getBitWidth();
17564 uint64_t RHSSize = RHS.getBitWidth();
17565 uint64_t ResultSize = Info.Ctx.getIntWidth(ResultType);
17566 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
17567
17568 // Add an additional bit if the signedness isn't uniformly agreed to. We
17569 // could do this ONLY if there is a signed and an unsigned that both have
17570 // MaxBits, but the code to check that is pretty nasty. The issue will be
17571 // caught in the shrink-to-result later anyway.
17572 if (IsSigned && !AllSigned)
17573 ++MaxBits;
17574
17575 LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
17576 RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
17577 Result = APSInt(MaxBits, !IsSigned);
17578 }
17579
17580 // Find largest int.
17581 switch (BuiltinOp) {
17582 default:
17583 llvm_unreachable("Invalid value for BuiltinOp");
17584 case Builtin::BI__builtin_add_overflow:
17585 case Builtin::BI__builtin_sadd_overflow:
17586 case Builtin::BI__builtin_saddl_overflow:
17587 case Builtin::BI__builtin_saddll_overflow:
17588 case Builtin::BI__builtin_uadd_overflow:
17589 case Builtin::BI__builtin_uaddl_overflow:
17590 case Builtin::BI__builtin_uaddll_overflow:
17591 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
17592 : LHS.uadd_ov(RHS, DidOverflow);
17593 break;
17594 case Builtin::BI__builtin_sub_overflow:
17595 case Builtin::BI__builtin_ssub_overflow:
17596 case Builtin::BI__builtin_ssubl_overflow:
17597 case Builtin::BI__builtin_ssubll_overflow:
17598 case Builtin::BI__builtin_usub_overflow:
17599 case Builtin::BI__builtin_usubl_overflow:
17600 case Builtin::BI__builtin_usubll_overflow:
17601 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
17602 : LHS.usub_ov(RHS, DidOverflow);
17603 break;
17604 case Builtin::BI__builtin_mul_overflow:
17605 case Builtin::BI__builtin_smul_overflow:
17606 case Builtin::BI__builtin_smull_overflow:
17607 case Builtin::BI__builtin_smulll_overflow:
17608 case Builtin::BI__builtin_umul_overflow:
17609 case Builtin::BI__builtin_umull_overflow:
17610 case Builtin::BI__builtin_umulll_overflow:
17611 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
17612 : LHS.umul_ov(RHS, DidOverflow);
17613 break;
17614 }
17615
17616 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
17617 // since it will give us the behavior of a TruncOrSelf in the case where
17618 // its parameter <= its size. We previously set Result to be at least the
17619 // integer width of the result, so getIntWidth(ResultType) <=
17620 // Result.BitWidth will work exactly like TruncOrSelf.
17621 APSInt Temp = Result.extOrTrunc(Info.Ctx.getIntWidth(ResultType));
17622 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
17623
17624 // In the case where multiple sizes are allowed, truncate and see if
17625 // the values are the same.
17626 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
17627 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
17628 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
17629 if (!APSInt::isSameValue(Temp, Result))
17630 DidOverflow = true;
17631 }
17632 Result = Temp;
17633
17634 APValue APV{Result};
17635 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
17636 return false;
17637 return Success(DidOverflow, E);
17638 }
17639
17640 case Builtin::BI__builtin_reduce_add:
17641 case Builtin::BI__builtin_reduce_mul:
17642 case Builtin::BI__builtin_reduce_and:
17643 case Builtin::BI__builtin_reduce_or:
17644 case Builtin::BI__builtin_reduce_xor:
17645 case Builtin::BI__builtin_reduce_min:
17646 case Builtin::BI__builtin_reduce_max: {
17647 APValue Source;
17648 if (!EvaluateAsRValue(Info, E->getArg(0), Source))
17649 return false;
17650
17651 unsigned SourceLen = Source.getVectorLength();
17652 APSInt Reduced = Source.getVectorElt(0).getInt();
17653 for (unsigned EltNum = 1; EltNum < SourceLen; ++EltNum) {
17654 switch (BuiltinOp) {
17655 default:
17656 return false;
17657 case Builtin::BI__builtin_reduce_add: {
17659 Info, E, Reduced, Source.getVectorElt(EltNum).getInt(),
17660 Reduced.getBitWidth() + 1, std::plus<APSInt>(), Reduced))
17661 return false;
17662 break;
17663 }
17664 case Builtin::BI__builtin_reduce_mul: {
17666 Info, E, Reduced, Source.getVectorElt(EltNum).getInt(),
17667 Reduced.getBitWidth() * 2, std::multiplies<APSInt>(), Reduced))
17668 return false;
17669 break;
17670 }
17671 case Builtin::BI__builtin_reduce_and: {
17672 Reduced &= Source.getVectorElt(EltNum).getInt();
17673 break;
17674 }
17675 case Builtin::BI__builtin_reduce_or: {
17676 Reduced |= Source.getVectorElt(EltNum).getInt();
17677 break;
17678 }
17679 case Builtin::BI__builtin_reduce_xor: {
17680 Reduced ^= Source.getVectorElt(EltNum).getInt();
17681 break;
17682 }
17683 case Builtin::BI__builtin_reduce_min: {
17684 Reduced = std::min(Reduced, Source.getVectorElt(EltNum).getInt());
17685 break;
17686 }
17687 case Builtin::BI__builtin_reduce_max: {
17688 Reduced = std::max(Reduced, Source.getVectorElt(EltNum).getInt());
17689 break;
17690 }
17691 }
17692 }
17693
17694 return Success(Reduced, E);
17695 }
17696
17697 case clang::X86::BI__builtin_ia32_addcarryx_u32:
17698 case clang::X86::BI__builtin_ia32_addcarryx_u64:
17699 case clang::X86::BI__builtin_ia32_subborrow_u32:
17700 case clang::X86::BI__builtin_ia32_subborrow_u64: {
17701 LValue ResultLValue;
17702 APSInt CarryIn, LHS, RHS;
17703 QualType ResultType = E->getArg(3)->getType()->getPointeeType();
17704 if (!EvaluateInteger(E->getArg(0), CarryIn, Info) ||
17705 !EvaluateInteger(E->getArg(1), LHS, Info) ||
17706 !EvaluateInteger(E->getArg(2), RHS, Info) ||
17707 !EvaluatePointer(E->getArg(3), ResultLValue, Info))
17708 return false;
17709
17710 bool IsAdd = BuiltinOp == clang::X86::BI__builtin_ia32_addcarryx_u32 ||
17711 BuiltinOp == clang::X86::BI__builtin_ia32_addcarryx_u64;
17712
17713 unsigned BitWidth = LHS.getBitWidth();
17714 unsigned CarryInBit = CarryIn.ugt(0) ? 1 : 0;
17715 APInt ExResult =
17716 IsAdd
17717 ? (LHS.zext(BitWidth + 1) + (RHS.zext(BitWidth + 1) + CarryInBit))
17718 : (LHS.zext(BitWidth + 1) - (RHS.zext(BitWidth + 1) + CarryInBit));
17719
17720 APInt Result = ExResult.extractBits(BitWidth, 0);
17721 uint64_t CarryOut = ExResult.extractBitsAsZExtValue(1, BitWidth);
17722
17723 APValue APV{APSInt(Result, /*isUnsigned=*/true)};
17724 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
17725 return false;
17726 return Success(CarryOut, E);
17727 }
17728
17729 case clang::X86::BI__builtin_ia32_movmskps:
17730 case clang::X86::BI__builtin_ia32_movmskpd:
17731 case clang::X86::BI__builtin_ia32_pmovmskb128:
17732 case clang::X86::BI__builtin_ia32_pmovmskb256:
17733 case clang::X86::BI__builtin_ia32_movmskps256:
17734 case clang::X86::BI__builtin_ia32_movmskpd256: {
17735 APValue Source;
17736 if (!Evaluate(Source, Info, E->getArg(0)))
17737 return false;
17738 unsigned SourceLen = Source.getVectorLength();
17739 const VectorType *VT = E->getArg(0)->getType()->castAs<VectorType>();
17740 QualType ElemQT = VT->getElementType();
17741 unsigned ResultLen = Info.Ctx.getTypeSize(
17742 E->getCallReturnType(Info.Ctx)); // Always 32-bit integer.
17743 APInt Result(ResultLen, 0);
17744
17745 for (unsigned I = 0; I != SourceLen; ++I) {
17746 APInt Elem;
17747 if (ElemQT->isIntegerType()) {
17748 Elem = Source.getVectorElt(I).getInt();
17749 } else if (ElemQT->isRealFloatingType()) {
17750 Elem = Source.getVectorElt(I).getFloat().bitcastToAPInt();
17751 } else {
17752 return false;
17753 }
17754 Result.setBitVal(I, Elem.isNegative());
17755 }
17756 return Success(Result, E);
17757 }
17758
17759 case clang::X86::BI__builtin_ia32_bextr_u32:
17760 case clang::X86::BI__builtin_ia32_bextr_u64:
17761 case clang::X86::BI__builtin_ia32_bextri_u32:
17762 case clang::X86::BI__builtin_ia32_bextri_u64: {
17763 APSInt Val, Idx;
17764 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
17765 !EvaluateInteger(E->getArg(1), Idx, Info))
17766 return false;
17767
17768 unsigned BitWidth = Val.getBitWidth();
17769 uint64_t Shift = Idx.extractBitsAsZExtValue(8, 0);
17770 uint64_t Length = Idx.extractBitsAsZExtValue(8, 8);
17771 Length = Length > BitWidth ? BitWidth : Length;
17772
17773 // Handle out of bounds cases.
17774 if (Length == 0 || Shift >= BitWidth)
17775 return Success(0, E);
17776
17777 uint64_t Result = Val.getZExtValue() >> Shift;
17778 Result &= llvm::maskTrailingOnes<uint64_t>(Length);
17779 return Success(Result, E);
17780 }
17781
17782 case clang::X86::BI__builtin_ia32_bzhi_si:
17783 case clang::X86::BI__builtin_ia32_bzhi_di: {
17784 APSInt Val, Idx;
17785 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
17786 !EvaluateInteger(E->getArg(1), Idx, Info))
17787 return false;
17788
17789 unsigned BitWidth = Val.getBitWidth();
17790 unsigned Index = Idx.extractBitsAsZExtValue(8, 0);
17791 if (Index < BitWidth)
17792 Val.clearHighBits(BitWidth - Index);
17793 return Success(Val, E);
17794 }
17795
17796 case clang::X86::BI__builtin_ia32_ktestcqi:
17797 case clang::X86::BI__builtin_ia32_ktestchi:
17798 case clang::X86::BI__builtin_ia32_ktestcsi:
17799 case clang::X86::BI__builtin_ia32_ktestcdi: {
17800 APSInt A, B;
17801 if (!EvaluateInteger(E->getArg(0), A, Info) ||
17802 !EvaluateInteger(E->getArg(1), B, Info))
17803 return false;
17804
17805 return Success((~A & B) == 0, E);
17806 }
17807
17808 case clang::X86::BI__builtin_ia32_ktestzqi:
17809 case clang::X86::BI__builtin_ia32_ktestzhi:
17810 case clang::X86::BI__builtin_ia32_ktestzsi:
17811 case clang::X86::BI__builtin_ia32_ktestzdi: {
17812 APSInt A, B;
17813 if (!EvaluateInteger(E->getArg(0), A, Info) ||
17814 !EvaluateInteger(E->getArg(1), B, Info))
17815 return false;
17816
17817 return Success((A & B) == 0, E);
17818 }
17819
17820 case clang::X86::BI__builtin_ia32_kortestcqi:
17821 case clang::X86::BI__builtin_ia32_kortestchi:
17822 case clang::X86::BI__builtin_ia32_kortestcsi:
17823 case clang::X86::BI__builtin_ia32_kortestcdi: {
17824 APSInt A, B;
17825 if (!EvaluateInteger(E->getArg(0), A, Info) ||
17826 !EvaluateInteger(E->getArg(1), B, Info))
17827 return false;
17828
17829 return Success(~(A | B) == 0, E);
17830 }
17831
17832 case clang::X86::BI__builtin_ia32_kortestzqi:
17833 case clang::X86::BI__builtin_ia32_kortestzhi:
17834 case clang::X86::BI__builtin_ia32_kortestzsi:
17835 case clang::X86::BI__builtin_ia32_kortestzdi: {
17836 APSInt A, B;
17837 if (!EvaluateInteger(E->getArg(0), A, Info) ||
17838 !EvaluateInteger(E->getArg(1), B, Info))
17839 return false;
17840
17841 return Success((A | B) == 0, E);
17842 }
17843
17844 case clang::X86::BI__builtin_ia32_kunpckhi:
17845 case clang::X86::BI__builtin_ia32_kunpckdi:
17846 case clang::X86::BI__builtin_ia32_kunpcksi: {
17847 APSInt A, B;
17848 if (!EvaluateInteger(E->getArg(0), A, Info) ||
17849 !EvaluateInteger(E->getArg(1), B, Info))
17850 return false;
17851
17852 // Generic kunpack: extract lower half of each operand and concatenate
17853 // Result = A[HalfWidth-1:0] concat B[HalfWidth-1:0]
17854 unsigned BW = A.getBitWidth();
17855 APSInt Result(A.trunc(BW / 2).concat(B.trunc(BW / 2)), A.isUnsigned());
17856 return Success(Result, E);
17857 }
17858
17859 case clang::X86::BI__builtin_ia32_lzcnt_u16:
17860 case clang::X86::BI__builtin_ia32_lzcnt_u32:
17861 case clang::X86::BI__builtin_ia32_lzcnt_u64: {
17862 APSInt Val;
17863 if (!EvaluateInteger(E->getArg(0), Val, Info))
17864 return false;
17865 return Success(Val.countLeadingZeros(), E);
17866 }
17867
17868 case clang::X86::BI__builtin_ia32_tzcnt_u16:
17869 case clang::X86::BI__builtin_ia32_tzcnt_u32:
17870 case clang::X86::BI__builtin_ia32_tzcnt_u64: {
17871 APSInt Val;
17872 if (!EvaluateInteger(E->getArg(0), Val, Info))
17873 return false;
17874 return Success(Val.countTrailingZeros(), E);
17875 }
17876
17877 case clang::X86::BI__builtin_ia32_pdep_si:
17878 case clang::X86::BI__builtin_ia32_pdep_di: {
17879 APSInt Val, Msk;
17880 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
17881 !EvaluateInteger(E->getArg(1), Msk, Info))
17882 return false;
17883 return Success(llvm::APIntOps::expandBits(Val, Msk), E);
17884 }
17885
17886 case clang::X86::BI__builtin_ia32_pext_si:
17887 case clang::X86::BI__builtin_ia32_pext_di: {
17888 APSInt Val, Msk;
17889 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
17890 !EvaluateInteger(E->getArg(1), Msk, Info))
17891 return false;
17892 return Success(llvm::APIntOps::compressBits(Val, Msk), E);
17893 }
17894 case X86::BI__builtin_ia32_ptestz128:
17895 case X86::BI__builtin_ia32_ptestz256:
17896 case X86::BI__builtin_ia32_vtestzps:
17897 case X86::BI__builtin_ia32_vtestzps256:
17898 case X86::BI__builtin_ia32_vtestzpd:
17899 case X86::BI__builtin_ia32_vtestzpd256: {
17900 return EvalTestOp(
17901 [](const APInt &A, const APInt &B) { return (A & B) == 0; });
17902 }
17903 case X86::BI__builtin_ia32_ptestc128:
17904 case X86::BI__builtin_ia32_ptestc256:
17905 case X86::BI__builtin_ia32_vtestcps:
17906 case X86::BI__builtin_ia32_vtestcps256:
17907 case X86::BI__builtin_ia32_vtestcpd:
17908 case X86::BI__builtin_ia32_vtestcpd256: {
17909 return EvalTestOp(
17910 [](const APInt &A, const APInt &B) { return (~A & B) == 0; });
17911 }
17912 case X86::BI__builtin_ia32_ptestnzc128:
17913 case X86::BI__builtin_ia32_ptestnzc256:
17914 case X86::BI__builtin_ia32_vtestnzcps:
17915 case X86::BI__builtin_ia32_vtestnzcps256:
17916 case X86::BI__builtin_ia32_vtestnzcpd:
17917 case X86::BI__builtin_ia32_vtestnzcpd256: {
17918 return EvalTestOp([](const APInt &A, const APInt &B) {
17919 return ((A & B) != 0) && ((~A & B) != 0);
17920 });
17921 }
17922 case X86::BI__builtin_ia32_kandqi:
17923 case X86::BI__builtin_ia32_kandhi:
17924 case X86::BI__builtin_ia32_kandsi:
17925 case X86::BI__builtin_ia32_kanddi: {
17926 return HandleMaskBinOp(
17927 [](const APSInt &LHS, const APSInt &RHS) { return LHS & RHS; });
17928 }
17929
17930 case X86::BI__builtin_ia32_kandnqi:
17931 case X86::BI__builtin_ia32_kandnhi:
17932 case X86::BI__builtin_ia32_kandnsi:
17933 case X86::BI__builtin_ia32_kandndi: {
17934 return HandleMaskBinOp(
17935 [](const APSInt &LHS, const APSInt &RHS) { return ~LHS & RHS; });
17936 }
17937
17938 case X86::BI__builtin_ia32_korqi:
17939 case X86::BI__builtin_ia32_korhi:
17940 case X86::BI__builtin_ia32_korsi:
17941 case X86::BI__builtin_ia32_kordi: {
17942 return HandleMaskBinOp(
17943 [](const APSInt &LHS, const APSInt &RHS) { return LHS | RHS; });
17944 }
17945
17946 case X86::BI__builtin_ia32_kxnorqi:
17947 case X86::BI__builtin_ia32_kxnorhi:
17948 case X86::BI__builtin_ia32_kxnorsi:
17949 case X86::BI__builtin_ia32_kxnordi: {
17950 return HandleMaskBinOp(
17951 [](const APSInt &LHS, const APSInt &RHS) { return ~(LHS ^ RHS); });
17952 }
17953
17954 case X86::BI__builtin_ia32_kxorqi:
17955 case X86::BI__builtin_ia32_kxorhi:
17956 case X86::BI__builtin_ia32_kxorsi:
17957 case X86::BI__builtin_ia32_kxordi: {
17958 return HandleMaskBinOp(
17959 [](const APSInt &LHS, const APSInt &RHS) { return LHS ^ RHS; });
17960 }
17961
17962 case X86::BI__builtin_ia32_knotqi:
17963 case X86::BI__builtin_ia32_knothi:
17964 case X86::BI__builtin_ia32_knotsi:
17965 case X86::BI__builtin_ia32_knotdi: {
17966 APSInt Val;
17967 if (!EvaluateInteger(E->getArg(0), Val, Info))
17968 return false;
17969 APSInt Result = ~Val;
17970 return Success(APValue(Result), E);
17971 }
17972
17973 case X86::BI__builtin_ia32_kaddqi:
17974 case X86::BI__builtin_ia32_kaddhi:
17975 case X86::BI__builtin_ia32_kaddsi:
17976 case X86::BI__builtin_ia32_kadddi: {
17977 return HandleMaskBinOp(
17978 [](const APSInt &LHS, const APSInt &RHS) { return LHS + RHS; });
17979 }
17980
17981 case X86::BI__builtin_ia32_kmovb:
17982 case X86::BI__builtin_ia32_kmovw:
17983 case X86::BI__builtin_ia32_kmovd:
17984 case X86::BI__builtin_ia32_kmovq: {
17985 APSInt Val;
17986 if (!EvaluateInteger(E->getArg(0), Val, Info))
17987 return false;
17988 return Success(Val, E);
17989 }
17990
17991 case X86::BI__builtin_ia32_kshiftliqi:
17992 case X86::BI__builtin_ia32_kshiftlihi:
17993 case X86::BI__builtin_ia32_kshiftlisi:
17994 case X86::BI__builtin_ia32_kshiftlidi: {
17995 return HandleMaskBinOp([](const APSInt &LHS, const APSInt &RHS) {
17996 unsigned Amt = RHS.getZExtValue() & 0xFF;
17997 if (Amt >= LHS.getBitWidth())
17998 return APSInt(APInt::getZero(LHS.getBitWidth()), LHS.isUnsigned());
17999 return APSInt(LHS.shl(Amt), LHS.isUnsigned());
18000 });
18001 }
18002
18003 case X86::BI__builtin_ia32_kshiftriqi:
18004 case X86::BI__builtin_ia32_kshiftrihi:
18005 case X86::BI__builtin_ia32_kshiftrisi:
18006 case X86::BI__builtin_ia32_kshiftridi: {
18007 return HandleMaskBinOp([](const APSInt &LHS, const APSInt &RHS) {
18008 unsigned Amt = RHS.getZExtValue() & 0xFF;
18009 if (Amt >= LHS.getBitWidth())
18010 return APSInt(APInt::getZero(LHS.getBitWidth()), LHS.isUnsigned());
18011 return APSInt(LHS.lshr(Amt), LHS.isUnsigned());
18012 });
18013 }
18014
18015 case clang::X86::BI__builtin_ia32_vec_ext_v4hi:
18016 case clang::X86::BI__builtin_ia32_vec_ext_v16qi:
18017 case clang::X86::BI__builtin_ia32_vec_ext_v8hi:
18018 case clang::X86::BI__builtin_ia32_vec_ext_v4si:
18019 case clang::X86::BI__builtin_ia32_vec_ext_v2di:
18020 case clang::X86::BI__builtin_ia32_vec_ext_v32qi:
18021 case clang::X86::BI__builtin_ia32_vec_ext_v16hi:
18022 case clang::X86::BI__builtin_ia32_vec_ext_v8si:
18023 case clang::X86::BI__builtin_ia32_vec_ext_v4di: {
18024 APValue Vec;
18025 APSInt IdxAPS;
18026 if (!EvaluateVector(E->getArg(0), Vec, Info) ||
18027 !EvaluateInteger(E->getArg(1), IdxAPS, Info))
18028 return false;
18029 unsigned N = Vec.getVectorLength();
18030 unsigned Idx = static_cast<unsigned>(IdxAPS.getZExtValue() & (N - 1));
18031 return Success(Vec.getVectorElt(Idx).getInt(), E);
18032 }
18033
18034 case clang::X86::BI__builtin_ia32_cvtb2mask128:
18035 case clang::X86::BI__builtin_ia32_cvtb2mask256:
18036 case clang::X86::BI__builtin_ia32_cvtb2mask512:
18037 case clang::X86::BI__builtin_ia32_cvtw2mask128:
18038 case clang::X86::BI__builtin_ia32_cvtw2mask256:
18039 case clang::X86::BI__builtin_ia32_cvtw2mask512:
18040 case clang::X86::BI__builtin_ia32_cvtd2mask128:
18041 case clang::X86::BI__builtin_ia32_cvtd2mask256:
18042 case clang::X86::BI__builtin_ia32_cvtd2mask512:
18043 case clang::X86::BI__builtin_ia32_cvtq2mask128:
18044 case clang::X86::BI__builtin_ia32_cvtq2mask256:
18045 case clang::X86::BI__builtin_ia32_cvtq2mask512: {
18046 assert(E->getNumArgs() == 1);
18047 APValue Vec;
18048 if (!EvaluateVector(E->getArg(0), Vec, Info))
18049 return false;
18050
18051 unsigned VectorLen = Vec.getVectorLength();
18052 unsigned RetWidth = Info.Ctx.getIntWidth(E->getType());
18053 llvm::APInt Bits(RetWidth, 0);
18054
18055 for (unsigned ElemNum = 0; ElemNum != VectorLen; ++ElemNum) {
18056 const APSInt &A = Vec.getVectorElt(ElemNum).getInt();
18057 unsigned MSB = A[A.getBitWidth() - 1];
18058 Bits.setBitVal(ElemNum, MSB);
18059 }
18060
18061 APSInt RetMask(Bits, /*isUnsigned=*/true);
18062 return Success(APValue(RetMask), E);
18063 }
18064
18065 case clang::X86::BI__builtin_ia32_cmpb128_mask:
18066 case clang::X86::BI__builtin_ia32_cmpw128_mask:
18067 case clang::X86::BI__builtin_ia32_cmpd128_mask:
18068 case clang::X86::BI__builtin_ia32_cmpq128_mask:
18069 case clang::X86::BI__builtin_ia32_cmpb256_mask:
18070 case clang::X86::BI__builtin_ia32_cmpw256_mask:
18071 case clang::X86::BI__builtin_ia32_cmpd256_mask:
18072 case clang::X86::BI__builtin_ia32_cmpq256_mask:
18073 case clang::X86::BI__builtin_ia32_cmpb512_mask:
18074 case clang::X86::BI__builtin_ia32_cmpw512_mask:
18075 case clang::X86::BI__builtin_ia32_cmpd512_mask:
18076 case clang::X86::BI__builtin_ia32_cmpq512_mask:
18077 case clang::X86::BI__builtin_ia32_ucmpb128_mask:
18078 case clang::X86::BI__builtin_ia32_ucmpw128_mask:
18079 case clang::X86::BI__builtin_ia32_ucmpd128_mask:
18080 case clang::X86::BI__builtin_ia32_ucmpq128_mask:
18081 case clang::X86::BI__builtin_ia32_ucmpb256_mask:
18082 case clang::X86::BI__builtin_ia32_ucmpw256_mask:
18083 case clang::X86::BI__builtin_ia32_ucmpd256_mask:
18084 case clang::X86::BI__builtin_ia32_ucmpq256_mask:
18085 case clang::X86::BI__builtin_ia32_ucmpb512_mask:
18086 case clang::X86::BI__builtin_ia32_ucmpw512_mask:
18087 case clang::X86::BI__builtin_ia32_ucmpd512_mask:
18088 case clang::X86::BI__builtin_ia32_ucmpq512_mask: {
18089 assert(E->getNumArgs() == 4);
18090
18091 bool IsUnsigned =
18092 (BuiltinOp >= clang::X86::BI__builtin_ia32_ucmpb128_mask &&
18093 BuiltinOp <= clang::X86::BI__builtin_ia32_ucmpw512_mask);
18094
18095 APValue LHS, RHS;
18096 APSInt Mask, Opcode;
18097 if (!EvaluateVector(E->getArg(0), LHS, Info) ||
18098 !EvaluateVector(E->getArg(1), RHS, Info) ||
18099 !EvaluateInteger(E->getArg(2), Opcode, Info) ||
18100 !EvaluateInteger(E->getArg(3), Mask, Info))
18101 return false;
18102
18103 assert(LHS.getVectorLength() == RHS.getVectorLength());
18104
18105 unsigned VectorLen = LHS.getVectorLength();
18106 unsigned RetWidth = Mask.getBitWidth();
18107
18108 APSInt RetMask(llvm::APInt(RetWidth, 0), /*isUnsigned=*/true);
18109
18110 for (unsigned ElemNum = 0; ElemNum < VectorLen; ++ElemNum) {
18111 const APSInt &A = LHS.getVectorElt(ElemNum).getInt();
18112 const APSInt &B = RHS.getVectorElt(ElemNum).getInt();
18113 bool Result = false;
18114
18115 switch (Opcode.getExtValue() & 0x7) {
18116 case 0: // _MM_CMPINT_EQ
18117 Result = (A == B);
18118 break;
18119 case 1: // _MM_CMPINT_LT
18120 Result = IsUnsigned ? A.ult(B) : A.slt(B);
18121 break;
18122 case 2: // _MM_CMPINT_LE
18123 Result = IsUnsigned ? A.ule(B) : A.sle(B);
18124 break;
18125 case 3: // _MM_CMPINT_FALSE
18126 Result = false;
18127 break;
18128 case 4: // _MM_CMPINT_NE
18129 Result = (A != B);
18130 break;
18131 case 5: // _MM_CMPINT_NLT (>=)
18132 Result = IsUnsigned ? A.uge(B) : A.sge(B);
18133 break;
18134 case 6: // _MM_CMPINT_NLE (>)
18135 Result = IsUnsigned ? A.ugt(B) : A.sgt(B);
18136 break;
18137 case 7: // _MM_CMPINT_TRUE
18138 Result = true;
18139 break;
18140 }
18141
18142 RetMask.setBitVal(ElemNum, Mask[ElemNum] && Result);
18143 }
18144
18145 return Success(APValue(RetMask), E);
18146 }
18147 case X86::BI__builtin_ia32_vpshufbitqmb128_mask:
18148 case X86::BI__builtin_ia32_vpshufbitqmb256_mask:
18149 case X86::BI__builtin_ia32_vpshufbitqmb512_mask: {
18150 assert(E->getNumArgs() == 3);
18151
18152 APValue Source, ShuffleMask;
18153 APSInt ZeroMask;
18154 if (!EvaluateVector(E->getArg(0), Source, Info) ||
18155 !EvaluateVector(E->getArg(1), ShuffleMask, Info) ||
18156 !EvaluateInteger(E->getArg(2), ZeroMask, Info))
18157 return false;
18158
18159 assert(Source.getVectorLength() == ShuffleMask.getVectorLength());
18160 assert(ZeroMask.getBitWidth() == Source.getVectorLength());
18161
18162 unsigned NumBytesInQWord = 8;
18163 unsigned NumBitsInByte = 8;
18164 unsigned NumBytes = Source.getVectorLength();
18165 unsigned NumQWords = NumBytes / NumBytesInQWord;
18166 unsigned RetWidth = ZeroMask.getBitWidth();
18167 APSInt RetMask(llvm::APInt(RetWidth, 0), /*isUnsigned=*/true);
18168
18169 for (unsigned QWordId = 0; QWordId != NumQWords; ++QWordId) {
18170 APInt SourceQWord(64, 0);
18171 for (unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
18172 uint64_t Byte = Source.getVectorElt(QWordId * NumBytesInQWord + ByteIdx)
18173 .getInt()
18174 .getZExtValue();
18175 SourceQWord.insertBits(APInt(8, Byte & 0xFF), ByteIdx * NumBitsInByte);
18176 }
18177
18178 for (unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
18179 unsigned SelIdx = QWordId * NumBytesInQWord + ByteIdx;
18180 unsigned M =
18181 ShuffleMask.getVectorElt(SelIdx).getInt().getZExtValue() & 0x3F;
18182 if (ZeroMask[SelIdx]) {
18183 RetMask.setBitVal(SelIdx, SourceQWord[M]);
18184 }
18185 }
18186 }
18187 return Success(APValue(RetMask), E);
18188 }
18189 }
18190}
18191
18192/// Determine whether this is a pointer past the end of the complete
18193/// object referred to by the lvalue.
18195 const LValue &LV) {
18196 // A null pointer can be viewed as being "past the end" but we don't
18197 // choose to look at it that way here.
18198 if (!LV.getLValueBase())
18199 return false;
18200
18201 // If the designator is valid and refers to a subobject, we're not pointing
18202 // past the end.
18203 if (!LV.getLValueDesignator().Invalid &&
18204 !LV.getLValueDesignator().isOnePastTheEnd())
18205 return false;
18206
18207 // A pointer to an incomplete type might be past-the-end if the type's size is
18208 // zero. We cannot tell because the type is incomplete.
18209 QualType Ty = getType(LV.getLValueBase());
18210 if (Ty->isIncompleteType())
18211 return true;
18212
18213 // Can't be past the end of an invalid object.
18214 if (LV.getLValueDesignator().Invalid)
18215 return false;
18216
18217 // We're a past-the-end pointer if we point to the byte after the object,
18218 // no matter what our type or path is.
18219 auto Size = Ctx.getTypeSizeInChars(Ty);
18220 return LV.getLValueOffset() == Size;
18221}
18222
18223namespace {
18224
18225/// Data recursive integer evaluator of certain binary operators.
18226///
18227/// We use a data recursive algorithm for binary operators so that we are able
18228/// to handle extreme cases of chained binary operators without causing stack
18229/// overflow.
18230class DataRecursiveIntBinOpEvaluator {
18231 struct EvalResult {
18232 APValue Val;
18233 bool Failed = false;
18234
18235 EvalResult() = default;
18236
18237 void swap(EvalResult &RHS) {
18238 Val.swap(RHS.Val);
18239 Failed = RHS.Failed;
18240 RHS.Failed = false;
18241 }
18242 };
18243
18244 struct Job {
18245 const Expr *E;
18246 EvalResult LHSResult; // meaningful only for binary operator expression.
18247 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
18248
18249 Job() = default;
18250 Job(Job &&) = default;
18251
18252 void startSpeculativeEval(EvalInfo &Info) {
18253 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
18254 }
18255
18256 private:
18257 SpeculativeEvaluationRAII SpecEvalRAII;
18258 };
18259
18260 SmallVector<Job, 16> Queue;
18261
18262 IntExprEvaluator &IntEval;
18263 EvalInfo &Info;
18264 APValue &FinalResult;
18265
18266public:
18267 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
18268 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
18269
18270 /// True if \param E is a binary operator that we are going to handle
18271 /// data recursively.
18272 /// We handle binary operators that are comma, logical, or that have operands
18273 /// with integral or enumeration type.
18274 static bool shouldEnqueue(const BinaryOperator *E) {
18275 return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
18279 }
18280
18281 bool Traverse(const BinaryOperator *E) {
18282 enqueue(E);
18283 EvalResult PrevResult;
18284 while (!Queue.empty())
18285 process(PrevResult);
18286
18287 if (PrevResult.Failed) return false;
18288
18289 FinalResult.swap(PrevResult.Val);
18290 return true;
18291 }
18292
18293private:
18294 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
18295 return IntEval.Success(Value, E, Result);
18296 }
18297 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
18298 return IntEval.Success(Value, E, Result);
18299 }
18300 bool Error(const Expr *E) {
18301 return IntEval.Error(E);
18302 }
18303 bool Error(const Expr *E, diag::kind D) {
18304 return IntEval.Error(E, D);
18305 }
18306
18307 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
18308 return Info.CCEDiag(E, D);
18309 }
18310
18311 // Returns true if visiting the RHS is necessary, false otherwise.
18312 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
18313 bool &SuppressRHSDiags);
18314
18315 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
18316 const BinaryOperator *E, APValue &Result);
18317
18318 void EvaluateExpr(const Expr *E, EvalResult &Result) {
18319 Result.Failed = !Evaluate(Result.Val, Info, E);
18320 if (Result.Failed)
18321 Result.Val = APValue();
18322 }
18323
18324 void process(EvalResult &Result);
18325
18326 void enqueue(const Expr *E) {
18327 E = E->IgnoreParens();
18328 Queue.resize(Queue.size()+1);
18329 Queue.back().E = E;
18330 Queue.back().Kind = Job::AnyExprKind;
18331 }
18332};
18333
18334}
18335
18336bool DataRecursiveIntBinOpEvaluator::
18337 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
18338 bool &SuppressRHSDiags) {
18339 if (E->getOpcode() == BO_Comma) {
18340 // Ignore LHS but note if we could not evaluate it.
18341 if (LHSResult.Failed)
18342 return Info.noteSideEffect();
18343 return true;
18344 }
18345
18346 if (E->isLogicalOp()) {
18347 bool LHSAsBool;
18348 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
18349 // We were able to evaluate the LHS, see if we can get away with not
18350 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
18351 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
18352 Success(LHSAsBool, E, LHSResult.Val);
18353 return false; // Ignore RHS
18354 }
18355 } else {
18356 LHSResult.Failed = true;
18357
18358 // Since we weren't able to evaluate the left hand side, it
18359 // might have had side effects.
18360 if (!Info.noteSideEffect())
18361 return false;
18362
18363 // We can't evaluate the LHS; however, sometimes the result
18364 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
18365 // Don't ignore RHS and suppress diagnostics from this arm.
18366 SuppressRHSDiags = true;
18367 }
18368
18369 return true;
18370 }
18371
18372 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
18374
18375 if (LHSResult.Failed && !Info.noteFailure())
18376 return false; // Ignore RHS;
18377
18378 return true;
18379}
18380
18381static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
18382 bool IsSub) {
18383 // Compute the new offset in the appropriate width, wrapping at 64 bits.
18384 // FIXME: When compiling for a 32-bit target, we should use 32-bit
18385 // offsets.
18386 assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
18387 CharUnits &Offset = LVal.getLValueOffset();
18388 uint64_t Offset64 = Offset.getQuantity();
18389 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
18390 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
18391 : Offset64 + Index64);
18392}
18393
18394bool DataRecursiveIntBinOpEvaluator::
18395 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
18396 const BinaryOperator *E, APValue &Result) {
18397 if (E->getOpcode() == BO_Comma) {
18398 if (RHSResult.Failed)
18399 return false;
18400 Result = RHSResult.Val;
18401 return true;
18402 }
18403
18404 if (E->isLogicalOp()) {
18405 bool lhsResult, rhsResult;
18406 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
18407 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
18408
18409 if (LHSIsOK) {
18410 if (RHSIsOK) {
18411 if (E->getOpcode() == BO_LOr)
18412 return Success(lhsResult || rhsResult, E, Result);
18413 else
18414 return Success(lhsResult && rhsResult, E, Result);
18415 }
18416 } else {
18417 if (RHSIsOK) {
18418 // We can't evaluate the LHS; however, sometimes the result
18419 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
18420 if (rhsResult == (E->getOpcode() == BO_LOr))
18421 return Success(rhsResult, E, Result);
18422 }
18423 }
18424
18425 return false;
18426 }
18427
18428 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
18430
18431 if (LHSResult.Failed || RHSResult.Failed)
18432 return false;
18433
18434 const APValue &LHSVal = LHSResult.Val;
18435 const APValue &RHSVal = RHSResult.Val;
18436
18437 // Handle cases like (unsigned long)&a + 4.
18438 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
18439 Result = LHSVal;
18440 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
18441 return true;
18442 }
18443
18444 // Handle cases like 4 + (unsigned long)&a
18445 if (E->getOpcode() == BO_Add &&
18446 RHSVal.isLValue() && LHSVal.isInt()) {
18447 Result = RHSVal;
18448 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
18449 return true;
18450 }
18451
18452 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
18453 // Handle (intptr_t)&&A - (intptr_t)&&B.
18454 if (!LHSVal.getLValueOffset().isZero() ||
18455 !RHSVal.getLValueOffset().isZero())
18456 return false;
18457 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
18458 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
18459 if (!LHSExpr || !RHSExpr)
18460 return false;
18461 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
18462 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
18463 if (!LHSAddrExpr || !RHSAddrExpr)
18464 return false;
18465 // Make sure both labels come from the same function.
18466 if (LHSAddrExpr->getLabel()->getDeclContext() !=
18467 RHSAddrExpr->getLabel()->getDeclContext())
18468 return false;
18469 Result = APValue(LHSAddrExpr, RHSAddrExpr);
18470 return true;
18471 }
18472
18473 // All the remaining cases expect both operands to be an integer
18474 if (!LHSVal.isInt() || !RHSVal.isInt())
18475 return Error(E);
18476
18477 // Set up the width and signedness manually, in case it can't be deduced
18478 // from the operation we're performing.
18479 // FIXME: Don't do this in the cases where we can deduce it.
18480 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
18482 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
18483 RHSVal.getInt(), Value))
18484 return false;
18485 return Success(Value, E, Result);
18486}
18487
18488void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
18489 Job &job = Queue.back();
18490
18491 switch (job.Kind) {
18492 case Job::AnyExprKind: {
18493 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
18494 if (shouldEnqueue(Bop)) {
18495 job.Kind = Job::BinOpKind;
18496 enqueue(Bop->getLHS());
18497 return;
18498 }
18499 }
18500
18501 EvaluateExpr(job.E, Result);
18502 Queue.pop_back();
18503 return;
18504 }
18505
18506 case Job::BinOpKind: {
18507 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
18508 bool SuppressRHSDiags = false;
18509 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
18510 Queue.pop_back();
18511 return;
18512 }
18513 if (SuppressRHSDiags)
18514 job.startSpeculativeEval(Info);
18515 job.LHSResult.swap(Result);
18516 job.Kind = Job::BinOpVisitedLHSKind;
18517 enqueue(Bop->getRHS());
18518 return;
18519 }
18520
18521 case Job::BinOpVisitedLHSKind: {
18522 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
18523 EvalResult RHS;
18524 RHS.swap(Result);
18525 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
18526 Queue.pop_back();
18527 return;
18528 }
18529 }
18530
18531 llvm_unreachable("Invalid Job::Kind!");
18532}
18533
18534namespace {
18535enum class CmpResult {
18536 Unequal,
18537 Less,
18538 Equal,
18539 Greater,
18540 Unordered,
18541};
18542}
18543
18544template <class SuccessCB, class AfterCB>
18545static bool
18547 SuccessCB &&Success, AfterCB &&DoAfter) {
18548 assert(!E->isValueDependent());
18549 assert(E->isComparisonOp() && "expected comparison operator");
18550 assert((E->getOpcode() == BO_Cmp ||
18552 "unsupported binary expression evaluation");
18553 auto Error = [&](const Expr *E) {
18554 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
18555 return false;
18556 };
18557
18558 bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp;
18559 bool IsEquality = E->isEqualityOp();
18560
18561 QualType LHSTy = E->getLHS()->getType();
18562 QualType RHSTy = E->getRHS()->getType();
18563
18564 if (LHSTy->isIntegralOrEnumerationType() &&
18565 RHSTy->isIntegralOrEnumerationType()) {
18566 APSInt LHS, RHS;
18567 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
18568 if (!LHSOK && !Info.noteFailure())
18569 return false;
18570 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
18571 return false;
18572 if (LHS < RHS)
18573 return Success(CmpResult::Less, E);
18574 if (LHS > RHS)
18575 return Success(CmpResult::Greater, E);
18576 return Success(CmpResult::Equal, E);
18577 }
18578
18579 if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
18580 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
18581 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
18582
18583 bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
18584 if (!LHSOK && !Info.noteFailure())
18585 return false;
18586 if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
18587 return false;
18588 if (LHSFX < RHSFX)
18589 return Success(CmpResult::Less, E);
18590 if (LHSFX > RHSFX)
18591 return Success(CmpResult::Greater, E);
18592 return Success(CmpResult::Equal, E);
18593 }
18594
18595 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
18596 ComplexValue LHS, RHS;
18597 bool LHSOK;
18598 if (E->isAssignmentOp()) {
18599 LValue LV;
18600 EvaluateLValue(E->getLHS(), LV, Info);
18601 LHSOK = false;
18602 } else if (LHSTy->isRealFloatingType()) {
18603 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
18604 if (LHSOK) {
18605 LHS.makeComplexFloat();
18606 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
18607 }
18608 } else {
18609 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
18610 }
18611 if (!LHSOK && !Info.noteFailure())
18612 return false;
18613
18614 if (E->getRHS()->getType()->isRealFloatingType()) {
18615 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
18616 return false;
18617 RHS.makeComplexFloat();
18618 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
18619 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
18620 return false;
18621
18622 if (LHS.isComplexFloat()) {
18623 APFloat::cmpResult CR_r =
18624 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
18625 APFloat::cmpResult CR_i =
18626 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
18627 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
18628 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
18629 } else {
18630 assert(IsEquality && "invalid complex comparison");
18631 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
18632 LHS.getComplexIntImag() == RHS.getComplexIntImag();
18633 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
18634 }
18635 }
18636
18637 if (LHSTy->isRealFloatingType() &&
18638 RHSTy->isRealFloatingType()) {
18639 APFloat RHS(0.0), LHS(0.0);
18640
18641 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
18642 if (!LHSOK && !Info.noteFailure())
18643 return false;
18644
18645 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
18646 return false;
18647
18648 assert(E->isComparisonOp() && "Invalid binary operator!");
18649 llvm::APFloatBase::cmpResult APFloatCmpResult = LHS.compare(RHS);
18650 if (!Info.InConstantContext &&
18651 APFloatCmpResult == APFloat::cmpUnordered &&
18652 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained()) {
18653 // Note: Compares may raise invalid in some cases involving NaN or sNaN.
18654 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
18655 return false;
18656 }
18657 auto GetCmpRes = [&]() {
18658 switch (APFloatCmpResult) {
18659 case APFloat::cmpEqual:
18660 return CmpResult::Equal;
18661 case APFloat::cmpLessThan:
18662 return CmpResult::Less;
18663 case APFloat::cmpGreaterThan:
18664 return CmpResult::Greater;
18665 case APFloat::cmpUnordered:
18666 return CmpResult::Unordered;
18667 }
18668 llvm_unreachable("Unrecognised APFloat::cmpResult enum");
18669 };
18670 return Success(GetCmpRes(), E);
18671 }
18672
18673 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
18674 LValue LHSValue, RHSValue;
18675
18676 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
18677 if (!LHSOK && !Info.noteFailure())
18678 return false;
18679
18680 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
18681 return false;
18682
18683 // Reject differing bases from the normal codepath; we special-case
18684 // comparisons to null.
18685 if (!HasSameBase(LHSValue, RHSValue)) {
18686 // Bail out early if we're checking potential constant expression.
18687 // Otherwise, prefer to diagnose other issues.
18688 if (Info.checkingPotentialConstantExpression() &&
18689 (LHSValue.AllowConstexprUnknown || RHSValue.AllowConstexprUnknown))
18690 return false;
18691 auto DiagComparison = [&] (unsigned DiagID, bool Reversed = false) {
18692 std::string LHS = LHSValue.toString(Info.Ctx, E->getLHS()->getType());
18693 std::string RHS = RHSValue.toString(Info.Ctx, E->getRHS()->getType());
18694 Info.FFDiag(E, DiagID)
18695 << (Reversed ? RHS : LHS) << (Reversed ? LHS : RHS);
18696 return false;
18697 };
18698 // Inequalities and subtractions between unrelated pointers have
18699 // unspecified or undefined behavior.
18700 if (!IsEquality)
18701 return DiagComparison(
18702 diag::note_constexpr_pointer_comparison_unspecified);
18703 // A constant address may compare equal to the address of a symbol.
18704 // The one exception is that address of an object cannot compare equal
18705 // to a null pointer constant.
18706 // TODO: Should we restrict this to actual null pointers, and exclude the
18707 // case of zero cast to pointer type?
18708 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
18709 (!RHSValue.Base && !RHSValue.Offset.isZero()))
18710 return DiagComparison(diag::note_constexpr_pointer_constant_comparison,
18711 !RHSValue.Base);
18712 // C++2c [intro.object]/10:
18713 // Two objects [...] may have the same address if [...] they are both
18714 // potentially non-unique objects.
18715 // C++2c [intro.object]/9:
18716 // An object is potentially non-unique if it is a string literal object,
18717 // the backing array of an initializer list, or a subobject thereof.
18718 //
18719 // This makes the comparison result unspecified, so it's not a constant
18720 // expression.
18721 //
18722 // TODO: Do we need to handle the initializer list case here?
18723 if (ArePotentiallyOverlappingStringLiterals(Info, LHSValue, RHSValue))
18724 return DiagComparison(diag::note_constexpr_literal_comparison);
18725 if (IsOpaqueConstantCall(LHSValue) || IsOpaqueConstantCall(RHSValue))
18726 return DiagComparison(diag::note_constexpr_opaque_call_comparison,
18727 !IsOpaqueConstantCall(LHSValue));
18728 // We can't tell whether weak symbols will end up pointing to the same
18729 // object.
18730 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
18731 return DiagComparison(diag::note_constexpr_pointer_weak_comparison,
18732 !IsWeakLValue(LHSValue));
18733 // We can't compare the address of the start of one object with the
18734 // past-the-end address of another object, per C++ DR1652.
18735 if (LHSValue.Base && LHSValue.Offset.isZero() &&
18736 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue))
18737 return DiagComparison(diag::note_constexpr_pointer_comparison_past_end,
18738 true);
18739 if (RHSValue.Base && RHSValue.Offset.isZero() &&
18740 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue))
18741 return DiagComparison(diag::note_constexpr_pointer_comparison_past_end,
18742 false);
18743 // We can't tell whether an object is at the same address as another
18744 // zero sized object.
18745 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
18746 (LHSValue.Base && isZeroSized(RHSValue)))
18747 return DiagComparison(
18748 diag::note_constexpr_pointer_comparison_zero_sized);
18749 if (LHSValue.AllowConstexprUnknown || RHSValue.AllowConstexprUnknown)
18750 return DiagComparison(
18751 diag::note_constexpr_pointer_comparison_unspecified);
18752 // FIXME: Verify both variables are live.
18753 return Success(CmpResult::Unequal, E);
18754 }
18755
18756 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
18757 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
18758
18759 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
18760 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
18761
18762 // C++11 [expr.rel]p2:
18763 // - If two pointers point to non-static data members of the same object,
18764 // or to subobjects or array elements fo such members, recursively, the
18765 // pointer to the later declared member compares greater provided the
18766 // two members have the same access control and provided their class is
18767 // not a union.
18768 // [...]
18769 // - Otherwise pointer comparisons are unspecified.
18770 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
18771 bool WasArrayIndex;
18772 unsigned Mismatch = FindDesignatorMismatch(
18773 LHSValue.Base.isNull() ? QualType()
18774 : getType(LHSValue.Base).getNonReferenceType(),
18775 LHSDesignator, RHSDesignator, WasArrayIndex);
18776 // At the point where the designators diverge, the comparison has a
18777 // specified value if:
18778 // - we are comparing array indices
18779 // - we are comparing fields of a union, or fields with the same access
18780 // Otherwise, the result is unspecified and thus the comparison is not a
18781 // constant expression.
18782 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
18783 Mismatch < RHSDesignator.Entries.size()) {
18784 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
18785 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
18786 if (!LF && !RF)
18787 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
18788 else if (!LF)
18789 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
18790 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
18791 << RF->getParent() << RF;
18792 else if (!RF)
18793 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
18794 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
18795 << LF->getParent() << LF;
18796 else if (!LF->getParent()->isUnion() &&
18797 LF->getAccess() != RF->getAccess())
18798 Info.CCEDiag(E,
18799 diag::note_constexpr_pointer_comparison_differing_access)
18800 << LF << LF->getAccess() << RF << RF->getAccess()
18801 << LF->getParent();
18802 }
18803 }
18804
18805 // The comparison here must be unsigned, and performed with the same
18806 // width as the pointer.
18807 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
18808 uint64_t CompareLHS = LHSOffset.getQuantity();
18809 uint64_t CompareRHS = RHSOffset.getQuantity();
18810 assert(PtrSize <= 64 && "Unexpected pointer width");
18811 uint64_t Mask = ~0ULL >> (64 - PtrSize);
18812 CompareLHS &= Mask;
18813 CompareRHS &= Mask;
18814
18815 // If there is a base and this is a relational operator, we can only
18816 // compare pointers within the object in question; otherwise, the result
18817 // depends on where the object is located in memory.
18818 if (!LHSValue.Base.isNull() && IsRelational) {
18819 QualType BaseTy = getType(LHSValue.Base).getNonReferenceType();
18820 if (BaseTy->isIncompleteType())
18821 return Error(E);
18822 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
18823 uint64_t OffsetLimit = Size.getQuantity();
18824 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
18825 return Error(E);
18826 }
18827
18828 if (CompareLHS < CompareRHS)
18829 return Success(CmpResult::Less, E);
18830 if (CompareLHS > CompareRHS)
18831 return Success(CmpResult::Greater, E);
18832 return Success(CmpResult::Equal, E);
18833 }
18834
18835 if (LHSTy->isMemberPointerType()) {
18836 assert(IsEquality && "unexpected member pointer operation");
18837 assert(RHSTy->isMemberPointerType() && "invalid comparison");
18838
18839 MemberPtr LHSValue, RHSValue;
18840
18841 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
18842 if (!LHSOK && !Info.noteFailure())
18843 return false;
18844
18845 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
18846 return false;
18847
18848 // If either operand is a pointer to a weak function, the comparison is not
18849 // constant.
18850 if (LHSValue.getDecl() && LHSValue.getDecl()->isWeak()) {
18851 Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison)
18852 << LHSValue.getDecl();
18853 return false;
18854 }
18855 if (RHSValue.getDecl() && RHSValue.getDecl()->isWeak()) {
18856 Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison)
18857 << RHSValue.getDecl();
18858 return false;
18859 }
18860
18861 // C++11 [expr.eq]p2:
18862 // If both operands are null, they compare equal. Otherwise if only one is
18863 // null, they compare unequal.
18864 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
18865 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
18866 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
18867 }
18868
18869 // Otherwise if either is a pointer to a virtual member function, the
18870 // result is unspecified.
18871 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
18872 if (MD->isVirtual())
18873 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
18874 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
18875 if (MD->isVirtual())
18876 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
18877
18878 // Otherwise they compare equal if and only if they would refer to the
18879 // same member of the same most derived object or the same subobject if
18880 // they were dereferenced with a hypothetical object of the associated
18881 // class type.
18882 bool Equal = LHSValue == RHSValue;
18883 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
18884 }
18885
18886 if (LHSTy->isNullPtrType()) {
18887 assert(E->isComparisonOp() && "unexpected nullptr operation");
18888 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
18889 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
18890 // are compared, the result is true of the operator is <=, >= or ==, and
18891 // false otherwise.
18892 LValue Res;
18893 if (!EvaluatePointer(E->getLHS(), Res, Info) ||
18894 !EvaluatePointer(E->getRHS(), Res, Info))
18895 return false;
18896 return Success(CmpResult::Equal, E);
18897 }
18898
18899 return DoAfter();
18900}
18901
18902bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
18903 if (!CheckLiteralType(Info, E))
18904 return false;
18905
18906 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
18908 switch (CR) {
18909 case CmpResult::Unequal:
18910 llvm_unreachable("should never produce Unequal for three-way comparison");
18911 case CmpResult::Less:
18912 CCR = ComparisonCategoryResult::Less;
18913 break;
18914 case CmpResult::Equal:
18915 CCR = ComparisonCategoryResult::Equal;
18916 break;
18917 case CmpResult::Greater:
18918 CCR = ComparisonCategoryResult::Greater;
18919 break;
18920 case CmpResult::Unordered:
18921 CCR = ComparisonCategoryResult::Unordered;
18922 break;
18923 }
18924 // Evaluation succeeded. Lookup the information for the comparison category
18925 // type and fetch the VarDecl for the result.
18926 const ComparisonCategoryInfo &CmpInfo =
18927 Info.Ctx.CompCategories.getInfoForType(E->getType());
18928 const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD;
18929 // Check and evaluate the result as a constant expression.
18930 LValue LV;
18931 LV.set(VD);
18932 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
18933 return false;
18934 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
18935 ConstantExprKind::Normal);
18936 };
18937 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
18938 return ExprEvaluatorBaseTy::VisitBinCmp(E);
18939 });
18940}
18941
18942bool RecordExprEvaluator::VisitCXXParenListInitExpr(
18943 const CXXParenListInitExpr *E) {
18944 return VisitCXXParenListOrInitListExpr(E, E->getInitExprs());
18945}
18946
18947bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
18948 // We don't support assignment in C. C++ assignments don't get here because
18949 // assignment is an lvalue in C++.
18950 if (E->isAssignmentOp()) {
18951 Error(E);
18952 if (!Info.noteFailure())
18953 return false;
18954 }
18955
18956 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
18957 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
18958
18959 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
18961 "DataRecursiveIntBinOpEvaluator should have handled integral types");
18962
18963 if (E->isComparisonOp()) {
18964 // Evaluate builtin binary comparisons by evaluating them as three-way
18965 // comparisons and then translating the result.
18966 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
18967 assert((CR != CmpResult::Unequal || E->isEqualityOp()) &&
18968 "should only produce Unequal for equality comparisons");
18969 bool IsEqual = CR == CmpResult::Equal,
18970 IsLess = CR == CmpResult::Less,
18971 IsGreater = CR == CmpResult::Greater;
18972 auto Op = E->getOpcode();
18973 switch (Op) {
18974 default:
18975 llvm_unreachable("unsupported binary operator");
18976 case BO_EQ:
18977 case BO_NE:
18978 return Success(IsEqual == (Op == BO_EQ), E);
18979 case BO_LT:
18980 return Success(IsLess, E);
18981 case BO_GT:
18982 return Success(IsGreater, E);
18983 case BO_LE:
18984 return Success(IsEqual || IsLess, E);
18985 case BO_GE:
18986 return Success(IsEqual || IsGreater, E);
18987 }
18988 };
18989 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
18990 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
18991 });
18992 }
18993
18994 QualType LHSTy = E->getLHS()->getType();
18995 QualType RHSTy = E->getRHS()->getType();
18996
18997 if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
18998 E->getOpcode() == BO_Sub) {
18999 LValue LHSValue, RHSValue;
19000
19001 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
19002 if (!LHSOK && !Info.noteFailure())
19003 return false;
19004
19005 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
19006 return false;
19007
19008 // Reject differing bases from the normal codepath; we special-case
19009 // comparisons to null.
19010 if (!HasSameBase(LHSValue, RHSValue)) {
19011 if (Info.checkingPotentialConstantExpression() &&
19012 (LHSValue.AllowConstexprUnknown || RHSValue.AllowConstexprUnknown))
19013 return false;
19014
19015 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
19016 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
19017
19018 auto DiagArith = [&](unsigned DiagID) {
19019 std::string LHS = LHSValue.toString(Info.Ctx, E->getLHS()->getType());
19020 std::string RHS = RHSValue.toString(Info.Ctx, E->getRHS()->getType());
19021 Info.FFDiag(E, DiagID) << LHS << RHS;
19022 if (LHSExpr && LHSExpr == RHSExpr)
19023 Info.Note(LHSExpr->getExprLoc(),
19024 diag::note_constexpr_repeated_literal_eval)
19025 << LHSExpr->getSourceRange();
19026 return false;
19027 };
19028
19029 if (!LHSExpr || !RHSExpr)
19030 return DiagArith(diag::note_constexpr_pointer_arith_unspecified);
19031
19032 if (ArePotentiallyOverlappingStringLiterals(Info, LHSValue, RHSValue))
19033 return DiagArith(diag::note_constexpr_literal_arith);
19034
19035 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
19036 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
19037 if (!LHSAddrExpr || !RHSAddrExpr)
19038 return Error(E);
19039 // Make sure both labels come from the same function.
19040 if (LHSAddrExpr->getLabel()->getDeclContext() !=
19041 RHSAddrExpr->getLabel()->getDeclContext())
19042 return Error(E);
19043 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
19044 }
19045 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
19046 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
19047
19048 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
19049 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
19050
19051 // C++11 [expr.add]p6:
19052 // Unless both pointers point to elements of the same array object, or
19053 // one past the last element of the array object, the behavior is
19054 // undefined.
19055 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
19056 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
19057 RHSDesignator))
19058 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
19059
19060 QualType Type = E->getLHS()->getType();
19061 QualType ElementType = Type->castAs<PointerType>()->getPointeeType();
19062
19063 CharUnits ElementSize;
19064 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
19065 return false;
19066
19067 // As an extension, a type may have zero size (empty struct or union in
19068 // C, array of zero length). Pointer subtraction in such cases has
19069 // undefined behavior, so is not constant.
19070 if (ElementSize.isZero()) {
19071 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
19072 << ElementType;
19073 return false;
19074 }
19075
19076 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
19077 // and produce incorrect results when it overflows. Such behavior
19078 // appears to be non-conforming, but is common, so perhaps we should
19079 // assume the standard intended for such cases to be undefined behavior
19080 // and check for them.
19081
19082 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
19083 // overflow in the final conversion to ptrdiff_t.
19084 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
19085 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
19086 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
19087 false);
19088 APSInt TrueResult = (LHS - RHS) / ElemSize;
19089 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
19090
19091 if (Result.extend(65) != TrueResult &&
19092 !HandleOverflow(Info, E, TrueResult, E->getType()))
19093 return false;
19094 return Success(Result, E);
19095 }
19096
19097 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
19098}
19099
19100/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
19101/// a result as the expression's type.
19102bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
19103 const UnaryExprOrTypeTraitExpr *E) {
19104 switch(E->getKind()) {
19105 case UETT_PreferredAlignOf:
19106 case UETT_AlignOf: {
19107 if (E->isArgumentType())
19108 return Success(
19109 GetAlignOfType(Info.Ctx, E->getArgumentType(), E->getKind()), E);
19110 else
19111 return Success(
19112 GetAlignOfExpr(Info.Ctx, E->getArgumentExpr(), E->getKind()), E);
19113 }
19114
19115 case UETT_PtrAuthTypeDiscriminator: {
19116 if (E->getArgumentType()->isDependentType())
19117 return false;
19118 return Success(
19119 Info.Ctx.getPointerAuthTypeDiscriminator(E->getArgumentType()), E);
19120 }
19121 case UETT_VecStep: {
19122 QualType Ty = E->getTypeOfArgument();
19123
19124 if (Ty->isVectorType()) {
19125 unsigned n = Ty->castAs<VectorType>()->getNumElements();
19126
19127 // The vec_step built-in functions that take a 3-component
19128 // vector return 4. (OpenCL 1.1 spec 6.11.12)
19129 if (n == 3)
19130 n = 4;
19131
19132 return Success(n, E);
19133 } else
19134 return Success(1, E);
19135 }
19136
19137 case UETT_DataSizeOf:
19138 case UETT_SizeOf: {
19139 QualType SrcTy = E->getTypeOfArgument();
19140 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
19141 // the result is the size of the referenced type."
19142 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
19143 SrcTy = Ref->getPointeeType();
19144
19145 CharUnits Sizeof;
19146 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof,
19147 E->getKind() == UETT_DataSizeOf ? SizeOfType::DataSizeOf
19148 : SizeOfType::SizeOf)) {
19149 return false;
19150 }
19151 return Success(Sizeof, E);
19152 }
19153 case UETT_OpenMPRequiredSimdAlign:
19154 assert(E->isArgumentType());
19155 return Success(
19156 Info.Ctx.toCharUnitsFromBits(
19157 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
19158 .getQuantity(),
19159 E);
19160 case UETT_VectorElements: {
19161 QualType Ty = E->getTypeOfArgument();
19162 // If the vector has a fixed size, we can determine the number of elements
19163 // at compile time.
19164 if (const auto *VT = Ty->getAs<VectorType>())
19165 return Success(VT->getNumElements(), E);
19166
19167 assert(Ty->isSizelessVectorType());
19168 if (Info.InConstantContext)
19169 Info.CCEDiag(E, diag::note_constexpr_non_const_vectorelements)
19170 << E->getSourceRange();
19171
19172 return false;
19173 }
19174 case UETT_CountOf: {
19175 QualType Ty = E->getTypeOfArgument();
19176 assert(Ty->isArrayType());
19177
19178 // We don't need to worry about array element qualifiers, so getting the
19179 // unsafe array type is fine.
19180 if (const auto *CAT =
19181 dyn_cast<ConstantArrayType>(Ty->getAsArrayTypeUnsafe())) {
19182 return Success(CAT->getSize(), E);
19183 }
19184
19185 assert(!Ty->isConstantSizeType());
19186
19187 // If it's a variable-length array type, we need to check whether it is a
19188 // multidimensional array. If so, we need to check the size expression of
19189 // the VLA to see if it's a constant size. If so, we can return that value.
19190 const auto *VAT = Info.Ctx.getAsVariableArrayType(Ty);
19191 assert(VAT);
19192 if (VAT->getElementType()->isArrayType()) {
19193 // Variable array size expression could be missing (e.g. int a[*][10]) In
19194 // that case, it can't be a constant expression.
19195 if (!VAT->getSizeExpr()) {
19196 Info.FFDiag(E->getBeginLoc());
19197 return false;
19198 }
19199
19200 std::optional<APSInt> Res =
19201 VAT->getSizeExpr()->getIntegerConstantExpr(Info.Ctx);
19202 if (Res) {
19203 // The resulting value always has type size_t, so we need to make the
19204 // returned APInt have the correct sign and bit-width.
19205 APInt Val{
19206 static_cast<unsigned>(Info.Ctx.getTypeSize(Info.Ctx.getSizeType())),
19207 Res->getZExtValue()};
19208 return Success(Val, E);
19209 }
19210 }
19211
19212 // Definitely a variable-length type, which is not an ICE.
19213 // FIXME: Better diagnostic.
19214 Info.FFDiag(E->getBeginLoc());
19215 return false;
19216 }
19217 }
19218
19219 llvm_unreachable("unknown expr/type trait");
19220}
19221
19222bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
19223 Info.Ctx.recordOffsetOfEvaluation(OOE);
19224 CharUnits Result;
19225 unsigned n = OOE->getNumComponents();
19226 if (n == 0)
19227 return Error(OOE);
19228 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
19229 for (unsigned i = 0; i != n; ++i) {
19230 OffsetOfNode ON = OOE->getComponent(i);
19231 switch (ON.getKind()) {
19232 case OffsetOfNode::Array: {
19233 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
19234 APSInt IdxResult;
19235 if (!EvaluateInteger(Idx, IdxResult, Info))
19236 return false;
19237 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
19238 if (!AT)
19239 return Error(OOE);
19240 CurrentType = AT->getElementType();
19241 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
19242 Result += IdxResult.getSExtValue() * ElementSize;
19243 break;
19244 }
19245
19246 case OffsetOfNode::Field: {
19247 FieldDecl *MemberDecl = ON.getField();
19248 const auto *RD = CurrentType->getAsRecordDecl();
19249 if (!RD)
19250 return Error(OOE);
19251 if (RD->isInvalidDecl()) return false;
19252 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
19253 unsigned i = MemberDecl->getFieldIndex();
19254 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
19255 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
19256 CurrentType = MemberDecl->getType().getNonReferenceType();
19257 break;
19258 }
19259
19261 llvm_unreachable("dependent __builtin_offsetof");
19262
19263 case OffsetOfNode::Base: {
19264 CXXBaseSpecifier *BaseSpec = ON.getBase();
19265 if (BaseSpec->isVirtual())
19266 return Error(OOE);
19267
19268 // Find the layout of the class whose base we are looking into.
19269 const auto *RD = CurrentType->getAsCXXRecordDecl();
19270 if (!RD)
19271 return Error(OOE);
19272 if (RD->isInvalidDecl()) return false;
19273 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
19274
19275 // Find the base class itself.
19276 CurrentType = BaseSpec->getType();
19277 const auto *BaseRD = CurrentType->getAsCXXRecordDecl();
19278 if (!BaseRD)
19279 return Error(OOE);
19280
19281 // Add the offset to the base.
19282 Result += RL.getBaseClassOffset(BaseRD);
19283 break;
19284 }
19285 }
19286 }
19287 return Success(Result, OOE);
19288}
19289
19290bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
19291 switch (E->getOpcode()) {
19292 default:
19293 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
19294 // See C99 6.6p3.
19295 return Error(E);
19296 case UO_Extension:
19297 // FIXME: Should extension allow i-c-e extension expressions in its scope?
19298 // If so, we could clear the diagnostic ID.
19299 return Visit(E->getSubExpr());
19300 case UO_Plus:
19301 // The result is just the value.
19302 return Visit(E->getSubExpr());
19303 case UO_Minus: {
19304 if (!Visit(E->getSubExpr()))
19305 return false;
19306 if (!Result.isInt()) return Error(E);
19307 const APSInt &Value = Result.getInt();
19308 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
19309 !E->getType().isWrapType()) {
19310 if (Info.checkingForUndefinedBehavior())
19311 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
19312 diag::warn_integer_constant_overflow)
19313 << toString(Value, 10, Value.isSigned(), /*formatAsCLiteral=*/false,
19314 /*UpperCase=*/true, /*InsertSeparators=*/true)
19315 << E->getType() << E->getSourceRange();
19316
19317 if (!HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
19318 E->getType()))
19319 return false;
19320 }
19321 return Success(-Value, E);
19322 }
19323 case UO_Not: {
19324 if (!Visit(E->getSubExpr()))
19325 return false;
19326 if (!Result.isInt()) return Error(E);
19327 return Success(~Result.getInt(), E);
19328 }
19329 case UO_LNot: {
19330 bool bres;
19331 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
19332 return false;
19333 return Success(!bres, E);
19334 }
19335 }
19336}
19337
19338/// HandleCast - This is used to evaluate implicit or explicit casts where the
19339/// result type is integer.
19340bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
19341 const Expr *SubExpr = E->getSubExpr();
19342 QualType DestType = E->getType();
19343 QualType SrcType = SubExpr->getType();
19344
19345 switch (E->getCastKind()) {
19346 case CK_BaseToDerived:
19347 case CK_DerivedToBase:
19348 case CK_UncheckedDerivedToBase:
19349 case CK_Dynamic:
19350 case CK_ToUnion:
19351 case CK_ArrayToPointerDecay:
19352 case CK_FunctionToPointerDecay:
19353 case CK_NullToPointer:
19354 case CK_NullToMemberPointer:
19355 case CK_BaseToDerivedMemberPointer:
19356 case CK_DerivedToBaseMemberPointer:
19357 case CK_ReinterpretMemberPointer:
19358 case CK_ConstructorConversion:
19359 case CK_IntegralToPointer:
19360 case CK_ToVoid:
19361 case CK_VectorSplat:
19362 case CK_IntegralToFloating:
19363 case CK_FloatingCast:
19364 case CK_CPointerToObjCPointerCast:
19365 case CK_BlockPointerToObjCPointerCast:
19366 case CK_AnyPointerToBlockPointerCast:
19367 case CK_ObjCObjectLValueCast:
19368 case CK_FloatingRealToComplex:
19369 case CK_FloatingComplexToReal:
19370 case CK_FloatingComplexCast:
19371 case CK_FloatingComplexToIntegralComplex:
19372 case CK_IntegralRealToComplex:
19373 case CK_IntegralComplexCast:
19374 case CK_IntegralComplexToFloatingComplex:
19375 case CK_BuiltinFnToFnPtr:
19376 case CK_ZeroToOCLOpaqueType:
19377 case CK_NonAtomicToAtomic:
19378 case CK_AddressSpaceConversion:
19379 case CK_IntToOCLSampler:
19380 case CK_FloatingToFixedPoint:
19381 case CK_FixedPointToFloating:
19382 case CK_FixedPointCast:
19383 case CK_IntegralToFixedPoint:
19384 case CK_MatrixCast:
19385 case CK_HLSLAggregateSplatCast:
19386 llvm_unreachable("invalid cast kind for integral value");
19387
19388 case CK_BitCast:
19389 case CK_Dependent:
19390 case CK_LValueBitCast:
19391 case CK_ARCProduceObject:
19392 case CK_ARCConsumeObject:
19393 case CK_ARCReclaimReturnedObject:
19394 case CK_ARCExtendBlockObject:
19395 case CK_CopyAndAutoreleaseBlockObject:
19396 return Error(E);
19397
19398 case CK_UserDefinedConversion:
19399 case CK_LValueToRValue:
19400 case CK_AtomicToNonAtomic:
19401 case CK_NoOp:
19402 case CK_LValueToRValueBitCast:
19403 case CK_HLSLArrayRValue:
19404 return ExprEvaluatorBaseTy::VisitCastExpr(E);
19405
19406 case CK_MemberPointerToBoolean:
19407 case CK_PointerToBoolean:
19408 case CK_IntegralToBoolean:
19409 case CK_FloatingToBoolean:
19410 case CK_BooleanToSignedIntegral:
19411 case CK_FloatingComplexToBoolean:
19412 case CK_IntegralComplexToBoolean: {
19413 bool BoolResult;
19414 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
19415 return false;
19416 uint64_t IntResult = BoolResult;
19417 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
19418 IntResult = (uint64_t)-1;
19419 return Success(IntResult, E);
19420 }
19421
19422 case CK_FixedPointToIntegral: {
19423 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
19424 if (!EvaluateFixedPoint(SubExpr, Src, Info))
19425 return false;
19426 bool Overflowed;
19427 llvm::APSInt Result = Src.convertToInt(
19428 Info.Ctx.getIntWidth(DestType),
19429 DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
19430 if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
19431 return false;
19432 return Success(Result, E);
19433 }
19434
19435 case CK_FixedPointToBoolean: {
19436 // Unsigned padding does not affect this.
19437 APValue Val;
19438 if (!Evaluate(Val, Info, SubExpr))
19439 return false;
19440 return Success(Val.getFixedPoint().getBoolValue(), E);
19441 }
19442
19443 case CK_IntegralCast: {
19444 if (!Visit(SubExpr))
19445 return false;
19446
19447 if (!Result.isInt()) {
19448 // Allow casts of address-of-label differences if they are no-ops
19449 // or narrowing, if the result is at least 32 bits wide.
19450 // (The narrowing case isn't actually guaranteed to
19451 // be constant-evaluatable except in some narrow cases which are hard
19452 // to detect here. We let it through on the assumption the user knows
19453 // what they are doing.)
19454 if (Result.isAddrLabelDiff()) {
19455 unsigned DestBits = Info.Ctx.getTypeSize(DestType);
19456 return DestBits >= 32 && DestBits <= Info.Ctx.getTypeSize(SrcType);
19457 }
19458 // Only allow casts of lvalues if they are lossless.
19459 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
19460 }
19461
19462 if (Info.Ctx.getLangOpts().CPlusPlus && DestType->isEnumeralType()) {
19463 const auto *ED = DestType->getAsEnumDecl();
19464 // Check that the value is within the range of the enumeration values.
19465 //
19466 // This corressponds to [expr.static.cast]p10 which says:
19467 // A value of integral or enumeration type can be explicitly converted
19468 // to a complete enumeration type ... If the enumeration type does not
19469 // have a fixed underlying type, the value is unchanged if the original
19470 // value is within the range of the enumeration values ([dcl.enum]), and
19471 // otherwise, the behavior is undefined.
19472 //
19473 // This was resolved as part of DR2338 which has CD5 status.
19474 if (!ED->isFixed()) {
19475 llvm::APInt Min;
19476 llvm::APInt Max;
19477
19478 ED->getValueRange(Max, Min);
19479 --Max;
19480
19481 if (ED->getNumNegativeBits() &&
19482 (Max.slt(Result.getInt().getSExtValue()) ||
19483 Min.sgt(Result.getInt().getSExtValue())))
19484 Info.CCEDiag(E, diag::note_constexpr_unscoped_enum_out_of_range)
19485 << llvm::toString(Result.getInt(), 10) << Min.getSExtValue()
19486 << Max.getSExtValue() << ED;
19487 else if (!ED->getNumNegativeBits() &&
19488 Max.ult(Result.getInt().getZExtValue()))
19489 Info.CCEDiag(E, diag::note_constexpr_unscoped_enum_out_of_range)
19490 << llvm::toString(Result.getInt(), 10) << Min.getZExtValue()
19491 << Max.getZExtValue() << ED;
19492 }
19493 }
19494
19495 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
19496 Result.getInt()), E);
19497 }
19498
19499 case CK_PointerToIntegral: {
19500 CCEDiag(E, diag::note_constexpr_invalid_cast)
19501 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
19502 << Info.Ctx.getLangOpts().CPlusPlus << E->getSourceRange();
19503
19504 LValue LV;
19505 if (!EvaluatePointer(SubExpr, LV, Info))
19506 return false;
19507
19508 if (LV.getLValueBase()) {
19509 // Only allow based lvalue casts if they are lossless.
19510 // FIXME: Allow a larger integer size than the pointer size, and allow
19511 // narrowing back down to pointer width in subsequent integral casts.
19512 // FIXME: Check integer type's active bits, not its type size.
19513 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
19514 return Error(E);
19515
19516 LV.Designator.setInvalid();
19517 LV.moveInto(Result);
19518 return true;
19519 }
19520
19521 APSInt AsInt;
19522 APValue V;
19523 LV.moveInto(V);
19524 if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
19525 llvm_unreachable("Can't cast this!");
19526
19527 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
19528 }
19529
19530 case CK_IntegralComplexToReal: {
19531 ComplexValue C;
19532 if (!EvaluateComplex(SubExpr, C, Info))
19533 return false;
19534 return Success(C.getComplexIntReal(), E);
19535 }
19536
19537 case CK_FloatingToIntegral: {
19538 APFloat F(0.0);
19539 if (!EvaluateFloat(SubExpr, F, Info))
19540 return false;
19541
19542 APSInt Value;
19543 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
19544 return false;
19545 return Success(Value, E);
19546 }
19547 case CK_HLSLVectorTruncation: {
19548 APValue Val;
19549 if (!EvaluateVector(SubExpr, Val, Info))
19550 return Error(E);
19551 return Success(Val.getVectorElt(0), E);
19552 }
19553 case CK_HLSLMatrixTruncation: {
19554 APValue Val;
19555 if (!EvaluateMatrix(SubExpr, Val, Info))
19556 return Error(E);
19557 return Success(Val.getMatrixElt(0, 0), E);
19558 }
19559 case CK_HLSLElementwiseCast: {
19560 SmallVector<APValue> SrcVals;
19561 SmallVector<QualType> SrcTypes;
19562
19563 if (!hlslElementwiseCastHelper(Info, SubExpr, DestType, SrcVals, SrcTypes))
19564 return false;
19565
19566 // cast our single element
19567 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
19568 APValue ResultVal;
19569 if (!handleScalarCast(Info, FPO, E, SrcTypes[0], DestType, SrcVals[0],
19570 ResultVal))
19571 return false;
19572 return Success(ResultVal, E);
19573 }
19574 }
19575
19576 llvm_unreachable("unknown cast resulting in integral value");
19577}
19578
19579bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
19580 if (E->getSubExpr()->getType()->isAnyComplexType()) {
19581 ComplexValue LV;
19582 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
19583 return false;
19584 if (!LV.isComplexInt())
19585 return Error(E);
19586 return Success(LV.getComplexIntReal(), E);
19587 }
19588
19589 return Visit(E->getSubExpr());
19590}
19591
19592bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
19593 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
19594 ComplexValue LV;
19595 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
19596 return false;
19597 if (!LV.isComplexInt())
19598 return Error(E);
19599 return Success(LV.getComplexIntImag(), E);
19600 }
19601
19602 VisitIgnoredValue(E->getSubExpr());
19603 return Success(0, E);
19604}
19605
19606bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
19607 return Success(E->getPackLength(), E);
19608}
19609
19610bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
19611 return Success(E->getValue(), E);
19612}
19613
19614bool IntExprEvaluator::VisitConceptSpecializationExpr(
19615 const ConceptSpecializationExpr *E) {
19616 return Success(E->isSatisfied(), E);
19617}
19618
19619bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) {
19620 return Success(E->isSatisfied(), E);
19621}
19622
19623bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
19624 switch (E->getOpcode()) {
19625 default:
19626 // Invalid unary operators
19627 return Error(E);
19628 case UO_Plus:
19629 // The result is just the value.
19630 return Visit(E->getSubExpr());
19631 case UO_Minus: {
19632 if (!Visit(E->getSubExpr())) return false;
19633 if (!Result.isFixedPoint())
19634 return Error(E);
19635 bool Overflowed;
19636 APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
19637 if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
19638 return false;
19639 return Success(Negated, E);
19640 }
19641 case UO_LNot: {
19642 bool bres;
19643 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
19644 return false;
19645 return Success(!bres, E);
19646 }
19647 }
19648}
19649
19650bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
19651 const Expr *SubExpr = E->getSubExpr();
19652 QualType DestType = E->getType();
19653 assert(DestType->isFixedPointType() &&
19654 "Expected destination type to be a fixed point type");
19655 auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
19656
19657 switch (E->getCastKind()) {
19658 case CK_FixedPointCast: {
19659 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
19660 if (!EvaluateFixedPoint(SubExpr, Src, Info))
19661 return false;
19662 bool Overflowed;
19663 APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
19664 if (Overflowed) {
19665 if (Info.checkingForUndefinedBehavior())
19666 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
19667 diag::warn_fixedpoint_constant_overflow)
19668 << Result.toString() << E->getType();
19669 if (!HandleOverflow(Info, E, Result, E->getType()))
19670 return false;
19671 }
19672 return Success(Result, E);
19673 }
19674 case CK_IntegralToFixedPoint: {
19675 APSInt Src;
19676 if (!EvaluateInteger(SubExpr, Src, Info))
19677 return false;
19678
19679 bool Overflowed;
19680 APFixedPoint IntResult = APFixedPoint::getFromIntValue(
19681 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
19682
19683 if (Overflowed) {
19684 if (Info.checkingForUndefinedBehavior())
19685 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
19686 diag::warn_fixedpoint_constant_overflow)
19687 << IntResult.toString() << E->getType();
19688 if (!HandleOverflow(Info, E, IntResult, E->getType()))
19689 return false;
19690 }
19691
19692 return Success(IntResult, E);
19693 }
19694 case CK_FloatingToFixedPoint: {
19695 APFloat Src(0.0);
19696 if (!EvaluateFloat(SubExpr, Src, Info))
19697 return false;
19698
19699 bool Overflowed;
19700 APFixedPoint Result = APFixedPoint::getFromFloatValue(
19701 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
19702
19703 if (Overflowed) {
19704 if (Info.checkingForUndefinedBehavior())
19705 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
19706 diag::warn_fixedpoint_constant_overflow)
19707 << Result.toString() << E->getType();
19708 if (!HandleOverflow(Info, E, Result, E->getType()))
19709 return false;
19710 }
19711
19712 return Success(Result, E);
19713 }
19714 case CK_NoOp:
19715 case CK_LValueToRValue:
19716 return ExprEvaluatorBaseTy::VisitCastExpr(E);
19717 default:
19718 return Error(E);
19719 }
19720}
19721
19722bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
19723 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
19724 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
19725
19726 const Expr *LHS = E->getLHS();
19727 const Expr *RHS = E->getRHS();
19728 FixedPointSemantics ResultFXSema =
19729 Info.Ctx.getFixedPointSemantics(E->getType());
19730
19731 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
19732 if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
19733 return false;
19734 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
19735 if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
19736 return false;
19737
19738 bool OpOverflow = false, ConversionOverflow = false;
19739 APFixedPoint Result(LHSFX.getSemantics());
19740 switch (E->getOpcode()) {
19741 case BO_Add: {
19742 Result = LHSFX.add(RHSFX, &OpOverflow)
19743 .convert(ResultFXSema, &ConversionOverflow);
19744 break;
19745 }
19746 case BO_Sub: {
19747 Result = LHSFX.sub(RHSFX, &OpOverflow)
19748 .convert(ResultFXSema, &ConversionOverflow);
19749 break;
19750 }
19751 case BO_Mul: {
19752 Result = LHSFX.mul(RHSFX, &OpOverflow)
19753 .convert(ResultFXSema, &ConversionOverflow);
19754 break;
19755 }
19756 case BO_Div: {
19757 if (RHSFX.getValue() == 0) {
19758 Info.FFDiag(E, diag::note_expr_divide_by_zero);
19759 return false;
19760 }
19761 Result = LHSFX.div(RHSFX, &OpOverflow)
19762 .convert(ResultFXSema, &ConversionOverflow);
19763 break;
19764 }
19765 case BO_Shl:
19766 case BO_Shr: {
19767 FixedPointSemantics LHSSema = LHSFX.getSemantics();
19768 llvm::APSInt RHSVal = RHSFX.getValue();
19769
19770 unsigned ShiftBW =
19771 LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding();
19772 unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1);
19773 // Embedded-C 4.1.6.2.2:
19774 // The right operand must be nonnegative and less than the total number
19775 // of (nonpadding) bits of the fixed-point operand ...
19776 if (RHSVal.isNegative())
19777 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal;
19778 else if (Amt != RHSVal)
19779 Info.CCEDiag(E, diag::note_constexpr_large_shift)
19780 << RHSVal << E->getType() << ShiftBW;
19781
19782 if (E->getOpcode() == BO_Shl)
19783 Result = LHSFX.shl(Amt, &OpOverflow);
19784 else
19785 Result = LHSFX.shr(Amt, &OpOverflow);
19786 break;
19787 }
19788 default:
19789 return false;
19790 }
19791 if (OpOverflow || ConversionOverflow) {
19792 if (Info.checkingForUndefinedBehavior())
19793 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
19794 diag::warn_fixedpoint_constant_overflow)
19795 << Result.toString() << E->getType();
19796 if (!HandleOverflow(Info, E, Result, E->getType()))
19797 return false;
19798 }
19799 return Success(Result, E);
19800}
19801
19802//===----------------------------------------------------------------------===//
19803// Float Evaluation
19804//===----------------------------------------------------------------------===//
19805
19806namespace {
19807class FloatExprEvaluator
19808 : public ExprEvaluatorBase<FloatExprEvaluator> {
19809 APFloat &Result;
19810public:
19811 FloatExprEvaluator(EvalInfo &info, APFloat &result)
19812 : ExprEvaluatorBaseTy(info), Result(result) {}
19813
19814 bool Success(const APValue &V, const Expr *e) {
19815 Result = V.getFloat();
19816 return true;
19817 }
19818
19819 bool ZeroInitialization(const Expr *E) {
19820 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
19821 return true;
19822 }
19823
19824 bool VisitCallExpr(const CallExpr *E);
19825
19826 bool VisitUnaryOperator(const UnaryOperator *E);
19827 bool VisitBinaryOperator(const BinaryOperator *E);
19828 bool VisitFloatingLiteral(const FloatingLiteral *E);
19829 bool VisitCastExpr(const CastExpr *E);
19830
19831 bool VisitUnaryReal(const UnaryOperator *E);
19832 bool VisitUnaryImag(const UnaryOperator *E);
19833
19834 // FIXME: Missing: array subscript of vector, member of vector
19835};
19836} // end anonymous namespace
19837
19838static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
19839 assert(!E->isValueDependent());
19840 assert(E->isPRValue() && E->getType()->isRealFloatingType());
19841 return FloatExprEvaluator(Info, Result).Visit(E);
19842}
19843
19844static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
19845 QualType ResultTy,
19846 const Expr *Arg,
19847 bool SNaN,
19848 llvm::APFloat &Result) {
19849 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
19850 if (!S) return false;
19851
19852 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
19853
19854 llvm::APInt fill;
19855
19856 // Treat empty strings as if they were zero.
19857 if (S->getString().empty())
19858 fill = llvm::APInt(32, 0);
19859 else if (S->getString().getAsInteger(0, fill))
19860 return false;
19861
19862 if (Context.getTargetInfo().isNan2008()) {
19863 if (SNaN)
19864 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
19865 else
19866 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
19867 } else {
19868 // Prior to IEEE 754-2008, architectures were allowed to choose whether
19869 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
19870 // a different encoding to what became a standard in 2008, and for pre-
19871 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
19872 // sNaN. This is now known as "legacy NaN" encoding.
19873 if (SNaN)
19874 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
19875 else
19876 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
19877 }
19878
19879 return true;
19880}
19881
19882bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
19883 if (!IsConstantEvaluatedBuiltinCall(E))
19884 return ExprEvaluatorBaseTy::VisitCallExpr(E);
19885
19886 switch (E->getBuiltinCallee()) {
19887 default:
19888 return false;
19889
19890 case Builtin::BI__builtin_huge_val:
19891 case Builtin::BI__builtin_huge_valf:
19892 case Builtin::BI__builtin_huge_vall:
19893 case Builtin::BI__builtin_huge_valf16:
19894 case Builtin::BI__builtin_huge_valf128:
19895 case Builtin::BI__builtin_inf:
19896 case Builtin::BI__builtin_inff:
19897 case Builtin::BI__builtin_infl:
19898 case Builtin::BI__builtin_inff16:
19899 case Builtin::BI__builtin_inff128: {
19900 const llvm::fltSemantics &Sem =
19901 Info.Ctx.getFloatTypeSemantics(E->getType());
19902 Result = llvm::APFloat::getInf(Sem);
19903 return true;
19904 }
19905
19906 case Builtin::BI__builtin_nans:
19907 case Builtin::BI__builtin_nansf:
19908 case Builtin::BI__builtin_nansl:
19909 case Builtin::BI__builtin_nansf16:
19910 case Builtin::BI__builtin_nansf128:
19911 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
19912 true, Result))
19913 return Error(E);
19914 return true;
19915
19916 case Builtin::BI__builtin_nan:
19917 case Builtin::BI__builtin_nanf:
19918 case Builtin::BI__builtin_nanl:
19919 case Builtin::BI__builtin_nanf16:
19920 case Builtin::BI__builtin_nanf128:
19921 // If this is __builtin_nan() turn this into a nan, otherwise we
19922 // can't constant fold it.
19923 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
19924 false, Result))
19925 return Error(E);
19926 return true;
19927
19928 case Builtin::BI__builtin_elementwise_abs:
19929 case Builtin::BI__builtin_fabs:
19930 case Builtin::BI__builtin_fabsf:
19931 case Builtin::BI__builtin_fabsl:
19932 case Builtin::BI__builtin_fabsf128:
19933 // The C standard says "fabs raises no floating-point exceptions,
19934 // even if x is a signaling NaN. The returned value is independent of
19935 // the current rounding direction mode." Therefore constant folding can
19936 // proceed without regard to the floating point settings.
19937 // Reference, WG14 N2478 F.10.4.3
19938 if (!EvaluateFloat(E->getArg(0), Result, Info))
19939 return false;
19940
19941 if (Result.isNegative())
19942 Result.changeSign();
19943 return true;
19944
19945 case Builtin::BI__arithmetic_fence:
19946 return EvaluateFloat(E->getArg(0), Result, Info);
19947
19948 // FIXME: Builtin::BI__builtin_powi
19949 // FIXME: Builtin::BI__builtin_powif
19950 // FIXME: Builtin::BI__builtin_powil
19951
19952 case Builtin::BI__builtin_copysign:
19953 case Builtin::BI__builtin_copysignf:
19954 case Builtin::BI__builtin_copysignl:
19955 case Builtin::BI__builtin_copysignf128: {
19956 APFloat RHS(0.);
19957 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
19958 !EvaluateFloat(E->getArg(1), RHS, Info))
19959 return false;
19960 Result.copySign(RHS);
19961 return true;
19962 }
19963
19964 case Builtin::BI__builtin_fmax:
19965 case Builtin::BI__builtin_fmaxf:
19966 case Builtin::BI__builtin_fmaxl:
19967 case Builtin::BI__builtin_fmaxf16:
19968 case Builtin::BI__builtin_fmaxf128: {
19969 APFloat RHS(0.);
19970 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
19971 !EvaluateFloat(E->getArg(1), RHS, Info))
19972 return false;
19973 Result = maxnum(Result, RHS);
19974 return true;
19975 }
19976
19977 case Builtin::BI__builtin_fmin:
19978 case Builtin::BI__builtin_fminf:
19979 case Builtin::BI__builtin_fminl:
19980 case Builtin::BI__builtin_fminf16:
19981 case Builtin::BI__builtin_fminf128: {
19982 APFloat RHS(0.);
19983 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
19984 !EvaluateFloat(E->getArg(1), RHS, Info))
19985 return false;
19986 Result = minnum(Result, RHS);
19987 return true;
19988 }
19989
19990 case Builtin::BI__builtin_fmaximum_num:
19991 case Builtin::BI__builtin_fmaximum_numf:
19992 case Builtin::BI__builtin_fmaximum_numl:
19993 case Builtin::BI__builtin_fmaximum_numf16:
19994 case Builtin::BI__builtin_fmaximum_numf128: {
19995 APFloat RHS(0.);
19996 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
19997 !EvaluateFloat(E->getArg(1), RHS, Info))
19998 return false;
19999 Result = maximumnum(Result, RHS);
20000 return true;
20001 }
20002
20003 case Builtin::BI__builtin_fminimum_num:
20004 case Builtin::BI__builtin_fminimum_numf:
20005 case Builtin::BI__builtin_fminimum_numl:
20006 case Builtin::BI__builtin_fminimum_numf16:
20007 case Builtin::BI__builtin_fminimum_numf128: {
20008 APFloat RHS(0.);
20009 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
20010 !EvaluateFloat(E->getArg(1), RHS, Info))
20011 return false;
20012 Result = minimumnum(Result, RHS);
20013 return true;
20014 }
20015
20016 case Builtin::BI__builtin_elementwise_fma: {
20017 if (!E->getArg(0)->isPRValue() || !E->getArg(1)->isPRValue() ||
20018 !E->getArg(2)->isPRValue()) {
20019 return false;
20020 }
20021 APFloat SourceY(0.), SourceZ(0.);
20022 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
20023 !EvaluateFloat(E->getArg(1), SourceY, Info) ||
20024 !EvaluateFloat(E->getArg(2), SourceZ, Info))
20025 return false;
20026 llvm::RoundingMode RM = getActiveRoundingMode(getEvalInfo(), E);
20027 (void)Result.fusedMultiplyAdd(SourceY, SourceZ, RM);
20028 return true;
20029 }
20030
20031 case clang::X86::BI__builtin_ia32_vec_ext_v4sf: {
20032 APValue Vec;
20033 APSInt IdxAPS;
20034 if (!EvaluateVector(E->getArg(0), Vec, Info) ||
20035 !EvaluateInteger(E->getArg(1), IdxAPS, Info))
20036 return false;
20037 unsigned N = Vec.getVectorLength();
20038 unsigned Idx = static_cast<unsigned>(IdxAPS.getZExtValue() & (N - 1));
20039 return Success(Vec.getVectorElt(Idx), E);
20040 }
20041 }
20042}
20043
20044bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
20045 if (E->getSubExpr()->getType()->isAnyComplexType()) {
20046 ComplexValue CV;
20047 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
20048 return false;
20049 Result = CV.FloatReal;
20050 return true;
20051 }
20052
20053 return Visit(E->getSubExpr());
20054}
20055
20056bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
20057 if (E->getSubExpr()->getType()->isAnyComplexType()) {
20058 ComplexValue CV;
20059 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
20060 return false;
20061 Result = CV.FloatImag;
20062 return true;
20063 }
20064
20065 VisitIgnoredValue(E->getSubExpr());
20066 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
20067 Result = llvm::APFloat::getZero(Sem);
20068 return true;
20069}
20070
20071bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
20072 switch (E->getOpcode()) {
20073 default: return Error(E);
20074 case UO_Plus:
20075 return EvaluateFloat(E->getSubExpr(), Result, Info);
20076 case UO_Minus:
20077 // In C standard, WG14 N2478 F.3 p4
20078 // "the unary - raises no floating point exceptions,
20079 // even if the operand is signalling."
20080 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
20081 return false;
20082 Result.changeSign();
20083 return true;
20084 }
20085}
20086
20087bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
20088 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
20089 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
20090
20091 APFloat RHS(0.0);
20092 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
20093 if (!LHSOK && !Info.noteFailure())
20094 return false;
20095 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
20096 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
20097}
20098
20099bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
20100 Result = E->getValue();
20101 return true;
20102}
20103
20104bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
20105 const Expr* SubExpr = E->getSubExpr();
20106
20107 switch (E->getCastKind()) {
20108 default:
20109 return ExprEvaluatorBaseTy::VisitCastExpr(E);
20110
20111 case CK_HLSLAggregateSplatCast:
20112 llvm_unreachable("invalid cast kind for floating value");
20113
20114 case CK_IntegralToFloating: {
20115 APSInt IntResult;
20116 const FPOptions FPO = E->getFPFeaturesInEffect(
20117 Info.Ctx.getLangOpts());
20118 return EvaluateInteger(SubExpr, IntResult, Info) &&
20119 HandleIntToFloatCast(Info, E, FPO, SubExpr->getType(),
20120 IntResult, E->getType(), Result);
20121 }
20122
20123 case CK_FixedPointToFloating: {
20124 APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
20125 if (!EvaluateFixedPoint(SubExpr, FixResult, Info))
20126 return false;
20127 Result =
20128 FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->getType()));
20129 return true;
20130 }
20131
20132 case CK_FloatingCast: {
20133 if (!Visit(SubExpr))
20134 return false;
20135 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
20136 Result);
20137 }
20138
20139 case CK_FloatingComplexToReal: {
20140 ComplexValue V;
20141 if (!EvaluateComplex(SubExpr, V, Info))
20142 return false;
20143 Result = V.getComplexFloatReal();
20144 return true;
20145 }
20146 case CK_HLSLVectorTruncation: {
20147 APValue Val;
20148 if (!EvaluateVector(SubExpr, Val, Info))
20149 return Error(E);
20150 return Success(Val.getVectorElt(0), E);
20151 }
20152 case CK_HLSLMatrixTruncation: {
20153 APValue Val;
20154 if (!EvaluateMatrix(SubExpr, Val, Info))
20155 return Error(E);
20156 return Success(Val.getMatrixElt(0, 0), E);
20157 }
20158 case CK_HLSLElementwiseCast: {
20159 SmallVector<APValue> SrcVals;
20160 SmallVector<QualType> SrcTypes;
20161
20162 if (!hlslElementwiseCastHelper(Info, SubExpr, E->getType(), SrcVals,
20163 SrcTypes))
20164 return false;
20165 APValue Val;
20166
20167 // cast our single element
20168 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
20169 APValue ResultVal;
20170 if (!handleScalarCast(Info, FPO, E, SrcTypes[0], E->getType(), SrcVals[0],
20171 ResultVal))
20172 return false;
20173 return Success(ResultVal, E);
20174 }
20175 }
20176}
20177
20178//===----------------------------------------------------------------------===//
20179// Complex Evaluation (for float and integer)
20180//===----------------------------------------------------------------------===//
20181
20182namespace {
20183class ComplexExprEvaluator
20184 : public ExprEvaluatorBase<ComplexExprEvaluator> {
20185 ComplexValue &Result;
20186
20187public:
20188 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
20189 : ExprEvaluatorBaseTy(info), Result(Result) {}
20190
20191 bool Success(const APValue &V, const Expr *e) {
20192 Result.setFrom(V);
20193 return true;
20194 }
20195
20196 bool ZeroInitialization(const Expr *E);
20197
20198 //===--------------------------------------------------------------------===//
20199 // Visitor Methods
20200 //===--------------------------------------------------------------------===//
20201
20202 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
20203 bool VisitCastExpr(const CastExpr *E);
20204 bool VisitBinaryOperator(const BinaryOperator *E);
20205 bool VisitUnaryOperator(const UnaryOperator *E);
20206 bool VisitInitListExpr(const InitListExpr *E);
20207 bool VisitCallExpr(const CallExpr *E);
20208};
20209} // end anonymous namespace
20210
20211static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
20212 EvalInfo &Info) {
20213 assert(!E->isValueDependent());
20214 assert(E->isPRValue() && E->getType()->isAnyComplexType());
20215 return ComplexExprEvaluator(Info, Result).Visit(E);
20216}
20217
20218bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
20219 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
20220 if (ElemTy->isRealFloatingType()) {
20221 Result.makeComplexFloat();
20222 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
20223 Result.FloatReal = Zero;
20224 Result.FloatImag = Zero;
20225 } else {
20226 Result.makeComplexInt();
20227 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
20228 Result.IntReal = Zero;
20229 Result.IntImag = Zero;
20230 }
20231 return true;
20232}
20233
20234bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
20235 const Expr* SubExpr = E->getSubExpr();
20236
20237 if (SubExpr->getType()->isRealFloatingType()) {
20238 Result.makeComplexFloat();
20239 APFloat &Imag = Result.FloatImag;
20240 if (!EvaluateFloat(SubExpr, Imag, Info))
20241 return false;
20242
20243 Result.FloatReal = APFloat(Imag.getSemantics());
20244 return true;
20245 } else {
20246 assert(SubExpr->getType()->isIntegerType() &&
20247 "Unexpected imaginary literal.");
20248
20249 Result.makeComplexInt();
20250 APSInt &Imag = Result.IntImag;
20251 if (!EvaluateInteger(SubExpr, Imag, Info))
20252 return false;
20253
20254 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
20255 return true;
20256 }
20257}
20258
20259bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
20260
20261 switch (E->getCastKind()) {
20262 case CK_BitCast:
20263 case CK_BaseToDerived:
20264 case CK_DerivedToBase:
20265 case CK_UncheckedDerivedToBase:
20266 case CK_Dynamic:
20267 case CK_ToUnion:
20268 case CK_ArrayToPointerDecay:
20269 case CK_FunctionToPointerDecay:
20270 case CK_NullToPointer:
20271 case CK_NullToMemberPointer:
20272 case CK_BaseToDerivedMemberPointer:
20273 case CK_DerivedToBaseMemberPointer:
20274 case CK_MemberPointerToBoolean:
20275 case CK_ReinterpretMemberPointer:
20276 case CK_ConstructorConversion:
20277 case CK_IntegralToPointer:
20278 case CK_PointerToIntegral:
20279 case CK_PointerToBoolean:
20280 case CK_ToVoid:
20281 case CK_VectorSplat:
20282 case CK_IntegralCast:
20283 case CK_BooleanToSignedIntegral:
20284 case CK_IntegralToBoolean:
20285 case CK_IntegralToFloating:
20286 case CK_FloatingToIntegral:
20287 case CK_FloatingToBoolean:
20288 case CK_FloatingCast:
20289 case CK_CPointerToObjCPointerCast:
20290 case CK_BlockPointerToObjCPointerCast:
20291 case CK_AnyPointerToBlockPointerCast:
20292 case CK_ObjCObjectLValueCast:
20293 case CK_FloatingComplexToReal:
20294 case CK_FloatingComplexToBoolean:
20295 case CK_IntegralComplexToReal:
20296 case CK_IntegralComplexToBoolean:
20297 case CK_ARCProduceObject:
20298 case CK_ARCConsumeObject:
20299 case CK_ARCReclaimReturnedObject:
20300 case CK_ARCExtendBlockObject:
20301 case CK_CopyAndAutoreleaseBlockObject:
20302 case CK_BuiltinFnToFnPtr:
20303 case CK_ZeroToOCLOpaqueType:
20304 case CK_NonAtomicToAtomic:
20305 case CK_AddressSpaceConversion:
20306 case CK_IntToOCLSampler:
20307 case CK_FloatingToFixedPoint:
20308 case CK_FixedPointToFloating:
20309 case CK_FixedPointCast:
20310 case CK_FixedPointToBoolean:
20311 case CK_FixedPointToIntegral:
20312 case CK_IntegralToFixedPoint:
20313 case CK_MatrixCast:
20314 case CK_HLSLVectorTruncation:
20315 case CK_HLSLMatrixTruncation:
20316 case CK_HLSLElementwiseCast:
20317 case CK_HLSLAggregateSplatCast:
20318 llvm_unreachable("invalid cast kind for complex value");
20319
20320 case CK_LValueToRValue:
20321 case CK_AtomicToNonAtomic:
20322 case CK_NoOp:
20323 case CK_LValueToRValueBitCast:
20324 case CK_HLSLArrayRValue:
20325 return ExprEvaluatorBaseTy::VisitCastExpr(E);
20326
20327 case CK_Dependent:
20328 case CK_LValueBitCast:
20329 case CK_UserDefinedConversion:
20330 return Error(E);
20331
20332 case CK_FloatingRealToComplex: {
20333 APFloat &Real = Result.FloatReal;
20334 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
20335 return false;
20336
20337 Result.makeComplexFloat();
20338 Result.FloatImag = APFloat(Real.getSemantics());
20339 return true;
20340 }
20341
20342 case CK_FloatingComplexCast: {
20343 if (!Visit(E->getSubExpr()))
20344 return false;
20345
20346 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
20347 QualType From
20348 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
20349
20350 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
20351 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
20352 }
20353
20354 case CK_FloatingComplexToIntegralComplex: {
20355 if (!Visit(E->getSubExpr()))
20356 return false;
20357
20358 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
20359 QualType From
20360 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
20361 Result.makeComplexInt();
20362 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
20363 To, Result.IntReal) &&
20364 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
20365 To, Result.IntImag);
20366 }
20367
20368 case CK_IntegralRealToComplex: {
20369 APSInt &Real = Result.IntReal;
20370 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
20371 return false;
20372
20373 Result.makeComplexInt();
20374 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
20375 return true;
20376 }
20377
20378 case CK_IntegralComplexCast: {
20379 if (!Visit(E->getSubExpr()))
20380 return false;
20381
20382 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
20383 QualType From
20384 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
20385
20386 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
20387 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
20388 return true;
20389 }
20390
20391 case CK_IntegralComplexToFloatingComplex: {
20392 if (!Visit(E->getSubExpr()))
20393 return false;
20394
20395 const FPOptions FPO = E->getFPFeaturesInEffect(
20396 Info.Ctx.getLangOpts());
20397 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
20398 QualType From
20399 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
20400 Result.makeComplexFloat();
20401 return HandleIntToFloatCast(Info, E, FPO, From, Result.IntReal,
20402 To, Result.FloatReal) &&
20403 HandleIntToFloatCast(Info, E, FPO, From, Result.IntImag,
20404 To, Result.FloatImag);
20405 }
20406 }
20407
20408 llvm_unreachable("unknown cast resulting in complex value");
20409}
20410
20411uint8_t GFNIMultiplicativeInverse(uint8_t Byte) {
20412 // Lookup Table for Multiplicative Inverse in GF(2^8)
20413 const uint8_t GFInv[256] = {
20414 0x00, 0x01, 0x8d, 0xf6, 0xcb, 0x52, 0x7b, 0xd1, 0xe8, 0x4f, 0x29, 0xc0,
20415 0xb0, 0xe1, 0xe5, 0xc7, 0x74, 0xb4, 0xaa, 0x4b, 0x99, 0x2b, 0x60, 0x5f,
20416 0x58, 0x3f, 0xfd, 0xcc, 0xff, 0x40, 0xee, 0xb2, 0x3a, 0x6e, 0x5a, 0xf1,
20417 0x55, 0x4d, 0xa8, 0xc9, 0xc1, 0x0a, 0x98, 0x15, 0x30, 0x44, 0xa2, 0xc2,
20418 0x2c, 0x45, 0x92, 0x6c, 0xf3, 0x39, 0x66, 0x42, 0xf2, 0x35, 0x20, 0x6f,
20419 0x77, 0xbb, 0x59, 0x19, 0x1d, 0xfe, 0x37, 0x67, 0x2d, 0x31, 0xf5, 0x69,
20420 0xa7, 0x64, 0xab, 0x13, 0x54, 0x25, 0xe9, 0x09, 0xed, 0x5c, 0x05, 0xca,
20421 0x4c, 0x24, 0x87, 0xbf, 0x18, 0x3e, 0x22, 0xf0, 0x51, 0xec, 0x61, 0x17,
20422 0x16, 0x5e, 0xaf, 0xd3, 0x49, 0xa6, 0x36, 0x43, 0xf4, 0x47, 0x91, 0xdf,
20423 0x33, 0x93, 0x21, 0x3b, 0x79, 0xb7, 0x97, 0x85, 0x10, 0xb5, 0xba, 0x3c,
20424 0xb6, 0x70, 0xd0, 0x06, 0xa1, 0xfa, 0x81, 0x82, 0x83, 0x7e, 0x7f, 0x80,
20425 0x96, 0x73, 0xbe, 0x56, 0x9b, 0x9e, 0x95, 0xd9, 0xf7, 0x02, 0xb9, 0xa4,
20426 0xde, 0x6a, 0x32, 0x6d, 0xd8, 0x8a, 0x84, 0x72, 0x2a, 0x14, 0x9f, 0x88,
20427 0xf9, 0xdc, 0x89, 0x9a, 0xfb, 0x7c, 0x2e, 0xc3, 0x8f, 0xb8, 0x65, 0x48,
20428 0x26, 0xc8, 0x12, 0x4a, 0xce, 0xe7, 0xd2, 0x62, 0x0c, 0xe0, 0x1f, 0xef,
20429 0x11, 0x75, 0x78, 0x71, 0xa5, 0x8e, 0x76, 0x3d, 0xbd, 0xbc, 0x86, 0x57,
20430 0x0b, 0x28, 0x2f, 0xa3, 0xda, 0xd4, 0xe4, 0x0f, 0xa9, 0x27, 0x53, 0x04,
20431 0x1b, 0xfc, 0xac, 0xe6, 0x7a, 0x07, 0xae, 0x63, 0xc5, 0xdb, 0xe2, 0xea,
20432 0x94, 0x8b, 0xc4, 0xd5, 0x9d, 0xf8, 0x90, 0x6b, 0xb1, 0x0d, 0xd6, 0xeb,
20433 0xc6, 0x0e, 0xcf, 0xad, 0x08, 0x4e, 0xd7, 0xe3, 0x5d, 0x50, 0x1e, 0xb3,
20434 0x5b, 0x23, 0x38, 0x34, 0x68, 0x46, 0x03, 0x8c, 0xdd, 0x9c, 0x7d, 0xa0,
20435 0xcd, 0x1a, 0x41, 0x1c};
20436
20437 return GFInv[Byte];
20438}
20439
20440uint8_t GFNIAffine(uint8_t XByte, const APInt &AQword, const APSInt &Imm,
20441 bool Inverse) {
20442 unsigned NumBitsInByte = 8;
20443 // Computing the affine transformation
20444 uint8_t RetByte = 0;
20445 for (uint32_t BitIdx = 0; BitIdx != NumBitsInByte; ++BitIdx) {
20446 uint8_t AByte =
20447 AQword.lshr((7 - static_cast<int32_t>(BitIdx)) * NumBitsInByte)
20448 .getLoBits(8)
20449 .getZExtValue();
20450 uint8_t Product;
20451 if (Inverse) {
20452 Product = AByte & GFNIMultiplicativeInverse(XByte);
20453 } else {
20454 Product = AByte & XByte;
20455 }
20456 uint8_t Parity = 0;
20457
20458 // Dot product in GF(2) uses XOR instead of addition
20459 for (unsigned PBitIdx = 0; PBitIdx != NumBitsInByte; ++PBitIdx) {
20460 Parity = Parity ^ ((Product >> PBitIdx) & 0x1);
20461 }
20462
20463 uint8_t Temp = Imm[BitIdx] ? 1 : 0;
20464 RetByte |= (Temp ^ Parity) << BitIdx;
20465 }
20466 return RetByte;
20467}
20468
20469uint8_t GFNIMul(uint8_t AByte, uint8_t BByte) {
20470 // Multiplying two polynomials of degree 7
20471 // Polynomial of degree 7
20472 // x^7 + x^6 + x^5 + x^4 + x^3 + x^2 + x + 1
20473 uint16_t TWord = 0;
20474 unsigned NumBitsInByte = 8;
20475 for (unsigned BitIdx = 0; BitIdx != NumBitsInByte; ++BitIdx) {
20476 if ((BByte >> BitIdx) & 0x1) {
20477 TWord = TWord ^ (AByte << BitIdx);
20478 }
20479 }
20480
20481 // When multiplying two polynomials of degree 7
20482 // results in a polynomial of degree 14
20483 // so the result has to be reduced to 7
20484 // Reduction polynomial is x^8 + x^4 + x^3 + x + 1 i.e. 0x11B
20485 for (int32_t BitIdx = 14; BitIdx > 7; --BitIdx) {
20486 if ((TWord >> BitIdx) & 0x1) {
20487 TWord = TWord ^ (0x11B << (BitIdx - 8));
20488 }
20489 }
20490 return (TWord & 0xFF);
20491}
20492
20493void HandleComplexComplexMul(APFloat A, APFloat B, APFloat C, APFloat D,
20494 APFloat &ResR, APFloat &ResI) {
20495 // This is an implementation of complex multiplication according to the
20496 // constraints laid out in C11 Annex G. The implementation uses the
20497 // following naming scheme:
20498 // (a + ib) * (c + id)
20499
20500 APFloat AC = A * C;
20501 APFloat BD = B * D;
20502 APFloat AD = A * D;
20503 APFloat BC = B * C;
20504 ResR = AC - BD;
20505 ResI = AD + BC;
20506 if (ResR.isNaN() && ResI.isNaN()) {
20507 bool Recalc = false;
20508 if (A.isInfinity() || B.isInfinity()) {
20509 A = APFloat::copySign(APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0),
20510 A);
20511 B = APFloat::copySign(APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0),
20512 B);
20513 if (C.isNaN())
20514 C = APFloat::copySign(APFloat(C.getSemantics()), C);
20515 if (D.isNaN())
20516 D = APFloat::copySign(APFloat(D.getSemantics()), D);
20517 Recalc = true;
20518 }
20519 if (C.isInfinity() || D.isInfinity()) {
20520 C = APFloat::copySign(APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0),
20521 C);
20522 D = APFloat::copySign(APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0),
20523 D);
20524 if (A.isNaN())
20525 A = APFloat::copySign(APFloat(A.getSemantics()), A);
20526 if (B.isNaN())
20527 B = APFloat::copySign(APFloat(B.getSemantics()), B);
20528 Recalc = true;
20529 }
20530 if (!Recalc && (AC.isInfinity() || BD.isInfinity() || AD.isInfinity() ||
20531 BC.isInfinity())) {
20532 if (A.isNaN())
20533 A = APFloat::copySign(APFloat(A.getSemantics()), A);
20534 if (B.isNaN())
20535 B = APFloat::copySign(APFloat(B.getSemantics()), B);
20536 if (C.isNaN())
20537 C = APFloat::copySign(APFloat(C.getSemantics()), C);
20538 if (D.isNaN())
20539 D = APFloat::copySign(APFloat(D.getSemantics()), D);
20540 Recalc = true;
20541 }
20542 if (Recalc) {
20543 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
20544 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
20545 }
20546 }
20547}
20548
20549void HandleComplexComplexDiv(APFloat A, APFloat B, APFloat C, APFloat D,
20550 APFloat &ResR, APFloat &ResI) {
20551 // This is an implementation of complex division according to the
20552 // constraints laid out in C11 Annex G. The implementation uses the
20553 // following naming scheme:
20554 // (a + ib) / (c + id)
20555
20556 int DenomLogB = 0;
20557 APFloat MaxCD = maxnum(abs(C), abs(D));
20558 if (MaxCD.isFinite()) {
20559 DenomLogB = ilogb(MaxCD);
20560 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
20561 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
20562 }
20563 APFloat Denom = C * C + D * D;
20564 ResR =
20565 scalbn((A * C + B * D) / Denom, -DenomLogB, APFloat::rmNearestTiesToEven);
20566 ResI =
20567 scalbn((B * C - A * D) / Denom, -DenomLogB, APFloat::rmNearestTiesToEven);
20568 if (ResR.isNaN() && ResI.isNaN()) {
20569 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
20570 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
20571 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
20572 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
20573 D.isFinite()) {
20574 A = APFloat::copySign(APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0),
20575 A);
20576 B = APFloat::copySign(APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0),
20577 B);
20578 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
20579 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
20580 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
20581 C = APFloat::copySign(APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0),
20582 C);
20583 D = APFloat::copySign(APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0),
20584 D);
20585 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
20586 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
20587 }
20588 }
20589}
20590
20592 // Normalize shift amount to [0, BitWidth) range to match runtime behavior
20593 APSInt NormAmt = Amount;
20594 unsigned BitWidth = Value.getBitWidth();
20595 unsigned AmtBitWidth = NormAmt.getBitWidth();
20596 if (BitWidth == 1) {
20597 // Rotating a 1-bit value is always a no-op
20598 NormAmt = APSInt(APInt(AmtBitWidth, 0), NormAmt.isUnsigned());
20599 } else if (BitWidth == 2) {
20600 // For 2-bit values: rotation amount is 0 or 1 based on
20601 // whether the amount is even or odd. We can't use srem here because
20602 // the divisor (2) would be misinterpreted as -2 in 2-bit signed arithmetic.
20603 NormAmt =
20604 APSInt(APInt(AmtBitWidth, NormAmt[0] ? 1 : 0), NormAmt.isUnsigned());
20605 } else {
20606 APInt Divisor;
20607 if (AmtBitWidth > BitWidth) {
20608 Divisor = llvm::APInt(AmtBitWidth, BitWidth);
20609 } else {
20610 Divisor = llvm::APInt(BitWidth, BitWidth);
20611 if (AmtBitWidth < BitWidth) {
20612 NormAmt = NormAmt.extend(BitWidth);
20613 }
20614 }
20615
20616 // Normalize to [0, BitWidth)
20617 if (NormAmt.isSigned()) {
20618 NormAmt = APSInt(NormAmt.srem(Divisor), /*isUnsigned=*/false);
20619 if (NormAmt.isNegative()) {
20620 APSInt SignedDivisor(Divisor, /*isUnsigned=*/false);
20621 NormAmt += SignedDivisor;
20622 }
20623 } else {
20624 NormAmt = APSInt(NormAmt.urem(Divisor), /*isUnsigned=*/true);
20625 }
20626 }
20627
20628 return NormAmt;
20629}
20630
20631bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
20632 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
20633 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
20634
20635 // Track whether the LHS or RHS is real at the type system level. When this is
20636 // the case we can simplify our evaluation strategy.
20637 bool LHSReal = false, RHSReal = false;
20638
20639 bool LHSOK;
20640 if (E->getLHS()->getType()->isRealFloatingType()) {
20641 LHSReal = true;
20642 APFloat &Real = Result.FloatReal;
20643 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
20644 if (LHSOK) {
20645 Result.makeComplexFloat();
20646 Result.FloatImag = APFloat(Real.getSemantics());
20647 }
20648 } else {
20649 LHSOK = Visit(E->getLHS());
20650 }
20651 if (!LHSOK && !Info.noteFailure())
20652 return false;
20653
20654 ComplexValue RHS;
20655 if (E->getRHS()->getType()->isRealFloatingType()) {
20656 RHSReal = true;
20657 APFloat &Real = RHS.FloatReal;
20658 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
20659 return false;
20660 RHS.makeComplexFloat();
20661 RHS.FloatImag = APFloat(Real.getSemantics());
20662 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
20663 return false;
20664
20665 assert(!(LHSReal && RHSReal) &&
20666 "Cannot have both operands of a complex operation be real.");
20667 switch (E->getOpcode()) {
20668 default: return Error(E);
20669 case BO_Add:
20670 if (Result.isComplexFloat()) {
20671 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
20672 APFloat::rmNearestTiesToEven);
20673 if (LHSReal)
20674 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
20675 else if (!RHSReal)
20676 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
20677 APFloat::rmNearestTiesToEven);
20678 } else {
20679 Result.getComplexIntReal() += RHS.getComplexIntReal();
20680 Result.getComplexIntImag() += RHS.getComplexIntImag();
20681 }
20682 break;
20683 case BO_Sub:
20684 if (Result.isComplexFloat()) {
20685 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
20686 APFloat::rmNearestTiesToEven);
20687 if (LHSReal) {
20688 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
20689 Result.getComplexFloatImag().changeSign();
20690 } else if (!RHSReal) {
20691 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
20692 APFloat::rmNearestTiesToEven);
20693 }
20694 } else {
20695 Result.getComplexIntReal() -= RHS.getComplexIntReal();
20696 Result.getComplexIntImag() -= RHS.getComplexIntImag();
20697 }
20698 break;
20699 case BO_Mul:
20700 if (Result.isComplexFloat()) {
20701 // This is an implementation of complex multiplication according to the
20702 // constraints laid out in C11 Annex G. The implementation uses the
20703 // following naming scheme:
20704 // (a + ib) * (c + id)
20705 ComplexValue LHS = Result;
20706 APFloat &A = LHS.getComplexFloatReal();
20707 APFloat &B = LHS.getComplexFloatImag();
20708 APFloat &C = RHS.getComplexFloatReal();
20709 APFloat &D = RHS.getComplexFloatImag();
20710 APFloat &ResR = Result.getComplexFloatReal();
20711 APFloat &ResI = Result.getComplexFloatImag();
20712 if (LHSReal) {
20713 assert(!RHSReal && "Cannot have two real operands for a complex op!");
20714 ResR = A;
20715 ResI = A;
20716 // ResR = A * C;
20717 // ResI = A * D;
20718 if (!handleFloatFloatBinOp(Info, E, ResR, BO_Mul, C) ||
20719 !handleFloatFloatBinOp(Info, E, ResI, BO_Mul, D))
20720 return false;
20721 } else if (RHSReal) {
20722 // ResR = C * A;
20723 // ResI = C * B;
20724 ResR = C;
20725 ResI = C;
20726 if (!handleFloatFloatBinOp(Info, E, ResR, BO_Mul, A) ||
20727 !handleFloatFloatBinOp(Info, E, ResI, BO_Mul, B))
20728 return false;
20729 } else {
20730 HandleComplexComplexMul(A, B, C, D, ResR, ResI);
20731 }
20732 } else {
20733 ComplexValue LHS = Result;
20734 Result.getComplexIntReal() =
20735 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
20736 LHS.getComplexIntImag() * RHS.getComplexIntImag());
20737 Result.getComplexIntImag() =
20738 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
20739 LHS.getComplexIntImag() * RHS.getComplexIntReal());
20740 }
20741 break;
20742 case BO_Div:
20743 if (Result.isComplexFloat()) {
20744 // This is an implementation of complex division according to the
20745 // constraints laid out in C11 Annex G. The implementation uses the
20746 // following naming scheme:
20747 // (a + ib) / (c + id)
20748 ComplexValue LHS = Result;
20749 APFloat &A = LHS.getComplexFloatReal();
20750 APFloat &B = LHS.getComplexFloatImag();
20751 APFloat &C = RHS.getComplexFloatReal();
20752 APFloat &D = RHS.getComplexFloatImag();
20753 APFloat &ResR = Result.getComplexFloatReal();
20754 APFloat &ResI = Result.getComplexFloatImag();
20755 if (RHSReal) {
20756 ResR = A;
20757 ResI = B;
20758 // ResR = A / C;
20759 // ResI = B / C;
20760 if (!handleFloatFloatBinOp(Info, E, ResR, BO_Div, C) ||
20761 !handleFloatFloatBinOp(Info, E, ResI, BO_Div, C))
20762 return false;
20763 } else {
20764 if (LHSReal) {
20765 // No real optimizations we can do here, stub out with zero.
20766 B = APFloat::getZero(A.getSemantics());
20767 }
20768 HandleComplexComplexDiv(A, B, C, D, ResR, ResI);
20769 }
20770 } else {
20771 ComplexValue LHS = Result;
20772 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
20773 RHS.getComplexIntImag() * RHS.getComplexIntImag();
20774 if (Den.isZero())
20775 return Error(E, diag::note_expr_divide_by_zero);
20776
20777 Result.getComplexIntReal() =
20778 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
20779 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
20780 Result.getComplexIntImag() =
20781 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
20782 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
20783 }
20784 break;
20785 }
20786
20787 return true;
20788}
20789
20790bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
20791 // Get the operand value into 'Result'.
20792 if (!Visit(E->getSubExpr()))
20793 return false;
20794
20795 switch (E->getOpcode()) {
20796 default:
20797 return Error(E);
20798 case UO_Extension:
20799 return true;
20800 case UO_Plus:
20801 // The result is always just the subexpr.
20802 return true;
20803 case UO_Minus:
20804 if (Result.isComplexFloat()) {
20805 Result.getComplexFloatReal().changeSign();
20806 Result.getComplexFloatImag().changeSign();
20807 }
20808 else {
20809 Result.getComplexIntReal() = -Result.getComplexIntReal();
20810 Result.getComplexIntImag() = -Result.getComplexIntImag();
20811 }
20812 return true;
20813 case UO_Not:
20814 if (Result.isComplexFloat())
20815 Result.getComplexFloatImag().changeSign();
20816 else
20817 Result.getComplexIntImag() = -Result.getComplexIntImag();
20818 return true;
20819 }
20820}
20821
20822bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
20823 if (E->getNumInits() == 2) {
20824 if (E->getType()->isComplexType()) {
20825 Result.makeComplexFloat();
20826 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
20827 return false;
20828 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
20829 return false;
20830 } else {
20831 Result.makeComplexInt();
20832 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
20833 return false;
20834 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
20835 return false;
20836 }
20837 return true;
20838 }
20839 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
20840}
20841
20842bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) {
20843 if (!IsConstantEvaluatedBuiltinCall(E))
20844 return ExprEvaluatorBaseTy::VisitCallExpr(E);
20845
20846 switch (E->getBuiltinCallee()) {
20847 case Builtin::BI__builtin_complex:
20848 Result.makeComplexFloat();
20849 if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info))
20850 return false;
20851 if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info))
20852 return false;
20853 return true;
20854
20855 default:
20856 return false;
20857 }
20858}
20859
20860//===----------------------------------------------------------------------===//
20861// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
20862// implicit conversion.
20863//===----------------------------------------------------------------------===//
20864
20865namespace {
20866class AtomicExprEvaluator :
20867 public ExprEvaluatorBase<AtomicExprEvaluator> {
20868 const LValue *This;
20869 APValue &Result;
20870public:
20871 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
20872 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
20873
20874 bool Success(const APValue &V, const Expr *E) {
20875 Result = V;
20876 return true;
20877 }
20878
20879 bool ZeroInitialization(const Expr *E) {
20880 ImplicitValueInitExpr VIE(
20881 E->getType()->castAs<AtomicType>()->getValueType());
20882 // For atomic-qualified class (and array) types in C++, initialize the
20883 // _Atomic-wrapped subobject directly, in-place.
20884 return This ? EvaluateInPlace(Result, Info, *This, &VIE)
20885 : Evaluate(Result, Info, &VIE);
20886 }
20887
20888 bool VisitCastExpr(const CastExpr *E) {
20889 switch (E->getCastKind()) {
20890 default:
20891 return ExprEvaluatorBaseTy::VisitCastExpr(E);
20892 case CK_NullToPointer:
20893 VisitIgnoredValue(E->getSubExpr());
20894 return ZeroInitialization(E);
20895 case CK_NonAtomicToAtomic:
20896 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
20897 : Evaluate(Result, Info, E->getSubExpr());
20898 }
20899 }
20900};
20901} // end anonymous namespace
20902
20903static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
20904 EvalInfo &Info) {
20905 assert(!E->isValueDependent());
20906 assert(E->isPRValue() && E->getType()->isAtomicType());
20907 return AtomicExprEvaluator(Info, This, Result).Visit(E);
20908}
20909
20910//===----------------------------------------------------------------------===//
20911// Void expression evaluation, primarily for a cast to void on the LHS of a
20912// comma operator
20913//===----------------------------------------------------------------------===//
20914
20915namespace {
20916class VoidExprEvaluator
20917 : public ExprEvaluatorBase<VoidExprEvaluator> {
20918public:
20919 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
20920
20921 bool Success(const APValue &V, const Expr *e) { return true; }
20922
20923 bool ZeroInitialization(const Expr *E) { return true; }
20924
20925 bool VisitCastExpr(const CastExpr *E) {
20926 switch (E->getCastKind()) {
20927 default:
20928 return ExprEvaluatorBaseTy::VisitCastExpr(E);
20929 case CK_ToVoid:
20930 VisitIgnoredValue(E->getSubExpr());
20931 return true;
20932 }
20933 }
20934
20935 bool VisitCallExpr(const CallExpr *E) {
20936 if (!IsConstantEvaluatedBuiltinCall(E))
20937 return ExprEvaluatorBaseTy::VisitCallExpr(E);
20938
20939 switch (E->getBuiltinCallee()) {
20940 case Builtin::BI__assume:
20941 case Builtin::BI__builtin_assume:
20942 // The argument is not evaluated!
20943 return true;
20944
20945 case Builtin::BI__builtin_operator_delete:
20946 return HandleOperatorDeleteCall(Info, E);
20947
20948 default:
20949 return false;
20950 }
20951 }
20952
20953 bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
20954};
20955} // end anonymous namespace
20956
20957bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
20958 // We cannot speculatively evaluate a delete expression.
20959 if (Info.SpeculativeEvaluationDepth)
20960 return false;
20961
20962 FunctionDecl *OperatorDelete = E->getOperatorDelete();
20963 if (!OperatorDelete
20964 ->isUsableAsGlobalAllocationFunctionInConstantEvaluation()) {
20965 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
20966 << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;
20967 return false;
20968 }
20969
20970 const Expr *Arg = E->getArgument();
20971
20972 LValue Pointer;
20973 if (!EvaluatePointer(Arg, Pointer, Info))
20974 return false;
20975 if (Pointer.Designator.Invalid)
20976 return false;
20977
20978 // Deleting a null pointer has no effect.
20979 if (Pointer.isNullPointer()) {
20980 // This is the only case where we need to produce an extension warning:
20981 // the only other way we can succeed is if we find a dynamic allocation,
20982 // and we will have warned when we allocated it in that case.
20983 if (!Info.getLangOpts().CPlusPlus20)
20984 Info.CCEDiag(E, diag::note_constexpr_new);
20985 return true;
20986 }
20987
20988 std::optional<DynAlloc *> Alloc = CheckDeleteKind(
20989 Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New);
20990 if (!Alloc)
20991 return false;
20992 QualType AllocType = Pointer.Base.getDynamicAllocType();
20993
20994 // For the non-array case, the designator must be empty if the static type
20995 // does not have a virtual destructor.
20996 if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 &&
20998 Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor)
20999 << Arg->getType()->getPointeeType() << AllocType;
21000 return false;
21001 }
21002
21003 // For a class type with a virtual destructor, the selected operator delete
21004 // is the one looked up when building the destructor.
21005 if (!E->isArrayForm() && !E->isGlobalDelete()) {
21006 const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType);
21007 if (VirtualDelete &&
21008 !VirtualDelete
21009 ->isUsableAsGlobalAllocationFunctionInConstantEvaluation()) {
21010 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
21011 << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete;
21012 return false;
21013 }
21014 }
21015
21016 if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(),
21017 (*Alloc)->Value, AllocType))
21018 return false;
21019
21020 if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) {
21021 // The element was already erased. This means the destructor call also
21022 // deleted the object.
21023 // FIXME: This probably results in undefined behavior before we get this
21024 // far, and should be diagnosed elsewhere first.
21025 Info.FFDiag(E, diag::note_constexpr_double_delete);
21026 return false;
21027 }
21028
21029 return true;
21030}
21031
21032static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
21033 assert(!E->isValueDependent());
21034 assert(E->isPRValue() && E->getType()->isVoidType());
21035 return VoidExprEvaluator(Info).Visit(E);
21036}
21037
21038//===----------------------------------------------------------------------===//
21039// Top level Expr::EvaluateAsRValue method.
21040//===----------------------------------------------------------------------===//
21041
21042static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
21043 assert(!E->isValueDependent());
21044 // In C, function designators are not lvalues, but we evaluate them as if they
21045 // are.
21046 QualType T = E->getType();
21047 if (E->isGLValue() || T->isFunctionType()) {
21048 LValue LV;
21049 if (!EvaluateLValue(E, LV, Info))
21050 return false;
21051 LV.moveInto(Result);
21052 } else if (T->isVectorType()) {
21053 if (!EvaluateVector(E, Result, Info))
21054 return false;
21055 } else if (T->isConstantMatrixType()) {
21056 if (!EvaluateMatrix(E, Result, Info))
21057 return false;
21058 } else if (T->isIntegralOrEnumerationType()) {
21059 if (!IntExprEvaluator(Info, Result).Visit(E))
21060 return false;
21061 } else if (T->hasPointerRepresentation()) {
21062 LValue LV;
21063 if (!EvaluatePointer(E, LV, Info))
21064 return false;
21065 LV.moveInto(Result);
21066 } else if (T->isRealFloatingType()) {
21067 llvm::APFloat F(0.0);
21068 if (!EvaluateFloat(E, F, Info))
21069 return false;
21070 Result = APValue(F);
21071 } else if (T->isAnyComplexType()) {
21072 ComplexValue C;
21073 if (!EvaluateComplex(E, C, Info))
21074 return false;
21075 C.moveInto(Result);
21076 } else if (T->isFixedPointType()) {
21077 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
21078 } else if (T->isMemberPointerType()) {
21079 MemberPtr P;
21080 if (!EvaluateMemberPointer(E, P, Info))
21081 return false;
21082 P.moveInto(Result);
21083 return true;
21084 } else if (T->isArrayType()) {
21085 LValue LV;
21086 APValue &Value =
21087 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
21088 if (!EvaluateArray(E, LV, Value, Info))
21089 return false;
21090 Result = Value;
21091 } else if (T->isRecordType()) {
21092 LValue LV;
21093 APValue &Value =
21094 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
21095 if (!EvaluateRecord(E, LV, Value, Info))
21096 return false;
21097 Result = Value;
21098 } else if (T->isVoidType()) {
21099 if (!Info.getLangOpts().CPlusPlus11)
21100 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
21101 << E->getType();
21102 if (!EvaluateVoid(E, Info))
21103 return false;
21104 } else if (T->isAtomicType()) {
21106 if (Unqual->isArrayType() || Unqual->isRecordType()) {
21107 LValue LV;
21108 APValue &Value = Info.CurrentCall->createTemporary(
21109 E, Unqual, ScopeKind::FullExpression, LV);
21110 if (!EvaluateAtomic(E, &LV, Value, Info))
21111 return false;
21112 Result = Value;
21113 } else {
21114 if (!EvaluateAtomic(E, nullptr, Result, Info))
21115 return false;
21116 }
21117 } else if (Info.getLangOpts().CPlusPlus11) {
21118 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
21119 return false;
21120 } else {
21121 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
21122 return false;
21123 }
21124
21125 return true;
21126}
21127
21128/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
21129/// cases, the in-place evaluation is essential, since later initializers for
21130/// an object can indirectly refer to subobjects which were initialized earlier.
21131static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
21132 const Expr *E, bool AllowNonLiteralTypes) {
21133 assert(!E->isValueDependent());
21134
21135 // Normally expressions passed to EvaluateInPlace have a type, but not when
21136 // a VarDecl initializer is evaluated before the untyped ParenListExpr is
21137 // replaced with a CXXConstructExpr. This can happen in LLDB.
21138 if (E->getType().isNull())
21139 return false;
21140
21141 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
21142 return false;
21143
21144 if (E->isPRValue()) {
21145 // Evaluate arrays and record types in-place, so that later initializers can
21146 // refer to earlier-initialized members of the object.
21147 QualType T = E->getType();
21148 if (T->isArrayType())
21149 return EvaluateArray(E, This, Result, Info);
21150 else if (T->isRecordType())
21151 return EvaluateRecord(E, This, Result, Info);
21152 else if (T->isAtomicType()) {
21154 if (Unqual->isArrayType() || Unqual->isRecordType())
21155 return EvaluateAtomic(E, &This, Result, Info);
21156 }
21157 }
21158
21159 // For any other type, in-place evaluation is unimportant.
21160 return Evaluate(Result, Info, E);
21161}
21162
21163/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
21164/// lvalue-to-rvalue cast if it is an lvalue.
21165static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
21166 assert(!E->isValueDependent());
21167
21168 if (E->getType().isNull())
21169 return false;
21170
21171 if (!CheckLiteralType(Info, E))
21172 return false;
21173
21174 if (Info.EnableNewConstInterp) {
21175 if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result))
21176 return false;
21177 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
21178 ConstantExprKind::Normal);
21179 }
21180
21181 if (!::Evaluate(Result, Info, E))
21182 return false;
21183
21184 // Implicit lvalue-to-rvalue cast.
21185 if (E->isGLValue()) {
21186 LValue LV;
21187 LV.setFrom(Info.Ctx, Result);
21188 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
21189 return false;
21190 }
21191
21192 // Check this core constant expression is a constant expression.
21193 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
21194 ConstantExprKind::Normal) &&
21195 CheckMemoryLeaks(Info);
21196}
21197
21198static bool FastEvaluateAsRValue(const Expr *Exp, APValue &Result,
21199 const ASTContext &Ctx, bool &IsConst) {
21200 // Fast-path evaluations of integer literals, since we sometimes see files
21201 // containing vast quantities of these.
21202 if (const auto *L = dyn_cast<IntegerLiteral>(Exp)) {
21203 Result =
21204 APValue(APSInt(L->getValue(), L->getType()->isUnsignedIntegerType()));
21205 IsConst = true;
21206 return true;
21207 }
21208
21209 if (const auto *L = dyn_cast<CXXBoolLiteralExpr>(Exp)) {
21210 Result = APValue(APSInt(APInt(1, L->getValue())));
21211 IsConst = true;
21212 return true;
21213 }
21214
21215 if (const auto *FL = dyn_cast<FloatingLiteral>(Exp)) {
21216 Result = APValue(FL->getValue());
21217 IsConst = true;
21218 return true;
21219 }
21220
21221 if (const auto *L = dyn_cast<CharacterLiteral>(Exp)) {
21222 Result = APValue(Ctx.MakeIntValue(L->getValue(), L->getType()));
21223 IsConst = true;
21224 return true;
21225 }
21226
21227 if (const auto *CE = dyn_cast<ConstantExpr>(Exp)) {
21228 if (CE->hasAPValueResult()) {
21229 APValue APV = CE->getAPValueResult();
21230 if (!APV.isLValue()) {
21231 Result = std::move(APV);
21232 IsConst = true;
21233 return true;
21234 }
21235 }
21236
21237 // The SubExpr is usually just an IntegerLiteral.
21238 return FastEvaluateAsRValue(CE->getSubExpr(), Result, Ctx, IsConst);
21239 }
21240
21241 // This case should be rare, but we need to check it before we check on
21242 // the type below.
21243 if (Exp->getType().isNull()) {
21244 IsConst = false;
21245 return true;
21246 }
21247
21248 return false;
21249}
21250
21253 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
21254 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
21255}
21256
21258 const ASTContext &Ctx, EvalInfo &Info) {
21259 assert(!E->isValueDependent());
21260 bool IsConst;
21261 if (FastEvaluateAsRValue(E, Result.Val, Ctx, IsConst))
21262 return IsConst;
21263
21264 return EvaluateAsRValue(Info, E, Result.Val);
21265}
21266
21268 const ASTContext &Ctx,
21269 Expr::SideEffectsKind AllowSideEffects,
21270 EvalInfo &Info) {
21271 assert(!E->isValueDependent());
21273 return false;
21274
21275 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
21276 !ExprResult.Val.isInt() ||
21277 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
21278 return false;
21279
21280 return true;
21281}
21282
21284 const ASTContext &Ctx,
21285 Expr::SideEffectsKind AllowSideEffects,
21286 EvalInfo &Info) {
21287 assert(!E->isValueDependent());
21288 if (!E->getType()->isFixedPointType())
21289 return false;
21290
21291 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
21292 return false;
21293
21294 if (!ExprResult.Val.isFixedPoint() ||
21295 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
21296 return false;
21297
21298 return true;
21299}
21300
21301/// EvaluateAsRValue - Return true if this is a constant which we can fold using
21302/// any crazy technique (that has nothing to do with language standards) that
21303/// we want to. If this function returns true, it returns the folded constant
21304/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
21305/// will be applied to the result.
21307 bool InConstantContext) const {
21308 assert(!isValueDependent() &&
21309 "Expression evaluator can't be called on a dependent expression.");
21310 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsRValue");
21311 EvalInfo Info(Ctx, Result, EvaluationMode::IgnoreSideEffects);
21312 Info.InConstantContext = InConstantContext;
21313 return ::EvaluateAsRValue(this, Result, Ctx, Info);
21314}
21315
21317 bool InConstantContext) const {
21318 assert(!isValueDependent() &&
21319 "Expression evaluator can't be called on a dependent expression.");
21320 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsBooleanCondition");
21321 EvalResult Scratch;
21322 return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
21323 HandleConversionToBool(Scratch.Val, Result);
21324}
21325
21327 SideEffectsKind AllowSideEffects,
21328 bool InConstantContext) const {
21329 assert(!isValueDependent() &&
21330 "Expression evaluator can't be called on a dependent expression.");
21331 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsInt");
21332 EvalInfo Info(Ctx, Result, EvaluationMode::IgnoreSideEffects);
21333 Info.InConstantContext = InConstantContext;
21334 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
21335}
21336
21338 SideEffectsKind AllowSideEffects,
21339 bool InConstantContext) const {
21340 assert(!isValueDependent() &&
21341 "Expression evaluator can't be called on a dependent expression.");
21342 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFixedPoint");
21343 EvalInfo Info(Ctx, Result, EvaluationMode::IgnoreSideEffects);
21344 Info.InConstantContext = InConstantContext;
21345 return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
21346}
21347
21348bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
21349 SideEffectsKind AllowSideEffects,
21350 bool InConstantContext) const {
21351 assert(!isValueDependent() &&
21352 "Expression evaluator can't be called on a dependent expression.");
21353
21354 if (!getType()->isRealFloatingType())
21355 return false;
21356
21357 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFloat");
21359 if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
21360 !ExprResult.Val.isFloat() ||
21361 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
21362 return false;
21363
21364 Result = ExprResult.Val.getFloat();
21365 return true;
21366}
21367
21369 bool InConstantContext) const {
21370 assert(!isValueDependent() &&
21371 "Expression evaluator can't be called on a dependent expression.");
21372
21373 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsLValue");
21374 EvalInfo Info(Ctx, Result, EvaluationMode::ConstantFold);
21375 Info.InConstantContext = InConstantContext;
21376 LValue LV;
21377 CheckedTemporaries CheckedTemps;
21378
21379 if (Info.EnableNewConstInterp) {
21380 if (!Info.Ctx.getInterpContext().evaluate(Info, this, Result.Val,
21381 ConstantExprKind::Normal))
21382 return false;
21383
21384 LV.setFrom(Ctx, Result.Val);
21386 Info, getExprLoc(), Ctx.getLValueReferenceType(getType()), LV,
21387 ConstantExprKind::Normal, CheckedTemps);
21388 }
21389
21390 if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() ||
21391 Result.HasSideEffects ||
21394 ConstantExprKind::Normal, CheckedTemps))
21395 return false;
21396
21397 LV.moveInto(Result.Val);
21398 return true;
21399}
21400
21402 APValue DestroyedValue, QualType Type,
21403 SourceLocation Loc, Expr::EvalStatus &EStatus,
21404 bool IsConstantDestruction) {
21405 EvalInfo Info(Ctx, EStatus,
21406 IsConstantDestruction ? EvaluationMode::ConstantExpression
21408 Info.setEvaluatingDecl(Base, DestroyedValue,
21409 EvalInfo::EvaluatingDeclKind::Dtor);
21410 Info.InConstantContext = IsConstantDestruction;
21411
21412 LValue LVal;
21413 LVal.set(Base);
21414
21415 if (!HandleDestruction(Info, Loc, Base, DestroyedValue, Type) ||
21416 EStatus.HasSideEffects)
21417 return false;
21418
21419 if (!Info.discardCleanups())
21420 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
21421
21422 return true;
21423}
21424
21426 ConstantExprKind Kind) const {
21427 assert(!isValueDependent() &&
21428 "Expression evaluator can't be called on a dependent expression.");
21429 bool IsConst;
21430 if (FastEvaluateAsRValue(this, Result.Val, Ctx, IsConst) &&
21431 Result.Val.hasValue())
21432 return true;
21433
21434 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsConstantExpr");
21436 EvalInfo Info(Ctx, Result, EM);
21437 Info.InConstantContext = true;
21438
21439 if (Info.EnableNewConstInterp) {
21440 if (!Info.Ctx.getInterpContext().evaluate(Info, this, Result.Val, Kind))
21441 return false;
21442 return CheckConstantExpression(Info, getExprLoc(),
21443 getStorageType(Ctx, this), Result.Val, Kind);
21444 }
21445
21446 // The type of the object we're initializing is 'const T' for a class NTTP.
21447 QualType T = getType();
21448 if (Kind == ConstantExprKind::ClassTemplateArgument)
21449 T.addConst();
21450
21451 // If we're evaluating a prvalue, fake up a MaterializeTemporaryExpr to
21452 // represent the result of the evaluation. CheckConstantExpression ensures
21453 // this doesn't escape.
21454 MaterializeTemporaryExpr BaseMTE(T, const_cast<Expr*>(this), true);
21455 APValue::LValueBase Base(&BaseMTE);
21456 Info.setEvaluatingDecl(Base, Result.Val);
21457
21458 LValue LVal;
21459 LVal.set(Base);
21460 // C++23 [intro.execution]/p5
21461 // A full-expression is [...] a constant-expression
21462 // So we need to make sure temporary objects are destroyed after having
21463 // evaluating the expression (per C++23 [class.temporary]/p4).
21464 FullExpressionRAII Scope(Info);
21465 if (!::EvaluateInPlace(Result.Val, Info, LVal, this) ||
21466 Result.HasSideEffects || !Scope.destroy())
21467 return false;
21468
21469 if (!Info.discardCleanups())
21470 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
21471
21472 if (!CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this),
21473 Result.Val, Kind))
21474 return false;
21475 if (!CheckMemoryLeaks(Info))
21476 return false;
21477
21478 // If this is a class template argument, it's required to have constant
21479 // destruction too.
21480 if (Kind == ConstantExprKind::ClassTemplateArgument &&
21482 true) ||
21483 Result.HasSideEffects)) {
21484 // FIXME: Prefix a note to indicate that the problem is lack of constant
21485 // destruction.
21486 return false;
21487 }
21488
21489 return true;
21490}
21491
21493 const VarDecl *VD,
21495 bool IsConstantInitialization) const {
21496 assert(!isValueDependent() &&
21497 "Expression evaluator can't be called on a dependent expression.");
21498 assert(VD && "Need a valid VarDecl");
21499
21500 llvm::TimeTraceScope TimeScope("EvaluateAsInitializer", [&] {
21501 std::string Name;
21502 llvm::raw_string_ostream OS(Name);
21503 VD->printQualifiedName(OS);
21504 return Name;
21505 });
21506
21507 Expr::EvalStatus EStatus;
21508 EStatus.Diag = &Notes;
21509
21510 EvalInfo Info(Ctx, EStatus,
21511 (IsConstantInitialization &&
21512 (Ctx.getLangOpts().CPlusPlus || Ctx.getLangOpts().C23))
21515 Info.setEvaluatingDecl(VD, Value);
21516 Info.InConstantContext = IsConstantInitialization;
21517
21518 SourceLocation DeclLoc = VD->getLocation();
21519 QualType DeclTy = VD->getType();
21520
21521 if (Info.EnableNewConstInterp) {
21522 auto &InterpCtx = Ctx.getInterpContext();
21523 if (!InterpCtx.evaluateAsInitializer(Info, VD, this, Value))
21524 return false;
21525
21526 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value,
21527 ConstantExprKind::Normal);
21528 } else {
21529 LValue LVal;
21530 LVal.set(VD);
21531
21532 {
21533 // C++23 [intro.execution]/p5
21534 // A full-expression is ... an init-declarator ([dcl.decl]) or a
21535 // mem-initializer.
21536 // So we need to make sure temporary objects are destroyed after having
21537 // evaluated the expression (per C++23 [class.temporary]/p4).
21538 //
21539 // FIXME: Otherwise this may break test/Modules/pr68702.cpp because the
21540 // serialization code calls ParmVarDecl::getDefaultArg() which strips the
21541 // outermost FullExpr, such as ExprWithCleanups.
21542 FullExpressionRAII Scope(Info);
21543 if (!EvaluateInPlace(Value, Info, LVal, this,
21544 /*AllowNonLiteralTypes=*/true) ||
21545 EStatus.HasSideEffects)
21546 return false;
21547 }
21548
21549 // At this point, any lifetime-extended temporaries are completely
21550 // initialized.
21551 Info.performLifetimeExtension();
21552
21553 if (!Info.discardCleanups())
21554 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
21555 }
21556
21557 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value,
21558 ConstantExprKind::Normal) &&
21559 CheckMemoryLeaks(Info);
21560}
21561
21564 Expr::EvalStatus EStatus;
21565 EStatus.Diag = &Notes;
21566
21567 // Only treat the destruction as constant destruction if we formally have
21568 // constant initialization (or are usable in a constant expression).
21569 bool IsConstantDestruction = hasConstantInitialization();
21570 ASTContext &Ctx = getASTContext();
21571
21572 // Make a copy of the value for the destructor to mutate, if we know it.
21573 // Otherwise, treat the value as default-initialized; if the destructor works
21574 // anyway, then the destruction is constant (and must be essentially empty).
21575 APValue DestroyedValue;
21576 if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent())
21577 DestroyedValue = *getEvaluatedValue();
21578 else if (!handleDefaultInitValue(getType(), DestroyedValue))
21579 return false;
21580
21581 if (Ctx.getLangOpts().EnableNewConstInterp) {
21582 EvalInfo Info(Ctx, EStatus,
21583 IsConstantDestruction ? EvaluationMode::ConstantExpression
21585 Info.setEvaluatingDecl(this, DestroyedValue,
21586 EvalInfo::EvaluatingDeclKind::Dtor);
21587 Info.InConstantContext = IsConstantDestruction;
21588 if (!Ctx.getInterpContext().evaluateDestruction(Info, this,
21589 std::move(DestroyedValue)))
21590 return false;
21591 ensureEvaluatedStmt()->HasConstantDestruction = true;
21592 return true;
21593 }
21594
21595 if (!EvaluateDestruction(Ctx, this, std::move(DestroyedValue), getType(),
21596 getLocation(), EStatus, IsConstantDestruction) ||
21597 EStatus.HasSideEffects)
21598 return false;
21599
21600 ensureEvaluatedStmt()->HasConstantDestruction = true;
21601 return true;
21602}
21603
21604/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
21605/// constant folded, but discard the result.
21607 assert(!isValueDependent() &&
21608 "Expression evaluator can't be called on a dependent expression.");
21609
21611 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
21613}
21614
21615APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
21616 assert(!isValueDependent() &&
21617 "Expression evaluator can't be called on a dependent expression.");
21618
21619 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstInt");
21620 EvalResult EVResult;
21621 EvalInfo Info(Ctx, EVResult, EvaluationMode::IgnoreSideEffects);
21622 Info.InConstantContext = true;
21623
21624 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
21625 (void)Result;
21626 assert(Result && "Could not evaluate expression");
21627 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
21628
21629 return EVResult.Val.getInt();
21630}
21631
21634 assert(!isValueDependent() &&
21635 "Expression evaluator can't be called on a dependent expression.");
21636
21637 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstIntCheckOverflow");
21638 EvalResult EVResult;
21639 EVResult.Diag = Diag;
21640 EvalInfo Info(Ctx, EVResult, EvaluationMode::IgnoreSideEffects);
21641 Info.InConstantContext = true;
21642 Info.CheckingForUndefinedBehavior = true;
21643
21644 bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
21645 (void)Result;
21646 assert(Result && "Could not evaluate expression");
21647 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
21648
21649 return EVResult.Val.getInt();
21650}
21651
21653 assert(!isValueDependent() &&
21654 "Expression evaluator can't be called on a dependent expression.");
21655
21656 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateForOverflow");
21657 bool IsConst;
21658 EvalResult EVResult;
21659 if (!FastEvaluateAsRValue(this, EVResult.Val, Ctx, IsConst)) {
21660 EvalInfo Info(Ctx, EVResult, EvaluationMode::IgnoreSideEffects);
21661 Info.CheckingForUndefinedBehavior = true;
21662 (void)::EvaluateAsRValue(Info, this, EVResult.Val);
21663 }
21664}
21665
21667 assert(Val.isLValue());
21668 return IsGlobalLValue(Val.getLValueBase());
21669}
21670
21671/// isIntegerConstantExpr - this recursive routine will test if an expression is
21672/// an integer constant expression.
21673
21674/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
21675/// comma, etc
21676
21677// CheckICE - This function does the fundamental ICE checking: the returned
21678// ICEDiag contains an ICEKind indicating whether the expression is an ICE.
21679//
21680// Note that to reduce code duplication, this helper does no evaluation
21681// itself; the caller checks whether the expression is evaluatable, and
21682// in the rare cases where CheckICE actually cares about the evaluated
21683// value, it calls into Evaluate.
21684
21685namespace {
21686
21687enum ICEKind {
21688 /// This expression is an ICE.
21689 IK_ICE,
21690 /// This expression is not an ICE, but if it isn't evaluated, it's
21691 /// a legal subexpression for an ICE. This return value is used to handle
21692 /// the comma operator in C99 mode, and non-constant subexpressions.
21693 IK_ICEIfUnevaluated,
21694 /// This expression is not an ICE, and is not a legal subexpression for one.
21695 IK_NotICE
21696};
21697
21698struct ICEDiag {
21699 ICEKind Kind;
21700 SourceLocation Loc;
21701
21702 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
21703};
21704
21705}
21706
21707static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
21708
21709static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
21710
21711static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
21712 Expr::EvalResult EVResult;
21713 Expr::EvalStatus Status;
21714 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantExpression);
21715
21716 Info.InConstantContext = true;
21717 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
21718 !EVResult.Val.isInt())
21719 return ICEDiag(IK_NotICE, E->getBeginLoc());
21720
21721 return NoDiag();
21722}
21723
21724static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
21725 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
21727 return ICEDiag(IK_NotICE, E->getBeginLoc());
21728
21729 switch (E->getStmtClass()) {
21730#define ABSTRACT_STMT(Node)
21731#define STMT(Node, Base) case Expr::Node##Class:
21732#define EXPR(Node, Base)
21733#include "clang/AST/StmtNodes.inc"
21734 case Expr::PredefinedExprClass:
21735 case Expr::FloatingLiteralClass:
21736 case Expr::ImaginaryLiteralClass:
21737 case Expr::StringLiteralClass:
21738 case Expr::ArraySubscriptExprClass:
21739 case Expr::MatrixSingleSubscriptExprClass:
21740 case Expr::MatrixSubscriptExprClass:
21741 case Expr::ArraySectionExprClass:
21742 case Expr::OMPArrayShapingExprClass:
21743 case Expr::OMPIteratorExprClass:
21744 case Expr::CompoundAssignOperatorClass:
21745 case Expr::CompoundLiteralExprClass:
21746 case Expr::ExtVectorElementExprClass:
21747 case Expr::MatrixElementExprClass:
21748 case Expr::DesignatedInitExprClass:
21749 case Expr::ArrayInitLoopExprClass:
21750 case Expr::ArrayInitIndexExprClass:
21751 case Expr::NoInitExprClass:
21752 case Expr::DesignatedInitUpdateExprClass:
21753 case Expr::ImplicitValueInitExprClass:
21754 case Expr::ParenListExprClass:
21755 case Expr::VAArgExprClass:
21756 case Expr::AddrLabelExprClass:
21757 case Expr::StmtExprClass:
21758 case Expr::CXXMemberCallExprClass:
21759 case Expr::CUDAKernelCallExprClass:
21760 case Expr::CXXAddrspaceCastExprClass:
21761 case Expr::CXXDynamicCastExprClass:
21762 case Expr::CXXTypeidExprClass:
21763 case Expr::CXXUuidofExprClass:
21764 case Expr::MSPropertyRefExprClass:
21765 case Expr::MSPropertySubscriptExprClass:
21766 case Expr::CXXNullPtrLiteralExprClass:
21767 case Expr::UserDefinedLiteralClass:
21768 case Expr::CXXThisExprClass:
21769 case Expr::CXXThrowExprClass:
21770 case Expr::CXXNewExprClass:
21771 case Expr::CXXDeleteExprClass:
21772 case Expr::CXXPseudoDestructorExprClass:
21773 case Expr::UnresolvedLookupExprClass:
21774 case Expr::RecoveryExprClass:
21775 case Expr::DependentScopeDeclRefExprClass:
21776 case Expr::CXXConstructExprClass:
21777 case Expr::CXXInheritedCtorInitExprClass:
21778 case Expr::CXXStdInitializerListExprClass:
21779 case Expr::CXXBindTemporaryExprClass:
21780 case Expr::ExprWithCleanupsClass:
21781 case Expr::CXXTemporaryObjectExprClass:
21782 case Expr::CXXUnresolvedConstructExprClass:
21783 case Expr::CXXDependentScopeMemberExprClass:
21784 case Expr::UnresolvedMemberExprClass:
21785 case Expr::ObjCStringLiteralClass:
21786 case Expr::ObjCBoxedExprClass:
21787 case Expr::ObjCArrayLiteralClass:
21788 case Expr::ObjCDictionaryLiteralClass:
21789 case Expr::ObjCEncodeExprClass:
21790 case Expr::ObjCMessageExprClass:
21791 case Expr::ObjCSelectorExprClass:
21792 case Expr::ObjCProtocolExprClass:
21793 case Expr::ObjCIvarRefExprClass:
21794 case Expr::ObjCPropertyRefExprClass:
21795 case Expr::ObjCSubscriptRefExprClass:
21796 case Expr::ObjCIsaExprClass:
21797 case Expr::ObjCAvailabilityCheckExprClass:
21798 case Expr::ShuffleVectorExprClass:
21799 case Expr::ConvertVectorExprClass:
21800 case Expr::BlockExprClass:
21801 case Expr::NoStmtClass:
21802 case Expr::OpaqueValueExprClass:
21803 case Expr::PackExpansionExprClass:
21804 case Expr::SubstNonTypeTemplateParmPackExprClass:
21805 case Expr::FunctionParmPackExprClass:
21806 case Expr::AsTypeExprClass:
21807 case Expr::ObjCIndirectCopyRestoreExprClass:
21808 case Expr::MaterializeTemporaryExprClass:
21809 case Expr::PseudoObjectExprClass:
21810 case Expr::AtomicExprClass:
21811 case Expr::LambdaExprClass:
21812 case Expr::CXXFoldExprClass:
21813 case Expr::CoawaitExprClass:
21814 case Expr::DependentCoawaitExprClass:
21815 case Expr::CoyieldExprClass:
21816 case Expr::SYCLUniqueStableNameExprClass:
21817 case Expr::CXXParenListInitExprClass:
21818 case Expr::HLSLOutArgExprClass:
21819 return ICEDiag(IK_NotICE, E->getBeginLoc());
21820
21821 case Expr::MemberExprClass: {
21822 if (Ctx.getLangOpts().C23) {
21823 const Expr *ME = E->IgnoreParenImpCasts();
21824 while (const auto *M = dyn_cast<MemberExpr>(ME)) {
21825 if (M->isArrow())
21826 return ICEDiag(IK_NotICE, E->getBeginLoc());
21827 ME = M->getBase()->IgnoreParenImpCasts();
21828 }
21829 const auto *DRE = dyn_cast<DeclRefExpr>(ME);
21830 if (DRE) {
21831 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
21832 VD && VD->isConstexpr())
21833 return CheckEvalInICE(E, Ctx);
21834 }
21835 }
21836 return ICEDiag(IK_NotICE, E->getBeginLoc());
21837 }
21838
21839 case Expr::InitListExprClass: {
21840 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
21841 // form "T x = { a };" is equivalent to "T x = a;".
21842 // Unless we're initializing a reference, T is a scalar as it is known to be
21843 // of integral or enumeration type.
21844 if (E->isPRValue())
21845 if (cast<InitListExpr>(E)->getNumInits() == 1)
21846 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
21847 return ICEDiag(IK_NotICE, E->getBeginLoc());
21848 }
21849
21850 case Expr::SizeOfPackExprClass:
21851 case Expr::GNUNullExprClass:
21852 case Expr::SourceLocExprClass:
21853 case Expr::EmbedExprClass:
21854 case Expr::OpenACCAsteriskSizeExprClass:
21855 return NoDiag();
21856
21857 case Expr::PackIndexingExprClass:
21858 return CheckICE(cast<PackIndexingExpr>(E)->getSelectedExpr(), Ctx);
21859
21860 case Expr::SubstNonTypeTemplateParmExprClass:
21861 return
21862 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
21863
21864 case Expr::ConstantExprClass:
21865 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
21866
21867 case Expr::ParenExprClass:
21868 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
21869 case Expr::GenericSelectionExprClass:
21870 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
21871 case Expr::IntegerLiteralClass:
21872 case Expr::FixedPointLiteralClass:
21873 case Expr::CharacterLiteralClass:
21874 case Expr::ObjCBoolLiteralExprClass:
21875 case Expr::CXXBoolLiteralExprClass:
21876 case Expr::CXXScalarValueInitExprClass:
21877 case Expr::TypeTraitExprClass:
21878 case Expr::ConceptSpecializationExprClass:
21879 case Expr::RequiresExprClass:
21880 case Expr::ArrayTypeTraitExprClass:
21881 case Expr::ExpressionTraitExprClass:
21882 case Expr::CXXNoexceptExprClass:
21883 case Expr::CXXReflectExprClass:
21884 return NoDiag();
21885 case Expr::CallExprClass:
21886 case Expr::CXXOperatorCallExprClass: {
21887 // C99 6.6/3 allows function calls within unevaluated subexpressions of
21888 // constant expressions, but they can never be ICEs because an ICE cannot
21889 // contain an operand of (pointer to) function type.
21890 const CallExpr *CE = cast<CallExpr>(E);
21891 if (CE->getBuiltinCallee())
21892 return CheckEvalInICE(E, Ctx);
21893 return ICEDiag(IK_NotICE, E->getBeginLoc());
21894 }
21895 case Expr::CXXRewrittenBinaryOperatorClass:
21896 return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(),
21897 Ctx);
21898 case Expr::DeclRefExprClass: {
21899 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
21900 if (isa<EnumConstantDecl>(D))
21901 return NoDiag();
21902
21903 // C++ and OpenCL (FIXME: spec reference?) allow reading const-qualified
21904 // integer variables in constant expressions:
21905 //
21906 // C++ 7.1.5.1p2
21907 // A variable of non-volatile const-qualified integral or enumeration
21908 // type initialized by an ICE can be used in ICEs.
21909 //
21910 // We sometimes use CheckICE to check the C++98 rules in C++11 mode. In
21911 // that mode, use of reference variables should not be allowed.
21912 const VarDecl *VD = dyn_cast<VarDecl>(D);
21913 if (VD && VD->isUsableInConstantExpressions(Ctx) &&
21914 !VD->getType()->isReferenceType())
21915 return NoDiag();
21916
21917 return ICEDiag(IK_NotICE, E->getBeginLoc());
21918 }
21919 case Expr::UnaryOperatorClass: {
21920 const UnaryOperator *Exp = cast<UnaryOperator>(E);
21921 switch (Exp->getOpcode()) {
21922 case UO_PostInc:
21923 case UO_PostDec:
21924 case UO_PreInc:
21925 case UO_PreDec:
21926 case UO_AddrOf:
21927 case UO_Deref:
21928 case UO_Coawait:
21929 // C99 6.6/3 allows increment and decrement within unevaluated
21930 // subexpressions of constant expressions, but they can never be ICEs
21931 // because an ICE cannot contain an lvalue operand.
21932 return ICEDiag(IK_NotICE, E->getBeginLoc());
21933 case UO_Extension:
21934 case UO_LNot:
21935 case UO_Plus:
21936 case UO_Minus:
21937 case UO_Not:
21938 case UO_Real:
21939 case UO_Imag:
21940 return CheckICE(Exp->getSubExpr(), Ctx);
21941 }
21942 llvm_unreachable("invalid unary operator class");
21943 }
21944 case Expr::OffsetOfExprClass: {
21945 // Note that per C99, offsetof must be an ICE. And AFAIK, using
21946 // EvaluateAsRValue matches the proposed gcc behavior for cases like
21947 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
21948 // compliance: we should warn earlier for offsetof expressions with
21949 // array subscripts that aren't ICEs, and if the array subscripts
21950 // are ICEs, the value of the offsetof must be an integer constant.
21951 return CheckEvalInICE(E, Ctx);
21952 }
21953 case Expr::UnaryExprOrTypeTraitExprClass: {
21955 if ((Exp->getKind() == UETT_SizeOf) &&
21957 return ICEDiag(IK_NotICE, E->getBeginLoc());
21958 if (Exp->getKind() == UETT_CountOf) {
21959 QualType ArgTy = Exp->getTypeOfArgument();
21960 if (ArgTy->isVariableArrayType()) {
21961 // We need to look whether the array is multidimensional. If it is,
21962 // then we want to check the size expression manually to see whether
21963 // it is an ICE or not.
21964 const auto *VAT = Ctx.getAsVariableArrayType(ArgTy);
21965 if (VAT->getElementType()->isArrayType())
21966 // Variable array size expression could be missing (e.g. int a[*][10])
21967 // In that case, it can't be a constant expression.
21968 return VAT->getSizeExpr() ? CheckICE(VAT->getSizeExpr(), Ctx)
21969 : ICEDiag(IK_NotICE, E->getBeginLoc());
21970
21971 // Otherwise, this is a regular VLA, which is definitely not an ICE.
21972 return ICEDiag(IK_NotICE, E->getBeginLoc());
21973 }
21974 }
21975 return NoDiag();
21976 }
21977 case Expr::BinaryOperatorClass: {
21978 const BinaryOperator *Exp = cast<BinaryOperator>(E);
21979 switch (Exp->getOpcode()) {
21980 case BO_PtrMemD:
21981 case BO_PtrMemI:
21982 case BO_Assign:
21983 case BO_MulAssign:
21984 case BO_DivAssign:
21985 case BO_RemAssign:
21986 case BO_AddAssign:
21987 case BO_SubAssign:
21988 case BO_ShlAssign:
21989 case BO_ShrAssign:
21990 case BO_AndAssign:
21991 case BO_XorAssign:
21992 case BO_OrAssign:
21993 // C99 6.6/3 allows assignments within unevaluated subexpressions of
21994 // constant expressions, but they can never be ICEs because an ICE cannot
21995 // contain an lvalue operand.
21996 return ICEDiag(IK_NotICE, E->getBeginLoc());
21997
21998 case BO_Mul:
21999 case BO_Div:
22000 case BO_Rem:
22001 case BO_Add:
22002 case BO_Sub:
22003 case BO_Shl:
22004 case BO_Shr:
22005 case BO_LT:
22006 case BO_GT:
22007 case BO_LE:
22008 case BO_GE:
22009 case BO_EQ:
22010 case BO_NE:
22011 case BO_And:
22012 case BO_Xor:
22013 case BO_Or:
22014 case BO_Comma:
22015 case BO_Cmp: {
22016 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
22017 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
22018 if (Exp->getOpcode() == BO_Div ||
22019 Exp->getOpcode() == BO_Rem) {
22020 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
22021 // we don't evaluate one.
22022 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
22023 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
22024 if (REval == 0)
22025 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
22026 if (REval.isSigned() && REval.isAllOnes()) {
22027 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
22028 if (LEval.isMinSignedValue())
22029 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
22030 }
22031 }
22032 }
22033 if (Exp->getOpcode() == BO_Comma) {
22034 if (Ctx.getLangOpts().C99) {
22035 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
22036 // if it isn't evaluated.
22037 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
22038 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
22039 } else {
22040 // In both C89 and C++, commas in ICEs are illegal.
22041 return ICEDiag(IK_NotICE, E->getBeginLoc());
22042 }
22043 }
22044 return Worst(LHSResult, RHSResult);
22045 }
22046 case BO_LAnd:
22047 case BO_LOr: {
22048 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
22049 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
22050 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
22051 // Rare case where the RHS has a comma "side-effect"; we need
22052 // to actually check the condition to see whether the side
22053 // with the comma is evaluated.
22054 if ((Exp->getOpcode() == BO_LAnd) !=
22055 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
22056 return RHSResult;
22057 return NoDiag();
22058 }
22059
22060 return Worst(LHSResult, RHSResult);
22061 }
22062 }
22063 llvm_unreachable("invalid binary operator kind");
22064 }
22065 case Expr::ImplicitCastExprClass:
22066 case Expr::CStyleCastExprClass:
22067 case Expr::CXXFunctionalCastExprClass:
22068 case Expr::CXXStaticCastExprClass:
22069 case Expr::CXXReinterpretCastExprClass:
22070 case Expr::CXXConstCastExprClass:
22071 case Expr::ObjCBridgedCastExprClass: {
22072 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
22073 if (isa<ExplicitCastExpr>(E)) {
22074 if (const FloatingLiteral *FL
22075 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
22076 unsigned DestWidth = Ctx.getIntWidth(E->getType());
22077 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
22078 APSInt IgnoredVal(DestWidth, !DestSigned);
22079 bool Ignored;
22080 // If the value does not fit in the destination type, the behavior is
22081 // undefined, so we are not required to treat it as a constant
22082 // expression.
22083 if (FL->getValue().convertToInteger(IgnoredVal,
22084 llvm::APFloat::rmTowardZero,
22085 &Ignored) & APFloat::opInvalidOp)
22086 return ICEDiag(IK_NotICE, E->getBeginLoc());
22087 return NoDiag();
22088 }
22089 }
22090 switch (cast<CastExpr>(E)->getCastKind()) {
22091 case CK_LValueToRValue:
22092 case CK_AtomicToNonAtomic:
22093 case CK_NonAtomicToAtomic:
22094 case CK_NoOp:
22095 case CK_IntegralToBoolean:
22096 case CK_IntegralCast:
22097 return CheckICE(SubExpr, Ctx);
22098 default:
22099 return ICEDiag(IK_NotICE, E->getBeginLoc());
22100 }
22101 }
22102 case Expr::BinaryConditionalOperatorClass: {
22104 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
22105 if (CommonResult.Kind == IK_NotICE) return CommonResult;
22106 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
22107 if (FalseResult.Kind == IK_NotICE) return FalseResult;
22108 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
22109 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
22110 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
22111 return FalseResult;
22112 }
22113 case Expr::ConditionalOperatorClass: {
22115 // If the condition (ignoring parens) is a __builtin_constant_p call,
22116 // then only the true side is actually considered in an integer constant
22117 // expression, and it is fully evaluated. This is an important GNU
22118 // extension. See GCC PR38377 for discussion.
22119 if (const CallExpr *CallCE
22120 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
22121 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
22122 return CheckEvalInICE(E, Ctx);
22123 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
22124 if (CondResult.Kind == IK_NotICE)
22125 return CondResult;
22126
22127 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
22128 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
22129
22130 if (TrueResult.Kind == IK_NotICE)
22131 return TrueResult;
22132 if (FalseResult.Kind == IK_NotICE)
22133 return FalseResult;
22134 if (CondResult.Kind == IK_ICEIfUnevaluated)
22135 return CondResult;
22136 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
22137 return NoDiag();
22138 // Rare case where the diagnostics depend on which side is evaluated
22139 // Note that if we get here, CondResult is 0, and at least one of
22140 // TrueResult and FalseResult is non-zero.
22141 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
22142 return FalseResult;
22143 return TrueResult;
22144 }
22145 case Expr::CXXDefaultArgExprClass:
22146 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
22147 case Expr::CXXDefaultInitExprClass:
22148 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
22149 case Expr::ChooseExprClass: {
22150 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
22151 }
22152 case Expr::BuiltinBitCastExprClass: {
22153 if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
22154 return ICEDiag(IK_NotICE, E->getBeginLoc());
22155 return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
22156 }
22157 }
22158
22159 llvm_unreachable("Invalid StmtClass!");
22160}
22161
22162/// Evaluate an expression as a C++11 integral constant expression.
22164 const Expr *E,
22165 llvm::APSInt *Value) {
22167 return false;
22168
22170 if (!E->isCXX11ConstantExpr(Ctx, &Result))
22171 return false;
22172
22173 if (!Result.isInt())
22174 return false;
22175
22176 if (Value) *Value = Result.getInt();
22177 return true;
22178}
22179
22181 assert(!isValueDependent() &&
22182 "Expression evaluator can't be called on a dependent expression.");
22183
22184 ExprTimeTraceScope TimeScope(this, Ctx, "isIntegerConstantExpr");
22185
22186 if (Ctx.getLangOpts().CPlusPlus11)
22187 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr);
22188
22189 ICEDiag D = CheckICE(this, Ctx);
22190 if (D.Kind != IK_ICE)
22191 return false;
22192 return true;
22193}
22194
22195std::optional<llvm::APSInt>
22197 if (isValueDependent()) {
22198 // Expression evaluator can't succeed on a dependent expression.
22199 return std::nullopt;
22200 }
22201
22202 if (Ctx.getLangOpts().CPlusPlus11) {
22203 APSInt Value;
22205 return Value;
22206 return std::nullopt;
22207 }
22208
22209 if (!isIntegerConstantExpr(Ctx))
22210 return std::nullopt;
22211
22212 // The only possible side-effects here are due to UB discovered in the
22213 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
22214 // required to treat the expression as an ICE, so we produce the folded
22215 // value.
22217 Expr::EvalStatus Status;
22218 EvalInfo Info(Ctx, Status, EvaluationMode::IgnoreSideEffects);
22219 Info.InConstantContext = true;
22220
22221 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
22222 llvm_unreachable("ICE cannot be evaluated!");
22223
22224 return ExprResult.Val.getInt();
22225}
22226
22228 assert(!isValueDependent() &&
22229 "Expression evaluator can't be called on a dependent expression.");
22230
22231 return CheckICE(this, Ctx).Kind == IK_ICE;
22232}
22233
22235 assert(!isValueDependent() &&
22236 "Expression evaluator can't be called on a dependent expression.");
22237
22238 // We support this checking in C++98 mode in order to diagnose compatibility
22239 // issues.
22240 assert(Ctx.getLangOpts().CPlusPlus);
22241
22242 bool IsConst;
22243 APValue Scratch;
22244 if (FastEvaluateAsRValue(this, Scratch, Ctx, IsConst) && Scratch.hasValue()) {
22245 if (Result)
22246 *Result = std::move(Scratch);
22247 return true;
22248 }
22249
22250 // Build evaluation settings.
22251 Expr::EvalStatus Status;
22253 Status.Diag = &Diags;
22254 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantExpression);
22255
22256 bool IsConstExpr =
22257 ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) &&
22258 // FIXME: We don't produce a diagnostic for this, but the callers that
22259 // call us on arbitrary full-expressions should generally not care.
22260 Info.discardCleanups() && !Status.HasSideEffects;
22261
22262 return IsConstExpr && Diags.empty();
22263}
22264
22266 const FunctionDecl *Callee,
22268 const Expr *This) const {
22269 assert(!isValueDependent() &&
22270 "Expression evaluator can't be called on a dependent expression.");
22271
22272 llvm::TimeTraceScope TimeScope("EvaluateWithSubstitution", [&] {
22273 std::string Name;
22274 llvm::raw_string_ostream OS(Name);
22275 Callee->getNameForDiagnostic(OS, Ctx.getPrintingPolicy(),
22276 /*Qualified=*/true);
22277 return Name;
22278 });
22279
22280 Expr::EvalStatus Status;
22281 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantExpressionUnevaluated);
22282 Info.InConstantContext = true;
22283
22284 LValue ThisVal;
22285 const LValue *ThisPtr = nullptr;
22286 if (This) {
22287#ifndef NDEBUG
22288 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
22289 assert(MD && "Don't provide `this` for non-methods.");
22290 assert(MD->isImplicitObjectMemberFunction() &&
22291 "Don't provide `this` for methods without an implicit object.");
22292#endif
22293 if (!This->isValueDependent() &&
22294 EvaluateObjectArgument(Info, This, ThisVal) &&
22295 !Info.EvalStatus.HasSideEffects)
22296 ThisPtr = &ThisVal;
22297
22298 // Ignore any side-effects from a failed evaluation. This is safe because
22299 // they can't interfere with any other argument evaluation.
22300 Info.EvalStatus.HasSideEffects = false;
22301 }
22302
22303 CallRef Call = Info.CurrentCall->createCall(Callee);
22304 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
22305 I != E; ++I) {
22306 unsigned Idx = I - Args.begin();
22307 if (Idx >= Callee->getNumParams())
22308 break;
22309 const ParmVarDecl *PVD = Callee->getParamDecl(Idx);
22310 if ((*I)->isValueDependent() ||
22311 !EvaluateCallArg(PVD, *I, Call, Info) ||
22312 Info.EvalStatus.HasSideEffects) {
22313 // If evaluation fails, throw away the argument entirely.
22314 if (APValue *Slot = Info.getParamSlot(Call, PVD))
22315 *Slot = APValue();
22316 }
22317
22318 // Ignore any side-effects from a failed evaluation. This is safe because
22319 // they can't interfere with any other argument evaluation.
22320 Info.EvalStatus.HasSideEffects = false;
22321 }
22322
22323 // Parameter cleanups happen in the caller and are not part of this
22324 // evaluation.
22325 Info.discardCleanups();
22326 Info.EvalStatus.HasSideEffects = false;
22327
22328 // Build fake call to Callee.
22329 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, This,
22330 Call);
22331 // FIXME: Missing ExprWithCleanups in enable_if conditions?
22332 FullExpressionRAII Scope(Info);
22333 return Evaluate(Value, Info, this) && Scope.destroy() &&
22334 !Info.EvalStatus.HasSideEffects;
22335}
22336
22339 PartialDiagnosticAt> &Diags) {
22340 // FIXME: It would be useful to check constexpr function templates, but at the
22341 // moment the constant expression evaluator cannot cope with the non-rigorous
22342 // ASTs which we build for dependent expressions.
22343 if (FD->isDependentContext())
22344 return true;
22345
22346 llvm::TimeTraceScope TimeScope("isPotentialConstantExpr", [&] {
22347 std::string Name;
22348 llvm::raw_string_ostream OS(Name);
22350 /*Qualified=*/true);
22351 return Name;
22352 });
22353
22354 Expr::EvalStatus Status;
22355 Status.Diag = &Diags;
22356
22357 EvalInfo Info(FD->getASTContext(), Status,
22359 Info.InConstantContext = true;
22360 Info.CheckingPotentialConstantExpression = true;
22361
22362 // The constexpr VM attempts to compile all methods to bytecode here.
22363 if (Info.EnableNewConstInterp) {
22364 Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD);
22365 return Diags.empty();
22366 }
22367
22368 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
22369 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
22370
22371 // Fabricate an arbitrary expression on the stack and pretend that it
22372 // is a temporary being used as the 'this' pointer.
22373 LValue This;
22374 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getCanonicalTagType(RD)
22375 : Info.Ctx.IntTy);
22376 This.set({&VIE, Info.CurrentCall->Index});
22377
22379
22380 APValue Scratch;
22381 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
22382 // Evaluate the call as a constant initializer, to allow the construction
22383 // of objects of non-literal types.
22384 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
22385 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
22386 } else {
22387 SourceLocation Loc = FD->getLocation();
22389 Loc, FD, (MD && MD->isImplicitObjectMemberFunction()) ? &This : nullptr,
22390 &VIE, Args, CallRef(), FD->getBody(), Info, Scratch,
22391 /*ResultSlot=*/nullptr);
22392 }
22393
22394 return Diags.empty();
22395}
22396
22398 const FunctionDecl *FD,
22400 PartialDiagnosticAt> &Diags) {
22401 assert(!E->isValueDependent() &&
22402 "Expression evaluator can't be called on a dependent expression.");
22403
22404 Expr::EvalStatus Status;
22405 Status.Diag = &Diags;
22406
22407 EvalInfo Info(FD->getASTContext(), Status,
22409 Info.InConstantContext = true;
22410 Info.CheckingPotentialConstantExpression = true;
22411
22412 if (Info.EnableNewConstInterp) {
22413 Info.Ctx.getInterpContext().isPotentialConstantExprUnevaluated(Info, E, FD);
22414 return Diags.empty();
22415 }
22416
22417 // Fabricate a call stack frame to give the arguments a plausible cover story.
22418 CallStackFrame Frame(Info, SourceLocation(), FD, /*This=*/nullptr,
22419 /*CallExpr=*/nullptr, CallRef());
22420
22421 APValue ResultScratch;
22422 Evaluate(ResultScratch, Info, E);
22423 return Diags.empty();
22424}
22425
22426std::optional<uint64_t> Expr::tryEvaluateObjectSize(const ASTContext &Ctx,
22427 unsigned Type) const {
22428 if (!getType()->isPointerType())
22429 return std::nullopt;
22430
22431 Expr::EvalStatus Status;
22432 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantFold);
22433 if (Info.EnableNewConstInterp)
22434 return Info.Ctx.getInterpContext().tryEvaluateObjectSize(Info, this, Type);
22435 return tryEvaluateBuiltinObjectSize(this, Type, Info);
22436}
22437
22438static std::optional<uint64_t>
22439EvaluateBuiltinStrLen(const Expr *E, EvalInfo &Info,
22440 std::string *StringResult) {
22441 if (!E->getType()->hasPointerRepresentation() || !E->isPRValue())
22442 return std::nullopt;
22443
22444 LValue String;
22445
22446 if (!EvaluatePointer(E, String, Info))
22447 return std::nullopt;
22448
22449 QualType CharTy = E->getType()->getPointeeType();
22450
22451 // Fast path: if it's a string literal, search the string value.
22452 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
22453 String.getLValueBase().dyn_cast<const Expr *>())) {
22454 StringRef Str = S->getBytes();
22455 int64_t Off = String.Offset.getQuantity();
22456 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
22457 S->getCharByteWidth() == 1 &&
22458 // FIXME: Add fast-path for wchar_t too.
22459 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
22460 Str = Str.substr(Off);
22461
22462 StringRef::size_type Pos = Str.find(0);
22463 if (Pos != StringRef::npos)
22464 Str = Str.substr(0, Pos);
22465
22466 if (StringResult)
22467 *StringResult = Str;
22468 return Str.size();
22469 }
22470
22471 // Fall through to slow path.
22472 }
22473
22474 // Slow path: scan the bytes of the string looking for the terminating 0.
22475 for (uint64_t Strlen = 0; /**/; ++Strlen) {
22476 APValue Char;
22477 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
22478 !Char.isInt())
22479 return std::nullopt;
22480 if (!Char.getInt())
22481 return Strlen;
22482 else if (StringResult)
22483 StringResult->push_back(Char.getInt().getExtValue());
22484 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
22485 return std::nullopt;
22486 }
22487}
22488
22489std::optional<std::string> Expr::tryEvaluateString(ASTContext &Ctx) const {
22490 Expr::EvalStatus Status;
22491 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantFold);
22492 std::string StringResult;
22493
22494 if (Info.EnableNewConstInterp) {
22495 if (!Info.Ctx.getInterpContext().evaluateString(Info, this, StringResult))
22496 return std::nullopt;
22497 return StringResult;
22498 }
22499
22500 if (EvaluateBuiltinStrLen(this, Info, &StringResult))
22501 return StringResult;
22502 return std::nullopt;
22503}
22504
22505template <typename T>
22507 const Expr *SizeExpression,
22508 const Expr *PtrExpression,
22509 ASTContext &Ctx,
22510 Expr::EvalResult &Status) {
22511 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantExpression);
22512 Info.InConstantContext = true;
22513
22514 if (Info.EnableNewConstInterp)
22515 return Info.Ctx.getInterpContext().evaluateCharRange(Info, SizeExpression,
22516 PtrExpression, Result);
22517
22518 LValue String;
22519 FullExpressionRAII Scope(Info);
22520 APSInt SizeValue;
22521 if (!::EvaluateInteger(SizeExpression, SizeValue, Info))
22522 return false;
22523
22524 uint64_t Size = SizeValue.getZExtValue();
22525
22526 // FIXME: better protect against invalid or excessive sizes
22527 if constexpr (std::is_same_v<APValue, T>)
22528 Result = APValue(APValue::UninitArray{}, Size, Size);
22529 else {
22530 if (Size < Result.max_size())
22531 Result.reserve(Size);
22532 }
22533 if (!::EvaluatePointer(PtrExpression, String, Info))
22534 return false;
22535
22536 QualType CharTy = PtrExpression->getType()->getPointeeType();
22537 for (uint64_t I = 0; I < Size; ++I) {
22538 APValue Char;
22539 if (!handleLValueToRValueConversion(Info, PtrExpression, CharTy, String,
22540 Char))
22541 return false;
22542
22543 if constexpr (std::is_same_v<APValue, T>) {
22544 Result.getArrayInitializedElt(I) = std::move(Char);
22545 } else {
22546 APSInt C = Char.getInt();
22547
22548 assert(C.getBitWidth() <= 8 &&
22549 "string element not representable in char");
22550
22551 Result.push_back(static_cast<char>(C.getExtValue()));
22552 }
22553
22554 if (!HandleLValueArrayAdjustment(Info, PtrExpression, String, CharTy, 1))
22555 return false;
22556 }
22557
22558 return Scope.destroy() && CheckMemoryLeaks(Info);
22559}
22560
22562 const Expr *SizeExpression,
22563 const Expr *PtrExpression, ASTContext &Ctx,
22564 EvalResult &Status) const {
22565 return EvaluateCharRangeAsStringImpl(this, Result, SizeExpression,
22566 PtrExpression, Ctx, Status);
22567}
22568
22570 const Expr *SizeExpression,
22571 const Expr *PtrExpression, ASTContext &Ctx,
22572 EvalResult &Status) const {
22573 return EvaluateCharRangeAsStringImpl(this, Result, SizeExpression,
22574 PtrExpression, Ctx, Status);
22575}
22576
22577std::optional<uint64_t> Expr::tryEvaluateStrLen(const ASTContext &Ctx) const {
22578 Expr::EvalStatus Status;
22579 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantFold);
22580
22581 if (Info.EnableNewConstInterp)
22582 return Info.Ctx.getInterpContext().evaluateStrlen(Info, this);
22583 return EvaluateBuiltinStrLen(this, Info);
22584}
22585
22586namespace {
22587struct IsWithinLifetimeHandler {
22588 EvalInfo &Info;
22589 static constexpr AccessKinds AccessKind = AccessKinds::AK_IsWithinLifetime;
22590 using result_type = std::optional<bool>;
22591 std::optional<bool> failed() { return std::nullopt; }
22592 template <typename T>
22593 std::optional<bool> found(T &Subobj, QualType SubobjType,
22595 return true;
22596 }
22597 template <typename T>
22598 std::optional<bool> found(T &Subobj, QualType SubobjType) {
22599 return true;
22600 }
22601};
22602
22603std::optional<bool> EvaluateBuiltinIsWithinLifetime(IntExprEvaluator &IEE,
22604 const CallExpr *E) {
22605 EvalInfo &Info = IEE.Info;
22606 // Sometimes this is called during some sorts of constant folding / early
22607 // evaluation. These are meant for non-constant expressions and are not
22608 // necessary since this consteval builtin will never be evaluated at runtime.
22609 // Just fail to evaluate when not in a constant context.
22610 if (!Info.InConstantContext)
22611 return std::nullopt;
22612 assert(E->getBuiltinCallee() == Builtin::BI__builtin_is_within_lifetime);
22613 const Expr *Arg = E->getArg(0);
22614 if (Arg->isValueDependent())
22615 return std::nullopt;
22616 LValue Val;
22617 if (!EvaluatePointer(Arg, Val, Info))
22618 return std::nullopt;
22619
22620 if (Val.allowConstexprUnknown())
22621 return true;
22622
22623 auto Error = [&](int Diag) {
22624 bool CalledFromStd = false;
22625 const auto *Callee = Info.CurrentCall->getCallee();
22626 if (Callee && Callee->isInStdNamespace()) {
22627 const IdentifierInfo *Identifier = Callee->getIdentifier();
22628 CalledFromStd = Identifier && Identifier->isStr("is_within_lifetime");
22629 }
22630 Info.CCEDiag(CalledFromStd ? Info.CurrentCall->getCallRange().getBegin()
22631 : E->getExprLoc(),
22632 diag::err_invalid_is_within_lifetime)
22633 << (CalledFromStd ? "std::is_within_lifetime"
22634 : "__builtin_is_within_lifetime")
22635 << Diag;
22636 return std::nullopt;
22637 };
22638 // C++2c [meta.const.eval]p4:
22639 // During the evaluation of an expression E as a core constant expression, a
22640 // call to this function is ill-formed unless p points to an object that is
22641 // usable in constant expressions or whose complete object's lifetime began
22642 // within E.
22643
22644 // Make sure it points to an object
22645 // nullptr does not point to an object
22646 if (Val.isNullPointer() || Val.getLValueBase().isNull())
22647 return Error(0);
22648 QualType T = Val.getLValueBase().getType();
22649 assert(!T->isFunctionType() &&
22650 "Pointers to functions should have been typed as function pointers "
22651 "which would have been rejected earlier");
22652 assert(T->isObjectType());
22653 // Hypothetical array element is not an object
22654 if (Val.getLValueDesignator().isOnePastTheEnd())
22655 return Error(1);
22656 assert(Val.getLValueDesignator().isValidSubobject() &&
22657 "Unchecked case for valid subobject");
22658 // All other ill-formed values should have failed EvaluatePointer, so the
22659 // object should be a pointer to an object that is usable in a constant
22660 // expression or whose complete lifetime began within the expression
22661 CompleteObject CO =
22662 findCompleteObject(Info, E, AccessKinds::AK_IsWithinLifetime, Val, T);
22663 // The lifetime hasn't begun yet if we are still evaluating the
22664 // initializer ([basic.life]p(1.2))
22665 if (Info.EvaluatingDeclValue && CO.Value == Info.EvaluatingDeclValue)
22666 return Error(2);
22667
22668 if (!CO)
22669 return false;
22670 IsWithinLifetimeHandler handler{Info};
22671 return findSubobject(Info, E, CO, Val.getLValueDesignator(), handler);
22672}
22673} // namespace
Defines the clang::ASTContext interface.
#define V(N, I)
This file provides some common utility functions for processing Lambda related AST Constructs.
Defines enum values for all the target-independent builtin functions.
static Address castToBase(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy, Address OriginalBaseAddress, llvm::Value *Addr)
static uint32_t getBitWidth(const Expr *E)
llvm::APSInt APSInt
Definition Compiler.cpp:24
static Decl::Kind getKind(const Decl *D)
GCCTypeClass
Values returned by __builtin_classify_type, chosen to match the values produced by GCC's builtin.
static bool isRead(AccessKinds AK)
static bool EvaluateCharRangeAsStringImpl(const Expr *, T &Result, const Expr *SizeExpression, const Expr *PtrExpression, ASTContext &Ctx, Expr::EvalResult &Status)
static bool isValidIndeterminateAccess(AccessKinds AK)
Is this kind of access valid on an indeterminate object value?
static unsigned elementwiseSize(EvalInfo &Info, QualType BaseTy)
static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, EvalInfo &Info)
static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result, Expr::SideEffectsKind SEK)
static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, AccessKinds AK, const LValue &LVal, QualType LValType)
Find the complete object to which an LValue refers.
static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base, LValue &Result)
Attempts to evaluate the given LValueBase as the result of a call to a function with the alloc_size a...
static const CXXMethodDecl * HandleVirtualDispatch(EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found, llvm::SmallVectorImpl< QualType > &CovariantAdjustmentPath)
Perform virtual dispatch.
static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD)
static bool CheckEvaluationResult(CheckEvaluationResultKind CERK, EvalInfo &Info, SourceLocation DiagLoc, QualType Type, const APValue &Value, ConstantExprKind Kind, const FieldDecl *SubobjectDecl, CheckedTemporaries &CheckedTemps)
static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E, LValue &LVal, QualType EltTy, bool Imag)
Update an lvalue to refer to a component of a complex number.
static bool evalPackBuiltin(const CallExpr *E, EvalInfo &Info, APValue &Result, llvm::function_ref< APInt(const APSInt &)> PackFn)
static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, QualType Type, CharUnits &Size, SizeOfType SOT=SizeOfType::SizeOf)
Get the size of the given type in char units.
static bool HandleConstructorCall(const Expr *E, const LValue &This, CallRef Call, const CXXConstructorDecl *Definition, EvalInfo &Info, APValue &Result)
Evaluate a constructor call.
static bool hlslElementwiseCastHelper(EvalInfo &Info, const Expr *E, QualType DestTy, SmallVectorImpl< APValue > &SrcVals, SmallVectorImpl< QualType > &SrcTypes)
static bool ShouldPropagateBreakContinue(EvalInfo &Info, const Stmt *LoopOrSwitch, ArrayRef< BlockScopeRAII * > Scopes, EvalStmtResult &ESR)
Helper to implement named break/continue.
static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info, const Stmt *Body, const SwitchCase *Case=nullptr)
Evaluate the body of a loop, and translate the result as appropriate.
static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info, bool InvalidBaseOK=false)
static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc, const CXXConstructorDecl *CD, bool IsValueInitialization)
CheckTrivialDefaultConstructor - Check whether a constructor is a trivial default constructor.
static bool EvaluateVector(const Expr *E, APValue &Result, EvalInfo &Info)
static const ValueDecl * GetLValueBaseDecl(const LValue &LVal)
SizeOfType
static bool TryEvaluateBuiltinNaN(const ASTContext &Context, QualType ResultTy, const Expr *Arg, bool SNaN, llvm::APFloat &Result)
static const Expr * ignorePointerCastsAndParens(const Expr *E)
A more selective version of E->IgnoreParenCasts for tryEvaluateBuiltinObjectSize. This ignores some c...
static bool isAnyAccess(AccessKinds AK)
static bool EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E, SuccessCB &&Success, AfterCB &&DoAfter)
static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E, const RecordDecl *RD, const LValue &This, APValue &Result)
Perform zero-initialization on an object of non-union class type. C++11 [dcl.init]p5: To zero-initial...
static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info)
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.
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 handleDefaultInitValue(QualType T, APValue &Result)
Get the value to use for a default-initialized object of type T.
static bool HandleLValueVectorElement(EvalInfo &Info, const Expr *E, LValue &LVal, QualType EltTy, uint64_t Size, uint64_t Idx)
static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base)
static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc, QualType Type, const LValue &LVal, ConstantExprKind Kind, CheckedTemporaries &CheckedTemps)
Check that this reference or pointer core constant expression is a valid value for an address or refe...
static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E, const APSInt &LHS, const APSInt &RHS, unsigned BitWidth, Operation Op, APSInt &Result)
Perform the given integer operation, which is known to need at most BitWidth bits,...
static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info)
Evaluate an expression of record type as a temporary.
static bool EvaluateArray(const Expr *E, const LValue &This, APValue &Result, EvalInfo &Info)
static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E, APValue &Value, const FieldDecl *FD)
static bool handleVectorShuffle(EvalInfo &Info, const ShuffleVectorExpr *E, QualType ElemType, APValue const &VecVal1, APValue const &VecVal2, unsigned EltNum, APValue &Result)
static bool handleVectorElementCast(EvalInfo &Info, const FPOptions FPO, const Expr *E, QualType SourceTy, QualType DestTy, APValue const &Original, APValue &Result)
static const ValueDecl * HandleMemberPointerAccess(EvalInfo &Info, QualType LVType, LValue &LV, const Expr *RHS, bool IncludeMember=true)
HandleMemberPointerAccess - Evaluate a member access operation and build an lvalue referring to the r...
static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E, LValue &Result)
HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on the provided lvalue,...
static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info)
static bool IsOpaqueConstantCall(const CallExpr *E)
Should this call expression be treated as forming an opaque constant?
static bool CheckMemberPointerConstantExpression(EvalInfo &Info, SourceLocation Loc, QualType Type, const APValue &Value, ConstantExprKind Kind)
Member pointers are constant expressions unless they point to a non-virtual dllimport member function...
static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult, const ASTContext &Ctx, Expr::SideEffectsKind AllowSideEffects, EvalInfo &Info)
static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type, const LValue &LVal, APValue &RVal, bool WantObjectRepresentation=false)
Perform an lvalue-to-rvalue conversion on the given glvalue.
static bool 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 std::optional< uint64_t > tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type, EvalInfo &Info)
Tries to evaluate the __builtin_object_size for E. If successful, returns true and stores the result ...
static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E, const FPOptions FPO, QualType SrcType, const APSInt &Value, QualType DestType, APFloat &Result)
static const CXXRecordDecl * getBaseClassType(SubobjectDesignator &Designator, unsigned PathLength)
static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result, const CXXRecordDecl *DerivedRD, const CXXRecordDecl *BaseRD)
Cast an lvalue referring to a derived class to a known base subobject.
static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj, const CXXRecordDecl *DerivedDecl, const CXXBaseSpecifier *Base)
static bool HandleConversionToBool(const APValue &Val, bool &Result)
static void expandVector(APValue &Vec, unsigned NumElements)
CharUnits GetAlignOfExpr(const ASTContext &Ctx, const Expr *E, UnaryExprOrTypeTrait ExprKind)
static bool isModification(AccessKinds AK)
static bool handleCompareOpForVector(const APValue &LHSValue, BinaryOperatorKind Opcode, const APValue &RHSValue, APInt &Result)
static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr)
static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object, LValue &This)
Build an lvalue for the object argument of a member function call.
static bool CheckLiteralType(EvalInfo &Info, const Expr *E, const LValue *This=nullptr)
Check that this core constant expression is of literal type, and if not, produce an appropriate diagn...
static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info)
CheckEvaluationResultKind
static bool isZeroSized(const LValue &Value)
static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit, uint64_t Index)
Extract the value of a character from a string literal.
static bool modifySubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj, const SubobjectDesignator &Sub, APValue &NewVal)
Update the designated sub-object of an rvalue to the given value.
static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx, const Expr *E, llvm::APSInt *Value)
Evaluate an expression as a C++11 integral constant expression.
static CharUnits GetAlignOfType(const ASTContext &Ctx, QualType T, UnaryExprOrTypeTrait ExprKind)
static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info, APValue &Val, APSInt &Alignment)
static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, LValue &LVal, QualType EltTy, APSInt Adjustment)
Update a pointer value to model pointer arithmetic.
static bool extractSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj, const SubobjectDesignator &Sub, APValue &Result, AccessKinds AK=AK_Read)
Extract the designated sub-object of an rvalue.
static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal, const FieldDecl *FD, const ASTRecordLayout *RL=nullptr)
Update LVal to refer to the given field, which must be a member of the type currently described by LV...
static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index, bool IsSub)
static bool IsDeclSourceLocationCurrent(const FunctionDecl *FD)
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 checkFloatingPointResult(EvalInfo &Info, const Expr *E, APFloat::opStatus St)
Check if the given evaluation result is allowed for constant evaluation.
static bool EvaluateBuiltinConstantPForLValue(const APValue &LV)
EvaluateBuiltinConstantPForLValue - Determine the result of __builtin_constant_p when applied to the ...
static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg)
EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to GCC as we can manage.
static bool checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E, const LValue &This, const CXXMethodDecl *NamedMember)
Check that the pointee of the 'this' pointer in a member function call is either within its lifetime ...
static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type, const APValue &Value, ConstantExprKind Kind)
Check that this core constant expression value is a valid value for a constant expression.
static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result, EvalInfo &Info)
static std::optional< DynamicType > ComputeDynamicType(EvalInfo &Info, const Expr *E, LValue &This, AccessKinds AK)
Determine the dynamic type of an object.
static bool EvaluateDecl(EvalInfo &Info, const Decl *D, bool EvaluateConditionDecl=false)
static void expandArray(APValue &Array, unsigned Index)
static bool handleLogicalOpForVector(const APInt &LHSValue, BinaryOperatorKind Opcode, const APInt &RHSValue, APInt &Result)
static unsigned FindDesignatorMismatch(QualType ObjType, const SubobjectDesignator &A, const SubobjectDesignator &B, bool &WasArrayIndex)
Find the position where two subobject designators diverge, or equivalently the length of the common i...
static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx, const LValue &LV)
Determine whether this is a pointer past the end of the complete object referred to by the lvalue.
static unsigned getBaseIndex(const CXXRecordDecl *Derived, const CXXRecordDecl *Base)
Get the base index of the given base class within an APValue representing the given derived class.
static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result, EvalInfo &Info)
Evaluate only a fixed point expression into an APResult.
void HandleComplexComplexMul(APFloat A, APFloat B, APFloat C, APFloat D, APFloat &ResR, APFloat &ResI)
static bool EvalPointerValueAsBool(const APValue &Value, bool &Result)
static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E, BinaryOperatorKind Opcode, APValue &LHSValue, const APValue &RHSValue)
static bool EvaluateMatrix(const Expr *E, APValue &Result, EvalInfo &Info)
static const FunctionDecl * getVirtualOperatorDelete(QualType T)
static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal)
Checks to see if the given LValue's Designator is at the end of the LValue's record layout....
static bool CheckArraySize(EvalInfo &Info, const ConstantArrayType *CAT, SourceLocation CallLoc={})
static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This, const Expr *E, bool AllowNonLiteralTypes=false)
EvaluateInPlace - Evaluate an expression in-place in an APValue. In some cases, the in-place evaluati...
static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E, APFloat &LHS, BinaryOperatorKind Opcode, const APFloat &RHS)
Perform the given binary floating-point operation, in-place, on LHS.
static std::optional< DynAlloc * > CheckDeleteKind(EvalInfo &Info, const Expr *E, const LValue &Pointer, DynAlloc::Kind DeallocKind)
Check that the given object is a suitable pointer to a heap allocation that still exists and is of th...
static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, bool InvalidBaseOK=false)
Evaluate an expression as an lvalue. This can be legitimately called on expressions which are not glv...
static bool FastEvaluateAsRValue(const Expr *Exp, APValue &Result, const ASTContext &Ctx, bool &IsConst)
static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E, APValue &Result, ArrayRef< QualType > Path)
Perform the adjustment from a value returned by a virtual function to a value of the statically expec...
static 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 EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, const Stmt *S, const SwitchCase *SC=nullptr)
static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This, APValue &Result, const InitListExpr *ILE, QualType AllocType)
static bool HasSameBase(const LValue &A, const LValue &B)
static bool CheckLocalVariableDeclaration(EvalInfo &Info, const VarDecl *VD)
static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj, const CXXRecordDecl *Derived, const CXXRecordDecl *Base, const ASTRecordLayout *RL=nullptr)
static bool IsGlobalLValue(APValue::LValueBase B)
static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E)
Get rounding mode to use in evaluation of the specified expression.
static QualType getObjectType(APValue::LValueBase B)
Retrieves the "underlying object type" of the given expression, as used by __builtin_object_size.
static bool handleCompareOpForVectorHelper(const APTy &LHSValue, BinaryOperatorKind Opcode, const APTy &RHSValue, APInt &Result)
static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E)
static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD)
Determine whether a type would actually be read by an lvalue-to-rvalue conversion.
static void negateAsSigned(APSInt &Int)
Negate an APSInt in place, converting it to a signed form if necessary, and preserving its value (by ...
static bool HandleFunctionCall(SourceLocation CallLoc, const FunctionDecl *Callee, const LValue *ObjectArg, const Expr *E, ArrayRef< const Expr * > Args, CallRef Call, const Stmt *Body, EvalInfo &Info, APValue &Result, const LValue *ResultSlot)
Evaluate a function call.
static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal)
Attempts to detect a user writing into a piece of memory that's impossible to figure out the size of ...
static bool GetLValueBaseAsString(const EvalInfo &Info, const LValue &LVal, LValueBaseString &AsString)
static bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E)
static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, EvalInfo &Info)
EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and produce either the intege...
static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E, LValue &Ptr)
Apply the given dynamic cast operation on the provided lvalue.
static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E, LValue &Result)
Perform a call to 'operator new' or to ‘__builtin_operator_new’.
static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E, QualType SrcType, QualType DestType, APFloat &Result)
static bool MaybeHandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr, const LValue &LHS)
Handle a builtin simple-assignment or a call to a trivial assignment operator whose left-hand side mi...
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 HandleDestructionImpl(EvalInfo &Info, SourceRange CallRange, const LValue &This, APValue &Value, QualType T)
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.
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.
Result
Implement __builtin_bit_cast and related operations.
#define X(type, name)
Definition Value.h:97
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Record Record
Definition MachO.h:31
Implements a partial diagnostic which may not be emitted.
llvm::DenseMap< Stmt *, Stmt * > MapTy
Definition ParentMap.cpp:21
llvm::json::Object Object
llvm::json::Array Array
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
Expr * getExpr()
Get 'expr' part of the associated expression/statement.
static QualType getPointeeType(const MemRegion *R)
Enumerates target-specific builtins in their own namespaces within namespace clang.
Defines the clang::TypeLoc interface and its subclasses.
C Language Family Type Representation.
__DEVICE__ long long abs(long long __n)
a trap message and trap category.
llvm::APInt getValue() const
QualType getType() const
Definition APValue.cpp:63
unsigned getVersion() const
Definition APValue.cpp:113
QualType getDynamicAllocType() const
Definition APValue.cpp:122
QualType getTypeInfoType() const
Definition APValue.cpp:117
static LValueBase getTypeInfo(TypeInfoLValue LV, QualType TypeInfo)
Definition APValue.cpp:55
static LValueBase getDynamicAlloc(DynamicAllocLValue LV, QualType Type)
Definition APValue.cpp:47
A non-discriminated union of a base, field, or array index.
Definition APValue.h:208
BaseOrMemberType getAsBaseOrMember() const
Definition APValue.h:222
static LValuePathEntry ArrayIndex(uint64_t Index)
Definition APValue.h:216
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:122
bool hasArrayFiller() const
Definition APValue.h:634
const LValueBase getLValueBase() const
Definition APValue.cpp:1015
APValue & getArrayInitializedElt(unsigned I)
Definition APValue.h:626
void swap(APValue &RHS)
Swaps the contents of this and the given APValue.
Definition APValue.cpp:482
APSInt & getInt()
Definition APValue.h:508
APValue & getStructField(unsigned i)
Definition APValue.h:667
unsigned getMatrixNumColumns() const
Definition APValue.h:599
const FieldDecl * getUnionField() const
Definition APValue.h:679
bool isVector() const
Definition APValue.h:491
APSInt & getComplexIntImag()
Definition APValue.h:546
bool isAbsent() const
Definition APValue.h:481
bool isComplexInt() const
Definition APValue.h:488
llvm::PointerIntPair< const Decl *, 1, bool > BaseOrMemberType
A FieldDecl or CXXRecordDecl, along with a flag indicating whether we mean a virtual or non-virtual b...
Definition APValue.h:205
ValueKind getKind() const
Definition APValue.h:479
unsigned getArrayInitializedElts() const
Definition APValue.h:645
static APValue IndeterminateValue()
Definition APValue.h:450
bool isFloat() const
Definition APValue.h:486
APFixedPoint & getFixedPoint()
Definition APValue.h:530
bool hasValue() const
Definition APValue.h:483
bool hasLValuePath() const
Definition APValue.cpp:1030
const ValueDecl * getMemberPointerDecl() const
Definition APValue.cpp:1098
APValue & getUnionValue()
Definition APValue.h:683
CharUnits & getLValueOffset()
Definition APValue.cpp:1025
void printPretty(raw_ostream &OS, const ASTContext &Ctx, QualType Ty) const
Definition APValue.cpp:717
bool isComplexFloat() const
Definition APValue.h:489
APValue & getVectorElt(unsigned I)
Definition APValue.h:582
APValue & getArrayFiller()
Definition APValue.h:637
unsigned getVectorLength() const
Definition APValue.h:590
bool isLValue() const
Definition APValue.h:490
void setUnion(const FieldDecl *Field, const APValue &Value)
Definition APValue.cpp:1091
bool isIndeterminate() const
Definition APValue.h:482
unsigned getMatrixNumRows() const
Definition APValue.h:595
bool isInt() const
Definition APValue.h:485
unsigned getArraySize() const
Definition APValue.h:649
bool allowConstexprUnknown() const
Definition APValue.h:329
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition APValue.cpp:988
bool isFixedPoint() const
Definition APValue.h:487
APValue & getMatrixElt(unsigned Idx)
Definition APValue.h:606
@ Indeterminate
This object has an indeterminate value (C++ [basic.indet]).
Definition APValue.h:131
@ None
There is no such object (it's outside its lifetime).
Definition APValue.h:129
bool isStruct() const
Definition APValue.h:494
APSInt & getComplexIntReal()
Definition APValue.h:538
APFloat & getComplexFloatImag()
Definition APValue.h:562
APFloat & getComplexFloatReal()
Definition APValue.h:554
APFloat & getFloat()
Definition APValue.h:522
APValue & getStructBase(unsigned i)
Definition APValue.h:662
bool isMatrix() const
Definition APValue.h:492
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:229
SourceManager & getSourceManager()
Definition ASTContext.h:868
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.
const LangOptions & getLangOpts() const
Definition ASTContext.h:961
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
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:860
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
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:4576
OpaqueValueExpr * getCommonExpr() const
Get the common subexpression shared by all initializations (the source array).
Definition Expr.h:5983
Expr * getSubExpr() const
Get the initializer to use for each array element.
Definition Expr.h:5988
Expr * getLHS()
An array access can be written A[4] or 4[A] (both are equivalent).
Definition Expr.h:2753
uint64_t getValue() const
Definition ExprCXX.h:3048
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3784
QualType getElementType() const
Definition TypeBase.h:3796
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition TypeBase.h:8244
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:4456
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression which will be evaluated if the condition evaluates to false; ...
Definition Expr.h:4510
OpaqueValueExpr * getOpaqueValue() const
getOpaqueValue - Return the opaque value placeholder.
Definition Expr.h:4494
Expr * getCommon() const
getCommon - Return the common expression, written to the left of the condition.
Definition Expr.h:4491
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:4041
static bool isLogicalOp(Opcode Opc)
Definition Expr.h:4174
Expr * getLHS() const
Definition Expr.h:4091
static bool isRelationalOp(Opcode Opc)
Definition Expr.h:4135
static bool isComparisonOp(Opcode Opc)
Definition Expr.h:4141
static Opcode getOpForCompoundAssignment(Opcode Opc)
Definition Expr.h:4188
SourceLocation getExprLoc() const
Definition Expr.h:4082
Expr * getRHS() const
Definition Expr.h:4093
static bool isAdditiveOp(Opcode Opc)
Definition Expr.h:4127
static bool isPtrMemOp(Opcode Opc)
predicates to categorize the respective opcodes.
Definition Expr.h:4118
static bool isAssignmentOp(Opcode Opc)
Definition Expr.h:4177
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operator.
Definition Expr.h:4254
Opcode getOpcode() const
Definition Expr.h:4086
static bool isEqualityOp(Opcode Opc)
Definition Expr.h:4138
bool hasCaptures() const
True if this block (or its nested blocks) captures anything of local storage from its enclosing scope...
Definition Decl.h:4813
const BlockDecl * getBlockDecl() const
Definition Expr.h:6684
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:2620
bool isDefaultConstructor() const
Whether this constructor is a default constructor (C++ [class.ctor]p5), which can be used to default-...
Definition DeclCXX.cpp:3047
CXXCtorInitializer *const * init_const_iterator
Iterates through the member/base initializer list.
Definition DeclCXX.h:2703
Expr * getExpr()
Get the initialization expression that will be used.
Definition ExprCXX.cpp:1112
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:2882
CXXForRangeStmt - This represents C++0x [stmt.ranged]'s ranged for statement, represented as 'for (ra...
Definition StmtCXX.h:135
DeclStmt * getBeginStmt()
Definition StmtCXX.h:163
DeclStmt * getLoopVarStmt()
Definition StmtCXX.h:169
DeclStmt * getEndStmt()
Definition StmtCXX.h:166
DeclStmt * getRangeStmt()
Definition StmtCXX.h:162
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will call.
Definition ExprCXX.h:1792
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2132
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:2717
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:2724
QualType getFunctionObjectParameterReferenceType() const
Return the type of the object pointed by this.
Definition DeclCXX.cpp:2868
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2271
bool isInstance() const
Definition DeclCXX.h:2159
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition DeclCXX.cpp:2749
bool isStatic() const
Definition DeclCXX.cpp:2415
bool isCopyAssignmentOperator() const
Determine whether this is a copy-assignment operator, regardless of whether it was declared implicitl...
Definition DeclCXX.cpp:2728
bool isLambdaStaticInvoker() const
Determine whether this is a lambda closure type's static member function that is used for the result ...
Definition DeclCXX.cpp:2893
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:4332
MutableArrayRef< Expr * > getInitExprs()
Definition ExprCXX.h:5181
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
bool hasMutableFields() const
Determine whether this class, or any of its class subobjects, contains a mutable field.
Definition DeclCXX.h:1233
bool isGenericLambda() const
Determine whether this class describes a generic lambda function object (i.e.
Definition DeclCXX.cpp:1679
base_class_iterator bases_end()
Definition DeclCXX.h:617
bool hasTrivialDestructor() const
Determine whether this class has a trivial destructor (C++ [class.dtor]p3)
Definition DeclCXX.h:1372
base_class_range bases()
Definition DeclCXX.h:608
void getCaptureFields(llvm::DenseMap< const ValueDecl *, FieldDecl * > &Captures, FieldDecl *&ThisCapture) const
For a closure type, retrieve the mapping from captured variables and this to the non-static data memb...
Definition DeclCXX.cpp:1790
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition DeclCXX.h:602
base_class_iterator bases_begin()
Definition DeclCXX.h:615
const CXXBaseSpecifier * base_class_const_iterator
Iterator that traverses the base classes of a class.
Definition DeclCXX.h:520
capture_const_range captures() const
Definition DeclCXX.h:1097
bool isEmpty() const
Determine whether this is an empty class in the sense of (C++11 [meta.unary.prop]).
Definition DeclCXX.h:1186
CXXDestructorDecl * getDestructor() const
Returns the destructor decl for this class.
Definition DeclCXX.cpp:2127
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition DeclCXX.cpp:1742
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:522
unsigned getNumVBases() const
Retrieves the number of virtual base classes of this class.
Definition DeclCXX.h:623
bool isDerivedFrom(const CXXRecordDecl *Base) const
Determine whether this class is derived from the class Base.
Expr * getSemanticForm()
Get an equivalent semantic form for this expression.
Definition ExprCXX.h: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:166
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:134
MSGuidDecl * getGuidDecl() const
Definition ExprCXX.h:1118
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2946
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3150
SourceLocation getBeginLoc() const
Definition Expr.h:3280
const AllocSizeAttr * getCalleeAllocSizeAttr() const
Try to get the alloc_size attribute of the callee. May return null.
Definition Expr.cpp:3599
unsigned getBuiltinCallee() const
getBuiltinCallee - If this is a call to a builtin, return the builtin ID of the callee.
Definition Expr.cpp:1597
Expr * getCallee()
Definition Expr.h:3093
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition Expr.h:3137
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operator.
Definition Expr.h:3239
Expr ** getArgs()
Retrieve the call arguments.
Definition Expr.h:3140
Decl * getCalleeDecl()
Definition Expr.h:3123
QualType getCallReturnType(const ASTContext &Ctx) const
getCallReturnType - Get the return type of the call expr.
Definition Expr.cpp:1608
CaseStmt - Represent a case statement.
Definition Stmt.h:1930
Expr * getLHS()
Definition Stmt.h:2013
Expr * getRHS()
Definition Stmt.h:2025
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition Expr.h:3679
path_iterator path_begin()
Definition Expr.h:3749
unsigned path_size() const
Definition Expr.h:3748
CastKind getCastKind() const
Definition Expr.h:3723
const FieldDecl * getTargetUnionField() const
Definition Expr.h:3773
path_iterator path_end()
Definition Expr.h:3750
const CXXBaseSpecifier *const * path_const_iterator
Definition Expr.h:3746
bool path_empty() const
Definition Expr.h:3747
Expr * getSubExpr()
Definition Expr.h:3729
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operation.
Definition Expr.h:3793
CharUnits - This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
bool isPowerOfTwo() const
isPowerOfTwo - Test whether the quantity is a power of two.
Definition CharUnits.h:135
CharUnits alignmentAtOffset(CharUnits offset) const
Given that this is a non-zero alignment value, what is the alignment at the given offset?
Definition CharUnits.h:207
bool isZero() const
isZero - Test whether the quantity equals zero.
Definition CharUnits.h:122
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition CharUnits.h:185
static CharUnits One()
One - Construct a CharUnits quantity of one.
Definition CharUnits.h:58
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition CharUnits.h:63
unsigned getValue() const
Definition Expr.h:1632
Expr * getChosenSubExpr() const
getChosenSubExpr - Return the subexpression chosen according to the condition.
Definition Expr.h:4887
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:3337
QualType getElementType() const
Definition TypeBase.h:3347
CompoundAssignOperator - For compound assignments (e.g.
Definition Expr.h:4303
QualType getComputationLHSType() const
Definition Expr.h:4337
CompoundLiteralExpr - [C99 6.5.2.5].
Definition Expr.h:3608
bool hasStaticStorage() const
Definition Expr.h:3653
APValue & getOrCreateStaticValue(ASTContext &Ctx) const
Definition Expr.cpp:5692
bool isFileScope() const
Definition Expr.h:3640
const Expr * getInitializer() const
Definition Expr.h:3636
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition Stmt.h:1750
bool body_empty() const
Definition Stmt.h:1794
Stmt *const * const_body_iterator
Definition Stmt.h:1822
body_iterator body_end()
Definition Stmt.h:1815
body_range body()
Definition Stmt.h:1813
body_iterator body_begin()
Definition Stmt.h:1814
bool isSatisfied() const
Whether or not the concept with the given arguments was satisfied when the expression was created.
ConditionalOperator - The ?
Definition Expr.h:4394
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression representing the value of the expression if the condition eva...
Definition Expr.h:4426
Expr * getCond() const
getCond - Return the expression representing the condition for the ?
Definition Expr.h:4417
Expr * getTrueExpr() const
getTrueExpr - Return the subexpression representing the value of the expression if the condition eval...
Definition Expr.h:4421
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3822
unsigned getSizeBitWidth() const
Return the bit width of the size type.
Definition TypeBase.h:3885
static unsigned getNumAddressingBits(const ASTContext &Context, QualType ElementType, const llvm::APInt &NumElements)
Determine the number of bits required to address a member of.
Definition Type.cpp:251
static unsigned getMaxSizeBits(const ASTContext &Context)
Determine the maximum number of active bits that an array's size can require, which limits the maximu...
Definition Type.cpp:291
uint64_t getLimitedSize() const
Return the size zero-extended to uint64_t or UINT64_MAX if the value is larger than UINT64_MAX.
Definition TypeBase.h:3911
bool isZeroSize() const
Return true if the size is zero.
Definition TypeBase.h:3892
const Expr * getSizeExpr() const
Return a pointer to the size expression.
Definition TypeBase.h:3918
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3878
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition TypeBase.h:3898
APValue getAPValueResult() const
Definition Expr.cpp:418
bool hasAPValueResult() const
Definition Expr.h:1160
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4449
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operator.
Definition Expr.h:4799
Expr * getSrcExpr() const
getSrcExpr - Return the Expr to be converted.
Definition Expr.h:4812
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:1462
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2122
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition DeclBase.h:2251
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:1273
bool refersToEnclosingVariableOrCapture() const
Does this DeclRefExpr refer to an enclosing local or a captured variable?
Definition Expr.h:1477
ValueDecl * getDecl()
Definition Expr.h:1341
DeclStmt - Adaptor class for mixing declarations with statements and expressions.
Definition Stmt.h:1641
decl_range decls()
Definition Stmt.h:1689
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
bool isInStdNamespace() const
Definition DeclBase.cpp:450
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:547
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:4254
auto flat_bindings() const
Definition DeclCXX.h:4297
InitListExpr * getUpdater() const
Definition Expr.h:5936
Designator - A designator in a C99 designated initializer.
Definition Designator.h:38
DoStmt - This represents a 'do/while' stmt.
Definition Stmt.h:2842
Stmt * getBody()
Definition Stmt.h:2867
Expr * getCond()
Definition Stmt.h:2860
Symbolic representation of a dynamic allocation.
Definition APValue.h:65
static unsigned getMaxIndex()
Definition APValue.h:85
const Expr * getBase() const
Definition Expr.h:6581
ChildElementIter< false > begin()
Definition Expr.h:5235
ExplicitCastExpr - An explicit cast written in the source code.
Definition Expr.h:3931
QualType getTypeAsWritten() const
getTypeAsWritten - Returns the type that this expression is casting to, as written in the source code...
Definition Expr.h:3958
This represents one expression.
Definition Expr.h:112
const Expr * skipRValueSubobjectAdjustments(SmallVectorImpl< const Expr * > &CommaLHS, SmallVectorImpl< SubobjectAdjustment > &Adjustments) const
Walk outwards from an expression we want to bind a reference to and find the expression whose lifetim...
Definition Expr.cpp:84
bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsInt - Return true if this is a constant which we can fold and convert to an integer,...
static bool isPotentialConstantExpr(const FunctionDecl *FD, SmallVectorImpl< PartialDiagnosticAt > &Diags)
isPotentialConstantExpr - Return true if this function's definition might be usable in a constant exp...
bool isIntegerConstantExpr(const ASTContext &Ctx) const
static bool isPotentialConstantExprUnevaluated(Expr *E, const FunctionDecl *FD, SmallVectorImpl< PartialDiagnosticAt > &Diags)
isPotentialConstantExprUnevaluated - Return true if this expression might be usable in a constant exp...
bool isGLValue() const
Definition Expr.h:287
SideEffectsKind
Definition Expr.h:673
@ SE_AllowSideEffects
Allow any unmodeled side effect.
Definition Expr.h:677
@ SE_AllowUndefinedBehavior
Allow UB that we can give a value, but not arbitrary unmodeled side effects.
Definition Expr.h:675
bool isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result=nullptr) const
isCXX11ConstantExpr - Return true if this expression is a constant expression in C++11.
bool EvaluateCharRangeAsString(std::string &Result, const Expr *SizeExpression, const Expr *PtrExpression, ASTContext &Ctx, EvalResult &Status) const
llvm::APSInt EvaluateKnownConstIntCheckOverflow(const ASTContext &Ctx, SmallVectorImpl< PartialDiagnosticAt > *Diag=nullptr) const
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition Expr.cpp:3102
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:177
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Returns the set of floating point options that apply to this expression.
Definition Expr.cpp:3996
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3097
bool containsErrors() const
Whether this expression contains subexpressions which had errors.
Definition Expr.h:246
bool EvaluateAsFloat(llvm::APFloat &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsFloat - Return true if this is a constant which we can fold and convert to a floating point...
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3093
bool EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsLValue - Evaluate an expression to see if we can fold it to an lvalue with link time known ...
bool EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsFixedPoint - Return true if this is a constant which we can fold and convert to a fixed poi...
bool isEvaluatable(const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects) const
isEvaluatable - Call EvaluateAsRValue to see if this expression can be constant folded without side-e...
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
bool isPRValue() const
Definition Expr.h:285
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition Expr.h:284
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
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:3695
bool EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx, ConstantExprKind Kind=ConstantExprKind::Normal) const
Evaluate an expression that is required to be a constant expression.
std::optional< std::string > tryEvaluateString(ASTContext &Ctx) const
If the current Expr can be evaluated to a pointer to a null-terminated constant string,...
bool EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsBooleanCondition - Return true if this is a constant which we can fold and convert to a boo...
bool isTemporaryObject(ASTContext &Ctx, const CXXRecordDecl *TempTy) const
Determine whether the result of this expression is a temporary object of the given class type.
Definition Expr.cpp:3260
Expr()=delete
ConstantExprKind
Definition Expr.h:752
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:282
QualType getType() const
Definition Expr.h:144
bool isCXX98IntegralConstantExpr(const ASTContext &Ctx) const
isCXX98IntegralConstantExpr - Return true if this expression is an integral constant expression in C+...
bool EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx, const FunctionDecl *Callee, ArrayRef< const Expr * > Args, const Expr *This=nullptr) const
EvaluateWithSubstitution - Evaluate an expression as if from the context of a call to the given funct...
bool EvaluateAsInitializer(APValue &Result, const ASTContext &Ctx, const VarDecl *VD, SmallVectorImpl< PartialDiagnosticAt > &Notes, bool IsConstantInitializer) const
EvaluateAsInitializer - Evaluate an expression as if it were the initializer of the given declaration...
void EvaluateForOverflow(const ASTContext &Ctx) const
bool isArrow() const
isArrow - Return true if the base expression is a pointer to vector, return false if the base express...
Definition Expr.cpp:4443
void getEncodedElementAccess(SmallVectorImpl< uint32_t > &Elts) const
getEncodedElementAccess - Encode the elements accessed into an llvm aggregate Constant of ConstantInt...
Definition Expr.cpp:4556
bool isFPConstrained() const
LangOptions::FPExceptionModeKind getExceptionMode() const
RoundingMode getRoundingMode() const
Represents a member of a struct/union/class.
Definition Decl.h:3182
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3285
unsigned getBitWidthValue() const
Computes the bit width of this field, if this is a bit field.
Definition Decl.cpp:4746
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition Decl.h:3267
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3418
FieldDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this field.
Definition Decl.h:3429
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:104
llvm::APInt getValue() const
Returns an internal integer representation of the literal.
Definition Expr.h:1578
llvm::APFloat getValue() const
Definition Expr.h:1669
ForStmt - This represents a 'for (init;cond;inc)' stmt.
Definition Stmt.h:2898
Stmt * getInit()
Definition Stmt.h:2913
VarDecl * getConditionVariable() const
Retrieve the variable declared in this "for" statement, if any.
Definition Stmt.cpp:1120
Stmt * getBody()
Definition Stmt.h:2942
Expr * getInc()
Definition Stmt.h:2941
Expr * getCond()
Definition Stmt.h:2940
const Expr * getSubExpr() const
Definition Expr.h:1065
Represents a function declaration or definition.
Definition Decl.h:2018
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2815
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition Decl.cpp:3253
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition Decl.cpp:4179
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition Decl.cpp:4167
bool hasCXXExplicitFunctionObjectParameter() const
Definition Decl.cpp:3839
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition Decl.h:2395
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition Decl.cpp:4303
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition Decl.h:2488
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:3400
bool isDefaulted() const
Whether this function is defaulted.
Definition Decl.h:2403
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:3099
FunctionDecl * findSpecialization(ArrayRef< TemplateArgument > Args, void *&InsertPos)
Return the specialization with the provided arguments if it exists, otherwise return the insertion po...
Expr * getResultExpr()
Return the result expression of this controlling expression.
Definition Expr.h:6468
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:2269
Stmt * getThen()
Definition Stmt.h:2358
Stmt * getInit()
Definition Stmt.h:2419
bool isNonNegatedConsteval() const
Definition Stmt.h:2454
Expr * getCond()
Definition Stmt.h:2346
Stmt * getElse()
Definition Stmt.h:2367
bool isConsteval() const
Definition Stmt.h:2449
VarDecl * getConditionVariable()
Retrieve the variable declared in this "if" statement, if any.
Definition Stmt.cpp:1068
const Expr * getSubExpr() const
Definition Expr.h:1746
Represents an implicitly-generated value initialization of an object of a given type.
Definition Expr.h:6057
Represents a field injected from an anonymous union/struct into the parent scope.
Definition Decl.h:3489
ArrayRef< NamedDecl * > chain() const
Definition Decl.h:3510
Describes an C or C++ initializer list.
Definition Expr.h:5302
bool isTransparent() const
Is this a transparent initializer list (that is, an InitListExpr that is purely syntactic,...
Definition Expr.cpp:2469
bool isStringLiteralInit() const
Is this an initializer for an array of characters, initialized by a string literal or an @encode?
Definition Expr.cpp:2455
unsigned getNumInits() const
Definition Expr.h:5335
Expr * getArrayFiller()
If this initializer list initializes an array with more elements than there are initializers in the l...
Definition Expr.h:5405
const Expr * getInit(unsigned Init) const
Definition Expr.h:5357
ArrayRef< Expr * > inits() const
Definition Expr.h:5355
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:1407
@ FPE_Ignore
Assume that floating-point exceptions are masked.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Represents a prvalue temporary that is written into memory so that a reference can bind to it.
Definition ExprCXX.h:4920
StorageDuration getStorageDuration() const
Retrieve the storage duration for the materialized temporary.
Definition ExprCXX.h:4945
Expr * getSubExpr() const
Retrieve the temporary-generating subexpression whose value will be materialized into a glvalue.
Definition ExprCXX.h:4937
APValue * getOrCreateValue(bool MayCreate) const
Get the storage for the constant value of a materialized temporary of static storage duration.
Definition ExprCXX.h:4953
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3367
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3450
Expr * getBase() const
Definition Expr.h:3444
bool isArrow() const
Definition Expr.h:3551
This represents a decl that may have a name.
Definition Decl.h:274
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:295
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:301
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:340
void printQualifiedName(raw_ostream &OS) const
Returns a human-readable qualified name for this declaration, like A::B::i, for i being member of nam...
Definition Decl.cpp:1688
bool isExpressibleAsConstantInitializer() const
Definition ExprObjC.h:68
Expr * getIndexExpr(unsigned Idx)
Definition Expr.h:2589
const OffsetOfNode & getComponent(unsigned Idx) const
Definition Expr.h:2577
TypeSourceInfo * getTypeSourceInfo() const
Definition Expr.h:2570
unsigned getNumComponents() const
Definition Expr.h:2585
unsigned getArrayExprIndex() const
For an array element node, returns the index into the array of expressions.
Definition Expr.h:2482
FieldDecl * getField() const
For a field offsetof node, returns the field.
Definition Expr.h:2488
@ Array
An index into an array.
Definition Expr.h:2429
@ Identifier
A field in a dependent type, known only by its name.
Definition Expr.h:2433
@ Field
A field.
Definition Expr.h:2431
@ Base
An implicit indirection through a C++ base class, when the field found is in a base class.
Definition Expr.h:2436
Kind getKind() const
Determine what kind of offsetof node this is.
Definition Expr.h:2478
CXXBaseSpecifier * getBase() const
For a base class node, returns the base specifier.
Definition Expr.h:2498
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition Expr.h:1181
Expr * getSourceExpr() const
The source expression of an opaque value expression is the expression which originally generated the ...
Definition Expr.h:1231
Expr * getSelectedExpr() const
Definition ExprCXX.h:4639
const Expr * getSubExpr() const
Definition Expr.h:2202
Represents a parameter to a function.
Definition Decl.h:1808
unsigned getFunctionScopeIndex() const
Returns the index of this parameter in its prototype or method scope.
Definition Decl.h:1868
bool isExplicitObjectParameter() const
Definition Decl.h:1896
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3390
StringLiteral * getFunctionName()
Definition Expr.h:2052
Expr * getResultExpr()
Return the result-bearing expression, or null if there is none.
Definition Expr.h:6852
ArrayRef< Expr * > semantics()
Definition Expr.h:6876
A (possibly-)qualified type.
Definition TypeBase.h:937
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8529
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition Type.cpp:2962
QualType withConst() const
Definition TypeBase.h:1174
void addConst()
Add the const type qualifier to this QualType.
Definition TypeBase.h:1171
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1004
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8445
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:8630
QualType getCanonicalType() const
Definition TypeBase.h:8497
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8539
void removeLocalVolatile()
Definition TypeBase.h:8561
void addVolatile()
Add the volatile type qualifier to this QualType.
Definition TypeBase.h:1179
void removeLocalConst()
Definition TypeBase.h:8553
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8518
QualType getAtomicUnqualifiedType() const
Remove all qualifiers including _Atomic.
Definition Type.cpp:1719
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition TypeBase.h:1560
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition TypeBase.h:8491
bool isWrapType() const
Returns true if it is a OverflowBehaviorType of Wrap kind.
Definition Type.cpp:3052
Represents a struct/union/class.
Definition Decl.h:4347
unsigned getNumFields() const
Returns the number of fields (non-static data members) in this record.
Definition Decl.h:4563
field_iterator field_end() const
Definition Decl.h:4553
field_range fields() const
Definition Decl.h:4550
specific_decl_iterator< FieldDecl > field_iterator
Definition Decl.h:4547
bool isAnonymousStructOrUnion() const
Whether this is an anonymous struct or union.
Definition Decl.h:4399
bool field_empty() const
Definition Decl.h:4558
field_iterator field_begin() const
Definition Decl.cpp:5269
bool isSatisfied() const
Whether or not the requires clause is satisfied.
SourceLocation getLocation() const
Definition Expr.h:2158
std::string ComputeName(ASTContext &Context) const
Definition Expr.cpp:592
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:4646
llvm::APSInt getShuffleMaskIdx(unsigned N) const
Definition Expr.h:4698
unsigned getNumSubExprs() const
getNumSubExprs - Return the size of the SubExprs array.
Definition Expr.h:4679
Expr * getExpr(unsigned Index)
getExpr - Return the Expr at the specified index.
Definition Expr.h:4685
unsigned getPackLength() const
Retrieve the length of the parameter pack.
Definition ExprCXX.h:4515
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:2287
bool isIntType() const
Definition Expr.h:5044
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:4615
Stmt - This represents one statement.
Definition Stmt.h:86
@ NoStmtClass
Definition Stmt.h:89
StmtClass getStmtClass() const
Definition Stmt.h:1503
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:1802
unsigned getLength() const
Definition Expr.h:1912
StringRef getBytes() const
Allow access to clients that need the byte representation, such as ASTWriterStmt::VisitStringLiteral(...
Definition Expr.h:1878
uint32_t getCodeUnit(size_t i) const
Definition Expr.h:1885
StringRef getString() const
Definition Expr.h:1870
unsigned getCharByteWidth() const
Definition Expr.h:1913
const SwitchCase * getNextSwitchCase() const
Definition Stmt.h:1903
SwitchStmt - This represents a 'switch' stmt.
Definition Stmt.h:2519
Expr * getCond()
Definition Stmt.h:2582
Stmt * getBody()
Definition Stmt.h:2594
VarDecl * getConditionVariable()
Retrieve the variable declared in this "switch" statement, if any.
Definition Stmt.cpp:1186
Stmt * getInit()
Definition Stmt.h:2599
SwitchCase * getSwitchCaseList()
Definition Stmt.h:2650
TagDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:4893
bool isUnion() const
Definition Decl.h:3950
unsigned size() const
Retrieve the number of template arguments in this template argument list.
ArrayRef< TemplateArgument > asArray() const
Produce this as an array ref.
@ Type
The template argument is a type.
Symbolic representation of typeid(T) for some type T.
Definition APValue.h:44
QualType getType() const
Return the type wrapped by this type source info.
Definition TypeBase.h:8427
bool getBoolValue() const
Definition ExprCXX.h:2951
const APValue & getAPValue() const
Definition ExprCXX.h:2956
bool isStoredAsBoolean() const
Definition ExprCXX.h:2947
The base class of the type hierarchy.
Definition TypeBase.h:1875
bool isVoidType() const
Definition TypeBase.h:9048
bool isBooleanType() const
Definition TypeBase.h:9185
bool isFunctionReferenceType() const
Definition TypeBase.h:8756
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:2289
bool isPackedVectorBoolType(const ASTContext &ctx) const
Definition Type.cpp:455
bool isLiteralType(const ASTContext &Ctx) const
Return true if this is a literal type (C++11 [basic.types]p10)
Definition Type.cpp:3109
bool isIncompleteArrayType() const
Definition TypeBase.h:8789
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2266
bool isComplexType() const
isComplexType() does not include complex integers (a GCC extension).
Definition Type.cpp:761
const ArrayType * castAsArrayTypeUnsafe() const
A variant of castAs<> for array type which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9351
bool isUnsignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is unsigned or an enumeration types whose underlying ...
Definition Type.cpp:2355
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition Type.cpp:2173
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:8785
bool isNothrowT() const
Definition Type.cpp:3293
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition Type.h:41
bool isVoidPointerType() const
Definition Type.cpp:749
bool isConstantSizeType() const
Return true if this is not a variable sized type, according to the rules of C99 6....
Definition Type.cpp:2517
bool isArrayType() const
Definition TypeBase.h:8781
bool isFunctionPointerType() const
Definition TypeBase.h:8749
bool isConstantMatrixType() const
Definition TypeBase.h:8849
bool isPointerType() const
Definition TypeBase.h:8682
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:8706
bool isEnumeralType() const
Definition TypeBase.h:8813
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:1958
bool isVariableArrayType() const
Definition TypeBase.h:8793
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition Type.cpp:2701
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:789
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:9170
bool isExtVectorBoolType() const
Definition TypeBase.h:8829
bool isMemberDataPointerType() const
Definition TypeBase.h:8774
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:2844
RecordDecl * castAsRecordDecl() const
Definition Type.h:48
bool isAnyComplexType() const
Definition TypeBase.h:8817
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:8763
bool isAtomicType() const
Definition TypeBase.h:8874
bool isComplexIntegerType() const
Definition Type.cpp:767
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9328
bool isObjectType() const
Determine whether this type is an object type.
Definition TypeBase.h:2570
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:2527
bool isFunctionType() const
Definition TypeBase.h:8678
bool isVectorType() const
Definition TypeBase.h:8821
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2405
bool isFloatingType() const
Definition Type.cpp:2389
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:2332
const T * castAsCanonical() const
Return this type's canonical type cast to the specified type.
Definition TypeBase.h:2990
bool isAnyPointerType() const
Definition TypeBase.h:8690
TypeClass getTypeClass() const
Definition TypeBase.h:2445
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:8809
bool isUnionType() const
Definition Type.cpp:755
bool isSizelessVectorType() const
Returns true for all scalable vector types.
Definition Type.cpp:2663
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:2628
QualType getArgumentType() const
Definition Expr.h:2671
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:2707
QualType getTypeOfArgument() const
Gets the argument type, or the type of the argument expression, whichever is appropriate.
Definition Expr.h:2697
UnaryExprOrTypeTrait getKind() const
Definition Expr.h:2660
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2247
SourceLocation getExprLoc() const
Definition Expr.h:2371
Expr * getSubExpr() const
Definition Expr.h:2288
Opcode getOpcode() const
Definition Expr.h:2283
static bool isIncrementOp(Opcode Op)
Definition Expr.h:2329
bool canOverflow() const
Returns true if the unary operator can cause an overflow.
Definition Expr.h:2301
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:712
QualType getType() const
Definition Decl.h:723
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr.
Definition Decl.cpp:5575
QualType getType() const
Definition Value.cpp:237
bool hasValue() const
Definition Value.h:135
Represents a variable declaration or definition.
Definition Decl.h:924
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition Decl.h:1582
bool hasInit() const
Definition Decl.cpp:2377
bool hasICEInitializer(const ASTContext &Context) const
Determine whether the initializer of this variable is an integer constant expression.
Definition Decl.cpp:2615
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition Decl.h:1591
APValue * evaluateValue() const
Attempt to evaluate the value of the initializer attached to this declaration, and produce notes expl...
Definition Decl.cpp:2554
CharUnits getFlexibleArrayInitChars(const ASTContext &Ctx) const
If hasFlexibleArrayInit is true, compute the number of additional bytes necessary to store those elem...
Definition Decl.cpp:2835
bool hasConstantInitialization() const
Determine whether this variable has constant initialization.
Definition Decl.cpp:2627
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
Definition Decl.cpp:2345
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:2465
EvaluatedStmt * ensureEvaluatedStmt() const
Convert the initializer for this declaration to the elaborated EvaluatedStmt form,...
Definition Decl.cpp:2536
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:1206
ThreadStorageClassSpecifier getTSCSpec() const
Definition Decl.h:1175
const Expr * getInit() const
Definition Decl.h:1381
APValue * getEvaluatedValue() const
Return the already-evaluated value of this variable's initializer, or NULL if the value is not yet kn...
Definition Decl.cpp:2607
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition Decl.h:1182
DefinitionKind hasDefinition(ASTContext &) const
Check whether this variable is defined in this translation unit.
Definition Decl.cpp:2354
bool isLocalVarDecl() const
Returns true for local variable declarations other than parameters.
Definition Decl.h:1266
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:2507
const Expr * getAnyInitializer() const
Get the initializer for this variable, no matter which declaration it is attached to.
Definition Decl.h:1371
Expr * getSizeExpr() const
Definition TypeBase.h:4042
Represents a GCC generic vector type.
Definition TypeBase.h:4237
unsigned getNumElements() const
Definition TypeBase.h:4252
QualType getElementType() const
Definition TypeBase.h:4251
WhileStmt - This represents a 'while' stmt.
Definition Stmt.h:2707
Expr * getCond()
Definition Stmt.h:2759
VarDecl * getConditionVariable()
Retrieve the variable declared in this "while" statement, if any.
Definition Stmt.cpp:1247
Stmt * getBody()
Definition Stmt.h:2771
bool evaluateDestruction(State &Parent, const VarDecl *VD, APValue Value)
Evaluates the destruction of a variable.
Definition Context.cpp:164
Base class for stack frames, shared between VM and walker.
Definition Frame.h:25
Interface for the VM to interact with the AST walker's context.
Definition State.h:81
Defines the clang::TargetInfo interface.
#define CHAR_BIT
Definition limits.h:71
#define UINT_MAX
Definition limits.h:64
bool computeOSLogBufferLayout(clang::ASTContext &Ctx, const clang::CallExpr *E, OSLogBufferLayout &layout)
Definition OSLog.cpp:192
static const FunctionDecl * getCallee(const CXXConstructExpr &D)
uint32_t Literal
Literals are represented as positive integers.
Definition CNFFormula.h:35
unsigned kind
All of the diagnostics that can be emitted by the frontend.
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 NE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1475
llvm::FixedPointSemantics FixedPointSemantics
Definition Interp.h:56
bool This(InterpState &S, CodePtr OpPC)
Definition Interp.h:3119
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:3825
std::variant< struct RequiresDecl, struct HeaderDecl, struct UmbrellaDirDecl, struct ModuleDecl, struct ExcludeDecl, struct ExportDecl, struct ExportAsDecl, struct ExternModuleDecl, struct UseDecl, struct LinkDecl, struct ConfigMacrosDecl, struct ConflictDecl > Decl
All declarations that can appear in a module declaration.
AccessKind
This enum distinguishes between different ways to access (read or write) a variable.
ASTEdit note(RangeSelector Anchor, TextGenerator Note)
Generates a single, no-op edit with the associated note anchored at the start location of the specifi...
The JSON file list parser is used to communicate input to InstallAPI.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
bool isa(CodeGen::Address addr)
Definition Address.h:330
bool hasSpecificAttr(const Container &container)
@ NonNull
Values of this type can never be null.
Definition Specifiers.h:351
@ Success
Annotation was successful.
Definition Parser.h:65
Expr::ConstantExprKind ConstantExprKind
Definition Expr.h:1045
@ Self
'self' clause, allowed on Compute and Combined Constructs, plus 'update'.
bool operator==(const CallGraphNode::CallRecord &LHS, const CallGraphNode::CallRecord &RHS)
Definition CallGraph.h:206
@ AS_public
Definition Specifiers.h:125
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
bool isLambdaCallWithExplicitObjectParameter(const DeclContext *DC)
Definition ASTLambda.h:45
@ TSCS_unspecified
Definition Specifiers.h:237
Expr * Cond
};
UnaryExprOrTypeTrait
Names for the "expression or type" traits.
Definition TypeTraits.h:51
ComparisonCategoryResult
An enumeration representing the possible results of a three-way comparison.
CheckSubobjectKind
The order of this enum is important for diagnostics.
Definition State.h:44
@ CSK_ArrayToPointer
Definition State.h:48
@ CSK_Derived
Definition State.h:46
@ CSK_Base
Definition State.h:45
@ CSK_Real
Definition State.h:50
@ CSK_ArrayIndex
Definition State.h:49
@ CSK_Imag
Definition State.h:51
@ CSK_VectorElement
Definition State.h:52
@ CSK_Field
Definition State.h:47
@ SD_Static
Static storage duration.
Definition Specifiers.h:344
@ SD_FullExpression
Full-expression storage duration (for temporaries).
Definition Specifiers.h:341
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition ASTLambda.h:28
@ Result
The result type of a method or function.
Definition TypeBase.h:905
AccessKinds
Kinds of access we can perform on an object, for diagnostics.
Definition State.h:28
@ AK_TypeId
Definition State.h:36
@ AK_Construct
Definition State.h:37
@ AK_Increment
Definition State.h:32
@ AK_DynamicCast
Definition State.h:35
@ AK_Read
Definition State.h:29
@ AK_Assign
Definition State.h:31
@ AK_IsWithinLifetime
Definition State.h:39
@ AK_MemberCall
Definition State.h:34
@ AK_ReadObjectRepresentation
Definition State.h:30
@ AK_Dereference
Definition State.h:40
@ AK_Destroy
Definition State.h:38
@ AK_Decrement
Definition State.h:33
@ Type
The name was classified as a type.
Definition Sema.h:564
CastKind
CastKind - The kind of operation required for a conversion.
llvm::hash_code hash_value(const CustomizableOptional< T > &O)
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:136
EvaluationMode
Definition State.h:55
@ ConstantFold
Fold the expression to a constant.
Definition State.h:69
@ ConstantExpressionUnevaluated
Evaluate as a constant expression.
Definition State.h:65
@ ConstantExpression
Evaluate as a constant expression.
Definition State.h:58
@ IgnoreSideEffects
Evaluate in any way we know how.
Definition State.h:73
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition DeclBase.h:1301
U cast(CodeGen::Address addr)
Definition Address.h:327
@ None
The alignment was not explicit in code.
Definition ASTContext.h:182
@ ArrayBound
Array bound in array declarator or new-expression.
Definition Sema.h:844
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5979
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ Other
Other implicit parameter.
Definition Decl.h:1763
ActionResult< Stmt * > StmtResult
Definition Ownership.h:250
unsigned long uint64_t
long int64_t
unsigned int uint32_t
Diagnostic wrappers for TextAPI types for error reporting.
Definition Dominators.h:30
hash_code hash_value(const clang::dependencies::ModuleID &ID)
#define false
Definition stdbool.h:26
unsigned PathLength
The corresponding path length in the lvalue.
const CXXRecordDecl * Type
The dynamic class type of the object.
std::string ObjCEncodeStorage
Represents an element in a path from a derived class to a base class.
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:648
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:650
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:612
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:636
bool HasSideEffects
Whether the evaluated expression has side effects.
Definition Expr.h:615
unsigned SuppressLambdaBody
Whether to suppress printing the body of a lambda.
static ObjectUnderConstruction getTombstoneKey()
DenseMapInfo< APValue::LValueBase > Base
static ObjectUnderConstruction getEmptyKey()
static unsigned getHashValue(const ObjectUnderConstruction &Object)
static bool isEqual(const ObjectUnderConstruction &LHS, const ObjectUnderConstruction &RHS)
#define ilogb(__x)
Definition tgmath.h:851
#define scalbn(__x, __y)
Definition tgmath.h:1165