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 default:
11793 return ExprEvaluatorBaseTy::VisitCastExpr(E);
11794 }
11795}
11796
11797bool
11798VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
11799 const VectorType *VT = E->getType()->castAs<VectorType>();
11800 unsigned NumInits = E->getNumInits();
11801 unsigned NumElements = VT->getNumElements();
11802
11803 QualType EltTy = VT->getElementType();
11804 SmallVector<APValue, 4> Elements;
11805
11806 // MFloat8 type doesn't have constants and thus constant folding
11807 // is impossible.
11808 if (EltTy->isMFloat8Type())
11809 return false;
11810
11811 // The number of initializers can be less than the number of
11812 // vector elements. For OpenCL, this can be due to nested vector
11813 // initialization. For GCC compatibility, missing trailing elements
11814 // should be initialized with zeroes.
11815 unsigned CountInits = 0, CountElts = 0;
11816 while (CountElts < NumElements) {
11817 // Handle nested vector initialization.
11818 if (CountInits < NumInits
11819 && E->getInit(CountInits)->getType()->isVectorType()) {
11820 APValue v;
11821 if (!EvaluateVector(E->getInit(CountInits), v, Info))
11822 return Error(E);
11823 unsigned vlen = v.getVectorLength();
11824 for (unsigned j = 0; j < vlen; j++)
11825 Elements.push_back(v.getVectorElt(j));
11826 CountElts += vlen;
11827 } else if (EltTy->isIntegerType()) {
11828 llvm::APSInt sInt(32);
11829 if (CountInits < NumInits) {
11830 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
11831 return false;
11832 } else // trailing integer zero.
11833 sInt = Info.Ctx.MakeIntValue(0, EltTy);
11834 Elements.push_back(APValue(sInt));
11835 CountElts++;
11836 } else {
11837 llvm::APFloat f(0.0);
11838 if (CountInits < NumInits) {
11839 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
11840 return false;
11841 } else // trailing float zero.
11842 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
11843 Elements.push_back(APValue(f));
11844 CountElts++;
11845 }
11846 CountInits++;
11847 }
11848 return Success(Elements, E);
11849}
11850
11851bool
11852VectorExprEvaluator::ZeroInitialization(const Expr *E) {
11853 const auto *VT = E->getType()->castAs<VectorType>();
11854 QualType EltTy = VT->getElementType();
11855 APValue ZeroElement;
11856 if (EltTy->isIntegerType())
11857 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
11858 else
11859 ZeroElement =
11860 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
11861
11862 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
11863 return Success(Elements, E);
11864}
11865
11866bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
11867 VisitIgnoredValue(E->getSubExpr());
11868 return ZeroInitialization(E);
11869}
11870
11871bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
11872 BinaryOperatorKind Op = E->getOpcode();
11873 assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp &&
11874 "Operation not supported on vector types");
11875
11876 if (Op == BO_Comma)
11877 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
11878
11879 Expr *LHS = E->getLHS();
11880 Expr *RHS = E->getRHS();
11881
11882 assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() &&
11883 "Must both be vector types");
11884 // Checking JUST the types are the same would be fine, except shifts don't
11885 // need to have their types be the same (since you always shift by an int).
11886 assert(LHS->getType()->castAs<VectorType>()->getNumElements() ==
11887 E->getType()->castAs<VectorType>()->getNumElements() &&
11888 RHS->getType()->castAs<VectorType>()->getNumElements() ==
11889 E->getType()->castAs<VectorType>()->getNumElements() &&
11890 "All operands must be the same size.");
11891
11892 APValue LHSValue;
11893 APValue RHSValue;
11894 bool LHSOK = Evaluate(LHSValue, Info, LHS);
11895 if (!LHSOK && !Info.noteFailure())
11896 return false;
11897 if (!Evaluate(RHSValue, Info, RHS) || !LHSOK)
11898 return false;
11899
11900 if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue))
11901 return false;
11902
11903 return Success(LHSValue, E);
11904}
11905
11906static std::optional<APValue> handleVectorUnaryOperator(ASTContext &Ctx,
11907 QualType ResultTy,
11909 APValue Elt) {
11910 switch (Op) {
11911 case UO_Plus:
11912 // Nothing to do here.
11913 return Elt;
11914 case UO_Minus:
11915 if (Elt.getKind() == APValue::Int) {
11916 Elt.getInt().negate();
11917 } else {
11918 assert(Elt.getKind() == APValue::Float &&
11919 "Vector can only be int or float type");
11920 Elt.getFloat().changeSign();
11921 }
11922 return Elt;
11923 case UO_Not:
11924 // This is only valid for integral types anyway, so we don't have to handle
11925 // float here.
11926 assert(Elt.getKind() == APValue::Int &&
11927 "Vector operator ~ can only be int");
11928 Elt.getInt().flipAllBits();
11929 return Elt;
11930 case UO_LNot: {
11931 if (Elt.getKind() == APValue::Int) {
11932 Elt.getInt() = !Elt.getInt();
11933 // operator ! on vectors returns -1 for 'truth', so negate it.
11934 Elt.getInt().negate();
11935 return Elt;
11936 }
11937 assert(Elt.getKind() == APValue::Float &&
11938 "Vector can only be int or float type");
11939 // Float types result in an int of the same size, but -1 for true, or 0 for
11940 // false.
11941 APSInt EltResult{Ctx.getIntWidth(ResultTy),
11942 ResultTy->isUnsignedIntegerType()};
11943 if (Elt.getFloat().isZero())
11944 EltResult.setAllBits();
11945 else
11946 EltResult.clearAllBits();
11947
11948 return APValue{EltResult};
11949 }
11950 default:
11951 // FIXME: Implement the rest of the unary operators.
11952 return std::nullopt;
11953 }
11954}
11955
11956bool VectorExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
11957 Expr *SubExpr = E->getSubExpr();
11958 const auto *VD = SubExpr->getType()->castAs<VectorType>();
11959 // This result element type differs in the case of negating a floating point
11960 // vector, since the result type is the a vector of the equivilant sized
11961 // integer.
11962 const QualType ResultEltTy = VD->getElementType();
11963 UnaryOperatorKind Op = E->getOpcode();
11964
11965 APValue SubExprValue;
11966 if (!Evaluate(SubExprValue, Info, SubExpr))
11967 return false;
11968
11969 // FIXME: This vector evaluator someday needs to be changed to be LValue
11970 // aware/keep LValue information around, rather than dealing with just vector
11971 // types directly. Until then, we cannot handle cases where the operand to
11972 // these unary operators is an LValue. The only case I've been able to see
11973 // cause this is operator++ assigning to a member expression (only valid in
11974 // altivec compilations) in C mode, so this shouldn't limit us too much.
11975 if (SubExprValue.isLValue())
11976 return false;
11977
11978 assert(SubExprValue.getVectorLength() == VD->getNumElements() &&
11979 "Vector length doesn't match type?");
11980
11981 SmallVector<APValue, 4> ResultElements;
11982 for (unsigned EltNum = 0; EltNum < VD->getNumElements(); ++EltNum) {
11983 std::optional<APValue> Elt = handleVectorUnaryOperator(
11984 Info.Ctx, ResultEltTy, Op, SubExprValue.getVectorElt(EltNum));
11985 if (!Elt)
11986 return false;
11987 ResultElements.push_back(*Elt);
11988 }
11989 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
11990}
11991
11992static bool handleVectorElementCast(EvalInfo &Info, const FPOptions FPO,
11993 const Expr *E, QualType SourceTy,
11994 QualType DestTy, APValue const &Original,
11995 APValue &Result) {
11996 if (SourceTy->isIntegerType()) {
11997 if (DestTy->isRealFloatingType()) {
11998 Result = APValue(APFloat(0.0));
11999 return HandleIntToFloatCast(Info, E, FPO, SourceTy, Original.getInt(),
12000 DestTy, Result.getFloat());
12001 }
12002 if (DestTy->isIntegerType()) {
12003 Result = APValue(
12004 HandleIntToIntCast(Info, E, DestTy, SourceTy, Original.getInt()));
12005 return true;
12006 }
12007 } else if (SourceTy->isRealFloatingType()) {
12008 if (DestTy->isRealFloatingType()) {
12009 Result = Original;
12010 return HandleFloatToFloatCast(Info, E, SourceTy, DestTy,
12011 Result.getFloat());
12012 }
12013 if (DestTy->isIntegerType()) {
12014 Result = APValue(APSInt());
12015 return HandleFloatToIntCast(Info, E, SourceTy, Original.getFloat(),
12016 DestTy, Result.getInt());
12017 }
12018 }
12019
12020 Info.FFDiag(E, diag::err_convertvector_constexpr_unsupported_vector_cast)
12021 << SourceTy << DestTy;
12022 return false;
12023}
12024
12025static bool evalPackBuiltin(const CallExpr *E, EvalInfo &Info, APValue &Result,
12026 llvm::function_ref<APInt(const APSInt &)> PackFn) {
12027 APValue LHS, RHS;
12028 if (!EvaluateAsRValue(Info, E->getArg(0), LHS) ||
12029 !EvaluateAsRValue(Info, E->getArg(1), RHS))
12030 return false;
12031
12032 unsigned LHSVecLen = LHS.getVectorLength();
12033 unsigned RHSVecLen = RHS.getVectorLength();
12034
12035 assert(LHSVecLen != 0 && LHSVecLen == RHSVecLen &&
12036 "pack builtin LHSVecLen must equal to RHSVecLen");
12037
12038 const VectorType *VT0 = E->getArg(0)->getType()->castAs<VectorType>();
12039 const unsigned SrcBits = Info.Ctx.getIntWidth(VT0->getElementType());
12040
12041 const VectorType *DstVT = E->getType()->castAs<VectorType>();
12042 QualType DstElemTy = DstVT->getElementType();
12043 const bool DstIsUnsigned = DstElemTy->isUnsignedIntegerType();
12044
12045 const unsigned SrcPerLane = 128 / SrcBits;
12046 const unsigned Lanes = LHSVecLen * SrcBits / 128;
12047
12049 Out.reserve(LHSVecLen + RHSVecLen);
12050
12051 for (unsigned Lane = 0; Lane != Lanes; ++Lane) {
12052 unsigned base = Lane * SrcPerLane;
12053 for (unsigned I = 0; I != SrcPerLane; ++I)
12054 Out.emplace_back(APValue(
12055 APSInt(PackFn(LHS.getVectorElt(base + I).getInt()), DstIsUnsigned)));
12056 for (unsigned I = 0; I != SrcPerLane; ++I)
12057 Out.emplace_back(APValue(
12058 APSInt(PackFn(RHS.getVectorElt(base + I).getInt()), DstIsUnsigned)));
12059 }
12060
12061 Result = APValue(Out.data(), Out.size());
12062 return true;
12063}
12064
12066 EvalInfo &Info, const CallExpr *Call, APValue &Out,
12067 llvm::function_ref<std::pair<unsigned, int>(unsigned, unsigned)>
12068 GetSourceIndex) {
12069
12070 const auto *VT = Call->getType()->getAs<VectorType>();
12071 if (!VT)
12072 return false;
12073
12074 unsigned ShuffleMask = 0;
12075 APValue A, MaskVector, B;
12076 bool IsVectorMask = false;
12077 bool IsSingleOperand = (Call->getNumArgs() == 2);
12078
12079 if (IsSingleOperand) {
12080 QualType MaskType = Call->getArg(1)->getType();
12081 if (MaskType->isVectorType()) {
12082 IsVectorMask = true;
12083 if (!EvaluateAsRValue(Info, Call->getArg(0), A) ||
12084 !EvaluateAsRValue(Info, Call->getArg(1), MaskVector))
12085 return false;
12086 B = A;
12087 } else if (MaskType->isIntegerType()) {
12088 APSInt MaskImm;
12089 if (!EvaluateInteger(Call->getArg(1), MaskImm, Info))
12090 return false;
12091 ShuffleMask = static_cast<unsigned>(MaskImm.getZExtValue());
12092 if (!EvaluateAsRValue(Info, Call->getArg(0), A))
12093 return false;
12094 B = A;
12095 } else {
12096 return false;
12097 }
12098 } else {
12099 QualType Arg2Type = Call->getArg(2)->getType();
12100 if (Arg2Type->isVectorType()) {
12101 IsVectorMask = true;
12102 if (!EvaluateAsRValue(Info, Call->getArg(0), A) ||
12103 !EvaluateAsRValue(Info, Call->getArg(1), MaskVector) ||
12104 !EvaluateAsRValue(Info, Call->getArg(2), B))
12105 return false;
12106 } else if (Arg2Type->isIntegerType()) {
12107 APSInt MaskImm;
12108 if (!EvaluateInteger(Call->getArg(2), MaskImm, Info))
12109 return false;
12110 ShuffleMask = static_cast<unsigned>(MaskImm.getZExtValue());
12111 if (!EvaluateAsRValue(Info, Call->getArg(0), A) ||
12112 !EvaluateAsRValue(Info, Call->getArg(1), B))
12113 return false;
12114 } else {
12115 return false;
12116 }
12117 }
12118
12119 unsigned NumElts = VT->getNumElements();
12120 SmallVector<APValue, 64> ResultElements;
12121 ResultElements.reserve(NumElts);
12122
12123 for (unsigned DstIdx = 0; DstIdx != NumElts; ++DstIdx) {
12124 if (IsVectorMask) {
12125 ShuffleMask = static_cast<unsigned>(
12126 MaskVector.getVectorElt(DstIdx).getInt().getZExtValue());
12127 }
12128 auto [SrcVecIdx, SrcIdx] = GetSourceIndex(DstIdx, ShuffleMask);
12129
12130 if (SrcIdx < 0) {
12131 // Zero out this element
12132 QualType ElemTy = VT->getElementType();
12133 if (ElemTy->isRealFloatingType()) {
12134 ResultElements.push_back(
12135 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy))));
12136 } else if (ElemTy->isIntegerType()) {
12137 APValue Zero(Info.Ctx.MakeIntValue(0, ElemTy));
12138 ResultElements.push_back(APValue(Zero));
12139 } else {
12140 // Other types of fallback logic
12141 ResultElements.push_back(APValue());
12142 }
12143 } else {
12144 const APValue &Src = (SrcVecIdx == 0) ? A : B;
12145 ResultElements.push_back(Src.getVectorElt(SrcIdx));
12146 }
12147 }
12148
12149 Out = APValue(ResultElements.data(), ResultElements.size());
12150 return true;
12151}
12152static bool ConvertDoubleToFloatStrict(EvalInfo &Info, const Expr *E,
12153 APFloat OrigVal, APValue &Result) {
12154
12155 if (OrigVal.isInfinity()) {
12156 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << 0;
12157 return false;
12158 }
12159 if (OrigVal.isNaN()) {
12160 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << 1;
12161 return false;
12162 }
12163
12164 APFloat Val = OrigVal;
12165 bool LosesInfo = false;
12166 APFloat::opStatus Status = Val.convert(
12167 APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, &LosesInfo);
12168
12169 if (LosesInfo || Val.isDenormal()) {
12170 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic_strict);
12171 return false;
12172 }
12173
12174 if (Status != APFloat::opOK) {
12175 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
12176 return false;
12177 }
12178
12179 Result = APValue(Val);
12180 return true;
12181}
12183 EvalInfo &Info, const CallExpr *Call, APValue &Out,
12184 llvm::function_ref<APInt(const APInt &, uint64_t)> ShiftOp,
12185 llvm::function_ref<APInt(const APInt &, unsigned)> OverflowOp) {
12186
12187 APValue Source, Count;
12188 if (!EvaluateAsRValue(Info, Call->getArg(0), Source) ||
12189 !EvaluateAsRValue(Info, Call->getArg(1), Count))
12190 return false;
12191
12192 assert(Call->getNumArgs() == 2);
12193
12194 QualType SourceTy = Call->getArg(0)->getType();
12195 assert(SourceTy->isVectorType() &&
12196 Call->getArg(1)->getType()->isVectorType());
12197
12198 QualType DestEltTy = SourceTy->castAs<VectorType>()->getElementType();
12199 unsigned DestEltWidth = Source.getVectorElt(0).getInt().getBitWidth();
12200 unsigned DestLen = Source.getVectorLength();
12201 bool IsDestUnsigned = DestEltTy->isUnsignedIntegerType();
12202 unsigned CountEltWidth = Count.getVectorElt(0).getInt().getBitWidth();
12203 unsigned NumBitsInQWord = 64;
12204 unsigned NumCountElts = NumBitsInQWord / CountEltWidth;
12206 Result.reserve(DestLen);
12207
12208 uint64_t CountLQWord = 0;
12209 for (unsigned EltIdx = 0; EltIdx != NumCountElts; ++EltIdx) {
12210 uint64_t Elt = Count.getVectorElt(EltIdx).getInt().getZExtValue();
12211 CountLQWord |= (Elt << (EltIdx * CountEltWidth));
12212 }
12213
12214 for (unsigned EltIdx = 0; EltIdx != DestLen; ++EltIdx) {
12215 APInt Elt = Source.getVectorElt(EltIdx).getInt();
12216 if (CountLQWord < DestEltWidth) {
12217 Result.push_back(
12218 APValue(APSInt(ShiftOp(Elt, CountLQWord), IsDestUnsigned)));
12219 } else {
12220 Result.push_back(
12221 APValue(APSInt(OverflowOp(Elt, DestEltWidth), IsDestUnsigned)));
12222 }
12223 }
12224 Out = APValue(Result.data(), Result.size());
12225 return true;
12226}
12227
12228std::optional<APFloat> EvalScalarMinMaxFp(const APFloat &A, const APFloat &B,
12229 std::optional<APSInt> RoundingMode,
12230 bool IsMin) {
12231 APSInt DefaultMode(APInt(32, 4), /*isUnsigned=*/true);
12232 if (RoundingMode.value_or(DefaultMode) != 4)
12233 return std::nullopt;
12234 if (A.isNaN() || A.isInfinity() || A.isDenormal() || B.isNaN() ||
12235 B.isInfinity() || B.isDenormal())
12236 return std::nullopt;
12237 if (A.isZero() && B.isZero())
12238 return B;
12239 return IsMin ? llvm::minimum(A, B) : llvm::maximum(A, B);
12240}
12241
12242bool VectorExprEvaluator::VisitCallExpr(const CallExpr *E) {
12243 if (!IsConstantEvaluatedBuiltinCall(E))
12244 return ExprEvaluatorBaseTy::VisitCallExpr(E);
12245
12246 auto EvaluateBinOpExpr =
12247 [&](llvm::function_ref<APInt(const APSInt &, const APSInt &)> Fn) {
12248 APValue SourceLHS, SourceRHS;
12249 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
12250 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
12251 return false;
12252
12253 auto *DestTy = E->getType()->castAs<VectorType>();
12254 QualType DestEltTy = DestTy->getElementType();
12255 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
12256 unsigned SourceLen = SourceLHS.getVectorLength();
12257 SmallVector<APValue, 4> ResultElements;
12258 ResultElements.reserve(SourceLen);
12259
12260 if (SourceRHS.isInt()) {
12261 const APSInt &RHS = SourceRHS.getInt();
12262 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12263 const APSInt &LHS = SourceLHS.getVectorElt(EltNum).getInt();
12264 ResultElements.push_back(
12265 APValue(APSInt(Fn(LHS, RHS), DestUnsigned)));
12266 }
12267 } else {
12268 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12269 const APSInt &LHS = SourceLHS.getVectorElt(EltNum).getInt();
12270 const APSInt &RHS = SourceRHS.getVectorElt(EltNum).getInt();
12271 ResultElements.push_back(
12272 APValue(APSInt(Fn(LHS, RHS), DestUnsigned)));
12273 }
12274 }
12275 return Success(APValue(ResultElements.data(), SourceLen), E);
12276 };
12277
12278 auto EvaluateFpBinOpExpr =
12279 [&](llvm::function_ref<std::optional<APFloat>(
12280 const APFloat &, const APFloat &, std::optional<APSInt>)>
12281 Fn,
12282 bool IsScalar = false) {
12283 assert(E->getNumArgs() == 2 || E->getNumArgs() == 3);
12284 APValue A, B;
12285 if (!EvaluateAsRValue(Info, E->getArg(0), A) ||
12286 !EvaluateAsRValue(Info, E->getArg(1), B))
12287 return false;
12288
12289 assert(A.isVector() && B.isVector());
12290 assert(A.getVectorLength() == B.getVectorLength());
12291
12292 std::optional<APSInt> RoundingMode;
12293 if (E->getNumArgs() == 3) {
12294 APSInt Imm;
12295 if (!EvaluateInteger(E->getArg(2), Imm, Info))
12296 return false;
12297 RoundingMode = Imm;
12298 }
12299
12300 unsigned NumElems = A.getVectorLength();
12301 SmallVector<APValue, 4> ResultElements;
12302 ResultElements.reserve(NumElems);
12303
12304 for (unsigned EltNum = 0; EltNum < NumElems; ++EltNum) {
12305 if (IsScalar && EltNum > 0) {
12306 ResultElements.push_back(A.getVectorElt(EltNum));
12307 continue;
12308 }
12309 const APFloat &EltA = A.getVectorElt(EltNum).getFloat();
12310 const APFloat &EltB = B.getVectorElt(EltNum).getFloat();
12311 std::optional<APFloat> Result = Fn(EltA, EltB, RoundingMode);
12312 if (!Result)
12313 return false;
12314 ResultElements.push_back(APValue(*Result));
12315 }
12316 return Success(APValue(ResultElements.data(), NumElems), E);
12317 };
12318
12319 auto EvaluateScalarFpRoundMaskBinOp =
12320 [&](llvm::function_ref<std::optional<APFloat>(
12321 const APFloat &, const APFloat &, std::optional<APSInt>)>
12322 Fn) {
12323 assert(E->getNumArgs() == 5);
12324 APValue VecA, VecB, VecSrc;
12325 APSInt MaskVal, Rounding;
12326
12327 if (!EvaluateAsRValue(Info, E->getArg(0), VecA) ||
12328 !EvaluateAsRValue(Info, E->getArg(1), VecB) ||
12329 !EvaluateAsRValue(Info, E->getArg(2), VecSrc) ||
12330 !EvaluateInteger(E->getArg(3), MaskVal, Info) ||
12331 !EvaluateInteger(E->getArg(4), Rounding, Info))
12332 return false;
12333
12334 unsigned NumElems = VecA.getVectorLength();
12335 SmallVector<APValue, 8> ResultElements;
12336 ResultElements.reserve(NumElems);
12337
12338 if (MaskVal.getZExtValue() & 1) {
12339 const APFloat &EltA = VecA.getVectorElt(0).getFloat();
12340 const APFloat &EltB = VecB.getVectorElt(0).getFloat();
12341 std::optional<APFloat> Result = Fn(EltA, EltB, Rounding);
12342 if (!Result)
12343 return false;
12344 ResultElements.push_back(APValue(*Result));
12345 } else {
12346 ResultElements.push_back(VecSrc.getVectorElt(0));
12347 }
12348
12349 for (unsigned I = 1; I < NumElems; ++I)
12350 ResultElements.push_back(VecA.getVectorElt(I));
12351
12352 return Success(APValue(ResultElements.data(), NumElems), E);
12353 };
12354
12355 auto EvalSelectScalar = [&](unsigned Len) -> bool {
12356 APSInt Mask;
12357 APValue AVal, WVal;
12358 if (!EvaluateInteger(E->getArg(0), Mask, Info) ||
12359 !EvaluateAsRValue(Info, E->getArg(1), AVal) ||
12360 !EvaluateAsRValue(Info, E->getArg(2), WVal))
12361 return false;
12362
12363 bool TakeA0 = (Mask.getZExtValue() & 1u) != 0;
12365 Res.reserve(Len);
12366 Res.push_back(TakeA0 ? AVal.getVectorElt(0) : WVal.getVectorElt(0));
12367 for (unsigned I = 1; I < Len; ++I)
12368 Res.push_back(WVal.getVectorElt(I));
12369 APValue V(Res.data(), Res.size());
12370 return Success(V, E);
12371 };
12372
12373 switch (E->getBuiltinCallee()) {
12374 default:
12375 return false;
12376 case Builtin::BI__builtin_elementwise_popcount:
12377 case Builtin::BI__builtin_elementwise_bitreverse: {
12378 APValue Source;
12379 if (!EvaluateAsRValue(Info, E->getArg(0), Source))
12380 return false;
12381
12382 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
12383 unsigned SourceLen = Source.getVectorLength();
12384 SmallVector<APValue, 4> ResultElements;
12385 ResultElements.reserve(SourceLen);
12386
12387 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12388 APSInt Elt = Source.getVectorElt(EltNum).getInt();
12389 switch (E->getBuiltinCallee()) {
12390 case Builtin::BI__builtin_elementwise_popcount:
12391 ResultElements.push_back(APValue(
12392 APSInt(APInt(Info.Ctx.getIntWidth(DestEltTy), Elt.popcount()),
12393 DestEltTy->isUnsignedIntegerOrEnumerationType())));
12394 break;
12395 case Builtin::BI__builtin_elementwise_bitreverse:
12396 ResultElements.push_back(
12397 APValue(APSInt(Elt.reverseBits(),
12398 DestEltTy->isUnsignedIntegerOrEnumerationType())));
12399 break;
12400 }
12401 }
12402
12403 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12404 }
12405 case Builtin::BI__builtin_elementwise_abs: {
12406 APValue Source;
12407 if (!EvaluateAsRValue(Info, E->getArg(0), Source))
12408 return false;
12409
12410 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
12411 unsigned SourceLen = Source.getVectorLength();
12412 SmallVector<APValue, 4> ResultElements;
12413 ResultElements.reserve(SourceLen);
12414
12415 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12416 APValue CurrentEle = Source.getVectorElt(EltNum);
12417 APValue Val = DestEltTy->isFloatingType()
12418 ? APValue(llvm::abs(CurrentEle.getFloat()))
12419 : APValue(APSInt(
12420 CurrentEle.getInt().abs(),
12421 DestEltTy->isUnsignedIntegerOrEnumerationType()));
12422 ResultElements.push_back(Val);
12423 }
12424
12425 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12426 }
12427
12428 case Builtin::BI__builtin_elementwise_add_sat:
12429 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
12430 return LHS.isSigned() ? LHS.sadd_sat(RHS) : LHS.uadd_sat(RHS);
12431 });
12432
12433 case Builtin::BI__builtin_elementwise_sub_sat:
12434 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
12435 return LHS.isSigned() ? LHS.ssub_sat(RHS) : LHS.usub_sat(RHS);
12436 });
12437
12438 case X86::BI__builtin_ia32_extract128i256:
12439 case X86::BI__builtin_ia32_vextractf128_pd256:
12440 case X86::BI__builtin_ia32_vextractf128_ps256:
12441 case X86::BI__builtin_ia32_vextractf128_si256: {
12442 APValue SourceVec, SourceImm;
12443 if (!EvaluateAsRValue(Info, E->getArg(0), SourceVec) ||
12444 !EvaluateAsRValue(Info, E->getArg(1), SourceImm))
12445 return false;
12446
12447 if (!SourceVec.isVector())
12448 return false;
12449
12450 const auto *RetVT = E->getType()->castAs<VectorType>();
12451 unsigned RetLen = RetVT->getNumElements();
12452 unsigned Idx = SourceImm.getInt().getZExtValue() & 1;
12453
12454 SmallVector<APValue, 32> ResultElements;
12455 ResultElements.reserve(RetLen);
12456
12457 for (unsigned I = 0; I < RetLen; I++)
12458 ResultElements.push_back(SourceVec.getVectorElt(Idx * RetLen + I));
12459
12460 return Success(APValue(ResultElements.data(), RetLen), E);
12461 }
12462
12463 case clang::X86::BI__builtin_ia32_cvtmask2b128:
12464 case clang::X86::BI__builtin_ia32_cvtmask2b256:
12465 case clang::X86::BI__builtin_ia32_cvtmask2b512:
12466 case clang::X86::BI__builtin_ia32_cvtmask2w128:
12467 case clang::X86::BI__builtin_ia32_cvtmask2w256:
12468 case clang::X86::BI__builtin_ia32_cvtmask2w512:
12469 case clang::X86::BI__builtin_ia32_cvtmask2d128:
12470 case clang::X86::BI__builtin_ia32_cvtmask2d256:
12471 case clang::X86::BI__builtin_ia32_cvtmask2d512:
12472 case clang::X86::BI__builtin_ia32_cvtmask2q128:
12473 case clang::X86::BI__builtin_ia32_cvtmask2q256:
12474 case clang::X86::BI__builtin_ia32_cvtmask2q512: {
12475 assert(E->getNumArgs() == 1);
12476 APSInt Mask;
12477 if (!EvaluateInteger(E->getArg(0), Mask, Info))
12478 return false;
12479
12480 QualType VecTy = E->getType();
12481 const VectorType *VT = VecTy->castAs<VectorType>();
12482 unsigned VectorLen = VT->getNumElements();
12483 QualType ElemTy = VT->getElementType();
12484 unsigned ElemWidth = Info.Ctx.getTypeSize(ElemTy);
12485
12487 for (unsigned I = 0; I != VectorLen; ++I) {
12488 bool BitSet = Mask[I];
12489 APSInt ElemVal(ElemWidth, /*isUnsigned=*/false);
12490 if (BitSet) {
12491 ElemVal.setAllBits();
12492 }
12493 Elems.push_back(APValue(ElemVal));
12494 }
12495 return Success(APValue(Elems.data(), VectorLen), E);
12496 }
12497
12498 case X86::BI__builtin_ia32_extracti32x4_256_mask:
12499 case X86::BI__builtin_ia32_extractf32x4_256_mask:
12500 case X86::BI__builtin_ia32_extracti32x4_mask:
12501 case X86::BI__builtin_ia32_extractf32x4_mask:
12502 case X86::BI__builtin_ia32_extracti32x8_mask:
12503 case X86::BI__builtin_ia32_extractf32x8_mask:
12504 case X86::BI__builtin_ia32_extracti64x2_256_mask:
12505 case X86::BI__builtin_ia32_extractf64x2_256_mask:
12506 case X86::BI__builtin_ia32_extracti64x2_512_mask:
12507 case X86::BI__builtin_ia32_extractf64x2_512_mask:
12508 case X86::BI__builtin_ia32_extracti64x4_mask:
12509 case X86::BI__builtin_ia32_extractf64x4_mask: {
12510 APValue SourceVec, MergeVec;
12511 APSInt Imm, MaskImm;
12512
12513 if (!EvaluateAsRValue(Info, E->getArg(0), SourceVec) ||
12514 !EvaluateInteger(E->getArg(1), Imm, Info) ||
12515 !EvaluateAsRValue(Info, E->getArg(2), MergeVec) ||
12516 !EvaluateInteger(E->getArg(3), MaskImm, Info))
12517 return false;
12518
12519 const auto *RetVT = E->getType()->castAs<VectorType>();
12520 unsigned RetLen = RetVT->getNumElements();
12521
12522 if (!SourceVec.isVector() || !MergeVec.isVector())
12523 return false;
12524 unsigned SrcLen = SourceVec.getVectorLength();
12525 unsigned Lanes = SrcLen / RetLen;
12526 unsigned Lane = static_cast<unsigned>(Imm.getZExtValue() % Lanes);
12527 unsigned Base = Lane * RetLen;
12528
12529 SmallVector<APValue, 32> ResultElements;
12530 ResultElements.reserve(RetLen);
12531 for (unsigned I = 0; I < RetLen; ++I) {
12532 if (MaskImm[I])
12533 ResultElements.push_back(SourceVec.getVectorElt(Base + I));
12534 else
12535 ResultElements.push_back(MergeVec.getVectorElt(I));
12536 }
12537 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12538 }
12539
12540 case clang::X86::BI__builtin_ia32_pavgb128:
12541 case clang::X86::BI__builtin_ia32_pavgw128:
12542 case clang::X86::BI__builtin_ia32_pavgb256:
12543 case clang::X86::BI__builtin_ia32_pavgw256:
12544 case clang::X86::BI__builtin_ia32_pavgb512:
12545 case clang::X86::BI__builtin_ia32_pavgw512:
12546 return EvaluateBinOpExpr(llvm::APIntOps::avgCeilU);
12547
12548 case clang::X86::BI__builtin_ia32_pmulhrsw128:
12549 case clang::X86::BI__builtin_ia32_pmulhrsw256:
12550 case clang::X86::BI__builtin_ia32_pmulhrsw512:
12551 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
12552 return (llvm::APIntOps::mulsExtended(LHS, RHS).ashr(14) + 1)
12553 .extractBits(16, 1);
12554 });
12555
12556 case clang::X86::BI__builtin_ia32_pmaddubsw128:
12557 case clang::X86::BI__builtin_ia32_pmaddubsw256:
12558 case clang::X86::BI__builtin_ia32_pmaddubsw512:
12559 case clang::X86::BI__builtin_ia32_pmaddwd128:
12560 case clang::X86::BI__builtin_ia32_pmaddwd256:
12561 case clang::X86::BI__builtin_ia32_pmaddwd512: {
12562 APValue SourceLHS, SourceRHS;
12563 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
12564 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
12565 return false;
12566
12567 auto *DestTy = E->getType()->castAs<VectorType>();
12568 QualType DestEltTy = DestTy->getElementType();
12569 unsigned SourceLen = SourceLHS.getVectorLength();
12570 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
12571 SmallVector<APValue, 4> ResultElements;
12572 ResultElements.reserve(SourceLen / 2);
12573
12574 for (unsigned EltNum = 0; EltNum < SourceLen; EltNum += 2) {
12575 const APSInt &LoLHS = SourceLHS.getVectorElt(EltNum).getInt();
12576 const APSInt &HiLHS = SourceLHS.getVectorElt(EltNum + 1).getInt();
12577 const APSInt &LoRHS = SourceRHS.getVectorElt(EltNum).getInt();
12578 const APSInt &HiRHS = SourceRHS.getVectorElt(EltNum + 1).getInt();
12579 unsigned BitWidth = 2 * LoLHS.getBitWidth();
12580
12581 switch (E->getBuiltinCallee()) {
12582 case clang::X86::BI__builtin_ia32_pmaddubsw128:
12583 case clang::X86::BI__builtin_ia32_pmaddubsw256:
12584 case clang::X86::BI__builtin_ia32_pmaddubsw512:
12585 ResultElements.push_back(APValue(
12586 APSInt((LoLHS.zext(BitWidth) * LoRHS.sext(BitWidth))
12587 .sadd_sat((HiLHS.zext(BitWidth) * HiRHS.sext(BitWidth))),
12588 DestUnsigned)));
12589 break;
12590 case clang::X86::BI__builtin_ia32_pmaddwd128:
12591 case clang::X86::BI__builtin_ia32_pmaddwd256:
12592 case clang::X86::BI__builtin_ia32_pmaddwd512:
12593 ResultElements.push_back(
12594 APValue(APSInt((LoLHS.sext(BitWidth) * LoRHS.sext(BitWidth)) +
12595 (HiLHS.sext(BitWidth) * HiRHS.sext(BitWidth)),
12596 DestUnsigned)));
12597 break;
12598 }
12599 }
12600
12601 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12602 }
12603
12604 case clang::X86::BI__builtin_ia32_dbpsadbw128:
12605 case clang::X86::BI__builtin_ia32_dbpsadbw256:
12606 case clang::X86::BI__builtin_ia32_dbpsadbw512: {
12607 APValue SourceA, SourceB, SourceImm;
12608 if (!EvaluateAsRValue(Info, E->getArg(0), SourceA) ||
12609 !EvaluateAsRValue(Info, E->getArg(1), SourceB) ||
12610 !EvaluateAsRValue(Info, E->getArg(2), SourceImm))
12611 return false;
12612
12613 unsigned SourceLen = SourceA.getVectorLength();
12614 constexpr unsigned LaneSize = 16; // 128-bit lane = 16 bytes
12615 unsigned Imm = SourceImm.getInt().getZExtValue();
12616
12617 auto *DestTy = E->getType()->castAs<VectorType>();
12618 QualType DestEltTy = DestTy->getElementType();
12619 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
12620 SmallVector<APValue, 32> ResultElements;
12621 ResultElements.reserve(SourceLen / 2);
12622
12623 // Phase 1: Shuffle SourceB using all four 2-bit fields of imm8.
12624 // Within each 128-bit lane, for group j (0..3), select a 4-byte block
12625 // from SourceB based on bits [2*j+1:2*j] of imm8.
12626 SmallVector<uint8_t, 64> Shuffled(SourceLen);
12627 for (unsigned I = 0; I < SourceLen; I += LaneSize) {
12628 for (unsigned J = 0; J < 4; ++J) {
12629 unsigned Part = (Imm >> (2 * J)) & 3;
12630 for (unsigned K = 0; K < 4; ++K) {
12631 Shuffled[I + 4 * J + K] = static_cast<uint8_t>(
12632 SourceB.getVectorElt(I + 4 * Part + K).getInt().getZExtValue());
12633 }
12634 }
12635 }
12636
12637 // Phase 2: Sliding SAD computation.
12638 // For every group of 4 output u16 values, compute absolute differences
12639 // using overlapping windows into SourceA and the shuffled array.
12640 unsigned Size = SourceLen / 2; // number of output u16 elements
12641 for (unsigned I = 0; I < Size; I += 4) {
12642 unsigned Sad[4] = {0, 0, 0, 0};
12643 for (unsigned J = 0; J < 4; ++J) {
12644 uint8_t A1 = static_cast<uint8_t>(
12645 SourceA.getVectorElt(2 * I + J).getInt().getZExtValue());
12646 uint8_t A2 = static_cast<uint8_t>(
12647 SourceA.getVectorElt(2 * I + J + 4).getInt().getZExtValue());
12648 uint8_t B0 = Shuffled[2 * I + J];
12649 uint8_t B1 = Shuffled[2 * I + J + 1];
12650 uint8_t B2 = Shuffled[2 * I + J + 2];
12651 uint8_t B3 = Shuffled[2 * I + J + 3];
12652 Sad[0] += (A1 > B0) ? (A1 - B0) : (B0 - A1);
12653 Sad[1] += (A1 > B1) ? (A1 - B1) : (B1 - A1);
12654 Sad[2] += (A2 > B2) ? (A2 - B2) : (B2 - A2);
12655 Sad[3] += (A2 > B3) ? (A2 - B3) : (B3 - A2);
12656 }
12657 for (unsigned R = 0; R < 4; ++R)
12658 ResultElements.push_back(
12659 APValue(APSInt(APInt(16, Sad[R]), DestUnsigned)));
12660 }
12661
12662 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12663 }
12664
12665 case clang::X86::BI__builtin_ia32_pmulhuw128:
12666 case clang::X86::BI__builtin_ia32_pmulhuw256:
12667 case clang::X86::BI__builtin_ia32_pmulhuw512:
12668 return EvaluateBinOpExpr(llvm::APIntOps::mulhu);
12669
12670 case clang::X86::BI__builtin_ia32_pmulhw128:
12671 case clang::X86::BI__builtin_ia32_pmulhw256:
12672 case clang::X86::BI__builtin_ia32_pmulhw512:
12673 return EvaluateBinOpExpr(llvm::APIntOps::mulhs);
12674
12675 case clang::X86::BI__builtin_ia32_psllv2di:
12676 case clang::X86::BI__builtin_ia32_psllv4di:
12677 case clang::X86::BI__builtin_ia32_psllv4si:
12678 case clang::X86::BI__builtin_ia32_psllv8di:
12679 case clang::X86::BI__builtin_ia32_psllv8hi:
12680 case clang::X86::BI__builtin_ia32_psllv8si:
12681 case clang::X86::BI__builtin_ia32_psllv16hi:
12682 case clang::X86::BI__builtin_ia32_psllv16si:
12683 case clang::X86::BI__builtin_ia32_psllv32hi:
12684 case clang::X86::BI__builtin_ia32_psllwi128:
12685 case clang::X86::BI__builtin_ia32_pslldi128:
12686 case clang::X86::BI__builtin_ia32_psllqi128:
12687 case clang::X86::BI__builtin_ia32_psllwi256:
12688 case clang::X86::BI__builtin_ia32_pslldi256:
12689 case clang::X86::BI__builtin_ia32_psllqi256:
12690 case clang::X86::BI__builtin_ia32_psllwi512:
12691 case clang::X86::BI__builtin_ia32_pslldi512:
12692 case clang::X86::BI__builtin_ia32_psllqi512:
12693 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
12694 if (RHS.uge(LHS.getBitWidth())) {
12695 return APInt::getZero(LHS.getBitWidth());
12696 }
12697 return LHS.shl(RHS.getZExtValue());
12698 });
12699
12700 case clang::X86::BI__builtin_ia32_psrav4si:
12701 case clang::X86::BI__builtin_ia32_psrav8di:
12702 case clang::X86::BI__builtin_ia32_psrav8hi:
12703 case clang::X86::BI__builtin_ia32_psrav8si:
12704 case clang::X86::BI__builtin_ia32_psrav16hi:
12705 case clang::X86::BI__builtin_ia32_psrav16si:
12706 case clang::X86::BI__builtin_ia32_psrav32hi:
12707 case clang::X86::BI__builtin_ia32_psravq128:
12708 case clang::X86::BI__builtin_ia32_psravq256:
12709 case clang::X86::BI__builtin_ia32_psrawi128:
12710 case clang::X86::BI__builtin_ia32_psradi128:
12711 case clang::X86::BI__builtin_ia32_psraqi128:
12712 case clang::X86::BI__builtin_ia32_psrawi256:
12713 case clang::X86::BI__builtin_ia32_psradi256:
12714 case clang::X86::BI__builtin_ia32_psraqi256:
12715 case clang::X86::BI__builtin_ia32_psrawi512:
12716 case clang::X86::BI__builtin_ia32_psradi512:
12717 case clang::X86::BI__builtin_ia32_psraqi512:
12718 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
12719 if (RHS.uge(LHS.getBitWidth())) {
12720 return LHS.ashr(LHS.getBitWidth() - 1);
12721 }
12722 return LHS.ashr(RHS.getZExtValue());
12723 });
12724
12725 case clang::X86::BI__builtin_ia32_psrlv2di:
12726 case clang::X86::BI__builtin_ia32_psrlv4di:
12727 case clang::X86::BI__builtin_ia32_psrlv4si:
12728 case clang::X86::BI__builtin_ia32_psrlv8di:
12729 case clang::X86::BI__builtin_ia32_psrlv8hi:
12730 case clang::X86::BI__builtin_ia32_psrlv8si:
12731 case clang::X86::BI__builtin_ia32_psrlv16hi:
12732 case clang::X86::BI__builtin_ia32_psrlv16si:
12733 case clang::X86::BI__builtin_ia32_psrlv32hi:
12734 case clang::X86::BI__builtin_ia32_psrlwi128:
12735 case clang::X86::BI__builtin_ia32_psrldi128:
12736 case clang::X86::BI__builtin_ia32_psrlqi128:
12737 case clang::X86::BI__builtin_ia32_psrlwi256:
12738 case clang::X86::BI__builtin_ia32_psrldi256:
12739 case clang::X86::BI__builtin_ia32_psrlqi256:
12740 case clang::X86::BI__builtin_ia32_psrlwi512:
12741 case clang::X86::BI__builtin_ia32_psrldi512:
12742 case clang::X86::BI__builtin_ia32_psrlqi512:
12743 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
12744 if (RHS.uge(LHS.getBitWidth())) {
12745 return APInt::getZero(LHS.getBitWidth());
12746 }
12747 return LHS.lshr(RHS.getZExtValue());
12748 });
12749 case X86::BI__builtin_ia32_packsswb128:
12750 case X86::BI__builtin_ia32_packsswb256:
12751 case X86::BI__builtin_ia32_packsswb512:
12752 case X86::BI__builtin_ia32_packssdw128:
12753 case X86::BI__builtin_ia32_packssdw256:
12754 case X86::BI__builtin_ia32_packssdw512:
12755 return evalPackBuiltin(E, Info, Result, [](const APSInt &Src) {
12756 return APSInt(Src).truncSSat(Src.getBitWidth() / 2);
12757 });
12758 case X86::BI__builtin_ia32_packusdw128:
12759 case X86::BI__builtin_ia32_packusdw256:
12760 case X86::BI__builtin_ia32_packusdw512:
12761 case X86::BI__builtin_ia32_packuswb128:
12762 case X86::BI__builtin_ia32_packuswb256:
12763 case X86::BI__builtin_ia32_packuswb512:
12764 return evalPackBuiltin(E, Info, Result, [](const APSInt &Src) {
12765 return APSInt(Src).truncSSatU(Src.getBitWidth() / 2);
12766 });
12767 case clang::X86::BI__builtin_ia32_selectss_128:
12768 return EvalSelectScalar(4);
12769 case clang::X86::BI__builtin_ia32_selectsd_128:
12770 return EvalSelectScalar(2);
12771 case clang::X86::BI__builtin_ia32_selectsh_128:
12772 case clang::X86::BI__builtin_ia32_selectsbf_128:
12773 return EvalSelectScalar(8);
12774 case clang::X86::BI__builtin_ia32_pmuldq128:
12775 case clang::X86::BI__builtin_ia32_pmuldq256:
12776 case clang::X86::BI__builtin_ia32_pmuldq512:
12777 case clang::X86::BI__builtin_ia32_pmuludq128:
12778 case clang::X86::BI__builtin_ia32_pmuludq256:
12779 case clang::X86::BI__builtin_ia32_pmuludq512: {
12780 APValue SourceLHS, SourceRHS;
12781 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
12782 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
12783 return false;
12784
12785 unsigned SourceLen = SourceLHS.getVectorLength();
12786 SmallVector<APValue, 4> ResultElements;
12787 ResultElements.reserve(SourceLen / 2);
12788
12789 for (unsigned EltNum = 0; EltNum < SourceLen; EltNum += 2) {
12790 APSInt LHS = SourceLHS.getVectorElt(EltNum).getInt();
12791 APSInt RHS = SourceRHS.getVectorElt(EltNum).getInt();
12792
12793 switch (E->getBuiltinCallee()) {
12794 case clang::X86::BI__builtin_ia32_pmuludq128:
12795 case clang::X86::BI__builtin_ia32_pmuludq256:
12796 case clang::X86::BI__builtin_ia32_pmuludq512:
12797 ResultElements.push_back(
12798 APValue(APSInt(llvm::APIntOps::muluExtended(LHS, RHS), true)));
12799 break;
12800 case clang::X86::BI__builtin_ia32_pmuldq128:
12801 case clang::X86::BI__builtin_ia32_pmuldq256:
12802 case clang::X86::BI__builtin_ia32_pmuldq512:
12803 ResultElements.push_back(
12804 APValue(APSInt(llvm::APIntOps::mulsExtended(LHS, RHS), false)));
12805 break;
12806 }
12807 }
12808
12809 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12810 }
12811
12812 case X86::BI__builtin_ia32_vpmadd52luq128:
12813 case X86::BI__builtin_ia32_vpmadd52luq256:
12814 case X86::BI__builtin_ia32_vpmadd52luq512: {
12815 APValue A, B, C;
12816 if (!EvaluateAsRValue(Info, E->getArg(0), A) ||
12817 !EvaluateAsRValue(Info, E->getArg(1), B) ||
12818 !EvaluateAsRValue(Info, E->getArg(2), C))
12819 return false;
12820
12821 unsigned ALen = A.getVectorLength();
12822 SmallVector<APValue, 4> ResultElements;
12823 ResultElements.reserve(ALen);
12824
12825 for (unsigned EltNum = 0; EltNum < ALen; EltNum += 1) {
12826 APInt AElt = A.getVectorElt(EltNum).getInt();
12827 APInt BElt = B.getVectorElt(EltNum).getInt().trunc(52);
12828 APInt CElt = C.getVectorElt(EltNum).getInt().trunc(52);
12829 APSInt ResElt(AElt + (BElt * CElt).zext(64), false);
12830 ResultElements.push_back(APValue(ResElt));
12831 }
12832
12833 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12834 }
12835 case X86::BI__builtin_ia32_vpmadd52huq128:
12836 case X86::BI__builtin_ia32_vpmadd52huq256:
12837 case X86::BI__builtin_ia32_vpmadd52huq512: {
12838 APValue A, B, C;
12839 if (!EvaluateAsRValue(Info, E->getArg(0), A) ||
12840 !EvaluateAsRValue(Info, E->getArg(1), B) ||
12841 !EvaluateAsRValue(Info, E->getArg(2), C))
12842 return false;
12843
12844 unsigned ALen = A.getVectorLength();
12845 SmallVector<APValue, 4> ResultElements;
12846 ResultElements.reserve(ALen);
12847
12848 for (unsigned EltNum = 0; EltNum < ALen; EltNum += 1) {
12849 APInt AElt = A.getVectorElt(EltNum).getInt();
12850 APInt BElt = B.getVectorElt(EltNum).getInt().trunc(52);
12851 APInt CElt = C.getVectorElt(EltNum).getInt().trunc(52);
12852 APSInt ResElt(AElt + llvm::APIntOps::mulhu(BElt, CElt).zext(64), false);
12853 ResultElements.push_back(APValue(ResElt));
12854 }
12855
12856 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12857 }
12858
12859 case clang::X86::BI__builtin_ia32_vprotbi:
12860 case clang::X86::BI__builtin_ia32_vprotdi:
12861 case clang::X86::BI__builtin_ia32_vprotqi:
12862 case clang::X86::BI__builtin_ia32_vprotwi:
12863 case clang::X86::BI__builtin_ia32_prold128:
12864 case clang::X86::BI__builtin_ia32_prold256:
12865 case clang::X86::BI__builtin_ia32_prold512:
12866 case clang::X86::BI__builtin_ia32_prolq128:
12867 case clang::X86::BI__builtin_ia32_prolq256:
12868 case clang::X86::BI__builtin_ia32_prolq512:
12869 return EvaluateBinOpExpr(
12870 [](const APSInt &LHS, const APSInt &RHS) { return LHS.rotl(RHS); });
12871
12872 case clang::X86::BI__builtin_ia32_prord128:
12873 case clang::X86::BI__builtin_ia32_prord256:
12874 case clang::X86::BI__builtin_ia32_prord512:
12875 case clang::X86::BI__builtin_ia32_prorq128:
12876 case clang::X86::BI__builtin_ia32_prorq256:
12877 case clang::X86::BI__builtin_ia32_prorq512:
12878 return EvaluateBinOpExpr(
12879 [](const APSInt &LHS, const APSInt &RHS) { return LHS.rotr(RHS); });
12880
12881 case Builtin::BI__builtin_elementwise_max:
12882 case Builtin::BI__builtin_elementwise_min: {
12883 APValue SourceLHS, SourceRHS;
12884 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
12885 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
12886 return false;
12887
12888 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
12889
12890 if (!DestEltTy->isIntegerType())
12891 return false;
12892
12893 unsigned SourceLen = SourceLHS.getVectorLength();
12894 SmallVector<APValue, 4> ResultElements;
12895 ResultElements.reserve(SourceLen);
12896
12897 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12898 APSInt LHS = SourceLHS.getVectorElt(EltNum).getInt();
12899 APSInt RHS = SourceRHS.getVectorElt(EltNum).getInt();
12900 switch (E->getBuiltinCallee()) {
12901 case Builtin::BI__builtin_elementwise_max:
12902 ResultElements.push_back(
12903 APValue(APSInt(std::max(LHS, RHS),
12904 DestEltTy->isUnsignedIntegerOrEnumerationType())));
12905 break;
12906 case Builtin::BI__builtin_elementwise_min:
12907 ResultElements.push_back(
12908 APValue(APSInt(std::min(LHS, RHS),
12909 DestEltTy->isUnsignedIntegerOrEnumerationType())));
12910 break;
12911 }
12912 }
12913
12914 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12915 }
12916 case X86::BI__builtin_ia32_vpshldd128:
12917 case X86::BI__builtin_ia32_vpshldd256:
12918 case X86::BI__builtin_ia32_vpshldd512:
12919 case X86::BI__builtin_ia32_vpshldq128:
12920 case X86::BI__builtin_ia32_vpshldq256:
12921 case X86::BI__builtin_ia32_vpshldq512:
12922 case X86::BI__builtin_ia32_vpshldw128:
12923 case X86::BI__builtin_ia32_vpshldw256:
12924 case X86::BI__builtin_ia32_vpshldw512: {
12925 APValue SourceHi, SourceLo, SourceAmt;
12926 if (!EvaluateAsRValue(Info, E->getArg(0), SourceHi) ||
12927 !EvaluateAsRValue(Info, E->getArg(1), SourceLo) ||
12928 !EvaluateAsRValue(Info, E->getArg(2), SourceAmt))
12929 return false;
12930
12931 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
12932 unsigned SourceLen = SourceHi.getVectorLength();
12933 SmallVector<APValue, 32> ResultElements;
12934 ResultElements.reserve(SourceLen);
12935
12936 APInt Amt = SourceAmt.getInt();
12937 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12938 APInt Hi = SourceHi.getVectorElt(EltNum).getInt();
12939 APInt Lo = SourceLo.getVectorElt(EltNum).getInt();
12940 APInt R = llvm::APIntOps::fshl(Hi, Lo, Amt);
12941 ResultElements.push_back(
12943 }
12944
12945 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12946 }
12947 case X86::BI__builtin_ia32_vpshrdd128:
12948 case X86::BI__builtin_ia32_vpshrdd256:
12949 case X86::BI__builtin_ia32_vpshrdd512:
12950 case X86::BI__builtin_ia32_vpshrdq128:
12951 case X86::BI__builtin_ia32_vpshrdq256:
12952 case X86::BI__builtin_ia32_vpshrdq512:
12953 case X86::BI__builtin_ia32_vpshrdw128:
12954 case X86::BI__builtin_ia32_vpshrdw256:
12955 case X86::BI__builtin_ia32_vpshrdw512: {
12956 // NOTE: Reversed Hi/Lo operands.
12957 APValue SourceHi, SourceLo, SourceAmt;
12958 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLo) ||
12959 !EvaluateAsRValue(Info, E->getArg(1), SourceHi) ||
12960 !EvaluateAsRValue(Info, E->getArg(2), SourceAmt))
12961 return false;
12962
12963 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
12964 unsigned SourceLen = SourceHi.getVectorLength();
12965 SmallVector<APValue, 32> ResultElements;
12966 ResultElements.reserve(SourceLen);
12967
12968 APInt Amt = SourceAmt.getInt();
12969 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12970 APInt Hi = SourceHi.getVectorElt(EltNum).getInt();
12971 APInt Lo = SourceLo.getVectorElt(EltNum).getInt();
12972 APInt R = llvm::APIntOps::fshr(Hi, Lo, Amt);
12973 ResultElements.push_back(
12975 }
12976
12977 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12978 }
12979 case X86::BI__builtin_ia32_compressdf128_mask:
12980 case X86::BI__builtin_ia32_compressdf256_mask:
12981 case X86::BI__builtin_ia32_compressdf512_mask:
12982 case X86::BI__builtin_ia32_compressdi128_mask:
12983 case X86::BI__builtin_ia32_compressdi256_mask:
12984 case X86::BI__builtin_ia32_compressdi512_mask:
12985 case X86::BI__builtin_ia32_compresshi128_mask:
12986 case X86::BI__builtin_ia32_compresshi256_mask:
12987 case X86::BI__builtin_ia32_compresshi512_mask:
12988 case X86::BI__builtin_ia32_compressqi128_mask:
12989 case X86::BI__builtin_ia32_compressqi256_mask:
12990 case X86::BI__builtin_ia32_compressqi512_mask:
12991 case X86::BI__builtin_ia32_compresssf128_mask:
12992 case X86::BI__builtin_ia32_compresssf256_mask:
12993 case X86::BI__builtin_ia32_compresssf512_mask:
12994 case X86::BI__builtin_ia32_compresssi128_mask:
12995 case X86::BI__builtin_ia32_compresssi256_mask:
12996 case X86::BI__builtin_ia32_compresssi512_mask: {
12997 APValue Source, Passthru;
12998 if (!EvaluateAsRValue(Info, E->getArg(0), Source) ||
12999 !EvaluateAsRValue(Info, E->getArg(1), Passthru))
13000 return false;
13001 APSInt Mask;
13002 if (!EvaluateInteger(E->getArg(2), Mask, Info))
13003 return false;
13004
13005 unsigned NumElts = Source.getVectorLength();
13006 SmallVector<APValue, 64> ResultElements;
13007 ResultElements.reserve(NumElts);
13008
13009 for (unsigned I = 0; I != NumElts; ++I) {
13010 if (Mask[I])
13011 ResultElements.push_back(Source.getVectorElt(I));
13012 }
13013 for (unsigned I = ResultElements.size(); I != NumElts; ++I) {
13014 ResultElements.push_back(Passthru.getVectorElt(I));
13015 }
13016
13017 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13018 }
13019 case X86::BI__builtin_ia32_expanddf128_mask:
13020 case X86::BI__builtin_ia32_expanddf256_mask:
13021 case X86::BI__builtin_ia32_expanddf512_mask:
13022 case X86::BI__builtin_ia32_expanddi128_mask:
13023 case X86::BI__builtin_ia32_expanddi256_mask:
13024 case X86::BI__builtin_ia32_expanddi512_mask:
13025 case X86::BI__builtin_ia32_expandhi128_mask:
13026 case X86::BI__builtin_ia32_expandhi256_mask:
13027 case X86::BI__builtin_ia32_expandhi512_mask:
13028 case X86::BI__builtin_ia32_expandqi128_mask:
13029 case X86::BI__builtin_ia32_expandqi256_mask:
13030 case X86::BI__builtin_ia32_expandqi512_mask:
13031 case X86::BI__builtin_ia32_expandsf128_mask:
13032 case X86::BI__builtin_ia32_expandsf256_mask:
13033 case X86::BI__builtin_ia32_expandsf512_mask:
13034 case X86::BI__builtin_ia32_expandsi128_mask:
13035 case X86::BI__builtin_ia32_expandsi256_mask:
13036 case X86::BI__builtin_ia32_expandsi512_mask: {
13037 APValue Source, Passthru;
13038 if (!EvaluateAsRValue(Info, E->getArg(0), Source) ||
13039 !EvaluateAsRValue(Info, E->getArg(1), Passthru))
13040 return false;
13041 APSInt Mask;
13042 if (!EvaluateInteger(E->getArg(2), Mask, Info))
13043 return false;
13044
13045 unsigned NumElts = Source.getVectorLength();
13046 SmallVector<APValue, 64> ResultElements;
13047 ResultElements.reserve(NumElts);
13048
13049 unsigned SourceIdx = 0;
13050 for (unsigned I = 0; I != NumElts; ++I) {
13051 if (Mask[I])
13052 ResultElements.push_back(Source.getVectorElt(SourceIdx++));
13053 else
13054 ResultElements.push_back(Passthru.getVectorElt(I));
13055 }
13056 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13057 }
13058 case X86::BI__builtin_ia32_vpconflictsi_128:
13059 case X86::BI__builtin_ia32_vpconflictsi_256:
13060 case X86::BI__builtin_ia32_vpconflictsi_512:
13061 case X86::BI__builtin_ia32_vpconflictdi_128:
13062 case X86::BI__builtin_ia32_vpconflictdi_256:
13063 case X86::BI__builtin_ia32_vpconflictdi_512: {
13064 APValue Source;
13065
13066 if (!EvaluateAsRValue(Info, E->getArg(0), Source))
13067 return false;
13068
13069 unsigned SourceLen = Source.getVectorLength();
13070 SmallVector<APValue, 32> ResultElements;
13071 ResultElements.reserve(SourceLen);
13072
13073 const auto *VecT = E->getType()->castAs<VectorType>();
13074 bool DestUnsigned =
13075 VecT->getElementType()->isUnsignedIntegerOrEnumerationType();
13076
13077 for (unsigned I = 0; I != SourceLen; ++I) {
13078 const APValue &EltI = Source.getVectorElt(I);
13079
13080 APInt ConflictMask(EltI.getInt().getBitWidth(), 0);
13081 for (unsigned J = 0; J != I; ++J) {
13082 const APValue &EltJ = Source.getVectorElt(J);
13083 ConflictMask.setBitVal(J, EltI.getInt() == EltJ.getInt());
13084 }
13085 ResultElements.push_back(APValue(APSInt(ConflictMask, DestUnsigned)));
13086 }
13087 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13088 }
13089 case X86::BI__builtin_ia32_blendpd:
13090 case X86::BI__builtin_ia32_blendpd256:
13091 case X86::BI__builtin_ia32_blendps:
13092 case X86::BI__builtin_ia32_blendps256:
13093 case X86::BI__builtin_ia32_pblendw128:
13094 case X86::BI__builtin_ia32_pblendw256:
13095 case X86::BI__builtin_ia32_pblendd128:
13096 case X86::BI__builtin_ia32_pblendd256: {
13097 APValue SourceF, SourceT, SourceC;
13098 if (!EvaluateAsRValue(Info, E->getArg(0), SourceF) ||
13099 !EvaluateAsRValue(Info, E->getArg(1), SourceT) ||
13100 !EvaluateAsRValue(Info, E->getArg(2), SourceC))
13101 return false;
13102
13103 const APInt &C = SourceC.getInt();
13104 unsigned SourceLen = SourceF.getVectorLength();
13105 SmallVector<APValue, 32> ResultElements;
13106 ResultElements.reserve(SourceLen);
13107 for (unsigned EltNum = 0; EltNum != SourceLen; ++EltNum) {
13108 const APValue &F = SourceF.getVectorElt(EltNum);
13109 const APValue &T = SourceT.getVectorElt(EltNum);
13110 ResultElements.push_back(C[EltNum % 8] ? T : F);
13111 }
13112
13113 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13114 }
13115
13116 case X86::BI__builtin_ia32_psignb128:
13117 case X86::BI__builtin_ia32_psignb256:
13118 case X86::BI__builtin_ia32_psignw128:
13119 case X86::BI__builtin_ia32_psignw256:
13120 case X86::BI__builtin_ia32_psignd128:
13121 case X86::BI__builtin_ia32_psignd256:
13122 return EvaluateBinOpExpr([](const APInt &AElem, const APInt &BElem) {
13123 if (BElem.isZero())
13124 return APInt::getZero(AElem.getBitWidth());
13125 if (BElem.isNegative())
13126 return -AElem;
13127 return AElem;
13128 });
13129
13130 case X86::BI__builtin_ia32_blendvpd:
13131 case X86::BI__builtin_ia32_blendvpd256:
13132 case X86::BI__builtin_ia32_blendvps:
13133 case X86::BI__builtin_ia32_blendvps256:
13134 case X86::BI__builtin_ia32_pblendvb128:
13135 case X86::BI__builtin_ia32_pblendvb256: {
13136 // SSE blendv by mask signbit: "Result = C[] < 0 ? T[] : F[]".
13137 APValue SourceF, SourceT, SourceC;
13138 if (!EvaluateAsRValue(Info, E->getArg(0), SourceF) ||
13139 !EvaluateAsRValue(Info, E->getArg(1), SourceT) ||
13140 !EvaluateAsRValue(Info, E->getArg(2), SourceC))
13141 return false;
13142
13143 unsigned SourceLen = SourceF.getVectorLength();
13144 SmallVector<APValue, 32> ResultElements;
13145 ResultElements.reserve(SourceLen);
13146
13147 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
13148 const APValue &F = SourceF.getVectorElt(EltNum);
13149 const APValue &T = SourceT.getVectorElt(EltNum);
13150 const APValue &C = SourceC.getVectorElt(EltNum);
13151 APInt M = C.isInt() ? (APInt)C.getInt() : C.getFloat().bitcastToAPInt();
13152 ResultElements.push_back(M.isNegative() ? T : F);
13153 }
13154
13155 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13156 }
13157 case X86::BI__builtin_ia32_selectb_128:
13158 case X86::BI__builtin_ia32_selectb_256:
13159 case X86::BI__builtin_ia32_selectb_512:
13160 case X86::BI__builtin_ia32_selectw_128:
13161 case X86::BI__builtin_ia32_selectw_256:
13162 case X86::BI__builtin_ia32_selectw_512:
13163 case X86::BI__builtin_ia32_selectd_128:
13164 case X86::BI__builtin_ia32_selectd_256:
13165 case X86::BI__builtin_ia32_selectd_512:
13166 case X86::BI__builtin_ia32_selectq_128:
13167 case X86::BI__builtin_ia32_selectq_256:
13168 case X86::BI__builtin_ia32_selectq_512:
13169 case X86::BI__builtin_ia32_selectph_128:
13170 case X86::BI__builtin_ia32_selectph_256:
13171 case X86::BI__builtin_ia32_selectph_512:
13172 case X86::BI__builtin_ia32_selectpbf_128:
13173 case X86::BI__builtin_ia32_selectpbf_256:
13174 case X86::BI__builtin_ia32_selectpbf_512:
13175 case X86::BI__builtin_ia32_selectps_128:
13176 case X86::BI__builtin_ia32_selectps_256:
13177 case X86::BI__builtin_ia32_selectps_512:
13178 case X86::BI__builtin_ia32_selectpd_128:
13179 case X86::BI__builtin_ia32_selectpd_256:
13180 case X86::BI__builtin_ia32_selectpd_512: {
13181 // AVX512 predicated move: "Result = Mask[] ? LHS[] : RHS[]".
13182 APValue SourceMask, SourceLHS, SourceRHS;
13183 if (!EvaluateAsRValue(Info, E->getArg(0), SourceMask) ||
13184 !EvaluateAsRValue(Info, E->getArg(1), SourceLHS) ||
13185 !EvaluateAsRValue(Info, E->getArg(2), SourceRHS))
13186 return false;
13187
13188 APSInt Mask = SourceMask.getInt();
13189 unsigned SourceLen = SourceLHS.getVectorLength();
13190 SmallVector<APValue, 4> ResultElements;
13191 ResultElements.reserve(SourceLen);
13192
13193 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
13194 const APValue &LHS = SourceLHS.getVectorElt(EltNum);
13195 const APValue &RHS = SourceRHS.getVectorElt(EltNum);
13196 ResultElements.push_back(Mask[EltNum] ? LHS : RHS);
13197 }
13198
13199 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13200 }
13201
13202 case X86::BI__builtin_ia32_cvtsd2ss: {
13203 APValue VecA, VecB;
13204 if (!EvaluateAsRValue(Info, E->getArg(0), VecA) ||
13205 !EvaluateAsRValue(Info, E->getArg(1), VecB))
13206 return false;
13207
13208 SmallVector<APValue, 4> Elements;
13209
13210 APValue ResultVal;
13211 if (!ConvertDoubleToFloatStrict(Info, E, VecB.getVectorElt(0).getFloat(),
13212 ResultVal))
13213 return false;
13214
13215 Elements.push_back(ResultVal);
13216
13217 unsigned NumEltsA = VecA.getVectorLength();
13218 for (unsigned I = 1; I < NumEltsA; ++I) {
13219 Elements.push_back(VecA.getVectorElt(I));
13220 }
13221
13222 return Success(Elements, E);
13223 }
13224 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: {
13225 APValue VecA, VecB, VecSrc, MaskValue;
13226
13227 if (!EvaluateAsRValue(Info, E->getArg(0), VecA) ||
13228 !EvaluateAsRValue(Info, E->getArg(1), VecB) ||
13229 !EvaluateAsRValue(Info, E->getArg(2), VecSrc) ||
13230 !EvaluateAsRValue(Info, E->getArg(3), MaskValue))
13231 return false;
13232
13233 unsigned Mask = MaskValue.getInt().getZExtValue();
13234 SmallVector<APValue, 4> Elements;
13235
13236 if (Mask & 1) {
13237 APValue ResultVal;
13238 if (!ConvertDoubleToFloatStrict(Info, E, VecB.getVectorElt(0).getFloat(),
13239 ResultVal))
13240 return false;
13241 Elements.push_back(ResultVal);
13242 } else {
13243 Elements.push_back(VecSrc.getVectorElt(0));
13244 }
13245
13246 unsigned NumEltsA = VecA.getVectorLength();
13247 for (unsigned I = 1; I < NumEltsA; ++I) {
13248 Elements.push_back(VecA.getVectorElt(I));
13249 }
13250
13251 return Success(Elements, E);
13252 }
13253 case X86::BI__builtin_ia32_cvtpd2ps:
13254 case X86::BI__builtin_ia32_cvtpd2ps256:
13255 case X86::BI__builtin_ia32_cvtpd2ps_mask:
13256 case X86::BI__builtin_ia32_cvtpd2ps512_mask: {
13257
13258 const auto BuiltinID = E->getBuiltinCallee();
13259 bool IsMasked = (BuiltinID == X86::BI__builtin_ia32_cvtpd2ps_mask ||
13260 BuiltinID == X86::BI__builtin_ia32_cvtpd2ps512_mask);
13261
13262 APValue InputValue;
13263 if (!EvaluateAsRValue(Info, E->getArg(0), InputValue))
13264 return false;
13265
13266 APValue MergeValue;
13267 unsigned Mask = 0xFFFFFFFF;
13268 bool NeedsMerge = false;
13269 if (IsMasked) {
13270 APValue MaskValue;
13271 if (!EvaluateAsRValue(Info, E->getArg(2), MaskValue))
13272 return false;
13273 Mask = MaskValue.getInt().getZExtValue();
13274 auto NumEltsResult = E->getType()->getAs<VectorType>()->getNumElements();
13275 for (unsigned I = 0; I < NumEltsResult; ++I) {
13276 if (!((Mask >> I) & 1)) {
13277 NeedsMerge = true;
13278 break;
13279 }
13280 }
13281 if (NeedsMerge) {
13282 if (!EvaluateAsRValue(Info, E->getArg(1), MergeValue))
13283 return false;
13284 }
13285 }
13286
13287 unsigned NumEltsResult =
13288 E->getType()->getAs<VectorType>()->getNumElements();
13289 unsigned NumEltsInput = InputValue.getVectorLength();
13290 SmallVector<APValue, 8> Elements;
13291 for (unsigned I = 0; I < NumEltsResult; ++I) {
13292 if (IsMasked && !((Mask >> I) & 1)) {
13293 if (!NeedsMerge) {
13294 return false;
13295 }
13296 Elements.push_back(MergeValue.getVectorElt(I));
13297 continue;
13298 }
13299
13300 if (I >= NumEltsInput) {
13301 Elements.push_back(APValue(APFloat::getZero(APFloat::IEEEsingle())));
13302 continue;
13303 }
13304
13305 APValue ResultVal;
13307 Info, E, InputValue.getVectorElt(I).getFloat(), ResultVal))
13308 return false;
13309
13310 Elements.push_back(ResultVal);
13311 }
13312 return Success(Elements, E);
13313 }
13314
13315 case X86::BI__builtin_ia32_shufps:
13316 case X86::BI__builtin_ia32_shufps256:
13317 case X86::BI__builtin_ia32_shufps512: {
13318 APValue R;
13319 if (!evalShuffleGeneric(
13320 Info, E, R,
13321 [](unsigned DstIdx,
13322 unsigned ShuffleMask) -> std::pair<unsigned, int> {
13323 constexpr unsigned LaneBits = 128u;
13324 unsigned NumElemPerLane = LaneBits / 32;
13325 unsigned NumSelectableElems = NumElemPerLane / 2;
13326 unsigned BitsPerElem = 2;
13327 unsigned IndexMask = (1u << BitsPerElem) - 1;
13328 unsigned MaskBits = 8;
13329 unsigned Lane = DstIdx / NumElemPerLane;
13330 unsigned ElemInLane = DstIdx % NumElemPerLane;
13331 unsigned LaneOffset = Lane * NumElemPerLane;
13332 unsigned BitIndex = (DstIdx * BitsPerElem) % MaskBits;
13333 unsigned SrcIdx = (ElemInLane < NumSelectableElems) ? 0 : 1;
13334 unsigned Index = (ShuffleMask >> BitIndex) & IndexMask;
13335 return {SrcIdx, static_cast<int>(LaneOffset + Index)};
13336 }))
13337 return false;
13338 return Success(R, E);
13339 }
13340 case X86::BI__builtin_ia32_shufpd:
13341 case X86::BI__builtin_ia32_shufpd256:
13342 case X86::BI__builtin_ia32_shufpd512: {
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 / 64;
13350 unsigned NumSelectableElems = NumElemPerLane / 2;
13351 unsigned BitsPerElem = 1;
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_insertps128: {
13366 APValue R;
13367 if (!evalShuffleGeneric(
13368 Info, E, R,
13369 [](unsigned DstIdx, unsigned Mask) -> std::pair<unsigned, int> {
13370 // Bits [3:0]: zero mask - if bit is set, zero this element
13371 if ((Mask & (1 << DstIdx)) != 0) {
13372 return {0, -1};
13373 }
13374 // Bits [7:6]: select element from source vector Y (0-3)
13375 // Bits [5:4]: select destination position (0-3)
13376 unsigned SrcElem = (Mask >> 6) & 0x3;
13377 unsigned DstElem = (Mask >> 4) & 0x3;
13378 if (DstIdx == DstElem) {
13379 // Insert element from source vector (B) at this position
13380 return {1, static_cast<int>(SrcElem)};
13381 } else {
13382 // Copy from destination vector (A)
13383 return {0, static_cast<int>(DstIdx)};
13384 }
13385 }))
13386 return false;
13387 return Success(R, E);
13388 }
13389 case X86::BI__builtin_ia32_pshufb128:
13390 case X86::BI__builtin_ia32_pshufb256:
13391 case X86::BI__builtin_ia32_pshufb512: {
13392 APValue R;
13393 if (!evalShuffleGeneric(
13394 Info, E, R,
13395 [](unsigned DstIdx,
13396 unsigned ShuffleMask) -> std::pair<unsigned, int> {
13397 uint8_t Ctlb = static_cast<uint8_t>(ShuffleMask);
13398 if (Ctlb & 0x80)
13399 return std::make_pair(0, -1);
13400
13401 unsigned LaneBase = (DstIdx / 16) * 16;
13402 unsigned SrcOffset = Ctlb & 0x0F;
13403 unsigned SrcIdx = LaneBase + SrcOffset;
13404 return std::make_pair(0, static_cast<int>(SrcIdx));
13405 }))
13406 return false;
13407 return Success(R, E);
13408 }
13409
13410 case X86::BI__builtin_ia32_pshuflw:
13411 case X86::BI__builtin_ia32_pshuflw256:
13412 case X86::BI__builtin_ia32_pshuflw512: {
13413 APValue R;
13414 if (!evalShuffleGeneric(
13415 Info, E, R,
13416 [](unsigned DstIdx, unsigned Mask) -> std::pair<unsigned, int> {
13417 constexpr unsigned LaneBits = 128u;
13418 constexpr unsigned ElemBits = 16u;
13419 constexpr unsigned LaneElts = LaneBits / ElemBits;
13420 constexpr unsigned HalfSize = 4;
13421 unsigned LaneBase = (DstIdx / LaneElts) * LaneElts;
13422 unsigned LaneIdx = DstIdx % LaneElts;
13423 if (LaneIdx < HalfSize) {
13424 unsigned Sel = (Mask >> (2 * LaneIdx)) & 0x3;
13425 return std::make_pair(0, static_cast<int>(LaneBase + Sel));
13426 }
13427 return std::make_pair(0, static_cast<int>(DstIdx));
13428 }))
13429 return false;
13430 return Success(R, E);
13431 }
13432
13433 case X86::BI__builtin_ia32_pshufhw:
13434 case X86::BI__builtin_ia32_pshufhw256:
13435 case X86::BI__builtin_ia32_pshufhw512: {
13436 APValue R;
13437 if (!evalShuffleGeneric(
13438 Info, E, R,
13439 [](unsigned DstIdx, unsigned Mask) -> std::pair<unsigned, int> {
13440 constexpr unsigned LaneBits = 128u;
13441 constexpr unsigned ElemBits = 16u;
13442 constexpr unsigned LaneElts = LaneBits / ElemBits;
13443 constexpr unsigned HalfSize = 4;
13444 unsigned LaneBase = (DstIdx / LaneElts) * LaneElts;
13445 unsigned LaneIdx = DstIdx % LaneElts;
13446 if (LaneIdx >= HalfSize) {
13447 unsigned Rel = LaneIdx - HalfSize;
13448 unsigned Sel = (Mask >> (2 * Rel)) & 0x3;
13449 return std::make_pair(
13450 0, static_cast<int>(LaneBase + HalfSize + 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_pshufd:
13459 case X86::BI__builtin_ia32_pshufd256:
13460 case X86::BI__builtin_ia32_pshufd512:
13461 case X86::BI__builtin_ia32_vpermilps:
13462 case X86::BI__builtin_ia32_vpermilps256:
13463 case X86::BI__builtin_ia32_vpermilps512: {
13464 APValue R;
13465 if (!evalShuffleGeneric(
13466 Info, E, R,
13467 [](unsigned DstIdx, unsigned Mask) -> std::pair<unsigned, int> {
13468 constexpr unsigned LaneBits = 128u;
13469 constexpr unsigned ElemBits = 32u;
13470 constexpr unsigned LaneElts = LaneBits / ElemBits;
13471 unsigned LaneBase = (DstIdx / LaneElts) * LaneElts;
13472 unsigned LaneIdx = DstIdx % LaneElts;
13473 unsigned Sel = (Mask >> (2 * LaneIdx)) & 0x3;
13474 return std::make_pair(0, static_cast<int>(LaneBase + Sel));
13475 }))
13476 return false;
13477 return Success(R, E);
13478 }
13479
13480 case X86::BI__builtin_ia32_vpermilvarpd:
13481 case X86::BI__builtin_ia32_vpermilvarpd256:
13482 case X86::BI__builtin_ia32_vpermilvarpd512: {
13483 APValue R;
13484 if (!evalShuffleGeneric(
13485 Info, E, R,
13486 [](unsigned DstIdx, unsigned Mask) -> std::pair<unsigned, int> {
13487 unsigned NumElemPerLane = 2;
13488 unsigned Lane = DstIdx / NumElemPerLane;
13489 unsigned Offset = Mask & 0b10 ? 1 : 0;
13490 return std::make_pair(
13491 0, static_cast<int>(Lane * NumElemPerLane + Offset));
13492 }))
13493 return false;
13494 return Success(R, E);
13495 }
13496
13497 case X86::BI__builtin_ia32_vpermilpd:
13498 case X86::BI__builtin_ia32_vpermilpd256:
13499 case X86::BI__builtin_ia32_vpermilpd512: {
13500 APValue R;
13501 if (!evalShuffleGeneric(Info, E, R, [](unsigned DstIdx, unsigned Control) {
13502 unsigned NumElemPerLane = 2;
13503 unsigned BitsPerElem = 1;
13504 unsigned MaskBits = 8;
13505 unsigned IndexMask = 0x1;
13506 unsigned Lane = DstIdx / NumElemPerLane;
13507 unsigned LaneOffset = Lane * NumElemPerLane;
13508 unsigned BitIndex = (DstIdx * BitsPerElem) % MaskBits;
13509 unsigned Index = (Control >> BitIndex) & IndexMask;
13510 return std::make_pair(0, static_cast<int>(LaneOffset + Index));
13511 }))
13512 return false;
13513 return Success(R, E);
13514 }
13515
13516 case X86::BI__builtin_ia32_permdf256:
13517 case X86::BI__builtin_ia32_permdi256: {
13518 APValue R;
13519 if (!evalShuffleGeneric(Info, E, R, [](unsigned DstIdx, unsigned Control) {
13520 // permute4x64 operates on 4 64-bit elements
13521 // For element i (0-3), extract bits [2*i+1:2*i] from Control
13522 unsigned Index = (Control >> (2 * DstIdx)) & 0x3;
13523 return std::make_pair(0, static_cast<int>(Index));
13524 }))
13525 return false;
13526 return Success(R, E);
13527 }
13528
13529 case X86::BI__builtin_ia32_vpermilvarps:
13530 case X86::BI__builtin_ia32_vpermilvarps256:
13531 case X86::BI__builtin_ia32_vpermilvarps512: {
13532 APValue R;
13533 if (!evalShuffleGeneric(
13534 Info, E, R,
13535 [](unsigned DstIdx, unsigned Mask) -> std::pair<unsigned, int> {
13536 unsigned NumElemPerLane = 4;
13537 unsigned Lane = DstIdx / NumElemPerLane;
13538 unsigned Offset = Mask & 0b11;
13539 return std::make_pair(
13540 0, static_cast<int>(Lane * NumElemPerLane + Offset));
13541 }))
13542 return false;
13543 return Success(R, E);
13544 }
13545
13546 case X86::BI__builtin_ia32_vpmultishiftqb128:
13547 case X86::BI__builtin_ia32_vpmultishiftqb256:
13548 case X86::BI__builtin_ia32_vpmultishiftqb512: {
13549 assert(E->getNumArgs() == 2);
13550
13551 APValue A, B;
13552 if (!Evaluate(A, Info, E->getArg(0)) || !Evaluate(B, Info, E->getArg(1)))
13553 return false;
13554
13555 assert(A.getVectorLength() == B.getVectorLength());
13556 unsigned NumBytesInQWord = 8;
13557 unsigned NumBitsInByte = 8;
13558 unsigned NumBytes = A.getVectorLength();
13559 unsigned NumQWords = NumBytes / NumBytesInQWord;
13561 Result.reserve(NumBytes);
13562
13563 for (unsigned QWordId = 0; QWordId != NumQWords; ++QWordId) {
13564 APInt BQWord(64, 0);
13565 for (unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
13566 unsigned Idx = QWordId * NumBytesInQWord + ByteIdx;
13567 uint64_t Byte = B.getVectorElt(Idx).getInt().getZExtValue();
13568 BQWord.insertBits(APInt(8, Byte & 0xFF), ByteIdx * NumBitsInByte);
13569 }
13570
13571 for (unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
13572 unsigned Idx = QWordId * NumBytesInQWord + ByteIdx;
13573 uint64_t Ctrl = A.getVectorElt(Idx).getInt().getZExtValue() & 0x3F;
13574
13575 APInt Byte(8, 0);
13576 for (unsigned BitIdx = 0; BitIdx != NumBitsInByte; ++BitIdx) {
13577 Byte.setBitVal(BitIdx, BQWord[(Ctrl + BitIdx) & 0x3F]);
13578 }
13579 Result.push_back(APValue(APSInt(Byte, /*isUnsigned*/ true)));
13580 }
13581 }
13582 return Success(APValue(Result.data(), Result.size()), E);
13583 }
13584
13585 case X86::BI__builtin_ia32_phminposuw128: {
13586 APValue Source;
13587 if (!Evaluate(Source, Info, E->getArg(0)))
13588 return false;
13589 unsigned SourceLen = Source.getVectorLength();
13590 const VectorType *VT = E->getArg(0)->getType()->castAs<VectorType>();
13591 QualType ElemQT = VT->getElementType();
13592 unsigned ElemBitWidth = Info.Ctx.getTypeSize(ElemQT);
13593
13594 APInt MinIndex(ElemBitWidth, 0);
13595 APInt MinVal = Source.getVectorElt(0).getInt();
13596 for (unsigned I = 1; I != SourceLen; ++I) {
13597 APInt Val = Source.getVectorElt(I).getInt();
13598 if (MinVal.ugt(Val)) {
13599 MinVal = Val;
13600 MinIndex = I;
13601 }
13602 }
13603
13604 bool ResultUnsigned = E->getCallReturnType(Info.Ctx)
13605 ->castAs<VectorType>()
13606 ->getElementType()
13607 ->isUnsignedIntegerOrEnumerationType();
13608
13610 Result.reserve(SourceLen);
13611 Result.emplace_back(APSInt(MinVal, ResultUnsigned));
13612 Result.emplace_back(APSInt(MinIndex, ResultUnsigned));
13613 for (unsigned I = 0; I != SourceLen - 2; ++I) {
13614 Result.emplace_back(APSInt(APInt(ElemBitWidth, 0), ResultUnsigned));
13615 }
13616 return Success(APValue(Result.data(), Result.size()), E);
13617 }
13618
13619 case X86::BI__builtin_ia32_psraq128:
13620 case X86::BI__builtin_ia32_psraq256:
13621 case X86::BI__builtin_ia32_psraq512:
13622 case X86::BI__builtin_ia32_psrad128:
13623 case X86::BI__builtin_ia32_psrad256:
13624 case X86::BI__builtin_ia32_psrad512:
13625 case X86::BI__builtin_ia32_psraw128:
13626 case X86::BI__builtin_ia32_psraw256:
13627 case X86::BI__builtin_ia32_psraw512: {
13628 APValue R;
13629 if (!evalShiftWithCount(
13630 Info, E, R,
13631 [](const APInt &Elt, uint64_t Count) { return Elt.ashr(Count); },
13632 [](const APInt &Elt, unsigned Width) {
13633 return Elt.ashr(Width - 1);
13634 }))
13635 return false;
13636 return Success(R, E);
13637 }
13638
13639 case X86::BI__builtin_ia32_psllq128:
13640 case X86::BI__builtin_ia32_psllq256:
13641 case X86::BI__builtin_ia32_psllq512:
13642 case X86::BI__builtin_ia32_pslld128:
13643 case X86::BI__builtin_ia32_pslld256:
13644 case X86::BI__builtin_ia32_pslld512:
13645 case X86::BI__builtin_ia32_psllw128:
13646 case X86::BI__builtin_ia32_psllw256:
13647 case X86::BI__builtin_ia32_psllw512: {
13648 APValue R;
13649 if (!evalShiftWithCount(
13650 Info, E, R,
13651 [](const APInt &Elt, uint64_t Count) { return Elt.shl(Count); },
13652 [](const APInt &Elt, unsigned Width) {
13653 return APInt::getZero(Width);
13654 }))
13655 return false;
13656 return Success(R, E);
13657 }
13658
13659 case X86::BI__builtin_ia32_psrlq128:
13660 case X86::BI__builtin_ia32_psrlq256:
13661 case X86::BI__builtin_ia32_psrlq512:
13662 case X86::BI__builtin_ia32_psrld128:
13663 case X86::BI__builtin_ia32_psrld256:
13664 case X86::BI__builtin_ia32_psrld512:
13665 case X86::BI__builtin_ia32_psrlw128:
13666 case X86::BI__builtin_ia32_psrlw256:
13667 case X86::BI__builtin_ia32_psrlw512: {
13668 APValue R;
13669 if (!evalShiftWithCount(
13670 Info, E, R,
13671 [](const APInt &Elt, uint64_t Count) { return Elt.lshr(Count); },
13672 [](const APInt &Elt, unsigned Width) {
13673 return APInt::getZero(Width);
13674 }))
13675 return false;
13676 return Success(R, E);
13677 }
13678
13679 case X86::BI__builtin_ia32_pternlogd128_mask:
13680 case X86::BI__builtin_ia32_pternlogd256_mask:
13681 case X86::BI__builtin_ia32_pternlogd512_mask:
13682 case X86::BI__builtin_ia32_pternlogq128_mask:
13683 case X86::BI__builtin_ia32_pternlogq256_mask:
13684 case X86::BI__builtin_ia32_pternlogq512_mask: {
13685 APValue AValue, BValue, CValue, ImmValue, UValue;
13686 if (!EvaluateAsRValue(Info, E->getArg(0), AValue) ||
13687 !EvaluateAsRValue(Info, E->getArg(1), BValue) ||
13688 !EvaluateAsRValue(Info, E->getArg(2), CValue) ||
13689 !EvaluateAsRValue(Info, E->getArg(3), ImmValue) ||
13690 !EvaluateAsRValue(Info, E->getArg(4), UValue))
13691 return false;
13692
13693 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
13694 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
13695 APInt Imm = ImmValue.getInt();
13696 APInt U = UValue.getInt();
13697 unsigned ResultLen = AValue.getVectorLength();
13698 SmallVector<APValue, 16> ResultElements;
13699 ResultElements.reserve(ResultLen);
13700
13701 for (unsigned EltNum = 0; EltNum < ResultLen; ++EltNum) {
13702 APInt ALane = AValue.getVectorElt(EltNum).getInt();
13703 APInt BLane = BValue.getVectorElt(EltNum).getInt();
13704 APInt CLane = CValue.getVectorElt(EltNum).getInt();
13705
13706 if (U[EltNum]) {
13707 unsigned BitWidth = ALane.getBitWidth();
13708 APInt ResLane(BitWidth, 0);
13709
13710 for (unsigned Bit = 0; Bit < BitWidth; ++Bit) {
13711 unsigned ABit = ALane[Bit];
13712 unsigned BBit = BLane[Bit];
13713 unsigned CBit = CLane[Bit];
13714
13715 unsigned Idx = (ABit << 2) | (BBit << 1) | CBit;
13716 ResLane.setBitVal(Bit, Imm[Idx]);
13717 }
13718 ResultElements.push_back(APValue(APSInt(ResLane, DestUnsigned)));
13719 } else {
13720 ResultElements.push_back(APValue(APSInt(ALane, DestUnsigned)));
13721 }
13722 }
13723 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13724 }
13725 case X86::BI__builtin_ia32_pternlogd128_maskz:
13726 case X86::BI__builtin_ia32_pternlogd256_maskz:
13727 case X86::BI__builtin_ia32_pternlogd512_maskz:
13728 case X86::BI__builtin_ia32_pternlogq128_maskz:
13729 case X86::BI__builtin_ia32_pternlogq256_maskz:
13730 case X86::BI__builtin_ia32_pternlogq512_maskz: {
13731 APValue AValue, BValue, CValue, ImmValue, UValue;
13732 if (!EvaluateAsRValue(Info, E->getArg(0), AValue) ||
13733 !EvaluateAsRValue(Info, E->getArg(1), BValue) ||
13734 !EvaluateAsRValue(Info, E->getArg(2), CValue) ||
13735 !EvaluateAsRValue(Info, E->getArg(3), ImmValue) ||
13736 !EvaluateAsRValue(Info, E->getArg(4), UValue))
13737 return false;
13738
13739 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
13740 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
13741 APInt Imm = ImmValue.getInt();
13742 APInt U = UValue.getInt();
13743 unsigned ResultLen = AValue.getVectorLength();
13744 SmallVector<APValue, 16> ResultElements;
13745 ResultElements.reserve(ResultLen);
13746
13747 for (unsigned EltNum = 0; EltNum < ResultLen; ++EltNum) {
13748 APInt ALane = AValue.getVectorElt(EltNum).getInt();
13749 APInt BLane = BValue.getVectorElt(EltNum).getInt();
13750 APInt CLane = CValue.getVectorElt(EltNum).getInt();
13751
13752 unsigned BitWidth = ALane.getBitWidth();
13753 APInt ResLane(BitWidth, 0);
13754
13755 if (U[EltNum]) {
13756 for (unsigned Bit = 0; Bit < BitWidth; ++Bit) {
13757 unsigned ABit = ALane[Bit];
13758 unsigned BBit = BLane[Bit];
13759 unsigned CBit = CLane[Bit];
13760
13761 unsigned Idx = (ABit << 2) | (BBit << 1) | CBit;
13762 ResLane.setBitVal(Bit, Imm[Idx]);
13763 }
13764 }
13765 ResultElements.push_back(APValue(APSInt(ResLane, DestUnsigned)));
13766 }
13767 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13768 }
13769
13770 case Builtin::BI__builtin_elementwise_clzg:
13771 case Builtin::BI__builtin_elementwise_ctzg: {
13772 APValue SourceLHS;
13773 std::optional<APValue> Fallback;
13774 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS))
13775 return false;
13776 if (E->getNumArgs() > 1) {
13777 APValue FallbackTmp;
13778 if (!EvaluateAsRValue(Info, E->getArg(1), FallbackTmp))
13779 return false;
13780 Fallback = FallbackTmp;
13781 }
13782
13783 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
13784 unsigned SourceLen = SourceLHS.getVectorLength();
13785 SmallVector<APValue, 4> ResultElements;
13786 ResultElements.reserve(SourceLen);
13787
13788 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
13789 APSInt LHS = SourceLHS.getVectorElt(EltNum).getInt();
13790 if (!LHS) {
13791 // Without a fallback, a zero element is undefined
13792 if (!Fallback) {
13793 Info.FFDiag(E, diag::note_constexpr_countzeroes_zero)
13794 << /*IsTrailing=*/(E->getBuiltinCallee() ==
13795 Builtin::BI__builtin_elementwise_ctzg);
13796 return false;
13797 }
13798 ResultElements.push_back(Fallback->getVectorElt(EltNum));
13799 continue;
13800 }
13801 switch (E->getBuiltinCallee()) {
13802 case Builtin::BI__builtin_elementwise_clzg:
13803 ResultElements.push_back(APValue(
13804 APSInt(APInt(Info.Ctx.getIntWidth(DestEltTy), LHS.countl_zero()),
13805 DestEltTy->isUnsignedIntegerOrEnumerationType())));
13806 break;
13807 case Builtin::BI__builtin_elementwise_ctzg:
13808 ResultElements.push_back(APValue(
13809 APSInt(APInt(Info.Ctx.getIntWidth(DestEltTy), LHS.countr_zero()),
13810 DestEltTy->isUnsignedIntegerOrEnumerationType())));
13811 break;
13812 }
13813 }
13814
13815 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13816 }
13817
13818 case Builtin::BI__builtin_elementwise_fma: {
13819 APValue SourceX, SourceY, SourceZ;
13820 if (!EvaluateAsRValue(Info, E->getArg(0), SourceX) ||
13821 !EvaluateAsRValue(Info, E->getArg(1), SourceY) ||
13822 !EvaluateAsRValue(Info, E->getArg(2), SourceZ))
13823 return false;
13824
13825 unsigned SourceLen = SourceX.getVectorLength();
13826 SmallVector<APValue> ResultElements;
13827 ResultElements.reserve(SourceLen);
13828 llvm::RoundingMode RM = getActiveRoundingMode(getEvalInfo(), E);
13829 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
13830 const APFloat &X = SourceX.getVectorElt(EltNum).getFloat();
13831 const APFloat &Y = SourceY.getVectorElt(EltNum).getFloat();
13832 const APFloat &Z = SourceZ.getVectorElt(EltNum).getFloat();
13833 APFloat Result(X);
13834 (void)Result.fusedMultiplyAdd(Y, Z, RM);
13835 ResultElements.push_back(APValue(Result));
13836 }
13837 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13838 }
13839
13840 case clang::X86::BI__builtin_ia32_phaddw128:
13841 case clang::X86::BI__builtin_ia32_phaddw256:
13842 case clang::X86::BI__builtin_ia32_phaddd128:
13843 case clang::X86::BI__builtin_ia32_phaddd256:
13844 case clang::X86::BI__builtin_ia32_phaddsw128:
13845 case clang::X86::BI__builtin_ia32_phaddsw256:
13846
13847 case clang::X86::BI__builtin_ia32_phsubw128:
13848 case clang::X86::BI__builtin_ia32_phsubw256:
13849 case clang::X86::BI__builtin_ia32_phsubd128:
13850 case clang::X86::BI__builtin_ia32_phsubd256:
13851 case clang::X86::BI__builtin_ia32_phsubsw128:
13852 case clang::X86::BI__builtin_ia32_phsubsw256: {
13853 APValue SourceLHS, SourceRHS;
13854 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
13855 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
13856 return false;
13857 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
13858 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
13859
13860 unsigned NumElts = SourceLHS.getVectorLength();
13861 unsigned EltBits = Info.Ctx.getIntWidth(DestEltTy);
13862 unsigned EltsPerLane = 128 / EltBits;
13863 SmallVector<APValue, 4> ResultElements;
13864 ResultElements.reserve(NumElts);
13865
13866 for (unsigned LaneStart = 0; LaneStart != NumElts;
13867 LaneStart += EltsPerLane) {
13868 for (unsigned I = 0; I != EltsPerLane; I += 2) {
13869 APSInt LHSA = SourceLHS.getVectorElt(LaneStart + I).getInt();
13870 APSInt LHSB = SourceLHS.getVectorElt(LaneStart + I + 1).getInt();
13871 switch (E->getBuiltinCallee()) {
13872 case clang::X86::BI__builtin_ia32_phaddw128:
13873 case clang::X86::BI__builtin_ia32_phaddw256:
13874 case clang::X86::BI__builtin_ia32_phaddd128:
13875 case clang::X86::BI__builtin_ia32_phaddd256: {
13876 APSInt Res(LHSA + LHSB, DestUnsigned);
13877 ResultElements.push_back(APValue(Res));
13878 break;
13879 }
13880 case clang::X86::BI__builtin_ia32_phaddsw128:
13881 case clang::X86::BI__builtin_ia32_phaddsw256: {
13882 APSInt Res(LHSA.sadd_sat(LHSB));
13883 ResultElements.push_back(APValue(Res));
13884 break;
13885 }
13886 case clang::X86::BI__builtin_ia32_phsubw128:
13887 case clang::X86::BI__builtin_ia32_phsubw256:
13888 case clang::X86::BI__builtin_ia32_phsubd128:
13889 case clang::X86::BI__builtin_ia32_phsubd256: {
13890 APSInt Res(LHSA - LHSB, DestUnsigned);
13891 ResultElements.push_back(APValue(Res));
13892 break;
13893 }
13894 case clang::X86::BI__builtin_ia32_phsubsw128:
13895 case clang::X86::BI__builtin_ia32_phsubsw256: {
13896 APSInt Res(LHSA.ssub_sat(LHSB));
13897 ResultElements.push_back(APValue(Res));
13898 break;
13899 }
13900 }
13901 }
13902 for (unsigned I = 0; I != EltsPerLane; I += 2) {
13903 APSInt RHSA = SourceRHS.getVectorElt(LaneStart + I).getInt();
13904 APSInt RHSB = SourceRHS.getVectorElt(LaneStart + I + 1).getInt();
13905 switch (E->getBuiltinCallee()) {
13906 case clang::X86::BI__builtin_ia32_phaddw128:
13907 case clang::X86::BI__builtin_ia32_phaddw256:
13908 case clang::X86::BI__builtin_ia32_phaddd128:
13909 case clang::X86::BI__builtin_ia32_phaddd256: {
13910 APSInt Res(RHSA + RHSB, DestUnsigned);
13911 ResultElements.push_back(APValue(Res));
13912 break;
13913 }
13914 case clang::X86::BI__builtin_ia32_phaddsw128:
13915 case clang::X86::BI__builtin_ia32_phaddsw256: {
13916 APSInt Res(RHSA.sadd_sat(RHSB));
13917 ResultElements.push_back(APValue(Res));
13918 break;
13919 }
13920 case clang::X86::BI__builtin_ia32_phsubw128:
13921 case clang::X86::BI__builtin_ia32_phsubw256:
13922 case clang::X86::BI__builtin_ia32_phsubd128:
13923 case clang::X86::BI__builtin_ia32_phsubd256: {
13924 APSInt Res(RHSA - RHSB, DestUnsigned);
13925 ResultElements.push_back(APValue(Res));
13926 break;
13927 }
13928 case clang::X86::BI__builtin_ia32_phsubsw128:
13929 case clang::X86::BI__builtin_ia32_phsubsw256: {
13930 APSInt Res(RHSA.ssub_sat(RHSB));
13931 ResultElements.push_back(APValue(Res));
13932 break;
13933 }
13934 }
13935 }
13936 }
13937 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13938 }
13939 case clang::X86::BI__builtin_ia32_haddpd:
13940 case clang::X86::BI__builtin_ia32_haddps:
13941 case clang::X86::BI__builtin_ia32_haddps256:
13942 case clang::X86::BI__builtin_ia32_haddpd256:
13943 case clang::X86::BI__builtin_ia32_hsubpd:
13944 case clang::X86::BI__builtin_ia32_hsubps:
13945 case clang::X86::BI__builtin_ia32_hsubps256:
13946 case clang::X86::BI__builtin_ia32_hsubpd256: {
13947 APValue SourceLHS, SourceRHS;
13948 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
13949 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
13950 return false;
13951 unsigned NumElts = SourceLHS.getVectorLength();
13952 SmallVector<APValue, 4> ResultElements;
13953 ResultElements.reserve(NumElts);
13954 llvm::RoundingMode RM = getActiveRoundingMode(getEvalInfo(), E);
13955 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
13956 unsigned EltBits = Info.Ctx.getTypeSize(DestEltTy);
13957 unsigned NumLanes = NumElts * EltBits / 128;
13958 unsigned NumElemsPerLane = NumElts / NumLanes;
13959 unsigned HalfElemsPerLane = NumElemsPerLane / 2;
13960
13961 for (unsigned L = 0; L != NumElts; L += NumElemsPerLane) {
13962 for (unsigned I = 0; I != HalfElemsPerLane; ++I) {
13963 APFloat LHSA = SourceLHS.getVectorElt(L + (2 * I) + 0).getFloat();
13964 APFloat LHSB = SourceLHS.getVectorElt(L + (2 * I) + 1).getFloat();
13965 switch (E->getBuiltinCallee()) {
13966 case clang::X86::BI__builtin_ia32_haddpd:
13967 case clang::X86::BI__builtin_ia32_haddps:
13968 case clang::X86::BI__builtin_ia32_haddps256:
13969 case clang::X86::BI__builtin_ia32_haddpd256:
13970 LHSA.add(LHSB, RM);
13971 break;
13972 case clang::X86::BI__builtin_ia32_hsubpd:
13973 case clang::X86::BI__builtin_ia32_hsubps:
13974 case clang::X86::BI__builtin_ia32_hsubps256:
13975 case clang::X86::BI__builtin_ia32_hsubpd256:
13976 LHSA.subtract(LHSB, RM);
13977 break;
13978 }
13979 ResultElements.push_back(APValue(LHSA));
13980 }
13981 for (unsigned I = 0; I != HalfElemsPerLane; ++I) {
13982 APFloat RHSA = SourceRHS.getVectorElt(L + (2 * I) + 0).getFloat();
13983 APFloat RHSB = SourceRHS.getVectorElt(L + (2 * I) + 1).getFloat();
13984 switch (E->getBuiltinCallee()) {
13985 case clang::X86::BI__builtin_ia32_haddpd:
13986 case clang::X86::BI__builtin_ia32_haddps:
13987 case clang::X86::BI__builtin_ia32_haddps256:
13988 case clang::X86::BI__builtin_ia32_haddpd256:
13989 RHSA.add(RHSB, RM);
13990 break;
13991 case clang::X86::BI__builtin_ia32_hsubpd:
13992 case clang::X86::BI__builtin_ia32_hsubps:
13993 case clang::X86::BI__builtin_ia32_hsubps256:
13994 case clang::X86::BI__builtin_ia32_hsubpd256:
13995 RHSA.subtract(RHSB, RM);
13996 break;
13997 }
13998 ResultElements.push_back(APValue(RHSA));
13999 }
14000 }
14001 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
14002 }
14003 case clang::X86::BI__builtin_ia32_addsubpd:
14004 case clang::X86::BI__builtin_ia32_addsubps:
14005 case clang::X86::BI__builtin_ia32_addsubpd256:
14006 case clang::X86::BI__builtin_ia32_addsubps256: {
14007 // Addsub: alternates between subtraction and addition
14008 // Result[i] = (i % 2 == 0) ? (a[i] - b[i]) : (a[i] + b[i])
14009 APValue SourceLHS, SourceRHS;
14010 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
14011 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
14012 return false;
14013 unsigned NumElems = SourceLHS.getVectorLength();
14014 SmallVector<APValue, 8> ResultElements;
14015 ResultElements.reserve(NumElems);
14016 llvm::RoundingMode RM = getActiveRoundingMode(getEvalInfo(), E);
14017
14018 for (unsigned I = 0; I != NumElems; ++I) {
14019 APFloat LHS = SourceLHS.getVectorElt(I).getFloat();
14020 APFloat RHS = SourceRHS.getVectorElt(I).getFloat();
14021 if (I % 2 == 0) {
14022 // Even indices: subtract
14023 LHS.subtract(RHS, RM);
14024 } else {
14025 // Odd indices: add
14026 LHS.add(RHS, RM);
14027 }
14028 ResultElements.push_back(APValue(LHS));
14029 }
14030 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
14031 }
14032 case clang::X86::BI__builtin_ia32_pclmulqdq128:
14033 case clang::X86::BI__builtin_ia32_pclmulqdq256:
14034 case clang::X86::BI__builtin_ia32_pclmulqdq512: {
14035 // PCLMULQDQ: carry-less multiplication of selected 64-bit halves
14036 // imm8 bit 0: selects lower (0) or upper (1) 64 bits of first operand
14037 // imm8 bit 4: selects lower (0) or upper (1) 64 bits of second operand
14038 APValue SourceLHS, SourceRHS;
14039 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
14040 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
14041 return false;
14042
14043 APSInt Imm8;
14044 if (!EvaluateInteger(E->getArg(2), Imm8, Info))
14045 return false;
14046
14047 // Extract bits 0 and 4 from imm8
14048 bool SelectUpperA = (Imm8 & 0x01) != 0;
14049 bool SelectUpperB = (Imm8 & 0x10) != 0;
14050
14051 unsigned NumElems = SourceLHS.getVectorLength();
14052 SmallVector<APValue, 8> ResultElements;
14053 ResultElements.reserve(NumElems);
14054 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
14055 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
14056
14057 // Process each 128-bit lane
14058 for (unsigned Lane = 0; Lane < NumElems; Lane += 2) {
14059 // Get the two 64-bit halves of the first operand
14060 APSInt A0 = SourceLHS.getVectorElt(Lane + 0).getInt();
14061 APSInt A1 = SourceLHS.getVectorElt(Lane + 1).getInt();
14062 // Get the two 64-bit halves of the second operand
14063 APSInt B0 = SourceRHS.getVectorElt(Lane + 0).getInt();
14064 APSInt B1 = SourceRHS.getVectorElt(Lane + 1).getInt();
14065
14066 // Select the appropriate 64-bit values based on imm8
14067 APInt A = SelectUpperA ? A1 : A0;
14068 APInt B = SelectUpperB ? B1 : B0;
14069
14070 // Extend both operands to 128 bits for carry-less multiplication
14071 APInt A128 = A.zext(128);
14072 APInt B128 = B.zext(128);
14073
14074 // Use APIntOps::clmul for carry-less multiplication
14075 APInt Result = llvm::APIntOps::clmul(A128, B128);
14076
14077 // Split the 128-bit result into two 64-bit halves
14078 APSInt ResultLow(Result.extractBits(64, 0), DestUnsigned);
14079 APSInt ResultHigh(Result.extractBits(64, 64), DestUnsigned);
14080
14081 ResultElements.push_back(APValue(ResultLow));
14082 ResultElements.push_back(APValue(ResultHigh));
14083 }
14084
14085 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
14086 }
14087 case Builtin::BI__builtin_elementwise_fshl:
14088 case Builtin::BI__builtin_elementwise_fshr: {
14089 APValue SourceHi, SourceLo, SourceShift;
14090 if (!EvaluateAsRValue(Info, E->getArg(0), SourceHi) ||
14091 !EvaluateAsRValue(Info, E->getArg(1), SourceLo) ||
14092 !EvaluateAsRValue(Info, E->getArg(2), SourceShift))
14093 return false;
14094
14095 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
14096 if (!DestEltTy->isIntegerType())
14097 return false;
14098
14099 unsigned SourceLen = SourceHi.getVectorLength();
14100 SmallVector<APValue> ResultElements;
14101 ResultElements.reserve(SourceLen);
14102 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
14103 const APSInt &Hi = SourceHi.getVectorElt(EltNum).getInt();
14104 const APSInt &Lo = SourceLo.getVectorElt(EltNum).getInt();
14105 const APSInt &Shift = SourceShift.getVectorElt(EltNum).getInt();
14106 switch (E->getBuiltinCallee()) {
14107 case Builtin::BI__builtin_elementwise_fshl:
14108 ResultElements.push_back(APValue(
14109 APSInt(llvm::APIntOps::fshl(Hi, Lo, Shift), Hi.isUnsigned())));
14110 break;
14111 case Builtin::BI__builtin_elementwise_fshr:
14112 ResultElements.push_back(APValue(
14113 APSInt(llvm::APIntOps::fshr(Hi, Lo, Shift), Hi.isUnsigned())));
14114 break;
14115 }
14116 }
14117
14118 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
14119 }
14120
14121 case X86::BI__builtin_ia32_shuf_f32x4_256:
14122 case X86::BI__builtin_ia32_shuf_i32x4_256:
14123 case X86::BI__builtin_ia32_shuf_f64x2_256:
14124 case X86::BI__builtin_ia32_shuf_i64x2_256:
14125 case X86::BI__builtin_ia32_shuf_f32x4:
14126 case X86::BI__builtin_ia32_shuf_i32x4:
14127 case X86::BI__builtin_ia32_shuf_f64x2:
14128 case X86::BI__builtin_ia32_shuf_i64x2: {
14129 APValue SourceA, SourceB;
14130 if (!EvaluateAsRValue(Info, E->getArg(0), SourceA) ||
14131 !EvaluateAsRValue(Info, E->getArg(1), SourceB))
14132 return false;
14133
14134 APSInt Imm;
14135 if (!EvaluateInteger(E->getArg(2), Imm, Info))
14136 return false;
14137
14138 // Destination and sources A, B all have the same type.
14139 unsigned NumElems = SourceA.getVectorLength();
14140 const VectorType *VT = E->getArg(0)->getType()->castAs<VectorType>();
14141 QualType ElemQT = VT->getElementType();
14142 unsigned ElemBits = Info.Ctx.getTypeSize(ElemQT);
14143 unsigned LaneBits = 128u;
14144 unsigned NumLanes = (NumElems * ElemBits) / LaneBits;
14145 unsigned NumElemsPerLane = LaneBits / ElemBits;
14146
14147 unsigned DstLen = SourceA.getVectorLength();
14148 SmallVector<APValue, 16> ResultElements;
14149 ResultElements.reserve(DstLen);
14150
14151 APValue R;
14152 if (!evalShuffleGeneric(
14153 Info, E, R,
14154 [NumLanes, NumElemsPerLane](unsigned DstIdx, unsigned ShuffleMask)
14155 -> std::pair<unsigned, int> {
14156 // DstIdx determines source. ShuffleMask selects lane in source.
14157 unsigned BitsPerElem = NumLanes / 2;
14158 unsigned IndexMask = (1u << BitsPerElem) - 1;
14159 unsigned Lane = DstIdx / NumElemsPerLane;
14160 unsigned SrcIdx = (Lane < NumLanes / 2) ? 0 : 1;
14161 unsigned BitIdx = BitsPerElem * Lane;
14162 unsigned SrcLaneIdx = (ShuffleMask >> BitIdx) & IndexMask;
14163 unsigned ElemInLane = DstIdx % NumElemsPerLane;
14164 unsigned IdxToPick = SrcLaneIdx * NumElemsPerLane + ElemInLane;
14165 return {SrcIdx, IdxToPick};
14166 }))
14167 return false;
14168 return Success(R, E);
14169 }
14170
14171 case X86::BI__builtin_ia32_vgf2p8affineinvqb_v16qi:
14172 case X86::BI__builtin_ia32_vgf2p8affineinvqb_v32qi:
14173 case X86::BI__builtin_ia32_vgf2p8affineinvqb_v64qi:
14174 case X86::BI__builtin_ia32_vgf2p8affineqb_v16qi:
14175 case X86::BI__builtin_ia32_vgf2p8affineqb_v32qi:
14176 case X86::BI__builtin_ia32_vgf2p8affineqb_v64qi: {
14177
14178 APValue X, A;
14179 APSInt Imm;
14180 if (!EvaluateAsRValue(Info, E->getArg(0), X) ||
14181 !EvaluateAsRValue(Info, E->getArg(1), A) ||
14182 !EvaluateInteger(E->getArg(2), Imm, Info))
14183 return false;
14184
14185 assert(X.isVector() && A.isVector());
14186 assert(X.getVectorLength() == A.getVectorLength());
14187
14188 bool IsInverse = false;
14189 switch (E->getBuiltinCallee()) {
14190 case X86::BI__builtin_ia32_vgf2p8affineinvqb_v16qi:
14191 case X86::BI__builtin_ia32_vgf2p8affineinvqb_v32qi:
14192 case X86::BI__builtin_ia32_vgf2p8affineinvqb_v64qi: {
14193 IsInverse = true;
14194 }
14195 }
14196
14197 unsigned NumBitsInByte = 8;
14198 unsigned NumBytesInQWord = 8;
14199 unsigned NumBitsInQWord = 64;
14200 unsigned NumBytes = A.getVectorLength();
14201 unsigned NumQWords = NumBytes / NumBytesInQWord;
14203 Result.reserve(NumBytes);
14204
14205 // computing A*X + Imm
14206 for (unsigned QWordIdx = 0; QWordIdx != NumQWords; ++QWordIdx) {
14207 // Extract the QWords from X, A
14208 APInt XQWord(NumBitsInQWord, 0);
14209 APInt AQWord(NumBitsInQWord, 0);
14210 for (unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
14211 unsigned Idx = QWordIdx * NumBytesInQWord + ByteIdx;
14212 APInt XByte = X.getVectorElt(Idx).getInt();
14213 APInt AByte = A.getVectorElt(Idx).getInt();
14214 XQWord.insertBits(XByte, ByteIdx * NumBitsInByte);
14215 AQWord.insertBits(AByte, ByteIdx * NumBitsInByte);
14216 }
14217
14218 for (unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
14219 uint8_t XByte =
14220 XQWord.lshr(ByteIdx * NumBitsInByte).getLoBits(8).getZExtValue();
14221 Result.push_back(APValue(APSInt(
14222 APInt(8, GFNIAffine(XByte, AQWord, Imm, IsInverse)), false)));
14223 }
14224 }
14225
14226 return Success(APValue(Result.data(), Result.size()), E);
14227 }
14228
14229 case X86::BI__builtin_ia32_vgf2p8mulb_v16qi:
14230 case X86::BI__builtin_ia32_vgf2p8mulb_v32qi:
14231 case X86::BI__builtin_ia32_vgf2p8mulb_v64qi: {
14232 APValue A, B;
14233 if (!EvaluateAsRValue(Info, E->getArg(0), A) ||
14234 !EvaluateAsRValue(Info, E->getArg(1), B))
14235 return false;
14236
14237 assert(A.isVector() && B.isVector());
14238 assert(A.getVectorLength() == B.getVectorLength());
14239
14240 unsigned NumBytes = A.getVectorLength();
14242 Result.reserve(NumBytes);
14243
14244 for (unsigned ByteIdx = 0; ByteIdx != NumBytes; ++ByteIdx) {
14245 uint8_t AByte = A.getVectorElt(ByteIdx).getInt().getZExtValue();
14246 uint8_t BByte = B.getVectorElt(ByteIdx).getInt().getZExtValue();
14247 Result.push_back(APValue(
14248 APSInt(APInt(8, GFNIMul(AByte, BByte)), /*IsUnsigned=*/false)));
14249 }
14250
14251 return Success(APValue(Result.data(), Result.size()), E);
14252 }
14253
14254 case X86::BI__builtin_ia32_insertf32x4_256:
14255 case X86::BI__builtin_ia32_inserti32x4_256:
14256 case X86::BI__builtin_ia32_insertf64x2_256:
14257 case X86::BI__builtin_ia32_inserti64x2_256:
14258 case X86::BI__builtin_ia32_insertf32x4:
14259 case X86::BI__builtin_ia32_inserti32x4:
14260 case X86::BI__builtin_ia32_insertf64x2_512:
14261 case X86::BI__builtin_ia32_inserti64x2_512:
14262 case X86::BI__builtin_ia32_insertf32x8:
14263 case X86::BI__builtin_ia32_inserti32x8:
14264 case X86::BI__builtin_ia32_insertf64x4:
14265 case X86::BI__builtin_ia32_inserti64x4:
14266 case X86::BI__builtin_ia32_vinsertf128_ps256:
14267 case X86::BI__builtin_ia32_vinsertf128_pd256:
14268 case X86::BI__builtin_ia32_vinsertf128_si256:
14269 case X86::BI__builtin_ia32_insert128i256: {
14270 APValue SourceDst, SourceSub;
14271 if (!EvaluateAsRValue(Info, E->getArg(0), SourceDst) ||
14272 !EvaluateAsRValue(Info, E->getArg(1), SourceSub))
14273 return false;
14274
14275 APSInt Imm;
14276 if (!EvaluateInteger(E->getArg(2), Imm, Info))
14277 return false;
14278
14279 assert(SourceDst.isVector() && SourceSub.isVector());
14280 unsigned DstLen = SourceDst.getVectorLength();
14281 unsigned SubLen = SourceSub.getVectorLength();
14282 assert(SubLen != 0 && DstLen != 0 && (DstLen % SubLen) == 0);
14283 unsigned NumLanes = DstLen / SubLen;
14284 unsigned LaneIdx = (Imm.getZExtValue() % NumLanes) * SubLen;
14285
14286 SmallVector<APValue, 16> ResultElements;
14287 ResultElements.reserve(DstLen);
14288
14289 for (unsigned EltNum = 0; EltNum < DstLen; ++EltNum) {
14290 if (EltNum >= LaneIdx && EltNum < LaneIdx + SubLen)
14291 ResultElements.push_back(SourceSub.getVectorElt(EltNum - LaneIdx));
14292 else
14293 ResultElements.push_back(SourceDst.getVectorElt(EltNum));
14294 }
14295
14296 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
14297 }
14298
14299 case clang::X86::BI__builtin_ia32_vec_set_v4hi:
14300 case clang::X86::BI__builtin_ia32_vec_set_v16qi:
14301 case clang::X86::BI__builtin_ia32_vec_set_v8hi:
14302 case clang::X86::BI__builtin_ia32_vec_set_v4si:
14303 case clang::X86::BI__builtin_ia32_vec_set_v2di:
14304 case clang::X86::BI__builtin_ia32_vec_set_v32qi:
14305 case clang::X86::BI__builtin_ia32_vec_set_v16hi:
14306 case clang::X86::BI__builtin_ia32_vec_set_v8si:
14307 case clang::X86::BI__builtin_ia32_vec_set_v4di: {
14308 APValue VecVal;
14309 APSInt Scalar, IndexAPS;
14310 if (!EvaluateVector(E->getArg(0), VecVal, Info) ||
14311 !EvaluateInteger(E->getArg(1), Scalar, Info) ||
14312 !EvaluateInteger(E->getArg(2), IndexAPS, Info))
14313 return false;
14314
14315 QualType ElemTy = E->getType()->castAs<VectorType>()->getElementType();
14316 unsigned ElemWidth = Info.Ctx.getIntWidth(ElemTy);
14317 bool ElemUnsigned = ElemTy->isUnsignedIntegerOrEnumerationType();
14318 Scalar.setIsUnsigned(ElemUnsigned);
14319 APSInt ElemAPS = Scalar.extOrTrunc(ElemWidth);
14320 APValue ElemAV(ElemAPS);
14321
14322 unsigned NumElems = VecVal.getVectorLength();
14323 unsigned Index =
14324 static_cast<unsigned>(IndexAPS.getZExtValue() & (NumElems - 1));
14325
14327 Elems.reserve(NumElems);
14328 for (unsigned ElemNum = 0; ElemNum != NumElems; ++ElemNum)
14329 Elems.push_back(ElemNum == Index ? ElemAV : VecVal.getVectorElt(ElemNum));
14330
14331 return Success(APValue(Elems.data(), NumElems), E);
14332 }
14333
14334 case X86::BI__builtin_ia32_pslldqi128_byteshift:
14335 case X86::BI__builtin_ia32_pslldqi256_byteshift:
14336 case X86::BI__builtin_ia32_pslldqi512_byteshift: {
14337 APValue R;
14338 if (!evalShuffleGeneric(
14339 Info, E, R,
14340 [](unsigned DstIdx, unsigned Shift) -> std::pair<unsigned, int> {
14341 unsigned LaneBase = (DstIdx / 16) * 16;
14342 unsigned LaneIdx = DstIdx % 16;
14343 if (LaneIdx < Shift)
14344 return std::make_pair(0, -1);
14345
14346 return std::make_pair(
14347 0, static_cast<int>(LaneBase + LaneIdx - Shift));
14348 }))
14349 return false;
14350 return Success(R, E);
14351 }
14352
14353 case X86::BI__builtin_ia32_psrldqi128_byteshift:
14354 case X86::BI__builtin_ia32_psrldqi256_byteshift:
14355 case X86::BI__builtin_ia32_psrldqi512_byteshift: {
14356 APValue R;
14357 if (!evalShuffleGeneric(
14358 Info, E, R,
14359 [](unsigned DstIdx, unsigned Shift) -> std::pair<unsigned, int> {
14360 unsigned LaneBase = (DstIdx / 16) * 16;
14361 unsigned LaneIdx = DstIdx % 16;
14362 if (LaneIdx + Shift < 16)
14363 return std::make_pair(
14364 0, static_cast<int>(LaneBase + LaneIdx + Shift));
14365
14366 return std::make_pair(0, -1);
14367 }))
14368 return false;
14369 return Success(R, E);
14370 }
14371
14372 case X86::BI__builtin_ia32_palignr128:
14373 case X86::BI__builtin_ia32_palignr256:
14374 case X86::BI__builtin_ia32_palignr512: {
14375 APValue R;
14376 if (!evalShuffleGeneric(Info, E, R, [](unsigned DstIdx, unsigned Shift) {
14377 // Default to -1 → zero-fill this destination element
14378 unsigned VecIdx = 1;
14379 int ElemIdx = -1;
14380
14381 int Lane = DstIdx / 16;
14382 int Offset = DstIdx % 16;
14383
14384 // Elements come from VecB first, then VecA after the shift boundary
14385 unsigned ShiftedIdx = Offset + (Shift & 0xFF);
14386 if (ShiftedIdx < 16) { // from VecB
14387 ElemIdx = ShiftedIdx + (Lane * 16);
14388 } else if (ShiftedIdx < 32) { // from VecA
14389 VecIdx = 0;
14390 ElemIdx = (ShiftedIdx - 16) + (Lane * 16);
14391 }
14392
14393 return std::pair<unsigned, int>{VecIdx, ElemIdx};
14394 }))
14395 return false;
14396 return Success(R, E);
14397 }
14398 case X86::BI__builtin_ia32_alignd128:
14399 case X86::BI__builtin_ia32_alignd256:
14400 case X86::BI__builtin_ia32_alignd512:
14401 case X86::BI__builtin_ia32_alignq128:
14402 case X86::BI__builtin_ia32_alignq256:
14403 case X86::BI__builtin_ia32_alignq512: {
14404 APValue R;
14405 unsigned NumElems = E->getType()->castAs<VectorType>()->getNumElements();
14406 if (!evalShuffleGeneric(Info, E, R,
14407 [NumElems](unsigned DstIdx, unsigned Shift) {
14408 unsigned Imm = Shift & 0xFF;
14409 unsigned EffectiveShift = Imm & (NumElems - 1);
14410 unsigned SourcePos = DstIdx + EffectiveShift;
14411 unsigned VecIdx = SourcePos < NumElems ? 1 : 0;
14412 unsigned ElemIdx = SourcePos & (NumElems - 1);
14413
14414 return std::pair<unsigned, int>{
14415 VecIdx, static_cast<int>(ElemIdx)};
14416 }))
14417 return false;
14418 return Success(R, E);
14419 }
14420 case X86::BI__builtin_ia32_permvarsi256:
14421 case X86::BI__builtin_ia32_permvarsf256:
14422 case X86::BI__builtin_ia32_permvardf512:
14423 case X86::BI__builtin_ia32_permvardi512:
14424 case X86::BI__builtin_ia32_permvarhi128: {
14425 APValue R;
14426 if (!evalShuffleGeneric(Info, E, R,
14427 [](unsigned DstIdx, unsigned ShuffleMask) {
14428 int Offset = ShuffleMask & 0x7;
14429 return std::pair<unsigned, int>{0, Offset};
14430 }))
14431 return false;
14432 return Success(R, E);
14433 }
14434 case X86::BI__builtin_ia32_permvarqi128:
14435 case X86::BI__builtin_ia32_permvarhi256:
14436 case X86::BI__builtin_ia32_permvarsi512:
14437 case X86::BI__builtin_ia32_permvarsf512: {
14438 APValue R;
14439 if (!evalShuffleGeneric(Info, E, R,
14440 [](unsigned DstIdx, unsigned ShuffleMask) {
14441 int Offset = ShuffleMask & 0xF;
14442 return std::pair<unsigned, int>{0, Offset};
14443 }))
14444 return false;
14445 return Success(R, E);
14446 }
14447 case X86::BI__builtin_ia32_permvardi256:
14448 case X86::BI__builtin_ia32_permvardf256: {
14449 APValue R;
14450 if (!evalShuffleGeneric(Info, E, R,
14451 [](unsigned DstIdx, unsigned ShuffleMask) {
14452 int Offset = ShuffleMask & 0x3;
14453 return std::pair<unsigned, int>{0, Offset};
14454 }))
14455 return false;
14456 return Success(R, E);
14457 }
14458 case X86::BI__builtin_ia32_permvarqi256:
14459 case X86::BI__builtin_ia32_permvarhi512: {
14460 APValue R;
14461 if (!evalShuffleGeneric(Info, E, R,
14462 [](unsigned DstIdx, unsigned ShuffleMask) {
14463 int Offset = ShuffleMask & 0x1F;
14464 return std::pair<unsigned, int>{0, Offset};
14465 }))
14466 return false;
14467 return Success(R, E);
14468 }
14469 case X86::BI__builtin_ia32_permvarqi512: {
14470 APValue R;
14471 if (!evalShuffleGeneric(Info, E, R,
14472 [](unsigned DstIdx, unsigned ShuffleMask) {
14473 int Offset = ShuffleMask & 0x3F;
14474 return std::pair<unsigned, int>{0, Offset};
14475 }))
14476 return false;
14477 return Success(R, E);
14478 }
14479 case X86::BI__builtin_ia32_vpermi2varq128:
14480 case X86::BI__builtin_ia32_vpermi2varpd128: {
14481 APValue R;
14482 if (!evalShuffleGeneric(Info, E, R,
14483 [](unsigned DstIdx, unsigned ShuffleMask) {
14484 int Offset = ShuffleMask & 0x1;
14485 unsigned SrcIdx = (ShuffleMask >> 1) & 0x1;
14486 return std::pair<unsigned, int>{SrcIdx, Offset};
14487 }))
14488 return false;
14489 return Success(R, E);
14490 }
14491 case X86::BI__builtin_ia32_vpermi2vard128:
14492 case X86::BI__builtin_ia32_vpermi2varps128:
14493 case X86::BI__builtin_ia32_vpermi2varq256:
14494 case X86::BI__builtin_ia32_vpermi2varpd256: {
14495 APValue R;
14496 if (!evalShuffleGeneric(Info, E, R,
14497 [](unsigned DstIdx, unsigned ShuffleMask) {
14498 int Offset = ShuffleMask & 0x3;
14499 unsigned SrcIdx = (ShuffleMask >> 2) & 0x1;
14500 return std::pair<unsigned, int>{SrcIdx, Offset};
14501 }))
14502 return false;
14503 return Success(R, E);
14504 }
14505 case X86::BI__builtin_ia32_vpermi2varhi128:
14506 case X86::BI__builtin_ia32_vpermi2vard256:
14507 case X86::BI__builtin_ia32_vpermi2varps256:
14508 case X86::BI__builtin_ia32_vpermi2varq512:
14509 case X86::BI__builtin_ia32_vpermi2varpd512: {
14510 APValue R;
14511 if (!evalShuffleGeneric(Info, E, R,
14512 [](unsigned DstIdx, unsigned ShuffleMask) {
14513 int Offset = ShuffleMask & 0x7;
14514 unsigned SrcIdx = (ShuffleMask >> 3) & 0x1;
14515 return std::pair<unsigned, int>{SrcIdx, Offset};
14516 }))
14517 return false;
14518 return Success(R, E);
14519 }
14520 case X86::BI__builtin_ia32_vpermi2varqi128:
14521 case X86::BI__builtin_ia32_vpermi2varhi256:
14522 case X86::BI__builtin_ia32_vpermi2vard512:
14523 case X86::BI__builtin_ia32_vpermi2varps512: {
14524 APValue R;
14525 if (!evalShuffleGeneric(Info, E, R,
14526 [](unsigned DstIdx, unsigned ShuffleMask) {
14527 int Offset = ShuffleMask & 0xF;
14528 unsigned SrcIdx = (ShuffleMask >> 4) & 0x1;
14529 return std::pair<unsigned, int>{SrcIdx, Offset};
14530 }))
14531 return false;
14532 return Success(R, E);
14533 }
14534 case X86::BI__builtin_ia32_vpermi2varqi256:
14535 case X86::BI__builtin_ia32_vpermi2varhi512: {
14536 APValue R;
14537 if (!evalShuffleGeneric(Info, E, R,
14538 [](unsigned DstIdx, unsigned ShuffleMask) {
14539 int Offset = ShuffleMask & 0x1F;
14540 unsigned SrcIdx = (ShuffleMask >> 5) & 0x1;
14541 return std::pair<unsigned, int>{SrcIdx, Offset};
14542 }))
14543 return false;
14544 return Success(R, E);
14545 }
14546 case X86::BI__builtin_ia32_vpermi2varqi512: {
14547 APValue R;
14548 if (!evalShuffleGeneric(Info, E, R,
14549 [](unsigned DstIdx, unsigned ShuffleMask) {
14550 int Offset = ShuffleMask & 0x3F;
14551 unsigned SrcIdx = (ShuffleMask >> 6) & 0x1;
14552 return std::pair<unsigned, int>{SrcIdx, Offset};
14553 }))
14554 return false;
14555 return Success(R, E);
14556 }
14557
14558 case clang::X86::BI__builtin_ia32_minps:
14559 case clang::X86::BI__builtin_ia32_minpd:
14560 case clang::X86::BI__builtin_ia32_minps256:
14561 case clang::X86::BI__builtin_ia32_minpd256:
14562 case clang::X86::BI__builtin_ia32_minps512:
14563 case clang::X86::BI__builtin_ia32_minpd512:
14564 case clang::X86::BI__builtin_ia32_minph128:
14565 case clang::X86::BI__builtin_ia32_minph256:
14566 case clang::X86::BI__builtin_ia32_minph512:
14567 return EvaluateFpBinOpExpr(
14568 [](const APFloat &A, const APFloat &B,
14569 std::optional<APSInt>) -> std::optional<APFloat> {
14570 if (A.isNaN() || A.isInfinity() || A.isDenormal() || B.isNaN() ||
14571 B.isInfinity() || B.isDenormal())
14572 return std::nullopt;
14573 if (A.isZero() && B.isZero())
14574 return B;
14575 return llvm::minimum(A, B);
14576 });
14577
14578 case clang::X86::BI__builtin_ia32_minss:
14579 case clang::X86::BI__builtin_ia32_minsd:
14580 return EvaluateFpBinOpExpr(
14581 [](const APFloat &A, const APFloat &B,
14582 std::optional<APSInt> RoundingMode) -> std::optional<APFloat> {
14583 return EvalScalarMinMaxFp(A, B, RoundingMode, /*IsMin=*/true);
14584 },
14585 /*IsScalar=*/true);
14586
14587 case clang::X86::BI__builtin_ia32_minsd_round_mask:
14588 case clang::X86::BI__builtin_ia32_minss_round_mask:
14589 case clang::X86::BI__builtin_ia32_minsh_round_mask:
14590 case clang::X86::BI__builtin_ia32_maxsd_round_mask:
14591 case clang::X86::BI__builtin_ia32_maxss_round_mask:
14592 case clang::X86::BI__builtin_ia32_maxsh_round_mask: {
14593 bool IsMin =
14594 E->getBuiltinCallee() ==
14595 clang::X86::BI__builtin_ia32_minsd_round_mask ||
14596 E->getBuiltinCallee() ==
14597 clang::X86::BI__builtin_ia32_minss_round_mask ||
14598 E->getBuiltinCallee() == clang::X86::BI__builtin_ia32_minsh_round_mask;
14599 return EvaluateScalarFpRoundMaskBinOp(
14600 [IsMin](const APFloat &A, const APFloat &B,
14601 std::optional<APSInt> RoundingMode) -> std::optional<APFloat> {
14602 return EvalScalarMinMaxFp(A, B, RoundingMode, IsMin);
14603 });
14604 }
14605
14606 case clang::X86::BI__builtin_ia32_maxps:
14607 case clang::X86::BI__builtin_ia32_maxpd:
14608 case clang::X86::BI__builtin_ia32_maxps256:
14609 case clang::X86::BI__builtin_ia32_maxpd256:
14610 case clang::X86::BI__builtin_ia32_maxps512:
14611 case clang::X86::BI__builtin_ia32_maxpd512:
14612 case clang::X86::BI__builtin_ia32_maxph128:
14613 case clang::X86::BI__builtin_ia32_maxph256:
14614 case clang::X86::BI__builtin_ia32_maxph512:
14615 return EvaluateFpBinOpExpr(
14616 [](const APFloat &A, const APFloat &B,
14617 std::optional<APSInt>) -> std::optional<APFloat> {
14618 if (A.isNaN() || A.isInfinity() || A.isDenormal() || B.isNaN() ||
14619 B.isInfinity() || B.isDenormal())
14620 return std::nullopt;
14621 if (A.isZero() && B.isZero())
14622 return B;
14623 return llvm::maximum(A, B);
14624 });
14625
14626 case clang::X86::BI__builtin_ia32_maxss:
14627 case clang::X86::BI__builtin_ia32_maxsd:
14628 return EvaluateFpBinOpExpr(
14629 [](const APFloat &A, const APFloat &B,
14630 std::optional<APSInt> RoundingMode) -> std::optional<APFloat> {
14631 return EvalScalarMinMaxFp(A, B, RoundingMode, /*IsMin=*/false);
14632 },
14633 /*IsScalar=*/true);
14634
14635 case clang::X86::BI__builtin_ia32_vcvtps2ph:
14636 case clang::X86::BI__builtin_ia32_vcvtps2ph256: {
14637 APValue SrcVec;
14638 if (!EvaluateAsRValue(Info, E->getArg(0), SrcVec))
14639 return false;
14640
14641 APSInt Imm;
14642 if (!EvaluateInteger(E->getArg(1), Imm, Info))
14643 return false;
14644
14645 const auto *SrcVTy = E->getArg(0)->getType()->castAs<VectorType>();
14646 unsigned SrcNumElems = SrcVTy->getNumElements();
14647 const auto *DstVTy = E->getType()->castAs<VectorType>();
14648 unsigned DstNumElems = DstVTy->getNumElements();
14649 QualType DstElemTy = DstVTy->getElementType();
14650
14651 const llvm::fltSemantics &HalfSem =
14652 Info.Ctx.getFloatTypeSemantics(Info.Ctx.HalfTy);
14653
14654 int ImmVal = Imm.getZExtValue();
14655 bool UseMXCSR = (ImmVal & 4) != 0;
14656 bool IsFPConstrained =
14657 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained();
14658
14659 llvm::RoundingMode RM;
14660 if (!UseMXCSR) {
14661 switch (ImmVal & 3) {
14662 case 0:
14663 RM = llvm::RoundingMode::NearestTiesToEven;
14664 break;
14665 case 1:
14666 RM = llvm::RoundingMode::TowardNegative;
14667 break;
14668 case 2:
14669 RM = llvm::RoundingMode::TowardPositive;
14670 break;
14671 case 3:
14672 RM = llvm::RoundingMode::TowardZero;
14673 break;
14674 default:
14675 llvm_unreachable("Invalid immediate rounding mode");
14676 }
14677 } else {
14678 RM = llvm::RoundingMode::NearestTiesToEven;
14679 }
14680
14681 SmallVector<APValue, 8> ResultElements;
14682 ResultElements.reserve(DstNumElems);
14683
14684 for (unsigned I = 0; I < SrcNumElems; ++I) {
14685 APFloat SrcVal = SrcVec.getVectorElt(I).getFloat();
14686
14687 bool LostInfo;
14688 APFloat::opStatus St = SrcVal.convert(HalfSem, RM, &LostInfo);
14689
14690 if (UseMXCSR && IsFPConstrained && St != APFloat::opOK) {
14691 Info.FFDiag(E, diag::note_constexpr_dynamic_rounding);
14692 return false;
14693 }
14694
14695 APSInt DstInt(SrcVal.bitcastToAPInt(),
14697 ResultElements.push_back(APValue(DstInt));
14698 }
14699
14700 if (DstNumElems > SrcNumElems) {
14701 APSInt Zero = Info.Ctx.MakeIntValue(0, DstElemTy);
14702 for (unsigned I = SrcNumElems; I < DstNumElems; ++I) {
14703 ResultElements.push_back(APValue(Zero));
14704 }
14705 }
14706
14707 return Success(ResultElements, E);
14708 }
14709 case X86::BI__builtin_ia32_vperm2f128_pd256:
14710 case X86::BI__builtin_ia32_vperm2f128_ps256:
14711 case X86::BI__builtin_ia32_vperm2f128_si256:
14712 case X86::BI__builtin_ia32_permti256: {
14713 unsigned NumElements =
14714 E->getArg(0)->getType()->getAs<VectorType>()->getNumElements();
14715 unsigned PreservedBitsCnt = NumElements >> 2;
14716 APValue R;
14717 if (!evalShuffleGeneric(
14718 Info, E, R,
14719 [PreservedBitsCnt](unsigned DstIdx, unsigned ShuffleMask) {
14720 unsigned ControlBitsCnt = DstIdx >> PreservedBitsCnt << 2;
14721 unsigned ControlBits = ShuffleMask >> ControlBitsCnt;
14722
14723 if (ControlBits & 0b1000)
14724 return std::make_pair(0u, -1);
14725
14726 unsigned SrcVecIdx = (ControlBits & 0b10) >> 1;
14727 unsigned PreservedBitsMask = (1 << PreservedBitsCnt) - 1;
14728 int SrcIdx = ((ControlBits & 0b1) << PreservedBitsCnt) |
14729 (DstIdx & PreservedBitsMask);
14730 return std::make_pair(SrcVecIdx, SrcIdx);
14731 }))
14732 return false;
14733 return Success(R, E);
14734 }
14735 }
14736}
14737
14738bool VectorExprEvaluator::VisitConvertVectorExpr(const ConvertVectorExpr *E) {
14739 APValue Source;
14740 QualType SourceVecType = E->getSrcExpr()->getType();
14741 if (!EvaluateAsRValue(Info, E->getSrcExpr(), Source))
14742 return false;
14743
14744 QualType DestTy = E->getType()->castAs<VectorType>()->getElementType();
14745 QualType SourceTy = SourceVecType->castAs<VectorType>()->getElementType();
14746
14747 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
14748
14749 auto SourceLen = Source.getVectorLength();
14750 SmallVector<APValue, 4> ResultElements;
14751 ResultElements.reserve(SourceLen);
14752 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
14753 APValue Elt;
14754 if (!handleVectorElementCast(Info, FPO, E, SourceTy, DestTy,
14755 Source.getVectorElt(EltNum), Elt))
14756 return false;
14757 ResultElements.push_back(std::move(Elt));
14758 }
14759
14760 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
14761}
14762
14763static bool handleVectorShuffle(EvalInfo &Info, const ShuffleVectorExpr *E,
14764 QualType ElemType, APValue const &VecVal1,
14765 APValue const &VecVal2, unsigned EltNum,
14766 APValue &Result) {
14767 unsigned const TotalElementsInInputVector1 = VecVal1.getVectorLength();
14768 unsigned const TotalElementsInInputVector2 = VecVal2.getVectorLength();
14769
14770 APSInt IndexVal = E->getShuffleMaskIdx(EltNum);
14771 int64_t index = IndexVal.getExtValue();
14772 // The spec says that -1 should be treated as undef for optimizations,
14773 // but in constexpr we'd have to produce an APValue::Indeterminate,
14774 // which is prohibited from being a top-level constant value. Emit a
14775 // diagnostic instead.
14776 if (index == -1) {
14777 Info.FFDiag(
14778 E, diag::err_shufflevector_minus_one_is_undefined_behavior_constexpr)
14779 << EltNum;
14780 return false;
14781 }
14782
14783 if (index < 0 ||
14784 index >= TotalElementsInInputVector1 + TotalElementsInInputVector2)
14785 llvm_unreachable("Out of bounds shuffle index");
14786
14787 if (index >= TotalElementsInInputVector1)
14788 Result = VecVal2.getVectorElt(index - TotalElementsInInputVector1);
14789 else
14790 Result = VecVal1.getVectorElt(index);
14791 return true;
14792}
14793
14794bool VectorExprEvaluator::VisitShuffleVectorExpr(const ShuffleVectorExpr *E) {
14795 // FIXME: Unary shuffle with mask not currently supported.
14796 if (E->getNumSubExprs() == 2)
14797 return Error(E);
14798 APValue VecVal1;
14799 const Expr *Vec1 = E->getExpr(0);
14800 if (!EvaluateAsRValue(Info, Vec1, VecVal1))
14801 return false;
14802 APValue VecVal2;
14803 const Expr *Vec2 = E->getExpr(1);
14804 if (!EvaluateAsRValue(Info, Vec2, VecVal2))
14805 return false;
14806
14807 VectorType const *DestVecTy = E->getType()->castAs<VectorType>();
14808 QualType DestElTy = DestVecTy->getElementType();
14809
14810 auto TotalElementsInOutputVector = DestVecTy->getNumElements();
14811
14812 SmallVector<APValue, 4> ResultElements;
14813 ResultElements.reserve(TotalElementsInOutputVector);
14814 for (unsigned EltNum = 0; EltNum < TotalElementsInOutputVector; ++EltNum) {
14815 APValue Elt;
14816 if (!handleVectorShuffle(Info, E, DestElTy, VecVal1, VecVal2, EltNum, Elt))
14817 return false;
14818 ResultElements.push_back(std::move(Elt));
14819 }
14820
14821 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
14822}
14823
14824//===----------------------------------------------------------------------===//
14825// Matrix Evaluation
14826//===----------------------------------------------------------------------===//
14827
14828namespace {
14829class MatrixExprEvaluator : public ExprEvaluatorBase<MatrixExprEvaluator> {
14830 APValue &Result;
14831
14832public:
14833 MatrixExprEvaluator(EvalInfo &Info, APValue &Result)
14834 : ExprEvaluatorBaseTy(Info), Result(Result) {}
14835
14836 bool Success(ArrayRef<APValue> M, const Expr *E) {
14837 auto *CMTy = E->getType()->castAs<ConstantMatrixType>();
14838 assert(M.size() == CMTy->getNumElementsFlattened());
14839 // FIXME: remove this APValue copy.
14840 Result = APValue(M.data(), CMTy->getNumRows(), CMTy->getNumColumns());
14841 return true;
14842 }
14843 bool Success(const APValue &M, const Expr *E) {
14844 assert(M.isMatrix() && "expected matrix");
14845 Result = M;
14846 return true;
14847 }
14848
14849 bool VisitCastExpr(const CastExpr *E);
14850 bool VisitInitListExpr(const InitListExpr *E);
14851};
14852} // end anonymous namespace
14853
14854static bool EvaluateMatrix(const Expr *E, APValue &Result, EvalInfo &Info) {
14855 assert(E->isPRValue() && E->getType()->isConstantMatrixType() &&
14856 "not a matrix prvalue");
14857 return MatrixExprEvaluator(Info, Result).Visit(E);
14858}
14859
14860bool MatrixExprEvaluator::VisitCastExpr(const CastExpr *E) {
14861 const auto *MT = E->getType()->castAs<ConstantMatrixType>();
14862 unsigned NumRows = MT->getNumRows();
14863 unsigned NumCols = MT->getNumColumns();
14864 unsigned NElts = NumRows * NumCols;
14865 QualType EltTy = MT->getElementType();
14866 const Expr *SE = E->getSubExpr();
14867
14868 switch (E->getCastKind()) {
14869 case CK_HLSLAggregateSplatCast: {
14870 APValue Val;
14871 QualType ValTy;
14872
14873 if (!hlslAggSplatHelper(Info, SE, Val, ValTy))
14874 return false;
14875
14876 APValue CastedVal;
14877 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
14878 if (!handleScalarCast(Info, FPO, E, ValTy, EltTy, Val, CastedVal))
14879 return false;
14880
14881 SmallVector<APValue, 16> SplatEls(NElts, CastedVal);
14882 return Success(SplatEls, E);
14883 }
14884 case CK_HLSLElementwiseCast: {
14885 SmallVector<APValue> SrcVals;
14886 SmallVector<QualType> SrcTypes;
14887
14888 if (!hlslElementwiseCastHelper(Info, SE, E->getType(), SrcVals, SrcTypes))
14889 return false;
14890
14891 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
14892 SmallVector<QualType, 16> DestTypes(NElts, EltTy);
14893 SmallVector<APValue, 16> ResultEls(NElts);
14894 if (!handleElementwiseCast(Info, E, FPO, SrcVals, SrcTypes, DestTypes,
14895 ResultEls))
14896 return false;
14897 return Success(ResultEls, E);
14898 }
14899 default:
14900 return ExprEvaluatorBaseTy::VisitCastExpr(E);
14901 }
14902}
14903
14904bool MatrixExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
14905 const auto *MT = E->getType()->castAs<ConstantMatrixType>();
14906 QualType EltTy = MT->getElementType();
14907
14908 assert(E->getNumInits() == MT->getNumElementsFlattened() &&
14909 "Expected number of elements in initializer list to match the number "
14910 "of matrix elements");
14911
14912 SmallVector<APValue, 16> Elements;
14913 Elements.reserve(MT->getNumElementsFlattened());
14914
14915 // The following loop assumes the elements of the matrix InitListExpr are in
14916 // row-major order, which matches the row-major ordering assumption of the
14917 // matrix APValue.
14918 for (unsigned I = 0, N = MT->getNumElementsFlattened(); I < N; ++I) {
14919 if (EltTy->isIntegerType()) {
14920 llvm::APSInt IntVal;
14921 if (!EvaluateInteger(E->getInit(I), IntVal, Info))
14922 return false;
14923 Elements.push_back(APValue(IntVal));
14924 } else {
14925 llvm::APFloat FloatVal(0.0);
14926 if (!EvaluateFloat(E->getInit(I), FloatVal, Info))
14927 return false;
14928 Elements.push_back(APValue(FloatVal));
14929 }
14930 }
14931
14932 return Success(Elements, E);
14933}
14934
14935//===----------------------------------------------------------------------===//
14936// Array Evaluation
14937//===----------------------------------------------------------------------===//
14938
14939namespace {
14940 class ArrayExprEvaluator
14941 : public ExprEvaluatorBase<ArrayExprEvaluator> {
14942 const LValue &This;
14943 APValue &Result;
14944 public:
14945
14946 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
14947 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
14948
14949 bool Success(const APValue &V, const Expr *E) {
14950 assert(V.isArray() && "expected array");
14951 Result = V;
14952 return true;
14953 }
14954
14955 bool ZeroInitialization(const Expr *E) {
14956 const ConstantArrayType *CAT =
14957 Info.Ctx.getAsConstantArrayType(E->getType());
14958 if (!CAT) {
14959 if (E->getType()->isIncompleteArrayType()) {
14960 // We can be asked to zero-initialize a flexible array member; this
14961 // is represented as an ImplicitValueInitExpr of incomplete array
14962 // type. In this case, the array has zero elements.
14963 Result = APValue(APValue::UninitArray(), 0, 0);
14964 return true;
14965 }
14966 // FIXME: We could handle VLAs here.
14967 return Error(E);
14968 }
14969
14970 Result = APValue(APValue::UninitArray(), 0, CAT->getZExtSize());
14971 if (!Result.hasArrayFiller())
14972 return true;
14973
14974 // Zero-initialize all elements.
14975 LValue Subobject = This;
14976 Subobject.addArray(Info, E, CAT);
14977 ImplicitValueInitExpr VIE(CAT->getElementType());
14978 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
14979 }
14980
14981 bool VisitCallExpr(const CallExpr *E) {
14982 return handleCallExpr(E, Result, &This);
14983 }
14984 bool VisitCastExpr(const CastExpr *E);
14985 bool VisitInitListExpr(const InitListExpr *E,
14986 QualType AllocType = QualType());
14987 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
14988 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
14989 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
14990 const LValue &Subobject,
14991 APValue *Value, QualType Type);
14992 bool VisitStringLiteral(const StringLiteral *E,
14993 QualType AllocType = QualType()) {
14994 expandStringLiteral(Info, E, Result, AllocType);
14995 return true;
14996 }
14997 bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E);
14998 bool VisitCXXParenListOrInitListExpr(const Expr *ExprToVisit,
14999 ArrayRef<Expr *> Args,
15000 const Expr *ArrayFiller,
15001 QualType AllocType = QualType());
15002 };
15003} // end anonymous namespace
15004
15005static bool EvaluateArray(const Expr *E, const LValue &This,
15006 APValue &Result, EvalInfo &Info) {
15007 assert(!E->isValueDependent());
15008 assert(E->isPRValue() && E->getType()->isArrayType() &&
15009 "not an array prvalue");
15010 return ArrayExprEvaluator(Info, This, Result).Visit(E);
15011}
15012
15013static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
15014 APValue &Result, const InitListExpr *ILE,
15015 QualType AllocType) {
15016 assert(!ILE->isValueDependent());
15017 assert(ILE->isPRValue() && ILE->getType()->isArrayType() &&
15018 "not an array prvalue");
15019 return ArrayExprEvaluator(Info, This, Result)
15020 .VisitInitListExpr(ILE, AllocType);
15021}
15022
15023static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
15024 APValue &Result,
15025 const CXXConstructExpr *CCE,
15026 QualType AllocType) {
15027 assert(!CCE->isValueDependent());
15028 assert(CCE->isPRValue() && CCE->getType()->isArrayType() &&
15029 "not an array prvalue");
15030 return ArrayExprEvaluator(Info, This, Result)
15031 .VisitCXXConstructExpr(CCE, This, &Result, AllocType);
15032}
15033
15034// Return true iff the given array filler may depend on the element index.
15035static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
15036 // For now, just allow non-class value-initialization and initialization
15037 // lists comprised of them.
15038 if (isa<ImplicitValueInitExpr>(FillerExpr))
15039 return false;
15040 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
15041 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
15042 if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
15043 return true;
15044 }
15045
15046 if (ILE->hasArrayFiller() &&
15047 MaybeElementDependentArrayFiller(ILE->getArrayFiller()))
15048 return true;
15049
15050 return false;
15051 }
15052 return true;
15053}
15054
15055bool ArrayExprEvaluator::VisitCastExpr(const CastExpr *E) {
15056 const Expr *SE = E->getSubExpr();
15057
15058 switch (E->getCastKind()) {
15059 default:
15060 return ExprEvaluatorBaseTy::VisitCastExpr(E);
15061 case CK_HLSLAggregateSplatCast: {
15062 APValue Val;
15063 QualType ValTy;
15064
15065 if (!hlslAggSplatHelper(Info, SE, Val, ValTy))
15066 return false;
15067
15068 unsigned NEls = elementwiseSize(Info, E->getType());
15069
15070 SmallVector<APValue> SplatEls(NEls, Val);
15071 SmallVector<QualType> SplatType(NEls, ValTy);
15072
15073 // cast the elements
15074 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
15075 if (!constructAggregate(Info, FPO, E, Result, E->getType(), SplatEls,
15076 SplatType))
15077 return false;
15078
15079 return true;
15080 }
15081 case CK_HLSLElementwiseCast: {
15082 SmallVector<APValue> SrcEls;
15083 SmallVector<QualType> SrcTypes;
15084
15085 if (!hlslElementwiseCastHelper(Info, SE, E->getType(), SrcEls, SrcTypes))
15086 return false;
15087
15088 // cast the elements
15089 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
15090 if (!constructAggregate(Info, FPO, E, Result, E->getType(), SrcEls,
15091 SrcTypes))
15092 return false;
15093 return true;
15094 }
15095 }
15096}
15097
15098bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E,
15099 QualType AllocType) {
15100 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
15101 AllocType.isNull() ? E->getType() : AllocType);
15102 if (!CAT)
15103 return Error(E);
15104
15105 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
15106 // an appropriately-typed string literal enclosed in braces.
15107 if (E->isStringLiteralInit()) {
15108 auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParenImpCasts());
15109 // FIXME: Support ObjCEncodeExpr here once we support it in
15110 // ArrayExprEvaluator generally.
15111 if (!SL)
15112 return Error(E);
15113 return VisitStringLiteral(SL, AllocType);
15114 }
15115 // Any other transparent list init will need proper handling of the
15116 // AllocType; we can't just recurse to the inner initializer.
15117 assert(!E->isTransparent() &&
15118 "transparent array list initialization is not string literal init?");
15119
15120 return VisitCXXParenListOrInitListExpr(E, E->inits(), E->getArrayFiller(),
15121 AllocType);
15122}
15123
15124bool ArrayExprEvaluator::VisitCXXParenListOrInitListExpr(
15125 const Expr *ExprToVisit, ArrayRef<Expr *> Args, const Expr *ArrayFiller,
15126 QualType AllocType) {
15127 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
15128 AllocType.isNull() ? ExprToVisit->getType() : AllocType);
15129
15130 bool Success = true;
15131
15132 unsigned NumEltsToInit = Args.size();
15133 unsigned NumElts = CAT->getZExtSize();
15134
15135 // If the initializer might depend on the array index, run it for each
15136 // array element.
15137 if (NumEltsToInit != NumElts &&
15138 MaybeElementDependentArrayFiller(ArrayFiller)) {
15139 NumEltsToInit = NumElts;
15140 } else {
15141 // Add additional elements represented by EmbedExpr.
15142 for (auto *Init : Args) {
15143 if (auto *EmbedS = dyn_cast<EmbedExpr>(Init->IgnoreParenImpCasts()))
15144 NumEltsToInit += EmbedS->getDataElementCount() - 1;
15145 }
15146 // If we have extra elements in the list, they will be discarded.
15147 if (NumEltsToInit > NumElts)
15148 NumEltsToInit = NumElts;
15149 // If we're overwriting memory which already has an object, make sure we
15150 // don't reduce the number of non-filler elements. (It's possible to
15151 // optimize this in some cases, but the logic gets really complicated.)
15152 if (Result.hasValue() && NumEltsToInit < Result.getArrayInitializedElts())
15153 NumEltsToInit = Result.getArrayInitializedElts();
15154 }
15155
15156 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
15157 << NumEltsToInit << ".\n");
15158
15159 if (!Result.hasValue()) {
15160 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
15161 } else if (Result.getArrayInitializedElts() != NumEltsToInit) {
15162 // Number of inititalized elts changed. Recreate the APValue, and copy over
15163 // the relevant elements. (This is essentially just fixing the internal
15164 // representation of the value, because it's tied to the number of
15165 // non-filler elements.)
15166 //
15167 // This should be hit rarely, but there are some edge cases:
15168 //
15169 // - The array could be zero-initialized.
15170 // - There could be a DesignatedInitListExpr.
15171 // - operator new[] can be used to start the lifetime early.
15172 APValue NewResult = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
15173 // First copy existing elements.
15174 unsigned NumOldElts = Result.getArrayInitializedElts();
15175 for (unsigned I = 0; I < NumOldElts; ++I) {
15176 NewResult.getArrayInitializedElt(I) =
15177 std::move(Result.getArrayInitializedElt(I));
15178 }
15179 // Then copy the array filler over the remaining elements.
15180 for (unsigned I = Result.getArrayInitializedElts(); I < NumEltsToInit; ++I)
15182 if (NewResult.hasArrayFiller() && Result.hasArrayFiller())
15183 NewResult.getArrayFiller() = Result.getArrayFiller();
15184 Result = std::move(NewResult);
15185 }
15186
15187 LValue Subobject = This;
15188 Subobject.addArray(Info, ExprToVisit, CAT);
15189 auto Eval = [&](const Expr *Init, unsigned ArrayIndex) {
15190 if (Init->isValueDependent())
15191 return EvaluateDependentExpr(Init, Info);
15192
15193 // If this is a child of a DesignatedInitUpdateExpr, skip elements which
15194 // aren't supposed to be modified.
15195 if (isa<NoInitExpr>(Init))
15196 return true;
15197
15198 if (!EvaluateInPlace(Result.getArrayInitializedElt(ArrayIndex), Info,
15199 Subobject, Init) ||
15200 !HandleLValueArrayAdjustment(Info, Init, Subobject,
15201 CAT->getElementType(), 1)) {
15202 if (!Info.noteFailure())
15203 return false;
15204 Success = false;
15205 }
15206 return true;
15207 };
15208 unsigned ArrayIndex = 0;
15209 QualType DestTy = CAT->getElementType();
15210 APSInt Value(Info.Ctx.getTypeSize(DestTy), DestTy->isUnsignedIntegerType());
15211 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
15212 const Expr *Init = Index < Args.size() ? Args[Index] : ArrayFiller;
15213 if (ArrayIndex >= NumEltsToInit)
15214 break;
15215 if (auto *EmbedS = dyn_cast<EmbedExpr>(Init->IgnoreParenImpCasts())) {
15216 StringLiteral *SL = EmbedS->getDataStringLiteral();
15217 for (unsigned I = EmbedS->getStartingElementPos(),
15218 N = EmbedS->getDataElementCount();
15219 I != EmbedS->getStartingElementPos() + N; ++I) {
15220 Value = SL->getCodeUnit(I);
15221 if (DestTy->isIntegerType()) {
15222 Result.getArrayInitializedElt(ArrayIndex) = APValue(Value);
15223 } else {
15224 assert(DestTy->isFloatingType() && "unexpected type");
15225 const FPOptions FPO =
15226 Init->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
15227 APFloat FValue(0.0);
15228 if (!HandleIntToFloatCast(Info, Init, FPO, EmbedS->getType(), Value,
15229 DestTy, FValue))
15230 return false;
15231 Result.getArrayInitializedElt(ArrayIndex) = APValue(FValue);
15232 }
15233 ArrayIndex++;
15234 }
15235 } else {
15236 if (!Eval(Init, ArrayIndex))
15237 return false;
15238 ++ArrayIndex;
15239 }
15240 }
15241
15242 if (!Result.hasArrayFiller())
15243 return Success;
15244
15245 // If we get here, we have a trivial filler, which we can just evaluate
15246 // once and splat over the rest of the array elements.
15247 assert(ArrayFiller && "no array filler for incomplete init list");
15248 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
15249 ArrayFiller) &&
15250 Success;
15251}
15252
15253bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
15254 LValue CommonLV;
15255 if (E->getCommonExpr() &&
15256 !Evaluate(Info.CurrentCall->createTemporary(
15257 E->getCommonExpr(),
15258 getStorageType(Info.Ctx, E->getCommonExpr()),
15259 ScopeKind::FullExpression, CommonLV),
15260 Info, E->getCommonExpr()->getSourceExpr()))
15261 return false;
15262
15264
15265 uint64_t Elements = CAT->getZExtSize();
15266 Result = APValue(APValue::UninitArray(), Elements, Elements);
15267
15268 LValue Subobject = This;
15269 Subobject.addArray(Info, E, CAT);
15270
15271 bool Success = true;
15272 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
15273 // C++ [class.temporary]/5
15274 // There are four contexts in which temporaries are destroyed at a different
15275 // point than the end of the full-expression. [...] The second context is
15276 // when a copy constructor is called to copy an element of an array while
15277 // the entire array is copied [...]. In either case, if the constructor has
15278 // one or more default arguments, the destruction of every temporary created
15279 // in a default argument is sequenced before the construction of the next
15280 // array element, if any.
15281 FullExpressionRAII Scope(Info);
15282
15283 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
15284 Info, Subobject, E->getSubExpr()) ||
15285 !HandleLValueArrayAdjustment(Info, E, Subobject,
15286 CAT->getElementType(), 1)) {
15287 if (!Info.noteFailure())
15288 return false;
15289 Success = false;
15290 }
15291
15292 // Make sure we run the destructors too.
15293 Scope.destroy();
15294 }
15295
15296 return Success;
15297}
15298
15299bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
15300 return VisitCXXConstructExpr(E, This, &Result, E->getType());
15301}
15302
15303bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
15304 const LValue &Subobject,
15305 APValue *Value,
15306 QualType Type) {
15307 bool HadZeroInit = Value->hasValue();
15308
15309 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
15310 unsigned FinalSize = CAT->getZExtSize();
15311
15312 // Preserve the array filler if we had prior zero-initialization.
15313 APValue Filler =
15314 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
15315 : APValue();
15316
15317 *Value = APValue(APValue::UninitArray(), 0, FinalSize);
15318 if (FinalSize == 0)
15319 return true;
15320
15321 bool HasTrivialConstructor = CheckTrivialDefaultConstructor(
15322 Info, E->getExprLoc(), E->getConstructor(),
15324 LValue ArrayElt = Subobject;
15325 ArrayElt.addArray(Info, E, CAT);
15326 // We do the whole initialization in two passes, first for just one element,
15327 // then for the whole array. It's possible we may find out we can't do const
15328 // init in the first pass, in which case we avoid allocating a potentially
15329 // large array. We don't do more passes because expanding array requires
15330 // copying the data, which is wasteful.
15331 for (const unsigned N : {1u, FinalSize}) {
15332 unsigned OldElts = Value->getArrayInitializedElts();
15333 if (OldElts == N)
15334 break;
15335
15336 // Expand the array to appropriate size.
15337 APValue NewValue(APValue::UninitArray(), N, FinalSize);
15338 for (unsigned I = 0; I < OldElts; ++I)
15339 NewValue.getArrayInitializedElt(I).swap(
15340 Value->getArrayInitializedElt(I));
15341 Value->swap(NewValue);
15342
15343 if (HadZeroInit)
15344 for (unsigned I = OldElts; I < N; ++I)
15345 Value->getArrayInitializedElt(I) = Filler;
15346
15347 if (HasTrivialConstructor && N == FinalSize && FinalSize != 1) {
15348 // If we have a trivial constructor, only evaluate it once and copy
15349 // the result into all the array elements.
15350 APValue &FirstResult = Value->getArrayInitializedElt(0);
15351 for (unsigned I = OldElts; I < FinalSize; ++I)
15352 Value->getArrayInitializedElt(I) = FirstResult;
15353 } else {
15354 for (unsigned I = OldElts; I < N; ++I) {
15355 if (!VisitCXXConstructExpr(E, ArrayElt,
15356 &Value->getArrayInitializedElt(I),
15357 CAT->getElementType()) ||
15358 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
15359 CAT->getElementType(), 1))
15360 return false;
15361 // When checking for const initilization any diagnostic is considered
15362 // an error.
15363 if (Info.EvalStatus.Diag && !Info.EvalStatus.Diag->empty() &&
15364 !Info.keepEvaluatingAfterFailure())
15365 return false;
15366 }
15367 }
15368 }
15369
15370 return true;
15371 }
15372
15373 if (!Type->isRecordType())
15374 return Error(E);
15375
15376 return RecordExprEvaluator(Info, Subobject, *Value)
15377 .VisitCXXConstructExpr(E, Type);
15378}
15379
15380bool ArrayExprEvaluator::VisitCXXParenListInitExpr(
15381 const CXXParenListInitExpr *E) {
15382 assert(E->getType()->isConstantArrayType() &&
15383 "Expression result is not a constant array type");
15384
15385 return VisitCXXParenListOrInitListExpr(E, E->getInitExprs(),
15386 E->getArrayFiller());
15387}
15388
15389//===----------------------------------------------------------------------===//
15390// Integer Evaluation
15391//
15392// As a GNU extension, we support casting pointers to sufficiently-wide integer
15393// types and back in constant folding. Integer values are thus represented
15394// either as an integer-valued APValue, or as an lvalue-valued APValue.
15395//===----------------------------------------------------------------------===//
15396
15397namespace {
15398class IntExprEvaluator
15399 : public ExprEvaluatorBase<IntExprEvaluator> {
15400 APValue &Result;
15401public:
15402 IntExprEvaluator(EvalInfo &info, APValue &result)
15403 : ExprEvaluatorBaseTy(info), Result(result) {}
15404
15405 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
15406 assert(E->getType()->isIntegralOrEnumerationType() &&
15407 "Invalid evaluation result.");
15408 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
15409 "Invalid evaluation result.");
15410 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
15411 "Invalid evaluation result.");
15412 Result = APValue(SI);
15413 return true;
15414 }
15415 bool Success(const llvm::APSInt &SI, const Expr *E) {
15416 return Success(SI, E, Result);
15417 }
15418
15419 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
15420 assert(E->getType()->isIntegralOrEnumerationType() &&
15421 "Invalid evaluation result.");
15422 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
15423 "Invalid evaluation result.");
15424 Result = APValue(APSInt(I));
15425 Result.getInt().setIsUnsigned(
15427 return true;
15428 }
15429 bool Success(const llvm::APInt &I, const Expr *E) {
15430 return Success(I, E, Result);
15431 }
15432
15433 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
15434 assert(E->getType()->isIntegralOrEnumerationType() &&
15435 "Invalid evaluation result.");
15436 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
15437 return true;
15438 }
15439 bool Success(uint64_t Value, const Expr *E) {
15440 return Success(Value, E, Result);
15441 }
15442
15443 bool Success(CharUnits Size, const Expr *E) {
15444 return Success(Size.getQuantity(), E);
15445 }
15446
15447 bool Success(const APValue &V, const Expr *E) {
15448 // C++23 [expr.const]p8 If we have a variable that is unknown reference or
15449 // pointer allow further evaluation of the value.
15450 if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate() ||
15451 V.allowConstexprUnknown()) {
15452 Result = V;
15453 return true;
15454 }
15455 return Success(V.getInt(), E);
15456 }
15457
15458 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
15459
15460 friend std::optional<bool> EvaluateBuiltinIsWithinLifetime(IntExprEvaluator &,
15461 const CallExpr *);
15462
15463 //===--------------------------------------------------------------------===//
15464 // Visitor Methods
15465 //===--------------------------------------------------------------------===//
15466
15467 bool VisitIntegerLiteral(const IntegerLiteral *E) {
15468 return Success(E->getValue(), E);
15469 }
15470 bool VisitCharacterLiteral(const CharacterLiteral *E) {
15471 return Success(E->getValue(), E);
15472 }
15473
15474 bool CheckReferencedDecl(const Expr *E, const Decl *D);
15475 bool VisitDeclRefExpr(const DeclRefExpr *E) {
15476 if (CheckReferencedDecl(E, E->getDecl()))
15477 return true;
15478
15479 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
15480 }
15481 bool VisitMemberExpr(const MemberExpr *E) {
15482 if (CheckReferencedDecl(E, E->getMemberDecl())) {
15483 VisitIgnoredBaseExpression(E->getBase());
15484 return true;
15485 }
15486
15487 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
15488 }
15489
15490 bool VisitCallExpr(const CallExpr *E);
15491 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
15492 bool VisitBinaryOperator(const BinaryOperator *E);
15493 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
15494 bool VisitUnaryOperator(const UnaryOperator *E);
15495
15496 bool VisitCastExpr(const CastExpr* E);
15497 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
15498
15499 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
15500 return Success(E->getValue(), E);
15501 }
15502
15503 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
15504 return Success(E->getValue(), E);
15505 }
15506
15507 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
15508 if (Info.ArrayInitIndex == uint64_t(-1)) {
15509 // We were asked to evaluate this subexpression independent of the
15510 // enclosing ArrayInitLoopExpr. We can't do that.
15511 Info.FFDiag(E);
15512 return false;
15513 }
15514 return Success(Info.ArrayInitIndex, E);
15515 }
15516
15517 // Note, GNU defines __null as an integer, not a pointer.
15518 bool VisitGNUNullExpr(const GNUNullExpr *E) {
15519 return ZeroInitialization(E);
15520 }
15521
15522 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
15523 if (E->isStoredAsBoolean())
15524 return Success(E->getBoolValue(), E);
15525 if (E->getAPValue().isAbsent())
15526 return false;
15527 assert(E->getAPValue().isInt() && "APValue type not supported");
15528 return Success(E->getAPValue().getInt(), E);
15529 }
15530
15531 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
15532 return Success(E->getValue(), E);
15533 }
15534
15535 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
15536 return Success(E->getValue(), E);
15537 }
15538
15539 bool VisitOpenACCAsteriskSizeExpr(const OpenACCAsteriskSizeExpr *E) {
15540 // This should not be evaluated during constant expr evaluation, as it
15541 // should always be in an unevaluated context (the args list of a 'gang' or
15542 // 'tile' clause).
15543 return Error(E);
15544 }
15545
15546 bool VisitUnaryReal(const UnaryOperator *E);
15547 bool VisitUnaryImag(const UnaryOperator *E);
15548
15549 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
15550 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
15551 bool VisitSourceLocExpr(const SourceLocExpr *E);
15552 bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E);
15553 bool VisitRequiresExpr(const RequiresExpr *E);
15554 // FIXME: Missing: array subscript of vector, member of vector
15555};
15556
15557class FixedPointExprEvaluator
15558 : public ExprEvaluatorBase<FixedPointExprEvaluator> {
15559 APValue &Result;
15560
15561 public:
15562 FixedPointExprEvaluator(EvalInfo &info, APValue &result)
15563 : ExprEvaluatorBaseTy(info), Result(result) {}
15564
15565 bool Success(const llvm::APInt &I, const Expr *E) {
15566 return Success(
15567 APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
15568 }
15569
15570 bool Success(uint64_t Value, const Expr *E) {
15571 return Success(
15572 APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
15573 }
15574
15575 bool Success(const APValue &V, const Expr *E) {
15576 return Success(V.getFixedPoint(), E);
15577 }
15578
15579 bool Success(const APFixedPoint &V, const Expr *E) {
15580 assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
15581 assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
15582 "Invalid evaluation result.");
15583 Result = APValue(V);
15584 return true;
15585 }
15586
15587 bool ZeroInitialization(const Expr *E) {
15588 return Success(0, E);
15589 }
15590
15591 //===--------------------------------------------------------------------===//
15592 // Visitor Methods
15593 //===--------------------------------------------------------------------===//
15594
15595 bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
15596 return Success(E->getValue(), E);
15597 }
15598
15599 bool VisitCastExpr(const CastExpr *E);
15600 bool VisitUnaryOperator(const UnaryOperator *E);
15601 bool VisitBinaryOperator(const BinaryOperator *E);
15602};
15603} // end anonymous namespace
15604
15605/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
15606/// produce either the integer value or a pointer.
15607///
15608/// GCC has a heinous extension which folds casts between pointer types and
15609/// pointer-sized integral types. We support this by allowing the evaluation of
15610/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
15611/// Some simple arithmetic on such values is supported (they are treated much
15612/// like char*).
15614 EvalInfo &Info) {
15615 assert(!E->isValueDependent());
15616 assert(E->isPRValue() && E->getType()->isIntegralOrEnumerationType());
15617 return IntExprEvaluator(Info, Result).Visit(E);
15618}
15619
15620static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
15621 assert(!E->isValueDependent());
15622 APValue Val;
15623 if (!EvaluateIntegerOrLValue(E, Val, Info))
15624 return false;
15625 if (!Val.isInt()) {
15626 // FIXME: It would be better to produce the diagnostic for casting
15627 // a pointer to an integer.
15628 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
15629 return false;
15630 }
15631 Result = Val.getInt();
15632 return true;
15633}
15634
15635bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
15637 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
15638 return Success(Evaluated, E);
15639}
15640
15641static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
15642 EvalInfo &Info) {
15643 assert(!E->isValueDependent());
15644 if (E->getType()->isFixedPointType()) {
15645 APValue Val;
15646 if (!FixedPointExprEvaluator(Info, Val).Visit(E))
15647 return false;
15648 if (!Val.isFixedPoint())
15649 return false;
15650
15651 Result = Val.getFixedPoint();
15652 return true;
15653 }
15654 return false;
15655}
15656
15657static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
15658 EvalInfo &Info) {
15659 assert(!E->isValueDependent());
15660 if (E->getType()->isIntegerType()) {
15661 auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
15662 APSInt Val;
15663 if (!EvaluateInteger(E, Val, Info))
15664 return false;
15665 Result = APFixedPoint(Val, FXSema);
15666 return true;
15667 } else if (E->getType()->isFixedPointType()) {
15668 return EvaluateFixedPoint(E, Result, Info);
15669 }
15670 return false;
15671}
15672
15673/// Check whether the given declaration can be directly converted to an integral
15674/// rvalue. If not, no diagnostic is produced; there are other things we can
15675/// try.
15676bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
15677 // Enums are integer constant exprs.
15678 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
15679 // Check for signedness/width mismatches between E type and ECD value.
15680 bool SameSign = (ECD->getInitVal().isSigned()
15682 bool SameWidth = (ECD->getInitVal().getBitWidth()
15683 == Info.Ctx.getIntWidth(E->getType()));
15684 if (SameSign && SameWidth)
15685 return Success(ECD->getInitVal(), E);
15686 else {
15687 // Get rid of mismatch (otherwise Success assertions will fail)
15688 // by computing a new value matching the type of E.
15689 llvm::APSInt Val = ECD->getInitVal();
15690 if (!SameSign)
15691 Val.setIsSigned(!ECD->getInitVal().isSigned());
15692 if (!SameWidth)
15693 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
15694 return Success(Val, E);
15695 }
15696 }
15697 return false;
15698}
15699
15700/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
15701/// as GCC.
15703 const LangOptions &LangOpts) {
15704 assert(!T->isDependentType() && "unexpected dependent type");
15705
15706 QualType CanTy = T.getCanonicalType();
15707
15708 switch (CanTy->getTypeClass()) {
15709#define TYPE(ID, BASE)
15710#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
15711#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
15712#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
15713#include "clang/AST/TypeNodes.inc"
15714 case Type::Auto:
15715 case Type::DeducedTemplateSpecialization:
15716 llvm_unreachable("unexpected non-canonical or dependent type");
15717
15718 case Type::Builtin:
15719 switch (cast<BuiltinType>(CanTy)->getKind()) {
15720#define BUILTIN_TYPE(ID, SINGLETON_ID)
15721#define SIGNED_TYPE(ID, SINGLETON_ID) \
15722 case BuiltinType::ID: return GCCTypeClass::Integer;
15723#define FLOATING_TYPE(ID, SINGLETON_ID) \
15724 case BuiltinType::ID: return GCCTypeClass::RealFloat;
15725#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
15726 case BuiltinType::ID: break;
15727#include "clang/AST/BuiltinTypes.def"
15728 case BuiltinType::Void:
15729 return GCCTypeClass::Void;
15730
15731 case BuiltinType::Bool:
15732 return GCCTypeClass::Bool;
15733
15734 case BuiltinType::Char_U:
15735 case BuiltinType::UChar:
15736 case BuiltinType::WChar_U:
15737 case BuiltinType::Char8:
15738 case BuiltinType::Char16:
15739 case BuiltinType::Char32:
15740 case BuiltinType::UShort:
15741 case BuiltinType::UInt:
15742 case BuiltinType::ULong:
15743 case BuiltinType::ULongLong:
15744 case BuiltinType::UInt128:
15745 return GCCTypeClass::Integer;
15746
15747 case BuiltinType::UShortAccum:
15748 case BuiltinType::UAccum:
15749 case BuiltinType::ULongAccum:
15750 case BuiltinType::UShortFract:
15751 case BuiltinType::UFract:
15752 case BuiltinType::ULongFract:
15753 case BuiltinType::SatUShortAccum:
15754 case BuiltinType::SatUAccum:
15755 case BuiltinType::SatULongAccum:
15756 case BuiltinType::SatUShortFract:
15757 case BuiltinType::SatUFract:
15758 case BuiltinType::SatULongFract:
15759 return GCCTypeClass::None;
15760
15761 case BuiltinType::NullPtr:
15762
15763 case BuiltinType::ObjCId:
15764 case BuiltinType::ObjCClass:
15765 case BuiltinType::ObjCSel:
15766#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
15767 case BuiltinType::Id:
15768#include "clang/Basic/OpenCLImageTypes.def"
15769#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
15770 case BuiltinType::Id:
15771#include "clang/Basic/OpenCLExtensionTypes.def"
15772 case BuiltinType::OCLSampler:
15773 case BuiltinType::OCLEvent:
15774 case BuiltinType::OCLClkEvent:
15775 case BuiltinType::OCLQueue:
15776 case BuiltinType::OCLReserveID:
15777#define SVE_TYPE(Name, Id, SingletonId) \
15778 case BuiltinType::Id:
15779#include "clang/Basic/AArch64ACLETypes.def"
15780#define PPC_VECTOR_TYPE(Name, Id, Size) \
15781 case BuiltinType::Id:
15782#include "clang/Basic/PPCTypes.def"
15783#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
15784#include "clang/Basic/RISCVVTypes.def"
15785#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
15786#include "clang/Basic/WebAssemblyReferenceTypes.def"
15787#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
15788#include "clang/Basic/AMDGPUTypes.def"
15789#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
15790#include "clang/Basic/HLSLIntangibleTypes.def"
15791 return GCCTypeClass::None;
15792
15793 case BuiltinType::Dependent:
15794 llvm_unreachable("unexpected dependent type");
15795 };
15796 llvm_unreachable("unexpected placeholder type");
15797
15798 case Type::Enum:
15799 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
15800
15801 case Type::Pointer:
15802 case Type::ConstantArray:
15803 case Type::VariableArray:
15804 case Type::IncompleteArray:
15805 case Type::FunctionNoProto:
15806 case Type::FunctionProto:
15807 case Type::ArrayParameter:
15808 return GCCTypeClass::Pointer;
15809
15810 case Type::MemberPointer:
15811 return CanTy->isMemberDataPointerType()
15814
15815 case Type::Complex:
15816 return GCCTypeClass::Complex;
15817
15818 case Type::Record:
15819 return CanTy->isUnionType() ? GCCTypeClass::Union
15821
15822 case Type::Atomic:
15823 // GCC classifies _Atomic T the same as T.
15825 CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
15826
15827 case Type::Vector:
15828 case Type::ExtVector:
15829 return GCCTypeClass::Vector;
15830
15831 case Type::BlockPointer:
15832 case Type::ConstantMatrix:
15833 case Type::ObjCObject:
15834 case Type::ObjCInterface:
15835 case Type::ObjCObjectPointer:
15836 case Type::Pipe:
15837 case Type::HLSLAttributedResource:
15838 case Type::HLSLInlineSpirv:
15839 case Type::OverflowBehavior:
15840 // Classify all other types that don't fit into the regular
15841 // classification the same way.
15842 return GCCTypeClass::None;
15843
15844 case Type::BitInt:
15845 return GCCTypeClass::BitInt;
15846
15847 case Type::LValueReference:
15848 case Type::RValueReference:
15849 llvm_unreachable("invalid type for expression");
15850 }
15851
15852 llvm_unreachable("unexpected type class");
15853}
15854
15855/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
15856/// as GCC.
15857static GCCTypeClass
15859 // If no argument was supplied, default to None. This isn't
15860 // ideal, however it is what gcc does.
15861 if (E->getNumArgs() == 0)
15862 return GCCTypeClass::None;
15863
15864 // FIXME: Bizarrely, GCC treats a call with more than one argument as not
15865 // being an ICE, but still folds it to a constant using the type of the first
15866 // argument.
15867 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
15868}
15869
15870/// EvaluateBuiltinConstantPForLValue - Determine the result of
15871/// __builtin_constant_p when applied to the given pointer.
15872///
15873/// A pointer is only "constant" if it is null (or a pointer cast to integer)
15874/// or it points to the first character of a string literal.
15877 if (Base.isNull()) {
15878 // A null base is acceptable.
15879 return true;
15880 } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
15881 if (!isa<StringLiteral>(E))
15882 return false;
15883 return LV.getLValueOffset().isZero();
15884 } else if (Base.is<TypeInfoLValue>()) {
15885 // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
15886 // evaluate to true.
15887 return true;
15888 } else {
15889 // Any other base is not constant enough for GCC.
15890 return false;
15891 }
15892}
15893
15894/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
15895/// GCC as we can manage.
15896static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
15897 // This evaluation is not permitted to have side-effects, so evaluate it in
15898 // a speculative evaluation context.
15899 SpeculativeEvaluationRAII SpeculativeEval(Info);
15900
15901 // Constant-folding is always enabled for the operand of __builtin_constant_p
15902 // (even when the enclosing evaluation context otherwise requires a strict
15903 // language-specific constant expression).
15904 FoldConstant Fold(Info, true);
15905
15906 QualType ArgType = Arg->getType();
15907
15908 // __builtin_constant_p always has one operand. The rules which gcc follows
15909 // are not precisely documented, but are as follows:
15910 //
15911 // - If the operand is of integral, floating, complex or enumeration type,
15912 // and can be folded to a known value of that type, it returns 1.
15913 // - If the operand can be folded to a pointer to the first character
15914 // of a string literal (or such a pointer cast to an integral type)
15915 // or to a null pointer or an integer cast to a pointer, it returns 1.
15916 //
15917 // Otherwise, it returns 0.
15918 //
15919 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
15920 // its support for this did not work prior to GCC 9 and is not yet well
15921 // understood.
15922 if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
15923 ArgType->isAnyComplexType() || ArgType->isPointerType() ||
15924 ArgType->isNullPtrType()) {
15925 APValue V;
15926 if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) {
15927 Fold.keepDiagnostics();
15928 return false;
15929 }
15930
15931 // For a pointer (possibly cast to integer), there are special rules.
15932 if (V.getKind() == APValue::LValue)
15934
15935 // Otherwise, any constant value is good enough.
15936 return V.hasValue();
15937 }
15938
15939 // Anything else isn't considered to be sufficiently constant.
15940 return false;
15941}
15942
15943/// Retrieves the "underlying object type" of the given expression,
15944/// as used by __builtin_object_size.
15946 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
15947 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
15948 return VD->getType();
15949 } else if (const Expr *E = B.dyn_cast<const Expr*>()) {
15951 return E->getType();
15952 } else if (B.is<TypeInfoLValue>()) {
15953 return B.getTypeInfoType();
15954 } else if (B.is<DynamicAllocLValue>()) {
15955 return B.getDynamicAllocType();
15956 }
15957
15958 return QualType();
15959}
15960
15961/// A more selective version of E->IgnoreParenCasts for
15962/// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
15963/// to change the type of E.
15964/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
15965///
15966/// Always returns an RValue with a pointer representation.
15967static const Expr *ignorePointerCastsAndParens(const Expr *E) {
15968 assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
15969
15970 const Expr *NoParens = E->IgnoreParens();
15971 const auto *Cast = dyn_cast<CastExpr>(NoParens);
15972 if (Cast == nullptr)
15973 return NoParens;
15974
15975 // We only conservatively allow a few kinds of casts, because this code is
15976 // inherently a simple solution that seeks to support the common case.
15977 auto CastKind = Cast->getCastKind();
15978 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
15979 CastKind != CK_AddressSpaceConversion)
15980 return NoParens;
15981
15982 const auto *SubExpr = Cast->getSubExpr();
15983 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isPRValue())
15984 return NoParens;
15985 return ignorePointerCastsAndParens(SubExpr);
15986}
15987
15988/// Checks to see if the given LValue's Designator is at the end of the LValue's
15989/// record layout. e.g.
15990/// struct { struct { int a, b; } fst, snd; } obj;
15991/// obj.fst // no
15992/// obj.snd // yes
15993/// obj.fst.a // no
15994/// obj.fst.b // no
15995/// obj.snd.a // no
15996/// obj.snd.b // yes
15997///
15998/// Please note: this function is specialized for how __builtin_object_size
15999/// views "objects".
16000///
16001/// If this encounters an invalid RecordDecl or otherwise cannot determine the
16002/// correct result, it will always return true.
16003static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
16004 assert(!LVal.Designator.Invalid);
16005
16006 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD) {
16007 const RecordDecl *Parent = FD->getParent();
16008 if (Parent->isInvalidDecl() || Parent->isUnion())
16009 return true;
16010 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
16011 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
16012 };
16013
16014 auto &Base = LVal.getLValueBase();
16015 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
16016 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
16017 if (!IsLastOrInvalidFieldDecl(FD))
16018 return false;
16019 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
16020 for (auto *FD : IFD->chain()) {
16021 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD)))
16022 return false;
16023 }
16024 }
16025 }
16026
16027 unsigned I = 0;
16028 QualType BaseType = getType(Base);
16029 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
16030 // If we don't know the array bound, conservatively assume we're looking at
16031 // the final array element.
16032 ++I;
16033 if (BaseType->isIncompleteArrayType())
16034 BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
16035 else
16036 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
16037 }
16038
16039 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
16040 const auto &Entry = LVal.Designator.Entries[I];
16041 if (BaseType->isArrayType()) {
16042 // Because __builtin_object_size treats arrays as objects, we can ignore
16043 // the index iff this is the last array in the Designator.
16044 if (I + 1 == E)
16045 return true;
16046 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
16047 uint64_t Index = Entry.getAsArrayIndex();
16048 if (Index + 1 != CAT->getZExtSize())
16049 return false;
16050 BaseType = CAT->getElementType();
16051 } else if (BaseType->isAnyComplexType()) {
16052 const auto *CT = BaseType->castAs<ComplexType>();
16053 uint64_t Index = Entry.getAsArrayIndex();
16054 if (Index != 1)
16055 return false;
16056 BaseType = CT->getElementType();
16057 } else if (auto *FD = getAsField(Entry)) {
16058 if (!IsLastOrInvalidFieldDecl(FD))
16059 return false;
16060 BaseType = FD->getType();
16061 } else {
16062 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
16063 return false;
16064 }
16065 }
16066 return true;
16067}
16068
16069/// Tests to see if the LValue has a user-specified designator (that isn't
16070/// necessarily valid). Note that this always returns 'true' if the LValue has
16071/// an unsized array as its first designator entry, because there's currently no
16072/// way to tell if the user typed *foo or foo[0].
16073static bool refersToCompleteObject(const LValue &LVal) {
16074 if (LVal.Designator.Invalid)
16075 return false;
16076
16077 if (!LVal.Designator.Entries.empty())
16078 return LVal.Designator.isMostDerivedAnUnsizedArray();
16079
16080 if (!LVal.InvalidBase)
16081 return true;
16082
16083 // If `E` is a MemberExpr, then the first part of the designator is hiding in
16084 // the LValueBase.
16085 const auto *E = LVal.Base.dyn_cast<const Expr *>();
16086 return !E || !isa<MemberExpr>(E);
16087}
16088
16089/// Attempts to detect a user writing into a piece of memory that's impossible
16090/// to figure out the size of by just using types.
16091static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
16092 const SubobjectDesignator &Designator = LVal.Designator;
16093 // Notes:
16094 // - Users can only write off of the end when we have an invalid base. Invalid
16095 // bases imply we don't know where the memory came from.
16096 // - We used to be a bit more aggressive here; we'd only be conservative if
16097 // the array at the end was flexible, or if it had 0 or 1 elements. This
16098 // broke some common standard library extensions (PR30346), but was
16099 // otherwise seemingly fine. It may be useful to reintroduce this behavior
16100 // with some sort of list. OTOH, it seems that GCC is always
16101 // conservative with the last element in structs (if it's an array), so our
16102 // current behavior is more compatible than an explicit list approach would
16103 // be.
16104 auto isFlexibleArrayMember = [&] {
16106 FAMKind StrictFlexArraysLevel =
16107 Ctx.getLangOpts().getStrictFlexArraysLevel();
16108
16109 if (Designator.isMostDerivedAnUnsizedArray())
16110 return true;
16111
16112 if (StrictFlexArraysLevel == FAMKind::Default)
16113 return true;
16114
16115 if (Designator.getMostDerivedArraySize() == 0 &&
16116 StrictFlexArraysLevel != FAMKind::IncompleteOnly)
16117 return true;
16118
16119 if (Designator.getMostDerivedArraySize() == 1 &&
16120 StrictFlexArraysLevel == FAMKind::OneZeroOrIncomplete)
16121 return true;
16122
16123 return false;
16124 };
16125
16126 return LVal.InvalidBase &&
16127 Designator.Entries.size() == Designator.MostDerivedPathLength &&
16128 Designator.MostDerivedIsArrayElement && isFlexibleArrayMember() &&
16129 isDesignatorAtObjectEnd(Ctx, LVal);
16130}
16131
16132/// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
16133/// Fails if the conversion would cause loss of precision.
16134static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
16135 CharUnits &Result) {
16136 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
16137 if (Int.ugt(CharUnitsMax))
16138 return false;
16139 Result = CharUnits::fromQuantity(Int.getZExtValue());
16140 return true;
16141}
16142
16143/// If we're evaluating the object size of an instance of a struct that
16144/// contains a flexible array member, add the size of the initializer.
16145static void addFlexibleArrayMemberInitSize(EvalInfo &Info, const QualType &T,
16146 const LValue &LV, CharUnits &Size) {
16147 if (!T.isNull() && T->isStructureType() &&
16148 T->castAsRecordDecl()->hasFlexibleArrayMember())
16149 if (const auto *V = LV.getLValueBase().dyn_cast<const ValueDecl *>())
16150 if (const auto *VD = dyn_cast<VarDecl>(V))
16151 if (VD->hasInit())
16152 Size += VD->getFlexibleArrayInitChars(Info.Ctx);
16153}
16154
16155/// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
16156/// determine how many bytes exist from the beginning of the object to either
16157/// the end of the current subobject, or the end of the object itself, depending
16158/// on what the LValue looks like + the value of Type.
16159///
16160/// If this returns false, the value of Result is undefined.
16161static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
16162 unsigned Type, const LValue &LVal,
16163 CharUnits &EndOffset) {
16164 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
16165
16166 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
16167 if (Ty.isNull())
16168 return false;
16169
16170 Ty = Ty.getNonReferenceType();
16171
16172 if (Ty->isIncompleteType() || Ty->isFunctionType())
16173 return false;
16174
16175 return HandleSizeof(Info, ExprLoc, Ty, Result);
16176 };
16177
16178 // We want to evaluate the size of the entire object. This is a valid fallback
16179 // for when Type=1 and the designator is invalid, because we're asked for an
16180 // upper-bound.
16181 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
16182 // Type=3 wants a lower bound, so we can't fall back to this.
16183 if (Type == 3 && !DetermineForCompleteObject)
16184 return false;
16185
16186 llvm::APInt APEndOffset;
16187 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
16188 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
16189 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
16190
16191 if (LVal.InvalidBase)
16192 return false;
16193
16194 QualType BaseTy = getObjectType(LVal.getLValueBase());
16195 const bool Ret = CheckedHandleSizeof(BaseTy, EndOffset);
16196 addFlexibleArrayMemberInitSize(Info, BaseTy, LVal, EndOffset);
16197 return Ret;
16198 }
16199
16200 // We want to evaluate the size of a subobject.
16201 const SubobjectDesignator &Designator = LVal.Designator;
16202
16203 // The following is a moderately common idiom in C:
16204 //
16205 // struct Foo { int a; char c[1]; };
16206 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
16207 // strcpy(&F->c[0], Bar);
16208 //
16209 // In order to not break too much legacy code, we need to support it.
16210 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
16211 // If we can resolve this to an alloc_size call, we can hand that back,
16212 // because we know for certain how many bytes there are to write to.
16213 llvm::APInt APEndOffset;
16214 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
16215 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
16216 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
16217
16218 // If we cannot determine the size of the initial allocation, then we can't
16219 // given an accurate upper-bound. However, we are still able to give
16220 // conservative lower-bounds for Type=3.
16221 if (Type == 1)
16222 return false;
16223 }
16224
16225 CharUnits BytesPerElem;
16226 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
16227 return false;
16228
16229 // According to the GCC documentation, we want the size of the subobject
16230 // denoted by the pointer. But that's not quite right -- what we actually
16231 // want is the size of the immediately-enclosing array, if there is one.
16232 int64_t ElemsRemaining;
16233 if (Designator.MostDerivedIsArrayElement &&
16234 Designator.Entries.size() == Designator.MostDerivedPathLength) {
16235 uint64_t ArraySize = Designator.getMostDerivedArraySize();
16236 uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
16237 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
16238 } else {
16239 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
16240 }
16241
16242 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
16243 return true;
16244}
16245
16246/// Tries to evaluate the __builtin_object_size for @p E. If successful,
16247/// returns true and stores the result in @p Size.
16248///
16249/// If @p WasError is non-null, this will report whether the failure to evaluate
16250/// is to be treated as an Error in IntExprEvaluator.
16251static std::optional<uint64_t>
16252tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type, EvalInfo &Info) {
16253 // Determine the denoted object.
16254 LValue LVal;
16255 {
16256 // The operand of __builtin_object_size is never evaluated for side-effects.
16257 // If there are any, but we can determine the pointed-to object anyway, then
16258 // ignore the side-effects.
16259 SpeculativeEvaluationRAII SpeculativeEval(Info);
16260 IgnoreSideEffectsRAII Fold(Info);
16261
16262 if (E->isGLValue()) {
16263 // It's possible for us to be given GLValues if we're called via
16264 // Expr::tryEvaluateObjectSize.
16265 APValue RVal;
16266 if (!EvaluateAsRValue(Info, E, RVal))
16267 return std::nullopt;
16268 LVal.setFrom(Info.Ctx, RVal);
16269 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
16270 /*InvalidBaseOK=*/true))
16271 return std::nullopt;
16272 }
16273
16274 // If we point to before the start of the object, there are no accessible
16275 // bytes.
16276 if (LVal.getLValueOffset().isNegative())
16277 return 0;
16278
16279 CharUnits EndOffset;
16280 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
16281 return std::nullopt;
16282
16283 // If we've fallen outside of the end offset, just pretend there's nothing to
16284 // write to/read from.
16285 if (EndOffset <= LVal.getLValueOffset())
16286 return 0;
16287 return (EndOffset - LVal.getLValueOffset()).getQuantity();
16288}
16289
16290bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
16291 if (!IsConstantEvaluatedBuiltinCall(E))
16292 return ExprEvaluatorBaseTy::VisitCallExpr(E);
16293 return VisitBuiltinCallExpr(E, E->getBuiltinCallee());
16294}
16295
16296static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info,
16297 APValue &Val, APSInt &Alignment) {
16298 QualType SrcTy = E->getArg(0)->getType();
16299 if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment))
16300 return false;
16301 // Even though we are evaluating integer expressions we could get a pointer
16302 // argument for the __builtin_is_aligned() case.
16303 if (SrcTy->isPointerType()) {
16304 LValue Ptr;
16305 if (!EvaluatePointer(E->getArg(0), Ptr, Info))
16306 return false;
16307 Ptr.moveInto(Val);
16308 } else if (!SrcTy->isIntegralOrEnumerationType()) {
16309 Info.FFDiag(E->getArg(0));
16310 return false;
16311 } else {
16312 APSInt SrcInt;
16313 if (!EvaluateInteger(E->getArg(0), SrcInt, Info))
16314 return false;
16315 assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() &&
16316 "Bit widths must be the same");
16317 Val = APValue(SrcInt);
16318 }
16319 assert(Val.hasValue());
16320 return true;
16321}
16322
16323bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
16324 unsigned BuiltinOp) {
16325 auto EvalTestOp = [&](llvm::function_ref<bool(const APInt &, const APInt &)>
16326 Fn) {
16327 APValue SourceLHS, SourceRHS;
16328 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
16329 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
16330 return false;
16331
16332 unsigned SourceLen = SourceLHS.getVectorLength();
16333 const VectorType *VT = E->getArg(0)->getType()->castAs<VectorType>();
16334 QualType ElemQT = VT->getElementType();
16335 unsigned LaneWidth = Info.Ctx.getTypeSize(ElemQT);
16336
16337 APInt AWide(LaneWidth * SourceLen, 0);
16338 APInt BWide(LaneWidth * SourceLen, 0);
16339
16340 for (unsigned I = 0; I != SourceLen; ++I) {
16341 APInt ALane;
16342 APInt BLane;
16343 if (ElemQT->isIntegerType()) { // Get value.
16344 ALane = SourceLHS.getVectorElt(I).getInt();
16345 BLane = SourceRHS.getVectorElt(I).getInt();
16346 } else if (ElemQT->isFloatingType()) { // Get only sign bit.
16347 ALane =
16348 SourceLHS.getVectorElt(I).getFloat().bitcastToAPInt().isNegative();
16349 BLane =
16350 SourceRHS.getVectorElt(I).getFloat().bitcastToAPInt().isNegative();
16351 } else { // Must be integer or floating type.
16352 return false;
16353 }
16354 AWide.insertBits(ALane, I * LaneWidth);
16355 BWide.insertBits(BLane, I * LaneWidth);
16356 }
16357 return Success(Fn(AWide, BWide), E);
16358 };
16359
16360 auto HandleMaskBinOp =
16361 [&](llvm::function_ref<APSInt(const APSInt &, const APSInt &)> Fn)
16362 -> bool {
16363 APValue LHS, RHS;
16364 if (!Evaluate(LHS, Info, E->getArg(0)) ||
16365 !Evaluate(RHS, Info, E->getArg(1)))
16366 return false;
16367
16368 APSInt ResultInt = Fn(LHS.getInt(), RHS.getInt());
16369
16370 return Success(APValue(ResultInt), E);
16371 };
16372
16373 auto HandleCRC32 = [&](unsigned DataBytes) -> bool {
16374 APSInt CRC, Data;
16375 if (!EvaluateInteger(E->getArg(0), CRC, Info) ||
16376 !EvaluateInteger(E->getArg(1), Data, Info))
16377 return false;
16378
16379 uint64_t CRCVal = CRC.getZExtValue();
16380 uint64_t DataVal = Data.getZExtValue();
16381
16382 // CRC32C polynomial (iSCSI polynomial, bit-reversed)
16383 static const uint32_t CRC32C_POLY = 0x82F63B78;
16384
16385 // Process each byte
16386 uint32_t Result = static_cast<uint32_t>(CRCVal);
16387 for (unsigned I = 0; I != DataBytes; ++I) {
16388 uint8_t Byte = static_cast<uint8_t>((DataVal >> (I * 8)) & 0xFF);
16389 Result ^= Byte;
16390 for (int J = 0; J != 8; ++J) {
16391 Result = (Result >> 1) ^ ((Result & 1) ? CRC32C_POLY : 0);
16392 }
16393 }
16394
16395 return Success(Result, E);
16396 };
16397
16398 switch (BuiltinOp) {
16399 default:
16400 return false;
16401
16402 case X86::BI__builtin_ia32_crc32qi:
16403 return HandleCRC32(1);
16404 case X86::BI__builtin_ia32_crc32hi:
16405 return HandleCRC32(2);
16406 case X86::BI__builtin_ia32_crc32si:
16407 return HandleCRC32(4);
16408 case X86::BI__builtin_ia32_crc32di:
16409 return HandleCRC32(8);
16410
16411 case Builtin::BI__builtin_dynamic_object_size:
16412 case Builtin::BI__builtin_object_size: {
16413 // The type was checked when we built the expression.
16414 unsigned Type =
16415 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
16416 assert(Type <= 3 && "unexpected type");
16417
16418 if (std::optional<uint64_t> Size =
16420 return Success(*Size, E);
16421
16422 if (E->getArg(0)->HasSideEffects(Info.Ctx))
16423 return Success((Type & 2) ? 0 : -1, E);
16424
16425 // Expression had no side effects, but we couldn't statically determine the
16426 // size of the referenced object.
16427 switch (Info.EvalMode) {
16428 case EvaluationMode::ConstantExpression:
16429 case EvaluationMode::ConstantFold:
16430 case EvaluationMode::IgnoreSideEffects:
16431 // Leave it to IR generation.
16432 return Error(E);
16433 case EvaluationMode::ConstantExpressionUnevaluated:
16434 // Reduce it to a constant now.
16435 return Success((Type & 2) ? 0 : -1, E);
16436 }
16437
16438 llvm_unreachable("unexpected EvalMode");
16439 }
16440
16441 case Builtin::BI__builtin_os_log_format_buffer_size: {
16442 analyze_os_log::OSLogBufferLayout Layout;
16443 analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
16444 return Success(Layout.size().getQuantity(), E);
16445 }
16446
16447 case Builtin::BI__builtin_is_aligned: {
16448 APValue Src;
16449 APSInt Alignment;
16450 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
16451 return false;
16452 if (Src.isLValue()) {
16453 // If we evaluated a pointer, check the minimum known alignment.
16454 LValue Ptr;
16455 Ptr.setFrom(Info.Ctx, Src);
16456 CharUnits BaseAlignment = getBaseAlignment(Info, Ptr);
16457 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset);
16458 // We can return true if the known alignment at the computed offset is
16459 // greater than the requested alignment.
16460 assert(PtrAlign.isPowerOfTwo());
16461 assert(Alignment.isPowerOf2());
16462 if (PtrAlign.getQuantity() >= Alignment)
16463 return Success(1, E);
16464 // If the alignment is not known to be sufficient, some cases could still
16465 // be aligned at run time. However, if the requested alignment is less or
16466 // equal to the base alignment and the offset is not aligned, we know that
16467 // the run-time value can never be aligned.
16468 if (BaseAlignment.getQuantity() >= Alignment &&
16469 PtrAlign.getQuantity() < Alignment)
16470 return Success(0, E);
16471 // Otherwise we can't infer whether the value is sufficiently aligned.
16472 // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N)
16473 // in cases where we can't fully evaluate the pointer.
16474 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute)
16475 << Alignment;
16476 return false;
16477 }
16478 assert(Src.isInt());
16479 return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E);
16480 }
16481 case Builtin::BI__builtin_align_up: {
16482 APValue Src;
16483 APSInt Alignment;
16484 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
16485 return false;
16486 if (!Src.isInt())
16487 return Error(E);
16488 APSInt AlignedVal =
16489 APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1),
16490 Src.getInt().isUnsigned());
16491 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
16492 return Success(AlignedVal, E);
16493 }
16494 case Builtin::BI__builtin_align_down: {
16495 APValue Src;
16496 APSInt Alignment;
16497 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
16498 return false;
16499 if (!Src.isInt())
16500 return Error(E);
16501 APSInt AlignedVal =
16502 APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned());
16503 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
16504 return Success(AlignedVal, E);
16505 }
16506
16507 case Builtin::BI__builtin_bitreverseg:
16508 case Builtin::BI__builtin_bitreverse8:
16509 case Builtin::BI__builtin_bitreverse16:
16510 case Builtin::BI__builtin_bitreverse32:
16511 case Builtin::BI__builtin_bitreverse64:
16512 case Builtin::BI__builtin_elementwise_bitreverse: {
16513 APSInt Val;
16514 if (!EvaluateInteger(E->getArg(0), Val, Info))
16515 return false;
16516
16517 return Success(Val.reverseBits(), E);
16518 }
16519 case Builtin::BI__builtin_bswapg:
16520 case Builtin::BI__builtin_bswap16:
16521 case Builtin::BI__builtin_bswap32:
16522 case Builtin::BI__builtin_bswap64: {
16523 APSInt Val;
16524 if (!EvaluateInteger(E->getArg(0), Val, Info))
16525 return false;
16526 if (Val.getBitWidth() == 8 || Val.getBitWidth() == 1)
16527 return Success(Val, E);
16528
16529 return Success(Val.byteSwap(), E);
16530 }
16531
16532 case Builtin::BI__builtin_classify_type:
16533 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
16534
16535 case Builtin::BI__builtin_clrsb:
16536 case Builtin::BI__builtin_clrsbl:
16537 case Builtin::BI__builtin_clrsbll: {
16538 APSInt Val;
16539 if (!EvaluateInteger(E->getArg(0), Val, Info))
16540 return false;
16541
16542 return Success(Val.getBitWidth() - Val.getSignificantBits(), E);
16543 }
16544
16545 case Builtin::BI__builtin_clz:
16546 case Builtin::BI__builtin_clzl:
16547 case Builtin::BI__builtin_clzll:
16548 case Builtin::BI__builtin_clzs:
16549 case Builtin::BI__builtin_clzg:
16550 case Builtin::BI__builtin_elementwise_clzg:
16551 case Builtin::BI__lzcnt16: // Microsoft variants of count leading-zeroes
16552 case Builtin::BI__lzcnt:
16553 case Builtin::BI__lzcnt64: {
16554 APSInt Val;
16555 if (E->getArg(0)->getType()->isExtVectorBoolType()) {
16556 APValue Vec;
16557 if (!EvaluateVector(E->getArg(0), Vec, Info))
16558 return false;
16559 Val = ConvertBoolVectorToInt(Vec);
16560 } else if (!EvaluateInteger(E->getArg(0), Val, Info)) {
16561 return false;
16562 }
16563
16564 std::optional<APSInt> Fallback;
16565 if ((BuiltinOp == Builtin::BI__builtin_clzg ||
16566 BuiltinOp == Builtin::BI__builtin_elementwise_clzg) &&
16567 E->getNumArgs() > 1) {
16568 APSInt FallbackTemp;
16569 if (!EvaluateInteger(E->getArg(1), FallbackTemp, Info))
16570 return false;
16571 Fallback = FallbackTemp;
16572 }
16573
16574 if (!Val) {
16575 if (Fallback)
16576 return Success(*Fallback, E);
16577
16578 // When the argument is 0, the result of GCC builtins is undefined,
16579 // whereas for Microsoft intrinsics, the result is the bit-width of the
16580 // argument.
16581 bool ZeroIsUndefined = BuiltinOp != Builtin::BI__lzcnt16 &&
16582 BuiltinOp != Builtin::BI__lzcnt &&
16583 BuiltinOp != Builtin::BI__lzcnt64;
16584
16585 if (BuiltinOp == Builtin::BI__builtin_elementwise_clzg) {
16586 Info.FFDiag(E, diag::note_constexpr_countzeroes_zero)
16587 << /*IsTrailing=*/false;
16588 }
16589
16590 if (ZeroIsUndefined)
16591 return Error(E);
16592 }
16593
16594 return Success(Val.countl_zero(), E);
16595 }
16596
16597 case Builtin::BI__builtin_constant_p: {
16598 const Expr *Arg = E->getArg(0);
16599 if (EvaluateBuiltinConstantP(Info, Arg))
16600 return Success(true, E);
16601 if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
16602 // Outside a constant context, eagerly evaluate to false in the presence
16603 // of side-effects in order to avoid -Wunsequenced false-positives in
16604 // a branch on __builtin_constant_p(expr).
16605 return Success(false, E);
16606 }
16607 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
16608 return false;
16609 }
16610
16611 case Builtin::BI__noop:
16612 // __noop always evaluates successfully and returns 0.
16613 return Success(0, E);
16614
16615 case Builtin::BI__builtin_is_constant_evaluated: {
16616 const auto *Callee = Info.CurrentCall->getCallee();
16617 if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression &&
16618 (Info.CallStackDepth == 1 ||
16619 (Info.CallStackDepth == 2 && Callee->isInStdNamespace() &&
16620 Callee->getIdentifier() &&
16621 Callee->getIdentifier()->isStr("is_constant_evaluated")))) {
16622 // FIXME: Find a better way to avoid duplicated diagnostics.
16623 if (Info.EvalStatus.Diag)
16624 Info.report((Info.CallStackDepth == 1)
16625 ? E->getExprLoc()
16626 : Info.CurrentCall->getCallRange().getBegin(),
16627 diag::warn_is_constant_evaluated_always_true_constexpr)
16628 << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated"
16629 : "std::is_constant_evaluated");
16630 }
16631
16632 return Success(Info.InConstantContext, E);
16633 }
16634
16635 case Builtin::BI__builtin_is_within_lifetime:
16636 if (auto result = EvaluateBuiltinIsWithinLifetime(*this, E))
16637 return Success(*result, E);
16638 return false;
16639
16640 case Builtin::BI__builtin_ctz:
16641 case Builtin::BI__builtin_ctzl:
16642 case Builtin::BI__builtin_ctzll:
16643 case Builtin::BI__builtin_ctzs:
16644 case Builtin::BI__builtin_ctzg:
16645 case Builtin::BI__builtin_elementwise_ctzg: {
16646 APSInt Val;
16647 if (E->getArg(0)->getType()->isExtVectorBoolType()) {
16648 APValue Vec;
16649 if (!EvaluateVector(E->getArg(0), Vec, Info))
16650 return false;
16651 Val = ConvertBoolVectorToInt(Vec);
16652 } else if (!EvaluateInteger(E->getArg(0), Val, Info)) {
16653 return false;
16654 }
16655
16656 std::optional<APSInt> Fallback;
16657 if ((BuiltinOp == Builtin::BI__builtin_ctzg ||
16658 BuiltinOp == Builtin::BI__builtin_elementwise_ctzg) &&
16659 E->getNumArgs() > 1) {
16660 APSInt FallbackTemp;
16661 if (!EvaluateInteger(E->getArg(1), FallbackTemp, Info))
16662 return false;
16663 Fallback = FallbackTemp;
16664 }
16665
16666 if (!Val) {
16667 if (Fallback)
16668 return Success(*Fallback, E);
16669
16670 if (BuiltinOp == Builtin::BI__builtin_elementwise_ctzg) {
16671 Info.FFDiag(E, diag::note_constexpr_countzeroes_zero)
16672 << /*IsTrailing=*/true;
16673 }
16674 return Error(E);
16675 }
16676
16677 return Success(Val.countr_zero(), E);
16678 }
16679
16680 case Builtin::BI__builtin_eh_return_data_regno: {
16681 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
16682 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
16683 return Success(Operand, E);
16684 }
16685
16686 case Builtin::BI__builtin_elementwise_abs: {
16687 APSInt Val;
16688 if (!EvaluateInteger(E->getArg(0), Val, Info))
16689 return false;
16690
16691 return Success(Val.abs(), E);
16692 }
16693
16694 case Builtin::BI__builtin_expect:
16695 case Builtin::BI__builtin_expect_with_probability:
16696 return Visit(E->getArg(0));
16697
16698 case Builtin::BI__builtin_ptrauth_string_discriminator: {
16699 const auto *Literal =
16701 uint64_t Result = getPointerAuthStableSipHash(Literal->getString());
16702 return Success(Result, E);
16703 }
16704
16705 case Builtin::BI__builtin_infer_alloc_token: {
16706 // If we fail to infer a type, this fails to be a constant expression; this
16707 // can be checked with __builtin_constant_p(...).
16708 QualType AllocType = infer_alloc::inferPossibleType(E, Info.Ctx, nullptr);
16709 if (AllocType.isNull())
16710 return Error(
16711 E, diag::note_constexpr_infer_alloc_token_type_inference_failed);
16712 auto ATMD = infer_alloc::getAllocTokenMetadata(AllocType, Info.Ctx);
16713 if (!ATMD)
16714 return Error(E, diag::note_constexpr_infer_alloc_token_no_metadata);
16715 auto Mode =
16716 Info.getLangOpts().AllocTokenMode.value_or(llvm::DefaultAllocTokenMode);
16717 uint64_t BitWidth = Info.Ctx.getTypeSize(Info.Ctx.getSizeType());
16718 auto MaxTokensOpt = Info.getLangOpts().AllocTokenMax;
16719 uint64_t MaxTokens =
16720 MaxTokensOpt.value_or(0) ? *MaxTokensOpt : (~0ULL >> (64 - BitWidth));
16721 auto MaybeToken = llvm::getAllocToken(Mode, *ATMD, MaxTokens);
16722 if (!MaybeToken)
16723 return Error(E, diag::note_constexpr_infer_alloc_token_stateful_mode);
16724 return Success(llvm::APInt(BitWidth, *MaybeToken), E);
16725 }
16726
16727 case Builtin::BI__builtin_ffs:
16728 case Builtin::BI__builtin_ffsl:
16729 case Builtin::BI__builtin_ffsll: {
16730 APSInt Val;
16731 if (!EvaluateInteger(E->getArg(0), Val, Info))
16732 return false;
16733
16734 unsigned N = Val.countr_zero();
16735 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
16736 }
16737
16738 case Builtin::BI__builtin_fpclassify: {
16739 APFloat Val(0.0);
16740 if (!EvaluateFloat(E->getArg(5), Val, Info))
16741 return false;
16742 unsigned Arg;
16743 switch (Val.getCategory()) {
16744 case APFloat::fcNaN: Arg = 0; break;
16745 case APFloat::fcInfinity: Arg = 1; break;
16746 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
16747 case APFloat::fcZero: Arg = 4; break;
16748 }
16749 return Visit(E->getArg(Arg));
16750 }
16751
16752 case Builtin::BI__builtin_isinf_sign: {
16753 APFloat Val(0.0);
16754 return EvaluateFloat(E->getArg(0), Val, Info) &&
16755 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
16756 }
16757
16758 case Builtin::BI__builtin_isinf: {
16759 APFloat Val(0.0);
16760 return EvaluateFloat(E->getArg(0), Val, Info) &&
16761 Success(Val.isInfinity() ? 1 : 0, E);
16762 }
16763
16764 case Builtin::BI__builtin_isfinite: {
16765 APFloat Val(0.0);
16766 return EvaluateFloat(E->getArg(0), Val, Info) &&
16767 Success(Val.isFinite() ? 1 : 0, E);
16768 }
16769
16770 case Builtin::BI__builtin_isnan: {
16771 APFloat Val(0.0);
16772 return EvaluateFloat(E->getArg(0), Val, Info) &&
16773 Success(Val.isNaN() ? 1 : 0, E);
16774 }
16775
16776 case Builtin::BI__builtin_isnormal: {
16777 APFloat Val(0.0);
16778 return EvaluateFloat(E->getArg(0), Val, Info) &&
16779 Success(Val.isNormal() ? 1 : 0, E);
16780 }
16781
16782 case Builtin::BI__builtin_issubnormal: {
16783 APFloat Val(0.0);
16784 return EvaluateFloat(E->getArg(0), Val, Info) &&
16785 Success(Val.isDenormal() ? 1 : 0, E);
16786 }
16787
16788 case Builtin::BI__builtin_iszero: {
16789 APFloat Val(0.0);
16790 return EvaluateFloat(E->getArg(0), Val, Info) &&
16791 Success(Val.isZero() ? 1 : 0, E);
16792 }
16793
16794 case Builtin::BI__builtin_signbit:
16795 case Builtin::BI__builtin_signbitf:
16796 case Builtin::BI__builtin_signbitl: {
16797 APFloat Val(0.0);
16798 return EvaluateFloat(E->getArg(0), Val, Info) &&
16799 Success(Val.isNegative() ? 1 : 0, E);
16800 }
16801
16802 case Builtin::BI__builtin_isgreater:
16803 case Builtin::BI__builtin_isgreaterequal:
16804 case Builtin::BI__builtin_isless:
16805 case Builtin::BI__builtin_islessequal:
16806 case Builtin::BI__builtin_islessgreater:
16807 case Builtin::BI__builtin_isunordered: {
16808 APFloat LHS(0.0);
16809 APFloat RHS(0.0);
16810 if (!EvaluateFloat(E->getArg(0), LHS, Info) ||
16811 !EvaluateFloat(E->getArg(1), RHS, Info))
16812 return false;
16813
16814 return Success(
16815 [&] {
16816 switch (BuiltinOp) {
16817 case Builtin::BI__builtin_isgreater:
16818 return LHS > RHS;
16819 case Builtin::BI__builtin_isgreaterequal:
16820 return LHS >= RHS;
16821 case Builtin::BI__builtin_isless:
16822 return LHS < RHS;
16823 case Builtin::BI__builtin_islessequal:
16824 return LHS <= RHS;
16825 case Builtin::BI__builtin_islessgreater: {
16826 APFloat::cmpResult cmp = LHS.compare(RHS);
16827 return cmp == APFloat::cmpResult::cmpLessThan ||
16828 cmp == APFloat::cmpResult::cmpGreaterThan;
16829 }
16830 case Builtin::BI__builtin_isunordered:
16831 return LHS.compare(RHS) == APFloat::cmpResult::cmpUnordered;
16832 default:
16833 llvm_unreachable("Unexpected builtin ID: Should be a floating "
16834 "point comparison function");
16835 }
16836 }()
16837 ? 1
16838 : 0,
16839 E);
16840 }
16841
16842 case Builtin::BI__builtin_issignaling: {
16843 APFloat Val(0.0);
16844 return EvaluateFloat(E->getArg(0), Val, Info) &&
16845 Success(Val.isSignaling() ? 1 : 0, E);
16846 }
16847
16848 case Builtin::BI__builtin_isfpclass: {
16849 APSInt MaskVal;
16850 if (!EvaluateInteger(E->getArg(1), MaskVal, Info))
16851 return false;
16852 unsigned Test = static_cast<llvm::FPClassTest>(MaskVal.getZExtValue());
16853 APFloat Val(0.0);
16854 return EvaluateFloat(E->getArg(0), Val, Info) &&
16855 Success((Val.classify() & Test) ? 1 : 0, E);
16856 }
16857
16858 case Builtin::BI__builtin_parity:
16859 case Builtin::BI__builtin_parityl:
16860 case Builtin::BI__builtin_parityll: {
16861 APSInt Val;
16862 if (!EvaluateInteger(E->getArg(0), Val, Info))
16863 return false;
16864
16865 return Success(Val.popcount() % 2, E);
16866 }
16867
16868 case Builtin::BI__builtin_abs:
16869 case Builtin::BI__builtin_labs:
16870 case Builtin::BI__builtin_llabs: {
16871 APSInt Val;
16872 if (!EvaluateInteger(E->getArg(0), Val, Info))
16873 return false;
16874 if (Val == APSInt(APInt::getSignedMinValue(Val.getBitWidth()),
16875 /*IsUnsigned=*/false))
16876 return false;
16877 if (Val.isNegative())
16878 Val.negate();
16879 return Success(Val, E);
16880 }
16881
16882 case Builtin::BI__builtin_popcount:
16883 case Builtin::BI__builtin_popcountl:
16884 case Builtin::BI__builtin_popcountll:
16885 case Builtin::BI__builtin_popcountg:
16886 case Builtin::BI__builtin_elementwise_popcount:
16887 case Builtin::BI__popcnt16: // Microsoft variants of popcount
16888 case Builtin::BI__popcnt:
16889 case Builtin::BI__popcnt64: {
16890 APSInt Val;
16891 if (E->getArg(0)->getType()->isExtVectorBoolType()) {
16892 APValue Vec;
16893 if (!EvaluateVector(E->getArg(0), Vec, Info))
16894 return false;
16895 Val = ConvertBoolVectorToInt(Vec);
16896 } else if (!EvaluateInteger(E->getArg(0), Val, Info)) {
16897 return false;
16898 }
16899
16900 return Success(Val.popcount(), E);
16901 }
16902
16903 case Builtin::BI__builtin_rotateleft8:
16904 case Builtin::BI__builtin_rotateleft16:
16905 case Builtin::BI__builtin_rotateleft32:
16906 case Builtin::BI__builtin_rotateleft64:
16907 case Builtin::BI__builtin_rotateright8:
16908 case Builtin::BI__builtin_rotateright16:
16909 case Builtin::BI__builtin_rotateright32:
16910 case Builtin::BI__builtin_rotateright64:
16911 case Builtin::BI__builtin_stdc_rotate_left:
16912 case Builtin::BI__builtin_stdc_rotate_right:
16913 case Builtin::BIstdc_rotate_left_uc:
16914 case Builtin::BIstdc_rotate_left_us:
16915 case Builtin::BIstdc_rotate_left_ui:
16916 case Builtin::BIstdc_rotate_left_ul:
16917 case Builtin::BIstdc_rotate_left_ull:
16918 case Builtin::BIstdc_rotate_right_uc:
16919 case Builtin::BIstdc_rotate_right_us:
16920 case Builtin::BIstdc_rotate_right_ui:
16921 case Builtin::BIstdc_rotate_right_ul:
16922 case Builtin::BIstdc_rotate_right_ull:
16923 case Builtin::BI_rotl8: // Microsoft variants of rotate left
16924 case Builtin::BI_rotl16:
16925 case Builtin::BI_rotl:
16926 case Builtin::BI_lrotl:
16927 case Builtin::BI_rotl64:
16928 case Builtin::BI_rotr8: // Microsoft variants of rotate right
16929 case Builtin::BI_rotr16:
16930 case Builtin::BI_rotr:
16931 case Builtin::BI_lrotr:
16932 case Builtin::BI_rotr64: {
16933 APSInt Value, Amount;
16934 if (!EvaluateInteger(E->getArg(0), Value, Info) ||
16935 !EvaluateInteger(E->getArg(1), Amount, Info))
16936 return false;
16937
16938 Amount = NormalizeRotateAmount(Value, Amount);
16939
16940 switch (BuiltinOp) {
16941 case Builtin::BI__builtin_rotateright8:
16942 case Builtin::BI__builtin_rotateright16:
16943 case Builtin::BI__builtin_rotateright32:
16944 case Builtin::BI__builtin_rotateright64:
16945 case Builtin::BI__builtin_stdc_rotate_right:
16946 case Builtin::BIstdc_rotate_right_uc:
16947 case Builtin::BIstdc_rotate_right_us:
16948 case Builtin::BIstdc_rotate_right_ui:
16949 case Builtin::BIstdc_rotate_right_ul:
16950 case Builtin::BIstdc_rotate_right_ull:
16951 case Builtin::BI_rotr8:
16952 case Builtin::BI_rotr16:
16953 case Builtin::BI_rotr:
16954 case Builtin::BI_lrotr:
16955 case Builtin::BI_rotr64:
16956 return Success(
16957 APSInt(Value.rotr(Amount.getZExtValue()), Value.isUnsigned()), E);
16958 default:
16959 return Success(
16960 APSInt(Value.rotl(Amount.getZExtValue()), Value.isUnsigned()), E);
16961 }
16962 }
16963
16964 case Builtin::BIstdc_leading_zeros_uc:
16965 case Builtin::BIstdc_leading_zeros_us:
16966 case Builtin::BIstdc_leading_zeros_ui:
16967 case Builtin::BIstdc_leading_zeros_ul:
16968 case Builtin::BIstdc_leading_zeros_ull:
16969 case Builtin::BIstdc_leading_ones_uc:
16970 case Builtin::BIstdc_leading_ones_us:
16971 case Builtin::BIstdc_leading_ones_ui:
16972 case Builtin::BIstdc_leading_ones_ul:
16973 case Builtin::BIstdc_leading_ones_ull:
16974 case Builtin::BIstdc_trailing_zeros_uc:
16975 case Builtin::BIstdc_trailing_zeros_us:
16976 case Builtin::BIstdc_trailing_zeros_ui:
16977 case Builtin::BIstdc_trailing_zeros_ul:
16978 case Builtin::BIstdc_trailing_zeros_ull:
16979 case Builtin::BIstdc_trailing_ones_uc:
16980 case Builtin::BIstdc_trailing_ones_us:
16981 case Builtin::BIstdc_trailing_ones_ui:
16982 case Builtin::BIstdc_trailing_ones_ul:
16983 case Builtin::BIstdc_trailing_ones_ull:
16984 case Builtin::BIstdc_first_leading_zero_uc:
16985 case Builtin::BIstdc_first_leading_zero_us:
16986 case Builtin::BIstdc_first_leading_zero_ui:
16987 case Builtin::BIstdc_first_leading_zero_ul:
16988 case Builtin::BIstdc_first_leading_zero_ull:
16989 case Builtin::BIstdc_first_leading_one_uc:
16990 case Builtin::BIstdc_first_leading_one_us:
16991 case Builtin::BIstdc_first_leading_one_ui:
16992 case Builtin::BIstdc_first_leading_one_ul:
16993 case Builtin::BIstdc_first_leading_one_ull:
16994 case Builtin::BIstdc_first_trailing_zero_uc:
16995 case Builtin::BIstdc_first_trailing_zero_us:
16996 case Builtin::BIstdc_first_trailing_zero_ui:
16997 case Builtin::BIstdc_first_trailing_zero_ul:
16998 case Builtin::BIstdc_first_trailing_zero_ull:
16999 case Builtin::BIstdc_first_trailing_one_uc:
17000 case Builtin::BIstdc_first_trailing_one_us:
17001 case Builtin::BIstdc_first_trailing_one_ui:
17002 case Builtin::BIstdc_first_trailing_one_ul:
17003 case Builtin::BIstdc_first_trailing_one_ull:
17004 case Builtin::BIstdc_count_zeros_uc:
17005 case Builtin::BIstdc_count_zeros_us:
17006 case Builtin::BIstdc_count_zeros_ui:
17007 case Builtin::BIstdc_count_zeros_ul:
17008 case Builtin::BIstdc_count_zeros_ull:
17009 case Builtin::BIstdc_count_ones_uc:
17010 case Builtin::BIstdc_count_ones_us:
17011 case Builtin::BIstdc_count_ones_ui:
17012 case Builtin::BIstdc_count_ones_ul:
17013 case Builtin::BIstdc_count_ones_ull:
17014 case Builtin::BIstdc_has_single_bit_uc:
17015 case Builtin::BIstdc_has_single_bit_us:
17016 case Builtin::BIstdc_has_single_bit_ui:
17017 case Builtin::BIstdc_has_single_bit_ul:
17018 case Builtin::BIstdc_has_single_bit_ull:
17019 case Builtin::BIstdc_bit_width_uc:
17020 case Builtin::BIstdc_bit_width_us:
17021 case Builtin::BIstdc_bit_width_ui:
17022 case Builtin::BIstdc_bit_width_ul:
17023 case Builtin::BIstdc_bit_width_ull:
17024 case Builtin::BIstdc_bit_floor_uc:
17025 case Builtin::BIstdc_bit_floor_us:
17026 case Builtin::BIstdc_bit_floor_ui:
17027 case Builtin::BIstdc_bit_floor_ul:
17028 case Builtin::BIstdc_bit_floor_ull:
17029 case Builtin::BIstdc_bit_ceil_uc:
17030 case Builtin::BIstdc_bit_ceil_us:
17031 case Builtin::BIstdc_bit_ceil_ui:
17032 case Builtin::BIstdc_bit_ceil_ul:
17033 case Builtin::BIstdc_bit_ceil_ull:
17034 case Builtin::BI__builtin_stdc_leading_zeros:
17035 case Builtin::BI__builtin_stdc_leading_ones:
17036 case Builtin::BI__builtin_stdc_trailing_zeros:
17037 case Builtin::BI__builtin_stdc_trailing_ones:
17038 case Builtin::BI__builtin_stdc_first_leading_zero:
17039 case Builtin::BI__builtin_stdc_first_leading_one:
17040 case Builtin::BI__builtin_stdc_first_trailing_zero:
17041 case Builtin::BI__builtin_stdc_first_trailing_one:
17042 case Builtin::BI__builtin_stdc_count_zeros:
17043 case Builtin::BI__builtin_stdc_count_ones:
17044 case Builtin::BI__builtin_stdc_has_single_bit:
17045 case Builtin::BI__builtin_stdc_bit_width:
17046 case Builtin::BI__builtin_stdc_bit_floor:
17047 case Builtin::BI__builtin_stdc_bit_ceil: {
17048 APSInt Val;
17049 if (!EvaluateInteger(E->getArg(0), Val, Info))
17050 return false;
17051
17052 unsigned BitWidth = Val.getBitWidth();
17053 const unsigned ResBitWidth = Info.Ctx.getIntWidth(E->getType());
17054
17055 switch (BuiltinOp) {
17056 case Builtin::BIstdc_leading_zeros_uc:
17057 case Builtin::BIstdc_leading_zeros_us:
17058 case Builtin::BIstdc_leading_zeros_ui:
17059 case Builtin::BIstdc_leading_zeros_ul:
17060 case Builtin::BIstdc_leading_zeros_ull:
17061 case Builtin::BI__builtin_stdc_leading_zeros:
17062 return Success(APInt(ResBitWidth, Val.countl_zero()), E);
17063 case Builtin::BIstdc_leading_ones_uc:
17064 case Builtin::BIstdc_leading_ones_us:
17065 case Builtin::BIstdc_leading_ones_ui:
17066 case Builtin::BIstdc_leading_ones_ul:
17067 case Builtin::BIstdc_leading_ones_ull:
17068 case Builtin::BI__builtin_stdc_leading_ones:
17069 return Success(APInt(ResBitWidth, Val.countl_one()), E);
17070 case Builtin::BIstdc_trailing_zeros_uc:
17071 case Builtin::BIstdc_trailing_zeros_us:
17072 case Builtin::BIstdc_trailing_zeros_ui:
17073 case Builtin::BIstdc_trailing_zeros_ul:
17074 case Builtin::BIstdc_trailing_zeros_ull:
17075 case Builtin::BI__builtin_stdc_trailing_zeros:
17076 return Success(APInt(ResBitWidth, Val.countr_zero()), E);
17077 case Builtin::BIstdc_trailing_ones_uc:
17078 case Builtin::BIstdc_trailing_ones_us:
17079 case Builtin::BIstdc_trailing_ones_ui:
17080 case Builtin::BIstdc_trailing_ones_ul:
17081 case Builtin::BIstdc_trailing_ones_ull:
17082 case Builtin::BI__builtin_stdc_trailing_ones:
17083 return Success(APInt(ResBitWidth, Val.countr_one()), E);
17084 case Builtin::BIstdc_first_leading_zero_uc:
17085 case Builtin::BIstdc_first_leading_zero_us:
17086 case Builtin::BIstdc_first_leading_zero_ui:
17087 case Builtin::BIstdc_first_leading_zero_ul:
17088 case Builtin::BIstdc_first_leading_zero_ull:
17089 case Builtin::BI__builtin_stdc_first_leading_zero:
17090 return Success(
17091 APInt(ResBitWidth, Val.isAllOnes() ? 0 : Val.countl_one() + 1), E);
17092 case Builtin::BIstdc_first_leading_one_uc:
17093 case Builtin::BIstdc_first_leading_one_us:
17094 case Builtin::BIstdc_first_leading_one_ui:
17095 case Builtin::BIstdc_first_leading_one_ul:
17096 case Builtin::BIstdc_first_leading_one_ull:
17097 case Builtin::BI__builtin_stdc_first_leading_one:
17098 return Success(
17099 APInt(ResBitWidth, Val.isZero() ? 0 : Val.countl_zero() + 1), E);
17100 case Builtin::BIstdc_first_trailing_zero_uc:
17101 case Builtin::BIstdc_first_trailing_zero_us:
17102 case Builtin::BIstdc_first_trailing_zero_ui:
17103 case Builtin::BIstdc_first_trailing_zero_ul:
17104 case Builtin::BIstdc_first_trailing_zero_ull:
17105 case Builtin::BI__builtin_stdc_first_trailing_zero:
17106 return Success(
17107 APInt(ResBitWidth, Val.isAllOnes() ? 0 : Val.countr_one() + 1), E);
17108 case Builtin::BIstdc_first_trailing_one_uc:
17109 case Builtin::BIstdc_first_trailing_one_us:
17110 case Builtin::BIstdc_first_trailing_one_ui:
17111 case Builtin::BIstdc_first_trailing_one_ul:
17112 case Builtin::BIstdc_first_trailing_one_ull:
17113 case Builtin::BI__builtin_stdc_first_trailing_one:
17114 return Success(
17115 APInt(ResBitWidth, Val.isZero() ? 0 : Val.countr_zero() + 1), E);
17116 case Builtin::BIstdc_count_zeros_uc:
17117 case Builtin::BIstdc_count_zeros_us:
17118 case Builtin::BIstdc_count_zeros_ui:
17119 case Builtin::BIstdc_count_zeros_ul:
17120 case Builtin::BIstdc_count_zeros_ull:
17121 case Builtin::BI__builtin_stdc_count_zeros: {
17122 APInt Cnt(ResBitWidth, BitWidth - Val.popcount());
17123 return Success(APSInt(Cnt, /*IsUnsigned*/ true), E);
17124 }
17125 case Builtin::BIstdc_count_ones_uc:
17126 case Builtin::BIstdc_count_ones_us:
17127 case Builtin::BIstdc_count_ones_ui:
17128 case Builtin::BIstdc_count_ones_ul:
17129 case Builtin::BIstdc_count_ones_ull:
17130 case Builtin::BI__builtin_stdc_count_ones: {
17131 APInt Cnt(ResBitWidth, Val.popcount());
17132 return Success(APSInt(Cnt, /*IsUnsigned*/ true), E);
17133 }
17134 case Builtin::BIstdc_has_single_bit_uc:
17135 case Builtin::BIstdc_has_single_bit_us:
17136 case Builtin::BIstdc_has_single_bit_ui:
17137 case Builtin::BIstdc_has_single_bit_ul:
17138 case Builtin::BIstdc_has_single_bit_ull:
17139 case Builtin::BI__builtin_stdc_has_single_bit: {
17140 APInt Res(ResBitWidth, Val.popcount() == 1 ? 1 : 0);
17141 return Success(APSInt(Res, /*IsUnsigned*/ true), E);
17142 }
17143 case Builtin::BIstdc_bit_width_uc:
17144 case Builtin::BIstdc_bit_width_us:
17145 case Builtin::BIstdc_bit_width_ui:
17146 case Builtin::BIstdc_bit_width_ul:
17147 case Builtin::BIstdc_bit_width_ull:
17148 case Builtin::BI__builtin_stdc_bit_width:
17149 return Success(APInt(ResBitWidth, BitWidth - Val.countl_zero()), E);
17150 case Builtin::BIstdc_bit_floor_uc:
17151 case Builtin::BIstdc_bit_floor_us:
17152 case Builtin::BIstdc_bit_floor_ui:
17153 case Builtin::BIstdc_bit_floor_ul:
17154 case Builtin::BIstdc_bit_floor_ull:
17155 case Builtin::BI__builtin_stdc_bit_floor: {
17156 if (Val.isZero())
17157 return Success(APInt(BitWidth, 0), E);
17158 unsigned Exp = BitWidth - Val.countl_zero() - 1;
17159 return Success(
17160 APSInt(APInt::getOneBitSet(BitWidth, Exp), /*IsUnsigned*/ true), E);
17161 }
17162 case Builtin::BIstdc_bit_ceil_uc:
17163 case Builtin::BIstdc_bit_ceil_us:
17164 case Builtin::BIstdc_bit_ceil_ui:
17165 case Builtin::BIstdc_bit_ceil_ul:
17166 case Builtin::BIstdc_bit_ceil_ull:
17167 case Builtin::BI__builtin_stdc_bit_ceil: {
17168 if (Val.ule(1))
17169 return Success(APSInt(APInt(BitWidth, 1), /*IsUnsigned*/ true), E);
17170 APInt ValMinusOne = Val - 1;
17171 unsigned LZ = ValMinusOne.countl_zero();
17172 if (LZ == 0)
17173 return Success(APSInt(APInt(BitWidth, 0), /*IsUnsigned*/ true),
17174 E); // overflows; wrap to 0
17175 APInt Result = APInt::getOneBitSet(BitWidth, BitWidth - LZ);
17176 return Success(APSInt(Result, /*IsUnsigned*/ true), E);
17177 }
17178 default:
17179 llvm_unreachable("Unknown stdc builtin");
17180 }
17181 }
17182
17183 case Builtin::BI__builtin_elementwise_add_sat: {
17184 APSInt LHS, RHS;
17185 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
17186 !EvaluateInteger(E->getArg(1), RHS, Info))
17187 return false;
17188
17189 APInt Result = LHS.isSigned() ? LHS.sadd_sat(RHS) : LHS.uadd_sat(RHS);
17190 return Success(APSInt(Result, !LHS.isSigned()), E);
17191 }
17192 case Builtin::BI__builtin_elementwise_sub_sat: {
17193 APSInt LHS, RHS;
17194 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
17195 !EvaluateInteger(E->getArg(1), RHS, Info))
17196 return false;
17197
17198 APInt Result = LHS.isSigned() ? LHS.ssub_sat(RHS) : LHS.usub_sat(RHS);
17199 return Success(APSInt(Result, !LHS.isSigned()), E);
17200 }
17201 case Builtin::BI__builtin_elementwise_max: {
17202 APSInt LHS, RHS;
17203 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
17204 !EvaluateInteger(E->getArg(1), RHS, Info))
17205 return false;
17206
17207 APInt Result = std::max(LHS, RHS);
17208 return Success(APSInt(Result, !LHS.isSigned()), E);
17209 }
17210 case Builtin::BI__builtin_elementwise_min: {
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 = std::min(LHS, RHS);
17217 return Success(APSInt(Result, !LHS.isSigned()), E);
17218 }
17219 case Builtin::BI__builtin_elementwise_fshl:
17220 case Builtin::BI__builtin_elementwise_fshr: {
17221 APSInt Hi, Lo, Shift;
17222 if (!EvaluateInteger(E->getArg(0), Hi, Info) ||
17223 !EvaluateInteger(E->getArg(1), Lo, Info) ||
17224 !EvaluateInteger(E->getArg(2), Shift, Info))
17225 return false;
17226
17227 switch (BuiltinOp) {
17228 case Builtin::BI__builtin_elementwise_fshl: {
17229 APSInt Result(llvm::APIntOps::fshl(Hi, Lo, Shift), Hi.isUnsigned());
17230 return Success(Result, E);
17231 }
17232 case Builtin::BI__builtin_elementwise_fshr: {
17233 APSInt Result(llvm::APIntOps::fshr(Hi, Lo, Shift), Hi.isUnsigned());
17234 return Success(Result, E);
17235 }
17236 }
17237 llvm_unreachable("Fully covered switch above");
17238 }
17239 case Builtin::BIstrlen:
17240 case Builtin::BIwcslen:
17241 // A call to strlen is not a constant expression.
17242 if (Info.getLangOpts().CPlusPlus11)
17243 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
17244 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
17245 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
17246 else
17247 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
17248 [[fallthrough]];
17249 case Builtin::BI__builtin_strlen:
17250 case Builtin::BI__builtin_wcslen: {
17251 // As an extension, we support __builtin_strlen() as a constant expression,
17252 // and support folding strlen() to a constant.
17253 if (std::optional<uint64_t> StrLen =
17254 EvaluateBuiltinStrLen(E->getArg(0), Info))
17255 return Success(*StrLen, E);
17256 return false;
17257 }
17258
17259 case Builtin::BIstrcmp:
17260 case Builtin::BIwcscmp:
17261 case Builtin::BIstrncmp:
17262 case Builtin::BIwcsncmp:
17263 case Builtin::BImemcmp:
17264 case Builtin::BIbcmp:
17265 case Builtin::BIwmemcmp:
17266 // A call to strlen is not a constant expression.
17267 if (Info.getLangOpts().CPlusPlus11)
17268 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
17269 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
17270 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
17271 else
17272 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
17273 [[fallthrough]];
17274 case Builtin::BI__builtin_strcmp:
17275 case Builtin::BI__builtin_wcscmp:
17276 case Builtin::BI__builtin_strncmp:
17277 case Builtin::BI__builtin_wcsncmp:
17278 case Builtin::BI__builtin_memcmp:
17279 case Builtin::BI__builtin_bcmp:
17280 case Builtin::BI__builtin_wmemcmp: {
17281 LValue String1, String2;
17282 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
17283 !EvaluatePointer(E->getArg(1), String2, Info))
17284 return false;
17285
17286 uint64_t MaxLength = uint64_t(-1);
17287 if (BuiltinOp != Builtin::BIstrcmp &&
17288 BuiltinOp != Builtin::BIwcscmp &&
17289 BuiltinOp != Builtin::BI__builtin_strcmp &&
17290 BuiltinOp != Builtin::BI__builtin_wcscmp) {
17291 APSInt N;
17292 if (!EvaluateInteger(E->getArg(2), N, Info))
17293 return false;
17294 MaxLength = N.getZExtValue();
17295 }
17296
17297 // Empty substrings compare equal by definition.
17298 if (MaxLength == 0u)
17299 return Success(0, E);
17300
17301 if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
17302 !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
17303 String1.Designator.Invalid || String2.Designator.Invalid)
17304 return false;
17305
17306 QualType CharTy1 = String1.Designator.getType(Info.Ctx);
17307 QualType CharTy2 = String2.Designator.getType(Info.Ctx);
17308
17309 bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
17310 BuiltinOp == Builtin::BIbcmp ||
17311 BuiltinOp == Builtin::BI__builtin_memcmp ||
17312 BuiltinOp == Builtin::BI__builtin_bcmp;
17313
17314 assert(IsRawByte ||
17315 (Info.Ctx.hasSameUnqualifiedType(
17316 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
17317 Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
17318
17319 // For memcmp, allow comparing any arrays of '[[un]signed] char' or
17320 // 'char8_t', but no other types.
17321 if (IsRawByte &&
17322 !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) {
17323 // FIXME: Consider using our bit_cast implementation to support this.
17324 Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported)
17325 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp) << CharTy1
17326 << CharTy2;
17327 return false;
17328 }
17329
17330 const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
17331 return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
17332 handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
17333 Char1.isInt() && Char2.isInt();
17334 };
17335 const auto &AdvanceElems = [&] {
17336 return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
17337 HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
17338 };
17339
17340 bool StopAtNull =
17341 (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
17342 BuiltinOp != Builtin::BIwmemcmp &&
17343 BuiltinOp != Builtin::BI__builtin_memcmp &&
17344 BuiltinOp != Builtin::BI__builtin_bcmp &&
17345 BuiltinOp != Builtin::BI__builtin_wmemcmp);
17346 bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
17347 BuiltinOp == Builtin::BIwcsncmp ||
17348 BuiltinOp == Builtin::BIwmemcmp ||
17349 BuiltinOp == Builtin::BI__builtin_wcscmp ||
17350 BuiltinOp == Builtin::BI__builtin_wcsncmp ||
17351 BuiltinOp == Builtin::BI__builtin_wmemcmp;
17352
17353 for (; MaxLength; --MaxLength) {
17354 APValue Char1, Char2;
17355 if (!ReadCurElems(Char1, Char2))
17356 return false;
17357 if (Char1.getInt().ne(Char2.getInt())) {
17358 if (IsWide) // wmemcmp compares with wchar_t signedness.
17359 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
17360 // memcmp always compares unsigned chars.
17361 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
17362 }
17363 if (StopAtNull && !Char1.getInt())
17364 return Success(0, E);
17365 assert(!(StopAtNull && !Char2.getInt()));
17366 if (!AdvanceElems())
17367 return false;
17368 }
17369 // We hit the strncmp / memcmp limit.
17370 return Success(0, E);
17371 }
17372
17373 case Builtin::BI__atomic_always_lock_free:
17374 case Builtin::BI__atomic_is_lock_free:
17375 case Builtin::BI__c11_atomic_is_lock_free: {
17376 APSInt SizeVal;
17377 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
17378 return false;
17379
17380 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
17381 // of two less than or equal to the maximum inline atomic width, we know it
17382 // is lock-free. If the size isn't a power of two, or greater than the
17383 // maximum alignment where we promote atomics, we know it is not lock-free
17384 // (at least not in the sense of atomic_is_lock_free). Otherwise,
17385 // the answer can only be determined at runtime; for example, 16-byte
17386 // atomics have lock-free implementations on some, but not all,
17387 // x86-64 processors.
17388
17389 // Check power-of-two.
17390 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
17391 if (Size.isPowerOfTwo()) {
17392 // Check against inlining width.
17393 unsigned InlineWidthBits =
17394 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
17395 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
17396 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
17397 Size == CharUnits::One())
17398 return Success(1, E);
17399
17400 // If the pointer argument can be evaluated to a compile-time constant
17401 // integer (or nullptr), check if that value is appropriately aligned.
17402 const Expr *PtrArg = E->getArg(1);
17403 Expr::EvalResult ExprResult;
17404 APSInt IntResult;
17405 if (PtrArg->EvaluateAsRValue(ExprResult, Info.Ctx) &&
17406 ExprResult.Val.toIntegralConstant(IntResult, PtrArg->getType(),
17407 Info.Ctx) &&
17408 IntResult.isAligned(Size.getAsAlign()))
17409 return Success(1, E);
17410
17411 // Otherwise, check if the type's alignment against Size.
17412 if (auto *ICE = dyn_cast<ImplicitCastExpr>(PtrArg)) {
17413 // Drop the potential implicit-cast to 'const volatile void*', getting
17414 // the underlying type.
17415 if (ICE->getCastKind() == CK_BitCast)
17416 PtrArg = ICE->getSubExpr();
17417 }
17418
17419 if (auto PtrTy = PtrArg->getType()->getAs<PointerType>()) {
17420 QualType PointeeType = PtrTy->getPointeeType();
17421 if (!PointeeType->isIncompleteType() &&
17422 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
17423 // OK, we will inline operations on this object.
17424 return Success(1, E);
17425 }
17426 }
17427 }
17428 }
17429
17430 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
17431 Success(0, E) : Error(E);
17432 }
17433 case Builtin::BI__builtin_addcb:
17434 case Builtin::BI__builtin_addcs:
17435 case Builtin::BI__builtin_addc:
17436 case Builtin::BI__builtin_addcl:
17437 case Builtin::BI__builtin_addcll:
17438 case Builtin::BI__builtin_subcb:
17439 case Builtin::BI__builtin_subcs:
17440 case Builtin::BI__builtin_subc:
17441 case Builtin::BI__builtin_subcl:
17442 case Builtin::BI__builtin_subcll: {
17443 LValue CarryOutLValue;
17444 APSInt LHS, RHS, CarryIn, CarryOut, Result;
17445 QualType ResultType = E->getArg(0)->getType();
17446 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
17447 !EvaluateInteger(E->getArg(1), RHS, Info) ||
17448 !EvaluateInteger(E->getArg(2), CarryIn, Info) ||
17449 !EvaluatePointer(E->getArg(3), CarryOutLValue, Info))
17450 return false;
17451 // Copy the number of bits and sign.
17452 Result = LHS;
17453 CarryOut = LHS;
17454
17455 bool FirstOverflowed = false;
17456 bool SecondOverflowed = false;
17457 switch (BuiltinOp) {
17458 default:
17459 llvm_unreachable("Invalid value for BuiltinOp");
17460 case Builtin::BI__builtin_addcb:
17461 case Builtin::BI__builtin_addcs:
17462 case Builtin::BI__builtin_addc:
17463 case Builtin::BI__builtin_addcl:
17464 case Builtin::BI__builtin_addcll:
17465 Result =
17466 LHS.uadd_ov(RHS, FirstOverflowed).uadd_ov(CarryIn, SecondOverflowed);
17467 break;
17468 case Builtin::BI__builtin_subcb:
17469 case Builtin::BI__builtin_subcs:
17470 case Builtin::BI__builtin_subc:
17471 case Builtin::BI__builtin_subcl:
17472 case Builtin::BI__builtin_subcll:
17473 Result =
17474 LHS.usub_ov(RHS, FirstOverflowed).usub_ov(CarryIn, SecondOverflowed);
17475 break;
17476 }
17477
17478 // It is possible for both overflows to happen but CGBuiltin uses an OR so
17479 // this is consistent.
17480 CarryOut = (uint64_t)(FirstOverflowed | SecondOverflowed);
17481 APValue APV{CarryOut};
17482 if (!handleAssignment(Info, E, CarryOutLValue, ResultType, APV))
17483 return false;
17484 return Success(Result, E);
17485 }
17486 case Builtin::BI__builtin_add_overflow:
17487 case Builtin::BI__builtin_sub_overflow:
17488 case Builtin::BI__builtin_mul_overflow:
17489 case Builtin::BI__builtin_sadd_overflow:
17490 case Builtin::BI__builtin_uadd_overflow:
17491 case Builtin::BI__builtin_uaddl_overflow:
17492 case Builtin::BI__builtin_uaddll_overflow:
17493 case Builtin::BI__builtin_usub_overflow:
17494 case Builtin::BI__builtin_usubl_overflow:
17495 case Builtin::BI__builtin_usubll_overflow:
17496 case Builtin::BI__builtin_umul_overflow:
17497 case Builtin::BI__builtin_umull_overflow:
17498 case Builtin::BI__builtin_umulll_overflow:
17499 case Builtin::BI__builtin_saddl_overflow:
17500 case Builtin::BI__builtin_saddll_overflow:
17501 case Builtin::BI__builtin_ssub_overflow:
17502 case Builtin::BI__builtin_ssubl_overflow:
17503 case Builtin::BI__builtin_ssubll_overflow:
17504 case Builtin::BI__builtin_smul_overflow:
17505 case Builtin::BI__builtin_smull_overflow:
17506 case Builtin::BI__builtin_smulll_overflow: {
17507 LValue ResultLValue;
17508 APSInt LHS, RHS;
17509
17510 QualType ResultType = E->getArg(2)->getType()->getPointeeType();
17511 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
17512 !EvaluateInteger(E->getArg(1), RHS, Info) ||
17513 !EvaluatePointer(E->getArg(2), ResultLValue, Info))
17514 return false;
17515
17516 APSInt Result;
17517 bool DidOverflow = false;
17518
17519 // If the types don't have to match, enlarge all 3 to the largest of them.
17520 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
17521 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
17522 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
17523 bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
17525 bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
17527 uint64_t LHSSize = LHS.getBitWidth();
17528 uint64_t RHSSize = RHS.getBitWidth();
17529 uint64_t ResultSize = Info.Ctx.getIntWidth(ResultType);
17530 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
17531
17532 // Add an additional bit if the signedness isn't uniformly agreed to. We
17533 // could do this ONLY if there is a signed and an unsigned that both have
17534 // MaxBits, but the code to check that is pretty nasty. The issue will be
17535 // caught in the shrink-to-result later anyway.
17536 if (IsSigned && !AllSigned)
17537 ++MaxBits;
17538
17539 LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
17540 RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
17541 Result = APSInt(MaxBits, !IsSigned);
17542 }
17543
17544 // Find largest int.
17545 switch (BuiltinOp) {
17546 default:
17547 llvm_unreachable("Invalid value for BuiltinOp");
17548 case Builtin::BI__builtin_add_overflow:
17549 case Builtin::BI__builtin_sadd_overflow:
17550 case Builtin::BI__builtin_saddl_overflow:
17551 case Builtin::BI__builtin_saddll_overflow:
17552 case Builtin::BI__builtin_uadd_overflow:
17553 case Builtin::BI__builtin_uaddl_overflow:
17554 case Builtin::BI__builtin_uaddll_overflow:
17555 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
17556 : LHS.uadd_ov(RHS, DidOverflow);
17557 break;
17558 case Builtin::BI__builtin_sub_overflow:
17559 case Builtin::BI__builtin_ssub_overflow:
17560 case Builtin::BI__builtin_ssubl_overflow:
17561 case Builtin::BI__builtin_ssubll_overflow:
17562 case Builtin::BI__builtin_usub_overflow:
17563 case Builtin::BI__builtin_usubl_overflow:
17564 case Builtin::BI__builtin_usubll_overflow:
17565 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
17566 : LHS.usub_ov(RHS, DidOverflow);
17567 break;
17568 case Builtin::BI__builtin_mul_overflow:
17569 case Builtin::BI__builtin_smul_overflow:
17570 case Builtin::BI__builtin_smull_overflow:
17571 case Builtin::BI__builtin_smulll_overflow:
17572 case Builtin::BI__builtin_umul_overflow:
17573 case Builtin::BI__builtin_umull_overflow:
17574 case Builtin::BI__builtin_umulll_overflow:
17575 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
17576 : LHS.umul_ov(RHS, DidOverflow);
17577 break;
17578 }
17579
17580 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
17581 // since it will give us the behavior of a TruncOrSelf in the case where
17582 // its parameter <= its size. We previously set Result to be at least the
17583 // integer width of the result, so getIntWidth(ResultType) <=
17584 // Result.BitWidth will work exactly like TruncOrSelf.
17585 APSInt Temp = Result.extOrTrunc(Info.Ctx.getIntWidth(ResultType));
17586 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
17587
17588 // In the case where multiple sizes are allowed, truncate and see if
17589 // the values are the same.
17590 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
17591 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
17592 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
17593 if (!APSInt::isSameValue(Temp, Result))
17594 DidOverflow = true;
17595 }
17596 Result = Temp;
17597
17598 APValue APV{Result};
17599 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
17600 return false;
17601 return Success(DidOverflow, E);
17602 }
17603
17604 case Builtin::BI__builtin_reduce_add:
17605 case Builtin::BI__builtin_reduce_mul:
17606 case Builtin::BI__builtin_reduce_and:
17607 case Builtin::BI__builtin_reduce_or:
17608 case Builtin::BI__builtin_reduce_xor:
17609 case Builtin::BI__builtin_reduce_min:
17610 case Builtin::BI__builtin_reduce_max: {
17611 APValue Source;
17612 if (!EvaluateAsRValue(Info, E->getArg(0), Source))
17613 return false;
17614
17615 unsigned SourceLen = Source.getVectorLength();
17616 APSInt Reduced = Source.getVectorElt(0).getInt();
17617 for (unsigned EltNum = 1; EltNum < SourceLen; ++EltNum) {
17618 switch (BuiltinOp) {
17619 default:
17620 return false;
17621 case Builtin::BI__builtin_reduce_add: {
17623 Info, E, Reduced, Source.getVectorElt(EltNum).getInt(),
17624 Reduced.getBitWidth() + 1, std::plus<APSInt>(), Reduced))
17625 return false;
17626 break;
17627 }
17628 case Builtin::BI__builtin_reduce_mul: {
17630 Info, E, Reduced, Source.getVectorElt(EltNum).getInt(),
17631 Reduced.getBitWidth() * 2, std::multiplies<APSInt>(), Reduced))
17632 return false;
17633 break;
17634 }
17635 case Builtin::BI__builtin_reduce_and: {
17636 Reduced &= Source.getVectorElt(EltNum).getInt();
17637 break;
17638 }
17639 case Builtin::BI__builtin_reduce_or: {
17640 Reduced |= Source.getVectorElt(EltNum).getInt();
17641 break;
17642 }
17643 case Builtin::BI__builtin_reduce_xor: {
17644 Reduced ^= Source.getVectorElt(EltNum).getInt();
17645 break;
17646 }
17647 case Builtin::BI__builtin_reduce_min: {
17648 Reduced = std::min(Reduced, Source.getVectorElt(EltNum).getInt());
17649 break;
17650 }
17651 case Builtin::BI__builtin_reduce_max: {
17652 Reduced = std::max(Reduced, Source.getVectorElt(EltNum).getInt());
17653 break;
17654 }
17655 }
17656 }
17657
17658 return Success(Reduced, E);
17659 }
17660
17661 case clang::X86::BI__builtin_ia32_addcarryx_u32:
17662 case clang::X86::BI__builtin_ia32_addcarryx_u64:
17663 case clang::X86::BI__builtin_ia32_subborrow_u32:
17664 case clang::X86::BI__builtin_ia32_subborrow_u64: {
17665 LValue ResultLValue;
17666 APSInt CarryIn, LHS, RHS;
17667 QualType ResultType = E->getArg(3)->getType()->getPointeeType();
17668 if (!EvaluateInteger(E->getArg(0), CarryIn, Info) ||
17669 !EvaluateInteger(E->getArg(1), LHS, Info) ||
17670 !EvaluateInteger(E->getArg(2), RHS, Info) ||
17671 !EvaluatePointer(E->getArg(3), ResultLValue, Info))
17672 return false;
17673
17674 bool IsAdd = BuiltinOp == clang::X86::BI__builtin_ia32_addcarryx_u32 ||
17675 BuiltinOp == clang::X86::BI__builtin_ia32_addcarryx_u64;
17676
17677 unsigned BitWidth = LHS.getBitWidth();
17678 unsigned CarryInBit = CarryIn.ugt(0) ? 1 : 0;
17679 APInt ExResult =
17680 IsAdd
17681 ? (LHS.zext(BitWidth + 1) + (RHS.zext(BitWidth + 1) + CarryInBit))
17682 : (LHS.zext(BitWidth + 1) - (RHS.zext(BitWidth + 1) + CarryInBit));
17683
17684 APInt Result = ExResult.extractBits(BitWidth, 0);
17685 uint64_t CarryOut = ExResult.extractBitsAsZExtValue(1, BitWidth);
17686
17687 APValue APV{APSInt(Result, /*isUnsigned=*/true)};
17688 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
17689 return false;
17690 return Success(CarryOut, E);
17691 }
17692
17693 case clang::X86::BI__builtin_ia32_movmskps:
17694 case clang::X86::BI__builtin_ia32_movmskpd:
17695 case clang::X86::BI__builtin_ia32_pmovmskb128:
17696 case clang::X86::BI__builtin_ia32_pmovmskb256:
17697 case clang::X86::BI__builtin_ia32_movmskps256:
17698 case clang::X86::BI__builtin_ia32_movmskpd256: {
17699 APValue Source;
17700 if (!Evaluate(Source, Info, E->getArg(0)))
17701 return false;
17702 unsigned SourceLen = Source.getVectorLength();
17703 const VectorType *VT = E->getArg(0)->getType()->castAs<VectorType>();
17704 QualType ElemQT = VT->getElementType();
17705 unsigned ResultLen = Info.Ctx.getTypeSize(
17706 E->getCallReturnType(Info.Ctx)); // Always 32-bit integer.
17707 APInt Result(ResultLen, 0);
17708
17709 for (unsigned I = 0; I != SourceLen; ++I) {
17710 APInt Elem;
17711 if (ElemQT->isIntegerType()) {
17712 Elem = Source.getVectorElt(I).getInt();
17713 } else if (ElemQT->isRealFloatingType()) {
17714 Elem = Source.getVectorElt(I).getFloat().bitcastToAPInt();
17715 } else {
17716 return false;
17717 }
17718 Result.setBitVal(I, Elem.isNegative());
17719 }
17720 return Success(Result, E);
17721 }
17722
17723 case clang::X86::BI__builtin_ia32_bextr_u32:
17724 case clang::X86::BI__builtin_ia32_bextr_u64:
17725 case clang::X86::BI__builtin_ia32_bextri_u32:
17726 case clang::X86::BI__builtin_ia32_bextri_u64: {
17727 APSInt Val, Idx;
17728 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
17729 !EvaluateInteger(E->getArg(1), Idx, Info))
17730 return false;
17731
17732 unsigned BitWidth = Val.getBitWidth();
17733 uint64_t Shift = Idx.extractBitsAsZExtValue(8, 0);
17734 uint64_t Length = Idx.extractBitsAsZExtValue(8, 8);
17735 Length = Length > BitWidth ? BitWidth : Length;
17736
17737 // Handle out of bounds cases.
17738 if (Length == 0 || Shift >= BitWidth)
17739 return Success(0, E);
17740
17741 uint64_t Result = Val.getZExtValue() >> Shift;
17742 Result &= llvm::maskTrailingOnes<uint64_t>(Length);
17743 return Success(Result, E);
17744 }
17745
17746 case clang::X86::BI__builtin_ia32_bzhi_si:
17747 case clang::X86::BI__builtin_ia32_bzhi_di: {
17748 APSInt Val, Idx;
17749 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
17750 !EvaluateInteger(E->getArg(1), Idx, Info))
17751 return false;
17752
17753 unsigned BitWidth = Val.getBitWidth();
17754 unsigned Index = Idx.extractBitsAsZExtValue(8, 0);
17755 if (Index < BitWidth)
17756 Val.clearHighBits(BitWidth - Index);
17757 return Success(Val, E);
17758 }
17759
17760 case clang::X86::BI__builtin_ia32_ktestcqi:
17761 case clang::X86::BI__builtin_ia32_ktestchi:
17762 case clang::X86::BI__builtin_ia32_ktestcsi:
17763 case clang::X86::BI__builtin_ia32_ktestcdi: {
17764 APSInt A, B;
17765 if (!EvaluateInteger(E->getArg(0), A, Info) ||
17766 !EvaluateInteger(E->getArg(1), B, Info))
17767 return false;
17768
17769 return Success((~A & B) == 0, E);
17770 }
17771
17772 case clang::X86::BI__builtin_ia32_ktestzqi:
17773 case clang::X86::BI__builtin_ia32_ktestzhi:
17774 case clang::X86::BI__builtin_ia32_ktestzsi:
17775 case clang::X86::BI__builtin_ia32_ktestzdi: {
17776 APSInt A, B;
17777 if (!EvaluateInteger(E->getArg(0), A, Info) ||
17778 !EvaluateInteger(E->getArg(1), B, Info))
17779 return false;
17780
17781 return Success((A & B) == 0, E);
17782 }
17783
17784 case clang::X86::BI__builtin_ia32_kortestcqi:
17785 case clang::X86::BI__builtin_ia32_kortestchi:
17786 case clang::X86::BI__builtin_ia32_kortestcsi:
17787 case clang::X86::BI__builtin_ia32_kortestcdi: {
17788 APSInt A, B;
17789 if (!EvaluateInteger(E->getArg(0), A, Info) ||
17790 !EvaluateInteger(E->getArg(1), B, Info))
17791 return false;
17792
17793 return Success(~(A | B) == 0, E);
17794 }
17795
17796 case clang::X86::BI__builtin_ia32_kortestzqi:
17797 case clang::X86::BI__builtin_ia32_kortestzhi:
17798 case clang::X86::BI__builtin_ia32_kortestzsi:
17799 case clang::X86::BI__builtin_ia32_kortestzdi: {
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_kunpckhi:
17809 case clang::X86::BI__builtin_ia32_kunpckdi:
17810 case clang::X86::BI__builtin_ia32_kunpcksi: {
17811 APSInt A, B;
17812 if (!EvaluateInteger(E->getArg(0), A, Info) ||
17813 !EvaluateInteger(E->getArg(1), B, Info))
17814 return false;
17815
17816 // Generic kunpack: extract lower half of each operand and concatenate
17817 // Result = A[HalfWidth-1:0] concat B[HalfWidth-1:0]
17818 unsigned BW = A.getBitWidth();
17819 APSInt Result(A.trunc(BW / 2).concat(B.trunc(BW / 2)), A.isUnsigned());
17820 return Success(Result, E);
17821 }
17822
17823 case clang::X86::BI__builtin_ia32_lzcnt_u16:
17824 case clang::X86::BI__builtin_ia32_lzcnt_u32:
17825 case clang::X86::BI__builtin_ia32_lzcnt_u64: {
17826 APSInt Val;
17827 if (!EvaluateInteger(E->getArg(0), Val, Info))
17828 return false;
17829 return Success(Val.countLeadingZeros(), E);
17830 }
17831
17832 case clang::X86::BI__builtin_ia32_tzcnt_u16:
17833 case clang::X86::BI__builtin_ia32_tzcnt_u32:
17834 case clang::X86::BI__builtin_ia32_tzcnt_u64: {
17835 APSInt Val;
17836 if (!EvaluateInteger(E->getArg(0), Val, Info))
17837 return false;
17838 return Success(Val.countTrailingZeros(), E);
17839 }
17840
17841 case clang::X86::BI__builtin_ia32_pdep_si:
17842 case clang::X86::BI__builtin_ia32_pdep_di: {
17843 APSInt Val, Msk;
17844 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
17845 !EvaluateInteger(E->getArg(1), Msk, Info))
17846 return false;
17847
17848 unsigned BitWidth = Val.getBitWidth();
17849 APInt Result = APInt::getZero(BitWidth);
17850 for (unsigned I = 0, P = 0; I != BitWidth; ++I)
17851 if (Msk[I])
17852 Result.setBitVal(I, Val[P++]);
17853 return Success(Result, E);
17854 }
17855
17856 case clang::X86::BI__builtin_ia32_pext_si:
17857 case clang::X86::BI__builtin_ia32_pext_di: {
17858 APSInt Val, Msk;
17859 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
17860 !EvaluateInteger(E->getArg(1), Msk, Info))
17861 return false;
17862
17863 unsigned BitWidth = Val.getBitWidth();
17864 APInt Result = APInt::getZero(BitWidth);
17865 for (unsigned I = 0, P = 0; I != BitWidth; ++I)
17866 if (Msk[I])
17867 Result.setBitVal(P++, Val[I]);
17868 return Success(Result, E);
17869 }
17870 case X86::BI__builtin_ia32_ptestz128:
17871 case X86::BI__builtin_ia32_ptestz256:
17872 case X86::BI__builtin_ia32_vtestzps:
17873 case X86::BI__builtin_ia32_vtestzps256:
17874 case X86::BI__builtin_ia32_vtestzpd:
17875 case X86::BI__builtin_ia32_vtestzpd256: {
17876 return EvalTestOp(
17877 [](const APInt &A, const APInt &B) { return (A & B) == 0; });
17878 }
17879 case X86::BI__builtin_ia32_ptestc128:
17880 case X86::BI__builtin_ia32_ptestc256:
17881 case X86::BI__builtin_ia32_vtestcps:
17882 case X86::BI__builtin_ia32_vtestcps256:
17883 case X86::BI__builtin_ia32_vtestcpd:
17884 case X86::BI__builtin_ia32_vtestcpd256: {
17885 return EvalTestOp(
17886 [](const APInt &A, const APInt &B) { return (~A & B) == 0; });
17887 }
17888 case X86::BI__builtin_ia32_ptestnzc128:
17889 case X86::BI__builtin_ia32_ptestnzc256:
17890 case X86::BI__builtin_ia32_vtestnzcps:
17891 case X86::BI__builtin_ia32_vtestnzcps256:
17892 case X86::BI__builtin_ia32_vtestnzcpd:
17893 case X86::BI__builtin_ia32_vtestnzcpd256: {
17894 return EvalTestOp([](const APInt &A, const APInt &B) {
17895 return ((A & B) != 0) && ((~A & B) != 0);
17896 });
17897 }
17898 case X86::BI__builtin_ia32_kandqi:
17899 case X86::BI__builtin_ia32_kandhi:
17900 case X86::BI__builtin_ia32_kandsi:
17901 case X86::BI__builtin_ia32_kanddi: {
17902 return HandleMaskBinOp(
17903 [](const APSInt &LHS, const APSInt &RHS) { return LHS & RHS; });
17904 }
17905
17906 case X86::BI__builtin_ia32_kandnqi:
17907 case X86::BI__builtin_ia32_kandnhi:
17908 case X86::BI__builtin_ia32_kandnsi:
17909 case X86::BI__builtin_ia32_kandndi: {
17910 return HandleMaskBinOp(
17911 [](const APSInt &LHS, const APSInt &RHS) { return ~LHS & RHS; });
17912 }
17913
17914 case X86::BI__builtin_ia32_korqi:
17915 case X86::BI__builtin_ia32_korhi:
17916 case X86::BI__builtin_ia32_korsi:
17917 case X86::BI__builtin_ia32_kordi: {
17918 return HandleMaskBinOp(
17919 [](const APSInt &LHS, const APSInt &RHS) { return LHS | RHS; });
17920 }
17921
17922 case X86::BI__builtin_ia32_kxnorqi:
17923 case X86::BI__builtin_ia32_kxnorhi:
17924 case X86::BI__builtin_ia32_kxnorsi:
17925 case X86::BI__builtin_ia32_kxnordi: {
17926 return HandleMaskBinOp(
17927 [](const APSInt &LHS, const APSInt &RHS) { return ~(LHS ^ RHS); });
17928 }
17929
17930 case X86::BI__builtin_ia32_kxorqi:
17931 case X86::BI__builtin_ia32_kxorhi:
17932 case X86::BI__builtin_ia32_kxorsi:
17933 case X86::BI__builtin_ia32_kxordi: {
17934 return HandleMaskBinOp(
17935 [](const APSInt &LHS, const APSInt &RHS) { return LHS ^ RHS; });
17936 }
17937
17938 case X86::BI__builtin_ia32_knotqi:
17939 case X86::BI__builtin_ia32_knothi:
17940 case X86::BI__builtin_ia32_knotsi:
17941 case X86::BI__builtin_ia32_knotdi: {
17942 APSInt Val;
17943 if (!EvaluateInteger(E->getArg(0), Val, Info))
17944 return false;
17945 APSInt Result = ~Val;
17946 return Success(APValue(Result), E);
17947 }
17948
17949 case X86::BI__builtin_ia32_kaddqi:
17950 case X86::BI__builtin_ia32_kaddhi:
17951 case X86::BI__builtin_ia32_kaddsi:
17952 case X86::BI__builtin_ia32_kadddi: {
17953 return HandleMaskBinOp(
17954 [](const APSInt &LHS, const APSInt &RHS) { return LHS + RHS; });
17955 }
17956
17957 case X86::BI__builtin_ia32_kmovb:
17958 case X86::BI__builtin_ia32_kmovw:
17959 case X86::BI__builtin_ia32_kmovd:
17960 case X86::BI__builtin_ia32_kmovq: {
17961 APSInt Val;
17962 if (!EvaluateInteger(E->getArg(0), Val, Info))
17963 return false;
17964 return Success(Val, E);
17965 }
17966
17967 case X86::BI__builtin_ia32_kshiftliqi:
17968 case X86::BI__builtin_ia32_kshiftlihi:
17969 case X86::BI__builtin_ia32_kshiftlisi:
17970 case X86::BI__builtin_ia32_kshiftlidi: {
17971 return HandleMaskBinOp([](const APSInt &LHS, const APSInt &RHS) {
17972 unsigned Amt = RHS.getZExtValue() & 0xFF;
17973 if (Amt >= LHS.getBitWidth())
17974 return APSInt(APInt::getZero(LHS.getBitWidth()), LHS.isUnsigned());
17975 return APSInt(LHS.shl(Amt), LHS.isUnsigned());
17976 });
17977 }
17978
17979 case X86::BI__builtin_ia32_kshiftriqi:
17980 case X86::BI__builtin_ia32_kshiftrihi:
17981 case X86::BI__builtin_ia32_kshiftrisi:
17982 case X86::BI__builtin_ia32_kshiftridi: {
17983 return HandleMaskBinOp([](const APSInt &LHS, const APSInt &RHS) {
17984 unsigned Amt = RHS.getZExtValue() & 0xFF;
17985 if (Amt >= LHS.getBitWidth())
17986 return APSInt(APInt::getZero(LHS.getBitWidth()), LHS.isUnsigned());
17987 return APSInt(LHS.lshr(Amt), LHS.isUnsigned());
17988 });
17989 }
17990
17991 case clang::X86::BI__builtin_ia32_vec_ext_v4hi:
17992 case clang::X86::BI__builtin_ia32_vec_ext_v16qi:
17993 case clang::X86::BI__builtin_ia32_vec_ext_v8hi:
17994 case clang::X86::BI__builtin_ia32_vec_ext_v4si:
17995 case clang::X86::BI__builtin_ia32_vec_ext_v2di:
17996 case clang::X86::BI__builtin_ia32_vec_ext_v32qi:
17997 case clang::X86::BI__builtin_ia32_vec_ext_v16hi:
17998 case clang::X86::BI__builtin_ia32_vec_ext_v8si:
17999 case clang::X86::BI__builtin_ia32_vec_ext_v4di: {
18000 APValue Vec;
18001 APSInt IdxAPS;
18002 if (!EvaluateVector(E->getArg(0), Vec, Info) ||
18003 !EvaluateInteger(E->getArg(1), IdxAPS, Info))
18004 return false;
18005 unsigned N = Vec.getVectorLength();
18006 unsigned Idx = static_cast<unsigned>(IdxAPS.getZExtValue() & (N - 1));
18007 return Success(Vec.getVectorElt(Idx).getInt(), E);
18008 }
18009
18010 case clang::X86::BI__builtin_ia32_cvtb2mask128:
18011 case clang::X86::BI__builtin_ia32_cvtb2mask256:
18012 case clang::X86::BI__builtin_ia32_cvtb2mask512:
18013 case clang::X86::BI__builtin_ia32_cvtw2mask128:
18014 case clang::X86::BI__builtin_ia32_cvtw2mask256:
18015 case clang::X86::BI__builtin_ia32_cvtw2mask512:
18016 case clang::X86::BI__builtin_ia32_cvtd2mask128:
18017 case clang::X86::BI__builtin_ia32_cvtd2mask256:
18018 case clang::X86::BI__builtin_ia32_cvtd2mask512:
18019 case clang::X86::BI__builtin_ia32_cvtq2mask128:
18020 case clang::X86::BI__builtin_ia32_cvtq2mask256:
18021 case clang::X86::BI__builtin_ia32_cvtq2mask512: {
18022 assert(E->getNumArgs() == 1);
18023 APValue Vec;
18024 if (!EvaluateVector(E->getArg(0), Vec, Info))
18025 return false;
18026
18027 unsigned VectorLen = Vec.getVectorLength();
18028 unsigned RetWidth = Info.Ctx.getIntWidth(E->getType());
18029 llvm::APInt Bits(RetWidth, 0);
18030
18031 for (unsigned ElemNum = 0; ElemNum != VectorLen; ++ElemNum) {
18032 const APSInt &A = Vec.getVectorElt(ElemNum).getInt();
18033 unsigned MSB = A[A.getBitWidth() - 1];
18034 Bits.setBitVal(ElemNum, MSB);
18035 }
18036
18037 APSInt RetMask(Bits, /*isUnsigned=*/true);
18038 return Success(APValue(RetMask), E);
18039 }
18040
18041 case clang::X86::BI__builtin_ia32_cmpb128_mask:
18042 case clang::X86::BI__builtin_ia32_cmpw128_mask:
18043 case clang::X86::BI__builtin_ia32_cmpd128_mask:
18044 case clang::X86::BI__builtin_ia32_cmpq128_mask:
18045 case clang::X86::BI__builtin_ia32_cmpb256_mask:
18046 case clang::X86::BI__builtin_ia32_cmpw256_mask:
18047 case clang::X86::BI__builtin_ia32_cmpd256_mask:
18048 case clang::X86::BI__builtin_ia32_cmpq256_mask:
18049 case clang::X86::BI__builtin_ia32_cmpb512_mask:
18050 case clang::X86::BI__builtin_ia32_cmpw512_mask:
18051 case clang::X86::BI__builtin_ia32_cmpd512_mask:
18052 case clang::X86::BI__builtin_ia32_cmpq512_mask:
18053 case clang::X86::BI__builtin_ia32_ucmpb128_mask:
18054 case clang::X86::BI__builtin_ia32_ucmpw128_mask:
18055 case clang::X86::BI__builtin_ia32_ucmpd128_mask:
18056 case clang::X86::BI__builtin_ia32_ucmpq128_mask:
18057 case clang::X86::BI__builtin_ia32_ucmpb256_mask:
18058 case clang::X86::BI__builtin_ia32_ucmpw256_mask:
18059 case clang::X86::BI__builtin_ia32_ucmpd256_mask:
18060 case clang::X86::BI__builtin_ia32_ucmpq256_mask:
18061 case clang::X86::BI__builtin_ia32_ucmpb512_mask:
18062 case clang::X86::BI__builtin_ia32_ucmpw512_mask:
18063 case clang::X86::BI__builtin_ia32_ucmpd512_mask:
18064 case clang::X86::BI__builtin_ia32_ucmpq512_mask: {
18065 assert(E->getNumArgs() == 4);
18066
18067 bool IsUnsigned =
18068 (BuiltinOp >= clang::X86::BI__builtin_ia32_ucmpb128_mask &&
18069 BuiltinOp <= clang::X86::BI__builtin_ia32_ucmpw512_mask);
18070
18071 APValue LHS, RHS;
18072 APSInt Mask, Opcode;
18073 if (!EvaluateVector(E->getArg(0), LHS, Info) ||
18074 !EvaluateVector(E->getArg(1), RHS, Info) ||
18075 !EvaluateInteger(E->getArg(2), Opcode, Info) ||
18076 !EvaluateInteger(E->getArg(3), Mask, Info))
18077 return false;
18078
18079 assert(LHS.getVectorLength() == RHS.getVectorLength());
18080
18081 unsigned VectorLen = LHS.getVectorLength();
18082 unsigned RetWidth = Mask.getBitWidth();
18083
18084 APSInt RetMask(llvm::APInt(RetWidth, 0), /*isUnsigned=*/true);
18085
18086 for (unsigned ElemNum = 0; ElemNum < VectorLen; ++ElemNum) {
18087 const APSInt &A = LHS.getVectorElt(ElemNum).getInt();
18088 const APSInt &B = RHS.getVectorElt(ElemNum).getInt();
18089 bool Result = false;
18090
18091 switch (Opcode.getExtValue() & 0x7) {
18092 case 0: // _MM_CMPINT_EQ
18093 Result = (A == B);
18094 break;
18095 case 1: // _MM_CMPINT_LT
18096 Result = IsUnsigned ? A.ult(B) : A.slt(B);
18097 break;
18098 case 2: // _MM_CMPINT_LE
18099 Result = IsUnsigned ? A.ule(B) : A.sle(B);
18100 break;
18101 case 3: // _MM_CMPINT_FALSE
18102 Result = false;
18103 break;
18104 case 4: // _MM_CMPINT_NE
18105 Result = (A != B);
18106 break;
18107 case 5: // _MM_CMPINT_NLT (>=)
18108 Result = IsUnsigned ? A.uge(B) : A.sge(B);
18109 break;
18110 case 6: // _MM_CMPINT_NLE (>)
18111 Result = IsUnsigned ? A.ugt(B) : A.sgt(B);
18112 break;
18113 case 7: // _MM_CMPINT_TRUE
18114 Result = true;
18115 break;
18116 }
18117
18118 RetMask.setBitVal(ElemNum, Mask[ElemNum] && Result);
18119 }
18120
18121 return Success(APValue(RetMask), E);
18122 }
18123 case X86::BI__builtin_ia32_vpshufbitqmb128_mask:
18124 case X86::BI__builtin_ia32_vpshufbitqmb256_mask:
18125 case X86::BI__builtin_ia32_vpshufbitqmb512_mask: {
18126 assert(E->getNumArgs() == 3);
18127
18128 APValue Source, ShuffleMask;
18129 APSInt ZeroMask;
18130 if (!EvaluateVector(E->getArg(0), Source, Info) ||
18131 !EvaluateVector(E->getArg(1), ShuffleMask, Info) ||
18132 !EvaluateInteger(E->getArg(2), ZeroMask, Info))
18133 return false;
18134
18135 assert(Source.getVectorLength() == ShuffleMask.getVectorLength());
18136 assert(ZeroMask.getBitWidth() == Source.getVectorLength());
18137
18138 unsigned NumBytesInQWord = 8;
18139 unsigned NumBitsInByte = 8;
18140 unsigned NumBytes = Source.getVectorLength();
18141 unsigned NumQWords = NumBytes / NumBytesInQWord;
18142 unsigned RetWidth = ZeroMask.getBitWidth();
18143 APSInt RetMask(llvm::APInt(RetWidth, 0), /*isUnsigned=*/true);
18144
18145 for (unsigned QWordId = 0; QWordId != NumQWords; ++QWordId) {
18146 APInt SourceQWord(64, 0);
18147 for (unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
18148 uint64_t Byte = Source.getVectorElt(QWordId * NumBytesInQWord + ByteIdx)
18149 .getInt()
18150 .getZExtValue();
18151 SourceQWord.insertBits(APInt(8, Byte & 0xFF), ByteIdx * NumBitsInByte);
18152 }
18153
18154 for (unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
18155 unsigned SelIdx = QWordId * NumBytesInQWord + ByteIdx;
18156 unsigned M =
18157 ShuffleMask.getVectorElt(SelIdx).getInt().getZExtValue() & 0x3F;
18158 if (ZeroMask[SelIdx]) {
18159 RetMask.setBitVal(SelIdx, SourceQWord[M]);
18160 }
18161 }
18162 }
18163 return Success(APValue(RetMask), E);
18164 }
18165 }
18166}
18167
18168/// Determine whether this is a pointer past the end of the complete
18169/// object referred to by the lvalue.
18171 const LValue &LV) {
18172 // A null pointer can be viewed as being "past the end" but we don't
18173 // choose to look at it that way here.
18174 if (!LV.getLValueBase())
18175 return false;
18176
18177 // If the designator is valid and refers to a subobject, we're not pointing
18178 // past the end.
18179 if (!LV.getLValueDesignator().Invalid &&
18180 !LV.getLValueDesignator().isOnePastTheEnd())
18181 return false;
18182
18183 // A pointer to an incomplete type might be past-the-end if the type's size is
18184 // zero. We cannot tell because the type is incomplete.
18185 QualType Ty = getType(LV.getLValueBase());
18186 if (Ty->isIncompleteType())
18187 return true;
18188
18189 // Can't be past the end of an invalid object.
18190 if (LV.getLValueDesignator().Invalid)
18191 return false;
18192
18193 // We're a past-the-end pointer if we point to the byte after the object,
18194 // no matter what our type or path is.
18195 auto Size = Ctx.getTypeSizeInChars(Ty);
18196 return LV.getLValueOffset() == Size;
18197}
18198
18199namespace {
18200
18201/// Data recursive integer evaluator of certain binary operators.
18202///
18203/// We use a data recursive algorithm for binary operators so that we are able
18204/// to handle extreme cases of chained binary operators without causing stack
18205/// overflow.
18206class DataRecursiveIntBinOpEvaluator {
18207 struct EvalResult {
18208 APValue Val;
18209 bool Failed = false;
18210
18211 EvalResult() = default;
18212
18213 void swap(EvalResult &RHS) {
18214 Val.swap(RHS.Val);
18215 Failed = RHS.Failed;
18216 RHS.Failed = false;
18217 }
18218 };
18219
18220 struct Job {
18221 const Expr *E;
18222 EvalResult LHSResult; // meaningful only for binary operator expression.
18223 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
18224
18225 Job() = default;
18226 Job(Job &&) = default;
18227
18228 void startSpeculativeEval(EvalInfo &Info) {
18229 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
18230 }
18231
18232 private:
18233 SpeculativeEvaluationRAII SpecEvalRAII;
18234 };
18235
18236 SmallVector<Job, 16> Queue;
18237
18238 IntExprEvaluator &IntEval;
18239 EvalInfo &Info;
18240 APValue &FinalResult;
18241
18242public:
18243 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
18244 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
18245
18246 /// True if \param E is a binary operator that we are going to handle
18247 /// data recursively.
18248 /// We handle binary operators that are comma, logical, or that have operands
18249 /// with integral or enumeration type.
18250 static bool shouldEnqueue(const BinaryOperator *E) {
18251 return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
18255 }
18256
18257 bool Traverse(const BinaryOperator *E) {
18258 enqueue(E);
18259 EvalResult PrevResult;
18260 while (!Queue.empty())
18261 process(PrevResult);
18262
18263 if (PrevResult.Failed) return false;
18264
18265 FinalResult.swap(PrevResult.Val);
18266 return true;
18267 }
18268
18269private:
18270 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
18271 return IntEval.Success(Value, E, Result);
18272 }
18273 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
18274 return IntEval.Success(Value, E, Result);
18275 }
18276 bool Error(const Expr *E) {
18277 return IntEval.Error(E);
18278 }
18279 bool Error(const Expr *E, diag::kind D) {
18280 return IntEval.Error(E, D);
18281 }
18282
18283 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
18284 return Info.CCEDiag(E, D);
18285 }
18286
18287 // Returns true if visiting the RHS is necessary, false otherwise.
18288 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
18289 bool &SuppressRHSDiags);
18290
18291 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
18292 const BinaryOperator *E, APValue &Result);
18293
18294 void EvaluateExpr(const Expr *E, EvalResult &Result) {
18295 Result.Failed = !Evaluate(Result.Val, Info, E);
18296 if (Result.Failed)
18297 Result.Val = APValue();
18298 }
18299
18300 void process(EvalResult &Result);
18301
18302 void enqueue(const Expr *E) {
18303 E = E->IgnoreParens();
18304 Queue.resize(Queue.size()+1);
18305 Queue.back().E = E;
18306 Queue.back().Kind = Job::AnyExprKind;
18307 }
18308};
18309
18310}
18311
18312bool DataRecursiveIntBinOpEvaluator::
18313 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
18314 bool &SuppressRHSDiags) {
18315 if (E->getOpcode() == BO_Comma) {
18316 // Ignore LHS but note if we could not evaluate it.
18317 if (LHSResult.Failed)
18318 return Info.noteSideEffect();
18319 return true;
18320 }
18321
18322 if (E->isLogicalOp()) {
18323 bool LHSAsBool;
18324 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
18325 // We were able to evaluate the LHS, see if we can get away with not
18326 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
18327 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
18328 Success(LHSAsBool, E, LHSResult.Val);
18329 return false; // Ignore RHS
18330 }
18331 } else {
18332 LHSResult.Failed = true;
18333
18334 // Since we weren't able to evaluate the left hand side, it
18335 // might have had side effects.
18336 if (!Info.noteSideEffect())
18337 return false;
18338
18339 // We can't evaluate the LHS; however, sometimes the result
18340 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
18341 // Don't ignore RHS and suppress diagnostics from this arm.
18342 SuppressRHSDiags = true;
18343 }
18344
18345 return true;
18346 }
18347
18348 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
18350
18351 if (LHSResult.Failed && !Info.noteFailure())
18352 return false; // Ignore RHS;
18353
18354 return true;
18355}
18356
18357static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
18358 bool IsSub) {
18359 // Compute the new offset in the appropriate width, wrapping at 64 bits.
18360 // FIXME: When compiling for a 32-bit target, we should use 32-bit
18361 // offsets.
18362 assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
18363 CharUnits &Offset = LVal.getLValueOffset();
18364 uint64_t Offset64 = Offset.getQuantity();
18365 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
18366 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
18367 : Offset64 + Index64);
18368}
18369
18370bool DataRecursiveIntBinOpEvaluator::
18371 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
18372 const BinaryOperator *E, APValue &Result) {
18373 if (E->getOpcode() == BO_Comma) {
18374 if (RHSResult.Failed)
18375 return false;
18376 Result = RHSResult.Val;
18377 return true;
18378 }
18379
18380 if (E->isLogicalOp()) {
18381 bool lhsResult, rhsResult;
18382 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
18383 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
18384
18385 if (LHSIsOK) {
18386 if (RHSIsOK) {
18387 if (E->getOpcode() == BO_LOr)
18388 return Success(lhsResult || rhsResult, E, Result);
18389 else
18390 return Success(lhsResult && rhsResult, E, Result);
18391 }
18392 } else {
18393 if (RHSIsOK) {
18394 // We can't evaluate the LHS; however, sometimes the result
18395 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
18396 if (rhsResult == (E->getOpcode() == BO_LOr))
18397 return Success(rhsResult, E, Result);
18398 }
18399 }
18400
18401 return false;
18402 }
18403
18404 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
18406
18407 if (LHSResult.Failed || RHSResult.Failed)
18408 return false;
18409
18410 const APValue &LHSVal = LHSResult.Val;
18411 const APValue &RHSVal = RHSResult.Val;
18412
18413 // Handle cases like (unsigned long)&a + 4.
18414 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
18415 Result = LHSVal;
18416 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
18417 return true;
18418 }
18419
18420 // Handle cases like 4 + (unsigned long)&a
18421 if (E->getOpcode() == BO_Add &&
18422 RHSVal.isLValue() && LHSVal.isInt()) {
18423 Result = RHSVal;
18424 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
18425 return true;
18426 }
18427
18428 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
18429 // Handle (intptr_t)&&A - (intptr_t)&&B.
18430 if (!LHSVal.getLValueOffset().isZero() ||
18431 !RHSVal.getLValueOffset().isZero())
18432 return false;
18433 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
18434 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
18435 if (!LHSExpr || !RHSExpr)
18436 return false;
18437 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
18438 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
18439 if (!LHSAddrExpr || !RHSAddrExpr)
18440 return false;
18441 // Make sure both labels come from the same function.
18442 if (LHSAddrExpr->getLabel()->getDeclContext() !=
18443 RHSAddrExpr->getLabel()->getDeclContext())
18444 return false;
18445 Result = APValue(LHSAddrExpr, RHSAddrExpr);
18446 return true;
18447 }
18448
18449 // All the remaining cases expect both operands to be an integer
18450 if (!LHSVal.isInt() || !RHSVal.isInt())
18451 return Error(E);
18452
18453 // Set up the width and signedness manually, in case it can't be deduced
18454 // from the operation we're performing.
18455 // FIXME: Don't do this in the cases where we can deduce it.
18456 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
18458 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
18459 RHSVal.getInt(), Value))
18460 return false;
18461 return Success(Value, E, Result);
18462}
18463
18464void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
18465 Job &job = Queue.back();
18466
18467 switch (job.Kind) {
18468 case Job::AnyExprKind: {
18469 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
18470 if (shouldEnqueue(Bop)) {
18471 job.Kind = Job::BinOpKind;
18472 enqueue(Bop->getLHS());
18473 return;
18474 }
18475 }
18476
18477 EvaluateExpr(job.E, Result);
18478 Queue.pop_back();
18479 return;
18480 }
18481
18482 case Job::BinOpKind: {
18483 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
18484 bool SuppressRHSDiags = false;
18485 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
18486 Queue.pop_back();
18487 return;
18488 }
18489 if (SuppressRHSDiags)
18490 job.startSpeculativeEval(Info);
18491 job.LHSResult.swap(Result);
18492 job.Kind = Job::BinOpVisitedLHSKind;
18493 enqueue(Bop->getRHS());
18494 return;
18495 }
18496
18497 case Job::BinOpVisitedLHSKind: {
18498 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
18499 EvalResult RHS;
18500 RHS.swap(Result);
18501 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
18502 Queue.pop_back();
18503 return;
18504 }
18505 }
18506
18507 llvm_unreachable("Invalid Job::Kind!");
18508}
18509
18510namespace {
18511enum class CmpResult {
18512 Unequal,
18513 Less,
18514 Equal,
18515 Greater,
18516 Unordered,
18517};
18518}
18519
18520template <class SuccessCB, class AfterCB>
18521static bool
18523 SuccessCB &&Success, AfterCB &&DoAfter) {
18524 assert(!E->isValueDependent());
18525 assert(E->isComparisonOp() && "expected comparison operator");
18526 assert((E->getOpcode() == BO_Cmp ||
18528 "unsupported binary expression evaluation");
18529 auto Error = [&](const Expr *E) {
18530 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
18531 return false;
18532 };
18533
18534 bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp;
18535 bool IsEquality = E->isEqualityOp();
18536
18537 QualType LHSTy = E->getLHS()->getType();
18538 QualType RHSTy = E->getRHS()->getType();
18539
18540 if (LHSTy->isIntegralOrEnumerationType() &&
18541 RHSTy->isIntegralOrEnumerationType()) {
18542 APSInt LHS, RHS;
18543 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
18544 if (!LHSOK && !Info.noteFailure())
18545 return false;
18546 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
18547 return false;
18548 if (LHS < RHS)
18549 return Success(CmpResult::Less, E);
18550 if (LHS > RHS)
18551 return Success(CmpResult::Greater, E);
18552 return Success(CmpResult::Equal, E);
18553 }
18554
18555 if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
18556 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
18557 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
18558
18559 bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
18560 if (!LHSOK && !Info.noteFailure())
18561 return false;
18562 if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
18563 return false;
18564 if (LHSFX < RHSFX)
18565 return Success(CmpResult::Less, E);
18566 if (LHSFX > RHSFX)
18567 return Success(CmpResult::Greater, E);
18568 return Success(CmpResult::Equal, E);
18569 }
18570
18571 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
18572 ComplexValue LHS, RHS;
18573 bool LHSOK;
18574 if (E->isAssignmentOp()) {
18575 LValue LV;
18576 EvaluateLValue(E->getLHS(), LV, Info);
18577 LHSOK = false;
18578 } else if (LHSTy->isRealFloatingType()) {
18579 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
18580 if (LHSOK) {
18581 LHS.makeComplexFloat();
18582 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
18583 }
18584 } else {
18585 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
18586 }
18587 if (!LHSOK && !Info.noteFailure())
18588 return false;
18589
18590 if (E->getRHS()->getType()->isRealFloatingType()) {
18591 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
18592 return false;
18593 RHS.makeComplexFloat();
18594 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
18595 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
18596 return false;
18597
18598 if (LHS.isComplexFloat()) {
18599 APFloat::cmpResult CR_r =
18600 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
18601 APFloat::cmpResult CR_i =
18602 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
18603 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
18604 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
18605 } else {
18606 assert(IsEquality && "invalid complex comparison");
18607 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
18608 LHS.getComplexIntImag() == RHS.getComplexIntImag();
18609 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
18610 }
18611 }
18612
18613 if (LHSTy->isRealFloatingType() &&
18614 RHSTy->isRealFloatingType()) {
18615 APFloat RHS(0.0), LHS(0.0);
18616
18617 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
18618 if (!LHSOK && !Info.noteFailure())
18619 return false;
18620
18621 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
18622 return false;
18623
18624 assert(E->isComparisonOp() && "Invalid binary operator!");
18625 llvm::APFloatBase::cmpResult APFloatCmpResult = LHS.compare(RHS);
18626 if (!Info.InConstantContext &&
18627 APFloatCmpResult == APFloat::cmpUnordered &&
18628 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained()) {
18629 // Note: Compares may raise invalid in some cases involving NaN or sNaN.
18630 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
18631 return false;
18632 }
18633 auto GetCmpRes = [&]() {
18634 switch (APFloatCmpResult) {
18635 case APFloat::cmpEqual:
18636 return CmpResult::Equal;
18637 case APFloat::cmpLessThan:
18638 return CmpResult::Less;
18639 case APFloat::cmpGreaterThan:
18640 return CmpResult::Greater;
18641 case APFloat::cmpUnordered:
18642 return CmpResult::Unordered;
18643 }
18644 llvm_unreachable("Unrecognised APFloat::cmpResult enum");
18645 };
18646 return Success(GetCmpRes(), E);
18647 }
18648
18649 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
18650 LValue LHSValue, RHSValue;
18651
18652 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
18653 if (!LHSOK && !Info.noteFailure())
18654 return false;
18655
18656 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
18657 return false;
18658
18659 // Reject differing bases from the normal codepath; we special-case
18660 // comparisons to null.
18661 if (!HasSameBase(LHSValue, RHSValue)) {
18662 // Bail out early if we're checking potential constant expression.
18663 // Otherwise, prefer to diagnose other issues.
18664 if (Info.checkingPotentialConstantExpression() &&
18665 (LHSValue.AllowConstexprUnknown || RHSValue.AllowConstexprUnknown))
18666 return false;
18667 auto DiagComparison = [&] (unsigned DiagID, bool Reversed = false) {
18668 std::string LHS = LHSValue.toString(Info.Ctx, E->getLHS()->getType());
18669 std::string RHS = RHSValue.toString(Info.Ctx, E->getRHS()->getType());
18670 Info.FFDiag(E, DiagID)
18671 << (Reversed ? RHS : LHS) << (Reversed ? LHS : RHS);
18672 return false;
18673 };
18674 // Inequalities and subtractions between unrelated pointers have
18675 // unspecified or undefined behavior.
18676 if (!IsEquality)
18677 return DiagComparison(
18678 diag::note_constexpr_pointer_comparison_unspecified);
18679 // A constant address may compare equal to the address of a symbol.
18680 // The one exception is that address of an object cannot compare equal
18681 // to a null pointer constant.
18682 // TODO: Should we restrict this to actual null pointers, and exclude the
18683 // case of zero cast to pointer type?
18684 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
18685 (!RHSValue.Base && !RHSValue.Offset.isZero()))
18686 return DiagComparison(diag::note_constexpr_pointer_constant_comparison,
18687 !RHSValue.Base);
18688 // C++2c [intro.object]/10:
18689 // Two objects [...] may have the same address if [...] they are both
18690 // potentially non-unique objects.
18691 // C++2c [intro.object]/9:
18692 // An object is potentially non-unique if it is a string literal object,
18693 // the backing array of an initializer list, or a subobject thereof.
18694 //
18695 // This makes the comparison result unspecified, so it's not a constant
18696 // expression.
18697 //
18698 // TODO: Do we need to handle the initializer list case here?
18699 if (ArePotentiallyOverlappingStringLiterals(Info, LHSValue, RHSValue))
18700 return DiagComparison(diag::note_constexpr_literal_comparison);
18701 if (IsOpaqueConstantCall(LHSValue) || IsOpaqueConstantCall(RHSValue))
18702 return DiagComparison(diag::note_constexpr_opaque_call_comparison,
18703 !IsOpaqueConstantCall(LHSValue));
18704 // We can't tell whether weak symbols will end up pointing to the same
18705 // object.
18706 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
18707 return DiagComparison(diag::note_constexpr_pointer_weak_comparison,
18708 !IsWeakLValue(LHSValue));
18709 // We can't compare the address of the start of one object with the
18710 // past-the-end address of another object, per C++ DR1652.
18711 if (LHSValue.Base && LHSValue.Offset.isZero() &&
18712 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue))
18713 return DiagComparison(diag::note_constexpr_pointer_comparison_past_end,
18714 true);
18715 if (RHSValue.Base && RHSValue.Offset.isZero() &&
18716 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue))
18717 return DiagComparison(diag::note_constexpr_pointer_comparison_past_end,
18718 false);
18719 // We can't tell whether an object is at the same address as another
18720 // zero sized object.
18721 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
18722 (LHSValue.Base && isZeroSized(RHSValue)))
18723 return DiagComparison(
18724 diag::note_constexpr_pointer_comparison_zero_sized);
18725 if (LHSValue.AllowConstexprUnknown || RHSValue.AllowConstexprUnknown)
18726 return DiagComparison(
18727 diag::note_constexpr_pointer_comparison_unspecified);
18728 // FIXME: Verify both variables are live.
18729 return Success(CmpResult::Unequal, E);
18730 }
18731
18732 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
18733 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
18734
18735 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
18736 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
18737
18738 // C++11 [expr.rel]p2:
18739 // - If two pointers point to non-static data members of the same object,
18740 // or to subobjects or array elements fo such members, recursively, the
18741 // pointer to the later declared member compares greater provided the
18742 // two members have the same access control and provided their class is
18743 // not a union.
18744 // [...]
18745 // - Otherwise pointer comparisons are unspecified.
18746 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
18747 bool WasArrayIndex;
18748 unsigned Mismatch = FindDesignatorMismatch(
18749 LHSValue.Base.isNull() ? QualType()
18750 : getType(LHSValue.Base).getNonReferenceType(),
18751 LHSDesignator, RHSDesignator, WasArrayIndex);
18752 // At the point where the designators diverge, the comparison has a
18753 // specified value if:
18754 // - we are comparing array indices
18755 // - we are comparing fields of a union, or fields with the same access
18756 // Otherwise, the result is unspecified and thus the comparison is not a
18757 // constant expression.
18758 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
18759 Mismatch < RHSDesignator.Entries.size()) {
18760 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
18761 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
18762 if (!LF && !RF)
18763 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
18764 else if (!LF)
18765 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
18766 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
18767 << RF->getParent() << RF;
18768 else if (!RF)
18769 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
18770 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
18771 << LF->getParent() << LF;
18772 else if (!LF->getParent()->isUnion() &&
18773 LF->getAccess() != RF->getAccess())
18774 Info.CCEDiag(E,
18775 diag::note_constexpr_pointer_comparison_differing_access)
18776 << LF << LF->getAccess() << RF << RF->getAccess()
18777 << LF->getParent();
18778 }
18779 }
18780
18781 // The comparison here must be unsigned, and performed with the same
18782 // width as the pointer.
18783 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
18784 uint64_t CompareLHS = LHSOffset.getQuantity();
18785 uint64_t CompareRHS = RHSOffset.getQuantity();
18786 assert(PtrSize <= 64 && "Unexpected pointer width");
18787 uint64_t Mask = ~0ULL >> (64 - PtrSize);
18788 CompareLHS &= Mask;
18789 CompareRHS &= Mask;
18790
18791 // If there is a base and this is a relational operator, we can only
18792 // compare pointers within the object in question; otherwise, the result
18793 // depends on where the object is located in memory.
18794 if (!LHSValue.Base.isNull() && IsRelational) {
18795 QualType BaseTy = getType(LHSValue.Base).getNonReferenceType();
18796 if (BaseTy->isIncompleteType())
18797 return Error(E);
18798 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
18799 uint64_t OffsetLimit = Size.getQuantity();
18800 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
18801 return Error(E);
18802 }
18803
18804 if (CompareLHS < CompareRHS)
18805 return Success(CmpResult::Less, E);
18806 if (CompareLHS > CompareRHS)
18807 return Success(CmpResult::Greater, E);
18808 return Success(CmpResult::Equal, E);
18809 }
18810
18811 if (LHSTy->isMemberPointerType()) {
18812 assert(IsEquality && "unexpected member pointer operation");
18813 assert(RHSTy->isMemberPointerType() && "invalid comparison");
18814
18815 MemberPtr LHSValue, RHSValue;
18816
18817 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
18818 if (!LHSOK && !Info.noteFailure())
18819 return false;
18820
18821 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
18822 return false;
18823
18824 // If either operand is a pointer to a weak function, the comparison is not
18825 // constant.
18826 if (LHSValue.getDecl() && LHSValue.getDecl()->isWeak()) {
18827 Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison)
18828 << LHSValue.getDecl();
18829 return false;
18830 }
18831 if (RHSValue.getDecl() && RHSValue.getDecl()->isWeak()) {
18832 Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison)
18833 << RHSValue.getDecl();
18834 return false;
18835 }
18836
18837 // C++11 [expr.eq]p2:
18838 // If both operands are null, they compare equal. Otherwise if only one is
18839 // null, they compare unequal.
18840 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
18841 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
18842 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
18843 }
18844
18845 // Otherwise if either is a pointer to a virtual member function, the
18846 // result is unspecified.
18847 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
18848 if (MD->isVirtual())
18849 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
18850 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
18851 if (MD->isVirtual())
18852 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
18853
18854 // Otherwise they compare equal if and only if they would refer to the
18855 // same member of the same most derived object or the same subobject if
18856 // they were dereferenced with a hypothetical object of the associated
18857 // class type.
18858 bool Equal = LHSValue == RHSValue;
18859 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
18860 }
18861
18862 if (LHSTy->isNullPtrType()) {
18863 assert(E->isComparisonOp() && "unexpected nullptr operation");
18864 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
18865 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
18866 // are compared, the result is true of the operator is <=, >= or ==, and
18867 // false otherwise.
18868 LValue Res;
18869 if (!EvaluatePointer(E->getLHS(), Res, Info) ||
18870 !EvaluatePointer(E->getRHS(), Res, Info))
18871 return false;
18872 return Success(CmpResult::Equal, E);
18873 }
18874
18875 return DoAfter();
18876}
18877
18878bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
18879 if (!CheckLiteralType(Info, E))
18880 return false;
18881
18882 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
18884 switch (CR) {
18885 case CmpResult::Unequal:
18886 llvm_unreachable("should never produce Unequal for three-way comparison");
18887 case CmpResult::Less:
18888 CCR = ComparisonCategoryResult::Less;
18889 break;
18890 case CmpResult::Equal:
18891 CCR = ComparisonCategoryResult::Equal;
18892 break;
18893 case CmpResult::Greater:
18894 CCR = ComparisonCategoryResult::Greater;
18895 break;
18896 case CmpResult::Unordered:
18897 CCR = ComparisonCategoryResult::Unordered;
18898 break;
18899 }
18900 // Evaluation succeeded. Lookup the information for the comparison category
18901 // type and fetch the VarDecl for the result.
18902 const ComparisonCategoryInfo &CmpInfo =
18903 Info.Ctx.CompCategories.getInfoForType(E->getType());
18904 const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD;
18905 // Check and evaluate the result as a constant expression.
18906 LValue LV;
18907 LV.set(VD);
18908 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
18909 return false;
18910 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
18911 ConstantExprKind::Normal);
18912 };
18913 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
18914 return ExprEvaluatorBaseTy::VisitBinCmp(E);
18915 });
18916}
18917
18918bool RecordExprEvaluator::VisitCXXParenListInitExpr(
18919 const CXXParenListInitExpr *E) {
18920 return VisitCXXParenListOrInitListExpr(E, E->getInitExprs());
18921}
18922
18923bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
18924 // We don't support assignment in C. C++ assignments don't get here because
18925 // assignment is an lvalue in C++.
18926 if (E->isAssignmentOp()) {
18927 Error(E);
18928 if (!Info.noteFailure())
18929 return false;
18930 }
18931
18932 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
18933 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
18934
18935 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
18937 "DataRecursiveIntBinOpEvaluator should have handled integral types");
18938
18939 if (E->isComparisonOp()) {
18940 // Evaluate builtin binary comparisons by evaluating them as three-way
18941 // comparisons and then translating the result.
18942 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
18943 assert((CR != CmpResult::Unequal || E->isEqualityOp()) &&
18944 "should only produce Unequal for equality comparisons");
18945 bool IsEqual = CR == CmpResult::Equal,
18946 IsLess = CR == CmpResult::Less,
18947 IsGreater = CR == CmpResult::Greater;
18948 auto Op = E->getOpcode();
18949 switch (Op) {
18950 default:
18951 llvm_unreachable("unsupported binary operator");
18952 case BO_EQ:
18953 case BO_NE:
18954 return Success(IsEqual == (Op == BO_EQ), E);
18955 case BO_LT:
18956 return Success(IsLess, E);
18957 case BO_GT:
18958 return Success(IsGreater, E);
18959 case BO_LE:
18960 return Success(IsEqual || IsLess, E);
18961 case BO_GE:
18962 return Success(IsEqual || IsGreater, E);
18963 }
18964 };
18965 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
18966 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
18967 });
18968 }
18969
18970 QualType LHSTy = E->getLHS()->getType();
18971 QualType RHSTy = E->getRHS()->getType();
18972
18973 if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
18974 E->getOpcode() == BO_Sub) {
18975 LValue LHSValue, RHSValue;
18976
18977 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
18978 if (!LHSOK && !Info.noteFailure())
18979 return false;
18980
18981 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
18982 return false;
18983
18984 // Reject differing bases from the normal codepath; we special-case
18985 // comparisons to null.
18986 if (!HasSameBase(LHSValue, RHSValue)) {
18987 if (Info.checkingPotentialConstantExpression() &&
18988 (LHSValue.AllowConstexprUnknown || RHSValue.AllowConstexprUnknown))
18989 return false;
18990
18991 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
18992 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
18993
18994 auto DiagArith = [&](unsigned DiagID) {
18995 std::string LHS = LHSValue.toString(Info.Ctx, E->getLHS()->getType());
18996 std::string RHS = RHSValue.toString(Info.Ctx, E->getRHS()->getType());
18997 Info.FFDiag(E, DiagID) << LHS << RHS;
18998 if (LHSExpr && LHSExpr == RHSExpr)
18999 Info.Note(LHSExpr->getExprLoc(),
19000 diag::note_constexpr_repeated_literal_eval)
19001 << LHSExpr->getSourceRange();
19002 return false;
19003 };
19004
19005 if (!LHSExpr || !RHSExpr)
19006 return DiagArith(diag::note_constexpr_pointer_arith_unspecified);
19007
19008 if (ArePotentiallyOverlappingStringLiterals(Info, LHSValue, RHSValue))
19009 return DiagArith(diag::note_constexpr_literal_arith);
19010
19011 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
19012 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
19013 if (!LHSAddrExpr || !RHSAddrExpr)
19014 return Error(E);
19015 // Make sure both labels come from the same function.
19016 if (LHSAddrExpr->getLabel()->getDeclContext() !=
19017 RHSAddrExpr->getLabel()->getDeclContext())
19018 return Error(E);
19019 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
19020 }
19021 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
19022 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
19023
19024 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
19025 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
19026
19027 // C++11 [expr.add]p6:
19028 // Unless both pointers point to elements of the same array object, or
19029 // one past the last element of the array object, the behavior is
19030 // undefined.
19031 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
19032 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
19033 RHSDesignator))
19034 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
19035
19036 QualType Type = E->getLHS()->getType();
19037 QualType ElementType = Type->castAs<PointerType>()->getPointeeType();
19038
19039 CharUnits ElementSize;
19040 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
19041 return false;
19042
19043 // As an extension, a type may have zero size (empty struct or union in
19044 // C, array of zero length). Pointer subtraction in such cases has
19045 // undefined behavior, so is not constant.
19046 if (ElementSize.isZero()) {
19047 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
19048 << ElementType;
19049 return false;
19050 }
19051
19052 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
19053 // and produce incorrect results when it overflows. Such behavior
19054 // appears to be non-conforming, but is common, so perhaps we should
19055 // assume the standard intended for such cases to be undefined behavior
19056 // and check for them.
19057
19058 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
19059 // overflow in the final conversion to ptrdiff_t.
19060 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
19061 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
19062 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
19063 false);
19064 APSInt TrueResult = (LHS - RHS) / ElemSize;
19065 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
19066
19067 if (Result.extend(65) != TrueResult &&
19068 !HandleOverflow(Info, E, TrueResult, E->getType()))
19069 return false;
19070 return Success(Result, E);
19071 }
19072
19073 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
19074}
19075
19076/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
19077/// a result as the expression's type.
19078bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
19079 const UnaryExprOrTypeTraitExpr *E) {
19080 switch(E->getKind()) {
19081 case UETT_PreferredAlignOf:
19082 case UETT_AlignOf: {
19083 if (E->isArgumentType())
19084 return Success(
19085 GetAlignOfType(Info.Ctx, E->getArgumentType(), E->getKind()), E);
19086 else
19087 return Success(
19088 GetAlignOfExpr(Info.Ctx, E->getArgumentExpr(), E->getKind()), E);
19089 }
19090
19091 case UETT_PtrAuthTypeDiscriminator: {
19092 if (E->getArgumentType()->isDependentType())
19093 return false;
19094 return Success(
19095 Info.Ctx.getPointerAuthTypeDiscriminator(E->getArgumentType()), E);
19096 }
19097 case UETT_VecStep: {
19098 QualType Ty = E->getTypeOfArgument();
19099
19100 if (Ty->isVectorType()) {
19101 unsigned n = Ty->castAs<VectorType>()->getNumElements();
19102
19103 // The vec_step built-in functions that take a 3-component
19104 // vector return 4. (OpenCL 1.1 spec 6.11.12)
19105 if (n == 3)
19106 n = 4;
19107
19108 return Success(n, E);
19109 } else
19110 return Success(1, E);
19111 }
19112
19113 case UETT_DataSizeOf:
19114 case UETT_SizeOf: {
19115 QualType SrcTy = E->getTypeOfArgument();
19116 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
19117 // the result is the size of the referenced type."
19118 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
19119 SrcTy = Ref->getPointeeType();
19120
19121 CharUnits Sizeof;
19122 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof,
19123 E->getKind() == UETT_DataSizeOf ? SizeOfType::DataSizeOf
19124 : SizeOfType::SizeOf)) {
19125 return false;
19126 }
19127 return Success(Sizeof, E);
19128 }
19129 case UETT_OpenMPRequiredSimdAlign:
19130 assert(E->isArgumentType());
19131 return Success(
19132 Info.Ctx.toCharUnitsFromBits(
19133 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
19134 .getQuantity(),
19135 E);
19136 case UETT_VectorElements: {
19137 QualType Ty = E->getTypeOfArgument();
19138 // If the vector has a fixed size, we can determine the number of elements
19139 // at compile time.
19140 if (const auto *VT = Ty->getAs<VectorType>())
19141 return Success(VT->getNumElements(), E);
19142
19143 assert(Ty->isSizelessVectorType());
19144 if (Info.InConstantContext)
19145 Info.CCEDiag(E, diag::note_constexpr_non_const_vectorelements)
19146 << E->getSourceRange();
19147
19148 return false;
19149 }
19150 case UETT_CountOf: {
19151 QualType Ty = E->getTypeOfArgument();
19152 assert(Ty->isArrayType());
19153
19154 // We don't need to worry about array element qualifiers, so getting the
19155 // unsafe array type is fine.
19156 if (const auto *CAT =
19157 dyn_cast<ConstantArrayType>(Ty->getAsArrayTypeUnsafe())) {
19158 return Success(CAT->getSize(), E);
19159 }
19160
19161 assert(!Ty->isConstantSizeType());
19162
19163 // If it's a variable-length array type, we need to check whether it is a
19164 // multidimensional array. If so, we need to check the size expression of
19165 // the VLA to see if it's a constant size. If so, we can return that value.
19166 const auto *VAT = Info.Ctx.getAsVariableArrayType(Ty);
19167 assert(VAT);
19168 if (VAT->getElementType()->isArrayType()) {
19169 // Variable array size expression could be missing (e.g. int a[*][10]) In
19170 // that case, it can't be a constant expression.
19171 if (!VAT->getSizeExpr()) {
19172 Info.FFDiag(E->getBeginLoc());
19173 return false;
19174 }
19175
19176 std::optional<APSInt> Res =
19177 VAT->getSizeExpr()->getIntegerConstantExpr(Info.Ctx);
19178 if (Res) {
19179 // The resulting value always has type size_t, so we need to make the
19180 // returned APInt have the correct sign and bit-width.
19181 APInt Val{
19182 static_cast<unsigned>(Info.Ctx.getTypeSize(Info.Ctx.getSizeType())),
19183 Res->getZExtValue()};
19184 return Success(Val, E);
19185 }
19186 }
19187
19188 // Definitely a variable-length type, which is not an ICE.
19189 // FIXME: Better diagnostic.
19190 Info.FFDiag(E->getBeginLoc());
19191 return false;
19192 }
19193 }
19194
19195 llvm_unreachable("unknown expr/type trait");
19196}
19197
19198bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
19199 Info.Ctx.recordOffsetOfEvaluation(OOE);
19200 CharUnits Result;
19201 unsigned n = OOE->getNumComponents();
19202 if (n == 0)
19203 return Error(OOE);
19204 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
19205 for (unsigned i = 0; i != n; ++i) {
19206 OffsetOfNode ON = OOE->getComponent(i);
19207 switch (ON.getKind()) {
19208 case OffsetOfNode::Array: {
19209 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
19210 APSInt IdxResult;
19211 if (!EvaluateInteger(Idx, IdxResult, Info))
19212 return false;
19213 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
19214 if (!AT)
19215 return Error(OOE);
19216 CurrentType = AT->getElementType();
19217 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
19218 Result += IdxResult.getSExtValue() * ElementSize;
19219 break;
19220 }
19221
19222 case OffsetOfNode::Field: {
19223 FieldDecl *MemberDecl = ON.getField();
19224 const auto *RD = CurrentType->getAsRecordDecl();
19225 if (!RD)
19226 return Error(OOE);
19227 if (RD->isInvalidDecl()) return false;
19228 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
19229 unsigned i = MemberDecl->getFieldIndex();
19230 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
19231 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
19232 CurrentType = MemberDecl->getType().getNonReferenceType();
19233 break;
19234 }
19235
19237 llvm_unreachable("dependent __builtin_offsetof");
19238
19239 case OffsetOfNode::Base: {
19240 CXXBaseSpecifier *BaseSpec = ON.getBase();
19241 if (BaseSpec->isVirtual())
19242 return Error(OOE);
19243
19244 // Find the layout of the class whose base we are looking into.
19245 const auto *RD = CurrentType->getAsCXXRecordDecl();
19246 if (!RD)
19247 return Error(OOE);
19248 if (RD->isInvalidDecl()) return false;
19249 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
19250
19251 // Find the base class itself.
19252 CurrentType = BaseSpec->getType();
19253 const auto *BaseRD = CurrentType->getAsCXXRecordDecl();
19254 if (!BaseRD)
19255 return Error(OOE);
19256
19257 // Add the offset to the base.
19258 Result += RL.getBaseClassOffset(BaseRD);
19259 break;
19260 }
19261 }
19262 }
19263 return Success(Result, OOE);
19264}
19265
19266bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
19267 switch (E->getOpcode()) {
19268 default:
19269 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
19270 // See C99 6.6p3.
19271 return Error(E);
19272 case UO_Extension:
19273 // FIXME: Should extension allow i-c-e extension expressions in its scope?
19274 // If so, we could clear the diagnostic ID.
19275 return Visit(E->getSubExpr());
19276 case UO_Plus:
19277 // The result is just the value.
19278 return Visit(E->getSubExpr());
19279 case UO_Minus: {
19280 if (!Visit(E->getSubExpr()))
19281 return false;
19282 if (!Result.isInt()) return Error(E);
19283 const APSInt &Value = Result.getInt();
19284 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
19285 !E->getType().isWrapType()) {
19286 if (Info.checkingForUndefinedBehavior())
19287 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
19288 diag::warn_integer_constant_overflow)
19289 << toString(Value, 10, Value.isSigned(), /*formatAsCLiteral=*/false,
19290 /*UpperCase=*/true, /*InsertSeparators=*/true)
19291 << E->getType() << E->getSourceRange();
19292
19293 if (!HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
19294 E->getType()))
19295 return false;
19296 }
19297 return Success(-Value, E);
19298 }
19299 case UO_Not: {
19300 if (!Visit(E->getSubExpr()))
19301 return false;
19302 if (!Result.isInt()) return Error(E);
19303 return Success(~Result.getInt(), E);
19304 }
19305 case UO_LNot: {
19306 bool bres;
19307 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
19308 return false;
19309 return Success(!bres, E);
19310 }
19311 }
19312}
19313
19314/// HandleCast - This is used to evaluate implicit or explicit casts where the
19315/// result type is integer.
19316bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
19317 const Expr *SubExpr = E->getSubExpr();
19318 QualType DestType = E->getType();
19319 QualType SrcType = SubExpr->getType();
19320
19321 switch (E->getCastKind()) {
19322 case CK_BaseToDerived:
19323 case CK_DerivedToBase:
19324 case CK_UncheckedDerivedToBase:
19325 case CK_Dynamic:
19326 case CK_ToUnion:
19327 case CK_ArrayToPointerDecay:
19328 case CK_FunctionToPointerDecay:
19329 case CK_NullToPointer:
19330 case CK_NullToMemberPointer:
19331 case CK_BaseToDerivedMemberPointer:
19332 case CK_DerivedToBaseMemberPointer:
19333 case CK_ReinterpretMemberPointer:
19334 case CK_ConstructorConversion:
19335 case CK_IntegralToPointer:
19336 case CK_ToVoid:
19337 case CK_VectorSplat:
19338 case CK_IntegralToFloating:
19339 case CK_FloatingCast:
19340 case CK_CPointerToObjCPointerCast:
19341 case CK_BlockPointerToObjCPointerCast:
19342 case CK_AnyPointerToBlockPointerCast:
19343 case CK_ObjCObjectLValueCast:
19344 case CK_FloatingRealToComplex:
19345 case CK_FloatingComplexToReal:
19346 case CK_FloatingComplexCast:
19347 case CK_FloatingComplexToIntegralComplex:
19348 case CK_IntegralRealToComplex:
19349 case CK_IntegralComplexCast:
19350 case CK_IntegralComplexToFloatingComplex:
19351 case CK_BuiltinFnToFnPtr:
19352 case CK_ZeroToOCLOpaqueType:
19353 case CK_NonAtomicToAtomic:
19354 case CK_AddressSpaceConversion:
19355 case CK_IntToOCLSampler:
19356 case CK_FloatingToFixedPoint:
19357 case CK_FixedPointToFloating:
19358 case CK_FixedPointCast:
19359 case CK_IntegralToFixedPoint:
19360 case CK_MatrixCast:
19361 case CK_HLSLAggregateSplatCast:
19362 llvm_unreachable("invalid cast kind for integral value");
19363
19364 case CK_BitCast:
19365 case CK_Dependent:
19366 case CK_LValueBitCast:
19367 case CK_ARCProduceObject:
19368 case CK_ARCConsumeObject:
19369 case CK_ARCReclaimReturnedObject:
19370 case CK_ARCExtendBlockObject:
19371 case CK_CopyAndAutoreleaseBlockObject:
19372 return Error(E);
19373
19374 case CK_UserDefinedConversion:
19375 case CK_LValueToRValue:
19376 case CK_AtomicToNonAtomic:
19377 case CK_NoOp:
19378 case CK_LValueToRValueBitCast:
19379 case CK_HLSLArrayRValue:
19380 return ExprEvaluatorBaseTy::VisitCastExpr(E);
19381
19382 case CK_MemberPointerToBoolean:
19383 case CK_PointerToBoolean:
19384 case CK_IntegralToBoolean:
19385 case CK_FloatingToBoolean:
19386 case CK_BooleanToSignedIntegral:
19387 case CK_FloatingComplexToBoolean:
19388 case CK_IntegralComplexToBoolean: {
19389 bool BoolResult;
19390 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
19391 return false;
19392 uint64_t IntResult = BoolResult;
19393 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
19394 IntResult = (uint64_t)-1;
19395 return Success(IntResult, E);
19396 }
19397
19398 case CK_FixedPointToIntegral: {
19399 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
19400 if (!EvaluateFixedPoint(SubExpr, Src, Info))
19401 return false;
19402 bool Overflowed;
19403 llvm::APSInt Result = Src.convertToInt(
19404 Info.Ctx.getIntWidth(DestType),
19405 DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
19406 if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
19407 return false;
19408 return Success(Result, E);
19409 }
19410
19411 case CK_FixedPointToBoolean: {
19412 // Unsigned padding does not affect this.
19413 APValue Val;
19414 if (!Evaluate(Val, Info, SubExpr))
19415 return false;
19416 return Success(Val.getFixedPoint().getBoolValue(), E);
19417 }
19418
19419 case CK_IntegralCast: {
19420 if (!Visit(SubExpr))
19421 return false;
19422
19423 if (!Result.isInt()) {
19424 // Allow casts of address-of-label differences if they are no-ops
19425 // or narrowing, if the result is at least 32 bits wide.
19426 // (The narrowing case isn't actually guaranteed to
19427 // be constant-evaluatable except in some narrow cases which are hard
19428 // to detect here. We let it through on the assumption the user knows
19429 // what they are doing.)
19430 if (Result.isAddrLabelDiff()) {
19431 unsigned DestBits = Info.Ctx.getTypeSize(DestType);
19432 return DestBits >= 32 && DestBits <= Info.Ctx.getTypeSize(SrcType);
19433 }
19434 // Only allow casts of lvalues if they are lossless.
19435 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
19436 }
19437
19438 if (Info.Ctx.getLangOpts().CPlusPlus && DestType->isEnumeralType()) {
19439 const auto *ED = DestType->getAsEnumDecl();
19440 // Check that the value is within the range of the enumeration values.
19441 //
19442 // This corressponds to [expr.static.cast]p10 which says:
19443 // A value of integral or enumeration type can be explicitly converted
19444 // to a complete enumeration type ... If the enumeration type does not
19445 // have a fixed underlying type, the value is unchanged if the original
19446 // value is within the range of the enumeration values ([dcl.enum]), and
19447 // otherwise, the behavior is undefined.
19448 //
19449 // This was resolved as part of DR2338 which has CD5 status.
19450 if (!ED->isFixed()) {
19451 llvm::APInt Min;
19452 llvm::APInt Max;
19453
19454 ED->getValueRange(Max, Min);
19455 --Max;
19456
19457 if (ED->getNumNegativeBits() &&
19458 (Max.slt(Result.getInt().getSExtValue()) ||
19459 Min.sgt(Result.getInt().getSExtValue())))
19460 Info.CCEDiag(E, diag::note_constexpr_unscoped_enum_out_of_range)
19461 << llvm::toString(Result.getInt(), 10) << Min.getSExtValue()
19462 << Max.getSExtValue() << ED;
19463 else if (!ED->getNumNegativeBits() &&
19464 Max.ult(Result.getInt().getZExtValue()))
19465 Info.CCEDiag(E, diag::note_constexpr_unscoped_enum_out_of_range)
19466 << llvm::toString(Result.getInt(), 10) << Min.getZExtValue()
19467 << Max.getZExtValue() << ED;
19468 }
19469 }
19470
19471 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
19472 Result.getInt()), E);
19473 }
19474
19475 case CK_PointerToIntegral: {
19476 CCEDiag(E, diag::note_constexpr_invalid_cast)
19477 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
19478 << Info.Ctx.getLangOpts().CPlusPlus << E->getSourceRange();
19479
19480 LValue LV;
19481 if (!EvaluatePointer(SubExpr, LV, Info))
19482 return false;
19483
19484 if (LV.getLValueBase()) {
19485 // Only allow based lvalue casts if they are lossless.
19486 // FIXME: Allow a larger integer size than the pointer size, and allow
19487 // narrowing back down to pointer width in subsequent integral casts.
19488 // FIXME: Check integer type's active bits, not its type size.
19489 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
19490 return Error(E);
19491
19492 LV.Designator.setInvalid();
19493 LV.moveInto(Result);
19494 return true;
19495 }
19496
19497 APSInt AsInt;
19498 APValue V;
19499 LV.moveInto(V);
19500 if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
19501 llvm_unreachable("Can't cast this!");
19502
19503 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
19504 }
19505
19506 case CK_IntegralComplexToReal: {
19507 ComplexValue C;
19508 if (!EvaluateComplex(SubExpr, C, Info))
19509 return false;
19510 return Success(C.getComplexIntReal(), E);
19511 }
19512
19513 case CK_FloatingToIntegral: {
19514 APFloat F(0.0);
19515 if (!EvaluateFloat(SubExpr, F, Info))
19516 return false;
19517
19518 APSInt Value;
19519 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
19520 return false;
19521 return Success(Value, E);
19522 }
19523 case CK_HLSLVectorTruncation: {
19524 APValue Val;
19525 if (!EvaluateVector(SubExpr, Val, Info))
19526 return Error(E);
19527 return Success(Val.getVectorElt(0), E);
19528 }
19529 case CK_HLSLMatrixTruncation: {
19530 APValue Val;
19531 if (!EvaluateMatrix(SubExpr, Val, Info))
19532 return Error(E);
19533 return Success(Val.getMatrixElt(0, 0), E);
19534 }
19535 case CK_HLSLElementwiseCast: {
19536 SmallVector<APValue> SrcVals;
19537 SmallVector<QualType> SrcTypes;
19538
19539 if (!hlslElementwiseCastHelper(Info, SubExpr, DestType, SrcVals, SrcTypes))
19540 return false;
19541
19542 // cast our single element
19543 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
19544 APValue ResultVal;
19545 if (!handleScalarCast(Info, FPO, E, SrcTypes[0], DestType, SrcVals[0],
19546 ResultVal))
19547 return false;
19548 return Success(ResultVal, E);
19549 }
19550 }
19551
19552 llvm_unreachable("unknown cast resulting in integral value");
19553}
19554
19555bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
19556 if (E->getSubExpr()->getType()->isAnyComplexType()) {
19557 ComplexValue LV;
19558 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
19559 return false;
19560 if (!LV.isComplexInt())
19561 return Error(E);
19562 return Success(LV.getComplexIntReal(), E);
19563 }
19564
19565 return Visit(E->getSubExpr());
19566}
19567
19568bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
19569 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
19570 ComplexValue LV;
19571 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
19572 return false;
19573 if (!LV.isComplexInt())
19574 return Error(E);
19575 return Success(LV.getComplexIntImag(), E);
19576 }
19577
19578 VisitIgnoredValue(E->getSubExpr());
19579 return Success(0, E);
19580}
19581
19582bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
19583 return Success(E->getPackLength(), E);
19584}
19585
19586bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
19587 return Success(E->getValue(), E);
19588}
19589
19590bool IntExprEvaluator::VisitConceptSpecializationExpr(
19591 const ConceptSpecializationExpr *E) {
19592 return Success(E->isSatisfied(), E);
19593}
19594
19595bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) {
19596 return Success(E->isSatisfied(), E);
19597}
19598
19599bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
19600 switch (E->getOpcode()) {
19601 default:
19602 // Invalid unary operators
19603 return Error(E);
19604 case UO_Plus:
19605 // The result is just the value.
19606 return Visit(E->getSubExpr());
19607 case UO_Minus: {
19608 if (!Visit(E->getSubExpr())) return false;
19609 if (!Result.isFixedPoint())
19610 return Error(E);
19611 bool Overflowed;
19612 APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
19613 if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
19614 return false;
19615 return Success(Negated, E);
19616 }
19617 case UO_LNot: {
19618 bool bres;
19619 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
19620 return false;
19621 return Success(!bres, E);
19622 }
19623 }
19624}
19625
19626bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
19627 const Expr *SubExpr = E->getSubExpr();
19628 QualType DestType = E->getType();
19629 assert(DestType->isFixedPointType() &&
19630 "Expected destination type to be a fixed point type");
19631 auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
19632
19633 switch (E->getCastKind()) {
19634 case CK_FixedPointCast: {
19635 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
19636 if (!EvaluateFixedPoint(SubExpr, Src, Info))
19637 return false;
19638 bool Overflowed;
19639 APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
19640 if (Overflowed) {
19641 if (Info.checkingForUndefinedBehavior())
19642 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
19643 diag::warn_fixedpoint_constant_overflow)
19644 << Result.toString() << E->getType();
19645 if (!HandleOverflow(Info, E, Result, E->getType()))
19646 return false;
19647 }
19648 return Success(Result, E);
19649 }
19650 case CK_IntegralToFixedPoint: {
19651 APSInt Src;
19652 if (!EvaluateInteger(SubExpr, Src, Info))
19653 return false;
19654
19655 bool Overflowed;
19656 APFixedPoint IntResult = APFixedPoint::getFromIntValue(
19657 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
19658
19659 if (Overflowed) {
19660 if (Info.checkingForUndefinedBehavior())
19661 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
19662 diag::warn_fixedpoint_constant_overflow)
19663 << IntResult.toString() << E->getType();
19664 if (!HandleOverflow(Info, E, IntResult, E->getType()))
19665 return false;
19666 }
19667
19668 return Success(IntResult, E);
19669 }
19670 case CK_FloatingToFixedPoint: {
19671 APFloat Src(0.0);
19672 if (!EvaluateFloat(SubExpr, Src, Info))
19673 return false;
19674
19675 bool Overflowed;
19676 APFixedPoint Result = APFixedPoint::getFromFloatValue(
19677 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
19678
19679 if (Overflowed) {
19680 if (Info.checkingForUndefinedBehavior())
19681 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
19682 diag::warn_fixedpoint_constant_overflow)
19683 << Result.toString() << E->getType();
19684 if (!HandleOverflow(Info, E, Result, E->getType()))
19685 return false;
19686 }
19687
19688 return Success(Result, E);
19689 }
19690 case CK_NoOp:
19691 case CK_LValueToRValue:
19692 return ExprEvaluatorBaseTy::VisitCastExpr(E);
19693 default:
19694 return Error(E);
19695 }
19696}
19697
19698bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
19699 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
19700 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
19701
19702 const Expr *LHS = E->getLHS();
19703 const Expr *RHS = E->getRHS();
19704 FixedPointSemantics ResultFXSema =
19705 Info.Ctx.getFixedPointSemantics(E->getType());
19706
19707 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
19708 if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
19709 return false;
19710 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
19711 if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
19712 return false;
19713
19714 bool OpOverflow = false, ConversionOverflow = false;
19715 APFixedPoint Result(LHSFX.getSemantics());
19716 switch (E->getOpcode()) {
19717 case BO_Add: {
19718 Result = LHSFX.add(RHSFX, &OpOverflow)
19719 .convert(ResultFXSema, &ConversionOverflow);
19720 break;
19721 }
19722 case BO_Sub: {
19723 Result = LHSFX.sub(RHSFX, &OpOverflow)
19724 .convert(ResultFXSema, &ConversionOverflow);
19725 break;
19726 }
19727 case BO_Mul: {
19728 Result = LHSFX.mul(RHSFX, &OpOverflow)
19729 .convert(ResultFXSema, &ConversionOverflow);
19730 break;
19731 }
19732 case BO_Div: {
19733 if (RHSFX.getValue() == 0) {
19734 Info.FFDiag(E, diag::note_expr_divide_by_zero);
19735 return false;
19736 }
19737 Result = LHSFX.div(RHSFX, &OpOverflow)
19738 .convert(ResultFXSema, &ConversionOverflow);
19739 break;
19740 }
19741 case BO_Shl:
19742 case BO_Shr: {
19743 FixedPointSemantics LHSSema = LHSFX.getSemantics();
19744 llvm::APSInt RHSVal = RHSFX.getValue();
19745
19746 unsigned ShiftBW =
19747 LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding();
19748 unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1);
19749 // Embedded-C 4.1.6.2.2:
19750 // The right operand must be nonnegative and less than the total number
19751 // of (nonpadding) bits of the fixed-point operand ...
19752 if (RHSVal.isNegative())
19753 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal;
19754 else if (Amt != RHSVal)
19755 Info.CCEDiag(E, diag::note_constexpr_large_shift)
19756 << RHSVal << E->getType() << ShiftBW;
19757
19758 if (E->getOpcode() == BO_Shl)
19759 Result = LHSFX.shl(Amt, &OpOverflow);
19760 else
19761 Result = LHSFX.shr(Amt, &OpOverflow);
19762 break;
19763 }
19764 default:
19765 return false;
19766 }
19767 if (OpOverflow || ConversionOverflow) {
19768 if (Info.checkingForUndefinedBehavior())
19769 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
19770 diag::warn_fixedpoint_constant_overflow)
19771 << Result.toString() << E->getType();
19772 if (!HandleOverflow(Info, E, Result, E->getType()))
19773 return false;
19774 }
19775 return Success(Result, E);
19776}
19777
19778//===----------------------------------------------------------------------===//
19779// Float Evaluation
19780//===----------------------------------------------------------------------===//
19781
19782namespace {
19783class FloatExprEvaluator
19784 : public ExprEvaluatorBase<FloatExprEvaluator> {
19785 APFloat &Result;
19786public:
19787 FloatExprEvaluator(EvalInfo &info, APFloat &result)
19788 : ExprEvaluatorBaseTy(info), Result(result) {}
19789
19790 bool Success(const APValue &V, const Expr *e) {
19791 Result = V.getFloat();
19792 return true;
19793 }
19794
19795 bool ZeroInitialization(const Expr *E) {
19796 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
19797 return true;
19798 }
19799
19800 bool VisitCallExpr(const CallExpr *E);
19801
19802 bool VisitUnaryOperator(const UnaryOperator *E);
19803 bool VisitBinaryOperator(const BinaryOperator *E);
19804 bool VisitFloatingLiteral(const FloatingLiteral *E);
19805 bool VisitCastExpr(const CastExpr *E);
19806
19807 bool VisitUnaryReal(const UnaryOperator *E);
19808 bool VisitUnaryImag(const UnaryOperator *E);
19809
19810 // FIXME: Missing: array subscript of vector, member of vector
19811};
19812} // end anonymous namespace
19813
19814static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
19815 assert(!E->isValueDependent());
19816 assert(E->isPRValue() && E->getType()->isRealFloatingType());
19817 return FloatExprEvaluator(Info, Result).Visit(E);
19818}
19819
19820static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
19821 QualType ResultTy,
19822 const Expr *Arg,
19823 bool SNaN,
19824 llvm::APFloat &Result) {
19825 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
19826 if (!S) return false;
19827
19828 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
19829
19830 llvm::APInt fill;
19831
19832 // Treat empty strings as if they were zero.
19833 if (S->getString().empty())
19834 fill = llvm::APInt(32, 0);
19835 else if (S->getString().getAsInteger(0, fill))
19836 return false;
19837
19838 if (Context.getTargetInfo().isNan2008()) {
19839 if (SNaN)
19840 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
19841 else
19842 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
19843 } else {
19844 // Prior to IEEE 754-2008, architectures were allowed to choose whether
19845 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
19846 // a different encoding to what became a standard in 2008, and for pre-
19847 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
19848 // sNaN. This is now known as "legacy NaN" encoding.
19849 if (SNaN)
19850 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
19851 else
19852 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
19853 }
19854
19855 return true;
19856}
19857
19858bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
19859 if (!IsConstantEvaluatedBuiltinCall(E))
19860 return ExprEvaluatorBaseTy::VisitCallExpr(E);
19861
19862 switch (E->getBuiltinCallee()) {
19863 default:
19864 return false;
19865
19866 case Builtin::BI__builtin_huge_val:
19867 case Builtin::BI__builtin_huge_valf:
19868 case Builtin::BI__builtin_huge_vall:
19869 case Builtin::BI__builtin_huge_valf16:
19870 case Builtin::BI__builtin_huge_valf128:
19871 case Builtin::BI__builtin_inf:
19872 case Builtin::BI__builtin_inff:
19873 case Builtin::BI__builtin_infl:
19874 case Builtin::BI__builtin_inff16:
19875 case Builtin::BI__builtin_inff128: {
19876 const llvm::fltSemantics &Sem =
19877 Info.Ctx.getFloatTypeSemantics(E->getType());
19878 Result = llvm::APFloat::getInf(Sem);
19879 return true;
19880 }
19881
19882 case Builtin::BI__builtin_nans:
19883 case Builtin::BI__builtin_nansf:
19884 case Builtin::BI__builtin_nansl:
19885 case Builtin::BI__builtin_nansf16:
19886 case Builtin::BI__builtin_nansf128:
19887 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
19888 true, Result))
19889 return Error(E);
19890 return true;
19891
19892 case Builtin::BI__builtin_nan:
19893 case Builtin::BI__builtin_nanf:
19894 case Builtin::BI__builtin_nanl:
19895 case Builtin::BI__builtin_nanf16:
19896 case Builtin::BI__builtin_nanf128:
19897 // If this is __builtin_nan() turn this into a nan, otherwise we
19898 // can't constant fold it.
19899 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
19900 false, Result))
19901 return Error(E);
19902 return true;
19903
19904 case Builtin::BI__builtin_elementwise_abs:
19905 case Builtin::BI__builtin_fabs:
19906 case Builtin::BI__builtin_fabsf:
19907 case Builtin::BI__builtin_fabsl:
19908 case Builtin::BI__builtin_fabsf128:
19909 // The C standard says "fabs raises no floating-point exceptions,
19910 // even if x is a signaling NaN. The returned value is independent of
19911 // the current rounding direction mode." Therefore constant folding can
19912 // proceed without regard to the floating point settings.
19913 // Reference, WG14 N2478 F.10.4.3
19914 if (!EvaluateFloat(E->getArg(0), Result, Info))
19915 return false;
19916
19917 if (Result.isNegative())
19918 Result.changeSign();
19919 return true;
19920
19921 case Builtin::BI__arithmetic_fence:
19922 return EvaluateFloat(E->getArg(0), Result, Info);
19923
19924 // FIXME: Builtin::BI__builtin_powi
19925 // FIXME: Builtin::BI__builtin_powif
19926 // FIXME: Builtin::BI__builtin_powil
19927
19928 case Builtin::BI__builtin_copysign:
19929 case Builtin::BI__builtin_copysignf:
19930 case Builtin::BI__builtin_copysignl:
19931 case Builtin::BI__builtin_copysignf128: {
19932 APFloat RHS(0.);
19933 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
19934 !EvaluateFloat(E->getArg(1), RHS, Info))
19935 return false;
19936 Result.copySign(RHS);
19937 return true;
19938 }
19939
19940 case Builtin::BI__builtin_fmax:
19941 case Builtin::BI__builtin_fmaxf:
19942 case Builtin::BI__builtin_fmaxl:
19943 case Builtin::BI__builtin_fmaxf16:
19944 case Builtin::BI__builtin_fmaxf128: {
19945 APFloat RHS(0.);
19946 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
19947 !EvaluateFloat(E->getArg(1), RHS, Info))
19948 return false;
19949 Result = maxnum(Result, RHS);
19950 return true;
19951 }
19952
19953 case Builtin::BI__builtin_fmin:
19954 case Builtin::BI__builtin_fminf:
19955 case Builtin::BI__builtin_fminl:
19956 case Builtin::BI__builtin_fminf16:
19957 case Builtin::BI__builtin_fminf128: {
19958 APFloat RHS(0.);
19959 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
19960 !EvaluateFloat(E->getArg(1), RHS, Info))
19961 return false;
19962 Result = minnum(Result, RHS);
19963 return true;
19964 }
19965
19966 case Builtin::BI__builtin_fmaximum_num:
19967 case Builtin::BI__builtin_fmaximum_numf:
19968 case Builtin::BI__builtin_fmaximum_numl:
19969 case Builtin::BI__builtin_fmaximum_numf16:
19970 case Builtin::BI__builtin_fmaximum_numf128: {
19971 APFloat RHS(0.);
19972 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
19973 !EvaluateFloat(E->getArg(1), RHS, Info))
19974 return false;
19975 Result = maximumnum(Result, RHS);
19976 return true;
19977 }
19978
19979 case Builtin::BI__builtin_fminimum_num:
19980 case Builtin::BI__builtin_fminimum_numf:
19981 case Builtin::BI__builtin_fminimum_numl:
19982 case Builtin::BI__builtin_fminimum_numf16:
19983 case Builtin::BI__builtin_fminimum_numf128: {
19984 APFloat RHS(0.);
19985 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
19986 !EvaluateFloat(E->getArg(1), RHS, Info))
19987 return false;
19988 Result = minimumnum(Result, RHS);
19989 return true;
19990 }
19991
19992 case Builtin::BI__builtin_elementwise_fma: {
19993 if (!E->getArg(0)->isPRValue() || !E->getArg(1)->isPRValue() ||
19994 !E->getArg(2)->isPRValue()) {
19995 return false;
19996 }
19997 APFloat SourceY(0.), SourceZ(0.);
19998 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
19999 !EvaluateFloat(E->getArg(1), SourceY, Info) ||
20000 !EvaluateFloat(E->getArg(2), SourceZ, Info))
20001 return false;
20002 llvm::RoundingMode RM = getActiveRoundingMode(getEvalInfo(), E);
20003 (void)Result.fusedMultiplyAdd(SourceY, SourceZ, RM);
20004 return true;
20005 }
20006
20007 case clang::X86::BI__builtin_ia32_vec_ext_v4sf: {
20008 APValue Vec;
20009 APSInt IdxAPS;
20010 if (!EvaluateVector(E->getArg(0), Vec, Info) ||
20011 !EvaluateInteger(E->getArg(1), IdxAPS, Info))
20012 return false;
20013 unsigned N = Vec.getVectorLength();
20014 unsigned Idx = static_cast<unsigned>(IdxAPS.getZExtValue() & (N - 1));
20015 return Success(Vec.getVectorElt(Idx), E);
20016 }
20017 }
20018}
20019
20020bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
20021 if (E->getSubExpr()->getType()->isAnyComplexType()) {
20022 ComplexValue CV;
20023 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
20024 return false;
20025 Result = CV.FloatReal;
20026 return true;
20027 }
20028
20029 return Visit(E->getSubExpr());
20030}
20031
20032bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
20033 if (E->getSubExpr()->getType()->isAnyComplexType()) {
20034 ComplexValue CV;
20035 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
20036 return false;
20037 Result = CV.FloatImag;
20038 return true;
20039 }
20040
20041 VisitIgnoredValue(E->getSubExpr());
20042 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
20043 Result = llvm::APFloat::getZero(Sem);
20044 return true;
20045}
20046
20047bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
20048 switch (E->getOpcode()) {
20049 default: return Error(E);
20050 case UO_Plus:
20051 return EvaluateFloat(E->getSubExpr(), Result, Info);
20052 case UO_Minus:
20053 // In C standard, WG14 N2478 F.3 p4
20054 // "the unary - raises no floating point exceptions,
20055 // even if the operand is signalling."
20056 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
20057 return false;
20058 Result.changeSign();
20059 return true;
20060 }
20061}
20062
20063bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
20064 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
20065 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
20066
20067 APFloat RHS(0.0);
20068 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
20069 if (!LHSOK && !Info.noteFailure())
20070 return false;
20071 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
20072 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
20073}
20074
20075bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
20076 Result = E->getValue();
20077 return true;
20078}
20079
20080bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
20081 const Expr* SubExpr = E->getSubExpr();
20082
20083 switch (E->getCastKind()) {
20084 default:
20085 return ExprEvaluatorBaseTy::VisitCastExpr(E);
20086
20087 case CK_HLSLAggregateSplatCast:
20088 llvm_unreachable("invalid cast kind for floating value");
20089
20090 case CK_IntegralToFloating: {
20091 APSInt IntResult;
20092 const FPOptions FPO = E->getFPFeaturesInEffect(
20093 Info.Ctx.getLangOpts());
20094 return EvaluateInteger(SubExpr, IntResult, Info) &&
20095 HandleIntToFloatCast(Info, E, FPO, SubExpr->getType(),
20096 IntResult, E->getType(), Result);
20097 }
20098
20099 case CK_FixedPointToFloating: {
20100 APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
20101 if (!EvaluateFixedPoint(SubExpr, FixResult, Info))
20102 return false;
20103 Result =
20104 FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->getType()));
20105 return true;
20106 }
20107
20108 case CK_FloatingCast: {
20109 if (!Visit(SubExpr))
20110 return false;
20111 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
20112 Result);
20113 }
20114
20115 case CK_FloatingComplexToReal: {
20116 ComplexValue V;
20117 if (!EvaluateComplex(SubExpr, V, Info))
20118 return false;
20119 Result = V.getComplexFloatReal();
20120 return true;
20121 }
20122 case CK_HLSLVectorTruncation: {
20123 APValue Val;
20124 if (!EvaluateVector(SubExpr, Val, Info))
20125 return Error(E);
20126 return Success(Val.getVectorElt(0), E);
20127 }
20128 case CK_HLSLMatrixTruncation: {
20129 APValue Val;
20130 if (!EvaluateMatrix(SubExpr, Val, Info))
20131 return Error(E);
20132 return Success(Val.getMatrixElt(0, 0), E);
20133 }
20134 case CK_HLSLElementwiseCast: {
20135 SmallVector<APValue> SrcVals;
20136 SmallVector<QualType> SrcTypes;
20137
20138 if (!hlslElementwiseCastHelper(Info, SubExpr, E->getType(), SrcVals,
20139 SrcTypes))
20140 return false;
20141 APValue Val;
20142
20143 // cast our single element
20144 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
20145 APValue ResultVal;
20146 if (!handleScalarCast(Info, FPO, E, SrcTypes[0], E->getType(), SrcVals[0],
20147 ResultVal))
20148 return false;
20149 return Success(ResultVal, E);
20150 }
20151 }
20152}
20153
20154//===----------------------------------------------------------------------===//
20155// Complex Evaluation (for float and integer)
20156//===----------------------------------------------------------------------===//
20157
20158namespace {
20159class ComplexExprEvaluator
20160 : public ExprEvaluatorBase<ComplexExprEvaluator> {
20161 ComplexValue &Result;
20162
20163public:
20164 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
20165 : ExprEvaluatorBaseTy(info), Result(Result) {}
20166
20167 bool Success(const APValue &V, const Expr *e) {
20168 Result.setFrom(V);
20169 return true;
20170 }
20171
20172 bool ZeroInitialization(const Expr *E);
20173
20174 //===--------------------------------------------------------------------===//
20175 // Visitor Methods
20176 //===--------------------------------------------------------------------===//
20177
20178 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
20179 bool VisitCastExpr(const CastExpr *E);
20180 bool VisitBinaryOperator(const BinaryOperator *E);
20181 bool VisitUnaryOperator(const UnaryOperator *E);
20182 bool VisitInitListExpr(const InitListExpr *E);
20183 bool VisitCallExpr(const CallExpr *E);
20184};
20185} // end anonymous namespace
20186
20187static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
20188 EvalInfo &Info) {
20189 assert(!E->isValueDependent());
20190 assert(E->isPRValue() && E->getType()->isAnyComplexType());
20191 return ComplexExprEvaluator(Info, Result).Visit(E);
20192}
20193
20194bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
20195 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
20196 if (ElemTy->isRealFloatingType()) {
20197 Result.makeComplexFloat();
20198 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
20199 Result.FloatReal = Zero;
20200 Result.FloatImag = Zero;
20201 } else {
20202 Result.makeComplexInt();
20203 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
20204 Result.IntReal = Zero;
20205 Result.IntImag = Zero;
20206 }
20207 return true;
20208}
20209
20210bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
20211 const Expr* SubExpr = E->getSubExpr();
20212
20213 if (SubExpr->getType()->isRealFloatingType()) {
20214 Result.makeComplexFloat();
20215 APFloat &Imag = Result.FloatImag;
20216 if (!EvaluateFloat(SubExpr, Imag, Info))
20217 return false;
20218
20219 Result.FloatReal = APFloat(Imag.getSemantics());
20220 return true;
20221 } else {
20222 assert(SubExpr->getType()->isIntegerType() &&
20223 "Unexpected imaginary literal.");
20224
20225 Result.makeComplexInt();
20226 APSInt &Imag = Result.IntImag;
20227 if (!EvaluateInteger(SubExpr, Imag, Info))
20228 return false;
20229
20230 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
20231 return true;
20232 }
20233}
20234
20235bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
20236
20237 switch (E->getCastKind()) {
20238 case CK_BitCast:
20239 case CK_BaseToDerived:
20240 case CK_DerivedToBase:
20241 case CK_UncheckedDerivedToBase:
20242 case CK_Dynamic:
20243 case CK_ToUnion:
20244 case CK_ArrayToPointerDecay:
20245 case CK_FunctionToPointerDecay:
20246 case CK_NullToPointer:
20247 case CK_NullToMemberPointer:
20248 case CK_BaseToDerivedMemberPointer:
20249 case CK_DerivedToBaseMemberPointer:
20250 case CK_MemberPointerToBoolean:
20251 case CK_ReinterpretMemberPointer:
20252 case CK_ConstructorConversion:
20253 case CK_IntegralToPointer:
20254 case CK_PointerToIntegral:
20255 case CK_PointerToBoolean:
20256 case CK_ToVoid:
20257 case CK_VectorSplat:
20258 case CK_IntegralCast:
20259 case CK_BooleanToSignedIntegral:
20260 case CK_IntegralToBoolean:
20261 case CK_IntegralToFloating:
20262 case CK_FloatingToIntegral:
20263 case CK_FloatingToBoolean:
20264 case CK_FloatingCast:
20265 case CK_CPointerToObjCPointerCast:
20266 case CK_BlockPointerToObjCPointerCast:
20267 case CK_AnyPointerToBlockPointerCast:
20268 case CK_ObjCObjectLValueCast:
20269 case CK_FloatingComplexToReal:
20270 case CK_FloatingComplexToBoolean:
20271 case CK_IntegralComplexToReal:
20272 case CK_IntegralComplexToBoolean:
20273 case CK_ARCProduceObject:
20274 case CK_ARCConsumeObject:
20275 case CK_ARCReclaimReturnedObject:
20276 case CK_ARCExtendBlockObject:
20277 case CK_CopyAndAutoreleaseBlockObject:
20278 case CK_BuiltinFnToFnPtr:
20279 case CK_ZeroToOCLOpaqueType:
20280 case CK_NonAtomicToAtomic:
20281 case CK_AddressSpaceConversion:
20282 case CK_IntToOCLSampler:
20283 case CK_FloatingToFixedPoint:
20284 case CK_FixedPointToFloating:
20285 case CK_FixedPointCast:
20286 case CK_FixedPointToBoolean:
20287 case CK_FixedPointToIntegral:
20288 case CK_IntegralToFixedPoint:
20289 case CK_MatrixCast:
20290 case CK_HLSLVectorTruncation:
20291 case CK_HLSLMatrixTruncation:
20292 case CK_HLSLElementwiseCast:
20293 case CK_HLSLAggregateSplatCast:
20294 llvm_unreachable("invalid cast kind for complex value");
20295
20296 case CK_LValueToRValue:
20297 case CK_AtomicToNonAtomic:
20298 case CK_NoOp:
20299 case CK_LValueToRValueBitCast:
20300 case CK_HLSLArrayRValue:
20301 return ExprEvaluatorBaseTy::VisitCastExpr(E);
20302
20303 case CK_Dependent:
20304 case CK_LValueBitCast:
20305 case CK_UserDefinedConversion:
20306 return Error(E);
20307
20308 case CK_FloatingRealToComplex: {
20309 APFloat &Real = Result.FloatReal;
20310 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
20311 return false;
20312
20313 Result.makeComplexFloat();
20314 Result.FloatImag = APFloat(Real.getSemantics());
20315 return true;
20316 }
20317
20318 case CK_FloatingComplexCast: {
20319 if (!Visit(E->getSubExpr()))
20320 return false;
20321
20322 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
20323 QualType From
20324 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
20325
20326 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
20327 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
20328 }
20329
20330 case CK_FloatingComplexToIntegralComplex: {
20331 if (!Visit(E->getSubExpr()))
20332 return false;
20333
20334 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
20335 QualType From
20336 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
20337 Result.makeComplexInt();
20338 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
20339 To, Result.IntReal) &&
20340 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
20341 To, Result.IntImag);
20342 }
20343
20344 case CK_IntegralRealToComplex: {
20345 APSInt &Real = Result.IntReal;
20346 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
20347 return false;
20348
20349 Result.makeComplexInt();
20350 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
20351 return true;
20352 }
20353
20354 case CK_IntegralComplexCast: {
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
20362 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
20363 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
20364 return true;
20365 }
20366
20367 case CK_IntegralComplexToFloatingComplex: {
20368 if (!Visit(E->getSubExpr()))
20369 return false;
20370
20371 const FPOptions FPO = E->getFPFeaturesInEffect(
20372 Info.Ctx.getLangOpts());
20373 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
20374 QualType From
20375 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
20376 Result.makeComplexFloat();
20377 return HandleIntToFloatCast(Info, E, FPO, From, Result.IntReal,
20378 To, Result.FloatReal) &&
20379 HandleIntToFloatCast(Info, E, FPO, From, Result.IntImag,
20380 To, Result.FloatImag);
20381 }
20382 }
20383
20384 llvm_unreachable("unknown cast resulting in complex value");
20385}
20386
20387uint8_t GFNIMultiplicativeInverse(uint8_t Byte) {
20388 // Lookup Table for Multiplicative Inverse in GF(2^8)
20389 const uint8_t GFInv[256] = {
20390 0x00, 0x01, 0x8d, 0xf6, 0xcb, 0x52, 0x7b, 0xd1, 0xe8, 0x4f, 0x29, 0xc0,
20391 0xb0, 0xe1, 0xe5, 0xc7, 0x74, 0xb4, 0xaa, 0x4b, 0x99, 0x2b, 0x60, 0x5f,
20392 0x58, 0x3f, 0xfd, 0xcc, 0xff, 0x40, 0xee, 0xb2, 0x3a, 0x6e, 0x5a, 0xf1,
20393 0x55, 0x4d, 0xa8, 0xc9, 0xc1, 0x0a, 0x98, 0x15, 0x30, 0x44, 0xa2, 0xc2,
20394 0x2c, 0x45, 0x92, 0x6c, 0xf3, 0x39, 0x66, 0x42, 0xf2, 0x35, 0x20, 0x6f,
20395 0x77, 0xbb, 0x59, 0x19, 0x1d, 0xfe, 0x37, 0x67, 0x2d, 0x31, 0xf5, 0x69,
20396 0xa7, 0x64, 0xab, 0x13, 0x54, 0x25, 0xe9, 0x09, 0xed, 0x5c, 0x05, 0xca,
20397 0x4c, 0x24, 0x87, 0xbf, 0x18, 0x3e, 0x22, 0xf0, 0x51, 0xec, 0x61, 0x17,
20398 0x16, 0x5e, 0xaf, 0xd3, 0x49, 0xa6, 0x36, 0x43, 0xf4, 0x47, 0x91, 0xdf,
20399 0x33, 0x93, 0x21, 0x3b, 0x79, 0xb7, 0x97, 0x85, 0x10, 0xb5, 0xba, 0x3c,
20400 0xb6, 0x70, 0xd0, 0x06, 0xa1, 0xfa, 0x81, 0x82, 0x83, 0x7e, 0x7f, 0x80,
20401 0x96, 0x73, 0xbe, 0x56, 0x9b, 0x9e, 0x95, 0xd9, 0xf7, 0x02, 0xb9, 0xa4,
20402 0xde, 0x6a, 0x32, 0x6d, 0xd8, 0x8a, 0x84, 0x72, 0x2a, 0x14, 0x9f, 0x88,
20403 0xf9, 0xdc, 0x89, 0x9a, 0xfb, 0x7c, 0x2e, 0xc3, 0x8f, 0xb8, 0x65, 0x48,
20404 0x26, 0xc8, 0x12, 0x4a, 0xce, 0xe7, 0xd2, 0x62, 0x0c, 0xe0, 0x1f, 0xef,
20405 0x11, 0x75, 0x78, 0x71, 0xa5, 0x8e, 0x76, 0x3d, 0xbd, 0xbc, 0x86, 0x57,
20406 0x0b, 0x28, 0x2f, 0xa3, 0xda, 0xd4, 0xe4, 0x0f, 0xa9, 0x27, 0x53, 0x04,
20407 0x1b, 0xfc, 0xac, 0xe6, 0x7a, 0x07, 0xae, 0x63, 0xc5, 0xdb, 0xe2, 0xea,
20408 0x94, 0x8b, 0xc4, 0xd5, 0x9d, 0xf8, 0x90, 0x6b, 0xb1, 0x0d, 0xd6, 0xeb,
20409 0xc6, 0x0e, 0xcf, 0xad, 0x08, 0x4e, 0xd7, 0xe3, 0x5d, 0x50, 0x1e, 0xb3,
20410 0x5b, 0x23, 0x38, 0x34, 0x68, 0x46, 0x03, 0x8c, 0xdd, 0x9c, 0x7d, 0xa0,
20411 0xcd, 0x1a, 0x41, 0x1c};
20412
20413 return GFInv[Byte];
20414}
20415
20416uint8_t GFNIAffine(uint8_t XByte, const APInt &AQword, const APSInt &Imm,
20417 bool Inverse) {
20418 unsigned NumBitsInByte = 8;
20419 // Computing the affine transformation
20420 uint8_t RetByte = 0;
20421 for (uint32_t BitIdx = 0; BitIdx != NumBitsInByte; ++BitIdx) {
20422 uint8_t AByte =
20423 AQword.lshr((7 - static_cast<int32_t>(BitIdx)) * NumBitsInByte)
20424 .getLoBits(8)
20425 .getZExtValue();
20426 uint8_t Product;
20427 if (Inverse) {
20428 Product = AByte & GFNIMultiplicativeInverse(XByte);
20429 } else {
20430 Product = AByte & XByte;
20431 }
20432 uint8_t Parity = 0;
20433
20434 // Dot product in GF(2) uses XOR instead of addition
20435 for (unsigned PBitIdx = 0; PBitIdx != NumBitsInByte; ++PBitIdx) {
20436 Parity = Parity ^ ((Product >> PBitIdx) & 0x1);
20437 }
20438
20439 uint8_t Temp = Imm[BitIdx] ? 1 : 0;
20440 RetByte |= (Temp ^ Parity) << BitIdx;
20441 }
20442 return RetByte;
20443}
20444
20445uint8_t GFNIMul(uint8_t AByte, uint8_t BByte) {
20446 // Multiplying two polynomials of degree 7
20447 // Polynomial of degree 7
20448 // x^7 + x^6 + x^5 + x^4 + x^3 + x^2 + x + 1
20449 uint16_t TWord = 0;
20450 unsigned NumBitsInByte = 8;
20451 for (unsigned BitIdx = 0; BitIdx != NumBitsInByte; ++BitIdx) {
20452 if ((BByte >> BitIdx) & 0x1) {
20453 TWord = TWord ^ (AByte << BitIdx);
20454 }
20455 }
20456
20457 // When multiplying two polynomials of degree 7
20458 // results in a polynomial of degree 14
20459 // so the result has to be reduced to 7
20460 // Reduction polynomial is x^8 + x^4 + x^3 + x + 1 i.e. 0x11B
20461 for (int32_t BitIdx = 14; BitIdx > 7; --BitIdx) {
20462 if ((TWord >> BitIdx) & 0x1) {
20463 TWord = TWord ^ (0x11B << (BitIdx - 8));
20464 }
20465 }
20466 return (TWord & 0xFF);
20467}
20468
20469void HandleComplexComplexMul(APFloat A, APFloat B, APFloat C, APFloat D,
20470 APFloat &ResR, APFloat &ResI) {
20471 // This is an implementation of complex multiplication according to the
20472 // constraints laid out in C11 Annex G. The implementation uses the
20473 // following naming scheme:
20474 // (a + ib) * (c + id)
20475
20476 APFloat AC = A * C;
20477 APFloat BD = B * D;
20478 APFloat AD = A * D;
20479 APFloat BC = B * C;
20480 ResR = AC - BD;
20481 ResI = AD + BC;
20482 if (ResR.isNaN() && ResI.isNaN()) {
20483 bool Recalc = false;
20484 if (A.isInfinity() || B.isInfinity()) {
20485 A = APFloat::copySign(APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0),
20486 A);
20487 B = APFloat::copySign(APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0),
20488 B);
20489 if (C.isNaN())
20490 C = APFloat::copySign(APFloat(C.getSemantics()), C);
20491 if (D.isNaN())
20492 D = APFloat::copySign(APFloat(D.getSemantics()), D);
20493 Recalc = true;
20494 }
20495 if (C.isInfinity() || D.isInfinity()) {
20496 C = APFloat::copySign(APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0),
20497 C);
20498 D = APFloat::copySign(APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0),
20499 D);
20500 if (A.isNaN())
20501 A = APFloat::copySign(APFloat(A.getSemantics()), A);
20502 if (B.isNaN())
20503 B = APFloat::copySign(APFloat(B.getSemantics()), B);
20504 Recalc = true;
20505 }
20506 if (!Recalc && (AC.isInfinity() || BD.isInfinity() || AD.isInfinity() ||
20507 BC.isInfinity())) {
20508 if (A.isNaN())
20509 A = APFloat::copySign(APFloat(A.getSemantics()), A);
20510 if (B.isNaN())
20511 B = APFloat::copySign(APFloat(B.getSemantics()), B);
20512 if (C.isNaN())
20513 C = APFloat::copySign(APFloat(C.getSemantics()), C);
20514 if (D.isNaN())
20515 D = APFloat::copySign(APFloat(D.getSemantics()), D);
20516 Recalc = true;
20517 }
20518 if (Recalc) {
20519 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
20520 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
20521 }
20522 }
20523}
20524
20525void HandleComplexComplexDiv(APFloat A, APFloat B, APFloat C, APFloat D,
20526 APFloat &ResR, APFloat &ResI) {
20527 // This is an implementation of complex division according to the
20528 // constraints laid out in C11 Annex G. The implementation uses the
20529 // following naming scheme:
20530 // (a + ib) / (c + id)
20531
20532 int DenomLogB = 0;
20533 APFloat MaxCD = maxnum(abs(C), abs(D));
20534 if (MaxCD.isFinite()) {
20535 DenomLogB = ilogb(MaxCD);
20536 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
20537 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
20538 }
20539 APFloat Denom = C * C + D * D;
20540 ResR =
20541 scalbn((A * C + B * D) / Denom, -DenomLogB, APFloat::rmNearestTiesToEven);
20542 ResI =
20543 scalbn((B * C - A * D) / Denom, -DenomLogB, APFloat::rmNearestTiesToEven);
20544 if (ResR.isNaN() && ResI.isNaN()) {
20545 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
20546 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
20547 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
20548 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
20549 D.isFinite()) {
20550 A = APFloat::copySign(APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0),
20551 A);
20552 B = APFloat::copySign(APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0),
20553 B);
20554 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
20555 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
20556 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
20557 C = APFloat::copySign(APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0),
20558 C);
20559 D = APFloat::copySign(APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0),
20560 D);
20561 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
20562 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
20563 }
20564 }
20565}
20566
20568 // Normalize shift amount to [0, BitWidth) range to match runtime behavior
20569 APSInt NormAmt = Amount;
20570 unsigned BitWidth = Value.getBitWidth();
20571 unsigned AmtBitWidth = NormAmt.getBitWidth();
20572 if (BitWidth == 1) {
20573 // Rotating a 1-bit value is always a no-op
20574 NormAmt = APSInt(APInt(AmtBitWidth, 0), NormAmt.isUnsigned());
20575 } else if (BitWidth == 2) {
20576 // For 2-bit values: rotation amount is 0 or 1 based on
20577 // whether the amount is even or odd. We can't use srem here because
20578 // the divisor (2) would be misinterpreted as -2 in 2-bit signed arithmetic.
20579 NormAmt =
20580 APSInt(APInt(AmtBitWidth, NormAmt[0] ? 1 : 0), NormAmt.isUnsigned());
20581 } else {
20582 APInt Divisor;
20583 if (AmtBitWidth > BitWidth) {
20584 Divisor = llvm::APInt(AmtBitWidth, BitWidth);
20585 } else {
20586 Divisor = llvm::APInt(BitWidth, BitWidth);
20587 if (AmtBitWidth < BitWidth) {
20588 NormAmt = NormAmt.extend(BitWidth);
20589 }
20590 }
20591
20592 // Normalize to [0, BitWidth)
20593 if (NormAmt.isSigned()) {
20594 NormAmt = APSInt(NormAmt.srem(Divisor), /*isUnsigned=*/false);
20595 if (NormAmt.isNegative()) {
20596 APSInt SignedDivisor(Divisor, /*isUnsigned=*/false);
20597 NormAmt += SignedDivisor;
20598 }
20599 } else {
20600 NormAmt = APSInt(NormAmt.urem(Divisor), /*isUnsigned=*/true);
20601 }
20602 }
20603
20604 return NormAmt;
20605}
20606
20607bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
20608 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
20609 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
20610
20611 // Track whether the LHS or RHS is real at the type system level. When this is
20612 // the case we can simplify our evaluation strategy.
20613 bool LHSReal = false, RHSReal = false;
20614
20615 bool LHSOK;
20616 if (E->getLHS()->getType()->isRealFloatingType()) {
20617 LHSReal = true;
20618 APFloat &Real = Result.FloatReal;
20619 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
20620 if (LHSOK) {
20621 Result.makeComplexFloat();
20622 Result.FloatImag = APFloat(Real.getSemantics());
20623 }
20624 } else {
20625 LHSOK = Visit(E->getLHS());
20626 }
20627 if (!LHSOK && !Info.noteFailure())
20628 return false;
20629
20630 ComplexValue RHS;
20631 if (E->getRHS()->getType()->isRealFloatingType()) {
20632 RHSReal = true;
20633 APFloat &Real = RHS.FloatReal;
20634 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
20635 return false;
20636 RHS.makeComplexFloat();
20637 RHS.FloatImag = APFloat(Real.getSemantics());
20638 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
20639 return false;
20640
20641 assert(!(LHSReal && RHSReal) &&
20642 "Cannot have both operands of a complex operation be real.");
20643 switch (E->getOpcode()) {
20644 default: return Error(E);
20645 case BO_Add:
20646 if (Result.isComplexFloat()) {
20647 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
20648 APFloat::rmNearestTiesToEven);
20649 if (LHSReal)
20650 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
20651 else if (!RHSReal)
20652 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
20653 APFloat::rmNearestTiesToEven);
20654 } else {
20655 Result.getComplexIntReal() += RHS.getComplexIntReal();
20656 Result.getComplexIntImag() += RHS.getComplexIntImag();
20657 }
20658 break;
20659 case BO_Sub:
20660 if (Result.isComplexFloat()) {
20661 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
20662 APFloat::rmNearestTiesToEven);
20663 if (LHSReal) {
20664 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
20665 Result.getComplexFloatImag().changeSign();
20666 } else if (!RHSReal) {
20667 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
20668 APFloat::rmNearestTiesToEven);
20669 }
20670 } else {
20671 Result.getComplexIntReal() -= RHS.getComplexIntReal();
20672 Result.getComplexIntImag() -= RHS.getComplexIntImag();
20673 }
20674 break;
20675 case BO_Mul:
20676 if (Result.isComplexFloat()) {
20677 // This is an implementation of complex multiplication according to the
20678 // constraints laid out in C11 Annex G. The implementation uses the
20679 // following naming scheme:
20680 // (a + ib) * (c + id)
20681 ComplexValue LHS = Result;
20682 APFloat &A = LHS.getComplexFloatReal();
20683 APFloat &B = LHS.getComplexFloatImag();
20684 APFloat &C = RHS.getComplexFloatReal();
20685 APFloat &D = RHS.getComplexFloatImag();
20686 APFloat &ResR = Result.getComplexFloatReal();
20687 APFloat &ResI = Result.getComplexFloatImag();
20688 if (LHSReal) {
20689 assert(!RHSReal && "Cannot have two real operands for a complex op!");
20690 ResR = A;
20691 ResI = A;
20692 // ResR = A * C;
20693 // ResI = A * D;
20694 if (!handleFloatFloatBinOp(Info, E, ResR, BO_Mul, C) ||
20695 !handleFloatFloatBinOp(Info, E, ResI, BO_Mul, D))
20696 return false;
20697 } else if (RHSReal) {
20698 // ResR = C * A;
20699 // ResI = C * B;
20700 ResR = C;
20701 ResI = C;
20702 if (!handleFloatFloatBinOp(Info, E, ResR, BO_Mul, A) ||
20703 !handleFloatFloatBinOp(Info, E, ResI, BO_Mul, B))
20704 return false;
20705 } else {
20706 HandleComplexComplexMul(A, B, C, D, ResR, ResI);
20707 }
20708 } else {
20709 ComplexValue LHS = Result;
20710 Result.getComplexIntReal() =
20711 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
20712 LHS.getComplexIntImag() * RHS.getComplexIntImag());
20713 Result.getComplexIntImag() =
20714 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
20715 LHS.getComplexIntImag() * RHS.getComplexIntReal());
20716 }
20717 break;
20718 case BO_Div:
20719 if (Result.isComplexFloat()) {
20720 // This is an implementation of complex division according to the
20721 // constraints laid out in C11 Annex G. The implementation uses the
20722 // following naming scheme:
20723 // (a + ib) / (c + id)
20724 ComplexValue LHS = Result;
20725 APFloat &A = LHS.getComplexFloatReal();
20726 APFloat &B = LHS.getComplexFloatImag();
20727 APFloat &C = RHS.getComplexFloatReal();
20728 APFloat &D = RHS.getComplexFloatImag();
20729 APFloat &ResR = Result.getComplexFloatReal();
20730 APFloat &ResI = Result.getComplexFloatImag();
20731 if (RHSReal) {
20732 ResR = A;
20733 ResI = B;
20734 // ResR = A / C;
20735 // ResI = B / C;
20736 if (!handleFloatFloatBinOp(Info, E, ResR, BO_Div, C) ||
20737 !handleFloatFloatBinOp(Info, E, ResI, BO_Div, C))
20738 return false;
20739 } else {
20740 if (LHSReal) {
20741 // No real optimizations we can do here, stub out with zero.
20742 B = APFloat::getZero(A.getSemantics());
20743 }
20744 HandleComplexComplexDiv(A, B, C, D, ResR, ResI);
20745 }
20746 } else {
20747 ComplexValue LHS = Result;
20748 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
20749 RHS.getComplexIntImag() * RHS.getComplexIntImag();
20750 if (Den.isZero())
20751 return Error(E, diag::note_expr_divide_by_zero);
20752
20753 Result.getComplexIntReal() =
20754 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
20755 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
20756 Result.getComplexIntImag() =
20757 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
20758 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
20759 }
20760 break;
20761 }
20762
20763 return true;
20764}
20765
20766bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
20767 // Get the operand value into 'Result'.
20768 if (!Visit(E->getSubExpr()))
20769 return false;
20770
20771 switch (E->getOpcode()) {
20772 default:
20773 return Error(E);
20774 case UO_Extension:
20775 return true;
20776 case UO_Plus:
20777 // The result is always just the subexpr.
20778 return true;
20779 case UO_Minus:
20780 if (Result.isComplexFloat()) {
20781 Result.getComplexFloatReal().changeSign();
20782 Result.getComplexFloatImag().changeSign();
20783 }
20784 else {
20785 Result.getComplexIntReal() = -Result.getComplexIntReal();
20786 Result.getComplexIntImag() = -Result.getComplexIntImag();
20787 }
20788 return true;
20789 case UO_Not:
20790 if (Result.isComplexFloat())
20791 Result.getComplexFloatImag().changeSign();
20792 else
20793 Result.getComplexIntImag() = -Result.getComplexIntImag();
20794 return true;
20795 }
20796}
20797
20798bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
20799 if (E->getNumInits() == 2) {
20800 if (E->getType()->isComplexType()) {
20801 Result.makeComplexFloat();
20802 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
20803 return false;
20804 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
20805 return false;
20806 } else {
20807 Result.makeComplexInt();
20808 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
20809 return false;
20810 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
20811 return false;
20812 }
20813 return true;
20814 }
20815 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
20816}
20817
20818bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) {
20819 if (!IsConstantEvaluatedBuiltinCall(E))
20820 return ExprEvaluatorBaseTy::VisitCallExpr(E);
20821
20822 switch (E->getBuiltinCallee()) {
20823 case Builtin::BI__builtin_complex:
20824 Result.makeComplexFloat();
20825 if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info))
20826 return false;
20827 if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info))
20828 return false;
20829 return true;
20830
20831 default:
20832 return false;
20833 }
20834}
20835
20836//===----------------------------------------------------------------------===//
20837// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
20838// implicit conversion.
20839//===----------------------------------------------------------------------===//
20840
20841namespace {
20842class AtomicExprEvaluator :
20843 public ExprEvaluatorBase<AtomicExprEvaluator> {
20844 const LValue *This;
20845 APValue &Result;
20846public:
20847 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
20848 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
20849
20850 bool Success(const APValue &V, const Expr *E) {
20851 Result = V;
20852 return true;
20853 }
20854
20855 bool ZeroInitialization(const Expr *E) {
20856 ImplicitValueInitExpr VIE(
20857 E->getType()->castAs<AtomicType>()->getValueType());
20858 // For atomic-qualified class (and array) types in C++, initialize the
20859 // _Atomic-wrapped subobject directly, in-place.
20860 return This ? EvaluateInPlace(Result, Info, *This, &VIE)
20861 : Evaluate(Result, Info, &VIE);
20862 }
20863
20864 bool VisitCastExpr(const CastExpr *E) {
20865 switch (E->getCastKind()) {
20866 default:
20867 return ExprEvaluatorBaseTy::VisitCastExpr(E);
20868 case CK_NullToPointer:
20869 VisitIgnoredValue(E->getSubExpr());
20870 return ZeroInitialization(E);
20871 case CK_NonAtomicToAtomic:
20872 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
20873 : Evaluate(Result, Info, E->getSubExpr());
20874 }
20875 }
20876};
20877} // end anonymous namespace
20878
20879static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
20880 EvalInfo &Info) {
20881 assert(!E->isValueDependent());
20882 assert(E->isPRValue() && E->getType()->isAtomicType());
20883 return AtomicExprEvaluator(Info, This, Result).Visit(E);
20884}
20885
20886//===----------------------------------------------------------------------===//
20887// Void expression evaluation, primarily for a cast to void on the LHS of a
20888// comma operator
20889//===----------------------------------------------------------------------===//
20890
20891namespace {
20892class VoidExprEvaluator
20893 : public ExprEvaluatorBase<VoidExprEvaluator> {
20894public:
20895 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
20896
20897 bool Success(const APValue &V, const Expr *e) { return true; }
20898
20899 bool ZeroInitialization(const Expr *E) { return true; }
20900
20901 bool VisitCastExpr(const CastExpr *E) {
20902 switch (E->getCastKind()) {
20903 default:
20904 return ExprEvaluatorBaseTy::VisitCastExpr(E);
20905 case CK_ToVoid:
20906 VisitIgnoredValue(E->getSubExpr());
20907 return true;
20908 }
20909 }
20910
20911 bool VisitCallExpr(const CallExpr *E) {
20912 if (!IsConstantEvaluatedBuiltinCall(E))
20913 return ExprEvaluatorBaseTy::VisitCallExpr(E);
20914
20915 switch (E->getBuiltinCallee()) {
20916 case Builtin::BI__assume:
20917 case Builtin::BI__builtin_assume:
20918 // The argument is not evaluated!
20919 return true;
20920
20921 case Builtin::BI__builtin_operator_delete:
20922 return HandleOperatorDeleteCall(Info, E);
20923
20924 default:
20925 return false;
20926 }
20927 }
20928
20929 bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
20930};
20931} // end anonymous namespace
20932
20933bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
20934 // We cannot speculatively evaluate a delete expression.
20935 if (Info.SpeculativeEvaluationDepth)
20936 return false;
20937
20938 FunctionDecl *OperatorDelete = E->getOperatorDelete();
20939 if (!OperatorDelete
20940 ->isUsableAsGlobalAllocationFunctionInConstantEvaluation()) {
20941 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
20942 << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;
20943 return false;
20944 }
20945
20946 const Expr *Arg = E->getArgument();
20947
20948 LValue Pointer;
20949 if (!EvaluatePointer(Arg, Pointer, Info))
20950 return false;
20951 if (Pointer.Designator.Invalid)
20952 return false;
20953
20954 // Deleting a null pointer has no effect.
20955 if (Pointer.isNullPointer()) {
20956 // This is the only case where we need to produce an extension warning:
20957 // the only other way we can succeed is if we find a dynamic allocation,
20958 // and we will have warned when we allocated it in that case.
20959 if (!Info.getLangOpts().CPlusPlus20)
20960 Info.CCEDiag(E, diag::note_constexpr_new);
20961 return true;
20962 }
20963
20964 std::optional<DynAlloc *> Alloc = CheckDeleteKind(
20965 Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New);
20966 if (!Alloc)
20967 return false;
20968 QualType AllocType = Pointer.Base.getDynamicAllocType();
20969
20970 // For the non-array case, the designator must be empty if the static type
20971 // does not have a virtual destructor.
20972 if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 &&
20974 Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor)
20975 << Arg->getType()->getPointeeType() << AllocType;
20976 return false;
20977 }
20978
20979 // For a class type with a virtual destructor, the selected operator delete
20980 // is the one looked up when building the destructor.
20981 if (!E->isArrayForm() && !E->isGlobalDelete()) {
20982 const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType);
20983 if (VirtualDelete &&
20984 !VirtualDelete
20985 ->isUsableAsGlobalAllocationFunctionInConstantEvaluation()) {
20986 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
20987 << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete;
20988 return false;
20989 }
20990 }
20991
20992 if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(),
20993 (*Alloc)->Value, AllocType))
20994 return false;
20995
20996 if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) {
20997 // The element was already erased. This means the destructor call also
20998 // deleted the object.
20999 // FIXME: This probably results in undefined behavior before we get this
21000 // far, and should be diagnosed elsewhere first.
21001 Info.FFDiag(E, diag::note_constexpr_double_delete);
21002 return false;
21003 }
21004
21005 return true;
21006}
21007
21008static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
21009 assert(!E->isValueDependent());
21010 assert(E->isPRValue() && E->getType()->isVoidType());
21011 return VoidExprEvaluator(Info).Visit(E);
21012}
21013
21014//===----------------------------------------------------------------------===//
21015// Top level Expr::EvaluateAsRValue method.
21016//===----------------------------------------------------------------------===//
21017
21018static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
21019 assert(!E->isValueDependent());
21020 // In C, function designators are not lvalues, but we evaluate them as if they
21021 // are.
21022 QualType T = E->getType();
21023 if (E->isGLValue() || T->isFunctionType()) {
21024 LValue LV;
21025 if (!EvaluateLValue(E, LV, Info))
21026 return false;
21027 LV.moveInto(Result);
21028 } else if (T->isVectorType()) {
21029 if (!EvaluateVector(E, Result, Info))
21030 return false;
21031 } else if (T->isConstantMatrixType()) {
21032 if (!EvaluateMatrix(E, Result, Info))
21033 return false;
21034 } else if (T->isIntegralOrEnumerationType()) {
21035 if (!IntExprEvaluator(Info, Result).Visit(E))
21036 return false;
21037 } else if (T->hasPointerRepresentation()) {
21038 LValue LV;
21039 if (!EvaluatePointer(E, LV, Info))
21040 return false;
21041 LV.moveInto(Result);
21042 } else if (T->isRealFloatingType()) {
21043 llvm::APFloat F(0.0);
21044 if (!EvaluateFloat(E, F, Info))
21045 return false;
21046 Result = APValue(F);
21047 } else if (T->isAnyComplexType()) {
21048 ComplexValue C;
21049 if (!EvaluateComplex(E, C, Info))
21050 return false;
21051 C.moveInto(Result);
21052 } else if (T->isFixedPointType()) {
21053 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
21054 } else if (T->isMemberPointerType()) {
21055 MemberPtr P;
21056 if (!EvaluateMemberPointer(E, P, Info))
21057 return false;
21058 P.moveInto(Result);
21059 return true;
21060 } else if (T->isArrayType()) {
21061 LValue LV;
21062 APValue &Value =
21063 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
21064 if (!EvaluateArray(E, LV, Value, Info))
21065 return false;
21066 Result = Value;
21067 } else if (T->isRecordType()) {
21068 LValue LV;
21069 APValue &Value =
21070 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
21071 if (!EvaluateRecord(E, LV, Value, Info))
21072 return false;
21073 Result = Value;
21074 } else if (T->isVoidType()) {
21075 if (!Info.getLangOpts().CPlusPlus11)
21076 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
21077 << E->getType();
21078 if (!EvaluateVoid(E, Info))
21079 return false;
21080 } else if (T->isAtomicType()) {
21082 if (Unqual->isArrayType() || Unqual->isRecordType()) {
21083 LValue LV;
21084 APValue &Value = Info.CurrentCall->createTemporary(
21085 E, Unqual, ScopeKind::FullExpression, LV);
21086 if (!EvaluateAtomic(E, &LV, Value, Info))
21087 return false;
21088 Result = Value;
21089 } else {
21090 if (!EvaluateAtomic(E, nullptr, Result, Info))
21091 return false;
21092 }
21093 } else if (Info.getLangOpts().CPlusPlus11) {
21094 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
21095 return false;
21096 } else {
21097 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
21098 return false;
21099 }
21100
21101 return true;
21102}
21103
21104/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
21105/// cases, the in-place evaluation is essential, since later initializers for
21106/// an object can indirectly refer to subobjects which were initialized earlier.
21107static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
21108 const Expr *E, bool AllowNonLiteralTypes) {
21109 assert(!E->isValueDependent());
21110
21111 // Normally expressions passed to EvaluateInPlace have a type, but not when
21112 // a VarDecl initializer is evaluated before the untyped ParenListExpr is
21113 // replaced with a CXXConstructExpr. This can happen in LLDB.
21114 if (E->getType().isNull())
21115 return false;
21116
21117 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
21118 return false;
21119
21120 if (E->isPRValue()) {
21121 // Evaluate arrays and record types in-place, so that later initializers can
21122 // refer to earlier-initialized members of the object.
21123 QualType T = E->getType();
21124 if (T->isArrayType())
21125 return EvaluateArray(E, This, Result, Info);
21126 else if (T->isRecordType())
21127 return EvaluateRecord(E, This, Result, Info);
21128 else if (T->isAtomicType()) {
21130 if (Unqual->isArrayType() || Unqual->isRecordType())
21131 return EvaluateAtomic(E, &This, Result, Info);
21132 }
21133 }
21134
21135 // For any other type, in-place evaluation is unimportant.
21136 return Evaluate(Result, Info, E);
21137}
21138
21139/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
21140/// lvalue-to-rvalue cast if it is an lvalue.
21141static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
21142 assert(!E->isValueDependent());
21143
21144 if (E->getType().isNull())
21145 return false;
21146
21147 if (!CheckLiteralType(Info, E))
21148 return false;
21149
21150 if (Info.EnableNewConstInterp) {
21151 if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result))
21152 return false;
21153 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
21154 ConstantExprKind::Normal);
21155 }
21156
21157 if (!::Evaluate(Result, Info, E))
21158 return false;
21159
21160 // Implicit lvalue-to-rvalue cast.
21161 if (E->isGLValue()) {
21162 LValue LV;
21163 LV.setFrom(Info.Ctx, Result);
21164 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
21165 return false;
21166 }
21167
21168 // Check this core constant expression is a constant expression.
21169 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
21170 ConstantExprKind::Normal) &&
21171 CheckMemoryLeaks(Info);
21172}
21173
21174static bool FastEvaluateAsRValue(const Expr *Exp, APValue &Result,
21175 const ASTContext &Ctx, bool &IsConst) {
21176 // Fast-path evaluations of integer literals, since we sometimes see files
21177 // containing vast quantities of these.
21178 if (const auto *L = dyn_cast<IntegerLiteral>(Exp)) {
21179 Result =
21180 APValue(APSInt(L->getValue(), L->getType()->isUnsignedIntegerType()));
21181 IsConst = true;
21182 return true;
21183 }
21184
21185 if (const auto *L = dyn_cast<CXXBoolLiteralExpr>(Exp)) {
21186 Result = APValue(APSInt(APInt(1, L->getValue())));
21187 IsConst = true;
21188 return true;
21189 }
21190
21191 if (const auto *FL = dyn_cast<FloatingLiteral>(Exp)) {
21192 Result = APValue(FL->getValue());
21193 IsConst = true;
21194 return true;
21195 }
21196
21197 if (const auto *L = dyn_cast<CharacterLiteral>(Exp)) {
21198 Result = APValue(Ctx.MakeIntValue(L->getValue(), L->getType()));
21199 IsConst = true;
21200 return true;
21201 }
21202
21203 if (const auto *CE = dyn_cast<ConstantExpr>(Exp)) {
21204 if (CE->hasAPValueResult()) {
21205 APValue APV = CE->getAPValueResult();
21206 if (!APV.isLValue()) {
21207 Result = std::move(APV);
21208 IsConst = true;
21209 return true;
21210 }
21211 }
21212
21213 // The SubExpr is usually just an IntegerLiteral.
21214 return FastEvaluateAsRValue(CE->getSubExpr(), Result, Ctx, IsConst);
21215 }
21216
21217 // This case should be rare, but we need to check it before we check on
21218 // the type below.
21219 if (Exp->getType().isNull()) {
21220 IsConst = false;
21221 return true;
21222 }
21223
21224 return false;
21225}
21226
21229 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
21230 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
21231}
21232
21234 const ASTContext &Ctx, EvalInfo &Info) {
21235 assert(!E->isValueDependent());
21236 bool IsConst;
21237 if (FastEvaluateAsRValue(E, Result.Val, Ctx, IsConst))
21238 return IsConst;
21239
21240 return EvaluateAsRValue(Info, E, Result.Val);
21241}
21242
21244 const ASTContext &Ctx,
21245 Expr::SideEffectsKind AllowSideEffects,
21246 EvalInfo &Info) {
21247 assert(!E->isValueDependent());
21249 return false;
21250
21251 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
21252 !ExprResult.Val.isInt() ||
21253 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
21254 return false;
21255
21256 return true;
21257}
21258
21260 const ASTContext &Ctx,
21261 Expr::SideEffectsKind AllowSideEffects,
21262 EvalInfo &Info) {
21263 assert(!E->isValueDependent());
21264 if (!E->getType()->isFixedPointType())
21265 return false;
21266
21267 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
21268 return false;
21269
21270 if (!ExprResult.Val.isFixedPoint() ||
21271 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
21272 return false;
21273
21274 return true;
21275}
21276
21277/// EvaluateAsRValue - Return true if this is a constant which we can fold using
21278/// any crazy technique (that has nothing to do with language standards) that
21279/// we want to. If this function returns true, it returns the folded constant
21280/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
21281/// will be applied to the result.
21283 bool InConstantContext) const {
21284 assert(!isValueDependent() &&
21285 "Expression evaluator can't be called on a dependent expression.");
21286 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsRValue");
21287 EvalInfo Info(Ctx, Result, EvaluationMode::IgnoreSideEffects);
21288 Info.InConstantContext = InConstantContext;
21289 return ::EvaluateAsRValue(this, Result, Ctx, Info);
21290}
21291
21293 bool InConstantContext) const {
21294 assert(!isValueDependent() &&
21295 "Expression evaluator can't be called on a dependent expression.");
21296 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsBooleanCondition");
21297 EvalResult Scratch;
21298 return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
21299 HandleConversionToBool(Scratch.Val, Result);
21300}
21301
21303 SideEffectsKind AllowSideEffects,
21304 bool InConstantContext) const {
21305 assert(!isValueDependent() &&
21306 "Expression evaluator can't be called on a dependent expression.");
21307 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsInt");
21308 EvalInfo Info(Ctx, Result, EvaluationMode::IgnoreSideEffects);
21309 Info.InConstantContext = InConstantContext;
21310 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
21311}
21312
21314 SideEffectsKind AllowSideEffects,
21315 bool InConstantContext) const {
21316 assert(!isValueDependent() &&
21317 "Expression evaluator can't be called on a dependent expression.");
21318 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFixedPoint");
21319 EvalInfo Info(Ctx, Result, EvaluationMode::IgnoreSideEffects);
21320 Info.InConstantContext = InConstantContext;
21321 return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
21322}
21323
21324bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
21325 SideEffectsKind AllowSideEffects,
21326 bool InConstantContext) const {
21327 assert(!isValueDependent() &&
21328 "Expression evaluator can't be called on a dependent expression.");
21329
21330 if (!getType()->isRealFloatingType())
21331 return false;
21332
21333 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFloat");
21335 if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
21336 !ExprResult.Val.isFloat() ||
21337 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
21338 return false;
21339
21340 Result = ExprResult.Val.getFloat();
21341 return true;
21342}
21343
21345 bool InConstantContext) const {
21346 assert(!isValueDependent() &&
21347 "Expression evaluator can't be called on a dependent expression.");
21348
21349 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsLValue");
21350 EvalInfo Info(Ctx, Result, EvaluationMode::ConstantFold);
21351 Info.InConstantContext = InConstantContext;
21352 LValue LV;
21353 CheckedTemporaries CheckedTemps;
21354
21355 if (Info.EnableNewConstInterp) {
21356 if (!Info.Ctx.getInterpContext().evaluate(Info, this, Result.Val,
21357 ConstantExprKind::Normal))
21358 return false;
21359
21360 LV.setFrom(Ctx, Result.Val);
21362 Info, getExprLoc(), Ctx.getLValueReferenceType(getType()), LV,
21363 ConstantExprKind::Normal, CheckedTemps);
21364 }
21365
21366 if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() ||
21367 Result.HasSideEffects ||
21370 ConstantExprKind::Normal, CheckedTemps))
21371 return false;
21372
21373 LV.moveInto(Result.Val);
21374 return true;
21375}
21376
21378 APValue DestroyedValue, QualType Type,
21379 SourceLocation Loc, Expr::EvalStatus &EStatus,
21380 bool IsConstantDestruction) {
21381 EvalInfo Info(Ctx, EStatus,
21382 IsConstantDestruction ? EvaluationMode::ConstantExpression
21384 Info.setEvaluatingDecl(Base, DestroyedValue,
21385 EvalInfo::EvaluatingDeclKind::Dtor);
21386 Info.InConstantContext = IsConstantDestruction;
21387
21388 LValue LVal;
21389 LVal.set(Base);
21390
21391 if (!HandleDestruction(Info, Loc, Base, DestroyedValue, Type) ||
21392 EStatus.HasSideEffects)
21393 return false;
21394
21395 if (!Info.discardCleanups())
21396 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
21397
21398 return true;
21399}
21400
21402 ConstantExprKind Kind) const {
21403 assert(!isValueDependent() &&
21404 "Expression evaluator can't be called on a dependent expression.");
21405 bool IsConst;
21406 if (FastEvaluateAsRValue(this, Result.Val, Ctx, IsConst) &&
21407 Result.Val.hasValue())
21408 return true;
21409
21410 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsConstantExpr");
21412 EvalInfo Info(Ctx, Result, EM);
21413 Info.InConstantContext = true;
21414
21415 if (Info.EnableNewConstInterp) {
21416 if (!Info.Ctx.getInterpContext().evaluate(Info, this, Result.Val, Kind))
21417 return false;
21418 return CheckConstantExpression(Info, getExprLoc(),
21419 getStorageType(Ctx, this), Result.Val, Kind);
21420 }
21421
21422 // The type of the object we're initializing is 'const T' for a class NTTP.
21423 QualType T = getType();
21424 if (Kind == ConstantExprKind::ClassTemplateArgument)
21425 T.addConst();
21426
21427 // If we're evaluating a prvalue, fake up a MaterializeTemporaryExpr to
21428 // represent the result of the evaluation. CheckConstantExpression ensures
21429 // this doesn't escape.
21430 MaterializeTemporaryExpr BaseMTE(T, const_cast<Expr*>(this), true);
21431 APValue::LValueBase Base(&BaseMTE);
21432 Info.setEvaluatingDecl(Base, Result.Val);
21433
21434 LValue LVal;
21435 LVal.set(Base);
21436 // C++23 [intro.execution]/p5
21437 // A full-expression is [...] a constant-expression
21438 // So we need to make sure temporary objects are destroyed after having
21439 // evaluating the expression (per C++23 [class.temporary]/p4).
21440 FullExpressionRAII Scope(Info);
21441 if (!::EvaluateInPlace(Result.Val, Info, LVal, this) ||
21442 Result.HasSideEffects || !Scope.destroy())
21443 return false;
21444
21445 if (!Info.discardCleanups())
21446 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
21447
21448 if (!CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this),
21449 Result.Val, Kind))
21450 return false;
21451 if (!CheckMemoryLeaks(Info))
21452 return false;
21453
21454 // If this is a class template argument, it's required to have constant
21455 // destruction too.
21456 if (Kind == ConstantExprKind::ClassTemplateArgument &&
21458 true) ||
21459 Result.HasSideEffects)) {
21460 // FIXME: Prefix a note to indicate that the problem is lack of constant
21461 // destruction.
21462 return false;
21463 }
21464
21465 return true;
21466}
21467
21469 const VarDecl *VD,
21471 bool IsConstantInitialization) const {
21472 assert(!isValueDependent() &&
21473 "Expression evaluator can't be called on a dependent expression.");
21474 assert(VD && "Need a valid VarDecl");
21475
21476 llvm::TimeTraceScope TimeScope("EvaluateAsInitializer", [&] {
21477 std::string Name;
21478 llvm::raw_string_ostream OS(Name);
21479 VD->printQualifiedName(OS);
21480 return Name;
21481 });
21482
21483 Expr::EvalStatus EStatus;
21484 EStatus.Diag = &Notes;
21485
21486 EvalInfo Info(Ctx, EStatus,
21487 (IsConstantInitialization &&
21488 (Ctx.getLangOpts().CPlusPlus || Ctx.getLangOpts().C23))
21491 Info.setEvaluatingDecl(VD, Value);
21492 Info.InConstantContext = IsConstantInitialization;
21493
21494 SourceLocation DeclLoc = VD->getLocation();
21495 QualType DeclTy = VD->getType();
21496
21497 if (Info.EnableNewConstInterp) {
21498 auto &InterpCtx = Ctx.getInterpContext();
21499 if (!InterpCtx.evaluateAsInitializer(Info, VD, this, Value))
21500 return false;
21501
21502 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value,
21503 ConstantExprKind::Normal);
21504 } else {
21505 LValue LVal;
21506 LVal.set(VD);
21507
21508 {
21509 // C++23 [intro.execution]/p5
21510 // A full-expression is ... an init-declarator ([dcl.decl]) or a
21511 // mem-initializer.
21512 // So we need to make sure temporary objects are destroyed after having
21513 // evaluated the expression (per C++23 [class.temporary]/p4).
21514 //
21515 // FIXME: Otherwise this may break test/Modules/pr68702.cpp because the
21516 // serialization code calls ParmVarDecl::getDefaultArg() which strips the
21517 // outermost FullExpr, such as ExprWithCleanups.
21518 FullExpressionRAII Scope(Info);
21519 if (!EvaluateInPlace(Value, Info, LVal, this,
21520 /*AllowNonLiteralTypes=*/true) ||
21521 EStatus.HasSideEffects)
21522 return false;
21523 }
21524
21525 // At this point, any lifetime-extended temporaries are completely
21526 // initialized.
21527 Info.performLifetimeExtension();
21528
21529 if (!Info.discardCleanups())
21530 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
21531 }
21532
21533 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value,
21534 ConstantExprKind::Normal) &&
21535 CheckMemoryLeaks(Info);
21536}
21537
21540 Expr::EvalStatus EStatus;
21541 EStatus.Diag = &Notes;
21542
21543 // Only treat the destruction as constant destruction if we formally have
21544 // constant initialization (or are usable in a constant expression).
21545 bool IsConstantDestruction = hasConstantInitialization();
21546
21547 // Make a copy of the value for the destructor to mutate, if we know it.
21548 // Otherwise, treat the value as default-initialized; if the destructor works
21549 // anyway, then the destruction is constant (and must be essentially empty).
21550 APValue DestroyedValue;
21551 if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent())
21552 DestroyedValue = *getEvaluatedValue();
21553 else if (!handleDefaultInitValue(getType(), DestroyedValue))
21554 return false;
21555
21556 if (!EvaluateDestruction(getASTContext(), this, std::move(DestroyedValue),
21557 getType(), getLocation(), EStatus,
21558 IsConstantDestruction) ||
21559 EStatus.HasSideEffects)
21560 return false;
21561
21562 ensureEvaluatedStmt()->HasConstantDestruction = true;
21563 return true;
21564}
21565
21566/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
21567/// constant folded, but discard the result.
21569 assert(!isValueDependent() &&
21570 "Expression evaluator can't be called on a dependent expression.");
21571
21573 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
21575}
21576
21577APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
21578 assert(!isValueDependent() &&
21579 "Expression evaluator can't be called on a dependent expression.");
21580
21581 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstInt");
21582 EvalResult EVResult;
21583 EvalInfo Info(Ctx, EVResult, EvaluationMode::IgnoreSideEffects);
21584 Info.InConstantContext = true;
21585
21586 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
21587 (void)Result;
21588 assert(Result && "Could not evaluate expression");
21589 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
21590
21591 return EVResult.Val.getInt();
21592}
21593
21596 assert(!isValueDependent() &&
21597 "Expression evaluator can't be called on a dependent expression.");
21598
21599 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstIntCheckOverflow");
21600 EvalResult EVResult;
21601 EVResult.Diag = Diag;
21602 EvalInfo Info(Ctx, EVResult, EvaluationMode::IgnoreSideEffects);
21603 Info.InConstantContext = true;
21604 Info.CheckingForUndefinedBehavior = true;
21605
21606 bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
21607 (void)Result;
21608 assert(Result && "Could not evaluate expression");
21609 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
21610
21611 return EVResult.Val.getInt();
21612}
21613
21615 assert(!isValueDependent() &&
21616 "Expression evaluator can't be called on a dependent expression.");
21617
21618 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateForOverflow");
21619 bool IsConst;
21620 EvalResult EVResult;
21621 if (!FastEvaluateAsRValue(this, EVResult.Val, Ctx, IsConst)) {
21622 EvalInfo Info(Ctx, EVResult, EvaluationMode::IgnoreSideEffects);
21623 Info.CheckingForUndefinedBehavior = true;
21624 (void)::EvaluateAsRValue(Info, this, EVResult.Val);
21625 }
21626}
21627
21629 assert(Val.isLValue());
21630 return IsGlobalLValue(Val.getLValueBase());
21631}
21632
21633/// isIntegerConstantExpr - this recursive routine will test if an expression is
21634/// an integer constant expression.
21635
21636/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
21637/// comma, etc
21638
21639// CheckICE - This function does the fundamental ICE checking: the returned
21640// ICEDiag contains an ICEKind indicating whether the expression is an ICE.
21641//
21642// Note that to reduce code duplication, this helper does no evaluation
21643// itself; the caller checks whether the expression is evaluatable, and
21644// in the rare cases where CheckICE actually cares about the evaluated
21645// value, it calls into Evaluate.
21646
21647namespace {
21648
21649enum ICEKind {
21650 /// This expression is an ICE.
21651 IK_ICE,
21652 /// This expression is not an ICE, but if it isn't evaluated, it's
21653 /// a legal subexpression for an ICE. This return value is used to handle
21654 /// the comma operator in C99 mode, and non-constant subexpressions.
21655 IK_ICEIfUnevaluated,
21656 /// This expression is not an ICE, and is not a legal subexpression for one.
21657 IK_NotICE
21658};
21659
21660struct ICEDiag {
21661 ICEKind Kind;
21662 SourceLocation Loc;
21663
21664 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
21665};
21666
21667}
21668
21669static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
21670
21671static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
21672
21673static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
21674 Expr::EvalResult EVResult;
21675 Expr::EvalStatus Status;
21676 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantExpression);
21677
21678 Info.InConstantContext = true;
21679 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
21680 !EVResult.Val.isInt())
21681 return ICEDiag(IK_NotICE, E->getBeginLoc());
21682
21683 return NoDiag();
21684}
21685
21686static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
21687 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
21689 return ICEDiag(IK_NotICE, E->getBeginLoc());
21690
21691 switch (E->getStmtClass()) {
21692#define ABSTRACT_STMT(Node)
21693#define STMT(Node, Base) case Expr::Node##Class:
21694#define EXPR(Node, Base)
21695#include "clang/AST/StmtNodes.inc"
21696 case Expr::PredefinedExprClass:
21697 case Expr::FloatingLiteralClass:
21698 case Expr::ImaginaryLiteralClass:
21699 case Expr::StringLiteralClass:
21700 case Expr::ArraySubscriptExprClass:
21701 case Expr::MatrixSingleSubscriptExprClass:
21702 case Expr::MatrixSubscriptExprClass:
21703 case Expr::ArraySectionExprClass:
21704 case Expr::OMPArrayShapingExprClass:
21705 case Expr::OMPIteratorExprClass:
21706 case Expr::CompoundAssignOperatorClass:
21707 case Expr::CompoundLiteralExprClass:
21708 case Expr::ExtVectorElementExprClass:
21709 case Expr::MatrixElementExprClass:
21710 case Expr::DesignatedInitExprClass:
21711 case Expr::ArrayInitLoopExprClass:
21712 case Expr::ArrayInitIndexExprClass:
21713 case Expr::NoInitExprClass:
21714 case Expr::DesignatedInitUpdateExprClass:
21715 case Expr::ImplicitValueInitExprClass:
21716 case Expr::ParenListExprClass:
21717 case Expr::VAArgExprClass:
21718 case Expr::AddrLabelExprClass:
21719 case Expr::StmtExprClass:
21720 case Expr::CXXMemberCallExprClass:
21721 case Expr::CUDAKernelCallExprClass:
21722 case Expr::CXXAddrspaceCastExprClass:
21723 case Expr::CXXDynamicCastExprClass:
21724 case Expr::CXXTypeidExprClass:
21725 case Expr::CXXUuidofExprClass:
21726 case Expr::MSPropertyRefExprClass:
21727 case Expr::MSPropertySubscriptExprClass:
21728 case Expr::CXXNullPtrLiteralExprClass:
21729 case Expr::UserDefinedLiteralClass:
21730 case Expr::CXXThisExprClass:
21731 case Expr::CXXThrowExprClass:
21732 case Expr::CXXNewExprClass:
21733 case Expr::CXXDeleteExprClass:
21734 case Expr::CXXPseudoDestructorExprClass:
21735 case Expr::UnresolvedLookupExprClass:
21736 case Expr::RecoveryExprClass:
21737 case Expr::DependentScopeDeclRefExprClass:
21738 case Expr::CXXConstructExprClass:
21739 case Expr::CXXInheritedCtorInitExprClass:
21740 case Expr::CXXStdInitializerListExprClass:
21741 case Expr::CXXBindTemporaryExprClass:
21742 case Expr::ExprWithCleanupsClass:
21743 case Expr::CXXTemporaryObjectExprClass:
21744 case Expr::CXXUnresolvedConstructExprClass:
21745 case Expr::CXXDependentScopeMemberExprClass:
21746 case Expr::UnresolvedMemberExprClass:
21747 case Expr::ObjCStringLiteralClass:
21748 case Expr::ObjCBoxedExprClass:
21749 case Expr::ObjCArrayLiteralClass:
21750 case Expr::ObjCDictionaryLiteralClass:
21751 case Expr::ObjCEncodeExprClass:
21752 case Expr::ObjCMessageExprClass:
21753 case Expr::ObjCSelectorExprClass:
21754 case Expr::ObjCProtocolExprClass:
21755 case Expr::ObjCIvarRefExprClass:
21756 case Expr::ObjCPropertyRefExprClass:
21757 case Expr::ObjCSubscriptRefExprClass:
21758 case Expr::ObjCIsaExprClass:
21759 case Expr::ObjCAvailabilityCheckExprClass:
21760 case Expr::ShuffleVectorExprClass:
21761 case Expr::ConvertVectorExprClass:
21762 case Expr::BlockExprClass:
21763 case Expr::NoStmtClass:
21764 case Expr::OpaqueValueExprClass:
21765 case Expr::PackExpansionExprClass:
21766 case Expr::SubstNonTypeTemplateParmPackExprClass:
21767 case Expr::FunctionParmPackExprClass:
21768 case Expr::AsTypeExprClass:
21769 case Expr::ObjCIndirectCopyRestoreExprClass:
21770 case Expr::MaterializeTemporaryExprClass:
21771 case Expr::PseudoObjectExprClass:
21772 case Expr::AtomicExprClass:
21773 case Expr::LambdaExprClass:
21774 case Expr::CXXFoldExprClass:
21775 case Expr::CoawaitExprClass:
21776 case Expr::DependentCoawaitExprClass:
21777 case Expr::CoyieldExprClass:
21778 case Expr::SYCLUniqueStableNameExprClass:
21779 case Expr::CXXParenListInitExprClass:
21780 case Expr::HLSLOutArgExprClass:
21781 return ICEDiag(IK_NotICE, E->getBeginLoc());
21782
21783 case Expr::MemberExprClass: {
21784 if (Ctx.getLangOpts().C23) {
21785 const Expr *ME = E->IgnoreParenImpCasts();
21786 while (const auto *M = dyn_cast<MemberExpr>(ME)) {
21787 if (M->isArrow())
21788 return ICEDiag(IK_NotICE, E->getBeginLoc());
21789 ME = M->getBase()->IgnoreParenImpCasts();
21790 }
21791 const auto *DRE = dyn_cast<DeclRefExpr>(ME);
21792 if (DRE) {
21793 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
21794 VD && VD->isConstexpr())
21795 return CheckEvalInICE(E, Ctx);
21796 }
21797 }
21798 return ICEDiag(IK_NotICE, E->getBeginLoc());
21799 }
21800
21801 case Expr::InitListExprClass: {
21802 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
21803 // form "T x = { a };" is equivalent to "T x = a;".
21804 // Unless we're initializing a reference, T is a scalar as it is known to be
21805 // of integral or enumeration type.
21806 if (E->isPRValue())
21807 if (cast<InitListExpr>(E)->getNumInits() == 1)
21808 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
21809 return ICEDiag(IK_NotICE, E->getBeginLoc());
21810 }
21811
21812 case Expr::SizeOfPackExprClass:
21813 case Expr::GNUNullExprClass:
21814 case Expr::SourceLocExprClass:
21815 case Expr::EmbedExprClass:
21816 case Expr::OpenACCAsteriskSizeExprClass:
21817 return NoDiag();
21818
21819 case Expr::PackIndexingExprClass:
21820 return CheckICE(cast<PackIndexingExpr>(E)->getSelectedExpr(), Ctx);
21821
21822 case Expr::SubstNonTypeTemplateParmExprClass:
21823 return
21824 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
21825
21826 case Expr::ConstantExprClass:
21827 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
21828
21829 case Expr::ParenExprClass:
21830 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
21831 case Expr::GenericSelectionExprClass:
21832 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
21833 case Expr::IntegerLiteralClass:
21834 case Expr::FixedPointLiteralClass:
21835 case Expr::CharacterLiteralClass:
21836 case Expr::ObjCBoolLiteralExprClass:
21837 case Expr::CXXBoolLiteralExprClass:
21838 case Expr::CXXScalarValueInitExprClass:
21839 case Expr::TypeTraitExprClass:
21840 case Expr::ConceptSpecializationExprClass:
21841 case Expr::RequiresExprClass:
21842 case Expr::ArrayTypeTraitExprClass:
21843 case Expr::ExpressionTraitExprClass:
21844 case Expr::CXXNoexceptExprClass:
21845 case Expr::CXXReflectExprClass:
21846 return NoDiag();
21847 case Expr::CallExprClass:
21848 case Expr::CXXOperatorCallExprClass: {
21849 // C99 6.6/3 allows function calls within unevaluated subexpressions of
21850 // constant expressions, but they can never be ICEs because an ICE cannot
21851 // contain an operand of (pointer to) function type.
21852 const CallExpr *CE = cast<CallExpr>(E);
21853 if (CE->getBuiltinCallee())
21854 return CheckEvalInICE(E, Ctx);
21855 return ICEDiag(IK_NotICE, E->getBeginLoc());
21856 }
21857 case Expr::CXXRewrittenBinaryOperatorClass:
21858 return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(),
21859 Ctx);
21860 case Expr::DeclRefExprClass: {
21861 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
21862 if (isa<EnumConstantDecl>(D))
21863 return NoDiag();
21864
21865 // C++ and OpenCL (FIXME: spec reference?) allow reading const-qualified
21866 // integer variables in constant expressions:
21867 //
21868 // C++ 7.1.5.1p2
21869 // A variable of non-volatile const-qualified integral or enumeration
21870 // type initialized by an ICE can be used in ICEs.
21871 //
21872 // We sometimes use CheckICE to check the C++98 rules in C++11 mode. In
21873 // that mode, use of reference variables should not be allowed.
21874 const VarDecl *VD = dyn_cast<VarDecl>(D);
21875 if (VD && VD->isUsableInConstantExpressions(Ctx) &&
21876 !VD->getType()->isReferenceType())
21877 return NoDiag();
21878
21879 return ICEDiag(IK_NotICE, E->getBeginLoc());
21880 }
21881 case Expr::UnaryOperatorClass: {
21882 const UnaryOperator *Exp = cast<UnaryOperator>(E);
21883 switch (Exp->getOpcode()) {
21884 case UO_PostInc:
21885 case UO_PostDec:
21886 case UO_PreInc:
21887 case UO_PreDec:
21888 case UO_AddrOf:
21889 case UO_Deref:
21890 case UO_Coawait:
21891 // C99 6.6/3 allows increment and decrement within unevaluated
21892 // subexpressions of constant expressions, but they can never be ICEs
21893 // because an ICE cannot contain an lvalue operand.
21894 return ICEDiag(IK_NotICE, E->getBeginLoc());
21895 case UO_Extension:
21896 case UO_LNot:
21897 case UO_Plus:
21898 case UO_Minus:
21899 case UO_Not:
21900 case UO_Real:
21901 case UO_Imag:
21902 return CheckICE(Exp->getSubExpr(), Ctx);
21903 }
21904 llvm_unreachable("invalid unary operator class");
21905 }
21906 case Expr::OffsetOfExprClass: {
21907 // Note that per C99, offsetof must be an ICE. And AFAIK, using
21908 // EvaluateAsRValue matches the proposed gcc behavior for cases like
21909 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
21910 // compliance: we should warn earlier for offsetof expressions with
21911 // array subscripts that aren't ICEs, and if the array subscripts
21912 // are ICEs, the value of the offsetof must be an integer constant.
21913 return CheckEvalInICE(E, Ctx);
21914 }
21915 case Expr::UnaryExprOrTypeTraitExprClass: {
21917 if ((Exp->getKind() == UETT_SizeOf) &&
21919 return ICEDiag(IK_NotICE, E->getBeginLoc());
21920 if (Exp->getKind() == UETT_CountOf) {
21921 QualType ArgTy = Exp->getTypeOfArgument();
21922 if (ArgTy->isVariableArrayType()) {
21923 // We need to look whether the array is multidimensional. If it is,
21924 // then we want to check the size expression manually to see whether
21925 // it is an ICE or not.
21926 const auto *VAT = Ctx.getAsVariableArrayType(ArgTy);
21927 if (VAT->getElementType()->isArrayType())
21928 // Variable array size expression could be missing (e.g. int a[*][10])
21929 // In that case, it can't be a constant expression.
21930 return VAT->getSizeExpr() ? CheckICE(VAT->getSizeExpr(), Ctx)
21931 : ICEDiag(IK_NotICE, E->getBeginLoc());
21932
21933 // Otherwise, this is a regular VLA, which is definitely not an ICE.
21934 return ICEDiag(IK_NotICE, E->getBeginLoc());
21935 }
21936 }
21937 return NoDiag();
21938 }
21939 case Expr::BinaryOperatorClass: {
21940 const BinaryOperator *Exp = cast<BinaryOperator>(E);
21941 switch (Exp->getOpcode()) {
21942 case BO_PtrMemD:
21943 case BO_PtrMemI:
21944 case BO_Assign:
21945 case BO_MulAssign:
21946 case BO_DivAssign:
21947 case BO_RemAssign:
21948 case BO_AddAssign:
21949 case BO_SubAssign:
21950 case BO_ShlAssign:
21951 case BO_ShrAssign:
21952 case BO_AndAssign:
21953 case BO_XorAssign:
21954 case BO_OrAssign:
21955 // C99 6.6/3 allows assignments within unevaluated subexpressions of
21956 // constant expressions, but they can never be ICEs because an ICE cannot
21957 // contain an lvalue operand.
21958 return ICEDiag(IK_NotICE, E->getBeginLoc());
21959
21960 case BO_Mul:
21961 case BO_Div:
21962 case BO_Rem:
21963 case BO_Add:
21964 case BO_Sub:
21965 case BO_Shl:
21966 case BO_Shr:
21967 case BO_LT:
21968 case BO_GT:
21969 case BO_LE:
21970 case BO_GE:
21971 case BO_EQ:
21972 case BO_NE:
21973 case BO_And:
21974 case BO_Xor:
21975 case BO_Or:
21976 case BO_Comma:
21977 case BO_Cmp: {
21978 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
21979 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
21980 if (Exp->getOpcode() == BO_Div ||
21981 Exp->getOpcode() == BO_Rem) {
21982 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
21983 // we don't evaluate one.
21984 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
21985 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
21986 if (REval == 0)
21987 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
21988 if (REval.isSigned() && REval.isAllOnes()) {
21989 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
21990 if (LEval.isMinSignedValue())
21991 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
21992 }
21993 }
21994 }
21995 if (Exp->getOpcode() == BO_Comma) {
21996 if (Ctx.getLangOpts().C99) {
21997 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
21998 // if it isn't evaluated.
21999 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
22000 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
22001 } else {
22002 // In both C89 and C++, commas in ICEs are illegal.
22003 return ICEDiag(IK_NotICE, E->getBeginLoc());
22004 }
22005 }
22006 return Worst(LHSResult, RHSResult);
22007 }
22008 case BO_LAnd:
22009 case BO_LOr: {
22010 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
22011 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
22012 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
22013 // Rare case where the RHS has a comma "side-effect"; we need
22014 // to actually check the condition to see whether the side
22015 // with the comma is evaluated.
22016 if ((Exp->getOpcode() == BO_LAnd) !=
22017 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
22018 return RHSResult;
22019 return NoDiag();
22020 }
22021
22022 return Worst(LHSResult, RHSResult);
22023 }
22024 }
22025 llvm_unreachable("invalid binary operator kind");
22026 }
22027 case Expr::ImplicitCastExprClass:
22028 case Expr::CStyleCastExprClass:
22029 case Expr::CXXFunctionalCastExprClass:
22030 case Expr::CXXStaticCastExprClass:
22031 case Expr::CXXReinterpretCastExprClass:
22032 case Expr::CXXConstCastExprClass:
22033 case Expr::ObjCBridgedCastExprClass: {
22034 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
22035 if (isa<ExplicitCastExpr>(E)) {
22036 if (const FloatingLiteral *FL
22037 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
22038 unsigned DestWidth = Ctx.getIntWidth(E->getType());
22039 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
22040 APSInt IgnoredVal(DestWidth, !DestSigned);
22041 bool Ignored;
22042 // If the value does not fit in the destination type, the behavior is
22043 // undefined, so we are not required to treat it as a constant
22044 // expression.
22045 if (FL->getValue().convertToInteger(IgnoredVal,
22046 llvm::APFloat::rmTowardZero,
22047 &Ignored) & APFloat::opInvalidOp)
22048 return ICEDiag(IK_NotICE, E->getBeginLoc());
22049 return NoDiag();
22050 }
22051 }
22052 switch (cast<CastExpr>(E)->getCastKind()) {
22053 case CK_LValueToRValue:
22054 case CK_AtomicToNonAtomic:
22055 case CK_NonAtomicToAtomic:
22056 case CK_NoOp:
22057 case CK_IntegralToBoolean:
22058 case CK_IntegralCast:
22059 return CheckICE(SubExpr, Ctx);
22060 default:
22061 return ICEDiag(IK_NotICE, E->getBeginLoc());
22062 }
22063 }
22064 case Expr::BinaryConditionalOperatorClass: {
22066 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
22067 if (CommonResult.Kind == IK_NotICE) return CommonResult;
22068 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
22069 if (FalseResult.Kind == IK_NotICE) return FalseResult;
22070 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
22071 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
22072 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
22073 return FalseResult;
22074 }
22075 case Expr::ConditionalOperatorClass: {
22077 // If the condition (ignoring parens) is a __builtin_constant_p call,
22078 // then only the true side is actually considered in an integer constant
22079 // expression, and it is fully evaluated. This is an important GNU
22080 // extension. See GCC PR38377 for discussion.
22081 if (const CallExpr *CallCE
22082 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
22083 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
22084 return CheckEvalInICE(E, Ctx);
22085 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
22086 if (CondResult.Kind == IK_NotICE)
22087 return CondResult;
22088
22089 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
22090 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
22091
22092 if (TrueResult.Kind == IK_NotICE)
22093 return TrueResult;
22094 if (FalseResult.Kind == IK_NotICE)
22095 return FalseResult;
22096 if (CondResult.Kind == IK_ICEIfUnevaluated)
22097 return CondResult;
22098 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
22099 return NoDiag();
22100 // Rare case where the diagnostics depend on which side is evaluated
22101 // Note that if we get here, CondResult is 0, and at least one of
22102 // TrueResult and FalseResult is non-zero.
22103 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
22104 return FalseResult;
22105 return TrueResult;
22106 }
22107 case Expr::CXXDefaultArgExprClass:
22108 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
22109 case Expr::CXXDefaultInitExprClass:
22110 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
22111 case Expr::ChooseExprClass: {
22112 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
22113 }
22114 case Expr::BuiltinBitCastExprClass: {
22115 if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
22116 return ICEDiag(IK_NotICE, E->getBeginLoc());
22117 return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
22118 }
22119 }
22120
22121 llvm_unreachable("Invalid StmtClass!");
22122}
22123
22124/// Evaluate an expression as a C++11 integral constant expression.
22126 const Expr *E,
22127 llvm::APSInt *Value) {
22129 return false;
22130
22132 if (!E->isCXX11ConstantExpr(Ctx, &Result))
22133 return false;
22134
22135 if (!Result.isInt())
22136 return false;
22137
22138 if (Value) *Value = Result.getInt();
22139 return true;
22140}
22141
22143 assert(!isValueDependent() &&
22144 "Expression evaluator can't be called on a dependent expression.");
22145
22146 ExprTimeTraceScope TimeScope(this, Ctx, "isIntegerConstantExpr");
22147
22148 if (Ctx.getLangOpts().CPlusPlus11)
22149 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr);
22150
22151 ICEDiag D = CheckICE(this, Ctx);
22152 if (D.Kind != IK_ICE)
22153 return false;
22154 return true;
22155}
22156
22157std::optional<llvm::APSInt>
22159 if (isValueDependent()) {
22160 // Expression evaluator can't succeed on a dependent expression.
22161 return std::nullopt;
22162 }
22163
22164 if (Ctx.getLangOpts().CPlusPlus11) {
22165 APSInt Value;
22167 return Value;
22168 return std::nullopt;
22169 }
22170
22171 if (!isIntegerConstantExpr(Ctx))
22172 return std::nullopt;
22173
22174 // The only possible side-effects here are due to UB discovered in the
22175 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
22176 // required to treat the expression as an ICE, so we produce the folded
22177 // value.
22179 Expr::EvalStatus Status;
22180 EvalInfo Info(Ctx, Status, EvaluationMode::IgnoreSideEffects);
22181 Info.InConstantContext = true;
22182
22183 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
22184 llvm_unreachable("ICE cannot be evaluated!");
22185
22186 return ExprResult.Val.getInt();
22187}
22188
22190 assert(!isValueDependent() &&
22191 "Expression evaluator can't be called on a dependent expression.");
22192
22193 return CheckICE(this, Ctx).Kind == IK_ICE;
22194}
22195
22197 assert(!isValueDependent() &&
22198 "Expression evaluator can't be called on a dependent expression.");
22199
22200 // We support this checking in C++98 mode in order to diagnose compatibility
22201 // issues.
22202 assert(Ctx.getLangOpts().CPlusPlus);
22203
22204 bool IsConst;
22205 APValue Scratch;
22206 if (FastEvaluateAsRValue(this, Scratch, Ctx, IsConst) && Scratch.hasValue()) {
22207 if (Result)
22208 *Result = std::move(Scratch);
22209 return true;
22210 }
22211
22212 // Build evaluation settings.
22213 Expr::EvalStatus Status;
22215 Status.Diag = &Diags;
22216 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantExpression);
22217
22218 bool IsConstExpr =
22219 ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) &&
22220 // FIXME: We don't produce a diagnostic for this, but the callers that
22221 // call us on arbitrary full-expressions should generally not care.
22222 Info.discardCleanups() && !Status.HasSideEffects;
22223
22224 return IsConstExpr && Diags.empty();
22225}
22226
22228 const FunctionDecl *Callee,
22230 const Expr *This) const {
22231 assert(!isValueDependent() &&
22232 "Expression evaluator can't be called on a dependent expression.");
22233
22234 llvm::TimeTraceScope TimeScope("EvaluateWithSubstitution", [&] {
22235 std::string Name;
22236 llvm::raw_string_ostream OS(Name);
22237 Callee->getNameForDiagnostic(OS, Ctx.getPrintingPolicy(),
22238 /*Qualified=*/true);
22239 return Name;
22240 });
22241
22242 Expr::EvalStatus Status;
22243 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantExpressionUnevaluated);
22244 Info.InConstantContext = true;
22245
22246 LValue ThisVal;
22247 const LValue *ThisPtr = nullptr;
22248 if (This) {
22249#ifndef NDEBUG
22250 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
22251 assert(MD && "Don't provide `this` for non-methods.");
22252 assert(MD->isImplicitObjectMemberFunction() &&
22253 "Don't provide `this` for methods without an implicit object.");
22254#endif
22255 if (!This->isValueDependent() &&
22256 EvaluateObjectArgument(Info, This, ThisVal) &&
22257 !Info.EvalStatus.HasSideEffects)
22258 ThisPtr = &ThisVal;
22259
22260 // Ignore any side-effects from a failed evaluation. This is safe because
22261 // they can't interfere with any other argument evaluation.
22262 Info.EvalStatus.HasSideEffects = false;
22263 }
22264
22265 CallRef Call = Info.CurrentCall->createCall(Callee);
22266 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
22267 I != E; ++I) {
22268 unsigned Idx = I - Args.begin();
22269 if (Idx >= Callee->getNumParams())
22270 break;
22271 const ParmVarDecl *PVD = Callee->getParamDecl(Idx);
22272 if ((*I)->isValueDependent() ||
22273 !EvaluateCallArg(PVD, *I, Call, Info) ||
22274 Info.EvalStatus.HasSideEffects) {
22275 // If evaluation fails, throw away the argument entirely.
22276 if (APValue *Slot = Info.getParamSlot(Call, PVD))
22277 *Slot = APValue();
22278 }
22279
22280 // Ignore any side-effects from a failed evaluation. This is safe because
22281 // they can't interfere with any other argument evaluation.
22282 Info.EvalStatus.HasSideEffects = false;
22283 }
22284
22285 // Parameter cleanups happen in the caller and are not part of this
22286 // evaluation.
22287 Info.discardCleanups();
22288 Info.EvalStatus.HasSideEffects = false;
22289
22290 // Build fake call to Callee.
22291 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, This,
22292 Call);
22293 // FIXME: Missing ExprWithCleanups in enable_if conditions?
22294 FullExpressionRAII Scope(Info);
22295 return Evaluate(Value, Info, this) && Scope.destroy() &&
22296 !Info.EvalStatus.HasSideEffects;
22297}
22298
22301 PartialDiagnosticAt> &Diags) {
22302 // FIXME: It would be useful to check constexpr function templates, but at the
22303 // moment the constant expression evaluator cannot cope with the non-rigorous
22304 // ASTs which we build for dependent expressions.
22305 if (FD->isDependentContext())
22306 return true;
22307
22308 llvm::TimeTraceScope TimeScope("isPotentialConstantExpr", [&] {
22309 std::string Name;
22310 llvm::raw_string_ostream OS(Name);
22312 /*Qualified=*/true);
22313 return Name;
22314 });
22315
22316 Expr::EvalStatus Status;
22317 Status.Diag = &Diags;
22318
22319 EvalInfo Info(FD->getASTContext(), Status,
22321 Info.InConstantContext = true;
22322 Info.CheckingPotentialConstantExpression = true;
22323
22324 // The constexpr VM attempts to compile all methods to bytecode here.
22325 if (Info.EnableNewConstInterp) {
22326 Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD);
22327 return Diags.empty();
22328 }
22329
22330 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
22331 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
22332
22333 // Fabricate an arbitrary expression on the stack and pretend that it
22334 // is a temporary being used as the 'this' pointer.
22335 LValue This;
22336 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getCanonicalTagType(RD)
22337 : Info.Ctx.IntTy);
22338 This.set({&VIE, Info.CurrentCall->Index});
22339
22341
22342 APValue Scratch;
22343 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
22344 // Evaluate the call as a constant initializer, to allow the construction
22345 // of objects of non-literal types.
22346 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
22347 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
22348 } else {
22349 SourceLocation Loc = FD->getLocation();
22351 Loc, FD, (MD && MD->isImplicitObjectMemberFunction()) ? &This : nullptr,
22352 &VIE, Args, CallRef(), FD->getBody(), Info, Scratch,
22353 /*ResultSlot=*/nullptr);
22354 }
22355
22356 return Diags.empty();
22357}
22358
22360 const FunctionDecl *FD,
22362 PartialDiagnosticAt> &Diags) {
22363 assert(!E->isValueDependent() &&
22364 "Expression evaluator can't be called on a dependent expression.");
22365
22366 Expr::EvalStatus Status;
22367 Status.Diag = &Diags;
22368
22369 EvalInfo Info(FD->getASTContext(), Status,
22371 Info.InConstantContext = true;
22372 Info.CheckingPotentialConstantExpression = true;
22373
22374 if (Info.EnableNewConstInterp) {
22375 Info.Ctx.getInterpContext().isPotentialConstantExprUnevaluated(Info, E, FD);
22376 return Diags.empty();
22377 }
22378
22379 // Fabricate a call stack frame to give the arguments a plausible cover story.
22380 CallStackFrame Frame(Info, SourceLocation(), FD, /*This=*/nullptr,
22381 /*CallExpr=*/nullptr, CallRef());
22382
22383 APValue ResultScratch;
22384 Evaluate(ResultScratch, Info, E);
22385 return Diags.empty();
22386}
22387
22388std::optional<uint64_t> Expr::tryEvaluateObjectSize(const ASTContext &Ctx,
22389 unsigned Type) const {
22390 if (!getType()->isPointerType())
22391 return std::nullopt;
22392
22393 Expr::EvalStatus Status;
22394 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantFold);
22395 if (Info.EnableNewConstInterp)
22396 return Info.Ctx.getInterpContext().tryEvaluateObjectSize(Info, this, Type);
22397 return tryEvaluateBuiltinObjectSize(this, Type, Info);
22398}
22399
22400static std::optional<uint64_t>
22401EvaluateBuiltinStrLen(const Expr *E, EvalInfo &Info,
22402 std::string *StringResult) {
22403 if (!E->getType()->hasPointerRepresentation() || !E->isPRValue())
22404 return std::nullopt;
22405
22406 LValue String;
22407
22408 if (!EvaluatePointer(E, String, Info))
22409 return std::nullopt;
22410
22411 QualType CharTy = E->getType()->getPointeeType();
22412
22413 // Fast path: if it's a string literal, search the string value.
22414 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
22415 String.getLValueBase().dyn_cast<const Expr *>())) {
22416 StringRef Str = S->getBytes();
22417 int64_t Off = String.Offset.getQuantity();
22418 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
22419 S->getCharByteWidth() == 1 &&
22420 // FIXME: Add fast-path for wchar_t too.
22421 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
22422 Str = Str.substr(Off);
22423
22424 StringRef::size_type Pos = Str.find(0);
22425 if (Pos != StringRef::npos)
22426 Str = Str.substr(0, Pos);
22427
22428 if (StringResult)
22429 *StringResult = Str;
22430 return Str.size();
22431 }
22432
22433 // Fall through to slow path.
22434 }
22435
22436 // Slow path: scan the bytes of the string looking for the terminating 0.
22437 for (uint64_t Strlen = 0; /**/; ++Strlen) {
22438 APValue Char;
22439 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
22440 !Char.isInt())
22441 return std::nullopt;
22442 if (!Char.getInt())
22443 return Strlen;
22444 else if (StringResult)
22445 StringResult->push_back(Char.getInt().getExtValue());
22446 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
22447 return std::nullopt;
22448 }
22449}
22450
22451std::optional<std::string> Expr::tryEvaluateString(ASTContext &Ctx) const {
22452 Expr::EvalStatus Status;
22453 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantFold);
22454 std::string StringResult;
22455
22456 if (Info.EnableNewConstInterp) {
22457 if (!Info.Ctx.getInterpContext().evaluateString(Info, this, StringResult))
22458 return std::nullopt;
22459 return StringResult;
22460 }
22461
22462 if (EvaluateBuiltinStrLen(this, Info, &StringResult))
22463 return StringResult;
22464 return std::nullopt;
22465}
22466
22467template <typename T>
22469 const Expr *SizeExpression,
22470 const Expr *PtrExpression,
22471 ASTContext &Ctx,
22472 Expr::EvalResult &Status) {
22473 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantExpression);
22474 Info.InConstantContext = true;
22475
22476 if (Info.EnableNewConstInterp)
22477 return Info.Ctx.getInterpContext().evaluateCharRange(Info, SizeExpression,
22478 PtrExpression, Result);
22479
22480 LValue String;
22481 FullExpressionRAII Scope(Info);
22482 APSInt SizeValue;
22483 if (!::EvaluateInteger(SizeExpression, SizeValue, Info))
22484 return false;
22485
22486 uint64_t Size = SizeValue.getZExtValue();
22487
22488 // FIXME: better protect against invalid or excessive sizes
22489 if constexpr (std::is_same_v<APValue, T>)
22490 Result = APValue(APValue::UninitArray{}, Size, Size);
22491 else {
22492 if (Size < Result.max_size())
22493 Result.reserve(Size);
22494 }
22495 if (!::EvaluatePointer(PtrExpression, String, Info))
22496 return false;
22497
22498 QualType CharTy = PtrExpression->getType()->getPointeeType();
22499 for (uint64_t I = 0; I < Size; ++I) {
22500 APValue Char;
22501 if (!handleLValueToRValueConversion(Info, PtrExpression, CharTy, String,
22502 Char))
22503 return false;
22504
22505 if constexpr (std::is_same_v<APValue, T>) {
22506 Result.getArrayInitializedElt(I) = std::move(Char);
22507 } else {
22508 APSInt C = Char.getInt();
22509
22510 assert(C.getBitWidth() <= 8 &&
22511 "string element not representable in char");
22512
22513 Result.push_back(static_cast<char>(C.getExtValue()));
22514 }
22515
22516 if (!HandleLValueArrayAdjustment(Info, PtrExpression, String, CharTy, 1))
22517 return false;
22518 }
22519
22520 return Scope.destroy() && CheckMemoryLeaks(Info);
22521}
22522
22524 const Expr *SizeExpression,
22525 const Expr *PtrExpression, ASTContext &Ctx,
22526 EvalResult &Status) const {
22527 return EvaluateCharRangeAsStringImpl(this, Result, SizeExpression,
22528 PtrExpression, Ctx, Status);
22529}
22530
22532 const Expr *SizeExpression,
22533 const Expr *PtrExpression, ASTContext &Ctx,
22534 EvalResult &Status) const {
22535 return EvaluateCharRangeAsStringImpl(this, Result, SizeExpression,
22536 PtrExpression, Ctx, Status);
22537}
22538
22539std::optional<uint64_t> Expr::tryEvaluateStrLen(const ASTContext &Ctx) const {
22540 Expr::EvalStatus Status;
22541 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantFold);
22542
22543 if (Info.EnableNewConstInterp)
22544 return Info.Ctx.getInterpContext().evaluateStrlen(Info, this);
22545 return EvaluateBuiltinStrLen(this, Info);
22546}
22547
22548namespace {
22549struct IsWithinLifetimeHandler {
22550 EvalInfo &Info;
22551 static constexpr AccessKinds AccessKind = AccessKinds::AK_IsWithinLifetime;
22552 using result_type = std::optional<bool>;
22553 std::optional<bool> failed() { return std::nullopt; }
22554 template <typename T>
22555 std::optional<bool> found(T &Subobj, QualType SubobjType,
22557 return true;
22558 }
22559 template <typename T>
22560 std::optional<bool> found(T &Subobj, QualType SubobjType) {
22561 return true;
22562 }
22563};
22564
22565std::optional<bool> EvaluateBuiltinIsWithinLifetime(IntExprEvaluator &IEE,
22566 const CallExpr *E) {
22567 EvalInfo &Info = IEE.Info;
22568 // Sometimes this is called during some sorts of constant folding / early
22569 // evaluation. These are meant for non-constant expressions and are not
22570 // necessary since this consteval builtin will never be evaluated at runtime.
22571 // Just fail to evaluate when not in a constant context.
22572 if (!Info.InConstantContext)
22573 return std::nullopt;
22574 assert(E->getBuiltinCallee() == Builtin::BI__builtin_is_within_lifetime);
22575 const Expr *Arg = E->getArg(0);
22576 if (Arg->isValueDependent())
22577 return std::nullopt;
22578 LValue Val;
22579 if (!EvaluatePointer(Arg, Val, Info))
22580 return std::nullopt;
22581
22582 if (Val.allowConstexprUnknown())
22583 return true;
22584
22585 auto Error = [&](int Diag) {
22586 bool CalledFromStd = false;
22587 const auto *Callee = Info.CurrentCall->getCallee();
22588 if (Callee && Callee->isInStdNamespace()) {
22589 const IdentifierInfo *Identifier = Callee->getIdentifier();
22590 CalledFromStd = Identifier && Identifier->isStr("is_within_lifetime");
22591 }
22592 Info.CCEDiag(CalledFromStd ? Info.CurrentCall->getCallRange().getBegin()
22593 : E->getExprLoc(),
22594 diag::err_invalid_is_within_lifetime)
22595 << (CalledFromStd ? "std::is_within_lifetime"
22596 : "__builtin_is_within_lifetime")
22597 << Diag;
22598 return std::nullopt;
22599 };
22600 // C++2c [meta.const.eval]p4:
22601 // During the evaluation of an expression E as a core constant expression, a
22602 // call to this function is ill-formed unless p points to an object that is
22603 // usable in constant expressions or whose complete object's lifetime began
22604 // within E.
22605
22606 // Make sure it points to an object
22607 // nullptr does not point to an object
22608 if (Val.isNullPointer() || Val.getLValueBase().isNull())
22609 return Error(0);
22610 QualType T = Val.getLValueBase().getType();
22611 assert(!T->isFunctionType() &&
22612 "Pointers to functions should have been typed as function pointers "
22613 "which would have been rejected earlier");
22614 assert(T->isObjectType());
22615 // Hypothetical array element is not an object
22616 if (Val.getLValueDesignator().isOnePastTheEnd())
22617 return Error(1);
22618 assert(Val.getLValueDesignator().isValidSubobject() &&
22619 "Unchecked case for valid subobject");
22620 // All other ill-formed values should have failed EvaluatePointer, so the
22621 // object should be a pointer to an object that is usable in a constant
22622 // expression or whose complete lifetime began within the expression
22623 CompleteObject CO =
22624 findCompleteObject(Info, E, AccessKinds::AK_IsWithinLifetime, Val, T);
22625 // The lifetime hasn't begun yet if we are still evaluating the
22626 // initializer ([basic.life]p(1.2))
22627 if (Info.EvaluatingDeclValue && CO.Value == Info.EvaluatingDeclValue)
22628 return Error(2);
22629
22630 if (!CO)
22631 return false;
22632 IsWithinLifetimeHandler handler{Info};
22633 return findSubobject(Info, E, CO, Val.getLValueDesignator(), handler);
22634}
22635} // 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:227
SourceManager & getSourceManager()
Definition ASTContext.h:866
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:959
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:858
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:4809
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:3051
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:2721
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:2728
QualType getFunctionObjectParameterReferenceType() const
Return the type of the object pointed by this.
Definition DeclCXX.cpp:2872
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:2753
bool isStatic() const
Definition DeclCXX.cpp:2419
bool isCopyAssignmentOperator() const
Determine whether this is a copy-assignment operator, regardless of whether it was declared implicitl...
Definition DeclCXX.cpp:2732
bool isLambdaStaticInvoker() const
Determine whether this is a lambda closure type's static member function that is used for the result ...
Definition DeclCXX.cpp:2897
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:2131
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:3178
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3281
unsigned getBitWidthValue() const
Computes the bit width of this field, if this is a bit field.
Definition Decl.cpp:4752
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition Decl.h:3263
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3414
FieldDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this field.
Definition Decl.h:3425
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:3279
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition Decl.cpp:4205
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition Decl.cpp:4193
bool hasCXXExplicitFunctionObjectParameter() const
Definition Decl.cpp:3865
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:4329
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:3426
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:3125
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:3485
ArrayRef< NamedDecl * > chain() const
Definition Decl.h:3506
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:1693
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:4343
unsigned getNumFields() const
Returns the number of fields (non-static data members) in this record.
Definition Decl.h:4559
field_iterator field_end() const
Definition Decl.h:4549
field_range fields() const
Definition Decl.h:4546
specific_decl_iterator< FieldDecl > field_iterator
Definition Decl.h:4543
bool isAnonymousStructOrUnion() const
Whether this is an anonymous struct or union.
Definition Decl.h:4395
bool field_empty() const
Definition Decl.h:4554
field_iterator field_begin() const
Definition Decl.cpp:5275
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:4899
bool isUnion() const
Definition Decl.h:3946
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:5581
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:2382
bool hasICEInitializer(const ASTContext &Context) const
Determine whether the initializer of this variable is an integer constant expression.
Definition Decl.cpp:2620
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:2559
CharUnits getFlexibleArrayInitChars(const ASTContext &Ctx) const
If hasFlexibleArrayInit is true, compute the number of additional bytes necessary to store those elem...
Definition Decl.cpp:2861
bool hasConstantInitialization() const
Determine whether this variable has constant initialization.
Definition Decl.cpp:2632
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
Definition Decl.cpp:2350
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:2470
EvaluatedStmt * ensureEvaluatedStmt() const
Convert the initializer for this declaration to the elaborated EvaluatedStmt form,...
Definition Decl.cpp:2541
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:2612
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:2359
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:2512
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
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:1459
llvm::FixedPointSemantics FixedPointSemantics
Definition Interp.h:56
bool This(InterpState &S, CodePtr OpPC)
Definition Interp.h:3103
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:3809
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:180
@ 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