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 unsigned getHashValue(const ObjectUnderConstruction &Object) {
737 return hash_value(Object);
738 }
739 static bool isEqual(const ObjectUnderConstruction &LHS,
740 const ObjectUnderConstruction &RHS) {
741 return LHS == RHS;
742 }
743};
744}
745
746namespace {
747 /// A dynamically-allocated heap object.
748 struct DynAlloc {
749 /// The value of this heap-allocated object.
750 APValue Value;
751 /// The allocating expression; used for diagnostics. Either a CXXNewExpr
752 /// or a CallExpr (the latter is for direct calls to operator new inside
753 /// std::allocator<T>::allocate).
754 const Expr *AllocExpr = nullptr;
755
756 enum Kind {
757 New,
758 ArrayNew,
759 StdAllocator
760 };
761
762 /// Get the kind of the allocation. This must match between allocation
763 /// and deallocation.
764 Kind getKind() const {
765 if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr))
766 return NE->isArray() ? ArrayNew : New;
767 assert(isa<CallExpr>(AllocExpr));
768 return StdAllocator;
769 }
770 };
771
772 struct DynAllocOrder {
773 bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const {
774 return L.getIndex() < R.getIndex();
775 }
776 };
777
778 /// EvalInfo - This is a private struct used by the evaluator to capture
779 /// information about a subexpression as it is folded. It retains information
780 /// about the AST context, but also maintains information about the folded
781 /// expression.
782 ///
783 /// If an expression could be evaluated, it is still possible it is not a C
784 /// "integer constant expression" or constant expression. If not, this struct
785 /// captures information about how and why not.
786 ///
787 /// One bit of information passed *into* the request for constant folding
788 /// indicates whether the subexpression is "evaluated" or not according to C
789 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
790 /// evaluate the expression regardless of what the RHS is, but C only allows
791 /// certain things in certain situations.
792 class EvalInfo final : public interp::State {
793 public:
794 /// CurrentCall - The top of the constexpr call stack.
795 CallStackFrame *CurrentCall;
796
797 /// CallStackDepth - The number of calls in the call stack right now.
798 unsigned CallStackDepth;
799
800 /// NextCallIndex - The next call index to assign.
801 unsigned NextCallIndex;
802
803 /// StepsLeft - The remaining number of evaluation steps we're permitted
804 /// to perform. This is essentially a limit for the number of statements
805 /// we will evaluate.
806 unsigned StepsLeft;
807
808 /// Enable the experimental new constant interpreter. If an expression is
809 /// not supported by the interpreter, an error is triggered.
810 bool EnableNewConstInterp;
811
812 /// BottomFrame - The frame in which evaluation started. This must be
813 /// initialized after CurrentCall and CallStackDepth.
814 CallStackFrame BottomFrame;
815
816 /// A stack of values whose lifetimes end at the end of some surrounding
817 /// evaluation frame.
818 llvm::SmallVector<Cleanup, 16> CleanupStack;
819
820 /// EvaluatingDecl - This is the declaration whose initializer is being
821 /// evaluated, if any.
822 APValue::LValueBase EvaluatingDecl;
823
824 enum class EvaluatingDeclKind {
825 None,
826 /// We're evaluating the construction of EvaluatingDecl.
827 Ctor,
828 /// We're evaluating the destruction of EvaluatingDecl.
829 Dtor,
830 };
831 EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None;
832
833 /// EvaluatingDeclValue - This is the value being constructed for the
834 /// declaration whose initializer is being evaluated, if any.
835 APValue *EvaluatingDeclValue;
836
837 /// Stack of loops and 'switch' statements which we're currently
838 /// breaking/continuing; null entries are used to mark unlabeled
839 /// break/continue.
840 SmallVector<const Stmt *> BreakContinueStack;
841
842 /// Set of objects that are currently being constructed.
843 llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
844 ObjectsUnderConstruction;
845
846 /// Current heap allocations, along with the location where each was
847 /// allocated. We use std::map here because we need stable addresses
848 /// for the stored APValues.
849 std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs;
850
851 /// The number of heap allocations performed so far in this evaluation.
852 unsigned NumHeapAllocs = 0;
853
854 struct EvaluatingConstructorRAII {
855 EvalInfo &EI;
856 ObjectUnderConstruction Object;
857 bool DidInsert;
858 EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
859 bool HasBases)
860 : EI(EI), Object(Object) {
861 DidInsert =
862 EI.ObjectsUnderConstruction
863 .insert({Object, HasBases ? ConstructionPhase::Bases
864 : ConstructionPhase::AfterBases})
865 .second;
866 }
867 void finishedConstructingBases() {
868 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
869 }
870 void finishedConstructingFields() {
871 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields;
872 }
873 ~EvaluatingConstructorRAII() {
874 if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
875 }
876 };
877
878 struct EvaluatingDestructorRAII {
879 EvalInfo &EI;
880 ObjectUnderConstruction Object;
881 bool DidInsert;
882 EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object)
883 : EI(EI), Object(Object) {
884 DidInsert = EI.ObjectsUnderConstruction
885 .insert({Object, ConstructionPhase::Destroying})
886 .second;
887 }
888 void startedDestroyingBases() {
889 EI.ObjectsUnderConstruction[Object] =
890 ConstructionPhase::DestroyingBases;
891 }
892 ~EvaluatingDestructorRAII() {
893 if (DidInsert)
894 EI.ObjectsUnderConstruction.erase(Object);
895 }
896 };
897
898 ConstructionPhase
899 isEvaluatingCtorDtor(APValue::LValueBase Base,
900 ArrayRef<APValue::LValuePathEntry> Path) {
901 return ObjectsUnderConstruction.lookup({Base, Path});
902 }
903
904 /// If we're currently speculatively evaluating, the outermost call stack
905 /// depth at which we can mutate state, otherwise 0.
906 unsigned SpeculativeEvaluationDepth = 0;
907
908 /// The current array initialization index, if we're performing array
909 /// initialization.
910 uint64_t ArrayInitIndex = -1;
911
912 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
913 : State(const_cast<ASTContext &>(C), S), CurrentCall(nullptr),
914 CallStackDepth(0), NextCallIndex(1),
915 StepsLeft(C.getLangOpts().ConstexprStepLimit),
916 EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp),
917 BottomFrame(*this, SourceLocation(), /*Callee=*/nullptr,
918 /*This=*/nullptr,
919 /*CallExpr=*/nullptr, CallRef()),
920 EvaluatingDecl((const ValueDecl *)nullptr),
921 EvaluatingDeclValue(nullptr) {
922 EvalMode = Mode;
923 }
924
925 ~EvalInfo() {
926 discardCleanups();
927 }
928
929 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value,
930 EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) {
931 EvaluatingDecl = Base;
932 IsEvaluatingDecl = EDK;
933 EvaluatingDeclValue = &Value;
934 }
935
936 bool CheckCallLimit(SourceLocation Loc) {
937 // Don't perform any constexpr calls (other than the call we're checking)
938 // when checking a potential constant expression.
939 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
940 return false;
941 if (NextCallIndex == 0) {
942 // NextCallIndex has wrapped around.
943 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
944 return false;
945 }
946 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
947 return true;
948 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
949 << getLangOpts().ConstexprCallDepth;
950 return false;
951 }
952
953 bool CheckArraySize(SourceLocation Loc, unsigned BitWidth,
954 uint64_t ElemCount, bool Diag) {
955 // FIXME: GH63562
956 // APValue stores array extents as unsigned,
957 // so anything that is greater that unsigned would overflow when
958 // constructing the array, we catch this here.
959 if (BitWidth > ConstantArrayType::getMaxSizeBits(Ctx) ||
960 ElemCount > uint64_t(std::numeric_limits<unsigned>::max())) {
961 if (Diag)
962 FFDiag(Loc, diag::note_constexpr_new_too_large) << ElemCount;
963 return false;
964 }
965
966 // FIXME: GH63562
967 // Arrays allocate an APValue per element.
968 // We use the number of constexpr steps as a proxy for the maximum size
969 // of arrays to avoid exhausting the system resources, as initialization
970 // of each element is likely to take some number of steps anyway.
971 uint64_t Limit = getLangOpts().ConstexprStepLimit;
972 if (Limit != 0 && ElemCount > Limit) {
973 if (Diag)
974 FFDiag(Loc, diag::note_constexpr_new_exceeds_limits)
975 << ElemCount << Limit;
976 return false;
977 }
978 return true;
979 }
980
981 std::pair<CallStackFrame *, unsigned>
982 getCallFrameAndDepth(unsigned CallIndex) {
983 assert(CallIndex && "no call index in getCallFrameAndDepth");
984 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
985 // be null in this loop.
986 unsigned Depth = CallStackDepth;
987 CallStackFrame *Frame = CurrentCall;
988 while (Frame->Index > CallIndex) {
989 Frame = Frame->Caller;
990 --Depth;
991 }
992 if (Frame->Index == CallIndex)
993 return {Frame, Depth};
994 return {nullptr, 0};
995 }
996
997 bool nextStep(const Stmt *S) {
998 if (getLangOpts().ConstexprStepLimit == 0)
999 return true;
1000
1001 if (!StepsLeft) {
1002 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
1003 return false;
1004 }
1005 --StepsLeft;
1006 return true;
1007 }
1008
1009 APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV);
1010
1011 std::optional<DynAlloc *> lookupDynamicAlloc(DynamicAllocLValue DA) {
1012 std::optional<DynAlloc *> Result;
1013 auto It = HeapAllocs.find(DA);
1014 if (It != HeapAllocs.end())
1015 Result = &It->second;
1016 return Result;
1017 }
1018
1019 /// Get the allocated storage for the given parameter of the given call.
1020 APValue *getParamSlot(CallRef Call, const ParmVarDecl *PVD) {
1021 CallStackFrame *Frame = getCallFrameAndDepth(Call.CallIndex).first;
1022 return Frame ? Frame->getTemporary(Call.getOrigParam(PVD), Call.Version)
1023 : nullptr;
1024 }
1025
1026 /// Information about a stack frame for std::allocator<T>::[de]allocate.
1027 struct StdAllocatorCaller {
1028 unsigned FrameIndex;
1029 QualType ElemType;
1030 const Expr *Call;
1031 explicit operator bool() const { return FrameIndex != 0; };
1032 };
1033
1034 StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const {
1035 for (const CallStackFrame *Call = CurrentCall; Call->Caller != nullptr;
1036 Call = Call->Caller) {
1037 const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee);
1038 if (!MD)
1039 continue;
1040 const IdentifierInfo *FnII = MD->getIdentifier();
1041 if (!FnII || !FnII->isStr(FnName))
1042 continue;
1043
1044 const auto *CTSD =
1045 dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent());
1046 if (!CTSD)
1047 continue;
1048
1049 const IdentifierInfo *ClassII = CTSD->getIdentifier();
1050 const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
1051 if (CTSD->isInStdNamespace() && ClassII &&
1052 ClassII->isStr("allocator") && TAL.size() >= 1 &&
1053 TAL[0].getKind() == TemplateArgument::Type)
1054 return {Call->Index, TAL[0].getAsType(), Call->CallExpr};
1055 }
1056
1057 return {};
1058 }
1059
1060 void performLifetimeExtension() {
1061 // Disable the cleanups for lifetime-extended temporaries.
1062 llvm::erase_if(CleanupStack, [](Cleanup &C) {
1063 return !C.isDestroyedAtEndOf(ScopeKind::FullExpression);
1064 });
1065 }
1066
1067 /// Throw away any remaining cleanups at the end of evaluation. If any
1068 /// cleanups would have had a side-effect, note that as an unmodeled
1069 /// side-effect and return false. Otherwise, return true.
1070 bool discardCleanups() {
1071 for (Cleanup &C : CleanupStack) {
1072 if (C.hasSideEffect() && !noteSideEffect()) {
1073 CleanupStack.clear();
1074 return false;
1075 }
1076 }
1077 CleanupStack.clear();
1078 return true;
1079 }
1080
1081 private:
1082 const interp::Frame *getCurrentFrame() override { return CurrentCall; }
1083
1084 unsigned getCallStackDepth() override { return CallStackDepth; }
1085 bool stepsLeft() const override { return StepsLeft > 0; }
1086
1087 public:
1088 /// Notes that we failed to evaluate an expression that other expressions
1089 /// directly depend on, and determine if we should keep evaluating. This
1090 /// should only be called if we actually intend to keep evaluating.
1091 ///
1092 /// Call noteSideEffect() instead if we may be able to ignore the value that
1093 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1094 ///
1095 /// (Foo(), 1) // use noteSideEffect
1096 /// (Foo() || true) // use noteSideEffect
1097 /// Foo() + 1 // use noteFailure
1098 [[nodiscard]] bool noteFailure() {
1099 // Failure when evaluating some expression often means there is some
1100 // subexpression whose evaluation was skipped. Therefore, (because we
1101 // don't track whether we skipped an expression when unwinding after an
1102 // evaluation failure) every evaluation failure that bubbles up from a
1103 // subexpression implies that a side-effect has potentially happened. We
1104 // skip setting the HasSideEffects flag to true until we decide to
1105 // continue evaluating after that point, which happens here.
1106 bool KeepGoing = keepEvaluatingAfterFailure();
1107 EvalStatus.HasSideEffects |= KeepGoing;
1108 return KeepGoing;
1109 }
1110
1111 class ArrayInitLoopIndex {
1112 EvalInfo &Info;
1113 uint64_t OuterIndex;
1114
1115 public:
1116 ArrayInitLoopIndex(EvalInfo &Info)
1117 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1118 Info.ArrayInitIndex = 0;
1119 }
1120 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1121
1122 operator uint64_t&() { return Info.ArrayInitIndex; }
1123 };
1124 };
1125
1126 /// Object used to treat all foldable expressions as constant expressions.
1127 struct FoldConstant {
1128 EvalInfo &Info;
1129 bool Enabled;
1130 bool HadNoPriorDiags;
1131 EvaluationMode OldMode;
1132
1133 explicit FoldConstant(EvalInfo &Info, bool Enabled)
1134 : Info(Info),
1135 Enabled(Enabled),
1136 HadNoPriorDiags(Info.EvalStatus.Diag &&
1137 Info.EvalStatus.Diag->empty() &&
1138 !Info.EvalStatus.HasSideEffects),
1139 OldMode(Info.EvalMode) {
1140 if (Enabled)
1141 Info.EvalMode = EvaluationMode::ConstantFold;
1142 }
1143 void keepDiagnostics() { Enabled = false; }
1144 ~FoldConstant() {
1145 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
1146 !Info.EvalStatus.HasSideEffects) {
1147 Info.EvalStatus.Diag->clear();
1148 Info.EvalStatus.DiagEmitted = false;
1149 }
1150 Info.EvalMode = OldMode;
1151 }
1152 };
1153
1154 /// RAII object used to set the current evaluation mode to ignore
1155 /// side-effects.
1156 struct IgnoreSideEffectsRAII {
1157 EvalInfo &Info;
1158 EvaluationMode OldMode;
1159 explicit IgnoreSideEffectsRAII(EvalInfo &Info)
1160 : Info(Info), OldMode(Info.EvalMode) {
1161 Info.EvalMode = EvaluationMode::IgnoreSideEffects;
1162 }
1163
1164 ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
1165 };
1166
1167 /// RAII object used to optionally suppress diagnostics and side-effects from
1168 /// a speculative evaluation.
1169 class SpeculativeEvaluationRAII {
1170 EvalInfo *Info = nullptr;
1171 Expr::EvalStatus OldStatus;
1172 unsigned OldSpeculativeEvaluationDepth = 0;
1173
1174 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1175 Info = Other.Info;
1176 OldStatus = Other.OldStatus;
1177 OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
1178 Other.Info = nullptr;
1179 }
1180
1181 void maybeRestoreState() {
1182 if (!Info)
1183 return;
1184
1185 Info->EvalStatus = OldStatus;
1186 Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
1187 }
1188
1189 public:
1190 SpeculativeEvaluationRAII() = default;
1191
1192 SpeculativeEvaluationRAII(
1193 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1194 : Info(&Info), OldStatus(Info.EvalStatus),
1195 OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
1196 Info.EvalStatus.Diag = NewDiag;
1197 Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
1198 }
1199
1200 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1201 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1202 moveFromAndCancel(std::move(Other));
1203 }
1204
1205 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1206 maybeRestoreState();
1207 moveFromAndCancel(std::move(Other));
1208 return *this;
1209 }
1210
1211 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1212 };
1213
1214 /// RAII object wrapping a full-expression or block scope, and handling
1215 /// the ending of the lifetime of temporaries created within it.
1216 template<ScopeKind Kind>
1217 class ScopeRAII {
1218 EvalInfo &Info;
1219 unsigned OldStackSize;
1220 public:
1221 ScopeRAII(EvalInfo &Info)
1222 : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1223 // Push a new temporary version. This is needed to distinguish between
1224 // temporaries created in different iterations of a loop.
1225 Info.CurrentCall->pushTempVersion();
1226 }
1227 bool destroy(bool RunDestructors = true) {
1228 bool OK = cleanup(Info, RunDestructors, OldStackSize);
1229 OldStackSize = std::numeric_limits<unsigned>::max();
1230 return OK;
1231 }
1232 ~ScopeRAII() {
1233 if (OldStackSize != std::numeric_limits<unsigned>::max())
1234 destroy(false);
1235 // Body moved to a static method to encourage the compiler to inline away
1236 // instances of this class.
1237 Info.CurrentCall->popTempVersion();
1238 }
1239 private:
1240 static bool cleanup(EvalInfo &Info, bool RunDestructors,
1241 unsigned OldStackSize) {
1242 assert(OldStackSize <= Info.CleanupStack.size() &&
1243 "running cleanups out of order?");
1244
1245 // Run all cleanups for a block scope, and non-lifetime-extended cleanups
1246 // for a full-expression scope.
1247 bool Success = true;
1248 for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) {
1249 if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) {
1250 if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) {
1251 Success = false;
1252 break;
1253 }
1254 }
1255 }
1256
1257 // Compact any retained cleanups.
1258 auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
1259 if (Kind != ScopeKind::Block)
1260 NewEnd =
1261 std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) {
1262 return C.isDestroyedAtEndOf(Kind);
1263 });
1264 Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
1265 return Success;
1266 }
1267 };
1268 typedef ScopeRAII<ScopeKind::Block> BlockScopeRAII;
1269 typedef ScopeRAII<ScopeKind::FullExpression> FullExpressionRAII;
1270 typedef ScopeRAII<ScopeKind::Call> CallScopeRAII;
1271}
1272
1273bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1274 CheckSubobjectKind CSK) {
1275 if (Invalid)
1276 return false;
1277 if (isOnePastTheEnd()) {
1278 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1279 << CSK;
1280 setInvalid();
1281 return false;
1282 }
1283 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1284 // must actually be at least one array element; even a VLA cannot have a
1285 // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1286 return true;
1287}
1288
1289void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1290 const Expr *E) {
1291 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1292 // Do not set the designator as invalid: we can represent this situation,
1293 // and correct handling of __builtin_object_size requires us to do so.
1294}
1295
1296void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1297 const Expr *E,
1298 const APSInt &N) {
1299 // If we're complaining, we must be able to statically determine the size of
1300 // the most derived array.
1301 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1302 Info.CCEDiag(E, diag::note_constexpr_array_index)
1303 << N << /*array*/ 0
1304 << static_cast<unsigned>(getMostDerivedArraySize());
1305 else
1306 Info.CCEDiag(E, diag::note_constexpr_array_index)
1307 << N << /*non-array*/ 1;
1308 setInvalid();
1309}
1310
1311CallStackFrame::CallStackFrame(EvalInfo &Info, SourceRange CallRange,
1312 const FunctionDecl *Callee, const LValue *This,
1313 const Expr *CallExpr, CallRef Call)
1314 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1315 CallExpr(CallExpr), Arguments(Call), CallRange(CallRange),
1316 Index(Info.NextCallIndex++) {
1317 Info.CurrentCall = this;
1318 ++Info.CallStackDepth;
1319}
1320
1321CallStackFrame::~CallStackFrame() {
1322 assert(Info.CurrentCall == this && "calls retired out of order");
1323 --Info.CallStackDepth;
1324 Info.CurrentCall = Caller;
1325}
1326
1327static bool isRead(AccessKinds AK) {
1328 return AK == AK_Read || AK == AK_ReadObjectRepresentation ||
1329 AK == AK_IsWithinLifetime || AK == AK_Dereference;
1330}
1331
1333 switch (AK) {
1334 case AK_Read:
1336 case AK_MemberCall:
1337 case AK_DynamicCast:
1338 case AK_TypeId:
1340 case AK_Dereference:
1341 return false;
1342 case AK_Assign:
1343 case AK_Increment:
1344 case AK_Decrement:
1345 case AK_Construct:
1346 case AK_Destroy:
1347 return true;
1348 }
1349 llvm_unreachable("unknown access kind");
1350}
1351
1352static bool isAnyAccess(AccessKinds AK) {
1353 return isRead(AK) || isModification(AK);
1354}
1355
1356/// Is this an access per the C++ definition?
1358 return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy &&
1359 AK != AK_IsWithinLifetime && AK != AK_Dereference;
1360}
1361
1362/// Is this kind of access valid on an indeterminate object value?
1364 switch (AK) {
1365 case AK_Read:
1366 case AK_Increment:
1367 case AK_Decrement:
1368 case AK_Dereference:
1369 // These need the object's value.
1370 return false;
1371
1374 case AK_Assign:
1375 case AK_Construct:
1376 case AK_Destroy:
1377 // Construction and destruction don't need the value.
1378 return true;
1379
1380 case AK_MemberCall:
1381 case AK_DynamicCast:
1382 case AK_TypeId:
1383 // These aren't really meaningful on scalars.
1384 return true;
1385 }
1386 llvm_unreachable("unknown access kind");
1387}
1388
1389namespace {
1390 struct ComplexValue {
1391 private:
1392 bool IsInt;
1393
1394 public:
1395 APSInt IntReal, IntImag;
1396 APFloat FloatReal, FloatImag;
1397
1398 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1399
1400 void makeComplexFloat() { IsInt = false; }
1401 bool isComplexFloat() const { return !IsInt; }
1402 APFloat &getComplexFloatReal() { return FloatReal; }
1403 APFloat &getComplexFloatImag() { return FloatImag; }
1404
1405 void makeComplexInt() { IsInt = true; }
1406 bool isComplexInt() const { return IsInt; }
1407 APSInt &getComplexIntReal() { return IntReal; }
1408 APSInt &getComplexIntImag() { return IntImag; }
1409
1410 void moveInto(APValue &v) const {
1411 if (isComplexFloat())
1412 v = APValue(FloatReal, FloatImag);
1413 else
1414 v = APValue(IntReal, IntImag);
1415 }
1416 void setFrom(const APValue &v) {
1417 assert(v.isComplexFloat() || v.isComplexInt());
1418 if (v.isComplexFloat()) {
1419 makeComplexFloat();
1420 FloatReal = v.getComplexFloatReal();
1421 FloatImag = v.getComplexFloatImag();
1422 } else {
1423 makeComplexInt();
1424 IntReal = v.getComplexIntReal();
1425 IntImag = v.getComplexIntImag();
1426 }
1427 }
1428 };
1429
1430 struct LValue {
1431 APValue::LValueBase Base;
1432 CharUnits Offset;
1433 SubobjectDesignator Designator;
1434 bool IsNullPtr : 1;
1435 bool InvalidBase : 1;
1436 // P2280R4 track if we have an unknown reference or pointer.
1437 bool AllowConstexprUnknown = false;
1438
1439 const APValue::LValueBase getLValueBase() const { return Base; }
1440 bool allowConstexprUnknown() const { return AllowConstexprUnknown; }
1441 CharUnits &getLValueOffset() { return Offset; }
1442 const CharUnits &getLValueOffset() const { return Offset; }
1443 SubobjectDesignator &getLValueDesignator() { return Designator; }
1444 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1445 bool isNullPointer() const { return IsNullPtr;}
1446
1447 unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1448 unsigned getLValueVersion() const { return Base.getVersion(); }
1449
1450 void moveInto(APValue &V) const {
1451 if (Designator.Invalid)
1452 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
1453 else {
1454 assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1455 V = APValue(Base, Offset, Designator.Entries,
1456 Designator.IsOnePastTheEnd, IsNullPtr);
1457 }
1458 if (AllowConstexprUnknown)
1459 V.setConstexprUnknown();
1460 }
1461 void setFrom(const ASTContext &Ctx, const APValue &V) {
1462 assert(V.isLValue() && "Setting LValue from a non-LValue?");
1463 Base = V.getLValueBase();
1464 Offset = V.getLValueOffset();
1465 InvalidBase = false;
1466 Designator = SubobjectDesignator(Ctx, V);
1467 IsNullPtr = V.isNullPointer();
1468 AllowConstexprUnknown = V.allowConstexprUnknown();
1469 }
1470
1471 void set(APValue::LValueBase B, bool BInvalid = false) {
1472#ifndef NDEBUG
1473 // We only allow a few types of invalid bases. Enforce that here.
1474 if (BInvalid) {
1475 const auto *E = B.get<const Expr *>();
1476 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1477 "Unexpected type of invalid base");
1478 }
1479#endif
1480
1481 Base = B;
1482 Offset = CharUnits::fromQuantity(0);
1483 InvalidBase = BInvalid;
1484 Designator = SubobjectDesignator(getType(B));
1485 IsNullPtr = false;
1486 AllowConstexprUnknown = false;
1487 }
1488
1489 void setNull(ASTContext &Ctx, QualType PointerTy) {
1490 Base = (const ValueDecl *)nullptr;
1491 Offset =
1493 InvalidBase = false;
1494 Designator = SubobjectDesignator(PointerTy->getPointeeType());
1495 IsNullPtr = true;
1496 AllowConstexprUnknown = false;
1497 }
1498
1499 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1500 set(B, true);
1501 }
1502
1503 std::string toString(ASTContext &Ctx, QualType T) const {
1504 APValue Printable;
1505 moveInto(Printable);
1506 return Printable.getAsString(Ctx, T);
1507 }
1508
1509 private:
1510 // Check that this LValue is not based on a null pointer. If it is, produce
1511 // a diagnostic and mark the designator as invalid.
1512 template <typename GenDiagType>
1513 bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
1514 if (Designator.Invalid)
1515 return false;
1516 if (IsNullPtr) {
1517 GenDiag();
1518 Designator.setInvalid();
1519 return false;
1520 }
1521 return true;
1522 }
1523
1524 public:
1525 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1526 CheckSubobjectKind CSK) {
1527 return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1528 Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1529 });
1530 }
1531
1532 bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1533 AccessKinds AK) {
1534 return checkNullPointerDiagnosingWith([&Info, E, AK] {
1535 if (AK == AccessKinds::AK_Dereference)
1536 Info.FFDiag(E, diag::note_constexpr_dereferencing_null);
1537 else
1538 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1539 });
1540 }
1541
1542 // Check this LValue refers to an object. If not, set the designator to be
1543 // invalid and emit a diagnostic.
1544 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1545 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1546 Designator.checkSubobject(Info, E, CSK);
1547 }
1548
1549 void addDecl(EvalInfo &Info, const Expr *E,
1550 const Decl *D, bool Virtual = false) {
1551 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1552 Designator.addDeclUnchecked(D, Virtual);
1553 }
1554 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1555 if (!Designator.Entries.empty()) {
1556 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1557 Designator.setInvalid();
1558 return;
1559 }
1560 if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1561 assert(getType(Base).getNonReferenceType()->isPointerType() ||
1562 getType(Base).getNonReferenceType()->isArrayType());
1563 Designator.FirstEntryIsAnUnsizedArray = true;
1564 Designator.addUnsizedArrayUnchecked(ElemTy);
1565 }
1566 }
1567 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1568 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1569 Designator.addArrayUnchecked(CAT);
1570 }
1571 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1572 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1573 Designator.addComplexUnchecked(EltTy, Imag);
1574 }
1575 void addVectorElement(EvalInfo &Info, const Expr *E, QualType EltTy,
1576 uint64_t Size, uint64_t Idx) {
1577 if (checkSubobject(Info, E, CSK_VectorElement))
1578 Designator.addVectorElementUnchecked(EltTy, Size, Idx);
1579 }
1580 void clearIsNullPointer() {
1581 IsNullPtr = false;
1582 }
1583 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1584 const APSInt &Index, CharUnits ElementSize) {
1585 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1586 // but we're not required to diagnose it and it's valid in C++.)
1587 if (!Index)
1588 return;
1589
1590 // Compute the new offset in the appropriate width, wrapping at 64 bits.
1591 // FIXME: When compiling for a 32-bit target, we should use 32-bit
1592 // offsets.
1593 uint64_t Offset64 = Offset.getQuantity();
1594 uint64_t ElemSize64 = ElementSize.getQuantity();
1595 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1596 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1597
1598 if (checkNullPointer(Info, E, CSK_ArrayIndex))
1599 Designator.adjustIndex(Info, E, Index, *this);
1600 clearIsNullPointer();
1601 }
1602 void adjustOffset(CharUnits N) {
1603 Offset += N;
1604 if (N.getQuantity())
1605 clearIsNullPointer();
1606 }
1607 };
1608
1609 struct MemberPtr {
1610 MemberPtr() {}
1611 explicit MemberPtr(const ValueDecl *Decl)
1612 : DeclAndIsDerivedMember(Decl, false) {}
1613
1614 /// The member or (direct or indirect) field referred to by this member
1615 /// pointer, or 0 if this is a null member pointer.
1616 const ValueDecl *getDecl() const {
1617 return DeclAndIsDerivedMember.getPointer();
1618 }
1619 /// Is this actually a member of some type derived from the relevant class?
1620 bool isDerivedMember() const {
1621 return DeclAndIsDerivedMember.getInt();
1622 }
1623 /// Get the class which the declaration actually lives in.
1624 const CXXRecordDecl *getContainingRecord() const {
1625 return cast<CXXRecordDecl>(
1626 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1627 }
1628
1629 void moveInto(APValue &V) const {
1630 V = APValue(getDecl(), isDerivedMember(), Path);
1631 }
1632 void setFrom(const APValue &V) {
1633 assert(V.isMemberPointer());
1634 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1635 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1636 Path.clear();
1637 llvm::append_range(Path, V.getMemberPointerPath());
1638 }
1639
1640 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1641 /// whether the member is a member of some class derived from the class type
1642 /// of the member pointer.
1643 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1644 /// Path - The path of base/derived classes from the member declaration's
1645 /// class (exclusive) to the class type of the member pointer (inclusive).
1646 SmallVector<const CXXRecordDecl*, 4> Path;
1647
1648 /// Perform a cast towards the class of the Decl (either up or down the
1649 /// hierarchy).
1650 bool castBack(const CXXRecordDecl *Class) {
1651 assert(!Path.empty());
1652 const CXXRecordDecl *Expected;
1653 if (Path.size() >= 2)
1654 Expected = Path[Path.size() - 2];
1655 else
1656 Expected = getContainingRecord();
1657 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1658 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1659 // if B does not contain the original member and is not a base or
1660 // derived class of the class containing the original member, the result
1661 // of the cast is undefined.
1662 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1663 // (D::*). We consider that to be a language defect.
1664 return false;
1665 }
1666 Path.pop_back();
1667 return true;
1668 }
1669 /// Perform a base-to-derived member pointer cast.
1670 bool castToDerived(const CXXRecordDecl *Derived) {
1671 if (!getDecl())
1672 return true;
1673 if (!isDerivedMember()) {
1674 Path.push_back(Derived);
1675 return true;
1676 }
1677 if (!castBack(Derived))
1678 return false;
1679 if (Path.empty())
1680 DeclAndIsDerivedMember.setInt(false);
1681 return true;
1682 }
1683 /// Perform a derived-to-base member pointer cast.
1684 bool castToBase(const CXXRecordDecl *Base) {
1685 if (!getDecl())
1686 return true;
1687 if (Path.empty())
1688 DeclAndIsDerivedMember.setInt(true);
1689 if (isDerivedMember()) {
1690 Path.push_back(Base);
1691 return true;
1692 }
1693 return castBack(Base);
1694 }
1695 };
1696
1697 /// Compare two member pointers, which are assumed to be of the same type.
1698 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1699 if (!LHS.getDecl() || !RHS.getDecl())
1700 return !LHS.getDecl() && !RHS.getDecl();
1701 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1702 return false;
1703 return LHS.Path == RHS.Path;
1704 }
1705}
1706
1707void SubobjectDesignator::adjustIndex(EvalInfo &Info, const Expr *E, APSInt N,
1708 const LValue &LV) {
1709 if (Invalid || !N)
1710 return;
1711 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
1712 if (isMostDerivedAnUnsizedArray()) {
1713 diagnoseUnsizedArrayPointerArithmetic(Info, E);
1714 // Can't verify -- trust that the user is doing the right thing (or if
1715 // not, trust that the caller will catch the bad behavior).
1716 // FIXME: Should we reject if this overflows, at least?
1717 Entries.back() =
1718 PathEntry::ArrayIndex(Entries.back().getAsArrayIndex() + TruncatedN);
1719 return;
1720 }
1721
1722 // [expr.add]p4: For the purposes of these operators, a pointer to a
1723 // nonarray object behaves the same as a pointer to the first element of
1724 // an array of length one with the type of the object as its element type.
1725 bool IsArray =
1726 MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement;
1727 uint64_t ArrayIndex =
1728 IsArray ? Entries.back().getAsArrayIndex() : (uint64_t)IsOnePastTheEnd;
1729 uint64_t ArraySize = IsArray ? getMostDerivedArraySize() : (uint64_t)1;
1730
1731 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
1732 if (!Info.checkingPotentialConstantExpression() ||
1733 !LV.AllowConstexprUnknown) {
1734 // Calculate the actual index in a wide enough type, so we can include
1735 // it in the note.
1736 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
1737 (llvm::APInt &)N += ArrayIndex;
1738 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
1739 diagnosePointerArithmetic(Info, E, N);
1740 }
1741 setInvalid();
1742 return;
1743 }
1744
1745 ArrayIndex += TruncatedN;
1746 assert(ArrayIndex <= ArraySize &&
1747 "bounds check succeeded for out-of-bounds index");
1748
1749 if (IsArray)
1750 Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
1751 else
1752 IsOnePastTheEnd = (ArrayIndex != 0);
1753}
1754
1755static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1756static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1757 const LValue &This, const Expr *E,
1758 bool AllowNonLiteralTypes = false);
1759static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1760 bool InvalidBaseOK = false);
1761static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1762 bool InvalidBaseOK = false);
1763static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1764 EvalInfo &Info);
1765static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1766static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1767static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1768 EvalInfo &Info);
1769static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1770static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1771static bool EvaluateMatrix(const Expr *E, APValue &Result, EvalInfo &Info);
1772static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1773 EvalInfo &Info);
1774static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1775static std::optional<uint64_t>
1776EvaluateBuiltinStrLen(const Expr *E, EvalInfo &Info,
1777 std::string *StringResult = nullptr);
1778
1779/// Evaluate an integer or fixed point expression into an APResult.
1780static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1781 EvalInfo &Info);
1782
1783/// Evaluate only a fixed point expression into an APResult.
1784static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1785 EvalInfo &Info);
1786
1787//===----------------------------------------------------------------------===//
1788// Misc utilities
1789//===----------------------------------------------------------------------===//
1790
1791/// Negate an APSInt in place, converting it to a signed form if necessary, and
1792/// preserving its value (by extending by up to one bit as needed).
1793static void negateAsSigned(APSInt &Int) {
1794 if (Int.isUnsigned() || Int.isMinSignedValue()) {
1795 Int = Int.extend(Int.getBitWidth() + 1);
1796 Int.setIsSigned(true);
1797 }
1798 Int = -Int;
1799}
1800
1801template<typename KeyT>
1802APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T,
1803 ScopeKind Scope, LValue &LV) {
1804 unsigned Version = getTempVersion();
1805 APValue::LValueBase Base(Key, Index, Version);
1806 LV.set(Base);
1807 return createLocal(Base, Key, T, Scope);
1808}
1809
1810/// Allocate storage for a parameter of a function call made in this frame.
1811APValue &CallStackFrame::createParam(CallRef Args, const ParmVarDecl *PVD,
1812 LValue &LV) {
1813 assert(Args.CallIndex == Index && "creating parameter in wrong frame");
1814 APValue::LValueBase Base(PVD, Index, Args.Version);
1815 LV.set(Base);
1816 // We always destroy parameters at the end of the call, even if we'd allow
1817 // them to live to the end of the full-expression at runtime, in order to
1818 // give portable results and match other compilers.
1819 return createLocal(Base, PVD, PVD->getType(), ScopeKind::Call);
1820}
1821
1822APValue &CallStackFrame::createLocal(APValue::LValueBase Base, const void *Key,
1823 QualType T, ScopeKind Scope) {
1824 assert(Base.getCallIndex() == Index && "lvalue for wrong frame");
1825 unsigned Version = Base.getVersion();
1826 APValue &Result = Temporaries[MapKeyTy(Key, Version)];
1827 assert(Result.isAbsent() && "local created multiple times");
1828
1829 // If we're creating a local immediately in the operand of a speculative
1830 // evaluation, don't register a cleanup to be run outside the speculative
1831 // evaluation context, since we won't actually be able to initialize this
1832 // object.
1833 if (Index <= Info.SpeculativeEvaluationDepth) {
1834 if (T.isDestructedType())
1835 Info.noteSideEffect();
1836 } else {
1837 Info.CleanupStack.push_back(Cleanup(&Result, Base, T, Scope));
1838 }
1839 return Result;
1840}
1841
1842APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) {
1843 if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) {
1844 FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded);
1845 return nullptr;
1846 }
1847
1848 DynamicAllocLValue DA(NumHeapAllocs++);
1850 auto Result = HeapAllocs.emplace(std::piecewise_construct,
1851 std::forward_as_tuple(DA), std::tuple<>());
1852 assert(Result.second && "reused a heap alloc index?");
1853 Result.first->second.AllocExpr = E;
1854 return &Result.first->second.Value;
1855}
1856
1857/// Produce a string describing the given constexpr call.
1858void CallStackFrame::describe(raw_ostream &Out) const {
1859 bool IsMemberCall = false;
1860 bool ExplicitInstanceParam = false;
1861 clang::PrintingPolicy PrintingPolicy = Info.Ctx.getPrintingPolicy();
1862 PrintingPolicy.SuppressLambdaBody = true;
1863
1864 if (const auto *MD = dyn_cast<CXXMethodDecl>(Callee)) {
1865 IsMemberCall = !isa<CXXConstructorDecl>(MD) && !MD->isStatic();
1866 ExplicitInstanceParam = MD->isExplicitObjectMemberFunction();
1867 }
1868
1869 if (!IsMemberCall)
1870 Callee->getNameForDiagnostic(Out, PrintingPolicy,
1871 /*Qualified=*/false);
1872
1873 if (This && IsMemberCall) {
1874 if (const auto *MCE = dyn_cast_if_present<CXXMemberCallExpr>(CallExpr)) {
1875 const Expr *Object = MCE->getImplicitObjectArgument();
1876 Object->printPretty(Out, /*Helper=*/nullptr, PrintingPolicy,
1877 /*Indentation=*/0);
1878 if (Object->getType()->isPointerType())
1879 Out << "->";
1880 else
1881 Out << ".";
1882 } else if (const auto *OCE =
1883 dyn_cast_if_present<CXXOperatorCallExpr>(CallExpr)) {
1884 OCE->getArg(0)->printPretty(Out, /*Helper=*/nullptr, PrintingPolicy,
1885 /*Indentation=*/0);
1886 Out << ".";
1887 } else {
1888 APValue Val;
1889 This->moveInto(Val);
1890 Val.printPretty(
1891 Out, Info.Ctx,
1892 Info.Ctx.getLValueReferenceType(This->Designator.MostDerivedType));
1893 Out << ".";
1894 }
1895 Callee->getNameForDiagnostic(Out, PrintingPolicy,
1896 /*Qualified=*/false);
1897 }
1898
1899 Out << '(';
1900
1901 llvm::ListSeparator Comma;
1902 for (const ParmVarDecl *Param :
1903 Callee->parameters().slice(ExplicitInstanceParam)) {
1904 Out << Comma;
1905 const APValue *V = Info.getParamSlot(Arguments, Param);
1906 if (V)
1907 V->printPretty(Out, Info.Ctx, Param->getType());
1908 else
1909 Out << "<...>";
1910 }
1911
1912 Out << ')';
1913}
1914
1915/// Evaluate an expression to see if it had side-effects, and discard its
1916/// result.
1917/// \return \c true if the caller should keep evaluating.
1918static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
1919 assert(!E->isValueDependent());
1920 APValue Scratch;
1921 if (!Evaluate(Scratch, Info, E))
1922 // We don't need the value, but we might have skipped a side effect here.
1923 return Info.noteSideEffect();
1924 return true;
1925}
1926
1927/// Should this call expression be treated as forming an opaque constant?
1928static bool IsOpaqueConstantCall(const CallExpr *E) {
1929 unsigned Builtin = E->getBuiltinCallee();
1930 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1931 Builtin == Builtin::BI__builtin___NSStringMakeConstantString ||
1932 Builtin == Builtin::BI__builtin_ptrauth_sign_constant ||
1933 Builtin == Builtin::BI__builtin_function_start);
1934}
1935
1936static bool IsOpaqueConstantCall(const LValue &LVal) {
1937 const auto *BaseExpr =
1938 llvm::dyn_cast_if_present<CallExpr>(LVal.Base.dyn_cast<const Expr *>());
1939 return BaseExpr && IsOpaqueConstantCall(BaseExpr);
1940}
1941
1943 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1944 // constant expression of pointer type that evaluates to...
1945
1946 // ... a null pointer value, or a prvalue core constant expression of type
1947 // std::nullptr_t.
1948 if (!B)
1949 return true;
1950
1951 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1952 // ... the address of an object with static storage duration,
1953 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1954 return VD->hasGlobalStorage();
1956 return true;
1957 // ... the address of a function,
1958 // ... the address of a GUID [MS extension],
1959 // ... the address of an unnamed global constant
1961 }
1962
1963 if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>())
1964 return true;
1965
1966 const Expr *E = B.get<const Expr*>();
1967 switch (E->getStmtClass()) {
1968 default:
1969 return false;
1970 case Expr::CompoundLiteralExprClass: {
1972 return CLE->isFileScope() && CLE->isLValue();
1973 }
1974 case Expr::MaterializeTemporaryExprClass:
1975 // A materialized temporary might have been lifetime-extended to static
1976 // storage duration.
1977 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
1978 // A string literal has static storage duration.
1979 case Expr::StringLiteralClass:
1980 case Expr::PredefinedExprClass:
1981 case Expr::ObjCStringLiteralClass:
1982 case Expr::ObjCEncodeExprClass:
1983 return true;
1984 case Expr::ObjCBoxedExprClass:
1985 case Expr::ObjCArrayLiteralClass:
1986 case Expr::ObjCDictionaryLiteralClass:
1987 return cast<ObjCObjectLiteral>(E)->isExpressibleAsConstantInitializer();
1988 case Expr::CallExprClass:
1990 // For GCC compatibility, &&label has static storage duration.
1991 case Expr::AddrLabelExprClass:
1992 return true;
1993 // A Block literal expression may be used as the initialization value for
1994 // Block variables at global or local static scope.
1995 case Expr::BlockExprClass:
1996 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
1997 // The APValue generated from a __builtin_source_location will be emitted as a
1998 // literal.
1999 case Expr::SourceLocExprClass:
2000 return true;
2001 case Expr::ImplicitValueInitExprClass:
2002 // FIXME:
2003 // We can never form an lvalue with an implicit value initialization as its
2004 // base through expression evaluation, so these only appear in one case: the
2005 // implicit variable declaration we invent when checking whether a constexpr
2006 // constructor can produce a constant expression. We must assume that such
2007 // an expression might be a global lvalue.
2008 return true;
2009 }
2010}
2011
2012static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
2013 return LVal.Base.dyn_cast<const ValueDecl*>();
2014}
2015
2016// Information about an LValueBase that is some kind of string.
2019 StringRef Bytes;
2021};
2022
2023// Gets the lvalue base of LVal as a string.
2024static bool GetLValueBaseAsString(const EvalInfo &Info, const LValue &LVal,
2025 LValueBaseString &AsString) {
2026 const auto *BaseExpr = LVal.Base.dyn_cast<const Expr *>();
2027 if (!BaseExpr)
2028 return false;
2029
2030 // For ObjCEncodeExpr, we need to compute and store the string.
2031 if (const auto *EE = dyn_cast<ObjCEncodeExpr>(BaseExpr)) {
2032 Info.Ctx.getObjCEncodingForType(EE->getEncodedType(),
2033 AsString.ObjCEncodeStorage);
2034 AsString.Bytes = AsString.ObjCEncodeStorage;
2035 AsString.CharWidth = 1;
2036 return true;
2037 }
2038
2039 // Otherwise, we have a StringLiteral.
2040 const auto *Lit = dyn_cast<StringLiteral>(BaseExpr);
2041 if (const auto *PE = dyn_cast<PredefinedExpr>(BaseExpr))
2042 Lit = PE->getFunctionName();
2043
2044 if (!Lit)
2045 return false;
2046
2047 AsString.Bytes = Lit->getBytes();
2048 AsString.CharWidth = Lit->getCharByteWidth();
2049 return true;
2050}
2051
2052// Determine whether two string literals potentially overlap. This will be the
2053// case if they agree on the values of all the bytes on the overlapping region
2054// between them.
2055//
2056// The overlapping region is the portion of the two string literals that must
2057// overlap in memory if the pointers actually point to the same address at
2058// runtime. For example, if LHS is "abcdef" + 3 and RHS is "cdef\0gh" + 1 then
2059// the overlapping region is "cdef\0", which in this case does agree, so the
2060// strings are potentially overlapping. Conversely, for "foobar" + 3 versus
2061// "bazbar" + 3, the overlapping region contains all of both strings, so they
2062// are not potentially overlapping, even though they agree from the given
2063// addresses onwards.
2064//
2065// See open core issue CWG2765 which is discussing the desired rule here.
2066static bool ArePotentiallyOverlappingStringLiterals(const EvalInfo &Info,
2067 const LValue &LHS,
2068 const LValue &RHS) {
2069 LValueBaseString LHSString, RHSString;
2070 if (!GetLValueBaseAsString(Info, LHS, LHSString) ||
2071 !GetLValueBaseAsString(Info, RHS, RHSString))
2072 return false;
2073
2074 // This is the byte offset to the location of the first character of LHS
2075 // within RHS. We don't need to look at the characters of one string that
2076 // would appear before the start of the other string if they were merged.
2077 CharUnits Offset = RHS.Offset - LHS.Offset;
2078 if (Offset.isNegative()) {
2079 if (LHSString.Bytes.size() < (size_t)-Offset.getQuantity())
2080 return false;
2081 LHSString.Bytes = LHSString.Bytes.drop_front(-Offset.getQuantity());
2082 } else {
2083 if (RHSString.Bytes.size() < (size_t)Offset.getQuantity())
2084 return false;
2085 RHSString.Bytes = RHSString.Bytes.drop_front(Offset.getQuantity());
2086 }
2087
2088 bool LHSIsLonger = LHSString.Bytes.size() > RHSString.Bytes.size();
2089 StringRef Longer = LHSIsLonger ? LHSString.Bytes : RHSString.Bytes;
2090 StringRef Shorter = LHSIsLonger ? RHSString.Bytes : LHSString.Bytes;
2091 int ShorterCharWidth = (LHSIsLonger ? RHSString : LHSString).CharWidth;
2092
2093 // The null terminator isn't included in the string data, so check for it
2094 // manually. If the longer string doesn't have a null terminator where the
2095 // shorter string ends, they aren't potentially overlapping.
2096 for (int NullByte : llvm::seq(ShorterCharWidth)) {
2097 if (Shorter.size() + NullByte >= Longer.size())
2098 break;
2099 if (Longer[Shorter.size() + NullByte])
2100 return false;
2101 }
2102
2103 // Otherwise, they're potentially overlapping if and only if the overlapping
2104 // region is the same.
2105 return Shorter == Longer.take_front(Shorter.size());
2106}
2107
2108static bool IsWeakLValue(const LValue &Value) {
2110 return Decl && Decl->isWeak();
2111}
2112
2113static bool isZeroSized(const LValue &Value) {
2115 if (isa_and_nonnull<VarDecl>(Decl)) {
2116 QualType Ty = Decl->getType();
2117 if (Ty->isArrayType())
2118 return Ty->isIncompleteType() ||
2119 Decl->getASTContext().getTypeSize(Ty) == 0;
2120 }
2121 return false;
2122}
2123
2124static bool HasSameBase(const LValue &A, const LValue &B) {
2125 if (!A.getLValueBase())
2126 return !B.getLValueBase();
2127 if (!B.getLValueBase())
2128 return false;
2129
2130 if (A.getLValueBase().getOpaqueValue() !=
2131 B.getLValueBase().getOpaqueValue())
2132 return false;
2133
2134 return A.getLValueCallIndex() == B.getLValueCallIndex() &&
2135 A.getLValueVersion() == B.getLValueVersion();
2136}
2137
2138static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
2139 assert(Base && "no location for a null lvalue");
2140 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2141
2142 // For a parameter, find the corresponding call stack frame (if it still
2143 // exists), and point at the parameter of the function definition we actually
2144 // invoked.
2145 if (auto *PVD = dyn_cast_or_null<ParmVarDecl>(VD)) {
2146 unsigned Idx = PVD->getFunctionScopeIndex();
2147 for (CallStackFrame *F = Info.CurrentCall; F; F = F->Caller) {
2148 if (F->Arguments.CallIndex == Base.getCallIndex() &&
2149 F->Arguments.Version == Base.getVersion() && F->Callee &&
2150 Idx < F->Callee->getNumParams()) {
2151 VD = F->Callee->getParamDecl(Idx);
2152 break;
2153 }
2154 }
2155 }
2156
2157 if (VD)
2158 Info.Note(VD->getLocation(), diag::note_declared_at);
2159 else if (const Expr *E = Base.dyn_cast<const Expr*>())
2160 Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
2161 else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
2162 // FIXME: Produce a note for dangling pointers too.
2163 if (std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA))
2164 Info.Note((*Alloc)->AllocExpr->getExprLoc(),
2165 diag::note_constexpr_dynamic_alloc_here);
2166 }
2167
2168 // We have no information to show for a typeid(T) object.
2169}
2170
2175
2176/// Materialized temporaries that we've already checked to determine if they're
2177/// initializsed by a constant expression.
2180
2182 EvalInfo &Info, SourceLocation DiagLoc,
2183 QualType Type, const APValue &Value,
2184 ConstantExprKind Kind,
2185 const FieldDecl *SubobjectDecl,
2186 CheckedTemporaries &CheckedTemps);
2187
2188/// Check that this reference or pointer core constant expression is a valid
2189/// value for an address or reference constant expression. Return true if we
2190/// can fold this expression, whether or not it's a constant expression.
2191static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
2192 QualType Type, const LValue &LVal,
2193 ConstantExprKind Kind,
2194 CheckedTemporaries &CheckedTemps) {
2195 bool IsReferenceType = Type->isReferenceType();
2196
2197 APValue::LValueBase Base = LVal.getLValueBase();
2198 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
2199
2200 const Expr *BaseE = Base.dyn_cast<const Expr *>();
2201 const ValueDecl *BaseVD = Base.dyn_cast<const ValueDecl*>();
2202
2203 // Additional restrictions apply in a template argument. We only enforce the
2204 // C++20 restrictions here; additional syntactic and semantic restrictions
2205 // are applied elsewhere.
2206 if (isTemplateArgument(Kind)) {
2207 int InvalidBaseKind = -1;
2208 StringRef Ident;
2209 if (Base.is<TypeInfoLValue>())
2210 InvalidBaseKind = 0;
2211 else if (isa_and_nonnull<StringLiteral>(BaseE))
2212 InvalidBaseKind = 1;
2213 else if (isa_and_nonnull<MaterializeTemporaryExpr>(BaseE) ||
2214 isa_and_nonnull<LifetimeExtendedTemporaryDecl>(BaseVD))
2215 InvalidBaseKind = 2;
2216 else if (auto *PE = dyn_cast_or_null<PredefinedExpr>(BaseE)) {
2217 InvalidBaseKind = 3;
2218 Ident = PE->getIdentKindName();
2219 }
2220
2221 if (InvalidBaseKind != -1) {
2222 Info.FFDiag(Loc, diag::note_constexpr_invalid_template_arg)
2223 << IsReferenceType << !Designator.Entries.empty() << InvalidBaseKind
2224 << Ident;
2225 return false;
2226 }
2227 }
2228
2229 if (auto *FD = dyn_cast_or_null<FunctionDecl>(BaseVD);
2230 FD && FD->isImmediateFunction()) {
2231 Info.FFDiag(Loc, diag::note_consteval_address_accessible)
2232 << !Type->isAnyPointerType();
2233 Info.Note(FD->getLocation(), diag::note_declared_at);
2234 return false;
2235 }
2236
2237 // Check that the object is a global. Note that the fake 'this' object we
2238 // manufacture when checking potential constant expressions is conservatively
2239 // assumed to be global here.
2240 if (!IsGlobalLValue(Base)) {
2241 if (Info.getLangOpts().CPlusPlus11) {
2242 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
2243 << IsReferenceType << !Designator.Entries.empty() << !!BaseVD
2244 << BaseVD;
2245 auto *VarD = dyn_cast_or_null<VarDecl>(BaseVD);
2246 if (VarD && VarD->isConstexpr()) {
2247 // Non-static local constexpr variables have unintuitive semantics:
2248 // constexpr int a = 1;
2249 // constexpr const int *p = &a;
2250 // ... is invalid because the address of 'a' is not constant. Suggest
2251 // adding a 'static' in this case.
2252 Info.Note(VarD->getLocation(), diag::note_constexpr_not_static)
2253 << VarD
2254 << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static ");
2255 } else {
2256 NoteLValueLocation(Info, Base);
2257 }
2258 } else {
2259 Info.FFDiag(Loc);
2260 }
2261 // Don't allow references to temporaries to escape.
2262 return false;
2263 }
2264 assert((Info.checkingPotentialConstantExpression() ||
2265 LVal.getLValueCallIndex() == 0) &&
2266 "have call index for global lvalue");
2267
2268 if (LVal.allowConstexprUnknown()) {
2269 if (BaseVD) {
2270 Info.FFDiag(Loc, diag::note_constexpr_var_init_non_constant, 1) << BaseVD;
2271 NoteLValueLocation(Info, Base);
2272 } else {
2273 Info.FFDiag(Loc);
2274 }
2275 return false;
2276 }
2277
2278 if (Base.is<DynamicAllocLValue>()) {
2279 Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc)
2280 << IsReferenceType << !Designator.Entries.empty();
2281 NoteLValueLocation(Info, Base);
2282 return false;
2283 }
2284
2285 if (BaseVD) {
2286 if (const VarDecl *Var = dyn_cast<const VarDecl>(BaseVD)) {
2287 // Check if this is a thread-local variable.
2288 if (Var->getTLSKind())
2289 // FIXME: Diagnostic!
2290 return false;
2291
2292 // A dllimport variable never acts like a constant, unless we're
2293 // evaluating a value for use only in name mangling, and unless it's a
2294 // static local. For the latter case, we'd still need to evaluate the
2295 // constant expression in case we're inside a (inlined) function.
2296 if (!isForManglingOnly(Kind) && Var->hasAttr<DLLImportAttr>() &&
2297 !Var->isStaticLocal())
2298 return false;
2299
2300 // In CUDA/HIP device compilation, only device side variables have
2301 // constant addresses.
2302 if (Info.getLangOpts().CUDA && Info.getLangOpts().CUDAIsDevice &&
2303 Info.Ctx.CUDAConstantEvalCtx.NoWrongSidedVars) {
2304 if ((!Var->hasAttr<CUDADeviceAttr>() &&
2305 !Var->hasAttr<CUDAConstantAttr>() &&
2306 !Var->getType()->isCUDADeviceBuiltinSurfaceType() &&
2307 !Var->getType()->isCUDADeviceBuiltinTextureType()) ||
2308 Var->hasAttr<HIPManagedAttr>())
2309 return false;
2310 }
2311 }
2312 if (const auto *FD = dyn_cast<const FunctionDecl>(BaseVD)) {
2313 // __declspec(dllimport) must be handled very carefully:
2314 // We must never initialize an expression with the thunk in C++.
2315 // Doing otherwise would allow the same id-expression to yield
2316 // different addresses for the same function in different translation
2317 // units. However, this means that we must dynamically initialize the
2318 // expression with the contents of the import address table at runtime.
2319 //
2320 // The C language has no notion of ODR; furthermore, it has no notion of
2321 // dynamic initialization. This means that we are permitted to
2322 // perform initialization with the address of the thunk.
2323 if (Info.getLangOpts().CPlusPlus && !isForManglingOnly(Kind) &&
2324 FD->hasAttr<DLLImportAttr>())
2325 // FIXME: Diagnostic!
2326 return false;
2327 }
2328 } else if (const auto *MTE =
2329 dyn_cast_or_null<MaterializeTemporaryExpr>(BaseE)) {
2330 if (CheckedTemps.insert(MTE).second) {
2331 QualType TempType = getType(Base);
2332 if (TempType.isDestructedType()) {
2333 Info.FFDiag(MTE->getExprLoc(),
2334 diag::note_constexpr_unsupported_temporary_nontrivial_dtor)
2335 << TempType;
2336 return false;
2337 }
2338
2339 APValue *V = MTE->getOrCreateValue(false);
2340 assert(V && "evasluation result refers to uninitialised temporary");
2342 Info, MTE->getExprLoc(), TempType, *V, Kind,
2343 /*SubobjectDecl=*/nullptr, CheckedTemps))
2344 return false;
2345 }
2346 }
2347
2348 // Allow address constant expressions to be past-the-end pointers. This is
2349 // an extension: the standard requires them to point to an object.
2350 if (!IsReferenceType)
2351 return true;
2352
2353 // A reference constant expression must refer to an object.
2354 if (!Base) {
2355 // FIXME: diagnostic
2356 Info.CCEDiag(Loc);
2357 return true;
2358 }
2359
2360 // Does this refer one past the end of some object?
2361 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
2362 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
2363 << !Designator.Entries.empty() << !!BaseVD << BaseVD;
2364 NoteLValueLocation(Info, Base);
2365 }
2366
2367 return true;
2368}
2369
2370/// Member pointers are constant expressions unless they point to a
2371/// non-virtual dllimport member function.
2372static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
2373 SourceLocation Loc,
2374 QualType Type,
2375 const APValue &Value,
2376 ConstantExprKind Kind) {
2377 const ValueDecl *Member = Value.getMemberPointerDecl();
2378 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
2379 if (!FD)
2380 return true;
2381 if (FD->isImmediateFunction()) {
2382 Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0;
2383 Info.Note(FD->getLocation(), diag::note_declared_at);
2384 return false;
2385 }
2386 return isForManglingOnly(Kind) || FD->isVirtual() ||
2387 !FD->hasAttr<DLLImportAttr>();
2388}
2389
2390/// Check that this core constant expression is of literal type, and if not,
2391/// produce an appropriate diagnostic.
2392static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
2393 const LValue *This = nullptr) {
2394 // The restriction to literal types does not exist in C++23 anymore.
2395 if (Info.getLangOpts().CPlusPlus23)
2396 return true;
2397
2398 if (!E->isPRValue() || E->getType()->isLiteralType(Info.Ctx))
2399 return true;
2400
2401 // C++1y: A constant initializer for an object o [...] may also invoke
2402 // constexpr constructors for o and its subobjects even if those objects
2403 // are of non-literal class types.
2404 //
2405 // C++11 missed this detail for aggregates, so classes like this:
2406 // struct foo_t { union { int i; volatile int j; } u; };
2407 // are not (obviously) initializable like so:
2408 // __attribute__((__require_constant_initialization__))
2409 // static const foo_t x = {{0}};
2410 // because "i" is a subobject with non-literal initialization (due to the
2411 // volatile member of the union). See:
2412 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2413 // Therefore, we use the C++1y behavior.
2414 if (This && Info.EvaluatingDecl == This->getLValueBase())
2415 return true;
2416
2417 // Prvalue constant expressions must be of literal types.
2418 if (Info.getLangOpts().CPlusPlus11)
2419 Info.FFDiag(E, diag::note_constexpr_nonliteral)
2420 << E->getType();
2421 else
2422 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2423 return false;
2424}
2425
2427 EvalInfo &Info, SourceLocation DiagLoc,
2428 QualType Type, const APValue &Value,
2429 ConstantExprKind Kind,
2430 const FieldDecl *SubobjectDecl,
2431 CheckedTemporaries &CheckedTemps) {
2432 if (!Value.hasValue()) {
2433 if (SubobjectDecl) {
2434 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2435 << /*(name)*/ 1 << SubobjectDecl;
2436 Info.Note(SubobjectDecl->getLocation(),
2437 diag::note_constexpr_subobject_declared_here);
2438 } else {
2439 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2440 << /*of type*/ 0 << Type;
2441 }
2442 return false;
2443 }
2444
2445 // We allow _Atomic(T) to be initialized from anything that T can be
2446 // initialized from.
2447 if (const AtomicType *AT = Type->getAs<AtomicType>())
2448 Type = AT->getValueType();
2449
2450 // Core issue 1454: For a literal constant expression of array or class type,
2451 // each subobject of its value shall have been initialized by a constant
2452 // expression.
2453 if (Value.isArray()) {
2455 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
2456 if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2457 Value.getArrayInitializedElt(I), Kind,
2458 SubobjectDecl, CheckedTemps))
2459 return false;
2460 }
2461 if (!Value.hasArrayFiller())
2462 return true;
2463 return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2464 Value.getArrayFiller(), Kind, SubobjectDecl,
2465 CheckedTemps);
2466 }
2467 if (Value.isUnion() && Value.getUnionField()) {
2468 return CheckEvaluationResult(
2469 CERK, Info, DiagLoc, Value.getUnionField()->getType(),
2470 Value.getUnionValue(), Kind, Value.getUnionField(), CheckedTemps);
2471 }
2472 if (Value.isStruct()) {
2473 auto *RD = Type->castAsRecordDecl();
2474 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2475 unsigned BaseIndex = 0;
2476 for (const CXXBaseSpecifier &BS : CD->bases()) {
2477 const APValue &BaseValue = Value.getStructBase(BaseIndex);
2478 if (!BaseValue.hasValue()) {
2479 SourceLocation TypeBeginLoc = BS.getBaseTypeLoc();
2480 Info.FFDiag(TypeBeginLoc, diag::note_constexpr_uninitialized_base)
2481 << BS.getType() << SourceRange(TypeBeginLoc, BS.getEndLoc());
2482 return false;
2483 }
2484 if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(), BaseValue,
2485 Kind, /*SubobjectDecl=*/nullptr,
2486 CheckedTemps))
2487 return false;
2488 ++BaseIndex;
2489 }
2490 }
2491 for (const auto *I : RD->fields()) {
2492 if (I->isUnnamedBitField())
2493 continue;
2494
2495 if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),
2496 Value.getStructField(I->getFieldIndex()), Kind,
2497 I, CheckedTemps))
2498 return false;
2499 }
2500 }
2501
2502 if (Value.isLValue() &&
2504 LValue LVal;
2505 LVal.setFrom(Info.Ctx, Value);
2506 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Kind,
2507 CheckedTemps);
2508 }
2509
2510 if (Value.isMemberPointer() &&
2512 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Kind);
2513
2514 // Everything else is fine.
2515 return true;
2516}
2517
2518/// Check that this core constant expression value is a valid value for a
2519/// constant expression. If not, report an appropriate diagnostic. Does not
2520/// check that the expression is of literal type.
2521static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
2522 QualType Type, const APValue &Value,
2523 ConstantExprKind Kind) {
2524 // Nothing to check for a constant expression of type 'cv void'.
2525 if (Type->isVoidType())
2526 return true;
2527
2528 CheckedTemporaries CheckedTemps;
2530 Info, DiagLoc, Type, Value, Kind,
2531 /*SubobjectDecl=*/nullptr, CheckedTemps);
2532}
2533
2534/// Check that this evaluated value is fully-initialized and can be loaded by
2535/// an lvalue-to-rvalue conversion.
2536static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,
2537 QualType Type, const APValue &Value) {
2538 CheckedTemporaries CheckedTemps;
2539 return CheckEvaluationResult(
2541 ConstantExprKind::Normal, /*SubobjectDecl=*/nullptr, CheckedTemps);
2542}
2543
2544/// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless
2545/// "the allocated storage is deallocated within the evaluation".
2546static bool CheckMemoryLeaks(EvalInfo &Info) {
2547 if (!Info.HeapAllocs.empty()) {
2548 // We can still fold to a constant despite a compile-time memory leak,
2549 // so long as the heap allocation isn't referenced in the result (we check
2550 // that in CheckConstantExpression).
2551 Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr,
2552 diag::note_constexpr_memory_leak)
2553 << unsigned(Info.HeapAllocs.size() - 1);
2554 }
2555 return true;
2556}
2557
2558static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
2559 // A null base expression indicates a null pointer. These are always
2560 // evaluatable, and they are false unless the offset is zero.
2561 if (!Value.getLValueBase()) {
2562 // TODO: Should a non-null pointer with an offset of zero evaluate to true?
2563 Result = !Value.getLValueOffset().isZero();
2564 return true;
2565 }
2566
2567 // We have a non-null base. These are generally known to be true, but if it's
2568 // a weak declaration it can be null at runtime.
2569 Result = true;
2570 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
2571 return !Decl || !Decl->isWeak();
2572}
2573
2574static bool HandleConversionToBool(const APValue &Val, bool &Result) {
2575 // TODO: This function should produce notes if it fails.
2576 switch (Val.getKind()) {
2577 case APValue::None:
2579 return false;
2580 case APValue::Int:
2581 Result = Val.getInt().getBoolValue();
2582 return true;
2584 Result = Val.getFixedPoint().getBoolValue();
2585 return true;
2586 case APValue::Float:
2587 Result = !Val.getFloat().isZero();
2588 return true;
2590 Result = Val.getComplexIntReal().getBoolValue() ||
2591 Val.getComplexIntImag().getBoolValue();
2592 return true;
2594 Result = !Val.getComplexFloatReal().isZero() ||
2595 !Val.getComplexFloatImag().isZero();
2596 return true;
2597 case APValue::LValue:
2598 return EvalPointerValueAsBool(Val, Result);
2600 if (Val.getMemberPointerDecl() && Val.getMemberPointerDecl()->isWeak()) {
2601 return false;
2602 }
2604 return true;
2605 case APValue::Vector:
2606 case APValue::Matrix:
2607 case APValue::Array:
2608 case APValue::Struct:
2609 case APValue::Union:
2611 return false;
2612 }
2613
2614 llvm_unreachable("unknown APValue kind");
2615}
2616
2617static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2618 EvalInfo &Info) {
2619 assert(!E->isValueDependent());
2620 assert(E->isPRValue() && "missing lvalue-to-rvalue conv in bool condition");
2621 APValue Val;
2622 if (!Evaluate(Val, Info, E))
2623 return false;
2624 return HandleConversionToBool(Val, Result);
2625}
2626
2627template<typename T>
2628static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2629 const T &SrcValue, QualType DestType) {
2630 Info.CCEDiag(E, diag::note_constexpr_overflow) << SrcValue << DestType;
2631 if (const auto *OBT = DestType->getAs<OverflowBehaviorType>();
2632 OBT && OBT->isTrapKind()) {
2633 return false;
2634 }
2635 return Info.noteUndefinedBehavior();
2636}
2637
2638static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2639 QualType SrcType, const APFloat &Value,
2640 QualType DestType, APSInt &Result) {
2641 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2642 // Determine whether we are converting to unsigned or signed.
2643 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2644
2645 Result = APSInt(DestWidth, !DestSigned);
2646 bool ignored;
2647 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2648 & APFloat::opInvalidOp)
2649 return HandleOverflow(Info, E, Value, DestType);
2650 return true;
2651}
2652
2653/// Get rounding mode to use in evaluation of the specified expression.
2654///
2655/// If rounding mode is unknown at compile time, still try to evaluate the
2656/// expression. If the result is exact, it does not depend on rounding mode.
2657/// So return "tonearest" mode instead of "dynamic".
2658static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E) {
2659 llvm::RoundingMode RM =
2660 E->getFPFeaturesInEffect(Info.getLangOpts()).getRoundingMode();
2661 if (RM == llvm::RoundingMode::Dynamic)
2662 RM = llvm::RoundingMode::NearestTiesToEven;
2663 return RM;
2664}
2665
2666/// Check if the given evaluation result is allowed for constant evaluation.
2667static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E,
2668 APFloat::opStatus St) {
2669 // In a constant context, assume that any dynamic rounding mode or FP
2670 // exception state matches the default floating-point environment.
2671 if (Info.InConstantContext)
2672 return true;
2673
2674 FPOptions FPO = E->getFPFeaturesInEffect(Info.getLangOpts());
2675 if ((St & APFloat::opInexact) &&
2676 FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) {
2677 // Inexact result means that it depends on rounding mode. If the requested
2678 // mode is dynamic, the evaluation cannot be made in compile time.
2679 Info.FFDiag(E, diag::note_constexpr_dynamic_rounding);
2680 return false;
2681 }
2682
2683 if ((St != APFloat::opOK) &&
2684 (FPO.getRoundingMode() == llvm::RoundingMode::Dynamic ||
2686 FPO.getAllowFEnvAccess())) {
2687 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
2688 return false;
2689 }
2690
2691 if ((St & APFloat::opStatus::opInvalidOp) &&
2693 // There is no usefully definable result.
2694 Info.FFDiag(E);
2695 return false;
2696 }
2697
2698 // FIXME: if:
2699 // - evaluation triggered other FP exception, and
2700 // - exception mode is not "ignore", and
2701 // - the expression being evaluated is not a part of global variable
2702 // initializer,
2703 // the evaluation probably need to be rejected.
2704 return true;
2705}
2706
2707static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2708 QualType SrcType, QualType DestType,
2709 APFloat &Result) {
2710 assert((isa<CastExpr>(E) || isa<CompoundAssignOperator>(E) ||
2712 "HandleFloatToFloatCast has been checked with only CastExpr, "
2713 "CompoundAssignOperator and ConvertVectorExpr. Please either validate "
2714 "the new expression or address the root cause of this usage.");
2715 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2716 APFloat::opStatus St;
2717 APFloat Value = Result;
2718 bool ignored;
2719 St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored);
2720 return checkFloatingPointResult(Info, E, St);
2721}
2722
2723static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2724 QualType DestType, QualType SrcType,
2725 const APSInt &Value) {
2726 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2727 // Figure out if this is a truncate, extend or noop cast.
2728 // If the input is signed, do a sign extend, noop, or truncate.
2729 APSInt Result = Value.extOrTrunc(DestWidth);
2730 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2731 if (DestType->isBooleanType())
2732 Result = Value.getBoolValue();
2733 return Result;
2734}
2735
2736static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2737 const FPOptions FPO,
2738 QualType SrcType, const APSInt &Value,
2739 QualType DestType, APFloat &Result) {
2740 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2741 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2742 APFloat::opStatus St = Result.convertFromAPInt(Value, Value.isSigned(), RM);
2743 return checkFloatingPointResult(Info, E, St);
2744}
2745
2746static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2747 APValue &Value, const FieldDecl *FD) {
2748 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2749
2750 if (!Value.isInt()) {
2751 // Trying to store a pointer-cast-to-integer into a bitfield.
2752 // FIXME: In this case, we should provide the diagnostic for casting
2753 // a pointer to an integer.
2754 assert(Value.isLValue() && "integral value neither int nor lvalue?");
2755 Info.FFDiag(E);
2756 return false;
2757 }
2758
2759 APSInt &Int = Value.getInt();
2760 unsigned OldBitWidth = Int.getBitWidth();
2761 unsigned NewBitWidth = FD->getBitWidthValue();
2762 if (NewBitWidth < OldBitWidth)
2763 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2764 return true;
2765}
2766
2767/// Perform the given integer operation, which is known to need at most BitWidth
2768/// bits, and check for overflow in the original type (if that type was not an
2769/// unsigned type).
2770template<typename Operation>
2771static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2772 const APSInt &LHS, const APSInt &RHS,
2773 unsigned BitWidth, Operation Op,
2774 APSInt &Result) {
2775 if (LHS.isUnsigned()) {
2776 Result = Op(LHS, RHS);
2777 return true;
2778 }
2779
2780 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2781 Result = Value.trunc(LHS.getBitWidth());
2782 if (Result.extend(BitWidth) != Value && !E->getType().isWrapType()) {
2783 if (Info.checkingForUndefinedBehavior())
2784 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2785 diag::warn_integer_constant_overflow)
2786 << toString(Result, 10, Result.isSigned(), /*formatAsCLiteral=*/false,
2787 /*UpperCase=*/true, /*InsertSeparators=*/true)
2788 << E->getType() << E->getSourceRange();
2789 return HandleOverflow(Info, E, Value, E->getType());
2790 }
2791 return true;
2792}
2793
2794/// Perform the given binary integer operation.
2795static bool handleIntIntBinOp(EvalInfo &Info, const BinaryOperator *E,
2796 const APSInt &LHS, BinaryOperatorKind Opcode,
2797 APSInt RHS, APSInt &Result) {
2798 bool HandleOverflowResult = true;
2799 switch (Opcode) {
2800 default:
2801 Info.FFDiag(E);
2802 return false;
2803 case BO_Mul:
2804 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2805 std::multiplies<APSInt>(), Result);
2806 case BO_Add:
2807 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2808 std::plus<APSInt>(), Result);
2809 case BO_Sub:
2810 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2811 std::minus<APSInt>(), Result);
2812 case BO_And: Result = LHS & RHS; return true;
2813 case BO_Xor: Result = LHS ^ RHS; return true;
2814 case BO_Or: Result = LHS | RHS; return true;
2815 case BO_Div:
2816 case BO_Rem:
2817 if (RHS == 0) {
2818 Info.FFDiag(E, diag::note_expr_divide_by_zero)
2819 << E->getRHS()->getSourceRange();
2820 return false;
2821 }
2822 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2823 // this operation and gives the two's complement result.
2824 if (RHS.isNegative() && RHS.isAllOnes() && LHS.isSigned() &&
2825 LHS.isMinSignedValue())
2826 HandleOverflowResult = HandleOverflow(
2827 Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
2828 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2829 return HandleOverflowResult;
2830 case BO_Shl: {
2831 if (Info.getLangOpts().OpenCL)
2832 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2833 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2834 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2835 RHS.isUnsigned());
2836 else if (RHS.isSigned() && RHS.isNegative()) {
2837 // During constant-folding, a negative shift is an opposite shift. Such
2838 // a shift is not a constant expression.
2839 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2840 if (!Info.noteUndefinedBehavior())
2841 return false;
2842 RHS = -RHS;
2843 goto shift_right;
2844 }
2845 shift_left:
2846 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2847 // the shifted type.
2848 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2849 if (SA != RHS) {
2850 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2851 << RHS << E->getType() << LHS.getBitWidth();
2852 if (!Info.noteUndefinedBehavior())
2853 return false;
2854 } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) {
2855 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2856 // operand, and must not overflow the corresponding unsigned type.
2857 // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2858 // E1 x 2^E2 module 2^N.
2859 if (LHS.isNegative()) {
2860 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2861 if (!Info.noteUndefinedBehavior())
2862 return false;
2863 } else if (LHS.countl_zero() < SA) {
2864 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2865 if (!Info.noteUndefinedBehavior())
2866 return false;
2867 }
2868 }
2869 Result = LHS << SA;
2870 return true;
2871 }
2872 case BO_Shr: {
2873 if (Info.getLangOpts().OpenCL)
2874 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2875 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2876 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2877 RHS.isUnsigned());
2878 else if (RHS.isSigned() && RHS.isNegative()) {
2879 // During constant-folding, a negative shift is an opposite shift. Such a
2880 // shift is not a constant expression.
2881 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2882 if (!Info.noteUndefinedBehavior())
2883 return false;
2884 RHS = -RHS;
2885 goto shift_left;
2886 }
2887 shift_right:
2888 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2889 // shifted type.
2890 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2891 if (SA != RHS) {
2892 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2893 << RHS << E->getType() << LHS.getBitWidth();
2894 if (!Info.noteUndefinedBehavior())
2895 return false;
2896 }
2897
2898 Result = LHS >> SA;
2899 return true;
2900 }
2901
2902 case BO_LT: Result = LHS < RHS; return true;
2903 case BO_GT: Result = LHS > RHS; return true;
2904 case BO_LE: Result = LHS <= RHS; return true;
2905 case BO_GE: Result = LHS >= RHS; return true;
2906 case BO_EQ: Result = LHS == RHS; return true;
2907 case BO_NE: Result = LHS != RHS; return true;
2908 case BO_Cmp:
2909 llvm_unreachable("BO_Cmp should be handled elsewhere");
2910 }
2911}
2912
2913/// Perform the given binary floating-point operation, in-place, on LHS.
2914static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E,
2915 APFloat &LHS, BinaryOperatorKind Opcode,
2916 const APFloat &RHS) {
2917 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2918 APFloat::opStatus St;
2919 switch (Opcode) {
2920 default:
2921 Info.FFDiag(E);
2922 return false;
2923 case BO_Mul:
2924 St = LHS.multiply(RHS, RM);
2925 break;
2926 case BO_Add:
2927 St = LHS.add(RHS, RM);
2928 break;
2929 case BO_Sub:
2930 St = LHS.subtract(RHS, RM);
2931 break;
2932 case BO_Div:
2933 // [expr.mul]p4:
2934 // If the second operand of / or % is zero the behavior is undefined.
2935 if (RHS.isZero())
2936 Info.CCEDiag(E, diag::note_expr_divide_by_zero);
2937 St = LHS.divide(RHS, RM);
2938 break;
2939 }
2940
2941 // [expr.pre]p4:
2942 // If during the evaluation of an expression, the result is not
2943 // mathematically defined [...], the behavior is undefined.
2944 // FIXME: C++ rules require us to not conform to IEEE 754 here.
2945 if (LHS.isNaN()) {
2946 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
2947 return Info.noteUndefinedBehavior();
2948 }
2949
2950 return checkFloatingPointResult(Info, E, St);
2951}
2952
2953static bool handleLogicalOpForVector(const APInt &LHSValue,
2954 BinaryOperatorKind Opcode,
2955 const APInt &RHSValue, APInt &Result) {
2956 bool LHS = (LHSValue != 0);
2957 bool RHS = (RHSValue != 0);
2958
2959 if (Opcode == BO_LAnd)
2960 Result = LHS && RHS;
2961 else
2962 Result = LHS || RHS;
2963 return true;
2964}
2965static bool handleLogicalOpForVector(const APFloat &LHSValue,
2966 BinaryOperatorKind Opcode,
2967 const APFloat &RHSValue, APInt &Result) {
2968 bool LHS = !LHSValue.isZero();
2969 bool RHS = !RHSValue.isZero();
2970
2971 if (Opcode == BO_LAnd)
2972 Result = LHS && RHS;
2973 else
2974 Result = LHS || RHS;
2975 return true;
2976}
2977
2978static bool handleLogicalOpForVector(const APValue &LHSValue,
2979 BinaryOperatorKind Opcode,
2980 const APValue &RHSValue, APInt &Result) {
2981 // The result is always an int type, however operands match the first.
2982 if (LHSValue.getKind() == APValue::Int)
2983 return handleLogicalOpForVector(LHSValue.getInt(), Opcode,
2984 RHSValue.getInt(), Result);
2985 assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
2986 return handleLogicalOpForVector(LHSValue.getFloat(), Opcode,
2987 RHSValue.getFloat(), Result);
2988}
2989
2990template <typename APTy>
2991static bool
2993 const APTy &RHSValue, APInt &Result) {
2994 switch (Opcode) {
2995 default:
2996 llvm_unreachable("unsupported binary operator");
2997 case BO_EQ:
2998 Result = (LHSValue == RHSValue);
2999 break;
3000 case BO_NE:
3001 Result = (LHSValue != RHSValue);
3002 break;
3003 case BO_LT:
3004 Result = (LHSValue < RHSValue);
3005 break;
3006 case BO_GT:
3007 Result = (LHSValue > RHSValue);
3008 break;
3009 case BO_LE:
3010 Result = (LHSValue <= RHSValue);
3011 break;
3012 case BO_GE:
3013 Result = (LHSValue >= RHSValue);
3014 break;
3015 }
3016
3017 // The boolean operations on these vector types use an instruction that
3018 // results in a mask of '-1' for the 'truth' value. Ensure that we negate 1
3019 // to -1 to make sure that we produce the correct value.
3020 Result.negate();
3021
3022 return true;
3023}
3024
3025static bool handleCompareOpForVector(const APValue &LHSValue,
3026 BinaryOperatorKind Opcode,
3027 const APValue &RHSValue, APInt &Result) {
3028 // The result is always an int type, however operands match the first.
3029 if (LHSValue.getKind() == APValue::Int)
3030 return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode,
3031 RHSValue.getInt(), Result);
3032 assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
3033 return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode,
3034 RHSValue.getFloat(), Result);
3035}
3036
3037// Perform binary operations for vector types, in place on the LHS.
3038static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E,
3039 BinaryOperatorKind Opcode,
3040 APValue &LHSValue,
3041 const APValue &RHSValue) {
3042 assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI &&
3043 "Operation not supported on vector types");
3044
3045 const auto *VT = E->getType()->castAs<VectorType>();
3046 unsigned NumElements = VT->getNumElements();
3047 QualType EltTy = VT->getElementType();
3048
3049 // In the cases (typically C as I've observed) where we aren't evaluating
3050 // constexpr but are checking for cases where the LHS isn't yet evaluatable,
3051 // just give up.
3052 if (!LHSValue.isVector()) {
3053 assert(LHSValue.isLValue() &&
3054 "A vector result that isn't a vector OR uncalculated LValue");
3055 Info.FFDiag(E);
3056 return false;
3057 }
3058
3059 assert(LHSValue.getVectorLength() == NumElements &&
3060 RHSValue.getVectorLength() == NumElements && "Different vector sizes");
3061
3062 SmallVector<APValue, 4> ResultElements;
3063
3064 for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) {
3065 APValue LHSElt = LHSValue.getVectorElt(EltNum);
3066 APValue RHSElt = RHSValue.getVectorElt(EltNum);
3067
3068 if (EltTy->isIntegerType()) {
3069 APSInt EltResult{Info.Ctx.getIntWidth(EltTy),
3070 EltTy->isUnsignedIntegerType()};
3071 bool Success = true;
3072
3073 if (BinaryOperator::isLogicalOp(Opcode))
3074 Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3075 else if (BinaryOperator::isComparisonOp(Opcode))
3076 Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3077 else
3078 Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode,
3079 RHSElt.getInt(), EltResult);
3080
3081 if (!Success) {
3082 Info.FFDiag(E);
3083 return false;
3084 }
3085 ResultElements.emplace_back(EltResult);
3086
3087 } else if (EltTy->isFloatingType()) {
3088 assert(LHSElt.getKind() == APValue::Float &&
3089 RHSElt.getKind() == APValue::Float &&
3090 "Mismatched LHS/RHS/Result Type");
3091 APFloat LHSFloat = LHSElt.getFloat();
3092
3093 if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode,
3094 RHSElt.getFloat())) {
3095 Info.FFDiag(E);
3096 return false;
3097 }
3098
3099 ResultElements.emplace_back(LHSFloat);
3100 }
3101 }
3102
3103 LHSValue = APValue(ResultElements.data(), ResultElements.size());
3104 return true;
3105}
3106
3107/// Cast an lvalue referring to a base subobject to a derived class, by
3108/// truncating the lvalue's path to the given length.
3109static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
3110 const RecordDecl *TruncatedType,
3111 unsigned TruncatedElements) {
3112 SubobjectDesignator &D = Result.Designator;
3113
3114 // Check we actually point to a derived class object.
3115 if (TruncatedElements == D.Entries.size())
3116 return true;
3117 assert(TruncatedElements >= D.MostDerivedPathLength &&
3118 "not casting to a derived class");
3119 if (!Result.checkSubobject(Info, E, CSK_Derived))
3120 return false;
3121
3122 // Truncate the path to the subobject, and remove any derived-to-base offsets.
3123 const RecordDecl *RD = TruncatedType;
3124 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
3125 if (RD->isInvalidDecl()) return false;
3126 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3127 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
3128 if (isVirtualBaseClass(D.Entries[I]))
3129 Result.Offset -= Layout.getVBaseClassOffset(Base);
3130 else
3131 Result.Offset -= Layout.getBaseClassOffset(Base);
3132 RD = Base;
3133 }
3134 D.Entries.resize(TruncatedElements);
3135 return true;
3136}
3137
3138static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3139 const CXXRecordDecl *Derived,
3140 const CXXRecordDecl *Base,
3141 const ASTRecordLayout *RL = nullptr) {
3142 if (!RL) {
3143 if (Derived->isInvalidDecl()) return false;
3144 RL = &Info.Ctx.getASTRecordLayout(Derived);
3145 }
3146
3147 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
3148 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
3149 return true;
3150}
3151
3152static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3153 const CXXRecordDecl *DerivedDecl,
3154 const CXXBaseSpecifier *Base) {
3155 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
3156
3157 if (!Base->isVirtual())
3158 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
3159
3160 SubobjectDesignator &D = Obj.Designator;
3161 if (D.Invalid)
3162 return false;
3163
3164 // Extract most-derived object and corresponding type.
3165 // FIXME: After implementing P2280R4 it became possible to get references
3166 // here. We do MostDerivedType->getAsCXXRecordDecl() in several other
3167 // locations and if we see crashes in those locations in the future
3168 // it may make more sense to move this fix into Lvalue::set.
3169 DerivedDecl = D.MostDerivedType.getNonReferenceType()->getAsCXXRecordDecl();
3170 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
3171 return false;
3172
3173 // Find the virtual base class.
3174 if (DerivedDecl->isInvalidDecl()) return false;
3175 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
3176 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
3177 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
3178 return true;
3179}
3180
3181static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
3182 QualType Type, LValue &Result) {
3183 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3184 PathE = E->path_end();
3185 PathI != PathE; ++PathI) {
3187 *PathI))
3188 return false;
3189 Type = (*PathI)->getType();
3190 }
3191 return true;
3192}
3193
3194/// Cast an lvalue referring to a derived class to a known base subobject.
3195static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
3196 const CXXRecordDecl *DerivedRD,
3197 const CXXRecordDecl *BaseRD) {
3198 CXXBasePaths Paths(/*FindAmbiguities=*/false,
3199 /*RecordPaths=*/true, /*DetectVirtual=*/false);
3200 if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
3201 llvm_unreachable("Class must be derived from the passed in base class!");
3202
3203 for (CXXBasePathElement &Elem : Paths.front())
3204 if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
3205 return false;
3206 return true;
3207}
3208
3209/// Update LVal to refer to the given field, which must be a member of the type
3210/// currently described by LVal.
3211static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
3212 const FieldDecl *FD,
3213 const ASTRecordLayout *RL = nullptr) {
3214 if (!RL) {
3215 if (FD->getParent()->isInvalidDecl()) return false;
3216 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
3217 }
3218
3219 unsigned I = FD->getFieldIndex();
3220 LVal.addDecl(Info, E, FD);
3221 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
3222 return true;
3223}
3224
3225/// Update LVal to refer to the given indirect field.
3226static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
3227 LValue &LVal,
3228 const IndirectFieldDecl *IFD) {
3229 for (const auto *C : IFD->chain())
3230 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
3231 return false;
3232 return true;
3233}
3234
3239
3240/// Get the size of the given type in char units.
3241static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, QualType Type,
3243 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
3244 // extension.
3245 if (Type->isVoidType() || Type->isFunctionType()) {
3246 Size = CharUnits::One();
3247 return true;
3248 }
3249
3250 if (Type->isDependentType()) {
3251 Info.FFDiag(Loc);
3252 return false;
3253 }
3254
3255 if (!Type->isConstantSizeType()) {
3256 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
3257 // FIXME: Better diagnostic.
3258 Info.FFDiag(Loc);
3259 return false;
3260 }
3261
3262 if (SOT == SizeOfType::SizeOf)
3263 Size = Info.Ctx.getTypeSizeInChars(Type);
3264 else
3265 Size = Info.Ctx.getTypeInfoDataSizeInChars(Type).Width;
3266 return true;
3267}
3268
3269/// Update a pointer value to model pointer arithmetic.
3270/// \param Info - Information about the ongoing evaluation.
3271/// \param E - The expression being evaluated, for diagnostic purposes.
3272/// \param LVal - The pointer value to be updated.
3273/// \param EltTy - The pointee type represented by LVal.
3274/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
3275static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3276 LValue &LVal, QualType EltTy,
3277 APSInt Adjustment) {
3278 CharUnits SizeOfPointee;
3279 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
3280 return false;
3281
3282 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
3283 return true;
3284}
3285
3286static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3287 LValue &LVal, QualType EltTy,
3288 int64_t Adjustment) {
3289 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
3290 APSInt::get(Adjustment));
3291}
3292
3293/// Update an lvalue to refer to a component of a complex number.
3294/// \param Info - Information about the ongoing evaluation.
3295/// \param LVal - The lvalue to be updated.
3296/// \param EltTy - The complex number's component type.
3297/// \param Imag - False for the real component, true for the imaginary.
3298static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
3299 LValue &LVal, QualType EltTy,
3300 bool Imag) {
3301 if (Imag) {
3302 CharUnits SizeOfComponent;
3303 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
3304 return false;
3305 LVal.Offset += SizeOfComponent;
3306 }
3307 LVal.addComplex(Info, E, EltTy, Imag);
3308 return true;
3309}
3310
3311static bool HandleLValueVectorElement(EvalInfo &Info, const Expr *E,
3312 LValue &LVal, QualType EltTy,
3313 uint64_t Size, uint64_t Idx) {
3314 if (Idx) {
3315 CharUnits SizeOfElement;
3316 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfElement))
3317 return false;
3318 LVal.Offset += SizeOfElement * Idx;
3319 }
3320 LVal.addVectorElement(Info, E, EltTy, Size, Idx);
3321 return true;
3322}
3323
3324/// Try to evaluate the initializer for a variable declaration.
3325///
3326/// \param Info Information about the ongoing evaluation.
3327/// \param E An expression to be used when printing diagnostics.
3328/// \param VD The variable whose initializer should be obtained.
3329/// \param Version The version of the variable within the frame.
3330/// \param Frame The frame in which the variable was created. Must be null
3331/// if this variable is not local to the evaluation.
3332/// \param Result Filled in with a pointer to the value of the variable.
3333static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
3334 const VarDecl *VD, CallStackFrame *Frame,
3335 unsigned Version, APValue *&Result) {
3336 // C++23 [expr.const]p8 If we have a reference type allow unknown references
3337 // and pointers.
3338 bool AllowConstexprUnknown =
3339 Info.getLangOpts().CPlusPlus23 && VD->getType()->isReferenceType();
3340
3341 APValue::LValueBase Base(VD, Frame ? Frame->Index : 0, Version);
3342
3343 auto CheckUninitReference = [&](bool IsLocalVariable) {
3344 if (!Result || (!Result->hasValue() && VD->getType()->isReferenceType())) {
3345 // C++23 [expr.const]p8
3346 // ... For such an object that is not usable in constant expressions, the
3347 // dynamic type of the object is constexpr-unknown. For such a reference
3348 // that is not usable in constant expressions, the reference is treated
3349 // as binding to an unspecified object of the referenced type whose
3350 // lifetime and that of all subobjects includes the entire constant
3351 // evaluation and whose dynamic type is constexpr-unknown.
3352 //
3353 // Variables that are part of the current evaluation are not
3354 // constexpr-unknown.
3355 if (!AllowConstexprUnknown || IsLocalVariable) {
3356 if (!Info.checkingPotentialConstantExpression())
3357 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
3358 return false;
3359 }
3360 Result = nullptr;
3361 }
3362 return true;
3363 };
3364
3365 // If this is a local variable, dig out its value.
3366 if (Frame) {
3367 Result = Frame->getTemporary(VD, Version);
3368 if (Result)
3369 return CheckUninitReference(/*IsLocalVariable=*/true);
3370
3371 if (!isa<ParmVarDecl>(VD)) {
3372 // Assume variables referenced within a lambda's call operator that were
3373 // not declared within the call operator are captures and during checking
3374 // of a potential constant expression, assume they are unknown constant
3375 // expressions.
3376 assert(isLambdaCallOperator(Frame->Callee) &&
3377 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
3378 "missing value for local variable");
3379 if (Info.checkingPotentialConstantExpression())
3380 return false;
3381
3382 llvm_unreachable(
3383 "A variable in a frame should either be a local or a parameter");
3384 }
3385 }
3386
3387 // If we're currently evaluating the initializer of this declaration, use that
3388 // in-flight value.
3389 if (Info.EvaluatingDecl == Base) {
3390 Result = Info.EvaluatingDeclValue;
3391 return CheckUninitReference(/*IsLocalVariable=*/false);
3392 }
3393
3394 // P2280R4 struck the restriction that variable of reference type lifetime
3395 // should begin within the evaluation of E
3396 // Used to be C++20 [expr.const]p5.12.2:
3397 // ... its lifetime began within the evaluation of E;
3398 if (isa<ParmVarDecl>(VD)) {
3399 if (AllowConstexprUnknown) {
3400 Result = nullptr;
3401 return true;
3402 }
3403
3404 // Assume parameters of a potential constant expression are usable in
3405 // constant expressions.
3406 if (!Info.checkingPotentialConstantExpression() ||
3407 !Info.CurrentCall->Callee ||
3408 !Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
3409 if (Info.getLangOpts().CPlusPlus11) {
3410 Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown)
3411 << VD;
3412 NoteLValueLocation(Info, Base);
3413 } else {
3414 Info.FFDiag(E);
3415 }
3416 }
3417 return false;
3418 }
3419
3420 if (E->isValueDependent())
3421 return false;
3422
3423 // Dig out the initializer, and use the declaration which it's attached to.
3424 // FIXME: We should eventually check whether the variable has a reachable
3425 // initializing declaration.
3426 const Expr *Init = VD->getAnyInitializer(VD);
3427 // P2280R4 struck the restriction that variable of reference type should have
3428 // a preceding initialization.
3429 // Used to be C++20 [expr.const]p5.12:
3430 // ... reference has a preceding initialization and either ...
3431 if (!Init && !AllowConstexprUnknown) {
3432 // Don't diagnose during potential constant expression checking; an
3433 // initializer might be added later.
3434 if (!Info.checkingPotentialConstantExpression()) {
3435 Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1)
3436 << VD;
3437 NoteLValueLocation(Info, Base);
3438 }
3439 return false;
3440 }
3441
3442 // P2280R4 struck the initialization requirement for variables of reference
3443 // type so we can no longer assume we have an Init.
3444 // Used to be C++20 [expr.const]p5.12:
3445 // ... reference has a preceding initialization and either ...
3446 if (Init && Init->isValueDependent()) {
3447 // The DeclRefExpr is not value-dependent, but the variable it refers to
3448 // has a value-dependent initializer. This should only happen in
3449 // constant-folding cases, where the variable is not actually of a suitable
3450 // type for use in a constant expression (otherwise the DeclRefExpr would
3451 // have been value-dependent too), so diagnose that.
3452 assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx));
3453 if (!Info.checkingPotentialConstantExpression()) {
3454 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
3455 ? diag::note_constexpr_ltor_non_constexpr
3456 : diag::note_constexpr_ltor_non_integral, 1)
3457 << VD << VD->getType();
3458 NoteLValueLocation(Info, Base);
3459 }
3460 return false;
3461 }
3462
3463 // Check that we can fold the initializer. In C++, we will have already done
3464 // this in the cases where it matters for conformance.
3465 // P2280R4 struck the initialization requirement for variables of reference
3466 // type so we can no longer assume we have an Init.
3467 // Used to be C++20 [expr.const]p5.12:
3468 // ... reference has a preceding initialization and either ...
3469 if (Init && !VD->evaluateValue() && !AllowConstexprUnknown) {
3470 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3471 NoteLValueLocation(Info, Base);
3472 return false;
3473 }
3474
3475 // Check that the variable is actually usable in constant expressions. For a
3476 // const integral variable or a reference, we might have a non-constant
3477 // initializer that we can nonetheless evaluate the initializer for. Such
3478 // variables are not usable in constant expressions. In C++98, the
3479 // initializer also syntactically needs to be an ICE.
3480 //
3481 // FIXME: We don't diagnose cases that aren't potentially usable in constant
3482 // expressions here; doing so would regress diagnostics for things like
3483 // reading from a volatile constexpr variable.
3484 if ((Info.getLangOpts().CPlusPlus && !VD->hasConstantInitialization() &&
3485 VD->mightBeUsableInConstantExpressions(Info.Ctx) &&
3486 !AllowConstexprUnknown) ||
3487 ((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) &&
3488 !Info.getLangOpts().CPlusPlus11 && !VD->hasICEInitializer(Info.Ctx))) {
3489 if (Init) {
3490 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3491 NoteLValueLocation(Info, Base);
3492 } else {
3493 Info.CCEDiag(E);
3494 }
3495 }
3496
3497 // Never use the initializer of a weak variable, not even for constant
3498 // folding. We can't be sure that this is the definition that will be used.
3499 if (VD->isWeak()) {
3500 Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD;
3501 NoteLValueLocation(Info, Base);
3502 return false;
3503 }
3504
3505 Result = VD->getEvaluatedValue();
3506
3507 if (!Result && !AllowConstexprUnknown)
3508 return false;
3509
3510 return CheckUninitReference(/*IsLocalVariable=*/false);
3511}
3512
3513/// Get the base index of the given base class within an APValue representing
3514/// the given derived class.
3515static unsigned getBaseIndex(const CXXRecordDecl *Derived,
3516 const CXXRecordDecl *Base) {
3517 Base = Base->getCanonicalDecl();
3518 unsigned Index = 0;
3520 E = Derived->bases_end(); I != E; ++I, ++Index) {
3521 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
3522 return Index;
3523 }
3524
3525 llvm_unreachable("base class missing from derived class's bases list");
3526}
3527
3528/// Extract the value of a character from a string literal.
3529static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
3530 uint64_t Index) {
3531 assert(!isa<SourceLocExpr>(Lit) &&
3532 "SourceLocExpr should have already been converted to a StringLiteral");
3533
3534 // FIXME: Support MakeStringConstant
3535 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
3536 std::string Str;
3537 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
3538 assert(Index <= Str.size() && "Index too large");
3539 return APSInt::getUnsigned(Str.c_str()[Index]);
3540 }
3541
3542 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
3543 Lit = PE->getFunctionName();
3544 const StringLiteral *S = cast<StringLiteral>(Lit);
3545 const ConstantArrayType *CAT =
3546 Info.Ctx.getAsConstantArrayType(S->getType());
3547 assert(CAT && "string literal isn't an array");
3548 QualType CharType = CAT->getElementType();
3549 assert(CharType->isIntegerType() && "unexpected character type");
3550 APSInt Value(Info.Ctx.getTypeSize(CharType),
3551 CharType->isUnsignedIntegerType());
3552 if (Index < S->getLength())
3553 Value = S->getCodeUnit(Index);
3554 return Value;
3555}
3556
3557// Expand a string literal into an array of characters.
3558//
3559// FIXME: This is inefficient; we should probably introduce something similar
3560// to the LLVM ConstantDataArray to make this cheaper.
3561static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
3562 APValue &Result,
3563 QualType AllocType = QualType()) {
3564 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
3565 AllocType.isNull() ? S->getType() : AllocType);
3566 assert(CAT && "string literal isn't an array");
3567 QualType CharType = CAT->getElementType();
3568 assert(CharType->isIntegerType() && "unexpected character type");
3569
3570 unsigned Elts = CAT->getZExtSize();
3572 std::min(S->getLength(), Elts), Elts);
3573 APSInt Value(Info.Ctx.getTypeSize(CharType),
3574 CharType->isUnsignedIntegerType());
3575 if (Result.hasArrayFiller())
3576 Result.getArrayFiller() = APValue(Value);
3577 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
3578 Value = S->getCodeUnit(I);
3579 Result.getArrayInitializedElt(I) = APValue(Value);
3580 }
3581}
3582
3583// Expand an array so that it has more than Index filled elements.
3584static void expandArray(APValue &Array, unsigned Index) {
3585 unsigned Size = Array.getArraySize();
3586 assert(Index < Size);
3587
3588 // Always at least double the number of elements for which we store a value.
3589 unsigned OldElts = Array.getArrayInitializedElts();
3590 unsigned NewElts = std::max(Index+1, OldElts * 2);
3591 NewElts = std::min(Size, std::max(NewElts, 8u));
3592
3593 // Copy the data across.
3594 APValue NewValue(APValue::UninitArray(), NewElts, Size);
3595 for (unsigned I = 0; I != OldElts; ++I)
3596 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
3597 for (unsigned I = OldElts; I != NewElts; ++I)
3598 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
3599 if (NewValue.hasArrayFiller())
3600 NewValue.getArrayFiller() = Array.getArrayFiller();
3601 Array.swap(NewValue);
3602}
3603
3604// Expand an indeterminate vector to materialize all elements.
3605static void expandVector(APValue &Vec, unsigned NumElements) {
3606 assert(Vec.isIndeterminate());
3608 Vec = APValue(Elts.data(), Elts.size());
3609}
3610
3611/// Determine whether a type would actually be read by an lvalue-to-rvalue
3612/// conversion. If it's of class type, we may assume that the copy operation
3613/// is trivial. Note that this is never true for a union type with fields
3614/// (because the copy always "reads" the active member) and always true for
3615/// a non-class type.
3616static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD);
3618 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3619 return !RD || isReadByLvalueToRvalueConversion(RD);
3620}
3622 // FIXME: A trivial copy of a union copies the object representation, even if
3623 // the union is empty.
3624 if (RD->isUnion())
3625 return !RD->field_empty();
3626 if (RD->isEmpty())
3627 return false;
3628
3629 for (auto *Field : RD->fields())
3630 if (!Field->isUnnamedBitField() &&
3631 isReadByLvalueToRvalueConversion(Field->getType()))
3632 return true;
3633
3634 for (auto &BaseSpec : RD->bases())
3635 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
3636 return true;
3637
3638 return false;
3639}
3640
3641/// Diagnose an attempt to read from any unreadable field within the specified
3642/// type, which might be a class type.
3643static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK,
3644 QualType T) {
3645 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3646 if (!RD)
3647 return false;
3648
3649 if (!RD->hasMutableFields())
3650 return false;
3651
3652 for (auto *Field : RD->fields()) {
3653 // If we're actually going to read this field in some way, then it can't
3654 // be mutable. If we're in a union, then assigning to a mutable field
3655 // (even an empty one) can change the active member, so that's not OK.
3656 // FIXME: Add core issue number for the union case.
3657 if (Field->isMutable() &&
3658 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
3659 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field;
3660 Info.Note(Field->getLocation(), diag::note_declared_at);
3661 return true;
3662 }
3663
3664 if (diagnoseMutableFields(Info, E, AK, Field->getType()))
3665 return true;
3666 }
3667
3668 for (auto &BaseSpec : RD->bases())
3669 if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType()))
3670 return true;
3671
3672 // All mutable fields were empty, and thus not actually read.
3673 return false;
3674}
3675
3676static bool lifetimeStartedInEvaluation(EvalInfo &Info,
3678 bool MutableSubobject = false) {
3679 // A temporary or transient heap allocation we created.
3680 if (Base.getCallIndex() || Base.is<DynamicAllocLValue>())
3681 return true;
3682
3683 switch (Info.IsEvaluatingDecl) {
3684 case EvalInfo::EvaluatingDeclKind::None:
3685 return false;
3686
3687 case EvalInfo::EvaluatingDeclKind::Ctor:
3688 // The variable whose initializer we're evaluating.
3689 if (Info.EvaluatingDecl == Base)
3690 return true;
3691
3692 // A temporary lifetime-extended by the variable whose initializer we're
3693 // evaluating.
3694 if (auto *BaseE = Base.dyn_cast<const Expr *>())
3695 if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
3696 return Info.EvaluatingDecl == BaseMTE->getExtendingDecl();
3697 return false;
3698
3699 case EvalInfo::EvaluatingDeclKind::Dtor:
3700 // C++2a [expr.const]p6:
3701 // [during constant destruction] the lifetime of a and its non-mutable
3702 // subobjects (but not its mutable subobjects) [are] considered to start
3703 // within e.
3704 if (MutableSubobject || Base != Info.EvaluatingDecl)
3705 return false;
3706 // FIXME: We can meaningfully extend this to cover non-const objects, but
3707 // we will need special handling: we should be able to access only
3708 // subobjects of such objects that are themselves declared const.
3709 QualType T = getType(Base);
3710 return T.isConstQualified() || T->isReferenceType();
3711 }
3712
3713 llvm_unreachable("unknown evaluating decl kind");
3714}
3715
3716static bool CheckArraySize(EvalInfo &Info, const ConstantArrayType *CAT,
3717 SourceLocation CallLoc = {}) {
3718 return Info.CheckArraySize(
3719 CAT->getSizeExpr() ? CAT->getSizeExpr()->getBeginLoc() : CallLoc,
3720 CAT->getNumAddressingBits(Info.Ctx), CAT->getZExtSize(),
3721 /*Diag=*/true);
3722}
3723
3724static bool handleScalarCast(EvalInfo &Info, const FPOptions FPO, const Expr *E,
3725 QualType SourceTy, QualType DestTy,
3726 APValue const &Original, APValue &Result) {
3727 // boolean must be checked before integer
3728 // since IsIntegerType() is true for bool
3729 if (SourceTy->isBooleanType()) {
3730 if (DestTy->isBooleanType()) {
3731 Result = Original;
3732 return true;
3733 }
3734 if (DestTy->isIntegerType() || DestTy->isRealFloatingType()) {
3735 bool BoolResult;
3736 if (!HandleConversionToBool(Original, BoolResult))
3737 return false;
3738 uint64_t IntResult = BoolResult;
3739 QualType IntType = DestTy->isIntegerType()
3740 ? DestTy
3741 : Info.Ctx.getIntTypeForBitwidth(64, false);
3742 Result = APValue(Info.Ctx.MakeIntValue(IntResult, IntType));
3743 }
3744 if (DestTy->isRealFloatingType()) {
3745 APValue Result2 = APValue(APFloat(0.0));
3746 if (!HandleIntToFloatCast(Info, E, FPO,
3747 Info.Ctx.getIntTypeForBitwidth(64, false),
3748 Result.getInt(), DestTy, Result2.getFloat()))
3749 return false;
3750 Result = std::move(Result2);
3751 }
3752 return true;
3753 }
3754 if (SourceTy->isIntegerType()) {
3755 if (DestTy->isRealFloatingType()) {
3756 Result = APValue(APFloat(0.0));
3757 return HandleIntToFloatCast(Info, E, FPO, SourceTy, Original.getInt(),
3758 DestTy, Result.getFloat());
3759 }
3760 if (DestTy->isBooleanType()) {
3761 bool BoolResult;
3762 if (!HandleConversionToBool(Original, BoolResult))
3763 return false;
3764 uint64_t IntResult = BoolResult;
3765 Result = APValue(Info.Ctx.MakeIntValue(IntResult, DestTy));
3766 return true;
3767 }
3768 if (DestTy->isIntegerType()) {
3769 Result = APValue(
3770 HandleIntToIntCast(Info, E, DestTy, SourceTy, Original.getInt()));
3771 return true;
3772 }
3773 } else if (SourceTy->isRealFloatingType()) {
3774 if (DestTy->isRealFloatingType()) {
3775 Result = Original;
3776 return HandleFloatToFloatCast(Info, E, SourceTy, DestTy,
3777 Result.getFloat());
3778 }
3779 if (DestTy->isBooleanType()) {
3780 bool BoolResult;
3781 if (!HandleConversionToBool(Original, BoolResult))
3782 return false;
3783 uint64_t IntResult = BoolResult;
3784 Result = APValue(Info.Ctx.MakeIntValue(IntResult, DestTy));
3785 return true;
3786 }
3787 if (DestTy->isIntegerType()) {
3788 Result = APValue(APSInt());
3789 return HandleFloatToIntCast(Info, E, SourceTy, Original.getFloat(),
3790 DestTy, Result.getInt());
3791 }
3792 }
3793
3794 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3795 return false;
3796}
3797
3798// do the heavy lifting for casting to aggregate types
3799// because we have to deal with bitfields specially
3800static bool constructAggregate(EvalInfo &Info, const FPOptions FPO,
3801 const Expr *E, APValue &Result,
3802 QualType ResultType,
3803 SmallVectorImpl<APValue> &Elements,
3804 SmallVectorImpl<QualType> &ElTypes) {
3805
3807 {&Result, ResultType, 0}};
3808
3809 unsigned ElI = 0;
3810 while (!WorkList.empty() && ElI < Elements.size()) {
3811 auto [Res, Type, BitWidth] = WorkList.pop_back_val();
3812
3813 if (Type->isRealFloatingType()) {
3814 if (!handleScalarCast(Info, FPO, E, ElTypes[ElI], Type, Elements[ElI],
3815 *Res))
3816 return false;
3817 ElI++;
3818 continue;
3819 }
3820 if (Type->isIntegerType()) {
3821 if (!handleScalarCast(Info, FPO, E, ElTypes[ElI], Type, Elements[ElI],
3822 *Res))
3823 return false;
3824 if (BitWidth > 0) {
3825 if (!Res->isInt())
3826 return false;
3827 APSInt &Int = Res->getInt();
3828 unsigned OldBitWidth = Int.getBitWidth();
3829 unsigned NewBitWidth = BitWidth;
3830 if (NewBitWidth < OldBitWidth)
3831 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
3832 }
3833 ElI++;
3834 continue;
3835 }
3836 if (Type->isVectorType()) {
3837 QualType ElTy = Type->castAs<VectorType>()->getElementType();
3838 unsigned NumEl = Type->castAs<VectorType>()->getNumElements();
3839 SmallVector<APValue> Vals(NumEl);
3840 for (unsigned I = 0; I < NumEl; ++I) {
3841 if (!handleScalarCast(Info, FPO, E, ElTypes[ElI], ElTy, Elements[ElI],
3842 Vals[I]))
3843 return false;
3844 ElI++;
3845 }
3846 *Res = APValue(Vals.data(), NumEl);
3847 continue;
3848 }
3849 if (Type->isConstantArrayType()) {
3850 QualType ElTy = cast<ConstantArrayType>(Info.Ctx.getAsArrayType(Type))
3851 ->getElementType();
3852 uint64_t Size =
3853 cast<ConstantArrayType>(Info.Ctx.getAsArrayType(Type))->getZExtSize();
3854 *Res = APValue(APValue::UninitArray(), Size, Size);
3855 for (int64_t I = Size - 1; I > -1; --I)
3856 WorkList.emplace_back(&Res->getArrayInitializedElt(I), ElTy, 0u);
3857 continue;
3858 }
3859 if (Type->isRecordType()) {
3860 const RecordDecl *RD = Type->getAsRecordDecl();
3861
3862 unsigned NumBases = 0;
3863 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
3864 NumBases = CXXRD->getNumBases();
3865
3866 *Res = APValue(APValue::UninitStruct(), NumBases, RD->getNumFields());
3867
3869 // we need to traverse backwards
3870 // Visit the base classes.
3871 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3872 if (CXXRD->getNumBases() > 0) {
3873 assert(CXXRD->getNumBases() == 1);
3874 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[0];
3875 ReverseList.emplace_back(&Res->getStructBase(0), BS.getType(), 0u);
3876 }
3877 }
3878
3879 // Visit the fields.
3880 for (FieldDecl *FD : RD->fields()) {
3881 unsigned FDBW = 0;
3882 if (FD->isUnnamedBitField())
3883 continue;
3884 if (FD->isBitField()) {
3885 FDBW = FD->getBitWidthValue();
3886 }
3887
3888 ReverseList.emplace_back(&Res->getStructField(FD->getFieldIndex()),
3889 FD->getType(), FDBW);
3890 }
3891
3892 std::reverse(ReverseList.begin(), ReverseList.end());
3893 llvm::append_range(WorkList, ReverseList);
3894 continue;
3895 }
3896 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3897 return false;
3898 }
3899 return true;
3900}
3901
3902static bool handleElementwiseCast(EvalInfo &Info, const Expr *E,
3903 const FPOptions FPO,
3904 SmallVectorImpl<APValue> &Elements,
3905 SmallVectorImpl<QualType> &SrcTypes,
3906 SmallVectorImpl<QualType> &DestTypes,
3907 SmallVectorImpl<APValue> &Results) {
3908
3909 assert((Elements.size() == SrcTypes.size()) &&
3910 (Elements.size() == DestTypes.size()));
3911
3912 for (unsigned I = 0, ESz = Elements.size(); I < ESz; ++I) {
3913 APValue Original = Elements[I];
3914 QualType SourceTy = SrcTypes[I];
3915 QualType DestTy = DestTypes[I];
3916
3917 if (!handleScalarCast(Info, FPO, E, SourceTy, DestTy, Original, Results[I]))
3918 return false;
3919 }
3920 return true;
3921}
3922
3923static unsigned elementwiseSize(EvalInfo &Info, QualType BaseTy) {
3924
3925 SmallVector<QualType> WorkList = {BaseTy};
3926
3927 unsigned Size = 0;
3928 while (!WorkList.empty()) {
3929 QualType Type = WorkList.pop_back_val();
3931 Type->isBooleanType()) {
3932 ++Size;
3933 continue;
3934 }
3935 if (Type->isVectorType()) {
3936 unsigned NumEl = Type->castAs<VectorType>()->getNumElements();
3937 Size += NumEl;
3938 continue;
3939 }
3940 if (Type->isConstantMatrixType()) {
3941 unsigned NumEl =
3942 Type->castAs<ConstantMatrixType>()->getNumElementsFlattened();
3943 Size += NumEl;
3944 continue;
3945 }
3946 if (Type->isConstantArrayType()) {
3947 QualType ElTy = cast<ConstantArrayType>(Info.Ctx.getAsArrayType(Type))
3948 ->getElementType();
3949 uint64_t ArrSize =
3950 cast<ConstantArrayType>(Info.Ctx.getAsArrayType(Type))->getZExtSize();
3951 for (uint64_t I = 0; I < ArrSize; ++I) {
3952 WorkList.push_back(ElTy);
3953 }
3954 continue;
3955 }
3956 if (Type->isRecordType()) {
3957 const RecordDecl *RD = Type->getAsRecordDecl();
3958
3959 // Visit the base classes.
3960 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3961 if (CXXRD->getNumBases() > 0) {
3962 assert(CXXRD->getNumBases() == 1);
3963 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[0];
3964 WorkList.push_back(BS.getType());
3965 }
3966 }
3967
3968 // visit the fields.
3969 for (FieldDecl *FD : RD->fields()) {
3970 if (FD->isUnnamedBitField())
3971 continue;
3972 WorkList.push_back(FD->getType());
3973 }
3974 continue;
3975 }
3976 }
3977 return Size;
3978}
3979
3980static bool hlslAggSplatHelper(EvalInfo &Info, const Expr *E, APValue &SrcVal,
3981 QualType &SrcTy) {
3982 SrcTy = E->getType();
3983
3984 if (!Evaluate(SrcVal, Info, E))
3985 return false;
3986
3987 assert((SrcVal.isFloat() || SrcVal.isInt() ||
3988 (SrcVal.isVector() && SrcVal.getVectorLength() == 1)) &&
3989 "Not a valid HLSLAggregateSplatCast.");
3990
3991 if (SrcVal.isVector()) {
3992 assert(SrcTy->isVectorType() && "Type mismatch.");
3993 SrcTy = SrcTy->castAs<VectorType>()->getElementType();
3994 SrcVal = SrcVal.getVectorElt(0);
3995 }
3996 if (SrcVal.isMatrix()) {
3997 assert(SrcTy->isConstantMatrixType() && "Type mismatch.");
3998 SrcTy = SrcTy->castAs<ConstantMatrixType>()->getElementType();
3999 SrcVal = SrcVal.getMatrixElt(0, 0);
4000 }
4001 return true;
4002}
4003
4004static bool flattenAPValue(EvalInfo &Info, const Expr *E, APValue Value,
4005 QualType BaseTy, SmallVectorImpl<APValue> &Elements,
4006 SmallVectorImpl<QualType> &Types, unsigned Size) {
4007
4008 SmallVector<std::pair<APValue, QualType>> WorkList = {{Value, BaseTy}};
4009 unsigned Populated = 0;
4010 while (!WorkList.empty() && Populated < Size) {
4011 auto [Work, Type] = WorkList.pop_back_val();
4012
4013 if (Work.isFloat() || Work.isInt()) {
4014 Elements.push_back(Work);
4015 Types.push_back(Type);
4016 Populated++;
4017 continue;
4018 }
4019 if (Work.isVector()) {
4020 assert(Type->isVectorType() && "Type mismatch.");
4021 QualType ElTy = Type->castAs<VectorType>()->getElementType();
4022 for (unsigned I = 0; I < Work.getVectorLength() && Populated < Size;
4023 I++) {
4024 Elements.push_back(Work.getVectorElt(I));
4025 Types.push_back(ElTy);
4026 Populated++;
4027 }
4028 continue;
4029 }
4030 if (Work.isMatrix()) {
4031 assert(Type->isConstantMatrixType() && "Type mismatch.");
4032 const auto *MT = Type->castAs<ConstantMatrixType>();
4033 QualType ElTy = MT->getElementType();
4034 // Matrix elements are flattened in row-major order.
4035 for (unsigned Row = 0; Row < Work.getMatrixNumRows() && Populated < Size;
4036 Row++) {
4037 for (unsigned Col = 0;
4038 Col < Work.getMatrixNumColumns() && Populated < Size; Col++) {
4039 Elements.push_back(Work.getMatrixElt(Row, Col));
4040 Types.push_back(ElTy);
4041 Populated++;
4042 }
4043 }
4044 continue;
4045 }
4046 if (Work.isArray()) {
4047 assert(Type->isConstantArrayType() && "Type mismatch.");
4048 QualType ElTy = cast<ConstantArrayType>(Info.Ctx.getAsArrayType(Type))
4049 ->getElementType();
4050 for (int64_t I = Work.getArraySize() - 1; I > -1; --I) {
4051 WorkList.emplace_back(Work.getArrayInitializedElt(I), ElTy);
4052 }
4053 continue;
4054 }
4055
4056 if (Work.isStruct()) {
4057 assert(Type->isRecordType() && "Type mismatch.");
4058
4059 const RecordDecl *RD = Type->getAsRecordDecl();
4060
4062 // Visit the fields.
4063 for (FieldDecl *FD : RD->fields()) {
4064 if (FD->isUnnamedBitField())
4065 continue;
4066 ReverseList.emplace_back(Work.getStructField(FD->getFieldIndex()),
4067 FD->getType());
4068 }
4069
4070 std::reverse(ReverseList.begin(), ReverseList.end());
4071 llvm::append_range(WorkList, ReverseList);
4072
4073 // Visit the base classes.
4074 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
4075 if (CXXRD->getNumBases() > 0) {
4076 assert(CXXRD->getNumBases() == 1);
4077 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[0];
4078 const APValue &Base = Work.getStructBase(0);
4079
4080 // Can happen in error cases.
4081 if (!Base.isStruct())
4082 return false;
4083
4084 WorkList.emplace_back(Base, BS.getType());
4085 }
4086 }
4087 continue;
4088 }
4089 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
4090 return false;
4091 }
4092 return true;
4093}
4094
4095namespace {
4096/// A handle to a complete object (an object that is not a subobject of
4097/// another object).
4098struct CompleteObject {
4099 /// The identity of the object.
4100 APValue::LValueBase Base;
4101 /// The value of the complete object.
4102 APValue *Value;
4103 /// The type of the complete object.
4104 QualType Type;
4105
4106 CompleteObject() : Value(nullptr) {}
4107 CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
4108 : Base(Base), Value(Value), Type(Type) {}
4109
4110 bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const {
4111 // If this isn't a "real" access (eg, if it's just accessing the type
4112 // info), allow it. We assume the type doesn't change dynamically for
4113 // subobjects of constexpr objects (even though we'd hit UB here if it
4114 // did). FIXME: Is this right?
4115 if (!isAnyAccess(AK))
4116 return true;
4117
4118 // In C++14 onwards, it is permitted to read a mutable member whose
4119 // lifetime began within the evaluation.
4120 // FIXME: Should we also allow this in C++11?
4121 if (!Info.getLangOpts().CPlusPlus14 &&
4122 AK != AccessKinds::AK_IsWithinLifetime)
4123 return false;
4124 return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);
4125 }
4126
4127 explicit operator bool() const { return !Type.isNull(); }
4128};
4129} // end anonymous namespace
4130
4131static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
4132 bool IsMutable = false) {
4133 // C++ [basic.type.qualifier]p1:
4134 // - A const object is an object of type const T or a non-mutable subobject
4135 // of a const object.
4136 if (ObjType.isConstQualified() && !IsMutable)
4137 SubobjType.addConst();
4138 // - A volatile object is an object of type const T or a subobject of a
4139 // volatile object.
4140 if (ObjType.isVolatileQualified())
4141 SubobjType.addVolatile();
4142 return SubobjType;
4143}
4144
4145/// Find the designated sub-object of an rvalue.
4146template <typename SubobjectHandler>
4147static typename SubobjectHandler::result_type
4148findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
4149 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
4150 if (Sub.Invalid)
4151 // A diagnostic will have already been produced.
4152 return handler.failed();
4153 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
4154 if (Info.getLangOpts().CPlusPlus11)
4155 Info.FFDiag(E, Sub.isOnePastTheEnd()
4156 ? diag::note_constexpr_access_past_end
4157 : diag::note_constexpr_access_unsized_array)
4158 << handler.AccessKind;
4159 else
4160 Info.FFDiag(E);
4161 return handler.failed();
4162 }
4163
4164 APValue *O = Obj.Value;
4165 QualType ObjType = Obj.Type;
4166 const FieldDecl *LastField = nullptr;
4167 const FieldDecl *VolatileField = nullptr;
4168
4169 // Walk the designator's path to find the subobject.
4170 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
4171 // Reading an indeterminate value is undefined, but assigning over one is OK.
4172 if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) ||
4173 (O->isIndeterminate() &&
4174 !isValidIndeterminateAccess(handler.AccessKind))) {
4175 // Object has ended lifetime.
4176 // If I is non-zero, some subobject (member or array element) of a
4177 // complete object has ended its lifetime, so this is valid for
4178 // IsWithinLifetime, resulting in false.
4179 if (I != 0 && handler.AccessKind == AK_IsWithinLifetime)
4180 return false;
4181 if (!Info.checkingPotentialConstantExpression()) {
4182 Info.FFDiag(E, diag::note_constexpr_access_uninit)
4183 << handler.AccessKind << O->isIndeterminate()
4184 << E->getSourceRange();
4185 NoteLValueLocation(Info, Obj.Base);
4186 }
4187 return handler.failed();
4188 }
4189
4190 // C++ [class.ctor]p5, C++ [class.dtor]p5:
4191 // const and volatile semantics are not applied on an object under
4192 // {con,de}struction.
4193 if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
4194 ObjType->isRecordType() &&
4195 Info.isEvaluatingCtorDtor(
4196 Obj.Base, ArrayRef(Sub.Entries.begin(), Sub.Entries.begin() + I)) !=
4197 ConstructionPhase::None) {
4198 ObjType = Info.Ctx.getCanonicalType(ObjType);
4199 ObjType.removeLocalConst();
4200 ObjType.removeLocalVolatile();
4201 }
4202
4203 // If this is our last pass, check that the final object type is OK.
4204 if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
4205 // Accesses to volatile objects are prohibited.
4206 if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
4207 if (Info.getLangOpts().CPlusPlus) {
4208 int DiagKind;
4209 SourceLocation Loc;
4210 const NamedDecl *Decl = nullptr;
4211 if (VolatileField) {
4212 DiagKind = 2;
4213 Loc = VolatileField->getLocation();
4214 Decl = VolatileField;
4215 } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
4216 DiagKind = 1;
4217 Loc = VD->getLocation();
4218 Decl = VD;
4219 } else {
4220 DiagKind = 0;
4221 if (auto *E = Obj.Base.dyn_cast<const Expr *>())
4222 Loc = E->getExprLoc();
4223 }
4224 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
4225 << handler.AccessKind << DiagKind << Decl;
4226 Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
4227 } else {
4228 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
4229 }
4230 return handler.failed();
4231 }
4232
4233 // If we are reading an object of class type, there may still be more
4234 // things we need to check: if there are any mutable subobjects, we
4235 // cannot perform this read. (This only happens when performing a trivial
4236 // copy or assignment.)
4237 if (ObjType->isRecordType() &&
4238 !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
4239 diagnoseMutableFields(Info, E, handler.AccessKind, ObjType))
4240 return handler.failed();
4241 }
4242
4243 if (I == N) {
4244 if (!handler.found(*O, ObjType, Obj.Base))
4245 return false;
4246
4247 // If we modified a bit-field, truncate it to the right width.
4248 if (isModification(handler.AccessKind) &&
4249 LastField && LastField->isBitField() &&
4250 !truncateBitfieldValue(Info, E, *O, LastField))
4251 return false;
4252
4253 return true;
4254 }
4255
4256 LastField = nullptr;
4257 if (ObjType->isArrayType()) {
4258 // Next subobject is an array element.
4259 const ArrayType *AT = Info.Ctx.getAsArrayType(ObjType);
4261 "vla in literal type?");
4262 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
4263 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT);
4264 CAT && CAT->getSize().ule(Index)) {
4265 // Note, it should not be possible to form a pointer with a valid
4266 // designator which points more than one past the end of the array.
4267 if (Info.getLangOpts().CPlusPlus11)
4268 Info.FFDiag(E, diag::note_constexpr_access_past_end)
4269 << handler.AccessKind;
4270 else
4271 Info.FFDiag(E);
4272 return handler.failed();
4273 }
4274
4275 ObjType = AT->getElementType();
4276
4277 if (O->getArrayInitializedElts() > Index)
4278 O = &O->getArrayInitializedElt(Index);
4279 else if (!isRead(handler.AccessKind)) {
4280 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT);
4281 CAT && !CheckArraySize(Info, CAT, E->getExprLoc()))
4282 return handler.failed();
4283
4284 expandArray(*O, Index);
4285 O = &O->getArrayInitializedElt(Index);
4286 } else
4287 O = &O->getArrayFiller();
4288 } else if (ObjType->isAnyComplexType()) {
4289 // Next subobject is a complex number.
4290 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
4291 if (Index > 1) {
4292 if (Info.getLangOpts().CPlusPlus11)
4293 Info.FFDiag(E, diag::note_constexpr_access_past_end)
4294 << handler.AccessKind;
4295 else
4296 Info.FFDiag(E);
4297 return handler.failed();
4298 }
4299
4300 ObjType = getSubobjectType(
4301 ObjType, ObjType->castAs<ComplexType>()->getElementType());
4302
4303 assert(I == N - 1 && "extracting subobject of scalar?");
4304 if (O->isComplexInt()) {
4305 return handler.found(Index ? O->getComplexIntImag()
4306 : O->getComplexIntReal(), ObjType);
4307 } else {
4308 assert(O->isComplexFloat());
4309 return handler.found(Index ? O->getComplexFloatImag()
4310 : O->getComplexFloatReal(), ObjType);
4311 }
4312 } else if (const auto *VT = ObjType->getAs<VectorType>()) {
4313 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
4314 unsigned NumElements = VT->getNumElements();
4315 if (Index == NumElements) {
4316 if (Info.getLangOpts().CPlusPlus11)
4317 Info.FFDiag(E, diag::note_constexpr_access_past_end)
4318 << handler.AccessKind;
4319 else
4320 Info.FFDiag(E);
4321 return handler.failed();
4322 }
4323
4324 if (Index > NumElements) {
4325 Info.CCEDiag(E, diag::note_constexpr_array_index)
4326 << Index << /*array*/ 0 << NumElements;
4327 return handler.failed();
4328 }
4329
4330 ObjType = VT->getElementType();
4331 assert(I == N - 1 && "extracting subobject of scalar?");
4332
4333 if (O->isIndeterminate()) {
4334 if (isRead(handler.AccessKind)) {
4335 Info.FFDiag(E);
4336 return handler.failed();
4337 }
4338 expandVector(*O, NumElements);
4339 }
4340 assert(O->isVector() && "unexpected object during vector element access");
4341 return handler.found(O->getVectorElt(Index), ObjType, Obj.Base);
4342 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
4343 if (Field->isMutable() &&
4344 !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) {
4345 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
4346 << handler.AccessKind << Field;
4347 Info.Note(Field->getLocation(), diag::note_declared_at);
4348 return handler.failed();
4349 }
4350
4351 // Next subobject is a class, struct or union field.
4352 RecordDecl *RD = ObjType->castAsCanonical<RecordType>()->getDecl();
4353 if (RD->isUnion()) {
4354 const FieldDecl *UnionField = O->getUnionField();
4355 if (!UnionField ||
4356 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
4357 if (I == N - 1 && handler.AccessKind == AK_Construct) {
4358 // Placement new onto an inactive union member makes it active.
4359 O->setUnion(Field, APValue());
4360 } else {
4361 // Pointer to/into inactive union member: Not within lifetime
4362 if (handler.AccessKind == AK_IsWithinLifetime)
4363 return false;
4364 // FIXME: If O->getUnionValue() is absent, report that there's no
4365 // active union member rather than reporting the prior active union
4366 // member. We'll need to fix nullptr_t to not use APValue() as its
4367 // representation first.
4368 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
4369 << handler.AccessKind << Field << !UnionField << UnionField;
4370 return handler.failed();
4371 }
4372 }
4373 O = &O->getUnionValue();
4374 } else
4375 O = &O->getStructField(Field->getFieldIndex());
4376
4377 ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
4378 LastField = Field;
4379 if (Field->getType().isVolatileQualified())
4380 VolatileField = Field;
4381 } else {
4382 // Next subobject is a base class.
4383 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
4384 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
4385 O = &O->getStructBase(getBaseIndex(Derived, Base));
4386
4387 ObjType = getSubobjectType(ObjType, Info.Ctx.getCanonicalTagType(Base));
4388 }
4389 }
4390}
4391
4392namespace {
4393struct ExtractSubobjectHandler {
4394 EvalInfo &Info;
4395 const Expr *E;
4396 APValue &Result;
4397 const AccessKinds AccessKind;
4398
4399 typedef bool result_type;
4400 bool failed() { return false; }
4401 bool found(APValue &Subobj, QualType SubobjType, APValue::LValueBase Base) {
4402 Result = Subobj;
4403 if (AccessKind == AK_ReadObjectRepresentation)
4404 return true;
4405 return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
4406 }
4407 bool found(APSInt &Value, QualType SubobjType) {
4408 Result = APValue(Value);
4409 return true;
4410 }
4411 bool found(APFloat &Value, QualType SubobjType) {
4412 Result = APValue(Value);
4413 return true;
4414 }
4415};
4416} // end anonymous namespace
4417
4418/// Extract the designated sub-object of an rvalue.
4419static bool extractSubobject(EvalInfo &Info, const Expr *E,
4420 const CompleteObject &Obj,
4421 const SubobjectDesignator &Sub, APValue &Result,
4422 AccessKinds AK = AK_Read) {
4423 assert(AK == AK_Read || AK == AK_ReadObjectRepresentation);
4424 ExtractSubobjectHandler Handler = {Info, E, Result, AK};
4425 return findSubobject(Info, E, Obj, Sub, Handler);
4426}
4427
4428namespace {
4429struct ModifySubobjectHandler {
4430 EvalInfo &Info;
4431 APValue &NewVal;
4432 const Expr *E;
4433
4434 typedef bool result_type;
4435 static const AccessKinds AccessKind = AK_Assign;
4436
4437 bool checkConst(QualType QT) {
4438 // Assigning to a const object has undefined behavior.
4439 if (QT.isConstQualified()) {
4440 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4441 return false;
4442 }
4443 return true;
4444 }
4445
4446 bool failed() { return false; }
4447 bool found(APValue &Subobj, QualType SubobjType, APValue::LValueBase Base) {
4448 if (!checkConst(SubobjType))
4449 return false;
4450 // We've been given ownership of NewVal, so just swap it in.
4451 Subobj.swap(NewVal);
4452 return true;
4453 }
4454 bool found(APSInt &Value, QualType SubobjType) {
4455 if (!checkConst(SubobjType))
4456 return false;
4457 if (!NewVal.isInt()) {
4458 // Maybe trying to write a cast pointer value into a complex?
4459 Info.FFDiag(E);
4460 return false;
4461 }
4462 Value = NewVal.getInt();
4463 return true;
4464 }
4465 bool found(APFloat &Value, QualType SubobjType) {
4466 if (!checkConst(SubobjType))
4467 return false;
4468 Value = NewVal.getFloat();
4469 return true;
4470 }
4471};
4472} // end anonymous namespace
4473
4474const AccessKinds ModifySubobjectHandler::AccessKind;
4475
4476/// Update the designated sub-object of an rvalue to the given value.
4477static bool modifySubobject(EvalInfo &Info, const Expr *E,
4478 const CompleteObject &Obj,
4479 const SubobjectDesignator &Sub,
4480 APValue &NewVal) {
4481 ModifySubobjectHandler Handler = { Info, NewVal, E };
4482 return findSubobject(Info, E, Obj, Sub, Handler);
4483}
4484
4485/// Find the position where two subobject designators diverge, or equivalently
4486/// the length of the common initial subsequence.
4487static unsigned FindDesignatorMismatch(QualType ObjType,
4488 const SubobjectDesignator &A,
4489 const SubobjectDesignator &B,
4490 bool &WasArrayIndex) {
4491 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
4492 for (/**/; I != N; ++I) {
4493 if (!ObjType.isNull() &&
4494 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
4495 // Next subobject is an array element.
4496 if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
4497 WasArrayIndex = true;
4498 return I;
4499 }
4500 if (ObjType->isAnyComplexType())
4501 ObjType = ObjType->castAs<ComplexType>()->getElementType();
4502 else
4503 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
4504 } else {
4505 if (A.Entries[I].getAsBaseOrMember() !=
4506 B.Entries[I].getAsBaseOrMember()) {
4507 WasArrayIndex = false;
4508 return I;
4509 }
4510 if (const FieldDecl *FD = getAsField(A.Entries[I]))
4511 // Next subobject is a field.
4512 ObjType = FD->getType();
4513 else
4514 // Next subobject is a base class.
4515 ObjType = QualType();
4516 }
4517 }
4518 WasArrayIndex = false;
4519 return I;
4520}
4521
4522/// Determine whether the given subobject designators refer to elements of the
4523/// same array object.
4525 const SubobjectDesignator &A,
4526 const SubobjectDesignator &B) {
4527 if (A.Entries.size() != B.Entries.size())
4528 return false;
4529
4530 bool IsArray = A.MostDerivedIsArrayElement;
4531 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
4532 // A is a subobject of the array element.
4533 return false;
4534
4535 // If A (and B) designates an array element, the last entry will be the array
4536 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
4537 // of length 1' case, and the entire path must match.
4538 bool WasArrayIndex;
4539 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
4540 return CommonLength >= A.Entries.size() - IsArray;
4541}
4542
4543/// Find the complete object to which an LValue refers.
4544static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
4545 AccessKinds AK, const LValue &LVal,
4546 QualType LValType) {
4547 if (LVal.InvalidBase) {
4548 Info.FFDiag(E);
4549 return CompleteObject();
4550 }
4551
4552 if (!LVal.Base) {
4554 Info.FFDiag(E, diag::note_constexpr_dereferencing_null);
4555 else
4556 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
4557 return CompleteObject();
4558 }
4559
4560 CallStackFrame *Frame = nullptr;
4561 unsigned Depth = 0;
4562 if (LVal.getLValueCallIndex()) {
4563 std::tie(Frame, Depth) =
4564 Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
4565 if (!Frame) {
4566 Info.FFDiag(E, diag::note_constexpr_access_uninit, 1)
4567 << AK << /*Indeterminate=*/false << E->getSourceRange();
4568 NoteLValueLocation(Info, LVal.Base);
4569 return CompleteObject();
4570 }
4571 }
4572
4573 bool IsAccess = isAnyAccess(AK);
4574
4575 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
4576 // is not a constant expression (even if the object is non-volatile). We also
4577 // apply this rule to C++98, in order to conform to the expected 'volatile'
4578 // semantics.
4579 if (isFormalAccess(AK) && LValType.isVolatileQualified()) {
4580 if (Info.getLangOpts().CPlusPlus)
4581 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
4582 << AK << LValType;
4583 else
4584 Info.FFDiag(E);
4585 return CompleteObject();
4586 }
4587
4588 // Compute value storage location and type of base object.
4589 APValue *BaseVal = nullptr;
4590 QualType BaseType = getType(LVal.Base);
4591
4592 if (Info.getLangOpts().CPlusPlus14 && LVal.Base == Info.EvaluatingDecl &&
4593 lifetimeStartedInEvaluation(Info, LVal.Base)) {
4594 // This is the object whose initializer we're evaluating, so its lifetime
4595 // started in the current evaluation.
4596 BaseVal = Info.EvaluatingDeclValue;
4597 } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) {
4598 // Allow reading from a GUID declaration.
4599 if (auto *GD = dyn_cast<MSGuidDecl>(D)) {
4600 if (isModification(AK)) {
4601 // All the remaining cases do not permit modification of the object.
4602 Info.FFDiag(E, diag::note_constexpr_modify_global);
4603 return CompleteObject();
4604 }
4605 APValue &V = GD->getAsAPValue();
4606 if (V.isAbsent()) {
4607 Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
4608 << GD->getType();
4609 return CompleteObject();
4610 }
4611 return CompleteObject(LVal.Base, &V, GD->getType());
4612 }
4613
4614 // Allow reading the APValue from an UnnamedGlobalConstantDecl.
4615 if (auto *GCD = dyn_cast<UnnamedGlobalConstantDecl>(D)) {
4616 if (isModification(AK)) {
4617 Info.FFDiag(E, diag::note_constexpr_modify_global);
4618 return CompleteObject();
4619 }
4620 return CompleteObject(LVal.Base, const_cast<APValue *>(&GCD->getValue()),
4621 GCD->getType());
4622 }
4623
4624 // Allow reading from template parameter objects.
4625 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) {
4626 if (isModification(AK)) {
4627 Info.FFDiag(E, diag::note_constexpr_modify_global);
4628 return CompleteObject();
4629 }
4630 return CompleteObject(LVal.Base, const_cast<APValue *>(&TPO->getValue()),
4631 TPO->getType());
4632 }
4633
4634 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
4635 // In C++11, constexpr, non-volatile variables initialized with constant
4636 // expressions are constant expressions too. Inside constexpr functions,
4637 // parameters are constant expressions even if they're non-const.
4638 // In C++1y, objects local to a constant expression (those with a Frame) are
4639 // both readable and writable inside constant expressions.
4640 // In C, such things can also be folded, although they are not ICEs.
4641 const VarDecl *VD = dyn_cast<VarDecl>(D);
4642 if (VD) {
4643 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
4644 VD = VDef;
4645 }
4646 if (!VD || VD->isInvalidDecl()) {
4647 Info.FFDiag(E);
4648 return CompleteObject();
4649 }
4650
4651 bool IsConstant = BaseType.isConstant(Info.Ctx);
4652 bool ConstexprVar = false;
4653 if (const auto *VD = dyn_cast_if_present<VarDecl>(
4654 Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()))
4655 ConstexprVar = VD->isConstexpr();
4656
4657 // Unless we're looking at a local variable or argument in a constexpr call,
4658 // the variable we're reading must be const (unless we are binding to a
4659 // reference).
4660 if (AK != clang::AK_Dereference && !Frame) {
4661 if (IsAccess && isa<ParmVarDecl>(VD)) {
4662 // Access of a parameter that's not associated with a frame isn't going
4663 // to work out, but we can leave it to evaluateVarDeclInit to provide a
4664 // suitable diagnostic.
4665 } else if (Info.getLangOpts().CPlusPlus14 &&
4666 lifetimeStartedInEvaluation(Info, LVal.Base)) {
4667 // OK, we can read and modify an object if we're in the process of
4668 // evaluating its initializer, because its lifetime began in this
4669 // evaluation.
4670 } else if (isModification(AK)) {
4671 // All the remaining cases do not permit modification of the object.
4672 Info.FFDiag(E, diag::note_constexpr_modify_global);
4673 return CompleteObject();
4674 } else if (VD->isConstexpr()) {
4675 // OK, we can read this variable.
4676 } else if (Info.getLangOpts().C23 && ConstexprVar) {
4677 Info.FFDiag(E);
4678 return CompleteObject();
4679 } else if (BaseType->isIntegralOrEnumerationType()) {
4680 if (!IsConstant) {
4681 if (!IsAccess)
4682 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4683 if (Info.getLangOpts().CPlusPlus) {
4684 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
4685 Info.Note(VD->getLocation(), diag::note_declared_at);
4686 } else {
4687 Info.FFDiag(E);
4688 }
4689 return CompleteObject();
4690 }
4691 } else if (!IsAccess) {
4692 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4693 } else if ((IsConstant || BaseType->isReferenceType()) &&
4694 Info.checkingPotentialConstantExpression() &&
4695 BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) {
4696 // This variable might end up being constexpr. Don't diagnose it yet.
4697 } else if (IsConstant) {
4698 // Keep evaluating to see what we can do. In particular, we support
4699 // folding of const floating-point types, in order to make static const
4700 // data members of such types (supported as an extension) more useful.
4701 if (Info.getLangOpts().CPlusPlus) {
4702 Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11
4703 ? diag::note_constexpr_ltor_non_constexpr
4704 : diag::note_constexpr_ltor_non_integral, 1)
4705 << VD << BaseType;
4706 Info.Note(VD->getLocation(), diag::note_declared_at);
4707 } else {
4708 Info.CCEDiag(E);
4709 }
4710 } else {
4711 // Never allow reading a non-const value.
4712 if (Info.getLangOpts().CPlusPlus) {
4713 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
4714 ? diag::note_constexpr_ltor_non_constexpr
4715 : diag::note_constexpr_ltor_non_integral, 1)
4716 << VD << BaseType;
4717 Info.Note(VD->getLocation(), diag::note_declared_at);
4718 } else {
4719 Info.FFDiag(E);
4720 }
4721 return CompleteObject();
4722 }
4723 }
4724
4725 // When binding to a reference, the variable does not need to be constexpr
4726 // or have constant initalization.
4727 if (AK != clang::AK_Dereference &&
4728 !evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(),
4729 BaseVal))
4730 return CompleteObject();
4731 // If evaluateVarDeclInit sees a constexpr-unknown variable, it returns
4732 // a null BaseVal. Any constexpr-unknown variable seen here is an error:
4733 // we can't access a constexpr-unknown object.
4734 if (AK != clang::AK_Dereference && !BaseVal) {
4735 if (!Info.checkingPotentialConstantExpression()) {
4736 Info.FFDiag(E, diag::note_constexpr_access_unknown_variable, 1)
4737 << AK << VD;
4738 Info.Note(VD->getLocation(), diag::note_declared_at);
4739 }
4740 return CompleteObject();
4741 }
4742 } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) {
4743 std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
4744 if (!Alloc) {
4745 Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK;
4746 return CompleteObject();
4747 }
4748 return CompleteObject(LVal.Base, &(*Alloc)->Value,
4749 LVal.Base.getDynamicAllocType());
4750 }
4751 // When binding to a reference, the variable does not need to be
4752 // within its lifetime.
4753 else if (AK != clang::AK_Dereference) {
4754 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4755
4756 if (!Frame) {
4757 if (const MaterializeTemporaryExpr *MTE =
4758 dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
4759 assert(MTE->getStorageDuration() == SD_Static &&
4760 "should have a frame for a non-global materialized temporary");
4761
4762 // C++20 [expr.const]p4: [DR2126]
4763 // An object or reference is usable in constant expressions if it is
4764 // - a temporary object of non-volatile const-qualified literal type
4765 // whose lifetime is extended to that of a variable that is usable
4766 // in constant expressions
4767 //
4768 // C++20 [expr.const]p5:
4769 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
4770 // - a non-volatile glvalue that refers to an object that is usable
4771 // in constant expressions, or
4772 // - a non-volatile glvalue of literal type that refers to a
4773 // non-volatile object whose lifetime began within the evaluation
4774 // of E;
4775 //
4776 // C++11 misses the 'began within the evaluation of e' check and
4777 // instead allows all temporaries, including things like:
4778 // int &&r = 1;
4779 // int x = ++r;
4780 // constexpr int k = r;
4781 // Therefore we use the C++14-onwards rules in C++11 too.
4782 //
4783 // Note that temporaries whose lifetimes began while evaluating a
4784 // variable's constructor are not usable while evaluating the
4785 // corresponding destructor, not even if they're of const-qualified
4786 // types.
4787 if (!MTE->isUsableInConstantExpressions(Info.Ctx) &&
4788 !lifetimeStartedInEvaluation(Info, LVal.Base)) {
4789 if (!IsAccess)
4790 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4791 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
4792 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
4793 return CompleteObject();
4794 }
4795
4796 BaseVal = MTE->getOrCreateValue(false);
4797 assert(BaseVal && "got reference to unevaluated temporary");
4798 } else if (const CompoundLiteralExpr *CLE =
4799 dyn_cast_or_null<CompoundLiteralExpr>(Base)) {
4800 // According to GCC info page:
4801 //
4802 // 6.28 Compound Literals
4803 //
4804 // As an optimization, G++ sometimes gives array compound literals
4805 // longer lifetimes: when the array either appears outside a function or
4806 // has a const-qualified type. If foo and its initializer had elements
4807 // of type char *const rather than char *, or if foo were a global
4808 // variable, the array would have static storage duration. But it is
4809 // probably safest just to avoid the use of array compound literals in
4810 // C++ code.
4811 //
4812 // Obey that rule by checking constness for converted array types.
4813 if (QualType CLETy = CLE->getType(); CLETy->isArrayType() &&
4814 !LValType->isArrayType() &&
4815 !CLETy.isConstant(Info.Ctx)) {
4816 Info.FFDiag(E);
4817 Info.Note(CLE->getExprLoc(), diag::note_declared_at);
4818 return CompleteObject();
4819 }
4820
4821 BaseVal = &CLE->getStaticValue();
4822 } else {
4823 if (!IsAccess)
4824 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4825 APValue Val;
4826 LVal.moveInto(Val);
4827 Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
4828 << AK
4829 << Val.getAsString(Info.Ctx,
4830 Info.Ctx.getLValueReferenceType(LValType));
4831 NoteLValueLocation(Info, LVal.Base);
4832 return CompleteObject();
4833 }
4834 } else if (AK != clang::AK_Dereference) {
4835 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
4836 assert(BaseVal && "missing value for temporary");
4837 }
4838 }
4839
4840 // In C++14, we can't safely access any mutable state when we might be
4841 // evaluating after an unmodeled side effect. Parameters are modeled as state
4842 // in the caller, but aren't visible once the call returns, so they can be
4843 // modified in a speculatively-evaluated call.
4844 //
4845 // FIXME: Not all local state is mutable. Allow local constant subobjects
4846 // to be read here (but take care with 'mutable' fields).
4847 unsigned VisibleDepth = Depth;
4848 if (llvm::isa_and_nonnull<ParmVarDecl>(
4849 LVal.Base.dyn_cast<const ValueDecl *>()))
4850 ++VisibleDepth;
4851 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
4852 Info.EvalStatus.HasSideEffects) ||
4853 (isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth))
4854 return CompleteObject();
4855
4856 return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
4857}
4858
4859/// Perform an lvalue-to-rvalue conversion on the given glvalue. This
4860/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
4861/// glvalue referred to by an entity of reference type.
4862///
4863/// \param Info - Information about the ongoing evaluation.
4864/// \param Conv - The expression for which we are performing the conversion.
4865/// Used for diagnostics.
4866/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
4867/// case of a non-class type).
4868/// \param LVal - The glvalue on which we are attempting to perform this action.
4869/// \param RVal - The produced value will be placed here.
4870/// \param WantObjectRepresentation - If true, we're looking for the object
4871/// representation rather than the value, and in particular,
4872/// there is no requirement that the result be fully initialized.
4873static bool
4875 const LValue &LVal, APValue &RVal,
4876 bool WantObjectRepresentation = false) {
4877 if (LVal.Designator.Invalid)
4878 return false;
4879
4880 // Check for special cases where there is no existing APValue to look at.
4881 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4882
4883 AccessKinds AK =
4884 WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;
4885
4886 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
4888 // Special-case character extraction so we don't have to construct an
4889 // APValue for the whole string.
4890 assert(LVal.Designator.Entries.size() <= 1 &&
4891 "Can only read characters from string literals");
4892 if (LVal.Designator.Entries.empty()) {
4893 // Fail for now for LValue to RValue conversion of an array.
4894 // (This shouldn't show up in C/C++, but it could be triggered by a
4895 // weird EvaluateAsRValue call from a tool.)
4896 Info.FFDiag(Conv);
4897 return false;
4898 }
4899 if (LVal.Designator.isOnePastTheEnd()) {
4900 if (Info.getLangOpts().CPlusPlus11)
4901 Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
4902 else
4903 Info.FFDiag(Conv);
4904 return false;
4905 }
4906 uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
4907 RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
4908 return true;
4909 }
4910 }
4911
4912 CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
4913 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
4914}
4915
4916static bool hlslElementwiseCastHelper(EvalInfo &Info, const Expr *E,
4917 QualType DestTy,
4918 SmallVectorImpl<APValue> &SrcVals,
4919 SmallVectorImpl<QualType> &SrcTypes) {
4920 APValue Val;
4921 if (!Evaluate(Val, Info, E))
4922 return false;
4923
4924 // must be dealing with a record
4925 if (Val.isLValue()) {
4926 LValue LVal;
4927 LVal.setFrom(Info.Ctx, Val);
4928 if (!handleLValueToRValueConversion(Info, E, E->getType(), LVal, Val))
4929 return false;
4930 }
4931
4932 unsigned NEls = elementwiseSize(Info, DestTy);
4933 // flatten the source
4934 if (!flattenAPValue(Info, E, Val, E->getType(), SrcVals, SrcTypes, NEls))
4935 return false;
4936
4937 return true;
4938}
4939
4940/// Perform an assignment of Val to LVal. Takes ownership of Val.
4941static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
4942 QualType LValType, APValue &Val) {
4943 if (LVal.Designator.Invalid)
4944 return false;
4945
4946 if (!Info.getLangOpts().CPlusPlus14) {
4947 Info.FFDiag(E);
4948 return false;
4949 }
4950
4951 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4952 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
4953}
4954
4955namespace {
4956struct CompoundAssignSubobjectHandler {
4957 EvalInfo &Info;
4958 const CompoundAssignOperator *E;
4959 QualType PromotedLHSType;
4961 const APValue &RHS;
4962
4963 static const AccessKinds AccessKind = AK_Assign;
4964
4965 typedef bool result_type;
4966
4967 bool checkConst(QualType QT) {
4968 // Assigning to a const object has undefined behavior.
4969 if (QT.isConstQualified()) {
4970 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4971 return false;
4972 }
4973 return true;
4974 }
4975
4976 bool failed() { return false; }
4977 bool found(APValue &Subobj, QualType SubobjType, APValue::LValueBase Base) {
4978 switch (Subobj.getKind()) {
4979 case APValue::Int:
4980 return found(Subobj.getInt(), SubobjType);
4981 case APValue::Float:
4982 return found(Subobj.getFloat(), SubobjType);
4985 // FIXME: Implement complex compound assignment.
4986 Info.FFDiag(E);
4987 return false;
4988 case APValue::LValue:
4989 return foundPointer(Subobj, SubobjType);
4990 case APValue::Vector:
4991 return foundVector(Subobj, SubobjType);
4993 Info.FFDiag(E, diag::note_constexpr_access_uninit)
4994 << /*read of=*/0 << /*uninitialized object=*/1
4995 << E->getLHS()->getSourceRange();
4996 NoteLValueLocation(Info, Base);
4997 return false;
4998 default:
4999 // FIXME: can this happen?
5000 Info.FFDiag(E);
5001 return false;
5002 }
5003 }
5004
5005 bool foundVector(APValue &Value, QualType SubobjType) {
5006 if (!checkConst(SubobjType))
5007 return false;
5008
5009 if (!SubobjType->isVectorType()) {
5010 Info.FFDiag(E);
5011 return false;
5012 }
5013 return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS);
5014 }
5015
5016 bool found(APSInt &Value, QualType SubobjType) {
5017 if (!checkConst(SubobjType))
5018 return false;
5019
5020 if (!SubobjType->isIntegerType()) {
5021 // We don't support compound assignment on integer-cast-to-pointer
5022 // values.
5023 Info.FFDiag(E);
5024 return false;
5025 }
5026
5027 if (RHS.isInt()) {
5028 APSInt LHS =
5029 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
5030 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
5031 return false;
5032 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
5033 return true;
5034 } else if (RHS.isFloat()) {
5035 const FPOptions FPO = E->getFPFeaturesInEffect(
5036 Info.Ctx.getLangOpts());
5037 APFloat FValue(0.0);
5038 return HandleIntToFloatCast(Info, E, FPO, SubobjType, Value,
5039 PromotedLHSType, FValue) &&
5040 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
5041 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
5042 Value);
5043 }
5044
5045 Info.FFDiag(E);
5046 return false;
5047 }
5048 bool found(APFloat &Value, QualType SubobjType) {
5049 return checkConst(SubobjType) &&
5050 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
5051 Value) &&
5052 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
5053 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
5054 }
5055 bool foundPointer(APValue &Subobj, QualType SubobjType) {
5056 if (!checkConst(SubobjType))
5057 return false;
5058
5059 QualType PointeeType;
5060 if (const PointerType *PT = SubobjType->getAs<PointerType>())
5061 PointeeType = PT->getPointeeType();
5062
5063 if (PointeeType.isNull() || !RHS.isInt() ||
5064 (Opcode != BO_Add && Opcode != BO_Sub)) {
5065 Info.FFDiag(E);
5066 return false;
5067 }
5068
5069 APSInt Offset = RHS.getInt();
5070 if (Opcode == BO_Sub)
5071 negateAsSigned(Offset);
5072
5073 LValue LVal;
5074 LVal.setFrom(Info.Ctx, Subobj);
5075 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
5076 return false;
5077 LVal.moveInto(Subobj);
5078 return true;
5079 }
5080};
5081} // end anonymous namespace
5082
5083const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
5084
5085/// Perform a compound assignment of LVal <op>= RVal.
5086static bool handleCompoundAssignment(EvalInfo &Info,
5087 const CompoundAssignOperator *E,
5088 const LValue &LVal, QualType LValType,
5089 QualType PromotedLValType,
5090 BinaryOperatorKind Opcode,
5091 const APValue &RVal) {
5092 if (LVal.Designator.Invalid)
5093 return false;
5094
5095 if (!Info.getLangOpts().CPlusPlus14) {
5096 Info.FFDiag(E);
5097 return false;
5098 }
5099
5100 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
5101 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
5102 RVal };
5103 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
5104}
5105
5106namespace {
5107struct IncDecSubobjectHandler {
5108 EvalInfo &Info;
5109 const UnaryOperator *E;
5111 APValue *Old;
5112
5113 typedef bool result_type;
5114
5115 bool checkConst(QualType QT) {
5116 // Assigning to a const object has undefined behavior.
5117 if (QT.isConstQualified()) {
5118 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
5119 return false;
5120 }
5121 return true;
5122 }
5123
5124 bool failed() { return false; }
5125 bool found(APValue &Subobj, QualType SubobjType, APValue::LValueBase Base) {
5126 // Stash the old value. Also clear Old, so we don't clobber it later
5127 // if we're post-incrementing a complex.
5128 if (Old) {
5129 *Old = Subobj;
5130 Old = nullptr;
5131 }
5132
5133 switch (Subobj.getKind()) {
5134 case APValue::Int:
5135 return found(Subobj.getInt(), SubobjType);
5136 case APValue::Float:
5137 return found(Subobj.getFloat(), SubobjType);
5139 return found(Subobj.getComplexIntReal(),
5140 SubobjType->castAs<ComplexType>()->getElementType()
5141 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
5143 return found(Subobj.getComplexFloatReal(),
5144 SubobjType->castAs<ComplexType>()->getElementType()
5145 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
5146 case APValue::LValue:
5147 return foundPointer(Subobj, SubobjType);
5148 default:
5149 // FIXME: can this happen?
5150 Info.FFDiag(E);
5151 return false;
5152 }
5153 }
5154 bool found(APSInt &Value, QualType SubobjType) {
5155 if (!checkConst(SubobjType))
5156 return false;
5157
5158 if (!SubobjType->isIntegerType()) {
5159 // We don't support increment / decrement on integer-cast-to-pointer
5160 // values.
5161 Info.FFDiag(E);
5162 return false;
5163 }
5164
5165 if (Old) *Old = APValue(Value);
5166
5167 // bool arithmetic promotes to int, and the conversion back to bool
5168 // doesn't reduce mod 2^n, so special-case it.
5169 if (SubobjType->isBooleanType()) {
5170 if (AccessKind == AK_Increment)
5171 Value = 1;
5172 else
5173 Value = !Value;
5174 return true;
5175 }
5176
5177 bool WasNegative = Value.isNegative();
5178 if (AccessKind == AK_Increment) {
5179 ++Value;
5180
5181 if (!WasNegative && Value.isNegative() && E->canOverflow() &&
5182 !SubobjType.isWrapType()) {
5183 APSInt ActualValue(Value, /*IsUnsigned*/true);
5184 return HandleOverflow(Info, E, ActualValue, SubobjType);
5185 }
5186 } else {
5187 --Value;
5188
5189 if (WasNegative && !Value.isNegative() && E->canOverflow() &&
5190 !SubobjType.isWrapType()) {
5191 unsigned BitWidth = Value.getBitWidth();
5192 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
5193 ActualValue.setBit(BitWidth);
5194 return HandleOverflow(Info, E, ActualValue, SubobjType);
5195 }
5196 }
5197 return true;
5198 }
5199 bool found(APFloat &Value, QualType SubobjType) {
5200 if (!checkConst(SubobjType))
5201 return false;
5202
5203 if (Old) *Old = APValue(Value);
5204
5205 APFloat One(Value.getSemantics(), 1);
5206 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
5207 APFloat::opStatus St;
5208 if (AccessKind == AK_Increment)
5209 St = Value.add(One, RM);
5210 else
5211 St = Value.subtract(One, RM);
5212 return checkFloatingPointResult(Info, E, St);
5213 }
5214 bool foundPointer(APValue &Subobj, QualType SubobjType) {
5215 if (!checkConst(SubobjType))
5216 return false;
5217
5218 QualType PointeeType;
5219 if (const PointerType *PT = SubobjType->getAs<PointerType>())
5220 PointeeType = PT->getPointeeType();
5221 else {
5222 Info.FFDiag(E);
5223 return false;
5224 }
5225
5226 LValue LVal;
5227 LVal.setFrom(Info.Ctx, Subobj);
5228 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
5229 AccessKind == AK_Increment ? 1 : -1))
5230 return false;
5231 LVal.moveInto(Subobj);
5232 return true;
5233 }
5234};
5235} // end anonymous namespace
5236
5237/// Perform an increment or decrement on LVal.
5238static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
5239 QualType LValType, bool IsIncrement, APValue *Old) {
5240 if (LVal.Designator.Invalid)
5241 return false;
5242
5243 if (!Info.getLangOpts().CPlusPlus14) {
5244 Info.FFDiag(E);
5245 return false;
5246 }
5247
5248 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
5249 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
5250 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
5251 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
5252}
5253
5254/// Build an lvalue for the object argument of a member function call.
5255static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
5256 LValue &This) {
5257 if (Object->getType()->isPointerType() && Object->isPRValue())
5258 return EvaluatePointer(Object, This, Info);
5259
5260 if (Object->isGLValue())
5261 return EvaluateLValue(Object, This, Info);
5262
5263 if (Object->getType()->isLiteralType(Info.Ctx))
5264 return EvaluateTemporary(Object, This, Info);
5265
5266 if (Object->getType()->isRecordType() && Object->isPRValue())
5267 return EvaluateTemporary(Object, This, Info);
5268
5269 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
5270 return false;
5271}
5272
5273/// HandleMemberPointerAccess - Evaluate a member access operation and build an
5274/// lvalue referring to the result.
5275///
5276/// \param Info - Information about the ongoing evaluation.
5277/// \param LV - An lvalue referring to the base of the member pointer.
5278/// \param RHS - The member pointer expression.
5279/// \param IncludeMember - Specifies whether the member itself is included in
5280/// the resulting LValue subobject designator. This is not possible when
5281/// creating a bound member function.
5282/// \return The field or method declaration to which the member pointer refers,
5283/// or 0 if evaluation fails.
5284static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
5285 QualType LVType,
5286 LValue &LV,
5287 const Expr *RHS,
5288 bool IncludeMember = true) {
5289 MemberPtr MemPtr;
5290 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
5291 return nullptr;
5292
5293 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
5294 // member value, the behavior is undefined.
5295 if (!MemPtr.getDecl()) {
5296 // FIXME: Specific diagnostic.
5297 Info.FFDiag(RHS);
5298 return nullptr;
5299 }
5300
5301 if (MemPtr.isDerivedMember()) {
5302 // This is a member of some derived class. Truncate LV appropriately.
5303 // The end of the derived-to-base path for the base object must match the
5304 // derived-to-base path for the member pointer.
5305 // C++23 [expr.mptr.oper]p4:
5306 // If the result of E1 is an object [...] whose most derived object does
5307 // not contain the member to which E2 refers, the behavior is undefined.
5308 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
5309 LV.Designator.Entries.size()) {
5310 Info.FFDiag(RHS);
5311 return nullptr;
5312 }
5313 unsigned PathLengthToMember =
5314 LV.Designator.Entries.size() - MemPtr.Path.size();
5315 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
5316 const CXXRecordDecl *LVDecl = getAsBaseClass(
5317 LV.Designator.Entries[PathLengthToMember + I]);
5318 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
5319 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
5320 Info.FFDiag(RHS);
5321 return nullptr;
5322 }
5323 }
5324 // MemPtr.Path only contains the base classes of the class directly
5325 // containing the member E2. It is still necessary to check that the class
5326 // directly containing the member E2 lies on the derived-to-base path of E1
5327 // to avoid incorrectly permitting member pointer access into a sibling
5328 // class of the class containing the member E2. If this class would
5329 // correspond to the most-derived class of E1, it either isn't contained in
5330 // LV.Designator.Entries or the corresponding entry refers to an array
5331 // element instead. Therefore get the most derived class directly in this
5332 // case. Otherwise the previous entry should correpond to this class.
5333 const CXXRecordDecl *LastLVDecl =
5334 (PathLengthToMember > LV.Designator.MostDerivedPathLength)
5335 ? getAsBaseClass(LV.Designator.Entries[PathLengthToMember - 1])
5336 : LV.Designator.MostDerivedType->getAsCXXRecordDecl();
5337 const CXXRecordDecl *LastMPDecl = MemPtr.getContainingRecord();
5338 if (LastLVDecl->getCanonicalDecl() != LastMPDecl->getCanonicalDecl()) {
5339 Info.FFDiag(RHS);
5340 return nullptr;
5341 }
5342
5343 // Truncate the lvalue to the appropriate derived class.
5344 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
5345 PathLengthToMember))
5346 return nullptr;
5347 } else if (!MemPtr.Path.empty()) {
5348 // Extend the LValue path with the member pointer's path.
5349 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
5350 MemPtr.Path.size() + IncludeMember);
5351
5352 // Walk down to the appropriate base class.
5353 if (const PointerType *PT = LVType->getAs<PointerType>())
5354 LVType = PT->getPointeeType();
5355 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
5356 assert(RD && "member pointer access on non-class-type expression");
5357 // The first class in the path is that of the lvalue.
5358 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
5359 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
5360 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
5361 return nullptr;
5362 RD = Base;
5363 }
5364 // Finally cast to the class containing the member.
5365 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
5366 MemPtr.getContainingRecord()))
5367 return nullptr;
5368 }
5369
5370 // Add the member. Note that we cannot build bound member functions here.
5371 if (IncludeMember) {
5372 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
5373 if (!HandleLValueMember(Info, RHS, LV, FD))
5374 return nullptr;
5375 } else if (const IndirectFieldDecl *IFD =
5376 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
5377 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
5378 return nullptr;
5379 } else {
5380 llvm_unreachable("can't construct reference to bound member function");
5381 }
5382 }
5383
5384 return MemPtr.getDecl();
5385}
5386
5387static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
5388 const BinaryOperator *BO,
5389 LValue &LV,
5390 bool IncludeMember = true) {
5391 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
5392
5393 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
5394 if (Info.noteFailure()) {
5395 MemberPtr MemPtr;
5396 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
5397 }
5398 return nullptr;
5399 }
5400
5401 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
5402 BO->getRHS(), IncludeMember);
5403}
5404
5405/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
5406/// the provided lvalue, which currently refers to the base object.
5407static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
5408 LValue &Result) {
5409 SubobjectDesignator &D = Result.Designator;
5410 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
5411 return false;
5412
5413 QualType TargetQT = E->getType();
5414 if (const PointerType *PT = TargetQT->getAs<PointerType>())
5415 TargetQT = PT->getPointeeType();
5416
5417 auto InvalidCast = [&]() {
5418 if (!Info.checkingPotentialConstantExpression() ||
5419 !Result.AllowConstexprUnknown) {
5420 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
5421 << D.MostDerivedType << TargetQT;
5422 }
5423 return false;
5424 };
5425
5426 // Check this cast lands within the final derived-to-base subobject path.
5427 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size())
5428 return InvalidCast();
5429
5430 // Check the type of the final cast. We don't need to check the path,
5431 // since a cast can only be formed if the path is unique.
5432 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
5433 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
5434 const CXXRecordDecl *FinalType;
5435 if (NewEntriesSize == D.MostDerivedPathLength)
5436 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
5437 else
5438 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
5439 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl())
5440 return InvalidCast();
5441
5442 // Truncate the lvalue to the appropriate derived class.
5443 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
5444}
5445
5446/// Get the value to use for a default-initialized object of type T.
5447/// Return false if it encounters something invalid.
5449 bool Success = true;
5450
5451 // If there is already a value present don't overwrite it.
5452 if (!Result.isAbsent())
5453 return true;
5454
5455 if (auto *RD = T->getAsCXXRecordDecl()) {
5456 if (RD->isInvalidDecl()) {
5457 Result = APValue();
5458 return false;
5459 }
5460 if (RD->isUnion()) {
5461 Result = APValue((const FieldDecl *)nullptr);
5462 return true;
5463 }
5464 Result =
5465 APValue(APValue::UninitStruct(), RD->getNumBases(), RD->getNumFields());
5466
5467 unsigned Index = 0;
5468 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
5469 End = RD->bases_end();
5470 I != End; ++I, ++Index)
5471 Success &=
5472 handleDefaultInitValue(I->getType(), Result.getStructBase(Index));
5473
5474 for (const auto *I : RD->fields()) {
5475 if (I->isUnnamedBitField())
5476 continue;
5478 I->getType(), Result.getStructField(I->getFieldIndex()));
5479 }
5480 return Success;
5481 }
5482
5483 if (auto *AT =
5484 dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
5485 Result = APValue(APValue::UninitArray(), 0, AT->getZExtSize());
5486 if (Result.hasArrayFiller())
5487 Success &=
5488 handleDefaultInitValue(AT->getElementType(), Result.getArrayFiller());
5489
5490 return Success;
5491 }
5492
5494 return true;
5495}
5496
5497namespace {
5498enum EvalStmtResult {
5499 /// Evaluation failed.
5500 ESR_Failed,
5501 /// Hit a 'return' statement.
5502 ESR_Returned,
5503 /// Evaluation succeeded.
5504 ESR_Succeeded,
5505 /// Hit a 'continue' statement.
5506 ESR_Continue,
5507 /// Hit a 'break' statement.
5508 ESR_Break,
5509 /// Still scanning for 'case' or 'default' statement.
5510 ESR_CaseNotFound
5511};
5512}
5513/// Evaluates the initializer of a reference.
5514static bool EvaluateInitForDeclOfReferenceType(EvalInfo &Info,
5515 const ValueDecl *D,
5516 const Expr *Init, LValue &Result,
5517 APValue &Val) {
5518 assert(Init->isGLValue() && D->getType()->isReferenceType());
5519 // A reference is an lvalue.
5520 if (!EvaluateLValue(Init, Result, Info))
5521 return false;
5522 // [C++26][decl.ref]
5523 // The object designated by such a glvalue can be outside its lifetime
5524 // Because a null pointer value or a pointer past the end of an object
5525 // does not point to an object, a reference in a well-defined program cannot
5526 // refer to such things;
5527 if (!Result.Designator.Invalid && Result.Designator.isOnePastTheEnd()) {
5528 Info.FFDiag(Init, diag::note_constexpr_access_past_end) << AK_Dereference;
5529 return false;
5530 }
5531
5532 // Save the result.
5533 Result.moveInto(Val);
5534 return true;
5535}
5536
5537static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
5538 if (VD->isInvalidDecl())
5539 return false;
5540 // We don't need to evaluate the initializer for a static local.
5541 if (!VD->hasLocalStorage())
5542 return true;
5543
5544 LValue Result;
5545 APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(),
5546 ScopeKind::Block, Result);
5547
5548 const Expr *InitE = VD->getInit();
5549 if (!InitE) {
5550 if (VD->getType()->isDependentType())
5551 return Info.noteSideEffect();
5552 return handleDefaultInitValue(VD->getType(), Val);
5553 }
5554 if (InitE->isValueDependent())
5555 return false;
5556
5557 // For references to objects, check they do not designate a one-past-the-end
5558 // object.
5559 if (VD->getType()->isReferenceType()) {
5560 return EvaluateInitForDeclOfReferenceType(Info, VD, InitE, Result, Val);
5561 } else if (!EvaluateInPlace(Val, Info, Result, InitE)) {
5562 // Wipe out any partially-computed value, to allow tracking that this
5563 // evaluation failed.
5564 Val = APValue();
5565 return false;
5566 }
5567
5568 return true;
5569}
5570
5571static bool EvaluateDecompositionDeclInit(EvalInfo &Info,
5572 const DecompositionDecl *DD);
5573
5574static bool EvaluateDecl(EvalInfo &Info, const Decl *D,
5575 bool EvaluateConditionDecl = false) {
5576 bool OK = true;
5577 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
5578 OK &= EvaluateVarDecl(Info, VD);
5579
5580 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D);
5581 EvaluateConditionDecl && DD)
5582 OK &= EvaluateDecompositionDeclInit(Info, DD);
5583
5584 return OK;
5585}
5586
5587static bool EvaluateDecompositionDeclInit(EvalInfo &Info,
5588 const DecompositionDecl *DD) {
5589 bool OK = true;
5590 for (auto *BD : DD->flat_bindings())
5591 if (auto *VD = BD->getHoldingVar())
5592 OK &= EvaluateDecl(Info, VD, /*EvaluateConditionDecl=*/true);
5593
5594 return OK;
5595}
5596
5597static bool MaybeEvaluateDeferredVarDeclInit(EvalInfo &Info,
5598 const VarDecl *VD) {
5599 if (auto *DD = dyn_cast_if_present<DecompositionDecl>(VD)) {
5600 if (!EvaluateDecompositionDeclInit(Info, DD))
5601 return false;
5602 }
5603 return true;
5604}
5605
5606static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info) {
5607 assert(E->isValueDependent());
5608 if (Info.noteSideEffect())
5609 return true;
5610 assert(E->containsErrors() && "valid value-dependent expression should never "
5611 "reach invalid code path.");
5612 return false;
5613}
5614
5615/// Evaluate a condition (either a variable declaration or an expression).
5616static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
5617 const Expr *Cond, bool &Result) {
5618 if (Cond->isValueDependent())
5619 return false;
5620 FullExpressionRAII Scope(Info);
5621 if (CondDecl && !EvaluateDecl(Info, CondDecl))
5622 return false;
5624 return false;
5625 if (!MaybeEvaluateDeferredVarDeclInit(Info, CondDecl))
5626 return false;
5627 return Scope.destroy();
5628}
5629
5630namespace {
5631/// A location where the result (returned value) of evaluating a
5632/// statement should be stored.
5633struct StmtResult {
5634 /// The APValue that should be filled in with the returned value.
5635 APValue &Value;
5636 /// The location containing the result, if any (used to support RVO).
5637 const LValue *Slot;
5638};
5639
5640struct TempVersionRAII {
5641 CallStackFrame &Frame;
5642
5643 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
5644 Frame.pushTempVersion();
5645 }
5646
5647 ~TempVersionRAII() {
5648 Frame.popTempVersion();
5649 }
5650};
5651
5652}
5653
5654static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
5655 const Stmt *S,
5656 const SwitchCase *SC = nullptr);
5657
5658/// Helper to implement named break/continue. Returns 'true' if the evaluation
5659/// result should be propagated up. Otherwise, it sets the evaluation result
5660/// to either Continue to continue the current loop, or Succeeded to break it.
5661static bool ShouldPropagateBreakContinue(EvalInfo &Info,
5662 const Stmt *LoopOrSwitch,
5664 EvalStmtResult &ESR) {
5665 bool IsSwitch = isa<SwitchStmt>(LoopOrSwitch);
5666
5667 // For loops, map Succeeded to Continue so we don't have to check for both.
5668 if (!IsSwitch && ESR == ESR_Succeeded) {
5669 ESR = ESR_Continue;
5670 return false;
5671 }
5672
5673 if (ESR != ESR_Break && ESR != ESR_Continue)
5674 return false;
5675
5676 // Are we breaking out of or continuing this statement?
5677 bool CanBreakOrContinue = !IsSwitch || ESR == ESR_Break;
5678 const Stmt *StackTop = Info.BreakContinueStack.back();
5679 if (CanBreakOrContinue && (StackTop == nullptr || StackTop == LoopOrSwitch)) {
5680 Info.BreakContinueStack.pop_back();
5681 if (ESR == ESR_Break)
5682 ESR = ESR_Succeeded;
5683 return false;
5684 }
5685
5686 // We're not. Propagate the result up.
5687 for (BlockScopeRAII *S : Scopes) {
5688 if (!S->destroy()) {
5689 ESR = ESR_Failed;
5690 break;
5691 }
5692 }
5693 return true;
5694}
5695
5696/// Evaluate the body of a loop, and translate the result as appropriate.
5697static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
5698 const Stmt *Body,
5699 const SwitchCase *Case = nullptr) {
5700 BlockScopeRAII Scope(Info);
5701
5702 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case);
5703 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
5704 ESR = ESR_Failed;
5705
5706 return ESR;
5707}
5708
5709/// Evaluate a switch statement.
5710static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
5711 const SwitchStmt *SS) {
5712 BlockScopeRAII Scope(Info);
5713
5714 // Evaluate the switch condition.
5715 APSInt Value;
5716 {
5717 if (const Stmt *Init = SS->getInit()) {
5718 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
5719 if (ESR != ESR_Succeeded) {
5720 if (ESR != ESR_Failed && !Scope.destroy())
5721 ESR = ESR_Failed;
5722 return ESR;
5723 }
5724 }
5725
5726 FullExpressionRAII CondScope(Info);
5727 if (SS->getConditionVariable() &&
5728 !EvaluateDecl(Info, SS->getConditionVariable()))
5729 return ESR_Failed;
5730 if (SS->getCond()->isValueDependent()) {
5731 // We don't know what the value is, and which branch should jump to.
5732 EvaluateDependentExpr(SS->getCond(), Info);
5733 return ESR_Failed;
5734 }
5735 if (!EvaluateInteger(SS->getCond(), Value, Info))
5736 return ESR_Failed;
5737
5739 return ESR_Failed;
5740
5741 if (!CondScope.destroy())
5742 return ESR_Failed;
5743 }
5744
5745 // Find the switch case corresponding to the value of the condition.
5746 // FIXME: Cache this lookup.
5747 const SwitchCase *Found = nullptr;
5748 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
5749 SC = SC->getNextSwitchCase()) {
5750 if (isa<DefaultStmt>(SC)) {
5751 Found = SC;
5752 continue;
5753 }
5754
5755 const CaseStmt *CS = cast<CaseStmt>(SC);
5756 const Expr *LHS = CS->getLHS();
5757 const Expr *RHS = CS->getRHS();
5758 if (LHS->isValueDependent() || (RHS && RHS->isValueDependent()))
5759 return ESR_Failed;
5760 APSInt LHSValue = LHS->EvaluateKnownConstInt(Info.Ctx);
5761 APSInt RHSValue = RHS ? RHS->EvaluateKnownConstInt(Info.Ctx) : LHSValue;
5762 if (LHSValue <= Value && Value <= RHSValue) {
5763 Found = SC;
5764 break;
5765 }
5766 }
5767
5768 if (!Found)
5769 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5770
5771 // Search the switch body for the switch case and evaluate it from there.
5772 EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found);
5773 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
5774 return ESR_Failed;
5775 if (ShouldPropagateBreakContinue(Info, SS, /*Scopes=*/{}, ESR))
5776 return ESR;
5777
5778 switch (ESR) {
5779 case ESR_Break:
5780 llvm_unreachable("Should have been converted to Succeeded");
5781 case ESR_Succeeded:
5782 case ESR_Continue:
5783 case ESR_Failed:
5784 case ESR_Returned:
5785 return ESR;
5786 case ESR_CaseNotFound:
5787 // This can only happen if the switch case is nested within a statement
5788 // expression. We have no intention of supporting that.
5789 Info.FFDiag(Found->getBeginLoc(),
5790 diag::note_constexpr_stmt_expr_unsupported);
5791 return ESR_Failed;
5792 }
5793 llvm_unreachable("Invalid EvalStmtResult!");
5794}
5795
5796static bool CheckLocalVariableDeclaration(EvalInfo &Info, const VarDecl *VD) {
5797 // An expression E is a core constant expression unless the evaluation of E
5798 // would evaluate one of the following: [C++23] - a control flow that passes
5799 // through a declaration of a variable with static or thread storage duration
5800 // unless that variable is usable in constant expressions.
5801 if (VD->isLocalVarDecl() && VD->isStaticLocal() &&
5802 !VD->isUsableInConstantExpressions(Info.Ctx)) {
5803 Info.CCEDiag(VD->getLocation(), diag::note_constexpr_static_local)
5804 << (VD->getTSCSpec() == TSCS_unspecified ? 0 : 1) << VD;
5805 return false;
5806 }
5807 return true;
5808}
5809
5810// Evaluate a statement.
5811static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
5812 const Stmt *S, const SwitchCase *Case) {
5813 if (!Info.nextStep(S))
5814 return ESR_Failed;
5815
5816 // If we're hunting down a 'case' or 'default' label, recurse through
5817 // substatements until we hit the label.
5818 if (Case) {
5819 switch (S->getStmtClass()) {
5820 case Stmt::CompoundStmtClass:
5821 // FIXME: Precompute which substatement of a compound statement we
5822 // would jump to, and go straight there rather than performing a
5823 // linear scan each time.
5824 case Stmt::LabelStmtClass:
5825 case Stmt::AttributedStmtClass:
5826 case Stmt::DoStmtClass:
5827 break;
5828
5829 case Stmt::CaseStmtClass:
5830 case Stmt::DefaultStmtClass:
5831 if (Case == S)
5832 Case = nullptr;
5833 break;
5834
5835 case Stmt::IfStmtClass: {
5836 // FIXME: Precompute which side of an 'if' we would jump to, and go
5837 // straight there rather than scanning both sides.
5838 const IfStmt *IS = cast<IfStmt>(S);
5839
5840 // Wrap the evaluation in a block scope, in case it's a DeclStmt
5841 // preceded by our switch label.
5842 BlockScopeRAII Scope(Info);
5843
5844 // Step into the init statement in case it brings an (uninitialized)
5845 // variable into scope.
5846 if (const Stmt *Init = IS->getInit()) {
5847 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5848 if (ESR != ESR_CaseNotFound) {
5849 assert(ESR != ESR_Succeeded);
5850 return ESR;
5851 }
5852 }
5853
5854 // Condition variable must be initialized if it exists.
5855 // FIXME: We can skip evaluating the body if there's a condition
5856 // variable, as there can't be any case labels within it.
5857 // (The same is true for 'for' statements.)
5858
5859 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
5860 if (ESR == ESR_Failed)
5861 return ESR;
5862 if (ESR != ESR_CaseNotFound)
5863 return Scope.destroy() ? ESR : ESR_Failed;
5864 if (!IS->getElse())
5865 return ESR_CaseNotFound;
5866
5867 ESR = EvaluateStmt(Result, Info, IS->getElse(), Case);
5868 if (ESR == ESR_Failed)
5869 return ESR;
5870 if (ESR != ESR_CaseNotFound)
5871 return Scope.destroy() ? ESR : ESR_Failed;
5872 return ESR_CaseNotFound;
5873 }
5874
5875 case Stmt::WhileStmtClass: {
5876 EvalStmtResult ESR =
5877 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
5878 if (ShouldPropagateBreakContinue(Info, S, /*Scopes=*/{}, ESR))
5879 return ESR;
5880 if (ESR != ESR_Continue)
5881 return ESR;
5882 break;
5883 }
5884
5885 case Stmt::ForStmtClass: {
5886 const ForStmt *FS = cast<ForStmt>(S);
5887 BlockScopeRAII Scope(Info);
5888
5889 // Step into the init statement in case it brings an (uninitialized)
5890 // variable into scope.
5891 if (const Stmt *Init = FS->getInit()) {
5892 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5893 if (ESR != ESR_CaseNotFound) {
5894 assert(ESR != ESR_Succeeded);
5895 return ESR;
5896 }
5897 }
5898
5899 EvalStmtResult ESR =
5900 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
5901 if (ShouldPropagateBreakContinue(Info, FS, /*Scopes=*/{}, ESR))
5902 return ESR;
5903 if (ESR != ESR_Continue)
5904 return ESR;
5905 if (const auto *Inc = FS->getInc()) {
5906 if (Inc->isValueDependent()) {
5907 if (!EvaluateDependentExpr(Inc, Info))
5908 return ESR_Failed;
5909 } else {
5910 FullExpressionRAII IncScope(Info);
5911 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5912 return ESR_Failed;
5913 }
5914 }
5915 break;
5916 }
5917
5918 case Stmt::DeclStmtClass: {
5919 // Start the lifetime of any uninitialized variables we encounter. They
5920 // might be used by the selected branch of the switch.
5921 const DeclStmt *DS = cast<DeclStmt>(S);
5922 for (const auto *D : DS->decls()) {
5923 if (const auto *VD = dyn_cast<VarDecl>(D)) {
5924 if (!CheckLocalVariableDeclaration(Info, VD))
5925 return ESR_Failed;
5926 if (VD->hasLocalStorage() && !VD->getInit())
5927 if (!EvaluateVarDecl(Info, VD))
5928 return ESR_Failed;
5929 // FIXME: If the variable has initialization that can't be jumped
5930 // over, bail out of any immediately-surrounding compound-statement
5931 // too. There can't be any case labels here.
5932 }
5933 }
5934 return ESR_CaseNotFound;
5935 }
5936
5937 default:
5938 return ESR_CaseNotFound;
5939 }
5940 }
5941
5942 switch (S->getStmtClass()) {
5943 default:
5944 if (const Expr *E = dyn_cast<Expr>(S)) {
5945 if (E->isValueDependent()) {
5946 if (!EvaluateDependentExpr(E, Info))
5947 return ESR_Failed;
5948 } else {
5949 // Don't bother evaluating beyond an expression-statement which couldn't
5950 // be evaluated.
5951 // FIXME: Do we need the FullExpressionRAII object here?
5952 // VisitExprWithCleanups should create one when necessary.
5953 FullExpressionRAII Scope(Info);
5954 if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy())
5955 return ESR_Failed;
5956 }
5957 return ESR_Succeeded;
5958 }
5959
5960 Info.FFDiag(S->getBeginLoc()) << S->getSourceRange();
5961 return ESR_Failed;
5962
5963 case Stmt::NullStmtClass:
5964 return ESR_Succeeded;
5965
5966 case Stmt::DeclStmtClass: {
5967 const DeclStmt *DS = cast<DeclStmt>(S);
5968 for (const auto *D : DS->decls()) {
5969 const VarDecl *VD = dyn_cast_or_null<VarDecl>(D);
5970 if (VD && !CheckLocalVariableDeclaration(Info, VD))
5971 return ESR_Failed;
5972 // Each declaration initialization is its own full-expression.
5973 FullExpressionRAII Scope(Info);
5974 if (!EvaluateDecl(Info, D, /*EvaluateConditionDecl=*/true) &&
5975 !Info.noteFailure())
5976 return ESR_Failed;
5977 if (!Scope.destroy())
5978 return ESR_Failed;
5979 }
5980 return ESR_Succeeded;
5981 }
5982
5983 case Stmt::ReturnStmtClass: {
5984 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
5985 FullExpressionRAII Scope(Info);
5986 if (RetExpr && RetExpr->isValueDependent()) {
5987 EvaluateDependentExpr(RetExpr, Info);
5988 // We know we returned, but we don't know what the value is.
5989 return ESR_Failed;
5990 }
5991 if (RetExpr &&
5992 !(Result.Slot
5993 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
5994 : Evaluate(Result.Value, Info, RetExpr)))
5995 return ESR_Failed;
5996 return Scope.destroy() ? ESR_Returned : ESR_Failed;
5997 }
5998
5999 case Stmt::CompoundStmtClass: {
6000 BlockScopeRAII Scope(Info);
6001
6002 const CompoundStmt *CS = cast<CompoundStmt>(S);
6003 for (const auto *BI : CS->body()) {
6004 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
6005 if (ESR == ESR_Succeeded)
6006 Case = nullptr;
6007 else if (ESR != ESR_CaseNotFound) {
6008 if (ESR != ESR_Failed && !Scope.destroy())
6009 return ESR_Failed;
6010 return ESR;
6011 }
6012 }
6013 if (Case)
6014 return ESR_CaseNotFound;
6015 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
6016 }
6017
6018 case Stmt::IfStmtClass: {
6019 const IfStmt *IS = cast<IfStmt>(S);
6020
6021 // Evaluate the condition, as either a var decl or as an expression.
6022 BlockScopeRAII Scope(Info);
6023 if (const Stmt *Init = IS->getInit()) {
6024 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
6025 if (ESR != ESR_Succeeded) {
6026 if (ESR != ESR_Failed && !Scope.destroy())
6027 return ESR_Failed;
6028 return ESR;
6029 }
6030 }
6031 bool Cond;
6032 if (IS->isConsteval()) {
6034 // If we are not in a constant context, if consteval should not evaluate
6035 // to true.
6036 if (!Info.InConstantContext)
6037 Cond = !Cond;
6038 } else if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(),
6039 Cond))
6040 return ESR_Failed;
6041
6042 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
6043 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
6044 if (ESR != ESR_Succeeded) {
6045 if (ESR != ESR_Failed && !Scope.destroy())
6046 return ESR_Failed;
6047 return ESR;
6048 }
6049 }
6050 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
6051 }
6052
6053 case Stmt::WhileStmtClass: {
6054 const WhileStmt *WS = cast<WhileStmt>(S);
6055 while (true) {
6056 BlockScopeRAII Scope(Info);
6057 bool Continue;
6058 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
6059 Continue))
6060 return ESR_Failed;
6061 if (!Continue)
6062 break;
6063
6064 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
6065 if (ShouldPropagateBreakContinue(Info, WS, &Scope, ESR))
6066 return ESR;
6067
6068 if (ESR != ESR_Continue) {
6069 if (ESR != ESR_Failed && !Scope.destroy())
6070 return ESR_Failed;
6071 return ESR;
6072 }
6073 if (!Scope.destroy())
6074 return ESR_Failed;
6075 }
6076 return ESR_Succeeded;
6077 }
6078
6079 case Stmt::DoStmtClass: {
6080 const DoStmt *DS = cast<DoStmt>(S);
6081 bool Continue;
6082 do {
6083 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
6084 if (ShouldPropagateBreakContinue(Info, DS, /*Scopes=*/{}, ESR))
6085 return ESR;
6086 if (ESR != ESR_Continue)
6087 return ESR;
6088 Case = nullptr;
6089
6090 if (DS->getCond()->isValueDependent()) {
6091 EvaluateDependentExpr(DS->getCond(), Info);
6092 // Bailout as we don't know whether to keep going or terminate the loop.
6093 return ESR_Failed;
6094 }
6095 FullExpressionRAII CondScope(Info);
6096 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) ||
6097 !CondScope.destroy())
6098 return ESR_Failed;
6099 } while (Continue);
6100 return ESR_Succeeded;
6101 }
6102
6103 case Stmt::ForStmtClass: {
6104 const ForStmt *FS = cast<ForStmt>(S);
6105 BlockScopeRAII ForScope(Info);
6106 if (FS->getInit()) {
6107 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
6108 if (ESR != ESR_Succeeded) {
6109 if (ESR != ESR_Failed && !ForScope.destroy())
6110 return ESR_Failed;
6111 return ESR;
6112 }
6113 }
6114 while (true) {
6115 BlockScopeRAII IterScope(Info);
6116 bool Continue = true;
6117 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
6118 FS->getCond(), Continue))
6119 return ESR_Failed;
6120
6121 if (!Continue) {
6122 if (!IterScope.destroy())
6123 return ESR_Failed;
6124 break;
6125 }
6126
6127 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
6128 if (ShouldPropagateBreakContinue(Info, FS, {&IterScope, &ForScope}, ESR))
6129 return ESR;
6130 if (ESR != ESR_Continue) {
6131 if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))
6132 return ESR_Failed;
6133 return ESR;
6134 }
6135
6136 if (const auto *Inc = FS->getInc()) {
6137 if (Inc->isValueDependent()) {
6138 if (!EvaluateDependentExpr(Inc, Info))
6139 return ESR_Failed;
6140 } else {
6141 FullExpressionRAII IncScope(Info);
6142 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
6143 return ESR_Failed;
6144 }
6145 }
6146
6147 if (!IterScope.destroy())
6148 return ESR_Failed;
6149 }
6150 return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;
6151 }
6152
6153 case Stmt::CXXForRangeStmtClass: {
6155 BlockScopeRAII Scope(Info);
6156
6157 // Evaluate the init-statement if present.
6158 if (FS->getInit()) {
6159 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
6160 if (ESR != ESR_Succeeded) {
6161 if (ESR != ESR_Failed && !Scope.destroy())
6162 return ESR_Failed;
6163 return ESR;
6164 }
6165 }
6166
6167 // Initialize the __range variable.
6168 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
6169 if (ESR != ESR_Succeeded) {
6170 if (ESR != ESR_Failed && !Scope.destroy())
6171 return ESR_Failed;
6172 return ESR;
6173 }
6174
6175 // In error-recovery cases it's possible to get here even if we failed to
6176 // synthesize the __begin and __end variables.
6177 if (!FS->getBeginStmt() || !FS->getEndStmt() || !FS->getCond())
6178 return ESR_Failed;
6179
6180 // Create the __begin and __end iterators.
6181 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
6182 if (ESR != ESR_Succeeded) {
6183 if (ESR != ESR_Failed && !Scope.destroy())
6184 return ESR_Failed;
6185 return ESR;
6186 }
6187 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
6188 if (ESR != ESR_Succeeded) {
6189 if (ESR != ESR_Failed && !Scope.destroy())
6190 return ESR_Failed;
6191 return ESR;
6192 }
6193
6194 while (true) {
6195 // Condition: __begin != __end.
6196 {
6197 if (FS->getCond()->isValueDependent()) {
6198 EvaluateDependentExpr(FS->getCond(), Info);
6199 // We don't know whether to keep going or terminate the loop.
6200 return ESR_Failed;
6201 }
6202 bool Continue = true;
6203 FullExpressionRAII CondExpr(Info);
6204 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
6205 return ESR_Failed;
6206 if (!Continue)
6207 break;
6208 }
6209
6210 // User's variable declaration, initialized by *__begin.
6211 BlockScopeRAII InnerScope(Info);
6212 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
6213 if (ESR != ESR_Succeeded) {
6214 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
6215 return ESR_Failed;
6216 return ESR;
6217 }
6218
6219 // Loop body.
6220 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
6221 if (ShouldPropagateBreakContinue(Info, FS, {&InnerScope, &Scope}, ESR))
6222 return ESR;
6223 if (ESR != ESR_Continue) {
6224 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
6225 return ESR_Failed;
6226 return ESR;
6227 }
6228 if (FS->getInc()->isValueDependent()) {
6229 if (!EvaluateDependentExpr(FS->getInc(), Info))
6230 return ESR_Failed;
6231 } else {
6232 // Increment: ++__begin
6233 if (!EvaluateIgnoredValue(Info, FS->getInc()))
6234 return ESR_Failed;
6235 }
6236
6237 if (!InnerScope.destroy())
6238 return ESR_Failed;
6239 }
6240
6241 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
6242 }
6243
6244 case Stmt::SwitchStmtClass:
6245 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
6246
6247 case Stmt::ContinueStmtClass:
6248 case Stmt::BreakStmtClass: {
6249 auto *B = cast<LoopControlStmt>(S);
6250 Info.BreakContinueStack.push_back(B->getNamedLoopOrSwitch());
6251 return isa<ContinueStmt>(S) ? ESR_Continue : ESR_Break;
6252 }
6253
6254 case Stmt::LabelStmtClass:
6255 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
6256
6257 case Stmt::AttributedStmtClass: {
6258 const auto *AS = cast<AttributedStmt>(S);
6259 const auto *SS = AS->getSubStmt();
6260 MSConstexprContextRAII ConstexprContext(
6261 *Info.CurrentCall, hasSpecificAttr<MSConstexprAttr>(AS->getAttrs()) &&
6262 isa<ReturnStmt>(SS));
6263
6264 auto LO = Info.Ctx.getLangOpts();
6265 if (LO.CXXAssumptions && !LO.MSVCCompat) {
6266 for (auto *Attr : AS->getAttrs()) {
6267 auto *AA = dyn_cast<CXXAssumeAttr>(Attr);
6268 if (!AA)
6269 continue;
6270
6271 auto *Assumption = AA->getAssumption();
6272 if (Assumption->isValueDependent())
6273 return ESR_Failed;
6274
6275 if (Assumption->HasSideEffects(Info.Ctx))
6276 continue;
6277
6278 bool Value;
6279 if (!EvaluateAsBooleanCondition(Assumption, Value, Info))
6280 return ESR_Failed;
6281 if (!Value) {
6282 Info.CCEDiag(Assumption->getExprLoc(),
6283 diag::note_constexpr_assumption_failed);
6284 return ESR_Failed;
6285 }
6286 }
6287 }
6288
6289 return EvaluateStmt(Result, Info, SS, Case);
6290 }
6291
6292 case Stmt::CaseStmtClass:
6293 case Stmt::DefaultStmtClass:
6294 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
6295 case Stmt::CXXTryStmtClass:
6296 // Evaluate try blocks by evaluating all sub statements.
6297 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
6298 }
6299}
6300
6301/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
6302/// default constructor. If so, we'll fold it whether or not it's marked as
6303/// constexpr. If it is marked as constexpr, we will never implicitly define it,
6304/// so we need special handling.
6305static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
6306 const CXXConstructorDecl *CD,
6307 bool IsValueInitialization) {
6308 if (!CD->isTrivial() || !CD->isDefaultConstructor())
6309 return false;
6310
6311 // Value-initialization does not call a trivial default constructor, so such a
6312 // call is a core constant expression whether or not the constructor is
6313 // constexpr.
6314 if (!CD->isConstexpr() && !IsValueInitialization) {
6315 if (Info.getLangOpts().CPlusPlus11) {
6316 // FIXME: If DiagDecl is an implicitly-declared special member function,
6317 // we should be much more explicit about why it's not constexpr.
6318 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
6319 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
6320 Info.Note(CD->getLocation(), diag::note_declared_at);
6321 } else {
6322 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
6323 }
6324 }
6325 return true;
6326}
6327
6328/// CheckConstexprFunction - Check that a function can be called in a constant
6329/// expression.
6330static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
6332 const FunctionDecl *Definition,
6333 const Stmt *Body) {
6334 // Potential constant expressions can contain calls to declared, but not yet
6335 // defined, constexpr functions.
6336 if (Info.checkingPotentialConstantExpression() && !Definition &&
6337 Declaration->isConstexpr())
6338 return false;
6339
6340 // Bail out if the function declaration itself is invalid. We will
6341 // have produced a relevant diagnostic while parsing it, so just
6342 // note the problematic sub-expression.
6343 if (Declaration->isInvalidDecl()) {
6344 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
6345 return false;
6346 }
6347
6348 // DR1872: An instantiated virtual constexpr function can't be called in a
6349 // constant expression (prior to C++20). We can still constant-fold such a
6350 // call.
6351 if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) &&
6352 cast<CXXMethodDecl>(Declaration)->isVirtual())
6353 Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
6354
6355 if (Definition && Definition->isInvalidDecl()) {
6356 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
6357 return false;
6358 }
6359
6360 // Can we evaluate this function call?
6361 if (Definition && Body &&
6362 (Definition->isConstexpr() || (Info.CurrentCall->CanEvalMSConstexpr &&
6363 Definition->hasAttr<MSConstexprAttr>())))
6364 return true;
6365
6366 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
6367 // Special note for the assert() macro, as the normal error message falsely
6368 // implies we cannot use an assertion during constant evaluation.
6369 if (CallLoc.isMacroID() && DiagDecl->getIdentifier()) {
6370 // FIXME: Instead of checking for an implementation-defined function,
6371 // check and evaluate the assert() macro.
6372 StringRef Name = DiagDecl->getName();
6373 bool AssertFailed =
6374 Name == "__assert_rtn" || Name == "__assert_fail" || Name == "_wassert";
6375 if (AssertFailed) {
6376 Info.FFDiag(CallLoc, diag::note_constexpr_assert_failed);
6377 return false;
6378 }
6379 }
6380
6381 if (Info.getLangOpts().CPlusPlus11) {
6382 // If this function is not constexpr because it is an inherited
6383 // non-constexpr constructor, diagnose that directly.
6384 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
6385 if (CD && CD->isInheritingConstructor()) {
6386 auto *Inherited = CD->getInheritedConstructor().getConstructor();
6387 if (!Inherited->isConstexpr())
6388 DiagDecl = CD = Inherited;
6389 }
6390
6391 // FIXME: If DiagDecl is an implicitly-declared special member function
6392 // or an inheriting constructor, we should be much more explicit about why
6393 // it's not constexpr.
6394 if (CD && CD->isInheritingConstructor())
6395 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
6396 << CD->getInheritedConstructor().getConstructor()->getParent();
6397 else
6398 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
6399 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
6400 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
6401 } else {
6402 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
6403 }
6404 return false;
6405}
6406
6407namespace {
6408struct CheckDynamicTypeHandler {
6410 typedef bool result_type;
6411 bool failed() { return false; }
6412 bool found(APValue &Subobj, QualType SubobjType, APValue::LValueBase Base) {
6413 return true;
6414 }
6415 bool found(APSInt &Value, QualType SubobjType) { return true; }
6416 bool found(APFloat &Value, QualType SubobjType) { return true; }
6417};
6418} // end anonymous namespace
6419
6420/// Check that we can access the notional vptr of an object / determine its
6421/// dynamic type.
6422static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
6423 AccessKinds AK, bool Polymorphic) {
6424 if (This.Designator.Invalid)
6425 return false;
6426
6427 CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
6428
6429 if (!Obj)
6430 return false;
6431
6432 if (!Obj.Value) {
6433 // The object is not usable in constant expressions, so we can't inspect
6434 // its value to see if it's in-lifetime or what the active union members
6435 // are. We can still check for a one-past-the-end lvalue.
6436 if (This.Designator.isOnePastTheEnd() ||
6437 This.Designator.isMostDerivedAnUnsizedArray()) {
6438 Info.FFDiag(E, This.Designator.isOnePastTheEnd()
6439 ? diag::note_constexpr_access_past_end
6440 : diag::note_constexpr_access_unsized_array)
6441 << AK;
6442 return false;
6443 } else if (Polymorphic) {
6444 // Conservatively refuse to perform a polymorphic operation if we would
6445 // not be able to read a notional 'vptr' value.
6446 if (!Info.checkingPotentialConstantExpression() ||
6447 !This.AllowConstexprUnknown) {
6448 APValue Val;
6449 This.moveInto(Val);
6450 QualType StarThisType =
6451 Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
6452 Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
6453 << AK << Val.getAsString(Info.Ctx, StarThisType);
6454 }
6455 return false;
6456 }
6457 return true;
6458 }
6459
6460 CheckDynamicTypeHandler Handler{AK};
6461 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
6462}
6463
6464/// Check that the pointee of the 'this' pointer in a member function call is
6465/// either within its lifetime or in its period of construction or destruction.
6466static bool
6468 const LValue &This,
6469 const CXXMethodDecl *NamedMember) {
6470 return checkDynamicType(
6471 Info, E, This,
6472 isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false);
6473}
6474
6476 /// The dynamic class type of the object.
6478 /// The corresponding path length in the lvalue.
6479 unsigned PathLength;
6480};
6481
6482static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
6483 unsigned PathLength) {
6484 assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
6485 Designator.Entries.size() && "invalid path length");
6486 return (PathLength == Designator.MostDerivedPathLength)
6487 ? Designator.MostDerivedType->getAsCXXRecordDecl()
6488 : getAsBaseClass(Designator.Entries[PathLength - 1]);
6489}
6490
6491/// Determine the dynamic type of an object.
6492static std::optional<DynamicType> ComputeDynamicType(EvalInfo &Info,
6493 const Expr *E,
6494 LValue &This,
6495 AccessKinds AK) {
6496 // If we don't have an lvalue denoting an object of class type, there is no
6497 // meaningful dynamic type. (We consider objects of non-class type to have no
6498 // dynamic type.)
6499 if (!checkDynamicType(Info, E, This, AK,
6500 AK != AK_TypeId || This.AllowConstexprUnknown))
6501 return std::nullopt;
6502
6503 if (This.Designator.Invalid)
6504 return std::nullopt;
6505
6506 // Refuse to compute a dynamic type in the presence of virtual bases. This
6507 // shouldn't happen other than in constant-folding situations, since literal
6508 // types can't have virtual bases.
6509 //
6510 // Note that consumers of DynamicType assume that the type has no virtual
6511 // bases, and will need modifications if this restriction is relaxed.
6512 const CXXRecordDecl *Class =
6513 This.Designator.MostDerivedType->getAsCXXRecordDecl();
6514 if (!Class || Class->getNumVBases()) {
6515 Info.FFDiag(E);
6516 return std::nullopt;
6517 }
6518
6519 // FIXME: For very deep class hierarchies, it might be beneficial to use a
6520 // binary search here instead. But the overwhelmingly common case is that
6521 // we're not in the middle of a constructor, so it probably doesn't matter
6522 // in practice.
6523 ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
6524 for (unsigned PathLength = This.Designator.MostDerivedPathLength;
6525 PathLength <= Path.size(); ++PathLength) {
6526 switch (Info.isEvaluatingCtorDtor(This.getLValueBase(),
6527 Path.slice(0, PathLength))) {
6528 case ConstructionPhase::Bases:
6529 case ConstructionPhase::DestroyingBases:
6530 // We're constructing or destroying a base class. This is not the dynamic
6531 // type.
6532 break;
6533
6534 case ConstructionPhase::None:
6535 case ConstructionPhase::AfterBases:
6536 case ConstructionPhase::AfterFields:
6537 case ConstructionPhase::Destroying:
6538 // We've finished constructing the base classes and not yet started
6539 // destroying them again, so this is the dynamic type.
6540 return DynamicType{getBaseClassType(This.Designator, PathLength),
6541 PathLength};
6542 }
6543 }
6544
6545 // CWG issue 1517: we're constructing a base class of the object described by
6546 // 'This', so that object has not yet begun its period of construction and
6547 // any polymorphic operation on it results in undefined behavior.
6548 Info.FFDiag(E);
6549 return std::nullopt;
6550}
6551
6552/// Perform virtual dispatch.
6554 EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
6555 llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
6556 std::optional<DynamicType> DynType = ComputeDynamicType(
6557 Info, E, This,
6559 if (!DynType)
6560 return nullptr;
6561
6562 // Find the final overrider. It must be declared in one of the classes on the
6563 // path from the dynamic type to the static type.
6564 // FIXME: If we ever allow literal types to have virtual base classes, that
6565 // won't be true.
6566 const CXXMethodDecl *Callee = Found;
6567 unsigned PathLength = DynType->PathLength;
6568 for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
6569 const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
6570 const CXXMethodDecl *Overrider =
6571 Found->getCorrespondingMethodDeclaredInClass(Class, false);
6572 if (Overrider) {
6573 Callee = Overrider;
6574 break;
6575 }
6576 }
6577
6578 // C++2a [class.abstract]p6:
6579 // the effect of making a virtual call to a pure virtual function [...] is
6580 // undefined
6581 if (Callee->isPureVirtual()) {
6582 Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
6583 Info.Note(Callee->getLocation(), diag::note_declared_at);
6584 return nullptr;
6585 }
6586
6587 // If necessary, walk the rest of the path to determine the sequence of
6588 // covariant adjustment steps to apply.
6589 if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
6590 Found->getReturnType())) {
6591 CovariantAdjustmentPath.push_back(Callee->getReturnType());
6592 for (unsigned CovariantPathLength = PathLength + 1;
6593 CovariantPathLength != This.Designator.Entries.size();
6594 ++CovariantPathLength) {
6595 const CXXRecordDecl *NextClass =
6596 getBaseClassType(This.Designator, CovariantPathLength);
6597 const CXXMethodDecl *Next =
6598 Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
6599 if (Next && !Info.Ctx.hasSameUnqualifiedType(
6600 Next->getReturnType(), CovariantAdjustmentPath.back()))
6601 CovariantAdjustmentPath.push_back(Next->getReturnType());
6602 }
6603 if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
6604 CovariantAdjustmentPath.back()))
6605 CovariantAdjustmentPath.push_back(Found->getReturnType());
6606 }
6607
6608 // Perform 'this' adjustment.
6609 if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
6610 return nullptr;
6611
6612 return Callee;
6613}
6614
6615/// Perform the adjustment from a value returned by a virtual function to
6616/// a value of the statically expected type, which may be a pointer or
6617/// reference to a base class of the returned type.
6618static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
6619 APValue &Result,
6620 ArrayRef<QualType> Path) {
6621 assert(Result.isLValue() &&
6622 "unexpected kind of APValue for covariant return");
6623 if (Result.isNullPointer())
6624 return true;
6625
6626 LValue LVal;
6627 LVal.setFrom(Info.Ctx, Result);
6628
6629 const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
6630 for (unsigned I = 1; I != Path.size(); ++I) {
6631 const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
6632 assert(OldClass && NewClass && "unexpected kind of covariant return");
6633 if (OldClass != NewClass &&
6634 !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
6635 return false;
6636 OldClass = NewClass;
6637 }
6638
6639 LVal.moveInto(Result);
6640 return true;
6641}
6642
6643/// Determine whether \p Base, which is known to be a direct base class of
6644/// \p Derived, is a public base class.
6645static bool isBaseClassPublic(const CXXRecordDecl *Derived,
6646 const CXXRecordDecl *Base) {
6647 for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
6648 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
6649 if (BaseClass && declaresSameEntity(BaseClass, Base))
6650 return BaseSpec.getAccessSpecifier() == AS_public;
6651 }
6652 llvm_unreachable("Base is not a direct base of Derived");
6653}
6654
6655/// Apply the given dynamic cast operation on the provided lvalue.
6656///
6657/// This implements the hard case of dynamic_cast, requiring a "runtime check"
6658/// to find a suitable target subobject.
6659static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
6660 LValue &Ptr) {
6661 // We can't do anything with a non-symbolic pointer value.
6662 SubobjectDesignator &D = Ptr.Designator;
6663 if (D.Invalid)
6664 return false;
6665
6666 // C++ [expr.dynamic.cast]p6:
6667 // If v is a null pointer value, the result is a null pointer value.
6668 if (Ptr.isNullPointer() && !E->isGLValue())
6669 return true;
6670
6671 // For all the other cases, we need the pointer to point to an object within
6672 // its lifetime / period of construction / destruction, and we need to know
6673 // its dynamic type.
6674 std::optional<DynamicType> DynType =
6675 ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
6676 if (!DynType)
6677 return false;
6678
6679 // C++ [expr.dynamic.cast]p7:
6680 // If T is "pointer to cv void", then the result is a pointer to the most
6681 // derived object
6682 if (E->getType()->isVoidPointerType())
6683 return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
6684
6686 assert(C && "dynamic_cast target is not void pointer nor class");
6687 CanQualType CQT = Info.Ctx.getCanonicalTagType(C);
6688
6689 auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
6690 // C++ [expr.dynamic.cast]p9:
6691 if (!E->isGLValue()) {
6692 // The value of a failed cast to pointer type is the null pointer value
6693 // of the required result type.
6694 Ptr.setNull(Info.Ctx, E->getType());
6695 return true;
6696 }
6697
6698 // A failed cast to reference type throws [...] std::bad_cast.
6699 unsigned DiagKind;
6700 if (!Paths && (declaresSameEntity(DynType->Type, C) ||
6701 DynType->Type->isDerivedFrom(C)))
6702 DiagKind = 0;
6703 else if (!Paths || Paths->begin() == Paths->end())
6704 DiagKind = 1;
6705 else if (Paths->isAmbiguous(CQT))
6706 DiagKind = 2;
6707 else {
6708 assert(Paths->front().Access != AS_public && "why did the cast fail?");
6709 DiagKind = 3;
6710 }
6711 Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
6712 << DiagKind << Ptr.Designator.getType(Info.Ctx)
6713 << Info.Ctx.getCanonicalTagType(DynType->Type)
6714 << E->getType().getUnqualifiedType();
6715 return false;
6716 };
6717
6718 // Runtime check, phase 1:
6719 // Walk from the base subobject towards the derived object looking for the
6720 // target type.
6721 for (int PathLength = Ptr.Designator.Entries.size();
6722 PathLength >= (int)DynType->PathLength; --PathLength) {
6723 const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
6724 if (declaresSameEntity(Class, C))
6725 return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
6726 // We can only walk across public inheritance edges.
6727 if (PathLength > (int)DynType->PathLength &&
6728 !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
6729 Class))
6730 return RuntimeCheckFailed(nullptr);
6731 }
6732
6733 // Runtime check, phase 2:
6734 // Search the dynamic type for an unambiguous public base of type C.
6735 CXXBasePaths Paths(/*FindAmbiguities=*/true,
6736 /*RecordPaths=*/true, /*DetectVirtual=*/false);
6737 if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
6738 Paths.front().Access == AS_public) {
6739 // Downcast to the dynamic type...
6740 if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
6741 return false;
6742 // ... then upcast to the chosen base class subobject.
6743 for (CXXBasePathElement &Elem : Paths.front())
6744 if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
6745 return false;
6746 return true;
6747 }
6748
6749 // Otherwise, the runtime check fails.
6750 return RuntimeCheckFailed(&Paths);
6751}
6752
6753namespace {
6754struct StartLifetimeOfUnionMemberHandler {
6755 EvalInfo &Info;
6756 const Expr *LHSExpr;
6757 const FieldDecl *Field;
6758 bool DuringInit;
6759 bool Failed = false;
6760 static const AccessKinds AccessKind = AK_Assign;
6761
6762 typedef bool result_type;
6763 bool failed() { return Failed; }
6764 bool found(APValue &Subobj, QualType SubobjType, APValue::LValueBase Base) {
6765 // We are supposed to perform no initialization but begin the lifetime of
6766 // the object. We interpret that as meaning to do what default
6767 // initialization of the object would do if all constructors involved were
6768 // trivial:
6769 // * All base, non-variant member, and array element subobjects' lifetimes
6770 // begin
6771 // * No variant members' lifetimes begin
6772 // * All scalar subobjects whose lifetimes begin have indeterminate values
6773 assert(SubobjType->isUnionType());
6774 if (declaresSameEntity(Subobj.getUnionField(), Field)) {
6775 // This union member is already active. If it's also in-lifetime, there's
6776 // nothing to do.
6777 if (Subobj.getUnionValue().hasValue())
6778 return true;
6779 } else if (DuringInit) {
6780 // We're currently in the process of initializing a different union
6781 // member. If we carried on, that initialization would attempt to
6782 // store to an inactive union member, resulting in undefined behavior.
6783 Info.FFDiag(LHSExpr,
6784 diag::note_constexpr_union_member_change_during_init);
6785 return false;
6786 }
6788 Failed = !handleDefaultInitValue(Field->getType(), Result);
6789 Subobj.setUnion(Field, Result);
6790 return true;
6791 }
6792 bool found(APSInt &Value, QualType SubobjType) {
6793 llvm_unreachable("wrong value kind for union object");
6794 }
6795 bool found(APFloat &Value, QualType SubobjType) {
6796 llvm_unreachable("wrong value kind for union object");
6797 }
6798};
6799} // end anonymous namespace
6800
6801const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
6802
6803/// Handle a builtin simple-assignment or a call to a trivial assignment
6804/// operator whose left-hand side might involve a union member access. If it
6805/// does, implicitly start the lifetime of any accessed union elements per
6806/// C++20 [class.union]5.
6807static bool MaybeHandleUnionActiveMemberChange(EvalInfo &Info,
6808 const Expr *LHSExpr,
6809 const LValue &LHS) {
6810 if (LHS.InvalidBase || LHS.Designator.Invalid)
6811 return false;
6812
6814 // C++ [class.union]p5:
6815 // define the set S(E) of subexpressions of E as follows:
6816 unsigned PathLength = LHS.Designator.Entries.size();
6817 for (const Expr *E = LHSExpr; E != nullptr;) {
6818 // -- If E is of the form A.B, S(E) contains the elements of S(A)...
6819 if (auto *ME = dyn_cast<MemberExpr>(E)) {
6820 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
6821 // Note that we can't implicitly start the lifetime of a reference,
6822 // so we don't need to proceed any further if we reach one.
6823 if (!FD || FD->getType()->isReferenceType())
6824 break;
6825
6826 // ... and also contains A.B if B names a union member ...
6827 if (FD->getParent()->isUnion()) {
6828 // ... of a non-class, non-array type, or of a class type with a
6829 // trivial default constructor that is not deleted, or an array of
6830 // such types.
6831 auto *RD =
6832 FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6833 if (!RD || RD->hasTrivialDefaultConstructor())
6834 UnionPathLengths.push_back({PathLength - 1, FD});
6835 }
6836
6837 E = ME->getBase();
6838 --PathLength;
6839 assert(declaresSameEntity(FD,
6840 LHS.Designator.Entries[PathLength]
6841 .getAsBaseOrMember().getPointer()));
6842
6843 // -- If E is of the form A[B] and is interpreted as a built-in array
6844 // subscripting operator, S(E) is [S(the array operand, if any)].
6845 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
6846 // Step over an ArrayToPointerDecay implicit cast.
6847 auto *Base = ASE->getBase()->IgnoreImplicit();
6848 if (!Base->getType()->isArrayType())
6849 break;
6850
6851 E = Base;
6852 --PathLength;
6853
6854 } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6855 // Step over a derived-to-base conversion.
6856 E = ICE->getSubExpr();
6857 if (ICE->getCastKind() == CK_NoOp)
6858 continue;
6859 if (ICE->getCastKind() != CK_DerivedToBase &&
6860 ICE->getCastKind() != CK_UncheckedDerivedToBase)
6861 break;
6862 // Walk path backwards as we walk up from the base to the derived class.
6863 for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
6864 if (Elt->isVirtual()) {
6865 // A class with virtual base classes never has a trivial default
6866 // constructor, so S(E) is empty in this case.
6867 E = nullptr;
6868 break;
6869 }
6870
6871 --PathLength;
6872 assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
6873 LHS.Designator.Entries[PathLength]
6874 .getAsBaseOrMember().getPointer()));
6875 }
6876
6877 // -- Otherwise, S(E) is empty.
6878 } else {
6879 break;
6880 }
6881 }
6882
6883 // Common case: no unions' lifetimes are started.
6884 if (UnionPathLengths.empty())
6885 return true;
6886
6887 // if modification of X [would access an inactive union member], an object
6888 // of the type of X is implicitly created
6889 CompleteObject Obj =
6890 findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
6891 if (!Obj)
6892 return false;
6893 for (std::pair<unsigned, const FieldDecl *> LengthAndField :
6894 llvm::reverse(UnionPathLengths)) {
6895 // Form a designator for the union object.
6896 SubobjectDesignator D = LHS.Designator;
6897 D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
6898
6899 bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) ==
6900 ConstructionPhase::AfterBases;
6901 StartLifetimeOfUnionMemberHandler StartLifetime{
6902 Info, LHSExpr, LengthAndField.second, DuringInit};
6903 if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
6904 return false;
6905 }
6906
6907 return true;
6908}
6909
6910static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg,
6911 CallRef Call, EvalInfo &Info, bool NonNull = false,
6912 APValue **EvaluatedArg = nullptr) {
6913 LValue LV;
6914 // Create the parameter slot and register its destruction. For a vararg
6915 // argument, create a temporary.
6916 // FIXME: For calling conventions that destroy parameters in the callee,
6917 // should we consider performing destruction when the function returns
6918 // instead?
6919 APValue &V = PVD ? Info.CurrentCall->createParam(Call, PVD, LV)
6920 : Info.CurrentCall->createTemporary(Arg, Arg->getType(),
6921 ScopeKind::Call, LV);
6922 if (!EvaluateInPlace(V, Info, LV, Arg))
6923 return false;
6924
6925 // Passing a null pointer to an __attribute__((nonnull)) parameter results in
6926 // undefined behavior, so is non-constant.
6927 if (NonNull && V.isLValue() && V.isNullPointer()) {
6928 Info.CCEDiag(Arg, diag::note_non_null_attribute_failed);
6929 return false;
6930 }
6931
6932 if (EvaluatedArg)
6933 *EvaluatedArg = &V;
6934
6935 return true;
6936}
6937
6938/// Evaluate the arguments to a function call.
6939static bool EvaluateArgs(ArrayRef<const Expr *> Args, CallRef Call,
6940 EvalInfo &Info, const FunctionDecl *Callee,
6941 bool RightToLeft = false,
6942 LValue *ObjectArg = nullptr) {
6943 bool Success = true;
6944 llvm::SmallBitVector ForbiddenNullArgs;
6945 if (Callee->hasAttr<NonNullAttr>()) {
6946 ForbiddenNullArgs.resize(Args.size());
6947 for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
6948 if (!Attr->args_size()) {
6949 ForbiddenNullArgs.set();
6950 break;
6951 } else
6952 for (auto Idx : Attr->args()) {
6953 unsigned ASTIdx = Idx.getASTIndex();
6954 if (ASTIdx >= Args.size())
6955 continue;
6956 ForbiddenNullArgs[ASTIdx] = true;
6957 }
6958 }
6959 }
6960 for (unsigned I = 0; I < Args.size(); I++) {
6961 unsigned Idx = RightToLeft ? Args.size() - I - 1 : I;
6962 const ParmVarDecl *PVD =
6963 Idx < Callee->getNumParams() ? Callee->getParamDecl(Idx) : nullptr;
6964 bool NonNull = !ForbiddenNullArgs.empty() && ForbiddenNullArgs[Idx];
6965 APValue *That = nullptr;
6966 if (!EvaluateCallArg(PVD, Args[Idx], Call, Info, NonNull, &That)) {
6967 // If we're checking for a potential constant expression, evaluate all
6968 // initializers even if some of them fail.
6969 if (!Info.noteFailure())
6970 return false;
6971 Success = false;
6972 }
6973 if (PVD && PVD->isExplicitObjectParameter() && That && That->isLValue())
6974 ObjectArg->setFrom(Info.Ctx, *That);
6975 }
6976 return Success;
6977}
6978
6979/// Perform a trivial copy from Param, which is the parameter of a copy or move
6980/// constructor or assignment operator.
6981static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param,
6982 const Expr *E, APValue &Result,
6983 bool CopyObjectRepresentation) {
6984 // Find the reference argument.
6985 CallStackFrame *Frame = Info.CurrentCall;
6986 APValue *RefValue = Info.getParamSlot(Frame->Arguments, Param);
6987 if (!RefValue) {
6988 Info.FFDiag(E);
6989 return false;
6990 }
6991
6992 // Copy out the contents of the RHS object.
6993 LValue RefLValue;
6994 RefLValue.setFrom(Info.Ctx, *RefValue);
6996 Info, E, Param->getType().getNonReferenceType(), RefLValue, Result,
6997 CopyObjectRepresentation);
6998}
6999
7000/// Evaluate a function call.
7002 const FunctionDecl *Callee,
7003 const LValue *ObjectArg, const Expr *E,
7004 ArrayRef<const Expr *> Args, CallRef Call,
7005 const Stmt *Body, EvalInfo &Info,
7006 APValue &Result, const LValue *ResultSlot) {
7007 if (!Info.CheckCallLimit(CallLoc))
7008 return false;
7009
7010 CallStackFrame Frame(Info, E->getSourceRange(), Callee, ObjectArg, E, Call);
7011
7012 // For a trivial copy or move assignment, perform an APValue copy. This is
7013 // essential for unions, where the operations performed by the assignment
7014 // operator cannot be represented as statements.
7015 //
7016 // Skip this for non-union classes with no fields; in that case, the defaulted
7017 // copy/move does not actually read the object.
7018 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
7019 if (MD && MD->isDefaulted() &&
7020 (MD->getParent()->isUnion() ||
7021 (MD->isTrivial() &&
7023 unsigned ExplicitOffset = MD->isExplicitObjectMemberFunction() ? 1 : 0;
7024 assert(ObjectArg &&
7026 APValue RHSValue;
7027 if (!handleTrivialCopy(Info, MD->getParamDecl(0), Args[0], RHSValue,
7028 MD->getParent()->isUnion()))
7029 return false;
7030
7031 LValue Obj;
7032 if (!handleAssignment(Info, Args[ExplicitOffset], *ObjectArg,
7034 RHSValue))
7035 return false;
7036 ObjectArg->moveInto(Result);
7037 return true;
7038 } else if (MD && isLambdaCallOperator(MD)) {
7039 // We're in a lambda; determine the lambda capture field maps unless we're
7040 // just constexpr checking a lambda's call operator. constexpr checking is
7041 // done before the captures have been added to the closure object (unless
7042 // we're inferring constexpr-ness), so we don't have access to them in this
7043 // case. But since we don't need the captures to constexpr check, we can
7044 // just ignore them.
7045 if (!Info.checkingPotentialConstantExpression())
7046 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
7047 Frame.LambdaThisCaptureField);
7048 }
7049
7050 StmtResult Ret = {Result, ResultSlot};
7051 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
7052 if (ESR == ESR_Succeeded) {
7053 if (Callee->getReturnType()->isVoidType())
7054 return true;
7055 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
7056 }
7057 return ESR == ESR_Returned;
7058}
7059
7060/// Evaluate a constructor call.
7061static bool HandleConstructorCall(const Expr *E, const LValue &This,
7062 CallRef Call,
7064 EvalInfo &Info, APValue &Result) {
7065 SourceLocation CallLoc = E->getExprLoc();
7066 if (!Info.CheckCallLimit(CallLoc))
7067 return false;
7068
7069 const CXXRecordDecl *RD = Definition->getParent();
7070 if (RD->getNumVBases()) {
7071 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
7072 return false;
7073 }
7074
7075 EvalInfo::EvaluatingConstructorRAII EvalObj(
7076 Info,
7077 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
7078 RD->getNumBases());
7079 CallStackFrame Frame(Info, E->getSourceRange(), Definition, &This, E, Call);
7080
7081 // FIXME: Creating an APValue just to hold a nonexistent return value is
7082 // wasteful.
7083 APValue RetVal;
7084 StmtResult Ret = {RetVal, nullptr};
7085
7086 // If it's a delegating constructor, delegate.
7087 if (Definition->isDelegatingConstructor()) {
7089 if ((*I)->getInit()->isValueDependent()) {
7090 if (!EvaluateDependentExpr((*I)->getInit(), Info))
7091 return false;
7092 } else {
7093 FullExpressionRAII InitScope(Info);
7094 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) ||
7095 !InitScope.destroy())
7096 return false;
7097 }
7098 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
7099 }
7100
7101 // For a trivial copy or move constructor, perform an APValue copy. This is
7102 // essential for unions (or classes with anonymous union members), where the
7103 // operations performed by the constructor cannot be represented by
7104 // ctor-initializers.
7105 //
7106 // Skip this for empty non-union classes; we should not perform an
7107 // lvalue-to-rvalue conversion on them because their copy constructor does not
7108 // actually read them.
7109 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
7110 (Definition->getParent()->isUnion() ||
7111 (Definition->isTrivial() &&
7113 return handleTrivialCopy(Info, Definition->getParamDecl(0), E, Result,
7114 Definition->getParent()->isUnion());
7115 }
7116
7117 // Reserve space for the struct members.
7118 if (!Result.hasValue()) {
7119 if (!RD->isUnion())
7121 RD->getNumFields());
7122 else
7123 // A union starts with no active member.
7124 Result = APValue((const FieldDecl*)nullptr);
7125 }
7126
7127 if (RD->isInvalidDecl()) return false;
7128 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7129
7130 // A scope for temporaries lifetime-extended by reference members.
7131 BlockScopeRAII LifetimeExtendedScope(Info);
7132
7133 bool Success = true;
7134 unsigned BasesSeen = 0;
7135#ifndef NDEBUG
7137#endif
7139 auto SkipToField = [&](FieldDecl *FD, bool Indirect) {
7140 // We might be initializing the same field again if this is an indirect
7141 // field initialization.
7142 if (FieldIt == RD->field_end() ||
7143 FieldIt->getFieldIndex() > FD->getFieldIndex()) {
7144 assert(Indirect && "fields out of order?");
7145 return;
7146 }
7147
7148 // Default-initialize any fields with no explicit initializer.
7149 for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
7150 assert(FieldIt != RD->field_end() && "missing field?");
7151 if (!FieldIt->isUnnamedBitField())
7153 FieldIt->getType(),
7154 Result.getStructField(FieldIt->getFieldIndex()));
7155 }
7156 ++FieldIt;
7157 };
7158 for (const auto *I : Definition->inits()) {
7159 LValue Subobject = This;
7160 LValue SubobjectParent = This;
7161 APValue *Value = &Result;
7162
7163 // Determine the subobject to initialize.
7164 FieldDecl *FD = nullptr;
7165 if (I->isBaseInitializer()) {
7166 QualType BaseType(I->getBaseClass(), 0);
7167#ifndef NDEBUG
7168 // Non-virtual base classes are initialized in the order in the class
7169 // definition. We have already checked for virtual base classes.
7170 assert(!BaseIt->isVirtual() && "virtual base for literal type");
7171 assert(Info.Ctx.hasSameUnqualifiedType(BaseIt->getType(), BaseType) &&
7172 "base class initializers not in expected order");
7173 ++BaseIt;
7174#endif
7175 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
7176 BaseType->getAsCXXRecordDecl(), &Layout))
7177 return false;
7178 Value = &Result.getStructBase(BasesSeen++);
7179 } else if ((FD = I->getMember())) {
7180 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
7181 return false;
7182 if (RD->isUnion()) {
7183 Result = APValue(FD);
7184 Value = &Result.getUnionValue();
7185 } else {
7186 SkipToField(FD, false);
7187 Value = &Result.getStructField(FD->getFieldIndex());
7188 }
7189 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
7190 // Walk the indirect field decl's chain to find the object to initialize,
7191 // and make sure we've initialized every step along it.
7192 auto IndirectFieldChain = IFD->chain();
7193 for (auto *C : IndirectFieldChain) {
7194 FD = cast<FieldDecl>(C);
7196 // Switch the union field if it differs. This happens if we had
7197 // preceding zero-initialization, and we're now initializing a union
7198 // subobject other than the first.
7199 // FIXME: In this case, the values of the other subobjects are
7200 // specified, since zero-initialization sets all padding bits to zero.
7201 if (!Value->hasValue() ||
7202 (Value->isUnion() &&
7203 !declaresSameEntity(Value->getUnionField(), FD))) {
7204 if (CD->isUnion())
7205 *Value = APValue(FD);
7206 else
7207 // FIXME: This immediately starts the lifetime of all members of
7208 // an anonymous struct. It would be preferable to strictly start
7209 // member lifetime in initialization order.
7210 Success &= handleDefaultInitValue(Info.Ctx.getCanonicalTagType(CD),
7211 *Value);
7212 }
7213 // Store Subobject as its parent before updating it for the last element
7214 // in the chain.
7215 if (C == IndirectFieldChain.back())
7216 SubobjectParent = Subobject;
7217 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
7218 return false;
7219 if (CD->isUnion())
7220 Value = &Value->getUnionValue();
7221 else {
7222 if (C == IndirectFieldChain.front() && !RD->isUnion())
7223 SkipToField(FD, true);
7224 Value = &Value->getStructField(FD->getFieldIndex());
7225 }
7226 }
7227 } else {
7228 llvm_unreachable("unknown base initializer kind");
7229 }
7230
7231 // Need to override This for implicit field initializers as in this case
7232 // This refers to innermost anonymous struct/union containing initializer,
7233 // not to currently constructed class.
7234 const Expr *Init = I->getInit();
7235 if (Init->isValueDependent()) {
7236 if (!EvaluateDependentExpr(Init, Info))
7237 return false;
7238 } else {
7239 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
7241 FullExpressionRAII InitScope(Info);
7242 if (FD && FD->getType()->isReferenceType() &&
7243 !FD->getType()->isFunctionReferenceType()) {
7244 LValue Result;
7246 *Value)) {
7247 if (!Info.noteFailure())
7248 return false;
7249 Success = false;
7250 }
7251 } else if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
7252 (FD && FD->isBitField() &&
7253 !truncateBitfieldValue(Info, Init, *Value, FD))) {
7254 // If we're checking for a potential constant expression, evaluate all
7255 // initializers even if some of them fail.
7256 if (!Info.noteFailure())
7257 return false;
7258 Success = false;
7259 }
7260 }
7261
7262 // This is the point at which the dynamic type of the object becomes this
7263 // class type.
7264 if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
7265 EvalObj.finishedConstructingBases();
7266 }
7267
7268 // Default-initialize any remaining fields.
7269 if (!RD->isUnion()) {
7270 for (; FieldIt != RD->field_end(); ++FieldIt) {
7271 if (!FieldIt->isUnnamedBitField())
7273 FieldIt->getType(),
7274 Result.getStructField(FieldIt->getFieldIndex()));
7275 }
7276 }
7277
7278 EvalObj.finishedConstructingFields();
7279
7280 return Success &&
7281 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed &&
7282 LifetimeExtendedScope.destroy();
7283}
7284
7285static bool HandleConstructorCall(const Expr *E, const LValue &This,
7288 EvalInfo &Info, APValue &Result) {
7289 CallScopeRAII CallScope(Info);
7290 CallRef Call = Info.CurrentCall->createCall(Definition);
7291 if (!EvaluateArgs(Args, Call, Info, Definition))
7292 return false;
7293
7294 return HandleConstructorCall(E, This, Call, Definition, Info, Result) &&
7295 CallScope.destroy();
7296}
7297
7298static bool HandleDestructionImpl(EvalInfo &Info, SourceRange CallRange,
7299 const LValue &This, APValue &Value,
7300 QualType T) {
7301 // Objects can only be destroyed while they're within their lifetimes.
7302 // FIXME: We have no representation for whether an object of type nullptr_t
7303 // is in its lifetime; it usually doesn't matter. Perhaps we should model it
7304 // as indeterminate instead?
7305 if (Value.isAbsent() && !T->isNullPtrType()) {
7306 APValue Printable;
7307 This.moveInto(Printable);
7308 Info.FFDiag(CallRange.getBegin(),
7309 diag::note_constexpr_destroy_out_of_lifetime)
7310 << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T));
7311 return false;
7312 }
7313
7314 // Invent an expression for location purposes.
7315 // FIXME: We shouldn't need to do this.
7316 OpaqueValueExpr LocE(CallRange.getBegin(), Info.Ctx.IntTy, VK_PRValue);
7317
7318 // For arrays, destroy elements right-to-left.
7319 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) {
7320 uint64_t Size = CAT->getZExtSize();
7321 QualType ElemT = CAT->getElementType();
7322
7323 if (!CheckArraySize(Info, CAT, CallRange.getBegin()))
7324 return false;
7325
7326 LValue ElemLV = This;
7327 ElemLV.addArray(Info, &LocE, CAT);
7328 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size))
7329 return false;
7330
7331 // Ensure that we have actual array elements available to destroy; the
7332 // destructors might mutate the value, so we can't run them on the array
7333 // filler.
7334 if (Size && Size > Value.getArrayInitializedElts())
7335 expandArray(Value, Value.getArraySize() - 1);
7336
7337 // The size of the array might have been reduced by
7338 // a placement new.
7339 for (Size = Value.getArraySize(); Size != 0; --Size) {
7340 APValue &Elem = Value.getArrayInitializedElt(Size - 1);
7341 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) ||
7342 !HandleDestructionImpl(Info, CallRange, ElemLV, Elem, ElemT))
7343 return false;
7344 }
7345
7346 // End the lifetime of this array now.
7347 Value = APValue();
7348 return true;
7349 }
7350
7351 const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
7352 if (!RD) {
7353 if (T.isDestructedType()) {
7354 Info.FFDiag(CallRange.getBegin(),
7355 diag::note_constexpr_unsupported_destruction)
7356 << T;
7357 return false;
7358 }
7359
7360 Value = APValue();
7361 return true;
7362 }
7363
7364 if (RD->getNumVBases()) {
7365 Info.FFDiag(CallRange.getBegin(), diag::note_constexpr_virtual_base) << RD;
7366 return false;
7367 }
7368
7369 const CXXDestructorDecl *DD = RD->getDestructor();
7370 if (!DD && !RD->hasTrivialDestructor()) {
7371 Info.FFDiag(CallRange.getBegin());
7372 return false;
7373 }
7374
7375 if (!DD || DD->isTrivial() ||
7376 (RD->isAnonymousStructOrUnion() && RD->isUnion())) {
7377 // A trivial destructor just ends the lifetime of the object. Check for
7378 // this case before checking for a body, because we might not bother
7379 // building a body for a trivial destructor. Note that it doesn't matter
7380 // whether the destructor is constexpr in this case; all trivial
7381 // destructors are constexpr.
7382 //
7383 // If an anonymous union would be destroyed, some enclosing destructor must
7384 // have been explicitly defined, and the anonymous union destruction should
7385 // have no effect.
7386 Value = APValue();
7387 return true;
7388 }
7389
7390 if (!Info.CheckCallLimit(CallRange.getBegin()))
7391 return false;
7392
7393 const FunctionDecl *Definition = nullptr;
7394 const Stmt *Body = DD->getBody(Definition);
7395
7396 if (!CheckConstexprFunction(Info, CallRange.getBegin(), DD, Definition, Body))
7397 return false;
7398
7399 CallStackFrame Frame(Info, CallRange, Definition, &This, /*CallExpr=*/nullptr,
7400 CallRef());
7401
7402 // We're now in the period of destruction of this object.
7403 unsigned BasesLeft = RD->getNumBases();
7404 EvalInfo::EvaluatingDestructorRAII EvalObj(
7405 Info,
7406 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries});
7407 if (!EvalObj.DidInsert) {
7408 // C++2a [class.dtor]p19:
7409 // the behavior is undefined if the destructor is invoked for an object
7410 // whose lifetime has ended
7411 // (Note that formally the lifetime ends when the period of destruction
7412 // begins, even though certain uses of the object remain valid until the
7413 // period of destruction ends.)
7414 Info.FFDiag(CallRange.getBegin(), diag::note_constexpr_double_destroy);
7415 return false;
7416 }
7417
7418 // FIXME: Creating an APValue just to hold a nonexistent return value is
7419 // wasteful.
7420 APValue RetVal;
7421 StmtResult Ret = {RetVal, nullptr};
7422 if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed)
7423 return false;
7424
7425 // A union destructor does not implicitly destroy its members.
7426 if (RD->isUnion())
7427 return true;
7428
7429 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7430
7431 // We don't have a good way to iterate fields in reverse, so collect all the
7432 // fields first and then walk them backwards.
7433 SmallVector<FieldDecl*, 16> Fields(RD->fields());
7434 for (const FieldDecl *FD : llvm::reverse(Fields)) {
7435 if (FD->isUnnamedBitField())
7436 continue;
7437
7438 LValue Subobject = This;
7439 if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout))
7440 return false;
7441
7442 APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex());
7443 if (!HandleDestructionImpl(Info, CallRange, Subobject, *SubobjectValue,
7444 FD->getType()))
7445 return false;
7446 }
7447
7448 if (BasesLeft != 0)
7449 EvalObj.startedDestroyingBases();
7450
7451 // Destroy base classes in reverse order.
7452 for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) {
7453 --BasesLeft;
7454
7455 QualType BaseType = Base.getType();
7456 LValue Subobject = This;
7457 if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD,
7458 BaseType->getAsCXXRecordDecl(), &Layout))
7459 return false;
7460
7461 APValue *SubobjectValue = &Value.getStructBase(BasesLeft);
7462 if (!HandleDestructionImpl(Info, CallRange, Subobject, *SubobjectValue,
7463 BaseType))
7464 return false;
7465 }
7466 assert(BasesLeft == 0 && "NumBases was wrong?");
7467
7468 // The period of destruction ends now. The object is gone.
7469 Value = APValue();
7470 return true;
7471}
7472
7473namespace {
7474struct DestroyObjectHandler {
7475 EvalInfo &Info;
7476 const Expr *E;
7477 const LValue &This;
7478 const AccessKinds AccessKind;
7479
7480 typedef bool result_type;
7481 bool failed() { return false; }
7482 bool found(APValue &Subobj, QualType SubobjType, APValue::LValueBase Base) {
7483 return HandleDestructionImpl(Info, E->getSourceRange(), This, Subobj,
7484 SubobjType);
7485 }
7486 bool found(APSInt &Value, QualType SubobjType) {
7487 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
7488 return false;
7489 }
7490 bool found(APFloat &Value, QualType SubobjType) {
7491 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
7492 return false;
7493 }
7494};
7495}
7496
7497/// Perform a destructor or pseudo-destructor call on the given object, which
7498/// might in general not be a complete object.
7499static bool HandleDestruction(EvalInfo &Info, const Expr *E,
7500 const LValue &This, QualType ThisType) {
7501 CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType);
7502 DestroyObjectHandler Handler = {Info, E, This, AK_Destroy};
7503 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
7504}
7505
7506/// Destroy and end the lifetime of the given complete object.
7507static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
7509 QualType T) {
7510 // If we've had an unmodeled side-effect, we can't rely on mutable state
7511 // (such as the object we're about to destroy) being correct.
7512 if (Info.EvalStatus.HasSideEffects)
7513 return false;
7514
7515 LValue LV;
7516 LV.set({LVBase});
7517 return HandleDestructionImpl(Info, Loc, LV, Value, T);
7518}
7519
7520/// Perform a call to 'operator new' or to `__builtin_operator_new'.
7521static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E,
7522 LValue &Result) {
7523 if (Info.checkingPotentialConstantExpression() ||
7524 Info.SpeculativeEvaluationDepth)
7525 return false;
7526
7527 // This is permitted only within a call to std::allocator<T>::allocate.
7528 auto Caller = Info.getStdAllocatorCaller("allocate");
7529 if (!Caller) {
7530 Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20
7531 ? diag::note_constexpr_new_untyped
7532 : diag::note_constexpr_new);
7533 return false;
7534 }
7535
7536 QualType ElemType = Caller.ElemType;
7537 if (ElemType->isIncompleteType() || ElemType->isFunctionType()) {
7538 Info.FFDiag(E->getExprLoc(),
7539 diag::note_constexpr_new_not_complete_object_type)
7540 << (ElemType->isIncompleteType() ? 0 : 1) << ElemType;
7541 return false;
7542 }
7543
7544 APSInt ByteSize;
7545 if (!EvaluateInteger(E->getArg(0), ByteSize, Info))
7546 return false;
7547 bool IsNothrow = false;
7548 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) {
7549 EvaluateIgnoredValue(Info, E->getArg(I));
7550 IsNothrow |= E->getType()->isNothrowT();
7551 }
7552
7553 CharUnits ElemSize;
7554 if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize))
7555 return false;
7556 APInt Size, Remainder;
7557 APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity());
7558 APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder);
7559 if (Remainder != 0) {
7560 // This likely indicates a bug in the implementation of 'std::allocator'.
7561 Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size)
7562 << ByteSize << APSInt(ElemSizeAP, true) << ElemType;
7563 return false;
7564 }
7565
7566 if (!Info.CheckArraySize(E->getBeginLoc(), ByteSize.getActiveBits(),
7567 Size.getZExtValue(), /*Diag=*/!IsNothrow)) {
7568 if (IsNothrow) {
7569 Result.setNull(Info.Ctx, E->getType());
7570 return true;
7571 }
7572 return false;
7573 }
7574
7575 QualType AllocType = Info.Ctx.getConstantArrayType(
7576 ElemType, Size, nullptr, ArraySizeModifier::Normal, 0);
7577 APValue *Val = Info.createHeapAlloc(Caller.Call, AllocType, Result);
7578 *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue());
7579 Result.addArray(Info, E, cast<ConstantArrayType>(AllocType));
7580 return true;
7581}
7582
7584 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
7585 if (CXXDestructorDecl *DD = RD->getDestructor())
7586 return DD->isVirtual();
7587 return false;
7588}
7589
7591 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
7592 if (CXXDestructorDecl *DD = RD->getDestructor())
7593 return DD->isVirtual() ? DD->getOperatorDelete() : nullptr;
7594 return nullptr;
7595}
7596
7597/// Check that the given object is a suitable pointer to a heap allocation that
7598/// still exists and is of the right kind for the purpose of a deletion.
7599///
7600/// On success, returns the heap allocation to deallocate. On failure, produces
7601/// a diagnostic and returns std::nullopt.
7602static std::optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E,
7603 const LValue &Pointer,
7604 DynAlloc::Kind DeallocKind) {
7605 auto PointerAsString = [&] {
7606 return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy);
7607 };
7608
7609 DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>();
7610 if (!DA) {
7611 Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc)
7612 << PointerAsString();
7613 if (Pointer.Base)
7614 NoteLValueLocation(Info, Pointer.Base);
7615 return std::nullopt;
7616 }
7617
7618 std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
7619 if (!Alloc) {
7620 Info.FFDiag(E, diag::note_constexpr_double_delete);
7621 return std::nullopt;
7622 }
7623
7624 if (DeallocKind != (*Alloc)->getKind()) {
7625 QualType AllocType = Pointer.Base.getDynamicAllocType();
7626 Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch)
7627 << DeallocKind << (*Alloc)->getKind() << AllocType;
7628 NoteLValueLocation(Info, Pointer.Base);
7629 return std::nullopt;
7630 }
7631
7632 bool Subobject = false;
7633 if (DeallocKind == DynAlloc::New) {
7634 Subobject = Pointer.Designator.MostDerivedPathLength != 0 ||
7635 Pointer.Designator.isOnePastTheEnd();
7636 } else {
7637 Subobject = Pointer.Designator.Entries.size() != 1 ||
7638 Pointer.Designator.Entries[0].getAsArrayIndex() != 0;
7639 }
7640 if (Subobject) {
7641 Info.FFDiag(E, diag::note_constexpr_delete_subobject)
7642 << PointerAsString() << Pointer.Designator.isOnePastTheEnd();
7643 return std::nullopt;
7644 }
7645
7646 return Alloc;
7647}
7648
7649// Perform a call to 'operator delete' or '__builtin_operator_delete'.
7650static bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) {
7651 if (Info.checkingPotentialConstantExpression() ||
7652 Info.SpeculativeEvaluationDepth)
7653 return false;
7654
7655 // This is permitted only within a call to std::allocator<T>::deallocate.
7656 if (!Info.getStdAllocatorCaller("deallocate")) {
7657 Info.FFDiag(E->getExprLoc());
7658 return true;
7659 }
7660
7661 LValue Pointer;
7662 if (!EvaluatePointer(E->getArg(0), Pointer, Info))
7663 return false;
7664 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
7665 EvaluateIgnoredValue(Info, E->getArg(I));
7666
7667 if (Pointer.Designator.Invalid)
7668 return false;
7669
7670 // Deleting a null pointer would have no effect, but it's not permitted by
7671 // std::allocator<T>::deallocate's contract.
7672 if (Pointer.isNullPointer()) {
7673 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_deallocate_null);
7674 return true;
7675 }
7676
7677 if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator))
7678 return false;
7679
7680 Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>());
7681 return true;
7682}
7683
7684//===----------------------------------------------------------------------===//
7685// Generic Evaluation
7686//===----------------------------------------------------------------------===//
7687namespace {
7688
7689class BitCastBuffer {
7690 // FIXME: We're going to need bit-level granularity when we support
7691 // bit-fields.
7692 // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
7693 // we don't support a host or target where that is the case. Still, we should
7694 // use a more generic type in case we ever do.
7695 SmallVector<std::optional<unsigned char>, 32> Bytes;
7696
7697 static_assert(std::numeric_limits<unsigned char>::digits >= 8,
7698 "Need at least 8 bit unsigned char");
7699
7700 bool TargetIsLittleEndian;
7701
7702public:
7703 BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
7704 : Bytes(Width.getQuantity()),
7705 TargetIsLittleEndian(TargetIsLittleEndian) {}
7706
7707 [[nodiscard]] bool readObject(CharUnits Offset, CharUnits Width,
7708 SmallVectorImpl<unsigned char> &Output) const {
7709 for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
7710 // If a byte of an integer is uninitialized, then the whole integer is
7711 // uninitialized.
7712 if (!Bytes[I.getQuantity()])
7713 return false;
7714 Output.push_back(*Bytes[I.getQuantity()]);
7715 }
7716 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
7717 std::reverse(Output.begin(), Output.end());
7718 return true;
7719 }
7720
7721 void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
7722 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
7723 std::reverse(Input.begin(), Input.end());
7724
7725 size_t Index = 0;
7726 for (unsigned char Byte : Input) {
7727 assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
7728 Bytes[Offset.getQuantity() + Index] = Byte;
7729 ++Index;
7730 }
7731 }
7732
7733 size_t size() { return Bytes.size(); }
7734};
7735
7736/// Traverse an APValue to produce an BitCastBuffer, emulating how the current
7737/// target would represent the value at runtime.
7738class APValueToBufferConverter {
7739 EvalInfo &Info;
7740 BitCastBuffer Buffer;
7741 const CastExpr *BCE;
7742
7743 APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
7744 const CastExpr *BCE)
7745 : Info(Info),
7746 Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
7747 BCE(BCE) {}
7748
7749 bool visit(const APValue &Val, QualType Ty) {
7750 return visit(Val, Ty, CharUnits::fromQuantity(0));
7751 }
7752
7753 // Write out Val with type Ty into Buffer starting at Offset.
7754 bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
7755 assert((size_t)Offset.getQuantity() <= Buffer.size());
7756
7757 // As a special case, nullptr_t has an indeterminate value.
7758 if (Ty->isNullPtrType())
7759 return true;
7760
7761 // Dig through Src to find the byte at SrcOffset.
7762 switch (Val.getKind()) {
7764 case APValue::None:
7765 return true;
7766
7767 case APValue::Int:
7768 return visitInt(Val.getInt(), Ty, Offset);
7769 case APValue::Float:
7770 return visitFloat(Val.getFloat(), Ty, Offset);
7771 case APValue::Array:
7772 return visitArray(Val, Ty, Offset);
7773 case APValue::Struct:
7774 return visitRecord(Val, Ty, Offset);
7775 case APValue::Vector:
7776 return visitVector(Val, Ty, Offset);
7777
7780 return visitComplex(Val, Ty, Offset);
7782 // FIXME: We should support these.
7783
7784 case APValue::LValue:
7785 case APValue::Matrix:
7786 case APValue::Union:
7789 Info.FFDiag(BCE->getBeginLoc(),
7790 diag::note_constexpr_bit_cast_unsupported_type)
7791 << Ty;
7792 return false;
7793 }
7794 }
7795 llvm_unreachable("Unhandled APValue::ValueKind");
7796 }
7797
7798 bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
7799 const RecordDecl *RD = Ty->getAsRecordDecl();
7800 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7801
7802 // Visit the base classes.
7803 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
7804 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
7805 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
7806 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
7807 const APValue &Base = Val.getStructBase(I);
7808
7809 // Can happen in error cases.
7810 if (!Base.isStruct())
7811 return false;
7812
7813 if (!visitRecord(Base, BS.getType(),
7814 Layout.getBaseClassOffset(BaseDecl) + Offset))
7815 return false;
7816 }
7817 }
7818
7819 // Visit the fields.
7820 unsigned FieldIdx = 0;
7821 for (FieldDecl *FD : RD->fields()) {
7822 if (FD->isBitField()) {
7823 Info.FFDiag(BCE->getBeginLoc(),
7824 diag::note_constexpr_bit_cast_unsupported_bitfield);
7825 return false;
7826 }
7827
7828 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
7829
7830 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
7831 "only bit-fields can have sub-char alignment");
7832 CharUnits FieldOffset =
7833 Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
7834 QualType FieldTy = FD->getType();
7835 if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
7836 return false;
7837 ++FieldIdx;
7838 }
7839
7840 return true;
7841 }
7842
7843 bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
7844 const auto *CAT =
7845 dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
7846 if (!CAT)
7847 return false;
7848
7849 CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
7850 unsigned NumInitializedElts = Val.getArrayInitializedElts();
7851 unsigned ArraySize = Val.getArraySize();
7852 // First, initialize the initialized elements.
7853 for (unsigned I = 0; I != NumInitializedElts; ++I) {
7854 const APValue &SubObj = Val.getArrayInitializedElt(I);
7855 if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
7856 return false;
7857 }
7858
7859 // Next, initialize the rest of the array using the filler.
7860 if (Val.hasArrayFiller()) {
7861 const APValue &Filler = Val.getArrayFiller();
7862 for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
7863 if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
7864 return false;
7865 }
7866 }
7867
7868 return true;
7869 }
7870
7871 bool visitComplex(const APValue &Val, QualType Ty, CharUnits Offset) {
7872 const ComplexType *ComplexTy = Ty->castAs<ComplexType>();
7873 QualType EltTy = ComplexTy->getElementType();
7874 CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
7875 bool IsInt = Val.isComplexInt();
7876
7877 if (IsInt) {
7878 if (!visitInt(Val.getComplexIntReal(), EltTy,
7879 Offset + (0 * EltSizeChars)))
7880 return false;
7881 if (!visitInt(Val.getComplexIntImag(), EltTy,
7882 Offset + (1 * EltSizeChars)))
7883 return false;
7884 } else {
7885 if (!visitFloat(Val.getComplexFloatReal(), EltTy,
7886 Offset + (0 * EltSizeChars)))
7887 return false;
7888 if (!visitFloat(Val.getComplexFloatImag(), EltTy,
7889 Offset + (1 * EltSizeChars)))
7890 return false;
7891 }
7892
7893 return true;
7894 }
7895
7896 bool visitVector(const APValue &Val, QualType Ty, CharUnits Offset) {
7897 const VectorType *VTy = Ty->castAs<VectorType>();
7898 QualType EltTy = VTy->getElementType();
7899 unsigned NElts = VTy->getNumElements();
7900
7901 if (VTy->isPackedVectorBoolType(Info.Ctx)) {
7902 // Special handling for OpenCL bool vectors:
7903 // Since these vectors are stored as packed bits, but we can't write
7904 // individual bits to the BitCastBuffer, we'll buffer all of the elements
7905 // together into an appropriately sized APInt and write them all out at
7906 // once. Because we don't accept vectors where NElts * EltSize isn't a
7907 // multiple of the char size, there will be no padding space, so we don't
7908 // have to worry about writing data which should have been left
7909 // uninitialized.
7910 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
7911
7912 llvm::APInt Res = llvm::APInt::getZero(NElts);
7913 for (unsigned I = 0; I < NElts; ++I) {
7914 const llvm::APSInt &EltAsInt = Val.getVectorElt(I).getInt();
7915 assert(EltAsInt.isUnsigned() && EltAsInt.getBitWidth() == 1 &&
7916 "bool vector element must be 1-bit unsigned integer!");
7917
7918 Res.insertBits(EltAsInt, BigEndian ? (NElts - I - 1) : I);
7919 }
7920
7921 SmallVector<uint8_t, 8> Bytes(NElts / 8);
7922 llvm::StoreIntToMemory(Res, &*Bytes.begin(), NElts / 8);
7923 Buffer.writeObject(Offset, Bytes);
7924 } else {
7925 // Iterate over each of the elements and write them out to the buffer at
7926 // the appropriate offset.
7927 CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
7928 for (unsigned I = 0; I < NElts; ++I) {
7929 if (!visit(Val.getVectorElt(I), EltTy, Offset + I * EltSizeChars))
7930 return false;
7931 }
7932 }
7933
7934 return true;
7935 }
7936
7937 bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
7938 APSInt AdjustedVal = Val;
7939 unsigned Width = AdjustedVal.getBitWidth();
7940 if (Ty->isBooleanType()) {
7941 Width = Info.Ctx.getTypeSize(Ty);
7942 AdjustedVal = AdjustedVal.extend(Width);
7943 }
7944
7945 SmallVector<uint8_t, 8> Bytes(Width / 8);
7946 llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8);
7947 Buffer.writeObject(Offset, Bytes);
7948 return true;
7949 }
7950
7951 bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
7952 APSInt AsInt(Val.bitcastToAPInt());
7953 return visitInt(AsInt, Ty, Offset);
7954 }
7955
7956public:
7957 static std::optional<BitCastBuffer>
7958 convert(EvalInfo &Info, const APValue &Src, const CastExpr *BCE) {
7959 CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
7960 APValueToBufferConverter Converter(Info, DstSize, BCE);
7961 if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
7962 return std::nullopt;
7963 return Converter.Buffer;
7964 }
7965};
7966
7967/// Write an BitCastBuffer into an APValue.
7968class BufferToAPValueConverter {
7969 EvalInfo &Info;
7970 const BitCastBuffer &Buffer;
7971 const CastExpr *BCE;
7972
7973 BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
7974 const CastExpr *BCE)
7975 : Info(Info), Buffer(Buffer), BCE(BCE) {}
7976
7977 // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
7978 // with an invalid type, so anything left is a deficiency on our part (FIXME).
7979 // Ideally this will be unreachable.
7980 std::nullopt_t unsupportedType(QualType Ty) {
7981 Info.FFDiag(BCE->getBeginLoc(),
7982 diag::note_constexpr_bit_cast_unsupported_type)
7983 << Ty;
7984 return std::nullopt;
7985 }
7986
7987 std::nullopt_t unrepresentableValue(QualType Ty, const APSInt &Val) {
7988 Info.FFDiag(BCE->getBeginLoc(),
7989 diag::note_constexpr_bit_cast_unrepresentable_value)
7990 << Ty << toString(Val, /*Radix=*/10);
7991 return std::nullopt;
7992 }
7993
7994 std::optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
7995 const EnumType *EnumSugar = nullptr) {
7996 if (T->isNullPtrType()) {
7997 uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
7998 return APValue((Expr *)nullptr,
7999 /*Offset=*/CharUnits::fromQuantity(NullValue),
8000 APValue::NoLValuePath{}, /*IsNullPtr=*/true);
8001 }
8002
8003 CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
8004
8005 // Work around floating point types that contain unused padding bytes. This
8006 // is really just `long double` on x86, which is the only fundamental type
8007 // with padding bytes.
8008 if (T->isRealFloatingType()) {
8009 const llvm::fltSemantics &Semantics =
8010 Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
8011 unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics);
8012 assert(NumBits % 8 == 0);
8013 CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8);
8014 if (NumBytes != SizeOf)
8015 SizeOf = NumBytes;
8016 }
8017
8018 SmallVector<uint8_t, 8> Bytes;
8019 if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
8020 // If this is std::byte or unsigned char, then its okay to store an
8021 // indeterminate value.
8022 bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
8023 bool IsUChar =
8024 !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
8025 T->isSpecificBuiltinType(BuiltinType::Char_U));
8026 if (!IsStdByte && !IsUChar) {
8027 QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
8028 Info.FFDiag(BCE->getExprLoc(),
8029 diag::note_constexpr_bit_cast_indet_dest)
8030 << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
8031 return std::nullopt;
8032 }
8033
8035 }
8036
8037 APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
8038 llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
8039
8040 if (T->isIntegralOrEnumerationType()) {
8041 Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
8042
8043 unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0));
8044 if (IntWidth != Val.getBitWidth()) {
8045 APSInt Truncated = Val.trunc(IntWidth);
8046 if (Truncated.extend(Val.getBitWidth()) != Val)
8047 return unrepresentableValue(QualType(T, 0), Val);
8048 Val = Truncated;
8049 }
8050
8051 return APValue(Val);
8052 }
8053
8054 if (T->isRealFloatingType()) {
8055 const llvm::fltSemantics &Semantics =
8056 Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
8057 return APValue(APFloat(Semantics, Val));
8058 }
8059
8060 return unsupportedType(QualType(T, 0));
8061 }
8062
8063 std::optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
8064 const RecordDecl *RD = RTy->getAsRecordDecl();
8065 if (RD->isInvalidDecl())
8066 return std::nullopt;
8067 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
8068
8069 unsigned NumBases = 0;
8070 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
8071 NumBases = CXXRD->getNumBases();
8072
8073 APValue ResultVal(APValue::UninitStruct(), NumBases, RD->getNumFields());
8074
8075 // Visit the base classes.
8076 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
8077 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
8078 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
8079 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
8080
8081 std::optional<APValue> SubObj = visitType(
8082 BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
8083 if (!SubObj)
8084 return std::nullopt;
8085 ResultVal.getStructBase(I) = *SubObj;
8086 }
8087 }
8088
8089 // Visit the fields.
8090 unsigned FieldIdx = 0;
8091 for (FieldDecl *FD : RD->fields()) {
8092 // FIXME: We don't currently support bit-fields. A lot of the logic for
8093 // this is in CodeGen, so we need to factor it around.
8094 if (FD->isBitField()) {
8095 Info.FFDiag(BCE->getBeginLoc(),
8096 diag::note_constexpr_bit_cast_unsupported_bitfield);
8097 return std::nullopt;
8098 }
8099
8100 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
8101 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
8102
8103 CharUnits FieldOffset =
8104 CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
8105 Offset;
8106 QualType FieldTy = FD->getType();
8107 std::optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
8108 if (!SubObj)
8109 return std::nullopt;
8110 ResultVal.getStructField(FieldIdx) = *SubObj;
8111 ++FieldIdx;
8112 }
8113
8114 return ResultVal;
8115 }
8116
8117 std::optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
8118 QualType RepresentationType =
8119 Ty->getDecl()->getDefinitionOrSelf()->getIntegerType();
8120 assert(!RepresentationType.isNull() &&
8121 "enum forward decl should be caught by Sema");
8122 const auto *AsBuiltin =
8123 RepresentationType.getCanonicalType()->castAs<BuiltinType>();
8124 // Recurse into the underlying type. Treat std::byte transparently as
8125 // unsigned char.
8126 return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
8127 }
8128
8129 std::optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
8130 size_t Size = Ty->getLimitedSize();
8131 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
8132
8133 APValue ArrayValue(APValue::UninitArray(), Size, Size);
8134 for (size_t I = 0; I != Size; ++I) {
8135 std::optional<APValue> ElementValue =
8136 visitType(Ty->getElementType(), Offset + I * ElementWidth);
8137 if (!ElementValue)
8138 return std::nullopt;
8139 ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
8140 }
8141
8142 return ArrayValue;
8143 }
8144
8145 std::optional<APValue> visit(const ComplexType *Ty, CharUnits Offset) {
8146 QualType ElementType = Ty->getElementType();
8147 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(ElementType);
8148 bool IsInt = ElementType->isIntegerType();
8149
8150 std::optional<APValue> Values[2];
8151 for (unsigned I = 0; I != 2; ++I) {
8152 Values[I] = visitType(Ty->getElementType(), Offset + I * ElementWidth);
8153 if (!Values[I])
8154 return std::nullopt;
8155 }
8156
8157 if (IsInt)
8158 return APValue(Values[0]->getInt(), Values[1]->getInt());
8159 return APValue(Values[0]->getFloat(), Values[1]->getFloat());
8160 }
8161
8162 std::optional<APValue> visit(const VectorType *VTy, CharUnits Offset) {
8163 QualType EltTy = VTy->getElementType();
8164 unsigned NElts = VTy->getNumElements();
8165 unsigned EltSize =
8166 VTy->isPackedVectorBoolType(Info.Ctx) ? 1 : Info.Ctx.getTypeSize(EltTy);
8167
8168 SmallVector<APValue, 4> Elts;
8169 Elts.reserve(NElts);
8170 if (VTy->isPackedVectorBoolType(Info.Ctx)) {
8171 // Special handling for OpenCL bool vectors:
8172 // Since these vectors are stored as packed bits, but we can't read
8173 // individual bits from the BitCastBuffer, we'll buffer all of the
8174 // elements together into an appropriately sized APInt and write them all
8175 // out at once. Because we don't accept vectors where NElts * EltSize
8176 // isn't a multiple of the char size, there will be no padding space, so
8177 // we don't have to worry about reading any padding data which didn't
8178 // actually need to be accessed.
8179 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
8180
8181 SmallVector<uint8_t, 8> Bytes;
8182 Bytes.reserve(NElts / 8);
8183 if (!Buffer.readObject(Offset, CharUnits::fromQuantity(NElts / 8), Bytes))
8184 return std::nullopt;
8185
8186 APSInt SValInt(NElts, true);
8187 llvm::LoadIntFromMemory(SValInt, &*Bytes.begin(), Bytes.size());
8188
8189 for (unsigned I = 0; I < NElts; ++I) {
8190 llvm::APInt Elt =
8191 SValInt.extractBits(1, (BigEndian ? NElts - I - 1 : I) * EltSize);
8192 Elts.emplace_back(
8193 APSInt(std::move(Elt), !EltTy->isSignedIntegerType()));
8194 }
8195 } else {
8196 // Iterate over each of the elements and read them from the buffer at
8197 // the appropriate offset.
8198 CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
8199 for (unsigned I = 0; I < NElts; ++I) {
8200 std::optional<APValue> EltValue =
8201 visitType(EltTy, Offset + I * EltSizeChars);
8202 if (!EltValue)
8203 return std::nullopt;
8204 Elts.push_back(std::move(*EltValue));
8205 }
8206 }
8207
8208 return APValue(Elts.data(), Elts.size());
8209 }
8210
8211 std::optional<APValue> visit(const Type *Ty, CharUnits Offset) {
8212 return unsupportedType(QualType(Ty, 0));
8213 }
8214
8215 std::optional<APValue> visitType(QualType Ty, CharUnits Offset) {
8216 QualType Can = Ty.getCanonicalType();
8217
8218 switch (Can->getTypeClass()) {
8219#define TYPE(Class, Base) \
8220 case Type::Class: \
8221 return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
8222#define ABSTRACT_TYPE(Class, Base)
8223#define NON_CANONICAL_TYPE(Class, Base) \
8224 case Type::Class: \
8225 llvm_unreachable("non-canonical type should be impossible!");
8226#define DEPENDENT_TYPE(Class, Base) \
8227 case Type::Class: \
8228 llvm_unreachable( \
8229 "dependent types aren't supported in the constant evaluator!");
8230#define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base) \
8231 case Type::Class: \
8232 llvm_unreachable("either dependent or not canonical!");
8233#include "clang/AST/TypeNodes.inc"
8234 }
8235 llvm_unreachable("Unhandled Type::TypeClass");
8236 }
8237
8238public:
8239 // Pull out a full value of type DstType.
8240 static std::optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
8241 const CastExpr *BCE) {
8242 BufferToAPValueConverter Converter(Info, Buffer, BCE);
8243 return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
8244 }
8245};
8246
8247static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
8248 QualType Ty, EvalInfo *Info,
8249 const ASTContext &Ctx,
8250 bool CheckingDest) {
8251 Ty = Ty.getCanonicalType();
8252
8253 auto diag = [&](int Reason) {
8254 if (Info)
8255 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
8256 << CheckingDest << (Reason == 4) << Reason;
8257 return false;
8258 };
8259 auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
8260 if (Info)
8261 Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
8262 << NoteTy << Construct << Ty;
8263 return false;
8264 };
8265
8266 if (Ty->isUnionType())
8267 return diag(0);
8268 if (Ty->isPointerType())
8269 return diag(1);
8270 if (Ty->isMemberPointerType())
8271 return diag(2);
8272 if (Ty.isVolatileQualified())
8273 return diag(3);
8274
8275 if (RecordDecl *Record = Ty->getAsRecordDecl()) {
8276 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
8277 for (CXXBaseSpecifier &BS : CXXRD->bases())
8278 if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
8279 CheckingDest))
8280 return note(1, BS.getType(), BS.getBeginLoc());
8281 }
8282 for (FieldDecl *FD : Record->fields()) {
8283 if (FD->getType()->isReferenceType())
8284 return diag(4);
8285 if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
8286 CheckingDest))
8287 return note(0, FD->getType(), FD->getBeginLoc());
8288 }
8289 }
8290
8291 if (Ty->isArrayType() &&
8292 !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
8293 Info, Ctx, CheckingDest))
8294 return false;
8295
8296 if (const auto *VTy = Ty->getAs<VectorType>()) {
8297 QualType EltTy = VTy->getElementType();
8298 unsigned NElts = VTy->getNumElements();
8299 unsigned EltSize =
8300 VTy->isPackedVectorBoolType(Ctx) ? 1 : Ctx.getTypeSize(EltTy);
8301
8302 if ((NElts * EltSize) % Ctx.getCharWidth() != 0) {
8303 // The vector's size in bits is not a multiple of the target's byte size,
8304 // so its layout is unspecified. For now, we'll simply treat these cases
8305 // as unsupported (this should only be possible with OpenCL bool vectors
8306 // whose element count isn't a multiple of the byte size).
8307 if (Info)
8308 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_vector)
8309 << QualType(VTy, 0) << EltSize << NElts << Ctx.getCharWidth();
8310 return false;
8311 }
8312
8313 if (EltTy->isRealFloatingType() &&
8314 &Ctx.getFloatTypeSemantics(EltTy) == &APFloat::x87DoubleExtended()) {
8315 // The layout for x86_fp80 vectors seems to be handled very inconsistently
8316 // by both clang and LLVM, so for now we won't allow bit_casts involving
8317 // it in a constexpr context.
8318 if (Info)
8319 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_unsupported_type)
8320 << EltTy;
8321 return false;
8322 }
8323 }
8324
8325 return true;
8326}
8327
8328static bool checkBitCastConstexprEligibility(EvalInfo *Info,
8329 const ASTContext &Ctx,
8330 const CastExpr *BCE) {
8331 bool DestOK = checkBitCastConstexprEligibilityType(
8332 BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
8333 bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
8334 BCE->getBeginLoc(),
8335 BCE->getSubExpr()->getType(), Info, Ctx, false);
8336 return SourceOK;
8337}
8338
8339static bool handleRValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
8340 const APValue &SourceRValue,
8341 const CastExpr *BCE) {
8342 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
8343 "no host or target supports non 8-bit chars");
8344
8345 if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
8346 return false;
8347
8348 // Read out SourceValue into a char buffer.
8349 std::optional<BitCastBuffer> Buffer =
8350 APValueToBufferConverter::convert(Info, SourceRValue, BCE);
8351 if (!Buffer)
8352 return false;
8353
8354 // Write out the buffer into a new APValue.
8355 std::optional<APValue> MaybeDestValue =
8356 BufferToAPValueConverter::convert(Info, *Buffer, BCE);
8357 if (!MaybeDestValue)
8358 return false;
8359
8360 DestValue = std::move(*MaybeDestValue);
8361 return true;
8362}
8363
8364static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
8365 APValue &SourceValue,
8366 const CastExpr *BCE) {
8367 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
8368 "no host or target supports non 8-bit chars");
8369 assert(SourceValue.isLValue() &&
8370 "LValueToRValueBitcast requires an lvalue operand!");
8371
8372 LValue SourceLValue;
8373 APValue SourceRValue;
8374 SourceLValue.setFrom(Info.Ctx, SourceValue);
8376 Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,
8377 SourceRValue, /*WantObjectRepresentation=*/true))
8378 return false;
8379
8380 return handleRValueToRValueBitCast(Info, DestValue, SourceRValue, BCE);
8381}
8382
8383template <class Derived>
8384class ExprEvaluatorBase
8385 : public ConstStmtVisitor<Derived, bool> {
8386private:
8387 Derived &getDerived() { return static_cast<Derived&>(*this); }
8388 bool DerivedSuccess(const APValue &V, const Expr *E) {
8389 return getDerived().Success(V, E);
8390 }
8391 bool DerivedZeroInitialization(const Expr *E) {
8392 return getDerived().ZeroInitialization(E);
8393 }
8394
8395 // Check whether a conditional operator with a non-constant condition is a
8396 // potential constant expression. If neither arm is a potential constant
8397 // expression, then the conditional operator is not either.
8398 template<typename ConditionalOperator>
8399 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
8400 assert(Info.checkingPotentialConstantExpression());
8401
8402 // Speculatively evaluate both arms.
8403 SmallVector<PartialDiagnosticAt, 8> Diag;
8404 {
8405 SpeculativeEvaluationRAII Speculate(Info, &Diag);
8406 StmtVisitorTy::Visit(E->getFalseExpr());
8407 if (Diag.empty())
8408 return;
8409 }
8410
8411 {
8412 SpeculativeEvaluationRAII Speculate(Info, &Diag);
8413 Diag.clear();
8414 Info.EvalStatus.DiagEmitted = false;
8415 StmtVisitorTy::Visit(E->getTrueExpr());
8416 if (Diag.empty())
8417 return;
8418 }
8419
8420 Error(E, diag::note_constexpr_conditional_never_const);
8421 }
8422
8423
8424 template<typename ConditionalOperator>
8425 bool HandleConditionalOperator(const ConditionalOperator *E) {
8426 bool BoolResult;
8427 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
8428 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
8429 CheckPotentialConstantConditional(E);
8430 return false;
8431 }
8432 if (Info.noteFailure()) {
8433 StmtVisitorTy::Visit(E->getTrueExpr());
8434 StmtVisitorTy::Visit(E->getFalseExpr());
8435 }
8436 return false;
8437 }
8438
8439 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
8440 return StmtVisitorTy::Visit(EvalExpr);
8441 }
8442
8443protected:
8444 EvalInfo &Info;
8445 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
8446 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
8447
8448 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
8449 return Info.CCEDiag(E, D);
8450 }
8451
8452 bool ZeroInitialization(const Expr *E) { return Error(E); }
8453
8454 bool IsConstantEvaluatedBuiltinCall(const CallExpr *E) {
8455 unsigned BuiltinOp = E->getBuiltinCallee();
8456 return BuiltinOp != 0 &&
8457 Info.Ctx.BuiltinInfo.isConstantEvaluated(BuiltinOp);
8458 }
8459
8460public:
8461 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
8462
8463 EvalInfo &getEvalInfo() { return Info; }
8464
8465 /// Report an evaluation error. This should only be called when an error is
8466 /// first discovered. When propagating an error, just return false.
8467 bool Error(const Expr *E, diag::kind D) {
8468 Info.FFDiag(E, D) << E->getSourceRange();
8469 return false;
8470 }
8471 bool Error(const Expr *E) {
8472 return Error(E, diag::note_invalid_subexpr_in_const_expr);
8473 }
8474
8475 bool VisitStmt(const Stmt *) {
8476 llvm_unreachable("Expression evaluator should not be called on stmts");
8477 }
8478 bool VisitExpr(const Expr *E) {
8479 return Error(E);
8480 }
8481
8482 bool VisitEmbedExpr(const EmbedExpr *E) {
8483 const auto It = E->begin();
8484 return StmtVisitorTy::Visit(*It);
8485 }
8486
8487 bool VisitPredefinedExpr(const PredefinedExpr *E) {
8488 return StmtVisitorTy::Visit(E->getFunctionName());
8489 }
8490 bool VisitConstantExpr(const ConstantExpr *E) {
8491 if (E->hasAPValueResult())
8492 return DerivedSuccess(E->getAPValueResult(), E);
8493
8494 return StmtVisitorTy::Visit(E->getSubExpr());
8495 }
8496
8497 bool VisitParenExpr(const ParenExpr *E)
8498 { return StmtVisitorTy::Visit(E->getSubExpr()); }
8499 bool VisitUnaryExtension(const UnaryOperator *E)
8500 { return StmtVisitorTy::Visit(E->getSubExpr()); }
8501 bool VisitUnaryPlus(const UnaryOperator *E)
8502 { return StmtVisitorTy::Visit(E->getSubExpr()); }
8503 bool VisitChooseExpr(const ChooseExpr *E)
8504 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
8505 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
8506 { return StmtVisitorTy::Visit(E->getResultExpr()); }
8507 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
8508 { return StmtVisitorTy::Visit(E->getReplacement()); }
8509 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
8510 TempVersionRAII RAII(*Info.CurrentCall);
8511 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
8512 return StmtVisitorTy::Visit(E->getExpr());
8513 }
8514 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
8515 TempVersionRAII RAII(*Info.CurrentCall);
8516 // The initializer may not have been parsed yet, or might be erroneous.
8517 if (!E->getExpr())
8518 return Error(E);
8519 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
8520 return StmtVisitorTy::Visit(E->getExpr());
8521 }
8522
8523 bool VisitExprWithCleanups(const ExprWithCleanups *E) {
8524 FullExpressionRAII Scope(Info);
8525 return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy();
8526 }
8527
8528 // Temporaries are registered when created, so we don't care about
8529 // CXXBindTemporaryExpr.
8530 bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
8531 return StmtVisitorTy::Visit(E->getSubExpr());
8532 }
8533
8534 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
8535 CCEDiag(E, diag::note_constexpr_invalid_cast)
8536 << diag::ConstexprInvalidCastKind::Reinterpret;
8537 return static_cast<Derived*>(this)->VisitCastExpr(E);
8538 }
8539 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
8540 if (!Info.Ctx.getLangOpts().CPlusPlus20)
8541 CCEDiag(E, diag::note_constexpr_invalid_cast)
8542 << diag::ConstexprInvalidCastKind::Dynamic;
8543 return static_cast<Derived*>(this)->VisitCastExpr(E);
8544 }
8545 bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
8546 return static_cast<Derived*>(this)->VisitCastExpr(E);
8547 }
8548
8549 bool VisitBinaryOperator(const BinaryOperator *E) {
8550 switch (E->getOpcode()) {
8551 default:
8552 return Error(E);
8553
8554 case BO_Comma:
8555 VisitIgnoredValue(E->getLHS());
8556 return StmtVisitorTy::Visit(E->getRHS());
8557
8558 case BO_PtrMemD:
8559 case BO_PtrMemI: {
8560 LValue Obj;
8561 if (!HandleMemberPointerAccess(Info, E, Obj))
8562 return false;
8564 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
8565 return false;
8566 return DerivedSuccess(Result, E);
8567 }
8568 }
8569 }
8570
8571 bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) {
8572 return StmtVisitorTy::Visit(E->getSemanticForm());
8573 }
8574
8575 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
8576 // Evaluate and cache the common expression. We treat it as a temporary,
8577 // even though it's not quite the same thing.
8578 LValue CommonLV;
8579 if (!Evaluate(Info.CurrentCall->createTemporary(
8580 E->getOpaqueValue(),
8581 getStorageType(Info.Ctx, E->getOpaqueValue()),
8582 ScopeKind::FullExpression, CommonLV),
8583 Info, E->getCommon()))
8584 return false;
8585
8586 return HandleConditionalOperator(E);
8587 }
8588
8589 bool VisitConditionalOperator(const ConditionalOperator *E) {
8590 bool IsBcpCall = false;
8591 // If the condition (ignoring parens) is a __builtin_constant_p call,
8592 // the result is a constant expression if it can be folded without
8593 // side-effects. This is an important GNU extension. See GCC PR38377
8594 // for discussion.
8595 if (const CallExpr *CallCE =
8596 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
8597 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
8598 IsBcpCall = true;
8599
8600 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
8601 // constant expression; we can't check whether it's potentially foldable.
8602 // FIXME: We should instead treat __builtin_constant_p as non-constant if
8603 // it would return 'false' in this mode.
8604 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
8605 return false;
8606
8607 FoldConstant Fold(Info, IsBcpCall);
8608 if (!HandleConditionalOperator(E)) {
8609 Fold.keepDiagnostics();
8610 return false;
8611 }
8612
8613 return true;
8614 }
8615
8616 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
8617 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E);
8618 Value && !Value->isAbsent())
8619 return DerivedSuccess(*Value, E);
8620
8621 const Expr *Source = E->getSourceExpr();
8622 if (!Source)
8623 return Error(E);
8624 if (Source == E) {
8625 assert(0 && "OpaqueValueExpr recursively refers to itself");
8626 return Error(E);
8627 }
8628 return StmtVisitorTy::Visit(Source);
8629 }
8630
8631 bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
8632 for (const Expr *SemE : E->semantics()) {
8633 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
8634 // FIXME: We can't handle the case where an OpaqueValueExpr is also the
8635 // result expression: there could be two different LValues that would
8636 // refer to the same object in that case, and we can't model that.
8637 if (SemE == E->getResultExpr())
8638 return Error(E);
8639
8640 // Unique OVEs get evaluated if and when we encounter them when
8641 // emitting the rest of the semantic form, rather than eagerly.
8642 if (OVE->isUnique())
8643 continue;
8644
8645 LValue LV;
8646 if (!Evaluate(Info.CurrentCall->createTemporary(
8647 OVE, getStorageType(Info.Ctx, OVE),
8648 ScopeKind::FullExpression, LV),
8649 Info, OVE->getSourceExpr()))
8650 return false;
8651 } else if (SemE == E->getResultExpr()) {
8652 if (!StmtVisitorTy::Visit(SemE))
8653 return false;
8654 } else {
8655 if (!EvaluateIgnoredValue(Info, SemE))
8656 return false;
8657 }
8658 }
8659 return true;
8660 }
8661
8662 bool VisitCallExpr(const CallExpr *E) {
8664 if (!handleCallExpr(E, Result, nullptr))
8665 return false;
8666 return DerivedSuccess(Result, E);
8667 }
8668
8669 bool handleCallExpr(const CallExpr *E, APValue &Result,
8670 const LValue *ResultSlot) {
8671 CallScopeRAII CallScope(Info);
8672
8673 const Expr *Callee = E->getCallee()->IgnoreParens();
8674 QualType CalleeType = Callee->getType();
8675
8676 const FunctionDecl *FD = nullptr;
8677 LValue *This = nullptr, ObjectArg;
8678 auto Args = ArrayRef(E->getArgs(), E->getNumArgs());
8679 bool HasQualifier = false;
8680
8681 CallRef Call;
8682
8683 // Extract function decl and 'this' pointer from the callee.
8684 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
8685 const CXXMethodDecl *Member = nullptr;
8686 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
8687 // Explicit bound member calls, such as x.f() or p->g();
8688 if (!EvaluateObjectArgument(Info, ME->getBase(), ObjectArg))
8689 return false;
8690 Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
8691 if (!Member)
8692 return Error(Callee);
8693 This = &ObjectArg;
8694 HasQualifier = ME->hasQualifier();
8695 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
8696 // Indirect bound member calls ('.*' or '->*').
8697 const ValueDecl *D =
8698 HandleMemberPointerAccess(Info, BE, ObjectArg, false);
8699 if (!D)
8700 return false;
8701 Member = dyn_cast<CXXMethodDecl>(D);
8702 if (!Member)
8703 return Error(Callee);
8704 This = &ObjectArg;
8705 } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
8706 if (!Info.getLangOpts().CPlusPlus20)
8707 Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
8708 return EvaluateObjectArgument(Info, PDE->getBase(), ObjectArg) &&
8709 HandleDestruction(Info, PDE, ObjectArg, PDE->getDestroyedType());
8710 } else
8711 return Error(Callee);
8712 FD = Member;
8713 } else if (CalleeType->isFunctionPointerType()) {
8714 LValue CalleeLV;
8715 if (!EvaluatePointer(Callee, CalleeLV, Info))
8716 return false;
8717
8718 if (!CalleeLV.getLValueOffset().isZero())
8719 return Error(Callee);
8720 if (CalleeLV.isNullPointer()) {
8721 Info.FFDiag(Callee, diag::note_constexpr_null_callee)
8722 << const_cast<Expr *>(Callee);
8723 return false;
8724 }
8725 FD = dyn_cast_or_null<FunctionDecl>(
8726 CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>());
8727 if (!FD)
8728 return Error(Callee);
8729 // Don't call function pointers which have been cast to some other type.
8730 // Per DR (no number yet), the caller and callee can differ in noexcept.
8731 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
8732 CalleeType->getPointeeType(), FD->getType())) {
8733 return Error(E);
8734 }
8735
8736 // For an (overloaded) assignment expression, evaluate the RHS before the
8737 // LHS.
8738 auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
8739 if (OCE && OCE->isAssignmentOp()) {
8740 assert(Args.size() == 2 && "wrong number of arguments in assignment");
8741 Call = Info.CurrentCall->createCall(FD);
8742 bool HasThis = false;
8743 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
8744 HasThis = MD->isImplicitObjectMemberFunction();
8745 if (!EvaluateArgs(HasThis ? Args.slice(1) : Args, Call, Info, FD,
8746 /*RightToLeft=*/true, &ObjectArg))
8747 return false;
8748 }
8749
8750 // Overloaded operator calls to member functions are represented as normal
8751 // calls with '*this' as the first argument.
8752 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8753 if (MD &&
8754 (MD->isImplicitObjectMemberFunction() || (OCE && MD->isStatic()))) {
8755 // FIXME: When selecting an implicit conversion for an overloaded
8756 // operator delete, we sometimes try to evaluate calls to conversion
8757 // operators without a 'this' parameter!
8758 if (Args.empty())
8759 return Error(E);
8760
8761 if (!EvaluateObjectArgument(Info, Args[0], ObjectArg))
8762 return false;
8763
8764 // If we are calling a static operator, the 'this' argument needs to be
8765 // ignored after being evaluated.
8766 if (MD->isInstance())
8767 This = &ObjectArg;
8768
8769 // If this is syntactically a simple assignment using a trivial
8770 // assignment operator, start the lifetimes of union members as needed,
8771 // per C++20 [class.union]5.
8772 if (Info.getLangOpts().CPlusPlus20 && OCE &&
8773 OCE->getOperator() == OO_Equal && MD->isTrivial() &&
8774 !MaybeHandleUnionActiveMemberChange(Info, Args[0], ObjectArg))
8775 return false;
8776
8777 Args = Args.slice(1);
8778 } else if (MD && MD->isLambdaStaticInvoker()) {
8779 // Map the static invoker for the lambda back to the call operator.
8780 // Conveniently, we don't have to slice out the 'this' argument (as is
8781 // being done for the non-static case), since a static member function
8782 // doesn't have an implicit argument passed in.
8783 const CXXRecordDecl *ClosureClass = MD->getParent();
8784 assert(
8785 ClosureClass->captures().empty() &&
8786 "Number of captures must be zero for conversion to function-ptr");
8787
8788 const CXXMethodDecl *LambdaCallOp =
8789 ClosureClass->getLambdaCallOperator();
8790
8791 // Set 'FD', the function that will be called below, to the call
8792 // operator. If the closure object represents a generic lambda, find
8793 // the corresponding specialization of the call operator.
8794
8795 if (ClosureClass->isGenericLambda()) {
8796 assert(MD->isFunctionTemplateSpecialization() &&
8797 "A generic lambda's static-invoker function must be a "
8798 "template specialization");
8799 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
8800 FunctionTemplateDecl *CallOpTemplate =
8801 LambdaCallOp->getDescribedFunctionTemplate();
8802 void *InsertPos = nullptr;
8803 FunctionDecl *CorrespondingCallOpSpecialization =
8804 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
8805 assert(CorrespondingCallOpSpecialization &&
8806 "We must always have a function call operator specialization "
8807 "that corresponds to our static invoker specialization");
8808 assert(isa<CXXMethodDecl>(CorrespondingCallOpSpecialization));
8809 FD = CorrespondingCallOpSpecialization;
8810 } else
8811 FD = LambdaCallOp;
8813 if (FD->getDeclName().isAnyOperatorNew()) {
8814 LValue Ptr;
8815 if (!HandleOperatorNewCall(Info, E, Ptr))
8816 return false;
8817 Ptr.moveInto(Result);
8818 return CallScope.destroy();
8819 } else {
8820 return HandleOperatorDeleteCall(Info, E) && CallScope.destroy();
8821 }
8822 }
8823 } else
8824 return Error(E);
8825
8826 // Evaluate the arguments now if we've not already done so.
8827 if (!Call) {
8828 Call = Info.CurrentCall->createCall(FD);
8829 if (!EvaluateArgs(Args, Call, Info, FD, /*RightToLeft*/ false,
8830 &ObjectArg))
8831 return false;
8832 }
8833
8834 SmallVector<QualType, 4> CovariantAdjustmentPath;
8835 if (This) {
8836 auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
8837 if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
8838 // Perform virtual dispatch, if necessary.
8839 FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
8840 CovariantAdjustmentPath);
8841 if (!FD)
8842 return false;
8843 } else if (NamedMember && NamedMember->isImplicitObjectMemberFunction()) {
8844 // Check that the 'this' pointer points to an object of the right type.
8845 // FIXME: If this is an assignment operator call, we may need to change
8846 // the active union member before we check this.
8847 if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
8848 return false;
8849 }
8850 }
8851
8852 // Destructor calls are different enough that they have their own codepath.
8853 if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
8854 assert(This && "no 'this' pointer for destructor call");
8855 return HandleDestruction(Info, E, *This,
8856 Info.Ctx.getCanonicalTagType(DD->getParent())) &&
8857 CallScope.destroy();
8858 }
8859
8860 const FunctionDecl *Definition = nullptr;
8861 Stmt *Body = FD->getBody(Definition);
8862 SourceLocation Loc = E->getExprLoc();
8863
8864 // Treat the object argument as `this` when evaluating defaulted
8865 // special menmber functions
8867 This = &ObjectArg;
8868
8869 if (!CheckConstexprFunction(Info, Loc, FD, Definition, Body) ||
8870 !HandleFunctionCall(Loc, Definition, This, E, Args, Call, Body, Info,
8871 Result, ResultSlot))
8872 return false;
8873
8874 if (!CovariantAdjustmentPath.empty() &&
8876 CovariantAdjustmentPath))
8877 return false;
8878
8879 return CallScope.destroy();
8880 }
8881
8882 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
8883 return StmtVisitorTy::Visit(E->getInitializer());
8884 }
8885 bool VisitInitListExpr(const InitListExpr *E) {
8886 if (E->getNumInits() == 0)
8887 return DerivedZeroInitialization(E);
8888 if (E->getNumInits() == 1)
8889 return StmtVisitorTy::Visit(E->getInit(0));
8890 return Error(E);
8891 }
8892 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
8893 return DerivedZeroInitialization(E);
8894 }
8895 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
8896 return DerivedZeroInitialization(E);
8897 }
8898 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
8899 return DerivedZeroInitialization(E);
8900 }
8901
8902 /// A member expression where the object is a prvalue is itself a prvalue.
8903 bool VisitMemberExpr(const MemberExpr *E) {
8904 assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
8905 "missing temporary materialization conversion");
8906 assert(!E->isArrow() && "missing call to bound member function?");
8907
8908 APValue Val;
8909 if (!Evaluate(Val, Info, E->getBase()))
8910 return false;
8911
8912 QualType BaseTy = E->getBase()->getType();
8913
8914 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
8915 if (!FD) return Error(E);
8916 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
8917 assert(BaseTy->castAsCanonical<RecordType>()->getDecl() ==
8918 FD->getParent()->getCanonicalDecl() &&
8919 "record / field mismatch");
8920
8921 // Note: there is no lvalue base here. But this case should only ever
8922 // happen in C or in C++98, where we cannot be evaluating a constexpr
8923 // constructor, which is the only case the base matters.
8924 CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
8925 SubobjectDesignator Designator(BaseTy);
8926 Designator.addDeclUnchecked(FD);
8927
8929 return extractSubobject(Info, E, Obj, Designator, Result) &&
8930 DerivedSuccess(Result, E);
8931 }
8932
8933 bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) {
8934 APValue Val;
8935 if (!Evaluate(Val, Info, E->getBase()))
8936 return false;
8937
8938 if (Val.isVector()) {
8939 SmallVector<uint32_t, 4> Indices;
8940 E->getEncodedElementAccess(Indices);
8941 if (Indices.size() == 1) {
8942 // Return scalar.
8943 return DerivedSuccess(Val.getVectorElt(Indices[0]), E);
8944 } else {
8945 // Construct new APValue vector.
8946 SmallVector<APValue, 4> Elts;
8947 for (unsigned I = 0; I < Indices.size(); ++I) {
8948 Elts.push_back(Val.getVectorElt(Indices[I]));
8949 }
8950 APValue VecResult(Elts.data(), Indices.size());
8951 return DerivedSuccess(VecResult, E);
8952 }
8953 }
8954
8955 return false;
8956 }
8957
8958 bool VisitCastExpr(const CastExpr *E) {
8959 switch (E->getCastKind()) {
8960 default:
8961 break;
8962
8963 case CK_AtomicToNonAtomic: {
8964 APValue AtomicVal;
8965 // This does not need to be done in place even for class/array types:
8966 // atomic-to-non-atomic conversion implies copying the object
8967 // representation.
8968 if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
8969 return false;
8970 return DerivedSuccess(AtomicVal, E);
8971 }
8972
8973 case CK_NoOp:
8974 case CK_UserDefinedConversion:
8975 return StmtVisitorTy::Visit(E->getSubExpr());
8976
8977 case CK_HLSLArrayRValue: {
8978 const Expr *SubExpr = E->getSubExpr();
8979 if (!SubExpr->isGLValue()) {
8980 APValue Val;
8981 if (!Evaluate(Val, Info, SubExpr))
8982 return false;
8983 return DerivedSuccess(Val, E);
8984 }
8985
8986 LValue LVal;
8987 if (!EvaluateLValue(SubExpr, LVal, Info))
8988 return false;
8989 APValue RVal;
8990 // Note, we use the subexpression's type in order to retain cv-qualifiers.
8991 if (!handleLValueToRValueConversion(Info, E, SubExpr->getType(), LVal,
8992 RVal))
8993 return false;
8994 return DerivedSuccess(RVal, E);
8995 }
8996 case CK_LValueToRValue: {
8997 LValue LVal;
8998 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
8999 return false;
9000 APValue RVal;
9001 // Note, we use the subexpression's type in order to retain cv-qualifiers.
9003 LVal, RVal))
9004 return false;
9005 return DerivedSuccess(RVal, E);
9006 }
9007 case CK_LValueToRValueBitCast: {
9008 APValue DestValue, SourceValue;
9009 if (!Evaluate(SourceValue, Info, E->getSubExpr()))
9010 return false;
9011 if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
9012 return false;
9013 return DerivedSuccess(DestValue, E);
9014 }
9015
9016 case CK_AddressSpaceConversion: {
9017 APValue Value;
9018 if (!Evaluate(Value, Info, E->getSubExpr()))
9019 return false;
9020 return DerivedSuccess(Value, E);
9021 }
9022 }
9023
9024 return Error(E);
9025 }
9026
9027 bool VisitUnaryPostInc(const UnaryOperator *UO) {
9028 return VisitUnaryPostIncDec(UO);
9029 }
9030 bool VisitUnaryPostDec(const UnaryOperator *UO) {
9031 return VisitUnaryPostIncDec(UO);
9032 }
9033 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
9034 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9035 return Error(UO);
9036
9037 LValue LVal;
9038 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
9039 return false;
9040 APValue RVal;
9041 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
9042 UO->isIncrementOp(), &RVal))
9043 return false;
9044 return DerivedSuccess(RVal, UO);
9045 }
9046
9047 bool VisitStmtExpr(const StmtExpr *E) {
9048 // We will have checked the full-expressions inside the statement expression
9049 // when they were completed, and don't need to check them again now.
9050 llvm::SaveAndRestore NotCheckingForUB(Info.CheckingForUndefinedBehavior,
9051 false);
9052
9053 const CompoundStmt *CS = E->getSubStmt();
9054 if (CS->body_empty())
9055 return true;
9056
9057 BlockScopeRAII Scope(Info);
9059 BE = CS->body_end();
9060 /**/; ++BI) {
9061 if (BI + 1 == BE) {
9062 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
9063 if (!FinalExpr) {
9064 Info.FFDiag((*BI)->getBeginLoc(),
9065 diag::note_constexpr_stmt_expr_unsupported);
9066 return false;
9067 }
9068 return this->Visit(FinalExpr) && Scope.destroy();
9069 }
9070
9072 StmtResult Result = { ReturnValue, nullptr };
9073 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
9074 if (ESR != ESR_Succeeded) {
9075 // FIXME: If the statement-expression terminated due to 'return',
9076 // 'break', or 'continue', it would be nice to propagate that to
9077 // the outer statement evaluation rather than bailing out.
9078 if (ESR != ESR_Failed)
9079 Info.FFDiag((*BI)->getBeginLoc(),
9080 diag::note_constexpr_stmt_expr_unsupported);
9081 return false;
9082 }
9083 }
9084
9085 llvm_unreachable("Return from function from the loop above.");
9086 }
9087
9088 bool VisitPackIndexingExpr(const PackIndexingExpr *E) {
9089 return StmtVisitorTy::Visit(E->getSelectedExpr());
9090 }
9091
9092 /// Visit a value which is evaluated, but whose value is ignored.
9093 void VisitIgnoredValue(const Expr *E) {
9094 EvaluateIgnoredValue(Info, E);
9095 }
9096
9097 /// Potentially visit a MemberExpr's base expression.
9098 void VisitIgnoredBaseExpression(const Expr *E) {
9099 // While MSVC doesn't evaluate the base expression, it does diagnose the
9100 // presence of side-effecting behavior.
9101 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
9102 return;
9103 VisitIgnoredValue(E);
9104 }
9105};
9106
9107} // namespace
9108
9109//===----------------------------------------------------------------------===//
9110// Common base class for lvalue and temporary evaluation.
9111//===----------------------------------------------------------------------===//
9112namespace {
9113template<class Derived>
9114class LValueExprEvaluatorBase
9115 : public ExprEvaluatorBase<Derived> {
9116protected:
9117 LValue &Result;
9118 bool InvalidBaseOK;
9119 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
9120 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
9121
9122 bool Success(APValue::LValueBase B) {
9123 Result.set(B);
9124 return true;
9125 }
9126
9127 bool evaluatePointer(const Expr *E, LValue &Result) {
9128 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
9129 }
9130
9131public:
9132 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
9133 : ExprEvaluatorBaseTy(Info), Result(Result),
9134 InvalidBaseOK(InvalidBaseOK) {}
9135
9136 bool Success(const APValue &V, const Expr *E) {
9137 Result.setFrom(this->Info.Ctx, V);
9138 return true;
9139 }
9140
9141 bool VisitMemberExpr(const MemberExpr *E) {
9142 // Handle non-static data members.
9143 QualType BaseTy;
9144 bool EvalOK;
9145 if (E->isArrow()) {
9146 EvalOK = evaluatePointer(E->getBase(), Result);
9147 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
9148 } else if (E->getBase()->isPRValue()) {
9149 assert(E->getBase()->getType()->isRecordType());
9150 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
9151 BaseTy = E->getBase()->getType();
9152 } else {
9153 EvalOK = this->Visit(E->getBase());
9154 BaseTy = E->getBase()->getType();
9155 }
9156 if (!EvalOK) {
9157 if (!InvalidBaseOK)
9158 return false;
9159 Result.setInvalid(E);
9160 return true;
9161 }
9162
9163 const ValueDecl *MD = E->getMemberDecl();
9164 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
9165 assert(BaseTy->castAsCanonical<RecordType>()->getDecl() ==
9166 FD->getParent()->getCanonicalDecl() &&
9167 "record / field mismatch");
9168 (void)BaseTy;
9169 if (!HandleLValueMember(this->Info, E, Result, FD))
9170 return false;
9171 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
9172 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
9173 return false;
9174 } else
9175 return this->Error(E);
9176
9177 if (MD->getType()->isReferenceType()) {
9178 APValue RefValue;
9179 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
9180 RefValue))
9181 return false;
9182 return Success(RefValue, E);
9183 }
9184 return true;
9185 }
9186
9187 bool VisitBinaryOperator(const BinaryOperator *E) {
9188 switch (E->getOpcode()) {
9189 default:
9190 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9191
9192 case BO_PtrMemD:
9193 case BO_PtrMemI:
9194 return HandleMemberPointerAccess(this->Info, E, Result);
9195 }
9196 }
9197
9198 bool VisitCastExpr(const CastExpr *E) {
9199 switch (E->getCastKind()) {
9200 default:
9201 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9202
9203 case CK_DerivedToBase:
9204 case CK_UncheckedDerivedToBase:
9205 if (!this->Visit(E->getSubExpr()))
9206 return false;
9207
9208 // Now figure out the necessary offset to add to the base LV to get from
9209 // the derived class to the base class.
9210 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
9211 Result);
9212 }
9213 }
9214};
9215}
9216
9217//===----------------------------------------------------------------------===//
9218// LValue Evaluation
9219//
9220// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
9221// function designators (in C), decl references to void objects (in C), and
9222// temporaries (if building with -Wno-address-of-temporary).
9223//
9224// LValue evaluation produces values comprising a base expression of one of the
9225// following types:
9226// - Declarations
9227// * VarDecl
9228// * FunctionDecl
9229// - Literals
9230// * CompoundLiteralExpr in C (and in global scope in C++)
9231// * StringLiteral
9232// * PredefinedExpr
9233// * ObjCStringLiteralExpr
9234// * ObjCEncodeExpr
9235// * AddrLabelExpr
9236// * BlockExpr
9237// * CallExpr for a MakeStringConstant builtin
9238// - typeid(T) expressions, as TypeInfoLValues
9239// - Locals and temporaries
9240// * MaterializeTemporaryExpr
9241// * Any Expr, with a CallIndex indicating the function in which the temporary
9242// was evaluated, for cases where the MaterializeTemporaryExpr is missing
9243// from the AST (FIXME).
9244// * A MaterializeTemporaryExpr that has static storage duration, with no
9245// CallIndex, for a lifetime-extended temporary.
9246// * The ConstantExpr that is currently being evaluated during evaluation of an
9247// immediate invocation.
9248// plus an offset in bytes.
9249//===----------------------------------------------------------------------===//
9250namespace {
9251class LValueExprEvaluator
9252 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
9253public:
9254 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
9255 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
9256
9257 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
9258 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
9259
9260 bool VisitCallExpr(const CallExpr *E);
9261 bool VisitDeclRefExpr(const DeclRefExpr *E);
9262 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
9263 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
9264 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
9265 bool VisitMemberExpr(const MemberExpr *E);
9266 bool VisitStringLiteral(const StringLiteral *E) {
9267 return Success(
9268 APValue::LValueBase(E, 0, Info.Ctx.getNextStringLiteralVersion()));
9269 }
9270 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
9271 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
9272 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
9273 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
9274 bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E);
9275 bool VisitUnaryDeref(const UnaryOperator *E);
9276 bool VisitUnaryReal(const UnaryOperator *E);
9277 bool VisitUnaryImag(const UnaryOperator *E);
9278 bool VisitUnaryPreInc(const UnaryOperator *UO) {
9279 return VisitUnaryPreIncDec(UO);
9280 }
9281 bool VisitUnaryPreDec(const UnaryOperator *UO) {
9282 return VisitUnaryPreIncDec(UO);
9283 }
9284 bool VisitBinAssign(const BinaryOperator *BO);
9285 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
9286
9287 bool VisitCastExpr(const CastExpr *E) {
9288 switch (E->getCastKind()) {
9289 default:
9290 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
9291
9292 case CK_LValueBitCast:
9293 this->CCEDiag(E, diag::note_constexpr_invalid_cast)
9294 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
9295 << Info.Ctx.getLangOpts().CPlusPlus;
9296 if (!Visit(E->getSubExpr()))
9297 return false;
9298 Result.Designator.setInvalid();
9299 return true;
9300
9301 case CK_BaseToDerived:
9302 if (!Visit(E->getSubExpr()))
9303 return false;
9304 return HandleBaseToDerivedCast(Info, E, Result);
9305
9306 case CK_Dynamic:
9307 if (!Visit(E->getSubExpr()))
9308 return false;
9310 }
9311 }
9312};
9313} // end anonymous namespace
9314
9315/// Get an lvalue to a field of a lambda's closure type.
9316static bool HandleLambdaCapture(EvalInfo &Info, const Expr *E, LValue &Result,
9317 const CXXMethodDecl *MD, const FieldDecl *FD,
9318 bool LValueToRValueConversion) {
9319 // Static lambda function call operators can't have captures. We already
9320 // diagnosed this, so bail out here.
9321 if (MD->isStatic()) {
9322 assert(Info.CurrentCall->This == nullptr &&
9323 "This should not be set for a static call operator");
9324 return false;
9325 }
9326
9327 // Start with 'Result' referring to the complete closure object...
9329 // Self may be passed by reference or by value.
9330 const ParmVarDecl *Self = MD->getParamDecl(0);
9331 if (Self->getType()->isReferenceType()) {
9332 APValue *RefValue = Info.getParamSlot(Info.CurrentCall->Arguments, Self);
9333 if (!RefValue->allowConstexprUnknown() || RefValue->hasValue())
9334 Result.setFrom(Info.Ctx, *RefValue);
9335 } else {
9336 const ParmVarDecl *VD = Info.CurrentCall->Arguments.getOrigParam(Self);
9337 CallStackFrame *Frame =
9338 Info.getCallFrameAndDepth(Info.CurrentCall->Arguments.CallIndex)
9339 .first;
9340 unsigned Version = Info.CurrentCall->Arguments.Version;
9341 Result.set({VD, Frame->Index, Version});
9342 }
9343 } else
9344 Result = *Info.CurrentCall->This;
9345
9346 // ... then update it to refer to the field of the closure object
9347 // that represents the capture.
9348 if (!HandleLValueMember(Info, E, Result, FD))
9349 return false;
9350
9351 // And if the field is of reference type (or if we captured '*this' by
9352 // reference), update 'Result' to refer to what
9353 // the field refers to.
9354 if (LValueToRValueConversion) {
9355 APValue RVal;
9356 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result, RVal))
9357 return false;
9358 Result.setFrom(Info.Ctx, RVal);
9359 }
9360 return true;
9361}
9362
9363/// Evaluate an expression as an lvalue. This can be legitimately called on
9364/// expressions which are not glvalues, in three cases:
9365/// * function designators in C, and
9366/// * "extern void" objects
9367/// * @selector() expressions in Objective-C
9368static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
9369 bool InvalidBaseOK) {
9370 assert(!E->isValueDependent());
9371 assert(E->isGLValue() || E->getType()->isFunctionType() ||
9373 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
9374}
9375
9376bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
9377 const ValueDecl *D = E->getDecl();
9378
9379 // If we are within a lambda's call operator, check whether the 'VD' referred
9380 // to within 'E' actually represents a lambda-capture that maps to a
9381 // data-member/field within the closure object, and if so, evaluate to the
9382 // field or what the field refers to.
9383 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
9385 // We don't always have a complete capture-map when checking or inferring if
9386 // the function call operator meets the requirements of a constexpr function
9387 // - but we don't need to evaluate the captures to determine constexprness
9388 // (dcl.constexpr C++17).
9389 if (Info.checkingPotentialConstantExpression())
9390 return false;
9391
9392 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(D)) {
9393 const auto *MD = cast<CXXMethodDecl>(Info.CurrentCall->Callee);
9394 return HandleLambdaCapture(Info, E, Result, MD, FD,
9395 FD->getType()->isReferenceType());
9396 }
9397 }
9398
9399 if (isa<FunctionDecl, MSGuidDecl, TemplateParamObjectDecl,
9400 UnnamedGlobalConstantDecl>(D))
9401 return Success(cast<ValueDecl>(D));
9402 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
9403 return VisitVarDecl(E, VD);
9404 if (const BindingDecl *BD = dyn_cast<BindingDecl>(D))
9405 return Visit(BD->getBinding());
9406 return Error(E);
9407}
9408
9409bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
9410 CallStackFrame *Frame = nullptr;
9411 unsigned Version = 0;
9412 if (VD->hasLocalStorage()) {
9413 // Only if a local variable was declared in the function currently being
9414 // evaluated, do we expect to be able to find its value in the current
9415 // frame. (Otherwise it was likely declared in an enclosing context and
9416 // could either have a valid evaluatable value (for e.g. a constexpr
9417 // variable) or be ill-formed (and trigger an appropriate evaluation
9418 // diagnostic)).
9419 CallStackFrame *CurrFrame = Info.CurrentCall;
9420 if (CurrFrame->Callee && CurrFrame->Callee->Equals(VD->getDeclContext())) {
9421 // Function parameters are stored in some caller's frame. (Usually the
9422 // immediate caller, but for an inherited constructor they may be more
9423 // distant.)
9424 if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) {
9425 if (CurrFrame->Arguments) {
9426 VD = CurrFrame->Arguments.getOrigParam(PVD);
9427 Frame =
9428 Info.getCallFrameAndDepth(CurrFrame->Arguments.CallIndex).first;
9429 Version = CurrFrame->Arguments.Version;
9430 }
9431 } else {
9432 Frame = CurrFrame;
9433 Version = CurrFrame->getCurrentTemporaryVersion(VD);
9434 }
9435 }
9436 }
9437
9438 if (!VD->getType()->isReferenceType()) {
9439 if (Frame) {
9440 Result.set({VD, Frame->Index, Version});
9441 return true;
9442 }
9443 return Success(VD);
9444 }
9445
9446 if (!Info.getLangOpts().CPlusPlus11) {
9447 Info.CCEDiag(E, diag::note_constexpr_ltor_non_integral, 1)
9448 << VD << VD->getType();
9449 Info.Note(VD->getLocation(), diag::note_declared_at);
9450 }
9451
9452 APValue *V;
9453 if (!evaluateVarDeclInit(Info, E, VD, Frame, Version, V))
9454 return false;
9455
9456 if (!V) {
9457 Result.set(VD);
9458 Result.AllowConstexprUnknown = true;
9459 return true;
9460 }
9461
9462 return Success(*V, E);
9463}
9464
9465bool LValueExprEvaluator::VisitCallExpr(const CallExpr *E) {
9466 if (!IsConstantEvaluatedBuiltinCall(E))
9467 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9468
9469 switch (E->getBuiltinCallee()) {
9470 default:
9471 return false;
9472 case Builtin::BIas_const:
9473 case Builtin::BIforward:
9474 case Builtin::BIforward_like:
9475 case Builtin::BImove:
9476 case Builtin::BImove_if_noexcept:
9477 if (cast<FunctionDecl>(E->getCalleeDecl())->isConstexpr())
9478 return Visit(E->getArg(0));
9479 break;
9480 }
9481
9482 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9483}
9484
9485bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
9486 const MaterializeTemporaryExpr *E) {
9487 // Walk through the expression to find the materialized temporary itself.
9490 const Expr *Inner =
9491 E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
9492
9493 // If we passed any comma operators, evaluate their LHSs.
9494 for (const Expr *E : CommaLHSs)
9495 if (!EvaluateIgnoredValue(Info, E))
9496 return false;
9497
9498 // A materialized temporary with static storage duration can appear within the
9499 // result of a constant expression evaluation, so we need to preserve its
9500 // value for use outside this evaluation.
9501 APValue *Value;
9502 if (E->getStorageDuration() == SD_Static) {
9503 if (Info.EvalMode == EvaluationMode::ConstantFold)
9504 return false;
9505 // FIXME: What about SD_Thread?
9506 Value = E->getOrCreateValue(true);
9507 *Value = APValue();
9508 Result.set(E);
9509 } else {
9510 Value = &Info.CurrentCall->createTemporary(
9511 E, Inner->getType(),
9512 E->getStorageDuration() == SD_FullExpression ? ScopeKind::FullExpression
9513 : ScopeKind::Block,
9514 Result);
9515 }
9516
9517 QualType Type = Inner->getType();
9518
9519 // Materialize the temporary itself.
9520 if (!EvaluateInPlace(*Value, Info, Result, Inner)) {
9521 *Value = APValue();
9522 return false;
9523 }
9524
9525 // Adjust our lvalue to refer to the desired subobject.
9526 for (unsigned I = Adjustments.size(); I != 0; /**/) {
9527 --I;
9528 switch (Adjustments[I].Kind) {
9530 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
9531 Type, Result))
9532 return false;
9533 Type = Adjustments[I].DerivedToBase.BasePath->getType();
9534 break;
9535
9537 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
9538 return false;
9539 Type = Adjustments[I].Field->getType();
9540 break;
9541
9543 if (!HandleMemberPointerAccess(this->Info, Type, Result,
9544 Adjustments[I].Ptr.RHS))
9545 return false;
9546 Type = Adjustments[I].Ptr.MPT->getPointeeType();
9547 break;
9548 }
9549 }
9550
9551 return true;
9552}
9553
9554bool
9555LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
9556 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
9557 "lvalue compound literal in c++?");
9558 APValue *Lit;
9559 // If CompountLiteral has static storage, its value can be used outside
9560 // this expression. So evaluate it once and store it in ASTContext.
9561 if (E->hasStaticStorage()) {
9562 Lit = &E->getOrCreateStaticValue(Info.Ctx);
9563 Result.set(E);
9564 // Reset any previously evaluated state, otherwise evaluation below might
9565 // fail.
9566 // FIXME: Should we just re-use the previously evaluated value instead?
9567 *Lit = APValue();
9568 } else {
9569 assert(!Info.getLangOpts().CPlusPlus);
9570 Lit = &Info.CurrentCall->createTemporary(E, E->getInitializer()->getType(),
9571 ScopeKind::Block, Result);
9572 }
9573 // FIXME: Evaluating in place isn't always right. We should figure out how to
9574 // use appropriate evaluation context here, see
9575 // clang/test/AST/static-compound-literals-reeval.cpp for a failure.
9576 if (!EvaluateInPlace(*Lit, Info, Result, E->getInitializer())) {
9577 *Lit = APValue();
9578 return false;
9579 }
9580 return true;
9581}
9582
9583bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
9584 TypeInfoLValue TypeInfo;
9585
9586 if (!E->isPotentiallyEvaluated()) {
9587 if (E->isTypeOperand())
9588 TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
9589 else
9590 TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
9591 } else {
9592 if (!Info.Ctx.getLangOpts().CPlusPlus20) {
9593 Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
9594 << E->getExprOperand()->getType()
9595 << E->getExprOperand()->getSourceRange();
9596 }
9597
9598 if (!Visit(E->getExprOperand()))
9599 return false;
9600
9601 std::optional<DynamicType> DynType =
9603 if (!DynType)
9604 return false;
9605
9606 TypeInfo = TypeInfoLValue(
9607 Info.Ctx.getCanonicalTagType(DynType->Type).getTypePtr());
9608 }
9609
9610 return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
9611}
9612
9613bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
9614 return Success(E->getGuidDecl());
9615}
9616
9617bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
9618 // Handle static data members.
9619 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
9620 VisitIgnoredBaseExpression(E->getBase());
9621 return VisitVarDecl(E, VD);
9622 }
9623
9624 // Handle static member functions.
9625 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
9626 if (MD->isStatic()) {
9627 VisitIgnoredBaseExpression(E->getBase());
9628 return Success(MD);
9629 }
9630 }
9631
9632 // Handle non-static data members.
9633 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
9634}
9635
9636bool LValueExprEvaluator::VisitExtVectorElementExpr(
9637 const ExtVectorElementExpr *E) {
9638 bool Success = true;
9639
9640 APValue Val;
9641 if (!Evaluate(Val, Info, E->getBase())) {
9642 if (!Info.noteFailure())
9643 return false;
9644 Success = false;
9645 }
9646
9648 E->getEncodedElementAccess(Indices);
9649 // FIXME: support accessing more than one element
9650 if (Indices.size() > 1)
9651 return false;
9652
9653 if (Success) {
9654 Result.setFrom(Info.Ctx, Val);
9655 QualType BaseType = E->getBase()->getType();
9656 if (E->isArrow())
9657 BaseType = BaseType->getPointeeType();
9658 const auto *VT = BaseType->castAs<VectorType>();
9659 HandleLValueVectorElement(Info, E, Result, VT->getElementType(),
9660 VT->getNumElements(), Indices[0]);
9661 }
9662
9663 return Success;
9664}
9665
9666bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
9667 if (E->getBase()->getType()->isSveVLSBuiltinType())
9668 return Error(E);
9669
9670 APSInt Index;
9671 bool Success = true;
9672
9673 if (const auto *VT = E->getBase()->getType()->getAs<VectorType>()) {
9674 APValue Val;
9675 if (!Evaluate(Val, Info, E->getBase())) {
9676 if (!Info.noteFailure())
9677 return false;
9678 Success = false;
9679 }
9680
9681 if (!EvaluateInteger(E->getIdx(), Index, Info)) {
9682 if (!Info.noteFailure())
9683 return false;
9684 Success = false;
9685 }
9686
9687 if (Success) {
9688 Result.setFrom(Info.Ctx, Val);
9689 HandleLValueVectorElement(Info, E, Result, VT->getElementType(),
9690 VT->getNumElements(), Index.getZExtValue());
9691 }
9692
9693 return Success;
9694 }
9695
9696 // C++17's rules require us to evaluate the LHS first, regardless of which
9697 // side is the base.
9698 for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) {
9699 if (SubExpr == E->getBase() ? !evaluatePointer(SubExpr, Result)
9700 : !EvaluateInteger(SubExpr, Index, Info)) {
9701 if (!Info.noteFailure())
9702 return false;
9703 Success = false;
9704 }
9705 }
9706
9707 return Success &&
9708 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
9709}
9710
9711bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
9712 bool Success = evaluatePointer(E->getSubExpr(), Result);
9713 // [C++26][expr.unary.op]
9714 // If the operand points to an object or function, the result
9715 // denotes that object or function; otherwise, the behavior is undefined.
9716 // Because &(*(type*)0) is a common pattern, we do not fail the evaluation
9717 // immediately.
9719 return Success;
9721 E->getType())) ||
9722 Info.noteUndefinedBehavior();
9723}
9724
9725bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
9726 if (!Visit(E->getSubExpr()))
9727 return false;
9728 // __real is a no-op on scalar lvalues.
9729 if (E->getSubExpr()->getType()->isAnyComplexType())
9730 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
9731 return true;
9732}
9733
9734bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
9735 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
9736 "lvalue __imag__ on scalar?");
9737 if (!Visit(E->getSubExpr()))
9738 return false;
9739 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
9740 return true;
9741}
9742
9743bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
9744 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9745 return Error(UO);
9746
9747 if (!this->Visit(UO->getSubExpr()))
9748 return false;
9749
9750 return handleIncDec(
9751 this->Info, UO, Result, UO->getSubExpr()->getType(),
9752 UO->isIncrementOp(), nullptr);
9753}
9754
9755bool LValueExprEvaluator::VisitCompoundAssignOperator(
9756 const CompoundAssignOperator *CAO) {
9757 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9758 return Error(CAO);
9759
9760 bool Success = true;
9761
9762 // C++17 onwards require that we evaluate the RHS first.
9763 APValue RHS;
9764 if (!Evaluate(RHS, this->Info, CAO->getRHS())) {
9765 if (!Info.noteFailure())
9766 return false;
9767 Success = false;
9768 }
9769
9770 // The overall lvalue result is the result of evaluating the LHS.
9771 if (!this->Visit(CAO->getLHS()) || !Success)
9772 return false;
9773
9775 this->Info, CAO,
9776 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
9777 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
9778}
9779
9780bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
9781 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9782 return Error(E);
9783
9784 bool Success = true;
9785
9786 // C++17 onwards require that we evaluate the RHS first.
9787 APValue NewVal;
9788 if (!Evaluate(NewVal, this->Info, E->getRHS())) {
9789 if (!Info.noteFailure())
9790 return false;
9791 Success = false;
9792 }
9793
9794 if (!this->Visit(E->getLHS()) || !Success)
9795 return false;
9796
9797 if (Info.getLangOpts().CPlusPlus20 &&
9799 return false;
9800
9801 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
9802 NewVal);
9803}
9804
9805//===----------------------------------------------------------------------===//
9806// Pointer Evaluation
9807//===----------------------------------------------------------------------===//
9808
9809/// Convenience function. LVal's base must be a call to an alloc_size
9810/// function.
9812 const LValue &LVal,
9813 llvm::APInt &Result) {
9814 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
9815 "Can't get the size of a non alloc_size function");
9816 const auto *Base = LVal.getLValueBase().get<const Expr *>();
9817 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
9818 std::optional<llvm::APInt> Size =
9819 CE->evaluateBytesReturnedByAllocSizeCall(Ctx);
9820 if (!Size)
9821 return false;
9822
9823 Result = std::move(*Size);
9824 return true;
9825}
9826
9827/// Attempts to evaluate the given LValueBase as the result of a call to
9828/// a function with the alloc_size attribute. If it was possible to do so, this
9829/// function will return true, make Result's Base point to said function call,
9830/// and mark Result's Base as invalid.
9832 LValue &Result) {
9833 if (Base.isNull())
9834 return false;
9835
9836 // Because we do no form of static analysis, we only support const variables.
9837 //
9838 // Additionally, we can't support parameters, nor can we support static
9839 // variables (in the latter case, use-before-assign isn't UB; in the former,
9840 // we have no clue what they'll be assigned to).
9841 const auto *VD =
9842 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
9843 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
9844 return false;
9845
9846 const Expr *Init = VD->getAnyInitializer();
9847 if (!Init || Init->getType().isNull())
9848 return false;
9849
9850 const Expr *E = Init->IgnoreParens();
9851 if (!tryUnwrapAllocSizeCall(E))
9852 return false;
9853
9854 // Store E instead of E unwrapped so that the type of the LValue's base is
9855 // what the user wanted.
9856 Result.setInvalid(E);
9857
9858 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
9859 Result.addUnsizedArray(Info, E, Pointee);
9860 return true;
9861}
9862
9863namespace {
9864class PointerExprEvaluator
9865 : public ExprEvaluatorBase<PointerExprEvaluator> {
9866 LValue &Result;
9867 bool InvalidBaseOK;
9868
9869 bool Success(const Expr *E) {
9870 Result.set(E);
9871 return true;
9872 }
9873
9874 bool evaluateLValue(const Expr *E, LValue &Result) {
9875 return EvaluateLValue(E, Result, Info, InvalidBaseOK);
9876 }
9877
9878 bool evaluatePointer(const Expr *E, LValue &Result) {
9879 return EvaluatePointer(E, Result, Info, InvalidBaseOK);
9880 }
9881
9882 bool visitNonBuiltinCallExpr(const CallExpr *E);
9883public:
9884
9885 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
9886 : ExprEvaluatorBaseTy(info), Result(Result),
9887 InvalidBaseOK(InvalidBaseOK) {}
9888
9889 bool Success(const APValue &V, const Expr *E) {
9890 Result.setFrom(Info.Ctx, V);
9891 return true;
9892 }
9893 bool ZeroInitialization(const Expr *E) {
9894 Result.setNull(Info.Ctx, E->getType());
9895 return true;
9896 }
9897
9898 bool VisitBinaryOperator(const BinaryOperator *E);
9899 bool VisitCastExpr(const CastExpr* E);
9900 bool VisitUnaryAddrOf(const UnaryOperator *E);
9901 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
9902 { return Success(E); }
9903 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
9905 return Success(E);
9906 if (Info.noteFailure())
9907 EvaluateIgnoredValue(Info, E->getSubExpr());
9908 return Error(E);
9909 }
9910 bool VisitObjCArrayLiteral(const ObjCArrayLiteral *E) {
9911 return E->isExpressibleAsConstantInitializer() ? Success(E) : Error(E);
9912 }
9913 bool VisitObjCDictionaryLiteral(const ObjCDictionaryLiteral *E) {
9914 return E->isExpressibleAsConstantInitializer() ? Success(E) : Error(E);
9915 }
9916 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
9917 { return Success(E); }
9918 bool VisitCallExpr(const CallExpr *E);
9919 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
9920 bool VisitBlockExpr(const BlockExpr *E) {
9921 if (!E->getBlockDecl()->hasCaptures())
9922 return Success(E);
9923 return Error(E);
9924 }
9925 bool VisitCXXThisExpr(const CXXThisExpr *E) {
9926 auto DiagnoseInvalidUseOfThis = [&] {
9927 if (Info.getLangOpts().CPlusPlus11)
9928 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
9929 else
9930 Info.FFDiag(E);
9931 };
9932
9933 // Can't look at 'this' when checking a potential constant expression.
9934 if (Info.checkingPotentialConstantExpression())
9935 return false;
9936
9937 bool IsExplicitLambda =
9938 isLambdaCallWithExplicitObjectParameter(Info.CurrentCall->Callee);
9939 if (!IsExplicitLambda) {
9940 if (!Info.CurrentCall->This) {
9941 DiagnoseInvalidUseOfThis();
9942 return false;
9943 }
9944
9945 Result = *Info.CurrentCall->This;
9946 }
9947
9948 if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
9949 // Ensure we actually have captured 'this'. If something was wrong with
9950 // 'this' capture, the error would have been previously reported.
9951 // Otherwise we can be inside of a default initialization of an object
9952 // declared by lambda's body, so no need to return false.
9953 if (!Info.CurrentCall->LambdaThisCaptureField) {
9954 if (IsExplicitLambda && !Info.CurrentCall->This) {
9955 DiagnoseInvalidUseOfThis();
9956 return false;
9957 }
9958
9959 return true;
9960 }
9961
9962 const auto *MD = cast<CXXMethodDecl>(Info.CurrentCall->Callee);
9963 return HandleLambdaCapture(
9964 Info, E, Result, MD, Info.CurrentCall->LambdaThisCaptureField,
9965 Info.CurrentCall->LambdaThisCaptureField->getType()->isPointerType());
9966 }
9967 return true;
9968 }
9969
9970 bool VisitCXXNewExpr(const CXXNewExpr *E);
9971
9972 bool VisitSourceLocExpr(const SourceLocExpr *E) {
9973 assert(!E->isIntType() && "SourceLocExpr isn't a pointer type?");
9974 APValue LValResult = E->EvaluateInContext(
9975 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
9976 Result.setFrom(Info.Ctx, LValResult);
9977 return true;
9978 }
9979
9980 bool VisitEmbedExpr(const EmbedExpr *E) {
9981 llvm::report_fatal_error("Not yet implemented for ExprConstant.cpp");
9982 return true;
9983 }
9984
9985 bool VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr *E) {
9986 std::string ResultStr = E->ComputeName(Info.Ctx);
9987
9988 QualType CharTy = Info.Ctx.CharTy.withConst();
9989 APInt Size(Info.Ctx.getTypeSize(Info.Ctx.getSizeType()),
9990 ResultStr.size() + 1);
9991 QualType ArrayTy = Info.Ctx.getConstantArrayType(
9992 CharTy, Size, nullptr, ArraySizeModifier::Normal, 0);
9993
9994 StringLiteral *SL =
9995 StringLiteral::Create(Info.Ctx, ResultStr, StringLiteralKind::Ordinary,
9996 /*Pascal*/ false, ArrayTy, E->getLocation());
9997
9998 evaluateLValue(SL, Result);
9999 Result.addArray(Info, E, cast<ConstantArrayType>(ArrayTy));
10000 return true;
10001 }
10002
10003 // FIXME: Missing: @protocol, @selector
10004};
10005} // end anonymous namespace
10006
10007static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
10008 bool InvalidBaseOK) {
10009 assert(!E->isValueDependent());
10010 assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
10011 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
10012}
10013
10014bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
10015 if (E->getOpcode() != BO_Add &&
10016 E->getOpcode() != BO_Sub)
10017 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10018
10019 const Expr *PExp = E->getLHS();
10020 const Expr *IExp = E->getRHS();
10021 if (IExp->getType()->isPointerType())
10022 std::swap(PExp, IExp);
10023
10024 bool EvalPtrOK = evaluatePointer(PExp, Result);
10025 if (!EvalPtrOK && !Info.noteFailure())
10026 return false;
10027
10028 llvm::APSInt Offset;
10029 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
10030 return false;
10031
10032 if (E->getOpcode() == BO_Sub)
10033 negateAsSigned(Offset);
10034
10035 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
10036 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
10037}
10038
10039bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
10040 // [C11 6.5.3.2p3]: if the operand of '&' is the result of a unary '*'
10041 // operator, neither operator is evaluated and the result is as if both were
10042 // omitted (except that the operators' constraints, already enforced by Sema,
10043 // still apply, and the result is not an lvalue). So '&*p' is just the pointer
10044 // value 'p' with no dereference, and forming it is therefore not undefined
10045 // behavior even when 'p' is null, e.g. '&*(int *)0'. Evaluate the pointer
10046 // operand directly so we don't spuriously diagnose a null dereference.
10047 if (!Info.getLangOpts().CPlusPlus) {
10048 const Expr *Sub = E->getSubExpr()->IgnoreParens();
10049 if (const auto *Deref = dyn_cast<UnaryOperator>(Sub);
10050 Deref && Deref->getOpcode() == UO_Deref)
10051 return evaluatePointer(Deref->getSubExpr(), Result);
10052 }
10053 return evaluateLValue(E->getSubExpr(), Result);
10054}
10055
10056// Is the provided decl 'std::source_location::current'?
10058 if (!FD)
10059 return false;
10060 const IdentifierInfo *FnII = FD->getIdentifier();
10061 if (!FnII || !FnII->isStr("current"))
10062 return false;
10063
10064 const auto *RD = dyn_cast<RecordDecl>(FD->getParent());
10065 if (!RD)
10066 return false;
10067
10068 const IdentifierInfo *ClassII = RD->getIdentifier();
10069 return RD->isInStdNamespace() && ClassII && ClassII->isStr("source_location");
10070}
10071
10072bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
10073 const Expr *SubExpr = E->getSubExpr();
10074
10075 switch (E->getCastKind()) {
10076 default:
10077 break;
10078 case CK_BitCast:
10079 case CK_CPointerToObjCPointerCast:
10080 case CK_BlockPointerToObjCPointerCast:
10081 case CK_AnyPointerToBlockPointerCast:
10082 case CK_AddressSpaceConversion:
10083 if (!Visit(SubExpr))
10084 return false;
10085 if (E->getType()->isFunctionPointerType() ||
10086 SubExpr->getType()->isFunctionPointerType()) {
10087 // Casting between two function pointer types, or between a function
10088 // pointer and an object pointer, is always a reinterpret_cast.
10089 CCEDiag(E, diag::note_constexpr_invalid_cast)
10090 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
10091 << Info.Ctx.getLangOpts().CPlusPlus;
10092 Result.Designator.setInvalid();
10093 } else if (!E->getType()->isVoidPointerType()) {
10094 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
10095 // permitted in constant expressions in C++11. Bitcasts from cv void* are
10096 // also static_casts, but we disallow them as a resolution to DR1312.
10097 //
10098 // In some circumstances, we permit casting from void* to cv1 T*, when the
10099 // actual pointee object is actually a cv2 T.
10100 bool HasValidResult = !Result.InvalidBase && !Result.Designator.Invalid &&
10101 !Result.IsNullPtr;
10102 bool VoidPtrCastMaybeOK =
10103 Result.IsNullPtr ||
10104 (HasValidResult &&
10105 Info.Ctx.hasSimilarType(Result.Designator.getType(Info.Ctx),
10106 E->getType()->getPointeeType()));
10107 // 1. We'll allow it in std::allocator::allocate, and anything which that
10108 // calls.
10109 // 2. HACK 2022-03-28: Work around an issue with libstdc++'s
10110 // <source_location> header. Fixed in GCC 12 and later (2022-04-??).
10111 // We'll allow it in the body of std::source_location::current. GCC's
10112 // implementation had a parameter of type `void*`, and casts from
10113 // that back to `const __impl*` in its body.
10114 if (VoidPtrCastMaybeOK &&
10115 (Info.getStdAllocatorCaller("allocate") ||
10116 IsDeclSourceLocationCurrent(Info.CurrentCall->Callee) ||
10117 Info.getLangOpts().CPlusPlus26)) {
10118 // Permitted.
10119 } else {
10120 if (SubExpr->getType()->isVoidPointerType() &&
10121 Info.getLangOpts().CPlusPlus) {
10122 if (HasValidResult)
10123 CCEDiag(E, diag::note_constexpr_invalid_void_star_cast)
10124 << SubExpr->getType() << Info.getLangOpts().CPlusPlus26
10125 << Result.Designator.getType(Info.Ctx).getCanonicalType()
10126 << E->getType()->getPointeeType();
10127 else
10128 CCEDiag(E, diag::note_constexpr_invalid_cast)
10129 << diag::ConstexprInvalidCastKind::CastFrom
10130 << SubExpr->getType();
10131 } else
10132 CCEDiag(E, diag::note_constexpr_invalid_cast)
10133 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
10134 << Info.Ctx.getLangOpts().CPlusPlus;
10135 Result.Designator.setInvalid();
10136 }
10137 }
10138 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
10139 ZeroInitialization(E);
10140 return true;
10141
10142 case CK_DerivedToBase:
10143 case CK_UncheckedDerivedToBase:
10144 if (!evaluatePointer(E->getSubExpr(), Result))
10145 return false;
10146 if (!Result.Base && Result.Offset.isZero())
10147 return true;
10148
10149 // Now figure out the necessary offset to add to the base LV to get from
10150 // the derived class to the base class.
10151 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
10152 castAs<PointerType>()->getPointeeType(),
10153 Result);
10154
10155 case CK_BaseToDerived:
10156 if (!Visit(E->getSubExpr()))
10157 return false;
10158 if (!Result.Base && Result.Offset.isZero())
10159 return true;
10160 return HandleBaseToDerivedCast(Info, E, Result);
10161
10162 case CK_Dynamic:
10163 if (!Visit(E->getSubExpr()))
10164 return false;
10166
10167 case CK_NullToPointer:
10168 VisitIgnoredValue(E->getSubExpr());
10169 return ZeroInitialization(E);
10170
10171 case CK_IntegralToPointer: {
10172 CCEDiag(E, diag::note_constexpr_invalid_cast)
10173 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
10174 << Info.Ctx.getLangOpts().CPlusPlus;
10175
10176 APValue Value;
10177 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
10178 break;
10179
10180 if (Value.isInt()) {
10181 unsigned Size = Info.Ctx.getTypeSize(E->getType());
10182 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
10183 if (N == Info.Ctx.getTargetNullPointerValue(E->getType())) {
10184 Result.setNull(Info.Ctx, E->getType());
10185 } else {
10186 Result.Base = (Expr *)nullptr;
10187 Result.InvalidBase = false;
10188 Result.Offset = CharUnits::fromQuantity(N);
10189 Result.Designator.setInvalid();
10190 Result.IsNullPtr = false;
10191 }
10192 return true;
10193 } else {
10194 // In rare instances, the value isn't an lvalue.
10195 // For example, when the value is the difference between the addresses of
10196 // two labels. We reject that as a constant expression because we can't
10197 // compute a valid offset to convert into a pointer.
10198 if (!Value.isLValue())
10199 return false;
10200
10201 // Cast is of an lvalue, no need to change value.
10202 Result.setFrom(Info.Ctx, Value);
10203 return true;
10204 }
10205 }
10206
10207 case CK_ArrayToPointerDecay: {
10208 if (SubExpr->isGLValue()) {
10209 if (!evaluateLValue(SubExpr, Result))
10210 return false;
10211 } else {
10212 APValue &Value = Info.CurrentCall->createTemporary(
10213 SubExpr, SubExpr->getType(), ScopeKind::FullExpression, Result);
10214 if (!EvaluateInPlace(Value, Info, Result, SubExpr))
10215 return false;
10216 }
10217 // The result is a pointer to the first element of the array.
10218 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
10219 if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
10220 Result.addArray(Info, E, CAT);
10221 else
10222 Result.addUnsizedArray(Info, E, AT->getElementType());
10223 return true;
10224 }
10225
10226 case CK_FunctionToPointerDecay:
10227 return evaluateLValue(SubExpr, Result);
10228
10229 case CK_LValueToRValue: {
10230 LValue LVal;
10231 if (!evaluateLValue(E->getSubExpr(), LVal))
10232 return false;
10233
10234 APValue RVal;
10235 // Note, we use the subexpression's type in order to retain cv-qualifiers.
10237 LVal, RVal))
10238 return InvalidBaseOK &&
10239 evaluateLValueAsAllocSize(Info, LVal.Base, Result);
10240 return Success(RVal, E);
10241 }
10242 }
10243
10244 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10245}
10246
10248 UnaryExprOrTypeTrait ExprKind) {
10249 // C++ [expr.alignof]p3:
10250 // When alignof is applied to a reference type, the result is the
10251 // alignment of the referenced type.
10252 T = T.getNonReferenceType();
10253
10254 if (T.getQualifiers().hasUnaligned())
10255 return CharUnits::One();
10256
10257 const bool AlignOfReturnsPreferred =
10258 Ctx.getLangOpts().isCompatibleWith(LangOptions::ClangABI::Ver7);
10259
10260 // __alignof is defined to return the preferred alignment.
10261 // Before 8, clang returned the preferred alignment for alignof and _Alignof
10262 // as well.
10263 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
10264 return Ctx.toCharUnitsFromBits(Ctx.getPreferredTypeAlign(T.getTypePtr()));
10265 // alignof and _Alignof are defined to return the ABI alignment.
10266 else if (ExprKind == UETT_AlignOf)
10267 return Ctx.getTypeAlignInChars(T.getTypePtr());
10268 else
10269 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
10270}
10271
10273 UnaryExprOrTypeTrait ExprKind) {
10274 E = E->IgnoreParens();
10275
10276 // The kinds of expressions that we have special-case logic here for
10277 // should be kept up to date with the special checks for those
10278 // expressions in Sema.
10279
10280 // alignof decl is always accepted, even if it doesn't make sense: we default
10281 // to 1 in those cases.
10282 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
10283 return Ctx.getDeclAlign(DRE->getDecl(),
10284 /*RefAsPointee*/ true);
10285
10286 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
10287 return Ctx.getDeclAlign(ME->getMemberDecl(),
10288 /*RefAsPointee*/ true);
10289
10290 return GetAlignOfType(Ctx, E->getType(), ExprKind);
10291}
10292
10293static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) {
10294 if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>())
10295 return Info.Ctx.getDeclAlign(VD);
10296 if (const auto *E = Value.Base.dyn_cast<const Expr *>())
10297 return GetAlignOfExpr(Info.Ctx, E, UETT_AlignOf);
10298 return GetAlignOfType(Info.Ctx, Value.Base.getTypeInfoType(), UETT_AlignOf);
10299}
10300
10301/// Evaluate the value of the alignment argument to __builtin_align_{up,down},
10302/// __builtin_is_aligned and __builtin_assume_aligned.
10303static bool getAlignmentArgument(const Expr *E, QualType ForType,
10304 EvalInfo &Info, APSInt &Alignment) {
10305 if (!EvaluateInteger(E, Alignment, Info))
10306 return false;
10307 if (Alignment < 0 || !Alignment.isPowerOf2()) {
10308 Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment;
10309 return false;
10310 }
10311 unsigned SrcWidth = Info.Ctx.getIntWidth(ForType);
10312 APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1));
10313 if (APSInt::compareValues(Alignment, MaxValue) > 0) {
10314 Info.FFDiag(E, diag::note_constexpr_alignment_too_big)
10315 << MaxValue << ForType << Alignment;
10316 return false;
10317 }
10318 // Ensure both alignment and source value have the same bit width so that we
10319 // don't assert when computing the resulting value.
10320 APSInt ExtAlignment =
10321 APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true);
10322 assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 &&
10323 "Alignment should not be changed by ext/trunc");
10324 Alignment = ExtAlignment;
10325 assert(Alignment.getBitWidth() == SrcWidth);
10326 return true;
10327}
10328
10329// To be clear: this happily visits unsupported builtins. Better name welcomed.
10330bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
10331 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
10332 return true;
10333
10334 if (!(InvalidBaseOK && E->getCalleeAllocSizeAttr()))
10335 return false;
10336
10337 Result.setInvalid(E);
10338 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
10339 Result.addUnsizedArray(Info, E, PointeeTy);
10340 return true;
10341}
10342
10343bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
10344 if (!IsConstantEvaluatedBuiltinCall(E))
10345 return visitNonBuiltinCallExpr(E);
10346 return VisitBuiltinCallExpr(E, E->getBuiltinCallee());
10347}
10348
10349// Determine if T is a character type for which we guarantee that
10350// sizeof(T) == 1.
10352 return T->isCharType() || T->isChar8Type();
10353}
10354
10355bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
10356 unsigned BuiltinOp) {
10357 if (IsOpaqueConstantCall(E))
10358 return Success(E);
10359
10360 switch (BuiltinOp) {
10361 case Builtin::BIaddressof:
10362 case Builtin::BI__addressof:
10363 case Builtin::BI__builtin_addressof:
10364 return evaluateLValue(E->getArg(0), Result);
10365 case Builtin::BI__builtin_assume_aligned: {
10366 // We need to be very careful here because: if the pointer does not have the
10367 // asserted alignment, then the behavior is undefined, and undefined
10368 // behavior is non-constant.
10369 if (!evaluatePointer(E->getArg(0), Result))
10370 return false;
10371
10372 LValue OffsetResult(Result);
10373 APSInt Alignment;
10374 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
10375 Alignment))
10376 return false;
10377 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
10378
10379 if (E->getNumArgs() > 2) {
10380 APSInt Offset;
10381 if (!EvaluateInteger(E->getArg(2), Offset, Info))
10382 return false;
10383
10384 int64_t AdditionalOffset = -Offset.getZExtValue();
10385 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
10386 }
10387
10388 // If there is a base object, then it must have the correct alignment.
10389 if (OffsetResult.Base) {
10390 CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult);
10391
10392 if (BaseAlignment < Align) {
10393 Result.Designator.setInvalid();
10394 CCEDiag(E->getArg(0), diag::note_constexpr_baa_insufficient_alignment)
10395 << 0 << BaseAlignment.getQuantity() << Align.getQuantity();
10396 return false;
10397 }
10398 }
10399
10400 // The offset must also have the correct alignment.
10401 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
10402 Result.Designator.setInvalid();
10403
10404 (OffsetResult.Base
10405 ? CCEDiag(E->getArg(0),
10406 diag::note_constexpr_baa_insufficient_alignment)
10407 << 1
10408 : CCEDiag(E->getArg(0),
10409 diag::note_constexpr_baa_value_insufficient_alignment))
10410 << OffsetResult.Offset.getQuantity() << Align.getQuantity();
10411 return false;
10412 }
10413
10414 return true;
10415 }
10416 case Builtin::BI__builtin_align_up:
10417 case Builtin::BI__builtin_align_down: {
10418 if (!evaluatePointer(E->getArg(0), Result))
10419 return false;
10420 APSInt Alignment;
10421 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
10422 Alignment))
10423 return false;
10424 CharUnits BaseAlignment = getBaseAlignment(Info, Result);
10425 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset);
10426 // For align_up/align_down, we can return the same value if the alignment
10427 // is known to be greater or equal to the requested value.
10428 if (PtrAlign.getQuantity() >= Alignment)
10429 return true;
10430
10431 // The alignment could be greater than the minimum at run-time, so we cannot
10432 // infer much about the resulting pointer value. One case is possible:
10433 // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we
10434 // can infer the correct index if the requested alignment is smaller than
10435 // the base alignment so we can perform the computation on the offset.
10436 if (BaseAlignment.getQuantity() >= Alignment) {
10437 assert(Alignment.getBitWidth() <= 64 &&
10438 "Cannot handle > 64-bit address-space");
10439 uint64_t Alignment64 = Alignment.getZExtValue();
10440 CharUnits NewOffset = CharUnits::fromQuantity(
10441 BuiltinOp == Builtin::BI__builtin_align_down
10442 ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64)
10443 : llvm::alignTo(Result.Offset.getQuantity(), Alignment64));
10444 Result.adjustOffset(NewOffset - Result.Offset);
10445 // TODO: diagnose out-of-bounds values/only allow for arrays?
10446 return true;
10447 }
10448 // Otherwise, we cannot constant-evaluate the result.
10449 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust)
10450 << Alignment;
10451 return false;
10452 }
10453 case Builtin::BI__builtin_operator_new:
10454 return HandleOperatorNewCall(Info, E, Result);
10455 case Builtin::BI__builtin_launder:
10456 return evaluatePointer(E->getArg(0), Result);
10457 case Builtin::BIstrchr:
10458 case Builtin::BIwcschr:
10459 case Builtin::BImemchr:
10460 case Builtin::BIwmemchr:
10461 if (Info.getLangOpts().CPlusPlus11)
10462 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
10463 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
10464 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
10465 else
10466 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
10467 [[fallthrough]];
10468 case Builtin::BI__builtin_strchr:
10469 case Builtin::BI__builtin_wcschr:
10470 case Builtin::BI__builtin_memchr:
10471 case Builtin::BI__builtin_char_memchr:
10472 case Builtin::BI__builtin_wmemchr: {
10473 if (!Visit(E->getArg(0)))
10474 return false;
10475 APSInt Desired;
10476 if (!EvaluateInteger(E->getArg(1), Desired, Info))
10477 return false;
10478 uint64_t MaxLength = uint64_t(-1);
10479 if (BuiltinOp != Builtin::BIstrchr &&
10480 BuiltinOp != Builtin::BIwcschr &&
10481 BuiltinOp != Builtin::BI__builtin_strchr &&
10482 BuiltinOp != Builtin::BI__builtin_wcschr) {
10483 APSInt N;
10484 if (!EvaluateInteger(E->getArg(2), N, Info))
10485 return false;
10486 MaxLength = N.getZExtValue();
10487 }
10488 // We cannot find the value if there are no candidates to match against.
10489 if (MaxLength == 0u)
10490 return ZeroInitialization(E);
10491 if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
10492 Result.Designator.Invalid)
10493 return false;
10494 QualType CharTy = Result.Designator.getType(Info.Ctx);
10495 bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
10496 BuiltinOp == Builtin::BI__builtin_memchr;
10497 assert(IsRawByte ||
10498 Info.Ctx.hasSameUnqualifiedType(
10499 CharTy, E->getArg(0)->getType()->getPointeeType()));
10500 // Pointers to const void may point to objects of incomplete type.
10501 if (IsRawByte && CharTy->isIncompleteType()) {
10502 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
10503 return false;
10504 }
10505 // Give up on byte-oriented matching against multibyte elements.
10506 // FIXME: We can compare the bytes in the correct order.
10507 if (IsRawByte && !isOneByteCharacterType(CharTy)) {
10508 Info.FFDiag(E, diag::note_constexpr_memchr_unsupported)
10509 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp) << CharTy;
10510 return false;
10511 }
10512 // Figure out what value we're actually looking for (after converting to
10513 // the corresponding unsigned type if necessary).
10514 uint64_t DesiredVal;
10515 bool StopAtNull = false;
10516 switch (BuiltinOp) {
10517 case Builtin::BIstrchr:
10518 case Builtin::BI__builtin_strchr:
10519 // strchr compares directly to the passed integer, and therefore
10520 // always fails if given an int that is not a char.
10521 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
10522 E->getArg(1)->getType(),
10523 Desired),
10524 Desired))
10525 return ZeroInitialization(E);
10526 StopAtNull = true;
10527 [[fallthrough]];
10528 case Builtin::BImemchr:
10529 case Builtin::BI__builtin_memchr:
10530 case Builtin::BI__builtin_char_memchr:
10531 // memchr compares by converting both sides to unsigned char. That's also
10532 // correct for strchr if we get this far (to cope with plain char being
10533 // unsigned in the strchr case).
10534 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
10535 break;
10536
10537 case Builtin::BIwcschr:
10538 case Builtin::BI__builtin_wcschr:
10539 StopAtNull = true;
10540 [[fallthrough]];
10541 case Builtin::BIwmemchr:
10542 case Builtin::BI__builtin_wmemchr:
10543 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
10544 DesiredVal = Desired.getZExtValue();
10545 break;
10546 }
10547
10548 for (; MaxLength; --MaxLength) {
10549 APValue Char;
10550 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
10551 !Char.isInt())
10552 return false;
10553 if (Char.getInt().getZExtValue() == DesiredVal)
10554 return true;
10555 if (StopAtNull && !Char.getInt())
10556 break;
10557 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
10558 return false;
10559 }
10560 // Not found: return nullptr.
10561 return ZeroInitialization(E);
10562 }
10563
10564 case Builtin::BImemcpy:
10565 case Builtin::BImemmove:
10566 case Builtin::BIwmemcpy:
10567 case Builtin::BIwmemmove:
10568 if (Info.getLangOpts().CPlusPlus11)
10569 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
10570 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
10571 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
10572 else
10573 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
10574 [[fallthrough]];
10575 case Builtin::BI__builtin_memcpy:
10576 case Builtin::BI__builtin_memmove:
10577 case Builtin::BI__builtin_wmemcpy:
10578 case Builtin::BI__builtin_wmemmove: {
10579 bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
10580 BuiltinOp == Builtin::BIwmemmove ||
10581 BuiltinOp == Builtin::BI__builtin_wmemcpy ||
10582 BuiltinOp == Builtin::BI__builtin_wmemmove;
10583 bool Move = BuiltinOp == Builtin::BImemmove ||
10584 BuiltinOp == Builtin::BIwmemmove ||
10585 BuiltinOp == Builtin::BI__builtin_memmove ||
10586 BuiltinOp == Builtin::BI__builtin_wmemmove;
10587
10588 // The result of mem* is the first argument.
10589 if (!Visit(E->getArg(0)))
10590 return false;
10591 LValue Dest = Result;
10592
10593 LValue Src;
10594 if (!EvaluatePointer(E->getArg(1), Src, Info))
10595 return false;
10596
10597 APSInt N;
10598 if (!EvaluateInteger(E->getArg(2), N, Info))
10599 return false;
10600 assert(!N.isSigned() && "memcpy and friends take an unsigned size");
10601
10602 // If the size is zero, we treat this as always being a valid no-op.
10603 // (Even if one of the src and dest pointers is null.)
10604 if (!N)
10605 return true;
10606
10607 // Otherwise, if either of the operands is null, we can't proceed. Don't
10608 // try to determine the type of the copied objects, because there aren't
10609 // any.
10610 if (!Src.Base || !Dest.Base) {
10611 APValue Val;
10612 (!Src.Base ? Src : Dest).moveInto(Val);
10613 Info.FFDiag(E, diag::note_constexpr_memcpy_null)
10614 << Move << WChar << !!Src.Base
10615 << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
10616 return false;
10617 }
10618 if (Src.Designator.Invalid || Dest.Designator.Invalid)
10619 return false;
10620
10621 // We require that Src and Dest are both pointers to arrays of
10622 // trivially-copyable type. (For the wide version, the designator will be
10623 // invalid if the designated object is not a wchar_t.)
10624 QualType T = Dest.Designator.getType(Info.Ctx);
10625 QualType SrcT = Src.Designator.getType(Info.Ctx);
10626 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
10627 // FIXME: Consider using our bit_cast implementation to support this.
10628 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
10629 return false;
10630 }
10631 if (T->isIncompleteType()) {
10632 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
10633 return false;
10634 }
10635 if (!T.isTriviallyCopyableType(Info.Ctx)) {
10636 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
10637 return false;
10638 }
10639
10640 // Figure out how many T's we're copying.
10641 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
10642 if (TSize == 0)
10643 return false;
10644 if (!WChar) {
10645 uint64_t Remainder;
10646 llvm::APInt OrigN = N;
10647 llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
10648 if (Remainder) {
10649 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
10650 << Move << WChar << 0 << T << toString(OrigN, 10, /*Signed*/false)
10651 << (unsigned)TSize;
10652 return false;
10653 }
10654 }
10655
10656 // Check that the copying will remain within the arrays, just so that we
10657 // can give a more meaningful diagnostic. This implicitly also checks that
10658 // N fits into 64 bits.
10659 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
10660 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
10661 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
10662 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
10663 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
10664 << toString(N, 10, /*Signed*/false);
10665 return false;
10666 }
10667 uint64_t NElems = N.getZExtValue();
10668 uint64_t NBytes = NElems * TSize;
10669
10670 // Check for overlap.
10671 int Direction = 1;
10672 if (HasSameBase(Src, Dest)) {
10673 uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
10674 uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
10675 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
10676 // Dest is inside the source region.
10677 if (!Move) {
10678 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
10679 return false;
10680 }
10681 // For memmove and friends, copy backwards.
10682 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
10683 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
10684 return false;
10685 Direction = -1;
10686 } else if (!Move && SrcOffset >= DestOffset &&
10687 SrcOffset - DestOffset < NBytes) {
10688 // Src is inside the destination region for memcpy: invalid.
10689 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
10690 return false;
10691 }
10692 }
10693
10694 while (true) {
10695 APValue Val;
10696 // FIXME: Set WantObjectRepresentation to true if we're copying a
10697 // char-like type?
10698 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
10699 !handleAssignment(Info, E, Dest, T, Val))
10700 return false;
10701 // Do not iterate past the last element; if we're copying backwards, that
10702 // might take us off the start of the array.
10703 if (--NElems == 0)
10704 return true;
10705 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
10706 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
10707 return false;
10708 }
10709 }
10710
10711 default:
10712 return false;
10713 }
10714}
10715
10716static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
10717 APValue &Result, const InitListExpr *ILE,
10718 QualType AllocType);
10719static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
10720 APValue &Result,
10721 const CXXConstructExpr *CCE,
10722 QualType AllocType);
10723
10724bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) {
10725 if (!Info.getLangOpts().CPlusPlus20)
10726 Info.CCEDiag(E, diag::note_constexpr_new);
10727
10728 // We cannot speculatively evaluate a delete expression.
10729 if (Info.SpeculativeEvaluationDepth)
10730 return false;
10731
10732 FunctionDecl *OperatorNew = E->getOperatorNew();
10733 QualType AllocType = E->getAllocatedType();
10734 QualType TargetType = AllocType;
10735
10736 bool IsNothrow = false;
10737 bool IsPlacement = false;
10738
10739 if (E->getNumPlacementArgs() == 1 &&
10740 E->getPlacementArg(0)->getType()->isNothrowT()) {
10741 // The only new-placement list we support is of the form (std::nothrow).
10742 //
10743 // FIXME: There is no restriction on this, but it's not clear that any
10744 // other form makes any sense. We get here for cases such as:
10745 //
10746 // new (std::align_val_t{N}) X(int)
10747 //
10748 // (which should presumably be valid only if N is a multiple of
10749 // alignof(int), and in any case can't be deallocated unless N is
10750 // alignof(X) and X has new-extended alignment).
10751 LValue Nothrow;
10752 if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info))
10753 return false;
10754 IsNothrow = true;
10755 } else if (OperatorNew->isReservedGlobalPlacementOperator()) {
10756 if (Info.CurrentCall->isStdFunction() || Info.getLangOpts().CPlusPlus26 ||
10757 (Info.CurrentCall->CanEvalMSConstexpr &&
10758 OperatorNew->hasAttr<MSConstexprAttr>())) {
10759 if (!EvaluatePointer(E->getPlacementArg(0), Result, Info))
10760 return false;
10761 if (Result.Designator.Invalid)
10762 return false;
10763 TargetType = E->getPlacementArg(0)->getType();
10764 IsPlacement = true;
10765 } else {
10766 Info.FFDiag(E, diag::note_constexpr_new_placement)
10767 << /*C++26 feature*/ 1 << E->getSourceRange();
10768 return false;
10769 }
10770 } else if (E->getNumPlacementArgs()) {
10771 Info.FFDiag(E, diag::note_constexpr_new_placement)
10772 << /*Unsupported*/ 0 << E->getSourceRange();
10773 return false;
10774 } else if (!OperatorNew
10775 ->isUsableAsGlobalAllocationFunctionInConstantEvaluation()) {
10776 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
10777 << isa<CXXMethodDecl>(OperatorNew) << OperatorNew;
10778 return false;
10779 }
10780
10781 const Expr *Init = E->getInitializer();
10782 const InitListExpr *ResizedArrayILE = nullptr;
10783 const CXXConstructExpr *ResizedArrayCCE = nullptr;
10784 bool ValueInit = false;
10785
10786 if (std::optional<const Expr *> ArraySize = E->getArraySize()) {
10787 const Expr *Stripped = *ArraySize;
10788 for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
10789 Stripped = ICE->getSubExpr())
10790 if (ICE->getCastKind() != CK_NoOp &&
10791 ICE->getCastKind() != CK_IntegralCast)
10792 break;
10793
10794 llvm::APSInt ArrayBound;
10795 if (!EvaluateInteger(Stripped, ArrayBound, Info))
10796 return false;
10797
10798 // C++ [expr.new]p9:
10799 // The expression is erroneous if:
10800 // -- [...] its value before converting to size_t [or] applying the
10801 // second standard conversion sequence is less than zero
10802 if (ArrayBound.isSigned() && ArrayBound.isNegative()) {
10803 if (IsNothrow)
10804 return ZeroInitialization(E);
10805
10806 Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative)
10807 << ArrayBound << (*ArraySize)->getSourceRange();
10808 return false;
10809 }
10810
10811 // -- its value is such that the size of the allocated object would
10812 // exceed the implementation-defined limit
10813 if (!Info.CheckArraySize(ArraySize.value()->getExprLoc(),
10815 Info.Ctx, AllocType, ArrayBound),
10816 ArrayBound.getZExtValue(), /*Diag=*/!IsNothrow)) {
10817 if (IsNothrow)
10818 return ZeroInitialization(E);
10819 return false;
10820 }
10821
10822 // -- the new-initializer is a braced-init-list and the number of
10823 // array elements for which initializers are provided [...]
10824 // exceeds the number of elements to initialize
10825 if (!Init) {
10826 // No initialization is performed.
10827 } else if (isa<CXXScalarValueInitExpr>(Init) ||
10829 ValueInit = true;
10830 } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) {
10831 ResizedArrayCCE = CCE;
10832 } else {
10833 auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType());
10834 assert(CAT && "unexpected type for array initializer");
10835
10836 unsigned Bits =
10837 std::max(CAT->getSizeBitWidth(), ArrayBound.getBitWidth());
10838 llvm::APInt InitBound = CAT->getSize().zext(Bits);
10839 llvm::APInt AllocBound = ArrayBound.zext(Bits);
10840 if (InitBound.ugt(AllocBound)) {
10841 if (IsNothrow)
10842 return ZeroInitialization(E);
10843
10844 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small)
10845 << toString(AllocBound, 10, /*Signed=*/false)
10846 << toString(InitBound, 10, /*Signed=*/false)
10847 << (*ArraySize)->getSourceRange();
10848 return false;
10849 }
10850
10851 // If the sizes differ, we must have an initializer list, and we need
10852 // special handling for this case when we initialize.
10853 if (InitBound != AllocBound)
10854 ResizedArrayILE = cast<InitListExpr>(Init);
10855 }
10856
10857 AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr,
10858 ArraySizeModifier::Normal, 0);
10859 } else {
10860 assert(!AllocType->isArrayType() &&
10861 "array allocation with non-array new");
10862 }
10863
10864 APValue *Val;
10865 if (IsPlacement) {
10867 struct FindObjectHandler {
10868 EvalInfo &Info;
10869 const Expr *E;
10870 QualType AllocType;
10871 const AccessKinds AccessKind;
10872 APValue *Value;
10873
10874 typedef bool result_type;
10875 bool failed() { return false; }
10876 bool checkConst(QualType QT) {
10877 if (QT.isConstQualified()) {
10878 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
10879 return false;
10880 }
10881 return true;
10882 }
10883 bool found(APValue &Subobj, QualType SubobjType,
10884 APValue::LValueBase Base) {
10885 if (!checkConst(SubobjType))
10886 return false;
10887 // FIXME: Reject the cases where [basic.life]p8 would not permit the
10888 // old name of the object to be used to name the new object.
10889 unsigned SubobjectSize = 1;
10890 unsigned AllocSize = 1;
10891 if (auto *CAT = dyn_cast<ConstantArrayType>(AllocType))
10892 AllocSize = CAT->getZExtSize();
10893 if (auto *CAT = dyn_cast<ConstantArrayType>(SubobjType))
10894 SubobjectSize = CAT->getZExtSize();
10895 if (SubobjectSize < AllocSize ||
10896 !Info.Ctx.hasSimilarType(Info.Ctx.getBaseElementType(SubobjType),
10897 Info.Ctx.getBaseElementType(AllocType))) {
10898 Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type)
10899 << SubobjType << AllocType;
10900 return false;
10901 }
10902 Value = &Subobj;
10903 return true;
10904 }
10905 bool found(APSInt &Value, QualType SubobjType) {
10906 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
10907 return false;
10908 }
10909 bool found(APFloat &Value, QualType SubobjType) {
10910 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
10911 return false;
10912 }
10913 } Handler = {Info, E, AllocType, AK, nullptr};
10914
10915 CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType);
10916 if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler))
10917 return false;
10918
10919 Val = Handler.Value;
10920
10921 // [basic.life]p1:
10922 // The lifetime of an object o of type T ends when [...] the storage
10923 // which the object occupies is [...] reused by an object that is not
10924 // nested within o (6.6.2).
10925 *Val = APValue();
10926 } else {
10927 // Perform the allocation and obtain a pointer to the resulting object.
10928 Val = Info.createHeapAlloc(E, AllocType, Result);
10929 if (!Val)
10930 return false;
10931 }
10932
10933 if (ValueInit) {
10934 ImplicitValueInitExpr VIE(AllocType);
10935 if (!EvaluateInPlace(*Val, Info, Result, &VIE))
10936 return false;
10937 } else if (ResizedArrayILE) {
10938 if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE,
10939 AllocType))
10940 return false;
10941 } else if (ResizedArrayCCE) {
10942 if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE,
10943 AllocType))
10944 return false;
10945 } else if (Init) {
10946 if (!EvaluateInPlace(*Val, Info, Result, Init))
10947 return false;
10948 } else if (!handleDefaultInitValue(AllocType, *Val)) {
10949 return false;
10950 }
10951
10952 // Array new returns a pointer to the first element, not a pointer to the
10953 // array.
10954 if (auto *AT = AllocType->getAsArrayTypeUnsafe())
10955 Result.addArray(Info, E, cast<ConstantArrayType>(AT));
10956
10957 return true;
10958}
10959//===----------------------------------------------------------------------===//
10960// Member Pointer Evaluation
10961//===----------------------------------------------------------------------===//
10962
10963namespace {
10964class MemberPointerExprEvaluator
10965 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
10966 MemberPtr &Result;
10967
10968 bool Success(const ValueDecl *D) {
10969 Result = MemberPtr(D);
10970 return true;
10971 }
10972public:
10973
10974 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
10975 : ExprEvaluatorBaseTy(Info), Result(Result) {}
10976
10977 bool Success(const APValue &V, const Expr *E) {
10978 Result.setFrom(V);
10979 return true;
10980 }
10981 bool ZeroInitialization(const Expr *E) {
10982 return Success((const ValueDecl*)nullptr);
10983 }
10984
10985 bool VisitCastExpr(const CastExpr *E);
10986 bool VisitUnaryAddrOf(const UnaryOperator *E);
10987};
10988} // end anonymous namespace
10989
10990static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
10991 EvalInfo &Info) {
10992 assert(!E->isValueDependent());
10993 assert(E->isPRValue() && E->getType()->isMemberPointerType());
10994 return MemberPointerExprEvaluator(Info, Result).Visit(E);
10995}
10996
10997bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
10998 switch (E->getCastKind()) {
10999 default:
11000 return ExprEvaluatorBaseTy::VisitCastExpr(E);
11001
11002 case CK_NullToMemberPointer:
11003 VisitIgnoredValue(E->getSubExpr());
11004 return ZeroInitialization(E);
11005
11006 case CK_BaseToDerivedMemberPointer: {
11007 if (!Visit(E->getSubExpr()))
11008 return false;
11009 if (E->path_empty())
11010 return true;
11011 // Base-to-derived member pointer casts store the path in derived-to-base
11012 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
11013 // the wrong end of the derived->base arc, so stagger the path by one class.
11014 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
11015 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
11016 PathI != PathE; ++PathI) {
11017 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
11018 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
11019 if (!Result.castToDerived(Derived))
11020 return Error(E);
11021 }
11022 if (!Result.castToDerived(E->getType()
11023 ->castAs<MemberPointerType>()
11024 ->getMostRecentCXXRecordDecl()))
11025 return Error(E);
11026 return true;
11027 }
11028
11029 case CK_DerivedToBaseMemberPointer:
11030 if (!Visit(E->getSubExpr()))
11031 return false;
11032 for (CastExpr::path_const_iterator PathI = E->path_begin(),
11033 PathE = E->path_end(); PathI != PathE; ++PathI) {
11034 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
11035 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
11036 if (!Result.castToBase(Base))
11037 return Error(E);
11038 }
11039 return true;
11040 }
11041}
11042
11043bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
11044 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
11045 // member can be formed.
11046 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
11047}
11048
11049//===----------------------------------------------------------------------===//
11050// Record Evaluation
11051//===----------------------------------------------------------------------===//
11052
11053namespace {
11054 class RecordExprEvaluator
11055 : public ExprEvaluatorBase<RecordExprEvaluator> {
11056 const LValue &This;
11057 APValue &Result;
11058 public:
11059
11060 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
11061 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
11062
11063 bool Success(const APValue &V, const Expr *E) {
11064 Result = V;
11065 return true;
11066 }
11067 bool ZeroInitialization(const Expr *E) {
11068 return ZeroInitialization(E, E->getType());
11069 }
11070 bool ZeroInitialization(const Expr *E, QualType T);
11071
11072 bool VisitCallExpr(const CallExpr *E) {
11073 return handleCallExpr(E, Result, &This);
11074 }
11075 bool VisitCastExpr(const CastExpr *E);
11076 bool VisitInitListExpr(const InitListExpr *E);
11077 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
11078 return VisitCXXConstructExpr(E, E->getType());
11079 }
11080 bool VisitLambdaExpr(const LambdaExpr *E);
11081 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
11082 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
11083 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
11084 bool VisitBinCmp(const BinaryOperator *E);
11085 bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E);
11086 bool VisitCXXParenListOrInitListExpr(const Expr *ExprToVisit,
11087 ArrayRef<Expr *> Args);
11088 bool VisitDesignatedInitUpdateExpr(const DesignatedInitUpdateExpr *E);
11089 };
11090}
11091
11092/// Perform zero-initialization on an object of non-union class type.
11093/// C++11 [dcl.init]p5:
11094/// To zero-initialize an object or reference of type T means:
11095/// [...]
11096/// -- if T is a (possibly cv-qualified) non-union class type,
11097/// each non-static data member and each base-class subobject is
11098/// zero-initialized
11099static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
11100 const RecordDecl *RD,
11101 const LValue &This, APValue &Result) {
11102 assert(!RD->isUnion() && "Expected non-union class type");
11103 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
11104 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
11105 RD->getNumFields());
11106
11107 if (RD->isInvalidDecl()) return false;
11108 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
11109
11110 if (CD) {
11111 unsigned Index = 0;
11113 End = CD->bases_end(); I != End; ++I, ++Index) {
11114 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
11115 LValue Subobject = This;
11116 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
11117 return false;
11118 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
11119 Result.getStructBase(Index)))
11120 return false;
11121 }
11122 }
11123
11124 for (const auto *I : RD->fields()) {
11125 // -- if T is a reference type, no initialization is performed.
11126 if (I->isUnnamedBitField() || I->getType()->isReferenceType())
11127 continue;
11128
11129 LValue Subobject = This;
11130 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
11131 return false;
11132
11133 ImplicitValueInitExpr VIE(I->getType());
11134 if (!EvaluateInPlace(
11135 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
11136 return false;
11137 }
11138
11139 return true;
11140}
11141
11142bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
11143 const auto *RD = T->castAsRecordDecl();
11144 if (RD->isInvalidDecl()) return false;
11145 if (RD->isUnion()) {
11146 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
11147 // object's first non-static named data member is zero-initialized
11149 while (I != RD->field_end() && (*I)->isUnnamedBitField())
11150 ++I;
11151 if (I == RD->field_end()) {
11152 Result = APValue((const FieldDecl*)nullptr);
11153 return true;
11154 }
11155
11156 LValue Subobject = This;
11157 if (!HandleLValueMember(Info, E, Subobject, *I))
11158 return false;
11159 Result = APValue(*I);
11160 ImplicitValueInitExpr VIE(I->getType());
11161 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
11162 }
11163
11164 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
11165 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
11166 return false;
11167 }
11168
11169 return HandleClassZeroInitialization(Info, E, RD, This, Result);
11170}
11171
11172bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
11173 switch (E->getCastKind()) {
11174 default:
11175 return ExprEvaluatorBaseTy::VisitCastExpr(E);
11176
11177 case CK_ConstructorConversion:
11178 return Visit(E->getSubExpr());
11179
11180 case CK_DerivedToBase:
11181 case CK_UncheckedDerivedToBase: {
11182 APValue DerivedObject;
11183 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
11184 return false;
11185 if (!DerivedObject.isStruct())
11186 return Error(E->getSubExpr());
11187
11188 // Derived-to-base rvalue conversion: just slice off the derived part.
11189 APValue *Value = &DerivedObject;
11190 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
11191 for (CastExpr::path_const_iterator PathI = E->path_begin(),
11192 PathE = E->path_end(); PathI != PathE; ++PathI) {
11193 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
11194 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
11195 Value = &Value->getStructBase(getBaseIndex(RD, Base));
11196 RD = Base;
11197 }
11198 Result = *Value;
11199 return true;
11200 }
11201 case CK_HLSLAggregateSplatCast: {
11202 APValue Val;
11203 QualType ValTy;
11204
11205 if (!hlslAggSplatHelper(Info, E->getSubExpr(), Val, ValTy))
11206 return false;
11207
11208 unsigned NEls = elementwiseSize(Info, E->getType());
11209 // splat our Val
11210 SmallVector<APValue> SplatEls(NEls, Val);
11211 SmallVector<QualType> SplatType(NEls, ValTy);
11212
11213 // cast the elements and construct our struct result
11214 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
11215 if (!constructAggregate(Info, FPO, E, Result, E->getType(), SplatEls,
11216 SplatType))
11217 return false;
11218
11219 return true;
11220 }
11221 case CK_HLSLElementwiseCast: {
11222 SmallVector<APValue> SrcEls;
11223 SmallVector<QualType> SrcTypes;
11224
11225 if (!hlslElementwiseCastHelper(Info, E->getSubExpr(), E->getType(), SrcEls,
11226 SrcTypes))
11227 return false;
11228
11229 // cast the elements and construct our struct result
11230 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
11231 if (!constructAggregate(Info, FPO, E, Result, E->getType(), SrcEls,
11232 SrcTypes))
11233 return false;
11234
11235 return true;
11236 }
11237 case CK_ToUnion: {
11238 const FieldDecl *Field = E->getTargetUnionField();
11239 LValue Subobject = This;
11240 if (!HandleLValueMember(Info, E, Subobject, Field))
11241 return false;
11242 Result = APValue(Field);
11243 if (!EvaluateInPlace(Result.getUnionValue(), Info, Subobject,
11244 E->getSubExpr()))
11245 return false;
11246 if (Field->isBitField()) {
11247 if (!truncateBitfieldValue(Info, E->getSubExpr(), Result.getUnionValue(),
11248 Field))
11249 return false;
11250 }
11251 return true;
11252 }
11253 }
11254}
11255
11256bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
11257 if (E->isTransparent())
11258 return Visit(E->getInit(0));
11259 return VisitCXXParenListOrInitListExpr(E, E->inits());
11260}
11261
11262bool RecordExprEvaluator::VisitCXXParenListOrInitListExpr(
11263 const Expr *ExprToVisit, ArrayRef<Expr *> Args) {
11264 const auto *RD = ExprToVisit->getType()->castAsRecordDecl();
11265 if (RD->isInvalidDecl()) return false;
11266 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
11267 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
11268
11269 EvalInfo::EvaluatingConstructorRAII EvalObj(
11270 Info,
11271 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
11272 CXXRD && CXXRD->getNumBases());
11273
11274 if (RD->isUnion()) {
11275 const FieldDecl *Field;
11276 if (auto *ILE = dyn_cast<InitListExpr>(ExprToVisit)) {
11277 Field = ILE->getInitializedFieldInUnion();
11278 } else if (auto *PLIE = dyn_cast<CXXParenListInitExpr>(ExprToVisit)) {
11279 Field = PLIE->getInitializedFieldInUnion();
11280 } else {
11281 llvm_unreachable(
11282 "Expression is neither an init list nor a C++ paren list");
11283 }
11284
11285 Result = APValue(Field);
11286 if (!Field)
11287 return true;
11288
11289 // If the initializer list for a union does not contain any elements, the
11290 // first element of the union is value-initialized.
11291 // FIXME: The element should be initialized from an initializer list.
11292 // Is this difference ever observable for initializer lists which
11293 // we don't build?
11294 ImplicitValueInitExpr VIE(Field->getType());
11295 const Expr *InitExpr = Args.empty() ? &VIE : Args[0];
11296
11297 LValue Subobject = This;
11298 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
11299 return false;
11300
11301 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
11302 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
11303 isa<CXXDefaultInitExpr>(InitExpr));
11304
11305 if (EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr)) {
11306 if (Field->isBitField())
11307 return truncateBitfieldValue(Info, InitExpr, Result.getUnionValue(),
11308 Field);
11309 return true;
11310 }
11311
11312 return false;
11313 }
11314
11315 if (!Result.hasValue())
11316 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
11317 RD->getNumFields());
11318 unsigned ElementNo = 0;
11319 bool Success = true;
11320
11321 // Initialize base classes.
11322 if (CXXRD && CXXRD->getNumBases()) {
11323 for (const auto &Base : CXXRD->bases()) {
11324 assert(ElementNo < Args.size() && "missing init for base class");
11325 const Expr *Init = Args[ElementNo];
11326
11327 LValue Subobject = This;
11328 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
11329 return false;
11330
11331 APValue &FieldVal = Result.getStructBase(ElementNo);
11332 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
11333 if (!Info.noteFailure())
11334 return false;
11335 Success = false;
11336 }
11337 ++ElementNo;
11338 }
11339
11340 EvalObj.finishedConstructingBases();
11341 }
11342
11343 // Initialize members.
11344 for (const auto *Field : RD->fields()) {
11345 // Anonymous bit-fields are not considered members of the class for
11346 // purposes of aggregate initialization.
11347 if (Field->isUnnamedBitField())
11348 continue;
11349
11350 LValue Subobject = This;
11351
11352 bool HaveInit = ElementNo < Args.size();
11353
11354 // FIXME: Diagnostics here should point to the end of the initializer
11355 // list, not the start.
11356 if (!HandleLValueMember(Info, HaveInit ? Args[ElementNo] : ExprToVisit,
11357 Subobject, Field, &Layout))
11358 return false;
11359
11360 // Perform an implicit value-initialization for members beyond the end of
11361 // the initializer list.
11362 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
11363 const Expr *Init = HaveInit ? Args[ElementNo++] : &VIE;
11364
11365 // If this is a child of a DesignatedInitUpdateExpr, skip elements which
11366 // aren't supposed to be modified.
11367 if (isa<NoInitExpr>(Init))
11368 continue;
11369
11370 if (Field->getType()->isIncompleteArrayType()) {
11371 if (auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType())) {
11372 if (!CAT->isZeroSize()) {
11373 // Bail out for now. This might sort of "work", but the rest of the
11374 // code isn't really prepared to handle it.
11375 Info.FFDiag(Init, diag::note_constexpr_unsupported_flexible_array);
11376 return false;
11377 }
11378 }
11379 }
11380
11381 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
11382 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
11384
11385 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
11386 if (Field->getType()->isReferenceType()) {
11387 LValue Result;
11389 FieldVal)) {
11390 if (!Info.noteFailure())
11391 return false;
11392 Success = false;
11393 }
11394 } else if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
11395 (Field->isBitField() &&
11396 !truncateBitfieldValue(Info, Init, FieldVal, Field))) {
11397 if (!Info.noteFailure())
11398 return false;
11399 Success = false;
11400 }
11401 }
11402
11403 EvalObj.finishedConstructingFields();
11404
11405 return Success;
11406}
11407
11408bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
11409 QualType T) {
11410 // Note that E's type is not necessarily the type of our class here; we might
11411 // be initializing an array element instead.
11412 const CXXConstructorDecl *FD = E->getConstructor();
11413 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
11414
11415 bool ZeroInit = E->requiresZeroInitialization();
11416 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
11417 if (ZeroInit)
11418 return ZeroInitialization(E, T);
11419
11420 return handleDefaultInitValue(T, Result);
11421 }
11422
11423 const FunctionDecl *Definition = nullptr;
11424 auto Body = FD->getBody(Definition);
11425
11426 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
11427 return false;
11428
11429 // Avoid materializing a temporary for an elidable copy/move constructor.
11430 if (E->isElidable() && !ZeroInit) {
11431 // FIXME: This only handles the simplest case, where the source object
11432 // is passed directly as the first argument to the constructor.
11433 // This should also handle stepping though implicit casts and
11434 // and conversion sequences which involve two steps, with a
11435 // conversion operator followed by a converting constructor.
11436 const Expr *SrcObj = E->getArg(0);
11437 assert(SrcObj->isTemporaryObject(Info.Ctx, FD->getParent()));
11438 assert(Info.Ctx.hasSameUnqualifiedType(E->getType(), SrcObj->getType()));
11439 if (const MaterializeTemporaryExpr *ME =
11440 dyn_cast<MaterializeTemporaryExpr>(SrcObj))
11441 return Visit(ME->getSubExpr());
11442 }
11443
11444 if (ZeroInit && !ZeroInitialization(E, T))
11445 return false;
11446
11447 auto Args = ArrayRef(E->getArgs(), E->getNumArgs());
11448 return HandleConstructorCall(E, This, Args,
11450 Result);
11451}
11452
11453bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
11454 const CXXInheritedCtorInitExpr *E) {
11455 if (!Info.CurrentCall) {
11456 assert(Info.checkingPotentialConstantExpression());
11457 return false;
11458 }
11459
11460 const CXXConstructorDecl *FD = E->getConstructor();
11461 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
11462 return false;
11463
11464 const FunctionDecl *Definition = nullptr;
11465 auto Body = FD->getBody(Definition);
11466
11467 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
11468 return false;
11469
11470 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
11472 Result);
11473}
11474
11475bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
11476 const CXXStdInitializerListExpr *E) {
11477 const ConstantArrayType *ArrayType =
11478 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
11479
11480 LValue Array;
11481 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
11482 return false;
11483
11484 assert(ArrayType && "unexpected type for array initializer");
11485
11486 // Get a pointer to the first element of the array.
11487 Array.addArray(Info, E, ArrayType);
11488
11489 // FIXME: What if the initializer_list type has base classes, etc?
11490 Result = APValue(APValue::UninitStruct(), 0, 2);
11491 Array.moveInto(Result.getStructField(0));
11492
11493 auto *Record = E->getType()->castAsRecordDecl();
11494 RecordDecl::field_iterator Field = Record->field_begin();
11495 assert(Field != Record->field_end() &&
11496 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
11497 ArrayType->getElementType()) &&
11498 "Expected std::initializer_list first field to be const E *");
11499 ++Field;
11500 assert(Field != Record->field_end() &&
11501 "Expected std::initializer_list to have two fields");
11502
11503 if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType())) {
11504 // Length.
11505 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
11506 } else {
11507 // End pointer.
11508 assert(Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
11509 ArrayType->getElementType()) &&
11510 "Expected std::initializer_list second field to be const E *");
11511 if (!HandleLValueArrayAdjustment(Info, E, Array,
11512 ArrayType->getElementType(),
11513 ArrayType->getZExtSize()))
11514 return false;
11515 Array.moveInto(Result.getStructField(1));
11516 }
11517
11518 assert(++Field == Record->field_end() &&
11519 "Expected std::initializer_list to only have two fields");
11520
11521 return true;
11522}
11523
11524bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
11525 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
11526 if (ClosureClass->isInvalidDecl())
11527 return false;
11528
11529 const size_t NumFields = ClosureClass->getNumFields();
11530
11531 assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
11532 E->capture_init_end()) &&
11533 "The number of lambda capture initializers should equal the number of "
11534 "fields within the closure type");
11535
11536 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
11537 // Iterate through all the lambda's closure object's fields and initialize
11538 // them.
11539 auto *CaptureInitIt = E->capture_init_begin();
11540 bool Success = true;
11541 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(ClosureClass);
11542 for (const auto *Field : ClosureClass->fields()) {
11543 assert(CaptureInitIt != E->capture_init_end());
11544 // Get the initializer for this field
11545 Expr *const CurFieldInit = *CaptureInitIt++;
11546
11547 // If there is no initializer, either this is a VLA or an error has
11548 // occurred.
11549 if (!CurFieldInit || CurFieldInit->containsErrors())
11550 return Error(E);
11551
11552 LValue Subobject = This;
11553
11554 if (!HandleLValueMember(Info, E, Subobject, Field, &Layout))
11555 return false;
11556
11557 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
11558 if (!EvaluateInPlace(FieldVal, Info, Subobject, CurFieldInit)) {
11559 if (!Info.keepEvaluatingAfterFailure())
11560 return false;
11561 Success = false;
11562 }
11563 }
11564 return Success;
11565}
11566
11567bool RecordExprEvaluator::VisitDesignatedInitUpdateExpr(
11568 const DesignatedInitUpdateExpr *E) {
11569 if (!Visit(E->getBase()))
11570 return false;
11571 return Visit(E->getUpdater());
11572}
11573
11574static bool EvaluateRecord(const Expr *E, const LValue &This,
11575 APValue &Result, EvalInfo &Info) {
11576 assert(!E->isValueDependent());
11577 assert(E->isPRValue() && E->getType()->isRecordType() &&
11578 "can't evaluate expression as a record rvalue");
11579 return RecordExprEvaluator(Info, This, Result).Visit(E);
11580}
11581
11582//===----------------------------------------------------------------------===//
11583// Temporary Evaluation
11584//
11585// Temporaries are represented in the AST as rvalues, but generally behave like
11586// lvalues. The full-object of which the temporary is a subobject is implicitly
11587// materialized so that a reference can bind to it.
11588//===----------------------------------------------------------------------===//
11589namespace {
11590class TemporaryExprEvaluator
11591 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
11592public:
11593 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
11594 LValueExprEvaluatorBaseTy(Info, Result, false) {}
11595
11596 /// Visit an expression which constructs the value of this temporary.
11597 bool VisitConstructExpr(const Expr *E) {
11598 APValue &Value = Info.CurrentCall->createTemporary(
11599 E, E->getType(), ScopeKind::FullExpression, Result);
11600 return EvaluateInPlace(Value, Info, Result, E);
11601 }
11602
11603 bool VisitCastExpr(const CastExpr *E) {
11604 switch (E->getCastKind()) {
11605 default:
11606 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
11607
11608 case CK_ConstructorConversion:
11609 return VisitConstructExpr(E->getSubExpr());
11610 }
11611 }
11612 bool VisitInitListExpr(const InitListExpr *E) {
11613 return VisitConstructExpr(E);
11614 }
11615 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
11616 return VisitConstructExpr(E);
11617 }
11618 bool VisitCallExpr(const CallExpr *E) {
11619 return VisitConstructExpr(E);
11620 }
11621 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
11622 return VisitConstructExpr(E);
11623 }
11624 bool VisitLambdaExpr(const LambdaExpr *E) {
11625 return VisitConstructExpr(E);
11626 }
11627};
11628} // end anonymous namespace
11629
11630/// Evaluate an expression of record type as a temporary.
11631static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
11632 assert(!E->isValueDependent());
11633 assert(E->isPRValue() && E->getType()->isRecordType());
11634 return TemporaryExprEvaluator(Info, Result).Visit(E);
11635}
11636
11637//===----------------------------------------------------------------------===//
11638// Vector Evaluation
11639//===----------------------------------------------------------------------===//
11640
11641namespace {
11642 class VectorExprEvaluator
11643 : public ExprEvaluatorBase<VectorExprEvaluator> {
11644 APValue &Result;
11645 public:
11646
11647 VectorExprEvaluator(EvalInfo &info, APValue &Result)
11648 : ExprEvaluatorBaseTy(info), Result(Result) {}
11649
11650 bool Success(ArrayRef<APValue> V, const Expr *E) {
11651 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
11652 // FIXME: remove this APValue copy.
11653 Result = APValue(V.data(), V.size());
11654 return true;
11655 }
11656 bool Success(const APValue &V, const Expr *E) {
11657 assert(V.isVector());
11658 Result = V;
11659 return true;
11660 }
11661 bool ZeroInitialization(const Expr *E);
11662
11663 bool VisitUnaryReal(const UnaryOperator *E)
11664 { return Visit(E->getSubExpr()); }
11665 bool VisitCastExpr(const CastExpr* E);
11666 bool VisitInitListExpr(const InitListExpr *E);
11667 bool VisitUnaryImag(const UnaryOperator *E);
11668 bool VisitBinaryOperator(const BinaryOperator *E);
11669 bool VisitUnaryOperator(const UnaryOperator *E);
11670 bool VisitCallExpr(const CallExpr *E);
11671 bool VisitConvertVectorExpr(const ConvertVectorExpr *E);
11672 bool VisitShuffleVectorExpr(const ShuffleVectorExpr *E);
11673
11674 // FIXME: Missing: conditional operator (for GNU
11675 // conditional select), ExtVectorElementExpr
11676 };
11677} // end anonymous namespace
11678
11679static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
11680 assert(E->isPRValue() && E->getType()->isVectorType() &&
11681 "not a vector prvalue");
11682 return VectorExprEvaluator(Info, Result).Visit(E);
11683}
11684
11685static llvm::APInt ConvertBoolVectorToInt(const APValue &Val) {
11686 assert(Val.isVector() && "expected vector APValue");
11687 unsigned NumElts = Val.getVectorLength();
11688
11689 // Each element is one bit, so create an integer with NumElts bits.
11690 llvm::APInt Result(NumElts, 0);
11691
11692 for (unsigned I = 0; I < NumElts; ++I) {
11693 const APValue &Elt = Val.getVectorElt(I);
11694 assert(Elt.isInt() && "expected integer element in bool vector");
11695
11696 if (Elt.getInt().getBoolValue())
11697 Result.setBit(I);
11698 }
11699
11700 return Result;
11701}
11702
11703bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
11704 const VectorType *VTy = E->getType()->castAs<VectorType>();
11705 unsigned NElts = VTy->getNumElements();
11706
11707 const Expr *SE = E->getSubExpr();
11708 QualType SETy = SE->getType();
11709
11710 switch (E->getCastKind()) {
11711 case CK_VectorSplat: {
11712 APValue Val = APValue();
11713 if (SETy->isIntegerType()) {
11714 APSInt IntResult;
11715 if (!EvaluateInteger(SE, IntResult, Info))
11716 return false;
11717 Val = APValue(std::move(IntResult));
11718 } else if (SETy->isRealFloatingType()) {
11719 APFloat FloatResult(0.0);
11720 if (!EvaluateFloat(SE, FloatResult, Info))
11721 return false;
11722 Val = APValue(std::move(FloatResult));
11723 } else {
11724 return Error(E);
11725 }
11726
11727 // Splat and create vector APValue.
11728 SmallVector<APValue, 4> Elts(NElts, Val);
11729 return Success(Elts, E);
11730 }
11731 case CK_BitCast: {
11732 APValue SVal;
11733 if (!Evaluate(SVal, Info, SE))
11734 return false;
11735
11736 if (!SVal.isInt() && !SVal.isFloat() && !SVal.isVector()) {
11737 // Give up if the input isn't an int, float, or vector. For example, we
11738 // reject "(v4i16)(intptr_t)&a".
11739 Info.FFDiag(E, diag::note_constexpr_invalid_cast)
11740 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
11741 << Info.Ctx.getLangOpts().CPlusPlus;
11742 return false;
11743 }
11744
11745 if (!handleRValueToRValueBitCast(Info, Result, SVal, E))
11746 return false;
11747
11748 return true;
11749 }
11750 case CK_HLSLVectorTruncation: {
11751 APValue Val;
11752 SmallVector<APValue, 4> Elements;
11753 if (!EvaluateVector(SE, Val, Info))
11754 return Error(E);
11755 for (unsigned I = 0; I < NElts; I++)
11756 Elements.push_back(Val.getVectorElt(I));
11757 return Success(Elements, E);
11758 }
11759 case CK_HLSLMatrixTruncation: {
11760 // Matrix truncation occurs in row-major order.
11761 APValue Val;
11762 if (!EvaluateMatrix(SE, Val, Info))
11763 return Error(E);
11764 SmallVector<APValue, 16> Elements;
11765 for (unsigned Row = 0;
11766 Row < Val.getMatrixNumRows() && Elements.size() < NElts; Row++)
11767 for (unsigned Col = 0;
11768 Col < Val.getMatrixNumColumns() && Elements.size() < NElts; Col++)
11769 Elements.push_back(Val.getMatrixElt(Row, Col));
11770 return Success(Elements, E);
11771 }
11772 case CK_HLSLAggregateSplatCast: {
11773 APValue Val;
11774 QualType ValTy;
11775
11776 if (!hlslAggSplatHelper(Info, SE, Val, ValTy))
11777 return false;
11778
11779 // cast our Val once.
11781 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
11782 if (!handleScalarCast(Info, FPO, E, ValTy, VTy->getElementType(), Val,
11783 Result))
11784 return false;
11785
11786 SmallVector<APValue, 4> SplatEls(NElts, Result);
11787 return Success(SplatEls, E);
11788 }
11789 case CK_HLSLElementwiseCast: {
11790 SmallVector<APValue> SrcVals;
11791 SmallVector<QualType> SrcTypes;
11792
11793 if (!hlslElementwiseCastHelper(Info, SE, E->getType(), SrcVals, SrcTypes))
11794 return false;
11795
11796 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
11797 SmallVector<QualType, 4> DestTypes(NElts, VTy->getElementType());
11798 SmallVector<APValue, 4> ResultEls(NElts);
11799 if (!handleElementwiseCast(Info, E, FPO, SrcVals, SrcTypes, DestTypes,
11800 ResultEls))
11801 return false;
11802 return Success(ResultEls, E);
11803 }
11804 case CK_IntegralToFloating:
11805 case CK_FloatingToIntegral:
11806 case CK_IntegralCast:
11807 case CK_FloatingCast:
11808 case CK_FloatingToBoolean:
11809 case CK_IntegralToBoolean: {
11810 // These casts apply element-wise when the source is a vector type.
11811 assert(SETy->isVectorType() && "expected vector source type");
11812 APValue SrcVal;
11813 if (!EvaluateVector(SE, SrcVal, Info))
11814 return Error(E);
11815
11816 assert(SrcVal.getVectorLength() == NElts);
11817 QualType SrcEltTy = SETy->castAs<VectorType>()->getElementType();
11818 QualType DstEltTy = VTy->getElementType();
11819 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
11820
11821 SmallVector<APValue, 4> ResultEls(NElts);
11822 for (unsigned I = 0; I < NElts; ++I) {
11823 if (!handleScalarCast(Info, FPO, E, SrcEltTy, DstEltTy,
11824 SrcVal.getVectorElt(I), ResultEls[I]))
11825 return Error(E);
11826 }
11827 return Success(ResultEls, E);
11828 }
11829 default:
11830 return ExprEvaluatorBaseTy::VisitCastExpr(E);
11831 }
11832}
11833
11834bool
11835VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
11836 const VectorType *VT = E->getType()->castAs<VectorType>();
11837 unsigned NumInits = E->getNumInits();
11838 unsigned NumElements = VT->getNumElements();
11839
11840 QualType EltTy = VT->getElementType();
11841 SmallVector<APValue, 4> Elements;
11842
11843 // MFloat8 type doesn't have constants and thus constant folding
11844 // is impossible.
11845 if (EltTy->isMFloat8Type())
11846 return false;
11847
11848 // The number of initializers can be less than the number of
11849 // vector elements. For OpenCL, this can be due to nested vector
11850 // initialization. For GCC compatibility, missing trailing elements
11851 // should be initialized with zeroes.
11852 unsigned CountInits = 0, CountElts = 0;
11853 while (CountElts < NumElements) {
11854 // Handle nested vector initialization.
11855 if (CountInits < NumInits
11856 && E->getInit(CountInits)->getType()->isVectorType()) {
11857 APValue v;
11858 if (!EvaluateVector(E->getInit(CountInits), v, Info))
11859 return Error(E);
11860 unsigned vlen = v.getVectorLength();
11861 for (unsigned j = 0; j < vlen; j++)
11862 Elements.push_back(v.getVectorElt(j));
11863 CountElts += vlen;
11864 } else if (EltTy->isIntegerType()) {
11865 llvm::APSInt sInt(32);
11866 if (CountInits < NumInits) {
11867 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
11868 return false;
11869 } else // trailing integer zero.
11870 sInt = Info.Ctx.MakeIntValue(0, EltTy);
11871 Elements.push_back(APValue(sInt));
11872 CountElts++;
11873 } else {
11874 llvm::APFloat f(0.0);
11875 if (CountInits < NumInits) {
11876 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
11877 return false;
11878 } else // trailing float zero.
11879 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
11880 Elements.push_back(APValue(f));
11881 CountElts++;
11882 }
11883 CountInits++;
11884 }
11885 return Success(Elements, E);
11886}
11887
11888bool
11889VectorExprEvaluator::ZeroInitialization(const Expr *E) {
11890 const auto *VT = E->getType()->castAs<VectorType>();
11891 QualType EltTy = VT->getElementType();
11892 APValue ZeroElement;
11893 if (EltTy->isIntegerType())
11894 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
11895 else
11896 ZeroElement =
11897 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
11898
11899 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
11900 return Success(Elements, E);
11901}
11902
11903bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
11904 VisitIgnoredValue(E->getSubExpr());
11905 return ZeroInitialization(E);
11906}
11907
11908bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
11909 BinaryOperatorKind Op = E->getOpcode();
11910 assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp &&
11911 "Operation not supported on vector types");
11912
11913 if (Op == BO_Comma)
11914 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
11915
11916 Expr *LHS = E->getLHS();
11917 Expr *RHS = E->getRHS();
11918
11919 assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() &&
11920 "Must both be vector types");
11921 // Checking JUST the types are the same would be fine, except shifts don't
11922 // need to have their types be the same (since you always shift by an int).
11923 assert(LHS->getType()->castAs<VectorType>()->getNumElements() ==
11924 E->getType()->castAs<VectorType>()->getNumElements() &&
11925 RHS->getType()->castAs<VectorType>()->getNumElements() ==
11926 E->getType()->castAs<VectorType>()->getNumElements() &&
11927 "All operands must be the same size.");
11928
11929 APValue LHSValue;
11930 APValue RHSValue;
11931 bool LHSOK = Evaluate(LHSValue, Info, LHS);
11932 if (!LHSOK && !Info.noteFailure())
11933 return false;
11934 if (!Evaluate(RHSValue, Info, RHS) || !LHSOK)
11935 return false;
11936
11937 if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue))
11938 return false;
11939
11940 return Success(LHSValue, E);
11941}
11942
11943static std::optional<APValue> handleVectorUnaryOperator(ASTContext &Ctx,
11944 QualType ResultTy,
11946 APValue Elt) {
11947 switch (Op) {
11948 case UO_Plus:
11949 // Nothing to do here.
11950 return Elt;
11951 case UO_Minus:
11952 if (Elt.getKind() == APValue::Int) {
11953 Elt.getInt().negate();
11954 } else {
11955 assert(Elt.getKind() == APValue::Float &&
11956 "Vector can only be int or float type");
11957 Elt.getFloat().changeSign();
11958 }
11959 return Elt;
11960 case UO_Not:
11961 // This is only valid for integral types anyway, so we don't have to handle
11962 // float here.
11963 assert(Elt.getKind() == APValue::Int &&
11964 "Vector operator ~ can only be int");
11965 Elt.getInt().flipAllBits();
11966 return Elt;
11967 case UO_LNot: {
11968 if (Elt.getKind() == APValue::Int) {
11969 Elt.getInt() = !Elt.getInt();
11970 // operator ! on vectors returns -1 for 'truth', so negate it.
11971 Elt.getInt().negate();
11972 return Elt;
11973 }
11974 assert(Elt.getKind() == APValue::Float &&
11975 "Vector can only be int or float type");
11976 // Float types result in an int of the same size, but -1 for true, or 0 for
11977 // false.
11978 APSInt EltResult{Ctx.getIntWidth(ResultTy),
11979 ResultTy->isUnsignedIntegerType()};
11980 if (Elt.getFloat().isZero())
11981 EltResult.setAllBits();
11982 else
11983 EltResult.clearAllBits();
11984
11985 return APValue{EltResult};
11986 }
11987 default:
11988 // FIXME: Implement the rest of the unary operators.
11989 return std::nullopt;
11990 }
11991}
11992
11993bool VectorExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
11994 Expr *SubExpr = E->getSubExpr();
11995 const auto *VD = SubExpr->getType()->castAs<VectorType>();
11996 // This result element type differs in the case of negating a floating point
11997 // vector, since the result type is the a vector of the equivilant sized
11998 // integer.
11999 const QualType ResultEltTy = VD->getElementType();
12000 UnaryOperatorKind Op = E->getOpcode();
12001
12002 APValue SubExprValue;
12003 if (!Evaluate(SubExprValue, Info, SubExpr))
12004 return false;
12005
12006 // FIXME: This vector evaluator someday needs to be changed to be LValue
12007 // aware/keep LValue information around, rather than dealing with just vector
12008 // types directly. Until then, we cannot handle cases where the operand to
12009 // these unary operators is an LValue. The only case I've been able to see
12010 // cause this is operator++ assigning to a member expression (only valid in
12011 // altivec compilations) in C mode, so this shouldn't limit us too much.
12012 if (SubExprValue.isLValue())
12013 return false;
12014
12015 assert(SubExprValue.getVectorLength() == VD->getNumElements() &&
12016 "Vector length doesn't match type?");
12017
12018 SmallVector<APValue, 4> ResultElements;
12019 for (unsigned EltNum = 0; EltNum < VD->getNumElements(); ++EltNum) {
12020 std::optional<APValue> Elt = handleVectorUnaryOperator(
12021 Info.Ctx, ResultEltTy, Op, SubExprValue.getVectorElt(EltNum));
12022 if (!Elt)
12023 return false;
12024 ResultElements.push_back(*Elt);
12025 }
12026 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12027}
12028
12029static bool handleVectorElementCast(EvalInfo &Info, const FPOptions FPO,
12030 const Expr *E, QualType SourceTy,
12031 QualType DestTy, APValue const &Original,
12032 APValue &Result) {
12033 if (SourceTy->isIntegerType()) {
12034 if (DestTy->isRealFloatingType()) {
12035 Result = APValue(APFloat(0.0));
12036 return HandleIntToFloatCast(Info, E, FPO, SourceTy, Original.getInt(),
12037 DestTy, Result.getFloat());
12038 }
12039 if (DestTy->isIntegerType()) {
12040 Result = APValue(
12041 HandleIntToIntCast(Info, E, DestTy, SourceTy, Original.getInt()));
12042 return true;
12043 }
12044 } else if (SourceTy->isRealFloatingType()) {
12045 if (DestTy->isRealFloatingType()) {
12046 Result = Original;
12047 return HandleFloatToFloatCast(Info, E, SourceTy, DestTy,
12048 Result.getFloat());
12049 }
12050 if (DestTy->isIntegerType()) {
12051 Result = APValue(APSInt());
12052 return HandleFloatToIntCast(Info, E, SourceTy, Original.getFloat(),
12053 DestTy, Result.getInt());
12054 }
12055 }
12056
12057 Info.FFDiag(E, diag::err_convertvector_constexpr_unsupported_vector_cast)
12058 << SourceTy << DestTy;
12059 return false;
12060}
12061
12062static bool evalPackBuiltin(const CallExpr *E, EvalInfo &Info, APValue &Result,
12063 llvm::function_ref<APInt(const APSInt &)> PackFn) {
12064 APValue LHS, RHS;
12065 if (!EvaluateAsRValue(Info, E->getArg(0), LHS) ||
12066 !EvaluateAsRValue(Info, E->getArg(1), RHS))
12067 return false;
12068
12069 unsigned LHSVecLen = LHS.getVectorLength();
12070 unsigned RHSVecLen = RHS.getVectorLength();
12071
12072 assert(LHSVecLen != 0 && LHSVecLen == RHSVecLen &&
12073 "pack builtin LHSVecLen must equal to RHSVecLen");
12074
12075 const VectorType *VT0 = E->getArg(0)->getType()->castAs<VectorType>();
12076 const unsigned SrcBits = Info.Ctx.getIntWidth(VT0->getElementType());
12077
12078 const VectorType *DstVT = E->getType()->castAs<VectorType>();
12079 QualType DstElemTy = DstVT->getElementType();
12080 const bool DstIsUnsigned = DstElemTy->isUnsignedIntegerType();
12081
12082 const unsigned SrcPerLane = 128 / SrcBits;
12083 const unsigned Lanes = LHSVecLen * SrcBits / 128;
12084
12086 Out.reserve(LHSVecLen + RHSVecLen);
12087
12088 for (unsigned Lane = 0; Lane != Lanes; ++Lane) {
12089 unsigned base = Lane * SrcPerLane;
12090 for (unsigned I = 0; I != SrcPerLane; ++I)
12091 Out.emplace_back(APValue(
12092 APSInt(PackFn(LHS.getVectorElt(base + I).getInt()), DstIsUnsigned)));
12093 for (unsigned I = 0; I != SrcPerLane; ++I)
12094 Out.emplace_back(APValue(
12095 APSInt(PackFn(RHS.getVectorElt(base + I).getInt()), DstIsUnsigned)));
12096 }
12097
12098 Result = APValue(Out.data(), Out.size());
12099 return true;
12100}
12101
12103 EvalInfo &Info, const CallExpr *Call, APValue &Out,
12104 llvm::function_ref<std::pair<unsigned, int>(unsigned, unsigned)>
12105 GetSourceIndex) {
12106
12107 const auto *VT = Call->getType()->getAs<VectorType>();
12108 if (!VT)
12109 return false;
12110
12111 unsigned ShuffleMask = 0;
12112 APValue A, MaskVector, B;
12113 bool IsVectorMask = false;
12114 bool IsSingleOperand = (Call->getNumArgs() == 2);
12115
12116 if (IsSingleOperand) {
12117 QualType MaskType = Call->getArg(1)->getType();
12118 if (MaskType->isVectorType()) {
12119 IsVectorMask = true;
12120 if (!EvaluateAsRValue(Info, Call->getArg(0), A) ||
12121 !EvaluateAsRValue(Info, Call->getArg(1), MaskVector))
12122 return false;
12123 B = A;
12124 } else if (MaskType->isIntegerType()) {
12125 APSInt MaskImm;
12126 if (!EvaluateInteger(Call->getArg(1), MaskImm, Info))
12127 return false;
12128 ShuffleMask = static_cast<unsigned>(MaskImm.getZExtValue());
12129 if (!EvaluateAsRValue(Info, Call->getArg(0), A))
12130 return false;
12131 B = A;
12132 } else {
12133 return false;
12134 }
12135 } else {
12136 QualType Arg2Type = Call->getArg(2)->getType();
12137 if (Arg2Type->isVectorType()) {
12138 IsVectorMask = true;
12139 if (!EvaluateAsRValue(Info, Call->getArg(0), A) ||
12140 !EvaluateAsRValue(Info, Call->getArg(1), MaskVector) ||
12141 !EvaluateAsRValue(Info, Call->getArg(2), B))
12142 return false;
12143 } else if (Arg2Type->isIntegerType()) {
12144 APSInt MaskImm;
12145 if (!EvaluateInteger(Call->getArg(2), MaskImm, Info))
12146 return false;
12147 ShuffleMask = static_cast<unsigned>(MaskImm.getZExtValue());
12148 if (!EvaluateAsRValue(Info, Call->getArg(0), A) ||
12149 !EvaluateAsRValue(Info, Call->getArg(1), B))
12150 return false;
12151 } else {
12152 return false;
12153 }
12154 }
12155
12156 unsigned NumElts = VT->getNumElements();
12157 SmallVector<APValue, 64> ResultElements;
12158 ResultElements.reserve(NumElts);
12159
12160 for (unsigned DstIdx = 0; DstIdx != NumElts; ++DstIdx) {
12161 if (IsVectorMask) {
12162 ShuffleMask = static_cast<unsigned>(
12163 MaskVector.getVectorElt(DstIdx).getInt().getZExtValue());
12164 }
12165 auto [SrcVecIdx, SrcIdx] = GetSourceIndex(DstIdx, ShuffleMask);
12166
12167 if (SrcIdx < 0) {
12168 // Zero out this element
12169 QualType ElemTy = VT->getElementType();
12170 if (ElemTy->isRealFloatingType()) {
12171 ResultElements.push_back(
12172 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy))));
12173 } else if (ElemTy->isIntegerType()) {
12174 APValue Zero(Info.Ctx.MakeIntValue(0, ElemTy));
12175 ResultElements.push_back(APValue(Zero));
12176 } else {
12177 // Other types of fallback logic
12178 ResultElements.push_back(APValue());
12179 }
12180 } else {
12181 const APValue &Src = (SrcVecIdx == 0) ? A : B;
12182 ResultElements.push_back(Src.getVectorElt(SrcIdx));
12183 }
12184 }
12185
12186 Out = APValue(ResultElements.data(), ResultElements.size());
12187 return true;
12188}
12189static bool ConvertDoubleToFloatStrict(EvalInfo &Info, const Expr *E,
12190 APFloat OrigVal, APValue &Result) {
12191
12192 if (OrigVal.isInfinity()) {
12193 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << 0;
12194 return false;
12195 }
12196 if (OrigVal.isNaN()) {
12197 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << 1;
12198 return false;
12199 }
12200
12201 APFloat Val = OrigVal;
12202 bool LosesInfo = false;
12203 APFloat::opStatus Status = Val.convert(
12204 APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, &LosesInfo);
12205
12206 if (LosesInfo || Val.isDenormal()) {
12207 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic_strict);
12208 return false;
12209 }
12210
12211 if (Status != APFloat::opOK) {
12212 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
12213 return false;
12214 }
12215
12216 Result = APValue(Val);
12217 return true;
12218}
12220 EvalInfo &Info, const CallExpr *Call, APValue &Out,
12221 llvm::function_ref<APInt(const APInt &, uint64_t)> ShiftOp,
12222 llvm::function_ref<APInt(const APInt &, unsigned)> OverflowOp) {
12223
12224 APValue Source, Count;
12225 if (!EvaluateAsRValue(Info, Call->getArg(0), Source) ||
12226 !EvaluateAsRValue(Info, Call->getArg(1), Count))
12227 return false;
12228
12229 assert(Call->getNumArgs() == 2);
12230
12231 QualType SourceTy = Call->getArg(0)->getType();
12232 assert(SourceTy->isVectorType() &&
12233 Call->getArg(1)->getType()->isVectorType());
12234
12235 QualType DestEltTy = SourceTy->castAs<VectorType>()->getElementType();
12236 unsigned DestEltWidth = Source.getVectorElt(0).getInt().getBitWidth();
12237 unsigned DestLen = Source.getVectorLength();
12238 bool IsDestUnsigned = DestEltTy->isUnsignedIntegerType();
12239 unsigned CountEltWidth = Count.getVectorElt(0).getInt().getBitWidth();
12240 unsigned NumBitsInQWord = 64;
12241 unsigned NumCountElts = NumBitsInQWord / CountEltWidth;
12243 Result.reserve(DestLen);
12244
12245 uint64_t CountLQWord = 0;
12246 for (unsigned EltIdx = 0; EltIdx != NumCountElts; ++EltIdx) {
12247 uint64_t Elt = Count.getVectorElt(EltIdx).getInt().getZExtValue();
12248 CountLQWord |= (Elt << (EltIdx * CountEltWidth));
12249 }
12250
12251 for (unsigned EltIdx = 0; EltIdx != DestLen; ++EltIdx) {
12252 APInt Elt = Source.getVectorElt(EltIdx).getInt();
12253 if (CountLQWord < DestEltWidth) {
12254 Result.push_back(
12255 APValue(APSInt(ShiftOp(Elt, CountLQWord), IsDestUnsigned)));
12256 } else {
12257 Result.push_back(
12258 APValue(APSInt(OverflowOp(Elt, DestEltWidth), IsDestUnsigned)));
12259 }
12260 }
12261 Out = APValue(Result.data(), Result.size());
12262 return true;
12263}
12264
12265std::optional<APFloat> EvalScalarMinMaxFp(const APFloat &A, const APFloat &B,
12266 std::optional<APSInt> RoundingMode,
12267 bool IsMin) {
12268 APSInt DefaultMode(APInt(32, 4), /*isUnsigned=*/true);
12269 if (RoundingMode.value_or(DefaultMode) != 4)
12270 return std::nullopt;
12271 if (A.isNaN() || A.isInfinity() || A.isDenormal() || B.isNaN() ||
12272 B.isInfinity() || B.isDenormal())
12273 return std::nullopt;
12274 if (A.isZero() && B.isZero())
12275 return B;
12276 return IsMin ? llvm::minimum(A, B) : llvm::maximum(A, B);
12277}
12278
12279bool VectorExprEvaluator::VisitCallExpr(const CallExpr *E) {
12280 if (!IsConstantEvaluatedBuiltinCall(E))
12281 return ExprEvaluatorBaseTy::VisitCallExpr(E);
12282
12283 auto EvaluateBinOpExpr =
12284 [&](llvm::function_ref<APInt(const APSInt &, const APSInt &)> Fn) {
12285 APValue SourceLHS, SourceRHS;
12286 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
12287 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
12288 return false;
12289
12290 auto *DestTy = E->getType()->castAs<VectorType>();
12291 QualType DestEltTy = DestTy->getElementType();
12292 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
12293 unsigned SourceLen = SourceLHS.getVectorLength();
12294 SmallVector<APValue, 4> ResultElements;
12295 ResultElements.reserve(SourceLen);
12296
12297 if (SourceRHS.isInt()) {
12298 const APSInt &RHS = SourceRHS.getInt();
12299 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12300 const APSInt &LHS = SourceLHS.getVectorElt(EltNum).getInt();
12301 ResultElements.push_back(
12302 APValue(APSInt(Fn(LHS, RHS), DestUnsigned)));
12303 }
12304 } else {
12305 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12306 const APSInt &LHS = SourceLHS.getVectorElt(EltNum).getInt();
12307 const APSInt &RHS = SourceRHS.getVectorElt(EltNum).getInt();
12308 ResultElements.push_back(
12309 APValue(APSInt(Fn(LHS, RHS), DestUnsigned)));
12310 }
12311 }
12312 return Success(APValue(ResultElements.data(), SourceLen), E);
12313 };
12314
12315 auto EvaluateFpBinOpExpr =
12316 [&](llvm::function_ref<std::optional<APFloat>(
12317 const APFloat &, const APFloat &, std::optional<APSInt>)>
12318 Fn,
12319 bool IsScalar = false) {
12320 assert(E->getNumArgs() == 2 || E->getNumArgs() == 3);
12321 APValue A, B;
12322 if (!EvaluateAsRValue(Info, E->getArg(0), A) ||
12323 !EvaluateAsRValue(Info, E->getArg(1), B))
12324 return false;
12325
12326 assert(A.isVector() && B.isVector());
12327 assert(A.getVectorLength() == B.getVectorLength());
12328
12329 std::optional<APSInt> RoundingMode;
12330 if (E->getNumArgs() == 3) {
12331 APSInt Imm;
12332 if (!EvaluateInteger(E->getArg(2), Imm, Info))
12333 return false;
12334 RoundingMode = Imm;
12335 }
12336
12337 unsigned NumElems = A.getVectorLength();
12338 SmallVector<APValue, 4> ResultElements;
12339 ResultElements.reserve(NumElems);
12340
12341 for (unsigned EltNum = 0; EltNum < NumElems; ++EltNum) {
12342 if (IsScalar && EltNum > 0) {
12343 ResultElements.push_back(A.getVectorElt(EltNum));
12344 continue;
12345 }
12346 const APFloat &EltA = A.getVectorElt(EltNum).getFloat();
12347 const APFloat &EltB = B.getVectorElt(EltNum).getFloat();
12348 std::optional<APFloat> Result = Fn(EltA, EltB, RoundingMode);
12349 if (!Result)
12350 return false;
12351 ResultElements.push_back(APValue(*Result));
12352 }
12353 return Success(APValue(ResultElements.data(), NumElems), E);
12354 };
12355
12356 auto EvaluateScalarFpRoundMaskBinOp =
12357 [&](llvm::function_ref<std::optional<APFloat>(
12358 const APFloat &, const APFloat &, std::optional<APSInt>)>
12359 Fn) {
12360 assert(E->getNumArgs() == 5);
12361 APValue VecA, VecB, VecSrc;
12362 APSInt MaskVal, Rounding;
12363
12364 if (!EvaluateAsRValue(Info, E->getArg(0), VecA) ||
12365 !EvaluateAsRValue(Info, E->getArg(1), VecB) ||
12366 !EvaluateAsRValue(Info, E->getArg(2), VecSrc) ||
12367 !EvaluateInteger(E->getArg(3), MaskVal, Info) ||
12368 !EvaluateInteger(E->getArg(4), Rounding, Info))
12369 return false;
12370
12371 unsigned NumElems = VecA.getVectorLength();
12372 SmallVector<APValue, 8> ResultElements;
12373 ResultElements.reserve(NumElems);
12374
12375 if (MaskVal.getZExtValue() & 1) {
12376 const APFloat &EltA = VecA.getVectorElt(0).getFloat();
12377 const APFloat &EltB = VecB.getVectorElt(0).getFloat();
12378 std::optional<APFloat> Result = Fn(EltA, EltB, Rounding);
12379 if (!Result)
12380 return false;
12381 ResultElements.push_back(APValue(*Result));
12382 } else {
12383 ResultElements.push_back(VecSrc.getVectorElt(0));
12384 }
12385
12386 for (unsigned I = 1; I < NumElems; ++I)
12387 ResultElements.push_back(VecA.getVectorElt(I));
12388
12389 return Success(APValue(ResultElements.data(), NumElems), E);
12390 };
12391
12392 auto EvalSelectScalar = [&](unsigned Len) -> bool {
12393 APSInt Mask;
12394 APValue AVal, WVal;
12395 if (!EvaluateInteger(E->getArg(0), Mask, Info) ||
12396 !EvaluateAsRValue(Info, E->getArg(1), AVal) ||
12397 !EvaluateAsRValue(Info, E->getArg(2), WVal))
12398 return false;
12399
12400 bool TakeA0 = (Mask.getZExtValue() & 1u) != 0;
12402 Res.reserve(Len);
12403 Res.push_back(TakeA0 ? AVal.getVectorElt(0) : WVal.getVectorElt(0));
12404 for (unsigned I = 1; I < Len; ++I)
12405 Res.push_back(WVal.getVectorElt(I));
12406 APValue V(Res.data(), Res.size());
12407 return Success(V, E);
12408 };
12409
12410 switch (E->getBuiltinCallee()) {
12411 default:
12412 return false;
12413 case Builtin::BI__builtin_elementwise_popcount:
12414 case Builtin::BI__builtin_elementwise_bitreverse: {
12415 APValue Source;
12416 if (!EvaluateAsRValue(Info, E->getArg(0), Source))
12417 return false;
12418
12419 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
12420 unsigned SourceLen = Source.getVectorLength();
12421 SmallVector<APValue, 4> ResultElements;
12422 ResultElements.reserve(SourceLen);
12423
12424 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12425 APSInt Elt = Source.getVectorElt(EltNum).getInt();
12426 switch (E->getBuiltinCallee()) {
12427 case Builtin::BI__builtin_elementwise_popcount:
12428 ResultElements.push_back(APValue(
12429 APSInt(APInt(Info.Ctx.getIntWidth(DestEltTy), Elt.popcount()),
12430 DestEltTy->isUnsignedIntegerOrEnumerationType())));
12431 break;
12432 case Builtin::BI__builtin_elementwise_bitreverse:
12433 ResultElements.push_back(
12434 APValue(APSInt(Elt.reverseBits(),
12435 DestEltTy->isUnsignedIntegerOrEnumerationType())));
12436 break;
12437 }
12438 }
12439
12440 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12441 }
12442 case Builtin::BI__builtin_elementwise_abs: {
12443 APValue Source;
12444 if (!EvaluateAsRValue(Info, E->getArg(0), Source))
12445 return false;
12446
12447 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
12448 unsigned SourceLen = Source.getVectorLength();
12449 SmallVector<APValue, 4> ResultElements;
12450 ResultElements.reserve(SourceLen);
12451
12452 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12453 APValue CurrentEle = Source.getVectorElt(EltNum);
12454 APValue Val = DestEltTy->isFloatingType()
12455 ? APValue(llvm::abs(CurrentEle.getFloat()))
12456 : APValue(APSInt(
12457 CurrentEle.getInt().abs(),
12458 DestEltTy->isUnsignedIntegerOrEnumerationType()));
12459 ResultElements.push_back(Val);
12460 }
12461
12462 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12463 }
12464
12465 case Builtin::BI__builtin_elementwise_add_sat:
12466 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
12467 return LHS.isSigned() ? LHS.sadd_sat(RHS) : LHS.uadd_sat(RHS);
12468 });
12469
12470 case Builtin::BI__builtin_elementwise_sub_sat:
12471 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
12472 return LHS.isSigned() ? LHS.ssub_sat(RHS) : LHS.usub_sat(RHS);
12473 });
12474
12475 case X86::BI__builtin_ia32_extract128i256:
12476 case X86::BI__builtin_ia32_vextractf128_pd256:
12477 case X86::BI__builtin_ia32_vextractf128_ps256:
12478 case X86::BI__builtin_ia32_vextractf128_si256: {
12479 APValue SourceVec, SourceImm;
12480 if (!EvaluateAsRValue(Info, E->getArg(0), SourceVec) ||
12481 !EvaluateAsRValue(Info, E->getArg(1), SourceImm))
12482 return false;
12483
12484 if (!SourceVec.isVector())
12485 return false;
12486
12487 const auto *RetVT = E->getType()->castAs<VectorType>();
12488 unsigned RetLen = RetVT->getNumElements();
12489 unsigned Idx = SourceImm.getInt().getZExtValue() & 1;
12490
12491 SmallVector<APValue, 32> ResultElements;
12492 ResultElements.reserve(RetLen);
12493
12494 for (unsigned I = 0; I < RetLen; I++)
12495 ResultElements.push_back(SourceVec.getVectorElt(Idx * RetLen + I));
12496
12497 return Success(APValue(ResultElements.data(), RetLen), E);
12498 }
12499
12500 case clang::X86::BI__builtin_ia32_cvtmask2b128:
12501 case clang::X86::BI__builtin_ia32_cvtmask2b256:
12502 case clang::X86::BI__builtin_ia32_cvtmask2b512:
12503 case clang::X86::BI__builtin_ia32_cvtmask2w128:
12504 case clang::X86::BI__builtin_ia32_cvtmask2w256:
12505 case clang::X86::BI__builtin_ia32_cvtmask2w512:
12506 case clang::X86::BI__builtin_ia32_cvtmask2d128:
12507 case clang::X86::BI__builtin_ia32_cvtmask2d256:
12508 case clang::X86::BI__builtin_ia32_cvtmask2d512:
12509 case clang::X86::BI__builtin_ia32_cvtmask2q128:
12510 case clang::X86::BI__builtin_ia32_cvtmask2q256:
12511 case clang::X86::BI__builtin_ia32_cvtmask2q512: {
12512 assert(E->getNumArgs() == 1);
12513 APSInt Mask;
12514 if (!EvaluateInteger(E->getArg(0), Mask, Info))
12515 return false;
12516
12517 QualType VecTy = E->getType();
12518 const VectorType *VT = VecTy->castAs<VectorType>();
12519 unsigned VectorLen = VT->getNumElements();
12520 QualType ElemTy = VT->getElementType();
12521 unsigned ElemWidth = Info.Ctx.getTypeSize(ElemTy);
12522
12524 for (unsigned I = 0; I != VectorLen; ++I) {
12525 bool BitSet = Mask[I];
12526 APSInt ElemVal(ElemWidth, /*isUnsigned=*/false);
12527 if (BitSet) {
12528 ElemVal.setAllBits();
12529 }
12530 Elems.push_back(APValue(ElemVal));
12531 }
12532 return Success(APValue(Elems.data(), VectorLen), E);
12533 }
12534
12535 case X86::BI__builtin_ia32_extracti32x4_256_mask:
12536 case X86::BI__builtin_ia32_extractf32x4_256_mask:
12537 case X86::BI__builtin_ia32_extracti32x4_mask:
12538 case X86::BI__builtin_ia32_extractf32x4_mask:
12539 case X86::BI__builtin_ia32_extracti32x8_mask:
12540 case X86::BI__builtin_ia32_extractf32x8_mask:
12541 case X86::BI__builtin_ia32_extracti64x2_256_mask:
12542 case X86::BI__builtin_ia32_extractf64x2_256_mask:
12543 case X86::BI__builtin_ia32_extracti64x2_512_mask:
12544 case X86::BI__builtin_ia32_extractf64x2_512_mask:
12545 case X86::BI__builtin_ia32_extracti64x4_mask:
12546 case X86::BI__builtin_ia32_extractf64x4_mask: {
12547 APValue SourceVec, MergeVec;
12548 APSInt Imm, MaskImm;
12549
12550 if (!EvaluateAsRValue(Info, E->getArg(0), SourceVec) ||
12551 !EvaluateInteger(E->getArg(1), Imm, Info) ||
12552 !EvaluateAsRValue(Info, E->getArg(2), MergeVec) ||
12553 !EvaluateInteger(E->getArg(3), MaskImm, Info))
12554 return false;
12555
12556 const auto *RetVT = E->getType()->castAs<VectorType>();
12557 unsigned RetLen = RetVT->getNumElements();
12558
12559 if (!SourceVec.isVector() || !MergeVec.isVector())
12560 return false;
12561 unsigned SrcLen = SourceVec.getVectorLength();
12562 unsigned Lanes = SrcLen / RetLen;
12563 unsigned Lane = static_cast<unsigned>(Imm.getZExtValue() % Lanes);
12564 unsigned Base = Lane * RetLen;
12565
12566 SmallVector<APValue, 32> ResultElements;
12567 ResultElements.reserve(RetLen);
12568 for (unsigned I = 0; I < RetLen; ++I) {
12569 if (MaskImm[I])
12570 ResultElements.push_back(SourceVec.getVectorElt(Base + I));
12571 else
12572 ResultElements.push_back(MergeVec.getVectorElt(I));
12573 }
12574 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12575 }
12576
12577 case clang::X86::BI__builtin_ia32_pavgb128:
12578 case clang::X86::BI__builtin_ia32_pavgw128:
12579 case clang::X86::BI__builtin_ia32_pavgb256:
12580 case clang::X86::BI__builtin_ia32_pavgw256:
12581 case clang::X86::BI__builtin_ia32_pavgb512:
12582 case clang::X86::BI__builtin_ia32_pavgw512:
12583 return EvaluateBinOpExpr(llvm::APIntOps::avgCeilU);
12584
12585 case clang::X86::BI__builtin_ia32_pmulhrsw128:
12586 case clang::X86::BI__builtin_ia32_pmulhrsw256:
12587 case clang::X86::BI__builtin_ia32_pmulhrsw512:
12588 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
12589 return (llvm::APIntOps::mulsExtended(LHS, RHS).ashr(14) + 1)
12590 .extractBits(16, 1);
12591 });
12592
12593 case clang::X86::BI__builtin_ia32_pmaddubsw128:
12594 case clang::X86::BI__builtin_ia32_pmaddubsw256:
12595 case clang::X86::BI__builtin_ia32_pmaddubsw512:
12596 case clang::X86::BI__builtin_ia32_pmaddwd128:
12597 case clang::X86::BI__builtin_ia32_pmaddwd256:
12598 case clang::X86::BI__builtin_ia32_pmaddwd512: {
12599 APValue SourceLHS, SourceRHS;
12600 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
12601 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
12602 return false;
12603
12604 auto *DestTy = E->getType()->castAs<VectorType>();
12605 QualType DestEltTy = DestTy->getElementType();
12606 unsigned SourceLen = SourceLHS.getVectorLength();
12607 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
12608 SmallVector<APValue, 4> ResultElements;
12609 ResultElements.reserve(SourceLen / 2);
12610
12611 for (unsigned EltNum = 0; EltNum < SourceLen; EltNum += 2) {
12612 const APSInt &LoLHS = SourceLHS.getVectorElt(EltNum).getInt();
12613 const APSInt &HiLHS = SourceLHS.getVectorElt(EltNum + 1).getInt();
12614 const APSInt &LoRHS = SourceRHS.getVectorElt(EltNum).getInt();
12615 const APSInt &HiRHS = SourceRHS.getVectorElt(EltNum + 1).getInt();
12616 unsigned BitWidth = 2 * LoLHS.getBitWidth();
12617
12618 switch (E->getBuiltinCallee()) {
12619 case clang::X86::BI__builtin_ia32_pmaddubsw128:
12620 case clang::X86::BI__builtin_ia32_pmaddubsw256:
12621 case clang::X86::BI__builtin_ia32_pmaddubsw512:
12622 ResultElements.push_back(APValue(
12623 APSInt((LoLHS.zext(BitWidth) * LoRHS.sext(BitWidth))
12624 .sadd_sat((HiLHS.zext(BitWidth) * HiRHS.sext(BitWidth))),
12625 DestUnsigned)));
12626 break;
12627 case clang::X86::BI__builtin_ia32_pmaddwd128:
12628 case clang::X86::BI__builtin_ia32_pmaddwd256:
12629 case clang::X86::BI__builtin_ia32_pmaddwd512:
12630 ResultElements.push_back(
12631 APValue(APSInt((LoLHS.sext(BitWidth) * LoRHS.sext(BitWidth)) +
12632 (HiLHS.sext(BitWidth) * HiRHS.sext(BitWidth)),
12633 DestUnsigned)));
12634 break;
12635 }
12636 }
12637
12638 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12639 }
12640
12641 case clang::X86::BI__builtin_ia32_dbpsadbw128:
12642 case clang::X86::BI__builtin_ia32_dbpsadbw256:
12643 case clang::X86::BI__builtin_ia32_dbpsadbw512: {
12644 APValue SourceA, SourceB, SourceImm;
12645 if (!EvaluateAsRValue(Info, E->getArg(0), SourceA) ||
12646 !EvaluateAsRValue(Info, E->getArg(1), SourceB) ||
12647 !EvaluateAsRValue(Info, E->getArg(2), SourceImm))
12648 return false;
12649
12650 unsigned SourceLen = SourceA.getVectorLength();
12651 constexpr unsigned LaneSize = 16; // 128-bit lane = 16 bytes
12652 unsigned Imm = SourceImm.getInt().getZExtValue();
12653
12654 auto *DestTy = E->getType()->castAs<VectorType>();
12655 QualType DestEltTy = DestTy->getElementType();
12656 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
12657 SmallVector<APValue, 32> ResultElements;
12658 ResultElements.reserve(SourceLen / 2);
12659
12660 // Phase 1: Shuffle SourceB using all four 2-bit fields of imm8.
12661 // Within each 128-bit lane, for group j (0..3), select a 4-byte block
12662 // from SourceB based on bits [2*j+1:2*j] of imm8.
12663 SmallVector<uint8_t, 64> Shuffled(SourceLen);
12664 for (unsigned I = 0; I < SourceLen; I += LaneSize) {
12665 for (unsigned J = 0; J < 4; ++J) {
12666 unsigned Part = (Imm >> (2 * J)) & 3;
12667 for (unsigned K = 0; K < 4; ++K) {
12668 Shuffled[I + 4 * J + K] = static_cast<uint8_t>(
12669 SourceB.getVectorElt(I + 4 * Part + K).getInt().getZExtValue());
12670 }
12671 }
12672 }
12673
12674 // Phase 2: Sliding SAD computation.
12675 // For every group of 4 output u16 values, compute absolute differences
12676 // using overlapping windows into SourceA and the shuffled array.
12677 unsigned Size = SourceLen / 2; // number of output u16 elements
12678 for (unsigned I = 0; I < Size; I += 4) {
12679 unsigned Sad[4] = {0, 0, 0, 0};
12680 for (unsigned J = 0; J < 4; ++J) {
12681 uint8_t A1 = static_cast<uint8_t>(
12682 SourceA.getVectorElt(2 * I + J).getInt().getZExtValue());
12683 uint8_t A2 = static_cast<uint8_t>(
12684 SourceA.getVectorElt(2 * I + J + 4).getInt().getZExtValue());
12685 uint8_t B0 = Shuffled[2 * I + J];
12686 uint8_t B1 = Shuffled[2 * I + J + 1];
12687 uint8_t B2 = Shuffled[2 * I + J + 2];
12688 uint8_t B3 = Shuffled[2 * I + J + 3];
12689 Sad[0] += (A1 > B0) ? (A1 - B0) : (B0 - A1);
12690 Sad[1] += (A1 > B1) ? (A1 - B1) : (B1 - A1);
12691 Sad[2] += (A2 > B2) ? (A2 - B2) : (B2 - A2);
12692 Sad[3] += (A2 > B3) ? (A2 - B3) : (B3 - A2);
12693 }
12694 for (unsigned R = 0; R < 4; ++R)
12695 ResultElements.push_back(
12696 APValue(APSInt(APInt(16, Sad[R]), DestUnsigned)));
12697 }
12698
12699 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12700 }
12701
12702 case clang::X86::BI__builtin_ia32_pmulhuw128:
12703 case clang::X86::BI__builtin_ia32_pmulhuw256:
12704 case clang::X86::BI__builtin_ia32_pmulhuw512:
12705 return EvaluateBinOpExpr(llvm::APIntOps::mulhu);
12706
12707 case clang::X86::BI__builtin_ia32_pmulhw128:
12708 case clang::X86::BI__builtin_ia32_pmulhw256:
12709 case clang::X86::BI__builtin_ia32_pmulhw512:
12710 return EvaluateBinOpExpr(llvm::APIntOps::mulhs);
12711
12712 case clang::X86::BI__builtin_ia32_psllv2di:
12713 case clang::X86::BI__builtin_ia32_psllv4di:
12714 case clang::X86::BI__builtin_ia32_psllv4si:
12715 case clang::X86::BI__builtin_ia32_psllv8di:
12716 case clang::X86::BI__builtin_ia32_psllv8hi:
12717 case clang::X86::BI__builtin_ia32_psllv8si:
12718 case clang::X86::BI__builtin_ia32_psllv16hi:
12719 case clang::X86::BI__builtin_ia32_psllv16si:
12720 case clang::X86::BI__builtin_ia32_psllv32hi:
12721 case clang::X86::BI__builtin_ia32_psllwi128:
12722 case clang::X86::BI__builtin_ia32_pslldi128:
12723 case clang::X86::BI__builtin_ia32_psllqi128:
12724 case clang::X86::BI__builtin_ia32_psllwi256:
12725 case clang::X86::BI__builtin_ia32_pslldi256:
12726 case clang::X86::BI__builtin_ia32_psllqi256:
12727 case clang::X86::BI__builtin_ia32_psllwi512:
12728 case clang::X86::BI__builtin_ia32_pslldi512:
12729 case clang::X86::BI__builtin_ia32_psllqi512:
12730 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
12731 if (RHS.uge(LHS.getBitWidth())) {
12732 return APInt::getZero(LHS.getBitWidth());
12733 }
12734 return LHS.shl(RHS.getZExtValue());
12735 });
12736
12737 case clang::X86::BI__builtin_ia32_psrav4si:
12738 case clang::X86::BI__builtin_ia32_psrav8di:
12739 case clang::X86::BI__builtin_ia32_psrav8hi:
12740 case clang::X86::BI__builtin_ia32_psrav8si:
12741 case clang::X86::BI__builtin_ia32_psrav16hi:
12742 case clang::X86::BI__builtin_ia32_psrav16si:
12743 case clang::X86::BI__builtin_ia32_psrav32hi:
12744 case clang::X86::BI__builtin_ia32_psravq128:
12745 case clang::X86::BI__builtin_ia32_psravq256:
12746 case clang::X86::BI__builtin_ia32_psrawi128:
12747 case clang::X86::BI__builtin_ia32_psradi128:
12748 case clang::X86::BI__builtin_ia32_psraqi128:
12749 case clang::X86::BI__builtin_ia32_psrawi256:
12750 case clang::X86::BI__builtin_ia32_psradi256:
12751 case clang::X86::BI__builtin_ia32_psraqi256:
12752 case clang::X86::BI__builtin_ia32_psrawi512:
12753 case clang::X86::BI__builtin_ia32_psradi512:
12754 case clang::X86::BI__builtin_ia32_psraqi512:
12755 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
12756 if (RHS.uge(LHS.getBitWidth())) {
12757 return LHS.ashr(LHS.getBitWidth() - 1);
12758 }
12759 return LHS.ashr(RHS.getZExtValue());
12760 });
12761
12762 case clang::X86::BI__builtin_ia32_psrlv2di:
12763 case clang::X86::BI__builtin_ia32_psrlv4di:
12764 case clang::X86::BI__builtin_ia32_psrlv4si:
12765 case clang::X86::BI__builtin_ia32_psrlv8di:
12766 case clang::X86::BI__builtin_ia32_psrlv8hi:
12767 case clang::X86::BI__builtin_ia32_psrlv8si:
12768 case clang::X86::BI__builtin_ia32_psrlv16hi:
12769 case clang::X86::BI__builtin_ia32_psrlv16si:
12770 case clang::X86::BI__builtin_ia32_psrlv32hi:
12771 case clang::X86::BI__builtin_ia32_psrlwi128:
12772 case clang::X86::BI__builtin_ia32_psrldi128:
12773 case clang::X86::BI__builtin_ia32_psrlqi128:
12774 case clang::X86::BI__builtin_ia32_psrlwi256:
12775 case clang::X86::BI__builtin_ia32_psrldi256:
12776 case clang::X86::BI__builtin_ia32_psrlqi256:
12777 case clang::X86::BI__builtin_ia32_psrlwi512:
12778 case clang::X86::BI__builtin_ia32_psrldi512:
12779 case clang::X86::BI__builtin_ia32_psrlqi512:
12780 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
12781 if (RHS.uge(LHS.getBitWidth())) {
12782 return APInt::getZero(LHS.getBitWidth());
12783 }
12784 return LHS.lshr(RHS.getZExtValue());
12785 });
12786 case X86::BI__builtin_ia32_packsswb128:
12787 case X86::BI__builtin_ia32_packsswb256:
12788 case X86::BI__builtin_ia32_packsswb512:
12789 case X86::BI__builtin_ia32_packssdw128:
12790 case X86::BI__builtin_ia32_packssdw256:
12791 case X86::BI__builtin_ia32_packssdw512:
12792 return evalPackBuiltin(E, Info, Result, [](const APSInt &Src) {
12793 return APSInt(Src).truncSSat(Src.getBitWidth() / 2);
12794 });
12795 case X86::BI__builtin_ia32_packusdw128:
12796 case X86::BI__builtin_ia32_packusdw256:
12797 case X86::BI__builtin_ia32_packusdw512:
12798 case X86::BI__builtin_ia32_packuswb128:
12799 case X86::BI__builtin_ia32_packuswb256:
12800 case X86::BI__builtin_ia32_packuswb512:
12801 return evalPackBuiltin(E, Info, Result, [](const APSInt &Src) {
12802 return APSInt(Src).truncSSatU(Src.getBitWidth() / 2);
12803 });
12804 case clang::X86::BI__builtin_ia32_selectss_128:
12805 return EvalSelectScalar(4);
12806 case clang::X86::BI__builtin_ia32_selectsd_128:
12807 return EvalSelectScalar(2);
12808 case clang::X86::BI__builtin_ia32_selectsh_128:
12809 case clang::X86::BI__builtin_ia32_selectsbf_128:
12810 return EvalSelectScalar(8);
12811 case clang::X86::BI__builtin_ia32_pmuldq128:
12812 case clang::X86::BI__builtin_ia32_pmuldq256:
12813 case clang::X86::BI__builtin_ia32_pmuldq512:
12814 case clang::X86::BI__builtin_ia32_pmuludq128:
12815 case clang::X86::BI__builtin_ia32_pmuludq256:
12816 case clang::X86::BI__builtin_ia32_pmuludq512: {
12817 APValue SourceLHS, SourceRHS;
12818 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
12819 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
12820 return false;
12821
12822 unsigned SourceLen = SourceLHS.getVectorLength();
12823 SmallVector<APValue, 4> ResultElements;
12824 ResultElements.reserve(SourceLen / 2);
12825
12826 for (unsigned EltNum = 0; EltNum < SourceLen; EltNum += 2) {
12827 APSInt LHS = SourceLHS.getVectorElt(EltNum).getInt();
12828 APSInt RHS = SourceRHS.getVectorElt(EltNum).getInt();
12829
12830 switch (E->getBuiltinCallee()) {
12831 case clang::X86::BI__builtin_ia32_pmuludq128:
12832 case clang::X86::BI__builtin_ia32_pmuludq256:
12833 case clang::X86::BI__builtin_ia32_pmuludq512:
12834 ResultElements.push_back(
12835 APValue(APSInt(llvm::APIntOps::muluExtended(LHS, RHS), true)));
12836 break;
12837 case clang::X86::BI__builtin_ia32_pmuldq128:
12838 case clang::X86::BI__builtin_ia32_pmuldq256:
12839 case clang::X86::BI__builtin_ia32_pmuldq512:
12840 ResultElements.push_back(
12841 APValue(APSInt(llvm::APIntOps::mulsExtended(LHS, RHS), false)));
12842 break;
12843 }
12844 }
12845
12846 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12847 }
12848
12849 case X86::BI__builtin_ia32_vpmadd52luq128:
12850 case X86::BI__builtin_ia32_vpmadd52luq256:
12851 case X86::BI__builtin_ia32_vpmadd52luq512: {
12852 APValue A, B, C;
12853 if (!EvaluateAsRValue(Info, E->getArg(0), A) ||
12854 !EvaluateAsRValue(Info, E->getArg(1), B) ||
12855 !EvaluateAsRValue(Info, E->getArg(2), C))
12856 return false;
12857
12858 unsigned ALen = A.getVectorLength();
12859 SmallVector<APValue, 4> ResultElements;
12860 ResultElements.reserve(ALen);
12861
12862 for (unsigned EltNum = 0; EltNum < ALen; EltNum += 1) {
12863 APInt AElt = A.getVectorElt(EltNum).getInt();
12864 APInt BElt = B.getVectorElt(EltNum).getInt().trunc(52);
12865 APInt CElt = C.getVectorElt(EltNum).getInt().trunc(52);
12866 APSInt ResElt(AElt + (BElt * CElt).zext(64), false);
12867 ResultElements.push_back(APValue(ResElt));
12868 }
12869
12870 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12871 }
12872 case X86::BI__builtin_ia32_vpmadd52huq128:
12873 case X86::BI__builtin_ia32_vpmadd52huq256:
12874 case X86::BI__builtin_ia32_vpmadd52huq512: {
12875 APValue A, B, C;
12876 if (!EvaluateAsRValue(Info, E->getArg(0), A) ||
12877 !EvaluateAsRValue(Info, E->getArg(1), B) ||
12878 !EvaluateAsRValue(Info, E->getArg(2), C))
12879 return false;
12880
12881 unsigned ALen = A.getVectorLength();
12882 SmallVector<APValue, 4> ResultElements;
12883 ResultElements.reserve(ALen);
12884
12885 for (unsigned EltNum = 0; EltNum < ALen; EltNum += 1) {
12886 APInt AElt = A.getVectorElt(EltNum).getInt();
12887 APInt BElt = B.getVectorElt(EltNum).getInt().trunc(52);
12888 APInt CElt = C.getVectorElt(EltNum).getInt().trunc(52);
12889 APSInt ResElt(AElt + llvm::APIntOps::mulhu(BElt, CElt).zext(64), false);
12890 ResultElements.push_back(APValue(ResElt));
12891 }
12892
12893 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12894 }
12895
12896 case clang::X86::BI__builtin_ia32_vprotbi:
12897 case clang::X86::BI__builtin_ia32_vprotdi:
12898 case clang::X86::BI__builtin_ia32_vprotqi:
12899 case clang::X86::BI__builtin_ia32_vprotwi:
12900 case clang::X86::BI__builtin_ia32_prold128:
12901 case clang::X86::BI__builtin_ia32_prold256:
12902 case clang::X86::BI__builtin_ia32_prold512:
12903 case clang::X86::BI__builtin_ia32_prolq128:
12904 case clang::X86::BI__builtin_ia32_prolq256:
12905 case clang::X86::BI__builtin_ia32_prolq512:
12906 return EvaluateBinOpExpr(
12907 [](const APSInt &LHS, const APSInt &RHS) { return LHS.rotl(RHS); });
12908
12909 case clang::X86::BI__builtin_ia32_prord128:
12910 case clang::X86::BI__builtin_ia32_prord256:
12911 case clang::X86::BI__builtin_ia32_prord512:
12912 case clang::X86::BI__builtin_ia32_prorq128:
12913 case clang::X86::BI__builtin_ia32_prorq256:
12914 case clang::X86::BI__builtin_ia32_prorq512:
12915 return EvaluateBinOpExpr(
12916 [](const APSInt &LHS, const APSInt &RHS) { return LHS.rotr(RHS); });
12917
12918 case Builtin::BI__builtin_elementwise_max:
12919 case Builtin::BI__builtin_elementwise_min: {
12920 APValue SourceLHS, SourceRHS;
12921 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
12922 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
12923 return false;
12924
12925 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
12926
12927 if (!DestEltTy->isIntegerType())
12928 return false;
12929
12930 unsigned SourceLen = SourceLHS.getVectorLength();
12931 SmallVector<APValue, 4> ResultElements;
12932 ResultElements.reserve(SourceLen);
12933
12934 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12935 APSInt LHS = SourceLHS.getVectorElt(EltNum).getInt();
12936 APSInt RHS = SourceRHS.getVectorElt(EltNum).getInt();
12937 switch (E->getBuiltinCallee()) {
12938 case Builtin::BI__builtin_elementwise_max:
12939 ResultElements.push_back(
12940 APValue(APSInt(std::max(LHS, RHS),
12941 DestEltTy->isUnsignedIntegerOrEnumerationType())));
12942 break;
12943 case Builtin::BI__builtin_elementwise_min:
12944 ResultElements.push_back(
12945 APValue(APSInt(std::min(LHS, RHS),
12946 DestEltTy->isUnsignedIntegerOrEnumerationType())));
12947 break;
12948 }
12949 }
12950
12951 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12952 }
12953 case X86::BI__builtin_ia32_vpshldd128:
12954 case X86::BI__builtin_ia32_vpshldd256:
12955 case X86::BI__builtin_ia32_vpshldd512:
12956 case X86::BI__builtin_ia32_vpshldq128:
12957 case X86::BI__builtin_ia32_vpshldq256:
12958 case X86::BI__builtin_ia32_vpshldq512:
12959 case X86::BI__builtin_ia32_vpshldw128:
12960 case X86::BI__builtin_ia32_vpshldw256:
12961 case X86::BI__builtin_ia32_vpshldw512: {
12962 APValue SourceHi, SourceLo, SourceAmt;
12963 if (!EvaluateAsRValue(Info, E->getArg(0), SourceHi) ||
12964 !EvaluateAsRValue(Info, E->getArg(1), SourceLo) ||
12965 !EvaluateAsRValue(Info, E->getArg(2), SourceAmt))
12966 return false;
12967
12968 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
12969 unsigned SourceLen = SourceHi.getVectorLength();
12970 SmallVector<APValue, 32> ResultElements;
12971 ResultElements.reserve(SourceLen);
12972
12973 APInt Amt = SourceAmt.getInt();
12974 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12975 APInt Hi = SourceHi.getVectorElt(EltNum).getInt();
12976 APInt Lo = SourceLo.getVectorElt(EltNum).getInt();
12977 APInt R = llvm::APIntOps::fshl(Hi, Lo, Amt);
12978 ResultElements.push_back(
12980 }
12981
12982 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12983 }
12984 case X86::BI__builtin_ia32_vpshrdd128:
12985 case X86::BI__builtin_ia32_vpshrdd256:
12986 case X86::BI__builtin_ia32_vpshrdd512:
12987 case X86::BI__builtin_ia32_vpshrdq128:
12988 case X86::BI__builtin_ia32_vpshrdq256:
12989 case X86::BI__builtin_ia32_vpshrdq512:
12990 case X86::BI__builtin_ia32_vpshrdw128:
12991 case X86::BI__builtin_ia32_vpshrdw256:
12992 case X86::BI__builtin_ia32_vpshrdw512: {
12993 // NOTE: Reversed Hi/Lo operands.
12994 APValue SourceHi, SourceLo, SourceAmt;
12995 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLo) ||
12996 !EvaluateAsRValue(Info, E->getArg(1), SourceHi) ||
12997 !EvaluateAsRValue(Info, E->getArg(2), SourceAmt))
12998 return false;
12999
13000 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
13001 unsigned SourceLen = SourceHi.getVectorLength();
13002 SmallVector<APValue, 32> ResultElements;
13003 ResultElements.reserve(SourceLen);
13004
13005 APInt Amt = SourceAmt.getInt();
13006 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
13007 APInt Hi = SourceHi.getVectorElt(EltNum).getInt();
13008 APInt Lo = SourceLo.getVectorElt(EltNum).getInt();
13009 APInt R = llvm::APIntOps::fshr(Hi, Lo, Amt);
13010 ResultElements.push_back(
13012 }
13013
13014 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13015 }
13016 case X86::BI__builtin_ia32_compressdf128_mask:
13017 case X86::BI__builtin_ia32_compressdf256_mask:
13018 case X86::BI__builtin_ia32_compressdf512_mask:
13019 case X86::BI__builtin_ia32_compressdi128_mask:
13020 case X86::BI__builtin_ia32_compressdi256_mask:
13021 case X86::BI__builtin_ia32_compressdi512_mask:
13022 case X86::BI__builtin_ia32_compresshi128_mask:
13023 case X86::BI__builtin_ia32_compresshi256_mask:
13024 case X86::BI__builtin_ia32_compresshi512_mask:
13025 case X86::BI__builtin_ia32_compressqi128_mask:
13026 case X86::BI__builtin_ia32_compressqi256_mask:
13027 case X86::BI__builtin_ia32_compressqi512_mask:
13028 case X86::BI__builtin_ia32_compresssf128_mask:
13029 case X86::BI__builtin_ia32_compresssf256_mask:
13030 case X86::BI__builtin_ia32_compresssf512_mask:
13031 case X86::BI__builtin_ia32_compresssi128_mask:
13032 case X86::BI__builtin_ia32_compresssi256_mask:
13033 case X86::BI__builtin_ia32_compresssi512_mask: {
13034 APValue Source, Passthru;
13035 if (!EvaluateAsRValue(Info, E->getArg(0), Source) ||
13036 !EvaluateAsRValue(Info, E->getArg(1), Passthru))
13037 return false;
13038 APSInt Mask;
13039 if (!EvaluateInteger(E->getArg(2), Mask, Info))
13040 return false;
13041
13042 unsigned NumElts = Source.getVectorLength();
13043 SmallVector<APValue, 64> ResultElements;
13044 ResultElements.reserve(NumElts);
13045
13046 for (unsigned I = 0; I != NumElts; ++I) {
13047 if (Mask[I])
13048 ResultElements.push_back(Source.getVectorElt(I));
13049 }
13050 for (unsigned I = ResultElements.size(); I != NumElts; ++I) {
13051 ResultElements.push_back(Passthru.getVectorElt(I));
13052 }
13053
13054 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13055 }
13056 case X86::BI__builtin_ia32_expanddf128_mask:
13057 case X86::BI__builtin_ia32_expanddf256_mask:
13058 case X86::BI__builtin_ia32_expanddf512_mask:
13059 case X86::BI__builtin_ia32_expanddi128_mask:
13060 case X86::BI__builtin_ia32_expanddi256_mask:
13061 case X86::BI__builtin_ia32_expanddi512_mask:
13062 case X86::BI__builtin_ia32_expandhi128_mask:
13063 case X86::BI__builtin_ia32_expandhi256_mask:
13064 case X86::BI__builtin_ia32_expandhi512_mask:
13065 case X86::BI__builtin_ia32_expandqi128_mask:
13066 case X86::BI__builtin_ia32_expandqi256_mask:
13067 case X86::BI__builtin_ia32_expandqi512_mask:
13068 case X86::BI__builtin_ia32_expandsf128_mask:
13069 case X86::BI__builtin_ia32_expandsf256_mask:
13070 case X86::BI__builtin_ia32_expandsf512_mask:
13071 case X86::BI__builtin_ia32_expandsi128_mask:
13072 case X86::BI__builtin_ia32_expandsi256_mask:
13073 case X86::BI__builtin_ia32_expandsi512_mask: {
13074 APValue Source, Passthru;
13075 if (!EvaluateAsRValue(Info, E->getArg(0), Source) ||
13076 !EvaluateAsRValue(Info, E->getArg(1), Passthru))
13077 return false;
13078 APSInt Mask;
13079 if (!EvaluateInteger(E->getArg(2), Mask, Info))
13080 return false;
13081
13082 unsigned NumElts = Source.getVectorLength();
13083 SmallVector<APValue, 64> ResultElements;
13084 ResultElements.reserve(NumElts);
13085
13086 unsigned SourceIdx = 0;
13087 for (unsigned I = 0; I != NumElts; ++I) {
13088 if (Mask[I])
13089 ResultElements.push_back(Source.getVectorElt(SourceIdx++));
13090 else
13091 ResultElements.push_back(Passthru.getVectorElt(I));
13092 }
13093 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13094 }
13095 case X86::BI__builtin_ia32_vpconflictsi_128:
13096 case X86::BI__builtin_ia32_vpconflictsi_256:
13097 case X86::BI__builtin_ia32_vpconflictsi_512:
13098 case X86::BI__builtin_ia32_vpconflictdi_128:
13099 case X86::BI__builtin_ia32_vpconflictdi_256:
13100 case X86::BI__builtin_ia32_vpconflictdi_512: {
13101 APValue Source;
13102
13103 if (!EvaluateAsRValue(Info, E->getArg(0), Source))
13104 return false;
13105
13106 unsigned SourceLen = Source.getVectorLength();
13107 SmallVector<APValue, 32> ResultElements;
13108 ResultElements.reserve(SourceLen);
13109
13110 const auto *VecT = E->getType()->castAs<VectorType>();
13111 bool DestUnsigned =
13112 VecT->getElementType()->isUnsignedIntegerOrEnumerationType();
13113
13114 for (unsigned I = 0; I != SourceLen; ++I) {
13115 const APValue &EltI = Source.getVectorElt(I);
13116
13117 APInt ConflictMask(EltI.getInt().getBitWidth(), 0);
13118 for (unsigned J = 0; J != I; ++J) {
13119 const APValue &EltJ = Source.getVectorElt(J);
13120 ConflictMask.setBitVal(J, EltI.getInt() == EltJ.getInt());
13121 }
13122 ResultElements.push_back(APValue(APSInt(ConflictMask, DestUnsigned)));
13123 }
13124 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13125 }
13126 case X86::BI__builtin_ia32_blendpd:
13127 case X86::BI__builtin_ia32_blendpd256:
13128 case X86::BI__builtin_ia32_blendps:
13129 case X86::BI__builtin_ia32_blendps256:
13130 case X86::BI__builtin_ia32_pblendw128:
13131 case X86::BI__builtin_ia32_pblendw256:
13132 case X86::BI__builtin_ia32_pblendd128:
13133 case X86::BI__builtin_ia32_pblendd256: {
13134 APValue SourceF, SourceT, SourceC;
13135 if (!EvaluateAsRValue(Info, E->getArg(0), SourceF) ||
13136 !EvaluateAsRValue(Info, E->getArg(1), SourceT) ||
13137 !EvaluateAsRValue(Info, E->getArg(2), SourceC))
13138 return false;
13139
13140 const APInt &C = SourceC.getInt();
13141 unsigned SourceLen = SourceF.getVectorLength();
13142 SmallVector<APValue, 32> ResultElements;
13143 ResultElements.reserve(SourceLen);
13144 for (unsigned EltNum = 0; EltNum != SourceLen; ++EltNum) {
13145 const APValue &F = SourceF.getVectorElt(EltNum);
13146 const APValue &T = SourceT.getVectorElt(EltNum);
13147 ResultElements.push_back(C[EltNum % 8] ? T : F);
13148 }
13149
13150 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13151 }
13152
13153 case X86::BI__builtin_ia32_psignb128:
13154 case X86::BI__builtin_ia32_psignb256:
13155 case X86::BI__builtin_ia32_psignw128:
13156 case X86::BI__builtin_ia32_psignw256:
13157 case X86::BI__builtin_ia32_psignd128:
13158 case X86::BI__builtin_ia32_psignd256:
13159 return EvaluateBinOpExpr([](const APInt &AElem, const APInt &BElem) {
13160 if (BElem.isZero())
13161 return APInt::getZero(AElem.getBitWidth());
13162 if (BElem.isNegative())
13163 return -AElem;
13164 return AElem;
13165 });
13166
13167 case X86::BI__builtin_ia32_blendvpd:
13168 case X86::BI__builtin_ia32_blendvpd256:
13169 case X86::BI__builtin_ia32_blendvps:
13170 case X86::BI__builtin_ia32_blendvps256:
13171 case X86::BI__builtin_ia32_pblendvb128:
13172 case X86::BI__builtin_ia32_pblendvb256: {
13173 // SSE blendv by mask signbit: "Result = C[] < 0 ? T[] : F[]".
13174 APValue SourceF, SourceT, SourceC;
13175 if (!EvaluateAsRValue(Info, E->getArg(0), SourceF) ||
13176 !EvaluateAsRValue(Info, E->getArg(1), SourceT) ||
13177 !EvaluateAsRValue(Info, E->getArg(2), SourceC))
13178 return false;
13179
13180 unsigned SourceLen = SourceF.getVectorLength();
13181 SmallVector<APValue, 32> ResultElements;
13182 ResultElements.reserve(SourceLen);
13183
13184 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
13185 const APValue &F = SourceF.getVectorElt(EltNum);
13186 const APValue &T = SourceT.getVectorElt(EltNum);
13187 const APValue &C = SourceC.getVectorElt(EltNum);
13188 APInt M = C.isInt() ? (APInt)C.getInt() : C.getFloat().bitcastToAPInt();
13189 ResultElements.push_back(M.isNegative() ? T : F);
13190 }
13191
13192 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13193 }
13194 case X86::BI__builtin_ia32_selectb_128:
13195 case X86::BI__builtin_ia32_selectb_256:
13196 case X86::BI__builtin_ia32_selectb_512:
13197 case X86::BI__builtin_ia32_selectw_128:
13198 case X86::BI__builtin_ia32_selectw_256:
13199 case X86::BI__builtin_ia32_selectw_512:
13200 case X86::BI__builtin_ia32_selectd_128:
13201 case X86::BI__builtin_ia32_selectd_256:
13202 case X86::BI__builtin_ia32_selectd_512:
13203 case X86::BI__builtin_ia32_selectq_128:
13204 case X86::BI__builtin_ia32_selectq_256:
13205 case X86::BI__builtin_ia32_selectq_512:
13206 case X86::BI__builtin_ia32_selectph_128:
13207 case X86::BI__builtin_ia32_selectph_256:
13208 case X86::BI__builtin_ia32_selectph_512:
13209 case X86::BI__builtin_ia32_selectpbf_128:
13210 case X86::BI__builtin_ia32_selectpbf_256:
13211 case X86::BI__builtin_ia32_selectpbf_512:
13212 case X86::BI__builtin_ia32_selectps_128:
13213 case X86::BI__builtin_ia32_selectps_256:
13214 case X86::BI__builtin_ia32_selectps_512:
13215 case X86::BI__builtin_ia32_selectpd_128:
13216 case X86::BI__builtin_ia32_selectpd_256:
13217 case X86::BI__builtin_ia32_selectpd_512: {
13218 // AVX512 predicated move: "Result = Mask[] ? LHS[] : RHS[]".
13219 APValue SourceMask, SourceLHS, SourceRHS;
13220 if (!EvaluateAsRValue(Info, E->getArg(0), SourceMask) ||
13221 !EvaluateAsRValue(Info, E->getArg(1), SourceLHS) ||
13222 !EvaluateAsRValue(Info, E->getArg(2), SourceRHS))
13223 return false;
13224
13225 APSInt Mask = SourceMask.getInt();
13226 unsigned SourceLen = SourceLHS.getVectorLength();
13227 SmallVector<APValue, 4> ResultElements;
13228 ResultElements.reserve(SourceLen);
13229
13230 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
13231 const APValue &LHS = SourceLHS.getVectorElt(EltNum);
13232 const APValue &RHS = SourceRHS.getVectorElt(EltNum);
13233 ResultElements.push_back(Mask[EltNum] ? LHS : RHS);
13234 }
13235
13236 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13237 }
13238
13239 case X86::BI__builtin_ia32_cvtsd2ss: {
13240 APValue VecA, VecB;
13241 if (!EvaluateAsRValue(Info, E->getArg(0), VecA) ||
13242 !EvaluateAsRValue(Info, E->getArg(1), VecB))
13243 return false;
13244
13245 SmallVector<APValue, 4> Elements;
13246
13247 APValue ResultVal;
13248 if (!ConvertDoubleToFloatStrict(Info, E, VecB.getVectorElt(0).getFloat(),
13249 ResultVal))
13250 return false;
13251
13252 Elements.push_back(ResultVal);
13253
13254 unsigned NumEltsA = VecA.getVectorLength();
13255 for (unsigned I = 1; I < NumEltsA; ++I) {
13256 Elements.push_back(VecA.getVectorElt(I));
13257 }
13258
13259 return Success(Elements, E);
13260 }
13261 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: {
13262 APValue VecA, VecB, VecSrc, MaskValue;
13263
13264 if (!EvaluateAsRValue(Info, E->getArg(0), VecA) ||
13265 !EvaluateAsRValue(Info, E->getArg(1), VecB) ||
13266 !EvaluateAsRValue(Info, E->getArg(2), VecSrc) ||
13267 !EvaluateAsRValue(Info, E->getArg(3), MaskValue))
13268 return false;
13269
13270 unsigned Mask = MaskValue.getInt().getZExtValue();
13271 SmallVector<APValue, 4> Elements;
13272
13273 if (Mask & 1) {
13274 APValue ResultVal;
13275 if (!ConvertDoubleToFloatStrict(Info, E, VecB.getVectorElt(0).getFloat(),
13276 ResultVal))
13277 return false;
13278 Elements.push_back(ResultVal);
13279 } else {
13280 Elements.push_back(VecSrc.getVectorElt(0));
13281 }
13282
13283 unsigned NumEltsA = VecA.getVectorLength();
13284 for (unsigned I = 1; I < NumEltsA; ++I) {
13285 Elements.push_back(VecA.getVectorElt(I));
13286 }
13287
13288 return Success(Elements, E);
13289 }
13290 case X86::BI__builtin_ia32_cvtpd2ps:
13291 case X86::BI__builtin_ia32_cvtpd2ps256:
13292 case X86::BI__builtin_ia32_cvtpd2ps_mask:
13293 case X86::BI__builtin_ia32_cvtpd2ps512_mask: {
13294
13295 const auto BuiltinID = E->getBuiltinCallee();
13296 bool IsMasked = (BuiltinID == X86::BI__builtin_ia32_cvtpd2ps_mask ||
13297 BuiltinID == X86::BI__builtin_ia32_cvtpd2ps512_mask);
13298
13299 APValue InputValue;
13300 if (!EvaluateAsRValue(Info, E->getArg(0), InputValue))
13301 return false;
13302
13303 APValue MergeValue;
13304 unsigned Mask = 0xFFFFFFFF;
13305 bool NeedsMerge = false;
13306 if (IsMasked) {
13307 APValue MaskValue;
13308 if (!EvaluateAsRValue(Info, E->getArg(2), MaskValue))
13309 return false;
13310 Mask = MaskValue.getInt().getZExtValue();
13311 auto NumEltsResult = E->getType()->getAs<VectorType>()->getNumElements();
13312 for (unsigned I = 0; I < NumEltsResult; ++I) {
13313 if (!((Mask >> I) & 1)) {
13314 NeedsMerge = true;
13315 break;
13316 }
13317 }
13318 if (NeedsMerge) {
13319 if (!EvaluateAsRValue(Info, E->getArg(1), MergeValue))
13320 return false;
13321 }
13322 }
13323
13324 unsigned NumEltsResult =
13325 E->getType()->getAs<VectorType>()->getNumElements();
13326 unsigned NumEltsInput = InputValue.getVectorLength();
13327 SmallVector<APValue, 8> Elements;
13328 for (unsigned I = 0; I < NumEltsResult; ++I) {
13329 if (IsMasked && !((Mask >> I) & 1)) {
13330 if (!NeedsMerge) {
13331 return false;
13332 }
13333 Elements.push_back(MergeValue.getVectorElt(I));
13334 continue;
13335 }
13336
13337 if (I >= NumEltsInput) {
13338 Elements.push_back(APValue(APFloat::getZero(APFloat::IEEEsingle())));
13339 continue;
13340 }
13341
13342 APValue ResultVal;
13344 Info, E, InputValue.getVectorElt(I).getFloat(), ResultVal))
13345 return false;
13346
13347 Elements.push_back(ResultVal);
13348 }
13349 return Success(Elements, E);
13350 }
13351
13352 case X86::BI__builtin_ia32_shufps:
13353 case X86::BI__builtin_ia32_shufps256:
13354 case X86::BI__builtin_ia32_shufps512: {
13355 APValue R;
13356 if (!evalShuffleGeneric(
13357 Info, E, R,
13358 [](unsigned DstIdx,
13359 unsigned ShuffleMask) -> std::pair<unsigned, int> {
13360 constexpr unsigned LaneBits = 128u;
13361 unsigned NumElemPerLane = LaneBits / 32;
13362 unsigned NumSelectableElems = NumElemPerLane / 2;
13363 unsigned BitsPerElem = 2;
13364 unsigned IndexMask = (1u << BitsPerElem) - 1;
13365 unsigned MaskBits = 8;
13366 unsigned Lane = DstIdx / NumElemPerLane;
13367 unsigned ElemInLane = DstIdx % NumElemPerLane;
13368 unsigned LaneOffset = Lane * NumElemPerLane;
13369 unsigned BitIndex = (DstIdx * BitsPerElem) % MaskBits;
13370 unsigned SrcIdx = (ElemInLane < NumSelectableElems) ? 0 : 1;
13371 unsigned Index = (ShuffleMask >> BitIndex) & IndexMask;
13372 return {SrcIdx, static_cast<int>(LaneOffset + Index)};
13373 }))
13374 return false;
13375 return Success(R, E);
13376 }
13377 case X86::BI__builtin_ia32_shufpd:
13378 case X86::BI__builtin_ia32_shufpd256:
13379 case X86::BI__builtin_ia32_shufpd512: {
13380 APValue R;
13381 if (!evalShuffleGeneric(
13382 Info, E, R,
13383 [](unsigned DstIdx,
13384 unsigned ShuffleMask) -> std::pair<unsigned, int> {
13385 constexpr unsigned LaneBits = 128u;
13386 unsigned NumElemPerLane = LaneBits / 64;
13387 unsigned NumSelectableElems = NumElemPerLane / 2;
13388 unsigned BitsPerElem = 1;
13389 unsigned IndexMask = (1u << BitsPerElem) - 1;
13390 unsigned MaskBits = 8;
13391 unsigned Lane = DstIdx / NumElemPerLane;
13392 unsigned ElemInLane = DstIdx % NumElemPerLane;
13393 unsigned LaneOffset = Lane * NumElemPerLane;
13394 unsigned BitIndex = (DstIdx * BitsPerElem) % MaskBits;
13395 unsigned SrcIdx = (ElemInLane < NumSelectableElems) ? 0 : 1;
13396 unsigned Index = (ShuffleMask >> BitIndex) & IndexMask;
13397 return {SrcIdx, static_cast<int>(LaneOffset + Index)};
13398 }))
13399 return false;
13400 return Success(R, E);
13401 }
13402 case X86::BI__builtin_ia32_insertps128: {
13403 APValue R;
13404 if (!evalShuffleGeneric(
13405 Info, E, R,
13406 [](unsigned DstIdx, unsigned Mask) -> std::pair<unsigned, int> {
13407 // Bits [3:0]: zero mask - if bit is set, zero this element
13408 if ((Mask & (1 << DstIdx)) != 0) {
13409 return {0, -1};
13410 }
13411 // Bits [7:6]: select element from source vector Y (0-3)
13412 // Bits [5:4]: select destination position (0-3)
13413 unsigned SrcElem = (Mask >> 6) & 0x3;
13414 unsigned DstElem = (Mask >> 4) & 0x3;
13415 if (DstIdx == DstElem) {
13416 // Insert element from source vector (B) at this position
13417 return {1, static_cast<int>(SrcElem)};
13418 } else {
13419 // Copy from destination vector (A)
13420 return {0, static_cast<int>(DstIdx)};
13421 }
13422 }))
13423 return false;
13424 return Success(R, E);
13425 }
13426 case X86::BI__builtin_ia32_pshufb128:
13427 case X86::BI__builtin_ia32_pshufb256:
13428 case X86::BI__builtin_ia32_pshufb512: {
13429 APValue R;
13430 if (!evalShuffleGeneric(
13431 Info, E, R,
13432 [](unsigned DstIdx,
13433 unsigned ShuffleMask) -> std::pair<unsigned, int> {
13434 uint8_t Ctlb = static_cast<uint8_t>(ShuffleMask);
13435 if (Ctlb & 0x80)
13436 return std::make_pair(0, -1);
13437
13438 unsigned LaneBase = (DstIdx / 16) * 16;
13439 unsigned SrcOffset = Ctlb & 0x0F;
13440 unsigned SrcIdx = LaneBase + SrcOffset;
13441 return std::make_pair(0, static_cast<int>(SrcIdx));
13442 }))
13443 return false;
13444 return Success(R, E);
13445 }
13446
13447 case X86::BI__builtin_ia32_pshuflw:
13448 case X86::BI__builtin_ia32_pshuflw256:
13449 case X86::BI__builtin_ia32_pshuflw512: {
13450 APValue R;
13451 if (!evalShuffleGeneric(
13452 Info, E, R,
13453 [](unsigned DstIdx, unsigned Mask) -> std::pair<unsigned, int> {
13454 constexpr unsigned LaneBits = 128u;
13455 constexpr unsigned ElemBits = 16u;
13456 constexpr unsigned LaneElts = LaneBits / ElemBits;
13457 constexpr unsigned HalfSize = 4;
13458 unsigned LaneBase = (DstIdx / LaneElts) * LaneElts;
13459 unsigned LaneIdx = DstIdx % LaneElts;
13460 if (LaneIdx < HalfSize) {
13461 unsigned Sel = (Mask >> (2 * LaneIdx)) & 0x3;
13462 return std::make_pair(0, static_cast<int>(LaneBase + Sel));
13463 }
13464 return std::make_pair(0, static_cast<int>(DstIdx));
13465 }))
13466 return false;
13467 return Success(R, E);
13468 }
13469
13470 case X86::BI__builtin_ia32_pshufhw:
13471 case X86::BI__builtin_ia32_pshufhw256:
13472 case X86::BI__builtin_ia32_pshufhw512: {
13473 APValue R;
13474 if (!evalShuffleGeneric(
13475 Info, E, R,
13476 [](unsigned DstIdx, unsigned Mask) -> std::pair<unsigned, int> {
13477 constexpr unsigned LaneBits = 128u;
13478 constexpr unsigned ElemBits = 16u;
13479 constexpr unsigned LaneElts = LaneBits / ElemBits;
13480 constexpr unsigned HalfSize = 4;
13481 unsigned LaneBase = (DstIdx / LaneElts) * LaneElts;
13482 unsigned LaneIdx = DstIdx % LaneElts;
13483 if (LaneIdx >= HalfSize) {
13484 unsigned Rel = LaneIdx - HalfSize;
13485 unsigned Sel = (Mask >> (2 * Rel)) & 0x3;
13486 return std::make_pair(
13487 0, static_cast<int>(LaneBase + HalfSize + Sel));
13488 }
13489 return std::make_pair(0, static_cast<int>(DstIdx));
13490 }))
13491 return false;
13492 return Success(R, E);
13493 }
13494
13495 case X86::BI__builtin_ia32_pshufd:
13496 case X86::BI__builtin_ia32_pshufd256:
13497 case X86::BI__builtin_ia32_pshufd512:
13498 case X86::BI__builtin_ia32_vpermilps:
13499 case X86::BI__builtin_ia32_vpermilps256:
13500 case X86::BI__builtin_ia32_vpermilps512: {
13501 APValue R;
13502 if (!evalShuffleGeneric(
13503 Info, E, R,
13504 [](unsigned DstIdx, unsigned Mask) -> std::pair<unsigned, int> {
13505 constexpr unsigned LaneBits = 128u;
13506 constexpr unsigned ElemBits = 32u;
13507 constexpr unsigned LaneElts = LaneBits / ElemBits;
13508 unsigned LaneBase = (DstIdx / LaneElts) * LaneElts;
13509 unsigned LaneIdx = DstIdx % LaneElts;
13510 unsigned Sel = (Mask >> (2 * LaneIdx)) & 0x3;
13511 return std::make_pair(0, static_cast<int>(LaneBase + Sel));
13512 }))
13513 return false;
13514 return Success(R, E);
13515 }
13516
13517 case X86::BI__builtin_ia32_vpermilvarpd:
13518 case X86::BI__builtin_ia32_vpermilvarpd256:
13519 case X86::BI__builtin_ia32_vpermilvarpd512: {
13520 APValue R;
13521 if (!evalShuffleGeneric(
13522 Info, E, R,
13523 [](unsigned DstIdx, unsigned Mask) -> std::pair<unsigned, int> {
13524 unsigned NumElemPerLane = 2;
13525 unsigned Lane = DstIdx / NumElemPerLane;
13526 unsigned Offset = Mask & 0b10 ? 1 : 0;
13527 return std::make_pair(
13528 0, static_cast<int>(Lane * NumElemPerLane + Offset));
13529 }))
13530 return false;
13531 return Success(R, E);
13532 }
13533
13534 case X86::BI__builtin_ia32_vpermilpd:
13535 case X86::BI__builtin_ia32_vpermilpd256:
13536 case X86::BI__builtin_ia32_vpermilpd512: {
13537 APValue R;
13538 if (!evalShuffleGeneric(Info, E, R, [](unsigned DstIdx, unsigned Control) {
13539 unsigned NumElemPerLane = 2;
13540 unsigned BitsPerElem = 1;
13541 unsigned MaskBits = 8;
13542 unsigned IndexMask = 0x1;
13543 unsigned Lane = DstIdx / NumElemPerLane;
13544 unsigned LaneOffset = Lane * NumElemPerLane;
13545 unsigned BitIndex = (DstIdx * BitsPerElem) % MaskBits;
13546 unsigned Index = (Control >> BitIndex) & IndexMask;
13547 return std::make_pair(0, static_cast<int>(LaneOffset + Index));
13548 }))
13549 return false;
13550 return Success(R, E);
13551 }
13552
13553 case X86::BI__builtin_ia32_permdf256:
13554 case X86::BI__builtin_ia32_permdi256: {
13555 APValue R;
13556 if (!evalShuffleGeneric(Info, E, R, [](unsigned DstIdx, unsigned Control) {
13557 // permute4x64 operates on 4 64-bit elements
13558 // For element i (0-3), extract bits [2*i+1:2*i] from Control
13559 unsigned Index = (Control >> (2 * DstIdx)) & 0x3;
13560 return std::make_pair(0, static_cast<int>(Index));
13561 }))
13562 return false;
13563 return Success(R, E);
13564 }
13565
13566 case X86::BI__builtin_ia32_vpermilvarps:
13567 case X86::BI__builtin_ia32_vpermilvarps256:
13568 case X86::BI__builtin_ia32_vpermilvarps512: {
13569 APValue R;
13570 if (!evalShuffleGeneric(
13571 Info, E, R,
13572 [](unsigned DstIdx, unsigned Mask) -> std::pair<unsigned, int> {
13573 unsigned NumElemPerLane = 4;
13574 unsigned Lane = DstIdx / NumElemPerLane;
13575 unsigned Offset = Mask & 0b11;
13576 return std::make_pair(
13577 0, static_cast<int>(Lane * NumElemPerLane + Offset));
13578 }))
13579 return false;
13580 return Success(R, E);
13581 }
13582
13583 case X86::BI__builtin_ia32_vpmultishiftqb128:
13584 case X86::BI__builtin_ia32_vpmultishiftqb256:
13585 case X86::BI__builtin_ia32_vpmultishiftqb512: {
13586 assert(E->getNumArgs() == 2);
13587
13588 APValue A, B;
13589 if (!Evaluate(A, Info, E->getArg(0)) || !Evaluate(B, Info, E->getArg(1)))
13590 return false;
13591
13592 assert(A.getVectorLength() == B.getVectorLength());
13593 unsigned NumBytesInQWord = 8;
13594 unsigned NumBitsInByte = 8;
13595 unsigned NumBytes = A.getVectorLength();
13596 unsigned NumQWords = NumBytes / NumBytesInQWord;
13598 Result.reserve(NumBytes);
13599
13600 for (unsigned QWordId = 0; QWordId != NumQWords; ++QWordId) {
13601 APInt BQWord(64, 0);
13602 for (unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
13603 unsigned Idx = QWordId * NumBytesInQWord + ByteIdx;
13604 uint64_t Byte = B.getVectorElt(Idx).getInt().getZExtValue();
13605 BQWord.insertBits(APInt(8, Byte & 0xFF), ByteIdx * NumBitsInByte);
13606 }
13607
13608 for (unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
13609 unsigned Idx = QWordId * NumBytesInQWord + ByteIdx;
13610 uint64_t Ctrl = A.getVectorElt(Idx).getInt().getZExtValue() & 0x3F;
13611
13612 APInt Byte(8, 0);
13613 for (unsigned BitIdx = 0; BitIdx != NumBitsInByte; ++BitIdx) {
13614 Byte.setBitVal(BitIdx, BQWord[(Ctrl + BitIdx) & 0x3F]);
13615 }
13616 Result.push_back(APValue(APSInt(Byte, /*isUnsigned*/ true)));
13617 }
13618 }
13619 return Success(APValue(Result.data(), Result.size()), E);
13620 }
13621
13622 case X86::BI__builtin_ia32_phminposuw128: {
13623 APValue Source;
13624 if (!Evaluate(Source, Info, E->getArg(0)))
13625 return false;
13626 unsigned SourceLen = Source.getVectorLength();
13627 const VectorType *VT = E->getArg(0)->getType()->castAs<VectorType>();
13628 QualType ElemQT = VT->getElementType();
13629 unsigned ElemBitWidth = Info.Ctx.getTypeSize(ElemQT);
13630
13631 APInt MinIndex(ElemBitWidth, 0);
13632 APInt MinVal = Source.getVectorElt(0).getInt();
13633 for (unsigned I = 1; I != SourceLen; ++I) {
13634 APInt Val = Source.getVectorElt(I).getInt();
13635 if (MinVal.ugt(Val)) {
13636 MinVal = Val;
13637 MinIndex = I;
13638 }
13639 }
13640
13641 bool ResultUnsigned = E->getCallReturnType(Info.Ctx)
13642 ->castAs<VectorType>()
13643 ->getElementType()
13644 ->isUnsignedIntegerOrEnumerationType();
13645
13647 Result.reserve(SourceLen);
13648 Result.emplace_back(APSInt(MinVal, ResultUnsigned));
13649 Result.emplace_back(APSInt(MinIndex, ResultUnsigned));
13650 for (unsigned I = 0; I != SourceLen - 2; ++I) {
13651 Result.emplace_back(APSInt(APInt(ElemBitWidth, 0), ResultUnsigned));
13652 }
13653 return Success(APValue(Result.data(), Result.size()), E);
13654 }
13655
13656 case X86::BI__builtin_ia32_psraq128:
13657 case X86::BI__builtin_ia32_psraq256:
13658 case X86::BI__builtin_ia32_psraq512:
13659 case X86::BI__builtin_ia32_psrad128:
13660 case X86::BI__builtin_ia32_psrad256:
13661 case X86::BI__builtin_ia32_psrad512:
13662 case X86::BI__builtin_ia32_psraw128:
13663 case X86::BI__builtin_ia32_psraw256:
13664 case X86::BI__builtin_ia32_psraw512: {
13665 APValue R;
13666 if (!evalShiftWithCount(
13667 Info, E, R,
13668 [](const APInt &Elt, uint64_t Count) { return Elt.ashr(Count); },
13669 [](const APInt &Elt, unsigned Width) {
13670 return Elt.ashr(Width - 1);
13671 }))
13672 return false;
13673 return Success(R, E);
13674 }
13675
13676 case X86::BI__builtin_ia32_psllq128:
13677 case X86::BI__builtin_ia32_psllq256:
13678 case X86::BI__builtin_ia32_psllq512:
13679 case X86::BI__builtin_ia32_pslld128:
13680 case X86::BI__builtin_ia32_pslld256:
13681 case X86::BI__builtin_ia32_pslld512:
13682 case X86::BI__builtin_ia32_psllw128:
13683 case X86::BI__builtin_ia32_psllw256:
13684 case X86::BI__builtin_ia32_psllw512: {
13685 APValue R;
13686 if (!evalShiftWithCount(
13687 Info, E, R,
13688 [](const APInt &Elt, uint64_t Count) { return Elt.shl(Count); },
13689 [](const APInt &Elt, unsigned Width) {
13690 return APInt::getZero(Width);
13691 }))
13692 return false;
13693 return Success(R, E);
13694 }
13695
13696 case X86::BI__builtin_ia32_psrlq128:
13697 case X86::BI__builtin_ia32_psrlq256:
13698 case X86::BI__builtin_ia32_psrlq512:
13699 case X86::BI__builtin_ia32_psrld128:
13700 case X86::BI__builtin_ia32_psrld256:
13701 case X86::BI__builtin_ia32_psrld512:
13702 case X86::BI__builtin_ia32_psrlw128:
13703 case X86::BI__builtin_ia32_psrlw256:
13704 case X86::BI__builtin_ia32_psrlw512: {
13705 APValue R;
13706 if (!evalShiftWithCount(
13707 Info, E, R,
13708 [](const APInt &Elt, uint64_t Count) { return Elt.lshr(Count); },
13709 [](const APInt &Elt, unsigned Width) {
13710 return APInt::getZero(Width);
13711 }))
13712 return false;
13713 return Success(R, E);
13714 }
13715
13716 case X86::BI__builtin_ia32_pternlogd128_mask:
13717 case X86::BI__builtin_ia32_pternlogd256_mask:
13718 case X86::BI__builtin_ia32_pternlogd512_mask:
13719 case X86::BI__builtin_ia32_pternlogq128_mask:
13720 case X86::BI__builtin_ia32_pternlogq256_mask:
13721 case X86::BI__builtin_ia32_pternlogq512_mask: {
13722 APValue AValue, BValue, CValue, ImmValue, UValue;
13723 if (!EvaluateAsRValue(Info, E->getArg(0), AValue) ||
13724 !EvaluateAsRValue(Info, E->getArg(1), BValue) ||
13725 !EvaluateAsRValue(Info, E->getArg(2), CValue) ||
13726 !EvaluateAsRValue(Info, E->getArg(3), ImmValue) ||
13727 !EvaluateAsRValue(Info, E->getArg(4), UValue))
13728 return false;
13729
13730 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
13731 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
13732 APInt Imm = ImmValue.getInt();
13733 APInt U = UValue.getInt();
13734 unsigned ResultLen = AValue.getVectorLength();
13735 SmallVector<APValue, 16> ResultElements;
13736 ResultElements.reserve(ResultLen);
13737
13738 for (unsigned EltNum = 0; EltNum < ResultLen; ++EltNum) {
13739 APInt ALane = AValue.getVectorElt(EltNum).getInt();
13740 APInt BLane = BValue.getVectorElt(EltNum).getInt();
13741 APInt CLane = CValue.getVectorElt(EltNum).getInt();
13742
13743 if (U[EltNum]) {
13744 unsigned BitWidth = ALane.getBitWidth();
13745 APInt ResLane(BitWidth, 0);
13746
13747 for (unsigned Bit = 0; Bit < BitWidth; ++Bit) {
13748 unsigned ABit = ALane[Bit];
13749 unsigned BBit = BLane[Bit];
13750 unsigned CBit = CLane[Bit];
13751
13752 unsigned Idx = (ABit << 2) | (BBit << 1) | CBit;
13753 ResLane.setBitVal(Bit, Imm[Idx]);
13754 }
13755 ResultElements.push_back(APValue(APSInt(ResLane, DestUnsigned)));
13756 } else {
13757 ResultElements.push_back(APValue(APSInt(ALane, DestUnsigned)));
13758 }
13759 }
13760 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13761 }
13762 case X86::BI__builtin_ia32_pternlogd128_maskz:
13763 case X86::BI__builtin_ia32_pternlogd256_maskz:
13764 case X86::BI__builtin_ia32_pternlogd512_maskz:
13765 case X86::BI__builtin_ia32_pternlogq128_maskz:
13766 case X86::BI__builtin_ia32_pternlogq256_maskz:
13767 case X86::BI__builtin_ia32_pternlogq512_maskz: {
13768 APValue AValue, BValue, CValue, ImmValue, UValue;
13769 if (!EvaluateAsRValue(Info, E->getArg(0), AValue) ||
13770 !EvaluateAsRValue(Info, E->getArg(1), BValue) ||
13771 !EvaluateAsRValue(Info, E->getArg(2), CValue) ||
13772 !EvaluateAsRValue(Info, E->getArg(3), ImmValue) ||
13773 !EvaluateAsRValue(Info, E->getArg(4), UValue))
13774 return false;
13775
13776 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
13777 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
13778 APInt Imm = ImmValue.getInt();
13779 APInt U = UValue.getInt();
13780 unsigned ResultLen = AValue.getVectorLength();
13781 SmallVector<APValue, 16> ResultElements;
13782 ResultElements.reserve(ResultLen);
13783
13784 for (unsigned EltNum = 0; EltNum < ResultLen; ++EltNum) {
13785 APInt ALane = AValue.getVectorElt(EltNum).getInt();
13786 APInt BLane = BValue.getVectorElt(EltNum).getInt();
13787 APInt CLane = CValue.getVectorElt(EltNum).getInt();
13788
13789 unsigned BitWidth = ALane.getBitWidth();
13790 APInt ResLane(BitWidth, 0);
13791
13792 if (U[EltNum]) {
13793 for (unsigned Bit = 0; Bit < BitWidth; ++Bit) {
13794 unsigned ABit = ALane[Bit];
13795 unsigned BBit = BLane[Bit];
13796 unsigned CBit = CLane[Bit];
13797
13798 unsigned Idx = (ABit << 2) | (BBit << 1) | CBit;
13799 ResLane.setBitVal(Bit, Imm[Idx]);
13800 }
13801 }
13802 ResultElements.push_back(APValue(APSInt(ResLane, DestUnsigned)));
13803 }
13804 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13805 }
13806
13807 case Builtin::BI__builtin_elementwise_clzg:
13808 case Builtin::BI__builtin_elementwise_ctzg: {
13809 APValue SourceLHS;
13810 std::optional<APValue> Fallback;
13811 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS))
13812 return false;
13813 if (E->getNumArgs() > 1) {
13814 APValue FallbackTmp;
13815 if (!EvaluateAsRValue(Info, E->getArg(1), FallbackTmp))
13816 return false;
13817 Fallback = FallbackTmp;
13818 }
13819
13820 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
13821 unsigned SourceLen = SourceLHS.getVectorLength();
13822 SmallVector<APValue, 4> ResultElements;
13823 ResultElements.reserve(SourceLen);
13824
13825 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
13826 APSInt LHS = SourceLHS.getVectorElt(EltNum).getInt();
13827 if (!LHS) {
13828 // Without a fallback, a zero element is undefined
13829 if (!Fallback) {
13830 Info.FFDiag(E, diag::note_constexpr_countzeroes_zero)
13831 << /*IsTrailing=*/(E->getBuiltinCallee() ==
13832 Builtin::BI__builtin_elementwise_ctzg);
13833 return false;
13834 }
13835 ResultElements.push_back(Fallback->getVectorElt(EltNum));
13836 continue;
13837 }
13838 switch (E->getBuiltinCallee()) {
13839 case Builtin::BI__builtin_elementwise_clzg:
13840 ResultElements.push_back(APValue(
13841 APSInt(APInt(Info.Ctx.getIntWidth(DestEltTy), LHS.countl_zero()),
13842 DestEltTy->isUnsignedIntegerOrEnumerationType())));
13843 break;
13844 case Builtin::BI__builtin_elementwise_ctzg:
13845 ResultElements.push_back(APValue(
13846 APSInt(APInt(Info.Ctx.getIntWidth(DestEltTy), LHS.countr_zero()),
13847 DestEltTy->isUnsignedIntegerOrEnumerationType())));
13848 break;
13849 }
13850 }
13851
13852 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13853 }
13854
13855 case Builtin::BI__builtin_elementwise_fma: {
13856 APValue SourceX, SourceY, SourceZ;
13857 if (!EvaluateAsRValue(Info, E->getArg(0), SourceX) ||
13858 !EvaluateAsRValue(Info, E->getArg(1), SourceY) ||
13859 !EvaluateAsRValue(Info, E->getArg(2), SourceZ))
13860 return false;
13861
13862 unsigned SourceLen = SourceX.getVectorLength();
13863 SmallVector<APValue> ResultElements;
13864 ResultElements.reserve(SourceLen);
13865 llvm::RoundingMode RM = getActiveRoundingMode(getEvalInfo(), E);
13866 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
13867 const APFloat &X = SourceX.getVectorElt(EltNum).getFloat();
13868 const APFloat &Y = SourceY.getVectorElt(EltNum).getFloat();
13869 const APFloat &Z = SourceZ.getVectorElt(EltNum).getFloat();
13870 APFloat Result(X);
13871 (void)Result.fusedMultiplyAdd(Y, Z, RM);
13872 ResultElements.push_back(APValue(Result));
13873 }
13874 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13875 }
13876
13877 case clang::X86::BI__builtin_ia32_phaddw128:
13878 case clang::X86::BI__builtin_ia32_phaddw256:
13879 case clang::X86::BI__builtin_ia32_phaddd128:
13880 case clang::X86::BI__builtin_ia32_phaddd256:
13881 case clang::X86::BI__builtin_ia32_phaddsw128:
13882 case clang::X86::BI__builtin_ia32_phaddsw256:
13883
13884 case clang::X86::BI__builtin_ia32_phsubw128:
13885 case clang::X86::BI__builtin_ia32_phsubw256:
13886 case clang::X86::BI__builtin_ia32_phsubd128:
13887 case clang::X86::BI__builtin_ia32_phsubd256:
13888 case clang::X86::BI__builtin_ia32_phsubsw128:
13889 case clang::X86::BI__builtin_ia32_phsubsw256: {
13890 APValue SourceLHS, SourceRHS;
13891 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
13892 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
13893 return false;
13894 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
13895 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
13896
13897 unsigned NumElts = SourceLHS.getVectorLength();
13898 unsigned EltBits = Info.Ctx.getIntWidth(DestEltTy);
13899 unsigned EltsPerLane = 128 / EltBits;
13900 SmallVector<APValue, 4> ResultElements;
13901 ResultElements.reserve(NumElts);
13902
13903 for (unsigned LaneStart = 0; LaneStart != NumElts;
13904 LaneStart += EltsPerLane) {
13905 for (unsigned I = 0; I != EltsPerLane; I += 2) {
13906 APSInt LHSA = SourceLHS.getVectorElt(LaneStart + I).getInt();
13907 APSInt LHSB = SourceLHS.getVectorElt(LaneStart + I + 1).getInt();
13908 switch (E->getBuiltinCallee()) {
13909 case clang::X86::BI__builtin_ia32_phaddw128:
13910 case clang::X86::BI__builtin_ia32_phaddw256:
13911 case clang::X86::BI__builtin_ia32_phaddd128:
13912 case clang::X86::BI__builtin_ia32_phaddd256: {
13913 APSInt Res(LHSA + LHSB, DestUnsigned);
13914 ResultElements.push_back(APValue(Res));
13915 break;
13916 }
13917 case clang::X86::BI__builtin_ia32_phaddsw128:
13918 case clang::X86::BI__builtin_ia32_phaddsw256: {
13919 APSInt Res(LHSA.sadd_sat(LHSB));
13920 ResultElements.push_back(APValue(Res));
13921 break;
13922 }
13923 case clang::X86::BI__builtin_ia32_phsubw128:
13924 case clang::X86::BI__builtin_ia32_phsubw256:
13925 case clang::X86::BI__builtin_ia32_phsubd128:
13926 case clang::X86::BI__builtin_ia32_phsubd256: {
13927 APSInt Res(LHSA - LHSB, DestUnsigned);
13928 ResultElements.push_back(APValue(Res));
13929 break;
13930 }
13931 case clang::X86::BI__builtin_ia32_phsubsw128:
13932 case clang::X86::BI__builtin_ia32_phsubsw256: {
13933 APSInt Res(LHSA.ssub_sat(LHSB));
13934 ResultElements.push_back(APValue(Res));
13935 break;
13936 }
13937 }
13938 }
13939 for (unsigned I = 0; I != EltsPerLane; I += 2) {
13940 APSInt RHSA = SourceRHS.getVectorElt(LaneStart + I).getInt();
13941 APSInt RHSB = SourceRHS.getVectorElt(LaneStart + I + 1).getInt();
13942 switch (E->getBuiltinCallee()) {
13943 case clang::X86::BI__builtin_ia32_phaddw128:
13944 case clang::X86::BI__builtin_ia32_phaddw256:
13945 case clang::X86::BI__builtin_ia32_phaddd128:
13946 case clang::X86::BI__builtin_ia32_phaddd256: {
13947 APSInt Res(RHSA + RHSB, DestUnsigned);
13948 ResultElements.push_back(APValue(Res));
13949 break;
13950 }
13951 case clang::X86::BI__builtin_ia32_phaddsw128:
13952 case clang::X86::BI__builtin_ia32_phaddsw256: {
13953 APSInt Res(RHSA.sadd_sat(RHSB));
13954 ResultElements.push_back(APValue(Res));
13955 break;
13956 }
13957 case clang::X86::BI__builtin_ia32_phsubw128:
13958 case clang::X86::BI__builtin_ia32_phsubw256:
13959 case clang::X86::BI__builtin_ia32_phsubd128:
13960 case clang::X86::BI__builtin_ia32_phsubd256: {
13961 APSInt Res(RHSA - RHSB, DestUnsigned);
13962 ResultElements.push_back(APValue(Res));
13963 break;
13964 }
13965 case clang::X86::BI__builtin_ia32_phsubsw128:
13966 case clang::X86::BI__builtin_ia32_phsubsw256: {
13967 APSInt Res(RHSA.ssub_sat(RHSB));
13968 ResultElements.push_back(APValue(Res));
13969 break;
13970 }
13971 }
13972 }
13973 }
13974 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13975 }
13976 case clang::X86::BI__builtin_ia32_haddpd:
13977 case clang::X86::BI__builtin_ia32_haddps:
13978 case clang::X86::BI__builtin_ia32_haddps256:
13979 case clang::X86::BI__builtin_ia32_haddpd256:
13980 case clang::X86::BI__builtin_ia32_hsubpd:
13981 case clang::X86::BI__builtin_ia32_hsubps:
13982 case clang::X86::BI__builtin_ia32_hsubps256:
13983 case clang::X86::BI__builtin_ia32_hsubpd256: {
13984 APValue SourceLHS, SourceRHS;
13985 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
13986 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
13987 return false;
13988 unsigned NumElts = SourceLHS.getVectorLength();
13989 SmallVector<APValue, 4> ResultElements;
13990 ResultElements.reserve(NumElts);
13991 llvm::RoundingMode RM = getActiveRoundingMode(getEvalInfo(), E);
13992 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
13993 unsigned EltBits = Info.Ctx.getTypeSize(DestEltTy);
13994 unsigned NumLanes = NumElts * EltBits / 128;
13995 unsigned NumElemsPerLane = NumElts / NumLanes;
13996 unsigned HalfElemsPerLane = NumElemsPerLane / 2;
13997
13998 for (unsigned L = 0; L != NumElts; L += NumElemsPerLane) {
13999 for (unsigned I = 0; I != HalfElemsPerLane; ++I) {
14000 APFloat LHSA = SourceLHS.getVectorElt(L + (2 * I) + 0).getFloat();
14001 APFloat LHSB = SourceLHS.getVectorElt(L + (2 * I) + 1).getFloat();
14002 switch (E->getBuiltinCallee()) {
14003 case clang::X86::BI__builtin_ia32_haddpd:
14004 case clang::X86::BI__builtin_ia32_haddps:
14005 case clang::X86::BI__builtin_ia32_haddps256:
14006 case clang::X86::BI__builtin_ia32_haddpd256:
14007 LHSA.add(LHSB, RM);
14008 break;
14009 case clang::X86::BI__builtin_ia32_hsubpd:
14010 case clang::X86::BI__builtin_ia32_hsubps:
14011 case clang::X86::BI__builtin_ia32_hsubps256:
14012 case clang::X86::BI__builtin_ia32_hsubpd256:
14013 LHSA.subtract(LHSB, RM);
14014 break;
14015 }
14016 ResultElements.push_back(APValue(LHSA));
14017 }
14018 for (unsigned I = 0; I != HalfElemsPerLane; ++I) {
14019 APFloat RHSA = SourceRHS.getVectorElt(L + (2 * I) + 0).getFloat();
14020 APFloat RHSB = SourceRHS.getVectorElt(L + (2 * I) + 1).getFloat();
14021 switch (E->getBuiltinCallee()) {
14022 case clang::X86::BI__builtin_ia32_haddpd:
14023 case clang::X86::BI__builtin_ia32_haddps:
14024 case clang::X86::BI__builtin_ia32_haddps256:
14025 case clang::X86::BI__builtin_ia32_haddpd256:
14026 RHSA.add(RHSB, RM);
14027 break;
14028 case clang::X86::BI__builtin_ia32_hsubpd:
14029 case clang::X86::BI__builtin_ia32_hsubps:
14030 case clang::X86::BI__builtin_ia32_hsubps256:
14031 case clang::X86::BI__builtin_ia32_hsubpd256:
14032 RHSA.subtract(RHSB, RM);
14033 break;
14034 }
14035 ResultElements.push_back(APValue(RHSA));
14036 }
14037 }
14038 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
14039 }
14040 case clang::X86::BI__builtin_ia32_addsubpd:
14041 case clang::X86::BI__builtin_ia32_addsubps:
14042 case clang::X86::BI__builtin_ia32_addsubpd256:
14043 case clang::X86::BI__builtin_ia32_addsubps256: {
14044 // Addsub: alternates between subtraction and addition
14045 // Result[i] = (i % 2 == 0) ? (a[i] - b[i]) : (a[i] + b[i])
14046 APValue SourceLHS, SourceRHS;
14047 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
14048 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
14049 return false;
14050 unsigned NumElems = SourceLHS.getVectorLength();
14051 SmallVector<APValue, 8> ResultElements;
14052 ResultElements.reserve(NumElems);
14053 llvm::RoundingMode RM = getActiveRoundingMode(getEvalInfo(), E);
14054
14055 for (unsigned I = 0; I != NumElems; ++I) {
14056 APFloat LHS = SourceLHS.getVectorElt(I).getFloat();
14057 APFloat RHS = SourceRHS.getVectorElt(I).getFloat();
14058 if (I % 2 == 0) {
14059 // Even indices: subtract
14060 LHS.subtract(RHS, RM);
14061 } else {
14062 // Odd indices: add
14063 LHS.add(RHS, RM);
14064 }
14065 ResultElements.push_back(APValue(LHS));
14066 }
14067 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
14068 }
14069 case clang::X86::BI__builtin_ia32_pclmulqdq128:
14070 case clang::X86::BI__builtin_ia32_pclmulqdq256:
14071 case clang::X86::BI__builtin_ia32_pclmulqdq512: {
14072 // PCLMULQDQ: carry-less multiplication of selected 64-bit halves
14073 // imm8 bit 0: selects lower (0) or upper (1) 64 bits of first operand
14074 // imm8 bit 4: selects lower (0) or upper (1) 64 bits of second operand
14075 APValue SourceLHS, SourceRHS;
14076 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
14077 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
14078 return false;
14079
14080 APSInt Imm8;
14081 if (!EvaluateInteger(E->getArg(2), Imm8, Info))
14082 return false;
14083
14084 // Extract bits 0 and 4 from imm8
14085 bool SelectUpperA = (Imm8 & 0x01) != 0;
14086 bool SelectUpperB = (Imm8 & 0x10) != 0;
14087
14088 unsigned NumElems = SourceLHS.getVectorLength();
14089 SmallVector<APValue, 8> ResultElements;
14090 ResultElements.reserve(NumElems);
14091 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
14092 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
14093
14094 // Process each 128-bit lane
14095 for (unsigned Lane = 0; Lane < NumElems; Lane += 2) {
14096 // Get the two 64-bit halves of the first operand
14097 APSInt A0 = SourceLHS.getVectorElt(Lane + 0).getInt();
14098 APSInt A1 = SourceLHS.getVectorElt(Lane + 1).getInt();
14099 // Get the two 64-bit halves of the second operand
14100 APSInt B0 = SourceRHS.getVectorElt(Lane + 0).getInt();
14101 APSInt B1 = SourceRHS.getVectorElt(Lane + 1).getInt();
14102
14103 // Select the appropriate 64-bit values based on imm8
14104 APInt A = SelectUpperA ? A1 : A0;
14105 APInt B = SelectUpperB ? B1 : B0;
14106
14107 // Extend both operands to 128 bits for carry-less multiplication
14108 APInt A128 = A.zext(128);
14109 APInt B128 = B.zext(128);
14110
14111 // Use APIntOps::clmul for carry-less multiplication
14112 APInt Result = llvm::APIntOps::clmul(A128, B128);
14113
14114 // Split the 128-bit result into two 64-bit halves
14115 APSInt ResultLow(Result.extractBits(64, 0), DestUnsigned);
14116 APSInt ResultHigh(Result.extractBits(64, 64), DestUnsigned);
14117
14118 ResultElements.push_back(APValue(ResultLow));
14119 ResultElements.push_back(APValue(ResultHigh));
14120 }
14121
14122 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
14123 }
14124 case Builtin::BI__builtin_elementwise_clmul:
14125 return EvaluateBinOpExpr(llvm::APIntOps::clmul);
14126 case Builtin::BI__builtin_elementwise_pext:
14127 return EvaluateBinOpExpr(llvm::APIntOps::compressBits);
14128 case Builtin::BI__builtin_elementwise_pdep:
14129 return EvaluateBinOpExpr(llvm::APIntOps::expandBits);
14130 case Builtin::BI__builtin_elementwise_fshl:
14131 case Builtin::BI__builtin_elementwise_fshr: {
14132 APValue SourceHi, SourceLo, SourceShift;
14133 if (!EvaluateAsRValue(Info, E->getArg(0), SourceHi) ||
14134 !EvaluateAsRValue(Info, E->getArg(1), SourceLo) ||
14135 !EvaluateAsRValue(Info, E->getArg(2), SourceShift))
14136 return false;
14137
14138 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
14139 if (!DestEltTy->isIntegerType())
14140 return false;
14141
14142 unsigned SourceLen = SourceHi.getVectorLength();
14143 SmallVector<APValue> ResultElements;
14144 ResultElements.reserve(SourceLen);
14145 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
14146 const APSInt &Hi = SourceHi.getVectorElt(EltNum).getInt();
14147 const APSInt &Lo = SourceLo.getVectorElt(EltNum).getInt();
14148 const APSInt &Shift = SourceShift.getVectorElt(EltNum).getInt();
14149 switch (E->getBuiltinCallee()) {
14150 case Builtin::BI__builtin_elementwise_fshl:
14151 ResultElements.push_back(APValue(
14152 APSInt(llvm::APIntOps::fshl(Hi, Lo, Shift), Hi.isUnsigned())));
14153 break;
14154 case Builtin::BI__builtin_elementwise_fshr:
14155 ResultElements.push_back(APValue(
14156 APSInt(llvm::APIntOps::fshr(Hi, Lo, Shift), Hi.isUnsigned())));
14157 break;
14158 }
14159 }
14160
14161 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
14162 }
14163
14164 case X86::BI__builtin_ia32_shuf_f32x4_256:
14165 case X86::BI__builtin_ia32_shuf_i32x4_256:
14166 case X86::BI__builtin_ia32_shuf_f64x2_256:
14167 case X86::BI__builtin_ia32_shuf_i64x2_256:
14168 case X86::BI__builtin_ia32_shuf_f32x4:
14169 case X86::BI__builtin_ia32_shuf_i32x4:
14170 case X86::BI__builtin_ia32_shuf_f64x2:
14171 case X86::BI__builtin_ia32_shuf_i64x2: {
14172 APValue SourceA, SourceB;
14173 if (!EvaluateAsRValue(Info, E->getArg(0), SourceA) ||
14174 !EvaluateAsRValue(Info, E->getArg(1), SourceB))
14175 return false;
14176
14177 APSInt Imm;
14178 if (!EvaluateInteger(E->getArg(2), Imm, Info))
14179 return false;
14180
14181 // Destination and sources A, B all have the same type.
14182 unsigned NumElems = SourceA.getVectorLength();
14183 const VectorType *VT = E->getArg(0)->getType()->castAs<VectorType>();
14184 QualType ElemQT = VT->getElementType();
14185 unsigned ElemBits = Info.Ctx.getTypeSize(ElemQT);
14186 unsigned LaneBits = 128u;
14187 unsigned NumLanes = (NumElems * ElemBits) / LaneBits;
14188 unsigned NumElemsPerLane = LaneBits / ElemBits;
14189
14190 unsigned DstLen = SourceA.getVectorLength();
14191 SmallVector<APValue, 16> ResultElements;
14192 ResultElements.reserve(DstLen);
14193
14194 APValue R;
14195 if (!evalShuffleGeneric(
14196 Info, E, R,
14197 [NumLanes, NumElemsPerLane](unsigned DstIdx, unsigned ShuffleMask)
14198 -> std::pair<unsigned, int> {
14199 // DstIdx determines source. ShuffleMask selects lane in source.
14200 unsigned BitsPerElem = NumLanes / 2;
14201 unsigned IndexMask = (1u << BitsPerElem) - 1;
14202 unsigned Lane = DstIdx / NumElemsPerLane;
14203 unsigned SrcIdx = (Lane < NumLanes / 2) ? 0 : 1;
14204 unsigned BitIdx = BitsPerElem * Lane;
14205 unsigned SrcLaneIdx = (ShuffleMask >> BitIdx) & IndexMask;
14206 unsigned ElemInLane = DstIdx % NumElemsPerLane;
14207 unsigned IdxToPick = SrcLaneIdx * NumElemsPerLane + ElemInLane;
14208 return {SrcIdx, IdxToPick};
14209 }))
14210 return false;
14211 return Success(R, E);
14212 }
14213
14214 case X86::BI__builtin_ia32_vgf2p8affineinvqb_v16qi:
14215 case X86::BI__builtin_ia32_vgf2p8affineinvqb_v32qi:
14216 case X86::BI__builtin_ia32_vgf2p8affineinvqb_v64qi:
14217 case X86::BI__builtin_ia32_vgf2p8affineqb_v16qi:
14218 case X86::BI__builtin_ia32_vgf2p8affineqb_v32qi:
14219 case X86::BI__builtin_ia32_vgf2p8affineqb_v64qi: {
14220
14221 APValue X, A;
14222 APSInt Imm;
14223 if (!EvaluateAsRValue(Info, E->getArg(0), X) ||
14224 !EvaluateAsRValue(Info, E->getArg(1), A) ||
14225 !EvaluateInteger(E->getArg(2), Imm, Info))
14226 return false;
14227
14228 assert(X.isVector() && A.isVector());
14229 assert(X.getVectorLength() == A.getVectorLength());
14230
14231 bool IsInverse = false;
14232 switch (E->getBuiltinCallee()) {
14233 case X86::BI__builtin_ia32_vgf2p8affineinvqb_v16qi:
14234 case X86::BI__builtin_ia32_vgf2p8affineinvqb_v32qi:
14235 case X86::BI__builtin_ia32_vgf2p8affineinvqb_v64qi: {
14236 IsInverse = true;
14237 }
14238 }
14239
14240 unsigned NumBitsInByte = 8;
14241 unsigned NumBytesInQWord = 8;
14242 unsigned NumBitsInQWord = 64;
14243 unsigned NumBytes = A.getVectorLength();
14244 unsigned NumQWords = NumBytes / NumBytesInQWord;
14246 Result.reserve(NumBytes);
14247
14248 // computing A*X + Imm
14249 for (unsigned QWordIdx = 0; QWordIdx != NumQWords; ++QWordIdx) {
14250 // Extract the QWords from X, A
14251 APInt XQWord(NumBitsInQWord, 0);
14252 APInt AQWord(NumBitsInQWord, 0);
14253 for (unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
14254 unsigned Idx = QWordIdx * NumBytesInQWord + ByteIdx;
14255 APInt XByte = X.getVectorElt(Idx).getInt();
14256 APInt AByte = A.getVectorElt(Idx).getInt();
14257 XQWord.insertBits(XByte, ByteIdx * NumBitsInByte);
14258 AQWord.insertBits(AByte, ByteIdx * NumBitsInByte);
14259 }
14260
14261 for (unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
14262 uint8_t XByte =
14263 XQWord.lshr(ByteIdx * NumBitsInByte).getLoBits(8).getZExtValue();
14264 Result.push_back(APValue(APSInt(
14265 APInt(8, GFNIAffine(XByte, AQWord, Imm, IsInverse)), false)));
14266 }
14267 }
14268
14269 return Success(APValue(Result.data(), Result.size()), E);
14270 }
14271
14272 case X86::BI__builtin_ia32_vgf2p8mulb_v16qi:
14273 case X86::BI__builtin_ia32_vgf2p8mulb_v32qi:
14274 case X86::BI__builtin_ia32_vgf2p8mulb_v64qi: {
14275 APValue A, B;
14276 if (!EvaluateAsRValue(Info, E->getArg(0), A) ||
14277 !EvaluateAsRValue(Info, E->getArg(1), B))
14278 return false;
14279
14280 assert(A.isVector() && B.isVector());
14281 assert(A.getVectorLength() == B.getVectorLength());
14282
14283 unsigned NumBytes = A.getVectorLength();
14285 Result.reserve(NumBytes);
14286
14287 for (unsigned ByteIdx = 0; ByteIdx != NumBytes; ++ByteIdx) {
14288 uint8_t AByte = A.getVectorElt(ByteIdx).getInt().getZExtValue();
14289 uint8_t BByte = B.getVectorElt(ByteIdx).getInt().getZExtValue();
14290 Result.push_back(APValue(
14291 APSInt(APInt(8, GFNIMul(AByte, BByte)), /*IsUnsigned=*/false)));
14292 }
14293
14294 return Success(APValue(Result.data(), Result.size()), E);
14295 }
14296
14297 case X86::BI__builtin_ia32_insertf32x4_256:
14298 case X86::BI__builtin_ia32_inserti32x4_256:
14299 case X86::BI__builtin_ia32_insertf64x2_256:
14300 case X86::BI__builtin_ia32_inserti64x2_256:
14301 case X86::BI__builtin_ia32_insertf32x4:
14302 case X86::BI__builtin_ia32_inserti32x4:
14303 case X86::BI__builtin_ia32_insertf64x2_512:
14304 case X86::BI__builtin_ia32_inserti64x2_512:
14305 case X86::BI__builtin_ia32_insertf32x8:
14306 case X86::BI__builtin_ia32_inserti32x8:
14307 case X86::BI__builtin_ia32_insertf64x4:
14308 case X86::BI__builtin_ia32_inserti64x4:
14309 case X86::BI__builtin_ia32_vinsertf128_ps256:
14310 case X86::BI__builtin_ia32_vinsertf128_pd256:
14311 case X86::BI__builtin_ia32_vinsertf128_si256:
14312 case X86::BI__builtin_ia32_insert128i256: {
14313 APValue SourceDst, SourceSub;
14314 if (!EvaluateAsRValue(Info, E->getArg(0), SourceDst) ||
14315 !EvaluateAsRValue(Info, E->getArg(1), SourceSub))
14316 return false;
14317
14318 APSInt Imm;
14319 if (!EvaluateInteger(E->getArg(2), Imm, Info))
14320 return false;
14321
14322 assert(SourceDst.isVector() && SourceSub.isVector());
14323 unsigned DstLen = SourceDst.getVectorLength();
14324 unsigned SubLen = SourceSub.getVectorLength();
14325 assert(SubLen != 0 && DstLen != 0 && (DstLen % SubLen) == 0);
14326 unsigned NumLanes = DstLen / SubLen;
14327 unsigned LaneIdx = (Imm.getZExtValue() % NumLanes) * SubLen;
14328
14329 SmallVector<APValue, 16> ResultElements;
14330 ResultElements.reserve(DstLen);
14331
14332 for (unsigned EltNum = 0; EltNum < DstLen; ++EltNum) {
14333 if (EltNum >= LaneIdx && EltNum < LaneIdx + SubLen)
14334 ResultElements.push_back(SourceSub.getVectorElt(EltNum - LaneIdx));
14335 else
14336 ResultElements.push_back(SourceDst.getVectorElt(EltNum));
14337 }
14338
14339 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
14340 }
14341
14342 case clang::X86::BI__builtin_ia32_vec_set_v4hi:
14343 case clang::X86::BI__builtin_ia32_vec_set_v16qi:
14344 case clang::X86::BI__builtin_ia32_vec_set_v8hi:
14345 case clang::X86::BI__builtin_ia32_vec_set_v4si:
14346 case clang::X86::BI__builtin_ia32_vec_set_v2di:
14347 case clang::X86::BI__builtin_ia32_vec_set_v32qi:
14348 case clang::X86::BI__builtin_ia32_vec_set_v16hi:
14349 case clang::X86::BI__builtin_ia32_vec_set_v8si:
14350 case clang::X86::BI__builtin_ia32_vec_set_v4di: {
14351 APValue VecVal;
14352 APSInt Scalar, IndexAPS;
14353 if (!EvaluateVector(E->getArg(0), VecVal, Info) ||
14354 !EvaluateInteger(E->getArg(1), Scalar, Info) ||
14355 !EvaluateInteger(E->getArg(2), IndexAPS, Info))
14356 return false;
14357
14358 QualType ElemTy = E->getType()->castAs<VectorType>()->getElementType();
14359 unsigned ElemWidth = Info.Ctx.getIntWidth(ElemTy);
14360 bool ElemUnsigned = ElemTy->isUnsignedIntegerOrEnumerationType();
14361 Scalar.setIsUnsigned(ElemUnsigned);
14362 APSInt ElemAPS = Scalar.extOrTrunc(ElemWidth);
14363 APValue ElemAV(ElemAPS);
14364
14365 unsigned NumElems = VecVal.getVectorLength();
14366 unsigned Index =
14367 static_cast<unsigned>(IndexAPS.getZExtValue() & (NumElems - 1));
14368
14370 Elems.reserve(NumElems);
14371 for (unsigned ElemNum = 0; ElemNum != NumElems; ++ElemNum)
14372 Elems.push_back(ElemNum == Index ? ElemAV : VecVal.getVectorElt(ElemNum));
14373
14374 return Success(APValue(Elems.data(), NumElems), E);
14375 }
14376
14377 case X86::BI__builtin_ia32_pslldqi128_byteshift:
14378 case X86::BI__builtin_ia32_pslldqi256_byteshift:
14379 case X86::BI__builtin_ia32_pslldqi512_byteshift: {
14380 APValue R;
14381 if (!evalShuffleGeneric(
14382 Info, E, R,
14383 [](unsigned DstIdx, unsigned Shift) -> std::pair<unsigned, int> {
14384 unsigned LaneBase = (DstIdx / 16) * 16;
14385 unsigned LaneIdx = DstIdx % 16;
14386 if (LaneIdx < Shift)
14387 return std::make_pair(0, -1);
14388
14389 return std::make_pair(
14390 0, static_cast<int>(LaneBase + LaneIdx - Shift));
14391 }))
14392 return false;
14393 return Success(R, E);
14394 }
14395
14396 case X86::BI__builtin_ia32_psrldqi128_byteshift:
14397 case X86::BI__builtin_ia32_psrldqi256_byteshift:
14398 case X86::BI__builtin_ia32_psrldqi512_byteshift: {
14399 APValue R;
14400 if (!evalShuffleGeneric(
14401 Info, E, R,
14402 [](unsigned DstIdx, unsigned Shift) -> std::pair<unsigned, int> {
14403 unsigned LaneBase = (DstIdx / 16) * 16;
14404 unsigned LaneIdx = DstIdx % 16;
14405 if (LaneIdx + Shift < 16)
14406 return std::make_pair(
14407 0, static_cast<int>(LaneBase + LaneIdx + Shift));
14408
14409 return std::make_pair(0, -1);
14410 }))
14411 return false;
14412 return Success(R, E);
14413 }
14414
14415 case X86::BI__builtin_ia32_palignr128:
14416 case X86::BI__builtin_ia32_palignr256:
14417 case X86::BI__builtin_ia32_palignr512: {
14418 APValue R;
14419 if (!evalShuffleGeneric(Info, E, R, [](unsigned DstIdx, unsigned Shift) {
14420 // Default to -1 → zero-fill this destination element
14421 unsigned VecIdx = 1;
14422 int ElemIdx = -1;
14423
14424 int Lane = DstIdx / 16;
14425 int Offset = DstIdx % 16;
14426
14427 // Elements come from VecB first, then VecA after the shift boundary
14428 unsigned ShiftedIdx = Offset + (Shift & 0xFF);
14429 if (ShiftedIdx < 16) { // from VecB
14430 ElemIdx = ShiftedIdx + (Lane * 16);
14431 } else if (ShiftedIdx < 32) { // from VecA
14432 VecIdx = 0;
14433 ElemIdx = (ShiftedIdx - 16) + (Lane * 16);
14434 }
14435
14436 return std::pair<unsigned, int>{VecIdx, ElemIdx};
14437 }))
14438 return false;
14439 return Success(R, E);
14440 }
14441 case X86::BI__builtin_ia32_alignd128:
14442 case X86::BI__builtin_ia32_alignd256:
14443 case X86::BI__builtin_ia32_alignd512:
14444 case X86::BI__builtin_ia32_alignq128:
14445 case X86::BI__builtin_ia32_alignq256:
14446 case X86::BI__builtin_ia32_alignq512: {
14447 APValue R;
14448 unsigned NumElems = E->getType()->castAs<VectorType>()->getNumElements();
14449 if (!evalShuffleGeneric(Info, E, R,
14450 [NumElems](unsigned DstIdx, unsigned Shift) {
14451 unsigned Imm = Shift & 0xFF;
14452 unsigned EffectiveShift = Imm & (NumElems - 1);
14453 unsigned SourcePos = DstIdx + EffectiveShift;
14454 unsigned VecIdx = SourcePos < NumElems ? 1 : 0;
14455 unsigned ElemIdx = SourcePos & (NumElems - 1);
14456
14457 return std::pair<unsigned, int>{
14458 VecIdx, static_cast<int>(ElemIdx)};
14459 }))
14460 return false;
14461 return Success(R, E);
14462 }
14463 case X86::BI__builtin_ia32_permvarsi256:
14464 case X86::BI__builtin_ia32_permvarsf256:
14465 case X86::BI__builtin_ia32_permvardf512:
14466 case X86::BI__builtin_ia32_permvardi512:
14467 case X86::BI__builtin_ia32_permvarhi128: {
14468 APValue R;
14469 if (!evalShuffleGeneric(Info, E, R,
14470 [](unsigned DstIdx, unsigned ShuffleMask) {
14471 int Offset = ShuffleMask & 0x7;
14472 return std::pair<unsigned, int>{0, Offset};
14473 }))
14474 return false;
14475 return Success(R, E);
14476 }
14477 case X86::BI__builtin_ia32_permvarqi128:
14478 case X86::BI__builtin_ia32_permvarhi256:
14479 case X86::BI__builtin_ia32_permvarsi512:
14480 case X86::BI__builtin_ia32_permvarsf512: {
14481 APValue R;
14482 if (!evalShuffleGeneric(Info, E, R,
14483 [](unsigned DstIdx, unsigned ShuffleMask) {
14484 int Offset = ShuffleMask & 0xF;
14485 return std::pair<unsigned, int>{0, Offset};
14486 }))
14487 return false;
14488 return Success(R, E);
14489 }
14490 case X86::BI__builtin_ia32_permvardi256:
14491 case X86::BI__builtin_ia32_permvardf256: {
14492 APValue R;
14493 if (!evalShuffleGeneric(Info, E, R,
14494 [](unsigned DstIdx, unsigned ShuffleMask) {
14495 int Offset = ShuffleMask & 0x3;
14496 return std::pair<unsigned, int>{0, Offset};
14497 }))
14498 return false;
14499 return Success(R, E);
14500 }
14501 case X86::BI__builtin_ia32_permvarqi256:
14502 case X86::BI__builtin_ia32_permvarhi512: {
14503 APValue R;
14504 if (!evalShuffleGeneric(Info, E, R,
14505 [](unsigned DstIdx, unsigned ShuffleMask) {
14506 int Offset = ShuffleMask & 0x1F;
14507 return std::pair<unsigned, int>{0, Offset};
14508 }))
14509 return false;
14510 return Success(R, E);
14511 }
14512 case X86::BI__builtin_ia32_permvarqi512: {
14513 APValue R;
14514 if (!evalShuffleGeneric(Info, E, R,
14515 [](unsigned DstIdx, unsigned ShuffleMask) {
14516 int Offset = ShuffleMask & 0x3F;
14517 return std::pair<unsigned, int>{0, Offset};
14518 }))
14519 return false;
14520 return Success(R, E);
14521 }
14522 case X86::BI__builtin_ia32_vpermi2varq128:
14523 case X86::BI__builtin_ia32_vpermi2varpd128: {
14524 APValue R;
14525 if (!evalShuffleGeneric(Info, E, R,
14526 [](unsigned DstIdx, unsigned ShuffleMask) {
14527 int Offset = ShuffleMask & 0x1;
14528 unsigned SrcIdx = (ShuffleMask >> 1) & 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_vpermi2vard128:
14535 case X86::BI__builtin_ia32_vpermi2varps128:
14536 case X86::BI__builtin_ia32_vpermi2varq256:
14537 case X86::BI__builtin_ia32_vpermi2varpd256: {
14538 APValue R;
14539 if (!evalShuffleGeneric(Info, E, R,
14540 [](unsigned DstIdx, unsigned ShuffleMask) {
14541 int Offset = ShuffleMask & 0x3;
14542 unsigned SrcIdx = (ShuffleMask >> 2) & 0x1;
14543 return std::pair<unsigned, int>{SrcIdx, Offset};
14544 }))
14545 return false;
14546 return Success(R, E);
14547 }
14548 case X86::BI__builtin_ia32_vpermi2varhi128:
14549 case X86::BI__builtin_ia32_vpermi2vard256:
14550 case X86::BI__builtin_ia32_vpermi2varps256:
14551 case X86::BI__builtin_ia32_vpermi2varq512:
14552 case X86::BI__builtin_ia32_vpermi2varpd512: {
14553 APValue R;
14554 if (!evalShuffleGeneric(Info, E, R,
14555 [](unsigned DstIdx, unsigned ShuffleMask) {
14556 int Offset = ShuffleMask & 0x7;
14557 unsigned SrcIdx = (ShuffleMask >> 3) & 0x1;
14558 return std::pair<unsigned, int>{SrcIdx, Offset};
14559 }))
14560 return false;
14561 return Success(R, E);
14562 }
14563 case X86::BI__builtin_ia32_vpermi2varqi128:
14564 case X86::BI__builtin_ia32_vpermi2varhi256:
14565 case X86::BI__builtin_ia32_vpermi2vard512:
14566 case X86::BI__builtin_ia32_vpermi2varps512: {
14567 APValue R;
14568 if (!evalShuffleGeneric(Info, E, R,
14569 [](unsigned DstIdx, unsigned ShuffleMask) {
14570 int Offset = ShuffleMask & 0xF;
14571 unsigned SrcIdx = (ShuffleMask >> 4) & 0x1;
14572 return std::pair<unsigned, int>{SrcIdx, Offset};
14573 }))
14574 return false;
14575 return Success(R, E);
14576 }
14577 case X86::BI__builtin_ia32_vpermi2varqi256:
14578 case X86::BI__builtin_ia32_vpermi2varhi512: {
14579 APValue R;
14580 if (!evalShuffleGeneric(Info, E, R,
14581 [](unsigned DstIdx, unsigned ShuffleMask) {
14582 int Offset = ShuffleMask & 0x1F;
14583 unsigned SrcIdx = (ShuffleMask >> 5) & 0x1;
14584 return std::pair<unsigned, int>{SrcIdx, Offset};
14585 }))
14586 return false;
14587 return Success(R, E);
14588 }
14589 case X86::BI__builtin_ia32_vpermi2varqi512: {
14590 APValue R;
14591 if (!evalShuffleGeneric(Info, E, R,
14592 [](unsigned DstIdx, unsigned ShuffleMask) {
14593 int Offset = ShuffleMask & 0x3F;
14594 unsigned SrcIdx = (ShuffleMask >> 6) & 0x1;
14595 return std::pair<unsigned, int>{SrcIdx, Offset};
14596 }))
14597 return false;
14598 return Success(R, E);
14599 }
14600
14601 case clang::X86::BI__builtin_ia32_minps:
14602 case clang::X86::BI__builtin_ia32_minpd:
14603 case clang::X86::BI__builtin_ia32_minps256:
14604 case clang::X86::BI__builtin_ia32_minpd256:
14605 case clang::X86::BI__builtin_ia32_minps512:
14606 case clang::X86::BI__builtin_ia32_minpd512:
14607 case clang::X86::BI__builtin_ia32_minph128:
14608 case clang::X86::BI__builtin_ia32_minph256:
14609 case clang::X86::BI__builtin_ia32_minph512:
14610 return EvaluateFpBinOpExpr(
14611 [](const APFloat &A, const APFloat &B,
14612 std::optional<APSInt>) -> std::optional<APFloat> {
14613 if (A.isNaN() || A.isInfinity() || A.isDenormal() || B.isNaN() ||
14614 B.isInfinity() || B.isDenormal())
14615 return std::nullopt;
14616 if (A.isZero() && B.isZero())
14617 return B;
14618 return llvm::minimum(A, B);
14619 });
14620
14621 case clang::X86::BI__builtin_ia32_minss:
14622 case clang::X86::BI__builtin_ia32_minsd:
14623 return EvaluateFpBinOpExpr(
14624 [](const APFloat &A, const APFloat &B,
14625 std::optional<APSInt> RoundingMode) -> std::optional<APFloat> {
14626 return EvalScalarMinMaxFp(A, B, RoundingMode, /*IsMin=*/true);
14627 },
14628 /*IsScalar=*/true);
14629
14630 case clang::X86::BI__builtin_ia32_minsd_round_mask:
14631 case clang::X86::BI__builtin_ia32_minss_round_mask:
14632 case clang::X86::BI__builtin_ia32_minsh_round_mask:
14633 case clang::X86::BI__builtin_ia32_maxsd_round_mask:
14634 case clang::X86::BI__builtin_ia32_maxss_round_mask:
14635 case clang::X86::BI__builtin_ia32_maxsh_round_mask: {
14636 bool IsMin =
14637 E->getBuiltinCallee() ==
14638 clang::X86::BI__builtin_ia32_minsd_round_mask ||
14639 E->getBuiltinCallee() ==
14640 clang::X86::BI__builtin_ia32_minss_round_mask ||
14641 E->getBuiltinCallee() == clang::X86::BI__builtin_ia32_minsh_round_mask;
14642 return EvaluateScalarFpRoundMaskBinOp(
14643 [IsMin](const APFloat &A, const APFloat &B,
14644 std::optional<APSInt> RoundingMode) -> std::optional<APFloat> {
14645 return EvalScalarMinMaxFp(A, B, RoundingMode, IsMin);
14646 });
14647 }
14648
14649 case clang::X86::BI__builtin_ia32_maxps:
14650 case clang::X86::BI__builtin_ia32_maxpd:
14651 case clang::X86::BI__builtin_ia32_maxps256:
14652 case clang::X86::BI__builtin_ia32_maxpd256:
14653 case clang::X86::BI__builtin_ia32_maxps512:
14654 case clang::X86::BI__builtin_ia32_maxpd512:
14655 case clang::X86::BI__builtin_ia32_maxph128:
14656 case clang::X86::BI__builtin_ia32_maxph256:
14657 case clang::X86::BI__builtin_ia32_maxph512:
14658 return EvaluateFpBinOpExpr(
14659 [](const APFloat &A, const APFloat &B,
14660 std::optional<APSInt>) -> std::optional<APFloat> {
14661 if (A.isNaN() || A.isInfinity() || A.isDenormal() || B.isNaN() ||
14662 B.isInfinity() || B.isDenormal())
14663 return std::nullopt;
14664 if (A.isZero() && B.isZero())
14665 return B;
14666 return llvm::maximum(A, B);
14667 });
14668
14669 case clang::X86::BI__builtin_ia32_maxss:
14670 case clang::X86::BI__builtin_ia32_maxsd:
14671 return EvaluateFpBinOpExpr(
14672 [](const APFloat &A, const APFloat &B,
14673 std::optional<APSInt> RoundingMode) -> std::optional<APFloat> {
14674 return EvalScalarMinMaxFp(A, B, RoundingMode, /*IsMin=*/false);
14675 },
14676 /*IsScalar=*/true);
14677
14678 case clang::X86::BI__builtin_ia32_vcvtps2ph:
14679 case clang::X86::BI__builtin_ia32_vcvtps2ph256: {
14680 APValue SrcVec;
14681 if (!EvaluateAsRValue(Info, E->getArg(0), SrcVec))
14682 return false;
14683
14684 APSInt Imm;
14685 if (!EvaluateInteger(E->getArg(1), Imm, Info))
14686 return false;
14687
14688 const auto *SrcVTy = E->getArg(0)->getType()->castAs<VectorType>();
14689 unsigned SrcNumElems = SrcVTy->getNumElements();
14690 const auto *DstVTy = E->getType()->castAs<VectorType>();
14691 unsigned DstNumElems = DstVTy->getNumElements();
14692 QualType DstElemTy = DstVTy->getElementType();
14693
14694 const llvm::fltSemantics &HalfSem =
14695 Info.Ctx.getFloatTypeSemantics(Info.Ctx.HalfTy);
14696
14697 int ImmVal = Imm.getZExtValue();
14698 bool UseMXCSR = (ImmVal & 4) != 0;
14699 bool IsFPConstrained =
14700 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained();
14701
14702 llvm::RoundingMode RM;
14703 if (!UseMXCSR) {
14704 switch (ImmVal & 3) {
14705 case 0:
14706 RM = llvm::RoundingMode::NearestTiesToEven;
14707 break;
14708 case 1:
14709 RM = llvm::RoundingMode::TowardNegative;
14710 break;
14711 case 2:
14712 RM = llvm::RoundingMode::TowardPositive;
14713 break;
14714 case 3:
14715 RM = llvm::RoundingMode::TowardZero;
14716 break;
14717 default:
14718 llvm_unreachable("Invalid immediate rounding mode");
14719 }
14720 } else {
14721 RM = llvm::RoundingMode::NearestTiesToEven;
14722 }
14723
14724 SmallVector<APValue, 8> ResultElements;
14725 ResultElements.reserve(DstNumElems);
14726
14727 for (unsigned I = 0; I < SrcNumElems; ++I) {
14728 APFloat SrcVal = SrcVec.getVectorElt(I).getFloat();
14729
14730 bool LostInfo;
14731 APFloat::opStatus St = SrcVal.convert(HalfSem, RM, &LostInfo);
14732
14733 if (UseMXCSR && IsFPConstrained && St != APFloat::opOK) {
14734 Info.FFDiag(E, diag::note_constexpr_dynamic_rounding);
14735 return false;
14736 }
14737
14738 APSInt DstInt(SrcVal.bitcastToAPInt(),
14740 ResultElements.push_back(APValue(DstInt));
14741 }
14742
14743 if (DstNumElems > SrcNumElems) {
14744 APSInt Zero = Info.Ctx.MakeIntValue(0, DstElemTy);
14745 for (unsigned I = SrcNumElems; I < DstNumElems; ++I) {
14746 ResultElements.push_back(APValue(Zero));
14747 }
14748 }
14749
14750 return Success(ResultElements, E);
14751 }
14752 case X86::BI__builtin_ia32_vperm2f128_pd256:
14753 case X86::BI__builtin_ia32_vperm2f128_ps256:
14754 case X86::BI__builtin_ia32_vperm2f128_si256:
14755 case X86::BI__builtin_ia32_permti256: {
14756 unsigned NumElements =
14757 E->getArg(0)->getType()->getAs<VectorType>()->getNumElements();
14758 unsigned PreservedBitsCnt = NumElements >> 2;
14759 APValue R;
14760 if (!evalShuffleGeneric(
14761 Info, E, R,
14762 [PreservedBitsCnt](unsigned DstIdx, unsigned ShuffleMask) {
14763 unsigned ControlBitsCnt = DstIdx >> PreservedBitsCnt << 2;
14764 unsigned ControlBits = ShuffleMask >> ControlBitsCnt;
14765
14766 if (ControlBits & 0b1000)
14767 return std::make_pair(0u, -1);
14768
14769 unsigned SrcVecIdx = (ControlBits & 0b10) >> 1;
14770 unsigned PreservedBitsMask = (1 << PreservedBitsCnt) - 1;
14771 int SrcIdx = ((ControlBits & 0b1) << PreservedBitsCnt) |
14772 (DstIdx & PreservedBitsMask);
14773 return std::make_pair(SrcVecIdx, SrcIdx);
14774 }))
14775 return false;
14776 return Success(R, E);
14777 }
14778 }
14779}
14780
14781bool VectorExprEvaluator::VisitConvertVectorExpr(const ConvertVectorExpr *E) {
14782 APValue Source;
14783 QualType SourceVecType = E->getSrcExpr()->getType();
14784 if (!EvaluateAsRValue(Info, E->getSrcExpr(), Source))
14785 return false;
14786
14787 QualType DestTy = E->getType()->castAs<VectorType>()->getElementType();
14788 QualType SourceTy = SourceVecType->castAs<VectorType>()->getElementType();
14789
14790 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
14791
14792 auto SourceLen = Source.getVectorLength();
14793 SmallVector<APValue, 4> ResultElements;
14794 ResultElements.reserve(SourceLen);
14795 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
14796 APValue Elt;
14797 if (!handleVectorElementCast(Info, FPO, E, SourceTy, DestTy,
14798 Source.getVectorElt(EltNum), Elt))
14799 return false;
14800 ResultElements.push_back(std::move(Elt));
14801 }
14802
14803 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
14804}
14805
14806static bool handleVectorShuffle(EvalInfo &Info, const ShuffleVectorExpr *E,
14807 QualType ElemType, APValue const &VecVal1,
14808 APValue const &VecVal2, unsigned EltNum,
14809 APValue &Result) {
14810 unsigned const TotalElementsInInputVector1 = VecVal1.getVectorLength();
14811 unsigned const TotalElementsInInputVector2 = VecVal2.getVectorLength();
14812
14813 APSInt IndexVal = E->getShuffleMaskIdx(EltNum);
14814 int64_t index = IndexVal.getExtValue();
14815 // The spec says that -1 should be treated as undef for optimizations,
14816 // but in constexpr we'd have to produce an APValue::Indeterminate,
14817 // which is prohibited from being a top-level constant value. Emit a
14818 // diagnostic instead.
14819 if (index == -1) {
14820 Info.FFDiag(
14821 E, diag::err_shufflevector_minus_one_is_undefined_behavior_constexpr)
14822 << EltNum;
14823 return false;
14824 }
14825
14826 if (index < 0 ||
14827 index >= TotalElementsInInputVector1 + TotalElementsInInputVector2)
14828 llvm_unreachable("Out of bounds shuffle index");
14829
14830 if (index >= TotalElementsInInputVector1)
14831 Result = VecVal2.getVectorElt(index - TotalElementsInInputVector1);
14832 else
14833 Result = VecVal1.getVectorElt(index);
14834 return true;
14835}
14836
14837bool VectorExprEvaluator::VisitShuffleVectorExpr(const ShuffleVectorExpr *E) {
14838 // FIXME: Unary shuffle with mask not currently supported.
14839 if (E->getNumSubExprs() == 2)
14840 return Error(E);
14841 APValue VecVal1;
14842 const Expr *Vec1 = E->getExpr(0);
14843 if (!EvaluateAsRValue(Info, Vec1, VecVal1))
14844 return false;
14845 APValue VecVal2;
14846 const Expr *Vec2 = E->getExpr(1);
14847 if (!EvaluateAsRValue(Info, Vec2, VecVal2))
14848 return false;
14849
14850 VectorType const *DestVecTy = E->getType()->castAs<VectorType>();
14851 QualType DestElTy = DestVecTy->getElementType();
14852
14853 auto TotalElementsInOutputVector = DestVecTy->getNumElements();
14854
14855 SmallVector<APValue, 4> ResultElements;
14856 ResultElements.reserve(TotalElementsInOutputVector);
14857 for (unsigned EltNum = 0; EltNum < TotalElementsInOutputVector; ++EltNum) {
14858 APValue Elt;
14859 if (!handleVectorShuffle(Info, E, DestElTy, VecVal1, VecVal2, EltNum, Elt))
14860 return false;
14861 ResultElements.push_back(std::move(Elt));
14862 }
14863
14864 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
14865}
14866
14867//===----------------------------------------------------------------------===//
14868// Matrix Evaluation
14869//===----------------------------------------------------------------------===//
14870
14871namespace {
14872class MatrixExprEvaluator : public ExprEvaluatorBase<MatrixExprEvaluator> {
14873 APValue &Result;
14874
14875public:
14876 MatrixExprEvaluator(EvalInfo &Info, APValue &Result)
14877 : ExprEvaluatorBaseTy(Info), Result(Result) {}
14878
14879 bool Success(ArrayRef<APValue> M, const Expr *E) {
14880 auto *CMTy = E->getType()->castAs<ConstantMatrixType>();
14881 assert(M.size() == CMTy->getNumElementsFlattened());
14882 // FIXME: remove this APValue copy.
14883 Result = APValue(M.data(), CMTy->getNumRows(), CMTy->getNumColumns());
14884 return true;
14885 }
14886 bool Success(const APValue &M, const Expr *E) {
14887 assert(M.isMatrix() && "expected matrix");
14888 Result = M;
14889 return true;
14890 }
14891
14892 bool VisitCastExpr(const CastExpr *E);
14893 bool VisitInitListExpr(const InitListExpr *E);
14894};
14895} // end anonymous namespace
14896
14897static bool EvaluateMatrix(const Expr *E, APValue &Result, EvalInfo &Info) {
14898 assert(E->isPRValue() && E->getType()->isConstantMatrixType() &&
14899 "not a matrix prvalue");
14900 return MatrixExprEvaluator(Info, Result).Visit(E);
14901}
14902
14903bool MatrixExprEvaluator::VisitCastExpr(const CastExpr *E) {
14904 const auto *MT = E->getType()->castAs<ConstantMatrixType>();
14905 unsigned NumRows = MT->getNumRows();
14906 unsigned NumCols = MT->getNumColumns();
14907 unsigned NElts = NumRows * NumCols;
14908 QualType EltTy = MT->getElementType();
14909 const Expr *SE = E->getSubExpr();
14910
14911 switch (E->getCastKind()) {
14912 case CK_HLSLAggregateSplatCast: {
14913 APValue Val;
14914 QualType ValTy;
14915
14916 if (!hlslAggSplatHelper(Info, SE, Val, ValTy))
14917 return false;
14918
14919 APValue CastedVal;
14920 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
14921 if (!handleScalarCast(Info, FPO, E, ValTy, EltTy, Val, CastedVal))
14922 return false;
14923
14924 SmallVector<APValue, 16> SplatEls(NElts, CastedVal);
14925 return Success(SplatEls, E);
14926 }
14927 case CK_HLSLElementwiseCast: {
14928 SmallVector<APValue> SrcVals;
14929 SmallVector<QualType> SrcTypes;
14930
14931 if (!hlslElementwiseCastHelper(Info, SE, E->getType(), SrcVals, SrcTypes))
14932 return false;
14933
14934 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
14935 SmallVector<QualType, 16> DestTypes(NElts, EltTy);
14936 SmallVector<APValue, 16> ResultEls(NElts);
14937 if (!handleElementwiseCast(Info, E, FPO, SrcVals, SrcTypes, DestTypes,
14938 ResultEls))
14939 return false;
14940 return Success(ResultEls, E);
14941 }
14942 default:
14943 return ExprEvaluatorBaseTy::VisitCastExpr(E);
14944 }
14945}
14946
14947bool MatrixExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
14948 const auto *MT = E->getType()->castAs<ConstantMatrixType>();
14949 QualType EltTy = MT->getElementType();
14950
14951 assert(E->getNumInits() == MT->getNumElementsFlattened() &&
14952 "Expected number of elements in initializer list to match the number "
14953 "of matrix elements");
14954
14955 SmallVector<APValue, 16> Elements;
14956 Elements.reserve(MT->getNumElementsFlattened());
14957
14958 // The following loop assumes the elements of the matrix InitListExpr are in
14959 // row-major order, which matches the row-major ordering assumption of the
14960 // matrix APValue.
14961 for (unsigned I = 0, N = MT->getNumElementsFlattened(); I < N; ++I) {
14962 if (EltTy->isIntegerType()) {
14963 llvm::APSInt IntVal;
14964 if (!EvaluateInteger(E->getInit(I), IntVal, Info))
14965 return false;
14966 Elements.push_back(APValue(IntVal));
14967 } else {
14968 llvm::APFloat FloatVal(0.0);
14969 if (!EvaluateFloat(E->getInit(I), FloatVal, Info))
14970 return false;
14971 Elements.push_back(APValue(FloatVal));
14972 }
14973 }
14974
14975 return Success(Elements, E);
14976}
14977
14978//===----------------------------------------------------------------------===//
14979// Array Evaluation
14980//===----------------------------------------------------------------------===//
14981
14982namespace {
14983 class ArrayExprEvaluator
14984 : public ExprEvaluatorBase<ArrayExprEvaluator> {
14985 const LValue &This;
14986 APValue &Result;
14987 public:
14988
14989 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
14990 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
14991
14992 bool Success(const APValue &V, const Expr *E) {
14993 assert(V.isArray() && "expected array");
14994 Result = V;
14995 return true;
14996 }
14997
14998 bool ZeroInitialization(const Expr *E) {
14999 const ConstantArrayType *CAT =
15000 Info.Ctx.getAsConstantArrayType(E->getType());
15001 if (!CAT) {
15002 if (E->getType()->isIncompleteArrayType()) {
15003 // We can be asked to zero-initialize a flexible array member; this
15004 // is represented as an ImplicitValueInitExpr of incomplete array
15005 // type. In this case, the array has zero elements.
15006 Result = APValue(APValue::UninitArray(), 0, 0);
15007 return true;
15008 }
15009 // FIXME: We could handle VLAs here.
15010 return Error(E);
15011 }
15012
15013 Result = APValue(APValue::UninitArray(), 0, CAT->getZExtSize());
15014 if (!Result.hasArrayFiller())
15015 return true;
15016
15017 // Zero-initialize all elements.
15018 LValue Subobject = This;
15019 Subobject.addArray(Info, E, CAT);
15020 ImplicitValueInitExpr VIE(CAT->getElementType());
15021 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
15022 }
15023
15024 bool VisitCallExpr(const CallExpr *E) {
15025 return handleCallExpr(E, Result, &This);
15026 }
15027 bool VisitCastExpr(const CastExpr *E);
15028 bool VisitInitListExpr(const InitListExpr *E,
15029 QualType AllocType = QualType());
15030 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
15031 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
15032 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
15033 const LValue &Subobject,
15034 APValue *Value, QualType Type);
15035 bool VisitStringLiteral(const StringLiteral *E,
15036 QualType AllocType = QualType()) {
15037 expandStringLiteral(Info, E, Result, AllocType);
15038 return true;
15039 }
15040 bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E);
15041 bool VisitCXXParenListOrInitListExpr(const Expr *ExprToVisit,
15042 ArrayRef<Expr *> Args,
15043 const Expr *ArrayFiller,
15044 QualType AllocType = QualType());
15045 bool VisitDesignatedInitUpdateExpr(const DesignatedInitUpdateExpr *E);
15046 };
15047} // end anonymous namespace
15048
15049static bool EvaluateArray(const Expr *E, const LValue &This,
15050 APValue &Result, EvalInfo &Info) {
15051 assert(!E->isValueDependent());
15052 assert(E->isPRValue() && E->getType()->isArrayType() &&
15053 "not an array prvalue");
15054 return ArrayExprEvaluator(Info, This, Result).Visit(E);
15055}
15056
15057static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
15058 APValue &Result, const InitListExpr *ILE,
15059 QualType AllocType) {
15060 assert(!ILE->isValueDependent());
15061 assert(ILE->isPRValue() && ILE->getType()->isArrayType() &&
15062 "not an array prvalue");
15063 return ArrayExprEvaluator(Info, This, Result)
15064 .VisitInitListExpr(ILE, AllocType);
15065}
15066
15067static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
15068 APValue &Result,
15069 const CXXConstructExpr *CCE,
15070 QualType AllocType) {
15071 assert(!CCE->isValueDependent());
15072 assert(CCE->isPRValue() && CCE->getType()->isArrayType() &&
15073 "not an array prvalue");
15074 return ArrayExprEvaluator(Info, This, Result)
15075 .VisitCXXConstructExpr(CCE, This, &Result, AllocType);
15076}
15077
15078// Return true iff the given array filler may depend on the element index.
15079static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
15080 // For now, just allow non-class value-initialization and initialization
15081 // lists comprised of them.
15082 if (isa<ImplicitValueInitExpr>(FillerExpr))
15083 return false;
15084 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
15085 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
15086 if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
15087 return true;
15088 }
15089
15090 if (ILE->hasArrayFiller() &&
15091 MaybeElementDependentArrayFiller(ILE->getArrayFiller()))
15092 return true;
15093
15094 return false;
15095 }
15096 return true;
15097}
15098
15099bool ArrayExprEvaluator::VisitCastExpr(const CastExpr *E) {
15100 const Expr *SE = E->getSubExpr();
15101
15102 switch (E->getCastKind()) {
15103 default:
15104 return ExprEvaluatorBaseTy::VisitCastExpr(E);
15105 case CK_HLSLAggregateSplatCast: {
15106 APValue Val;
15107 QualType ValTy;
15108
15109 if (!hlslAggSplatHelper(Info, SE, Val, ValTy))
15110 return false;
15111
15112 unsigned NEls = elementwiseSize(Info, E->getType());
15113
15114 SmallVector<APValue> SplatEls(NEls, Val);
15115 SmallVector<QualType> SplatType(NEls, ValTy);
15116
15117 // cast the elements
15118 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
15119 if (!constructAggregate(Info, FPO, E, Result, E->getType(), SplatEls,
15120 SplatType))
15121 return false;
15122
15123 return true;
15124 }
15125 case CK_HLSLElementwiseCast: {
15126 SmallVector<APValue> SrcEls;
15127 SmallVector<QualType> SrcTypes;
15128
15129 if (!hlslElementwiseCastHelper(Info, SE, E->getType(), SrcEls, SrcTypes))
15130 return false;
15131
15132 // cast the elements
15133 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
15134 if (!constructAggregate(Info, FPO, E, Result, E->getType(), SrcEls,
15135 SrcTypes))
15136 return false;
15137 return true;
15138 }
15139 }
15140}
15141
15142bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E,
15143 QualType AllocType) {
15144 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
15145 AllocType.isNull() ? E->getType() : AllocType);
15146 if (!CAT)
15147 return Error(E);
15148
15149 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
15150 // an appropriately-typed string literal enclosed in braces.
15151 if (E->isStringLiteralInit()) {
15152 auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParenImpCasts());
15153 // FIXME: Support ObjCEncodeExpr here once we support it in
15154 // ArrayExprEvaluator generally.
15155 if (!SL)
15156 return Error(E);
15157 return VisitStringLiteral(SL, AllocType);
15158 }
15159 // Any other transparent list init will need proper handling of the
15160 // AllocType; we can't just recurse to the inner initializer.
15161 assert(!E->isTransparent() &&
15162 "transparent array list initialization is not string literal init?");
15163
15164 return VisitCXXParenListOrInitListExpr(E, E->inits(), E->getArrayFiller(),
15165 AllocType);
15166}
15167
15168bool ArrayExprEvaluator::VisitCXXParenListOrInitListExpr(
15169 const Expr *ExprToVisit, ArrayRef<Expr *> Args, const Expr *ArrayFiller,
15170 QualType AllocType) {
15171 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
15172 AllocType.isNull() ? ExprToVisit->getType() : AllocType);
15173
15174 bool Success = true;
15175
15176 unsigned NumEltsToInit = Args.size();
15177 unsigned NumElts = CAT->getZExtSize();
15178
15179 // If the initializer might depend on the array index, run it for each
15180 // array element.
15181 if (NumEltsToInit != NumElts &&
15182 MaybeElementDependentArrayFiller(ArrayFiller)) {
15183 NumEltsToInit = NumElts;
15184 } else {
15185 // Add additional elements represented by EmbedExpr.
15186 for (auto *Init : Args) {
15187 if (auto *EmbedS = dyn_cast<EmbedExpr>(Init->IgnoreParenImpCasts()))
15188 NumEltsToInit += EmbedS->getDataElementCount() - 1;
15189 }
15190 // If we have extra elements in the list, they will be discarded.
15191 if (NumEltsToInit > NumElts)
15192 NumEltsToInit = NumElts;
15193 // If we're overwriting memory which already has an object, make sure we
15194 // don't reduce the number of non-filler elements. (It's possible to
15195 // optimize this in some cases, but the logic gets really complicated.)
15196 if (Result.hasValue() && NumEltsToInit < Result.getArrayInitializedElts())
15197 NumEltsToInit = Result.getArrayInitializedElts();
15198 }
15199
15200 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
15201 << NumEltsToInit << ".\n");
15202
15203 if (!Result.hasValue()) {
15204 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
15205 } else if (Result.getArrayInitializedElts() != NumEltsToInit) {
15206 // Number of inititalized elts changed. Recreate the APValue, and copy over
15207 // the relevant elements. (This is essentially just fixing the internal
15208 // representation of the value, because it's tied to the number of
15209 // non-filler elements.)
15210 //
15211 // This should be hit rarely, but there are some edge cases:
15212 //
15213 // - The array could be zero-initialized.
15214 // - There could be a DesignatedInitListExpr.
15215 // - operator new[] can be used to start the lifetime early.
15216 APValue NewResult = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
15217 // First copy existing elements.
15218 unsigned NumOldElts = Result.getArrayInitializedElts();
15219 for (unsigned I = 0; I < NumOldElts; ++I) {
15220 NewResult.getArrayInitializedElt(I) =
15221 std::move(Result.getArrayInitializedElt(I));
15222 }
15223 // Then copy the array filler over the remaining elements.
15224 for (unsigned I = Result.getArrayInitializedElts(); I < NumEltsToInit; ++I)
15226 if (NewResult.hasArrayFiller() && Result.hasArrayFiller())
15227 NewResult.getArrayFiller() = Result.getArrayFiller();
15228 Result = std::move(NewResult);
15229 }
15230
15231 LValue Subobject = This;
15232 Subobject.addArray(Info, ExprToVisit, CAT);
15233 auto Eval = [&](const Expr *Init, unsigned ArrayIndex) {
15234 if (Init->isValueDependent())
15235 return EvaluateDependentExpr(Init, Info);
15236
15237 // If this is a child of a DesignatedInitUpdateExpr, skip elements which
15238 // aren't supposed to be modified.
15239 if (isa<NoInitExpr>(Init))
15240 return true;
15241
15242 if (!EvaluateInPlace(Result.getArrayInitializedElt(ArrayIndex), Info,
15243 Subobject, Init) ||
15244 !HandleLValueArrayAdjustment(Info, Init, Subobject,
15245 CAT->getElementType(), 1)) {
15246 if (!Info.noteFailure())
15247 return false;
15248 Success = false;
15249 }
15250 return true;
15251 };
15252 unsigned ArrayIndex = 0;
15253 QualType DestTy = CAT->getElementType();
15254 APSInt Value(Info.Ctx.getTypeSize(DestTy), DestTy->isUnsignedIntegerType());
15255 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
15256 const Expr *Init = Index < Args.size() ? Args[Index] : ArrayFiller;
15257 if (ArrayIndex >= NumEltsToInit)
15258 break;
15259 if (auto *EmbedS = dyn_cast<EmbedExpr>(Init->IgnoreParenImpCasts())) {
15260 StringLiteral *SL = EmbedS->getDataStringLiteral();
15261 for (unsigned I = EmbedS->getStartingElementPos(),
15262 N = EmbedS->getDataElementCount();
15263 I != EmbedS->getStartingElementPos() + N; ++I) {
15264 Value = SL->getCodeUnit(I);
15265 if (DestTy->isIntegerType()) {
15266 Result.getArrayInitializedElt(ArrayIndex) = APValue(Value);
15267 } else {
15268 assert(DestTy->isFloatingType() && "unexpected type");
15269 const FPOptions FPO =
15270 Init->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
15271 APFloat FValue(0.0);
15272 if (!HandleIntToFloatCast(Info, Init, FPO, EmbedS->getType(), Value,
15273 DestTy, FValue))
15274 return false;
15275 Result.getArrayInitializedElt(ArrayIndex) = APValue(FValue);
15276 }
15277 ArrayIndex++;
15278 }
15279 } else {
15280 if (!Eval(Init, ArrayIndex))
15281 return false;
15282 ++ArrayIndex;
15283 }
15284 }
15285
15286 if (!Result.hasArrayFiller())
15287 return Success;
15288
15289 // If we get here, we have a trivial filler, which we can just evaluate
15290 // once and splat over the rest of the array elements.
15291 assert(ArrayFiller && "no array filler for incomplete init list");
15292 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
15293 ArrayFiller) &&
15294 Success;
15295}
15296
15297bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
15298 LValue CommonLV;
15299 if (E->getCommonExpr() &&
15300 !Evaluate(Info.CurrentCall->createTemporary(
15301 E->getCommonExpr(),
15302 getStorageType(Info.Ctx, E->getCommonExpr()),
15303 ScopeKind::FullExpression, CommonLV),
15304 Info, E->getCommonExpr()->getSourceExpr()))
15305 return false;
15306
15308
15309 uint64_t Elements = CAT->getZExtSize();
15310 Result = APValue(APValue::UninitArray(), Elements, Elements);
15311
15312 LValue Subobject = This;
15313 Subobject.addArray(Info, E, CAT);
15314
15315 bool Success = true;
15316 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
15317 // C++ [class.temporary]/5
15318 // There are four contexts in which temporaries are destroyed at a different
15319 // point than the end of the full-expression. [...] The second context is
15320 // when a copy constructor is called to copy an element of an array while
15321 // the entire array is copied [...]. In either case, if the constructor has
15322 // one or more default arguments, the destruction of every temporary created
15323 // in a default argument is sequenced before the construction of the next
15324 // array element, if any.
15325 FullExpressionRAII Scope(Info);
15326
15327 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
15328 Info, Subobject, E->getSubExpr()) ||
15329 !HandleLValueArrayAdjustment(Info, E, Subobject,
15330 CAT->getElementType(), 1)) {
15331 if (!Info.noteFailure())
15332 return false;
15333 Success = false;
15334 }
15335
15336 // Make sure we run the destructors too.
15337 Scope.destroy();
15338 }
15339
15340 return Success;
15341}
15342
15343bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
15344 return VisitCXXConstructExpr(E, This, &Result, E->getType());
15345}
15346
15347bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
15348 const LValue &Subobject,
15349 APValue *Value,
15350 QualType Type) {
15351 bool HadZeroInit = Value->hasValue();
15352
15353 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
15354 unsigned FinalSize = CAT->getZExtSize();
15355
15356 // Preserve the array filler if we had prior zero-initialization.
15357 APValue Filler =
15358 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
15359 : APValue();
15360
15361 *Value = APValue(APValue::UninitArray(), 0, FinalSize);
15362 if (FinalSize == 0)
15363 return true;
15364
15365 bool HasTrivialConstructor = CheckTrivialDefaultConstructor(
15366 Info, E->getExprLoc(), E->getConstructor(),
15368 LValue ArrayElt = Subobject;
15369 ArrayElt.addArray(Info, E, CAT);
15370 // We do the whole initialization in two passes, first for just one element,
15371 // then for the whole array. It's possible we may find out we can't do const
15372 // init in the first pass, in which case we avoid allocating a potentially
15373 // large array. We don't do more passes because expanding array requires
15374 // copying the data, which is wasteful.
15375 for (const unsigned N : {1u, FinalSize}) {
15376 unsigned OldElts = Value->getArrayInitializedElts();
15377 if (OldElts == N)
15378 break;
15379
15380 // Expand the array to appropriate size.
15381 APValue NewValue(APValue::UninitArray(), N, FinalSize);
15382 for (unsigned I = 0; I < OldElts; ++I)
15383 NewValue.getArrayInitializedElt(I).swap(
15384 Value->getArrayInitializedElt(I));
15385 Value->swap(NewValue);
15386
15387 if (HadZeroInit)
15388 for (unsigned I = OldElts; I < N; ++I)
15389 Value->getArrayInitializedElt(I) = Filler;
15390
15391 if (HasTrivialConstructor && N == FinalSize && FinalSize != 1) {
15392 // If we have a trivial constructor, only evaluate it once and copy
15393 // the result into all the array elements.
15394 APValue &FirstResult = Value->getArrayInitializedElt(0);
15395 for (unsigned I = OldElts; I < FinalSize; ++I)
15396 Value->getArrayInitializedElt(I) = FirstResult;
15397 } else {
15398 for (unsigned I = OldElts; I < N; ++I) {
15399 if (!VisitCXXConstructExpr(E, ArrayElt,
15400 &Value->getArrayInitializedElt(I),
15401 CAT->getElementType()) ||
15402 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
15403 CAT->getElementType(), 1))
15404 return false;
15405 // When checking for const initilization any diagnostic is considered
15406 // an error.
15407 if (Info.EvalStatus.Diag && !Info.EvalStatus.Diag->empty() &&
15408 !Info.keepEvaluatingAfterFailure())
15409 return false;
15410 }
15411 }
15412 }
15413
15414 return true;
15415 }
15416
15417 if (!Type->isRecordType())
15418 return Error(E);
15419
15420 return RecordExprEvaluator(Info, Subobject, *Value)
15421 .VisitCXXConstructExpr(E, Type);
15422}
15423
15424bool ArrayExprEvaluator::VisitCXXParenListInitExpr(
15425 const CXXParenListInitExpr *E) {
15426 assert(E->getType()->isConstantArrayType() &&
15427 "Expression result is not a constant array type");
15428
15429 return VisitCXXParenListOrInitListExpr(E, E->getInitExprs(),
15430 E->getArrayFiller());
15431}
15432
15433bool ArrayExprEvaluator::VisitDesignatedInitUpdateExpr(
15434 const DesignatedInitUpdateExpr *E) {
15435 if (!Visit(E->getBase()))
15436 return false;
15437 return Visit(E->getUpdater());
15438}
15439
15440//===----------------------------------------------------------------------===//
15441// Integer Evaluation
15442//
15443// As a GNU extension, we support casting pointers to sufficiently-wide integer
15444// types and back in constant folding. Integer values are thus represented
15445// either as an integer-valued APValue, or as an lvalue-valued APValue.
15446//===----------------------------------------------------------------------===//
15447
15448namespace {
15449class IntExprEvaluator
15450 : public ExprEvaluatorBase<IntExprEvaluator> {
15451 APValue &Result;
15452public:
15453 IntExprEvaluator(EvalInfo &info, APValue &result)
15454 : ExprEvaluatorBaseTy(info), Result(result) {}
15455
15456 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
15457 assert(E->getType()->isIntegralOrEnumerationType() &&
15458 "Invalid evaluation result.");
15459 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
15460 "Invalid evaluation result.");
15461 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
15462 "Invalid evaluation result.");
15463 Result = APValue(SI);
15464 return true;
15465 }
15466 bool Success(const llvm::APSInt &SI, const Expr *E) {
15467 return Success(SI, E, Result);
15468 }
15469
15470 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
15471 assert(E->getType()->isIntegralOrEnumerationType() &&
15472 "Invalid evaluation result.");
15473 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
15474 "Invalid evaluation result.");
15475 Result = APValue(APSInt(I));
15476 Result.getInt().setIsUnsigned(
15478 return true;
15479 }
15480 bool Success(const llvm::APInt &I, const Expr *E) {
15481 return Success(I, E, Result);
15482 }
15483
15484 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
15485 assert(E->getType()->isIntegralOrEnumerationType() &&
15486 "Invalid evaluation result.");
15487 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
15488 return true;
15489 }
15490 bool Success(uint64_t Value, const Expr *E) {
15491 return Success(Value, E, Result);
15492 }
15493
15494 bool Success(CharUnits Size, const Expr *E) {
15495 return Success(Size.getQuantity(), E);
15496 }
15497
15498 bool Success(const APValue &V, const Expr *E) {
15499 // C++23 [expr.const]p8 If we have a variable that is unknown reference or
15500 // pointer allow further evaluation of the value.
15501 if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate() ||
15502 V.allowConstexprUnknown()) {
15503 Result = V;
15504 return true;
15505 }
15506 return Success(V.getInt(), E);
15507 }
15508
15509 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
15510
15511 friend std::optional<bool> EvaluateBuiltinIsWithinLifetime(IntExprEvaluator &,
15512 const CallExpr *);
15513
15514 //===--------------------------------------------------------------------===//
15515 // Visitor Methods
15516 //===--------------------------------------------------------------------===//
15517
15518 bool VisitIntegerLiteral(const IntegerLiteral *E) {
15519 return Success(E->getValue(), E);
15520 }
15521 bool VisitCharacterLiteral(const CharacterLiteral *E) {
15522 return Success(E->getValue(), E);
15523 }
15524
15525 bool CheckReferencedDecl(const Expr *E, const Decl *D);
15526 bool VisitDeclRefExpr(const DeclRefExpr *E) {
15527 if (CheckReferencedDecl(E, E->getDecl()))
15528 return true;
15529
15530 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
15531 }
15532 bool VisitMemberExpr(const MemberExpr *E) {
15533 if (CheckReferencedDecl(E, E->getMemberDecl())) {
15534 VisitIgnoredBaseExpression(E->getBase());
15535 return true;
15536 }
15537
15538 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
15539 }
15540
15541 bool VisitCallExpr(const CallExpr *E);
15542 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
15543 bool VisitBinaryOperator(const BinaryOperator *E);
15544 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
15545 bool VisitUnaryOperator(const UnaryOperator *E);
15546
15547 bool VisitCastExpr(const CastExpr* E);
15548 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
15549
15550 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
15551 return Success(E->getValue(), E);
15552 }
15553
15554 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
15555 return Success(E->getValue(), E);
15556 }
15557
15558 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
15559 if (Info.ArrayInitIndex == uint64_t(-1)) {
15560 // We were asked to evaluate this subexpression independent of the
15561 // enclosing ArrayInitLoopExpr. We can't do that.
15562 Info.FFDiag(E);
15563 return false;
15564 }
15565 return Success(Info.ArrayInitIndex, E);
15566 }
15567
15568 // Note, GNU defines __null as an integer, not a pointer.
15569 bool VisitGNUNullExpr(const GNUNullExpr *E) {
15570 return ZeroInitialization(E);
15571 }
15572
15573 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
15574 if (E->isStoredAsBoolean())
15575 return Success(E->getBoolValue(), E);
15576 if (E->getAPValue().isAbsent())
15577 return false;
15578 assert(E->getAPValue().isInt() && "APValue type not supported");
15579 return Success(E->getAPValue().getInt(), E);
15580 }
15581
15582 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
15583 return Success(E->getValue(), E);
15584 }
15585
15586 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
15587 return Success(E->getValue(), E);
15588 }
15589
15590 bool VisitOpenACCAsteriskSizeExpr(const OpenACCAsteriskSizeExpr *E) {
15591 // This should not be evaluated during constant expr evaluation, as it
15592 // should always be in an unevaluated context (the args list of a 'gang' or
15593 // 'tile' clause).
15594 return Error(E);
15595 }
15596
15597 bool VisitUnaryReal(const UnaryOperator *E);
15598 bool VisitUnaryImag(const UnaryOperator *E);
15599
15600 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
15601 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
15602 bool VisitSourceLocExpr(const SourceLocExpr *E);
15603 bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E);
15604 bool VisitRequiresExpr(const RequiresExpr *E);
15605 // FIXME: Missing: array subscript of vector, member of vector
15606};
15607
15608class FixedPointExprEvaluator
15609 : public ExprEvaluatorBase<FixedPointExprEvaluator> {
15610 APValue &Result;
15611
15612 public:
15613 FixedPointExprEvaluator(EvalInfo &info, APValue &result)
15614 : ExprEvaluatorBaseTy(info), Result(result) {}
15615
15616 bool Success(const llvm::APInt &I, const Expr *E) {
15617 return Success(
15618 APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
15619 }
15620
15621 bool Success(uint64_t Value, const Expr *E) {
15622 return Success(
15623 APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
15624 }
15625
15626 bool Success(const APValue &V, const Expr *E) {
15627 return Success(V.getFixedPoint(), E);
15628 }
15629
15630 bool Success(const APFixedPoint &V, const Expr *E) {
15631 assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
15632 assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
15633 "Invalid evaluation result.");
15634 Result = APValue(V);
15635 return true;
15636 }
15637
15638 bool ZeroInitialization(const Expr *E) {
15639 return Success(0, E);
15640 }
15641
15642 //===--------------------------------------------------------------------===//
15643 // Visitor Methods
15644 //===--------------------------------------------------------------------===//
15645
15646 bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
15647 return Success(E->getValue(), E);
15648 }
15649
15650 bool VisitCastExpr(const CastExpr *E);
15651 bool VisitUnaryOperator(const UnaryOperator *E);
15652 bool VisitBinaryOperator(const BinaryOperator *E);
15653};
15654} // end anonymous namespace
15655
15656/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
15657/// produce either the integer value or a pointer.
15658///
15659/// GCC has a heinous extension which folds casts between pointer types and
15660/// pointer-sized integral types. We support this by allowing the evaluation of
15661/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
15662/// Some simple arithmetic on such values is supported (they are treated much
15663/// like char*).
15665 EvalInfo &Info) {
15666 assert(!E->isValueDependent());
15667 assert(E->isPRValue() && E->getType()->isIntegralOrEnumerationType());
15668 return IntExprEvaluator(Info, Result).Visit(E);
15669}
15670
15671static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
15672 assert(!E->isValueDependent());
15673 APValue Val;
15674 if (!EvaluateIntegerOrLValue(E, Val, Info))
15675 return false;
15676 if (!Val.isInt()) {
15677 // FIXME: It would be better to produce the diagnostic for casting
15678 // a pointer to an integer.
15679 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
15680 return false;
15681 }
15682 Result = Val.getInt();
15683 return true;
15684}
15685
15686bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
15688 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
15689 return Success(Evaluated, E);
15690}
15691
15692static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
15693 EvalInfo &Info) {
15694 assert(!E->isValueDependent());
15695 if (E->getType()->isFixedPointType()) {
15696 APValue Val;
15697 if (!FixedPointExprEvaluator(Info, Val).Visit(E))
15698 return false;
15699 if (!Val.isFixedPoint())
15700 return false;
15701
15702 Result = Val.getFixedPoint();
15703 return true;
15704 }
15705 return false;
15706}
15707
15708static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
15709 EvalInfo &Info) {
15710 assert(!E->isValueDependent());
15711 if (E->getType()->isIntegerType()) {
15712 auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
15713 APSInt Val;
15714 if (!EvaluateInteger(E, Val, Info))
15715 return false;
15716 Result = APFixedPoint(Val, FXSema);
15717 return true;
15718 } else if (E->getType()->isFixedPointType()) {
15719 return EvaluateFixedPoint(E, Result, Info);
15720 }
15721 return false;
15722}
15723
15724/// Check whether the given declaration can be directly converted to an integral
15725/// rvalue. If not, no diagnostic is produced; there are other things we can
15726/// try.
15727bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
15728 // Enums are integer constant exprs.
15729 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
15730 // Check for signedness/width mismatches between E type and ECD value.
15731 bool SameSign = (ECD->getInitVal().isSigned()
15733 bool SameWidth = (ECD->getInitVal().getBitWidth()
15734 == Info.Ctx.getIntWidth(E->getType()));
15735 if (SameSign && SameWidth)
15736 return Success(ECD->getInitVal(), E);
15737 else {
15738 // Get rid of mismatch (otherwise Success assertions will fail)
15739 // by computing a new value matching the type of E.
15740 llvm::APSInt Val = ECD->getInitVal();
15741 if (!SameSign)
15742 Val.setIsSigned(!ECD->getInitVal().isSigned());
15743 if (!SameWidth)
15744 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
15745 return Success(Val, E);
15746 }
15747 }
15748 return false;
15749}
15750
15751/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
15752/// as GCC.
15754 const LangOptions &LangOpts) {
15755 assert(!T->isDependentType() && "unexpected dependent type");
15756
15757 QualType CanTy = T.getCanonicalType();
15758
15759 switch (CanTy->getTypeClass()) {
15760#define TYPE(ID, BASE)
15761#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
15762#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
15763#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
15764#include "clang/AST/TypeNodes.inc"
15765 case Type::Auto:
15766 case Type::DeducedTemplateSpecialization:
15767 llvm_unreachable("unexpected non-canonical or dependent type");
15768
15769 case Type::Builtin:
15770 switch (cast<BuiltinType>(CanTy)->getKind()) {
15771#define BUILTIN_TYPE(ID, SINGLETON_ID)
15772#define SIGNED_TYPE(ID, SINGLETON_ID) \
15773 case BuiltinType::ID: return GCCTypeClass::Integer;
15774#define FLOATING_TYPE(ID, SINGLETON_ID) \
15775 case BuiltinType::ID: return GCCTypeClass::RealFloat;
15776#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
15777 case BuiltinType::ID: break;
15778#include "clang/AST/BuiltinTypes.def"
15779 case BuiltinType::Void:
15780 return GCCTypeClass::Void;
15781
15782 case BuiltinType::Bool:
15783 return GCCTypeClass::Bool;
15784
15785 case BuiltinType::Char_U:
15786 case BuiltinType::UChar:
15787 case BuiltinType::WChar_U:
15788 case BuiltinType::Char8:
15789 case BuiltinType::Char16:
15790 case BuiltinType::Char32:
15791 case BuiltinType::UShort:
15792 case BuiltinType::UInt:
15793 case BuiltinType::ULong:
15794 case BuiltinType::ULongLong:
15795 case BuiltinType::UInt128:
15796 return GCCTypeClass::Integer;
15797
15798 case BuiltinType::UShortAccum:
15799 case BuiltinType::UAccum:
15800 case BuiltinType::ULongAccum:
15801 case BuiltinType::UShortFract:
15802 case BuiltinType::UFract:
15803 case BuiltinType::ULongFract:
15804 case BuiltinType::SatUShortAccum:
15805 case BuiltinType::SatUAccum:
15806 case BuiltinType::SatULongAccum:
15807 case BuiltinType::SatUShortFract:
15808 case BuiltinType::SatUFract:
15809 case BuiltinType::SatULongFract:
15810 return GCCTypeClass::None;
15811
15812 case BuiltinType::NullPtr:
15813
15814 case BuiltinType::ObjCId:
15815 case BuiltinType::ObjCClass:
15816 case BuiltinType::ObjCSel:
15817#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
15818 case BuiltinType::Id:
15819#include "clang/Basic/OpenCLImageTypes.def"
15820#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
15821 case BuiltinType::Id:
15822#include "clang/Basic/OpenCLExtensionTypes.def"
15823 case BuiltinType::OCLSampler:
15824 case BuiltinType::OCLEvent:
15825 case BuiltinType::OCLClkEvent:
15826 case BuiltinType::OCLQueue:
15827 case BuiltinType::OCLReserveID:
15828#define SVE_TYPE(Name, Id, SingletonId) \
15829 case BuiltinType::Id:
15830#include "clang/Basic/AArch64ACLETypes.def"
15831#define PPC_VECTOR_TYPE(Name, Id, Size) \
15832 case BuiltinType::Id:
15833#include "clang/Basic/PPCTypes.def"
15834#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
15835#include "clang/Basic/RISCVVTypes.def"
15836#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
15837#include "clang/Basic/WebAssemblyReferenceTypes.def"
15838#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
15839#include "clang/Basic/AMDGPUTypes.def"
15840#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
15841#include "clang/Basic/HLSLIntangibleTypes.def"
15842 return GCCTypeClass::None;
15843
15844 case BuiltinType::Dependent:
15845 llvm_unreachable("unexpected dependent type");
15846 };
15847 llvm_unreachable("unexpected placeholder type");
15848
15849 case Type::Enum:
15850 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
15851
15852 case Type::Pointer:
15853 case Type::ConstantArray:
15854 case Type::VariableArray:
15855 case Type::IncompleteArray:
15856 case Type::FunctionNoProto:
15857 case Type::FunctionProto:
15858 case Type::ArrayParameter:
15859 return GCCTypeClass::Pointer;
15860
15861 case Type::MemberPointer:
15862 return CanTy->isMemberDataPointerType()
15865
15866 case Type::Complex:
15867 return GCCTypeClass::Complex;
15868
15869 case Type::Record:
15870 return CanTy->isUnionType() ? GCCTypeClass::Union
15872
15873 case Type::Atomic:
15874 // GCC classifies _Atomic T the same as T.
15876 CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
15877
15878 case Type::Vector:
15879 case Type::ExtVector:
15880 return GCCTypeClass::Vector;
15881
15882 case Type::BlockPointer:
15883 case Type::ConstantMatrix:
15884 case Type::ObjCObject:
15885 case Type::ObjCInterface:
15886 case Type::ObjCObjectPointer:
15887 case Type::Pipe:
15888 case Type::HLSLAttributedResource:
15889 case Type::HLSLInlineSpirv:
15890 case Type::OverflowBehavior:
15891 // Classify all other types that don't fit into the regular
15892 // classification the same way.
15893 return GCCTypeClass::None;
15894
15895 case Type::BitInt:
15896 return GCCTypeClass::BitInt;
15897
15898 case Type::LValueReference:
15899 case Type::RValueReference:
15900 llvm_unreachable("invalid type for expression");
15901 }
15902
15903 llvm_unreachable("unexpected type class");
15904}
15905
15906/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
15907/// as GCC.
15908static GCCTypeClass
15910 // If no argument was supplied, default to None. This isn't
15911 // ideal, however it is what gcc does.
15912 if (E->getNumArgs() == 0)
15913 return GCCTypeClass::None;
15914
15915 // FIXME: Bizarrely, GCC treats a call with more than one argument as not
15916 // being an ICE, but still folds it to a constant using the type of the first
15917 // argument.
15918 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
15919}
15920
15921/// EvaluateBuiltinConstantPForLValue - Determine the result of
15922/// __builtin_constant_p when applied to the given pointer.
15923///
15924/// A pointer is only "constant" if it is null (or a pointer cast to integer)
15925/// or it points to the first character of a string literal.
15928 if (Base.isNull()) {
15929 // A null base is acceptable.
15930 return true;
15931 } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
15932 if (!isa<StringLiteral>(E))
15933 return false;
15934 return LV.getLValueOffset().isZero();
15935 } else if (Base.is<TypeInfoLValue>()) {
15936 // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
15937 // evaluate to true.
15938 return true;
15939 } else {
15940 // Any other base is not constant enough for GCC.
15941 return false;
15942 }
15943}
15944
15945/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
15946/// GCC as we can manage.
15947static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
15948 // This evaluation is not permitted to have side-effects, so evaluate it in
15949 // a speculative evaluation context.
15950 SpeculativeEvaluationRAII SpeculativeEval(Info);
15951
15952 // Constant-folding is always enabled for the operand of __builtin_constant_p
15953 // (even when the enclosing evaluation context otherwise requires a strict
15954 // language-specific constant expression).
15955 FoldConstant Fold(Info, true);
15956
15957 QualType ArgType = Arg->getType();
15958
15959 // __builtin_constant_p always has one operand. The rules which gcc follows
15960 // are not precisely documented, but are as follows:
15961 //
15962 // - If the operand is of integral, floating, complex or enumeration type,
15963 // and can be folded to a known value of that type, it returns 1.
15964 // - If the operand can be folded to a pointer to the first character
15965 // of a string literal (or such a pointer cast to an integral type)
15966 // or to a null pointer or an integer cast to a pointer, it returns 1.
15967 //
15968 // Otherwise, it returns 0.
15969 //
15970 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
15971 // its support for this did not work prior to GCC 9 and is not yet well
15972 // understood.
15973 if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
15974 ArgType->isAnyComplexType() || ArgType->isPointerType() ||
15975 ArgType->isNullPtrType()) {
15976 APValue V;
15977 if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) {
15978 Fold.keepDiagnostics();
15979 return false;
15980 }
15981
15982 // For a pointer (possibly cast to integer), there are special rules.
15983 if (V.getKind() == APValue::LValue)
15985
15986 // Otherwise, any constant value is good enough.
15987 return V.hasValue();
15988 }
15989
15990 // Anything else isn't considered to be sufficiently constant.
15991 return false;
15992}
15993
15994/// Retrieves the "underlying object type" of the given expression,
15995/// as used by __builtin_object_size.
15997 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
15998 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
15999 return VD->getType();
16000 } else if (const Expr *E = B.dyn_cast<const Expr*>()) {
16002 return E->getType();
16003 } else if (B.is<TypeInfoLValue>()) {
16004 return B.getTypeInfoType();
16005 } else if (B.is<DynamicAllocLValue>()) {
16006 return B.getDynamicAllocType();
16007 }
16008
16009 return QualType();
16010}
16011
16012/// A more selective version of E->IgnoreParenCasts for
16013/// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
16014/// to change the type of E.
16015/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
16016///
16017/// Always returns an RValue with a pointer representation.
16018static const Expr *ignorePointerCastsAndParens(const Expr *E) {
16019 assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
16020
16021 const Expr *NoParens = E->IgnoreParens();
16022 const auto *Cast = dyn_cast<CastExpr>(NoParens);
16023 if (Cast == nullptr)
16024 return NoParens;
16025
16026 // We only conservatively allow a few kinds of casts, because this code is
16027 // inherently a simple solution that seeks to support the common case.
16028 auto CastKind = Cast->getCastKind();
16029 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
16030 CastKind != CK_AddressSpaceConversion)
16031 return NoParens;
16032
16033 const auto *SubExpr = Cast->getSubExpr();
16034 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isPRValue())
16035 return NoParens;
16036 return ignorePointerCastsAndParens(SubExpr);
16037}
16038
16039/// Checks to see if the given LValue's Designator is at the end of the LValue's
16040/// record layout. e.g.
16041/// struct { struct { int a, b; } fst, snd; } obj;
16042/// obj.fst // no
16043/// obj.snd // yes
16044/// obj.fst.a // no
16045/// obj.fst.b // no
16046/// obj.snd.a // no
16047/// obj.snd.b // yes
16048///
16049/// Please note: this function is specialized for how __builtin_object_size
16050/// views "objects".
16051///
16052/// If this encounters an invalid RecordDecl or otherwise cannot determine the
16053/// correct result, it will always return true.
16054static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
16055 assert(!LVal.Designator.Invalid);
16056
16057 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD) {
16058 const RecordDecl *Parent = FD->getParent();
16059 if (Parent->isInvalidDecl() || Parent->isUnion())
16060 return true;
16061 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
16062 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
16063 };
16064
16065 auto &Base = LVal.getLValueBase();
16066 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
16067 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
16068 if (!IsLastOrInvalidFieldDecl(FD))
16069 return false;
16070 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
16071 for (auto *FD : IFD->chain()) {
16072 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD)))
16073 return false;
16074 }
16075 }
16076 }
16077
16078 unsigned I = 0;
16079 QualType BaseType = getType(Base);
16080 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
16081 // If we don't know the array bound, conservatively assume we're looking at
16082 // the final array element.
16083 ++I;
16084 if (BaseType->isIncompleteArrayType())
16085 BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
16086 else
16087 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
16088 }
16089
16090 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
16091 const auto &Entry = LVal.Designator.Entries[I];
16092 if (BaseType->isArrayType()) {
16093 // Because __builtin_object_size treats arrays as objects, we can ignore
16094 // the index iff this is the last array in the Designator.
16095 if (I + 1 == E)
16096 return true;
16097 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
16098 uint64_t Index = Entry.getAsArrayIndex();
16099 if (Index + 1 != CAT->getZExtSize())
16100 return false;
16101 BaseType = CAT->getElementType();
16102 } else if (BaseType->isAnyComplexType()) {
16103 const auto *CT = BaseType->castAs<ComplexType>();
16104 uint64_t Index = Entry.getAsArrayIndex();
16105 if (Index != 1)
16106 return false;
16107 BaseType = CT->getElementType();
16108 } else if (auto *FD = getAsField(Entry)) {
16109 if (!IsLastOrInvalidFieldDecl(FD))
16110 return false;
16111 BaseType = FD->getType();
16112 } else {
16113 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
16114 return false;
16115 }
16116 }
16117 return true;
16118}
16119
16120/// Tests to see if the LValue has a user-specified designator (that isn't
16121/// necessarily valid). Note that this always returns 'true' if the LValue has
16122/// an unsized array as its first designator entry, because there's currently no
16123/// way to tell if the user typed *foo or foo[0].
16124static bool refersToCompleteObject(const LValue &LVal) {
16125 if (LVal.Designator.Invalid)
16126 return false;
16127
16128 if (!LVal.Designator.Entries.empty())
16129 return LVal.Designator.isMostDerivedAnUnsizedArray();
16130
16131 if (!LVal.InvalidBase)
16132 return true;
16133
16134 // If `E` is a MemberExpr, then the first part of the designator is hiding in
16135 // the LValueBase.
16136 const auto *E = LVal.Base.dyn_cast<const Expr *>();
16137 return !E || !isa<MemberExpr>(E);
16138}
16139
16140/// Attempts to detect a user writing into a piece of memory that's impossible
16141/// to figure out the size of by just using types.
16142static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
16143 const SubobjectDesignator &Designator = LVal.Designator;
16144 // Notes:
16145 // - Users can only write off of the end when we have an invalid base. Invalid
16146 // bases imply we don't know where the memory came from.
16147 // - We used to be a bit more aggressive here; we'd only be conservative if
16148 // the array at the end was flexible, or if it had 0 or 1 elements. This
16149 // broke some common standard library extensions (PR30346), but was
16150 // otherwise seemingly fine. It may be useful to reintroduce this behavior
16151 // with some sort of list. OTOH, it seems that GCC is always
16152 // conservative with the last element in structs (if it's an array), so our
16153 // current behavior is more compatible than an explicit list approach would
16154 // be.
16155 auto isFlexibleArrayMember = [&] {
16157 FAMKind StrictFlexArraysLevel =
16158 Ctx.getLangOpts().getStrictFlexArraysLevel();
16159
16160 if (Designator.isMostDerivedAnUnsizedArray())
16161 return true;
16162
16163 if (StrictFlexArraysLevel == FAMKind::Default)
16164 return true;
16165
16166 if (Designator.getMostDerivedArraySize() == 0 &&
16167 StrictFlexArraysLevel != FAMKind::IncompleteOnly)
16168 return true;
16169
16170 if (Designator.getMostDerivedArraySize() == 1 &&
16171 StrictFlexArraysLevel == FAMKind::OneZeroOrIncomplete)
16172 return true;
16173
16174 return false;
16175 };
16176
16177 return LVal.InvalidBase &&
16178 Designator.Entries.size() == Designator.MostDerivedPathLength &&
16179 Designator.MostDerivedIsArrayElement && isFlexibleArrayMember() &&
16180 isDesignatorAtObjectEnd(Ctx, LVal);
16181}
16182
16183/// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
16184/// Fails if the conversion would cause loss of precision.
16185static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
16186 CharUnits &Result) {
16187 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
16188 if (Int.ugt(CharUnitsMax))
16189 return false;
16190 Result = CharUnits::fromQuantity(Int.getZExtValue());
16191 return true;
16192}
16193
16194/// If we're evaluating the object size of an instance of a struct that
16195/// contains a flexible array member, add the size of the initializer.
16196static void addFlexibleArrayMemberInitSize(EvalInfo &Info, const QualType &T,
16197 const LValue &LV, CharUnits &Size) {
16198 if (!T.isNull() && T->isStructureType() &&
16199 T->castAsRecordDecl()->hasFlexibleArrayMember())
16200 if (const auto *V = LV.getLValueBase().dyn_cast<const ValueDecl *>())
16201 if (const auto *VD = dyn_cast<VarDecl>(V))
16202 if (VD->hasInit())
16203 Size += VD->getFlexibleArrayInitChars(Info.Ctx);
16204}
16205
16206/// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
16207/// determine how many bytes exist from the beginning of the object to either
16208/// the end of the current subobject, or the end of the object itself, depending
16209/// on what the LValue looks like + the value of Type.
16210///
16211/// If this returns false, the value of Result is undefined.
16212static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
16213 unsigned Type, const LValue &LVal,
16214 CharUnits &EndOffset) {
16215 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
16216
16217 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
16218 if (Ty.isNull())
16219 return false;
16220
16221 Ty = Ty.getNonReferenceType();
16222
16223 if (Ty->isIncompleteType() || Ty->isFunctionType())
16224 return false;
16225
16226 return HandleSizeof(Info, ExprLoc, Ty, Result);
16227 };
16228
16229 // We want to evaluate the size of the entire object. This is a valid fallback
16230 // for when Type=1 and the designator is invalid, because we're asked for an
16231 // upper-bound.
16232 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
16233 // Type=3 wants a lower bound, so we can't fall back to this.
16234 if (Type == 3 && !DetermineForCompleteObject)
16235 return false;
16236
16237 llvm::APInt APEndOffset;
16238 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
16239 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
16240 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
16241
16242 if (LVal.InvalidBase)
16243 return false;
16244
16245 QualType BaseTy = getObjectType(LVal.getLValueBase());
16246 const bool Ret = CheckedHandleSizeof(BaseTy, EndOffset);
16247 addFlexibleArrayMemberInitSize(Info, BaseTy, LVal, EndOffset);
16248 return Ret;
16249 }
16250
16251 // We want to evaluate the size of a subobject.
16252 const SubobjectDesignator &Designator = LVal.Designator;
16253
16254 // The following is a moderately common idiom in C:
16255 //
16256 // struct Foo { int a; char c[1]; };
16257 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
16258 // strcpy(&F->c[0], Bar);
16259 //
16260 // In order to not break too much legacy code, we need to support it.
16261 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
16262 // If we can resolve this to an alloc_size call, we can hand that back,
16263 // because we know for certain how many bytes there are to write to.
16264 llvm::APInt APEndOffset;
16265 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
16266 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
16267 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
16268
16269 // If we cannot determine the size of the initial allocation, then we can't
16270 // given an accurate upper-bound. However, we are still able to give
16271 // conservative lower-bounds for Type=3.
16272 if (Type == 1)
16273 return false;
16274 }
16275
16276 CharUnits BytesPerElem;
16277 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
16278 return false;
16279
16280 // According to the GCC documentation, we want the size of the subobject
16281 // denoted by the pointer. But that's not quite right -- what we actually
16282 // want is the size of the immediately-enclosing array, if there is one.
16283 int64_t ElemsRemaining;
16284 if (Designator.MostDerivedIsArrayElement &&
16285 Designator.Entries.size() == Designator.MostDerivedPathLength) {
16286 uint64_t ArraySize = Designator.getMostDerivedArraySize();
16287 uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
16288 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
16289 } else {
16290 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
16291 }
16292
16293 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
16294 return true;
16295}
16296
16297/// Tries to evaluate the __builtin_object_size for @p E. If successful,
16298/// returns true and stores the result in @p Size.
16299///
16300/// If @p WasError is non-null, this will report whether the failure to evaluate
16301/// is to be treated as an Error in IntExprEvaluator.
16302///
16303/// If @p IsDynamic is true (i.e. we're evaluating
16304/// __builtin_dynamic_object_size) and the operand designates a flexible array
16305/// member annotated with 'counted_by', we refuse to fold so that IR generation
16306/// can emit the count-based runtime size computation.
16307static std::optional<uint64_t>
16308tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type, EvalInfo &Info,
16309 bool IsDynamic = false) {
16310 // Determine the denoted object.
16311 LValue LVal;
16312 {
16313 // The operand of __builtin_object_size is never evaluated for side-effects.
16314 // If there are any, but we can determine the pointed-to object anyway, then
16315 // ignore the side-effects.
16316 SpeculativeEvaluationRAII SpeculativeEval(Info);
16317 IgnoreSideEffectsRAII Fold(Info);
16318
16319 if (E->isGLValue()) {
16320 // It's possible for us to be given GLValues if we're called via
16321 // Expr::tryEvaluateObjectSize.
16322 APValue RVal;
16323 if (!EvaluateAsRValue(Info, E, RVal))
16324 return std::nullopt;
16325 LVal.setFrom(Info.Ctx, RVal);
16326 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
16327 /*InvalidBaseOK=*/true))
16328 return std::nullopt;
16329 }
16330
16331 // If we point to before the start of the object, there are no accessible
16332 // bytes.
16333 if (LVal.getLValueOffset().isNegative())
16334 return 0;
16335
16336 // For __builtin_dynamic_object_size on a counted_by-annotated flexible
16337 // array member, defer to IR generation (emitCountedBySize in CGBuiltin):
16338 // its runtime computation uses the live 'count' field and is more accurate
16339 // than the layout/initializer-derived size we'd produce here. Use the same
16340 // findStructFieldAccess form-recognition CGBuiltin does, so we refuse to
16341 // fold on exactly the shapes that path handles (and, importantly, *not*
16342 // on '&af.fam' which designates the array-as-a-whole and stays on the
16343 // layout-derived path to match GCC). Checked after the negative-offset
16344 // early return above so that obviously out-of-bounds operands still fold
16345 // to 0, preserving existing behavior.
16346 if (IsDynamic) {
16347 const auto *ME = dyn_cast_or_null<MemberExpr>(findStructFieldAccess(E));
16348 const auto *FD = ME ? dyn_cast<FieldDecl>(ME->getMemberDecl()) : nullptr;
16349 if (FD && FD->getType()->isCountAttributedType())
16350 return std::nullopt;
16351 }
16352
16353 CharUnits EndOffset;
16354 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
16355 return std::nullopt;
16356
16357 // If we've fallen outside of the end offset, just pretend there's nothing to
16358 // write to/read from.
16359 if (EndOffset <= LVal.getLValueOffset())
16360 return 0;
16361 return (EndOffset - LVal.getLValueOffset()).getQuantity();
16362}
16363
16364bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
16365 if (!IsConstantEvaluatedBuiltinCall(E))
16366 return ExprEvaluatorBaseTy::VisitCallExpr(E);
16367 return VisitBuiltinCallExpr(E, E->getBuiltinCallee());
16368}
16369
16370static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info,
16371 APValue &Val, APSInt &Alignment) {
16372 QualType SrcTy = E->getArg(0)->getType();
16373 if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment))
16374 return false;
16375 // Even though we are evaluating integer expressions we could get a pointer
16376 // argument for the __builtin_is_aligned() case.
16377 if (SrcTy->isPointerType()) {
16378 LValue Ptr;
16379 if (!EvaluatePointer(E->getArg(0), Ptr, Info))
16380 return false;
16381 Ptr.moveInto(Val);
16382 } else if (!SrcTy->isIntegralOrEnumerationType()) {
16383 Info.FFDiag(E->getArg(0));
16384 return false;
16385 } else {
16386 APSInt SrcInt;
16387 if (!EvaluateInteger(E->getArg(0), SrcInt, Info))
16388 return false;
16389 assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() &&
16390 "Bit widths must be the same");
16391 Val = APValue(SrcInt);
16392 }
16393 assert(Val.hasValue());
16394 return true;
16395}
16396
16397bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
16398 unsigned BuiltinOp) {
16399 auto EvalTestOp = [&](llvm::function_ref<bool(const APInt &, const APInt &)>
16400 Fn) {
16401 APValue SourceLHS, SourceRHS;
16402 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
16403 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
16404 return false;
16405
16406 unsigned SourceLen = SourceLHS.getVectorLength();
16407 const VectorType *VT = E->getArg(0)->getType()->castAs<VectorType>();
16408 QualType ElemQT = VT->getElementType();
16409 unsigned LaneWidth = Info.Ctx.getTypeSize(ElemQT);
16410
16411 APInt AWide(LaneWidth * SourceLen, 0);
16412 APInt BWide(LaneWidth * SourceLen, 0);
16413
16414 for (unsigned I = 0; I != SourceLen; ++I) {
16415 APInt ALane;
16416 APInt BLane;
16417 if (ElemQT->isIntegerType()) { // Get value.
16418 ALane = SourceLHS.getVectorElt(I).getInt();
16419 BLane = SourceRHS.getVectorElt(I).getInt();
16420 } else if (ElemQT->isFloatingType()) { // Get only sign bit.
16421 ALane =
16422 SourceLHS.getVectorElt(I).getFloat().bitcastToAPInt().isNegative();
16423 BLane =
16424 SourceRHS.getVectorElt(I).getFloat().bitcastToAPInt().isNegative();
16425 } else { // Must be integer or floating type.
16426 return false;
16427 }
16428 AWide.insertBits(ALane, I * LaneWidth);
16429 BWide.insertBits(BLane, I * LaneWidth);
16430 }
16431 return Success(Fn(AWide, BWide), E);
16432 };
16433
16434 auto HandleMaskBinOp =
16435 [&](llvm::function_ref<APSInt(const APSInt &, const APSInt &)> Fn)
16436 -> bool {
16437 APValue LHS, RHS;
16438 if (!Evaluate(LHS, Info, E->getArg(0)) ||
16439 !Evaluate(RHS, Info, E->getArg(1)))
16440 return false;
16441
16442 APSInt ResultInt = Fn(LHS.getInt(), RHS.getInt());
16443
16444 return Success(APValue(ResultInt), E);
16445 };
16446
16447 auto HandleCRC32 = [&](unsigned DataBytes) -> bool {
16448 APSInt CRC, Data;
16449 if (!EvaluateInteger(E->getArg(0), CRC, Info) ||
16450 !EvaluateInteger(E->getArg(1), Data, Info))
16451 return false;
16452
16453 uint64_t CRCVal = CRC.getZExtValue();
16454 uint64_t DataVal = Data.getZExtValue();
16455
16456 // CRC32C polynomial (iSCSI polynomial, bit-reversed)
16457 static const uint32_t CRC32C_POLY = 0x82F63B78;
16458
16459 // Process each byte
16460 uint32_t Result = static_cast<uint32_t>(CRCVal);
16461 for (unsigned I = 0; I != DataBytes; ++I) {
16462 uint8_t Byte = static_cast<uint8_t>((DataVal >> (I * 8)) & 0xFF);
16463 Result ^= Byte;
16464 for (int J = 0; J != 8; ++J) {
16465 Result = (Result >> 1) ^ ((Result & 1) ? CRC32C_POLY : 0);
16466 }
16467 }
16468
16469 return Success(Result, E);
16470 };
16471
16472 switch (BuiltinOp) {
16473 default:
16474 return false;
16475
16476 case X86::BI__builtin_ia32_crc32qi:
16477 return HandleCRC32(1);
16478 case X86::BI__builtin_ia32_crc32hi:
16479 return HandleCRC32(2);
16480 case X86::BI__builtin_ia32_crc32si:
16481 return HandleCRC32(4);
16482 case X86::BI__builtin_ia32_crc32di:
16483 return HandleCRC32(8);
16484
16485 case Builtin::BI__builtin_dynamic_object_size:
16486 case Builtin::BI__builtin_object_size: {
16487 // The type was checked when we built the expression.
16488 unsigned Type =
16489 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
16490 assert(Type <= 3 && "unexpected type");
16491
16492 bool IsDynamic = BuiltinOp == Builtin::BI__builtin_dynamic_object_size;
16493 if (std::optional<uint64_t> Size =
16494 tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, IsDynamic))
16495 return Success(*Size, E);
16496
16497 if (E->getArg(0)->HasSideEffects(Info.Ctx))
16498 return Success((Type & 2) ? 0 : -1, E);
16499
16500 // Expression had no side effects, but we couldn't statically determine the
16501 // size of the referenced object.
16502 switch (Info.EvalMode) {
16503 case EvaluationMode::ConstantExpression:
16504 case EvaluationMode::ConstantFold:
16505 case EvaluationMode::IgnoreSideEffects:
16506 // Leave it to IR generation.
16507 return Error(E);
16508 case EvaluationMode::ConstantExpressionUnevaluated:
16509 // Reduce it to a constant now.
16510 return Success((Type & 2) ? 0 : -1, E);
16511 }
16512
16513 llvm_unreachable("unexpected EvalMode");
16514 }
16515
16516 case Builtin::BI__builtin_os_log_format_buffer_size: {
16517 analyze_os_log::OSLogBufferLayout Layout;
16518 analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
16519 return Success(Layout.size().getQuantity(), E);
16520 }
16521
16522 case Builtin::BI__builtin_is_aligned: {
16523 APValue Src;
16524 APSInt Alignment;
16525 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
16526 return false;
16527 if (Src.isLValue()) {
16528 // If we evaluated a pointer, check the minimum known alignment.
16529 LValue Ptr;
16530 Ptr.setFrom(Info.Ctx, Src);
16531 CharUnits BaseAlignment = getBaseAlignment(Info, Ptr);
16532 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset);
16533 // We can return true if the known alignment at the computed offset is
16534 // greater than the requested alignment.
16535 assert(PtrAlign.isPowerOfTwo());
16536 assert(Alignment.isPowerOf2());
16537 if (PtrAlign.getQuantity() >= Alignment)
16538 return Success(1, E);
16539 // If the alignment is not known to be sufficient, some cases could still
16540 // be aligned at run time. However, if the requested alignment is less or
16541 // equal to the base alignment and the offset is not aligned, we know that
16542 // the run-time value can never be aligned.
16543 if (BaseAlignment.getQuantity() >= Alignment &&
16544 PtrAlign.getQuantity() < Alignment)
16545 return Success(0, E);
16546 // Otherwise we can't infer whether the value is sufficiently aligned.
16547 // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N)
16548 // in cases where we can't fully evaluate the pointer.
16549 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute)
16550 << Alignment;
16551 return false;
16552 }
16553 assert(Src.isInt());
16554 return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E);
16555 }
16556 case Builtin::BI__builtin_align_up: {
16557 APValue Src;
16558 APSInt Alignment;
16559 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
16560 return false;
16561 if (!Src.isInt())
16562 return Error(E);
16563 APSInt AlignedVal =
16564 APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1),
16565 Src.getInt().isUnsigned());
16566 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
16567 return Success(AlignedVal, E);
16568 }
16569 case Builtin::BI__builtin_align_down: {
16570 APValue Src;
16571 APSInt Alignment;
16572 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
16573 return false;
16574 if (!Src.isInt())
16575 return Error(E);
16576 APSInt AlignedVal =
16577 APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned());
16578 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
16579 return Success(AlignedVal, E);
16580 }
16581
16582 case Builtin::BI__builtin_bitreverseg:
16583 case Builtin::BI__builtin_bitreverse8:
16584 case Builtin::BI__builtin_bitreverse16:
16585 case Builtin::BI__builtin_bitreverse32:
16586 case Builtin::BI__builtin_bitreverse64:
16587 case Builtin::BI__builtin_elementwise_bitreverse: {
16588 APSInt Val;
16589 if (!EvaluateInteger(E->getArg(0), Val, Info))
16590 return false;
16591
16592 return Success(Val.reverseBits(), E);
16593 }
16594 case Builtin::BI__builtin_bswapg:
16595 case Builtin::BI__builtin_bswap16:
16596 case Builtin::BI__builtin_bswap32:
16597 case Builtin::BI__builtin_bswap64:
16598 case Builtin::BIstdc_memreverse8u8:
16599 case Builtin::BIstdc_memreverse8u16:
16600 case Builtin::BIstdc_memreverse8u32:
16601 case Builtin::BIstdc_memreverse8u64: {
16602 APSInt Val;
16603 if (!EvaluateInteger(E->getArg(0), Val, Info))
16604 return false;
16605 if (Val.getBitWidth() == 8 || Val.getBitWidth() == 1)
16606 return Success(Val, E);
16607
16608 return Success(Val.byteSwap(), E);
16609 }
16610
16611 case Builtin::BI__builtin_classify_type:
16612 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
16613
16614 case Builtin::BI__builtin_clrsb:
16615 case Builtin::BI__builtin_clrsbl:
16616 case Builtin::BI__builtin_clrsbll: {
16617 APSInt Val;
16618 if (!EvaluateInteger(E->getArg(0), Val, Info))
16619 return false;
16620
16621 return Success(Val.getBitWidth() - Val.getSignificantBits(), E);
16622 }
16623
16624 case Builtin::BI__builtin_clz:
16625 case Builtin::BI__builtin_clzl:
16626 case Builtin::BI__builtin_clzll:
16627 case Builtin::BI__builtin_clzs:
16628 case Builtin::BI__builtin_clzg:
16629 case Builtin::BI__builtin_elementwise_clzg:
16630 case Builtin::BI__lzcnt16: // Microsoft variants of count leading-zeroes
16631 case Builtin::BI__lzcnt:
16632 case Builtin::BI__lzcnt64: {
16633 APSInt Val;
16634 if (E->getArg(0)->getType()->isExtVectorBoolType()) {
16635 APValue Vec;
16636 if (!EvaluateVector(E->getArg(0), Vec, Info))
16637 return false;
16638 Val = ConvertBoolVectorToInt(Vec);
16639 } else if (!EvaluateInteger(E->getArg(0), Val, Info)) {
16640 return false;
16641 }
16642
16643 std::optional<APSInt> Fallback;
16644 if ((BuiltinOp == Builtin::BI__builtin_clzg ||
16645 BuiltinOp == Builtin::BI__builtin_elementwise_clzg) &&
16646 E->getNumArgs() > 1) {
16647 APSInt FallbackTemp;
16648 if (!EvaluateInteger(E->getArg(1), FallbackTemp, Info))
16649 return false;
16650 Fallback = FallbackTemp;
16651 }
16652
16653 if (!Val) {
16654 if (Fallback)
16655 return Success(*Fallback, E);
16656
16657 // When the argument is 0, the result of GCC builtins is undefined,
16658 // whereas for Microsoft intrinsics, the result is the bit-width of the
16659 // argument.
16660 bool ZeroIsUndefined = BuiltinOp != Builtin::BI__lzcnt16 &&
16661 BuiltinOp != Builtin::BI__lzcnt &&
16662 BuiltinOp != Builtin::BI__lzcnt64;
16663
16664 if (BuiltinOp == Builtin::BI__builtin_elementwise_clzg) {
16665 Info.FFDiag(E, diag::note_constexpr_countzeroes_zero)
16666 << /*IsTrailing=*/false;
16667 }
16668
16669 if (ZeroIsUndefined)
16670 return Error(E);
16671 }
16672
16673 return Success(Val.countl_zero(), E);
16674 }
16675
16676 case Builtin::BI__builtin_constant_p: {
16677 const Expr *Arg = E->getArg(0);
16678 if (EvaluateBuiltinConstantP(Info, Arg))
16679 return Success(true, E);
16680 if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
16681 // Outside a constant context, eagerly evaluate to false in the presence
16682 // of side-effects in order to avoid -Wunsequenced false-positives in
16683 // a branch on __builtin_constant_p(expr).
16684 return Success(false, E);
16685 }
16686 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
16687 return false;
16688 }
16689
16690 case Builtin::BI__noop:
16691 // __noop always evaluates successfully and returns 0.
16692 return Success(0, E);
16693
16694 case Builtin::BI__builtin_is_constant_evaluated: {
16695 const auto *Callee = Info.CurrentCall->getCallee();
16696 if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression &&
16697 (Info.CallStackDepth == 1 ||
16698 (Info.CallStackDepth == 2 && Callee->isInStdNamespace() &&
16699 Callee->getIdentifier() &&
16700 Callee->getIdentifier()->isStr("is_constant_evaluated")))) {
16701 // FIXME: Find a better way to avoid duplicated diagnostics.
16702 if (Info.EvalStatus.Diag)
16703 Info.report((Info.CallStackDepth == 1)
16704 ? E->getExprLoc()
16705 : Info.CurrentCall->getCallRange().getBegin(),
16706 diag::warn_is_constant_evaluated_always_true_constexpr)
16707 << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated"
16708 : "std::is_constant_evaluated");
16709 }
16710
16711 return Success(Info.InConstantContext, E);
16712 }
16713
16714 case Builtin::BI__builtin_is_within_lifetime:
16715 if (auto result = EvaluateBuiltinIsWithinLifetime(*this, E))
16716 return Success(*result, E);
16717 return false;
16718
16719 case Builtin::BI__builtin_ctz:
16720 case Builtin::BI__builtin_ctzl:
16721 case Builtin::BI__builtin_ctzll:
16722 case Builtin::BI__builtin_ctzs:
16723 case Builtin::BI__builtin_ctzg:
16724 case Builtin::BI__builtin_elementwise_ctzg: {
16725 APSInt Val;
16726 if (E->getArg(0)->getType()->isExtVectorBoolType()) {
16727 APValue Vec;
16728 if (!EvaluateVector(E->getArg(0), Vec, Info))
16729 return false;
16730 Val = ConvertBoolVectorToInt(Vec);
16731 } else if (!EvaluateInteger(E->getArg(0), Val, Info)) {
16732 return false;
16733 }
16734
16735 std::optional<APSInt> Fallback;
16736 if ((BuiltinOp == Builtin::BI__builtin_ctzg ||
16737 BuiltinOp == Builtin::BI__builtin_elementwise_ctzg) &&
16738 E->getNumArgs() > 1) {
16739 APSInt FallbackTemp;
16740 if (!EvaluateInteger(E->getArg(1), FallbackTemp, Info))
16741 return false;
16742 Fallback = FallbackTemp;
16743 }
16744
16745 if (!Val) {
16746 if (Fallback)
16747 return Success(*Fallback, E);
16748
16749 if (BuiltinOp == Builtin::BI__builtin_elementwise_ctzg) {
16750 Info.FFDiag(E, diag::note_constexpr_countzeroes_zero)
16751 << /*IsTrailing=*/true;
16752 }
16753 return Error(E);
16754 }
16755
16756 return Success(Val.countr_zero(), E);
16757 }
16758
16759 case Builtin::BI__builtin_eh_return_data_regno: {
16760 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
16761 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
16762 return Success(Operand, E);
16763 }
16764
16765 case Builtin::BI__builtin_elementwise_abs: {
16766 APSInt Val;
16767 if (!EvaluateInteger(E->getArg(0), Val, Info))
16768 return false;
16769
16770 return Success(Val.abs(), E);
16771 }
16772
16773 case Builtin::BI__builtin_expect:
16774 case Builtin::BI__builtin_expect_with_probability:
16775 return Visit(E->getArg(0));
16776
16777 case Builtin::BI__builtin_ptrauth_string_discriminator: {
16778 const auto *Literal =
16780 uint64_t Result = getPointerAuthStableSipHash(Literal->getString());
16781 return Success(Result, E);
16782 }
16783
16784 case Builtin::BI__builtin_infer_alloc_token: {
16785 // If we fail to infer a type, this fails to be a constant expression; this
16786 // can be checked with __builtin_constant_p(...).
16787 QualType AllocType = infer_alloc::inferPossibleType(E, Info.Ctx, nullptr);
16788 if (AllocType.isNull())
16789 return Error(
16790 E, diag::note_constexpr_infer_alloc_token_type_inference_failed);
16791 auto ATMD = infer_alloc::getAllocTokenMetadata(AllocType, Info.Ctx);
16792 if (!ATMD)
16793 return Error(E, diag::note_constexpr_infer_alloc_token_no_metadata);
16794 auto Mode =
16795 Info.getLangOpts().AllocTokenMode.value_or(llvm::DefaultAllocTokenMode);
16796 uint64_t BitWidth = Info.Ctx.getTypeSize(Info.Ctx.getSizeType());
16797 auto MaxTokensOpt = Info.getLangOpts().AllocTokenMax;
16798 uint64_t MaxTokens =
16799 MaxTokensOpt.value_or(0) ? *MaxTokensOpt : (~0ULL >> (64 - BitWidth));
16800 auto MaybeToken = llvm::getAllocToken(Mode, *ATMD, MaxTokens);
16801 if (!MaybeToken)
16802 return Error(E, diag::note_constexpr_infer_alloc_token_stateful_mode);
16803 return Success(llvm::APInt(BitWidth, *MaybeToken), E);
16804 }
16805
16806 case Builtin::BI__builtin_ffs:
16807 case Builtin::BI__builtin_ffsl:
16808 case Builtin::BI__builtin_ffsll: {
16809 APSInt Val;
16810 if (!EvaluateInteger(E->getArg(0), Val, Info))
16811 return false;
16812
16813 unsigned N = Val.countr_zero();
16814 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
16815 }
16816
16817 case Builtin::BI__builtin_fpclassify: {
16818 APFloat Val(0.0);
16819 if (!EvaluateFloat(E->getArg(5), Val, Info))
16820 return false;
16821 unsigned Arg;
16822 switch (Val.getCategory()) {
16823 case APFloat::fcNaN: Arg = 0; break;
16824 case APFloat::fcInfinity: Arg = 1; break;
16825 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
16826 case APFloat::fcZero: Arg = 4; break;
16827 }
16828 return Visit(E->getArg(Arg));
16829 }
16830
16831 case Builtin::BI__builtin_isinf_sign: {
16832 APFloat Val(0.0);
16833 return EvaluateFloat(E->getArg(0), Val, Info) &&
16834 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
16835 }
16836
16837 case Builtin::BI__builtin_isinf: {
16838 APFloat Val(0.0);
16839 return EvaluateFloat(E->getArg(0), Val, Info) &&
16840 Success(Val.isInfinity() ? 1 : 0, E);
16841 }
16842
16843 case Builtin::BI__builtin_isfinite: {
16844 APFloat Val(0.0);
16845 return EvaluateFloat(E->getArg(0), Val, Info) &&
16846 Success(Val.isFinite() ? 1 : 0, E);
16847 }
16848
16849 case Builtin::BI__builtin_isnan: {
16850 APFloat Val(0.0);
16851 return EvaluateFloat(E->getArg(0), Val, Info) &&
16852 Success(Val.isNaN() ? 1 : 0, E);
16853 }
16854
16855 case Builtin::BI__builtin_isnormal: {
16856 APFloat Val(0.0);
16857 return EvaluateFloat(E->getArg(0), Val, Info) &&
16858 Success(Val.isNormal() ? 1 : 0, E);
16859 }
16860
16861 case Builtin::BI__builtin_issubnormal: {
16862 APFloat Val(0.0);
16863 return EvaluateFloat(E->getArg(0), Val, Info) &&
16864 Success(Val.isDenormal() ? 1 : 0, E);
16865 }
16866
16867 case Builtin::BI__builtin_iszero: {
16868 APFloat Val(0.0);
16869 return EvaluateFloat(E->getArg(0), Val, Info) &&
16870 Success(Val.isZero() ? 1 : 0, E);
16871 }
16872
16873 case Builtin::BI__builtin_signbit:
16874 case Builtin::BI__builtin_signbitf:
16875 case Builtin::BI__builtin_signbitl: {
16876 APFloat Val(0.0);
16877 return EvaluateFloat(E->getArg(0), Val, Info) &&
16878 Success(Val.isNegative() ? 1 : 0, E);
16879 }
16880
16881 case Builtin::BI__builtin_isgreater:
16882 case Builtin::BI__builtin_isgreaterequal:
16883 case Builtin::BI__builtin_isless:
16884 case Builtin::BI__builtin_islessequal:
16885 case Builtin::BI__builtin_islessgreater:
16886 case Builtin::BI__builtin_isunordered: {
16887 APFloat LHS(0.0);
16888 APFloat RHS(0.0);
16889 if (!EvaluateFloat(E->getArg(0), LHS, Info) ||
16890 !EvaluateFloat(E->getArg(1), RHS, Info))
16891 return false;
16892
16893 return Success(
16894 [&] {
16895 switch (BuiltinOp) {
16896 case Builtin::BI__builtin_isgreater:
16897 return LHS > RHS;
16898 case Builtin::BI__builtin_isgreaterequal:
16899 return LHS >= RHS;
16900 case Builtin::BI__builtin_isless:
16901 return LHS < RHS;
16902 case Builtin::BI__builtin_islessequal:
16903 return LHS <= RHS;
16904 case Builtin::BI__builtin_islessgreater: {
16905 APFloat::cmpResult cmp = LHS.compare(RHS);
16906 return cmp == APFloat::cmpResult::cmpLessThan ||
16907 cmp == APFloat::cmpResult::cmpGreaterThan;
16908 }
16909 case Builtin::BI__builtin_isunordered:
16910 return LHS.compare(RHS) == APFloat::cmpResult::cmpUnordered;
16911 default:
16912 llvm_unreachable("Unexpected builtin ID: Should be a floating "
16913 "point comparison function");
16914 }
16915 }()
16916 ? 1
16917 : 0,
16918 E);
16919 }
16920
16921 case Builtin::BI__builtin_issignaling: {
16922 APFloat Val(0.0);
16923 return EvaluateFloat(E->getArg(0), Val, Info) &&
16924 Success(Val.isSignaling() ? 1 : 0, E);
16925 }
16926
16927 case Builtin::BI__builtin_isfpclass: {
16928 APSInt MaskVal;
16929 if (!EvaluateInteger(E->getArg(1), MaskVal, Info))
16930 return false;
16931 unsigned Test = static_cast<llvm::FPClassTest>(MaskVal.getZExtValue());
16932 APFloat Val(0.0);
16933 return EvaluateFloat(E->getArg(0), Val, Info) &&
16934 Success((Val.classify() & Test) ? 1 : 0, E);
16935 }
16936
16937 case Builtin::BI__builtin_parity:
16938 case Builtin::BI__builtin_parityl:
16939 case Builtin::BI__builtin_parityll: {
16940 APSInt Val;
16941 if (!EvaluateInteger(E->getArg(0), Val, Info))
16942 return false;
16943
16944 return Success(Val.popcount() % 2, E);
16945 }
16946
16947 case Builtin::BI__builtin_abs:
16948 case Builtin::BI__builtin_labs:
16949 case Builtin::BI__builtin_llabs: {
16950 APSInt Val;
16951 if (!EvaluateInteger(E->getArg(0), Val, Info))
16952 return false;
16953 if (Val == APSInt(APInt::getSignedMinValue(Val.getBitWidth()),
16954 /*IsUnsigned=*/false))
16955 return false;
16956 if (Val.isNegative())
16957 Val.negate();
16958 return Success(Val, E);
16959 }
16960
16961 case Builtin::BI__builtin_popcount:
16962 case Builtin::BI__builtin_popcountl:
16963 case Builtin::BI__builtin_popcountll:
16964 case Builtin::BI__builtin_popcountg:
16965 case Builtin::BI__builtin_elementwise_popcount:
16966 case Builtin::BI__popcnt16: // Microsoft variants of popcount
16967 case Builtin::BI__popcnt:
16968 case Builtin::BI__popcnt64: {
16969 APSInt Val;
16970 if (E->getArg(0)->getType()->isExtVectorBoolType()) {
16971 APValue Vec;
16972 if (!EvaluateVector(E->getArg(0), Vec, Info))
16973 return false;
16974 Val = ConvertBoolVectorToInt(Vec);
16975 } else if (!EvaluateInteger(E->getArg(0), Val, Info)) {
16976 return false;
16977 }
16978
16979 return Success(Val.popcount(), E);
16980 }
16981
16982 case Builtin::BI__builtin_rotateleft8:
16983 case Builtin::BI__builtin_rotateleft16:
16984 case Builtin::BI__builtin_rotateleft32:
16985 case Builtin::BI__builtin_rotateleft64:
16986 case Builtin::BI__builtin_rotateright8:
16987 case Builtin::BI__builtin_rotateright16:
16988 case Builtin::BI__builtin_rotateright32:
16989 case Builtin::BI__builtin_rotateright64:
16990 case Builtin::BI__builtin_stdc_rotate_left:
16991 case Builtin::BI__builtin_stdc_rotate_right:
16992 case Builtin::BIstdc_rotate_left_uc:
16993 case Builtin::BIstdc_rotate_left_us:
16994 case Builtin::BIstdc_rotate_left_ui:
16995 case Builtin::BIstdc_rotate_left_ul:
16996 case Builtin::BIstdc_rotate_left_ull:
16997 case Builtin::BIstdc_rotate_right_uc:
16998 case Builtin::BIstdc_rotate_right_us:
16999 case Builtin::BIstdc_rotate_right_ui:
17000 case Builtin::BIstdc_rotate_right_ul:
17001 case Builtin::BIstdc_rotate_right_ull:
17002 case Builtin::BI_rotl8: // Microsoft variants of rotate left
17003 case Builtin::BI_rotl16:
17004 case Builtin::BI_rotl:
17005 case Builtin::BI_lrotl:
17006 case Builtin::BI_rotl64:
17007 case Builtin::BI_rotr8: // Microsoft variants of rotate right
17008 case Builtin::BI_rotr16:
17009 case Builtin::BI_rotr:
17010 case Builtin::BI_lrotr:
17011 case Builtin::BI_rotr64: {
17012 APSInt Value, Amount;
17013 if (!EvaluateInteger(E->getArg(0), Value, Info) ||
17014 !EvaluateInteger(E->getArg(1), Amount, Info))
17015 return false;
17016
17017 Amount = NormalizeRotateAmount(Value, Amount);
17018
17019 switch (BuiltinOp) {
17020 case Builtin::BI__builtin_rotateright8:
17021 case Builtin::BI__builtin_rotateright16:
17022 case Builtin::BI__builtin_rotateright32:
17023 case Builtin::BI__builtin_rotateright64:
17024 case Builtin::BI__builtin_stdc_rotate_right:
17025 case Builtin::BIstdc_rotate_right_uc:
17026 case Builtin::BIstdc_rotate_right_us:
17027 case Builtin::BIstdc_rotate_right_ui:
17028 case Builtin::BIstdc_rotate_right_ul:
17029 case Builtin::BIstdc_rotate_right_ull:
17030 case Builtin::BI_rotr8:
17031 case Builtin::BI_rotr16:
17032 case Builtin::BI_rotr:
17033 case Builtin::BI_lrotr:
17034 case Builtin::BI_rotr64:
17035 return Success(
17036 APSInt(Value.rotr(Amount.getZExtValue()), Value.isUnsigned()), E);
17037 default:
17038 return Success(
17039 APSInt(Value.rotl(Amount.getZExtValue()), Value.isUnsigned()), E);
17040 }
17041 }
17042
17043 case Builtin::BIstdc_leading_zeros_uc:
17044 case Builtin::BIstdc_leading_zeros_us:
17045 case Builtin::BIstdc_leading_zeros_ui:
17046 case Builtin::BIstdc_leading_zeros_ul:
17047 case Builtin::BIstdc_leading_zeros_ull:
17048 case Builtin::BIstdc_leading_ones_uc:
17049 case Builtin::BIstdc_leading_ones_us:
17050 case Builtin::BIstdc_leading_ones_ui:
17051 case Builtin::BIstdc_leading_ones_ul:
17052 case Builtin::BIstdc_leading_ones_ull:
17053 case Builtin::BIstdc_trailing_zeros_uc:
17054 case Builtin::BIstdc_trailing_zeros_us:
17055 case Builtin::BIstdc_trailing_zeros_ui:
17056 case Builtin::BIstdc_trailing_zeros_ul:
17057 case Builtin::BIstdc_trailing_zeros_ull:
17058 case Builtin::BIstdc_trailing_ones_uc:
17059 case Builtin::BIstdc_trailing_ones_us:
17060 case Builtin::BIstdc_trailing_ones_ui:
17061 case Builtin::BIstdc_trailing_ones_ul:
17062 case Builtin::BIstdc_trailing_ones_ull:
17063 case Builtin::BIstdc_first_leading_zero_uc:
17064 case Builtin::BIstdc_first_leading_zero_us:
17065 case Builtin::BIstdc_first_leading_zero_ui:
17066 case Builtin::BIstdc_first_leading_zero_ul:
17067 case Builtin::BIstdc_first_leading_zero_ull:
17068 case Builtin::BIstdc_first_leading_one_uc:
17069 case Builtin::BIstdc_first_leading_one_us:
17070 case Builtin::BIstdc_first_leading_one_ui:
17071 case Builtin::BIstdc_first_leading_one_ul:
17072 case Builtin::BIstdc_first_leading_one_ull:
17073 case Builtin::BIstdc_first_trailing_zero_uc:
17074 case Builtin::BIstdc_first_trailing_zero_us:
17075 case Builtin::BIstdc_first_trailing_zero_ui:
17076 case Builtin::BIstdc_first_trailing_zero_ul:
17077 case Builtin::BIstdc_first_trailing_zero_ull:
17078 case Builtin::BIstdc_first_trailing_one_uc:
17079 case Builtin::BIstdc_first_trailing_one_us:
17080 case Builtin::BIstdc_first_trailing_one_ui:
17081 case Builtin::BIstdc_first_trailing_one_ul:
17082 case Builtin::BIstdc_first_trailing_one_ull:
17083 case Builtin::BIstdc_count_zeros_uc:
17084 case Builtin::BIstdc_count_zeros_us:
17085 case Builtin::BIstdc_count_zeros_ui:
17086 case Builtin::BIstdc_count_zeros_ul:
17087 case Builtin::BIstdc_count_zeros_ull:
17088 case Builtin::BIstdc_count_ones_uc:
17089 case Builtin::BIstdc_count_ones_us:
17090 case Builtin::BIstdc_count_ones_ui:
17091 case Builtin::BIstdc_count_ones_ul:
17092 case Builtin::BIstdc_count_ones_ull:
17093 case Builtin::BIstdc_has_single_bit_uc:
17094 case Builtin::BIstdc_has_single_bit_us:
17095 case Builtin::BIstdc_has_single_bit_ui:
17096 case Builtin::BIstdc_has_single_bit_ul:
17097 case Builtin::BIstdc_has_single_bit_ull:
17098 case Builtin::BIstdc_bit_width_uc:
17099 case Builtin::BIstdc_bit_width_us:
17100 case Builtin::BIstdc_bit_width_ui:
17101 case Builtin::BIstdc_bit_width_ul:
17102 case Builtin::BIstdc_bit_width_ull:
17103 case Builtin::BIstdc_bit_floor_uc:
17104 case Builtin::BIstdc_bit_floor_us:
17105 case Builtin::BIstdc_bit_floor_ui:
17106 case Builtin::BIstdc_bit_floor_ul:
17107 case Builtin::BIstdc_bit_floor_ull:
17108 case Builtin::BIstdc_bit_ceil_uc:
17109 case Builtin::BIstdc_bit_ceil_us:
17110 case Builtin::BIstdc_bit_ceil_ui:
17111 case Builtin::BIstdc_bit_ceil_ul:
17112 case Builtin::BIstdc_bit_ceil_ull:
17113 case Builtin::BI__builtin_stdc_leading_zeros:
17114 case Builtin::BI__builtin_stdc_leading_ones:
17115 case Builtin::BI__builtin_stdc_trailing_zeros:
17116 case Builtin::BI__builtin_stdc_trailing_ones:
17117 case Builtin::BI__builtin_stdc_first_leading_zero:
17118 case Builtin::BI__builtin_stdc_first_leading_one:
17119 case Builtin::BI__builtin_stdc_first_trailing_zero:
17120 case Builtin::BI__builtin_stdc_first_trailing_one:
17121 case Builtin::BI__builtin_stdc_count_zeros:
17122 case Builtin::BI__builtin_stdc_count_ones:
17123 case Builtin::BI__builtin_stdc_has_single_bit:
17124 case Builtin::BI__builtin_stdc_bit_width:
17125 case Builtin::BI__builtin_stdc_bit_floor:
17126 case Builtin::BI__builtin_stdc_bit_ceil: {
17127 APSInt Val;
17128 if (!EvaluateInteger(E->getArg(0), Val, Info))
17129 return false;
17130
17131 unsigned BitWidth = Val.getBitWidth();
17132 const unsigned ResBitWidth = Info.Ctx.getIntWidth(E->getType());
17133
17134 switch (BuiltinOp) {
17135 case Builtin::BIstdc_leading_zeros_uc:
17136 case Builtin::BIstdc_leading_zeros_us:
17137 case Builtin::BIstdc_leading_zeros_ui:
17138 case Builtin::BIstdc_leading_zeros_ul:
17139 case Builtin::BIstdc_leading_zeros_ull:
17140 case Builtin::BI__builtin_stdc_leading_zeros:
17141 return Success(APInt(ResBitWidth, Val.countl_zero()), E);
17142 case Builtin::BIstdc_leading_ones_uc:
17143 case Builtin::BIstdc_leading_ones_us:
17144 case Builtin::BIstdc_leading_ones_ui:
17145 case Builtin::BIstdc_leading_ones_ul:
17146 case Builtin::BIstdc_leading_ones_ull:
17147 case Builtin::BI__builtin_stdc_leading_ones:
17148 return Success(APInt(ResBitWidth, Val.countl_one()), E);
17149 case Builtin::BIstdc_trailing_zeros_uc:
17150 case Builtin::BIstdc_trailing_zeros_us:
17151 case Builtin::BIstdc_trailing_zeros_ui:
17152 case Builtin::BIstdc_trailing_zeros_ul:
17153 case Builtin::BIstdc_trailing_zeros_ull:
17154 case Builtin::BI__builtin_stdc_trailing_zeros:
17155 return Success(APInt(ResBitWidth, Val.countr_zero()), E);
17156 case Builtin::BIstdc_trailing_ones_uc:
17157 case Builtin::BIstdc_trailing_ones_us:
17158 case Builtin::BIstdc_trailing_ones_ui:
17159 case Builtin::BIstdc_trailing_ones_ul:
17160 case Builtin::BIstdc_trailing_ones_ull:
17161 case Builtin::BI__builtin_stdc_trailing_ones:
17162 return Success(APInt(ResBitWidth, Val.countr_one()), E);
17163 case Builtin::BIstdc_first_leading_zero_uc:
17164 case Builtin::BIstdc_first_leading_zero_us:
17165 case Builtin::BIstdc_first_leading_zero_ui:
17166 case Builtin::BIstdc_first_leading_zero_ul:
17167 case Builtin::BIstdc_first_leading_zero_ull:
17168 case Builtin::BI__builtin_stdc_first_leading_zero:
17169 return Success(
17170 APInt(ResBitWidth, Val.isAllOnes() ? 0 : Val.countl_one() + 1), E);
17171 case Builtin::BIstdc_first_leading_one_uc:
17172 case Builtin::BIstdc_first_leading_one_us:
17173 case Builtin::BIstdc_first_leading_one_ui:
17174 case Builtin::BIstdc_first_leading_one_ul:
17175 case Builtin::BIstdc_first_leading_one_ull:
17176 case Builtin::BI__builtin_stdc_first_leading_one:
17177 return Success(
17178 APInt(ResBitWidth, Val.isZero() ? 0 : Val.countl_zero() + 1), E);
17179 case Builtin::BIstdc_first_trailing_zero_uc:
17180 case Builtin::BIstdc_first_trailing_zero_us:
17181 case Builtin::BIstdc_first_trailing_zero_ui:
17182 case Builtin::BIstdc_first_trailing_zero_ul:
17183 case Builtin::BIstdc_first_trailing_zero_ull:
17184 case Builtin::BI__builtin_stdc_first_trailing_zero:
17185 return Success(
17186 APInt(ResBitWidth, Val.isAllOnes() ? 0 : Val.countr_one() + 1), E);
17187 case Builtin::BIstdc_first_trailing_one_uc:
17188 case Builtin::BIstdc_first_trailing_one_us:
17189 case Builtin::BIstdc_first_trailing_one_ui:
17190 case Builtin::BIstdc_first_trailing_one_ul:
17191 case Builtin::BIstdc_first_trailing_one_ull:
17192 case Builtin::BI__builtin_stdc_first_trailing_one:
17193 return Success(
17194 APInt(ResBitWidth, Val.isZero() ? 0 : Val.countr_zero() + 1), E);
17195 case Builtin::BIstdc_count_zeros_uc:
17196 case Builtin::BIstdc_count_zeros_us:
17197 case Builtin::BIstdc_count_zeros_ui:
17198 case Builtin::BIstdc_count_zeros_ul:
17199 case Builtin::BIstdc_count_zeros_ull:
17200 case Builtin::BI__builtin_stdc_count_zeros: {
17201 APInt Cnt(ResBitWidth, BitWidth - Val.popcount());
17202 return Success(APSInt(Cnt, /*IsUnsigned*/ true), E);
17203 }
17204 case Builtin::BIstdc_count_ones_uc:
17205 case Builtin::BIstdc_count_ones_us:
17206 case Builtin::BIstdc_count_ones_ui:
17207 case Builtin::BIstdc_count_ones_ul:
17208 case Builtin::BIstdc_count_ones_ull:
17209 case Builtin::BI__builtin_stdc_count_ones: {
17210 APInt Cnt(ResBitWidth, Val.popcount());
17211 return Success(APSInt(Cnt, /*IsUnsigned*/ true), E);
17212 }
17213 case Builtin::BIstdc_has_single_bit_uc:
17214 case Builtin::BIstdc_has_single_bit_us:
17215 case Builtin::BIstdc_has_single_bit_ui:
17216 case Builtin::BIstdc_has_single_bit_ul:
17217 case Builtin::BIstdc_has_single_bit_ull:
17218 case Builtin::BI__builtin_stdc_has_single_bit: {
17219 APInt Res(ResBitWidth, Val.popcount() == 1 ? 1 : 0);
17220 return Success(APSInt(Res, /*IsUnsigned*/ true), E);
17221 }
17222 case Builtin::BIstdc_bit_width_uc:
17223 case Builtin::BIstdc_bit_width_us:
17224 case Builtin::BIstdc_bit_width_ui:
17225 case Builtin::BIstdc_bit_width_ul:
17226 case Builtin::BIstdc_bit_width_ull:
17227 case Builtin::BI__builtin_stdc_bit_width:
17228 return Success(APInt(ResBitWidth, BitWidth - Val.countl_zero()), E);
17229 case Builtin::BIstdc_bit_floor_uc:
17230 case Builtin::BIstdc_bit_floor_us:
17231 case Builtin::BIstdc_bit_floor_ui:
17232 case Builtin::BIstdc_bit_floor_ul:
17233 case Builtin::BIstdc_bit_floor_ull:
17234 case Builtin::BI__builtin_stdc_bit_floor: {
17235 if (Val.isZero())
17236 return Success(APInt(BitWidth, 0), E);
17237 unsigned Exp = BitWidth - Val.countl_zero() - 1;
17238 return Success(
17239 APSInt(APInt::getOneBitSet(BitWidth, Exp), /*IsUnsigned*/ true), E);
17240 }
17241 case Builtin::BIstdc_bit_ceil_uc:
17242 case Builtin::BIstdc_bit_ceil_us:
17243 case Builtin::BIstdc_bit_ceil_ui:
17244 case Builtin::BIstdc_bit_ceil_ul:
17245 case Builtin::BIstdc_bit_ceil_ull:
17246 case Builtin::BI__builtin_stdc_bit_ceil: {
17247 if (Val.ule(1))
17248 return Success(APSInt(APInt(BitWidth, 1), /*IsUnsigned*/ true), E);
17249 APInt ValMinusOne = Val - 1;
17250 unsigned LZ = ValMinusOne.countl_zero();
17251 if (LZ == 0)
17252 return Success(APSInt(APInt(BitWidth, 0), /*IsUnsigned*/ true),
17253 E); // overflows; wrap to 0
17254 APInt Result = APInt::getOneBitSet(BitWidth, BitWidth - LZ);
17255 return Success(APSInt(Result, /*IsUnsigned*/ true), E);
17256 }
17257 default:
17258 llvm_unreachable("Unknown stdc builtin");
17259 }
17260 }
17261
17262 case Builtin::BI__builtin_elementwise_add_sat: {
17263 APSInt LHS, RHS;
17264 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
17265 !EvaluateInteger(E->getArg(1), RHS, Info))
17266 return false;
17267
17268 APInt Result = LHS.isSigned() ? LHS.sadd_sat(RHS) : LHS.uadd_sat(RHS);
17269 return Success(APSInt(Result, !LHS.isSigned()), E);
17270 }
17271 case Builtin::BI__builtin_elementwise_sub_sat: {
17272 APSInt LHS, RHS;
17273 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
17274 !EvaluateInteger(E->getArg(1), RHS, Info))
17275 return false;
17276
17277 APInt Result = LHS.isSigned() ? LHS.ssub_sat(RHS) : LHS.usub_sat(RHS);
17278 return Success(APSInt(Result, !LHS.isSigned()), E);
17279 }
17280 case Builtin::BI__builtin_elementwise_max: {
17281 APSInt LHS, RHS;
17282 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
17283 !EvaluateInteger(E->getArg(1), RHS, Info))
17284 return false;
17285
17286 APInt Result = std::max(LHS, RHS);
17287 return Success(APSInt(Result, !LHS.isSigned()), E);
17288 }
17289 case Builtin::BI__builtin_elementwise_min: {
17290 APSInt LHS, RHS;
17291 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
17292 !EvaluateInteger(E->getArg(1), RHS, Info))
17293 return false;
17294
17295 APInt Result = std::min(LHS, RHS);
17296 return Success(APSInt(Result, !LHS.isSigned()), E);
17297 }
17298 case Builtin::BI__builtin_elementwise_clmul: {
17299 APSInt LHS, RHS;
17300 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
17301 !EvaluateInteger(E->getArg(1), RHS, Info))
17302 return false;
17303
17304 APInt Result = llvm::APIntOps::clmul(LHS, RHS);
17305 return Success(APSInt(Result, LHS.isUnsigned()), E);
17306 }
17307 case Builtin::BI__builtin_elementwise_fshl:
17308 case Builtin::BI__builtin_elementwise_fshr: {
17309 APSInt Hi, Lo, Shift;
17310 if (!EvaluateInteger(E->getArg(0), Hi, Info) ||
17311 !EvaluateInteger(E->getArg(1), Lo, Info) ||
17312 !EvaluateInteger(E->getArg(2), Shift, Info))
17313 return false;
17314
17315 switch (BuiltinOp) {
17316 case Builtin::BI__builtin_elementwise_fshl: {
17317 APSInt Result(llvm::APIntOps::fshl(Hi, Lo, Shift), Hi.isUnsigned());
17318 return Success(Result, E);
17319 }
17320 case Builtin::BI__builtin_elementwise_fshr: {
17321 APSInt Result(llvm::APIntOps::fshr(Hi, Lo, Shift), Hi.isUnsigned());
17322 return Success(Result, E);
17323 }
17324 }
17325 llvm_unreachable("Fully covered switch above");
17326 }
17327 case Builtin::BIstrlen:
17328 case Builtin::BIwcslen:
17329 // A call to strlen is not a constant expression.
17330 if (Info.getLangOpts().CPlusPlus11)
17331 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
17332 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
17333 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
17334 else
17335 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
17336 [[fallthrough]];
17337 case Builtin::BI__builtin_strlen:
17338 case Builtin::BI__builtin_wcslen: {
17339 // As an extension, we support __builtin_strlen() as a constant expression,
17340 // and support folding strlen() to a constant.
17341 if (std::optional<uint64_t> StrLen =
17342 EvaluateBuiltinStrLen(E->getArg(0), Info))
17343 return Success(*StrLen, E);
17344 return false;
17345 }
17346
17347 case Builtin::BIstrcmp:
17348 case Builtin::BIwcscmp:
17349 case Builtin::BIstrncmp:
17350 case Builtin::BIwcsncmp:
17351 case Builtin::BImemcmp:
17352 case Builtin::BIbcmp:
17353 case Builtin::BIwmemcmp:
17354 // A call to strlen is not a constant expression.
17355 if (Info.getLangOpts().CPlusPlus11)
17356 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
17357 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
17358 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
17359 else
17360 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
17361 [[fallthrough]];
17362 case Builtin::BI__builtin_strcmp:
17363 case Builtin::BI__builtin_wcscmp:
17364 case Builtin::BI__builtin_strncmp:
17365 case Builtin::BI__builtin_wcsncmp:
17366 case Builtin::BI__builtin_memcmp:
17367 case Builtin::BI__builtin_bcmp:
17368 case Builtin::BI__builtin_wmemcmp: {
17369 LValue String1, String2;
17370 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
17371 !EvaluatePointer(E->getArg(1), String2, Info))
17372 return false;
17373
17374 uint64_t MaxLength = uint64_t(-1);
17375 if (BuiltinOp != Builtin::BIstrcmp &&
17376 BuiltinOp != Builtin::BIwcscmp &&
17377 BuiltinOp != Builtin::BI__builtin_strcmp &&
17378 BuiltinOp != Builtin::BI__builtin_wcscmp) {
17379 APSInt N;
17380 if (!EvaluateInteger(E->getArg(2), N, Info))
17381 return false;
17382 MaxLength = N.getZExtValue();
17383 }
17384
17385 // Empty substrings compare equal by definition.
17386 if (MaxLength == 0u)
17387 return Success(0, E);
17388
17389 if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
17390 !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
17391 String1.Designator.Invalid || String2.Designator.Invalid)
17392 return false;
17393
17394 QualType CharTy1 = String1.Designator.getType(Info.Ctx);
17395 QualType CharTy2 = String2.Designator.getType(Info.Ctx);
17396
17397 bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
17398 BuiltinOp == Builtin::BIbcmp ||
17399 BuiltinOp == Builtin::BI__builtin_memcmp ||
17400 BuiltinOp == Builtin::BI__builtin_bcmp;
17401
17402 assert(IsRawByte ||
17403 (Info.Ctx.hasSameUnqualifiedType(
17404 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
17405 Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
17406
17407 // For memcmp, allow comparing any arrays of '[[un]signed] char' or
17408 // 'char8_t', but no other types.
17409 if (IsRawByte &&
17410 !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) {
17411 // FIXME: Consider using our bit_cast implementation to support this.
17412 Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported)
17413 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp) << CharTy1
17414 << CharTy2;
17415 return false;
17416 }
17417
17418 const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
17419 return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
17420 handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
17421 Char1.isInt() && Char2.isInt();
17422 };
17423 const auto &AdvanceElems = [&] {
17424 return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
17425 HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
17426 };
17427
17428 bool StopAtNull =
17429 (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
17430 BuiltinOp != Builtin::BIwmemcmp &&
17431 BuiltinOp != Builtin::BI__builtin_memcmp &&
17432 BuiltinOp != Builtin::BI__builtin_bcmp &&
17433 BuiltinOp != Builtin::BI__builtin_wmemcmp);
17434 bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
17435 BuiltinOp == Builtin::BIwcsncmp ||
17436 BuiltinOp == Builtin::BIwmemcmp ||
17437 BuiltinOp == Builtin::BI__builtin_wcscmp ||
17438 BuiltinOp == Builtin::BI__builtin_wcsncmp ||
17439 BuiltinOp == Builtin::BI__builtin_wmemcmp;
17440
17441 for (; MaxLength; --MaxLength) {
17442 APValue Char1, Char2;
17443 if (!ReadCurElems(Char1, Char2))
17444 return false;
17445 if (Char1.getInt().ne(Char2.getInt())) {
17446 if (IsWide) // wmemcmp compares with wchar_t signedness.
17447 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
17448 // memcmp always compares unsigned chars.
17449 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
17450 }
17451 if (StopAtNull && !Char1.getInt())
17452 return Success(0, E);
17453 assert(!(StopAtNull && !Char2.getInt()));
17454 if (!AdvanceElems())
17455 return false;
17456 }
17457 // We hit the strncmp / memcmp limit.
17458 return Success(0, E);
17459 }
17460
17461 case Builtin::BI__atomic_always_lock_free:
17462 case Builtin::BI__atomic_is_lock_free:
17463 case Builtin::BI__c11_atomic_is_lock_free: {
17464 APSInt SizeVal;
17465 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
17466 return false;
17467
17468 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
17469 // of two less than or equal to the maximum inline atomic width, we know it
17470 // is lock-free. If the size isn't a power of two, or greater than the
17471 // maximum alignment where we promote atomics, we know it is not lock-free
17472 // (at least not in the sense of atomic_is_lock_free). Otherwise,
17473 // the answer can only be determined at runtime; for example, 16-byte
17474 // atomics have lock-free implementations on some, but not all,
17475 // x86-64 processors.
17476
17477 // Check power-of-two.
17478 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
17479 if (Size.isPowerOfTwo()) {
17480 // Check against inlining width.
17481 unsigned InlineWidthBits =
17482 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
17483 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
17484 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
17485 Size == CharUnits::One())
17486 return Success(1, E);
17487
17488 // If the pointer argument can be evaluated to a compile-time constant
17489 // integer (or nullptr), check if that value is appropriately aligned.
17490 const Expr *PtrArg = E->getArg(1);
17491 Expr::EvalResult ExprResult;
17492 APSInt IntResult;
17493 if (PtrArg->EvaluateAsRValue(ExprResult, Info.Ctx) &&
17494 ExprResult.Val.toIntegralConstant(IntResult, PtrArg->getType(),
17495 Info.Ctx) &&
17496 IntResult.isAligned(Size.getAsAlign()))
17497 return Success(1, E);
17498
17499 // Otherwise, check if the type's alignment against Size.
17500 if (auto *ICE = dyn_cast<ImplicitCastExpr>(PtrArg)) {
17501 // Drop the potential implicit-cast to 'const volatile void*', getting
17502 // the underlying type.
17503 if (ICE->getCastKind() == CK_BitCast)
17504 PtrArg = ICE->getSubExpr();
17505 }
17506
17507 if (auto PtrTy = PtrArg->getType()->getAs<PointerType>()) {
17508 QualType PointeeType = PtrTy->getPointeeType();
17509 if (!PointeeType->isIncompleteType() &&
17510 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
17511 // OK, we will inline operations on this object.
17512 return Success(1, E);
17513 }
17514 }
17515 }
17516 }
17517
17518 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
17519 Success(0, E) : Error(E);
17520 }
17521 case Builtin::BI__builtin_addcb:
17522 case Builtin::BI__builtin_addcs:
17523 case Builtin::BI__builtin_addc:
17524 case Builtin::BI__builtin_addcl:
17525 case Builtin::BI__builtin_addcll:
17526 case Builtin::BI__builtin_subcb:
17527 case Builtin::BI__builtin_subcs:
17528 case Builtin::BI__builtin_subc:
17529 case Builtin::BI__builtin_subcl:
17530 case Builtin::BI__builtin_subcll: {
17531 LValue CarryOutLValue;
17532 APSInt LHS, RHS, CarryIn, CarryOut, Result;
17533 QualType ResultType = E->getArg(0)->getType();
17534 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
17535 !EvaluateInteger(E->getArg(1), RHS, Info) ||
17536 !EvaluateInteger(E->getArg(2), CarryIn, Info) ||
17537 !EvaluatePointer(E->getArg(3), CarryOutLValue, Info))
17538 return false;
17539 // Copy the number of bits and sign.
17540 Result = LHS;
17541 CarryOut = LHS;
17542
17543 bool FirstOverflowed = false;
17544 bool SecondOverflowed = false;
17545 switch (BuiltinOp) {
17546 default:
17547 llvm_unreachable("Invalid value for BuiltinOp");
17548 case Builtin::BI__builtin_addcb:
17549 case Builtin::BI__builtin_addcs:
17550 case Builtin::BI__builtin_addc:
17551 case Builtin::BI__builtin_addcl:
17552 case Builtin::BI__builtin_addcll:
17553 Result =
17554 LHS.uadd_ov(RHS, FirstOverflowed).uadd_ov(CarryIn, SecondOverflowed);
17555 break;
17556 case Builtin::BI__builtin_subcb:
17557 case Builtin::BI__builtin_subcs:
17558 case Builtin::BI__builtin_subc:
17559 case Builtin::BI__builtin_subcl:
17560 case Builtin::BI__builtin_subcll:
17561 Result =
17562 LHS.usub_ov(RHS, FirstOverflowed).usub_ov(CarryIn, SecondOverflowed);
17563 break;
17564 }
17565
17566 // It is possible for both overflows to happen but CGBuiltin uses an OR so
17567 // this is consistent.
17568 CarryOut = (uint64_t)(FirstOverflowed | SecondOverflowed);
17569 APValue APV{CarryOut};
17570 if (!handleAssignment(Info, E, CarryOutLValue, ResultType, APV))
17571 return false;
17572 return Success(Result, E);
17573 }
17574 case Builtin::BI__builtin_add_overflow:
17575 case Builtin::BI__builtin_sub_overflow:
17576 case Builtin::BI__builtin_mul_overflow:
17577 case Builtin::BI__builtin_sadd_overflow:
17578 case Builtin::BI__builtin_uadd_overflow:
17579 case Builtin::BI__builtin_uaddl_overflow:
17580 case Builtin::BI__builtin_uaddll_overflow:
17581 case Builtin::BI__builtin_usub_overflow:
17582 case Builtin::BI__builtin_usubl_overflow:
17583 case Builtin::BI__builtin_usubll_overflow:
17584 case Builtin::BI__builtin_umul_overflow:
17585 case Builtin::BI__builtin_umull_overflow:
17586 case Builtin::BI__builtin_umulll_overflow:
17587 case Builtin::BI__builtin_saddl_overflow:
17588 case Builtin::BI__builtin_saddll_overflow:
17589 case Builtin::BI__builtin_ssub_overflow:
17590 case Builtin::BI__builtin_ssubl_overflow:
17591 case Builtin::BI__builtin_ssubll_overflow:
17592 case Builtin::BI__builtin_smul_overflow:
17593 case Builtin::BI__builtin_smull_overflow:
17594 case Builtin::BI__builtin_smulll_overflow: {
17595 LValue ResultLValue;
17596 APSInt LHS, RHS;
17597
17598 QualType ResultType = E->getArg(2)->getType()->getPointeeType();
17599 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
17600 !EvaluateInteger(E->getArg(1), RHS, Info) ||
17601 !EvaluatePointer(E->getArg(2), ResultLValue, Info))
17602 return false;
17603
17604 APSInt Result;
17605 bool DidOverflow = false;
17606
17607 // If the types don't have to match, enlarge all 3 to the largest of them.
17608 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
17609 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
17610 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
17611 bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
17613 bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
17615 uint64_t LHSSize = LHS.getBitWidth();
17616 uint64_t RHSSize = RHS.getBitWidth();
17617 uint64_t ResultSize = Info.Ctx.getIntWidth(ResultType);
17618 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
17619
17620 // Add an additional bit if the signedness isn't uniformly agreed to. We
17621 // could do this ONLY if there is a signed and an unsigned that both have
17622 // MaxBits, but the code to check that is pretty nasty. The issue will be
17623 // caught in the shrink-to-result later anyway.
17624 if (IsSigned && !AllSigned)
17625 ++MaxBits;
17626
17627 LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
17628 RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
17629 Result = APSInt(MaxBits, !IsSigned);
17630 }
17631
17632 // Find largest int.
17633 switch (BuiltinOp) {
17634 default:
17635 llvm_unreachable("Invalid value for BuiltinOp");
17636 case Builtin::BI__builtin_add_overflow:
17637 case Builtin::BI__builtin_sadd_overflow:
17638 case Builtin::BI__builtin_saddl_overflow:
17639 case Builtin::BI__builtin_saddll_overflow:
17640 case Builtin::BI__builtin_uadd_overflow:
17641 case Builtin::BI__builtin_uaddl_overflow:
17642 case Builtin::BI__builtin_uaddll_overflow:
17643 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
17644 : LHS.uadd_ov(RHS, DidOverflow);
17645 break;
17646 case Builtin::BI__builtin_sub_overflow:
17647 case Builtin::BI__builtin_ssub_overflow:
17648 case Builtin::BI__builtin_ssubl_overflow:
17649 case Builtin::BI__builtin_ssubll_overflow:
17650 case Builtin::BI__builtin_usub_overflow:
17651 case Builtin::BI__builtin_usubl_overflow:
17652 case Builtin::BI__builtin_usubll_overflow:
17653 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
17654 : LHS.usub_ov(RHS, DidOverflow);
17655 break;
17656 case Builtin::BI__builtin_mul_overflow:
17657 case Builtin::BI__builtin_smul_overflow:
17658 case Builtin::BI__builtin_smull_overflow:
17659 case Builtin::BI__builtin_smulll_overflow:
17660 case Builtin::BI__builtin_umul_overflow:
17661 case Builtin::BI__builtin_umull_overflow:
17662 case Builtin::BI__builtin_umulll_overflow:
17663 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
17664 : LHS.umul_ov(RHS, DidOverflow);
17665 break;
17666 }
17667
17668 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
17669 // since it will give us the behavior of a TruncOrSelf in the case where
17670 // its parameter <= its size. We previously set Result to be at least the
17671 // integer width of the result, so getIntWidth(ResultType) <=
17672 // Result.BitWidth will work exactly like TruncOrSelf.
17673 APSInt Temp = Result.extOrTrunc(Info.Ctx.getIntWidth(ResultType));
17674 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
17675
17676 // In the case where multiple sizes are allowed, truncate and see if
17677 // the values are the same.
17678 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
17679 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
17680 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
17681 if (!APSInt::isSameValue(Temp, Result))
17682 DidOverflow = true;
17683 }
17684 Result = Temp;
17685
17686 APValue APV{Result};
17687 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
17688 return false;
17689 return Success(DidOverflow, E);
17690 }
17691
17692 case Builtin::BI__builtin_reduce_add:
17693 case Builtin::BI__builtin_reduce_mul:
17694 case Builtin::BI__builtin_reduce_and:
17695 case Builtin::BI__builtin_reduce_or:
17696 case Builtin::BI__builtin_reduce_xor:
17697 case Builtin::BI__builtin_reduce_min:
17698 case Builtin::BI__builtin_reduce_max: {
17699 APValue Source;
17700 if (!EvaluateAsRValue(Info, E->getArg(0), Source))
17701 return false;
17702
17703 unsigned SourceLen = Source.getVectorLength();
17704 APSInt Reduced = Source.getVectorElt(0).getInt();
17705 for (unsigned EltNum = 1; EltNum < SourceLen; ++EltNum) {
17706 switch (BuiltinOp) {
17707 default:
17708 return false;
17709 case Builtin::BI__builtin_reduce_add: {
17711 Info, E, Reduced, Source.getVectorElt(EltNum).getInt(),
17712 Reduced.getBitWidth() + 1, std::plus<APSInt>(), Reduced))
17713 return false;
17714 break;
17715 }
17716 case Builtin::BI__builtin_reduce_mul: {
17718 Info, E, Reduced, Source.getVectorElt(EltNum).getInt(),
17719 Reduced.getBitWidth() * 2, std::multiplies<APSInt>(), Reduced))
17720 return false;
17721 break;
17722 }
17723 case Builtin::BI__builtin_reduce_and: {
17724 Reduced &= Source.getVectorElt(EltNum).getInt();
17725 break;
17726 }
17727 case Builtin::BI__builtin_reduce_or: {
17728 Reduced |= Source.getVectorElt(EltNum).getInt();
17729 break;
17730 }
17731 case Builtin::BI__builtin_reduce_xor: {
17732 Reduced ^= Source.getVectorElt(EltNum).getInt();
17733 break;
17734 }
17735 case Builtin::BI__builtin_reduce_min: {
17736 Reduced = std::min(Reduced, Source.getVectorElt(EltNum).getInt());
17737 break;
17738 }
17739 case Builtin::BI__builtin_reduce_max: {
17740 Reduced = std::max(Reduced, Source.getVectorElt(EltNum).getInt());
17741 break;
17742 }
17743 }
17744 }
17745
17746 return Success(Reduced, E);
17747 }
17748
17749 case clang::X86::BI__builtin_ia32_addcarryx_u32:
17750 case clang::X86::BI__builtin_ia32_addcarryx_u64:
17751 case clang::X86::BI__builtin_ia32_subborrow_u32:
17752 case clang::X86::BI__builtin_ia32_subborrow_u64: {
17753 LValue ResultLValue;
17754 APSInt CarryIn, LHS, RHS;
17755 QualType ResultType = E->getArg(3)->getType()->getPointeeType();
17756 if (!EvaluateInteger(E->getArg(0), CarryIn, Info) ||
17757 !EvaluateInteger(E->getArg(1), LHS, Info) ||
17758 !EvaluateInteger(E->getArg(2), RHS, Info) ||
17759 !EvaluatePointer(E->getArg(3), ResultLValue, Info))
17760 return false;
17761
17762 bool IsAdd = BuiltinOp == clang::X86::BI__builtin_ia32_addcarryx_u32 ||
17763 BuiltinOp == clang::X86::BI__builtin_ia32_addcarryx_u64;
17764
17765 unsigned BitWidth = LHS.getBitWidth();
17766 unsigned CarryInBit = CarryIn.ugt(0) ? 1 : 0;
17767 APInt ExResult =
17768 IsAdd
17769 ? (LHS.zext(BitWidth + 1) + (RHS.zext(BitWidth + 1) + CarryInBit))
17770 : (LHS.zext(BitWidth + 1) - (RHS.zext(BitWidth + 1) + CarryInBit));
17771
17772 APInt Result = ExResult.extractBits(BitWidth, 0);
17773 uint64_t CarryOut = ExResult.extractBitsAsZExtValue(1, BitWidth);
17774
17775 APValue APV{APSInt(Result, /*isUnsigned=*/true)};
17776 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
17777 return false;
17778 return Success(CarryOut, E);
17779 }
17780
17781 case clang::X86::BI__builtin_ia32_movmskps:
17782 case clang::X86::BI__builtin_ia32_movmskpd:
17783 case clang::X86::BI__builtin_ia32_pmovmskb128:
17784 case clang::X86::BI__builtin_ia32_pmovmskb256:
17785 case clang::X86::BI__builtin_ia32_movmskps256:
17786 case clang::X86::BI__builtin_ia32_movmskpd256: {
17787 APValue Source;
17788 if (!Evaluate(Source, Info, E->getArg(0)))
17789 return false;
17790 unsigned SourceLen = Source.getVectorLength();
17791 const VectorType *VT = E->getArg(0)->getType()->castAs<VectorType>();
17792 QualType ElemQT = VT->getElementType();
17793 unsigned ResultLen = Info.Ctx.getTypeSize(
17794 E->getCallReturnType(Info.Ctx)); // Always 32-bit integer.
17795 APInt Result(ResultLen, 0);
17796
17797 for (unsigned I = 0; I != SourceLen; ++I) {
17798 APInt Elem;
17799 if (ElemQT->isIntegerType()) {
17800 Elem = Source.getVectorElt(I).getInt();
17801 } else if (ElemQT->isRealFloatingType()) {
17802 Elem = Source.getVectorElt(I).getFloat().bitcastToAPInt();
17803 } else {
17804 return false;
17805 }
17806 Result.setBitVal(I, Elem.isNegative());
17807 }
17808 return Success(Result, E);
17809 }
17810
17811 case clang::X86::BI__builtin_ia32_bextr_u32:
17812 case clang::X86::BI__builtin_ia32_bextr_u64:
17813 case clang::X86::BI__builtin_ia32_bextri_u32:
17814 case clang::X86::BI__builtin_ia32_bextri_u64: {
17815 APSInt Val, Idx;
17816 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
17817 !EvaluateInteger(E->getArg(1), Idx, Info))
17818 return false;
17819
17820 unsigned BitWidth = Val.getBitWidth();
17821 uint64_t Shift = Idx.extractBitsAsZExtValue(8, 0);
17822 uint64_t Length = Idx.extractBitsAsZExtValue(8, 8);
17823 Length = Length > BitWidth ? BitWidth : Length;
17824
17825 // Handle out of bounds cases.
17826 if (Length == 0 || Shift >= BitWidth)
17827 return Success(0, E);
17828
17829 uint64_t Result = Val.getZExtValue() >> Shift;
17830 Result &= llvm::maskTrailingOnes<uint64_t>(Length);
17831 return Success(Result, E);
17832 }
17833
17834 case clang::X86::BI__builtin_ia32_bzhi_si:
17835 case clang::X86::BI__builtin_ia32_bzhi_di: {
17836 APSInt Val, Idx;
17837 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
17838 !EvaluateInteger(E->getArg(1), Idx, Info))
17839 return false;
17840
17841 unsigned BitWidth = Val.getBitWidth();
17842 unsigned Index = Idx.extractBitsAsZExtValue(8, 0);
17843 if (Index < BitWidth)
17844 Val.clearHighBits(BitWidth - Index);
17845 return Success(Val, E);
17846 }
17847
17848 case clang::X86::BI__builtin_ia32_ktestcqi:
17849 case clang::X86::BI__builtin_ia32_ktestchi:
17850 case clang::X86::BI__builtin_ia32_ktestcsi:
17851 case clang::X86::BI__builtin_ia32_ktestcdi: {
17852 APSInt A, B;
17853 if (!EvaluateInteger(E->getArg(0), A, Info) ||
17854 !EvaluateInteger(E->getArg(1), B, Info))
17855 return false;
17856
17857 return Success((~A & B) == 0, E);
17858 }
17859
17860 case clang::X86::BI__builtin_ia32_ktestzqi:
17861 case clang::X86::BI__builtin_ia32_ktestzhi:
17862 case clang::X86::BI__builtin_ia32_ktestzsi:
17863 case clang::X86::BI__builtin_ia32_ktestzdi: {
17864 APSInt A, B;
17865 if (!EvaluateInteger(E->getArg(0), A, Info) ||
17866 !EvaluateInteger(E->getArg(1), B, Info))
17867 return false;
17868
17869 return Success((A & B) == 0, E);
17870 }
17871
17872 case clang::X86::BI__builtin_ia32_kortestcqi:
17873 case clang::X86::BI__builtin_ia32_kortestchi:
17874 case clang::X86::BI__builtin_ia32_kortestcsi:
17875 case clang::X86::BI__builtin_ia32_kortestcdi: {
17876 APSInt A, B;
17877 if (!EvaluateInteger(E->getArg(0), A, Info) ||
17878 !EvaluateInteger(E->getArg(1), B, Info))
17879 return false;
17880
17881 return Success(~(A | B) == 0, E);
17882 }
17883
17884 case clang::X86::BI__builtin_ia32_kortestzqi:
17885 case clang::X86::BI__builtin_ia32_kortestzhi:
17886 case clang::X86::BI__builtin_ia32_kortestzsi:
17887 case clang::X86::BI__builtin_ia32_kortestzdi: {
17888 APSInt A, B;
17889 if (!EvaluateInteger(E->getArg(0), A, Info) ||
17890 !EvaluateInteger(E->getArg(1), B, Info))
17891 return false;
17892
17893 return Success((A | B) == 0, E);
17894 }
17895
17896 case clang::X86::BI__builtin_ia32_kunpckhi:
17897 case clang::X86::BI__builtin_ia32_kunpckdi:
17898 case clang::X86::BI__builtin_ia32_kunpcksi: {
17899 APSInt A, B;
17900 if (!EvaluateInteger(E->getArg(0), A, Info) ||
17901 !EvaluateInteger(E->getArg(1), B, Info))
17902 return false;
17903
17904 // Generic kunpack: extract lower half of each operand and concatenate
17905 // Result = A[HalfWidth-1:0] concat B[HalfWidth-1:0]
17906 unsigned BW = A.getBitWidth();
17907 APSInt Result(A.trunc(BW / 2).concat(B.trunc(BW / 2)), A.isUnsigned());
17908 return Success(Result, E);
17909 }
17910
17911 case clang::X86::BI__builtin_ia32_lzcnt_u16:
17912 case clang::X86::BI__builtin_ia32_lzcnt_u32:
17913 case clang::X86::BI__builtin_ia32_lzcnt_u64: {
17914 APSInt Val;
17915 if (!EvaluateInteger(E->getArg(0), Val, Info))
17916 return false;
17917 return Success(Val.countLeadingZeros(), E);
17918 }
17919
17920 case clang::X86::BI__builtin_ia32_tzcnt_u16:
17921 case clang::X86::BI__builtin_ia32_tzcnt_u32:
17922 case clang::X86::BI__builtin_ia32_tzcnt_u64: {
17923 APSInt Val;
17924 if (!EvaluateInteger(E->getArg(0), Val, Info))
17925 return false;
17926 return Success(Val.countTrailingZeros(), E);
17927 }
17928
17929 case clang::X86::BI__builtin_ia32_pdep_si:
17930 case clang::X86::BI__builtin_ia32_pdep_di:
17931 case Builtin::BI__builtin_elementwise_pdep: {
17932 APSInt Val, Msk;
17933 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
17934 !EvaluateInteger(E->getArg(1), Msk, Info))
17935 return false;
17936 return Success(llvm::APIntOps::expandBits(Val, Msk), E);
17937 }
17938
17939 case clang::X86::BI__builtin_ia32_pext_si:
17940 case clang::X86::BI__builtin_ia32_pext_di:
17941 case Builtin::BI__builtin_elementwise_pext: {
17942 APSInt Val, Msk;
17943 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
17944 !EvaluateInteger(E->getArg(1), Msk, Info))
17945 return false;
17946 return Success(llvm::APIntOps::compressBits(Val, Msk), E);
17947 }
17948 case X86::BI__builtin_ia32_ptestz128:
17949 case X86::BI__builtin_ia32_ptestz256:
17950 case X86::BI__builtin_ia32_vtestzps:
17951 case X86::BI__builtin_ia32_vtestzps256:
17952 case X86::BI__builtin_ia32_vtestzpd:
17953 case X86::BI__builtin_ia32_vtestzpd256: {
17954 return EvalTestOp(
17955 [](const APInt &A, const APInt &B) { return (A & B) == 0; });
17956 }
17957 case X86::BI__builtin_ia32_ptestc128:
17958 case X86::BI__builtin_ia32_ptestc256:
17959 case X86::BI__builtin_ia32_vtestcps:
17960 case X86::BI__builtin_ia32_vtestcps256:
17961 case X86::BI__builtin_ia32_vtestcpd:
17962 case X86::BI__builtin_ia32_vtestcpd256: {
17963 return EvalTestOp(
17964 [](const APInt &A, const APInt &B) { return (~A & B) == 0; });
17965 }
17966 case X86::BI__builtin_ia32_ptestnzc128:
17967 case X86::BI__builtin_ia32_ptestnzc256:
17968 case X86::BI__builtin_ia32_vtestnzcps:
17969 case X86::BI__builtin_ia32_vtestnzcps256:
17970 case X86::BI__builtin_ia32_vtestnzcpd:
17971 case X86::BI__builtin_ia32_vtestnzcpd256: {
17972 return EvalTestOp([](const APInt &A, const APInt &B) {
17973 return ((A & B) != 0) && ((~A & B) != 0);
17974 });
17975 }
17976 case X86::BI__builtin_ia32_kandqi:
17977 case X86::BI__builtin_ia32_kandhi:
17978 case X86::BI__builtin_ia32_kandsi:
17979 case X86::BI__builtin_ia32_kanddi: {
17980 return HandleMaskBinOp(
17981 [](const APSInt &LHS, const APSInt &RHS) { return LHS & RHS; });
17982 }
17983
17984 case X86::BI__builtin_ia32_kandnqi:
17985 case X86::BI__builtin_ia32_kandnhi:
17986 case X86::BI__builtin_ia32_kandnsi:
17987 case X86::BI__builtin_ia32_kandndi: {
17988 return HandleMaskBinOp(
17989 [](const APSInt &LHS, const APSInt &RHS) { return ~LHS & RHS; });
17990 }
17991
17992 case X86::BI__builtin_ia32_korqi:
17993 case X86::BI__builtin_ia32_korhi:
17994 case X86::BI__builtin_ia32_korsi:
17995 case X86::BI__builtin_ia32_kordi: {
17996 return HandleMaskBinOp(
17997 [](const APSInt &LHS, const APSInt &RHS) { return LHS | RHS; });
17998 }
17999
18000 case X86::BI__builtin_ia32_kxnorqi:
18001 case X86::BI__builtin_ia32_kxnorhi:
18002 case X86::BI__builtin_ia32_kxnorsi:
18003 case X86::BI__builtin_ia32_kxnordi: {
18004 return HandleMaskBinOp(
18005 [](const APSInt &LHS, const APSInt &RHS) { return ~(LHS ^ RHS); });
18006 }
18007
18008 case X86::BI__builtin_ia32_kxorqi:
18009 case X86::BI__builtin_ia32_kxorhi:
18010 case X86::BI__builtin_ia32_kxorsi:
18011 case X86::BI__builtin_ia32_kxordi: {
18012 return HandleMaskBinOp(
18013 [](const APSInt &LHS, const APSInt &RHS) { return LHS ^ RHS; });
18014 }
18015
18016 case X86::BI__builtin_ia32_knotqi:
18017 case X86::BI__builtin_ia32_knothi:
18018 case X86::BI__builtin_ia32_knotsi:
18019 case X86::BI__builtin_ia32_knotdi: {
18020 APSInt Val;
18021 if (!EvaluateInteger(E->getArg(0), Val, Info))
18022 return false;
18023 APSInt Result = ~Val;
18024 return Success(APValue(Result), E);
18025 }
18026
18027 case X86::BI__builtin_ia32_kaddqi:
18028 case X86::BI__builtin_ia32_kaddhi:
18029 case X86::BI__builtin_ia32_kaddsi:
18030 case X86::BI__builtin_ia32_kadddi: {
18031 return HandleMaskBinOp(
18032 [](const APSInt &LHS, const APSInt &RHS) { return LHS + RHS; });
18033 }
18034
18035 case X86::BI__builtin_ia32_kmovb:
18036 case X86::BI__builtin_ia32_kmovw:
18037 case X86::BI__builtin_ia32_kmovd:
18038 case X86::BI__builtin_ia32_kmovq: {
18039 APSInt Val;
18040 if (!EvaluateInteger(E->getArg(0), Val, Info))
18041 return false;
18042 return Success(Val, E);
18043 }
18044
18045 case X86::BI__builtin_ia32_kshiftliqi:
18046 case X86::BI__builtin_ia32_kshiftlihi:
18047 case X86::BI__builtin_ia32_kshiftlisi:
18048 case X86::BI__builtin_ia32_kshiftlidi: {
18049 return HandleMaskBinOp([](const APSInt &LHS, const APSInt &RHS) {
18050 unsigned Amt = RHS.getZExtValue() & 0xFF;
18051 if (Amt >= LHS.getBitWidth())
18052 return APSInt(APInt::getZero(LHS.getBitWidth()), LHS.isUnsigned());
18053 return APSInt(LHS.shl(Amt), LHS.isUnsigned());
18054 });
18055 }
18056
18057 case X86::BI__builtin_ia32_kshiftriqi:
18058 case X86::BI__builtin_ia32_kshiftrihi:
18059 case X86::BI__builtin_ia32_kshiftrisi:
18060 case X86::BI__builtin_ia32_kshiftridi: {
18061 return HandleMaskBinOp([](const APSInt &LHS, const APSInt &RHS) {
18062 unsigned Amt = RHS.getZExtValue() & 0xFF;
18063 if (Amt >= LHS.getBitWidth())
18064 return APSInt(APInt::getZero(LHS.getBitWidth()), LHS.isUnsigned());
18065 return APSInt(LHS.lshr(Amt), LHS.isUnsigned());
18066 });
18067 }
18068
18069 case clang::X86::BI__builtin_ia32_vec_ext_v4hi:
18070 case clang::X86::BI__builtin_ia32_vec_ext_v16qi:
18071 case clang::X86::BI__builtin_ia32_vec_ext_v8hi:
18072 case clang::X86::BI__builtin_ia32_vec_ext_v4si:
18073 case clang::X86::BI__builtin_ia32_vec_ext_v2di:
18074 case clang::X86::BI__builtin_ia32_vec_ext_v32qi:
18075 case clang::X86::BI__builtin_ia32_vec_ext_v16hi:
18076 case clang::X86::BI__builtin_ia32_vec_ext_v8si:
18077 case clang::X86::BI__builtin_ia32_vec_ext_v4di: {
18078 APValue Vec;
18079 APSInt IdxAPS;
18080 if (!EvaluateVector(E->getArg(0), Vec, Info) ||
18081 !EvaluateInteger(E->getArg(1), IdxAPS, Info))
18082 return false;
18083 unsigned N = Vec.getVectorLength();
18084 unsigned Idx = static_cast<unsigned>(IdxAPS.getZExtValue() & (N - 1));
18085 return Success(Vec.getVectorElt(Idx).getInt(), E);
18086 }
18087
18088 case clang::X86::BI__builtin_ia32_cvtb2mask128:
18089 case clang::X86::BI__builtin_ia32_cvtb2mask256:
18090 case clang::X86::BI__builtin_ia32_cvtb2mask512:
18091 case clang::X86::BI__builtin_ia32_cvtw2mask128:
18092 case clang::X86::BI__builtin_ia32_cvtw2mask256:
18093 case clang::X86::BI__builtin_ia32_cvtw2mask512:
18094 case clang::X86::BI__builtin_ia32_cvtd2mask128:
18095 case clang::X86::BI__builtin_ia32_cvtd2mask256:
18096 case clang::X86::BI__builtin_ia32_cvtd2mask512:
18097 case clang::X86::BI__builtin_ia32_cvtq2mask128:
18098 case clang::X86::BI__builtin_ia32_cvtq2mask256:
18099 case clang::X86::BI__builtin_ia32_cvtq2mask512: {
18100 assert(E->getNumArgs() == 1);
18101 APValue Vec;
18102 if (!EvaluateVector(E->getArg(0), Vec, Info))
18103 return false;
18104
18105 unsigned VectorLen = Vec.getVectorLength();
18106 unsigned RetWidth = Info.Ctx.getIntWidth(E->getType());
18107 llvm::APInt Bits(RetWidth, 0);
18108
18109 for (unsigned ElemNum = 0; ElemNum != VectorLen; ++ElemNum) {
18110 const APSInt &A = Vec.getVectorElt(ElemNum).getInt();
18111 unsigned MSB = A[A.getBitWidth() - 1];
18112 Bits.setBitVal(ElemNum, MSB);
18113 }
18114
18115 APSInt RetMask(Bits, /*isUnsigned=*/true);
18116 return Success(APValue(RetMask), E);
18117 }
18118
18119 case clang::X86::BI__builtin_ia32_cmpb128_mask:
18120 case clang::X86::BI__builtin_ia32_cmpw128_mask:
18121 case clang::X86::BI__builtin_ia32_cmpd128_mask:
18122 case clang::X86::BI__builtin_ia32_cmpq128_mask:
18123 case clang::X86::BI__builtin_ia32_cmpb256_mask:
18124 case clang::X86::BI__builtin_ia32_cmpw256_mask:
18125 case clang::X86::BI__builtin_ia32_cmpd256_mask:
18126 case clang::X86::BI__builtin_ia32_cmpq256_mask:
18127 case clang::X86::BI__builtin_ia32_cmpb512_mask:
18128 case clang::X86::BI__builtin_ia32_cmpw512_mask:
18129 case clang::X86::BI__builtin_ia32_cmpd512_mask:
18130 case clang::X86::BI__builtin_ia32_cmpq512_mask:
18131 case clang::X86::BI__builtin_ia32_ucmpb128_mask:
18132 case clang::X86::BI__builtin_ia32_ucmpw128_mask:
18133 case clang::X86::BI__builtin_ia32_ucmpd128_mask:
18134 case clang::X86::BI__builtin_ia32_ucmpq128_mask:
18135 case clang::X86::BI__builtin_ia32_ucmpb256_mask:
18136 case clang::X86::BI__builtin_ia32_ucmpw256_mask:
18137 case clang::X86::BI__builtin_ia32_ucmpd256_mask:
18138 case clang::X86::BI__builtin_ia32_ucmpq256_mask:
18139 case clang::X86::BI__builtin_ia32_ucmpb512_mask:
18140 case clang::X86::BI__builtin_ia32_ucmpw512_mask:
18141 case clang::X86::BI__builtin_ia32_ucmpd512_mask:
18142 case clang::X86::BI__builtin_ia32_ucmpq512_mask: {
18143 assert(E->getNumArgs() == 4);
18144
18145 bool IsUnsigned =
18146 (BuiltinOp >= clang::X86::BI__builtin_ia32_ucmpb128_mask &&
18147 BuiltinOp <= clang::X86::BI__builtin_ia32_ucmpw512_mask);
18148
18149 APValue LHS, RHS;
18150 APSInt Mask, Opcode;
18151 if (!EvaluateVector(E->getArg(0), LHS, Info) ||
18152 !EvaluateVector(E->getArg(1), RHS, Info) ||
18153 !EvaluateInteger(E->getArg(2), Opcode, Info) ||
18154 !EvaluateInteger(E->getArg(3), Mask, Info))
18155 return false;
18156
18157 assert(LHS.getVectorLength() == RHS.getVectorLength());
18158
18159 unsigned VectorLen = LHS.getVectorLength();
18160 unsigned RetWidth = Mask.getBitWidth();
18161
18162 APSInt RetMask(llvm::APInt(RetWidth, 0), /*isUnsigned=*/true);
18163
18164 for (unsigned ElemNum = 0; ElemNum < VectorLen; ++ElemNum) {
18165 const APSInt &A = LHS.getVectorElt(ElemNum).getInt();
18166 const APSInt &B = RHS.getVectorElt(ElemNum).getInt();
18167 bool Result = false;
18168
18169 switch (Opcode.getExtValue() & 0x7) {
18170 case 0: // _MM_CMPINT_EQ
18171 Result = (A == B);
18172 break;
18173 case 1: // _MM_CMPINT_LT
18174 Result = IsUnsigned ? A.ult(B) : A.slt(B);
18175 break;
18176 case 2: // _MM_CMPINT_LE
18177 Result = IsUnsigned ? A.ule(B) : A.sle(B);
18178 break;
18179 case 3: // _MM_CMPINT_FALSE
18180 Result = false;
18181 break;
18182 case 4: // _MM_CMPINT_NE
18183 Result = (A != B);
18184 break;
18185 case 5: // _MM_CMPINT_NLT (>=)
18186 Result = IsUnsigned ? A.uge(B) : A.sge(B);
18187 break;
18188 case 6: // _MM_CMPINT_NLE (>)
18189 Result = IsUnsigned ? A.ugt(B) : A.sgt(B);
18190 break;
18191 case 7: // _MM_CMPINT_TRUE
18192 Result = true;
18193 break;
18194 }
18195
18196 RetMask.setBitVal(ElemNum, Mask[ElemNum] && Result);
18197 }
18198
18199 return Success(APValue(RetMask), E);
18200 }
18201 case X86::BI__builtin_ia32_vpshufbitqmb128_mask:
18202 case X86::BI__builtin_ia32_vpshufbitqmb256_mask:
18203 case X86::BI__builtin_ia32_vpshufbitqmb512_mask: {
18204 assert(E->getNumArgs() == 3);
18205
18206 APValue Source, ShuffleMask;
18207 APSInt ZeroMask;
18208 if (!EvaluateVector(E->getArg(0), Source, Info) ||
18209 !EvaluateVector(E->getArg(1), ShuffleMask, Info) ||
18210 !EvaluateInteger(E->getArg(2), ZeroMask, Info))
18211 return false;
18212
18213 assert(Source.getVectorLength() == ShuffleMask.getVectorLength());
18214 assert(ZeroMask.getBitWidth() == Source.getVectorLength());
18215
18216 unsigned NumBytesInQWord = 8;
18217 unsigned NumBitsInByte = 8;
18218 unsigned NumBytes = Source.getVectorLength();
18219 unsigned NumQWords = NumBytes / NumBytesInQWord;
18220 unsigned RetWidth = ZeroMask.getBitWidth();
18221 APSInt RetMask(llvm::APInt(RetWidth, 0), /*isUnsigned=*/true);
18222
18223 for (unsigned QWordId = 0; QWordId != NumQWords; ++QWordId) {
18224 APInt SourceQWord(64, 0);
18225 for (unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
18226 uint64_t Byte = Source.getVectorElt(QWordId * NumBytesInQWord + ByteIdx)
18227 .getInt()
18228 .getZExtValue();
18229 SourceQWord.insertBits(APInt(8, Byte & 0xFF), ByteIdx * NumBitsInByte);
18230 }
18231
18232 for (unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
18233 unsigned SelIdx = QWordId * NumBytesInQWord + ByteIdx;
18234 unsigned M =
18235 ShuffleMask.getVectorElt(SelIdx).getInt().getZExtValue() & 0x3F;
18236 if (ZeroMask[SelIdx]) {
18237 RetMask.setBitVal(SelIdx, SourceQWord[M]);
18238 }
18239 }
18240 }
18241 return Success(APValue(RetMask), E);
18242 }
18243 }
18244}
18245
18246/// Determine whether this is a pointer past the end of the complete
18247/// object referred to by the lvalue.
18249 const LValue &LV) {
18250 // A null pointer can be viewed as being "past the end" but we don't
18251 // choose to look at it that way here.
18252 if (!LV.getLValueBase())
18253 return false;
18254
18255 // If the designator is valid and refers to a subobject, we're not pointing
18256 // past the end.
18257 if (!LV.getLValueDesignator().Invalid &&
18258 !LV.getLValueDesignator().isOnePastTheEnd())
18259 return false;
18260
18261 // A pointer to an incomplete type might be past-the-end if the type's size is
18262 // zero. We cannot tell because the type is incomplete.
18263 QualType Ty = getType(LV.getLValueBase());
18264 if (Ty->isIncompleteType())
18265 return true;
18266
18267 // Can't be past the end of an invalid object.
18268 if (LV.getLValueDesignator().Invalid)
18269 return false;
18270
18271 // We're a past-the-end pointer if we point to the byte after the object,
18272 // no matter what our type or path is.
18273 auto Size = Ctx.getTypeSizeInChars(Ty);
18274 return LV.getLValueOffset() == Size;
18275}
18276
18277namespace {
18278
18279/// Data recursive integer evaluator of certain binary operators.
18280///
18281/// We use a data recursive algorithm for binary operators so that we are able
18282/// to handle extreme cases of chained binary operators without causing stack
18283/// overflow.
18284class DataRecursiveIntBinOpEvaluator {
18285 struct EvalResult {
18286 APValue Val;
18287 bool Failed = false;
18288
18289 EvalResult() = default;
18290
18291 void swap(EvalResult &RHS) {
18292 Val.swap(RHS.Val);
18293 Failed = RHS.Failed;
18294 RHS.Failed = false;
18295 }
18296 };
18297
18298 struct Job {
18299 const Expr *E;
18300 EvalResult LHSResult; // meaningful only for binary operator expression.
18301 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
18302
18303 Job() = default;
18304 Job(Job &&) = default;
18305
18306 void startSpeculativeEval(EvalInfo &Info) {
18307 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
18308 }
18309
18310 private:
18311 SpeculativeEvaluationRAII SpecEvalRAII;
18312 };
18313
18314 SmallVector<Job, 16> Queue;
18315
18316 IntExprEvaluator &IntEval;
18317 EvalInfo &Info;
18318 APValue &FinalResult;
18319
18320public:
18321 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
18322 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
18323
18324 /// True if \param E is a binary operator that we are going to handle
18325 /// data recursively.
18326 /// We handle binary operators that are comma, logical, or that have operands
18327 /// with integral or enumeration type.
18328 static bool shouldEnqueue(const BinaryOperator *E) {
18329 return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
18333 }
18334
18335 bool Traverse(const BinaryOperator *E) {
18336 enqueue(E);
18337 EvalResult PrevResult;
18338 while (!Queue.empty())
18339 process(PrevResult);
18340
18341 if (PrevResult.Failed) return false;
18342
18343 FinalResult.swap(PrevResult.Val);
18344 return true;
18345 }
18346
18347private:
18348 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
18349 return IntEval.Success(Value, E, Result);
18350 }
18351 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
18352 return IntEval.Success(Value, E, Result);
18353 }
18354 bool Error(const Expr *E) {
18355 return IntEval.Error(E);
18356 }
18357 bool Error(const Expr *E, diag::kind D) {
18358 return IntEval.Error(E, D);
18359 }
18360
18361 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
18362 return Info.CCEDiag(E, D);
18363 }
18364
18365 // Returns true if visiting the RHS is necessary, false otherwise.
18366 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
18367 bool &SuppressRHSDiags);
18368
18369 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
18370 const BinaryOperator *E, APValue &Result);
18371
18372 void EvaluateExpr(const Expr *E, EvalResult &Result) {
18373 Result.Failed = !Evaluate(Result.Val, Info, E);
18374 if (Result.Failed)
18375 Result.Val = APValue();
18376 }
18377
18378 void process(EvalResult &Result);
18379
18380 void enqueue(const Expr *E) {
18381 E = E->IgnoreParens();
18382 Queue.resize(Queue.size()+1);
18383 Queue.back().E = E;
18384 Queue.back().Kind = Job::AnyExprKind;
18385 }
18386};
18387
18388}
18389
18390bool DataRecursiveIntBinOpEvaluator::
18391 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
18392 bool &SuppressRHSDiags) {
18393 if (E->getOpcode() == BO_Comma) {
18394 // Ignore LHS but note if we could not evaluate it.
18395 if (LHSResult.Failed)
18396 return Info.noteSideEffect();
18397 return true;
18398 }
18399
18400 if (E->isLogicalOp()) {
18401 bool LHSAsBool;
18402 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
18403 // We were able to evaluate the LHS, see if we can get away with not
18404 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
18405 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
18406 Success(LHSAsBool, E, LHSResult.Val);
18407 return false; // Ignore RHS
18408 }
18409 } else {
18410 LHSResult.Failed = true;
18411
18412 // Since we weren't able to evaluate the left hand side, it
18413 // might have had side effects.
18414 if (!Info.noteSideEffect())
18415 return false;
18416
18417 // We can't evaluate the LHS; however, sometimes the result
18418 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
18419 // Don't ignore RHS and suppress diagnostics from this arm.
18420 SuppressRHSDiags = true;
18421 }
18422
18423 return true;
18424 }
18425
18426 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
18428
18429 if (LHSResult.Failed && !Info.noteFailure())
18430 return false; // Ignore RHS;
18431
18432 return true;
18433}
18434
18435static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
18436 bool IsSub) {
18437 // Compute the new offset in the appropriate width, wrapping at 64 bits.
18438 // FIXME: When compiling for a 32-bit target, we should use 32-bit
18439 // offsets.
18440 assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
18441 CharUnits &Offset = LVal.getLValueOffset();
18442 uint64_t Offset64 = Offset.getQuantity();
18443 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
18444 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
18445 : Offset64 + Index64);
18446}
18447
18448bool DataRecursiveIntBinOpEvaluator::
18449 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
18450 const BinaryOperator *E, APValue &Result) {
18451 if (E->getOpcode() == BO_Comma) {
18452 if (RHSResult.Failed)
18453 return false;
18454 Result = RHSResult.Val;
18455 return true;
18456 }
18457
18458 if (E->isLogicalOp()) {
18459 bool lhsResult, rhsResult;
18460 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
18461 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
18462
18463 if (LHSIsOK) {
18464 if (RHSIsOK) {
18465 if (E->getOpcode() == BO_LOr)
18466 return Success(lhsResult || rhsResult, E, Result);
18467 else
18468 return Success(lhsResult && rhsResult, E, Result);
18469 }
18470 } else {
18471 if (RHSIsOK) {
18472 // We can't evaluate the LHS; however, sometimes the result
18473 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
18474 if (rhsResult == (E->getOpcode() == BO_LOr))
18475 return Success(rhsResult, E, Result);
18476 }
18477 }
18478
18479 return false;
18480 }
18481
18482 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
18484
18485 if (LHSResult.Failed || RHSResult.Failed)
18486 return false;
18487
18488 const APValue &LHSVal = LHSResult.Val;
18489 const APValue &RHSVal = RHSResult.Val;
18490
18491 // Handle cases like (unsigned long)&a + 4.
18492 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
18493 Result = LHSVal;
18494 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
18495 return true;
18496 }
18497
18498 // Handle cases like 4 + (unsigned long)&a
18499 if (E->getOpcode() == BO_Add &&
18500 RHSVal.isLValue() && LHSVal.isInt()) {
18501 Result = RHSVal;
18502 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
18503 return true;
18504 }
18505
18506 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
18507 // Handle (intptr_t)&&A - (intptr_t)&&B.
18508 if (!LHSVal.getLValueOffset().isZero() ||
18509 !RHSVal.getLValueOffset().isZero())
18510 return false;
18511 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
18512 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
18513 if (!LHSExpr || !RHSExpr)
18514 return false;
18515 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
18516 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
18517 if (!LHSAddrExpr || !RHSAddrExpr)
18518 return false;
18519 // Make sure both labels come from the same function.
18520 if (LHSAddrExpr->getLabel()->getDeclContext() !=
18521 RHSAddrExpr->getLabel()->getDeclContext())
18522 return false;
18523 Result = APValue(LHSAddrExpr, RHSAddrExpr);
18524 return true;
18525 }
18526
18527 // All the remaining cases expect both operands to be an integer
18528 if (!LHSVal.isInt() || !RHSVal.isInt())
18529 return Error(E);
18530
18531 // Set up the width and signedness manually, in case it can't be deduced
18532 // from the operation we're performing.
18533 // FIXME: Don't do this in the cases where we can deduce it.
18534 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
18536 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
18537 RHSVal.getInt(), Value))
18538 return false;
18539 return Success(Value, E, Result);
18540}
18541
18542void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
18543 Job &job = Queue.back();
18544
18545 switch (job.Kind) {
18546 case Job::AnyExprKind: {
18547 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
18548 if (shouldEnqueue(Bop)) {
18549 job.Kind = Job::BinOpKind;
18550 enqueue(Bop->getLHS());
18551 return;
18552 }
18553 }
18554
18555 EvaluateExpr(job.E, Result);
18556 Queue.pop_back();
18557 return;
18558 }
18559
18560 case Job::BinOpKind: {
18561 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
18562 bool SuppressRHSDiags = false;
18563 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
18564 Queue.pop_back();
18565 return;
18566 }
18567 if (SuppressRHSDiags)
18568 job.startSpeculativeEval(Info);
18569 job.LHSResult.swap(Result);
18570 job.Kind = Job::BinOpVisitedLHSKind;
18571 enqueue(Bop->getRHS());
18572 return;
18573 }
18574
18575 case Job::BinOpVisitedLHSKind: {
18576 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
18577 EvalResult RHS;
18578 RHS.swap(Result);
18579 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
18580 Queue.pop_back();
18581 return;
18582 }
18583 }
18584
18585 llvm_unreachable("Invalid Job::Kind!");
18586}
18587
18588namespace {
18589enum class CmpResult {
18590 Unequal,
18591 Less,
18592 Equal,
18593 Greater,
18594 Unordered,
18595};
18596}
18597
18598template <class SuccessCB, class AfterCB>
18599static bool
18601 SuccessCB &&Success, AfterCB &&DoAfter) {
18602 assert(!E->isValueDependent());
18603 assert(E->isComparisonOp() && "expected comparison operator");
18604 assert((E->getOpcode() == BO_Cmp ||
18606 "unsupported binary expression evaluation");
18607 auto Error = [&](const Expr *E) {
18608 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
18609 return false;
18610 };
18611
18612 bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp;
18613 bool IsEquality = E->isEqualityOp();
18614
18615 QualType LHSTy = E->getLHS()->getType();
18616 QualType RHSTy = E->getRHS()->getType();
18617
18618 if (LHSTy->isIntegralOrEnumerationType() &&
18619 RHSTy->isIntegralOrEnumerationType()) {
18620 APSInt LHS, RHS;
18621 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
18622 if (!LHSOK && !Info.noteFailure())
18623 return false;
18624 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
18625 return false;
18626 if (LHS < RHS)
18627 return Success(CmpResult::Less, E);
18628 if (LHS > RHS)
18629 return Success(CmpResult::Greater, E);
18630 return Success(CmpResult::Equal, E);
18631 }
18632
18633 if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
18634 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
18635 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
18636
18637 bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
18638 if (!LHSOK && !Info.noteFailure())
18639 return false;
18640 if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
18641 return false;
18642 if (LHSFX < RHSFX)
18643 return Success(CmpResult::Less, E);
18644 if (LHSFX > RHSFX)
18645 return Success(CmpResult::Greater, E);
18646 return Success(CmpResult::Equal, E);
18647 }
18648
18649 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
18650 ComplexValue LHS, RHS;
18651 bool LHSOK;
18652 if (E->isAssignmentOp()) {
18653 LValue LV;
18654 EvaluateLValue(E->getLHS(), LV, Info);
18655 LHSOK = false;
18656 } else if (LHSTy->isRealFloatingType()) {
18657 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
18658 if (LHSOK) {
18659 LHS.makeComplexFloat();
18660 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
18661 }
18662 } else {
18663 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
18664 }
18665 if (!LHSOK && !Info.noteFailure())
18666 return false;
18667
18668 if (E->getRHS()->getType()->isRealFloatingType()) {
18669 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
18670 return false;
18671 RHS.makeComplexFloat();
18672 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
18673 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
18674 return false;
18675
18676 if (LHS.isComplexFloat()) {
18677 APFloat::cmpResult CR_r =
18678 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
18679 APFloat::cmpResult CR_i =
18680 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
18681 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
18682 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
18683 } else {
18684 assert(IsEquality && "invalid complex comparison");
18685 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
18686 LHS.getComplexIntImag() == RHS.getComplexIntImag();
18687 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
18688 }
18689 }
18690
18691 if (LHSTy->isRealFloatingType() &&
18692 RHSTy->isRealFloatingType()) {
18693 APFloat RHS(0.0), LHS(0.0);
18694
18695 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
18696 if (!LHSOK && !Info.noteFailure())
18697 return false;
18698
18699 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
18700 return false;
18701
18702 assert(E->isComparisonOp() && "Invalid binary operator!");
18703 llvm::APFloatBase::cmpResult APFloatCmpResult = LHS.compare(RHS);
18704 if (!Info.InConstantContext &&
18705 APFloatCmpResult == APFloat::cmpUnordered &&
18706 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained()) {
18707 // Note: Compares may raise invalid in some cases involving NaN or sNaN.
18708 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
18709 return false;
18710 }
18711 auto GetCmpRes = [&]() {
18712 switch (APFloatCmpResult) {
18713 case APFloat::cmpEqual:
18714 return CmpResult::Equal;
18715 case APFloat::cmpLessThan:
18716 return CmpResult::Less;
18717 case APFloat::cmpGreaterThan:
18718 return CmpResult::Greater;
18719 case APFloat::cmpUnordered:
18720 return CmpResult::Unordered;
18721 }
18722 llvm_unreachable("Unrecognised APFloat::cmpResult enum");
18723 };
18724 return Success(GetCmpRes(), E);
18725 }
18726
18727 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
18728 LValue LHSValue, RHSValue;
18729
18730 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
18731 if (!LHSOK && !Info.noteFailure())
18732 return false;
18733
18734 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
18735 return false;
18736
18737 // Reject differing bases from the normal codepath; we special-case
18738 // comparisons to null.
18739 if (!HasSameBase(LHSValue, RHSValue)) {
18740 // Bail out early if we're checking potential constant expression.
18741 // Otherwise, prefer to diagnose other issues.
18742 if (Info.checkingPotentialConstantExpression() &&
18743 (LHSValue.AllowConstexprUnknown || RHSValue.AllowConstexprUnknown))
18744 return false;
18745 auto DiagComparison = [&] (unsigned DiagID, bool Reversed = false) {
18746 std::string LHS = LHSValue.toString(Info.Ctx, E->getLHS()->getType());
18747 std::string RHS = RHSValue.toString(Info.Ctx, E->getRHS()->getType());
18748 Info.FFDiag(E, DiagID)
18749 << (Reversed ? RHS : LHS) << (Reversed ? LHS : RHS);
18750 return false;
18751 };
18752 // Inequalities and subtractions between unrelated pointers have
18753 // unspecified or undefined behavior.
18754 if (!IsEquality)
18755 return DiagComparison(
18756 diag::note_constexpr_pointer_comparison_unspecified);
18757 // A constant address may compare equal to the address of a symbol.
18758 // The one exception is that address of an object cannot compare equal
18759 // to a null pointer constant.
18760 // TODO: Should we restrict this to actual null pointers, and exclude the
18761 // case of zero cast to pointer type?
18762 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
18763 (!RHSValue.Base && !RHSValue.Offset.isZero()))
18764 return DiagComparison(diag::note_constexpr_pointer_constant_comparison,
18765 !RHSValue.Base);
18766 // C++2c [intro.object]/10:
18767 // Two objects [...] may have the same address if [...] they are both
18768 // potentially non-unique objects.
18769 // C++2c [intro.object]/9:
18770 // An object is potentially non-unique if it is a string literal object,
18771 // the backing array of an initializer list, or a subobject thereof.
18772 //
18773 // This makes the comparison result unspecified, so it's not a constant
18774 // expression.
18775 //
18776 // TODO: Do we need to handle the initializer list case here?
18777 if (ArePotentiallyOverlappingStringLiterals(Info, LHSValue, RHSValue))
18778 return DiagComparison(diag::note_constexpr_literal_comparison);
18779 if (IsOpaqueConstantCall(LHSValue) || IsOpaqueConstantCall(RHSValue))
18780 return DiagComparison(diag::note_constexpr_opaque_call_comparison,
18781 !IsOpaqueConstantCall(LHSValue));
18782 // We can't tell whether weak symbols will end up pointing to the same
18783 // object.
18784 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
18785 return DiagComparison(diag::note_constexpr_pointer_weak_comparison,
18786 !IsWeakLValue(LHSValue));
18787 // We can't compare the address of the start of one object with the
18788 // past-the-end address of another object, per C++ DR1652.
18789 if (LHSValue.Base && LHSValue.Offset.isZero() &&
18790 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue))
18791 return DiagComparison(diag::note_constexpr_pointer_comparison_past_end,
18792 true);
18793 if (RHSValue.Base && RHSValue.Offset.isZero() &&
18794 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue))
18795 return DiagComparison(diag::note_constexpr_pointer_comparison_past_end,
18796 false);
18797 // We can't tell whether an object is at the same address as another
18798 // zero sized object.
18799 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
18800 (LHSValue.Base && isZeroSized(RHSValue)))
18801 return DiagComparison(
18802 diag::note_constexpr_pointer_comparison_zero_sized);
18803 if (LHSValue.AllowConstexprUnknown || RHSValue.AllowConstexprUnknown)
18804 return DiagComparison(
18805 diag::note_constexpr_pointer_comparison_unspecified);
18806 // FIXME: Verify both variables are live.
18807 return Success(CmpResult::Unequal, E);
18808 }
18809
18810 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
18811 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
18812
18813 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
18814 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
18815
18816 // C++11 [expr.rel]p2:
18817 // - If two pointers point to non-static data members of the same object,
18818 // or to subobjects or array elements fo such members, recursively, the
18819 // pointer to the later declared member compares greater provided the
18820 // two members have the same access control and provided their class is
18821 // not a union.
18822 // [...]
18823 // - Otherwise pointer comparisons are unspecified.
18824 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
18825 bool WasArrayIndex;
18826 unsigned Mismatch = FindDesignatorMismatch(
18827 LHSValue.Base.isNull() ? QualType()
18828 : getType(LHSValue.Base).getNonReferenceType(),
18829 LHSDesignator, RHSDesignator, WasArrayIndex);
18830 // At the point where the designators diverge, the comparison has a
18831 // specified value if:
18832 // - we are comparing array indices
18833 // - we are comparing fields of a union, or fields with the same access
18834 // Otherwise, the result is unspecified and thus the comparison is not a
18835 // constant expression.
18836 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
18837 Mismatch < RHSDesignator.Entries.size()) {
18838 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
18839 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
18840 if (!LF && !RF)
18841 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
18842 else if (!LF)
18843 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
18844 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
18845 << RF->getParent() << RF;
18846 else if (!RF)
18847 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
18848 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
18849 << LF->getParent() << LF;
18850 else if (!LF->getParent()->isUnion() &&
18851 LF->getAccess() != RF->getAccess())
18852 Info.CCEDiag(E,
18853 diag::note_constexpr_pointer_comparison_differing_access)
18854 << LF << LF->getAccess() << RF << RF->getAccess()
18855 << LF->getParent();
18856 }
18857 }
18858
18859 // The comparison here must be unsigned, and performed with the same
18860 // width as the pointer.
18861 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
18862 uint64_t CompareLHS = LHSOffset.getQuantity();
18863 uint64_t CompareRHS = RHSOffset.getQuantity();
18864 assert(PtrSize <= 64 && "Unexpected pointer width");
18865 uint64_t Mask = ~0ULL >> (64 - PtrSize);
18866 CompareLHS &= Mask;
18867 CompareRHS &= Mask;
18868
18869 // If there is a base and this is a relational operator, we can only
18870 // compare pointers within the object in question; otherwise, the result
18871 // depends on where the object is located in memory.
18872 if (!LHSValue.Base.isNull() && IsRelational) {
18873 QualType BaseTy = getType(LHSValue.Base).getNonReferenceType();
18874 if (BaseTy->isIncompleteType())
18875 return Error(E);
18876 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
18877 uint64_t OffsetLimit = Size.getQuantity();
18878 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
18879 return Error(E);
18880 }
18881
18882 if (CompareLHS < CompareRHS)
18883 return Success(CmpResult::Less, E);
18884 if (CompareLHS > CompareRHS)
18885 return Success(CmpResult::Greater, E);
18886 return Success(CmpResult::Equal, E);
18887 }
18888
18889 if (LHSTy->isMemberPointerType()) {
18890 assert(IsEquality && "unexpected member pointer operation");
18891 assert(RHSTy->isMemberPointerType() && "invalid comparison");
18892
18893 MemberPtr LHSValue, RHSValue;
18894
18895 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
18896 if (!LHSOK && !Info.noteFailure())
18897 return false;
18898
18899 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
18900 return false;
18901
18902 // If either operand is a pointer to a weak function, the comparison is not
18903 // constant.
18904 if (LHSValue.getDecl() && LHSValue.getDecl()->isWeak()) {
18905 Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison)
18906 << LHSValue.getDecl();
18907 return false;
18908 }
18909 if (RHSValue.getDecl() && RHSValue.getDecl()->isWeak()) {
18910 Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison)
18911 << RHSValue.getDecl();
18912 return false;
18913 }
18914
18915 // C++11 [expr.eq]p2:
18916 // If both operands are null, they compare equal. Otherwise if only one is
18917 // null, they compare unequal.
18918 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
18919 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
18920 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
18921 }
18922
18923 // Otherwise if either is a pointer to a virtual member function, the
18924 // result is unspecified.
18925 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
18926 if (MD->isVirtual())
18927 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
18928 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
18929 if (MD->isVirtual())
18930 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
18931
18932 // Otherwise they compare equal if and only if they would refer to the
18933 // same member of the same most derived object or the same subobject if
18934 // they were dereferenced with a hypothetical object of the associated
18935 // class type.
18936 bool Equal = LHSValue == RHSValue;
18937 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
18938 }
18939
18940 if (LHSTy->isNullPtrType()) {
18941 assert(E->isComparisonOp() && "unexpected nullptr operation");
18942 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
18943 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
18944 // are compared, the result is true of the operator is <=, >= or ==, and
18945 // false otherwise.
18946 LValue Res;
18947 if (!EvaluatePointer(E->getLHS(), Res, Info) ||
18948 !EvaluatePointer(E->getRHS(), Res, Info))
18949 return false;
18950 return Success(CmpResult::Equal, E);
18951 }
18952
18953 return DoAfter();
18954}
18955
18956bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
18957 if (!CheckLiteralType(Info, E))
18958 return false;
18959
18960 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
18962 switch (CR) {
18963 case CmpResult::Unequal:
18964 llvm_unreachable("should never produce Unequal for three-way comparison");
18965 case CmpResult::Less:
18966 CCR = ComparisonCategoryResult::Less;
18967 break;
18968 case CmpResult::Equal:
18969 CCR = ComparisonCategoryResult::Equal;
18970 break;
18971 case CmpResult::Greater:
18972 CCR = ComparisonCategoryResult::Greater;
18973 break;
18974 case CmpResult::Unordered:
18975 CCR = ComparisonCategoryResult::Unordered;
18976 break;
18977 }
18978 // Evaluation succeeded. Lookup the information for the comparison category
18979 // type and fetch the VarDecl for the result.
18980 const ComparisonCategoryInfo &CmpInfo =
18981 Info.Ctx.CompCategories.getInfoForType(E->getType());
18982 const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD;
18983 // Check and evaluate the result as a constant expression.
18984 LValue LV;
18985 LV.set(VD);
18986 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
18987 return false;
18988 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
18989 ConstantExprKind::Normal);
18990 };
18991 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
18992 return ExprEvaluatorBaseTy::VisitBinCmp(E);
18993 });
18994}
18995
18996bool RecordExprEvaluator::VisitCXXParenListInitExpr(
18997 const CXXParenListInitExpr *E) {
18998 return VisitCXXParenListOrInitListExpr(E, E->getInitExprs());
18999}
19000
19001bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
19002 // We don't support assignment in C. C++ assignments don't get here because
19003 // assignment is an lvalue in C++.
19004 if (E->isAssignmentOp()) {
19005 Error(E);
19006 if (!Info.noteFailure())
19007 return false;
19008 }
19009
19010 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
19011 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
19012
19013 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
19015 "DataRecursiveIntBinOpEvaluator should have handled integral types");
19016
19017 if (E->isComparisonOp()) {
19018 // Evaluate builtin binary comparisons by evaluating them as three-way
19019 // comparisons and then translating the result.
19020 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
19021 assert((CR != CmpResult::Unequal || E->isEqualityOp()) &&
19022 "should only produce Unequal for equality comparisons");
19023 bool IsEqual = CR == CmpResult::Equal,
19024 IsLess = CR == CmpResult::Less,
19025 IsGreater = CR == CmpResult::Greater;
19026 auto Op = E->getOpcode();
19027 switch (Op) {
19028 default:
19029 llvm_unreachable("unsupported binary operator");
19030 case BO_EQ:
19031 case BO_NE:
19032 return Success(IsEqual == (Op == BO_EQ), E);
19033 case BO_LT:
19034 return Success(IsLess, E);
19035 case BO_GT:
19036 return Success(IsGreater, E);
19037 case BO_LE:
19038 return Success(IsEqual || IsLess, E);
19039 case BO_GE:
19040 return Success(IsEqual || IsGreater, E);
19041 }
19042 };
19043 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
19044 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
19045 });
19046 }
19047
19048 QualType LHSTy = E->getLHS()->getType();
19049 QualType RHSTy = E->getRHS()->getType();
19050
19051 if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
19052 E->getOpcode() == BO_Sub) {
19053 LValue LHSValue, RHSValue;
19054
19055 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
19056 if (!LHSOK && !Info.noteFailure())
19057 return false;
19058
19059 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
19060 return false;
19061
19062 // Reject differing bases from the normal codepath; we special-case
19063 // comparisons to null.
19064 if (!HasSameBase(LHSValue, RHSValue)) {
19065 if (Info.checkingPotentialConstantExpression() &&
19066 (LHSValue.AllowConstexprUnknown || RHSValue.AllowConstexprUnknown))
19067 return false;
19068
19069 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
19070 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
19071
19072 auto DiagArith = [&](unsigned DiagID) {
19073 std::string LHS = LHSValue.toString(Info.Ctx, E->getLHS()->getType());
19074 std::string RHS = RHSValue.toString(Info.Ctx, E->getRHS()->getType());
19075 Info.FFDiag(E, DiagID) << LHS << RHS;
19076 if (LHSExpr && LHSExpr == RHSExpr)
19077 Info.Note(LHSExpr->getExprLoc(),
19078 diag::note_constexpr_repeated_literal_eval)
19079 << LHSExpr->getSourceRange();
19080 return false;
19081 };
19082
19083 if (!LHSExpr || !RHSExpr)
19084 return DiagArith(diag::note_constexpr_pointer_arith_unspecified);
19085
19086 if (ArePotentiallyOverlappingStringLiterals(Info, LHSValue, RHSValue))
19087 return DiagArith(diag::note_constexpr_literal_arith);
19088
19089 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
19090 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
19091 if (!LHSAddrExpr || !RHSAddrExpr)
19092 return Error(E);
19093 // Make sure both labels come from the same function.
19094 if (LHSAddrExpr->getLabel()->getDeclContext() !=
19095 RHSAddrExpr->getLabel()->getDeclContext())
19096 return Error(E);
19097 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
19098 }
19099 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
19100 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
19101
19102 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
19103 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
19104
19105 // C++11 [expr.add]p6:
19106 // Unless both pointers point to elements of the same array object, or
19107 // one past the last element of the array object, the behavior is
19108 // undefined.
19109 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
19110 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
19111 RHSDesignator))
19112 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
19113
19114 QualType Type = E->getLHS()->getType();
19115 QualType ElementType = Type->castAs<PointerType>()->getPointeeType();
19116
19117 CharUnits ElementSize;
19118 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
19119 return false;
19120
19121 // As an extension, a type may have zero size (empty struct or union in
19122 // C, array of zero length). Pointer subtraction in such cases has
19123 // undefined behavior, so is not constant.
19124 if (ElementSize.isZero()) {
19125 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
19126 << ElementType;
19127 return false;
19128 }
19129
19130 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
19131 // and produce incorrect results when it overflows. Such behavior
19132 // appears to be non-conforming, but is common, so perhaps we should
19133 // assume the standard intended for such cases to be undefined behavior
19134 // and check for them.
19135
19136 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
19137 // overflow in the final conversion to ptrdiff_t.
19138 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
19139 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
19140 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
19141 false);
19142 APSInt TrueResult = (LHS - RHS) / ElemSize;
19143 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
19144
19145 if (Result.extend(65) != TrueResult &&
19146 !HandleOverflow(Info, E, TrueResult, E->getType()))
19147 return false;
19148 return Success(Result, E);
19149 }
19150
19151 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
19152}
19153
19154/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
19155/// a result as the expression's type.
19156bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
19157 const UnaryExprOrTypeTraitExpr *E) {
19158 switch(E->getKind()) {
19159 case UETT_PreferredAlignOf:
19160 case UETT_AlignOf: {
19161 if (E->isArgumentType())
19162 return Success(
19163 GetAlignOfType(Info.Ctx, E->getArgumentType(), E->getKind()), E);
19164 else
19165 return Success(
19166 GetAlignOfExpr(Info.Ctx, E->getArgumentExpr(), E->getKind()), E);
19167 }
19168
19169 case UETT_PtrAuthTypeDiscriminator: {
19170 if (E->getArgumentType()->isDependentType())
19171 return false;
19172 return Success(
19173 Info.Ctx.getPointerAuthTypeDiscriminator(E->getArgumentType()), E);
19174 }
19175 case UETT_VecStep: {
19176 QualType Ty = E->getTypeOfArgument();
19177
19178 if (Ty->isVectorType()) {
19179 unsigned n = Ty->castAs<VectorType>()->getNumElements();
19180
19181 // The vec_step built-in functions that take a 3-component
19182 // vector return 4. (OpenCL 1.1 spec 6.11.12)
19183 if (n == 3)
19184 n = 4;
19185
19186 return Success(n, E);
19187 } else
19188 return Success(1, E);
19189 }
19190
19191 case UETT_DataSizeOf:
19192 case UETT_SizeOf: {
19193 QualType SrcTy = E->getTypeOfArgument();
19194 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
19195 // the result is the size of the referenced type."
19196 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
19197 SrcTy = Ref->getPointeeType();
19198
19199 CharUnits Sizeof;
19200 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof,
19201 E->getKind() == UETT_DataSizeOf ? SizeOfType::DataSizeOf
19202 : SizeOfType::SizeOf)) {
19203 return false;
19204 }
19205 return Success(Sizeof, E);
19206 }
19207 case UETT_OpenMPRequiredSimdAlign:
19208 assert(E->isArgumentType());
19209 return Success(
19210 Info.Ctx.toCharUnitsFromBits(
19211 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
19212 .getQuantity(),
19213 E);
19214 case UETT_VectorElements: {
19215 QualType Ty = E->getTypeOfArgument();
19216 // If the vector has a fixed size, we can determine the number of elements
19217 // at compile time.
19218 if (const auto *VT = Ty->getAs<VectorType>())
19219 return Success(VT->getNumElements(), E);
19220
19221 assert(Ty->isSizelessVectorType());
19222 if (Info.InConstantContext)
19223 Info.CCEDiag(E, diag::note_constexpr_non_const_vectorelements)
19224 << E->getSourceRange();
19225
19226 return false;
19227 }
19228 case UETT_CountOf: {
19229 QualType Ty = E->getTypeOfArgument();
19230 assert(Ty->isArrayType());
19231
19232 // We don't need to worry about array element qualifiers, so getting the
19233 // unsafe array type is fine.
19234 if (const auto *CAT =
19235 dyn_cast<ConstantArrayType>(Ty->getAsArrayTypeUnsafe())) {
19236 return Success(CAT->getSize(), E);
19237 }
19238
19239 assert(!Ty->isConstantSizeType());
19240
19241 // If it's a variable-length array type, we need to check whether it is a
19242 // multidimensional array. If so, we need to check the size expression of
19243 // the VLA to see if it's a constant size. If so, we can return that value.
19244 const auto *VAT = Info.Ctx.getAsVariableArrayType(Ty);
19245 assert(VAT);
19246 if (VAT->getElementType()->isArrayType()) {
19247 // Variable array size expression could be missing (e.g. int a[*][10]) In
19248 // that case, it can't be a constant expression.
19249 if (!VAT->getSizeExpr()) {
19250 Info.FFDiag(E->getBeginLoc());
19251 return false;
19252 }
19253
19254 std::optional<APSInt> Res =
19255 VAT->getSizeExpr()->getIntegerConstantExpr(Info.Ctx);
19256 if (Res) {
19257 // The resulting value always has type size_t, so we need to make the
19258 // returned APInt have the correct sign and bit-width.
19259 APInt Val{
19260 static_cast<unsigned>(Info.Ctx.getTypeSize(Info.Ctx.getSizeType())),
19261 Res->getZExtValue()};
19262 return Success(Val, E);
19263 }
19264 }
19265
19266 // Definitely a variable-length type, which is not an ICE.
19267 // FIXME: Better diagnostic.
19268 Info.FFDiag(E->getBeginLoc());
19269 return false;
19270 }
19271 }
19272
19273 llvm_unreachable("unknown expr/type trait");
19274}
19275
19276bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
19277 Info.Ctx.recordOffsetOfEvaluation(OOE);
19278 CharUnits Result;
19279 unsigned n = OOE->getNumComponents();
19280 if (n == 0)
19281 return Error(OOE);
19282 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
19283 for (unsigned i = 0; i != n; ++i) {
19284 OffsetOfNode ON = OOE->getComponent(i);
19285 switch (ON.getKind()) {
19286 case OffsetOfNode::Array: {
19287 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
19288 APSInt IdxResult;
19289 if (!EvaluateInteger(Idx, IdxResult, Info))
19290 return false;
19291 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
19292 if (!AT)
19293 return Error(OOE);
19294 CurrentType = AT->getElementType();
19295 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
19296 Result += IdxResult.getSExtValue() * ElementSize;
19297 break;
19298 }
19299
19300 case OffsetOfNode::Field: {
19301 FieldDecl *MemberDecl = ON.getField();
19302 const auto *RD = CurrentType->getAsRecordDecl();
19303 if (!RD)
19304 return Error(OOE);
19305 if (RD->isInvalidDecl()) return false;
19306 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
19307 unsigned i = MemberDecl->getFieldIndex();
19308 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
19309 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
19310 CurrentType = MemberDecl->getType().getNonReferenceType();
19311 break;
19312 }
19313
19315 llvm_unreachable("dependent __builtin_offsetof");
19316
19317 case OffsetOfNode::Base: {
19318 CXXBaseSpecifier *BaseSpec = ON.getBase();
19319 if (BaseSpec->isVirtual())
19320 return Error(OOE);
19321
19322 // Find the layout of the class whose base we are looking into.
19323 const auto *RD = CurrentType->getAsCXXRecordDecl();
19324 if (!RD)
19325 return Error(OOE);
19326 if (RD->isInvalidDecl()) return false;
19327 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
19328
19329 // Find the base class itself.
19330 CurrentType = BaseSpec->getType();
19331 const auto *BaseRD = CurrentType->getAsCXXRecordDecl();
19332 if (!BaseRD)
19333 return Error(OOE);
19334
19335 // Add the offset to the base.
19336 Result += RL.getBaseClassOffset(BaseRD);
19337 break;
19338 }
19339 }
19340 }
19341 return Success(Result, OOE);
19342}
19343
19344bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
19345 switch (E->getOpcode()) {
19346 default:
19347 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
19348 // See C99 6.6p3.
19349 return Error(E);
19350 case UO_Extension:
19351 // FIXME: Should extension allow i-c-e extension expressions in its scope?
19352 // If so, we could clear the diagnostic ID.
19353 return Visit(E->getSubExpr());
19354 case UO_Plus:
19355 // The result is just the value.
19356 return Visit(E->getSubExpr());
19357 case UO_Minus: {
19358 if (!Visit(E->getSubExpr()))
19359 return false;
19360 if (!Result.isInt()) return Error(E);
19361 const APSInt &Value = Result.getInt();
19362 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
19363 !E->getType().isWrapType()) {
19364 if (Info.checkingForUndefinedBehavior())
19365 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
19366 diag::warn_integer_constant_overflow)
19367 << toString(Value, 10, Value.isSigned(), /*formatAsCLiteral=*/false,
19368 /*UpperCase=*/true, /*InsertSeparators=*/true)
19369 << E->getType() << E->getSourceRange();
19370
19371 if (!HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
19372 E->getType()))
19373 return false;
19374 }
19375 return Success(-Value, E);
19376 }
19377 case UO_Not: {
19378 if (!Visit(E->getSubExpr()))
19379 return false;
19380 if (!Result.isInt()) return Error(E);
19381 return Success(~Result.getInt(), E);
19382 }
19383 case UO_LNot: {
19384 bool bres;
19385 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
19386 return false;
19387 return Success(!bres, E);
19388 }
19389 }
19390}
19391
19392/// HandleCast - This is used to evaluate implicit or explicit casts where the
19393/// result type is integer.
19394bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
19395 const Expr *SubExpr = E->getSubExpr();
19396 QualType DestType = E->getType();
19397 QualType SrcType = SubExpr->getType();
19398
19399 switch (E->getCastKind()) {
19400 case CK_BaseToDerived:
19401 case CK_DerivedToBase:
19402 case CK_UncheckedDerivedToBase:
19403 case CK_Dynamic:
19404 case CK_ToUnion:
19405 case CK_ArrayToPointerDecay:
19406 case CK_FunctionToPointerDecay:
19407 case CK_NullToPointer:
19408 case CK_NullToMemberPointer:
19409 case CK_BaseToDerivedMemberPointer:
19410 case CK_DerivedToBaseMemberPointer:
19411 case CK_ReinterpretMemberPointer:
19412 case CK_ConstructorConversion:
19413 case CK_IntegralToPointer:
19414 case CK_ToVoid:
19415 case CK_VectorSplat:
19416 case CK_IntegralToFloating:
19417 case CK_FloatingCast:
19418 case CK_CPointerToObjCPointerCast:
19419 case CK_BlockPointerToObjCPointerCast:
19420 case CK_AnyPointerToBlockPointerCast:
19421 case CK_ObjCObjectLValueCast:
19422 case CK_FloatingRealToComplex:
19423 case CK_FloatingComplexToReal:
19424 case CK_FloatingComplexCast:
19425 case CK_FloatingComplexToIntegralComplex:
19426 case CK_IntegralRealToComplex:
19427 case CK_IntegralComplexCast:
19428 case CK_IntegralComplexToFloatingComplex:
19429 case CK_BuiltinFnToFnPtr:
19430 case CK_ZeroToOCLOpaqueType:
19431 case CK_NonAtomicToAtomic:
19432 case CK_AddressSpaceConversion:
19433 case CK_IntToOCLSampler:
19434 case CK_FloatingToFixedPoint:
19435 case CK_FixedPointToFloating:
19436 case CK_FixedPointCast:
19437 case CK_IntegralToFixedPoint:
19438 case CK_MatrixCast:
19439 case CK_HLSLAggregateSplatCast:
19440 llvm_unreachable("invalid cast kind for integral value");
19441
19442 case CK_BitCast:
19443 case CK_Dependent:
19444 case CK_LValueBitCast:
19445 case CK_ARCProduceObject:
19446 case CK_ARCConsumeObject:
19447 case CK_ARCReclaimReturnedObject:
19448 case CK_ARCExtendBlockObject:
19449 case CK_CopyAndAutoreleaseBlockObject:
19450 return Error(E);
19451
19452 case CK_UserDefinedConversion:
19453 case CK_LValueToRValue:
19454 case CK_AtomicToNonAtomic:
19455 case CK_NoOp:
19456 case CK_LValueToRValueBitCast:
19457 case CK_HLSLArrayRValue:
19458 return ExprEvaluatorBaseTy::VisitCastExpr(E);
19459
19460 case CK_MemberPointerToBoolean:
19461 case CK_PointerToBoolean:
19462 case CK_IntegralToBoolean:
19463 case CK_FloatingToBoolean:
19464 case CK_BooleanToSignedIntegral:
19465 case CK_FloatingComplexToBoolean:
19466 case CK_IntegralComplexToBoolean: {
19467 bool BoolResult;
19468 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
19469 return false;
19470 uint64_t IntResult = BoolResult;
19471 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
19472 IntResult = (uint64_t)-1;
19473 return Success(IntResult, E);
19474 }
19475
19476 case CK_FixedPointToIntegral: {
19477 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
19478 if (!EvaluateFixedPoint(SubExpr, Src, Info))
19479 return false;
19480 bool Overflowed;
19481 llvm::APSInt Result = Src.convertToInt(
19482 Info.Ctx.getIntWidth(DestType),
19483 DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
19484 if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
19485 return false;
19486 return Success(Result, E);
19487 }
19488
19489 case CK_FixedPointToBoolean: {
19490 // Unsigned padding does not affect this.
19491 APValue Val;
19492 if (!Evaluate(Val, Info, SubExpr))
19493 return false;
19494 return Success(Val.getFixedPoint().getBoolValue(), E);
19495 }
19496
19497 case CK_IntegralCast: {
19498 if (!Visit(SubExpr))
19499 return false;
19500
19501 if (!Result.isInt()) {
19502 // Allow casts of address-of-label differences if they are no-ops
19503 // or narrowing, if the result is at least 32 bits wide.
19504 // (The narrowing case isn't actually guaranteed to
19505 // be constant-evaluatable except in some narrow cases which are hard
19506 // to detect here. We let it through on the assumption the user knows
19507 // what they are doing.)
19508 if (Result.isAddrLabelDiff()) {
19509 unsigned DestBits = Info.Ctx.getTypeSize(DestType);
19510 return DestBits >= 32 && DestBits <= Info.Ctx.getTypeSize(SrcType);
19511 }
19512 // Only allow casts of lvalues if they are lossless.
19513 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
19514 }
19515
19516 if (Info.Ctx.getLangOpts().CPlusPlus && DestType->isEnumeralType()) {
19517 const auto *ED = DestType->getAsEnumDecl();
19518 // Check that the value is within the range of the enumeration values.
19519 //
19520 // This corressponds to [expr.static.cast]p10 which says:
19521 // A value of integral or enumeration type can be explicitly converted
19522 // to a complete enumeration type ... If the enumeration type does not
19523 // have a fixed underlying type, the value is unchanged if the original
19524 // value is within the range of the enumeration values ([dcl.enum]), and
19525 // otherwise, the behavior is undefined.
19526 //
19527 // This was resolved as part of DR2338 which has CD5 status.
19528 if (!ED->isFixed()) {
19529 llvm::APInt Min;
19530 llvm::APInt Max;
19531
19532 ED->getValueRange(Max, Min);
19533 --Max;
19534
19535 if (ED->getNumNegativeBits() &&
19536 (Max.slt(Result.getInt().getSExtValue()) ||
19537 Min.sgt(Result.getInt().getSExtValue())))
19538 Info.CCEDiag(E, diag::note_constexpr_unscoped_enum_out_of_range)
19539 << llvm::toString(Result.getInt(), 10) << Min.getSExtValue()
19540 << Max.getSExtValue() << ED;
19541 else if (!ED->getNumNegativeBits() &&
19542 Max.ult(Result.getInt().getZExtValue()))
19543 Info.CCEDiag(E, diag::note_constexpr_unscoped_enum_out_of_range)
19544 << llvm::toString(Result.getInt(), 10) << Min.getZExtValue()
19545 << Max.getZExtValue() << ED;
19546 }
19547 }
19548
19549 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
19550 Result.getInt()), E);
19551 }
19552
19553 case CK_PointerToIntegral: {
19554 CCEDiag(E, diag::note_constexpr_invalid_cast)
19555 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
19556 << Info.Ctx.getLangOpts().CPlusPlus << E->getSourceRange();
19557
19558 LValue LV;
19559 if (!EvaluatePointer(SubExpr, LV, Info))
19560 return false;
19561
19562 if (LV.getLValueBase()) {
19563 // Only allow based lvalue casts if they are lossless.
19564 // FIXME: Allow a larger integer size than the pointer size, and allow
19565 // narrowing back down to pointer width in subsequent integral casts.
19566 // FIXME: Check integer type's active bits, not its type size.
19567 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
19568 return Error(E);
19569
19570 LV.Designator.setInvalid();
19571 LV.moveInto(Result);
19572 return true;
19573 }
19574
19575 APSInt AsInt;
19576 APValue V;
19577 LV.moveInto(V);
19578 if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
19579 llvm_unreachable("Can't cast this!");
19580
19581 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
19582 }
19583
19584 case CK_IntegralComplexToReal: {
19585 ComplexValue C;
19586 if (!EvaluateComplex(SubExpr, C, Info))
19587 return false;
19588 return Success(C.getComplexIntReal(), E);
19589 }
19590
19591 case CK_FloatingToIntegral: {
19592 APFloat F(0.0);
19593 if (!EvaluateFloat(SubExpr, F, Info))
19594 return false;
19595
19596 APSInt Value;
19597 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
19598 return false;
19599 return Success(Value, E);
19600 }
19601 case CK_HLSLVectorTruncation: {
19602 APValue Val;
19603 if (!EvaluateVector(SubExpr, Val, Info))
19604 return Error(E);
19605 return Success(Val.getVectorElt(0), E);
19606 }
19607 case CK_HLSLMatrixTruncation: {
19608 APValue Val;
19609 if (!EvaluateMatrix(SubExpr, Val, Info))
19610 return Error(E);
19611 return Success(Val.getMatrixElt(0, 0), E);
19612 }
19613 case CK_HLSLElementwiseCast: {
19614 SmallVector<APValue> SrcVals;
19615 SmallVector<QualType> SrcTypes;
19616
19617 if (!hlslElementwiseCastHelper(Info, SubExpr, DestType, SrcVals, SrcTypes))
19618 return false;
19619
19620 // cast our single element
19621 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
19622 APValue ResultVal;
19623 if (!handleScalarCast(Info, FPO, E, SrcTypes[0], DestType, SrcVals[0],
19624 ResultVal))
19625 return false;
19626 return Success(ResultVal, E);
19627 }
19628 }
19629
19630 llvm_unreachable("unknown cast resulting in integral value");
19631}
19632
19633bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
19634 if (E->getSubExpr()->getType()->isAnyComplexType()) {
19635 ComplexValue LV;
19636 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
19637 return false;
19638 if (!LV.isComplexInt())
19639 return Error(E);
19640 return Success(LV.getComplexIntReal(), E);
19641 }
19642
19643 return Visit(E->getSubExpr());
19644}
19645
19646bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
19647 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
19648 ComplexValue LV;
19649 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
19650 return false;
19651 if (!LV.isComplexInt())
19652 return Error(E);
19653 return Success(LV.getComplexIntImag(), E);
19654 }
19655
19656 VisitIgnoredValue(E->getSubExpr());
19657 return Success(0, E);
19658}
19659
19660bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
19661 return Success(E->getPackLength(), E);
19662}
19663
19664bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
19665 return Success(E->getValue(), E);
19666}
19667
19668bool IntExprEvaluator::VisitConceptSpecializationExpr(
19669 const ConceptSpecializationExpr *E) {
19670 return Success(E->isSatisfied(), E);
19671}
19672
19673bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) {
19674 return Success(E->isSatisfied(), E);
19675}
19676
19677bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
19678 switch (E->getOpcode()) {
19679 default:
19680 // Invalid unary operators
19681 return Error(E);
19682 case UO_Plus:
19683 // The result is just the value.
19684 return Visit(E->getSubExpr());
19685 case UO_Minus: {
19686 if (!Visit(E->getSubExpr())) return false;
19687 if (!Result.isFixedPoint())
19688 return Error(E);
19689 bool Overflowed;
19690 APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
19691 if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
19692 return false;
19693 return Success(Negated, E);
19694 }
19695 case UO_LNot: {
19696 bool bres;
19697 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
19698 return false;
19699 return Success(!bres, E);
19700 }
19701 }
19702}
19703
19704bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
19705 const Expr *SubExpr = E->getSubExpr();
19706 QualType DestType = E->getType();
19707 assert(DestType->isFixedPointType() &&
19708 "Expected destination type to be a fixed point type");
19709 auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
19710
19711 switch (E->getCastKind()) {
19712 case CK_FixedPointCast: {
19713 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
19714 if (!EvaluateFixedPoint(SubExpr, Src, Info))
19715 return false;
19716 bool Overflowed;
19717 APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
19718 if (Overflowed) {
19719 if (Info.checkingForUndefinedBehavior())
19720 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
19721 diag::warn_fixedpoint_constant_overflow)
19722 << Result.toString() << E->getType();
19723 if (!HandleOverflow(Info, E, Result, E->getType()))
19724 return false;
19725 }
19726 return Success(Result, E);
19727 }
19728 case CK_IntegralToFixedPoint: {
19729 APSInt Src;
19730 if (!EvaluateInteger(SubExpr, Src, Info))
19731 return false;
19732
19733 bool Overflowed;
19734 APFixedPoint IntResult = APFixedPoint::getFromIntValue(
19735 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
19736
19737 if (Overflowed) {
19738 if (Info.checkingForUndefinedBehavior())
19739 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
19740 diag::warn_fixedpoint_constant_overflow)
19741 << IntResult.toString() << E->getType();
19742 if (!HandleOverflow(Info, E, IntResult, E->getType()))
19743 return false;
19744 }
19745
19746 return Success(IntResult, E);
19747 }
19748 case CK_FloatingToFixedPoint: {
19749 APFloat Src(0.0);
19750 if (!EvaluateFloat(SubExpr, Src, Info))
19751 return false;
19752
19753 bool Overflowed;
19754 APFixedPoint Result = APFixedPoint::getFromFloatValue(
19755 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
19756
19757 if (Overflowed) {
19758 if (Info.checkingForUndefinedBehavior())
19759 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
19760 diag::warn_fixedpoint_constant_overflow)
19761 << Result.toString() << E->getType();
19762 if (!HandleOverflow(Info, E, Result, E->getType()))
19763 return false;
19764 }
19765
19766 return Success(Result, E);
19767 }
19768 case CK_NoOp:
19769 case CK_LValueToRValue:
19770 return ExprEvaluatorBaseTy::VisitCastExpr(E);
19771 default:
19772 return Error(E);
19773 }
19774}
19775
19776bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
19777 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
19778 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
19779
19780 const Expr *LHS = E->getLHS();
19781 const Expr *RHS = E->getRHS();
19782 FixedPointSemantics ResultFXSema =
19783 Info.Ctx.getFixedPointSemantics(E->getType());
19784
19785 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
19786 if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
19787 return false;
19788 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
19789 if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
19790 return false;
19791
19792 bool OpOverflow = false, ConversionOverflow = false;
19793 APFixedPoint Result(LHSFX.getSemantics());
19794 switch (E->getOpcode()) {
19795 case BO_Add: {
19796 Result = LHSFX.add(RHSFX, &OpOverflow)
19797 .convert(ResultFXSema, &ConversionOverflow);
19798 break;
19799 }
19800 case BO_Sub: {
19801 Result = LHSFX.sub(RHSFX, &OpOverflow)
19802 .convert(ResultFXSema, &ConversionOverflow);
19803 break;
19804 }
19805 case BO_Mul: {
19806 Result = LHSFX.mul(RHSFX, &OpOverflow)
19807 .convert(ResultFXSema, &ConversionOverflow);
19808 break;
19809 }
19810 case BO_Div: {
19811 if (RHSFX.getValue() == 0) {
19812 Info.FFDiag(E, diag::note_expr_divide_by_zero);
19813 return false;
19814 }
19815 Result = LHSFX.div(RHSFX, &OpOverflow)
19816 .convert(ResultFXSema, &ConversionOverflow);
19817 break;
19818 }
19819 case BO_Shl:
19820 case BO_Shr: {
19821 FixedPointSemantics LHSSema = LHSFX.getSemantics();
19822 llvm::APSInt RHSVal = RHSFX.getValue();
19823
19824 unsigned ShiftBW =
19825 LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding();
19826 unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1);
19827 // Embedded-C 4.1.6.2.2:
19828 // The right operand must be nonnegative and less than the total number
19829 // of (nonpadding) bits of the fixed-point operand ...
19830 if (RHSVal.isNegative())
19831 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal;
19832 else if (Amt != RHSVal)
19833 Info.CCEDiag(E, diag::note_constexpr_large_shift)
19834 << RHSVal << E->getType() << ShiftBW;
19835
19836 if (E->getOpcode() == BO_Shl)
19837 Result = LHSFX.shl(Amt, &OpOverflow);
19838 else
19839 Result = LHSFX.shr(Amt, &OpOverflow);
19840 break;
19841 }
19842 default:
19843 return false;
19844 }
19845 if (OpOverflow || ConversionOverflow) {
19846 if (Info.checkingForUndefinedBehavior())
19847 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
19848 diag::warn_fixedpoint_constant_overflow)
19849 << Result.toString() << E->getType();
19850 if (!HandleOverflow(Info, E, Result, E->getType()))
19851 return false;
19852 }
19853 return Success(Result, E);
19854}
19855
19856//===----------------------------------------------------------------------===//
19857// Float Evaluation
19858//===----------------------------------------------------------------------===//
19859
19860namespace {
19861class FloatExprEvaluator
19862 : public ExprEvaluatorBase<FloatExprEvaluator> {
19863 APFloat &Result;
19864public:
19865 FloatExprEvaluator(EvalInfo &info, APFloat &result)
19866 : ExprEvaluatorBaseTy(info), Result(result) {}
19867
19868 bool Success(const APValue &V, const Expr *e) {
19869 Result = V.getFloat();
19870 return true;
19871 }
19872
19873 bool ZeroInitialization(const Expr *E) {
19874 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
19875 return true;
19876 }
19877
19878 bool VisitCallExpr(const CallExpr *E);
19879
19880 bool VisitUnaryOperator(const UnaryOperator *E);
19881 bool VisitBinaryOperator(const BinaryOperator *E);
19882 bool VisitFloatingLiteral(const FloatingLiteral *E);
19883 bool VisitCastExpr(const CastExpr *E);
19884
19885 bool VisitUnaryReal(const UnaryOperator *E);
19886 bool VisitUnaryImag(const UnaryOperator *E);
19887
19888 // FIXME: Missing: array subscript of vector, member of vector
19889};
19890} // end anonymous namespace
19891
19892static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
19893 assert(!E->isValueDependent());
19894 assert(E->isPRValue() && E->getType()->isRealFloatingType());
19895 return FloatExprEvaluator(Info, Result).Visit(E);
19896}
19897
19898static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
19899 QualType ResultTy,
19900 const Expr *Arg,
19901 bool SNaN,
19902 llvm::APFloat &Result) {
19903 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
19904 if (!S) return false;
19905
19906 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
19907
19908 llvm::APInt fill;
19909
19910 // Treat empty strings as if they were zero.
19911 if (S->getString().empty())
19912 fill = llvm::APInt(32, 0);
19913 else if (S->getString().getAsInteger(0, fill))
19914 return false;
19915
19916 if (Context.getTargetInfo().isNan2008()) {
19917 if (SNaN)
19918 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
19919 else
19920 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
19921 } else {
19922 // Prior to IEEE 754-2008, architectures were allowed to choose whether
19923 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
19924 // a different encoding to what became a standard in 2008, and for pre-
19925 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
19926 // sNaN. This is now known as "legacy NaN" encoding.
19927 if (SNaN)
19928 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
19929 else
19930 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
19931 }
19932
19933 return true;
19934}
19935
19936bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
19937 if (!IsConstantEvaluatedBuiltinCall(E))
19938 return ExprEvaluatorBaseTy::VisitCallExpr(E);
19939
19940 switch (E->getBuiltinCallee()) {
19941 default:
19942 return false;
19943
19944 case Builtin::BI__builtin_huge_val:
19945 case Builtin::BI__builtin_huge_valf:
19946 case Builtin::BI__builtin_huge_vall:
19947 case Builtin::BI__builtin_huge_valf16:
19948 case Builtin::BI__builtin_huge_valf128:
19949 case Builtin::BI__builtin_inf:
19950 case Builtin::BI__builtin_inff:
19951 case Builtin::BI__builtin_infl:
19952 case Builtin::BI__builtin_inff16:
19953 case Builtin::BI__builtin_inff128: {
19954 const llvm::fltSemantics &Sem =
19955 Info.Ctx.getFloatTypeSemantics(E->getType());
19956 Result = llvm::APFloat::getInf(Sem);
19957 return true;
19958 }
19959
19960 case Builtin::BI__builtin_nans:
19961 case Builtin::BI__builtin_nansf:
19962 case Builtin::BI__builtin_nansl:
19963 case Builtin::BI__builtin_nansf16:
19964 case Builtin::BI__builtin_nansf128:
19965 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
19966 true, Result))
19967 return Error(E);
19968 return true;
19969
19970 case Builtin::BI__builtin_nan:
19971 case Builtin::BI__builtin_nanf:
19972 case Builtin::BI__builtin_nanl:
19973 case Builtin::BI__builtin_nanf16:
19974 case Builtin::BI__builtin_nanf128:
19975 // If this is __builtin_nan() turn this into a nan, otherwise we
19976 // can't constant fold it.
19977 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
19978 false, Result))
19979 return Error(E);
19980 return true;
19981
19982 case Builtin::BI__builtin_elementwise_abs:
19983 case Builtin::BI__builtin_fabs:
19984 case Builtin::BI__builtin_fabsf:
19985 case Builtin::BI__builtin_fabsl:
19986 case Builtin::BI__builtin_fabsf128:
19987 // The C standard says "fabs raises no floating-point exceptions,
19988 // even if x is a signaling NaN. The returned value is independent of
19989 // the current rounding direction mode." Therefore constant folding can
19990 // proceed without regard to the floating point settings.
19991 // Reference, WG14 N2478 F.10.4.3
19992 if (!EvaluateFloat(E->getArg(0), Result, Info))
19993 return false;
19994
19995 if (Result.isNegative())
19996 Result.changeSign();
19997 return true;
19998
19999 case Builtin::BI__arithmetic_fence:
20000 return EvaluateFloat(E->getArg(0), Result, Info);
20001
20002 // FIXME: Builtin::BI__builtin_powi
20003 // FIXME: Builtin::BI__builtin_powif
20004 // FIXME: Builtin::BI__builtin_powil
20005
20006 case Builtin::BI__builtin_copysign:
20007 case Builtin::BI__builtin_copysignf:
20008 case Builtin::BI__builtin_copysignl:
20009 case Builtin::BI__builtin_copysignf128: {
20010 APFloat RHS(0.);
20011 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
20012 !EvaluateFloat(E->getArg(1), RHS, Info))
20013 return false;
20014 Result.copySign(RHS);
20015 return true;
20016 }
20017
20018 case Builtin::BI__builtin_fmax:
20019 case Builtin::BI__builtin_fmaxf:
20020 case Builtin::BI__builtin_fmaxl:
20021 case Builtin::BI__builtin_fmaxf16:
20022 case Builtin::BI__builtin_fmaxf128: {
20023 APFloat RHS(0.);
20024 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
20025 !EvaluateFloat(E->getArg(1), RHS, Info))
20026 return false;
20027 Result = maxnum(Result, RHS);
20028 return true;
20029 }
20030
20031 case Builtin::BI__builtin_fmin:
20032 case Builtin::BI__builtin_fminf:
20033 case Builtin::BI__builtin_fminl:
20034 case Builtin::BI__builtin_fminf16:
20035 case Builtin::BI__builtin_fminf128: {
20036 APFloat RHS(0.);
20037 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
20038 !EvaluateFloat(E->getArg(1), RHS, Info))
20039 return false;
20040 Result = minnum(Result, RHS);
20041 return true;
20042 }
20043
20044 case Builtin::BI__builtin_fmaximum_num:
20045 case Builtin::BI__builtin_fmaximum_numf:
20046 case Builtin::BI__builtin_fmaximum_numl:
20047 case Builtin::BI__builtin_fmaximum_numf16:
20048 case Builtin::BI__builtin_fmaximum_numf128: {
20049 APFloat RHS(0.);
20050 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
20051 !EvaluateFloat(E->getArg(1), RHS, Info))
20052 return false;
20053 Result = maximumnum(Result, RHS);
20054 return true;
20055 }
20056
20057 case Builtin::BI__builtin_fminimum_num:
20058 case Builtin::BI__builtin_fminimum_numf:
20059 case Builtin::BI__builtin_fminimum_numl:
20060 case Builtin::BI__builtin_fminimum_numf16:
20061 case Builtin::BI__builtin_fminimum_numf128: {
20062 APFloat RHS(0.);
20063 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
20064 !EvaluateFloat(E->getArg(1), RHS, Info))
20065 return false;
20066 Result = minimumnum(Result, RHS);
20067 return true;
20068 }
20069
20070 case Builtin::BI__builtin_elementwise_fma: {
20071 if (!E->getArg(0)->isPRValue() || !E->getArg(1)->isPRValue() ||
20072 !E->getArg(2)->isPRValue()) {
20073 return false;
20074 }
20075 APFloat SourceY(0.), SourceZ(0.);
20076 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
20077 !EvaluateFloat(E->getArg(1), SourceY, Info) ||
20078 !EvaluateFloat(E->getArg(2), SourceZ, Info))
20079 return false;
20080 llvm::RoundingMode RM = getActiveRoundingMode(getEvalInfo(), E);
20081 (void)Result.fusedMultiplyAdd(SourceY, SourceZ, RM);
20082 return true;
20083 }
20084
20085 case clang::X86::BI__builtin_ia32_vec_ext_v4sf: {
20086 APValue Vec;
20087 APSInt IdxAPS;
20088 if (!EvaluateVector(E->getArg(0), Vec, Info) ||
20089 !EvaluateInteger(E->getArg(1), IdxAPS, Info))
20090 return false;
20091 unsigned N = Vec.getVectorLength();
20092 unsigned Idx = static_cast<unsigned>(IdxAPS.getZExtValue() & (N - 1));
20093 return Success(Vec.getVectorElt(Idx), E);
20094 }
20095 }
20096}
20097
20098bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
20099 if (E->getSubExpr()->getType()->isAnyComplexType()) {
20100 ComplexValue CV;
20101 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
20102 return false;
20103 Result = CV.FloatReal;
20104 return true;
20105 }
20106
20107 return Visit(E->getSubExpr());
20108}
20109
20110bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
20111 if (E->getSubExpr()->getType()->isAnyComplexType()) {
20112 ComplexValue CV;
20113 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
20114 return false;
20115 Result = CV.FloatImag;
20116 return true;
20117 }
20118
20119 VisitIgnoredValue(E->getSubExpr());
20120 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
20121 Result = llvm::APFloat::getZero(Sem);
20122 return true;
20123}
20124
20125bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
20126 switch (E->getOpcode()) {
20127 default: return Error(E);
20128 case UO_Plus:
20129 return EvaluateFloat(E->getSubExpr(), Result, Info);
20130 case UO_Minus:
20131 // In C standard, WG14 N2478 F.3 p4
20132 // "the unary - raises no floating point exceptions,
20133 // even if the operand is signalling."
20134 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
20135 return false;
20136 Result.changeSign();
20137 return true;
20138 }
20139}
20140
20141bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
20142 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
20143 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
20144
20145 APFloat RHS(0.0);
20146 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
20147 if (!LHSOK && !Info.noteFailure())
20148 return false;
20149 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
20150 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
20151}
20152
20153bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
20154 Result = E->getValue();
20155 return true;
20156}
20157
20158bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
20159 const Expr* SubExpr = E->getSubExpr();
20160
20161 switch (E->getCastKind()) {
20162 default:
20163 return ExprEvaluatorBaseTy::VisitCastExpr(E);
20164
20165 case CK_HLSLAggregateSplatCast:
20166 llvm_unreachable("invalid cast kind for floating value");
20167
20168 case CK_IntegralToFloating: {
20169 APSInt IntResult;
20170 const FPOptions FPO = E->getFPFeaturesInEffect(
20171 Info.Ctx.getLangOpts());
20172 return EvaluateInteger(SubExpr, IntResult, Info) &&
20173 HandleIntToFloatCast(Info, E, FPO, SubExpr->getType(),
20174 IntResult, E->getType(), Result);
20175 }
20176
20177 case CK_FixedPointToFloating: {
20178 APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
20179 if (!EvaluateFixedPoint(SubExpr, FixResult, Info))
20180 return false;
20181 Result =
20182 FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->getType()));
20183 return true;
20184 }
20185
20186 case CK_FloatingCast: {
20187 if (!Visit(SubExpr))
20188 return false;
20189 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
20190 Result);
20191 }
20192
20193 case CK_FloatingComplexToReal: {
20194 ComplexValue V;
20195 if (!EvaluateComplex(SubExpr, V, Info))
20196 return false;
20197 Result = V.getComplexFloatReal();
20198 return true;
20199 }
20200 case CK_HLSLVectorTruncation: {
20201 APValue Val;
20202 if (!EvaluateVector(SubExpr, Val, Info))
20203 return Error(E);
20204 return Success(Val.getVectorElt(0), E);
20205 }
20206 case CK_HLSLMatrixTruncation: {
20207 APValue Val;
20208 if (!EvaluateMatrix(SubExpr, Val, Info))
20209 return Error(E);
20210 return Success(Val.getMatrixElt(0, 0), E);
20211 }
20212 case CK_HLSLElementwiseCast: {
20213 SmallVector<APValue> SrcVals;
20214 SmallVector<QualType> SrcTypes;
20215
20216 if (!hlslElementwiseCastHelper(Info, SubExpr, E->getType(), SrcVals,
20217 SrcTypes))
20218 return false;
20219 APValue Val;
20220
20221 // cast our single element
20222 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
20223 APValue ResultVal;
20224 if (!handleScalarCast(Info, FPO, E, SrcTypes[0], E->getType(), SrcVals[0],
20225 ResultVal))
20226 return false;
20227 return Success(ResultVal, E);
20228 }
20229 }
20230}
20231
20232//===----------------------------------------------------------------------===//
20233// Complex Evaluation (for float and integer)
20234//===----------------------------------------------------------------------===//
20235
20236namespace {
20237class ComplexExprEvaluator
20238 : public ExprEvaluatorBase<ComplexExprEvaluator> {
20239 ComplexValue &Result;
20240
20241public:
20242 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
20243 : ExprEvaluatorBaseTy(info), Result(Result) {}
20244
20245 bool Success(const APValue &V, const Expr *e) {
20246 Result.setFrom(V);
20247 return true;
20248 }
20249
20250 bool ZeroInitialization(const Expr *E);
20251
20252 //===--------------------------------------------------------------------===//
20253 // Visitor Methods
20254 //===--------------------------------------------------------------------===//
20255
20256 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
20257 bool VisitCastExpr(const CastExpr *E);
20258 bool VisitBinaryOperator(const BinaryOperator *E);
20259 bool VisitUnaryOperator(const UnaryOperator *E);
20260 bool VisitInitListExpr(const InitListExpr *E);
20261 bool VisitCallExpr(const CallExpr *E);
20262};
20263} // end anonymous namespace
20264
20265static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
20266 EvalInfo &Info) {
20267 assert(!E->isValueDependent());
20268 assert(E->isPRValue() && E->getType()->isAnyComplexType());
20269 return ComplexExprEvaluator(Info, Result).Visit(E);
20270}
20271
20272bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
20273 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
20274 if (ElemTy->isRealFloatingType()) {
20275 Result.makeComplexFloat();
20276 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
20277 Result.FloatReal = Zero;
20278 Result.FloatImag = Zero;
20279 } else {
20280 Result.makeComplexInt();
20281 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
20282 Result.IntReal = Zero;
20283 Result.IntImag = Zero;
20284 }
20285 return true;
20286}
20287
20288bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
20289 const Expr* SubExpr = E->getSubExpr();
20290
20291 if (SubExpr->getType()->isRealFloatingType()) {
20292 Result.makeComplexFloat();
20293 APFloat &Imag = Result.FloatImag;
20294 if (!EvaluateFloat(SubExpr, Imag, Info))
20295 return false;
20296
20297 Result.FloatReal = APFloat(Imag.getSemantics());
20298 return true;
20299 } else {
20300 assert(SubExpr->getType()->isIntegerType() &&
20301 "Unexpected imaginary literal.");
20302
20303 Result.makeComplexInt();
20304 APSInt &Imag = Result.IntImag;
20305 if (!EvaluateInteger(SubExpr, Imag, Info))
20306 return false;
20307
20308 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
20309 return true;
20310 }
20311}
20312
20313bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
20314
20315 switch (E->getCastKind()) {
20316 case CK_BitCast:
20317 case CK_BaseToDerived:
20318 case CK_DerivedToBase:
20319 case CK_UncheckedDerivedToBase:
20320 case CK_Dynamic:
20321 case CK_ToUnion:
20322 case CK_ArrayToPointerDecay:
20323 case CK_FunctionToPointerDecay:
20324 case CK_NullToPointer:
20325 case CK_NullToMemberPointer:
20326 case CK_BaseToDerivedMemberPointer:
20327 case CK_DerivedToBaseMemberPointer:
20328 case CK_MemberPointerToBoolean:
20329 case CK_ReinterpretMemberPointer:
20330 case CK_ConstructorConversion:
20331 case CK_IntegralToPointer:
20332 case CK_PointerToIntegral:
20333 case CK_PointerToBoolean:
20334 case CK_ToVoid:
20335 case CK_VectorSplat:
20336 case CK_IntegralCast:
20337 case CK_BooleanToSignedIntegral:
20338 case CK_IntegralToBoolean:
20339 case CK_IntegralToFloating:
20340 case CK_FloatingToIntegral:
20341 case CK_FloatingToBoolean:
20342 case CK_FloatingCast:
20343 case CK_CPointerToObjCPointerCast:
20344 case CK_BlockPointerToObjCPointerCast:
20345 case CK_AnyPointerToBlockPointerCast:
20346 case CK_ObjCObjectLValueCast:
20347 case CK_FloatingComplexToReal:
20348 case CK_FloatingComplexToBoolean:
20349 case CK_IntegralComplexToReal:
20350 case CK_IntegralComplexToBoolean:
20351 case CK_ARCProduceObject:
20352 case CK_ARCConsumeObject:
20353 case CK_ARCReclaimReturnedObject:
20354 case CK_ARCExtendBlockObject:
20355 case CK_CopyAndAutoreleaseBlockObject:
20356 case CK_BuiltinFnToFnPtr:
20357 case CK_ZeroToOCLOpaqueType:
20358 case CK_NonAtomicToAtomic:
20359 case CK_AddressSpaceConversion:
20360 case CK_IntToOCLSampler:
20361 case CK_FloatingToFixedPoint:
20362 case CK_FixedPointToFloating:
20363 case CK_FixedPointCast:
20364 case CK_FixedPointToBoolean:
20365 case CK_FixedPointToIntegral:
20366 case CK_IntegralToFixedPoint:
20367 case CK_MatrixCast:
20368 case CK_HLSLVectorTruncation:
20369 case CK_HLSLMatrixTruncation:
20370 case CK_HLSLElementwiseCast:
20371 case CK_HLSLAggregateSplatCast:
20372 llvm_unreachable("invalid cast kind for complex value");
20373
20374 case CK_LValueToRValue:
20375 case CK_AtomicToNonAtomic:
20376 case CK_NoOp:
20377 case CK_LValueToRValueBitCast:
20378 case CK_HLSLArrayRValue:
20379 return ExprEvaluatorBaseTy::VisitCastExpr(E);
20380
20381 case CK_Dependent:
20382 case CK_LValueBitCast:
20383 case CK_UserDefinedConversion:
20384 return Error(E);
20385
20386 case CK_FloatingRealToComplex: {
20387 APFloat &Real = Result.FloatReal;
20388 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
20389 return false;
20390
20391 Result.makeComplexFloat();
20392 Result.FloatImag = APFloat(Real.getSemantics());
20393 return true;
20394 }
20395
20396 case CK_FloatingComplexCast: {
20397 if (!Visit(E->getSubExpr()))
20398 return false;
20399
20400 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
20401 QualType From
20402 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
20403
20404 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
20405 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
20406 }
20407
20408 case CK_FloatingComplexToIntegralComplex: {
20409 if (!Visit(E->getSubExpr()))
20410 return false;
20411
20412 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
20413 QualType From
20414 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
20415 Result.makeComplexInt();
20416 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
20417 To, Result.IntReal) &&
20418 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
20419 To, Result.IntImag);
20420 }
20421
20422 case CK_IntegralRealToComplex: {
20423 APSInt &Real = Result.IntReal;
20424 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
20425 return false;
20426
20427 Result.makeComplexInt();
20428 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
20429 return true;
20430 }
20431
20432 case CK_IntegralComplexCast: {
20433 if (!Visit(E->getSubExpr()))
20434 return false;
20435
20436 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
20437 QualType From
20438 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
20439
20440 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
20441 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
20442 return true;
20443 }
20444
20445 case CK_IntegralComplexToFloatingComplex: {
20446 if (!Visit(E->getSubExpr()))
20447 return false;
20448
20449 const FPOptions FPO = E->getFPFeaturesInEffect(
20450 Info.Ctx.getLangOpts());
20451 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
20452 QualType From
20453 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
20454 Result.makeComplexFloat();
20455 return HandleIntToFloatCast(Info, E, FPO, From, Result.IntReal,
20456 To, Result.FloatReal) &&
20457 HandleIntToFloatCast(Info, E, FPO, From, Result.IntImag,
20458 To, Result.FloatImag);
20459 }
20460 }
20461
20462 llvm_unreachable("unknown cast resulting in complex value");
20463}
20464
20466 // Lookup Table for Multiplicative Inverse in GF(2^8)
20467 const uint8_t GFInv[256] = {
20468 0x00, 0x01, 0x8d, 0xf6, 0xcb, 0x52, 0x7b, 0xd1, 0xe8, 0x4f, 0x29, 0xc0,
20469 0xb0, 0xe1, 0xe5, 0xc7, 0x74, 0xb4, 0xaa, 0x4b, 0x99, 0x2b, 0x60, 0x5f,
20470 0x58, 0x3f, 0xfd, 0xcc, 0xff, 0x40, 0xee, 0xb2, 0x3a, 0x6e, 0x5a, 0xf1,
20471 0x55, 0x4d, 0xa8, 0xc9, 0xc1, 0x0a, 0x98, 0x15, 0x30, 0x44, 0xa2, 0xc2,
20472 0x2c, 0x45, 0x92, 0x6c, 0xf3, 0x39, 0x66, 0x42, 0xf2, 0x35, 0x20, 0x6f,
20473 0x77, 0xbb, 0x59, 0x19, 0x1d, 0xfe, 0x37, 0x67, 0x2d, 0x31, 0xf5, 0x69,
20474 0xa7, 0x64, 0xab, 0x13, 0x54, 0x25, 0xe9, 0x09, 0xed, 0x5c, 0x05, 0xca,
20475 0x4c, 0x24, 0x87, 0xbf, 0x18, 0x3e, 0x22, 0xf0, 0x51, 0xec, 0x61, 0x17,
20476 0x16, 0x5e, 0xaf, 0xd3, 0x49, 0xa6, 0x36, 0x43, 0xf4, 0x47, 0x91, 0xdf,
20477 0x33, 0x93, 0x21, 0x3b, 0x79, 0xb7, 0x97, 0x85, 0x10, 0xb5, 0xba, 0x3c,
20478 0xb6, 0x70, 0xd0, 0x06, 0xa1, 0xfa, 0x81, 0x82, 0x83, 0x7e, 0x7f, 0x80,
20479 0x96, 0x73, 0xbe, 0x56, 0x9b, 0x9e, 0x95, 0xd9, 0xf7, 0x02, 0xb9, 0xa4,
20480 0xde, 0x6a, 0x32, 0x6d, 0xd8, 0x8a, 0x84, 0x72, 0x2a, 0x14, 0x9f, 0x88,
20481 0xf9, 0xdc, 0x89, 0x9a, 0xfb, 0x7c, 0x2e, 0xc3, 0x8f, 0xb8, 0x65, 0x48,
20482 0x26, 0xc8, 0x12, 0x4a, 0xce, 0xe7, 0xd2, 0x62, 0x0c, 0xe0, 0x1f, 0xef,
20483 0x11, 0x75, 0x78, 0x71, 0xa5, 0x8e, 0x76, 0x3d, 0xbd, 0xbc, 0x86, 0x57,
20484 0x0b, 0x28, 0x2f, 0xa3, 0xda, 0xd4, 0xe4, 0x0f, 0xa9, 0x27, 0x53, 0x04,
20485 0x1b, 0xfc, 0xac, 0xe6, 0x7a, 0x07, 0xae, 0x63, 0xc5, 0xdb, 0xe2, 0xea,
20486 0x94, 0x8b, 0xc4, 0xd5, 0x9d, 0xf8, 0x90, 0x6b, 0xb1, 0x0d, 0xd6, 0xeb,
20487 0xc6, 0x0e, 0xcf, 0xad, 0x08, 0x4e, 0xd7, 0xe3, 0x5d, 0x50, 0x1e, 0xb3,
20488 0x5b, 0x23, 0x38, 0x34, 0x68, 0x46, 0x03, 0x8c, 0xdd, 0x9c, 0x7d, 0xa0,
20489 0xcd, 0x1a, 0x41, 0x1c};
20490
20491 return GFInv[Byte];
20492}
20493
20494uint8_t GFNIAffine(uint8_t XByte, const APInt &AQword, const APSInt &Imm,
20495 bool Inverse) {
20496 unsigned NumBitsInByte = 8;
20497 // Computing the affine transformation
20498 uint8_t RetByte = 0;
20499 for (uint32_t BitIdx = 0; BitIdx != NumBitsInByte; ++BitIdx) {
20500 uint8_t AByte =
20501 AQword.lshr((7 - static_cast<int32_t>(BitIdx)) * NumBitsInByte)
20502 .getLoBits(8)
20503 .getZExtValue();
20504 uint8_t Product;
20505 if (Inverse) {
20506 Product = AByte & GFNIMultiplicativeInverse(XByte);
20507 } else {
20508 Product = AByte & XByte;
20509 }
20510 uint8_t Parity = 0;
20511
20512 // Dot product in GF(2) uses XOR instead of addition
20513 for (unsigned PBitIdx = 0; PBitIdx != NumBitsInByte; ++PBitIdx) {
20514 Parity = Parity ^ ((Product >> PBitIdx) & 0x1);
20515 }
20516
20517 uint8_t Temp = Imm[BitIdx] ? 1 : 0;
20518 RetByte |= (Temp ^ Parity) << BitIdx;
20519 }
20520 return RetByte;
20521}
20522
20524 // Multiplying two polynomials of degree 7
20525 // Polynomial of degree 7
20526 // x^7 + x^6 + x^5 + x^4 + x^3 + x^2 + x + 1
20527 uint16_t TWord = 0;
20528 unsigned NumBitsInByte = 8;
20529 for (unsigned BitIdx = 0; BitIdx != NumBitsInByte; ++BitIdx) {
20530 if ((BByte >> BitIdx) & 0x1) {
20531 TWord = TWord ^ (AByte << BitIdx);
20532 }
20533 }
20534
20535 // When multiplying two polynomials of degree 7
20536 // results in a polynomial of degree 14
20537 // so the result has to be reduced to 7
20538 // Reduction polynomial is x^8 + x^4 + x^3 + x + 1 i.e. 0x11B
20539 for (int32_t BitIdx = 14; BitIdx > 7; --BitIdx) {
20540 if ((TWord >> BitIdx) & 0x1) {
20541 TWord = TWord ^ (0x11B << (BitIdx - 8));
20542 }
20543 }
20544 return (TWord & 0xFF);
20545}
20546
20547void HandleComplexComplexMul(APFloat A, APFloat B, APFloat C, APFloat D,
20548 APFloat &ResR, APFloat &ResI) {
20549 // This is an implementation of complex multiplication according to the
20550 // constraints laid out in C11 Annex G. The implementation uses the
20551 // following naming scheme:
20552 // (a + ib) * (c + id)
20553
20554 APFloat AC = A * C;
20555 APFloat BD = B * D;
20556 APFloat AD = A * D;
20557 APFloat BC = B * C;
20558 ResR = AC - BD;
20559 ResI = AD + BC;
20560 if (ResR.isNaN() && ResI.isNaN()) {
20561 bool Recalc = false;
20562 if (A.isInfinity() || B.isInfinity()) {
20563 A = APFloat::copySign(APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0),
20564 A);
20565 B = APFloat::copySign(APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0),
20566 B);
20567 if (C.isNaN())
20568 C = APFloat::copySign(APFloat(C.getSemantics()), C);
20569 if (D.isNaN())
20570 D = APFloat::copySign(APFloat(D.getSemantics()), D);
20571 Recalc = true;
20572 }
20573 if (C.isInfinity() || D.isInfinity()) {
20574 C = APFloat::copySign(APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0),
20575 C);
20576 D = APFloat::copySign(APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0),
20577 D);
20578 if (A.isNaN())
20579 A = APFloat::copySign(APFloat(A.getSemantics()), A);
20580 if (B.isNaN())
20581 B = APFloat::copySign(APFloat(B.getSemantics()), B);
20582 Recalc = true;
20583 }
20584 if (!Recalc && (AC.isInfinity() || BD.isInfinity() || AD.isInfinity() ||
20585 BC.isInfinity())) {
20586 if (A.isNaN())
20587 A = APFloat::copySign(APFloat(A.getSemantics()), A);
20588 if (B.isNaN())
20589 B = APFloat::copySign(APFloat(B.getSemantics()), B);
20590 if (C.isNaN())
20591 C = APFloat::copySign(APFloat(C.getSemantics()), C);
20592 if (D.isNaN())
20593 D = APFloat::copySign(APFloat(D.getSemantics()), D);
20594 Recalc = true;
20595 }
20596 if (Recalc) {
20597 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
20598 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
20599 }
20600 }
20601}
20602
20603void HandleComplexComplexDiv(APFloat A, APFloat B, APFloat C, APFloat D,
20604 APFloat &ResR, APFloat &ResI) {
20605 // This is an implementation of complex division according to the
20606 // constraints laid out in C11 Annex G. The implementation uses the
20607 // following naming scheme:
20608 // (a + ib) / (c + id)
20609
20610 int DenomLogB = 0;
20611 APFloat MaxCD = maxnum(abs(C), abs(D));
20612 if (MaxCD.isFinite()) {
20613 DenomLogB = ilogb(MaxCD);
20614 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
20615 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
20616 }
20617 APFloat Denom = C * C + D * D;
20618 ResR =
20619 scalbn((A * C + B * D) / Denom, -DenomLogB, APFloat::rmNearestTiesToEven);
20620 ResI =
20621 scalbn((B * C - A * D) / Denom, -DenomLogB, APFloat::rmNearestTiesToEven);
20622 if (ResR.isNaN() && ResI.isNaN()) {
20623 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
20624 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
20625 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
20626 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
20627 D.isFinite()) {
20628 A = APFloat::copySign(APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0),
20629 A);
20630 B = APFloat::copySign(APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0),
20631 B);
20632 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
20633 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
20634 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
20635 C = APFloat::copySign(APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0),
20636 C);
20637 D = APFloat::copySign(APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0),
20638 D);
20639 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
20640 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
20641 }
20642 }
20643}
20644
20646 // Normalize shift amount to [0, BitWidth) range to match runtime behavior
20647 APSInt NormAmt = Amount;
20648 unsigned BitWidth = Value.getBitWidth();
20649 unsigned AmtBitWidth = NormAmt.getBitWidth();
20650 if (BitWidth == 1) {
20651 // Rotating a 1-bit value is always a no-op
20652 NormAmt = APSInt(APInt(AmtBitWidth, 0), NormAmt.isUnsigned());
20653 } else if (BitWidth == 2) {
20654 // For 2-bit values: rotation amount is 0 or 1 based on
20655 // whether the amount is even or odd. We can't use srem here because
20656 // the divisor (2) would be misinterpreted as -2 in 2-bit signed arithmetic.
20657 NormAmt =
20658 APSInt(APInt(AmtBitWidth, NormAmt[0] ? 1 : 0), NormAmt.isUnsigned());
20659 } else {
20660 APInt Divisor;
20661 if (AmtBitWidth > BitWidth) {
20662 Divisor = llvm::APInt(AmtBitWidth, BitWidth);
20663 } else {
20664 Divisor = llvm::APInt(BitWidth, BitWidth);
20665 if (AmtBitWidth < BitWidth) {
20666 NormAmt = NormAmt.extend(BitWidth);
20667 }
20668 }
20669
20670 // Normalize to [0, BitWidth)
20671 if (NormAmt.isSigned()) {
20672 NormAmt = APSInt(NormAmt.srem(Divisor), /*isUnsigned=*/false);
20673 if (NormAmt.isNegative()) {
20674 APSInt SignedDivisor(Divisor, /*isUnsigned=*/false);
20675 NormAmt += SignedDivisor;
20676 }
20677 } else {
20678 NormAmt = APSInt(NormAmt.urem(Divisor), /*isUnsigned=*/true);
20679 }
20680 }
20681
20682 return NormAmt;
20683}
20684
20685bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
20686 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
20687 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
20688
20689 // Track whether the LHS or RHS is real at the type system level. When this is
20690 // the case we can simplify our evaluation strategy.
20691 bool LHSReal = false, RHSReal = false;
20692
20693 bool LHSOK;
20694 if (E->getLHS()->getType()->isRealFloatingType()) {
20695 LHSReal = true;
20696 APFloat &Real = Result.FloatReal;
20697 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
20698 if (LHSOK) {
20699 Result.makeComplexFloat();
20700 Result.FloatImag = APFloat(Real.getSemantics());
20701 }
20702 } else {
20703 LHSOK = Visit(E->getLHS());
20704 }
20705 if (!LHSOK && !Info.noteFailure())
20706 return false;
20707
20708 ComplexValue RHS;
20709 if (E->getRHS()->getType()->isRealFloatingType()) {
20710 RHSReal = true;
20711 APFloat &Real = RHS.FloatReal;
20712 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
20713 return false;
20714 RHS.makeComplexFloat();
20715 RHS.FloatImag = APFloat(Real.getSemantics());
20716 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
20717 return false;
20718
20719 assert(!(LHSReal && RHSReal) &&
20720 "Cannot have both operands of a complex operation be real.");
20721 switch (E->getOpcode()) {
20722 default: return Error(E);
20723 case BO_Add:
20724 if (Result.isComplexFloat()) {
20725 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
20726 APFloat::rmNearestTiesToEven);
20727 if (LHSReal)
20728 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
20729 else if (!RHSReal)
20730 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
20731 APFloat::rmNearestTiesToEven);
20732 } else {
20733 Result.getComplexIntReal() += RHS.getComplexIntReal();
20734 Result.getComplexIntImag() += RHS.getComplexIntImag();
20735 }
20736 break;
20737 case BO_Sub:
20738 if (Result.isComplexFloat()) {
20739 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
20740 APFloat::rmNearestTiesToEven);
20741 if (LHSReal) {
20742 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
20743 Result.getComplexFloatImag().changeSign();
20744 } else if (!RHSReal) {
20745 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
20746 APFloat::rmNearestTiesToEven);
20747 }
20748 } else {
20749 Result.getComplexIntReal() -= RHS.getComplexIntReal();
20750 Result.getComplexIntImag() -= RHS.getComplexIntImag();
20751 }
20752 break;
20753 case BO_Mul:
20754 if (Result.isComplexFloat()) {
20755 // This is an implementation of complex multiplication according to the
20756 // constraints laid out in C11 Annex G. The implementation uses the
20757 // following naming scheme:
20758 // (a + ib) * (c + id)
20759 ComplexValue LHS = Result;
20760 APFloat &A = LHS.getComplexFloatReal();
20761 APFloat &B = LHS.getComplexFloatImag();
20762 APFloat &C = RHS.getComplexFloatReal();
20763 APFloat &D = RHS.getComplexFloatImag();
20764 APFloat &ResR = Result.getComplexFloatReal();
20765 APFloat &ResI = Result.getComplexFloatImag();
20766 if (LHSReal) {
20767 assert(!RHSReal && "Cannot have two real operands for a complex op!");
20768 ResR = A;
20769 ResI = A;
20770 // ResR = A * C;
20771 // ResI = A * D;
20772 if (!handleFloatFloatBinOp(Info, E, ResR, BO_Mul, C) ||
20773 !handleFloatFloatBinOp(Info, E, ResI, BO_Mul, D))
20774 return false;
20775 } else if (RHSReal) {
20776 // ResR = C * A;
20777 // ResI = C * B;
20778 ResR = C;
20779 ResI = C;
20780 if (!handleFloatFloatBinOp(Info, E, ResR, BO_Mul, A) ||
20781 !handleFloatFloatBinOp(Info, E, ResI, BO_Mul, B))
20782 return false;
20783 } else {
20784 HandleComplexComplexMul(A, B, C, D, ResR, ResI);
20785 }
20786 } else {
20787 ComplexValue LHS = Result;
20788 Result.getComplexIntReal() =
20789 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
20790 LHS.getComplexIntImag() * RHS.getComplexIntImag());
20791 Result.getComplexIntImag() =
20792 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
20793 LHS.getComplexIntImag() * RHS.getComplexIntReal());
20794 }
20795 break;
20796 case BO_Div:
20797 if (Result.isComplexFloat()) {
20798 // This is an implementation of complex division according to the
20799 // constraints laid out in C11 Annex G. The implementation uses the
20800 // following naming scheme:
20801 // (a + ib) / (c + id)
20802 ComplexValue LHS = Result;
20803 APFloat &A = LHS.getComplexFloatReal();
20804 APFloat &B = LHS.getComplexFloatImag();
20805 APFloat &C = RHS.getComplexFloatReal();
20806 APFloat &D = RHS.getComplexFloatImag();
20807 APFloat &ResR = Result.getComplexFloatReal();
20808 APFloat &ResI = Result.getComplexFloatImag();
20809 if (RHSReal) {
20810 ResR = A;
20811 ResI = B;
20812 // ResR = A / C;
20813 // ResI = B / C;
20814 if (!handleFloatFloatBinOp(Info, E, ResR, BO_Div, C) ||
20815 !handleFloatFloatBinOp(Info, E, ResI, BO_Div, C))
20816 return false;
20817 } else {
20818 if (LHSReal) {
20819 // No real optimizations we can do here, stub out with zero.
20820 B = APFloat::getZero(A.getSemantics());
20821 }
20822 HandleComplexComplexDiv(A, B, C, D, ResR, ResI);
20823 }
20824 } else {
20825 ComplexValue LHS = Result;
20826 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
20827 RHS.getComplexIntImag() * RHS.getComplexIntImag();
20828 if (Den.isZero())
20829 return Error(E, diag::note_expr_divide_by_zero);
20830
20831 Result.getComplexIntReal() =
20832 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
20833 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
20834 Result.getComplexIntImag() =
20835 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
20836 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
20837 }
20838 break;
20839 }
20840
20841 return true;
20842}
20843
20844bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
20845 // Get the operand value into 'Result'.
20846 if (!Visit(E->getSubExpr()))
20847 return false;
20848
20849 switch (E->getOpcode()) {
20850 default:
20851 return Error(E);
20852 case UO_Extension:
20853 return true;
20854 case UO_Plus:
20855 // The result is always just the subexpr.
20856 return true;
20857 case UO_Minus:
20858 if (Result.isComplexFloat()) {
20859 Result.getComplexFloatReal().changeSign();
20860 Result.getComplexFloatImag().changeSign();
20861 }
20862 else {
20863 Result.getComplexIntReal() = -Result.getComplexIntReal();
20864 Result.getComplexIntImag() = -Result.getComplexIntImag();
20865 }
20866 return true;
20867 case UO_Not:
20868 if (Result.isComplexFloat())
20869 Result.getComplexFloatImag().changeSign();
20870 else
20871 Result.getComplexIntImag() = -Result.getComplexIntImag();
20872 return true;
20873 }
20874}
20875
20876bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
20877 if (E->getNumInits() == 2) {
20878 if (E->getType()->isComplexType()) {
20879 Result.makeComplexFloat();
20880 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
20881 return false;
20882 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
20883 return false;
20884 } else {
20885 Result.makeComplexInt();
20886 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
20887 return false;
20888 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
20889 return false;
20890 }
20891 return true;
20892 }
20893 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
20894}
20895
20896bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) {
20897 if (!IsConstantEvaluatedBuiltinCall(E))
20898 return ExprEvaluatorBaseTy::VisitCallExpr(E);
20899
20900 switch (E->getBuiltinCallee()) {
20901 case Builtin::BI__builtin_complex:
20902 Result.makeComplexFloat();
20903 if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info))
20904 return false;
20905 if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info))
20906 return false;
20907 return true;
20908
20909 default:
20910 return false;
20911 }
20912}
20913
20914//===----------------------------------------------------------------------===//
20915// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
20916// implicit conversion.
20917//===----------------------------------------------------------------------===//
20918
20919namespace {
20920class AtomicExprEvaluator :
20921 public ExprEvaluatorBase<AtomicExprEvaluator> {
20922 const LValue *This;
20923 APValue &Result;
20924public:
20925 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
20926 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
20927
20928 bool Success(const APValue &V, const Expr *E) {
20929 Result = V;
20930 return true;
20931 }
20932
20933 bool ZeroInitialization(const Expr *E) {
20934 ImplicitValueInitExpr VIE(
20935 E->getType()->castAs<AtomicType>()->getValueType());
20936 // For atomic-qualified class (and array) types in C++, initialize the
20937 // _Atomic-wrapped subobject directly, in-place.
20938 return This ? EvaluateInPlace(Result, Info, *This, &VIE)
20939 : Evaluate(Result, Info, &VIE);
20940 }
20941
20942 bool VisitCastExpr(const CastExpr *E) {
20943 switch (E->getCastKind()) {
20944 default:
20945 return ExprEvaluatorBaseTy::VisitCastExpr(E);
20946 case CK_NullToPointer:
20947 VisitIgnoredValue(E->getSubExpr());
20948 return ZeroInitialization(E);
20949 case CK_NonAtomicToAtomic:
20950 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
20951 : Evaluate(Result, Info, E->getSubExpr());
20952 }
20953 }
20954};
20955} // end anonymous namespace
20956
20957static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
20958 EvalInfo &Info) {
20959 assert(!E->isValueDependent());
20960 assert(E->isPRValue() && E->getType()->isAtomicType());
20961 return AtomicExprEvaluator(Info, This, Result).Visit(E);
20962}
20963
20964//===----------------------------------------------------------------------===//
20965// Void expression evaluation, primarily for a cast to void on the LHS of a
20966// comma operator
20967//===----------------------------------------------------------------------===//
20968
20969namespace {
20970class VoidExprEvaluator
20971 : public ExprEvaluatorBase<VoidExprEvaluator> {
20972public:
20973 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
20974
20975 bool Success(const APValue &V, const Expr *e) { return true; }
20976
20977 bool ZeroInitialization(const Expr *E) { return true; }
20978
20979 bool VisitCastExpr(const CastExpr *E) {
20980 switch (E->getCastKind()) {
20981 default:
20982 return ExprEvaluatorBaseTy::VisitCastExpr(E);
20983 case CK_ToVoid:
20984 VisitIgnoredValue(E->getSubExpr());
20985 return true;
20986 }
20987 }
20988
20989 bool VisitCallExpr(const CallExpr *E) {
20990 if (!IsConstantEvaluatedBuiltinCall(E))
20991 return ExprEvaluatorBaseTy::VisitCallExpr(E);
20992
20993 switch (E->getBuiltinCallee()) {
20994 case Builtin::BI__assume:
20995 case Builtin::BI__builtin_assume:
20996 // The argument is not evaluated!
20997 return true;
20998
20999 case Builtin::BI__builtin_operator_delete:
21000 return HandleOperatorDeleteCall(Info, E);
21001
21002 default:
21003 return false;
21004 }
21005 }
21006
21007 bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
21008};
21009} // end anonymous namespace
21010
21011bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
21012 // We cannot speculatively evaluate a delete expression.
21013 if (Info.SpeculativeEvaluationDepth)
21014 return false;
21015
21016 FunctionDecl *OperatorDelete = E->getOperatorDelete();
21017 if (!OperatorDelete
21018 ->isUsableAsGlobalAllocationFunctionInConstantEvaluation()) {
21019 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
21020 << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;
21021 return false;
21022 }
21023
21024 const Expr *Arg = E->getArgument();
21025
21026 LValue Pointer;
21027 if (!EvaluatePointer(Arg, Pointer, Info))
21028 return false;
21029 if (Pointer.Designator.Invalid)
21030 return false;
21031
21032 // Deleting a null pointer has no effect.
21033 if (Pointer.isNullPointer()) {
21034 // This is the only case where we need to produce an extension warning:
21035 // the only other way we can succeed is if we find a dynamic allocation,
21036 // and we will have warned when we allocated it in that case.
21037 if (!Info.getLangOpts().CPlusPlus20)
21038 Info.CCEDiag(E, diag::note_constexpr_new);
21039 return true;
21040 }
21041
21042 std::optional<DynAlloc *> Alloc = CheckDeleteKind(
21043 Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New);
21044 if (!Alloc)
21045 return false;
21046 QualType AllocType = Pointer.Base.getDynamicAllocType();
21047
21048 // For the non-array case, the designator must be empty if the static type
21049 // does not have a virtual destructor.
21050 if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 &&
21052 Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor)
21053 << Arg->getType()->getPointeeType() << AllocType;
21054 return false;
21055 }
21056
21057 // For a class type with a virtual destructor, the selected operator delete
21058 // is the one looked up when building the destructor.
21059 if (!E->isArrayForm() && !E->isGlobalDelete()) {
21060 const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType);
21061 if (VirtualDelete &&
21062 !VirtualDelete
21063 ->isUsableAsGlobalAllocationFunctionInConstantEvaluation()) {
21064 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
21065 << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete;
21066 return false;
21067 }
21068 }
21069
21070 if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(),
21071 (*Alloc)->Value, AllocType))
21072 return false;
21073
21074 if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) {
21075 // The element was already erased. This means the destructor call also
21076 // deleted the object.
21077 // FIXME: This probably results in undefined behavior before we get this
21078 // far, and should be diagnosed elsewhere first.
21079 Info.FFDiag(E, diag::note_constexpr_double_delete);
21080 return false;
21081 }
21082
21083 return true;
21084}
21085
21086static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
21087 assert(!E->isValueDependent());
21088 assert(E->isPRValue() && E->getType()->isVoidType());
21089 return VoidExprEvaluator(Info).Visit(E);
21090}
21091
21092//===----------------------------------------------------------------------===//
21093// Top level Expr::EvaluateAsRValue method.
21094//===----------------------------------------------------------------------===//
21095
21096static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
21097 assert(!E->isValueDependent());
21098 // In C, function designators are not lvalues, but we evaluate them as if they
21099 // are.
21100 QualType T = E->getType();
21101 if (E->isGLValue() || T->isFunctionType()) {
21102 LValue LV;
21103 if (!EvaluateLValue(E, LV, Info))
21104 return false;
21105 LV.moveInto(Result);
21106 } else if (T->isVectorType()) {
21107 if (!EvaluateVector(E, Result, Info))
21108 return false;
21109 } else if (T->isConstantMatrixType()) {
21110 if (!EvaluateMatrix(E, Result, Info))
21111 return false;
21112 } else if (T->isIntegralOrEnumerationType()) {
21113 if (!IntExprEvaluator(Info, Result).Visit(E))
21114 return false;
21115 } else if (T->hasPointerRepresentation()) {
21116 LValue LV;
21117 if (!EvaluatePointer(E, LV, Info))
21118 return false;
21119 LV.moveInto(Result);
21120 } else if (T->isRealFloatingType()) {
21121 llvm::APFloat F(0.0);
21122 if (!EvaluateFloat(E, F, Info))
21123 return false;
21124 Result = APValue(F);
21125 } else if (T->isAnyComplexType()) {
21126 ComplexValue C;
21127 if (!EvaluateComplex(E, C, Info))
21128 return false;
21129 C.moveInto(Result);
21130 } else if (T->isFixedPointType()) {
21131 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
21132 } else if (T->isMemberPointerType()) {
21133 MemberPtr P;
21134 if (!EvaluateMemberPointer(E, P, Info))
21135 return false;
21136 P.moveInto(Result);
21137 return true;
21138 } else if (T->isArrayType()) {
21139 LValue LV;
21140 APValue &Value =
21141 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
21142 if (!EvaluateArray(E, LV, Value, Info))
21143 return false;
21144 Result = Value;
21145 } else if (T->isRecordType()) {
21146 LValue LV;
21147 APValue &Value =
21148 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
21149 if (!EvaluateRecord(E, LV, Value, Info))
21150 return false;
21151 Result = Value;
21152 } else if (T->isVoidType()) {
21153 if (!Info.getLangOpts().CPlusPlus11)
21154 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
21155 << E->getType();
21156 if (!EvaluateVoid(E, Info))
21157 return false;
21158 } else if (T->isAtomicType()) {
21160 if (Unqual->isArrayType() || Unqual->isRecordType()) {
21161 LValue LV;
21162 APValue &Value = Info.CurrentCall->createTemporary(
21163 E, Unqual, ScopeKind::FullExpression, LV);
21164 if (!EvaluateAtomic(E, &LV, Value, Info))
21165 return false;
21166 Result = Value;
21167 } else {
21168 if (!EvaluateAtomic(E, nullptr, Result, Info))
21169 return false;
21170 }
21171 } else if (Info.getLangOpts().CPlusPlus11) {
21172 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
21173 return false;
21174 } else {
21175 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
21176 return false;
21177 }
21178
21179 return true;
21180}
21181
21182/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
21183/// cases, the in-place evaluation is essential, since later initializers for
21184/// an object can indirectly refer to subobjects which were initialized earlier.
21185static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
21186 const Expr *E, bool AllowNonLiteralTypes) {
21187 assert(!E->isValueDependent());
21188
21189 // Normally expressions passed to EvaluateInPlace have a type, but not when
21190 // a VarDecl initializer is evaluated before the untyped ParenListExpr is
21191 // replaced with a CXXConstructExpr. This can happen in LLDB.
21192 if (E->getType().isNull())
21193 return false;
21194
21195 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
21196 return false;
21197
21198 if (E->isPRValue()) {
21199 // Evaluate arrays and record types in-place, so that later initializers can
21200 // refer to earlier-initialized members of the object.
21201 QualType T = E->getType();
21202 if (T->isArrayType())
21203 return EvaluateArray(E, This, Result, Info);
21204 else if (T->isRecordType())
21205 return EvaluateRecord(E, This, Result, Info);
21206 else if (T->isAtomicType()) {
21208 if (Unqual->isArrayType() || Unqual->isRecordType())
21209 return EvaluateAtomic(E, &This, Result, Info);
21210 }
21211 }
21212
21213 // For any other type, in-place evaluation is unimportant.
21214 return Evaluate(Result, Info, E);
21215}
21216
21217/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
21218/// lvalue-to-rvalue cast if it is an lvalue.
21219static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
21220 assert(!E->isValueDependent());
21221
21222 if (E->getType().isNull())
21223 return false;
21224
21225 if (!CheckLiteralType(Info, E))
21226 return false;
21227
21228 if (Info.EnableNewConstInterp) {
21229 if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result))
21230 return false;
21231 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
21232 ConstantExprKind::Normal);
21233 }
21234
21235 if (!::Evaluate(Result, Info, E))
21236 return false;
21237
21238 // Implicit lvalue-to-rvalue cast.
21239 if (E->isGLValue()) {
21240 LValue LV;
21241 LV.setFrom(Info.Ctx, Result);
21242 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
21243 return false;
21244 }
21245
21246 // Check this core constant expression is a constant expression.
21247 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
21248 ConstantExprKind::Normal) &&
21249 CheckMemoryLeaks(Info);
21250}
21251
21252static bool FastEvaluateAsRValue(const Expr *Exp, APValue &Result,
21253 const ASTContext &Ctx, bool &IsConst) {
21254 // Fast-path evaluations of integer literals, since we sometimes see files
21255 // containing vast quantities of these.
21256 if (const auto *L = dyn_cast<IntegerLiteral>(Exp)) {
21257 Result =
21258 APValue(APSInt(L->getValue(), L->getType()->isUnsignedIntegerType()));
21259 IsConst = true;
21260 return true;
21261 }
21262
21263 if (const auto *L = dyn_cast<CXXBoolLiteralExpr>(Exp)) {
21264 Result = APValue(APSInt(APInt(1, L->getValue())));
21265 IsConst = true;
21266 return true;
21267 }
21268
21269 if (const auto *FL = dyn_cast<FloatingLiteral>(Exp)) {
21270 Result = APValue(FL->getValue());
21271 IsConst = true;
21272 return true;
21273 }
21274
21275 if (const auto *L = dyn_cast<CharacterLiteral>(Exp)) {
21276 Result = APValue(Ctx.MakeIntValue(L->getValue(), L->getType()));
21277 IsConst = true;
21278 return true;
21279 }
21280
21281 if (const auto *CE = dyn_cast<ConstantExpr>(Exp)) {
21282 if (CE->hasAPValueResult()) {
21283 APValue APV = CE->getAPValueResult();
21284 if (!APV.isLValue()) {
21285 Result = std::move(APV);
21286 IsConst = true;
21287 return true;
21288 }
21289 }
21290
21291 // The SubExpr is usually just an IntegerLiteral.
21292 return FastEvaluateAsRValue(CE->getSubExpr(), Result, Ctx, IsConst);
21293 }
21294
21295 // This case should be rare, but we need to check it before we check on
21296 // the type below.
21297 if (Exp->getType().isNull()) {
21298 IsConst = false;
21299 return true;
21300 }
21301
21302 return false;
21303}
21304
21307 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
21308 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
21309}
21310
21312 const ASTContext &Ctx, EvalInfo &Info) {
21313 assert(!E->isValueDependent());
21314 bool IsConst;
21315 if (FastEvaluateAsRValue(E, Result.Val, Ctx, IsConst))
21316 return IsConst;
21317
21318 return EvaluateAsRValue(Info, E, Result.Val);
21319}
21320
21322 const ASTContext &Ctx,
21323 Expr::SideEffectsKind AllowSideEffects,
21324 EvalInfo &Info) {
21325 assert(!E->isValueDependent());
21327 return false;
21328
21329 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
21330 !ExprResult.Val.isInt() ||
21331 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
21332 return false;
21333
21334 return true;
21335}
21336
21338 const ASTContext &Ctx,
21339 Expr::SideEffectsKind AllowSideEffects,
21340 EvalInfo &Info) {
21341 assert(!E->isValueDependent());
21342 if (!E->getType()->isFixedPointType())
21343 return false;
21344
21345 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
21346 return false;
21347
21348 if (!ExprResult.Val.isFixedPoint() ||
21349 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
21350 return false;
21351
21352 return true;
21353}
21354
21355/// EvaluateAsRValue - Return true if this is a constant which we can fold using
21356/// any crazy technique (that has nothing to do with language standards) that
21357/// we want to. If this function returns true, it returns the folded constant
21358/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
21359/// will be applied to the result.
21361 bool InConstantContext) const {
21362 assert(!isValueDependent() &&
21363 "Expression evaluator can't be called on a dependent expression.");
21364 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsRValue");
21365 EvalInfo Info(Ctx, Result, EvaluationMode::IgnoreSideEffects);
21366 Info.InConstantContext = InConstantContext;
21367 return ::EvaluateAsRValue(this, Result, Ctx, Info);
21368}
21369
21371 bool InConstantContext) const {
21372 assert(!isValueDependent() &&
21373 "Expression evaluator can't be called on a dependent expression.");
21374 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsBooleanCondition");
21375 EvalResult Scratch;
21376 return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
21377 HandleConversionToBool(Scratch.Val, Result);
21378}
21379
21381 SideEffectsKind AllowSideEffects,
21382 bool InConstantContext) const {
21383 assert(!isValueDependent() &&
21384 "Expression evaluator can't be called on a dependent expression.");
21385 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsInt");
21386 EvalInfo Info(Ctx, Result, EvaluationMode::IgnoreSideEffects);
21387 Info.InConstantContext = InConstantContext;
21388 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
21389}
21390
21392 SideEffectsKind AllowSideEffects,
21393 bool InConstantContext) const {
21394 assert(!isValueDependent() &&
21395 "Expression evaluator can't be called on a dependent expression.");
21396 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFixedPoint");
21397 EvalInfo Info(Ctx, Result, EvaluationMode::IgnoreSideEffects);
21398 Info.InConstantContext = InConstantContext;
21399 return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
21400}
21401
21402bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
21403 SideEffectsKind AllowSideEffects,
21404 bool InConstantContext) const {
21405 assert(!isValueDependent() &&
21406 "Expression evaluator can't be called on a dependent expression.");
21407
21408 if (!getType()->isRealFloatingType())
21409 return false;
21410
21411 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFloat");
21413 if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
21414 !ExprResult.Val.isFloat() ||
21415 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
21416 return false;
21417
21418 Result = ExprResult.Val.getFloat();
21419 return true;
21420}
21421
21423 bool InConstantContext) const {
21424 assert(!isValueDependent() &&
21425 "Expression evaluator can't be called on a dependent expression.");
21426
21427 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsLValue");
21428 EvalInfo Info(Ctx, Result, EvaluationMode::ConstantFold);
21429 Info.InConstantContext = InConstantContext;
21430 LValue LV;
21431 CheckedTemporaries CheckedTemps;
21432
21433 if (Info.EnableNewConstInterp) {
21434 if (!Info.Ctx.getInterpContext().evaluate(Info, this, Result.Val,
21435 ConstantExprKind::Normal))
21436 return false;
21437
21438 LV.setFrom(Ctx, Result.Val);
21440 Info, getExprLoc(), Ctx.getLValueReferenceType(getType()), LV,
21441 ConstantExprKind::Normal, CheckedTemps);
21442 }
21443
21444 if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() ||
21445 Result.HasSideEffects ||
21448 ConstantExprKind::Normal, CheckedTemps))
21449 return false;
21450
21451 LV.moveInto(Result.Val);
21452 return true;
21453}
21454
21456 APValue DestroyedValue, QualType Type,
21457 SourceLocation Loc, Expr::EvalStatus &EStatus,
21458 bool IsConstantDestruction) {
21459 EvalInfo Info(Ctx, EStatus,
21460 IsConstantDestruction ? EvaluationMode::ConstantExpression
21462 Info.setEvaluatingDecl(Base, DestroyedValue,
21463 EvalInfo::EvaluatingDeclKind::Dtor);
21464 Info.InConstantContext = IsConstantDestruction;
21465
21466 LValue LVal;
21467 LVal.set(Base);
21468
21469 if (!HandleDestruction(Info, Loc, Base, DestroyedValue, Type) ||
21470 EStatus.HasSideEffects)
21471 return false;
21472
21473 if (!Info.discardCleanups())
21474 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
21475
21476 return true;
21477}
21478
21480 ConstantExprKind Kind) const {
21481 assert(!isValueDependent() &&
21482 "Expression evaluator can't be called on a dependent expression.");
21483 bool IsConst;
21484 if (FastEvaluateAsRValue(this, Result.Val, Ctx, IsConst) &&
21485 Result.Val.hasValue())
21486 return true;
21487
21488 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsConstantExpr");
21490 EvalInfo Info(Ctx, Result, EM);
21491 Info.InConstantContext = true;
21492
21493 if (Info.EnableNewConstInterp) {
21494 if (!Info.Ctx.getInterpContext().evaluate(Info, this, Result.Val, Kind))
21495 return false;
21496 return CheckConstantExpression(Info, getExprLoc(),
21497 getStorageType(Ctx, this), Result.Val, Kind);
21498 }
21499
21500 // The type of the object we're initializing is 'const T' for a class NTTP.
21501 QualType T = getType();
21502 if (Kind == ConstantExprKind::ClassTemplateArgument)
21503 T.addConst();
21504
21505 // If we're evaluating a prvalue, fake up a MaterializeTemporaryExpr to
21506 // represent the result of the evaluation. CheckConstantExpression ensures
21507 // this doesn't escape.
21508 MaterializeTemporaryExpr BaseMTE(T, const_cast<Expr*>(this), true);
21509 APValue::LValueBase Base(&BaseMTE);
21510 Info.setEvaluatingDecl(Base, Result.Val);
21511
21512 LValue LVal;
21513 LVal.set(Base);
21514 // C++23 [intro.execution]/p5
21515 // A full-expression is [...] a constant-expression
21516 // So we need to make sure temporary objects are destroyed after having
21517 // evaluating the expression (per C++23 [class.temporary]/p4).
21518 FullExpressionRAII Scope(Info);
21519 if (!::EvaluateInPlace(Result.Val, Info, LVal, this) ||
21520 Result.HasSideEffects || !Scope.destroy())
21521 return false;
21522
21523 if (!Info.discardCleanups())
21524 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
21525
21526 if (!CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this),
21527 Result.Val, Kind))
21528 return false;
21529 if (!CheckMemoryLeaks(Info))
21530 return false;
21531
21532 // If this is a class template argument, it's required to have constant
21533 // destruction too.
21534 if (Kind == ConstantExprKind::ClassTemplateArgument &&
21536 true) ||
21537 Result.HasSideEffects)) {
21538 // FIXME: Prefix a note to indicate that the problem is lack of constant
21539 // destruction.
21540 return false;
21541 }
21542
21543 return true;
21544}
21545
21547 Expr::EvalResult &EStatus,
21548 bool IsConstantInitialization) const {
21549 assert(!isValueDependent() &&
21550 "Expression evaluator can't be called on a dependent expression.");
21551 assert(VD && "Need a valid VarDecl");
21552
21553 llvm::TimeTraceScope TimeScope("EvaluateAsInitializer", [&] {
21554 std::string Name;
21555 llvm::raw_string_ostream OS(Name);
21556 VD->printQualifiedName(OS);
21557 return Name;
21558 });
21559
21560 EvalInfo Info(Ctx, EStatus,
21561 (IsConstantInitialization &&
21562 (Ctx.getLangOpts().CPlusPlus || Ctx.getLangOpts().C23))
21565 Info.setEvaluatingDecl(VD, EStatus.Val);
21566 Info.InConstantContext = IsConstantInitialization;
21567
21568 SourceLocation DeclLoc = VD->getLocation();
21569 QualType DeclTy = VD->getType();
21570
21571 if (Info.EnableNewConstInterp) {
21572 auto &InterpCtx = Ctx.getInterpContext();
21573 if (!InterpCtx.evaluateAsInitializer(Info, VD, this, EStatus.Val))
21574 return false;
21575
21576 return CheckConstantExpression(Info, DeclLoc, DeclTy, EStatus.Val,
21577 ConstantExprKind::Normal);
21578 } else {
21579 LValue LVal;
21580 LVal.set(VD);
21581
21582 {
21583 // C++23 [intro.execution]/p5
21584 // A full-expression is ... an init-declarator ([dcl.decl]) or a
21585 // mem-initializer.
21586 // So we need to make sure temporary objects are destroyed after having
21587 // evaluated the expression (per C++23 [class.temporary]/p4).
21588 //
21589 // FIXME: Otherwise this may break test/Modules/pr68702.cpp because the
21590 // serialization code calls ParmVarDecl::getDefaultArg() which strips the
21591 // outermost FullExpr, such as ExprWithCleanups.
21592 FullExpressionRAII Scope(Info);
21593 if (!EvaluateInPlace(EStatus.Val, Info, LVal, this,
21594 /*AllowNonLiteralTypes=*/true) ||
21595 EStatus.HasSideEffects)
21596 return false;
21597 }
21598
21599 // At this point, any lifetime-extended temporaries are completely
21600 // initialized.
21601 Info.performLifetimeExtension();
21602
21603 if (!Info.discardCleanups())
21604 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
21605 }
21606
21607 return CheckConstantExpression(Info, DeclLoc, DeclTy, EStatus.Val,
21608 ConstantExprKind::Normal) &&
21609 CheckMemoryLeaks(Info);
21610}
21611
21614 Expr::EvalStatus EStatus;
21615 EStatus.Diag = &Notes;
21616
21617 // Only treat the destruction as constant destruction if we formally have
21618 // constant initialization (or are usable in a constant expression).
21619 bool IsConstantDestruction = hasConstantInitialization();
21620 ASTContext &Ctx = getASTContext();
21621
21622 // Make a copy of the value for the destructor to mutate, if we know it.
21623 // Otherwise, treat the value as default-initialized; if the destructor works
21624 // anyway, then the destruction is constant (and must be essentially empty).
21625 APValue DestroyedValue;
21626 if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent())
21627 DestroyedValue = *getEvaluatedValue();
21628 else if (!handleDefaultInitValue(getType(), DestroyedValue))
21629 return false;
21630
21631 if (Ctx.getLangOpts().EnableNewConstInterp) {
21632 EvalInfo Info(Ctx, EStatus,
21633 IsConstantDestruction ? EvaluationMode::ConstantExpression
21635 Info.setEvaluatingDecl(this, DestroyedValue,
21636 EvalInfo::EvaluatingDeclKind::Dtor);
21637 Info.InConstantContext = IsConstantDestruction;
21638 if (!Ctx.getInterpContext().evaluateDestruction(Info, this,
21639 std::move(DestroyedValue)))
21640 return false;
21641 ensureEvaluatedStmt()->HasConstantDestruction = true;
21642 return true;
21643 }
21644
21645 if (!EvaluateDestruction(Ctx, this, std::move(DestroyedValue), getType(),
21646 getLocation(), EStatus, IsConstantDestruction) ||
21647 EStatus.HasSideEffects)
21648 return false;
21649
21650 ensureEvaluatedStmt()->HasConstantDestruction = true;
21651 return true;
21652}
21653
21654/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
21655/// constant folded, but discard the result.
21657 assert(!isValueDependent() &&
21658 "Expression evaluator can't be called on a dependent expression.");
21659
21661 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
21663}
21664
21665APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
21666 assert(!isValueDependent() &&
21667 "Expression evaluator can't be called on a dependent expression.");
21668
21669 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstInt");
21670 EvalResult EVResult;
21671 EvalInfo Info(Ctx, EVResult, EvaluationMode::IgnoreSideEffects);
21672 Info.InConstantContext = true;
21673
21674 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
21675 (void)Result;
21676 assert(Result && "Could not evaluate expression");
21677 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
21678
21679 return EVResult.Val.getInt();
21680}
21681
21684 assert(!isValueDependent() &&
21685 "Expression evaluator can't be called on a dependent expression.");
21686
21687 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstIntCheckOverflow");
21688 EvalResult EVResult;
21689 EVResult.Diag = Diag;
21690 EvalInfo Info(Ctx, EVResult, EvaluationMode::IgnoreSideEffects);
21691 Info.InConstantContext = true;
21692 Info.CheckingForUndefinedBehavior = true;
21693
21694 bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
21695 (void)Result;
21696 assert(Result && "Could not evaluate expression");
21697 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
21698
21699 return EVResult.Val.getInt();
21700}
21701
21703 assert(!isValueDependent() &&
21704 "Expression evaluator can't be called on a dependent expression.");
21705
21706 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateForOverflow");
21707 bool IsConst;
21708 EvalResult EVResult;
21709 if (!FastEvaluateAsRValue(this, EVResult.Val, Ctx, IsConst)) {
21710 EvalInfo Info(Ctx, EVResult, EvaluationMode::IgnoreSideEffects);
21711 Info.CheckingForUndefinedBehavior = true;
21712 (void)::EvaluateAsRValue(Info, this, EVResult.Val);
21713 }
21714}
21715
21717 assert(Val.isLValue());
21718 return IsGlobalLValue(Val.getLValueBase());
21719}
21720
21721/// isIntegerConstantExpr - this recursive routine will test if an expression is
21722/// an integer constant expression.
21723
21724/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
21725/// comma, etc
21726
21727// CheckICE - This function does the fundamental ICE checking: the returned
21728// ICEDiag contains an ICEKind indicating whether the expression is an ICE.
21729//
21730// Note that to reduce code duplication, this helper does no evaluation
21731// itself; the caller checks whether the expression is evaluatable, and
21732// in the rare cases where CheckICE actually cares about the evaluated
21733// value, it calls into Evaluate.
21734
21735namespace {
21736
21737enum ICEKind {
21738 /// This expression is an ICE.
21739 IK_ICE,
21740 /// This expression is not an ICE, but if it isn't evaluated, it's
21741 /// a legal subexpression for an ICE. This return value is used to handle
21742 /// the comma operator in C99 mode, and non-constant subexpressions.
21743 IK_ICEIfUnevaluated,
21744 /// This expression is not an ICE, and is not a legal subexpression for one.
21745 IK_NotICE
21746};
21747
21748struct ICEDiag {
21749 ICEKind Kind;
21750 SourceLocation Loc;
21751
21752 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
21753};
21754
21755}
21756
21757static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
21758
21759static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
21760
21761static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
21762 Expr::EvalResult EVResult;
21763 Expr::EvalStatus Status;
21764 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantExpression);
21765
21766 Info.InConstantContext = true;
21767 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
21768 !EVResult.Val.isInt())
21769 return ICEDiag(IK_NotICE, E->getBeginLoc());
21770
21771 return NoDiag();
21772}
21773
21774static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
21775 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
21777 return ICEDiag(IK_NotICE, E->getBeginLoc());
21778
21779 switch (E->getStmtClass()) {
21780#define ABSTRACT_STMT(Node)
21781#define STMT(Node, Base) case Expr::Node##Class:
21782#define EXPR(Node, Base)
21783#include "clang/AST/StmtNodes.inc"
21784 case Expr::PredefinedExprClass:
21785 case Expr::FloatingLiteralClass:
21786 case Expr::ImaginaryLiteralClass:
21787 case Expr::StringLiteralClass:
21788 case Expr::ArraySubscriptExprClass:
21789 case Expr::MatrixSingleSubscriptExprClass:
21790 case Expr::MatrixSubscriptExprClass:
21791 case Expr::ArraySectionExprClass:
21792 case Expr::OMPArrayShapingExprClass:
21793 case Expr::OMPIteratorExprClass:
21794 case Expr::CompoundAssignOperatorClass:
21795 case Expr::CompoundLiteralExprClass:
21796 case Expr::ExtVectorElementExprClass:
21797 case Expr::MatrixElementExprClass:
21798 case Expr::DesignatedInitExprClass:
21799 case Expr::ArrayInitLoopExprClass:
21800 case Expr::ArrayInitIndexExprClass:
21801 case Expr::NoInitExprClass:
21802 case Expr::DesignatedInitUpdateExprClass:
21803 case Expr::ImplicitValueInitExprClass:
21804 case Expr::ParenListExprClass:
21805 case Expr::VAArgExprClass:
21806 case Expr::AddrLabelExprClass:
21807 case Expr::StmtExprClass:
21808 case Expr::CXXMemberCallExprClass:
21809 case Expr::CUDAKernelCallExprClass:
21810 case Expr::CXXAddrspaceCastExprClass:
21811 case Expr::CXXDynamicCastExprClass:
21812 case Expr::CXXTypeidExprClass:
21813 case Expr::CXXUuidofExprClass:
21814 case Expr::MSPropertyRefExprClass:
21815 case Expr::MSPropertySubscriptExprClass:
21816 case Expr::CXXNullPtrLiteralExprClass:
21817 case Expr::UserDefinedLiteralClass:
21818 case Expr::CXXThisExprClass:
21819 case Expr::CXXThrowExprClass:
21820 case Expr::CXXNewExprClass:
21821 case Expr::CXXDeleteExprClass:
21822 case Expr::CXXPseudoDestructorExprClass:
21823 case Expr::UnresolvedLookupExprClass:
21824 case Expr::RecoveryExprClass:
21825 case Expr::DependentScopeDeclRefExprClass:
21826 case Expr::CXXConstructExprClass:
21827 case Expr::CXXInheritedCtorInitExprClass:
21828 case Expr::CXXStdInitializerListExprClass:
21829 case Expr::CXXBindTemporaryExprClass:
21830 case Expr::ExprWithCleanupsClass:
21831 case Expr::CXXTemporaryObjectExprClass:
21832 case Expr::CXXUnresolvedConstructExprClass:
21833 case Expr::CXXDependentScopeMemberExprClass:
21834 case Expr::UnresolvedMemberExprClass:
21835 case Expr::ObjCStringLiteralClass:
21836 case Expr::ObjCBoxedExprClass:
21837 case Expr::ObjCArrayLiteralClass:
21838 case Expr::ObjCDictionaryLiteralClass:
21839 case Expr::ObjCEncodeExprClass:
21840 case Expr::ObjCMessageExprClass:
21841 case Expr::ObjCSelectorExprClass:
21842 case Expr::ObjCProtocolExprClass:
21843 case Expr::ObjCIvarRefExprClass:
21844 case Expr::ObjCPropertyRefExprClass:
21845 case Expr::ObjCSubscriptRefExprClass:
21846 case Expr::ObjCIsaExprClass:
21847 case Expr::ObjCAvailabilityCheckExprClass:
21848 case Expr::ShuffleVectorExprClass:
21849 case Expr::ConvertVectorExprClass:
21850 case Expr::BlockExprClass:
21851 case Expr::NoStmtClass:
21852 case Expr::OpaqueValueExprClass:
21853 case Expr::PackExpansionExprClass:
21854 case Expr::SubstNonTypeTemplateParmPackExprClass:
21855 case Expr::FunctionParmPackExprClass:
21856 case Expr::AsTypeExprClass:
21857 case Expr::ObjCIndirectCopyRestoreExprClass:
21858 case Expr::MaterializeTemporaryExprClass:
21859 case Expr::PseudoObjectExprClass:
21860 case Expr::AtomicExprClass:
21861 case Expr::LambdaExprClass:
21862 case Expr::CXXFoldExprClass:
21863 case Expr::CoawaitExprClass:
21864 case Expr::DependentCoawaitExprClass:
21865 case Expr::CoyieldExprClass:
21866 case Expr::SYCLUniqueStableNameExprClass:
21867 case Expr::CXXParenListInitExprClass:
21868 case Expr::HLSLOutArgExprClass:
21869 return ICEDiag(IK_NotICE, E->getBeginLoc());
21870
21871 case Expr::MemberExprClass: {
21872 if (Ctx.getLangOpts().C23) {
21873 const Expr *ME = E->IgnoreParenImpCasts();
21874 while (const auto *M = dyn_cast<MemberExpr>(ME)) {
21875 if (M->isArrow())
21876 return ICEDiag(IK_NotICE, E->getBeginLoc());
21877 ME = M->getBase()->IgnoreParenImpCasts();
21878 }
21879 const auto *DRE = dyn_cast<DeclRefExpr>(ME);
21880 if (DRE) {
21881 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
21882 VD && VD->isConstexpr())
21883 return CheckEvalInICE(E, Ctx);
21884 }
21885 }
21886 return ICEDiag(IK_NotICE, E->getBeginLoc());
21887 }
21888
21889 case Expr::InitListExprClass: {
21890 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
21891 // form "T x = { a };" is equivalent to "T x = a;".
21892 // Unless we're initializing a reference, T is a scalar as it is known to be
21893 // of integral or enumeration type.
21894 if (E->isPRValue())
21895 if (cast<InitListExpr>(E)->getNumInits() == 1)
21896 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
21897 return ICEDiag(IK_NotICE, E->getBeginLoc());
21898 }
21899
21900 case Expr::SizeOfPackExprClass:
21901 case Expr::GNUNullExprClass:
21902 case Expr::SourceLocExprClass:
21903 case Expr::EmbedExprClass:
21904 case Expr::OpenACCAsteriskSizeExprClass:
21905 return NoDiag();
21906
21907 case Expr::PackIndexingExprClass:
21908 return CheckICE(cast<PackIndexingExpr>(E)->getSelectedExpr(), Ctx);
21909
21910 case Expr::SubstNonTypeTemplateParmExprClass:
21911 return
21912 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
21913
21914 case Expr::ConstantExprClass:
21915 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
21916
21917 case Expr::ParenExprClass:
21918 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
21919 case Expr::GenericSelectionExprClass:
21920 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
21921 case Expr::IntegerLiteralClass:
21922 case Expr::FixedPointLiteralClass:
21923 case Expr::CharacterLiteralClass:
21924 case Expr::ObjCBoolLiteralExprClass:
21925 case Expr::CXXBoolLiteralExprClass:
21926 case Expr::CXXScalarValueInitExprClass:
21927 case Expr::TypeTraitExprClass:
21928 case Expr::ConceptSpecializationExprClass:
21929 case Expr::RequiresExprClass:
21930 case Expr::ArrayTypeTraitExprClass:
21931 case Expr::ExpressionTraitExprClass:
21932 case Expr::CXXNoexceptExprClass:
21933 case Expr::CXXReflectExprClass:
21934 return NoDiag();
21935 case Expr::CallExprClass:
21936 case Expr::CXXOperatorCallExprClass: {
21937 // C99 6.6/3 allows function calls within unevaluated subexpressions of
21938 // constant expressions, but they can never be ICEs because an ICE cannot
21939 // contain an operand of (pointer to) function type.
21940 const CallExpr *CE = cast<CallExpr>(E);
21941 if (CE->getBuiltinCallee())
21942 return CheckEvalInICE(E, Ctx);
21943 return ICEDiag(IK_NotICE, E->getBeginLoc());
21944 }
21945 case Expr::CXXRewrittenBinaryOperatorClass:
21946 return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(),
21947 Ctx);
21948 case Expr::DeclRefExprClass: {
21949 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
21950 if (isa<EnumConstantDecl>(D))
21951 return NoDiag();
21952
21953 // C++ and OpenCL (FIXME: spec reference?) allow reading const-qualified
21954 // integer variables in constant expressions:
21955 //
21956 // C++ 7.1.5.1p2
21957 // A variable of non-volatile const-qualified integral or enumeration
21958 // type initialized by an ICE can be used in ICEs.
21959 //
21960 // We sometimes use CheckICE to check the C++98 rules in C++11 mode. In
21961 // that mode, use of reference variables should not be allowed.
21962 const VarDecl *VD = dyn_cast<VarDecl>(D);
21963 if (VD && VD->isUsableInConstantExpressions(Ctx) &&
21964 !VD->getType()->isReferenceType())
21965 return NoDiag();
21966
21967 return ICEDiag(IK_NotICE, E->getBeginLoc());
21968 }
21969 case Expr::UnaryOperatorClass: {
21970 const UnaryOperator *Exp = cast<UnaryOperator>(E);
21971 switch (Exp->getOpcode()) {
21972 case UO_PostInc:
21973 case UO_PostDec:
21974 case UO_PreInc:
21975 case UO_PreDec:
21976 case UO_AddrOf:
21977 case UO_Deref:
21978 case UO_Coawait:
21979 // C99 6.6/3 allows increment and decrement within unevaluated
21980 // subexpressions of constant expressions, but they can never be ICEs
21981 // because an ICE cannot contain an lvalue operand.
21982 return ICEDiag(IK_NotICE, E->getBeginLoc());
21983 case UO_Extension:
21984 case UO_LNot:
21985 case UO_Plus:
21986 case UO_Minus:
21987 case UO_Not:
21988 case UO_Real:
21989 case UO_Imag:
21990 return CheckICE(Exp->getSubExpr(), Ctx);
21991 }
21992 llvm_unreachable("invalid unary operator class");
21993 }
21994 case Expr::OffsetOfExprClass: {
21995 // Note that per C99, offsetof must be an ICE. And AFAIK, using
21996 // EvaluateAsRValue matches the proposed gcc behavior for cases like
21997 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
21998 // compliance: we should warn earlier for offsetof expressions with
21999 // array subscripts that aren't ICEs, and if the array subscripts
22000 // are ICEs, the value of the offsetof must be an integer constant.
22001 return CheckEvalInICE(E, Ctx);
22002 }
22003 case Expr::UnaryExprOrTypeTraitExprClass: {
22005 if ((Exp->getKind() == UETT_SizeOf) &&
22007 return ICEDiag(IK_NotICE, E->getBeginLoc());
22008 if (Exp->getKind() == UETT_CountOf) {
22009 QualType ArgTy = Exp->getTypeOfArgument();
22010 if (ArgTy->isVariableArrayType()) {
22011 // We need to look whether the array is multidimensional. If it is,
22012 // then we want to check the size expression manually to see whether
22013 // it is an ICE or not.
22014 const auto *VAT = Ctx.getAsVariableArrayType(ArgTy);
22015 if (VAT->getElementType()->isArrayType())
22016 // Variable array size expression could be missing (e.g. int a[*][10])
22017 // In that case, it can't be a constant expression.
22018 return VAT->getSizeExpr() ? CheckICE(VAT->getSizeExpr(), Ctx)
22019 : ICEDiag(IK_NotICE, E->getBeginLoc());
22020
22021 // Otherwise, this is a regular VLA, which is definitely not an ICE.
22022 return ICEDiag(IK_NotICE, E->getBeginLoc());
22023 }
22024 }
22025 return NoDiag();
22026 }
22027 case Expr::BinaryOperatorClass: {
22028 const BinaryOperator *Exp = cast<BinaryOperator>(E);
22029 switch (Exp->getOpcode()) {
22030 case BO_PtrMemD:
22031 case BO_PtrMemI:
22032 case BO_Assign:
22033 case BO_MulAssign:
22034 case BO_DivAssign:
22035 case BO_RemAssign:
22036 case BO_AddAssign:
22037 case BO_SubAssign:
22038 case BO_ShlAssign:
22039 case BO_ShrAssign:
22040 case BO_AndAssign:
22041 case BO_XorAssign:
22042 case BO_OrAssign:
22043 // C99 6.6/3 allows assignments within unevaluated subexpressions of
22044 // constant expressions, but they can never be ICEs because an ICE cannot
22045 // contain an lvalue operand.
22046 return ICEDiag(IK_NotICE, E->getBeginLoc());
22047
22048 case BO_Mul:
22049 case BO_Div:
22050 case BO_Rem:
22051 case BO_Add:
22052 case BO_Sub:
22053 case BO_Shl:
22054 case BO_Shr:
22055 case BO_LT:
22056 case BO_GT:
22057 case BO_LE:
22058 case BO_GE:
22059 case BO_EQ:
22060 case BO_NE:
22061 case BO_And:
22062 case BO_Xor:
22063 case BO_Or:
22064 case BO_Comma:
22065 case BO_Cmp: {
22066 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
22067 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
22068 if (Exp->getOpcode() == BO_Div ||
22069 Exp->getOpcode() == BO_Rem) {
22070 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
22071 // we don't evaluate one.
22072 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
22073 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
22074 if (REval == 0)
22075 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
22076 if (REval.isSigned() && REval.isAllOnes()) {
22077 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
22078 if (LEval.isMinSignedValue())
22079 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
22080 }
22081 }
22082 }
22083 if (Exp->getOpcode() == BO_Comma) {
22084 if (Ctx.getLangOpts().C99) {
22085 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
22086 // if it isn't evaluated.
22087 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
22088 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
22089 } else {
22090 // In both C89 and C++, commas in ICEs are illegal.
22091 return ICEDiag(IK_NotICE, E->getBeginLoc());
22092 }
22093 }
22094 return Worst(LHSResult, RHSResult);
22095 }
22096 case BO_LAnd:
22097 case BO_LOr: {
22098 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
22099 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
22100 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
22101 // Rare case where the RHS has a comma "side-effect"; we need
22102 // to actually check the condition to see whether the side
22103 // with the comma is evaluated.
22104 if ((Exp->getOpcode() == BO_LAnd) !=
22105 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
22106 return RHSResult;
22107 return NoDiag();
22108 }
22109
22110 return Worst(LHSResult, RHSResult);
22111 }
22112 }
22113 llvm_unreachable("invalid binary operator kind");
22114 }
22115 case Expr::ImplicitCastExprClass:
22116 case Expr::CStyleCastExprClass:
22117 case Expr::CXXFunctionalCastExprClass:
22118 case Expr::CXXStaticCastExprClass:
22119 case Expr::CXXReinterpretCastExprClass:
22120 case Expr::CXXConstCastExprClass:
22121 case Expr::ObjCBridgedCastExprClass: {
22122 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
22123 if (isa<ExplicitCastExpr>(E)) {
22124 if (const FloatingLiteral *FL
22125 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
22126 unsigned DestWidth = Ctx.getIntWidth(E->getType());
22127 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
22128 APSInt IgnoredVal(DestWidth, !DestSigned);
22129 bool Ignored;
22130 // If the value does not fit in the destination type, the behavior is
22131 // undefined, so we are not required to treat it as a constant
22132 // expression.
22133 if (FL->getValue().convertToInteger(IgnoredVal,
22134 llvm::APFloat::rmTowardZero,
22135 &Ignored) & APFloat::opInvalidOp)
22136 return ICEDiag(IK_NotICE, E->getBeginLoc());
22137 return NoDiag();
22138 }
22139 }
22140 switch (cast<CastExpr>(E)->getCastKind()) {
22141 case CK_LValueToRValue:
22142 case CK_AtomicToNonAtomic:
22143 case CK_NonAtomicToAtomic:
22144 case CK_NoOp:
22145 case CK_IntegralToBoolean:
22146 case CK_IntegralCast:
22147 return CheckICE(SubExpr, Ctx);
22148 default:
22149 return ICEDiag(IK_NotICE, E->getBeginLoc());
22150 }
22151 }
22152 case Expr::BinaryConditionalOperatorClass: {
22154 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
22155 if (CommonResult.Kind == IK_NotICE) return CommonResult;
22156 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
22157 if (FalseResult.Kind == IK_NotICE) return FalseResult;
22158 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
22159 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
22160 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
22161 return FalseResult;
22162 }
22163 case Expr::ConditionalOperatorClass: {
22165 // If the condition (ignoring parens) is a __builtin_constant_p call,
22166 // then only the true side is actually considered in an integer constant
22167 // expression, and it is fully evaluated. This is an important GNU
22168 // extension. See GCC PR38377 for discussion.
22169 if (const CallExpr *CallCE
22170 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
22171 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
22172 return CheckEvalInICE(E, Ctx);
22173 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
22174 if (CondResult.Kind == IK_NotICE)
22175 return CondResult;
22176
22177 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
22178 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
22179
22180 if (TrueResult.Kind == IK_NotICE)
22181 return TrueResult;
22182 if (FalseResult.Kind == IK_NotICE)
22183 return FalseResult;
22184 if (CondResult.Kind == IK_ICEIfUnevaluated)
22185 return CondResult;
22186 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
22187 return NoDiag();
22188 // Rare case where the diagnostics depend on which side is evaluated
22189 // Note that if we get here, CondResult is 0, and at least one of
22190 // TrueResult and FalseResult is non-zero.
22191 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
22192 return FalseResult;
22193 return TrueResult;
22194 }
22195 case Expr::CXXDefaultArgExprClass:
22196 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
22197 case Expr::CXXDefaultInitExprClass:
22198 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
22199 case Expr::ChooseExprClass: {
22200 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
22201 }
22202 case Expr::BuiltinBitCastExprClass: {
22203 if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
22204 return ICEDiag(IK_NotICE, E->getBeginLoc());
22205 return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
22206 }
22207 }
22208
22209 llvm_unreachable("Invalid StmtClass!");
22210}
22211
22212/// Evaluate an expression as a C++11 integral constant expression.
22214 const Expr *E,
22215 llvm::APSInt *Value) {
22217 return false;
22218
22220 if (!E->isCXX11ConstantExpr(Ctx, &Result))
22221 return false;
22222
22223 if (!Result.isInt())
22224 return false;
22225
22226 if (Value) *Value = Result.getInt();
22227 return true;
22228}
22229
22231 assert(!isValueDependent() &&
22232 "Expression evaluator can't be called on a dependent expression.");
22233
22234 ExprTimeTraceScope TimeScope(this, Ctx, "isIntegerConstantExpr");
22235
22236 if (Ctx.getLangOpts().CPlusPlus11)
22237 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr);
22238
22239 ICEDiag D = CheckICE(this, Ctx);
22240 if (D.Kind != IK_ICE)
22241 return false;
22242 return true;
22243}
22244
22245std::optional<llvm::APSInt>
22247 if (isValueDependent()) {
22248 // Expression evaluator can't succeed on a dependent expression.
22249 return std::nullopt;
22250 }
22251
22252 if (Ctx.getLangOpts().CPlusPlus11) {
22253 APSInt Value;
22255 return Value;
22256 return std::nullopt;
22257 }
22258
22259 if (!isIntegerConstantExpr(Ctx))
22260 return std::nullopt;
22261
22262 // The only possible side-effects here are due to UB discovered in the
22263 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
22264 // required to treat the expression as an ICE, so we produce the folded
22265 // value.
22267 Expr::EvalStatus Status;
22268 EvalInfo Info(Ctx, Status, EvaluationMode::IgnoreSideEffects);
22269 Info.InConstantContext = true;
22270
22271 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
22272 llvm_unreachable("ICE cannot be evaluated!");
22273
22274 return ExprResult.Val.getInt();
22275}
22276
22278 assert(!isValueDependent() &&
22279 "Expression evaluator can't be called on a dependent expression.");
22280
22281 return CheckICE(this, Ctx).Kind == IK_ICE;
22282}
22283
22285 assert(!isValueDependent() &&
22286 "Expression evaluator can't be called on a dependent expression.");
22287
22288 // We support this checking in C++98 mode in order to diagnose compatibility
22289 // issues.
22290 assert(Ctx.getLangOpts().CPlusPlus);
22291
22292 bool IsConst;
22293 APValue Scratch;
22294 if (FastEvaluateAsRValue(this, Scratch, Ctx, IsConst) && Scratch.hasValue()) {
22295 if (Result)
22296 *Result = std::move(Scratch);
22297 return true;
22298 }
22299
22300 // Build evaluation settings.
22301 Expr::EvalStatus Status;
22302 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantExpression);
22303
22304 bool IsConstExpr =
22305 ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) &&
22306 // NOTE: We don't produce a diagnostic for this, but the callers that
22307 // call us on arbitrary full-expressions should generally not care.
22308 Info.discardCleanups() && !Status.HasSideEffects;
22309
22310 return IsConstExpr && !Status.DiagEmitted;
22311}
22312
22314 const FunctionDecl *Callee,
22316 const Expr *This) const {
22317 assert(!isValueDependent() &&
22318 "Expression evaluator can't be called on a dependent expression.");
22319
22320 llvm::TimeTraceScope TimeScope("EvaluateWithSubstitution", [&] {
22321 std::string Name;
22322 llvm::raw_string_ostream OS(Name);
22323 Callee->getNameForDiagnostic(OS, Ctx.getPrintingPolicy(),
22324 /*Qualified=*/true);
22325 return Name;
22326 });
22327
22328 Expr::EvalStatus Status;
22329 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantExpressionUnevaluated);
22330 Info.InConstantContext = true;
22331
22332 LValue ThisVal;
22333 const LValue *ThisPtr = nullptr;
22334 if (This) {
22335#ifndef NDEBUG
22336 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
22337 assert(MD && "Don't provide `this` for non-methods.");
22338 assert(MD->isImplicitObjectMemberFunction() &&
22339 "Don't provide `this` for methods without an implicit object.");
22340#endif
22341 if (!This->isValueDependent() &&
22342 EvaluateObjectArgument(Info, This, ThisVal) &&
22343 !Info.EvalStatus.HasSideEffects)
22344 ThisPtr = &ThisVal;
22345
22346 // Ignore any side-effects from a failed evaluation. This is safe because
22347 // they can't interfere with any other argument evaluation.
22348 Info.EvalStatus.HasSideEffects = false;
22349 }
22350
22351 CallRef Call = Info.CurrentCall->createCall(Callee);
22352 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
22353 I != E; ++I) {
22354 unsigned Idx = I - Args.begin();
22355 if (Idx >= Callee->getNumParams())
22356 break;
22357 const ParmVarDecl *PVD = Callee->getParamDecl(Idx);
22358 if ((*I)->isValueDependent() ||
22359 !EvaluateCallArg(PVD, *I, Call, Info) ||
22360 Info.EvalStatus.HasSideEffects) {
22361 // If evaluation fails, throw away the argument entirely.
22362 if (APValue *Slot = Info.getParamSlot(Call, PVD))
22363 *Slot = APValue();
22364 }
22365
22366 // Ignore any side-effects from a failed evaluation. This is safe because
22367 // they can't interfere with any other argument evaluation.
22368 Info.EvalStatus.HasSideEffects = false;
22369 }
22370
22371 // Parameter cleanups happen in the caller and are not part of this
22372 // evaluation.
22373 Info.discardCleanups();
22374 Info.EvalStatus.HasSideEffects = false;
22375
22376 // Build fake call to Callee.
22377 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, This,
22378 Call);
22379 // FIXME: Missing ExprWithCleanups in enable_if conditions?
22380 FullExpressionRAII Scope(Info);
22381 return Evaluate(Value, Info, this) && Scope.destroy() &&
22382 !Info.EvalStatus.HasSideEffects;
22383}
22384
22387 PartialDiagnosticAt> &Diags) {
22388 // FIXME: It would be useful to check constexpr function templates, but at the
22389 // moment the constant expression evaluator cannot cope with the non-rigorous
22390 // ASTs which we build for dependent expressions.
22391 if (FD->isDependentContext())
22392 return true;
22393
22394 llvm::TimeTraceScope TimeScope("isPotentialConstantExpr", [&] {
22395 std::string Name;
22396 llvm::raw_string_ostream OS(Name);
22398 /*Qualified=*/true);
22399 return Name;
22400 });
22401
22402 Expr::EvalStatus Status;
22403 Status.Diag = &Diags;
22404
22405 EvalInfo Info(FD->getASTContext(), Status,
22407 Info.InConstantContext = true;
22408 Info.CheckingPotentialConstantExpression = true;
22409
22410 // The constexpr VM attempts to compile all methods to bytecode here.
22411 if (Info.EnableNewConstInterp) {
22412 Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD);
22413 return Diags.empty();
22414 }
22415
22416 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
22417 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
22418
22419 // Fabricate an arbitrary expression on the stack and pretend that it
22420 // is a temporary being used as the 'this' pointer.
22421 LValue This;
22422 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getCanonicalTagType(RD)
22423 : Info.Ctx.IntTy);
22424 This.set({&VIE, Info.CurrentCall->Index});
22425
22427
22428 APValue Scratch;
22429 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
22430 // Evaluate the call as a constant initializer, to allow the construction
22431 // of objects of non-literal types.
22432 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
22433 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
22434 } else {
22435 SourceLocation Loc = FD->getLocation();
22437 Loc, FD, (MD && MD->isImplicitObjectMemberFunction()) ? &This : nullptr,
22438 &VIE, Args, CallRef(), FD->getBody(), Info, Scratch,
22439 /*ResultSlot=*/nullptr);
22440 }
22441
22442 return Diags.empty();
22443}
22444
22446 const FunctionDecl *FD,
22448 PartialDiagnosticAt> &Diags) {
22449 assert(!E->isValueDependent() &&
22450 "Expression evaluator can't be called on a dependent expression.");
22451
22452 Expr::EvalStatus Status;
22453 Status.Diag = &Diags;
22454
22455 EvalInfo Info(FD->getASTContext(), Status,
22457 Info.InConstantContext = true;
22458 Info.CheckingPotentialConstantExpression = true;
22459
22460 if (Info.EnableNewConstInterp) {
22461 Info.Ctx.getInterpContext().isPotentialConstantExprUnevaluated(Info, E, FD);
22462 return Diags.empty();
22463 }
22464
22465 // Fabricate a call stack frame to give the arguments a plausible cover story.
22466 CallStackFrame Frame(Info, SourceLocation(), FD, /*This=*/nullptr,
22467 /*CallExpr=*/nullptr, CallRef());
22468
22469 APValue ResultScratch;
22470 Evaluate(ResultScratch, Info, E);
22471 return Diags.empty();
22472}
22473
22474std::optional<uint64_t> Expr::tryEvaluateObjectSize(const ASTContext &Ctx,
22475 unsigned Type) const {
22476 if (!getType()->isPointerType())
22477 return std::nullopt;
22478
22479 Expr::EvalStatus Status;
22480 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantFold);
22481 if (Info.EnableNewConstInterp)
22482 return Info.Ctx.getInterpContext().tryEvaluateObjectSize(Info, this, Type);
22483 return tryEvaluateBuiltinObjectSize(this, Type, Info);
22484}
22485
22486static std::optional<uint64_t>
22487EvaluateBuiltinStrLen(const Expr *E, EvalInfo &Info,
22488 std::string *StringResult) {
22489 if (!E->getType()->hasPointerRepresentation() || !E->isPRValue())
22490 return std::nullopt;
22491
22492 LValue String;
22493
22494 if (!EvaluatePointer(E, String, Info))
22495 return std::nullopt;
22496
22497 QualType CharTy = E->getType()->getPointeeType();
22498
22499 // Fast path: if it's a string literal, search the string value.
22500 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
22501 String.getLValueBase().dyn_cast<const Expr *>())) {
22502 StringRef Str = S->getBytes();
22503 int64_t Off = String.Offset.getQuantity();
22504 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
22505 S->getCharByteWidth() == 1 &&
22506 // FIXME: Add fast-path for wchar_t too.
22507 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
22508 Str = Str.substr(Off);
22509
22510 StringRef::size_type Pos = Str.find(0);
22511 if (Pos != StringRef::npos)
22512 Str = Str.substr(0, Pos);
22513
22514 if (StringResult)
22515 *StringResult = Str;
22516 return Str.size();
22517 }
22518
22519 // Fall through to slow path.
22520 }
22521
22522 // Slow path: scan the bytes of the string looking for the terminating 0.
22523 for (uint64_t Strlen = 0; /**/; ++Strlen) {
22524 APValue Char;
22525 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
22526 !Char.isInt())
22527 return std::nullopt;
22528 if (!Char.getInt())
22529 return Strlen;
22530 else if (StringResult)
22531 StringResult->push_back(Char.getInt().getExtValue());
22532 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
22533 return std::nullopt;
22534 }
22535}
22536
22537std::optional<std::string> Expr::tryEvaluateString(ASTContext &Ctx) const {
22538 Expr::EvalStatus Status;
22539 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantFold);
22540 std::string StringResult;
22541
22542 if (Info.EnableNewConstInterp) {
22543 if (!Info.Ctx.getInterpContext().evaluateString(Info, this, StringResult))
22544 return std::nullopt;
22545 return StringResult;
22546 }
22547
22548 if (EvaluateBuiltinStrLen(this, Info, &StringResult))
22549 return StringResult;
22550 return std::nullopt;
22551}
22552
22553template <typename T>
22555 const Expr *SizeExpression,
22556 const Expr *PtrExpression,
22557 ASTContext &Ctx,
22558 Expr::EvalResult &Status) {
22559 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantExpression);
22560 Info.InConstantContext = true;
22561
22562 if (Info.EnableNewConstInterp)
22563 return Info.Ctx.getInterpContext().evaluateCharRange(Info, SizeExpression,
22564 PtrExpression, Result);
22565
22566 LValue String;
22567 FullExpressionRAII Scope(Info);
22568 APSInt SizeValue;
22569 if (!::EvaluateInteger(SizeExpression, SizeValue, Info))
22570 return false;
22571
22572 uint64_t Size = SizeValue.getZExtValue();
22573
22574 // FIXME: better protect against invalid or excessive sizes
22575 if constexpr (std::is_same_v<APValue, T>)
22576 Result = APValue(APValue::UninitArray{}, Size, Size);
22577 else {
22578 if (Size < Result.max_size())
22579 Result.reserve(Size);
22580 }
22581 if (!::EvaluatePointer(PtrExpression, String, Info))
22582 return false;
22583
22584 QualType CharTy = PtrExpression->getType()->getPointeeType();
22585 for (uint64_t I = 0; I < Size; ++I) {
22586 APValue Char;
22587 if (!handleLValueToRValueConversion(Info, PtrExpression, CharTy, String,
22588 Char))
22589 return false;
22590
22591 if constexpr (std::is_same_v<APValue, T>) {
22592 Result.getArrayInitializedElt(I) = std::move(Char);
22593 } else {
22594 APSInt C = Char.getInt();
22595
22596 assert(C.getBitWidth() <= 8 &&
22597 "string element not representable in char");
22598
22599 Result.push_back(static_cast<char>(C.getExtValue()));
22600 }
22601
22602 if (!HandleLValueArrayAdjustment(Info, PtrExpression, String, CharTy, 1))
22603 return false;
22604 }
22605
22606 return Scope.destroy() && CheckMemoryLeaks(Info);
22607}
22608
22610 const Expr *SizeExpression,
22611 const Expr *PtrExpression, ASTContext &Ctx,
22612 EvalResult &Status) const {
22613 return EvaluateCharRangeAsStringImpl(this, Result, SizeExpression,
22614 PtrExpression, Ctx, Status);
22615}
22616
22618 const Expr *SizeExpression,
22619 const Expr *PtrExpression, ASTContext &Ctx,
22620 EvalResult &Status) const {
22621 return EvaluateCharRangeAsStringImpl(this, Result, SizeExpression,
22622 PtrExpression, Ctx, Status);
22623}
22624
22625std::optional<uint64_t> Expr::tryEvaluateStrLen(const ASTContext &Ctx) const {
22626 Expr::EvalStatus Status;
22627 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantFold);
22628
22629 if (Info.EnableNewConstInterp)
22630 return Info.Ctx.getInterpContext().evaluateStrlen(Info, this);
22631 return EvaluateBuiltinStrLen(this, Info);
22632}
22633
22634namespace {
22635struct IsWithinLifetimeHandler {
22636 EvalInfo &Info;
22637 static constexpr AccessKinds AccessKind = AccessKinds::AK_IsWithinLifetime;
22638 using result_type = std::optional<bool>;
22639 std::optional<bool> failed() { return std::nullopt; }
22640 template <typename T>
22641 std::optional<bool> found(T &Subobj, QualType SubobjType,
22643 return true;
22644 }
22645 template <typename T>
22646 std::optional<bool> found(T &Subobj, QualType SubobjType) {
22647 return true;
22648 }
22649};
22650
22651std::optional<bool> EvaluateBuiltinIsWithinLifetime(IntExprEvaluator &IEE,
22652 const CallExpr *E) {
22653 EvalInfo &Info = IEE.Info;
22654 // Sometimes this is called during some sorts of constant folding / early
22655 // evaluation. These are meant for non-constant expressions and are not
22656 // necessary since this consteval builtin will never be evaluated at runtime.
22657 // Just fail to evaluate when not in a constant context.
22658 if (!Info.InConstantContext)
22659 return std::nullopt;
22660 assert(E->getBuiltinCallee() == Builtin::BI__builtin_is_within_lifetime);
22661 const Expr *Arg = E->getArg(0);
22662 if (Arg->isValueDependent())
22663 return std::nullopt;
22664 LValue Val;
22665 if (!EvaluatePointer(Arg, Val, Info))
22666 return std::nullopt;
22667
22668 if (Val.allowConstexprUnknown())
22669 return true;
22670
22671 auto Error = [&](int Diag) {
22672 bool CalledFromStd = false;
22673 const auto *Callee = Info.CurrentCall->getCallee();
22674 if (Callee && Callee->isInStdNamespace()) {
22675 const IdentifierInfo *Identifier = Callee->getIdentifier();
22676 CalledFromStd = Identifier && Identifier->isStr("is_within_lifetime");
22677 }
22678 Info.CCEDiag(CalledFromStd ? Info.CurrentCall->getCallRange().getBegin()
22679 : E->getExprLoc(),
22680 diag::err_invalid_is_within_lifetime)
22681 << (CalledFromStd ? "std::is_within_lifetime"
22682 : "__builtin_is_within_lifetime")
22683 << Diag;
22684 return std::nullopt;
22685 };
22686 // C++2c [meta.const.eval]p4:
22687 // During the evaluation of an expression E as a core constant expression, a
22688 // call to this function is ill-formed unless p points to an object that is
22689 // usable in constant expressions or whose complete object's lifetime began
22690 // within E.
22691
22692 // Make sure it points to an object
22693 // nullptr does not point to an object
22694 if (Val.isNullPointer() || Val.getLValueBase().isNull())
22695 return Error(0);
22696 QualType T = Val.getLValueBase().getType();
22697 assert(!T->isFunctionType() &&
22698 "Pointers to functions should have been typed as function pointers "
22699 "which would have been rejected earlier");
22700 assert(T->isObjectType());
22701 // Hypothetical array element is not an object
22702 if (Val.getLValueDesignator().isOnePastTheEnd())
22703 return Error(1);
22704 assert(Val.getLValueDesignator().isValidSubobject() &&
22705 "Unchecked case for valid subobject");
22706 // All other ill-formed values should have failed EvaluatePointer, so the
22707 // object should be a pointer to an object that is usable in a constant
22708 // expression or whose complete lifetime began within the expression
22709 CompleteObject CO =
22710 findCompleteObject(Info, E, AccessKinds::AK_IsWithinLifetime, Val, T);
22711 // The lifetime hasn't begun yet if we are still evaluating the
22712 // initializer ([basic.life]p(1.2))
22713 if (Info.EvaluatingDeclValue && CO.Value == Info.EvaluatingDeclValue)
22714 return Error(2);
22715
22716 if (!CO)
22717 return false;
22718 IsWithinLifetimeHandler handler{Info};
22719 return findSubobject(Info, E, CO, Val.getLValueDesignator(), handler);
22720}
22721} // 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 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 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 std::optional< uint64_t > tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type, EvalInfo &Info, bool IsDynamic=false)
Tries to evaluate the __builtin_object_size for E. If successful, returns true and stores the 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.
static bool isModification(AccessKinds AK)
Definition Interp.cpp:147
#define X(type, name)
Definition Value.h:97
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Record Record
Definition MachO.h:31
Implements a partial diagnostic which may not be emitted.
llvm::DenseMap< Stmt *, Stmt * > MapTy
Definition ParentMap.cpp:21
llvm::json::Object Object
llvm::json::Array Array
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
Expr * getExpr()
Get 'expr' part of the associated expression/statement.
static QualType getPointeeType(const MemRegion *R)
Enumerates target-specific builtins in their own namespaces within namespace clang.
Defines the clang::TypeLoc interface and its subclasses.
C Language Family Type Representation.
__DEVICE__ long long abs(long long __n)
a trap message and trap category.
llvm::APInt getValue() const
QualType getType() const
Definition APValue.cpp:63
unsigned getVersion() const
Definition APValue.cpp:113
QualType getDynamicAllocType() const
Definition APValue.cpp:122
QualType getTypeInfoType() const
Definition APValue.cpp:117
static LValueBase getTypeInfo(TypeInfoLValue LV, QualType TypeInfo)
Definition APValue.cpp:55
static LValueBase getDynamicAlloc(DynamicAllocLValue LV, QualType Type)
Definition APValue.cpp:47
A non-discriminated union of a base, field, or array index.
Definition APValue.h:208
BaseOrMemberType getAsBaseOrMember() const
Definition APValue.h:222
static LValuePathEntry ArrayIndex(uint64_t Index)
Definition APValue.h:216
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:122
bool hasArrayFiller() const
Definition APValue.h:634
const LValueBase getLValueBase() const
Definition APValue.cpp:1001
APValue & getArrayInitializedElt(unsigned I)
Definition APValue.h:626
void swap(APValue &RHS)
Swaps the contents of this and the given APValue.
Definition APValue.cpp:468
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:1016
const ValueDecl * getMemberPointerDecl() const
Definition APValue.cpp:1084
APValue & getUnionValue()
Definition APValue.h:683
CharUnits & getLValueOffset()
Definition APValue.cpp:1011
void printPretty(raw_ostream &OS, const ASTContext &Ctx, QualType Ty) const
Definition APValue.cpp:703
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:1077
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:974
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:223
SourceManager & getSourceManager()
Definition ASTContext.h:863
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:855
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:4579
OpaqueValueExpr * getCommonExpr() const
Get the common subexpression shared by all initializations (the source array).
Definition Expr.h:5986
Expr * getSubExpr() const
Get the initializer to use for each array element.
Definition Expr.h:5991
Expr * getLHS()
An array access can be written A[4] or 4[A] (both are equivalent).
Definition Expr.h:2756
uint64_t getValue() const
Definition ExprCXX.h:3048
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3786
QualType getElementType() const
Definition TypeBase.h:3798
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition TypeBase.h:8246
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:4459
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression which will be evaluated if the condition evaluates to false; ...
Definition Expr.h:4513
OpaqueValueExpr * getOpaqueValue() const
getOpaqueValue - Return the opaque value placeholder.
Definition Expr.h:4497
Expr * getCommon() const
getCommon - Return the common expression, written to the left of the condition.
Definition Expr.h:4494
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:4044
static bool isLogicalOp(Opcode Opc)
Definition Expr.h:4177
Expr * getLHS() const
Definition Expr.h:4094
static bool isRelationalOp(Opcode Opc)
Definition Expr.h:4138
static bool isComparisonOp(Opcode Opc)
Definition Expr.h:4144
static Opcode getOpForCompoundAssignment(Opcode Opc)
Definition Expr.h:4191
SourceLocation getExprLoc() const
Definition Expr.h:4085
Expr * getRHS() const
Definition Expr.h:4096
static bool isAdditiveOp(Opcode Opc)
Definition Expr.h:4130
static bool isPtrMemOp(Opcode Opc)
predicates to categorize the respective opcodes.
Definition Expr.h:4121
static bool isAssignmentOp(Opcode Opc)
Definition Expr.h:4180
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operator.
Definition Expr.h:4257
Opcode getOpcode() const
Definition Expr.h:4089
static bool isEqualityOp(Opcode Opc)
Definition Expr.h:4141
bool hasCaptures() const
True if this block (or its nested blocks) captures anything of local storage from its enclosing scope...
Definition Decl.h:4813
const BlockDecl * getBlockDecl() const
Definition Expr.h:6687
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:2633
bool isDefaultConstructor() const
Whether this constructor is a default constructor (C++ [class.ctor]p5), which can be used to default-...
Definition DeclCXX.cpp:3047
CXXCtorInitializer *const * init_const_iterator
Iterates through the member/base initializer list.
Definition DeclCXX.h:2716
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:2895
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:2145
bool isExplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An explicit object member function is a non-static member function with an explic...
Definition DeclCXX.cpp:2717
bool isImplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An implicit object member function is a non-static member function without an exp...
Definition DeclCXX.cpp:2724
QualType getFunctionObjectParameterReferenceType() const
Return the type of the object pointed by this.
Definition DeclCXX.cpp:2868
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2284
bool isInstance() const
Definition DeclCXX.h:2172
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition DeclCXX.cpp:2749
bool isStatic() const
Definition DeclCXX.cpp:2415
bool isCopyAssignmentOperator() const
Determine whether this is a copy-assignment operator, regardless of whether it was declared implicitl...
Definition DeclCXX.cpp:2728
bool isLambdaStaticInvoker() const
Determine whether this is a lambda closure type's static member function that is used for the result ...
Definition DeclCXX.cpp:2893
QualType getAllocatedType() const
Definition ExprCXX.h:2438
std::optional< Expr * > getArraySize()
This might return std::nullopt even if isArray() returns true, since there might not be an array size...
Definition ExprCXX.h:2473
Expr * getPlacementArg(unsigned I)
Definition ExprCXX.h:2507
unsigned getNumPlacementArgs() const
Definition ExprCXX.h:2498
SourceRange getSourceRange() const
Definition ExprCXX.h:2614
FunctionDecl * getOperatorNew() const
Definition ExprCXX.h:2463
Expr * getInitializer()
The initializer of this new-expression.
Definition ExprCXX.h:2537
bool getValue() const
Definition ExprCXX.h:4332
MutableArrayRef< Expr * > getInitExprs()
Definition ExprCXX.h:5181
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
bool hasMutableFields() const
Determine whether this class, or any of its class subobjects, contains a mutable field.
Definition DeclCXX.h:1238
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:1377
base_class_range bases()
Definition DeclCXX.h:608
void getCaptureFields(llvm::DenseMap< const ValueDecl *, FieldDecl * > &Captures, FieldDecl *&ThisCapture) const
For a closure type, retrieve the mapping from captured variables and this to the non-static data memb...
Definition DeclCXX.cpp: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:1102
bool isEmpty() const
Determine whether this is an empty class in the sense of (C++11 [meta.unary.prop]).
Definition DeclCXX.h:1191
CXXDestructorDecl * getDestructor() const
Returns the destructor decl for this class.
Definition DeclCXX.cpp:2127
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition DeclCXX.cpp:1742
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:522
unsigned getNumVBases() const
Retrieves the number of virtual base classes of this class.
Definition DeclCXX.h:623
bool isDerivedFrom(const CXXRecordDecl *Base) const
Determine whether this class is derived from the class Base.
Expr * getSemanticForm()
Get an equivalent semantic form for this expression.
Definition ExprCXX.h:308
bool isImplicit() const
Definition ExprCXX.h:1181
bool isTypeOperand() const
Definition ExprCXX.h:888
QualType getTypeOperand(const ASTContext &Context) const
Retrieves the type operand of this typeid() expression after various required adjustments (removing r...
Definition ExprCXX.cpp:166
Expr * getExprOperand() const
Definition ExprCXX.h:899
bool isPotentiallyEvaluated() const
Determine whether this typeid has a type operand which is potentially evaluated, per C++11 [expr....
Definition ExprCXX.cpp:134
MSGuidDecl * getGuidDecl() const
Definition ExprCXX.h:1118
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2949
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3153
SourceLocation getBeginLoc() const
Definition Expr.h:3283
const AllocSizeAttr * getCalleeAllocSizeAttr() const
Try to get the alloc_size attribute of the callee. May return null.
Definition Expr.cpp:3601
unsigned getBuiltinCallee() const
getBuiltinCallee - If this is a call to a builtin, return the builtin ID of the callee.
Definition Expr.cpp:1598
Expr * getCallee()
Definition Expr.h:3096
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition Expr.h:3140
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operator.
Definition Expr.h:3242
Expr ** getArgs()
Retrieve the call arguments.
Definition Expr.h:3143
Decl * getCalleeDecl()
Definition Expr.h:3126
QualType getCallReturnType(const ASTContext &Ctx) const
getCallReturnType - Get the return type of the call expr.
Definition Expr.cpp:1609
CaseStmt - Represent a case statement.
Definition Stmt.h: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:3682
path_iterator path_begin()
Definition Expr.h:3752
unsigned path_size() const
Definition Expr.h:3751
CastKind getCastKind() const
Definition Expr.h:3726
const FieldDecl * getTargetUnionField() const
Definition Expr.h:3776
path_iterator path_end()
Definition Expr.h:3753
const CXXBaseSpecifier *const * path_const_iterator
Definition Expr.h:3749
bool path_empty() const
Definition Expr.h:3750
Expr * getSubExpr()
Definition Expr.h:3732
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operation.
Definition Expr.h:3796
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:1635
Expr * getChosenSubExpr() const
getChosenSubExpr - Return the subexpression chosen according to the condition.
Definition Expr.h:4890
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:3339
QualType getElementType() const
Definition TypeBase.h:3349
CompoundAssignOperator - For compound assignments (e.g.
Definition Expr.h:4306
QualType getComputationLHSType() const
Definition Expr.h:4340
CompoundLiteralExpr - [C99 6.5.2.5].
Definition Expr.h:3611
bool hasStaticStorage() const
Definition Expr.h:3656
APValue & getOrCreateStaticValue(ASTContext &Ctx) const
Definition Expr.cpp:5694
bool isFileScope() const
Definition Expr.h:3643
const Expr * getInitializer() const
Definition Expr.h:3639
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:4397
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression representing the value of the expression if the condition eva...
Definition Expr.h:4429
Expr * getCond() const
getCond - Return the expression representing the condition for the ?
Definition Expr.h:4420
Expr * getTrueExpr() const
getTrueExpr - Return the subexpression representing the value of the expression if the condition eval...
Definition Expr.h:4424
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3824
unsigned getSizeBitWidth() const
Return the bit width of the size type.
Definition TypeBase.h:3887
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:3913
bool isZeroSize() const
Return true if the size is zero.
Definition TypeBase.h:3894
const Expr * getSizeExpr() const
Return a pointer to the size expression.
Definition TypeBase.h:3920
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3880
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition TypeBase.h:3900
APValue getAPValueResult() const
Definition Expr.cpp:419
bool hasAPValueResult() const
Definition Expr.h:1163
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4451
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operator.
Definition Expr.h:4802
Expr * getSrcExpr() const
getSrcExpr - Return the Expr to be converted.
Definition Expr.h:4815
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:1276
bool refersToEnclosingVariableOrCapture() const
Does this DeclRefExpr refer to an enclosing local or a captured variable?
Definition Expr.h:1480
ValueDecl * getDecl()
Definition Expr.h:1344
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:4267
auto flat_bindings() const
Definition DeclCXX.h:4310
InitListExpr * getUpdater() const
Definition Expr.h:5939
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:6584
ChildElementIter< false > begin()
Definition Expr.h:5238
ExplicitCastExpr - An explicit cast written in the source code.
Definition Expr.h:3934
QualType getTypeAsWritten() const
getTypeAsWritten - Returns the type that this expression is casting to, as written in the source code...
Definition Expr.h:3961
This represents one expression.
Definition Expr.h:112
const Expr * skipRValueSubobjectAdjustments(SmallVectorImpl< const Expr * > &CommaLHS, SmallVectorImpl< SubobjectAdjustment > &Adjustments) const
Walk outwards from an expression we want to bind a reference to and find the expression whose lifetim...
Definition Expr.cpp:85
bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsInt - Return true if this is a constant which we can fold and convert to an integer,...
static bool isPotentialConstantExpr(const FunctionDecl *FD, SmallVectorImpl< PartialDiagnosticAt > &Diags)
isPotentialConstantExpr - Return true if this function's definition might be usable in a constant exp...
bool isIntegerConstantExpr(const ASTContext &Ctx) const
static bool isPotentialConstantExprUnevaluated(Expr *E, const FunctionDecl *FD, SmallVectorImpl< PartialDiagnosticAt > &Diags)
isPotentialConstantExprUnevaluated - Return true if this expression might be usable in a constant exp...
bool isGLValue() const
Definition Expr.h:287
SideEffectsKind
Definition Expr.h:677
@ SE_AllowSideEffects
Allow any unmodeled side effect.
Definition Expr.h:681
@ SE_AllowUndefinedBehavior
Allow UB that we can give a value, but not arbitrary unmodeled side effects.
Definition Expr.h:679
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:3104
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:3998
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3099
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:3095
bool EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsLValue - Evaluate an expression to see if we can fold it to an lvalue with link time known ...
bool EvaluateAsInitializer(const ASTContext &Ctx, const VarDecl *VD, EvalResult &Result, bool IsConstantInitializer) const
EvaluateAsInitializer - Evaluate an expression as if it were the initializer of the given declaration...
bool EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsFixedPoint - Return true if this is a constant which we can fold and convert to a fixed poi...
bool isEvaluatable(const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects) const
isEvaluatable - Call EvaluateAsRValue to see if this expression can be constant folded without side-e...
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:3697
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:3262
Expr()=delete
ConstantExprKind
Definition Expr.h:755
std::optional< uint64_t > tryEvaluateObjectSize(const ASTContext &Ctx, unsigned Type) const
If the current Expr is a pointer, this will try to statically determine the number of bytes available...
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:283
QualType getType() const
Definition Expr.h:144
bool isCXX98IntegralConstantExpr(const ASTContext &Ctx) const
isCXX98IntegralConstantExpr - Return true if this expression is an integral constant expression in C+...
bool EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx, const FunctionDecl *Callee, ArrayRef< const Expr * > Args, const Expr *This=nullptr) const
EvaluateWithSubstitution - Evaluate an expression as if from the context of a call to the given funct...
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:4445
void getEncodedElementAccess(SmallVectorImpl< uint32_t > &Elts) const
getEncodedElementAccess - Encode the elements accessed into an llvm aggregate Constant of ConstantInt...
Definition Expr.cpp:4558
bool isFPConstrained() const
LangOptions::FPExceptionModeKind getExceptionMode() const
RoundingMode getRoundingMode() const
Represents a member of a struct/union/class.
Definition Decl.h:3182
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3285
unsigned getBitWidthValue() const
Computes the bit width of this field, if this is a bit field.
Definition Decl.cpp:4748
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition Decl.h:3267
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3418
FieldDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this field.
Definition Decl.h:3429
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition Diagnostic.h:104
llvm::APInt getValue() const
Returns an internal integer representation of the literal.
Definition Expr.h:1581
llvm::APFloat getValue() const
Definition Expr.h:1672
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:1068
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:3255
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition Decl.cpp:4181
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition Decl.cpp:4169
bool hasCXXExplicitFunctionObjectParameter() const
Definition Decl.cpp:3841
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:4305
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:3402
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:3101
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:6471
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:1749
Represents an implicitly-generated value initialization of an object of a given type.
Definition Expr.h:6060
Represents a field injected from an anonymous union/struct into the parent scope.
Definition Decl.h:3489
ArrayRef< NamedDecl * > chain() const
Definition Decl.h:3510
Describes an C or C++ initializer list.
Definition Expr.h:5305
bool isTransparent() const
Is this a transparent initializer list (that is, an InitListExpr that is purely syntactic,...
Definition Expr.cpp:2471
bool isStringLiteralInit() const
Is this an initializer for an array of characters, initialized by a string literal or an @encode?
Definition Expr.cpp:2457
unsigned getNumInits() const
Definition Expr.h:5338
Expr * getArrayFiller()
If this initializer list initializes an array with more elements than there are initializers in the l...
Definition Expr.h:5408
const Expr * getInit(unsigned Init) const
Definition Expr.h:5360
ArrayRef< Expr * > inits() const
Definition Expr.h:5358
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...
bool isCompatibleWith(ClangABI Version) const
Represents a prvalue temporary that is written into memory so that a reference can bind to it.
Definition ExprCXX.h: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:3370
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3453
Expr * getBase() const
Definition Expr.h:3447
bool isArrow() const
Definition Expr.h:3554
This represents a decl that may have a name.
Definition Decl.h:274
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:295
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:301
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:340
void printQualifiedName(raw_ostream &OS) const
Returns a human-readable qualified name for this declaration, like A::B::i, for i being member of nam...
Definition Decl.cpp:1688
bool isExpressibleAsConstantInitializer() const
Definition ExprObjC.h:68
Expr * getIndexExpr(unsigned Idx)
Definition Expr.h:2592
const OffsetOfNode & getComponent(unsigned Idx) const
Definition Expr.h:2580
TypeSourceInfo * getTypeSourceInfo() const
Definition Expr.h:2573
unsigned getNumComponents() const
Definition Expr.h:2588
unsigned getArrayExprIndex() const
For an array element node, returns the index into the array of expressions.
Definition Expr.h:2485
FieldDecl * getField() const
For a field offsetof node, returns the field.
Definition Expr.h:2491
@ Array
An index into an array.
Definition Expr.h:2432
@ Identifier
A field in a dependent type, known only by its name.
Definition Expr.h:2436
@ Field
A field.
Definition Expr.h:2434
@ Base
An implicit indirection through a C++ base class, when the field found is in a base class.
Definition Expr.h:2439
Kind getKind() const
Determine what kind of offsetof node this is.
Definition Expr.h:2481
CXXBaseSpecifier * getBase() const
For a base class node, returns the base specifier.
Definition Expr.h:2501
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition Expr.h:1184
Expr * getSourceExpr() const
The source expression of an opaque value expression is the expression which originally generated the ...
Definition Expr.h:1234
Expr * getSelectedExpr() const
Definition ExprCXX.h:4639
const Expr * getSubExpr() const
Definition Expr.h:2205
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:3392
StringLiteral * getFunctionName()
Definition Expr.h:2055
Expr * getResultExpr()
Return the result-bearing expression, or null if there is none.
Definition Expr.h:6855
ArrayRef< Expr * > semantics()
Definition Expr.h:6879
A (possibly-)qualified type.
Definition TypeBase.h:937
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8531
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition Type.cpp:2966
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:8447
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:8632
QualType getCanonicalType() const
Definition TypeBase.h:8499
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8541
void removeLocalVolatile()
Definition TypeBase.h:8563
void addVolatile()
Add the volatile type qualifier to this QualType.
Definition TypeBase.h:1179
void removeLocalConst()
Definition TypeBase.h:8555
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8520
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:8493
bool isWrapType() const
Returns true if it is a OverflowBehaviorType of Wrap kind.
Definition Type.cpp:3056
Represents a struct/union/class.
Definition Decl.h:4347
unsigned getNumFields() const
Returns the number of fields (non-static data members) in this record.
Definition Decl.h:4563
field_iterator field_end() const
Definition Decl.h:4553
field_range fields() const
Definition Decl.h:4550
specific_decl_iterator< FieldDecl > field_iterator
Definition Decl.h:4547
bool isAnonymousStructOrUnion() const
Whether this is an anonymous struct or union.
Definition Decl.h:4399
bool field_empty() const
Definition Decl.h:4558
field_iterator field_begin() const
Definition Decl.cpp:5271
bool isSatisfied() const
Whether or not the requires clause is satisfied.
SourceLocation getLocation() const
Definition Expr.h:2161
std::string ComputeName(ASTContext &Context) const
Definition Expr.cpp:593
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
ShuffleVectorExpr - clang-specific builtin-in function __builtin_shufflevector.
Definition Expr.h:4649
llvm::APSInt getShuffleMaskIdx(unsigned N) const
Definition Expr.h:4701
unsigned getNumSubExprs() const
getNumSubExprs - Return the size of the SubExprs array.
Definition Expr.h:4682
Expr * getExpr(unsigned Index)
getExpr - Return the Expr at the specified index.
Definition Expr.h:4688
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:2289
bool isIntType() const
Definition Expr.h:5047
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:4618
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:1805
unsigned getLength() const
Definition Expr.h:1915
StringRef getBytes() const
Allow access to clients that need the byte representation, such as ASTWriterStmt::VisitStringLiteral(...
Definition Expr.h:1881
uint32_t getCodeUnit(size_t i) const
Definition Expr.h:1888
StringRef getString() const
Definition Expr.h:1873
unsigned getCharByteWidth() const
Definition Expr.h:1916
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:4895
bool isUnion() const
Definition Decl.h:3950
unsigned size() const
Retrieve the number of template arguments in this template argument list.
ArrayRef< TemplateArgument > asArray() const
Produce this as an array ref.
@ Type
The template argument is a type.
Symbolic representation of typeid(T) for some type T.
Definition APValue.h:44
QualType getType() const
Return the type wrapped by this type source info.
Definition TypeBase.h:8429
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:9050
bool isBooleanType() const
Definition TypeBase.h:9187
bool isFunctionReferenceType() const
Definition TypeBase.h:8758
bool isMFloat8Type() const
Definition TypeBase.h:9075
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:3113
bool isIncompleteArrayType() const
Definition TypeBase.h:8791
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:9353
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:8787
bool isNothrowT() const
Definition Type.cpp:3297
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:8783
bool isFunctionPointerType() const
Definition TypeBase.h:8751
bool isCountAttributedType() const
Definition Type.cpp:778
bool isConstantMatrixType() const
Definition TypeBase.h:8851
bool isPointerType() const
Definition TypeBase.h:8684
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9094
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9344
bool isReferenceType() const
Definition TypeBase.h:8708
bool isEnumeralType() const
Definition TypeBase.h:8815
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:8795
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:9172
bool isExtVectorBoolType() const
Definition TypeBase.h:8831
bool isMemberDataPointerType() const
Definition TypeBase.h:8776
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition TypeBase.h:9019
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2846
RecordDecl * castAsRecordDecl() const
Definition Type.h:48
bool isAnyComplexType() const
Definition TypeBase.h:8819
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9110
bool isMemberPointerType() const
Definition TypeBase.h:8765
bool isAtomicType() const
Definition TypeBase.h:8876
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:9330
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:8680
bool isVectorType() const
Definition TypeBase.h:8823
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:2992
bool isAnyPointerType() const
Definition TypeBase.h:8692
TypeClass getTypeClass() const
Definition TypeBase.h:2445
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9277
bool isNullPtrType() const
Definition TypeBase.h:9087
bool isRecordType() const
Definition TypeBase.h:8811
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:9221
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand.
Definition Expr.h:2631
QualType getArgumentType() const
Definition Expr.h:2674
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:2710
QualType getTypeOfArgument() const
Gets the argument type, or the type of the argument expression, whichever is appropriate.
Definition Expr.h:2700
UnaryExprOrTypeTrait getKind() const
Definition Expr.h:2663
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2250
SourceLocation getExprLoc() const
Definition Expr.h:2374
Expr * getSubExpr() const
Definition Expr.h:2291
Opcode getOpcode() const
Definition Expr.h:2286
static bool isIncrementOp(Opcode Op)
Definition Expr.h:2332
bool canOverflow() const
Returns true if the unary operator can cause an overflow.
Definition Expr.h:2304
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:5577
QualType getType() const
Definition Value.cpp:238
bool hasValue() const
Definition Value.h:135
Represents a variable declaration or definition.
Definition Decl.h:924
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition Decl.h:1582
bool hasInit() const
Definition Decl.cpp:2377
bool hasICEInitializer(const ASTContext &Context) const
Determine whether the initializer of this variable is an integer constant expression.
Definition Decl.cpp:2617
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition Decl.h:1591
APValue * evaluateValue() const
Attempt to evaluate the value of the initializer attached to this declaration, and produce notes expl...
Definition Decl.cpp:2554
CharUnits getFlexibleArrayInitChars(const ASTContext &Ctx) const
If hasFlexibleArrayInit is true, compute the number of additional bytes necessary to store those elem...
Definition Decl.cpp:2837
bool hasConstantInitialization() const
Determine whether this variable has constant initialization.
Definition Decl.cpp:2629
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
Definition Decl.cpp:2345
bool mightBeUsableInConstantExpressions(const ASTContext &C) const
Determine whether this variable's value might be usable in a constant expression, according to the re...
Definition Decl.cpp:2465
EvaluatedStmt * ensureEvaluatedStmt() const
Convert the initializer for this declaration to the elaborated EvaluatedStmt form,...
Definition Decl.cpp:2536
bool evaluateDestruction(SmallVectorImpl< PartialDiagnosticAt > &Notes) const
Evaluate the destruction of this variable to determine if it constitutes constant destruction.
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition Decl.h:1206
ThreadStorageClassSpecifier getTSCSpec() const
Definition Decl.h:1175
const Expr * getInit() const
Definition Decl.h:1381
APValue * getEvaluatedValue() const
Return the already-evaluated value of this variable's initializer, or NULL if the value is not yet kn...
Definition Decl.cpp:2609
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition Decl.h:1182
DefinitionKind hasDefinition(ASTContext &) const
Check whether this variable is defined in this translation unit.
Definition Decl.cpp:2354
bool isLocalVarDecl() const
Returns true for local variable declarations other than parameters.
Definition Decl.h:1266
bool isUsableInConstantExpressions(const ASTContext &C) const
Determine whether this variable's value can be used in a constant expression, according to the releva...
Definition Decl.cpp:2507
const Expr * getAnyInitializer() const
Get the initializer for this variable, no matter which declaration it is attached to.
Definition Decl.h:1371
Expr * getSizeExpr() const
Definition TypeBase.h:4044
Represents a GCC generic vector type.
Definition TypeBase.h:4239
unsigned getNumElements() const
Definition TypeBase.h:4254
QualType getElementType() const
Definition TypeBase.h:4253
WhileStmt - This represents a 'while' stmt.
Definition Stmt.h:2707
Expr * getCond()
Definition Stmt.h:2759
VarDecl * getConditionVariable()
Retrieve the variable declared in this "while" statement, if any.
Definition Stmt.cpp:1247
Stmt * getBody()
Definition Stmt.h:2771
bool evaluateDestruction(State &Parent, const VarDecl *VD, APValue Value)
Evaluates the destruction of a variable.
Definition Context.cpp:164
Base class for stack frames, shared between VM and walker.
Definition Frame.h:25
Interface for the VM to interact with the AST walker's context.
Definition State.h:81
Defines the clang::TargetInfo interface.
#define CHAR_BIT
Definition limits.h:71
#define UINT_MAX
Definition limits.h:64
bool computeOSLogBufferLayout(clang::ASTContext &Ctx, const clang::CallExpr *E, OSLogBufferLayout &layout)
Definition OSLog.cpp:192
static const FunctionDecl * getCallee(const CXXConstructExpr &D)
uint32_t Literal
Literals are represented as positive integers.
Definition CNFFormula.h:35
unsigned kind
All of the diagnostics that can be emitted by the frontend.
std::optional< llvm::AllocTokenMetadata > getAllocTokenMetadata(QualType T, const ASTContext &Ctx)
Get the information required for construction of an allocation token ID.
QualType inferPossibleType(const CallExpr *E, const ASTContext &Ctx, const CastExpr *CastE)
Infer the possible allocated type from an allocation call expression.
bool Sub(InterpState &S, CodePtr OpPC)
Definition Interp.h:424
bool NE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1499
llvm::FixedPointSemantics FixedPointSemantics
Definition Interp.h:56
bool This(InterpState &S, CodePtr OpPC)
Definition Interp.h:3167
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:3875
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
const Expr * findStructFieldAccess(const Expr *E, const Expr **OutArrayIndex=nullptr, QualType *OutArrayElementTy=nullptr)
Walk E through parens, implicit casts, unary &/*, array subscripts and comma operators to find the he...
Definition Expr.cpp:5759
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:1048
@ Self
'self' clause, allowed on Compute and Combined Constructs, plus 'update'.
bool operator==(const CallGraphNode::CallRecord &LHS, const CallGraphNode::CallRecord &RHS)
Definition CallGraph.h:207
@ 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:176
@ 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:5981
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
Diagnostic wrappers for TextAPI types for error reporting.
Definition Dominators.h:30
hash_code hash_value(const clang::dependencies::ModuleID &ID)
__packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 int32_t
__packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 __packed_splat2 uint8_t
__packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 __packed_splat2 __packed_splat4 uint16_t
__packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 __packed_splat2 __packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 uint32_t
#define false
Definition stdbool.h:26
unsigned PathLength
The corresponding path length in the lvalue.
const CXXRecordDecl * Type
The dynamic class type of the object.
std::string ObjCEncodeStorage
Represents an element in a path from a derived class to a base class.
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:652
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:654
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:640
bool HasSideEffects
Whether the evaluated expression has side effects.
Definition Expr.h:615
unsigned SuppressLambdaBody
Whether to suppress printing the body of a lambda.
DenseMapInfo< APValue::LValueBase > Base
static unsigned getHashValue(const ObjectUnderConstruction &Object)
static bool isEqual(const ObjectUnderConstruction &LHS, const ObjectUnderConstruction &RHS)
#define ilogb(__x)
Definition tgmath.h:851
#define scalbn(__x, __y)
Definition tgmath.h:1165