Debian Codegraph @

clang/lib/AST/ExprConstant.cpp

raw
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"
40 #include "clang/AST/ASTContext.h"
41 #include "clang/AST/ASTLambda.h"
42 #include "clang/AST/Attr.h"
43 #include "clang/AST/CXXInheritance.h"
44 #include "clang/AST/CharUnits.h"
45 #include "clang/AST/CurrentSourceLocExprScope.h"
46 #include "clang/AST/Expr.h"
47 #include "clang/AST/InferAlloc.h"
48 #include "clang/AST/OSLog.h"
49 #include "clang/AST/OptionalDiagnostic.h"
50 #include "clang/AST/RecordLayout.h"
51 #include "clang/AST/StmtVisitor.h"
52 #include "clang/AST/Type.h"
53 #include "clang/AST/TypeLoc.h"
54 #include "clang/Basic/Builtins.h"
55 #include "clang/Basic/DiagnosticSema.h"
56 #include "clang/Basic/TargetBuiltins.h"
57 #include "clang/Basic/TargetInfo.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
75 using namespace clang;
76 using llvm::APFixedPoint;
77 using llvm::APInt;
78 using llvm::APSInt;
79 using llvm::APFloat;
80 using llvm::FixedPointSemantics;
81
82 namespace {
83 struct LValue;
84 class CallStackFrame;
85 class EvalInfo;
86
87 using SourceLocExprScopeGuard =
88 CurrentSourceLocExprScope::SourceLocExprScopeGuard;
89
90 static QualType getType(APValue::LValueBase B) {
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,
191 ArrayRef<APValue::LValuePathEntry> Path,
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.
280 SmallVector<PathEntry, 8> Entries;
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] {
649 return E->getSourceRange().printToString(Ctx.getSourceManager());
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
670 static bool HandleDestruction(EvalInfo &Info, const Expr *E,
671 const LValue &This, QualType ThisType);
672 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
673 APValue::LValueBase LVBase, APValue &Value,
674 QualType T);
675
676 namespace {
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
733 namespace llvm {
734 template<> struct DenseMapInfo<ObjectUnderConstruction> {
735 using Base = DenseMapInfo<APValue::LValueBase>;
736 static ObjectUnderConstruction getEmptyKey() {
737 return {Base::getEmptyKey(), {}}; }
738 static ObjectUnderConstruction getTombstoneKey() {
739 return {Base::getTombstoneKey(), {}};
740 }
741 static unsigned getHashValue(const ObjectUnderConstruction &Object) {
742 return hash_value(Object);
743 }
744 static bool isEqual(const ObjectUnderConstruction &LHS,
745 const ObjectUnderConstruction &RHS) {
746 return LHS == RHS;
747 }
748 };
749 }
750
751 namespace {
752 /// A dynamically-allocated heap object.
753 struct DynAlloc {
754 /// The value of this heap-allocated object.
755 APValue Value;
756 /// The allocating expression; used for diagnostics. Either a CXXNewExpr
757 /// or a CallExpr (the latter is for direct calls to operator new inside
758 /// std::allocator<T>::allocate).
759 const Expr *AllocExpr = nullptr;
760
761 enum Kind {
762 New,
763 ArrayNew,
764 StdAllocator
765 };
766
767 /// Get the kind of the allocation. This must match between allocation
768 /// and deallocation.
769 Kind getKind() const {
770 if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr))
771 return NE->isArray() ? ArrayNew : New;
772 assert(isa<CallExpr>(AllocExpr));
773 return StdAllocator;
774 }
775 };
776
777 struct DynAllocOrder {
778 bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const {
779 return L.getIndex() < R.getIndex();
780 }
781 };
782
783 /// EvalInfo - This is a private struct used by the evaluator to capture
784 /// information about a subexpression as it is folded. It retains information
785 /// about the AST context, but also maintains information about the folded
786 /// expression.
787 ///
788 /// If an expression could be evaluated, it is still possible it is not a C
789 /// "integer constant expression" or constant expression. If not, this struct
790 /// captures information about how and why not.
791 ///
792 /// One bit of information passed *into* the request for constant folding
793 /// indicates whether the subexpression is "evaluated" or not according to C
794 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
795 /// evaluate the expression regardless of what the RHS is, but C only allows
796 /// certain things in certain situations.
797 class EvalInfo : public interp::State {
798 public:
799 ASTContext &Ctx;
800
801 /// EvalStatus - Contains information about the evaluation.
802 Expr::EvalStatus &EvalStatus;
803
804 /// CurrentCall - The top of the constexpr call stack.
805 CallStackFrame *CurrentCall;
806
807 /// CallStackDepth - The number of calls in the call stack right now.
808 unsigned CallStackDepth;
809
810 /// NextCallIndex - The next call index to assign.
811 unsigned NextCallIndex;
812
813 /// StepsLeft - The remaining number of evaluation steps we're permitted
814 /// to perform. This is essentially a limit for the number of statements
815 /// we will evaluate.
816 unsigned StepsLeft;
817
818 /// Enable the experimental new constant interpreter. If an expression is
819 /// not supported by the interpreter, an error is triggered.
820 bool EnableNewConstInterp;
821
822 /// BottomFrame - The frame in which evaluation started. This must be
823 /// initialized after CurrentCall and CallStackDepth.
824 CallStackFrame BottomFrame;
825
826 /// A stack of values whose lifetimes end at the end of some surrounding
827 /// evaluation frame.
828 llvm::SmallVector<Cleanup, 16> CleanupStack;
829
830 /// EvaluatingDecl - This is the declaration whose initializer is being
831 /// evaluated, if any.
832 APValue::LValueBase EvaluatingDecl;
833
834 enum class EvaluatingDeclKind {
835 None,
836 /// We're evaluating the construction of EvaluatingDecl.
837 Ctor,
838 /// We're evaluating the destruction of EvaluatingDecl.
839 Dtor,
840 };
841 EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None;
842
843 /// EvaluatingDeclValue - This is the value being constructed for the
844 /// declaration whose initializer is being evaluated, if any.
845 APValue *EvaluatingDeclValue;
846
847 /// Stack of loops and 'switch' statements which we're currently
848 /// breaking/continuing; null entries are used to mark unlabeled
849 /// break/continue.
850 SmallVector<const Stmt *> BreakContinueStack;
851
852 /// Set of objects that are currently being constructed.
853 llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
854 ObjectsUnderConstruction;
855
856 /// Current heap allocations, along with the location where each was
857 /// allocated. We use std::map here because we need stable addresses
858 /// for the stored APValues.
859 std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs;
860
861 /// The number of heap allocations performed so far in this evaluation.
862 unsigned NumHeapAllocs = 0;
863
864 struct EvaluatingConstructorRAII {
865 EvalInfo &EI;
866 ObjectUnderConstruction Object;
867 bool DidInsert;
868 EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
869 bool HasBases)
870 : EI(EI), Object(Object) {
871 DidInsert =
872 EI.ObjectsUnderConstruction
873 .insert({Object, HasBases ? ConstructionPhase::Bases
874 : ConstructionPhase::AfterBases})
875 .second;
876 }
877 void finishedConstructingBases() {
878 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
879 }
880 void finishedConstructingFields() {
881 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields;
882 }
883 ~EvaluatingConstructorRAII() {
884 if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
885 }
886 };
887
888 struct EvaluatingDestructorRAII {
889 EvalInfo &EI;
890 ObjectUnderConstruction Object;
891 bool DidInsert;
892 EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object)
893 : EI(EI), Object(Object) {
894 DidInsert = EI.ObjectsUnderConstruction
895 .insert({Object, ConstructionPhase::Destroying})
896 .second;
897 }
898 void startedDestroyingBases() {
899 EI.ObjectsUnderConstruction[Object] =
900 ConstructionPhase::DestroyingBases;
901 }
902 ~EvaluatingDestructorRAII() {
903 if (DidInsert)
904 EI.ObjectsUnderConstruction.erase(Object);
905 }
906 };
907
908 ConstructionPhase
909 isEvaluatingCtorDtor(APValue::LValueBase Base,
910 ArrayRef<APValue::LValuePathEntry> Path) {
911 return ObjectsUnderConstruction.lookup({Base, Path});
912 }
913
914 /// If we're currently speculatively evaluating, the outermost call stack
915 /// depth at which we can mutate state, otherwise 0.
916 unsigned SpeculativeEvaluationDepth = 0;
917
918 /// The current array initialization index, if we're performing array
919 /// initialization.
920 uint64_t ArrayInitIndex = -1;
921
922 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
923 /// notes attached to it will also be stored, otherwise they will not be.
924 bool HasActiveDiagnostic;
925
926 /// Have we emitted a diagnostic explaining why we couldn't constant
927 /// fold (not just why it's not strictly a constant expression)?
928 bool HasFoldFailureDiagnostic;
929
930 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
931 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
932 CallStackDepth(0), NextCallIndex(1),
933 StepsLeft(C.getLangOpts().ConstexprStepLimit),
934 EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp),
935 BottomFrame(*this, SourceLocation(), /*Callee=*/nullptr,
936 /*This=*/nullptr,
937 /*CallExpr=*/nullptr, CallRef()),
938 EvaluatingDecl((const ValueDecl *)nullptr),
939 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
940 HasFoldFailureDiagnostic(false) {
941 EvalMode = Mode;
942 }
943
944 ~EvalInfo() {
945 discardCleanups();
946 }
947
948 ASTContext &getASTContext() const override { return Ctx; }
949 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
950
951 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value,
952 EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) {
953 EvaluatingDecl = Base;
954 IsEvaluatingDecl = EDK;
955 EvaluatingDeclValue = &Value;
956 }
957
958 bool CheckCallLimit(SourceLocation Loc) {
959 // Don't perform any constexpr calls (other than the call we're checking)
960 // when checking a potential constant expression.
961 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
962 return false;
963 if (NextCallIndex == 0) {
964 // NextCallIndex has wrapped around.
965 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
966 return false;
967 }
968 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
969 return true;
970 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
971 << getLangOpts().ConstexprCallDepth;
972 return false;
973 }
974
975 bool CheckArraySize(SourceLocation Loc, unsigned BitWidth,
976 uint64_t ElemCount, bool Diag) {
977 // FIXME: GH63562
978 // APValue stores array extents as unsigned,
979 // so anything that is greater that unsigned would overflow when
980 // constructing the array, we catch this here.
981 if (BitWidth > ConstantArrayType::getMaxSizeBits(Ctx) ||
982 ElemCount > uint64_t(std::numeric_limits<unsigned>::max())) {
983 if (Diag)
984 FFDiag(Loc, diag::note_constexpr_new_too_large) << ElemCount;
985 return false;
986 }
987
988 // FIXME: GH63562
989 // Arrays allocate an APValue per element.
990 // We use the number of constexpr steps as a proxy for the maximum size
991 // of arrays to avoid exhausting the system resources, as initialization
992 // of each element is likely to take some number of steps anyway.
993 uint64_t Limit = Ctx.getLangOpts().ConstexprStepLimit;
994 if (Limit != 0 && ElemCount > Limit) {
995 if (Diag)
996 FFDiag(Loc, diag::note_constexpr_new_exceeds_limits)
997 << ElemCount << Limit;
998 return false;
999 }
1000 return true;
1001 }
1002
1003 std::pair<CallStackFrame *, unsigned>
1004 getCallFrameAndDepth(unsigned CallIndex) {
1005 assert(CallIndex && "no call index in getCallFrameAndDepth");
1006 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
1007 // be null in this loop.
1008 unsigned Depth = CallStackDepth;
1009 CallStackFrame *Frame = CurrentCall;
1010 while (Frame->Index > CallIndex) {
1011 Frame = Frame->Caller;
1012 --Depth;
1013 }
1014 if (Frame->Index == CallIndex)
1015 return {Frame, Depth};
1016 return {nullptr, 0};
1017 }
1018
1019 bool nextStep(const Stmt *S) {
1020 if (Ctx.getLangOpts().ConstexprStepLimit == 0)
1021 return true;
1022
1023 if (!StepsLeft) {
1024 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
1025 return false;
1026 }
1027 --StepsLeft;
1028 return true;
1029 }
1030
1031 APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV);
1032
1033 std::optional<DynAlloc *> lookupDynamicAlloc(DynamicAllocLValue DA) {
1034 std::optional<DynAlloc *> Result;
1035 auto It = HeapAllocs.find(DA);
1036 if (It != HeapAllocs.end())
1037 Result = &It->second;
1038 return Result;
1039 }
1040
1041 /// Get the allocated storage for the given parameter of the given call.
1042 APValue *getParamSlot(CallRef Call, const ParmVarDecl *PVD) {
1043 CallStackFrame *Frame = getCallFrameAndDepth(Call.CallIndex).first;
1044 return Frame ? Frame->getTemporary(Call.getOrigParam(PVD), Call.Version)
1045 : nullptr;
1046 }
1047
1048 /// Information about a stack frame for std::allocator<T>::[de]allocate.
1049 struct StdAllocatorCaller {
1050 unsigned FrameIndex;
1051 QualType ElemType;
1052 const Expr *Call;
1053 explicit operator bool() const { return FrameIndex != 0; };
1054 };
1055
1056 StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const {
1057 for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame;
1058 Call = Call->Caller) {
1059 const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee);
1060 if (!MD)
1061 continue;
1062 const IdentifierInfo *FnII = MD->getIdentifier();
1063 if (!FnII || !FnII->isStr(FnName))
1064 continue;
1065
1066 const auto *CTSD =
1067 dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent());
1068 if (!CTSD)
1069 continue;
1070
1071 const IdentifierInfo *ClassII = CTSD->getIdentifier();
1072 const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
1073 if (CTSD->isInStdNamespace() && ClassII &&
1074 ClassII->isStr("allocator") && TAL.size() >= 1 &&
1075 TAL[0].getKind() == TemplateArgument::Type)
1076 return {Call->Index, TAL[0].getAsType(), Call->CallExpr};
1077 }
1078
1079 return {};
1080 }
1081
1082 void performLifetimeExtension() {
1083 // Disable the cleanups for lifetime-extended temporaries.
1084 llvm::erase_if(CleanupStack, [](Cleanup &C) {
1085 return !C.isDestroyedAtEndOf(ScopeKind::FullExpression);
1086 });
1087 }
1088
1089 /// Throw away any remaining cleanups at the end of evaluation. If any
1090 /// cleanups would have had a side-effect, note that as an unmodeled
1091 /// side-effect and return false. Otherwise, return true.
1092 bool discardCleanups() {
1093 for (Cleanup &C : CleanupStack) {
1094 if (C.hasSideEffect() && !noteSideEffect()) {
1095 CleanupStack.clear();
1096 return false;
1097 }
1098 }
1099 CleanupStack.clear();
1100 return true;
1101 }
1102
1103 private:
1104 interp::Frame *getCurrentFrame() override { return CurrentCall; }
1105 const interp::Frame *getBottomFrame() const override { return &BottomFrame; }
1106
1107 bool hasActiveDiagnostic() override { return HasActiveDiagnostic; }
1108 void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; }
1109
1110 void setFoldFailureDiagnostic(bool Flag) override {
1111 HasFoldFailureDiagnostic = Flag;
1112 }
1113
1114 Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; }
1115
1116 // If we have a prior diagnostic, it will be noting that the expression
1117 // isn't a constant expression. This diagnostic is more important,
1118 // unless we require this evaluation to produce a constant expression.
1119 //
1120 // FIXME: We might want to show both diagnostics to the user in
1121 // EvaluationMode::ConstantFold mode.
1122 bool hasPriorDiagnostic() override {
1123 if (!EvalStatus.Diag->empty()) {
1124 switch (EvalMode) {
1125 case EvaluationMode::ConstantFold:
1126 case EvaluationMode::IgnoreSideEffects:
1127 if (!HasFoldFailureDiagnostic)
1128 break;
1129 // We've already failed to fold something. Keep that diagnostic.
1130 [[fallthrough]];
1131 case EvaluationMode::ConstantExpression:
1132 case EvaluationMode::ConstantExpressionUnevaluated:
1133 setActiveDiagnostic(false);
1134 return true;
1135 }
1136 }
1137 return false;
1138 }
1139
1140 unsigned getCallStackDepth() override { return CallStackDepth; }
1141
1142 public:
1143 /// Should we continue evaluation after encountering a side-effect that we
1144 /// couldn't model?
1145 bool keepEvaluatingAfterSideEffect() const override {
1146 switch (EvalMode) {
1147 case EvaluationMode::IgnoreSideEffects:
1148 return true;
1149
1150 case EvaluationMode::ConstantExpression:
1151 case EvaluationMode::ConstantExpressionUnevaluated:
1152 case EvaluationMode::ConstantFold:
1153 // By default, assume any side effect might be valid in some other
1154 // evaluation of this expression from a different context.
1155 return checkingPotentialConstantExpression() ||
1156 checkingForUndefinedBehavior();
1157 }
1158 llvm_unreachable("Missed EvalMode case");
1159 }
1160
1161 /// Note that we have had a side-effect, and determine whether we should
1162 /// keep evaluating.
1163 bool noteSideEffect() override {
1164 EvalStatus.HasSideEffects = true;
1165 return keepEvaluatingAfterSideEffect();
1166 }
1167
1168 /// Should we continue evaluation after encountering undefined behavior?
1169 bool keepEvaluatingAfterUndefinedBehavior() {
1170 switch (EvalMode) {
1171 case EvaluationMode::IgnoreSideEffects:
1172 case EvaluationMode::ConstantFold:
1173 return true;
1174
1175 case EvaluationMode::ConstantExpression:
1176 case EvaluationMode::ConstantExpressionUnevaluated:
1177 return checkingForUndefinedBehavior();
1178 }
1179 llvm_unreachable("Missed EvalMode case");
1180 }
1181
1182 /// Note that we hit something that was technically undefined behavior, but
1183 /// that we can evaluate past it (such as signed overflow or floating-point
1184 /// division by zero.)
1185 bool noteUndefinedBehavior() override {
1186 EvalStatus.HasUndefinedBehavior = true;
1187 return keepEvaluatingAfterUndefinedBehavior();
1188 }
1189
1190 /// Should we continue evaluation as much as possible after encountering a
1191 /// construct which can't be reduced to a value?
1192 bool keepEvaluatingAfterFailure() const override {
1193 uint64_t Limit = Ctx.getLangOpts().ConstexprStepLimit;
1194 if (Limit != 0 && !StepsLeft)
1195 return false;
1196
1197 switch (EvalMode) {
1198 case EvaluationMode::ConstantExpression:
1199 case EvaluationMode::ConstantExpressionUnevaluated:
1200 case EvaluationMode::ConstantFold:
1201 case EvaluationMode::IgnoreSideEffects:
1202 return checkingPotentialConstantExpression() ||
1203 checkingForUndefinedBehavior();
1204 }
1205 llvm_unreachable("Missed EvalMode case");
1206 }
1207
1208 /// Notes that we failed to evaluate an expression that other expressions
1209 /// directly depend on, and determine if we should keep evaluating. This
1210 /// should only be called if we actually intend to keep evaluating.
1211 ///
1212 /// Call noteSideEffect() instead if we may be able to ignore the value that
1213 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1214 ///
1215 /// (Foo(), 1) // use noteSideEffect
1216 /// (Foo() || true) // use noteSideEffect
1217 /// Foo() + 1 // use noteFailure
1218 [[nodiscard]] bool noteFailure() {
1219 // Failure when evaluating some expression often means there is some
1220 // subexpression whose evaluation was skipped. Therefore, (because we
1221 // don't track whether we skipped an expression when unwinding after an
1222 // evaluation failure) every evaluation failure that bubbles up from a
1223 // subexpression implies that a side-effect has potentially happened. We
1224 // skip setting the HasSideEffects flag to true until we decide to
1225 // continue evaluating after that point, which happens here.
1226 bool KeepGoing = keepEvaluatingAfterFailure();
1227 EvalStatus.HasSideEffects |= KeepGoing;
1228 return KeepGoing;
1229 }
1230
1231 class ArrayInitLoopIndex {
1232 EvalInfo &Info;
1233 uint64_t OuterIndex;
1234
1235 public:
1236 ArrayInitLoopIndex(EvalInfo &Info)
1237 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1238 Info.ArrayInitIndex = 0;
1239 }
1240 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1241
1242 operator uint64_t&() { return Info.ArrayInitIndex; }
1243 };
1244 };
1245
1246 /// Object used to treat all foldable expressions as constant expressions.
1247 struct FoldConstant {
1248 EvalInfo &Info;
1249 bool Enabled;
1250 bool HadNoPriorDiags;
1251 EvaluationMode OldMode;
1252
1253 explicit FoldConstant(EvalInfo &Info, bool Enabled)
1254 : Info(Info),
1255 Enabled(Enabled),
1256 HadNoPriorDiags(Info.EvalStatus.Diag &&
1257 Info.EvalStatus.Diag->empty() &&
1258 !Info.EvalStatus.HasSideEffects),
1259 OldMode(Info.EvalMode) {
1260 if (Enabled)
1261 Info.EvalMode = EvaluationMode::ConstantFold;
1262 }
1263 void keepDiagnostics() { Enabled = false; }
1264 ~FoldConstant() {
1265 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
1266 !Info.EvalStatus.HasSideEffects)
1267 Info.EvalStatus.Diag->clear();
1268 Info.EvalMode = OldMode;
1269 }
1270 };
1271
1272 /// RAII object used to set the current evaluation mode to ignore
1273 /// side-effects.
1274 struct IgnoreSideEffectsRAII {
1275 EvalInfo &Info;
1276 EvaluationMode OldMode;
1277 explicit IgnoreSideEffectsRAII(EvalInfo &Info)
1278 : Info(Info), OldMode(Info.EvalMode) {
1279 Info.EvalMode = EvaluationMode::IgnoreSideEffects;
1280 }
1281
1282 ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
1283 };
1284
1285 /// RAII object used to optionally suppress diagnostics and side-effects from
1286 /// a speculative evaluation.
1287 class SpeculativeEvaluationRAII {
1288 EvalInfo *Info = nullptr;
1289 Expr::EvalStatus OldStatus;
1290 unsigned OldSpeculativeEvaluationDepth = 0;
1291
1292 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1293 Info = Other.Info;
1294 OldStatus = Other.OldStatus;
1295 OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
1296 Other.Info = nullptr;
1297 }
1298
1299 void maybeRestoreState() {
1300 if (!Info)
1301 return;
1302
1303 Info->EvalStatus = OldStatus;
1304 Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
1305 }
1306
1307 public:
1308 SpeculativeEvaluationRAII() = default;
1309
1310 SpeculativeEvaluationRAII(
1311 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1312 : Info(&Info), OldStatus(Info.EvalStatus),
1313 OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
1314 Info.EvalStatus.Diag = NewDiag;
1315 Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
1316 }
1317
1318 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1319 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1320 moveFromAndCancel(std::move(Other));
1321 }
1322
1323 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1324 maybeRestoreState();
1325 moveFromAndCancel(std::move(Other));
1326 return *this;
1327 }
1328
1329 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1330 };
1331
1332 /// RAII object wrapping a full-expression or block scope, and handling
1333 /// the ending of the lifetime of temporaries created within it.
1334 template<ScopeKind Kind>
1335 class ScopeRAII {
1336 EvalInfo &Info;
1337 unsigned OldStackSize;
1338 public:
1339 ScopeRAII(EvalInfo &Info)
1340 : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1341 // Push a new temporary version. This is needed to distinguish between
1342 // temporaries created in different iterations of a loop.
1343 Info.CurrentCall->pushTempVersion();
1344 }
1345 bool destroy(bool RunDestructors = true) {
1346 bool OK = cleanup(Info, RunDestructors, OldStackSize);
1347 OldStackSize = std::numeric_limits<unsigned>::max();
1348 return OK;
1349 }
1350 ~ScopeRAII() {
1351 if (OldStackSize != std::numeric_limits<unsigned>::max())
1352 destroy(false);
1353 // Body moved to a static method to encourage the compiler to inline away
1354 // instances of this class.
1355 Info.CurrentCall->popTempVersion();
1356 }
1357 private:
1358 static bool cleanup(EvalInfo &Info, bool RunDestructors,
1359 unsigned OldStackSize) {
1360 assert(OldStackSize <= Info.CleanupStack.size() &&
1361 "running cleanups out of order?");
1362
1363 // Run all cleanups for a block scope, and non-lifetime-extended cleanups
1364 // for a full-expression scope.
1365 bool Success = true;
1366 for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) {
1367 if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) {
1368 if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) {
1369 Success = false;
1370 break;
1371 }
1372 }
1373 }
1374
1375 // Compact any retained cleanups.
1376 auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
1377 if (Kind != ScopeKind::Block)
1378 NewEnd =
1379 std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) {
1380 return C.isDestroyedAtEndOf(Kind);
1381 });
1382 Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
1383 return Success;
1384 }
1385 };
1386 typedef ScopeRAII<ScopeKind::Block> BlockScopeRAII;
1387 typedef ScopeRAII<ScopeKind::FullExpression> FullExpressionRAII;
1388 typedef ScopeRAII<ScopeKind::Call> CallScopeRAII;
1389 }
1390
1391 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1392 CheckSubobjectKind CSK) {
1393 if (Invalid)
1394 return false;
1395 if (isOnePastTheEnd()) {
1396 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1397 << CSK;
1398 setInvalid();
1399 return false;
1400 }
1401 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1402 // must actually be at least one array element; even a VLA cannot have a
1403 // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1404 return true;
1405 }
1406
1407 void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1408 const Expr *E) {
1409 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1410 // Do not set the designator as invalid: we can represent this situation,
1411 // and correct handling of __builtin_object_size requires us to do so.
1412 }
1413
1414 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1415 const Expr *E,
1416 const APSInt &N) {
1417 // If we're complaining, we must be able to statically determine the size of
1418 // the most derived array.
1419 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1420 Info.CCEDiag(E, diag::note_constexpr_array_index)
1421 << N << /*array*/ 0
1422 << static_cast<unsigned>(getMostDerivedArraySize());
1423 else
1424 Info.CCEDiag(E, diag::note_constexpr_array_index)
1425 << N << /*non-array*/ 1;
1426 setInvalid();
1427 }
1428
1429 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceRange CallRange,
1430 const FunctionDecl *Callee, const LValue *This,
1431 const Expr *CallExpr, CallRef Call)
1432 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1433 CallExpr(CallExpr), Arguments(Call), CallRange(CallRange),
1434 Index(Info.NextCallIndex++) {
1435 Info.CurrentCall = this;
1436 ++Info.CallStackDepth;
1437 }
1438
1439 CallStackFrame::~CallStackFrame() {
1440 assert(Info.CurrentCall == this && "calls retired out of order");
1441 --Info.CallStackDepth;
1442 Info.CurrentCall = Caller;
1443 }
1444
1445 static bool isRead(AccessKinds AK) {
1446 return AK == AK_Read || AK == AK_ReadObjectRepresentation ||
1447 AK == AK_IsWithinLifetime || AK == AK_Dereference;
1448 }
1449
1450 static bool isModification(AccessKinds AK) {
1451 switch (AK) {
1452 case AK_Read:
1453 case AK_ReadObjectRepresentation:
1454 case AK_MemberCall:
1455 case AK_DynamicCast:
1456 case AK_TypeId:
1457 case AK_IsWithinLifetime:
1458 case AK_Dereference:
1459 return false;
1460 case AK_Assign:
1461 case AK_Increment:
1462 case AK_Decrement:
1463 case AK_Construct:
1464 case AK_Destroy:
1465 return true;
1466 }
1467 llvm_unreachable("unknown access kind");
1468 }
1469
1470 static bool isAnyAccess(AccessKinds AK) {
1471 return isRead(AK) || isModification(AK);
1472 }
1473
1474 /// Is this an access per the C++ definition?
1475 static bool isFormalAccess(AccessKinds AK) {
1476 return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy &&
1477 AK != AK_IsWithinLifetime && AK != AK_Dereference;
1478 }
1479
1480 /// Is this kind of access valid on an indeterminate object value?
1481 static bool isValidIndeterminateAccess(AccessKinds AK) {
1482 switch (AK) {
1483 case AK_Read:
1484 case AK_Increment:
1485 case AK_Decrement:
1486 case AK_Dereference:
1487 // These need the object's value.
1488 return false;
1489
1490 case AK_IsWithinLifetime:
1491 case AK_ReadObjectRepresentation:
1492 case AK_Assign:
1493 case AK_Construct:
1494 case AK_Destroy:
1495 // Construction and destruction don't need the value.
1496 return true;
1497
1498 case AK_MemberCall:
1499 case AK_DynamicCast:
1500 case AK_TypeId:
1501 // These aren't really meaningful on scalars.
1502 return true;
1503 }
1504 llvm_unreachable("unknown access kind");
1505 }
1506
1507 namespace {
1508 struct ComplexValue {
1509 private:
1510 bool IsInt;
1511
1512 public:
1513 APSInt IntReal, IntImag;
1514 APFloat FloatReal, FloatImag;
1515
1516 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1517
1518 void makeComplexFloat() { IsInt = false; }
1519 bool isComplexFloat() const { return !IsInt; }
1520 APFloat &getComplexFloatReal() { return FloatReal; }
1521 APFloat &getComplexFloatImag() { return FloatImag; }
1522
1523 void makeComplexInt() { IsInt = true; }
1524 bool isComplexInt() const { return IsInt; }
1525 APSInt &getComplexIntReal() { return IntReal; }
1526 APSInt &getComplexIntImag() { return IntImag; }
1527
1528 void moveInto(APValue &v) const {
1529 if (isComplexFloat())
1530 v = APValue(FloatReal, FloatImag);
1531 else
1532 v = APValue(IntReal, IntImag);
1533 }
1534 void setFrom(const APValue &v) {
1535 assert(v.isComplexFloat() || v.isComplexInt());
1536 if (v.isComplexFloat()) {
1537 makeComplexFloat();
1538 FloatReal = v.getComplexFloatReal();
1539 FloatImag = v.getComplexFloatImag();
1540 } else {
1541 makeComplexInt();
1542 IntReal = v.getComplexIntReal();
1543 IntImag = v.getComplexIntImag();
1544 }
1545 }
1546 };
1547
1548 struct LValue {
1549 APValue::LValueBase Base;
1550 CharUnits Offset;
1551 SubobjectDesignator Designator;
1552 bool IsNullPtr : 1;
1553 bool InvalidBase : 1;
1554 // P2280R4 track if we have an unknown reference or pointer.
1555 bool AllowConstexprUnknown = false;
1556
1557 const APValue::LValueBase getLValueBase() const { return Base; }
1558 bool allowConstexprUnknown() const { return AllowConstexprUnknown; }
1559 CharUnits &getLValueOffset() { return Offset; }
1560 const CharUnits &getLValueOffset() const { return Offset; }
1561 SubobjectDesignator &getLValueDesignator() { return Designator; }
1562 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1563 bool isNullPointer() const { return IsNullPtr;}
1564
1565 unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1566 unsigned getLValueVersion() const { return Base.getVersion(); }
1567
1568 void moveInto(APValue &V) const {
1569 if (Designator.Invalid)
1570 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
1571 else {
1572 assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1573 V = APValue(Base, Offset, Designator.Entries,
1574 Designator.IsOnePastTheEnd, IsNullPtr);
1575 }
1576 if (AllowConstexprUnknown)
1577 V.setConstexprUnknown();
1578 }
1579 void setFrom(const ASTContext &Ctx, const APValue &V) {
1580 assert(V.isLValue() && "Setting LValue from a non-LValue?");
1581 Base = V.getLValueBase();
1582 Offset = V.getLValueOffset();
1583 InvalidBase = false;
1584 Designator = SubobjectDesignator(Ctx, V);
1585 IsNullPtr = V.isNullPointer();
1586 AllowConstexprUnknown = V.allowConstexprUnknown();
1587 }
1588
1589 void set(APValue::LValueBase B, bool BInvalid = false) {
1590 #ifndef NDEBUG
1591 // We only allow a few types of invalid bases. Enforce that here.
1592 if (BInvalid) {
1593 const auto *E = B.get<const Expr *>();
1594 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1595 "Unexpected type of invalid base");
1596 }
1597 #endif
1598
1599 Base = B;
1600 Offset = CharUnits::fromQuantity(0);
1601 InvalidBase = BInvalid;
1602 Designator = SubobjectDesignator(getType(B));
1603 IsNullPtr = false;
1604 AllowConstexprUnknown = false;
1605 }
1606
1607 void setNull(ASTContext &Ctx, QualType PointerTy) {
1608 Base = (const ValueDecl *)nullptr;
1609 Offset =
1610 CharUnits::fromQuantity(Ctx.getTargetNullPointerValue(PointerTy));
1611 InvalidBase = false;
1612 Designator = SubobjectDesignator(PointerTy->getPointeeType());
1613 IsNullPtr = true;
1614 AllowConstexprUnknown = false;
1615 }
1616
1617 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1618 set(B, true);
1619 }
1620
1621 std::string toString(ASTContext &Ctx, QualType T) const {
1622 APValue Printable;
1623 moveInto(Printable);
1624 return Printable.getAsString(Ctx, T);
1625 }
1626
1627 private:
1628 // Check that this LValue is not based on a null pointer. If it is, produce
1629 // a diagnostic and mark the designator as invalid.
1630 template <typename GenDiagType>
1631 bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
1632 if (Designator.Invalid)
1633 return false;
1634 if (IsNullPtr) {
1635 GenDiag();
1636 Designator.setInvalid();
1637 return false;
1638 }
1639 return true;
1640 }
1641
1642 public:
1643 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1644 CheckSubobjectKind CSK) {
1645 return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1646 Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1647 });
1648 }
1649
1650 bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1651 AccessKinds AK) {
1652 return checkNullPointerDiagnosingWith([&Info, E, AK] {
1653 if (AK == AccessKinds::AK_Dereference)
1654 Info.FFDiag(E, diag::note_constexpr_dereferencing_null);
1655 else
1656 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1657 });
1658 }
1659
1660 // Check this LValue refers to an object. If not, set the designator to be
1661 // invalid and emit a diagnostic.
1662 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1663 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1664 Designator.checkSubobject(Info, E, CSK);
1665 }
1666
1667 void addDecl(EvalInfo &Info, const Expr *E,
1668 const Decl *D, bool Virtual = false) {
1669 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1670 Designator.addDeclUnchecked(D, Virtual);
1671 }
1672 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1673 if (!Designator.Entries.empty()) {
1674 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1675 Designator.setInvalid();
1676 return;
1677 }
1678 if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1679 assert(getType(Base).getNonReferenceType()->isPointerType() ||
1680 getType(Base).getNonReferenceType()->isArrayType());
1681 Designator.FirstEntryIsAnUnsizedArray = true;
1682 Designator.addUnsizedArrayUnchecked(ElemTy);
1683 }
1684 }
1685 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1686 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1687 Designator.addArrayUnchecked(CAT);
1688 }
1689 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1690 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1691 Designator.addComplexUnchecked(EltTy, Imag);
1692 }
1693 void addVectorElement(EvalInfo &Info, const Expr *E, QualType EltTy,
1694 uint64_t Size, uint64_t Idx) {
1695 if (checkSubobject(Info, E, CSK_VectorElement))
1696 Designator.addVectorElementUnchecked(EltTy, Size, Idx);
1697 }
1698 void clearIsNullPointer() {
1699 IsNullPtr = false;
1700 }
1701 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1702 const APSInt &Index, CharUnits ElementSize) {
1703 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1704 // but we're not required to diagnose it and it's valid in C++.)
1705 if (!Index)
1706 return;
1707
1708 // Compute the new offset in the appropriate width, wrapping at 64 bits.
1709 // FIXME: When compiling for a 32-bit target, we should use 32-bit
1710 // offsets.
1711 uint64_t Offset64 = Offset.getQuantity();
1712 uint64_t ElemSize64 = ElementSize.getQuantity();
1713 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1714 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1715
1716 if (checkNullPointer(Info, E, CSK_ArrayIndex))
1717 Designator.adjustIndex(Info, E, Index, *this);
1718 clearIsNullPointer();
1719 }
1720 void adjustOffset(CharUnits N) {
1721 Offset += N;
1722 if (N.getQuantity())
1723 clearIsNullPointer();
1724 }
1725 };
1726
1727 struct MemberPtr {
1728 MemberPtr() {}
1729 explicit MemberPtr(const ValueDecl *Decl)
1730 : DeclAndIsDerivedMember(Decl, false) {}
1731
1732 /// The member or (direct or indirect) field referred to by this member
1733 /// pointer, or 0 if this is a null member pointer.
1734 const ValueDecl *getDecl() const {
1735 return DeclAndIsDerivedMember.getPointer();
1736 }
1737 /// Is this actually a member of some type derived from the relevant class?
1738 bool isDerivedMember() const {
1739 return DeclAndIsDerivedMember.getInt();
1740 }
1741 /// Get the class which the declaration actually lives in.
1742 const CXXRecordDecl *getContainingRecord() const {
1743 return cast<CXXRecordDecl>(
1744 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1745 }
1746
1747 void moveInto(APValue &V) const {
1748 V = APValue(getDecl(), isDerivedMember(), Path);
1749 }
1750 void setFrom(const APValue &V) {
1751 assert(V.isMemberPointer());
1752 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1753 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1754 Path.clear();
1755 llvm::append_range(Path, V.getMemberPointerPath());
1756 }
1757
1758 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1759 /// whether the member is a member of some class derived from the class type
1760 /// of the member pointer.
1761 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1762 /// Path - The path of base/derived classes from the member declaration's
1763 /// class (exclusive) to the class type of the member pointer (inclusive).
1764 SmallVector<const CXXRecordDecl*, 4> Path;
1765
1766 /// Perform a cast towards the class of the Decl (either up or down the
1767 /// hierarchy).
1768 bool castBack(const CXXRecordDecl *Class) {
1769 assert(!Path.empty());
1770 const CXXRecordDecl *Expected;
1771 if (Path.size() >= 2)
1772 Expected = Path[Path.size() - 2];
1773 else
1774 Expected = getContainingRecord();
1775 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1776 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1777 // if B does not contain the original member and is not a base or
1778 // derived class of the class containing the original member, the result
1779 // of the cast is undefined.
1780 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1781 // (D::*). We consider that to be a language defect.
1782 return false;
1783 }
1784 Path.pop_back();
1785 return true;
1786 }
1787 /// Perform a base-to-derived member pointer cast.
1788 bool castToDerived(const CXXRecordDecl *Derived) {
1789 if (!getDecl())
1790 return true;
1791 if (!isDerivedMember()) {
1792 Path.push_back(Derived);
1793 return true;
1794 }
1795 if (!castBack(Derived))
1796 return false;
1797 if (Path.empty())
1798 DeclAndIsDerivedMember.setInt(false);
1799 return true;
1800 }
1801 /// Perform a derived-to-base member pointer cast.
1802 bool castToBase(const CXXRecordDecl *Base) {
1803 if (!getDecl())
1804 return true;
1805 if (Path.empty())
1806 DeclAndIsDerivedMember.setInt(true);
1807 if (isDerivedMember()) {
1808 Path.push_back(Base);
1809 return true;
1810 }
1811 return castBack(Base);
1812 }
1813 };
1814
1815 /// Compare two member pointers, which are assumed to be of the same type.
1816 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1817 if (!LHS.getDecl() || !RHS.getDecl())
1818 return !LHS.getDecl() && !RHS.getDecl();
1819 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1820 return false;
1821 return LHS.Path == RHS.Path;
1822 }
1823 }
1824
1825 void SubobjectDesignator::adjustIndex(EvalInfo &Info, const Expr *E, APSInt N,
1826 const LValue &LV) {
1827 if (Invalid || !N)
1828 return;
1829 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
1830 if (isMostDerivedAnUnsizedArray()) {
1831 diagnoseUnsizedArrayPointerArithmetic(Info, E);
1832 // Can't verify -- trust that the user is doing the right thing (or if
1833 // not, trust that the caller will catch the bad behavior).
1834 // FIXME: Should we reject if this overflows, at least?
1835 Entries.back() =
1836 PathEntry::ArrayIndex(Entries.back().getAsArrayIndex() + TruncatedN);
1837 return;
1838 }
1839
1840 // [expr.add]p4: For the purposes of these operators, a pointer to a
1841 // nonarray object behaves the same as a pointer to the first element of
1842 // an array of length one with the type of the object as its element type.
1843 bool IsArray =
1844 MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement;
1845 uint64_t ArrayIndex =
1846 IsArray ? Entries.back().getAsArrayIndex() : (uint64_t)IsOnePastTheEnd;
1847 uint64_t ArraySize = IsArray ? getMostDerivedArraySize() : (uint64_t)1;
1848
1849 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
1850 if (!Info.checkingPotentialConstantExpression() ||
1851 !LV.AllowConstexprUnknown) {
1852 // Calculate the actual index in a wide enough type, so we can include
1853 // it in the note.
1854 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
1855 (llvm::APInt &)N += ArrayIndex;
1856 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
1857 diagnosePointerArithmetic(Info, E, N);
1858 }
1859 setInvalid();
1860 return;
1861 }
1862
1863 ArrayIndex += TruncatedN;
1864 assert(ArrayIndex <= ArraySize &&
1865 "bounds check succeeded for out-of-bounds index");
1866
1867 if (IsArray)
1868 Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
1869 else
1870 IsOnePastTheEnd = (ArrayIndex != 0);
1871 }
1872
1873 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1874 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1875 const LValue &This, const Expr *E,
1876 bool AllowNonLiteralTypes = false);
1877 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1878 bool InvalidBaseOK = false);
1879 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1880 bool InvalidBaseOK = false);
1881 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1882 EvalInfo &Info);
1883 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1884 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1885 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1886 EvalInfo &Info);
1887 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1888 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1889 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1890 EvalInfo &Info);
1891 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1892 static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,
1893 EvalInfo &Info,
1894 std::string *StringResult = nullptr);
1895
1896 /// Evaluate an integer or fixed point expression into an APResult.
1897 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1898 EvalInfo &Info);
1899
1900 /// Evaluate only a fixed point expression into an APResult.
1901 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1902 EvalInfo &Info);
1903
1904 //===----------------------------------------------------------------------===//
1905 // Misc utilities
1906 //===----------------------------------------------------------------------===//
1907
1908 /// Negate an APSInt in place, converting it to a signed form if necessary, and
1909 /// preserving its value (by extending by up to one bit as needed).
1910 static void negateAsSigned(APSInt &Int) {
1911 if (Int.isUnsigned() || Int.isMinSignedValue()) {
1912 Int = Int.extend(Int.getBitWidth() + 1);
1913 Int.setIsSigned(true);
1914 }
1915 Int = -Int;
1916 }
1917
1918 template<typename KeyT>
1919 APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T,
1920 ScopeKind Scope, LValue &LV) {
1921 unsigned Version = getTempVersion();
1922 APValue::LValueBase Base(Key, Index, Version);
1923 LV.set(Base);
1924 return createLocal(Base, Key, T, Scope);
1925 }
1926
1927 /// Allocate storage for a parameter of a function call made in this frame.
1928 APValue &CallStackFrame::createParam(CallRef Args, const ParmVarDecl *PVD,
1929 LValue &LV) {
1930 assert(Args.CallIndex == Index && "creating parameter in wrong frame");
1931 APValue::LValueBase Base(PVD, Index, Args.Version);
1932 LV.set(Base);
1933 // We always destroy parameters at the end of the call, even if we'd allow
1934 // them to live to the end of the full-expression at runtime, in order to
1935 // give portable results and match other compilers.
1936 return createLocal(Base, PVD, PVD->getType(), ScopeKind::Call);
1937 }
1938
1939 APValue &CallStackFrame::createLocal(APValue::LValueBase Base, const void *Key,
1940 QualType T, ScopeKind Scope) {
1941 assert(Base.getCallIndex() == Index && "lvalue for wrong frame");
1942 unsigned Version = Base.getVersion();
1943 APValue &Result = Temporaries[MapKeyTy(Key, Version)];
1944 assert(Result.isAbsent() && "local created multiple times");
1945
1946 // If we're creating a local immediately in the operand of a speculative
1947 // evaluation, don't register a cleanup to be run outside the speculative
1948 // evaluation context, since we won't actually be able to initialize this
1949 // object.
1950 if (Index <= Info.SpeculativeEvaluationDepth) {
1951 if (T.isDestructedType())
1952 Info.noteSideEffect();
1953 } else {
1954 Info.CleanupStack.push_back(Cleanup(&Result, Base, T, Scope));
1955 }
1956 return Result;
1957 }
1958
1959 APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) {
1960 if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) {
1961 FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded);
1962 return nullptr;
1963 }
1964
1965 DynamicAllocLValue DA(NumHeapAllocs++);
1966 LV.set(APValue::LValueBase::getDynamicAlloc(DA, T));
1967 auto Result = HeapAllocs.emplace(std::piecewise_construct,
1968 std::forward_as_tuple(DA), std::tuple<>());
1969 assert(Result.second && "reused a heap alloc index?");
1970 Result.first->second.AllocExpr = E;
1971 return &Result.first->second.Value;
1972 }
1973
1974 /// Produce a string describing the given constexpr call.
1975 void CallStackFrame::describe(raw_ostream &Out) const {
1976 unsigned ArgIndex = 0;
1977 bool IsMemberCall =
1978 isa<CXXMethodDecl>(Callee) && !isa<CXXConstructorDecl>(Callee) &&
1979 cast<CXXMethodDecl>(Callee)->isImplicitObjectMemberFunction();
1980
1981 if (!IsMemberCall)
1982 Callee->getNameForDiagnostic(Out, Info.Ctx.getPrintingPolicy(),
1983 /*Qualified=*/false);
1984
1985 if (This && IsMemberCall) {
1986 if (const auto *MCE = dyn_cast_if_present<CXXMemberCallExpr>(CallExpr)) {
1987 const Expr *Object = MCE->getImplicitObjectArgument();
1988 Object->printPretty(Out, /*Helper=*/nullptr, Info.Ctx.getPrintingPolicy(),
1989 /*Indentation=*/0);
1990 if (Object->getType()->isPointerType())
1991 Out << "->";
1992 else
1993 Out << ".";
1994 } else if (const auto *OCE =
1995 dyn_cast_if_present<CXXOperatorCallExpr>(CallExpr)) {
1996 OCE->getArg(0)->printPretty(Out, /*Helper=*/nullptr,
1997 Info.Ctx.getPrintingPolicy(),
1998 /*Indentation=*/0);
1999 Out << ".";
2000 } else {
2001 APValue Val;
2002 This->moveInto(Val);
2003 Val.printPretty(
2004 Out, Info.Ctx,
2005 Info.Ctx.getLValueReferenceType(This->Designator.MostDerivedType));
2006 Out << ".";
2007 }
2008 Callee->getNameForDiagnostic(Out, Info.Ctx.getPrintingPolicy(),
2009 /*Qualified=*/false);
2010 IsMemberCall = false;
2011 }
2012
2013 Out << '(';
2014
2015 for (FunctionDecl::param_const_iterator I = Callee->param_begin(),
2016 E = Callee->param_end(); I != E; ++I, ++ArgIndex) {
2017 if (ArgIndex > (unsigned)IsMemberCall)
2018 Out << ", ";
2019
2020 const ParmVarDecl *Param = *I;
2021 APValue *V = Info.getParamSlot(Arguments, Param);
2022 if (V)
2023 V->printPretty(Out, Info.Ctx, Param->getType());
2024 else
2025 Out << "<...>";
2026
2027 if (ArgIndex == 0 && IsMemberCall)
2028 Out << "->" << *Callee << '(';
2029 }
2030
2031 Out << ')';
2032 }
2033
2034 /// Evaluate an expression to see if it had side-effects, and discard its
2035 /// result.
2036 /// \return \c true if the caller should keep evaluating.
2037 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
2038 assert(!E->isValueDependent());
2039 APValue Scratch;
2040 if (!Evaluate(Scratch, Info, E))
2041 // We don't need the value, but we might have skipped a side effect here.
2042 return Info.noteSideEffect();
2043 return true;
2044 }
2045
2046 /// Should this call expression be treated as forming an opaque constant?
2047 static bool IsOpaqueConstantCall(const CallExpr *E) {
2048 unsigned Builtin = E->getBuiltinCallee();
2049 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
2050 Builtin == Builtin::BI__builtin___NSStringMakeConstantString ||
2051 Builtin == Builtin::BI__builtin_ptrauth_sign_constant ||
2052 Builtin == Builtin::BI__builtin_function_start);
2053 }
2054
2055 static bool IsOpaqueConstantCall(const LValue &LVal) {
2056 const auto *BaseExpr =
2057 llvm::dyn_cast_if_present<CallExpr>(LVal.Base.dyn_cast<const Expr *>());
2058 return BaseExpr && IsOpaqueConstantCall(BaseExpr);
2059 }
2060
2061 static bool IsGlobalLValue(APValue::LValueBase B) {
2062 // C++11 [expr.const]p3 An address constant expression is a prvalue core
2063 // constant expression of pointer type that evaluates to...
2064
2065 // ... a null pointer value, or a prvalue core constant expression of type
2066 // std::nullptr_t.
2067 if (!B)
2068 return true;
2069
2070 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
2071 // ... the address of an object with static storage duration,
2072 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
2073 return VD->hasGlobalStorage();
2074 if (isa<TemplateParamObjectDecl>(D))
2075 return true;
2076 // ... the address of a function,
2077 // ... the address of a GUID [MS extension],
2078 // ... the address of an unnamed global constant
2079 return isa<FunctionDecl, MSGuidDecl, UnnamedGlobalConstantDecl>(D);
2080 }
2081
2082 if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>())
2083 return true;
2084
2085 const Expr *E = B.get<const Expr*>();
2086 switch (E->getStmtClass()) {
2087 default:
2088 return false;
2089 case Expr::CompoundLiteralExprClass: {
2090 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
2091 return CLE->isFileScope() && CLE->isLValue();
2092 }
2093 case Expr::MaterializeTemporaryExprClass:
2094 // A materialized temporary might have been lifetime-extended to static
2095 // storage duration.
2096 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
2097 // A string literal has static storage duration.
2098 case Expr::StringLiteralClass:
2099 case Expr::PredefinedExprClass:
2100 case Expr::ObjCStringLiteralClass:
2101 case Expr::ObjCEncodeExprClass:
2102 return true;
2103 case Expr::ObjCBoxedExprClass:
2104 return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
2105 case Expr::CallExprClass:
2106 return IsOpaqueConstantCall(cast<CallExpr>(E));
2107 // For GCC compatibility, &&label has static storage duration.
2108 case Expr::AddrLabelExprClass:
2109 return true;
2110 // A Block literal expression may be used as the initialization value for
2111 // Block variables at global or local static scope.
2112 case Expr::BlockExprClass:
2113 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
2114 // The APValue generated from a __builtin_source_location will be emitted as a
2115 // literal.
2116 case Expr::SourceLocExprClass:
2117 return true;
2118 case Expr::ImplicitValueInitExprClass:
2119 // FIXME:
2120 // We can never form an lvalue with an implicit value initialization as its
2121 // base through expression evaluation, so these only appear in one case: the
2122 // implicit variable declaration we invent when checking whether a constexpr
2123 // constructor can produce a constant expression. We must assume that such
2124 // an expression might be a global lvalue.
2125 return true;
2126 }
2127 }
2128
2129 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
2130 return LVal.Base.dyn_cast<const ValueDecl*>();
2131 }
2132
2133 // Information about an LValueBase that is some kind of string.
2134 struct LValueBaseString {
2135 std::string ObjCEncodeStorage;
2136 StringRef Bytes;
2137 int CharWidth;
2138 };
2139
2140 // Gets the lvalue base of LVal as a string.
2141 static bool GetLValueBaseAsString(const EvalInfo &Info, const LValue &LVal,
2142 LValueBaseString &AsString) {
2143 const auto *BaseExpr = LVal.Base.dyn_cast<const Expr *>();
2144 if (!BaseExpr)
2145 return false;
2146
2147 // For ObjCEncodeExpr, we need to compute and store the string.
2148 if (const auto *EE = dyn_cast<ObjCEncodeExpr>(BaseExpr)) {
2149 Info.Ctx.getObjCEncodingForType(EE->getEncodedType(),
2150 AsString.ObjCEncodeStorage);
2151 AsString.Bytes = AsString.ObjCEncodeStorage;
2152 AsString.CharWidth = 1;
2153 return true;
2154 }
2155
2156 // Otherwise, we have a StringLiteral.
2157 const auto *Lit = dyn_cast<StringLiteral>(BaseExpr);
2158 if (const auto *PE = dyn_cast<PredefinedExpr>(BaseExpr))
2159 Lit = PE->getFunctionName();
2160
2161 if (!Lit)
2162 return false;
2163
2164 AsString.Bytes = Lit->getBytes();
2165 AsString.CharWidth = Lit->getCharByteWidth();
2166 return true;
2167 }
2168
2169 // Determine whether two string literals potentially overlap. This will be the
2170 // case if they agree on the values of all the bytes on the overlapping region
2171 // between them.
2172 //
2173 // The overlapping region is the portion of the two string literals that must
2174 // overlap in memory if the pointers actually point to the same address at
2175 // runtime. For example, if LHS is "abcdef" + 3 and RHS is "cdef\0gh" + 1 then
2176 // the overlapping region is "cdef\0", which in this case does agree, so the
2177 // strings are potentially overlapping. Conversely, for "foobar" + 3 versus
2178 // "bazbar" + 3, the overlapping region contains all of both strings, so they
2179 // are not potentially overlapping, even though they agree from the given
2180 // addresses onwards.
2181 //
2182 // See open core issue CWG2765 which is discussing the desired rule here.
2183 static bool ArePotentiallyOverlappingStringLiterals(const EvalInfo &Info,
2184 const LValue &LHS,
2185 const LValue &RHS) {
2186 LValueBaseString LHSString, RHSString;
2187 if (!GetLValueBaseAsString(Info, LHS, LHSString) ||
2188 !GetLValueBaseAsString(Info, RHS, RHSString))
2189 return false;
2190
2191 // This is the byte offset to the location of the first character of LHS
2192 // within RHS. We don't need to look at the characters of one string that
2193 // would appear before the start of the other string if they were merged.
2194 CharUnits Offset = RHS.Offset - LHS.Offset;
2195 if (Offset.isNegative()) {
2196 if (LHSString.Bytes.size() < (size_t)-Offset.getQuantity())
2197 return false;
2198 LHSString.Bytes = LHSString.Bytes.drop_front(-Offset.getQuantity());
2199 } else {
2200 if (RHSString.Bytes.size() < (size_t)Offset.getQuantity())
2201 return false;
2202 RHSString.Bytes = RHSString.Bytes.drop_front(Offset.getQuantity());
2203 }
2204
2205 bool LHSIsLonger = LHSString.Bytes.size() > RHSString.Bytes.size();
2206 StringRef Longer = LHSIsLonger ? LHSString.Bytes : RHSString.Bytes;
2207 StringRef Shorter = LHSIsLonger ? RHSString.Bytes : LHSString.Bytes;
2208 int ShorterCharWidth = (LHSIsLonger ? RHSString : LHSString).CharWidth;
2209
2210 // The null terminator isn't included in the string data, so check for it
2211 // manually. If the longer string doesn't have a null terminator where the
2212 // shorter string ends, they aren't potentially overlapping.
2213 for (int NullByte : llvm::seq(ShorterCharWidth)) {
2214 if (Shorter.size() + NullByte >= Longer.size())
2215 break;
2216 if (Longer[Shorter.size() + NullByte])
2217 return false;
2218 }
2219
2220 // Otherwise, they're potentially overlapping if and only if the overlapping
2221 // region is the same.
2222 return Shorter == Longer.take_front(Shorter.size());
2223 }
2224
2225 static bool IsWeakLValue(const LValue &Value) {
2226 const ValueDecl *Decl = GetLValueBaseDecl(Value);
2227 return Decl && Decl->isWeak();
2228 }
2229
2230 static bool isZeroSized(const LValue &Value) {
2231 const ValueDecl *Decl = GetLValueBaseDecl(Value);
2232 if (isa_and_nonnull<VarDecl>(Decl)) {
2233 QualType Ty = Decl->getType();
2234 if (Ty->isArrayType())
2235 return Ty->isIncompleteType() ||
2236 Decl->getASTContext().getTypeSize(Ty) == 0;
2237 }
2238 return false;
2239 }
2240
2241 static bool HasSameBase(const LValue &A, const LValue &B) {
2242 if (!A.getLValueBase())
2243 return !B.getLValueBase();
2244 if (!B.getLValueBase())
2245 return false;
2246
2247 if (A.getLValueBase().getOpaqueValue() !=
2248 B.getLValueBase().getOpaqueValue())
2249 return false;
2250
2251 return A.getLValueCallIndex() == B.getLValueCallIndex() &&
2252 A.getLValueVersion() == B.getLValueVersion();
2253 }
2254
2255 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
2256 assert(Base && "no location for a null lvalue");
2257 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2258
2259 // For a parameter, find the corresponding call stack frame (if it still
2260 // exists), and point at the parameter of the function definition we actually
2261 // invoked.
2262 if (auto *PVD = dyn_cast_or_null<ParmVarDecl>(VD)) {
2263 unsigned Idx = PVD->getFunctionScopeIndex();
2264 for (CallStackFrame *F = Info.CurrentCall; F; F = F->Caller) {
2265 if (F->Arguments.CallIndex == Base.getCallIndex() &&
2266 F->Arguments.Version == Base.getVersion() && F->Callee &&
2267 Idx < F->Callee->getNumParams()) {
2268 VD = F->Callee->getParamDecl(Idx);
2269 break;
2270 }
2271 }
2272 }
2273
2274 if (VD)
2275 Info.Note(VD->getLocation(), diag::note_declared_at);
2276 else if (const Expr *E = Base.dyn_cast<const Expr*>())
2277 Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
2278 else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
2279 // FIXME: Produce a note for dangling pointers too.
2280 if (std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA))
2281 Info.Note((*Alloc)->AllocExpr->getExprLoc(),
2282 diag::note_constexpr_dynamic_alloc_here);
2283 }
2284
2285 // We have no information to show for a typeid(T) object.
2286 }
2287
2288 enum class CheckEvaluationResultKind {
2289 ConstantExpression,
2290 FullyInitialized,
2291 };
2292
2293 /// Materialized temporaries that we've already checked to determine if they're
2294 /// initializsed by a constant expression.
2295 using CheckedTemporaries =
2296 llvm::SmallPtrSet<const MaterializeTemporaryExpr *, 8>;
2297
2298 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2299 EvalInfo &Info, SourceLocation DiagLoc,
2300 QualType Type, const APValue &Value,
2301 ConstantExprKind Kind,
2302 const FieldDecl *SubobjectDecl,
2303 CheckedTemporaries &CheckedTemps);
2304
2305 /// Check that this reference or pointer core constant expression is a valid
2306 /// value for an address or reference constant expression. Return true if we
2307 /// can fold this expression, whether or not it's a constant expression.
2308 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
2309 QualType Type, const LValue &LVal,
2310 ConstantExprKind Kind,
2311 CheckedTemporaries &CheckedTemps) {
2312 bool IsReferenceType = Type->isReferenceType();
2313
2314 APValue::LValueBase Base = LVal.getLValueBase();
2315 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
2316
2317 const Expr *BaseE = Base.dyn_cast<const Expr *>();
2318 const ValueDecl *BaseVD = Base.dyn_cast<const ValueDecl*>();
2319
2320 // Additional restrictions apply in a template argument. We only enforce the
2321 // C++20 restrictions here; additional syntactic and semantic restrictions
2322 // are applied elsewhere.
2323 if (isTemplateArgument(Kind)) {
2324 int InvalidBaseKind = -1;
2325 StringRef Ident;
2326 if (Base.is<TypeInfoLValue>())
2327 InvalidBaseKind = 0;
2328 else if (isa_and_nonnull<StringLiteral>(BaseE))
2329 InvalidBaseKind = 1;
2330 else if (isa_and_nonnull<MaterializeTemporaryExpr>(BaseE) ||
2331 isa_and_nonnull<LifetimeExtendedTemporaryDecl>(BaseVD))
2332 InvalidBaseKind = 2;
2333 else if (auto *PE = dyn_cast_or_null<PredefinedExpr>(BaseE)) {
2334 InvalidBaseKind = 3;
2335 Ident = PE->getIdentKindName();
2336 }
2337
2338 if (InvalidBaseKind != -1) {
2339 Info.FFDiag(Loc, diag::note_constexpr_invalid_template_arg)
2340 << IsReferenceType << !Designator.Entries.empty() << InvalidBaseKind
2341 << Ident;
2342 return false;
2343 }
2344 }
2345
2346 if (auto *FD = dyn_cast_or_null<FunctionDecl>(BaseVD);
2347 FD && FD->isImmediateFunction()) {
2348 Info.FFDiag(Loc, diag::note_consteval_address_accessible)
2349 << !Type->isAnyPointerType();
2350 Info.Note(FD->getLocation(), diag::note_declared_at);
2351 return false;
2352 }
2353
2354 // Check that the object is a global. Note that the fake 'this' object we
2355 // manufacture when checking potential constant expressions is conservatively
2356 // assumed to be global here.
2357 if (!IsGlobalLValue(Base)) {
2358 if (Info.getLangOpts().CPlusPlus11) {
2359 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
2360 << IsReferenceType << !Designator.Entries.empty() << !!BaseVD
2361 << BaseVD;
2362 auto *VarD = dyn_cast_or_null<VarDecl>(BaseVD);
2363 if (VarD && VarD->isConstexpr()) {
2364 // Non-static local constexpr variables have unintuitive semantics:
2365 // constexpr int a = 1;
2366 // constexpr const int *p = &a;
2367 // ... is invalid because the address of 'a' is not constant. Suggest
2368 // adding a 'static' in this case.
2369 Info.Note(VarD->getLocation(), diag::note_constexpr_not_static)
2370 << VarD
2371 << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static ");
2372 } else {
2373 NoteLValueLocation(Info, Base);
2374 }
2375 } else {
2376 Info.FFDiag(Loc);
2377 }
2378 // Don't allow references to temporaries to escape.
2379 return false;
2380 }
2381 assert((Info.checkingPotentialConstantExpression() ||
2382 LVal.getLValueCallIndex() == 0) &&
2383 "have call index for global lvalue");
2384
2385 if (LVal.allowConstexprUnknown()) {
2386 if (BaseVD) {
2387 Info.FFDiag(Loc, diag::note_constexpr_var_init_non_constant, 1) << BaseVD;
2388 NoteLValueLocation(Info, Base);
2389 } else {
2390 Info.FFDiag(Loc);
2391 }
2392 return false;
2393 }
2394
2395 if (Base.is<DynamicAllocLValue>()) {
2396 Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc)
2397 << IsReferenceType << !Designator.Entries.empty();
2398 NoteLValueLocation(Info, Base);
2399 return false;
2400 }
2401
2402 if (BaseVD) {
2403 if (const VarDecl *Var = dyn_cast<const VarDecl>(BaseVD)) {
2404 // Check if this is a thread-local variable.
2405 if (Var->getTLSKind())
2406 // FIXME: Diagnostic!
2407 return false;
2408
2409 // A dllimport variable never acts like a constant, unless we're
2410 // evaluating a value for use only in name mangling, and unless it's a
2411 // static local. For the latter case, we'd still need to evaluate the
2412 // constant expression in case we're inside a (inlined) function.
2413 if (!isForManglingOnly(Kind) && Var->hasAttr<DLLImportAttr>() &&
2414 !Var->isStaticLocal())
2415 return false;
2416
2417 // In CUDA/HIP device compilation, only device side variables have
2418 // constant addresses.
2419 if (Info.getASTContext().getLangOpts().CUDA &&
2420 Info.getASTContext().getLangOpts().CUDAIsDevice &&
2421 Info.getASTContext().CUDAConstantEvalCtx.NoWrongSidedVars) {
2422 if ((!Var->hasAttr<CUDADeviceAttr>() &&
2423 !Var->hasAttr<CUDAConstantAttr>() &&
2424 !Var->getType()->isCUDADeviceBuiltinSurfaceType() &&
2425 !Var->getType()->isCUDADeviceBuiltinTextureType()) ||
2426 Var->hasAttr<HIPManagedAttr>())
2427 return false;
2428 }
2429 }
2430 if (const auto *FD = dyn_cast<const FunctionDecl>(BaseVD)) {
2431 // __declspec(dllimport) must be handled very carefully:
2432 // We must never initialize an expression with the thunk in C++.
2433 // Doing otherwise would allow the same id-expression to yield
2434 // different addresses for the same function in different translation
2435 // units. However, this means that we must dynamically initialize the
2436 // expression with the contents of the import address table at runtime.
2437 //
2438 // The C language has no notion of ODR; furthermore, it has no notion of
2439 // dynamic initialization. This means that we are permitted to
2440 // perform initialization with the address of the thunk.
2441 if (Info.getLangOpts().CPlusPlus && !isForManglingOnly(Kind) &&
2442 FD->hasAttr<DLLImportAttr>())
2443 // FIXME: Diagnostic!
2444 return false;
2445 }
2446 } else if (const auto *MTE =
2447 dyn_cast_or_null<MaterializeTemporaryExpr>(BaseE)) {
2448 if (CheckedTemps.insert(MTE).second) {
2449 QualType TempType = getType(Base);
2450 if (TempType.isDestructedType()) {
2451 Info.FFDiag(MTE->getExprLoc(),
2452 diag::note_constexpr_unsupported_temporary_nontrivial_dtor)
2453 << TempType;
2454 return false;
2455 }
2456
2457 APValue *V = MTE->getOrCreateValue(false);
2458 assert(V && "evasluation result refers to uninitialised temporary");
2459 if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2460 Info, MTE->getExprLoc(), TempType, *V, Kind,
2461 /*SubobjectDecl=*/nullptr, CheckedTemps))
2462 return false;
2463 }
2464 }
2465
2466 // Allow address constant expressions to be past-the-end pointers. This is
2467 // an extension: the standard requires them to point to an object.
2468 if (!IsReferenceType)
2469 return true;
2470
2471 // A reference constant expression must refer to an object.
2472 if (!Base) {
2473 // FIXME: diagnostic
2474 Info.CCEDiag(Loc);
2475 return true;
2476 }
2477
2478 // Does this refer one past the end of some object?
2479 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
2480 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
2481 << !Designator.Entries.empty() << !!BaseVD << BaseVD;
2482 NoteLValueLocation(Info, Base);
2483 }
2484
2485 return true;
2486 }
2487
2488 /// Member pointers are constant expressions unless they point to a
2489 /// non-virtual dllimport member function.
2490 static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
2491 SourceLocation Loc,
2492 QualType Type,
2493 const APValue &Value,
2494 ConstantExprKind Kind) {
2495 const ValueDecl *Member = Value.getMemberPointerDecl();
2496 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
2497 if (!FD)
2498 return true;
2499 if (FD->isImmediateFunction()) {
2500 Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0;
2501 Info.Note(FD->getLocation(), diag::note_declared_at);
2502 return false;
2503 }
2504 return isForManglingOnly(Kind) || FD->isVirtual() ||
2505 !FD->hasAttr<DLLImportAttr>();
2506 }
2507
2508 /// Check that this core constant expression is of literal type, and if not,
2509 /// produce an appropriate diagnostic.
2510 static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
2511 const LValue *This = nullptr) {
2512 // The restriction to literal types does not exist in C++23 anymore.
2513 if (Info.getLangOpts().CPlusPlus23)
2514 return true;
2515
2516 if (!E->isPRValue() || E->getType()->isLiteralType(Info.Ctx))
2517 return true;
2518
2519 // C++1y: A constant initializer for an object o [...] may also invoke
2520 // constexpr constructors for o and its subobjects even if those objects
2521 // are of non-literal class types.
2522 //
2523 // C++11 missed this detail for aggregates, so classes like this:
2524 // struct foo_t { union { int i; volatile int j; } u; };
2525 // are not (obviously) initializable like so:
2526 // __attribute__((__require_constant_initialization__))
2527 // static const foo_t x = {{0}};
2528 // because "i" is a subobject with non-literal initialization (due to the
2529 // volatile member of the union). See:
2530 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2531 // Therefore, we use the C++1y behavior.
2532 if (This && Info.EvaluatingDecl == This->getLValueBase())
2533 return true;
2534
2535 // Prvalue constant expressions must be of literal types.
2536 if (Info.getLangOpts().CPlusPlus11)
2537 Info.FFDiag(E, diag::note_constexpr_nonliteral)
2538 << E->getType();
2539 else
2540 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2541 return false;
2542 }
2543
2544 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2545 EvalInfo &Info, SourceLocation DiagLoc,
2546 QualType Type, const APValue &Value,
2547 ConstantExprKind Kind,
2548 const FieldDecl *SubobjectDecl,
2549 CheckedTemporaries &CheckedTemps) {
2550 if (!Value.hasValue()) {
2551 if (SubobjectDecl) {
2552 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2553 << /*(name)*/ 1 << SubobjectDecl;
2554 Info.Note(SubobjectDecl->getLocation(),
2555 diag::note_constexpr_subobject_declared_here);
2556 } else {
2557 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2558 << /*of type*/ 0 << Type;
2559 }
2560 return false;
2561 }
2562
2563 // We allow _Atomic(T) to be initialized from anything that T can be
2564 // initialized from.
2565 if (const AtomicType *AT = Type->getAs<AtomicType>())
2566 Type = AT->getValueType();
2567
2568 // Core issue 1454: For a literal constant expression of array or class type,
2569 // each subobject of its value shall have been initialized by a constant
2570 // expression.
2571 if (Value.isArray()) {
2572 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
2573 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
2574 if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2575 Value.getArrayInitializedElt(I), Kind,
2576 SubobjectDecl, CheckedTemps))
2577 return false;
2578 }
2579 if (!Value.hasArrayFiller())
2580 return true;
2581 return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2582 Value.getArrayFiller(), Kind, SubobjectDecl,
2583 CheckedTemps);
2584 }
2585 if (Value.isUnion() && Value.getUnionField()) {
2586 return CheckEvaluationResult(
2587 CERK, Info, DiagLoc, Value.getUnionField()->getType(),
2588 Value.getUnionValue(), Kind, Value.getUnionField(), CheckedTemps);
2589 }
2590 if (Value.isStruct()) {
2591 auto *RD = Type->castAsRecordDecl();
2592 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2593 unsigned BaseIndex = 0;
2594 for (const CXXBaseSpecifier &BS : CD->bases()) {
2595 const APValue &BaseValue = Value.getStructBase(BaseIndex);
2596 if (!BaseValue.hasValue()) {
2597 SourceLocation TypeBeginLoc = BS.getBaseTypeLoc();
2598 Info.FFDiag(TypeBeginLoc, diag::note_constexpr_uninitialized_base)
2599 << BS.getType() << SourceRange(TypeBeginLoc, BS.getEndLoc());
2600 return false;
2601 }
2602 if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(), BaseValue,
2603 Kind, /*SubobjectDecl=*/nullptr,
2604 CheckedTemps))
2605 return false;
2606 ++BaseIndex;
2607 }
2608 }
2609 for (const auto *I : RD->fields()) {
2610 if (I->isUnnamedBitField())
2611 continue;
2612
2613 if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),
2614 Value.getStructField(I->getFieldIndex()), Kind,
2615 I, CheckedTemps))
2616 return false;
2617 }
2618 }
2619
2620 if (Value.isLValue() &&
2621 CERK == CheckEvaluationResultKind::ConstantExpression) {
2622 LValue LVal;
2623 LVal.setFrom(Info.Ctx, Value);
2624 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Kind,
2625 CheckedTemps);
2626 }
2627
2628 if (Value.isMemberPointer() &&
2629 CERK == CheckEvaluationResultKind::ConstantExpression)
2630 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Kind);
2631
2632 // Everything else is fine.
2633 return true;
2634 }
2635
2636 /// Check that this core constant expression value is a valid value for a
2637 /// constant expression. If not, report an appropriate diagnostic. Does not
2638 /// check that the expression is of literal type.
2639 static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
2640 QualType Type, const APValue &Value,
2641 ConstantExprKind Kind) {
2642 // Nothing to check for a constant expression of type 'cv void'.
2643 if (Type->isVoidType())
2644 return true;
2645
2646 CheckedTemporaries CheckedTemps;
2647 return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2648 Info, DiagLoc, Type, Value, Kind,
2649 /*SubobjectDecl=*/nullptr, CheckedTemps);
2650 }
2651
2652 /// Check that this evaluated value is fully-initialized and can be loaded by
2653 /// an lvalue-to-rvalue conversion.
2654 static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,
2655 QualType Type, const APValue &Value) {
2656 CheckedTemporaries CheckedTemps;
2657 return CheckEvaluationResult(
2658 CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value,
2659 ConstantExprKind::Normal, /*SubobjectDecl=*/nullptr, CheckedTemps);
2660 }
2661
2662 /// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless
2663 /// "the allocated storage is deallocated within the evaluation".
2664 static bool CheckMemoryLeaks(EvalInfo &Info) {
2665 if (!Info.HeapAllocs.empty()) {
2666 // We can still fold to a constant despite a compile-time memory leak,
2667 // so long as the heap allocation isn't referenced in the result (we check
2668 // that in CheckConstantExpression).
2669 Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr,
2670 diag::note_constexpr_memory_leak)
2671 << unsigned(Info.HeapAllocs.size() - 1);
2672 }
2673 return true;
2674 }
2675
2676 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
2677 // A null base expression indicates a null pointer. These are always
2678 // evaluatable, and they are false unless the offset is zero.
2679 if (!Value.getLValueBase()) {
2680 // TODO: Should a non-null pointer with an offset of zero evaluate to true?
2681 Result = !Value.getLValueOffset().isZero();
2682 return true;
2683 }
2684
2685 // We have a non-null base. These are generally known to be true, but if it's
2686 // a weak declaration it can be null at runtime.
2687 Result = true;
2688 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
2689 return !Decl || !Decl->isWeak();
2690 }
2691
2692 static bool HandleConversionToBool(const APValue &Val, bool &Result) {
2693 // TODO: This function should produce notes if it fails.
2694 switch (Val.getKind()) {
2695 case APValue::None:
2696 case APValue::Indeterminate:
2697 return false;
2698 case APValue::Int:
2699 Result = Val.getInt().getBoolValue();
2700 return true;
2701 case APValue::FixedPoint:
2702 Result = Val.getFixedPoint().getBoolValue();
2703 return true;
2704 case APValue::Float:
2705 Result = !Val.getFloat().isZero();
2706 return true;
2707 case APValue::ComplexInt:
2708 Result = Val.getComplexIntReal().getBoolValue() ||
2709 Val.getComplexIntImag().getBoolValue();
2710 return true;
2711 case APValue::ComplexFloat:
2712 Result = !Val.getComplexFloatReal().isZero() ||
2713 !Val.getComplexFloatImag().isZero();
2714 return true;
2715 case APValue::LValue:
2716 return EvalPointerValueAsBool(Val, Result);
2717 case APValue::MemberPointer:
2718 if (Val.getMemberPointerDecl() && Val.getMemberPointerDecl()->isWeak()) {
2719 return false;
2720 }
2721 Result = Val.getMemberPointerDecl();
2722 return true;
2723 case APValue::Vector:
2724 case APValue::Array:
2725 case APValue::Struct:
2726 case APValue::Union:
2727 case APValue::AddrLabelDiff:
2728 return false;
2729 }
2730
2731 llvm_unreachable("unknown APValue kind");
2732 }
2733
2734 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2735 EvalInfo &Info) {
2736 assert(!E->isValueDependent());
2737 assert(E->isPRValue() && "missing lvalue-to-rvalue conv in bool condition");
2738 APValue Val;
2739 if (!Evaluate(Val, Info, E))
2740 return false;
2741 return HandleConversionToBool(Val, Result);
2742 }
2743
2744 template<typename T>
2745 static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2746 const T &SrcValue, QualType DestType) {
2747 Info.CCEDiag(E, diag::note_constexpr_overflow)
2748 << SrcValue << DestType;
2749 return Info.noteUndefinedBehavior();
2750 }
2751
2752 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2753 QualType SrcType, const APFloat &Value,
2754 QualType DestType, APSInt &Result) {
2755 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2756 // Determine whether we are converting to unsigned or signed.
2757 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2758
2759 Result = APSInt(DestWidth, !DestSigned);
2760 bool ignored;
2761 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2762 & APFloat::opInvalidOp)
2763 return HandleOverflow(Info, E, Value, DestType);
2764 return true;
2765 }
2766
2767 /// Get rounding mode to use in evaluation of the specified expression.
2768 ///
2769 /// If rounding mode is unknown at compile time, still try to evaluate the
2770 /// expression. If the result is exact, it does not depend on rounding mode.
2771 /// So return "tonearest" mode instead of "dynamic".
2772 static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E) {
2773 llvm::RoundingMode RM =
2774 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).getRoundingMode();
2775 if (RM == llvm::RoundingMode::Dynamic)
2776 RM = llvm::RoundingMode::NearestTiesToEven;
2777 return RM;
2778 }
2779
2780 /// Check if the given evaluation result is allowed for constant evaluation.
2781 static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E,
2782 APFloat::opStatus St) {
2783 // In a constant context, assume that any dynamic rounding mode or FP
2784 // exception state matches the default floating-point environment.
2785 if (Info.InConstantContext)
2786 return true;
2787
2788 FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
2789 if ((St & APFloat::opInexact) &&
2790 FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) {
2791 // Inexact result means that it depends on rounding mode. If the requested
2792 // mode is dynamic, the evaluation cannot be made in compile time.
2793 Info.FFDiag(E, diag::note_constexpr_dynamic_rounding);
2794 return false;
2795 }
2796
2797 if ((St != APFloat::opOK) &&
2798 (FPO.getRoundingMode() == llvm::RoundingMode::Dynamic ||
2799 FPO.getExceptionMode() != LangOptions::FPE_Ignore ||
2800 FPO.getAllowFEnvAccess())) {
2801 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
2802 return false;
2803 }
2804
2805 if ((St & APFloat::opStatus::opInvalidOp) &&
2806 FPO.getExceptionMode() != LangOptions::FPE_Ignore) {
2807 // There is no usefully definable result.
2808 Info.FFDiag(E);
2809 return false;
2810 }
2811
2812 // FIXME: if:
2813 // - evaluation triggered other FP exception, and
2814 // - exception mode is not "ignore", and
2815 // - the expression being evaluated is not a part of global variable
2816 // initializer,
2817 // the evaluation probably need to be rejected.
2818 return true;
2819 }
2820
2821 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2822 QualType SrcType, QualType DestType,
2823 APFloat &Result) {
2824 assert((isa<CastExpr>(E) || isa<CompoundAssignOperator>(E) ||
2825 isa<ConvertVectorExpr>(E)) &&
2826 "HandleFloatToFloatCast has been checked with only CastExpr, "
2827 "CompoundAssignOperator and ConvertVectorExpr. Please either validate "
2828 "the new expression or address the root cause of this usage.");
2829 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2830 APFloat::opStatus St;
2831 APFloat Value = Result;
2832 bool ignored;
2833 St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored);
2834 return checkFloatingPointResult(Info, E, St);
2835 }
2836
2837 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2838 QualType DestType, QualType SrcType,
2839 const APSInt &Value) {
2840 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2841 // Figure out if this is a truncate, extend or noop cast.
2842 // If the input is signed, do a sign extend, noop, or truncate.
2843 APSInt Result = Value.extOrTrunc(DestWidth);
2844 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2845 if (DestType->isBooleanType())
2846 Result = Value.getBoolValue();
2847 return Result;
2848 }
2849
2850 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2851 const FPOptions FPO,
2852 QualType SrcType, const APSInt &Value,
2853 QualType DestType, APFloat &Result) {
2854 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2855 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2856 APFloat::opStatus St = Result.convertFromAPInt(Value, Value.isSigned(), RM);
2857 return checkFloatingPointResult(Info, E, St);
2858 }
2859
2860 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2861 APValue &Value, const FieldDecl *FD) {
2862 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2863
2864 if (!Value.isInt()) {
2865 // Trying to store a pointer-cast-to-integer into a bitfield.
2866 // FIXME: In this case, we should provide the diagnostic for casting
2867 // a pointer to an integer.
2868 assert(Value.isLValue() && "integral value neither int nor lvalue?");
2869 Info.FFDiag(E);
2870 return false;
2871 }
2872
2873 APSInt &Int = Value.getInt();
2874 unsigned OldBitWidth = Int.getBitWidth();
2875 unsigned NewBitWidth = FD->getBitWidthValue();
2876 if (NewBitWidth < OldBitWidth)
2877 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2878 return true;
2879 }
2880
2881 /// Perform the given integer operation, which is known to need at most BitWidth
2882 /// bits, and check for overflow in the original type (if that type was not an
2883 /// unsigned type).
2884 template<typename Operation>
2885 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2886 const APSInt &LHS, const APSInt &RHS,
2887 unsigned BitWidth, Operation Op,
2888 APSInt &Result) {
2889 if (LHS.isUnsigned()) {
2890 Result = Op(LHS, RHS);
2891 return true;
2892 }
2893
2894 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2895 Result = Value.trunc(LHS.getBitWidth());
2896 if (Result.extend(BitWidth) != Value) {
2897 if (Info.checkingForUndefinedBehavior())
2898 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2899 diag::warn_integer_constant_overflow)
2900 << toString(Result, 10, Result.isSigned(), /*formatAsCLiteral=*/false,
2901 /*UpperCase=*/true, /*InsertSeparators=*/true)
2902 << E->getType() << E->getSourceRange();
2903 return HandleOverflow(Info, E, Value, E->getType());
2904 }
2905 return true;
2906 }
2907
2908 /// Perform the given binary integer operation.
2909 static bool handleIntIntBinOp(EvalInfo &Info, const BinaryOperator *E,
2910 const APSInt &LHS, BinaryOperatorKind Opcode,
2911 APSInt RHS, APSInt &Result) {
2912 bool HandleOverflowResult = true;
2913 switch (Opcode) {
2914 default:
2915 Info.FFDiag(E);
2916 return false;
2917 case BO_Mul:
2918 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2919 std::multiplies<APSInt>(), Result);
2920 case BO_Add:
2921 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2922 std::plus<APSInt>(), Result);
2923 case BO_Sub:
2924 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2925 std::minus<APSInt>(), Result);
2926 case BO_And: Result = LHS & RHS; return true;
2927 case BO_Xor: Result = LHS ^ RHS; return true;
2928 case BO_Or: Result = LHS | RHS; return true;
2929 case BO_Div:
2930 case BO_Rem:
2931 if (RHS == 0) {
2932 Info.FFDiag(E, diag::note_expr_divide_by_zero)
2933 << E->getRHS()->getSourceRange();
2934 return false;
2935 }
2936 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2937 // this operation and gives the two's complement result.
2938 if (RHS.isNegative() && RHS.isAllOnes() && LHS.isSigned() &&
2939 LHS.isMinSignedValue())
2940 HandleOverflowResult = HandleOverflow(
2941 Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
2942 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2943 return HandleOverflowResult;
2944 case BO_Shl: {
2945 if (Info.getLangOpts().OpenCL)
2946 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2947 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2948 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2949 RHS.isUnsigned());
2950 else if (RHS.isSigned() && RHS.isNegative()) {
2951 // During constant-folding, a negative shift is an opposite shift. Such
2952 // a shift is not a constant expression.
2953 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2954 if (!Info.noteUndefinedBehavior())
2955 return false;
2956 RHS = -RHS;
2957 goto shift_right;
2958 }
2959 shift_left:
2960 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2961 // the shifted type.
2962 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2963 if (SA != RHS) {
2964 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2965 << RHS << E->getType() << LHS.getBitWidth();
2966 if (!Info.noteUndefinedBehavior())
2967 return false;
2968 } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) {
2969 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2970 // operand, and must not overflow the corresponding unsigned type.
2971 // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2972 // E1 x 2^E2 module 2^N.
2973 if (LHS.isNegative()) {
2974 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2975 if (!Info.noteUndefinedBehavior())
2976 return false;
2977 } else if (LHS.countl_zero() < SA) {
2978 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2979 if (!Info.noteUndefinedBehavior())
2980 return false;
2981 }
2982 }
2983 Result = LHS << SA;
2984 return true;
2985 }
2986 case BO_Shr: {
2987 if (Info.getLangOpts().OpenCL)
2988 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2989 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2990 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2991 RHS.isUnsigned());
2992 else if (RHS.isSigned() && RHS.isNegative()) {
2993 // During constant-folding, a negative shift is an opposite shift. Such a
2994 // shift is not a constant expression.
2995 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2996 if (!Info.noteUndefinedBehavior())
2997 return false;
2998 RHS = -RHS;
2999 goto shift_left;
3000 }
3001 shift_right:
3002 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
3003 // shifted type.
3004 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
3005 if (SA != RHS) {
3006 Info.CCEDiag(E, diag::note_constexpr_large_shift)
3007 << RHS << E->getType() << LHS.getBitWidth();
3008 if (!Info.noteUndefinedBehavior())
3009 return false;
3010 }
3011
3012 Result = LHS >> SA;
3013 return true;
3014 }
3015
3016 case BO_LT: Result = LHS < RHS; return true;
3017 case BO_GT: Result = LHS > RHS; return true;
3018 case BO_LE: Result = LHS <= RHS; return true;
3019 case BO_GE: Result = LHS >= RHS; return true;
3020 case BO_EQ: Result = LHS == RHS; return true;
3021 case BO_NE: Result = LHS != RHS; return true;
3022 case BO_Cmp:
3023 llvm_unreachable("BO_Cmp should be handled elsewhere");
3024 }
3025 }
3026
3027 /// Perform the given binary floating-point operation, in-place, on LHS.
3028 static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E,
3029 APFloat &LHS, BinaryOperatorKind Opcode,
3030 const APFloat &RHS) {
3031 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
3032 APFloat::opStatus St;
3033 switch (Opcode) {
3034 default:
3035 Info.FFDiag(E);
3036 return false;
3037 case BO_Mul:
3038 St = LHS.multiply(RHS, RM);
3039 break;
3040 case BO_Add:
3041 St = LHS.add(RHS, RM);
3042 break;
3043 case BO_Sub:
3044 St = LHS.subtract(RHS, RM);
3045 break;
3046 case BO_Div:
3047 // [expr.mul]p4:
3048 // If the second operand of / or % is zero the behavior is undefined.
3049 if (RHS.isZero())
3050 Info.CCEDiag(E, diag::note_expr_divide_by_zero);
3051 St = LHS.divide(RHS, RM);
3052 break;
3053 }
3054
3055 // [expr.pre]p4:
3056 // If during the evaluation of an expression, the result is not
3057 // mathematically defined [...], the behavior is undefined.
3058 // FIXME: C++ rules require us to not conform to IEEE 754 here.
3059 if (LHS.isNaN()) {
3060 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
3061 return Info.noteUndefinedBehavior();
3062 }
3063
3064 return checkFloatingPointResult(Info, E, St);
3065 }
3066
3067 static bool handleLogicalOpForVector(const APInt &LHSValue,
3068 BinaryOperatorKind Opcode,
3069 const APInt &RHSValue, APInt &Result) {
3070 bool LHS = (LHSValue != 0);
3071 bool RHS = (RHSValue != 0);
3072
3073 if (Opcode == BO_LAnd)
3074 Result = LHS && RHS;
3075 else
3076 Result = LHS || RHS;
3077 return true;
3078 }
3079 static bool handleLogicalOpForVector(const APFloat &LHSValue,
3080 BinaryOperatorKind Opcode,
3081 const APFloat &RHSValue, APInt &Result) {
3082 bool LHS = !LHSValue.isZero();
3083 bool RHS = !RHSValue.isZero();
3084
3085 if (Opcode == BO_LAnd)
3086 Result = LHS && RHS;
3087 else
3088 Result = LHS || RHS;
3089 return true;
3090 }
3091
3092 static bool handleLogicalOpForVector(const APValue &LHSValue,
3093 BinaryOperatorKind Opcode,
3094 const APValue &RHSValue, APInt &Result) {
3095 // The result is always an int type, however operands match the first.
3096 if (LHSValue.getKind() == APValue::Int)
3097 return handleLogicalOpForVector(LHSValue.getInt(), Opcode,
3098 RHSValue.getInt(), Result);
3099 assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
3100 return handleLogicalOpForVector(LHSValue.getFloat(), Opcode,
3101 RHSValue.getFloat(), Result);
3102 }
3103
3104 template <typename APTy>
3105 static bool
3106 handleCompareOpForVectorHelper(const APTy &LHSValue, BinaryOperatorKind Opcode,
3107 const APTy &RHSValue, APInt &Result) {
3108 switch (Opcode) {
3109 default:
3110 llvm_unreachable("unsupported binary operator");
3111 case BO_EQ:
3112 Result = (LHSValue == RHSValue);
3113 break;
3114 case BO_NE:
3115 Result = (LHSValue != RHSValue);
3116 break;
3117 case BO_LT:
3118 Result = (LHSValue < RHSValue);
3119 break;
3120 case BO_GT:
3121 Result = (LHSValue > RHSValue);
3122 break;
3123 case BO_LE:
3124 Result = (LHSValue <= RHSValue);
3125 break;
3126 case BO_GE:
3127 Result = (LHSValue >= RHSValue);
3128 break;
3129 }
3130
3131 // The boolean operations on these vector types use an instruction that
3132 // results in a mask of '-1' for the 'truth' value. Ensure that we negate 1
3133 // to -1 to make sure that we produce the correct value.
3134 Result.negate();
3135
3136 return true;
3137 }
3138
3139 static bool handleCompareOpForVector(const APValue &LHSValue,
3140 BinaryOperatorKind Opcode,
3141 const APValue &RHSValue, APInt &Result) {
3142 // The result is always an int type, however operands match the first.
3143 if (LHSValue.getKind() == APValue::Int)
3144 return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode,
3145 RHSValue.getInt(), Result);
3146 assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
3147 return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode,
3148 RHSValue.getFloat(), Result);
3149 }
3150
3151 // Perform binary operations for vector types, in place on the LHS.
3152 static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E,
3153 BinaryOperatorKind Opcode,
3154 APValue &LHSValue,
3155 const APValue &RHSValue) {
3156 assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI &&
3157 "Operation not supported on vector types");
3158
3159 const auto *VT = E->getType()->castAs<VectorType>();
3160 unsigned NumElements = VT->getNumElements();
3161 QualType EltTy = VT->getElementType();
3162
3163 // In the cases (typically C as I've observed) where we aren't evaluating
3164 // constexpr but are checking for cases where the LHS isn't yet evaluatable,
3165 // just give up.
3166 if (!LHSValue.isVector()) {
3167 assert(LHSValue.isLValue() &&
3168 "A vector result that isn't a vector OR uncalculated LValue");
3169 Info.FFDiag(E);
3170 return false;
3171 }
3172
3173 assert(LHSValue.getVectorLength() == NumElements &&
3174 RHSValue.getVectorLength() == NumElements && "Different vector sizes");
3175
3176 SmallVector<APValue, 4> ResultElements;
3177
3178 for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) {
3179 APValue LHSElt = LHSValue.getVectorElt(EltNum);
3180 APValue RHSElt = RHSValue.getVectorElt(EltNum);
3181
3182 if (EltTy->isIntegerType()) {
3183 APSInt EltResult{Info.Ctx.getIntWidth(EltTy),
3184 EltTy->isUnsignedIntegerType()};
3185 bool Success = true;
3186
3187 if (BinaryOperator::isLogicalOp(Opcode))
3188 Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3189 else if (BinaryOperator::isComparisonOp(Opcode))
3190 Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3191 else
3192 Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode,
3193 RHSElt.getInt(), EltResult);
3194
3195 if (!Success) {
3196 Info.FFDiag(E);
3197 return false;
3198 }
3199 ResultElements.emplace_back(EltResult);
3200
3201 } else if (EltTy->isFloatingType()) {
3202 assert(LHSElt.getKind() == APValue::Float &&
3203 RHSElt.getKind() == APValue::Float &&
3204 "Mismatched LHS/RHS/Result Type");
3205 APFloat LHSFloat = LHSElt.getFloat();
3206
3207 if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode,
3208 RHSElt.getFloat())) {
3209 Info.FFDiag(E);
3210 return false;
3211 }
3212
3213 ResultElements.emplace_back(LHSFloat);
3214 }
3215 }
3216
3217 LHSValue = APValue(ResultElements.data(), ResultElements.size());
3218 return true;
3219 }
3220
3221 /// Cast an lvalue referring to a base subobject to a derived class, by
3222 /// truncating the lvalue's path to the given length.
3223 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
3224 const RecordDecl *TruncatedType,
3225 unsigned TruncatedElements) {
3226 SubobjectDesignator &D = Result.Designator;
3227
3228 // Check we actually point to a derived class object.
3229 if (TruncatedElements == D.Entries.size())
3230 return true;
3231 assert(TruncatedElements >= D.MostDerivedPathLength &&
3232 "not casting to a derived class");
3233 if (!Result.checkSubobject(Info, E, CSK_Derived))
3234 return false;
3235
3236 // Truncate the path to the subobject, and remove any derived-to-base offsets.
3237 const RecordDecl *RD = TruncatedType;
3238 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
3239 if (RD->isInvalidDecl()) return false;
3240 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3241 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
3242 if (isVirtualBaseClass(D.Entries[I]))
3243 Result.Offset -= Layout.getVBaseClassOffset(Base);
3244 else
3245 Result.Offset -= Layout.getBaseClassOffset(Base);
3246 RD = Base;
3247 }
3248 D.Entries.resize(TruncatedElements);
3249 return true;
3250 }
3251
3252 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3253 const CXXRecordDecl *Derived,
3254 const CXXRecordDecl *Base,
3255 const ASTRecordLayout *RL = nullptr) {
3256 if (!RL) {
3257 if (Derived->isInvalidDecl()) return false;
3258 RL = &Info.Ctx.getASTRecordLayout(Derived);
3259 }
3260
3261 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
3262 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
3263 return true;
3264 }
3265
3266 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3267 const CXXRecordDecl *DerivedDecl,
3268 const CXXBaseSpecifier *Base) {
3269 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
3270
3271 if (!Base->isVirtual())
3272 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
3273
3274 SubobjectDesignator &D = Obj.Designator;
3275 if (D.Invalid)
3276 return false;
3277
3278 // Extract most-derived object and corresponding type.
3279 // FIXME: After implementing P2280R4 it became possible to get references
3280 // here. We do MostDerivedType->getAsCXXRecordDecl() in several other
3281 // locations and if we see crashes in those locations in the future
3282 // it may make more sense to move this fix into Lvalue::set.
3283 DerivedDecl = D.MostDerivedType.getNonReferenceType()->getAsCXXRecordDecl();
3284 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
3285 return false;
3286
3287 // Find the virtual base class.
3288 if (DerivedDecl->isInvalidDecl()) return false;
3289 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
3290 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
3291 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
3292 return true;
3293 }
3294
3295 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
3296 QualType Type, LValue &Result) {
3297 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3298 PathE = E->path_end();
3299 PathI != PathE; ++PathI) {
3300 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3301 *PathI))
3302 return false;
3303 Type = (*PathI)->getType();
3304 }
3305 return true;
3306 }
3307
3308 /// Cast an lvalue referring to a derived class to a known base subobject.
3309 static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
3310 const CXXRecordDecl *DerivedRD,
3311 const CXXRecordDecl *BaseRD) {
3312 CXXBasePaths Paths(/*FindAmbiguities=*/false,
3313 /*RecordPaths=*/true, /*DetectVirtual=*/false);
3314 if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
3315 llvm_unreachable("Class must be derived from the passed in base class!");
3316
3317 for (CXXBasePathElement &Elem : Paths.front())
3318 if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
3319 return false;
3320 return true;
3321 }
3322
3323 /// Update LVal to refer to the given field, which must be a member of the type
3324 /// currently described by LVal.
3325 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
3326 const FieldDecl *FD,
3327 const ASTRecordLayout *RL = nullptr) {
3328 if (!RL) {
3329 if (FD->getParent()->isInvalidDecl()) return false;
3330 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
3331 }
3332
3333 unsigned I = FD->getFieldIndex();
3334 LVal.addDecl(Info, E, FD);
3335 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
3336 return true;
3337 }
3338
3339 /// Update LVal to refer to the given indirect field.
3340 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
3341 LValue &LVal,
3342 const IndirectFieldDecl *IFD) {
3343 for (const auto *C : IFD->chain())
3344 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
3345 return false;
3346 return true;
3347 }
3348
3349 enum class SizeOfType {
3350 SizeOf,
3351 DataSizeOf,
3352 };
3353
3354 /// Get the size of the given type in char units.
3355 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, QualType Type,
3356 CharUnits &Size, SizeOfType SOT = SizeOfType::SizeOf) {
3357 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
3358 // extension.
3359 if (Type->isVoidType() || Type->isFunctionType()) {
3360 Size = CharUnits::One();
3361 return true;
3362 }
3363
3364 if (Type->isDependentType()) {
3365 Info.FFDiag(Loc);
3366 return false;
3367 }
3368
3369 if (!Type->isConstantSizeType()) {
3370 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
3371 // FIXME: Better diagnostic.
3372 Info.FFDiag(Loc);
3373 return false;
3374 }
3375
3376 if (SOT == SizeOfType::SizeOf)
3377 Size = Info.Ctx.getTypeSizeInChars(Type);
3378 else
3379 Size = Info.Ctx.getTypeInfoDataSizeInChars(Type).Width;
3380 return true;
3381 }
3382
3383 /// Update a pointer value to model pointer arithmetic.
3384 /// \param Info - Information about the ongoing evaluation.
3385 /// \param E - The expression being evaluated, for diagnostic purposes.
3386 /// \param LVal - The pointer value to be updated.
3387 /// \param EltTy - The pointee type represented by LVal.
3388 /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
3389 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3390 LValue &LVal, QualType EltTy,
3391 APSInt Adjustment) {
3392 CharUnits SizeOfPointee;
3393 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
3394 return false;
3395
3396 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
3397 return true;
3398 }
3399
3400 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3401 LValue &LVal, QualType EltTy,
3402 int64_t Adjustment) {
3403 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
3404 APSInt::get(Adjustment));
3405 }
3406
3407 /// Update an lvalue to refer to a component of a complex number.
3408 /// \param Info - Information about the ongoing evaluation.
3409 /// \param LVal - The lvalue to be updated.
3410 /// \param EltTy - The complex number's component type.
3411 /// \param Imag - False for the real component, true for the imaginary.
3412 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
3413 LValue &LVal, QualType EltTy,
3414 bool Imag) {
3415 if (Imag) {
3416 CharUnits SizeOfComponent;
3417 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
3418 return false;
3419 LVal.Offset += SizeOfComponent;
3420 }
3421 LVal.addComplex(Info, E, EltTy, Imag);
3422 return true;
3423 }
3424
3425 static bool HandleLValueVectorElement(EvalInfo &Info, const Expr *E,
3426 LValue &LVal, QualType EltTy,
3427 uint64_t Size, uint64_t Idx) {
3428 if (Idx) {
3429 CharUnits SizeOfElement;
3430 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfElement))
3431 return false;
3432 LVal.Offset += SizeOfElement * Idx;
3433 }
3434 LVal.addVectorElement(Info, E, EltTy, Size, Idx);
3435 return true;
3436 }
3437
3438 /// Try to evaluate the initializer for a variable declaration.
3439 ///
3440 /// \param Info Information about the ongoing evaluation.
3441 /// \param E An expression to be used when printing diagnostics.
3442 /// \param VD The variable whose initializer should be obtained.
3443 /// \param Version The version of the variable within the frame.
3444 /// \param Frame The frame in which the variable was created. Must be null
3445 /// if this variable is not local to the evaluation.
3446 /// \param Result Filled in with a pointer to the value of the variable.
3447 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
3448 const VarDecl *VD, CallStackFrame *Frame,
3449 unsigned Version, APValue *&Result) {
3450 // C++23 [expr.const]p8 If we have a reference type allow unknown references
3451 // and pointers.
3452 bool AllowConstexprUnknown =
3453 Info.getLangOpts().CPlusPlus23 && VD->getType()->isReferenceType();
3454
3455 APValue::LValueBase Base(VD, Frame ? Frame->Index : 0, Version);
3456
3457 auto CheckUninitReference = [&](bool IsLocalVariable) {
3458 if (!Result || (!Result->hasValue() && VD->getType()->isReferenceType())) {
3459 // C++23 [expr.const]p8
3460 // ... For such an object that is not usable in constant expressions, the
3461 // dynamic type of the object is constexpr-unknown. For such a reference
3462 // that is not usable in constant expressions, the reference is treated
3463 // as binding to an unspecified object of the referenced type whose
3464 // lifetime and that of all subobjects includes the entire constant
3465 // evaluation and whose dynamic type is constexpr-unknown.
3466 //
3467 // Variables that are part of the current evaluation are not
3468 // constexpr-unknown.
3469 if (!AllowConstexprUnknown || IsLocalVariable) {
3470 if (!Info.checkingPotentialConstantExpression())
3471 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
3472 return false;
3473 }
3474 Result = nullptr;
3475 }
3476 return true;
3477 };
3478
3479 // If this is a local variable, dig out its value.
3480 if (Frame) {
3481 Result = Frame->getTemporary(VD, Version);
3482 if (Result)
3483 return CheckUninitReference(/*IsLocalVariable=*/true);
3484
3485 if (!isa<ParmVarDecl>(VD)) {
3486 // Assume variables referenced within a lambda's call operator that were
3487 // not declared within the call operator are captures and during checking
3488 // of a potential constant expression, assume they are unknown constant
3489 // expressions.
3490 assert(isLambdaCallOperator(Frame->Callee) &&
3491 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
3492 "missing value for local variable");
3493 if (Info.checkingPotentialConstantExpression())
3494 return false;
3495 // FIXME: This diagnostic is bogus; we do support captures. Is this code
3496 // still reachable at all?
3497 Info.FFDiag(E->getBeginLoc(),
3498 diag::note_unimplemented_constexpr_lambda_feature_ast)
3499 << "captures not currently allowed";
3500 return false;
3501 }
3502 }
3503
3504 // If we're currently evaluating the initializer of this declaration, use that
3505 // in-flight value.
3506 if (Info.EvaluatingDecl == Base) {
3507 Result = Info.EvaluatingDeclValue;
3508 return CheckUninitReference(/*IsLocalVariable=*/false);
3509 }
3510
3511 // P2280R4 struck the restriction that variable of reference type lifetime
3512 // should begin within the evaluation of E
3513 // Used to be C++20 [expr.const]p5.12.2:
3514 // ... its lifetime began within the evaluation of E;
3515 if (isa<ParmVarDecl>(VD)) {
3516 if (AllowConstexprUnknown) {
3517 Result = nullptr;
3518 return true;
3519 }
3520
3521 // Assume parameters of a potential constant expression are usable in
3522 // constant expressions.
3523 if (!Info.checkingPotentialConstantExpression() ||
3524 !Info.CurrentCall->Callee ||
3525 !Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
3526 if (Info.getLangOpts().CPlusPlus11) {
3527 Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown)
3528 << VD;
3529 NoteLValueLocation(Info, Base);
3530 } else {
3531 Info.FFDiag(E);
3532 }
3533 }
3534 return false;
3535 }
3536
3537 if (E->isValueDependent())
3538 return false;
3539
3540 // Dig out the initializer, and use the declaration which it's attached to.
3541 // FIXME: We should eventually check whether the variable has a reachable
3542 // initializing declaration.
3543 const Expr *Init = VD->getAnyInitializer(VD);
3544 // P2280R4 struck the restriction that variable of reference type should have
3545 // a preceding initialization.
3546 // Used to be C++20 [expr.const]p5.12:
3547 // ... reference has a preceding initialization and either ...
3548 if (!Init && !AllowConstexprUnknown) {
3549 // Don't diagnose during potential constant expression checking; an
3550 // initializer might be added later.
3551 if (!Info.checkingPotentialConstantExpression()) {
3552 Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1)
3553 << VD;
3554 NoteLValueLocation(Info, Base);
3555 }
3556 return false;
3557 }
3558
3559 // P2280R4 struck the initialization requirement for variables of reference
3560 // type so we can no longer assume we have an Init.
3561 // Used to be C++20 [expr.const]p5.12:
3562 // ... reference has a preceding initialization and either ...
3563 if (Init && Init->isValueDependent()) {
3564 // The DeclRefExpr is not value-dependent, but the variable it refers to
3565 // has a value-dependent initializer. This should only happen in
3566 // constant-folding cases, where the variable is not actually of a suitable
3567 // type for use in a constant expression (otherwise the DeclRefExpr would
3568 // have been value-dependent too), so diagnose that.
3569 assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx));
3570 if (!Info.checkingPotentialConstantExpression()) {
3571 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
3572 ? diag::note_constexpr_ltor_non_constexpr
3573 : diag::note_constexpr_ltor_non_integral, 1)
3574 << VD << VD->getType();
3575 NoteLValueLocation(Info, Base);
3576 }
3577 return false;
3578 }
3579
3580 // Check that we can fold the initializer. In C++, we will have already done
3581 // this in the cases where it matters for conformance.
3582 // P2280R4 struck the initialization requirement for variables of reference
3583 // type so we can no longer assume we have an Init.
3584 // Used to be C++20 [expr.const]p5.12:
3585 // ... reference has a preceding initialization and either ...
3586 if (Init && !VD->evaluateValue() && !AllowConstexprUnknown) {
3587 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3588 NoteLValueLocation(Info, Base);
3589 return false;
3590 }
3591
3592 // Check that the variable is actually usable in constant expressions. For a
3593 // const integral variable or a reference, we might have a non-constant
3594 // initializer that we can nonetheless evaluate the initializer for. Such
3595 // variables are not usable in constant expressions. In C++98, the
3596 // initializer also syntactically needs to be an ICE.
3597 //
3598 // FIXME: We don't diagnose cases that aren't potentially usable in constant
3599 // expressions here; doing so would regress diagnostics for things like
3600 // reading from a volatile constexpr variable.
3601 if ((Info.getLangOpts().CPlusPlus && !VD->hasConstantInitialization() &&
3602 VD->mightBeUsableInConstantExpressions(Info.Ctx) &&
3603 !AllowConstexprUnknown) ||
3604 ((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) &&
3605 !Info.getLangOpts().CPlusPlus11 && !VD->hasICEInitializer(Info.Ctx))) {
3606 if (Init) {
3607 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3608 NoteLValueLocation(Info, Base);
3609 } else {
3610 Info.CCEDiag(E);
3611 }
3612 }
3613
3614 // Never use the initializer of a weak variable, not even for constant
3615 // folding. We can't be sure that this is the definition that will be used.
3616 if (VD->isWeak()) {
3617 Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD;
3618 NoteLValueLocation(Info, Base);
3619 return false;
3620 }
3621
3622 Result = VD->getEvaluatedValue();
3623
3624 if (!Result && !AllowConstexprUnknown)
3625 return false;
3626
3627 return CheckUninitReference(/*IsLocalVariable=*/false);
3628 }
3629
3630 /// Get the base index of the given base class within an APValue representing
3631 /// the given derived class.
3632 static unsigned getBaseIndex(const CXXRecordDecl *Derived,
3633 const CXXRecordDecl *Base) {
3634 Base = Base->getCanonicalDecl();
3635 unsigned Index = 0;
3636 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
3637 E = Derived->bases_end(); I != E; ++I, ++Index) {
3638 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
3639 return Index;
3640 }
3641
3642 llvm_unreachable("base class missing from derived class's bases list");
3643 }
3644
3645 /// Extract the value of a character from a string literal.
3646 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
3647 uint64_t Index) {
3648 assert(!isa<SourceLocExpr>(Lit) &&
3649 "SourceLocExpr should have already been converted to a StringLiteral");
3650
3651 // FIXME: Support MakeStringConstant
3652 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
3653 std::string Str;
3654 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
3655 assert(Index <= Str.size() && "Index too large");
3656 return APSInt::getUnsigned(Str.c_str()[Index]);
3657 }
3658
3659 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
3660 Lit = PE->getFunctionName();
3661 const StringLiteral *S = cast<StringLiteral>(Lit);
3662 const ConstantArrayType *CAT =
3663 Info.Ctx.getAsConstantArrayType(S->getType());
3664 assert(CAT && "string literal isn't an array");
3665 QualType CharType = CAT->getElementType();
3666 assert(CharType->isIntegerType() && "unexpected character type");
3667 APSInt Value(Info.Ctx.getTypeSize(CharType),
3668 CharType->isUnsignedIntegerType());
3669 if (Index < S->getLength())
3670 Value = S->getCodeUnit(Index);
3671 return Value;
3672 }
3673
3674 // Expand a string literal into an array of characters.
3675 //
3676 // FIXME: This is inefficient; we should probably introduce something similar
3677 // to the LLVM ConstantDataArray to make this cheaper.
3678 static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
3679 APValue &Result,
3680 QualType AllocType = QualType()) {
3681 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
3682 AllocType.isNull() ? S->getType() : AllocType);
3683 assert(CAT && "string literal isn't an array");
3684 QualType CharType = CAT->getElementType();
3685 assert(CharType->isIntegerType() && "unexpected character type");
3686
3687 unsigned Elts = CAT->getZExtSize();
3688 Result = APValue(APValue::UninitArray(),
3689 std::min(S->getLength(), Elts), Elts);
3690 APSInt Value(Info.Ctx.getTypeSize(CharType),
3691 CharType->isUnsignedIntegerType());
3692 if (Result.hasArrayFiller())
3693 Result.getArrayFiller() = APValue(Value);
3694 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
3695 Value = S->getCodeUnit(I);
3696 Result.getArrayInitializedElt(I) = APValue(Value);
3697 }
3698 }
3699
3700 // Expand an array so that it has more than Index filled elements.
3701 static void expandArray(APValue &Array, unsigned Index) {
3702 unsigned Size = Array.getArraySize();
3703 assert(Index < Size);
3704
3705 // Always at least double the number of elements for which we store a value.
3706 unsigned OldElts = Array.getArrayInitializedElts();
3707 unsigned NewElts = std::max(Index+1, OldElts * 2);
3708 NewElts = std::min(Size, std::max(NewElts, 8u));
3709
3710 // Copy the data across.
3711 APValue NewValue(APValue::UninitArray(), NewElts, Size);
3712 for (unsigned I = 0; I != OldElts; ++I)
3713 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
3714 for (unsigned I = OldElts; I != NewElts; ++I)
3715 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
3716 if (NewValue.hasArrayFiller())
3717 NewValue.getArrayFiller() = Array.getArrayFiller();
3718 Array.swap(NewValue);
3719 }
3720
3721 /// Determine whether a type would actually be read by an lvalue-to-rvalue
3722 /// conversion. If it's of class type, we may assume that the copy operation
3723 /// is trivial. Note that this is never true for a union type with fields
3724 /// (because the copy always "reads" the active member) and always true for
3725 /// a non-class type.
3726 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD);
3727 static bool isReadByLvalueToRvalueConversion(QualType T) {
3728 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3729 return !RD || isReadByLvalueToRvalueConversion(RD);
3730 }
3731 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD) {
3732 // FIXME: A trivial copy of a union copies the object representation, even if
3733 // the union is empty.
3734 if (RD->isUnion())
3735 return !RD->field_empty();
3736 if (RD->isEmpty())
3737 return false;
3738
3739 for (auto *Field : RD->fields())
3740 if (!Field->isUnnamedBitField() &&
3741 isReadByLvalueToRvalueConversion(Field->getType()))
3742 return true;
3743
3744 for (auto &BaseSpec : RD->bases())
3745 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
3746 return true;
3747
3748 return false;
3749 }
3750
3751 /// Diagnose an attempt to read from any unreadable field within the specified
3752 /// type, which might be a class type.
3753 static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK,
3754 QualType T) {
3755 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3756 if (!RD)
3757 return false;
3758
3759 if (!RD->hasMutableFields())
3760 return false;
3761
3762 for (auto *Field : RD->fields()) {
3763 // If we're actually going to read this field in some way, then it can't
3764 // be mutable. If we're in a union, then assigning to a mutable field
3765 // (even an empty one) can change the active member, so that's not OK.
3766 // FIXME: Add core issue number for the union case.
3767 if (Field->isMutable() &&
3768 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
3769 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field;
3770 Info.Note(Field->getLocation(), diag::note_declared_at);
3771 return true;
3772 }
3773
3774 if (diagnoseMutableFields(Info, E, AK, Field->getType()))
3775 return true;
3776 }
3777
3778 for (auto &BaseSpec : RD->bases())
3779 if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType()))
3780 return true;
3781
3782 // All mutable fields were empty, and thus not actually read.
3783 return false;
3784 }
3785
3786 static bool lifetimeStartedInEvaluation(EvalInfo &Info,
3787 APValue::LValueBase Base,
3788 bool MutableSubobject = false) {
3789 // A temporary or transient heap allocation we created.
3790 if (Base.getCallIndex() || Base.is<DynamicAllocLValue>())
3791 return true;
3792
3793 switch (Info.IsEvaluatingDecl) {
3794 case EvalInfo::EvaluatingDeclKind::None:
3795 return false;
3796
3797 case EvalInfo::EvaluatingDeclKind::Ctor:
3798 // The variable whose initializer we're evaluating.
3799 if (Info.EvaluatingDecl == Base)
3800 return true;
3801
3802 // A temporary lifetime-extended by the variable whose initializer we're
3803 // evaluating.
3804 if (auto *BaseE = Base.dyn_cast<const Expr *>())
3805 if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
3806 return Info.EvaluatingDecl == BaseMTE->getExtendingDecl();
3807 return false;
3808
3809 case EvalInfo::EvaluatingDeclKind::Dtor:
3810 // C++2a [expr.const]p6:
3811 // [during constant destruction] the lifetime of a and its non-mutable
3812 // subobjects (but not its mutable subobjects) [are] considered to start
3813 // within e.
3814 if (MutableSubobject || Base != Info.EvaluatingDecl)
3815 return false;
3816 // FIXME: We can meaningfully extend this to cover non-const objects, but
3817 // we will need special handling: we should be able to access only
3818 // subobjects of such objects that are themselves declared const.
3819 QualType T = getType(Base);
3820 return T.isConstQualified() || T->isReferenceType();
3821 }
3822
3823 llvm_unreachable("unknown evaluating decl kind");
3824 }
3825
3826 static bool CheckArraySize(EvalInfo &Info, const ConstantArrayType *CAT,
3827 SourceLocation CallLoc = {}) {
3828 return Info.CheckArraySize(
3829 CAT->getSizeExpr() ? CAT->getSizeExpr()->getBeginLoc() : CallLoc,
3830 CAT->getNumAddressingBits(Info.Ctx), CAT->getZExtSize(),
3831 /*Diag=*/true);
3832 }
3833
3834 static bool handleScalarCast(EvalInfo &Info, const FPOptions FPO, const Expr *E,
3835 QualType SourceTy, QualType DestTy,
3836 APValue const &Original, APValue &Result) {
3837 // boolean must be checked before integer
3838 // since IsIntegerType() is true for bool
3839 if (SourceTy->isBooleanType()) {
3840 if (DestTy->isBooleanType()) {
3841 Result = Original;
3842 return true;
3843 }
3844 if (DestTy->isIntegerType() || DestTy->isRealFloatingType()) {
3845 bool BoolResult;
3846 if (!HandleConversionToBool(Original, BoolResult))
3847 return false;
3848 uint64_t IntResult = BoolResult;
3849 QualType IntType = DestTy->isIntegerType()
3850 ? DestTy
3851 : Info.Ctx.getIntTypeForBitwidth(64, false);
3852 Result = APValue(Info.Ctx.MakeIntValue(IntResult, IntType));
3853 }
3854 if (DestTy->isRealFloatingType()) {
3855 APValue Result2 = APValue(APFloat(0.0));
3856 if (!HandleIntToFloatCast(Info, E, FPO,
3857 Info.Ctx.getIntTypeForBitwidth(64, false),
3858 Result.getInt(), DestTy, Result2.getFloat()))
3859 return false;
3860 Result = Result2;
3861 }
3862 return true;
3863 }
3864 if (SourceTy->isIntegerType()) {
3865 if (DestTy->isRealFloatingType()) {
3866 Result = APValue(APFloat(0.0));
3867 return HandleIntToFloatCast(Info, E, FPO, SourceTy, Original.getInt(),
3868 DestTy, Result.getFloat());
3869 }
3870 if (DestTy->isBooleanType()) {
3871 bool BoolResult;
3872 if (!HandleConversionToBool(Original, BoolResult))
3873 return false;
3874 uint64_t IntResult = BoolResult;
3875 Result = APValue(Info.Ctx.MakeIntValue(IntResult, DestTy));
3876 return true;
3877 }
3878 if (DestTy->isIntegerType()) {
3879 Result = APValue(
3880 HandleIntToIntCast(Info, E, DestTy, SourceTy, Original.getInt()));
3881 return true;
3882 }
3883 } else if (SourceTy->isRealFloatingType()) {
3884 if (DestTy->isRealFloatingType()) {
3885 Result = Original;
3886 return HandleFloatToFloatCast(Info, E, SourceTy, DestTy,
3887 Result.getFloat());
3888 }
3889 if (DestTy->isBooleanType()) {
3890 bool BoolResult;
3891 if (!HandleConversionToBool(Original, BoolResult))
3892 return false;
3893 uint64_t IntResult = BoolResult;
3894 Result = APValue(Info.Ctx.MakeIntValue(IntResult, DestTy));
3895 return true;
3896 }
3897 if (DestTy->isIntegerType()) {
3898 Result = APValue(APSInt());
3899 return HandleFloatToIntCast(Info, E, SourceTy, Original.getFloat(),
3900 DestTy, Result.getInt());
3901 }
3902 }
3903
3904 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3905 return false;
3906 }
3907
3908 // do the heavy lifting for casting to aggregate types
3909 // because we have to deal with bitfields specially
3910 static bool constructAggregate(EvalInfo &Info, const FPOptions FPO,
3911 const Expr *E, APValue &Result,
3912 QualType ResultType,
3913 SmallVectorImpl<APValue> &Elements,
3914 SmallVectorImpl<QualType> &ElTypes) {
3915
3916 SmallVector<std::tuple<APValue *, QualType, unsigned>> WorkList = {
3917 {&Result, ResultType, 0}};
3918
3919 unsigned ElI = 0;
3920 while (!WorkList.empty() && ElI < Elements.size()) {
3921 auto [Res, Type, BitWidth] = WorkList.pop_back_val();
3922
3923 if (Type->isRealFloatingType()) {
3924 if (!handleScalarCast(Info, FPO, E, ElTypes[ElI], Type, Elements[ElI],
3925 *Res))
3926 return false;
3927 ElI++;
3928 continue;
3929 }
3930 if (Type->isIntegerType()) {
3931 if (!handleScalarCast(Info, FPO, E, ElTypes[ElI], Type, Elements[ElI],
3932 *Res))
3933 return false;
3934 if (BitWidth > 0) {
3935 if (!Res->isInt())
3936 return false;
3937 APSInt &Int = Res->getInt();
3938 unsigned OldBitWidth = Int.getBitWidth();
3939 unsigned NewBitWidth = BitWidth;
3940 if (NewBitWidth < OldBitWidth)
3941 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
3942 }
3943 ElI++;
3944 continue;
3945 }
3946 if (Type->isVectorType()) {
3947 QualType ElTy = Type->castAs<VectorType>()->getElementType();
3948 unsigned NumEl = Type->castAs<VectorType>()->getNumElements();
3949 SmallVector<APValue> Vals(NumEl);
3950 for (unsigned I = 0; I < NumEl; ++I) {
3951 if (!handleScalarCast(Info, FPO, E, ElTypes[ElI], ElTy, Elements[ElI],
3952 Vals[I]))
3953 return false;
3954 ElI++;
3955 }
3956 *Res = APValue(Vals.data(), NumEl);
3957 continue;
3958 }
3959 if (Type->isConstantArrayType()) {
3960 QualType ElTy = cast<ConstantArrayType>(Info.Ctx.getAsArrayType(Type))
3961 ->getElementType();
3962 uint64_t Size =
3963 cast<ConstantArrayType>(Info.Ctx.getAsArrayType(Type))->getZExtSize();
3964 *Res = APValue(APValue::UninitArray(), Size, Size);
3965 for (int64_t I = Size - 1; I > -1; --I)
3966 WorkList.emplace_back(&Res->getArrayInitializedElt(I), ElTy, 0u);
3967 continue;
3968 }
3969 if (Type->isRecordType()) {
3970 const RecordDecl *RD = Type->getAsRecordDecl();
3971
3972 unsigned NumBases = 0;
3973 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
3974 NumBases = CXXRD->getNumBases();
3975
3976 *Res = APValue(APValue::UninitStruct(), NumBases, RD->getNumFields());
3977
3978 SmallVector<std::tuple<APValue *, QualType, unsigned>> ReverseList;
3979 // we need to traverse backwards
3980 // Visit the base classes.
3981 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3982 if (CXXRD->getNumBases() > 0) {
3983 assert(CXXRD->getNumBases() == 1);
3984 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[0];
3985 ReverseList.emplace_back(&Res->getStructBase(0), BS.getType(), 0u);
3986 }
3987 }
3988
3989 // Visit the fields.
3990 for (FieldDecl *FD : RD->fields()) {
3991 unsigned FDBW = 0;
3992 if (FD->isUnnamedBitField())
3993 continue;
3994 if (FD->isBitField()) {
3995 FDBW = FD->getBitWidthValue();
3996 }
3997
3998 ReverseList.emplace_back(&Res->getStructField(FD->getFieldIndex()),
3999 FD->getType(), FDBW);
4000 }
4001
4002 std::reverse(ReverseList.begin(), ReverseList.end());
4003 llvm::append_range(WorkList, ReverseList);
4004 continue;
4005 }
4006 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
4007 return false;
4008 }
4009 return true;
4010 }
4011
4012 static bool handleElementwiseCast(EvalInfo &Info, const Expr *E,
4013 const FPOptions FPO,
4014 SmallVectorImpl<APValue> &Elements,
4015 SmallVectorImpl<QualType> &SrcTypes,
4016 SmallVectorImpl<QualType> &DestTypes,
4017 SmallVectorImpl<APValue> &Results) {
4018
4019 assert((Elements.size() == SrcTypes.size()) &&
4020 (Elements.size() == DestTypes.size()));
4021
4022 for (unsigned I = 0, ESz = Elements.size(); I < ESz; ++I) {
4023 APValue Original = Elements[I];
4024 QualType SourceTy = SrcTypes[I];
4025 QualType DestTy = DestTypes[I];
4026
4027 if (!handleScalarCast(Info, FPO, E, SourceTy, DestTy, Original, Results[I]))
4028 return false;
4029 }
4030 return true;
4031 }
4032
4033 static unsigned elementwiseSize(EvalInfo &Info, QualType BaseTy) {
4034
4035 SmallVector<QualType> WorkList = {BaseTy};
4036
4037 unsigned Size = 0;
4038 while (!WorkList.empty()) {
4039 QualType Type = WorkList.pop_back_val();
4040 if (Type->isRealFloatingType() || Type->isIntegerType() ||
4041 Type->isBooleanType()) {
4042 ++Size;
4043 continue;
4044 }
4045 if (Type->isVectorType()) {
4046 unsigned NumEl = Type->castAs<VectorType>()->getNumElements();
4047 Size += NumEl;
4048 continue;
4049 }
4050 if (Type->isConstantArrayType()) {
4051 QualType ElTy = cast<ConstantArrayType>(Info.Ctx.getAsArrayType(Type))
4052 ->getElementType();
4053 uint64_t ArrSize =
4054 cast<ConstantArrayType>(Info.Ctx.getAsArrayType(Type))->getZExtSize();
4055 for (uint64_t I = 0; I < ArrSize; ++I) {
4056 WorkList.push_back(ElTy);
4057 }
4058 continue;
4059 }
4060 if (Type->isRecordType()) {
4061 const RecordDecl *RD = Type->getAsRecordDecl();
4062
4063 // Visit the base classes.
4064 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
4065 if (CXXRD->getNumBases() > 0) {
4066 assert(CXXRD->getNumBases() == 1);
4067 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[0];
4068 WorkList.push_back(BS.getType());
4069 }
4070 }
4071
4072 // visit the fields.
4073 for (FieldDecl *FD : RD->fields()) {
4074 if (FD->isUnnamedBitField())
4075 continue;
4076 WorkList.push_back(FD->getType());
4077 }
4078 continue;
4079 }
4080 }
4081 return Size;
4082 }
4083
4084 static bool hlslAggSplatHelper(EvalInfo &Info, const Expr *E, APValue &SrcVal,
4085 QualType &SrcTy) {
4086 SrcTy = E->getType();
4087
4088 if (!Evaluate(SrcVal, Info, E))
4089 return false;
4090
4091 assert((SrcVal.isFloat() || SrcVal.isInt() ||
4092 (SrcVal.isVector() && SrcVal.getVectorLength() == 1)) &&
4093 "Not a valid HLSLAggregateSplatCast.");
4094
4095 if (SrcVal.isVector()) {
4096 assert(SrcTy->isVectorType() && "Type mismatch.");
4097 SrcTy = SrcTy->castAs<VectorType>()->getElementType();
4098 SrcVal = SrcVal.getVectorElt(0);
4099 }
4100 return true;
4101 }
4102
4103 static bool flattenAPValue(EvalInfo &Info, const Expr *E, APValue Value,
4104 QualType BaseTy, SmallVectorImpl<APValue> &Elements,
4105 SmallVectorImpl<QualType> &Types, unsigned Size) {
4106
4107 SmallVector<std::pair<APValue, QualType>> WorkList = {{Value, BaseTy}};
4108 unsigned Populated = 0;
4109 while (!WorkList.empty() && Populated < Size) {
4110 auto [Work, Type] = WorkList.pop_back_val();
4111
4112 if (Work.isFloat() || Work.isInt()) {
4113 Elements.push_back(Work);
4114 Types.push_back(Type);
4115 Populated++;
4116 continue;
4117 }
4118 if (Work.isVector()) {
4119 assert(Type->isVectorType() && "Type mismatch.");
4120 QualType ElTy = Type->castAs<VectorType>()->getElementType();
4121 for (unsigned I = 0; I < Work.getVectorLength() && Populated < Size;
4122 I++) {
4123 Elements.push_back(Work.getVectorElt(I));
4124 Types.push_back(ElTy);
4125 Populated++;
4126 }
4127 continue;
4128 }
4129 if (Work.isArray()) {
4130 assert(Type->isConstantArrayType() && "Type mismatch.");
4131 QualType ElTy = cast<ConstantArrayType>(Info.Ctx.getAsArrayType(Type))
4132 ->getElementType();
4133 for (int64_t I = Work.getArraySize() - 1; I > -1; --I) {
4134 WorkList.emplace_back(Work.getArrayInitializedElt(I), ElTy);
4135 }
4136 continue;
4137 }
4138
4139 if (Work.isStruct()) {
4140 assert(Type->isRecordType() && "Type mismatch.");
4141
4142 const RecordDecl *RD = Type->getAsRecordDecl();
4143
4144 SmallVector<std::pair<APValue, QualType>> ReverseList;
4145 // Visit the fields.
4146 for (FieldDecl *FD : RD->fields()) {
4147 if (FD->isUnnamedBitField())
4148 continue;
4149 ReverseList.emplace_back(Work.getStructField(FD->getFieldIndex()),
4150 FD->getType());
4151 }
4152
4153 std::reverse(ReverseList.begin(), ReverseList.end());
4154 llvm::append_range(WorkList, ReverseList);
4155
4156 // Visit the base classes.
4157 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
4158 if (CXXRD->getNumBases() > 0) {
4159 assert(CXXRD->getNumBases() == 1);
4160 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[0];
4161 const APValue &Base = Work.getStructBase(0);
4162
4163 // Can happen in error cases.
4164 if (!Base.isStruct())
4165 return false;
4166
4167 WorkList.emplace_back(Base, BS.getType());
4168 }
4169 }
4170 continue;
4171 }
4172 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
4173 return false;
4174 }
4175 return true;
4176 }
4177
4178 namespace {
4179 /// A handle to a complete object (an object that is not a subobject of
4180 /// another object).
4181 struct CompleteObject {
4182 /// The identity of the object.
4183 APValue::LValueBase Base;
4184 /// The value of the complete object.
4185 APValue *Value;
4186 /// The type of the complete object.
4187 QualType Type;
4188
4189 CompleteObject() : Value(nullptr) {}
4190 CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
4191 : Base(Base), Value(Value), Type(Type) {}
4192
4193 bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const {
4194 // If this isn't a "real" access (eg, if it's just accessing the type
4195 // info), allow it. We assume the type doesn't change dynamically for
4196 // subobjects of constexpr objects (even though we'd hit UB here if it
4197 // did). FIXME: Is this right?
4198 if (!isAnyAccess(AK))
4199 return true;
4200
4201 // In C++14 onwards, it is permitted to read a mutable member whose
4202 // lifetime began within the evaluation.
4203 // FIXME: Should we also allow this in C++11?
4204 if (!Info.getLangOpts().CPlusPlus14 &&
4205 AK != AccessKinds::AK_IsWithinLifetime)
4206 return false;
4207 return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);
4208 }
4209
4210 explicit operator bool() const { return !Type.isNull(); }
4211 };
4212 } // end anonymous namespace
4213
4214 static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
4215 bool IsMutable = false) {
4216 // C++ [basic.type.qualifier]p1:
4217 // - A const object is an object of type const T or a non-mutable subobject
4218 // of a const object.
4219 if (ObjType.isConstQualified() && !IsMutable)
4220 SubobjType.addConst();
4221 // - A volatile object is an object of type const T or a subobject of a
4222 // volatile object.
4223 if (ObjType.isVolatileQualified())
4224 SubobjType.addVolatile();
4225 return SubobjType;
4226 }
4227
4228 /// Find the designated sub-object of an rvalue.
4229 template <typename SubobjectHandler>
4230 static typename SubobjectHandler::result_type
4231 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
4232 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
4233 if (Sub.Invalid)
4234 // A diagnostic will have already been produced.
4235 return handler.failed();
4236 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
4237 if (Info.getLangOpts().CPlusPlus11)
4238 Info.FFDiag(E, Sub.isOnePastTheEnd()
4239 ? diag::note_constexpr_access_past_end
4240 : diag::note_constexpr_access_unsized_array)
4241 << handler.AccessKind;
4242 else
4243 Info.FFDiag(E);
4244 return handler.failed();
4245 }
4246
4247 APValue *O = Obj.Value;
4248 QualType ObjType = Obj.Type;
4249 const FieldDecl *LastField = nullptr;
4250 const FieldDecl *VolatileField = nullptr;
4251
4252 // Walk the designator's path to find the subobject.
4253 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
4254 // Reading an indeterminate value is undefined, but assigning over one is OK.
4255 if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) ||
4256 (O->isIndeterminate() &&
4257 !isValidIndeterminateAccess(handler.AccessKind))) {
4258 // Object has ended lifetime.
4259 // If I is non-zero, some subobject (member or array element) of a
4260 // complete object has ended its lifetime, so this is valid for
4261 // IsWithinLifetime, resulting in false.
4262 if (I != 0 && handler.AccessKind == AK_IsWithinLifetime)
4263 return false;
4264 if (!Info.checkingPotentialConstantExpression())
4265 Info.FFDiag(E, diag::note_constexpr_access_uninit)
4266 << handler.AccessKind << O->isIndeterminate()
4267 << E->getSourceRange();
4268 return handler.failed();
4269 }
4270
4271 // C++ [class.ctor]p5, C++ [class.dtor]p5:
4272 // const and volatile semantics are not applied on an object under
4273 // {con,de}struction.
4274 if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
4275 ObjType->isRecordType() &&
4276 Info.isEvaluatingCtorDtor(
4277 Obj.Base, ArrayRef(Sub.Entries.begin(), Sub.Entries.begin() + I)) !=
4278 ConstructionPhase::None) {
4279 ObjType = Info.Ctx.getCanonicalType(ObjType);
4280 ObjType.removeLocalConst();
4281 ObjType.removeLocalVolatile();
4282 }
4283
4284 // If this is our last pass, check that the final object type is OK.
4285 if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
4286 // Accesses to volatile objects are prohibited.
4287 if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
4288 if (Info.getLangOpts().CPlusPlus) {
4289 int DiagKind;
4290 SourceLocation Loc;
4291 const NamedDecl *Decl = nullptr;
4292 if (VolatileField) {
4293 DiagKind = 2;
4294 Loc = VolatileField->getLocation();
4295 Decl = VolatileField;
4296 } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
4297 DiagKind = 1;
4298 Loc = VD->getLocation();
4299 Decl = VD;
4300 } else {
4301 DiagKind = 0;
4302 if (auto *E = Obj.Base.dyn_cast<const Expr *>())
4303 Loc = E->getExprLoc();
4304 }
4305 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
4306 << handler.AccessKind << DiagKind << Decl;
4307 Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
4308 } else {
4309 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
4310 }
4311 return handler.failed();
4312 }
4313
4314 // If we are reading an object of class type, there may still be more
4315 // things we need to check: if there are any mutable subobjects, we
4316 // cannot perform this read. (This only happens when performing a trivial
4317 // copy or assignment.)
4318 if (ObjType->isRecordType() &&
4319 !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
4320 diagnoseMutableFields(Info, E, handler.AccessKind, ObjType))
4321 return handler.failed();
4322 }
4323
4324 if (I == N) {
4325 if (!handler.found(*O, ObjType))
4326 return false;
4327
4328 // If we modified a bit-field, truncate it to the right width.
4329 if (isModification(handler.AccessKind) &&
4330 LastField && LastField->isBitField() &&
4331 !truncateBitfieldValue(Info, E, *O, LastField))
4332 return false;
4333
4334 return true;
4335 }
4336
4337 LastField = nullptr;
4338 if (ObjType->isArrayType()) {
4339 // Next subobject is an array element.
4340 const ArrayType *AT = Info.Ctx.getAsArrayType(ObjType);
4341 assert((isa<ConstantArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
4342 "vla in literal type?");
4343 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
4344 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT);
4345 CAT && CAT->getSize().ule(Index)) {
4346 // Note, it should not be possible to form a pointer with a valid
4347 // designator which points more than one past the end of the array.
4348 if (Info.getLangOpts().CPlusPlus11)
4349 Info.FFDiag(E, diag::note_constexpr_access_past_end)
4350 << handler.AccessKind;
4351 else
4352 Info.FFDiag(E);
4353 return handler.failed();
4354 }
4355
4356 ObjType = AT->getElementType();
4357
4358 if (O->getArrayInitializedElts() > Index)
4359 O = &O->getArrayInitializedElt(Index);
4360 else if (!isRead(handler.AccessKind)) {
4361 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT);
4362 CAT && !CheckArraySize(Info, CAT, E->getExprLoc()))
4363 return handler.failed();
4364
4365 expandArray(*O, Index);
4366 O = &O->getArrayInitializedElt(Index);
4367 } else
4368 O = &O->getArrayFiller();
4369 } else if (ObjType->isAnyComplexType()) {
4370 // Next subobject is a complex number.
4371 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
4372 if (Index > 1) {
4373 if (Info.getLangOpts().CPlusPlus11)
4374 Info.FFDiag(E, diag::note_constexpr_access_past_end)
4375 << handler.AccessKind;
4376 else
4377 Info.FFDiag(E);
4378 return handler.failed();
4379 }
4380
4381 ObjType = getSubobjectType(
4382 ObjType, ObjType->castAs<ComplexType>()->getElementType());
4383
4384 assert(I == N - 1 && "extracting subobject of scalar?");
4385 if (O->isComplexInt()) {
4386 return handler.found(Index ? O->getComplexIntImag()
4387 : O->getComplexIntReal(), ObjType);
4388 } else {
4389 assert(O->isComplexFloat());
4390 return handler.found(Index ? O->getComplexFloatImag()
4391 : O->getComplexFloatReal(), ObjType);
4392 }
4393 } else if (const auto *VT = ObjType->getAs<VectorType>()) {
4394 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
4395 unsigned NumElements = VT->getNumElements();
4396 if (Index == NumElements) {
4397 if (Info.getLangOpts().CPlusPlus11)
4398 Info.FFDiag(E, diag::note_constexpr_access_past_end)
4399 << handler.AccessKind;
4400 else
4401 Info.FFDiag(E);
4402 return handler.failed();
4403 }
4404
4405 if (Index > NumElements) {
4406 Info.CCEDiag(E, diag::note_constexpr_array_index)
4407 << Index << /*array*/ 0 << NumElements;
4408 return handler.failed();
4409 }
4410
4411 ObjType = VT->getElementType();
4412 assert(I == N - 1 && "extracting subobject of scalar?");
4413 return handler.found(O->getVectorElt(Index), ObjType);
4414 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
4415 if (Field->isMutable() &&
4416 !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) {
4417 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
4418 << handler.AccessKind << Field;
4419 Info.Note(Field->getLocation(), diag::note_declared_at);
4420 return handler.failed();
4421 }
4422
4423 // Next subobject is a class, struct or union field.
4424 RecordDecl *RD = ObjType->castAsCanonical<RecordType>()->getDecl();
4425 if (RD->isUnion()) {
4426 const FieldDecl *UnionField = O->getUnionField();
4427 if (!UnionField ||
4428 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
4429 if (I == N - 1 && handler.AccessKind == AK_Construct) {
4430 // Placement new onto an inactive union member makes it active.
4431 O->setUnion(Field, APValue());
4432 } else {
4433 // Pointer to/into inactive union member: Not within lifetime
4434 if (handler.AccessKind == AK_IsWithinLifetime)
4435 return false;
4436 // FIXME: If O->getUnionValue() is absent, report that there's no
4437 // active union member rather than reporting the prior active union
4438 // member. We'll need to fix nullptr_t to not use APValue() as its
4439 // representation first.
4440 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
4441 << handler.AccessKind << Field << !UnionField << UnionField;
4442 return handler.failed();
4443 }
4444 }
4445 O = &O->getUnionValue();
4446 } else
4447 O = &O->getStructField(Field->getFieldIndex());
4448
4449 ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
4450 LastField = Field;
4451 if (Field->getType().isVolatileQualified())
4452 VolatileField = Field;
4453 } else {
4454 // Next subobject is a base class.
4455 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
4456 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
4457 O = &O->getStructBase(getBaseIndex(Derived, Base));
4458
4459 ObjType = getSubobjectType(ObjType, Info.Ctx.getCanonicalTagType(Base));
4460 }
4461 }
4462 }
4463
4464 namespace {
4465 struct ExtractSubobjectHandler {
4466 EvalInfo &Info;
4467 const Expr *E;
4468 APValue &Result;
4469 const AccessKinds AccessKind;
4470
4471 typedef bool result_type;
4472 bool failed() { return false; }
4473 bool found(APValue &Subobj, QualType SubobjType) {
4474 Result = Subobj;
4475 if (AccessKind == AK_ReadObjectRepresentation)
4476 return true;
4477 return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
4478 }
4479 bool found(APSInt &Value, QualType SubobjType) {
4480 Result = APValue(Value);
4481 return true;
4482 }
4483 bool found(APFloat &Value, QualType SubobjType) {
4484 Result = APValue(Value);
4485 return true;
4486 }
4487 };
4488 } // end anonymous namespace
4489
4490 /// Extract the designated sub-object of an rvalue.
4491 static bool extractSubobject(EvalInfo &Info, const Expr *E,
4492 const CompleteObject &Obj,
4493 const SubobjectDesignator &Sub, APValue &Result,
4494 AccessKinds AK = AK_Read) {
4495 assert(AK == AK_Read || AK == AK_ReadObjectRepresentation);
4496 ExtractSubobjectHandler Handler = {Info, E, Result, AK};
4497 return findSubobject(Info, E, Obj, Sub, Handler);
4498 }
4499
4500 namespace {
4501 struct ModifySubobjectHandler {
4502 EvalInfo &Info;
4503 APValue &NewVal;
4504 const Expr *E;
4505
4506 typedef bool result_type;
4507 static const AccessKinds AccessKind = AK_Assign;
4508
4509 bool checkConst(QualType QT) {
4510 // Assigning to a const object has undefined behavior.
4511 if (QT.isConstQualified()) {
4512 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4513 return false;
4514 }
4515 return true;
4516 }
4517
4518 bool failed() { return false; }
4519 bool found(APValue &Subobj, QualType SubobjType) {
4520 if (!checkConst(SubobjType))
4521 return false;
4522 // We've been given ownership of NewVal, so just swap it in.
4523 Subobj.swap(NewVal);
4524 return true;
4525 }
4526 bool found(APSInt &Value, QualType SubobjType) {
4527 if (!checkConst(SubobjType))
4528 return false;
4529 if (!NewVal.isInt()) {
4530 // Maybe trying to write a cast pointer value into a complex?
4531 Info.FFDiag(E);
4532 return false;
4533 }
4534 Value = NewVal.getInt();
4535 return true;
4536 }
4537 bool found(APFloat &Value, QualType SubobjType) {
4538 if (!checkConst(SubobjType))
4539 return false;
4540 Value = NewVal.getFloat();
4541 return true;
4542 }
4543 };
4544 } // end anonymous namespace
4545
4546 const AccessKinds ModifySubobjectHandler::AccessKind;
4547
4548 /// Update the designated sub-object of an rvalue to the given value.
4549 static bool modifySubobject(EvalInfo &Info, const Expr *E,
4550 const CompleteObject &Obj,
4551 const SubobjectDesignator &Sub,
4552 APValue &NewVal) {
4553 ModifySubobjectHandler Handler = { Info, NewVal, E };
4554 return findSubobject(Info, E, Obj, Sub, Handler);
4555 }
4556
4557 /// Find the position where two subobject designators diverge, or equivalently
4558 /// the length of the common initial subsequence.
4559 static unsigned FindDesignatorMismatch(QualType ObjType,
4560 const SubobjectDesignator &A,
4561 const SubobjectDesignator &B,
4562 bool &WasArrayIndex) {
4563 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
4564 for (/**/; I != N; ++I) {
4565 if (!ObjType.isNull() &&
4566 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
4567 // Next subobject is an array element.
4568 if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
4569 WasArrayIndex = true;
4570 return I;
4571 }
4572 if (ObjType->isAnyComplexType())
4573 ObjType = ObjType->castAs<ComplexType>()->getElementType();
4574 else
4575 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
4576 } else {
4577 if (A.Entries[I].getAsBaseOrMember() !=
4578 B.Entries[I].getAsBaseOrMember()) {
4579 WasArrayIndex = false;
4580 return I;
4581 }
4582 if (const FieldDecl *FD = getAsField(A.Entries[I]))
4583 // Next subobject is a field.
4584 ObjType = FD->getType();
4585 else
4586 // Next subobject is a base class.
4587 ObjType = QualType();
4588 }
4589 }
4590 WasArrayIndex = false;
4591 return I;
4592 }
4593
4594 /// Determine whether the given subobject designators refer to elements of the
4595 /// same array object.
4596 static bool AreElementsOfSameArray(QualType ObjType,
4597 const SubobjectDesignator &A,
4598 const SubobjectDesignator &B) {
4599 if (A.Entries.size() != B.Entries.size())
4600 return false;
4601
4602 bool IsArray = A.MostDerivedIsArrayElement;
4603 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
4604 // A is a subobject of the array element.
4605 return false;
4606
4607 // If A (and B) designates an array element, the last entry will be the array
4608 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
4609 // of length 1' case, and the entire path must match.
4610 bool WasArrayIndex;
4611 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
4612 return CommonLength >= A.Entries.size() - IsArray;
4613 }
4614
4615 /// Find the complete object to which an LValue refers.
4616 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
4617 AccessKinds AK, const LValue &LVal,
4618 QualType LValType) {
4619 if (LVal.InvalidBase) {
4620 Info.FFDiag(E);
4621 return CompleteObject();
4622 }
4623
4624 if (!LVal.Base) {
4625 if (AK == AccessKinds::AK_Dereference)
4626 Info.FFDiag(E, diag::note_constexpr_dereferencing_null);
4627 else
4628 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
4629 return CompleteObject();
4630 }
4631
4632 CallStackFrame *Frame = nullptr;
4633 unsigned Depth = 0;
4634 if (LVal.getLValueCallIndex()) {
4635 std::tie(Frame, Depth) =
4636 Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
4637 if (!Frame) {
4638 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
4639 << AK << LVal.Base.is<const ValueDecl*>();
4640 NoteLValueLocation(Info, LVal.Base);
4641 return CompleteObject();
4642 }
4643 }
4644
4645 bool IsAccess = isAnyAccess(AK);
4646
4647 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
4648 // is not a constant expression (even if the object is non-volatile). We also
4649 // apply this rule to C++98, in order to conform to the expected 'volatile'
4650 // semantics.
4651 if (isFormalAccess(AK) && LValType.isVolatileQualified()) {
4652 if (Info.getLangOpts().CPlusPlus)
4653 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
4654 << AK << LValType;
4655 else
4656 Info.FFDiag(E);
4657 return CompleteObject();
4658 }
4659
4660 // Compute value storage location and type of base object.
4661 APValue *BaseVal = nullptr;
4662 QualType BaseType = getType(LVal.Base);
4663
4664 if (Info.getLangOpts().CPlusPlus14 && LVal.Base == Info.EvaluatingDecl &&
4665 lifetimeStartedInEvaluation(Info, LVal.Base)) {
4666 // This is the object whose initializer we're evaluating, so its lifetime
4667 // started in the current evaluation.
4668 BaseVal = Info.EvaluatingDeclValue;
4669 } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) {
4670 // Allow reading from a GUID declaration.
4671 if (auto *GD = dyn_cast<MSGuidDecl>(D)) {
4672 if (isModification(AK)) {
4673 // All the remaining cases do not permit modification of the object.
4674 Info.FFDiag(E, diag::note_constexpr_modify_global);
4675 return CompleteObject();
4676 }
4677 APValue &V = GD->getAsAPValue();
4678 if (V.isAbsent()) {
4679 Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
4680 << GD->getType();
4681 return CompleteObject();
4682 }
4683 return CompleteObject(LVal.Base, &V, GD->getType());
4684 }
4685
4686 // Allow reading the APValue from an UnnamedGlobalConstantDecl.
4687 if (auto *GCD = dyn_cast<UnnamedGlobalConstantDecl>(D)) {
4688 if (isModification(AK)) {
4689 Info.FFDiag(E, diag::note_constexpr_modify_global);
4690 return CompleteObject();
4691 }
4692 return CompleteObject(LVal.Base, const_cast<APValue *>(&GCD->getValue()),
4693 GCD->getType());
4694 }
4695
4696 // Allow reading from template parameter objects.
4697 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) {
4698 if (isModification(AK)) {
4699 Info.FFDiag(E, diag::note_constexpr_modify_global);
4700 return CompleteObject();
4701 }
4702 return CompleteObject(LVal.Base, const_cast<APValue *>(&TPO->getValue()),
4703 TPO->getType());
4704 }
4705
4706 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
4707 // In C++11, constexpr, non-volatile variables initialized with constant
4708 // expressions are constant expressions too. Inside constexpr functions,
4709 // parameters are constant expressions even if they're non-const.
4710 // In C++1y, objects local to a constant expression (those with a Frame) are
4711 // both readable and writable inside constant expressions.
4712 // In C, such things can also be folded, although they are not ICEs.
4713 const VarDecl *VD = dyn_cast<VarDecl>(D);
4714 if (VD) {
4715 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
4716 VD = VDef;
4717 }
4718 if (!VD || VD->isInvalidDecl()) {
4719 Info.FFDiag(E);
4720 return CompleteObject();
4721 }
4722
4723 bool IsConstant = BaseType.isConstant(Info.Ctx);
4724 bool ConstexprVar = false;
4725 if (const auto *VD = dyn_cast_if_present<VarDecl>(
4726 Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()))
4727 ConstexprVar = VD->isConstexpr();
4728
4729 // Unless we're looking at a local variable or argument in a constexpr call,
4730 // the variable we're reading must be const (unless we are binding to a
4731 // reference).
4732 if (AK != clang::AK_Dereference && !Frame) {
4733 if (IsAccess && isa<ParmVarDecl>(VD)) {
4734 // Access of a parameter that's not associated with a frame isn't going
4735 // to work out, but we can leave it to evaluateVarDeclInit to provide a
4736 // suitable diagnostic.
4737 } else if (Info.getLangOpts().CPlusPlus14 &&
4738 lifetimeStartedInEvaluation(Info, LVal.Base)) {
4739 // OK, we can read and modify an object if we're in the process of
4740 // evaluating its initializer, because its lifetime began in this
4741 // evaluation.
4742 } else if (isModification(AK)) {
4743 // All the remaining cases do not permit modification of the object.
4744 Info.FFDiag(E, diag::note_constexpr_modify_global);
4745 return CompleteObject();
4746 } else if (VD->isConstexpr()) {
4747 // OK, we can read this variable.
4748 } else if (Info.getLangOpts().C23 && ConstexprVar) {
4749 Info.FFDiag(E);
4750 return CompleteObject();
4751 } else if (BaseType->isIntegralOrEnumerationType()) {
4752 if (!IsConstant) {
4753 if (!IsAccess)
4754 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4755 if (Info.getLangOpts().CPlusPlus) {
4756 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
4757 Info.Note(VD->getLocation(), diag::note_declared_at);
4758 } else {
4759 Info.FFDiag(E);
4760 }
4761 return CompleteObject();
4762 }
4763 } else if (!IsAccess) {
4764 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4765 } else if ((IsConstant || BaseType->isReferenceType()) &&
4766 Info.checkingPotentialConstantExpression() &&
4767 BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) {
4768 // This variable might end up being constexpr. Don't diagnose it yet.
4769 } else if (IsConstant) {
4770 // Keep evaluating to see what we can do. In particular, we support
4771 // folding of const floating-point types, in order to make static const
4772 // data members of such types (supported as an extension) more useful.
4773 if (Info.getLangOpts().CPlusPlus) {
4774 Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11
4775 ? diag::note_constexpr_ltor_non_constexpr
4776 : diag::note_constexpr_ltor_non_integral, 1)
4777 << VD << BaseType;
4778 Info.Note(VD->getLocation(), diag::note_declared_at);
4779 } else {
4780 Info.CCEDiag(E);
4781 }
4782 } else {
4783 // Never allow reading a non-const value.
4784 if (Info.getLangOpts().CPlusPlus) {
4785 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
4786 ? diag::note_constexpr_ltor_non_constexpr
4787 : diag::note_constexpr_ltor_non_integral, 1)
4788 << VD << BaseType;
4789 Info.Note(VD->getLocation(), diag::note_declared_at);
4790 } else {
4791 Info.FFDiag(E);
4792 }
4793 return CompleteObject();
4794 }
4795 }
4796
4797 // When binding to a reference, the variable does not need to be constexpr
4798 // or have constant initalization.
4799 if (AK != clang::AK_Dereference &&
4800 !evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(),
4801 BaseVal))
4802 return CompleteObject();
4803 // If evaluateVarDeclInit sees a constexpr-unknown variable, it returns
4804 // a null BaseVal. Any constexpr-unknown variable seen here is an error:
4805 // we can't access a constexpr-unknown object.
4806 if (AK != clang::AK_Dereference && !BaseVal) {
4807 if (!Info.checkingPotentialConstantExpression()) {
4808 Info.FFDiag(E, diag::note_constexpr_access_unknown_variable, 1)
4809 << AK << VD;
4810 Info.Note(VD->getLocation(), diag::note_declared_at);
4811 }
4812 return CompleteObject();
4813 }
4814 } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) {
4815 std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
4816 if (!Alloc) {
4817 Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK;
4818 return CompleteObject();
4819 }
4820 return CompleteObject(LVal.Base, &(*Alloc)->Value,
4821 LVal.Base.getDynamicAllocType());
4822 }
4823 // When binding to a reference, the variable does not need to be
4824 // within its lifetime.
4825 else if (AK != clang::AK_Dereference) {
4826 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4827
4828 if (!Frame) {
4829 if (const MaterializeTemporaryExpr *MTE =
4830 dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
4831 assert(MTE->getStorageDuration() == SD_Static &&
4832 "should have a frame for a non-global materialized temporary");
4833
4834 // C++20 [expr.const]p4: [DR2126]
4835 // An object or reference is usable in constant expressions if it is
4836 // - a temporary object of non-volatile const-qualified literal type
4837 // whose lifetime is extended to that of a variable that is usable
4838 // in constant expressions
4839 //
4840 // C++20 [expr.const]p5:
4841 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
4842 // - a non-volatile glvalue that refers to an object that is usable
4843 // in constant expressions, or
4844 // - a non-volatile glvalue of literal type that refers to a
4845 // non-volatile object whose lifetime began within the evaluation
4846 // of E;
4847 //
4848 // C++11 misses the 'began within the evaluation of e' check and
4849 // instead allows all temporaries, including things like:
4850 // int &&r = 1;
4851 // int x = ++r;
4852 // constexpr int k = r;
4853 // Therefore we use the C++14-onwards rules in C++11 too.
4854 //
4855 // Note that temporaries whose lifetimes began while evaluating a
4856 // variable's constructor are not usable while evaluating the
4857 // corresponding destructor, not even if they're of const-qualified
4858 // types.
4859 if (!MTE->isUsableInConstantExpressions(Info.Ctx) &&
4860 !lifetimeStartedInEvaluation(Info, LVal.Base)) {
4861 if (!IsAccess)
4862 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4863 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
4864 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
4865 return CompleteObject();
4866 }
4867
4868 BaseVal = MTE->getOrCreateValue(false);
4869 assert(BaseVal && "got reference to unevaluated temporary");
4870 } else if (const CompoundLiteralExpr *CLE =
4871 dyn_cast_or_null<CompoundLiteralExpr>(Base)) {
4872 // According to GCC info page:
4873 //
4874 // 6.28 Compound Literals
4875 //
4876 // As an optimization, G++ sometimes gives array compound literals
4877 // longer lifetimes: when the array either appears outside a function or
4878 // has a const-qualified type. If foo and its initializer had elements
4879 // of type char *const rather than char *, or if foo were a global
4880 // variable, the array would have static storage duration. But it is
4881 // probably safest just to avoid the use of array compound literals in
4882 // C++ code.
4883 //
4884 // Obey that rule by checking constness for converted array types.
4885 if (QualType CLETy = CLE->getType(); CLETy->isArrayType() &&
4886 !LValType->isArrayType() &&
4887 !CLETy.isConstant(Info.Ctx)) {
4888 Info.FFDiag(E);
4889 Info.Note(CLE->getExprLoc(), diag::note_declared_at);
4890 return CompleteObject();
4891 }
4892
4893 BaseVal = &CLE->getStaticValue();
4894 } else {
4895 if (!IsAccess)
4896 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4897 APValue Val;
4898 LVal.moveInto(Val);
4899 Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
4900 << AK
4901 << Val.getAsString(Info.Ctx,
4902 Info.Ctx.getLValueReferenceType(LValType));
4903 NoteLValueLocation(Info, LVal.Base);
4904 return CompleteObject();
4905 }
4906 } else if (AK != clang::AK_Dereference) {
4907 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
4908 assert(BaseVal && "missing value for temporary");
4909 }
4910 }
4911
4912 // In C++14, we can't safely access any mutable state when we might be
4913 // evaluating after an unmodeled side effect. Parameters are modeled as state
4914 // in the caller, but aren't visible once the call returns, so they can be
4915 // modified in a speculatively-evaluated call.
4916 //
4917 // FIXME: Not all local state is mutable. Allow local constant subobjects
4918 // to be read here (but take care with 'mutable' fields).
4919 unsigned VisibleDepth = Depth;
4920 if (llvm::isa_and_nonnull<ParmVarDecl>(
4921 LVal.Base.dyn_cast<const ValueDecl *>()))
4922 ++VisibleDepth;
4923 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
4924 Info.EvalStatus.HasSideEffects) ||
4925 (isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth))
4926 return CompleteObject();
4927
4928 return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
4929 }
4930
4931 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This
4932 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
4933 /// glvalue referred to by an entity of reference type.
4934 ///
4935 /// \param Info - Information about the ongoing evaluation.
4936 /// \param Conv - The expression for which we are performing the conversion.
4937 /// Used for diagnostics.
4938 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
4939 /// case of a non-class type).
4940 /// \param LVal - The glvalue on which we are attempting to perform this action.
4941 /// \param RVal - The produced value will be placed here.
4942 /// \param WantObjectRepresentation - If true, we're looking for the object
4943 /// representation rather than the value, and in particular,
4944 /// there is no requirement that the result be fully initialized.
4945 static bool
4946 handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type,
4947 const LValue &LVal, APValue &RVal,
4948 bool WantObjectRepresentation = false) {
4949 if (LVal.Designator.Invalid)
4950 return false;
4951
4952 // Check for special cases where there is no existing APValue to look at.
4953 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4954
4955 AccessKinds AK =
4956 WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;
4957
4958 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
4959 if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
4960 // Special-case character extraction so we don't have to construct an
4961 // APValue for the whole string.
4962 assert(LVal.Designator.Entries.size() <= 1 &&
4963 "Can only read characters from string literals");
4964 if (LVal.Designator.Entries.empty()) {
4965 // Fail for now for LValue to RValue conversion of an array.
4966 // (This shouldn't show up in C/C++, but it could be triggered by a
4967 // weird EvaluateAsRValue call from a tool.)
4968 Info.FFDiag(Conv);
4969 return false;
4970 }
4971 if (LVal.Designator.isOnePastTheEnd()) {
4972 if (Info.getLangOpts().CPlusPlus11)
4973 Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
4974 else
4975 Info.FFDiag(Conv);
4976 return false;
4977 }
4978 uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
4979 RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
4980 return true;
4981 }
4982 }
4983
4984 CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
4985 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
4986 }
4987
4988 static bool hlslElementwiseCastHelper(EvalInfo &Info, const Expr *E,
4989 QualType DestTy,
4990 SmallVectorImpl<APValue> &SrcVals,
4991 SmallVectorImpl<QualType> &SrcTypes) {
4992 APValue Val;
4993 if (!Evaluate(Val, Info, E))
4994 return false;
4995
4996 // must be dealing with a record
4997 if (Val.isLValue()) {
4998 LValue LVal;
4999 LVal.setFrom(Info.Ctx, Val);
5000 if (!handleLValueToRValueConversion(Info, E, E->getType(), LVal, Val))
5001 return false;
5002 }
5003
5004 unsigned NEls = elementwiseSize(Info, DestTy);
5005 // flatten the source
5006 if (!flattenAPValue(Info, E, Val, E->getType(), SrcVals, SrcTypes, NEls))
5007 return false;
5008
5009 return true;
5010 }
5011
5012 /// Perform an assignment of Val to LVal. Takes ownership of Val.
5013 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
5014 QualType LValType, APValue &Val) {
5015 if (LVal.Designator.Invalid)
5016 return false;
5017
5018 if (!Info.getLangOpts().CPlusPlus14) {
5019 Info.FFDiag(E);
5020 return false;
5021 }
5022
5023 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
5024 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
5025 }
5026
5027 namespace {
5028 struct CompoundAssignSubobjectHandler {
5029 EvalInfo &Info;
5030 const CompoundAssignOperator *E;
5031 QualType PromotedLHSType;
5032 BinaryOperatorKind Opcode;
5033 const APValue &RHS;
5034
5035 static const AccessKinds AccessKind = AK_Assign;
5036
5037 typedef bool result_type;
5038
5039 bool checkConst(QualType QT) {
5040 // Assigning to a const object has undefined behavior.
5041 if (QT.isConstQualified()) {
5042 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
5043 return false;
5044 }
5045 return true;
5046 }
5047
5048 bool failed() { return false; }
5049 bool found(APValue &Subobj, QualType SubobjType) {
5050 switch (Subobj.getKind()) {
5051 case APValue::Int:
5052 return found(Subobj.getInt(), SubobjType);
5053 case APValue::Float:
5054 return found(Subobj.getFloat(), SubobjType);
5055 case APValue::ComplexInt:
5056 case APValue::ComplexFloat:
5057 // FIXME: Implement complex compound assignment.
5058 Info.FFDiag(E);
5059 return false;
5060 case APValue::LValue:
5061 return foundPointer(Subobj, SubobjType);
5062 case APValue::Vector:
5063 return foundVector(Subobj, SubobjType);
5064 case APValue::Indeterminate:
5065 Info.FFDiag(E, diag::note_constexpr_access_uninit)
5066 << /*read of=*/0 << /*uninitialized object=*/1
5067 << E->getLHS()->getSourceRange();
5068 return false;
5069 default:
5070 // FIXME: can this happen?
5071 Info.FFDiag(E);
5072 return false;
5073 }
5074 }
5075
5076 bool foundVector(APValue &Value, QualType SubobjType) {
5077 if (!checkConst(SubobjType))
5078 return false;
5079
5080 if (!SubobjType->isVectorType()) {
5081 Info.FFDiag(E);
5082 return false;
5083 }
5084 return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS);
5085 }
5086
5087 bool found(APSInt &Value, QualType SubobjType) {
5088 if (!checkConst(SubobjType))
5089 return false;
5090
5091 if (!SubobjType->isIntegerType()) {
5092 // We don't support compound assignment on integer-cast-to-pointer
5093 // values.
5094 Info.FFDiag(E);
5095 return false;
5096 }
5097
5098 if (RHS.isInt()) {
5099 APSInt LHS =
5100 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
5101 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
5102 return false;
5103 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
5104 return true;
5105 } else if (RHS.isFloat()) {
5106 const FPOptions FPO = E->getFPFeaturesInEffect(
5107 Info.Ctx.getLangOpts());
5108 APFloat FValue(0.0);
5109 return HandleIntToFloatCast(Info, E, FPO, SubobjType, Value,
5110 PromotedLHSType, FValue) &&
5111 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
5112 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
5113 Value);
5114 }
5115
5116 Info.FFDiag(E);
5117 return false;
5118 }
5119 bool found(APFloat &Value, QualType SubobjType) {
5120 return checkConst(SubobjType) &&
5121 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
5122 Value) &&
5123 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
5124 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
5125 }
5126 bool foundPointer(APValue &Subobj, QualType SubobjType) {
5127 if (!checkConst(SubobjType))
5128 return false;
5129
5130 QualType PointeeType;
5131 if (const PointerType *PT = SubobjType->getAs<PointerType>())
5132 PointeeType = PT->getPointeeType();
5133
5134 if (PointeeType.isNull() || !RHS.isInt() ||
5135 (Opcode != BO_Add && Opcode != BO_Sub)) {
5136 Info.FFDiag(E);
5137 return false;
5138 }
5139
5140 APSInt Offset = RHS.getInt();
5141 if (Opcode == BO_Sub)
5142 negateAsSigned(Offset);
5143
5144 LValue LVal;
5145 LVal.setFrom(Info.Ctx, Subobj);
5146 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
5147 return false;
5148 LVal.moveInto(Subobj);
5149 return true;
5150 }
5151 };
5152 } // end anonymous namespace
5153
5154 const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
5155
5156 /// Perform a compound assignment of LVal <op>= RVal.
5157 static bool handleCompoundAssignment(EvalInfo &Info,
5158 const CompoundAssignOperator *E,
5159 const LValue &LVal, QualType LValType,
5160 QualType PromotedLValType,
5161 BinaryOperatorKind Opcode,
5162 const APValue &RVal) {
5163 if (LVal.Designator.Invalid)
5164 return false;
5165
5166 if (!Info.getLangOpts().CPlusPlus14) {
5167 Info.FFDiag(E);
5168 return false;
5169 }
5170
5171 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
5172 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
5173 RVal };
5174 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
5175 }
5176
5177 namespace {
5178 struct IncDecSubobjectHandler {
5179 EvalInfo &Info;
5180 const UnaryOperator *E;
5181 AccessKinds AccessKind;
5182 APValue *Old;
5183
5184 typedef bool result_type;
5185
5186 bool checkConst(QualType QT) {
5187 // Assigning to a const object has undefined behavior.
5188 if (QT.isConstQualified()) {
5189 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
5190 return false;
5191 }
5192 return true;
5193 }
5194
5195 bool failed() { return false; }
5196 bool found(APValue &Subobj, QualType SubobjType) {
5197 // Stash the old value. Also clear Old, so we don't clobber it later
5198 // if we're post-incrementing a complex.
5199 if (Old) {
5200 *Old = Subobj;
5201 Old = nullptr;
5202 }
5203
5204 switch (Subobj.getKind()) {
5205 case APValue::Int:
5206 return found(Subobj.getInt(), SubobjType);
5207 case APValue::Float:
5208 return found(Subobj.getFloat(), SubobjType);
5209 case APValue::ComplexInt:
5210 return found(Subobj.getComplexIntReal(),
5211 SubobjType->castAs<ComplexType>()->getElementType()
5212 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
5213 case APValue::ComplexFloat:
5214 return found(Subobj.getComplexFloatReal(),
5215 SubobjType->castAs<ComplexType>()->getElementType()
5216 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
5217 case APValue::LValue:
5218 return foundPointer(Subobj, SubobjType);
5219 default:
5220 // FIXME: can this happen?
5221 Info.FFDiag(E);
5222 return false;
5223 }
5224 }
5225 bool found(APSInt &Value, QualType SubobjType) {
5226 if (!checkConst(SubobjType))
5227 return false;
5228
5229 if (!SubobjType->isIntegerType()) {
5230 // We don't support increment / decrement on integer-cast-to-pointer
5231 // values.
5232 Info.FFDiag(E);
5233 return false;
5234 }
5235
5236 if (Old) *Old = APValue(Value);
5237
5238 // bool arithmetic promotes to int, and the conversion back to bool
5239 // doesn't reduce mod 2^n, so special-case it.
5240 if (SubobjType->isBooleanType()) {
5241 if (AccessKind == AK_Increment)
5242 Value = 1;
5243 else
5244 Value = !Value;
5245 return true;
5246 }
5247
5248 bool WasNegative = Value.isNegative();
5249 if (AccessKind == AK_Increment) {
5250 ++Value;
5251
5252 if (!WasNegative && Value.isNegative() && E->canOverflow()) {
5253 APSInt ActualValue(Value, /*IsUnsigned*/true);
5254 return HandleOverflow(Info, E, ActualValue, SubobjType);
5255 }
5256 } else {
5257 --Value;
5258
5259 if (WasNegative && !Value.isNegative() && E->canOverflow()) {
5260 unsigned BitWidth = Value.getBitWidth();
5261 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
5262 ActualValue.setBit(BitWidth);
5263 return HandleOverflow(Info, E, ActualValue, SubobjType);
5264 }
5265 }
5266 return true;
5267 }
5268 bool found(APFloat &Value, QualType SubobjType) {
5269 if (!checkConst(SubobjType))
5270 return false;
5271
5272 if (Old) *Old = APValue(Value);
5273
5274 APFloat One(Value.getSemantics(), 1);
5275 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
5276 APFloat::opStatus St;
5277 if (AccessKind == AK_Increment)
5278 St = Value.add(One, RM);
5279 else
5280 St = Value.subtract(One, RM);
5281 return checkFloatingPointResult(Info, E, St);
5282 }
5283 bool foundPointer(APValue &Subobj, QualType SubobjType) {
5284 if (!checkConst(SubobjType))
5285 return false;
5286
5287 QualType PointeeType;
5288 if (const PointerType *PT = SubobjType->getAs<PointerType>())
5289 PointeeType = PT->getPointeeType();
5290 else {
5291 Info.FFDiag(E);
5292 return false;
5293 }
5294
5295 LValue LVal;
5296 LVal.setFrom(Info.Ctx, Subobj);
5297 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
5298 AccessKind == AK_Increment ? 1 : -1))
5299 return false;
5300 LVal.moveInto(Subobj);
5301 return true;
5302 }
5303 };
5304 } // end anonymous namespace
5305
5306 /// Perform an increment or decrement on LVal.
5307 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
5308 QualType LValType, bool IsIncrement, APValue *Old) {
5309 if (LVal.Designator.Invalid)
5310 return false;
5311
5312 if (!Info.getLangOpts().CPlusPlus14) {
5313 Info.FFDiag(E);
5314 return false;
5315 }
5316
5317 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
5318 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
5319 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
5320 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
5321 }
5322
5323 /// Build an lvalue for the object argument of a member function call.
5324 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
5325 LValue &This) {
5326 if (Object->getType()->isPointerType() && Object->isPRValue())
5327 return EvaluatePointer(Object, This, Info);
5328
5329 if (Object->isGLValue())
5330 return EvaluateLValue(Object, This, Info);
5331
5332 if (Object->getType()->isLiteralType(Info.Ctx))
5333 return EvaluateTemporary(Object, This, Info);
5334
5335 if (Object->getType()->isRecordType() && Object->isPRValue())
5336 return EvaluateTemporary(Object, This, Info);
5337
5338 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
5339 return false;
5340 }
5341
5342 /// HandleMemberPointerAccess - Evaluate a member access operation and build an
5343 /// lvalue referring to the result.
5344 ///
5345 /// \param Info - Information about the ongoing evaluation.
5346 /// \param LV - An lvalue referring to the base of the member pointer.
5347 /// \param RHS - The member pointer expression.
5348 /// \param IncludeMember - Specifies whether the member itself is included in
5349 /// the resulting LValue subobject designator. This is not possible when
5350 /// creating a bound member function.
5351 /// \return The field or method declaration to which the member pointer refers,
5352 /// or 0 if evaluation fails.
5353 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
5354 QualType LVType,
5355 LValue &LV,
5356 const Expr *RHS,
5357 bool IncludeMember = true) {
5358 MemberPtr MemPtr;
5359 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
5360 return nullptr;
5361
5362 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
5363 // member value, the behavior is undefined.
5364 if (!MemPtr.getDecl()) {
5365 // FIXME: Specific diagnostic.
5366 Info.FFDiag(RHS);
5367 return nullptr;
5368 }
5369
5370 if (MemPtr.isDerivedMember()) {
5371 // This is a member of some derived class. Truncate LV appropriately.
5372 // The end of the derived-to-base path for the base object must match the
5373 // derived-to-base path for the member pointer.
5374 // C++23 [expr.mptr.oper]p4:
5375 // If the result of E1 is an object [...] whose most derived object does
5376 // not contain the member to which E2 refers, the behavior is undefined.
5377 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
5378 LV.Designator.Entries.size()) {
5379 Info.FFDiag(RHS);
5380 return nullptr;
5381 }
5382 unsigned PathLengthToMember =
5383 LV.Designator.Entries.size() - MemPtr.Path.size();
5384 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
5385 const CXXRecordDecl *LVDecl = getAsBaseClass(
5386 LV.Designator.Entries[PathLengthToMember + I]);
5387 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
5388 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
5389 Info.FFDiag(RHS);
5390 return nullptr;
5391 }
5392 }
5393 // MemPtr.Path only contains the base classes of the class directly
5394 // containing the member E2. It is still necessary to check that the class
5395 // directly containing the member E2 lies on the derived-to-base path of E1
5396 // to avoid incorrectly permitting member pointer access into a sibling
5397 // class of the class containing the member E2. If this class would
5398 // correspond to the most-derived class of E1, it either isn't contained in
5399 // LV.Designator.Entries or the corresponding entry refers to an array
5400 // element instead. Therefore get the most derived class directly in this
5401 // case. Otherwise the previous entry should correpond to this class.
5402 const CXXRecordDecl *LastLVDecl =
5403 (PathLengthToMember > LV.Designator.MostDerivedPathLength)
5404 ? getAsBaseClass(LV.Designator.Entries[PathLengthToMember - 1])
5405 : LV.Designator.MostDerivedType->getAsCXXRecordDecl();
5406 const CXXRecordDecl *LastMPDecl = MemPtr.getContainingRecord();
5407 if (LastLVDecl->getCanonicalDecl() != LastMPDecl->getCanonicalDecl()) {
5408 Info.FFDiag(RHS);
5409 return nullptr;
5410 }
5411
5412 // Truncate the lvalue to the appropriate derived class.
5413 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
5414 PathLengthToMember))
5415 return nullptr;
5416 } else if (!MemPtr.Path.empty()) {
5417 // Extend the LValue path with the member pointer's path.
5418 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
5419 MemPtr.Path.size() + IncludeMember);
5420
5421 // Walk down to the appropriate base class.
5422 if (const PointerType *PT = LVType->getAs<PointerType>())
5423 LVType = PT->getPointeeType();
5424 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
5425 assert(RD && "member pointer access on non-class-type expression");
5426 // The first class in the path is that of the lvalue.
5427 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
5428 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
5429 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
5430 return nullptr;
5431 RD = Base;
5432 }
5433 // Finally cast to the class containing the member.
5434 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
5435 MemPtr.getContainingRecord()))
5436 return nullptr;
5437 }
5438
5439 // Add the member. Note that we cannot build bound member functions here.
5440 if (IncludeMember) {
5441 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
5442 if (!HandleLValueMember(Info, RHS, LV, FD))
5443 return nullptr;
5444 } else if (const IndirectFieldDecl *IFD =
5445 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
5446 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
5447 return nullptr;
5448 } else {
5449 llvm_unreachable("can't construct reference to bound member function");
5450 }
5451 }
5452
5453 return MemPtr.getDecl();
5454 }
5455
5456 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
5457 const BinaryOperator *BO,
5458 LValue &LV,
5459 bool IncludeMember = true) {
5460 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
5461
5462 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
5463 if (Info.noteFailure()) {
5464 MemberPtr MemPtr;
5465 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
5466 }
5467 return nullptr;
5468 }
5469
5470 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
5471 BO->getRHS(), IncludeMember);
5472 }
5473
5474 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
5475 /// the provided lvalue, which currently refers to the base object.
5476 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
5477 LValue &Result) {
5478 SubobjectDesignator &D = Result.Designator;
5479 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
5480 return false;
5481
5482 QualType TargetQT = E->getType();
5483 if (const PointerType *PT = TargetQT->getAs<PointerType>())
5484 TargetQT = PT->getPointeeType();
5485
5486 auto InvalidCast = [&]() {
5487 if (!Info.checkingPotentialConstantExpression() ||
5488 !Result.AllowConstexprUnknown) {
5489 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
5490 << D.MostDerivedType << TargetQT;
5491 }
5492 return false;
5493 };
5494
5495 // Check this cast lands within the final derived-to-base subobject path.
5496 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size())
5497 return InvalidCast();
5498
5499 // Check the type of the final cast. We don't need to check the path,
5500 // since a cast can only be formed if the path is unique.
5501 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
5502 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
5503 const CXXRecordDecl *FinalType;
5504 if (NewEntriesSize == D.MostDerivedPathLength)
5505 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
5506 else
5507 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
5508 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl())
5509 return InvalidCast();
5510
5511 // Truncate the lvalue to the appropriate derived class.
5512 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
5513 }
5514
5515 /// Get the value to use for a default-initialized object of type T.
5516 /// Return false if it encounters something invalid.
5517 static bool handleDefaultInitValue(QualType T, APValue &Result) {
5518 bool Success = true;
5519
5520 // If there is already a value present don't overwrite it.
5521 if (!Result.isAbsent())
5522 return true;
5523
5524 if (auto *RD = T->getAsCXXRecordDecl()) {
5525 if (RD->isInvalidDecl()) {
5526 Result = APValue();
5527 return false;
5528 }
5529 if (RD->isUnion()) {
5530 Result = APValue((const FieldDecl *)nullptr);
5531 return true;
5532 }
5533 Result =
5534 APValue(APValue::UninitStruct(), RD->getNumBases(), RD->getNumFields());
5535
5536 unsigned Index = 0;
5537 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
5538 End = RD->bases_end();
5539 I != End; ++I, ++Index)
5540 Success &=
5541 handleDefaultInitValue(I->getType(), Result.getStructBase(Index));
5542
5543 for (const auto *I : RD->fields()) {
5544 if (I->isUnnamedBitField())
5545 continue;
5546 Success &= handleDefaultInitValue(
5547 I->getType(), Result.getStructField(I->getFieldIndex()));
5548 }
5549 return Success;
5550 }
5551
5552 if (auto *AT =
5553 dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
5554 Result = APValue(APValue::UninitArray(), 0, AT->getZExtSize());
5555 if (Result.hasArrayFiller())
5556 Success &=
5557 handleDefaultInitValue(AT->getElementType(), Result.getArrayFiller());
5558
5559 return Success;
5560 }
5561
5562 Result = APValue::IndeterminateValue();
5563 return true;
5564 }
5565
5566 namespace {
5567 enum EvalStmtResult {
5568 /// Evaluation failed.
5569 ESR_Failed,
5570 /// Hit a 'return' statement.
5571 ESR_Returned,
5572 /// Evaluation succeeded.
5573 ESR_Succeeded,
5574 /// Hit a 'continue' statement.
5575 ESR_Continue,
5576 /// Hit a 'break' statement.
5577 ESR_Break,
5578 /// Still scanning for 'case' or 'default' statement.
5579 ESR_CaseNotFound
5580 };
5581 }
5582 /// Evaluates the initializer of a reference.
5583 static bool EvaluateInitForDeclOfReferenceType(EvalInfo &Info,
5584 const ValueDecl *D,
5585 const Expr *Init, LValue &Result,
5586 APValue &Val) {
5587 assert(Init->isGLValue() && D->getType()->isReferenceType());
5588 // A reference is an lvalue.
5589 if (!EvaluateLValue(Init, Result, Info))
5590 return false;
5591 // [C++26][decl.ref]
5592 // The object designated by such a glvalue can be outside its lifetime
5593 // Because a null pointer value or a pointer past the end of an object
5594 // does not point to an object, a reference in a well-defined program cannot
5595 // refer to such things;
5596 if (!Result.Designator.Invalid && Result.Designator.isOnePastTheEnd()) {
5597 Info.FFDiag(Init, diag::note_constexpr_access_past_end) << AK_Dereference;
5598 return false;
5599 }
5600
5601 // Save the result.
5602 Result.moveInto(Val);
5603 return true;
5604 }
5605
5606 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
5607 if (VD->isInvalidDecl())
5608 return false;
5609 // We don't need to evaluate the initializer for a static local.
5610 if (!VD->hasLocalStorage())
5611 return true;
5612
5613 LValue Result;
5614 APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(),
5615 ScopeKind::Block, Result);
5616
5617 const Expr *InitE = VD->getInit();
5618 if (!InitE) {
5619 if (VD->getType()->isDependentType())
5620 return Info.noteSideEffect();
5621 return handleDefaultInitValue(VD->getType(), Val);
5622 }
5623 if (InitE->isValueDependent())
5624 return false;
5625
5626 // For references to objects, check they do not designate a one-past-the-end
5627 // object.
5628 if (VD->getType()->isReferenceType()) {
5629 return EvaluateInitForDeclOfReferenceType(Info, VD, InitE, Result, Val);
5630 } else if (!EvaluateInPlace(Val, Info, Result, InitE)) {
5631 // Wipe out any partially-computed value, to allow tracking that this
5632 // evaluation failed.
5633 Val = APValue();
5634 return false;
5635 }
5636
5637 return true;
5638 }
5639
5640 static bool EvaluateDecompositionDeclInit(EvalInfo &Info,
5641 const DecompositionDecl *DD);
5642
5643 static bool EvaluateDecl(EvalInfo &Info, const Decl *D,
5644 bool EvaluateConditionDecl = false) {
5645 bool OK = true;
5646 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
5647 OK &= EvaluateVarDecl(Info, VD);
5648
5649 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D);
5650 EvaluateConditionDecl && DD)
5651 OK &= EvaluateDecompositionDeclInit(Info, DD);
5652
5653 return OK;
5654 }
5655
5656 static bool EvaluateDecompositionDeclInit(EvalInfo &Info,
5657 const DecompositionDecl *DD) {
5658 bool OK = true;
5659 for (auto *BD : DD->flat_bindings())
5660 if (auto *VD = BD->getHoldingVar())
5661 OK &= EvaluateDecl(Info, VD, /*EvaluateConditionDecl=*/true);
5662
5663 return OK;
5664 }
5665
5666 static bool MaybeEvaluateDeferredVarDeclInit(EvalInfo &Info,
5667 const VarDecl *VD) {
5668 if (auto *DD = dyn_cast_if_present<DecompositionDecl>(VD)) {
5669 if (!EvaluateDecompositionDeclInit(Info, DD))
5670 return false;
5671 }
5672 return true;
5673 }
5674
5675 static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info) {
5676 assert(E->isValueDependent());
5677 if (Info.noteSideEffect())
5678 return true;
5679 assert(E->containsErrors() && "valid value-dependent expression should never "
5680 "reach invalid code path.");
5681 return false;
5682 }
5683
5684 /// Evaluate a condition (either a variable declaration or an expression).
5685 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
5686 const Expr *Cond, bool &Result) {
5687 if (Cond->isValueDependent())
5688 return false;
5689 FullExpressionRAII Scope(Info);
5690 if (CondDecl && !EvaluateDecl(Info, CondDecl))
5691 return false;
5692 if (!EvaluateAsBooleanCondition(Cond, Result, Info))
5693 return false;
5694 if (!MaybeEvaluateDeferredVarDeclInit(Info, CondDecl))
5695 return false;
5696 return Scope.destroy();
5697 }
5698
5699 namespace {
5700 /// A location where the result (returned value) of evaluating a
5701 /// statement should be stored.
5702 struct StmtResult {
5703 /// The APValue that should be filled in with the returned value.
5704 APValue &Value;
5705 /// The location containing the result, if any (used to support RVO).
5706 const LValue *Slot;
5707 };
5708
5709 struct TempVersionRAII {
5710 CallStackFrame &Frame;
5711
5712 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
5713 Frame.pushTempVersion();
5714 }
5715
5716 ~TempVersionRAII() {
5717 Frame.popTempVersion();
5718 }
5719 };
5720
5721 }
5722
5723 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
5724 const Stmt *S,
5725 const SwitchCase *SC = nullptr);
5726
5727 /// Helper to implement named break/continue. Returns 'true' if the evaluation
5728 /// result should be propagated up. Otherwise, it sets the evaluation result
5729 /// to either Continue to continue the current loop, or Succeeded to break it.
5730 static bool ShouldPropagateBreakContinue(EvalInfo &Info,
5731 const Stmt *LoopOrSwitch,
5732 ArrayRef<BlockScopeRAII *> Scopes,
5733 EvalStmtResult &ESR) {
5734 bool IsSwitch = isa<SwitchStmt>(LoopOrSwitch);
5735
5736 // For loops, map Succeeded to Continue so we don't have to check for both.
5737 if (!IsSwitch && ESR == ESR_Succeeded) {
5738 ESR = ESR_Continue;
5739 return false;
5740 }
5741
5742 if (ESR != ESR_Break && ESR != ESR_Continue)
5743 return false;
5744
5745 // Are we breaking out of or continuing this statement?
5746 bool CanBreakOrContinue = !IsSwitch || ESR == ESR_Break;
5747 const Stmt *StackTop = Info.BreakContinueStack.back();
5748 if (CanBreakOrContinue && (StackTop == nullptr || StackTop == LoopOrSwitch)) {
5749 Info.BreakContinueStack.pop_back();
5750 if (ESR == ESR_Break)
5751 ESR = ESR_Succeeded;
5752 return false;
5753 }
5754
5755 // We're not. Propagate the result up.
5756 for (BlockScopeRAII *S : Scopes) {
5757 if (!S->destroy()) {
5758 ESR = ESR_Failed;
5759 break;
5760 }
5761 }
5762 return true;
5763 }
5764
5765 /// Evaluate the body of a loop, and translate the result as appropriate.
5766 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
5767 const Stmt *Body,
5768 const SwitchCase *Case = nullptr) {
5769 BlockScopeRAII Scope(Info);
5770
5771 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case);
5772 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
5773 ESR = ESR_Failed;
5774
5775 return ESR;
5776 }
5777
5778 /// Evaluate a switch statement.
5779 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
5780 const SwitchStmt *SS) {
5781 BlockScopeRAII Scope(Info);
5782
5783 // Evaluate the switch condition.
5784 APSInt Value;
5785 {
5786 if (const Stmt *Init = SS->getInit()) {
5787 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
5788 if (ESR != ESR_Succeeded) {
5789 if (ESR != ESR_Failed && !Scope.destroy())
5790 ESR = ESR_Failed;
5791 return ESR;
5792 }
5793 }
5794
5795 FullExpressionRAII CondScope(Info);
5796 if (SS->getConditionVariable() &&
5797 !EvaluateDecl(Info, SS->getConditionVariable()))
5798 return ESR_Failed;
5799 if (SS->getCond()->isValueDependent()) {
5800 // We don't know what the value is, and which branch should jump to.
5801 EvaluateDependentExpr(SS->getCond(), Info);
5802 return ESR_Failed;
5803 }
5804 if (!EvaluateInteger(SS->getCond(), Value, Info))
5805 return ESR_Failed;
5806
5807 if (!MaybeEvaluateDeferredVarDeclInit(Info, SS->getConditionVariable()))
5808 return ESR_Failed;
5809
5810 if (!CondScope.destroy())
5811 return ESR_Failed;
5812 }
5813
5814 // Find the switch case corresponding to the value of the condition.
5815 // FIXME: Cache this lookup.
5816 const SwitchCase *Found = nullptr;
5817 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
5818 SC = SC->getNextSwitchCase()) {
5819 if (isa<DefaultStmt>(SC)) {
5820 Found = SC;
5821 continue;
5822 }
5823
5824 const CaseStmt *CS = cast<CaseStmt>(SC);
5825 const Expr *LHS = CS->getLHS();
5826 const Expr *RHS = CS->getRHS();
5827 if (LHS->isValueDependent() || (RHS && RHS->isValueDependent()))
5828 return ESR_Failed;
5829 APSInt LHSValue = LHS->EvaluateKnownConstInt(Info.Ctx);
5830 APSInt RHSValue = RHS ? RHS->EvaluateKnownConstInt(Info.Ctx) : LHSValue;
5831 if (LHSValue <= Value && Value <= RHSValue) {
5832 Found = SC;
5833 break;
5834 }
5835 }
5836
5837 if (!Found)
5838 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5839
5840 // Search the switch body for the switch case and evaluate it from there.
5841 EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found);
5842 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
5843 return ESR_Failed;
5844 if (ShouldPropagateBreakContinue(Info, SS, /*Scopes=*/{}, ESR))
5845 return ESR;
5846
5847 switch (ESR) {
5848 case ESR_Break:
5849 llvm_unreachable("Should have been converted to Succeeded");
5850 case ESR_Succeeded:
5851 case ESR_Continue:
5852 case ESR_Failed:
5853 case ESR_Returned:
5854 return ESR;
5855 case ESR_CaseNotFound:
5856 // This can only happen if the switch case is nested within a statement
5857 // expression. We have no intention of supporting that.
5858 Info.FFDiag(Found->getBeginLoc(),
5859 diag::note_constexpr_stmt_expr_unsupported);
5860 return ESR_Failed;
5861 }
5862 llvm_unreachable("Invalid EvalStmtResult!");
5863 }
5864
5865 static bool CheckLocalVariableDeclaration(EvalInfo &Info, const VarDecl *VD) {
5866 // An expression E is a core constant expression unless the evaluation of E
5867 // would evaluate one of the following: [C++23] - a control flow that passes
5868 // through a declaration of a variable with static or thread storage duration
5869 // unless that variable is usable in constant expressions.
5870 if (VD->isLocalVarDecl() && VD->isStaticLocal() &&
5871 !VD->isUsableInConstantExpressions(Info.Ctx)) {
5872 Info.CCEDiag(VD->getLocation(), diag::note_constexpr_static_local)
5873 << (VD->getTSCSpec() == TSCS_unspecified ? 0 : 1) << VD;
5874 return false;
5875 }
5876 return true;
5877 }
5878
5879 // Evaluate a statement.
5880 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
5881 const Stmt *S, const SwitchCase *Case) {
5882 if (!Info.nextStep(S))
5883 return ESR_Failed;
5884
5885 // If we're hunting down a 'case' or 'default' label, recurse through
5886 // substatements until we hit the label.
5887 if (Case) {
5888 switch (S->getStmtClass()) {
5889 case Stmt::CompoundStmtClass:
5890 // FIXME: Precompute which substatement of a compound statement we
5891 // would jump to, and go straight there rather than performing a
5892 // linear scan each time.
5893 case Stmt::LabelStmtClass:
5894 case Stmt::AttributedStmtClass:
5895 case Stmt::DoStmtClass:
5896 break;
5897
5898 case Stmt::CaseStmtClass:
5899 case Stmt::DefaultStmtClass:
5900 if (Case == S)
5901 Case = nullptr;
5902 break;
5903
5904 case Stmt::IfStmtClass: {
5905 // FIXME: Precompute which side of an 'if' we would jump to, and go
5906 // straight there rather than scanning both sides.
5907 const IfStmt *IS = cast<IfStmt>(S);
5908
5909 // Wrap the evaluation in a block scope, in case it's a DeclStmt
5910 // preceded by our switch label.
5911 BlockScopeRAII Scope(Info);
5912
5913 // Step into the init statement in case it brings an (uninitialized)
5914 // variable into scope.
5915 if (const Stmt *Init = IS->getInit()) {
5916 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5917 if (ESR != ESR_CaseNotFound) {
5918 assert(ESR != ESR_Succeeded);
5919 return ESR;
5920 }
5921 }
5922
5923 // Condition variable must be initialized if it exists.
5924 // FIXME: We can skip evaluating the body if there's a condition
5925 // variable, as there can't be any case labels within it.
5926 // (The same is true for 'for' statements.)
5927
5928 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
5929 if (ESR == ESR_Failed)
5930 return ESR;
5931 if (ESR != ESR_CaseNotFound)
5932 return Scope.destroy() ? ESR : ESR_Failed;
5933 if (!IS->getElse())
5934 return ESR_CaseNotFound;
5935
5936 ESR = EvaluateStmt(Result, Info, IS->getElse(), Case);
5937 if (ESR == ESR_Failed)
5938 return ESR;
5939 if (ESR != ESR_CaseNotFound)
5940 return Scope.destroy() ? ESR : ESR_Failed;
5941 return ESR_CaseNotFound;
5942 }
5943
5944 case Stmt::WhileStmtClass: {
5945 EvalStmtResult ESR =
5946 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
5947 if (ShouldPropagateBreakContinue(Info, S, /*Scopes=*/{}, ESR))
5948 return ESR;
5949 if (ESR != ESR_Continue)
5950 return ESR;
5951 break;
5952 }
5953
5954 case Stmt::ForStmtClass: {
5955 const ForStmt *FS = cast<ForStmt>(S);
5956 BlockScopeRAII Scope(Info);
5957
5958 // Step into the init statement in case it brings an (uninitialized)
5959 // variable into scope.
5960 if (const Stmt *Init = FS->getInit()) {
5961 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5962 if (ESR != ESR_CaseNotFound) {
5963 assert(ESR != ESR_Succeeded);
5964 return ESR;
5965 }
5966 }
5967
5968 EvalStmtResult ESR =
5969 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
5970 if (ShouldPropagateBreakContinue(Info, FS, /*Scopes=*/{}, ESR))
5971 return ESR;
5972 if (ESR != ESR_Continue)
5973 return ESR;
5974 if (const auto *Inc = FS->getInc()) {
5975 if (Inc->isValueDependent()) {
5976 if (!EvaluateDependentExpr(Inc, Info))
5977 return ESR_Failed;
5978 } else {
5979 FullExpressionRAII IncScope(Info);
5980 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5981 return ESR_Failed;
5982 }
5983 }
5984 break;
5985 }
5986
5987 case Stmt::DeclStmtClass: {
5988 // Start the lifetime of any uninitialized variables we encounter. They
5989 // might be used by the selected branch of the switch.
5990 const DeclStmt *DS = cast<DeclStmt>(S);
5991 for (const auto *D : DS->decls()) {
5992 if (const auto *VD = dyn_cast<VarDecl>(D)) {
5993 if (!CheckLocalVariableDeclaration(Info, VD))
5994 return ESR_Failed;
5995 if (VD->hasLocalStorage() && !VD->getInit())
5996 if (!EvaluateVarDecl(Info, VD))
5997 return ESR_Failed;
5998 // FIXME: If the variable has initialization that can't be jumped
5999 // over, bail out of any immediately-surrounding compound-statement
6000 // too. There can't be any case labels here.
6001 }
6002 }
6003 return ESR_CaseNotFound;
6004 }
6005
6006 default:
6007 return ESR_CaseNotFound;
6008 }
6009 }
6010
6011 switch (S->getStmtClass()) {
6012 default:
6013 if (const Expr *E = dyn_cast<Expr>(S)) {
6014 if (E->isValueDependent()) {
6015 if (!EvaluateDependentExpr(E, Info))
6016 return ESR_Failed;
6017 } else {
6018 // Don't bother evaluating beyond an expression-statement which couldn't
6019 // be evaluated.
6020 // FIXME: Do we need the FullExpressionRAII object here?
6021 // VisitExprWithCleanups should create one when necessary.
6022 FullExpressionRAII Scope(Info);
6023 if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy())
6024 return ESR_Failed;
6025 }
6026 return ESR_Succeeded;
6027 }
6028
6029 Info.FFDiag(S->getBeginLoc()) << S->getSourceRange();
6030 return ESR_Failed;
6031
6032 case Stmt::NullStmtClass:
6033 return ESR_Succeeded;
6034
6035 case Stmt::DeclStmtClass: {
6036 const DeclStmt *DS = cast<DeclStmt>(S);
6037 for (const auto *D : DS->decls()) {
6038 const VarDecl *VD = dyn_cast_or_null<VarDecl>(D);
6039 if (VD && !CheckLocalVariableDeclaration(Info, VD))
6040 return ESR_Failed;
6041 // Each declaration initialization is its own full-expression.
6042 FullExpressionRAII Scope(Info);
6043 if (!EvaluateDecl(Info, D, /*EvaluateConditionDecl=*/true) &&
6044 !Info.noteFailure())
6045 return ESR_Failed;
6046 if (!Scope.destroy())
6047 return ESR_Failed;
6048 }
6049 return ESR_Succeeded;
6050 }
6051
6052 case Stmt::ReturnStmtClass: {
6053 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
6054 FullExpressionRAII Scope(Info);
6055 if (RetExpr && RetExpr->isValueDependent()) {
6056 EvaluateDependentExpr(RetExpr, Info);
6057 // We know we returned, but we don't know what the value is.
6058 return ESR_Failed;
6059 }
6060 if (RetExpr &&
6061 !(Result.Slot
6062 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
6063 : Evaluate(Result.Value, Info, RetExpr)))
6064 return ESR_Failed;
6065 return Scope.destroy() ? ESR_Returned : ESR_Failed;
6066 }
6067
6068 case Stmt::CompoundStmtClass: {
6069 BlockScopeRAII Scope(Info);
6070
6071 const CompoundStmt *CS = cast<CompoundStmt>(S);
6072 for (const auto *BI : CS->body()) {
6073 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
6074 if (ESR == ESR_Succeeded)
6075 Case = nullptr;
6076 else if (ESR != ESR_CaseNotFound) {
6077 if (ESR != ESR_Failed && !Scope.destroy())
6078 return ESR_Failed;
6079 return ESR;
6080 }
6081 }
6082 if (Case)
6083 return ESR_CaseNotFound;
6084 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
6085 }
6086
6087 case Stmt::IfStmtClass: {
6088 const IfStmt *IS = cast<IfStmt>(S);
6089
6090 // Evaluate the condition, as either a var decl or as an expression.
6091 BlockScopeRAII Scope(Info);
6092 if (const Stmt *Init = IS->getInit()) {
6093 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
6094 if (ESR != ESR_Succeeded) {
6095 if (ESR != ESR_Failed && !Scope.destroy())
6096 return ESR_Failed;
6097 return ESR;
6098 }
6099 }
6100 bool Cond;
6101 if (IS->isConsteval()) {
6102 Cond = IS->isNonNegatedConsteval();
6103 // If we are not in a constant context, if consteval should not evaluate
6104 // to true.
6105 if (!Info.InConstantContext)
6106 Cond = !Cond;
6107 } else if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(),
6108 Cond))
6109 return ESR_Failed;
6110
6111 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
6112 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
6113 if (ESR != ESR_Succeeded) {
6114 if (ESR != ESR_Failed && !Scope.destroy())
6115 return ESR_Failed;
6116 return ESR;
6117 }
6118 }
6119 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
6120 }
6121
6122 case Stmt::WhileStmtClass: {
6123 const WhileStmt *WS = cast<WhileStmt>(S);
6124 while (true) {
6125 BlockScopeRAII Scope(Info);
6126 bool Continue;
6127 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
6128 Continue))
6129 return ESR_Failed;
6130 if (!Continue)
6131 break;
6132
6133 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
6134 if (ShouldPropagateBreakContinue(Info, WS, &Scope, ESR))
6135 return ESR;
6136
6137 if (ESR != ESR_Continue) {
6138 if (ESR != ESR_Failed && !Scope.destroy())
6139 return ESR_Failed;
6140 return ESR;
6141 }
6142 if (!Scope.destroy())
6143 return ESR_Failed;
6144 }
6145 return ESR_Succeeded;
6146 }
6147
6148 case Stmt::DoStmtClass: {
6149 const DoStmt *DS = cast<DoStmt>(S);
6150 bool Continue;
6151 do {
6152 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
6153 if (ShouldPropagateBreakContinue(Info, DS, /*Scopes=*/{}, ESR))
6154 return ESR;
6155 if (ESR != ESR_Continue)
6156 return ESR;
6157 Case = nullptr;
6158
6159 if (DS->getCond()->isValueDependent()) {
6160 EvaluateDependentExpr(DS->getCond(), Info);
6161 // Bailout as we don't know whether to keep going or terminate the loop.
6162 return ESR_Failed;
6163 }
6164 FullExpressionRAII CondScope(Info);
6165 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) ||
6166 !CondScope.destroy())
6167 return ESR_Failed;
6168 } while (Continue);
6169 return ESR_Succeeded;
6170 }
6171
6172 case Stmt::ForStmtClass: {
6173 const ForStmt *FS = cast<ForStmt>(S);
6174 BlockScopeRAII ForScope(Info);
6175 if (FS->getInit()) {
6176 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
6177 if (ESR != ESR_Succeeded) {
6178 if (ESR != ESR_Failed && !ForScope.destroy())
6179 return ESR_Failed;
6180 return ESR;
6181 }
6182 }
6183 while (true) {
6184 BlockScopeRAII IterScope(Info);
6185 bool Continue = true;
6186 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
6187 FS->getCond(), Continue))
6188 return ESR_Failed;
6189
6190 if (!Continue) {
6191 if (!IterScope.destroy())
6192 return ESR_Failed;
6193 break;
6194 }
6195
6196 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
6197 if (ShouldPropagateBreakContinue(Info, FS, {&IterScope, &ForScope}, ESR))
6198 return ESR;
6199 if (ESR != ESR_Continue) {
6200 if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))
6201 return ESR_Failed;
6202 return ESR;
6203 }
6204
6205 if (const auto *Inc = FS->getInc()) {
6206 if (Inc->isValueDependent()) {
6207 if (!EvaluateDependentExpr(Inc, Info))
6208 return ESR_Failed;
6209 } else {
6210 FullExpressionRAII IncScope(Info);
6211 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
6212 return ESR_Failed;
6213 }
6214 }
6215
6216 if (!IterScope.destroy())
6217 return ESR_Failed;
6218 }
6219 return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;
6220 }
6221
6222 case Stmt::CXXForRangeStmtClass: {
6223 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
6224 BlockScopeRAII Scope(Info);
6225
6226 // Evaluate the init-statement if present.
6227 if (FS->getInit()) {
6228 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
6229 if (ESR != ESR_Succeeded) {
6230 if (ESR != ESR_Failed && !Scope.destroy())
6231 return ESR_Failed;
6232 return ESR;
6233 }
6234 }
6235
6236 // Initialize the __range variable.
6237 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
6238 if (ESR != ESR_Succeeded) {
6239 if (ESR != ESR_Failed && !Scope.destroy())
6240 return ESR_Failed;
6241 return ESR;
6242 }
6243
6244 // In error-recovery cases it's possible to get here even if we failed to
6245 // synthesize the __begin and __end variables.
6246 if (!FS->getBeginStmt() || !FS->getEndStmt() || !FS->getCond())
6247 return ESR_Failed;
6248
6249 // Create the __begin and __end iterators.
6250 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
6251 if (ESR != ESR_Succeeded) {
6252 if (ESR != ESR_Failed && !Scope.destroy())
6253 return ESR_Failed;
6254 return ESR;
6255 }
6256 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
6257 if (ESR != ESR_Succeeded) {
6258 if (ESR != ESR_Failed && !Scope.destroy())
6259 return ESR_Failed;
6260 return ESR;
6261 }
6262
6263 while (true) {
6264 // Condition: __begin != __end.
6265 {
6266 if (FS->getCond()->isValueDependent()) {
6267 EvaluateDependentExpr(FS->getCond(), Info);
6268 // We don't know whether to keep going or terminate the loop.
6269 return ESR_Failed;
6270 }
6271 bool Continue = true;
6272 FullExpressionRAII CondExpr(Info);
6273 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
6274 return ESR_Failed;
6275 if (!Continue)
6276 break;
6277 }
6278
6279 // User's variable declaration, initialized by *__begin.
6280 BlockScopeRAII InnerScope(Info);
6281 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
6282 if (ESR != ESR_Succeeded) {
6283 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
6284 return ESR_Failed;
6285 return ESR;
6286 }
6287
6288 // Loop body.
6289 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
6290 if (ShouldPropagateBreakContinue(Info, FS, {&InnerScope, &Scope}, ESR))
6291 return ESR;
6292 if (ESR != ESR_Continue) {
6293 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
6294 return ESR_Failed;
6295 return ESR;
6296 }
6297 if (FS->getInc()->isValueDependent()) {
6298 if (!EvaluateDependentExpr(FS->getInc(), Info))
6299 return ESR_Failed;
6300 } else {
6301 // Increment: ++__begin
6302 if (!EvaluateIgnoredValue(Info, FS->getInc()))
6303 return ESR_Failed;
6304 }
6305
6306 if (!InnerScope.destroy())
6307 return ESR_Failed;
6308 }
6309
6310 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
6311 }
6312
6313 case Stmt::SwitchStmtClass:
6314 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
6315
6316 case Stmt::ContinueStmtClass:
6317 case Stmt::BreakStmtClass: {
6318 auto *B = cast<LoopControlStmt>(S);
6319 Info.BreakContinueStack.push_back(B->getNamedLoopOrSwitch());
6320 return isa<ContinueStmt>(S) ? ESR_Continue : ESR_Break;
6321 }
6322
6323 case Stmt::LabelStmtClass:
6324 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
6325
6326 case Stmt::AttributedStmtClass: {
6327 const auto *AS = cast<AttributedStmt>(S);
6328 const auto *SS = AS->getSubStmt();
6329 MSConstexprContextRAII ConstexprContext(
6330 *Info.CurrentCall, hasSpecificAttr<MSConstexprAttr>(AS->getAttrs()) &&
6331 isa<ReturnStmt>(SS));
6332
6333 auto LO = Info.getASTContext().getLangOpts();
6334 if (LO.CXXAssumptions && !LO.MSVCCompat) {
6335 for (auto *Attr : AS->getAttrs()) {
6336 auto *AA = dyn_cast<CXXAssumeAttr>(Attr);
6337 if (!AA)
6338 continue;
6339
6340 auto *Assumption = AA->getAssumption();
6341 if (Assumption->isValueDependent())
6342 return ESR_Failed;
6343
6344 if (Assumption->HasSideEffects(Info.getASTContext()))
6345 continue;
6346
6347 bool Value;
6348 if (!EvaluateAsBooleanCondition(Assumption, Value, Info))
6349 return ESR_Failed;
6350 if (!Value) {
6351 Info.CCEDiag(Assumption->getExprLoc(),
6352 diag::note_constexpr_assumption_failed);
6353 return ESR_Failed;
6354 }
6355 }
6356 }
6357
6358 return EvaluateStmt(Result, Info, SS, Case);
6359 }
6360
6361 case Stmt::CaseStmtClass:
6362 case Stmt::DefaultStmtClass:
6363 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
6364 case Stmt::CXXTryStmtClass:
6365 // Evaluate try blocks by evaluating all sub statements.
6366 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
6367 }
6368 }
6369
6370 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
6371 /// default constructor. If so, we'll fold it whether or not it's marked as
6372 /// constexpr. If it is marked as constexpr, we will never implicitly define it,
6373 /// so we need special handling.
6374 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
6375 const CXXConstructorDecl *CD,
6376 bool IsValueInitialization) {
6377 if (!CD->isTrivial() || !CD->isDefaultConstructor())
6378 return false;
6379
6380 // Value-initialization does not call a trivial default constructor, so such a
6381 // call is a core constant expression whether or not the constructor is
6382 // constexpr.
6383 if (!CD->isConstexpr() && !IsValueInitialization) {
6384 if (Info.getLangOpts().CPlusPlus11) {
6385 // FIXME: If DiagDecl is an implicitly-declared special member function,
6386 // we should be much more explicit about why it's not constexpr.
6387 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
6388 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
6389 Info.Note(CD->getLocation(), diag::note_declared_at);
6390 } else {
6391 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
6392 }
6393 }
6394 return true;
6395 }
6396
6397 /// CheckConstexprFunction - Check that a function can be called in a constant
6398 /// expression.
6399 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
6400 const FunctionDecl *Declaration,
6401 const FunctionDecl *Definition,
6402 const Stmt *Body) {
6403 // Potential constant expressions can contain calls to declared, but not yet
6404 // defined, constexpr functions.
6405 if (Info.checkingPotentialConstantExpression() && !Definition &&
6406 Declaration->isConstexpr())
6407 return false;
6408
6409 // Bail out if the function declaration itself is invalid. We will
6410 // have produced a relevant diagnostic while parsing it, so just
6411 // note the problematic sub-expression.
6412 if (Declaration->isInvalidDecl()) {
6413 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
6414 return false;
6415 }
6416
6417 // DR1872: An instantiated virtual constexpr function can't be called in a
6418 // constant expression (prior to C++20). We can still constant-fold such a
6419 // call.
6420 if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) &&
6421 cast<CXXMethodDecl>(Declaration)->isVirtual())
6422 Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
6423
6424 if (Definition && Definition->isInvalidDecl()) {
6425 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
6426 return false;
6427 }
6428
6429 // Can we evaluate this function call?
6430 if (Definition && Body &&
6431 (Definition->isConstexpr() || (Info.CurrentCall->CanEvalMSConstexpr &&
6432 Definition->hasAttr<MSConstexprAttr>())))
6433 return true;
6434
6435 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
6436 // Special note for the assert() macro, as the normal error message falsely
6437 // implies we cannot use an assertion during constant evaluation.
6438 if (CallLoc.isMacroID() && DiagDecl->getIdentifier()) {
6439 // FIXME: Instead of checking for an implementation-defined function,
6440 // check and evaluate the assert() macro.
6441 StringRef Name = DiagDecl->getName();
6442 bool AssertFailed =
6443 Name == "__assert_rtn" || Name == "__assert_fail" || Name == "_wassert";
6444 if (AssertFailed) {
6445 Info.FFDiag(CallLoc, diag::note_constexpr_assert_failed);
6446 return false;
6447 }
6448 }
6449
6450 if (Info.getLangOpts().CPlusPlus11) {
6451 // If this function is not constexpr because it is an inherited
6452 // non-constexpr constructor, diagnose that directly.
6453 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
6454 if (CD && CD->isInheritingConstructor()) {
6455 auto *Inherited = CD->getInheritedConstructor().getConstructor();
6456 if (!Inherited->isConstexpr())
6457 DiagDecl = CD = Inherited;
6458 }
6459
6460 // FIXME: If DiagDecl is an implicitly-declared special member function
6461 // or an inheriting constructor, we should be much more explicit about why
6462 // it's not constexpr.
6463 if (CD && CD->isInheritingConstructor())
6464 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
6465 << CD->getInheritedConstructor().getConstructor()->getParent();
6466 else
6467 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
6468 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
6469 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
6470 } else {
6471 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
6472 }
6473 return false;
6474 }
6475
6476 namespace {
6477 struct CheckDynamicTypeHandler {
6478 AccessKinds AccessKind;
6479 typedef bool result_type;
6480 bool failed() { return false; }
6481 bool found(APValue &Subobj, QualType SubobjType) { return true; }
6482 bool found(APSInt &Value, QualType SubobjType) { return true; }
6483 bool found(APFloat &Value, QualType SubobjType) { return true; }
6484 };
6485 } // end anonymous namespace
6486
6487 /// Check that we can access the notional vptr of an object / determine its
6488 /// dynamic type.
6489 static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
6490 AccessKinds AK, bool Polymorphic) {
6491 if (This.Designator.Invalid)
6492 return false;
6493
6494 CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
6495
6496 if (!Obj)
6497 return false;
6498
6499 if (!Obj.Value) {
6500 // The object is not usable in constant expressions, so we can't inspect
6501 // its value to see if it's in-lifetime or what the active union members
6502 // are. We can still check for a one-past-the-end lvalue.
6503 if (This.Designator.isOnePastTheEnd() ||
6504 This.Designator.isMostDerivedAnUnsizedArray()) {
6505 Info.FFDiag(E, This.Designator.isOnePastTheEnd()
6506 ? diag::note_constexpr_access_past_end
6507 : diag::note_constexpr_access_unsized_array)
6508 << AK;
6509 return false;
6510 } else if (Polymorphic) {
6511 // Conservatively refuse to perform a polymorphic operation if we would
6512 // not be able to read a notional 'vptr' value.
6513 if (!Info.checkingPotentialConstantExpression() ||
6514 !This.AllowConstexprUnknown) {
6515 APValue Val;
6516 This.moveInto(Val);
6517 QualType StarThisType =
6518 Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
6519 Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
6520 << AK << Val.getAsString(Info.Ctx, StarThisType);
6521 }
6522 return false;
6523 }
6524 return true;
6525 }
6526
6527 CheckDynamicTypeHandler Handler{AK};
6528 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
6529 }
6530
6531 /// Check that the pointee of the 'this' pointer in a member function call is
6532 /// either within its lifetime or in its period of construction or destruction.
6533 static bool
6534 checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E,
6535 const LValue &This,
6536 const CXXMethodDecl *NamedMember) {
6537 return checkDynamicType(
6538 Info, E, This,
6539 isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false);
6540 }
6541
6542 struct DynamicType {
6543 /// The dynamic class type of the object.
6544 const CXXRecordDecl *Type;
6545 /// The corresponding path length in the lvalue.
6546 unsigned PathLength;
6547 };
6548
6549 static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
6550 unsigned PathLength) {
6551 assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
6552 Designator.Entries.size() && "invalid path length");
6553 return (PathLength == Designator.MostDerivedPathLength)
6554 ? Designator.MostDerivedType->getAsCXXRecordDecl()
6555 : getAsBaseClass(Designator.Entries[PathLength - 1]);
6556 }
6557
6558 /// Determine the dynamic type of an object.
6559 static std::optional<DynamicType> ComputeDynamicType(EvalInfo &Info,
6560 const Expr *E,
6561 LValue &This,
6562 AccessKinds AK) {
6563 // If we don't have an lvalue denoting an object of class type, there is no
6564 // meaningful dynamic type. (We consider objects of non-class type to have no
6565 // dynamic type.)
6566 if (!checkDynamicType(Info, E, This, AK,
6567 AK != AK_TypeId || This.AllowConstexprUnknown))
6568 return std::nullopt;
6569
6570 if (This.Designator.Invalid)
6571 return std::nullopt;
6572
6573 // Refuse to compute a dynamic type in the presence of virtual bases. This
6574 // shouldn't happen other than in constant-folding situations, since literal
6575 // types can't have virtual bases.
6576 //
6577 // Note that consumers of DynamicType assume that the type has no virtual
6578 // bases, and will need modifications if this restriction is relaxed.
6579 const CXXRecordDecl *Class =
6580 This.Designator.MostDerivedType->getAsCXXRecordDecl();
6581 if (!Class || Class->getNumVBases()) {
6582 Info.FFDiag(E);
6583 return std::nullopt;
6584 }
6585
6586 // FIXME: For very deep class hierarchies, it might be beneficial to use a
6587 // binary search here instead. But the overwhelmingly common case is that
6588 // we're not in the middle of a constructor, so it probably doesn't matter
6589 // in practice.
6590 ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
6591 for (unsigned PathLength = This.Designator.MostDerivedPathLength;
6592 PathLength <= Path.size(); ++PathLength) {
6593 switch (Info.isEvaluatingCtorDtor(This.getLValueBase(),
6594 Path.slice(0, PathLength))) {
6595 case ConstructionPhase::Bases:
6596 case ConstructionPhase::DestroyingBases:
6597 // We're constructing or destroying a base class. This is not the dynamic
6598 // type.
6599 break;
6600
6601 case ConstructionPhase::None:
6602 case ConstructionPhase::AfterBases:
6603 case ConstructionPhase::AfterFields:
6604 case ConstructionPhase::Destroying:
6605 // We've finished constructing the base classes and not yet started
6606 // destroying them again, so this is the dynamic type.
6607 return DynamicType{getBaseClassType(This.Designator, PathLength),
6608 PathLength};
6609 }
6610 }
6611
6612 // CWG issue 1517: we're constructing a base class of the object described by
6613 // 'This', so that object has not yet begun its period of construction and
6614 // any polymorphic operation on it results in undefined behavior.
6615 Info.FFDiag(E);
6616 return std::nullopt;
6617 }
6618
6619 /// Perform virtual dispatch.
6620 static const CXXMethodDecl *HandleVirtualDispatch(
6621 EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
6622 llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
6623 std::optional<DynamicType> DynType = ComputeDynamicType(
6624 Info, E, This,
6625 isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall);
6626 if (!DynType)
6627 return nullptr;
6628
6629 // Find the final overrider. It must be declared in one of the classes on the
6630 // path from the dynamic type to the static type.
6631 // FIXME: If we ever allow literal types to have virtual base classes, that
6632 // won't be true.
6633 const CXXMethodDecl *Callee = Found;
6634 unsigned PathLength = DynType->PathLength;
6635 for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
6636 const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
6637 const CXXMethodDecl *Overrider =
6638 Found->getCorrespondingMethodDeclaredInClass(Class, false);
6639 if (Overrider) {
6640 Callee = Overrider;
6641 break;
6642 }
6643 }
6644
6645 // C++2a [class.abstract]p6:
6646 // the effect of making a virtual call to a pure virtual function [...] is
6647 // undefined
6648 if (Callee->isPureVirtual()) {
6649 Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
6650 Info.Note(Callee->getLocation(), diag::note_declared_at);
6651 return nullptr;
6652 }
6653
6654 // If necessary, walk the rest of the path to determine the sequence of
6655 // covariant adjustment steps to apply.
6656 if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
6657 Found->getReturnType())) {
6658 CovariantAdjustmentPath.push_back(Callee->getReturnType());
6659 for (unsigned CovariantPathLength = PathLength + 1;
6660 CovariantPathLength != This.Designator.Entries.size();
6661 ++CovariantPathLength) {
6662 const CXXRecordDecl *NextClass =
6663 getBaseClassType(This.Designator, CovariantPathLength);
6664 const CXXMethodDecl *Next =
6665 Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
6666 if (Next && !Info.Ctx.hasSameUnqualifiedType(
6667 Next->getReturnType(), CovariantAdjustmentPath.back()))
6668 CovariantAdjustmentPath.push_back(Next->getReturnType());
6669 }
6670 if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
6671 CovariantAdjustmentPath.back()))
6672 CovariantAdjustmentPath.push_back(Found->getReturnType());
6673 }
6674
6675 // Perform 'this' adjustment.
6676 if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
6677 return nullptr;
6678
6679 return Callee;
6680 }
6681
6682 /// Perform the adjustment from a value returned by a virtual function to
6683 /// a value of the statically expected type, which may be a pointer or
6684 /// reference to a base class of the returned type.
6685 static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
6686 APValue &Result,
6687 ArrayRef<QualType> Path) {
6688 assert(Result.isLValue() &&
6689 "unexpected kind of APValue for covariant return");
6690 if (Result.isNullPointer())
6691 return true;
6692
6693 LValue LVal;
6694 LVal.setFrom(Info.Ctx, Result);
6695
6696 const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
6697 for (unsigned I = 1; I != Path.size(); ++I) {
6698 const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
6699 assert(OldClass && NewClass && "unexpected kind of covariant return");
6700 if (OldClass != NewClass &&
6701 !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
6702 return false;
6703 OldClass = NewClass;
6704 }
6705
6706 LVal.moveInto(Result);
6707 return true;
6708 }
6709
6710 /// Determine whether \p Base, which is known to be a direct base class of
6711 /// \p Derived, is a public base class.
6712 static bool isBaseClassPublic(const CXXRecordDecl *Derived,
6713 const CXXRecordDecl *Base) {
6714 for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
6715 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
6716 if (BaseClass && declaresSameEntity(BaseClass, Base))
6717 return BaseSpec.getAccessSpecifier() == AS_public;
6718 }
6719 llvm_unreachable("Base is not a direct base of Derived");
6720 }
6721
6722 /// Apply the given dynamic cast operation on the provided lvalue.
6723 ///
6724 /// This implements the hard case of dynamic_cast, requiring a "runtime check"
6725 /// to find a suitable target subobject.
6726 static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
6727 LValue &Ptr) {
6728 // We can't do anything with a non-symbolic pointer value.
6729 SubobjectDesignator &D = Ptr.Designator;
6730 if (D.Invalid)
6731 return false;
6732
6733 // C++ [expr.dynamic.cast]p6:
6734 // If v is a null pointer value, the result is a null pointer value.
6735 if (Ptr.isNullPointer() && !E->isGLValue())
6736 return true;
6737
6738 // For all the other cases, we need the pointer to point to an object within
6739 // its lifetime / period of construction / destruction, and we need to know
6740 // its dynamic type.
6741 std::optional<DynamicType> DynType =
6742 ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
6743 if (!DynType)
6744 return false;
6745
6746 // C++ [expr.dynamic.cast]p7:
6747 // If T is "pointer to cv void", then the result is a pointer to the most
6748 // derived object
6749 if (E->getType()->isVoidPointerType())
6750 return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
6751
6752 const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl();
6753 assert(C && "dynamic_cast target is not void pointer nor class");
6754 CanQualType CQT = Info.Ctx.getCanonicalTagType(C);
6755
6756 auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
6757 // C++ [expr.dynamic.cast]p9:
6758 if (!E->isGLValue()) {
6759 // The value of a failed cast to pointer type is the null pointer value
6760 // of the required result type.
6761 Ptr.setNull(Info.Ctx, E->getType());
6762 return true;
6763 }
6764
6765 // A failed cast to reference type throws [...] std::bad_cast.
6766 unsigned DiagKind;
6767 if (!Paths && (declaresSameEntity(DynType->Type, C) ||
6768 DynType->Type->isDerivedFrom(C)))
6769 DiagKind = 0;
6770 else if (!Paths || Paths->begin() == Paths->end())
6771 DiagKind = 1;
6772 else if (Paths->isAmbiguous(CQT))
6773 DiagKind = 2;
6774 else {
6775 assert(Paths->front().Access != AS_public && "why did the cast fail?");
6776 DiagKind = 3;
6777 }
6778 Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
6779 << DiagKind << Ptr.Designator.getType(Info.Ctx)
6780 << Info.Ctx.getCanonicalTagType(DynType->Type)
6781 << E->getType().getUnqualifiedType();
6782 return false;
6783 };
6784
6785 // Runtime check, phase 1:
6786 // Walk from the base subobject towards the derived object looking for the
6787 // target type.
6788 for (int PathLength = Ptr.Designator.Entries.size();
6789 PathLength >= (int)DynType->PathLength; --PathLength) {
6790 const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
6791 if (declaresSameEntity(Class, C))
6792 return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
6793 // We can only walk across public inheritance edges.
6794 if (PathLength > (int)DynType->PathLength &&
6795 !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
6796 Class))
6797 return RuntimeCheckFailed(nullptr);
6798 }
6799
6800 // Runtime check, phase 2:
6801 // Search the dynamic type for an unambiguous public base of type C.
6802 CXXBasePaths Paths(/*FindAmbiguities=*/true,
6803 /*RecordPaths=*/true, /*DetectVirtual=*/false);
6804 if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
6805 Paths.front().Access == AS_public) {
6806 // Downcast to the dynamic type...
6807 if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
6808 return false;
6809 // ... then upcast to the chosen base class subobject.
6810 for (CXXBasePathElement &Elem : Paths.front())
6811 if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
6812 return false;
6813 return true;
6814 }
6815
6816 // Otherwise, the runtime check fails.
6817 return RuntimeCheckFailed(&Paths);
6818 }
6819
6820 namespace {
6821 struct StartLifetimeOfUnionMemberHandler {
6822 EvalInfo &Info;
6823 const Expr *LHSExpr;
6824 const FieldDecl *Field;
6825 bool DuringInit;
6826 bool Failed = false;
6827 static const AccessKinds AccessKind = AK_Assign;
6828
6829 typedef bool result_type;
6830 bool failed() { return Failed; }
6831 bool found(APValue &Subobj, QualType SubobjType) {
6832 // We are supposed to perform no initialization but begin the lifetime of
6833 // the object. We interpret that as meaning to do what default
6834 // initialization of the object would do if all constructors involved were
6835 // trivial:
6836 // * All base, non-variant member, and array element subobjects' lifetimes
6837 // begin
6838 // * No variant members' lifetimes begin
6839 // * All scalar subobjects whose lifetimes begin have indeterminate values
6840 assert(SubobjType->isUnionType());
6841 if (declaresSameEntity(Subobj.getUnionField(), Field)) {
6842 // This union member is already active. If it's also in-lifetime, there's
6843 // nothing to do.
6844 if (Subobj.getUnionValue().hasValue())
6845 return true;
6846 } else if (DuringInit) {
6847 // We're currently in the process of initializing a different union
6848 // member. If we carried on, that initialization would attempt to
6849 // store to an inactive union member, resulting in undefined behavior.
6850 Info.FFDiag(LHSExpr,
6851 diag::note_constexpr_union_member_change_during_init);
6852 return false;
6853 }
6854 APValue Result;
6855 Failed = !handleDefaultInitValue(Field->getType(), Result);
6856 Subobj.setUnion(Field, Result);
6857 return true;
6858 }
6859 bool found(APSInt &Value, QualType SubobjType) {
6860 llvm_unreachable("wrong value kind for union object");
6861 }
6862 bool found(APFloat &Value, QualType SubobjType) {
6863 llvm_unreachable("wrong value kind for union object");
6864 }
6865 };
6866 } // end anonymous namespace
6867
6868 const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
6869
6870 /// Handle a builtin simple-assignment or a call to a trivial assignment
6871 /// operator whose left-hand side might involve a union member access. If it
6872 /// does, implicitly start the lifetime of any accessed union elements per
6873 /// C++20 [class.union]5.
6874 static bool MaybeHandleUnionActiveMemberChange(EvalInfo &Info,
6875 const Expr *LHSExpr,
6876 const LValue &LHS) {
6877 if (LHS.InvalidBase || LHS.Designator.Invalid)
6878 return false;
6879
6880 llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths;
6881 // C++ [class.union]p5:
6882 // define the set S(E) of subexpressions of E as follows:
6883 unsigned PathLength = LHS.Designator.Entries.size();
6884 for (const Expr *E = LHSExpr; E != nullptr;) {
6885 // -- If E is of the form A.B, S(E) contains the elements of S(A)...
6886 if (auto *ME = dyn_cast<MemberExpr>(E)) {
6887 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
6888 // Note that we can't implicitly start the lifetime of a reference,
6889 // so we don't need to proceed any further if we reach one.
6890 if (!FD || FD->getType()->isReferenceType())
6891 break;
6892
6893 // ... and also contains A.B if B names a union member ...
6894 if (FD->getParent()->isUnion()) {
6895 // ... of a non-class, non-array type, or of a class type with a
6896 // trivial default constructor that is not deleted, or an array of
6897 // such types.
6898 auto *RD =
6899 FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6900 if (!RD || RD->hasTrivialDefaultConstructor())
6901 UnionPathLengths.push_back({PathLength - 1, FD});
6902 }
6903
6904 E = ME->getBase();
6905 --PathLength;
6906 assert(declaresSameEntity(FD,
6907 LHS.Designator.Entries[PathLength]
6908 .getAsBaseOrMember().getPointer()));
6909
6910 // -- If E is of the form A[B] and is interpreted as a built-in array
6911 // subscripting operator, S(E) is [S(the array operand, if any)].
6912 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
6913 // Step over an ArrayToPointerDecay implicit cast.
6914 auto *Base = ASE->getBase()->IgnoreImplicit();
6915 if (!Base->getType()->isArrayType())
6916 break;
6917
6918 E = Base;
6919 --PathLength;
6920
6921 } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6922 // Step over a derived-to-base conversion.
6923 E = ICE->getSubExpr();
6924 if (ICE->getCastKind() == CK_NoOp)
6925 continue;
6926 if (ICE->getCastKind() != CK_DerivedToBase &&
6927 ICE->getCastKind() != CK_UncheckedDerivedToBase)
6928 break;
6929 // Walk path backwards as we walk up from the base to the derived class.
6930 for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
6931 if (Elt->isVirtual()) {
6932 // A class with virtual base classes never has a trivial default
6933 // constructor, so S(E) is empty in this case.
6934 E = nullptr;
6935 break;
6936 }
6937
6938 --PathLength;
6939 assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
6940 LHS.Designator.Entries[PathLength]
6941 .getAsBaseOrMember().getPointer()));
6942 }
6943
6944 // -- Otherwise, S(E) is empty.
6945 } else {
6946 break;
6947 }
6948 }
6949
6950 // Common case: no unions' lifetimes are started.
6951 if (UnionPathLengths.empty())
6952 return true;
6953
6954 // if modification of X [would access an inactive union member], an object
6955 // of the type of X is implicitly created
6956 CompleteObject Obj =
6957 findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
6958 if (!Obj)
6959 return false;
6960 for (std::pair<unsigned, const FieldDecl *> LengthAndField :
6961 llvm::reverse(UnionPathLengths)) {
6962 // Form a designator for the union object.
6963 SubobjectDesignator D = LHS.Designator;
6964 D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
6965
6966 bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) ==
6967 ConstructionPhase::AfterBases;
6968 StartLifetimeOfUnionMemberHandler StartLifetime{
6969 Info, LHSExpr, LengthAndField.second, DuringInit};
6970 if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
6971 return false;
6972 }
6973
6974 return true;
6975 }
6976
6977 static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg,
6978 CallRef Call, EvalInfo &Info, bool NonNull = false,
6979 APValue **EvaluatedArg = nullptr) {
6980 LValue LV;
6981 // Create the parameter slot and register its destruction. For a vararg
6982 // argument, create a temporary.
6983 // FIXME: For calling conventions that destroy parameters in the callee,
6984 // should we consider performing destruction when the function returns
6985 // instead?
6986 APValue &V = PVD ? Info.CurrentCall->createParam(Call, PVD, LV)
6987 : Info.CurrentCall->createTemporary(Arg, Arg->getType(),
6988 ScopeKind::Call, LV);
6989 if (!EvaluateInPlace(V, Info, LV, Arg))
6990 return false;
6991
6992 // Passing a null pointer to an __attribute__((nonnull)) parameter results in
6993 // undefined behavior, so is non-constant.
6994 if (NonNull && V.isLValue() && V.isNullPointer()) {
6995 Info.CCEDiag(Arg, diag::note_non_null_attribute_failed);
6996 return false;
6997 }
6998
6999 if (EvaluatedArg)
7000 *EvaluatedArg = &V;
7001
7002 return true;
7003 }
7004
7005 /// Evaluate the arguments to a function call.
7006 static bool EvaluateArgs(ArrayRef<const Expr *> Args, CallRef Call,
7007 EvalInfo &Info, const FunctionDecl *Callee,
7008 bool RightToLeft = false,
7009 LValue *ObjectArg = nullptr) {
7010 bool Success = true;
7011 llvm::SmallBitVector ForbiddenNullArgs;
7012 if (Callee->hasAttr<NonNullAttr>()) {
7013 ForbiddenNullArgs.resize(Args.size());
7014 for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
7015 if (!Attr->args_size()) {
7016 ForbiddenNullArgs.set();
7017 break;
7018 } else
7019 for (auto Idx : Attr->args()) {
7020 unsigned ASTIdx = Idx.getASTIndex();
7021 if (ASTIdx >= Args.size())
7022 continue;
7023 ForbiddenNullArgs[ASTIdx] = true;
7024 }
7025 }
7026 }
7027 for (unsigned I = 0; I < Args.size(); I++) {
7028 unsigned Idx = RightToLeft ? Args.size() - I - 1 : I;
7029 const ParmVarDecl *PVD =
7030 Idx < Callee->getNumParams() ? Callee->getParamDecl(Idx) : nullptr;
7031 bool NonNull = !ForbiddenNullArgs.empty() && ForbiddenNullArgs[Idx];
7032 APValue *That = nullptr;
7033 if (!EvaluateCallArg(PVD, Args[Idx], Call, Info, NonNull, &That)) {
7034 // If we're checking for a potential constant expression, evaluate all
7035 // initializers even if some of them fail.
7036 if (!Info.noteFailure())
7037 return false;
7038 Success = false;
7039 }
7040 if (PVD && PVD->isExplicitObjectParameter() && That && That->isLValue())
7041 ObjectArg->setFrom(Info.Ctx, *That);
7042 }
7043 return Success;
7044 }
7045
7046 /// Perform a trivial copy from Param, which is the parameter of a copy or move
7047 /// constructor or assignment operator.
7048 static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param,
7049 const Expr *E, APValue &Result,
7050 bool CopyObjectRepresentation) {
7051 // Find the reference argument.
7052 CallStackFrame *Frame = Info.CurrentCall;
7053 APValue *RefValue = Info.getParamSlot(Frame->Arguments, Param);
7054 if (!RefValue) {
7055 Info.FFDiag(E);
7056 return false;
7057 }
7058
7059 // Copy out the contents of the RHS object.
7060 LValue RefLValue;
7061 RefLValue.setFrom(Info.Ctx, *RefValue);
7062 return handleLValueToRValueConversion(
7063 Info, E, Param->getType().getNonReferenceType(), RefLValue, Result,
7064 CopyObjectRepresentation);
7065 }
7066
7067 /// Evaluate a function call.
7068 static bool HandleFunctionCall(SourceLocation CallLoc,
7069 const FunctionDecl *Callee,
7070 const LValue *ObjectArg, const Expr *E,
7071 ArrayRef<const Expr *> Args, CallRef Call,
7072 const Stmt *Body, EvalInfo &Info,
7073 APValue &Result, const LValue *ResultSlot) {
7074 if (!Info.CheckCallLimit(CallLoc))
7075 return false;
7076
7077 CallStackFrame Frame(Info, E->getSourceRange(), Callee, ObjectArg, E, Call);
7078
7079 // For a trivial copy or move assignment, perform an APValue copy. This is
7080 // essential for unions, where the operations performed by the assignment
7081 // operator cannot be represented as statements.
7082 //
7083 // Skip this for non-union classes with no fields; in that case, the defaulted
7084 // copy/move does not actually read the object.
7085 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
7086 if (MD && MD->isDefaulted() &&
7087 (MD->getParent()->isUnion() ||
7088 (MD->isTrivial() &&
7089 isReadByLvalueToRvalueConversion(MD->getParent())))) {
7090 unsigned ExplicitOffset = MD->isExplicitObjectMemberFunction() ? 1 : 0;
7091 assert(ObjectArg &&
7092 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
7093 APValue RHSValue;
7094 if (!handleTrivialCopy(Info, MD->getParamDecl(0), Args[0], RHSValue,
7095 MD->getParent()->isUnion()))
7096 return false;
7097
7098 LValue Obj;
7099 if (!handleAssignment(Info, Args[ExplicitOffset], *ObjectArg,
7100 MD->getFunctionObjectParameterReferenceType(),
7101 RHSValue))
7102 return false;
7103 ObjectArg->moveInto(Result);
7104 return true;
7105 } else if (MD && isLambdaCallOperator(MD)) {
7106 // We're in a lambda; determine the lambda capture field maps unless we're
7107 // just constexpr checking a lambda's call operator. constexpr checking is
7108 // done before the captures have been added to the closure object (unless
7109 // we're inferring constexpr-ness), so we don't have access to them in this
7110 // case. But since we don't need the captures to constexpr check, we can
7111 // just ignore them.
7112 if (!Info.checkingPotentialConstantExpression())
7113 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
7114 Frame.LambdaThisCaptureField);
7115 }
7116
7117 StmtResult Ret = {Result, ResultSlot};
7118 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
7119 if (ESR == ESR_Succeeded) {
7120 if (Callee->getReturnType()->isVoidType())
7121 return true;
7122 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
7123 }
7124 return ESR == ESR_Returned;
7125 }
7126
7127 /// Evaluate a constructor call.
7128 static bool HandleConstructorCall(const Expr *E, const LValue &This,
7129 CallRef Call,
7130 const CXXConstructorDecl *Definition,
7131 EvalInfo &Info, APValue &Result) {
7132 SourceLocation CallLoc = E->getExprLoc();
7133 if (!Info.CheckCallLimit(CallLoc))
7134 return false;
7135
7136 const CXXRecordDecl *RD = Definition->getParent();
7137 if (RD->getNumVBases()) {
7138 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
7139 return false;
7140 }
7141
7142 EvalInfo::EvaluatingConstructorRAII EvalObj(
7143 Info,
7144 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
7145 RD->getNumBases());
7146 CallStackFrame Frame(Info, E->getSourceRange(), Definition, &This, E, Call);
7147
7148 // FIXME: Creating an APValue just to hold a nonexistent return value is
7149 // wasteful.
7150 APValue RetVal;
7151 StmtResult Ret = {RetVal, nullptr};
7152
7153 // If it's a delegating constructor, delegate.
7154 if (Definition->isDelegatingConstructor()) {
7155 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
7156 if ((*I)->getInit()->isValueDependent()) {
7157 if (!EvaluateDependentExpr((*I)->getInit(), Info))
7158 return false;
7159 } else {
7160 FullExpressionRAII InitScope(Info);
7161 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) ||
7162 !InitScope.destroy())
7163 return false;
7164 }
7165 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
7166 }
7167
7168 // For a trivial copy or move constructor, perform an APValue copy. This is
7169 // essential for unions (or classes with anonymous union members), where the
7170 // operations performed by the constructor cannot be represented by
7171 // ctor-initializers.
7172 //
7173 // Skip this for empty non-union classes; we should not perform an
7174 // lvalue-to-rvalue conversion on them because their copy constructor does not
7175 // actually read them.
7176 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
7177 (Definition->getParent()->isUnion() ||
7178 (Definition->isTrivial() &&
7179 isReadByLvalueToRvalueConversion(Definition->getParent())))) {
7180 return handleTrivialCopy(Info, Definition->getParamDecl(0), E, Result,
7181 Definition->getParent()->isUnion());
7182 }
7183
7184 // Reserve space for the struct members.
7185 if (!Result.hasValue()) {
7186 if (!RD->isUnion())
7187 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
7188 RD->getNumFields());
7189 else
7190 // A union starts with no active member.
7191 Result = APValue((const FieldDecl*)nullptr);
7192 }
7193
7194 if (RD->isInvalidDecl()) return false;
7195 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7196
7197 // A scope for temporaries lifetime-extended by reference members.
7198 BlockScopeRAII LifetimeExtendedScope(Info);
7199
7200 bool Success = true;
7201 unsigned BasesSeen = 0;
7202 #ifndef NDEBUG
7203 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
7204 #endif
7205 CXXRecordDecl::field_iterator FieldIt = RD->field_begin();
7206 auto SkipToField = [&](FieldDecl *FD, bool Indirect) {
7207 // We might be initializing the same field again if this is an indirect
7208 // field initialization.
7209 if (FieldIt == RD->field_end() ||
7210 FieldIt->getFieldIndex() > FD->getFieldIndex()) {
7211 assert(Indirect && "fields out of order?");
7212 return;
7213 }
7214
7215 // Default-initialize any fields with no explicit initializer.
7216 for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
7217 assert(FieldIt != RD->field_end() && "missing field?");
7218 if (!FieldIt->isUnnamedBitField())
7219 Success &= handleDefaultInitValue(
7220 FieldIt->getType(),
7221 Result.getStructField(FieldIt->getFieldIndex()));
7222 }
7223 ++FieldIt;
7224 };
7225 for (const auto *I : Definition->inits()) {
7226 LValue Subobject = This;
7227 LValue SubobjectParent = This;
7228 APValue *Value = &Result;
7229
7230 // Determine the subobject to initialize.
7231 FieldDecl *FD = nullptr;
7232 if (I->isBaseInitializer()) {
7233 QualType BaseType(I->getBaseClass(), 0);
7234 #ifndef NDEBUG
7235 // Non-virtual base classes are initialized in the order in the class
7236 // definition. We have already checked for virtual base classes.
7237 assert(!BaseIt->isVirtual() && "virtual base for literal type");
7238 assert(Info.Ctx.hasSameUnqualifiedType(BaseIt->getType(), BaseType) &&
7239 "base class initializers not in expected order");
7240 ++BaseIt;
7241 #endif
7242 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
7243 BaseType->getAsCXXRecordDecl(), &Layout))
7244 return false;
7245 Value = &Result.getStructBase(BasesSeen++);
7246 } else if ((FD = I->getMember())) {
7247 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
7248 return false;
7249 if (RD->isUnion()) {
7250 Result = APValue(FD);
7251 Value = &Result.getUnionValue();
7252 } else {
7253 SkipToField(FD, false);
7254 Value = &Result.getStructField(FD->getFieldIndex());
7255 }
7256 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
7257 // Walk the indirect field decl's chain to find the object to initialize,
7258 // and make sure we've initialized every step along it.
7259 auto IndirectFieldChain = IFD->chain();
7260 for (auto *C : IndirectFieldChain) {
7261 FD = cast<FieldDecl>(C);
7262 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
7263 // Switch the union field if it differs. This happens if we had
7264 // preceding zero-initialization, and we're now initializing a union
7265 // subobject other than the first.
7266 // FIXME: In this case, the values of the other subobjects are
7267 // specified, since zero-initialization sets all padding bits to zero.
7268 if (!Value->hasValue() ||
7269 (Value->isUnion() &&
7270 !declaresSameEntity(Value->getUnionField(), FD))) {
7271 if (CD->isUnion())
7272 *Value = APValue(FD);
7273 else
7274 // FIXME: This immediately starts the lifetime of all members of
7275 // an anonymous struct. It would be preferable to strictly start
7276 // member lifetime in initialization order.
7277 Success &= handleDefaultInitValue(Info.Ctx.getCanonicalTagType(CD),
7278 *Value);
7279 }
7280 // Store Subobject as its parent before updating it for the last element
7281 // in the chain.
7282 if (C == IndirectFieldChain.back())
7283 SubobjectParent = Subobject;
7284 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
7285 return false;
7286 if (CD->isUnion())
7287 Value = &Value->getUnionValue();
7288 else {
7289 if (C == IndirectFieldChain.front() && !RD->isUnion())
7290 SkipToField(FD, true);
7291 Value = &Value->getStructField(FD->getFieldIndex());
7292 }
7293 }
7294 } else {
7295 llvm_unreachable("unknown base initializer kind");
7296 }
7297
7298 // Need to override This for implicit field initializers as in this case
7299 // This refers to innermost anonymous struct/union containing initializer,
7300 // not to currently constructed class.
7301 const Expr *Init = I->getInit();
7302 if (Init->isValueDependent()) {
7303 if (!EvaluateDependentExpr(Init, Info))
7304 return false;
7305 } else {
7306 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
7307 isa<CXXDefaultInitExpr>(Init));
7308 FullExpressionRAII InitScope(Info);
7309 if (FD && FD->getType()->isReferenceType() &&
7310 !FD->getType()->isFunctionReferenceType()) {
7311 LValue Result;
7312 if (!EvaluateInitForDeclOfReferenceType(Info, FD, Init, Result,
7313 *Value)) {
7314 if (!Info.noteFailure())
7315 return false;
7316 Success = false;
7317 }
7318 } else if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
7319 (FD && FD->isBitField() &&
7320 !truncateBitfieldValue(Info, Init, *Value, FD))) {
7321 // If we're checking for a potential constant expression, evaluate all
7322 // initializers even if some of them fail.
7323 if (!Info.noteFailure())
7324 return false;
7325 Success = false;
7326 }
7327 }
7328
7329 // This is the point at which the dynamic type of the object becomes this
7330 // class type.
7331 if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
7332 EvalObj.finishedConstructingBases();
7333 }
7334
7335 // Default-initialize any remaining fields.
7336 if (!RD->isUnion()) {
7337 for (; FieldIt != RD->field_end(); ++FieldIt) {
7338 if (!FieldIt->isUnnamedBitField())
7339 Success &= handleDefaultInitValue(
7340 FieldIt->getType(),
7341 Result.getStructField(FieldIt->getFieldIndex()));
7342 }
7343 }
7344
7345 EvalObj.finishedConstructingFields();
7346
7347 return Success &&
7348 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed &&
7349 LifetimeExtendedScope.destroy();
7350 }
7351
7352 static bool HandleConstructorCall(const Expr *E, const LValue &This,
7353 ArrayRef<const Expr*> Args,
7354 const CXXConstructorDecl *Definition,
7355 EvalInfo &Info, APValue &Result) {
7356 CallScopeRAII CallScope(Info);
7357 CallRef Call = Info.CurrentCall->createCall(Definition);
7358 if (!EvaluateArgs(Args, Call, Info, Definition))
7359 return false;
7360
7361 return HandleConstructorCall(E, This, Call, Definition, Info, Result) &&
7362 CallScope.destroy();
7363 }
7364
7365 static bool HandleDestructionImpl(EvalInfo &Info, SourceRange CallRange,
7366 const LValue &This, APValue &Value,
7367 QualType T) {
7368 // Objects can only be destroyed while they're within their lifetimes.
7369 // FIXME: We have no representation for whether an object of type nullptr_t
7370 // is in its lifetime; it usually doesn't matter. Perhaps we should model it
7371 // as indeterminate instead?
7372 if (Value.isAbsent() && !T->isNullPtrType()) {
7373 APValue Printable;
7374 This.moveInto(Printable);
7375 Info.FFDiag(CallRange.getBegin(),
7376 diag::note_constexpr_destroy_out_of_lifetime)
7377 << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T));
7378 return false;
7379 }
7380
7381 // Invent an expression for location purposes.
7382 // FIXME: We shouldn't need to do this.
7383 OpaqueValueExpr LocE(CallRange.getBegin(), Info.Ctx.IntTy, VK_PRValue);
7384
7385 // For arrays, destroy elements right-to-left.
7386 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) {
7387 uint64_t Size = CAT->getZExtSize();
7388 QualType ElemT = CAT->getElementType();
7389
7390 if (!CheckArraySize(Info, CAT, CallRange.getBegin()))
7391 return false;
7392
7393 LValue ElemLV = This;
7394 ElemLV.addArray(Info, &LocE, CAT);
7395 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size))
7396 return false;
7397
7398 // Ensure that we have actual array elements available to destroy; the
7399 // destructors might mutate the value, so we can't run them on the array
7400 // filler.
7401 if (Size && Size > Value.getArrayInitializedElts())
7402 expandArray(Value, Value.getArraySize() - 1);
7403
7404 // The size of the array might have been reduced by
7405 // a placement new.
7406 for (Size = Value.getArraySize(); Size != 0; --Size) {
7407 APValue &Elem = Value.getArrayInitializedElt(Size - 1);
7408 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) ||
7409 !HandleDestructionImpl(Info, CallRange, ElemLV, Elem, ElemT))
7410 return false;
7411 }
7412
7413 // End the lifetime of this array now.
7414 Value = APValue();
7415 return true;
7416 }
7417
7418 const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
7419 if (!RD) {
7420 if (T.isDestructedType()) {
7421 Info.FFDiag(CallRange.getBegin(),
7422 diag::note_constexpr_unsupported_destruction)
7423 << T;
7424 return false;
7425 }
7426
7427 Value = APValue();
7428 return true;
7429 }
7430
7431 if (RD->getNumVBases()) {
7432 Info.FFDiag(CallRange.getBegin(), diag::note_constexpr_virtual_base) << RD;
7433 return false;
7434 }
7435
7436 const CXXDestructorDecl *DD = RD->getDestructor();
7437 if (!DD && !RD->hasTrivialDestructor()) {
7438 Info.FFDiag(CallRange.getBegin());
7439 return false;
7440 }
7441
7442 if (!DD || DD->isTrivial() ||
7443 (RD->isAnonymousStructOrUnion() && RD->isUnion())) {
7444 // A trivial destructor just ends the lifetime of the object. Check for
7445 // this case before checking for a body, because we might not bother
7446 // building a body for a trivial destructor. Note that it doesn't matter
7447 // whether the destructor is constexpr in this case; all trivial
7448 // destructors are constexpr.
7449 //
7450 // If an anonymous union would be destroyed, some enclosing destructor must
7451 // have been explicitly defined, and the anonymous union destruction should
7452 // have no effect.
7453 Value = APValue();
7454 return true;
7455 }
7456
7457 if (!Info.CheckCallLimit(CallRange.getBegin()))
7458 return false;
7459
7460 const FunctionDecl *Definition = nullptr;
7461 const Stmt *Body = DD->getBody(Definition);
7462
7463 if (!CheckConstexprFunction(Info, CallRange.getBegin(), DD, Definition, Body))
7464 return false;
7465
7466 CallStackFrame Frame(Info, CallRange, Definition, &This, /*CallExpr=*/nullptr,
7467 CallRef());
7468
7469 // We're now in the period of destruction of this object.
7470 unsigned BasesLeft = RD->getNumBases();
7471 EvalInfo::EvaluatingDestructorRAII EvalObj(
7472 Info,
7473 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries});
7474 if (!EvalObj.DidInsert) {
7475 // C++2a [class.dtor]p19:
7476 // the behavior is undefined if the destructor is invoked for an object
7477 // whose lifetime has ended
7478 // (Note that formally the lifetime ends when the period of destruction
7479 // begins, even though certain uses of the object remain valid until the
7480 // period of destruction ends.)
7481 Info.FFDiag(CallRange.getBegin(), diag::note_constexpr_double_destroy);
7482 return false;
7483 }
7484
7485 // FIXME: Creating an APValue just to hold a nonexistent return value is
7486 // wasteful.
7487 APValue RetVal;
7488 StmtResult Ret = {RetVal, nullptr};
7489 if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed)
7490 return false;
7491
7492 // A union destructor does not implicitly destroy its members.
7493 if (RD->isUnion())
7494 return true;
7495
7496 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7497
7498 // We don't have a good way to iterate fields in reverse, so collect all the
7499 // fields first and then walk them backwards.
7500 SmallVector<FieldDecl*, 16> Fields(RD->fields());
7501 for (const FieldDecl *FD : llvm::reverse(Fields)) {
7502 if (FD->isUnnamedBitField())
7503 continue;
7504
7505 LValue Subobject = This;
7506 if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout))
7507 return false;
7508
7509 APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex());
7510 if (!HandleDestructionImpl(Info, CallRange, Subobject, *SubobjectValue,
7511 FD->getType()))
7512 return false;
7513 }
7514
7515 if (BasesLeft != 0)
7516 EvalObj.startedDestroyingBases();
7517
7518 // Destroy base classes in reverse order.
7519 for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) {
7520 --BasesLeft;
7521
7522 QualType BaseType = Base.getType();
7523 LValue Subobject = This;
7524 if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD,
7525 BaseType->getAsCXXRecordDecl(), &Layout))
7526 return false;
7527
7528 APValue *SubobjectValue = &Value.getStructBase(BasesLeft);
7529 if (!HandleDestructionImpl(Info, CallRange, Subobject, *SubobjectValue,
7530 BaseType))
7531 return false;
7532 }
7533 assert(BasesLeft == 0 && "NumBases was wrong?");
7534
7535 // The period of destruction ends now. The object is gone.
7536 Value = APValue();
7537 return true;
7538 }
7539
7540 namespace {
7541 struct DestroyObjectHandler {
7542 EvalInfo &Info;
7543 const Expr *E;
7544 const LValue &This;
7545 const AccessKinds AccessKind;
7546
7547 typedef bool result_type;
7548 bool failed() { return false; }
7549 bool found(APValue &Subobj, QualType SubobjType) {
7550 return HandleDestructionImpl(Info, E->getSourceRange(), This, Subobj,
7551 SubobjType);
7552 }
7553 bool found(APSInt &Value, QualType SubobjType) {
7554 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
7555 return false;
7556 }
7557 bool found(APFloat &Value, QualType SubobjType) {
7558 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
7559 return false;
7560 }
7561 };
7562 }
7563
7564 /// Perform a destructor or pseudo-destructor call on the given object, which
7565 /// might in general not be a complete object.
7566 static bool HandleDestruction(EvalInfo &Info, const Expr *E,
7567 const LValue &This, QualType ThisType) {
7568 CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType);
7569 DestroyObjectHandler Handler = {Info, E, This, AK_Destroy};
7570 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
7571 }
7572
7573 /// Destroy and end the lifetime of the given complete object.
7574 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
7575 APValue::LValueBase LVBase, APValue &Value,
7576 QualType T) {
7577 // If we've had an unmodeled side-effect, we can't rely on mutable state
7578 // (such as the object we're about to destroy) being correct.
7579 if (Info.EvalStatus.HasSideEffects)
7580 return false;
7581
7582 LValue LV;
7583 LV.set({LVBase});
7584 return HandleDestructionImpl(Info, Loc, LV, Value, T);
7585 }
7586
7587 /// Perform a call to 'operator new' or to `__builtin_operator_new'.
7588 static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E,
7589 LValue &Result) {
7590 if (Info.checkingPotentialConstantExpression() ||
7591 Info.SpeculativeEvaluationDepth)
7592 return false;
7593
7594 // This is permitted only within a call to std::allocator<T>::allocate.
7595 auto Caller = Info.getStdAllocatorCaller("allocate");
7596 if (!Caller) {
7597 Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20
7598 ? diag::note_constexpr_new_untyped
7599 : diag::note_constexpr_new);
7600 return false;
7601 }
7602
7603 QualType ElemType = Caller.ElemType;
7604 if (ElemType->isIncompleteType() || ElemType->isFunctionType()) {
7605 Info.FFDiag(E->getExprLoc(),
7606 diag::note_constexpr_new_not_complete_object_type)
7607 << (ElemType->isIncompleteType() ? 0 : 1) << ElemType;
7608 return false;
7609 }
7610
7611 APSInt ByteSize;
7612 if (!EvaluateInteger(E->getArg(0), ByteSize, Info))
7613 return false;
7614 bool IsNothrow = false;
7615 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) {
7616 EvaluateIgnoredValue(Info, E->getArg(I));
7617 IsNothrow |= E->getType()->isNothrowT();
7618 }
7619
7620 CharUnits ElemSize;
7621 if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize))
7622 return false;
7623 APInt Size, Remainder;
7624 APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity());
7625 APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder);
7626 if (Remainder != 0) {
7627 // This likely indicates a bug in the implementation of 'std::allocator'.
7628 Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size)
7629 << ByteSize << APSInt(ElemSizeAP, true) << ElemType;
7630 return false;
7631 }
7632
7633 if (!Info.CheckArraySize(E->getBeginLoc(), ByteSize.getActiveBits(),
7634 Size.getZExtValue(), /*Diag=*/!IsNothrow)) {
7635 if (IsNothrow) {
7636 Result.setNull(Info.Ctx, E->getType());
7637 return true;
7638 }
7639 return false;
7640 }
7641
7642 QualType AllocType = Info.Ctx.getConstantArrayType(
7643 ElemType, Size, nullptr, ArraySizeModifier::Normal, 0);
7644 APValue *Val = Info.createHeapAlloc(Caller.Call, AllocType, Result);
7645 *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue());
7646 Result.addArray(Info, E, cast<ConstantArrayType>(AllocType));
7647 return true;
7648 }
7649
7650 static bool hasVirtualDestructor(QualType T) {
7651 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
7652 if (CXXDestructorDecl *DD = RD->getDestructor())
7653 return DD->isVirtual();
7654 return false;
7655 }
7656
7657 static const FunctionDecl *getVirtualOperatorDelete(QualType T) {
7658 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
7659 if (CXXDestructorDecl *DD = RD->getDestructor())
7660 return DD->isVirtual() ? DD->getOperatorDelete() : nullptr;
7661 return nullptr;
7662 }
7663
7664 /// Check that the given object is a suitable pointer to a heap allocation that
7665 /// still exists and is of the right kind for the purpose of a deletion.
7666 ///
7667 /// On success, returns the heap allocation to deallocate. On failure, produces
7668 /// a diagnostic and returns std::nullopt.
7669 static std::optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E,
7670 const LValue &Pointer,
7671 DynAlloc::Kind DeallocKind) {
7672 auto PointerAsString = [&] {
7673 return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy);
7674 };
7675
7676 DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>();
7677 if (!DA) {
7678 Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc)
7679 << PointerAsString();
7680 if (Pointer.Base)
7681 NoteLValueLocation(Info, Pointer.Base);
7682 return std::nullopt;
7683 }
7684
7685 std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
7686 if (!Alloc) {
7687 Info.FFDiag(E, diag::note_constexpr_double_delete);
7688 return std::nullopt;
7689 }
7690
7691 if (DeallocKind != (*Alloc)->getKind()) {
7692 QualType AllocType = Pointer.Base.getDynamicAllocType();
7693 Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch)
7694 << DeallocKind << (*Alloc)->getKind() << AllocType;
7695 NoteLValueLocation(Info, Pointer.Base);
7696 return std::nullopt;
7697 }
7698
7699 bool Subobject = false;
7700 if (DeallocKind == DynAlloc::New) {
7701 Subobject = Pointer.Designator.MostDerivedPathLength != 0 ||
7702 Pointer.Designator.isOnePastTheEnd();
7703 } else {
7704 Subobject = Pointer.Designator.Entries.size() != 1 ||
7705 Pointer.Designator.Entries[0].getAsArrayIndex() != 0;
7706 }
7707 if (Subobject) {
7708 Info.FFDiag(E, diag::note_constexpr_delete_subobject)
7709 << PointerAsString() << Pointer.Designator.isOnePastTheEnd();
7710 return std::nullopt;
7711 }
7712
7713 return Alloc;
7714 }
7715
7716 // Perform a call to 'operator delete' or '__builtin_operator_delete'.
7717 static bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) {
7718 if (Info.checkingPotentialConstantExpression() ||
7719 Info.SpeculativeEvaluationDepth)
7720 return false;
7721
7722 // This is permitted only within a call to std::allocator<T>::deallocate.
7723 if (!Info.getStdAllocatorCaller("deallocate")) {
7724 Info.FFDiag(E->getExprLoc());
7725 return true;
7726 }
7727
7728 LValue Pointer;
7729 if (!EvaluatePointer(E->getArg(0), Pointer, Info))
7730 return false;
7731 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
7732 EvaluateIgnoredValue(Info, E->getArg(I));
7733
7734 if (Pointer.Designator.Invalid)
7735 return false;
7736
7737 // Deleting a null pointer would have no effect, but it's not permitted by
7738 // std::allocator<T>::deallocate's contract.
7739 if (Pointer.isNullPointer()) {
7740 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_deallocate_null);
7741 return true;
7742 }
7743
7744 if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator))
7745 return false;
7746
7747 Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>());
7748 return true;
7749 }
7750
7751 //===----------------------------------------------------------------------===//
7752 // Generic Evaluation
7753 //===----------------------------------------------------------------------===//
7754 namespace {
7755
7756 class BitCastBuffer {
7757 // FIXME: We're going to need bit-level granularity when we support
7758 // bit-fields.
7759 // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
7760 // we don't support a host or target where that is the case. Still, we should
7761 // use a more generic type in case we ever do.
7762 SmallVector<std::optional<unsigned char>, 32> Bytes;
7763
7764 static_assert(std::numeric_limits<unsigned char>::digits >= 8,
7765 "Need at least 8 bit unsigned char");
7766
7767 bool TargetIsLittleEndian;
7768
7769 public:
7770 BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
7771 : Bytes(Width.getQuantity()),
7772 TargetIsLittleEndian(TargetIsLittleEndian) {}
7773
7774 [[nodiscard]] bool readObject(CharUnits Offset, CharUnits Width,
7775 SmallVectorImpl<unsigned char> &Output) const {
7776 for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
7777 // If a byte of an integer is uninitialized, then the whole integer is
7778 // uninitialized.
7779 if (!Bytes[I.getQuantity()])
7780 return false;
7781 Output.push_back(*Bytes[I.getQuantity()]);
7782 }
7783 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
7784 std::reverse(Output.begin(), Output.end());
7785 return true;
7786 }
7787
7788 void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
7789 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
7790 std::reverse(Input.begin(), Input.end());
7791
7792 size_t Index = 0;
7793 for (unsigned char Byte : Input) {
7794 assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
7795 Bytes[Offset.getQuantity() + Index] = Byte;
7796 ++Index;
7797 }
7798 }
7799
7800 size_t size() { return Bytes.size(); }
7801 };
7802
7803 /// Traverse an APValue to produce an BitCastBuffer, emulating how the current
7804 /// target would represent the value at runtime.
7805 class APValueToBufferConverter {
7806 EvalInfo &Info;
7807 BitCastBuffer Buffer;
7808 const CastExpr *BCE;
7809
7810 APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
7811 const CastExpr *BCE)
7812 : Info(Info),
7813 Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
7814 BCE(BCE) {}
7815
7816 bool visit(const APValue &Val, QualType Ty) {
7817 return visit(Val, Ty, CharUnits::fromQuantity(0));
7818 }
7819
7820 // Write out Val with type Ty into Buffer starting at Offset.
7821 bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
7822 assert((size_t)Offset.getQuantity() <= Buffer.size());
7823
7824 // As a special case, nullptr_t has an indeterminate value.
7825 if (Ty->isNullPtrType())
7826 return true;
7827
7828 // Dig through Src to find the byte at SrcOffset.
7829 switch (Val.getKind()) {
7830 case APValue::Indeterminate:
7831 case APValue::None:
7832 return true;
7833
7834 case APValue::Int:
7835 return visitInt(Val.getInt(), Ty, Offset);
7836 case APValue::Float:
7837 return visitFloat(Val.getFloat(), Ty, Offset);
7838 case APValue::Array:
7839 return visitArray(Val, Ty, Offset);
7840 case APValue::Struct:
7841 return visitRecord(Val, Ty, Offset);
7842 case APValue::Vector:
7843 return visitVector(Val, Ty, Offset);
7844
7845 case APValue::ComplexInt:
7846 case APValue::ComplexFloat:
7847 return visitComplex(Val, Ty, Offset);
7848 case APValue::FixedPoint:
7849 // FIXME: We should support these.
7850
7851 case APValue::Union:
7852 case APValue::MemberPointer:
7853 case APValue::AddrLabelDiff: {
7854 Info.FFDiag(BCE->getBeginLoc(),
7855 diag::note_constexpr_bit_cast_unsupported_type)
7856 << Ty;
7857 return false;
7858 }
7859
7860 case APValue::LValue:
7861 llvm_unreachable("LValue subobject in bit_cast?");
7862 }
7863 llvm_unreachable("Unhandled APValue::ValueKind");
7864 }
7865
7866 bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
7867 const RecordDecl *RD = Ty->getAsRecordDecl();
7868 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7869
7870 // Visit the base classes.
7871 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
7872 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
7873 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
7874 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
7875 const APValue &Base = Val.getStructBase(I);
7876
7877 // Can happen in error cases.
7878 if (!Base.isStruct())
7879 return false;
7880
7881 if (!visitRecord(Base, BS.getType(),
7882 Layout.getBaseClassOffset(BaseDecl) + Offset))
7883 return false;
7884 }
7885 }
7886
7887 // Visit the fields.
7888 unsigned FieldIdx = 0;
7889 for (FieldDecl *FD : RD->fields()) {
7890 if (FD->isBitField()) {
7891 Info.FFDiag(BCE->getBeginLoc(),
7892 diag::note_constexpr_bit_cast_unsupported_bitfield);
7893 return false;
7894 }
7895
7896 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
7897
7898 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
7899 "only bit-fields can have sub-char alignment");
7900 CharUnits FieldOffset =
7901 Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
7902 QualType FieldTy = FD->getType();
7903 if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
7904 return false;
7905 ++FieldIdx;
7906 }
7907
7908 return true;
7909 }
7910
7911 bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
7912 const auto *CAT =
7913 dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
7914 if (!CAT)
7915 return false;
7916
7917 CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
7918 unsigned NumInitializedElts = Val.getArrayInitializedElts();
7919 unsigned ArraySize = Val.getArraySize();
7920 // First, initialize the initialized elements.
7921 for (unsigned I = 0; I != NumInitializedElts; ++I) {
7922 const APValue &SubObj = Val.getArrayInitializedElt(I);
7923 if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
7924 return false;
7925 }
7926
7927 // Next, initialize the rest of the array using the filler.
7928 if (Val.hasArrayFiller()) {
7929 const APValue &Filler = Val.getArrayFiller();
7930 for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
7931 if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
7932 return false;
7933 }
7934 }
7935
7936 return true;
7937 }
7938
7939 bool visitComplex(const APValue &Val, QualType Ty, CharUnits Offset) {
7940 const ComplexType *ComplexTy = Ty->castAs<ComplexType>();
7941 QualType EltTy = ComplexTy->getElementType();
7942 CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
7943 bool IsInt = Val.isComplexInt();
7944
7945 if (IsInt) {
7946 if (!visitInt(Val.getComplexIntReal(), EltTy,
7947 Offset + (0 * EltSizeChars)))
7948 return false;
7949 if (!visitInt(Val.getComplexIntImag(), EltTy,
7950 Offset + (1 * EltSizeChars)))
7951 return false;
7952 } else {
7953 if (!visitFloat(Val.getComplexFloatReal(), EltTy,
7954 Offset + (0 * EltSizeChars)))
7955 return false;
7956 if (!visitFloat(Val.getComplexFloatImag(), EltTy,
7957 Offset + (1 * EltSizeChars)))
7958 return false;
7959 }
7960
7961 return true;
7962 }
7963
7964 bool visitVector(const APValue &Val, QualType Ty, CharUnits Offset) {
7965 const VectorType *VTy = Ty->castAs<VectorType>();
7966 QualType EltTy = VTy->getElementType();
7967 unsigned NElts = VTy->getNumElements();
7968
7969 if (VTy->isPackedVectorBoolType(Info.Ctx)) {
7970 // Special handling for OpenCL bool vectors:
7971 // Since these vectors are stored as packed bits, but we can't write
7972 // individual bits to the BitCastBuffer, we'll buffer all of the elements
7973 // together into an appropriately sized APInt and write them all out at
7974 // once. Because we don't accept vectors where NElts * EltSize isn't a
7975 // multiple of the char size, there will be no padding space, so we don't
7976 // have to worry about writing data which should have been left
7977 // uninitialized.
7978 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
7979
7980 llvm::APInt Res = llvm::APInt::getZero(NElts);
7981 for (unsigned I = 0; I < NElts; ++I) {
7982 const llvm::APSInt &EltAsInt = Val.getVectorElt(I).getInt();
7983 assert(EltAsInt.isUnsigned() && EltAsInt.getBitWidth() == 1 &&
7984 "bool vector element must be 1-bit unsigned integer!");
7985
7986 Res.insertBits(EltAsInt, BigEndian ? (NElts - I - 1) : I);
7987 }
7988
7989 SmallVector<uint8_t, 8> Bytes(NElts / 8);
7990 llvm::StoreIntToMemory(Res, &*Bytes.begin(), NElts / 8);
7991 Buffer.writeObject(Offset, Bytes);
7992 } else {
7993 // Iterate over each of the elements and write them out to the buffer at
7994 // the appropriate offset.
7995 CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
7996 for (unsigned I = 0; I < NElts; ++I) {
7997 if (!visit(Val.getVectorElt(I), EltTy, Offset + I * EltSizeChars))
7998 return false;
7999 }
8000 }
8001
8002 return true;
8003 }
8004
8005 bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
8006 APSInt AdjustedVal = Val;
8007 unsigned Width = AdjustedVal.getBitWidth();
8008 if (Ty->isBooleanType()) {
8009 Width = Info.Ctx.getTypeSize(Ty);
8010 AdjustedVal = AdjustedVal.extend(Width);
8011 }
8012
8013 SmallVector<uint8_t, 8> Bytes(Width / 8);
8014 llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8);
8015 Buffer.writeObject(Offset, Bytes);
8016 return true;
8017 }
8018
8019 bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
8020 APSInt AsInt(Val.bitcastToAPInt());
8021 return visitInt(AsInt, Ty, Offset);
8022 }
8023
8024 public:
8025 static std::optional<BitCastBuffer>
8026 convert(EvalInfo &Info, const APValue &Src, const CastExpr *BCE) {
8027 CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
8028 APValueToBufferConverter Converter(Info, DstSize, BCE);
8029 if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
8030 return std::nullopt;
8031 return Converter.Buffer;
8032 }
8033 };
8034
8035 /// Write an BitCastBuffer into an APValue.
8036 class BufferToAPValueConverter {
8037 EvalInfo &Info;
8038 const BitCastBuffer &Buffer;
8039 const CastExpr *BCE;
8040
8041 BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
8042 const CastExpr *BCE)
8043 : Info(Info), Buffer(Buffer), BCE(BCE) {}
8044
8045 // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
8046 // with an invalid type, so anything left is a deficiency on our part (FIXME).
8047 // Ideally this will be unreachable.
8048 std::nullopt_t unsupportedType(QualType Ty) {
8049 Info.FFDiag(BCE->getBeginLoc(),
8050 diag::note_constexpr_bit_cast_unsupported_type)
8051 << Ty;
8052 return std::nullopt;
8053 }
8054
8055 std::nullopt_t unrepresentableValue(QualType Ty, const APSInt &Val) {
8056 Info.FFDiag(BCE->getBeginLoc(),
8057 diag::note_constexpr_bit_cast_unrepresentable_value)
8058 << Ty << toString(Val, /*Radix=*/10);
8059 return std::nullopt;
8060 }
8061
8062 std::optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
8063 const EnumType *EnumSugar = nullptr) {
8064 if (T->isNullPtrType()) {
8065 uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
8066 return APValue((Expr *)nullptr,
8067 /*Offset=*/CharUnits::fromQuantity(NullValue),
8068 APValue::NoLValuePath{}, /*IsNullPtr=*/true);
8069 }
8070
8071 CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
8072
8073 // Work around floating point types that contain unused padding bytes. This
8074 // is really just `long double` on x86, which is the only fundamental type
8075 // with padding bytes.
8076 if (T->isRealFloatingType()) {
8077 const llvm::fltSemantics &Semantics =
8078 Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
8079 unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics);
8080 assert(NumBits % 8 == 0);
8081 CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8);
8082 if (NumBytes != SizeOf)
8083 SizeOf = NumBytes;
8084 }
8085
8086 SmallVector<uint8_t, 8> Bytes;
8087 if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
8088 // If this is std::byte or unsigned char, then its okay to store an
8089 // indeterminate value.
8090 bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
8091 bool IsUChar =
8092 !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
8093 T->isSpecificBuiltinType(BuiltinType::Char_U));
8094 if (!IsStdByte && !IsUChar) {
8095 QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
8096 Info.FFDiag(BCE->getExprLoc(),
8097 diag::note_constexpr_bit_cast_indet_dest)
8098 << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
8099 return std::nullopt;
8100 }
8101
8102 return APValue::IndeterminateValue();
8103 }
8104
8105 APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
8106 llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
8107
8108 if (T->isIntegralOrEnumerationType()) {
8109 Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
8110
8111 unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0));
8112 if (IntWidth != Val.getBitWidth()) {
8113 APSInt Truncated = Val.trunc(IntWidth);
8114 if (Truncated.extend(Val.getBitWidth()) != Val)
8115 return unrepresentableValue(QualType(T, 0), Val);
8116 Val = Truncated;
8117 }
8118
8119 return APValue(Val);
8120 }
8121
8122 if (T->isRealFloatingType()) {
8123 const llvm::fltSemantics &Semantics =
8124 Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
8125 return APValue(APFloat(Semantics, Val));
8126 }
8127
8128 return unsupportedType(QualType(T, 0));
8129 }
8130
8131 std::optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
8132 const RecordDecl *RD = RTy->getAsRecordDecl();
8133 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
8134
8135 unsigned NumBases = 0;
8136 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
8137 NumBases = CXXRD->getNumBases();
8138
8139 APValue ResultVal(APValue::UninitStruct(), NumBases, RD->getNumFields());
8140
8141 // Visit the base classes.
8142 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
8143 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
8144 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
8145 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
8146
8147 std::optional<APValue> SubObj = visitType(
8148 BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
8149 if (!SubObj)
8150 return std::nullopt;
8151 ResultVal.getStructBase(I) = *SubObj;
8152 }
8153 }
8154
8155 // Visit the fields.
8156 unsigned FieldIdx = 0;
8157 for (FieldDecl *FD : RD->fields()) {
8158 // FIXME: We don't currently support bit-fields. A lot of the logic for
8159 // this is in CodeGen, so we need to factor it around.
8160 if (FD->isBitField()) {
8161 Info.FFDiag(BCE->getBeginLoc(),
8162 diag::note_constexpr_bit_cast_unsupported_bitfield);
8163 return std::nullopt;
8164 }
8165
8166 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
8167 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
8168
8169 CharUnits FieldOffset =
8170 CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
8171 Offset;
8172 QualType FieldTy = FD->getType();
8173 std::optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
8174 if (!SubObj)
8175 return std::nullopt;
8176 ResultVal.getStructField(FieldIdx) = *SubObj;
8177 ++FieldIdx;
8178 }
8179
8180 return ResultVal;
8181 }
8182
8183 std::optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
8184 QualType RepresentationType =
8185 Ty->getDecl()->getDefinitionOrSelf()->getIntegerType();
8186 assert(!RepresentationType.isNull() &&
8187 "enum forward decl should be caught by Sema");
8188 const auto *AsBuiltin =
8189 RepresentationType.getCanonicalType()->castAs<BuiltinType>();
8190 // Recurse into the underlying type. Treat std::byte transparently as
8191 // unsigned char.
8192 return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
8193 }
8194
8195 std::optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
8196 size_t Size = Ty->getLimitedSize();
8197 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
8198
8199 APValue ArrayValue(APValue::UninitArray(), Size, Size);
8200 for (size_t I = 0; I != Size; ++I) {
8201 std::optional<APValue> ElementValue =
8202 visitType(Ty->getElementType(), Offset + I * ElementWidth);
8203 if (!ElementValue)
8204 return std::nullopt;
8205 ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
8206 }
8207
8208 return ArrayValue;
8209 }
8210
8211 std::optional<APValue> visit(const ComplexType *Ty, CharUnits Offset) {
8212 QualType ElementType = Ty->getElementType();
8213 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(ElementType);
8214 bool IsInt = ElementType->isIntegerType();
8215
8216 std::optional<APValue> Values[2];
8217 for (unsigned I = 0; I != 2; ++I) {
8218 Values[I] = visitType(Ty->getElementType(), Offset + I * ElementWidth);
8219 if (!Values[I])
8220 return std::nullopt;
8221 }
8222
8223 if (IsInt)
8224 return APValue(Values[0]->getInt(), Values[1]->getInt());
8225 return APValue(Values[0]->getFloat(), Values[1]->getFloat());
8226 }
8227
8228 std::optional<APValue> visit(const VectorType *VTy, CharUnits Offset) {
8229 QualType EltTy = VTy->getElementType();
8230 unsigned NElts = VTy->getNumElements();
8231 unsigned EltSize =
8232 VTy->isPackedVectorBoolType(Info.Ctx) ? 1 : Info.Ctx.getTypeSize(EltTy);
8233
8234 SmallVector<APValue, 4> Elts;
8235 Elts.reserve(NElts);
8236 if (VTy->isPackedVectorBoolType(Info.Ctx)) {
8237 // Special handling for OpenCL bool vectors:
8238 // Since these vectors are stored as packed bits, but we can't read
8239 // individual bits from the BitCastBuffer, we'll buffer all of the
8240 // elements together into an appropriately sized APInt and write them all
8241 // out at once. Because we don't accept vectors where NElts * EltSize
8242 // isn't a multiple of the char size, there will be no padding space, so
8243 // we don't have to worry about reading any padding data which didn't
8244 // actually need to be accessed.
8245 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
8246
8247 SmallVector<uint8_t, 8> Bytes;
8248 Bytes.reserve(NElts / 8);
8249 if (!Buffer.readObject(Offset, CharUnits::fromQuantity(NElts / 8), Bytes))
8250 return std::nullopt;
8251
8252 APSInt SValInt(NElts, true);
8253 llvm::LoadIntFromMemory(SValInt, &*Bytes.begin(), Bytes.size());
8254
8255 for (unsigned I = 0; I < NElts; ++I) {
8256 llvm::APInt Elt =
8257 SValInt.extractBits(1, (BigEndian ? NElts - I - 1 : I) * EltSize);
8258 Elts.emplace_back(
8259 APSInt(std::move(Elt), !EltTy->isSignedIntegerType()));
8260 }
8261 } else {
8262 // Iterate over each of the elements and read them from the buffer at
8263 // the appropriate offset.
8264 CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
8265 for (unsigned I = 0; I < NElts; ++I) {
8266 std::optional<APValue> EltValue =
8267 visitType(EltTy, Offset + I * EltSizeChars);
8268 if (!EltValue)
8269 return std::nullopt;
8270 Elts.push_back(std::move(*EltValue));
8271 }
8272 }
8273
8274 return APValue(Elts.data(), Elts.size());
8275 }
8276
8277 std::optional<APValue> visit(const Type *Ty, CharUnits Offset) {
8278 return unsupportedType(QualType(Ty, 0));
8279 }
8280
8281 std::optional<APValue> visitType(QualType Ty, CharUnits Offset) {
8282 QualType Can = Ty.getCanonicalType();
8283
8284 switch (Can->getTypeClass()) {
8285 #define TYPE(Class, Base) \
8286 case Type::Class: \
8287 return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
8288 #define ABSTRACT_TYPE(Class, Base)
8289 #define NON_CANONICAL_TYPE(Class, Base) \
8290 case Type::Class: \
8291 llvm_unreachable("non-canonical type should be impossible!");
8292 #define DEPENDENT_TYPE(Class, Base) \
8293 case Type::Class: \
8294 llvm_unreachable( \
8295 "dependent types aren't supported in the constant evaluator!");
8296 #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base) \
8297 case Type::Class: \
8298 llvm_unreachable("either dependent or not canonical!");
8299 #include "clang/AST/TypeNodes.inc"
8300 }
8301 llvm_unreachable("Unhandled Type::TypeClass");
8302 }
8303
8304 public:
8305 // Pull out a full value of type DstType.
8306 static std::optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
8307 const CastExpr *BCE) {
8308 BufferToAPValueConverter Converter(Info, Buffer, BCE);
8309 return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
8310 }
8311 };
8312
8313 static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
8314 QualType Ty, EvalInfo *Info,
8315 const ASTContext &Ctx,
8316 bool CheckingDest) {
8317 Ty = Ty.getCanonicalType();
8318
8319 auto diag = [&](int Reason) {
8320 if (Info)
8321 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
8322 << CheckingDest << (Reason == 4) << Reason;
8323 return false;
8324 };
8325 auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
8326 if (Info)
8327 Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
8328 << NoteTy << Construct << Ty;
8329 return false;
8330 };
8331
8332 if (Ty->isUnionType())
8333 return diag(0);
8334 if (Ty->isPointerType())
8335 return diag(1);
8336 if (Ty->isMemberPointerType())
8337 return diag(2);
8338 if (Ty.isVolatileQualified())
8339 return diag(3);
8340
8341 if (RecordDecl *Record = Ty->getAsRecordDecl()) {
8342 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
8343 for (CXXBaseSpecifier &BS : CXXRD->bases())
8344 if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
8345 CheckingDest))
8346 return note(1, BS.getType(), BS.getBeginLoc());
8347 }
8348 for (FieldDecl *FD : Record->fields()) {
8349 if (FD->getType()->isReferenceType())
8350 return diag(4);
8351 if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
8352 CheckingDest))
8353 return note(0, FD->getType(), FD->getBeginLoc());
8354 }
8355 }
8356
8357 if (Ty->isArrayType() &&
8358 !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
8359 Info, Ctx, CheckingDest))
8360 return false;
8361
8362 if (const auto *VTy = Ty->getAs<VectorType>()) {
8363 QualType EltTy = VTy->getElementType();
8364 unsigned NElts = VTy->getNumElements();
8365 unsigned EltSize =
8366 VTy->isPackedVectorBoolType(Ctx) ? 1 : Ctx.getTypeSize(EltTy);
8367
8368 if ((NElts * EltSize) % Ctx.getCharWidth() != 0) {
8369 // The vector's size in bits is not a multiple of the target's byte size,
8370 // so its layout is unspecified. For now, we'll simply treat these cases
8371 // as unsupported (this should only be possible with OpenCL bool vectors
8372 // whose element count isn't a multiple of the byte size).
8373 if (Info)
8374 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_vector)
8375 << QualType(VTy, 0) << EltSize << NElts << Ctx.getCharWidth();
8376 return false;
8377 }
8378
8379 if (EltTy->isRealFloatingType() &&
8380 &Ctx.getFloatTypeSemantics(EltTy) == &APFloat::x87DoubleExtended()) {
8381 // The layout for x86_fp80 vectors seems to be handled very inconsistently
8382 // by both clang and LLVM, so for now we won't allow bit_casts involving
8383 // it in a constexpr context.
8384 if (Info)
8385 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_unsupported_type)
8386 << EltTy;
8387 return false;
8388 }
8389 }
8390
8391 return true;
8392 }
8393
8394 static bool checkBitCastConstexprEligibility(EvalInfo *Info,
8395 const ASTContext &Ctx,
8396 const CastExpr *BCE) {
8397 bool DestOK = checkBitCastConstexprEligibilityType(
8398 BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
8399 bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
8400 BCE->getBeginLoc(),
8401 BCE->getSubExpr()->getType(), Info, Ctx, false);
8402 return SourceOK;
8403 }
8404
8405 static bool handleRValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
8406 const APValue &SourceRValue,
8407 const CastExpr *BCE) {
8408 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
8409 "no host or target supports non 8-bit chars");
8410
8411 if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
8412 return false;
8413
8414 // Read out SourceValue into a char buffer.
8415 std::optional<BitCastBuffer> Buffer =
8416 APValueToBufferConverter::convert(Info, SourceRValue, BCE);
8417 if (!Buffer)
8418 return false;
8419
8420 // Write out the buffer into a new APValue.
8421 std::optional<APValue> MaybeDestValue =
8422 BufferToAPValueConverter::convert(Info, *Buffer, BCE);
8423 if (!MaybeDestValue)
8424 return false;
8425
8426 DestValue = std::move(*MaybeDestValue);
8427 return true;
8428 }
8429
8430 static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
8431 APValue &SourceValue,
8432 const CastExpr *BCE) {
8433 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
8434 "no host or target supports non 8-bit chars");
8435 assert(SourceValue.isLValue() &&
8436 "LValueToRValueBitcast requires an lvalue operand!");
8437
8438 LValue SourceLValue;
8439 APValue SourceRValue;
8440 SourceLValue.setFrom(Info.Ctx, SourceValue);
8441 if (!handleLValueToRValueConversion(
8442 Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,
8443 SourceRValue, /*WantObjectRepresentation=*/true))
8444 return false;
8445
8446 return handleRValueToRValueBitCast(Info, DestValue, SourceRValue, BCE);
8447 }
8448
8449 template <class Derived>
8450 class ExprEvaluatorBase
8451 : public ConstStmtVisitor<Derived, bool> {
8452 private:
8453 Derived &getDerived() { return static_cast<Derived&>(*this); }
8454 bool DerivedSuccess(const APValue &V, const Expr *E) {
8455 return getDerived().Success(V, E);
8456 }
8457 bool DerivedZeroInitialization(const Expr *E) {
8458 return getDerived().ZeroInitialization(E);
8459 }
8460
8461 // Check whether a conditional operator with a non-constant condition is a
8462 // potential constant expression. If neither arm is a potential constant
8463 // expression, then the conditional operator is not either.
8464 template<typename ConditionalOperator>
8465 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
8466 assert(Info.checkingPotentialConstantExpression());
8467
8468 // Speculatively evaluate both arms.
8469 SmallVector<PartialDiagnosticAt, 8> Diag;
8470 {
8471 SpeculativeEvaluationRAII Speculate(Info, &Diag);
8472 StmtVisitorTy::Visit(E->getFalseExpr());
8473 if (Diag.empty())
8474 return;
8475 }
8476
8477 {
8478 SpeculativeEvaluationRAII Speculate(Info, &Diag);
8479 Diag.clear();
8480 StmtVisitorTy::Visit(E->getTrueExpr());
8481 if (Diag.empty())
8482 return;
8483 }
8484
8485 Error(E, diag::note_constexpr_conditional_never_const);
8486 }
8487
8488
8489 template<typename ConditionalOperator>
8490 bool HandleConditionalOperator(const ConditionalOperator *E) {
8491 bool BoolResult;
8492 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
8493 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
8494 CheckPotentialConstantConditional(E);
8495 return false;
8496 }
8497 if (Info.noteFailure()) {
8498 StmtVisitorTy::Visit(E->getTrueExpr());
8499 StmtVisitorTy::Visit(E->getFalseExpr());
8500 }
8501 return false;
8502 }
8503
8504 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
8505 return StmtVisitorTy::Visit(EvalExpr);
8506 }
8507
8508 protected:
8509 EvalInfo &Info;
8510 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
8511 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
8512
8513 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
8514 return Info.CCEDiag(E, D);
8515 }
8516
8517 bool ZeroInitialization(const Expr *E) { return Error(E); }
8518
8519 bool IsConstantEvaluatedBuiltinCall(const CallExpr *E) {
8520 unsigned BuiltinOp = E->getBuiltinCallee();
8521 return BuiltinOp != 0 &&
8522 Info.Ctx.BuiltinInfo.isConstantEvaluated(BuiltinOp);
8523 }
8524
8525 public:
8526 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
8527
8528 EvalInfo &getEvalInfo() { return Info; }
8529
8530 /// Report an evaluation error. This should only be called when an error is
8531 /// first discovered. When propagating an error, just return false.
8532 bool Error(const Expr *E, diag::kind D) {
8533 Info.FFDiag(E, D) << E->getSourceRange();
8534 return false;
8535 }
8536 bool Error(const Expr *E) {
8537 return Error(E, diag::note_invalid_subexpr_in_const_expr);
8538 }
8539
8540 bool VisitStmt(const Stmt *) {
8541 llvm_unreachable("Expression evaluator should not be called on stmts");
8542 }
8543 bool VisitExpr(const Expr *E) {
8544 return Error(E);
8545 }
8546
8547 bool VisitEmbedExpr(const EmbedExpr *E) {
8548 const auto It = E->begin();
8549 return StmtVisitorTy::Visit(*It);
8550 }
8551
8552 bool VisitPredefinedExpr(const PredefinedExpr *E) {
8553 return StmtVisitorTy::Visit(E->getFunctionName());
8554 }
8555 bool VisitConstantExpr(const ConstantExpr *E) {
8556 if (E->hasAPValueResult())
8557 return DerivedSuccess(E->getAPValueResult(), E);
8558
8559 return StmtVisitorTy::Visit(E->getSubExpr());
8560 }
8561
8562 bool VisitParenExpr(const ParenExpr *E)
8563 { return StmtVisitorTy::Visit(E->getSubExpr()); }
8564 bool VisitUnaryExtension(const UnaryOperator *E)
8565 { return StmtVisitorTy::Visit(E->getSubExpr()); }
8566 bool VisitUnaryPlus(const UnaryOperator *E)
8567 { return StmtVisitorTy::Visit(E->getSubExpr()); }
8568 bool VisitChooseExpr(const ChooseExpr *E)
8569 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
8570 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
8571 { return StmtVisitorTy::Visit(E->getResultExpr()); }
8572 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
8573 { return StmtVisitorTy::Visit(E->getReplacement()); }
8574 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
8575 TempVersionRAII RAII(*Info.CurrentCall);
8576 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
8577 return StmtVisitorTy::Visit(E->getExpr());
8578 }
8579 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
8580 TempVersionRAII RAII(*Info.CurrentCall);
8581 // The initializer may not have been parsed yet, or might be erroneous.
8582 if (!E->getExpr())
8583 return Error(E);
8584 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
8585 return StmtVisitorTy::Visit(E->getExpr());
8586 }
8587
8588 bool VisitExprWithCleanups(const ExprWithCleanups *E) {
8589 FullExpressionRAII Scope(Info);
8590 return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy();
8591 }
8592
8593 // Temporaries are registered when created, so we don't care about
8594 // CXXBindTemporaryExpr.
8595 bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
8596 return StmtVisitorTy::Visit(E->getSubExpr());
8597 }
8598
8599 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
8600 CCEDiag(E, diag::note_constexpr_invalid_cast)
8601 << diag::ConstexprInvalidCastKind::Reinterpret;
8602 return static_cast<Derived*>(this)->VisitCastExpr(E);
8603 }
8604 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
8605 if (!Info.Ctx.getLangOpts().CPlusPlus20)
8606 CCEDiag(E, diag::note_constexpr_invalid_cast)
8607 << diag::ConstexprInvalidCastKind::Dynamic;
8608 return static_cast<Derived*>(this)->VisitCastExpr(E);
8609 }
8610 bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
8611 return static_cast<Derived*>(this)->VisitCastExpr(E);
8612 }
8613
8614 bool VisitBinaryOperator(const BinaryOperator *E) {
8615 switch (E->getOpcode()) {
8616 default:
8617 return Error(E);
8618
8619 case BO_Comma:
8620 VisitIgnoredValue(E->getLHS());
8621 return StmtVisitorTy::Visit(E->getRHS());
8622
8623 case BO_PtrMemD:
8624 case BO_PtrMemI: {
8625 LValue Obj;
8626 if (!HandleMemberPointerAccess(Info, E, Obj))
8627 return false;
8628 APValue Result;
8629 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
8630 return false;
8631 return DerivedSuccess(Result, E);
8632 }
8633 }
8634 }
8635
8636 bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) {
8637 return StmtVisitorTy::Visit(E->getSemanticForm());
8638 }
8639
8640 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
8641 // Evaluate and cache the common expression. We treat it as a temporary,
8642 // even though it's not quite the same thing.
8643 LValue CommonLV;
8644 if (!Evaluate(Info.CurrentCall->createTemporary(
8645 E->getOpaqueValue(),
8646 getStorageType(Info.Ctx, E->getOpaqueValue()),
8647 ScopeKind::FullExpression, CommonLV),
8648 Info, E->getCommon()))
8649 return false;
8650
8651 return HandleConditionalOperator(E);
8652 }
8653
8654 bool VisitConditionalOperator(const ConditionalOperator *E) {
8655 bool IsBcpCall = false;
8656 // If the condition (ignoring parens) is a __builtin_constant_p call,
8657 // the result is a constant expression if it can be folded without
8658 // side-effects. This is an important GNU extension. See GCC PR38377
8659 // for discussion.
8660 if (const CallExpr *CallCE =
8661 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
8662 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
8663 IsBcpCall = true;
8664
8665 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
8666 // constant expression; we can't check whether it's potentially foldable.
8667 // FIXME: We should instead treat __builtin_constant_p as non-constant if
8668 // it would return 'false' in this mode.
8669 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
8670 return false;
8671
8672 FoldConstant Fold(Info, IsBcpCall);
8673 if (!HandleConditionalOperator(E)) {
8674 Fold.keepDiagnostics();
8675 return false;
8676 }
8677
8678 return true;
8679 }
8680
8681 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
8682 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E);
8683 Value && !Value->isAbsent())
8684 return DerivedSuccess(*Value, E);
8685
8686 const Expr *Source = E->getSourceExpr();
8687 if (!Source)
8688 return Error(E);
8689 if (Source == E) {
8690 assert(0 && "OpaqueValueExpr recursively refers to itself");
8691 return Error(E);
8692 }
8693 return StmtVisitorTy::Visit(Source);
8694 }
8695
8696 bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
8697 for (const Expr *SemE : E->semantics()) {
8698 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
8699 // FIXME: We can't handle the case where an OpaqueValueExpr is also the
8700 // result expression: there could be two different LValues that would
8701 // refer to the same object in that case, and we can't model that.
8702 if (SemE == E->getResultExpr())
8703 return Error(E);
8704
8705 // Unique OVEs get evaluated if and when we encounter them when
8706 // emitting the rest of the semantic form, rather than eagerly.
8707 if (OVE->isUnique())
8708 continue;
8709
8710 LValue LV;
8711 if (!Evaluate(Info.CurrentCall->createTemporary(
8712 OVE, getStorageType(Info.Ctx, OVE),
8713 ScopeKind::FullExpression, LV),
8714 Info, OVE->getSourceExpr()))
8715 return false;
8716 } else if (SemE == E->getResultExpr()) {
8717 if (!StmtVisitorTy::Visit(SemE))
8718 return false;
8719 } else {
8720 if (!EvaluateIgnoredValue(Info, SemE))
8721 return false;
8722 }
8723 }
8724 return true;
8725 }
8726
8727 bool VisitCallExpr(const CallExpr *E) {
8728 APValue Result;
8729 if (!handleCallExpr(E, Result, nullptr))
8730 return false;
8731 return DerivedSuccess(Result, E);
8732 }
8733
8734 bool handleCallExpr(const CallExpr *E, APValue &Result,
8735 const LValue *ResultSlot) {
8736 CallScopeRAII CallScope(Info);
8737
8738 const Expr *Callee = E->getCallee()->IgnoreParens();
8739 QualType CalleeType = Callee->getType();
8740
8741 const FunctionDecl *FD = nullptr;
8742 LValue *This = nullptr, ObjectArg;
8743 auto Args = ArrayRef(E->getArgs(), E->getNumArgs());
8744 bool HasQualifier = false;
8745
8746 CallRef Call;
8747
8748 // Extract function decl and 'this' pointer from the callee.
8749 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
8750 const CXXMethodDecl *Member = nullptr;
8751 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
8752 // Explicit bound member calls, such as x.f() or p->g();
8753 if (!EvaluateObjectArgument(Info, ME->getBase(), ObjectArg))
8754 return false;
8755 Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
8756 if (!Member)
8757 return Error(Callee);
8758 This = &ObjectArg;
8759 HasQualifier = ME->hasQualifier();
8760 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
8761 // Indirect bound member calls ('.*' or '->*').
8762 const ValueDecl *D =
8763 HandleMemberPointerAccess(Info, BE, ObjectArg, false);
8764 if (!D)
8765 return false;
8766 Member = dyn_cast<CXXMethodDecl>(D);
8767 if (!Member)
8768 return Error(Callee);
8769 This = &ObjectArg;
8770 } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
8771 if (!Info.getLangOpts().CPlusPlus20)
8772 Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
8773 return EvaluateObjectArgument(Info, PDE->getBase(), ObjectArg) &&
8774 HandleDestruction(Info, PDE, ObjectArg, PDE->getDestroyedType());
8775 } else
8776 return Error(Callee);
8777 FD = Member;
8778 } else if (CalleeType->isFunctionPointerType()) {
8779 LValue CalleeLV;
8780 if (!EvaluatePointer(Callee, CalleeLV, Info))
8781 return false;
8782
8783 if (!CalleeLV.getLValueOffset().isZero())
8784 return Error(Callee);
8785 if (CalleeLV.isNullPointer()) {
8786 Info.FFDiag(Callee, diag::note_constexpr_null_callee)
8787 << const_cast<Expr *>(Callee);
8788 return false;
8789 }
8790 FD = dyn_cast_or_null<FunctionDecl>(
8791 CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>());
8792 if (!FD)
8793 return Error(Callee);
8794 // Don't call function pointers which have been cast to some other type.
8795 // Per DR (no number yet), the caller and callee can differ in noexcept.
8796 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
8797 CalleeType->getPointeeType(), FD->getType())) {
8798 return Error(E);
8799 }
8800
8801 // For an (overloaded) assignment expression, evaluate the RHS before the
8802 // LHS.
8803 auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
8804 if (OCE && OCE->isAssignmentOp()) {
8805 assert(Args.size() == 2 && "wrong number of arguments in assignment");
8806 Call = Info.CurrentCall->createCall(FD);
8807 bool HasThis = false;
8808 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
8809 HasThis = MD->isImplicitObjectMemberFunction();
8810 if (!EvaluateArgs(HasThis ? Args.slice(1) : Args, Call, Info, FD,
8811 /*RightToLeft=*/true, &ObjectArg))
8812 return false;
8813 }
8814
8815 // Overloaded operator calls to member functions are represented as normal
8816 // calls with '*this' as the first argument.
8817 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8818 if (MD &&
8819 (MD->isImplicitObjectMemberFunction() || (OCE && MD->isStatic()))) {
8820 // FIXME: When selecting an implicit conversion for an overloaded
8821 // operator delete, we sometimes try to evaluate calls to conversion
8822 // operators without a 'this' parameter!
8823 if (Args.empty())
8824 return Error(E);
8825
8826 if (!EvaluateObjectArgument(Info, Args[0], ObjectArg))
8827 return false;
8828
8829 // If we are calling a static operator, the 'this' argument needs to be
8830 // ignored after being evaluated.
8831 if (MD->isInstance())
8832 This = &ObjectArg;
8833
8834 // If this is syntactically a simple assignment using a trivial
8835 // assignment operator, start the lifetimes of union members as needed,
8836 // per C++20 [class.union]5.
8837 if (Info.getLangOpts().CPlusPlus20 && OCE &&
8838 OCE->getOperator() == OO_Equal && MD->isTrivial() &&
8839 !MaybeHandleUnionActiveMemberChange(Info, Args[0], ObjectArg))
8840 return false;
8841
8842 Args = Args.slice(1);
8843 } else if (MD && MD->isLambdaStaticInvoker()) {
8844 // Map the static invoker for the lambda back to the call operator.
8845 // Conveniently, we don't have to slice out the 'this' argument (as is
8846 // being done for the non-static case), since a static member function
8847 // doesn't have an implicit argument passed in.
8848 const CXXRecordDecl *ClosureClass = MD->getParent();
8849 assert(
8850 ClosureClass->captures().empty() &&
8851 "Number of captures must be zero for conversion to function-ptr");
8852
8853 const CXXMethodDecl *LambdaCallOp =
8854 ClosureClass->getLambdaCallOperator();
8855
8856 // Set 'FD', the function that will be called below, to the call
8857 // operator. If the closure object represents a generic lambda, find
8858 // the corresponding specialization of the call operator.
8859
8860 if (ClosureClass->isGenericLambda()) {
8861 assert(MD->isFunctionTemplateSpecialization() &&
8862 "A generic lambda's static-invoker function must be a "
8863 "template specialization");
8864 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
8865 FunctionTemplateDecl *CallOpTemplate =
8866 LambdaCallOp->getDescribedFunctionTemplate();
8867 void *InsertPos = nullptr;
8868 FunctionDecl *CorrespondingCallOpSpecialization =
8869 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
8870 assert(CorrespondingCallOpSpecialization &&
8871 "We must always have a function call operator specialization "
8872 "that corresponds to our static invoker specialization");
8873 assert(isa<CXXMethodDecl>(CorrespondingCallOpSpecialization));
8874 FD = CorrespondingCallOpSpecialization;
8875 } else
8876 FD = LambdaCallOp;
8877 } else if (FD->isUsableAsGlobalAllocationFunctionInConstantEvaluation()) {
8878 if (FD->getDeclName().isAnyOperatorNew()) {
8879 LValue Ptr;
8880 if (!HandleOperatorNewCall(Info, E, Ptr))
8881 return false;
8882 Ptr.moveInto(Result);
8883 return CallScope.destroy();
8884 } else {
8885 return HandleOperatorDeleteCall(Info, E) && CallScope.destroy();
8886 }
8887 }
8888 } else
8889 return Error(E);
8890
8891 // Evaluate the arguments now if we've not already done so.
8892 if (!Call) {
8893 Call = Info.CurrentCall->createCall(FD);
8894 if (!EvaluateArgs(Args, Call, Info, FD, /*RightToLeft*/ false,
8895 &ObjectArg))
8896 return false;
8897 }
8898
8899 SmallVector<QualType, 4> CovariantAdjustmentPath;
8900 if (This) {
8901 auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
8902 if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
8903 // Perform virtual dispatch, if necessary.
8904 FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
8905 CovariantAdjustmentPath);
8906 if (!FD)
8907 return false;
8908 } else if (NamedMember && NamedMember->isImplicitObjectMemberFunction()) {
8909 // Check that the 'this' pointer points to an object of the right type.
8910 // FIXME: If this is an assignment operator call, we may need to change
8911 // the active union member before we check this.
8912 if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
8913 return false;
8914 }
8915 }
8916
8917 // Destructor calls are different enough that they have their own codepath.
8918 if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
8919 assert(This && "no 'this' pointer for destructor call");
8920 return HandleDestruction(Info, E, *This,
8921 Info.Ctx.getCanonicalTagType(DD->getParent())) &&
8922 CallScope.destroy();
8923 }
8924
8925 const FunctionDecl *Definition = nullptr;
8926 Stmt *Body = FD->getBody(Definition);
8927 SourceLocation Loc = E->getExprLoc();
8928
8929 // Treat the object argument as `this` when evaluating defaulted
8930 // special menmber functions
8931 if (FD->hasCXXExplicitFunctionObjectParameter())
8932 This = &ObjectArg;
8933
8934 if (!CheckConstexprFunction(Info, Loc, FD, Definition, Body) ||
8935 !HandleFunctionCall(Loc, Definition, This, E, Args, Call, Body, Info,
8936 Result, ResultSlot))
8937 return false;
8938
8939 if (!CovariantAdjustmentPath.empty() &&
8940 !HandleCovariantReturnAdjustment(Info, E, Result,
8941 CovariantAdjustmentPath))
8942 return false;
8943
8944 return CallScope.destroy();
8945 }
8946
8947 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
8948 return StmtVisitorTy::Visit(E->getInitializer());
8949 }
8950 bool VisitInitListExpr(const InitListExpr *E) {
8951 if (E->getNumInits() == 0)
8952 return DerivedZeroInitialization(E);
8953 if (E->getNumInits() == 1)
8954 return StmtVisitorTy::Visit(E->getInit(0));
8955 return Error(E);
8956 }
8957 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
8958 return DerivedZeroInitialization(E);
8959 }
8960 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
8961 return DerivedZeroInitialization(E);
8962 }
8963 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
8964 return DerivedZeroInitialization(E);
8965 }
8966
8967 /// A member expression where the object is a prvalue is itself a prvalue.
8968 bool VisitMemberExpr(const MemberExpr *E) {
8969 assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
8970 "missing temporary materialization conversion");
8971 assert(!E->isArrow() && "missing call to bound member function?");
8972
8973 APValue Val;
8974 if (!Evaluate(Val, Info, E->getBase()))
8975 return false;
8976
8977 QualType BaseTy = E->getBase()->getType();
8978
8979 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
8980 if (!FD) return Error(E);
8981 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
8982 assert(BaseTy->castAsCanonical<RecordType>()->getDecl() ==
8983 FD->getParent()->getCanonicalDecl() &&
8984 "record / field mismatch");
8985
8986 // Note: there is no lvalue base here. But this case should only ever
8987 // happen in C or in C++98, where we cannot be evaluating a constexpr
8988 // constructor, which is the only case the base matters.
8989 CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
8990 SubobjectDesignator Designator(BaseTy);
8991 Designator.addDeclUnchecked(FD);
8992
8993 APValue Result;
8994 return extractSubobject(Info, E, Obj, Designator, Result) &&
8995 DerivedSuccess(Result, E);
8996 }
8997
8998 bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) {
8999 APValue Val;
9000 if (!Evaluate(Val, Info, E->getBase()))
9001 return false;
9002
9003 if (Val.isVector()) {
9004 SmallVector<uint32_t, 4> Indices;
9005 E->getEncodedElementAccess(Indices);
9006 if (Indices.size() == 1) {
9007 // Return scalar.
9008 return DerivedSuccess(Val.getVectorElt(Indices[0]), E);
9009 } else {
9010 // Construct new APValue vector.
9011 SmallVector<APValue, 4> Elts;
9012 for (unsigned I = 0; I < Indices.size(); ++I) {
9013 Elts.push_back(Val.getVectorElt(Indices[I]));
9014 }
9015 APValue VecResult(Elts.data(), Indices.size());
9016 return DerivedSuccess(VecResult, E);
9017 }
9018 }
9019
9020 return false;
9021 }
9022
9023 bool VisitCastExpr(const CastExpr *E) {
9024 switch (E->getCastKind()) {
9025 default:
9026 break;
9027
9028 case CK_AtomicToNonAtomic: {
9029 APValue AtomicVal;
9030 // This does not need to be done in place even for class/array types:
9031 // atomic-to-non-atomic conversion implies copying the object
9032 // representation.
9033 if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
9034 return false;
9035 return DerivedSuccess(AtomicVal, E);
9036 }
9037
9038 case CK_NoOp:
9039 case CK_UserDefinedConversion:
9040 return StmtVisitorTy::Visit(E->getSubExpr());
9041
9042 case CK_HLSLArrayRValue: {
9043 const Expr *SubExpr = E->getSubExpr();
9044 if (!SubExpr->isGLValue()) {
9045 APValue Val;
9046 if (!Evaluate(Val, Info, SubExpr))
9047 return false;
9048 return DerivedSuccess(Val, E);
9049 }
9050
9051 LValue LVal;
9052 if (!EvaluateLValue(SubExpr, LVal, Info))
9053 return false;
9054 APValue RVal;
9055 // Note, we use the subexpression's type in order to retain cv-qualifiers.
9056 if (!handleLValueToRValueConversion(Info, E, SubExpr->getType(), LVal,
9057 RVal))
9058 return false;
9059 return DerivedSuccess(RVal, E);
9060 }
9061 case CK_LValueToRValue: {
9062 LValue LVal;
9063 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
9064 return false;
9065 APValue RVal;
9066 // Note, we use the subexpression's type in order to retain cv-qualifiers.
9067 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
9068 LVal, RVal))
9069 return false;
9070 return DerivedSuccess(RVal, E);
9071 }
9072 case CK_LValueToRValueBitCast: {
9073 APValue DestValue, SourceValue;
9074 if (!Evaluate(SourceValue, Info, E->getSubExpr()))
9075 return false;
9076 if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
9077 return false;
9078 return DerivedSuccess(DestValue, E);
9079 }
9080
9081 case CK_AddressSpaceConversion: {
9082 APValue Value;
9083 if (!Evaluate(Value, Info, E->getSubExpr()))
9084 return false;
9085 return DerivedSuccess(Value, E);
9086 }
9087 }
9088
9089 return Error(E);
9090 }
9091
9092 bool VisitUnaryPostInc(const UnaryOperator *UO) {
9093 return VisitUnaryPostIncDec(UO);
9094 }
9095 bool VisitUnaryPostDec(const UnaryOperator *UO) {
9096 return VisitUnaryPostIncDec(UO);
9097 }
9098 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
9099 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9100 return Error(UO);
9101
9102 LValue LVal;
9103 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
9104 return false;
9105 APValue RVal;
9106 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
9107 UO->isIncrementOp(), &RVal))
9108 return false;
9109 return DerivedSuccess(RVal, UO);
9110 }
9111
9112 bool VisitStmtExpr(const StmtExpr *E) {
9113 // We will have checked the full-expressions inside the statement expression
9114 // when they were completed, and don't need to check them again now.
9115 llvm::SaveAndRestore NotCheckingForUB(Info.CheckingForUndefinedBehavior,
9116 false);
9117
9118 const CompoundStmt *CS = E->getSubStmt();
9119 if (CS->body_empty())
9120 return true;
9121
9122 BlockScopeRAII Scope(Info);
9123 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
9124 BE = CS->body_end();
9125 /**/; ++BI) {
9126 if (BI + 1 == BE) {
9127 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
9128 if (!FinalExpr) {
9129 Info.FFDiag((*BI)->getBeginLoc(),
9130 diag::note_constexpr_stmt_expr_unsupported);
9131 return false;
9132 }
9133 return this->Visit(FinalExpr) && Scope.destroy();
9134 }
9135
9136 APValue ReturnValue;
9137 StmtResult Result = { ReturnValue, nullptr };
9138 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
9139 if (ESR != ESR_Succeeded) {
9140 // FIXME: If the statement-expression terminated due to 'return',
9141 // 'break', or 'continue', it would be nice to propagate that to
9142 // the outer statement evaluation rather than bailing out.
9143 if (ESR != ESR_Failed)
9144 Info.FFDiag((*BI)->getBeginLoc(),
9145 diag::note_constexpr_stmt_expr_unsupported);
9146 return false;
9147 }
9148 }
9149
9150 llvm_unreachable("Return from function from the loop above.");
9151 }
9152
9153 bool VisitPackIndexingExpr(const PackIndexingExpr *E) {
9154 return StmtVisitorTy::Visit(E->getSelectedExpr());
9155 }
9156
9157 /// Visit a value which is evaluated, but whose value is ignored.
9158 void VisitIgnoredValue(const Expr *E) {
9159 EvaluateIgnoredValue(Info, E);
9160 }
9161
9162 /// Potentially visit a MemberExpr's base expression.
9163 void VisitIgnoredBaseExpression(const Expr *E) {
9164 // While MSVC doesn't evaluate the base expression, it does diagnose the
9165 // presence of side-effecting behavior.
9166 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
9167 return;
9168 VisitIgnoredValue(E);
9169 }
9170 };
9171
9172 } // namespace
9173
9174 //===----------------------------------------------------------------------===//
9175 // Common base class for lvalue and temporary evaluation.
9176 //===----------------------------------------------------------------------===//
9177 namespace {
9178 template<class Derived>
9179 class LValueExprEvaluatorBase
9180 : public ExprEvaluatorBase<Derived> {
9181 protected:
9182 LValue &Result;
9183 bool InvalidBaseOK;
9184 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
9185 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
9186
9187 bool Success(APValue::LValueBase B) {
9188 Result.set(B);
9189 return true;
9190 }
9191
9192 bool evaluatePointer(const Expr *E, LValue &Result) {
9193 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
9194 }
9195
9196 public:
9197 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
9198 : ExprEvaluatorBaseTy(Info), Result(Result),
9199 InvalidBaseOK(InvalidBaseOK) {}
9200
9201 bool Success(const APValue &V, const Expr *E) {
9202 Result.setFrom(this->Info.Ctx, V);
9203 return true;
9204 }
9205
9206 bool VisitMemberExpr(const MemberExpr *E) {
9207 // Handle non-static data members.
9208 QualType BaseTy;
9209 bool EvalOK;
9210 if (E->isArrow()) {
9211 EvalOK = evaluatePointer(E->getBase(), Result);
9212 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
9213 } else if (E->getBase()->isPRValue()) {
9214 assert(E->getBase()->getType()->isRecordType());
9215 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
9216 BaseTy = E->getBase()->getType();
9217 } else {
9218 EvalOK = this->Visit(E->getBase());
9219 BaseTy = E->getBase()->getType();
9220 }
9221 if (!EvalOK) {
9222 if (!InvalidBaseOK)
9223 return false;
9224 Result.setInvalid(E);
9225 return true;
9226 }
9227
9228 const ValueDecl *MD = E->getMemberDecl();
9229 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
9230 assert(BaseTy->castAsCanonical<RecordType>()->getDecl() ==
9231 FD->getParent()->getCanonicalDecl() &&
9232 "record / field mismatch");
9233 (void)BaseTy;
9234 if (!HandleLValueMember(this->Info, E, Result, FD))
9235 return false;
9236 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
9237 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
9238 return false;
9239 } else
9240 return this->Error(E);
9241
9242 if (MD->getType()->isReferenceType()) {
9243 APValue RefValue;
9244 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
9245 RefValue))
9246 return false;
9247 return Success(RefValue, E);
9248 }
9249 return true;
9250 }
9251
9252 bool VisitBinaryOperator(const BinaryOperator *E) {
9253 switch (E->getOpcode()) {
9254 default:
9255 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9256
9257 case BO_PtrMemD:
9258 case BO_PtrMemI:
9259 return HandleMemberPointerAccess(this->Info, E, Result);
9260 }
9261 }
9262
9263 bool VisitCastExpr(const CastExpr *E) {
9264 switch (E->getCastKind()) {
9265 default:
9266 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9267
9268 case CK_DerivedToBase:
9269 case CK_UncheckedDerivedToBase:
9270 if (!this->Visit(E->getSubExpr()))
9271 return false;
9272
9273 // Now figure out the necessary offset to add to the base LV to get from
9274 // the derived class to the base class.
9275 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
9276 Result);
9277 }
9278 }
9279 };
9280 }
9281
9282 //===----------------------------------------------------------------------===//
9283 // LValue Evaluation
9284 //
9285 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
9286 // function designators (in C), decl references to void objects (in C), and
9287 // temporaries (if building with -Wno-address-of-temporary).
9288 //
9289 // LValue evaluation produces values comprising a base expression of one of the
9290 // following types:
9291 // - Declarations
9292 // * VarDecl
9293 // * FunctionDecl
9294 // - Literals
9295 // * CompoundLiteralExpr in C (and in global scope in C++)
9296 // * StringLiteral
9297 // * PredefinedExpr
9298 // * ObjCStringLiteralExpr
9299 // * ObjCEncodeExpr
9300 // * AddrLabelExpr
9301 // * BlockExpr
9302 // * CallExpr for a MakeStringConstant builtin
9303 // - typeid(T) expressions, as TypeInfoLValues
9304 // - Locals and temporaries
9305 // * MaterializeTemporaryExpr
9306 // * Any Expr, with a CallIndex indicating the function in which the temporary
9307 // was evaluated, for cases where the MaterializeTemporaryExpr is missing
9308 // from the AST (FIXME).
9309 // * A MaterializeTemporaryExpr that has static storage duration, with no
9310 // CallIndex, for a lifetime-extended temporary.
9311 // * The ConstantExpr that is currently being evaluated during evaluation of an
9312 // immediate invocation.
9313 // plus an offset in bytes.
9314 //===----------------------------------------------------------------------===//
9315 namespace {
9316 class LValueExprEvaluator
9317 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
9318 public:
9319 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
9320 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
9321
9322 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
9323 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
9324
9325 bool VisitCallExpr(const CallExpr *E);
9326 bool VisitDeclRefExpr(const DeclRefExpr *E);
9327 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
9328 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
9329 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
9330 bool VisitMemberExpr(const MemberExpr *E);
9331 bool VisitStringLiteral(const StringLiteral *E) {
9332 return Success(APValue::LValueBase(
9333 E, 0, Info.getASTContext().getNextStringLiteralVersion()));
9334 }
9335 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
9336 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
9337 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
9338 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
9339 bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E);
9340 bool VisitUnaryDeref(const UnaryOperator *E);
9341 bool VisitUnaryReal(const UnaryOperator *E);
9342 bool VisitUnaryImag(const UnaryOperator *E);
9343 bool VisitUnaryPreInc(const UnaryOperator *UO) {
9344 return VisitUnaryPreIncDec(UO);
9345 }
9346 bool VisitUnaryPreDec(const UnaryOperator *UO) {
9347 return VisitUnaryPreIncDec(UO);
9348 }
9349 bool VisitBinAssign(const BinaryOperator *BO);
9350 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
9351
9352 bool VisitCastExpr(const CastExpr *E) {
9353 switch (E->getCastKind()) {
9354 default:
9355 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
9356
9357 case CK_LValueBitCast:
9358 this->CCEDiag(E, diag::note_constexpr_invalid_cast)
9359 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
9360 << Info.Ctx.getLangOpts().CPlusPlus;
9361 if (!Visit(E->getSubExpr()))
9362 return false;
9363 Result.Designator.setInvalid();
9364 return true;
9365
9366 case CK_BaseToDerived:
9367 if (!Visit(E->getSubExpr()))
9368 return false;
9369 return HandleBaseToDerivedCast(Info, E, Result);
9370
9371 case CK_Dynamic:
9372 if (!Visit(E->getSubExpr()))
9373 return false;
9374 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
9375 }
9376 }
9377 };
9378 } // end anonymous namespace
9379
9380 /// Get an lvalue to a field of a lambda's closure type.
9381 static bool HandleLambdaCapture(EvalInfo &Info, const Expr *E, LValue &Result,
9382 const CXXMethodDecl *MD, const FieldDecl *FD,
9383 bool LValueToRValueConversion) {
9384 // Static lambda function call operators can't have captures. We already
9385 // diagnosed this, so bail out here.
9386 if (MD->isStatic()) {
9387 assert(Info.CurrentCall->This == nullptr &&
9388 "This should not be set for a static call operator");
9389 return false;
9390 }
9391
9392 // Start with 'Result' referring to the complete closure object...
9393 if (MD->isExplicitObjectMemberFunction()) {
9394 // Self may be passed by reference or by value.
9395 const ParmVarDecl *Self = MD->getParamDecl(0);
9396 if (Self->getType()->isReferenceType()) {
9397 APValue *RefValue = Info.getParamSlot(Info.CurrentCall->Arguments, Self);
9398 if (!RefValue->allowConstexprUnknown() || RefValue->hasValue())
9399 Result.setFrom(Info.Ctx, *RefValue);
9400 } else {
9401 const ParmVarDecl *VD = Info.CurrentCall->Arguments.getOrigParam(Self);
9402 CallStackFrame *Frame =
9403 Info.getCallFrameAndDepth(Info.CurrentCall->Arguments.CallIndex)
9404 .first;
9405 unsigned Version = Info.CurrentCall->Arguments.Version;
9406 Result.set({VD, Frame->Index, Version});
9407 }
9408 } else
9409 Result = *Info.CurrentCall->This;
9410
9411 // ... then update it to refer to the field of the closure object
9412 // that represents the capture.
9413 if (!HandleLValueMember(Info, E, Result, FD))
9414 return false;
9415
9416 // And if the field is of reference type (or if we captured '*this' by
9417 // reference), update 'Result' to refer to what
9418 // the field refers to.
9419 if (LValueToRValueConversion) {
9420 APValue RVal;
9421 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result, RVal))
9422 return false;
9423 Result.setFrom(Info.Ctx, RVal);
9424 }
9425 return true;
9426 }
9427
9428 /// Evaluate an expression as an lvalue. This can be legitimately called on
9429 /// expressions which are not glvalues, in three cases:
9430 /// * function designators in C, and
9431 /// * "extern void" objects
9432 /// * @selector() expressions in Objective-C
9433 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
9434 bool InvalidBaseOK) {
9435 assert(!E->isValueDependent());
9436 assert(E->isGLValue() || E->getType()->isFunctionType() ||
9437 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E->IgnoreParens()));
9438 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
9439 }
9440
9441 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
9442 const ValueDecl *D = E->getDecl();
9443
9444 // If we are within a lambda's call operator, check whether the 'VD' referred
9445 // to within 'E' actually represents a lambda-capture that maps to a
9446 // data-member/field within the closure object, and if so, evaluate to the
9447 // field or what the field refers to.
9448 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
9449 E->refersToEnclosingVariableOrCapture()) {
9450 // We don't always have a complete capture-map when checking or inferring if
9451 // the function call operator meets the requirements of a constexpr function
9452 // - but we don't need to evaluate the captures to determine constexprness
9453 // (dcl.constexpr C++17).
9454 if (Info.checkingPotentialConstantExpression())
9455 return false;
9456
9457 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(D)) {
9458 const auto *MD = cast<CXXMethodDecl>(Info.CurrentCall->Callee);
9459 return HandleLambdaCapture(Info, E, Result, MD, FD,
9460 FD->getType()->isReferenceType());
9461 }
9462 }
9463
9464 if (isa<FunctionDecl, MSGuidDecl, TemplateParamObjectDecl,
9465 UnnamedGlobalConstantDecl>(D))
9466 return Success(cast<ValueDecl>(D));
9467 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
9468 return VisitVarDecl(E, VD);
9469 if (const BindingDecl *BD = dyn_cast<BindingDecl>(D))
9470 return Visit(BD->getBinding());
9471 return Error(E);
9472 }
9473
9474 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
9475 CallStackFrame *Frame = nullptr;
9476 unsigned Version = 0;
9477 if (VD->hasLocalStorage()) {
9478 // Only if a local variable was declared in the function currently being
9479 // evaluated, do we expect to be able to find its value in the current
9480 // frame. (Otherwise it was likely declared in an enclosing context and
9481 // could either have a valid evaluatable value (for e.g. a constexpr
9482 // variable) or be ill-formed (and trigger an appropriate evaluation
9483 // diagnostic)).
9484 CallStackFrame *CurrFrame = Info.CurrentCall;
9485 if (CurrFrame->Callee && CurrFrame->Callee->Equals(VD->getDeclContext())) {
9486 // Function parameters are stored in some caller's frame. (Usually the
9487 // immediate caller, but for an inherited constructor they may be more
9488 // distant.)
9489 if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) {
9490 if (CurrFrame->Arguments) {
9491 VD = CurrFrame->Arguments.getOrigParam(PVD);
9492 Frame =
9493 Info.getCallFrameAndDepth(CurrFrame->Arguments.CallIndex).first;
9494 Version = CurrFrame->Arguments.Version;
9495 }
9496 } else {
9497 Frame = CurrFrame;
9498 Version = CurrFrame->getCurrentTemporaryVersion(VD);
9499 }
9500 }
9501 }
9502
9503 if (!VD->getType()->isReferenceType()) {
9504 if (Frame) {
9505 Result.set({VD, Frame->Index, Version});
9506 return true;
9507 }
9508 return Success(VD);
9509 }
9510
9511 if (!Info.getLangOpts().CPlusPlus11) {
9512 Info.CCEDiag(E, diag::note_constexpr_ltor_non_integral, 1)
9513 << VD << VD->getType();
9514 Info.Note(VD->getLocation(), diag::note_declared_at);
9515 }
9516
9517 APValue *V;
9518 if (!evaluateVarDeclInit(Info, E, VD, Frame, Version, V))
9519 return false;
9520
9521 if (!V) {
9522 Result.set(VD);
9523 Result.AllowConstexprUnknown = true;
9524 return true;
9525 }
9526
9527 return Success(*V, E);
9528 }
9529
9530 bool LValueExprEvaluator::VisitCallExpr(const CallExpr *E) {
9531 if (!IsConstantEvaluatedBuiltinCall(E))
9532 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9533
9534 switch (E->getBuiltinCallee()) {
9535 default:
9536 return false;
9537 case Builtin::BIas_const:
9538 case Builtin::BIforward:
9539 case Builtin::BIforward_like:
9540 case Builtin::BImove:
9541 case Builtin::BImove_if_noexcept:
9542 if (cast<FunctionDecl>(E->getCalleeDecl())->isConstexpr())
9543 return Visit(E->getArg(0));
9544 break;
9545 }
9546
9547 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9548 }
9549
9550 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
9551 const MaterializeTemporaryExpr *E) {
9552 // Walk through the expression to find the materialized temporary itself.
9553 SmallVector<const Expr *, 2> CommaLHSs;
9554 SmallVector<SubobjectAdjustment, 2> Adjustments;
9555 const Expr *Inner =
9556 E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
9557
9558 // If we passed any comma operators, evaluate their LHSs.
9559 for (const Expr *E : CommaLHSs)
9560 if (!EvaluateIgnoredValue(Info, E))
9561 return false;
9562
9563 // A materialized temporary with static storage duration can appear within the
9564 // result of a constant expression evaluation, so we need to preserve its
9565 // value for use outside this evaluation.
9566 APValue *Value;
9567 if (E->getStorageDuration() == SD_Static) {
9568 if (Info.EvalMode == EvaluationMode::ConstantFold)
9569 return false;
9570 // FIXME: What about SD_Thread?
9571 Value = E->getOrCreateValue(true);
9572 *Value = APValue();
9573 Result.set(E);
9574 } else {
9575 Value = &Info.CurrentCall->createTemporary(
9576 E, Inner->getType(),
9577 E->getStorageDuration() == SD_FullExpression ? ScopeKind::FullExpression
9578 : ScopeKind::Block,
9579 Result);
9580 }
9581
9582 QualType Type = Inner->getType();
9583
9584 // Materialize the temporary itself.
9585 if (!EvaluateInPlace(*Value, Info, Result, Inner)) {
9586 *Value = APValue();
9587 return false;
9588 }
9589
9590 // Adjust our lvalue to refer to the desired subobject.
9591 for (unsigned I = Adjustments.size(); I != 0; /**/) {
9592 --I;
9593 switch (Adjustments[I].Kind) {
9594 case SubobjectAdjustment::DerivedToBaseAdjustment:
9595 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
9596 Type, Result))
9597 return false;
9598 Type = Adjustments[I].DerivedToBase.BasePath->getType();
9599 break;
9600
9601 case SubobjectAdjustment::FieldAdjustment:
9602 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
9603 return false;
9604 Type = Adjustments[I].Field->getType();
9605 break;
9606
9607 case SubobjectAdjustment::MemberPointerAdjustment:
9608 if (!HandleMemberPointerAccess(this->Info, Type, Result,
9609 Adjustments[I].Ptr.RHS))
9610 return false;
9611 Type = Adjustments[I].Ptr.MPT->getPointeeType();
9612 break;
9613 }
9614 }
9615
9616 return true;
9617 }
9618
9619 bool
9620 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
9621 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
9622 "lvalue compound literal in c++?");
9623 APValue *Lit;
9624 // If CompountLiteral has static storage, its value can be used outside
9625 // this expression. So evaluate it once and store it in ASTContext.
9626 if (E->hasStaticStorage()) {
9627 Lit = &E->getOrCreateStaticValue(Info.Ctx);
9628 Result.set(E);
9629 // Reset any previously evaluated state, otherwise evaluation below might
9630 // fail.
9631 // FIXME: Should we just re-use the previously evaluated value instead?
9632 *Lit = APValue();
9633 } else {
9634 assert(!Info.getLangOpts().CPlusPlus);
9635 Lit = &Info.CurrentCall->createTemporary(E, E->getInitializer()->getType(),
9636 ScopeKind::Block, Result);
9637 }
9638 // FIXME: Evaluating in place isn't always right. We should figure out how to
9639 // use appropriate evaluation context here, see
9640 // clang/test/AST/static-compound-literals-reeval.cpp for a failure.
9641 if (!EvaluateInPlace(*Lit, Info, Result, E->getInitializer())) {
9642 *Lit = APValue();
9643 return false;
9644 }
9645 return true;
9646 }
9647
9648 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
9649 TypeInfoLValue TypeInfo;
9650
9651 if (!E->isPotentiallyEvaluated()) {
9652 if (E->isTypeOperand())
9653 TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
9654 else
9655 TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
9656 } else {
9657 if (!Info.Ctx.getLangOpts().CPlusPlus20) {
9658 Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
9659 << E->getExprOperand()->getType()
9660 << E->getExprOperand()->getSourceRange();
9661 }
9662
9663 if (!Visit(E->getExprOperand()))
9664 return false;
9665
9666 std::optional<DynamicType> DynType =
9667 ComputeDynamicType(Info, E, Result, AK_TypeId);
9668 if (!DynType)
9669 return false;
9670
9671 TypeInfo = TypeInfoLValue(
9672 Info.Ctx.getCanonicalTagType(DynType->Type).getTypePtr());
9673 }
9674
9675 return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
9676 }
9677
9678 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
9679 return Success(E->getGuidDecl());
9680 }
9681
9682 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
9683 // Handle static data members.
9684 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
9685 VisitIgnoredBaseExpression(E->getBase());
9686 return VisitVarDecl(E, VD);
9687 }
9688
9689 // Handle static member functions.
9690 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
9691 if (MD->isStatic()) {
9692 VisitIgnoredBaseExpression(E->getBase());
9693 return Success(MD);
9694 }
9695 }
9696
9697 // Handle non-static data members.
9698 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
9699 }
9700
9701 bool LValueExprEvaluator::VisitExtVectorElementExpr(
9702 const ExtVectorElementExpr *E) {
9703 bool Success = true;
9704
9705 APValue Val;
9706 if (!Evaluate(Val, Info, E->getBase())) {
9707 if (!Info.noteFailure())
9708 return false;
9709 Success = false;
9710 }
9711
9712 SmallVector<uint32_t, 4> Indices;
9713 E->getEncodedElementAccess(Indices);
9714 // FIXME: support accessing more than one element
9715 if (Indices.size() > 1)
9716 return false;
9717
9718 if (Success) {
9719 Result.setFrom(Info.Ctx, Val);
9720 QualType BaseType = E->getBase()->getType();
9721 if (E->isArrow())
9722 BaseType = BaseType->getPointeeType();
9723 const auto *VT = BaseType->castAs<VectorType>();
9724 HandleLValueVectorElement(Info, E, Result, VT->getElementType(),
9725 VT->getNumElements(), Indices[0]);
9726 }
9727
9728 return Success;
9729 }
9730
9731 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
9732 if (E->getBase()->getType()->isSveVLSBuiltinType())
9733 return Error(E);
9734
9735 APSInt Index;
9736 bool Success = true;
9737
9738 if (const auto *VT = E->getBase()->getType()->getAs<VectorType>()) {
9739 APValue Val;
9740 if (!Evaluate(Val, Info, E->getBase())) {
9741 if (!Info.noteFailure())
9742 return false;
9743 Success = false;
9744 }
9745
9746 if (!EvaluateInteger(E->getIdx(), Index, Info)) {
9747 if (!Info.noteFailure())
9748 return false;
9749 Success = false;
9750 }
9751
9752 if (Success) {
9753 Result.setFrom(Info.Ctx, Val);
9754 HandleLValueVectorElement(Info, E, Result, VT->getElementType(),
9755 VT->getNumElements(), Index.getExtValue());
9756 }
9757
9758 return Success;
9759 }
9760
9761 // C++17's rules require us to evaluate the LHS first, regardless of which
9762 // side is the base.
9763 for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) {
9764 if (SubExpr == E->getBase() ? !evaluatePointer(SubExpr, Result)
9765 : !EvaluateInteger(SubExpr, Index, Info)) {
9766 if (!Info.noteFailure())
9767 return false;
9768 Success = false;
9769 }
9770 }
9771
9772 return Success &&
9773 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
9774 }
9775
9776 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
9777 bool Success = evaluatePointer(E->getSubExpr(), Result);
9778 // [C++26][expr.unary.op]
9779 // If the operand points to an object or function, the result
9780 // denotes that object or function; otherwise, the behavior is undefined.
9781 // Because &(*(type*)0) is a common pattern, we do not fail the evaluation
9782 // immediately.
9783 if (!Success || !E->getType().getNonReferenceType()->isObjectType())
9784 return Success;
9785 return bool(findCompleteObject(Info, E, AK_Dereference, Result,
9786 E->getType())) ||
9787 Info.noteUndefinedBehavior();
9788 }
9789
9790 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
9791 if (!Visit(E->getSubExpr()))
9792 return false;
9793 // __real is a no-op on scalar lvalues.
9794 if (E->getSubExpr()->getType()->isAnyComplexType())
9795 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
9796 return true;
9797 }
9798
9799 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
9800 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
9801 "lvalue __imag__ on scalar?");
9802 if (!Visit(E->getSubExpr()))
9803 return false;
9804 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
9805 return true;
9806 }
9807
9808 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
9809 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9810 return Error(UO);
9811
9812 if (!this->Visit(UO->getSubExpr()))
9813 return false;
9814
9815 return handleIncDec(
9816 this->Info, UO, Result, UO->getSubExpr()->getType(),
9817 UO->isIncrementOp(), nullptr);
9818 }
9819
9820 bool LValueExprEvaluator::VisitCompoundAssignOperator(
9821 const CompoundAssignOperator *CAO) {
9822 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9823 return Error(CAO);
9824
9825 bool Success = true;
9826
9827 // C++17 onwards require that we evaluate the RHS first.
9828 APValue RHS;
9829 if (!Evaluate(RHS, this->Info, CAO->getRHS())) {
9830 if (!Info.noteFailure())
9831 return false;
9832 Success = false;
9833 }
9834
9835 // The overall lvalue result is the result of evaluating the LHS.
9836 if (!this->Visit(CAO->getLHS()) || !Success)
9837 return false;
9838
9839 return handleCompoundAssignment(
9840 this->Info, CAO,
9841 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
9842 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
9843 }
9844
9845 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
9846 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9847 return Error(E);
9848
9849 bool Success = true;
9850
9851 // C++17 onwards require that we evaluate the RHS first.
9852 APValue NewVal;
9853 if (!Evaluate(NewVal, this->Info, E->getRHS())) {
9854 if (!Info.noteFailure())
9855 return false;
9856 Success = false;
9857 }
9858
9859 if (!this->Visit(E->getLHS()) || !Success)
9860 return false;
9861
9862 if (Info.getLangOpts().CPlusPlus20 &&
9863 !MaybeHandleUnionActiveMemberChange(Info, E->getLHS(), Result))
9864 return false;
9865
9866 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
9867 NewVal);
9868 }
9869
9870 //===----------------------------------------------------------------------===//
9871 // Pointer Evaluation
9872 //===----------------------------------------------------------------------===//
9873
9874 /// Convenience function. LVal's base must be a call to an alloc_size
9875 /// function.
9876 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
9877 const LValue &LVal,
9878 llvm::APInt &Result) {
9879 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
9880 "Can't get the size of a non alloc_size function");
9881 const auto *Base = LVal.getLValueBase().get<const Expr *>();
9882 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
9883 std::optional<llvm::APInt> Size =
9884 CE->evaluateBytesReturnedByAllocSizeCall(Ctx);
9885 if (!Size)
9886 return false;
9887
9888 Result = std::move(*Size);
9889 return true;
9890 }
9891
9892 /// Attempts to evaluate the given LValueBase as the result of a call to
9893 /// a function with the alloc_size attribute. If it was possible to do so, this
9894 /// function will return true, make Result's Base point to said function call,
9895 /// and mark Result's Base as invalid.
9896 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
9897 LValue &Result) {
9898 if (Base.isNull())
9899 return false;
9900
9901 // Because we do no form of static analysis, we only support const variables.
9902 //
9903 // Additionally, we can't support parameters, nor can we support static
9904 // variables (in the latter case, use-before-assign isn't UB; in the former,
9905 // we have no clue what they'll be assigned to).
9906 const auto *VD =
9907 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
9908 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
9909 return false;
9910
9911 const Expr *Init = VD->getAnyInitializer();
9912 if (!Init || Init->getType().isNull())
9913 return false;
9914
9915 const Expr *E = Init->IgnoreParens();
9916 if (!tryUnwrapAllocSizeCall(E))
9917 return false;
9918
9919 // Store E instead of E unwrapped so that the type of the LValue's base is
9920 // what the user wanted.
9921 Result.setInvalid(E);
9922
9923 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
9924 Result.addUnsizedArray(Info, E, Pointee);
9925 return true;
9926 }
9927
9928 namespace {
9929 class PointerExprEvaluator
9930 : public ExprEvaluatorBase<PointerExprEvaluator> {
9931 LValue &Result;
9932 bool InvalidBaseOK;
9933
9934 bool Success(const Expr *E) {
9935 Result.set(E);
9936 return true;
9937 }
9938
9939 bool evaluateLValue(const Expr *E, LValue &Result) {
9940 return EvaluateLValue(E, Result, Info, InvalidBaseOK);
9941 }
9942
9943 bool evaluatePointer(const Expr *E, LValue &Result) {
9944 return EvaluatePointer(E, Result, Info, InvalidBaseOK);
9945 }
9946
9947 bool visitNonBuiltinCallExpr(const CallExpr *E);
9948 public:
9949
9950 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
9951 : ExprEvaluatorBaseTy(info), Result(Result),
9952 InvalidBaseOK(InvalidBaseOK) {}
9953
9954 bool Success(const APValue &V, const Expr *E) {
9955 Result.setFrom(Info.Ctx, V);
9956 return true;
9957 }
9958 bool ZeroInitialization(const Expr *E) {
9959 Result.setNull(Info.Ctx, E->getType());
9960 return true;
9961 }
9962
9963 bool VisitBinaryOperator(const BinaryOperator *E);
9964 bool VisitCastExpr(const CastExpr* E);
9965 bool VisitUnaryAddrOf(const UnaryOperator *E);
9966 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
9967 { return Success(E); }
9968 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
9969 if (E->isExpressibleAsConstantInitializer())
9970 return Success(E);
9971 if (Info.noteFailure())
9972 EvaluateIgnoredValue(Info, E->getSubExpr());
9973 return Error(E);
9974 }
9975 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
9976 { return Success(E); }
9977 bool VisitCallExpr(const CallExpr *E);
9978 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
9979 bool VisitBlockExpr(const BlockExpr *E) {
9980 if (!E->getBlockDecl()->hasCaptures())
9981 return Success(E);
9982 return Error(E);
9983 }
9984 bool VisitCXXThisExpr(const CXXThisExpr *E) {
9985 auto DiagnoseInvalidUseOfThis = [&] {
9986 if (Info.getLangOpts().CPlusPlus11)
9987 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
9988 else
9989 Info.FFDiag(E);
9990 };
9991
9992 // Can't look at 'this' when checking a potential constant expression.
9993 if (Info.checkingPotentialConstantExpression())
9994 return false;
9995
9996 bool IsExplicitLambda =
9997 isLambdaCallWithExplicitObjectParameter(Info.CurrentCall->Callee);
9998 if (!IsExplicitLambda) {
9999 if (!Info.CurrentCall->This) {
10000 DiagnoseInvalidUseOfThis();
10001 return false;
10002 }
10003
10004 Result = *Info.CurrentCall->This;
10005 }
10006
10007 if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
10008 // Ensure we actually have captured 'this'. If something was wrong with
10009 // 'this' capture, the error would have been previously reported.
10010 // Otherwise we can be inside of a default initialization of an object
10011 // declared by lambda's body, so no need to return false.
10012 if (!Info.CurrentCall->LambdaThisCaptureField) {
10013 if (IsExplicitLambda && !Info.CurrentCall->This) {
10014 DiagnoseInvalidUseOfThis();
10015 return false;
10016 }
10017
10018 return true;
10019 }
10020
10021 const auto *MD = cast<CXXMethodDecl>(Info.CurrentCall->Callee);
10022 return HandleLambdaCapture(
10023 Info, E, Result, MD, Info.CurrentCall->LambdaThisCaptureField,
10024 Info.CurrentCall->LambdaThisCaptureField->getType()->isPointerType());
10025 }
10026 return true;
10027 }
10028
10029 bool VisitCXXNewExpr(const CXXNewExpr *E);
10030
10031 bool VisitSourceLocExpr(const SourceLocExpr *E) {
10032 assert(!E->isIntType() && "SourceLocExpr isn't a pointer type?");
10033 APValue LValResult = E->EvaluateInContext(
10034 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
10035 Result.setFrom(Info.Ctx, LValResult);
10036 return true;
10037 }
10038
10039 bool VisitEmbedExpr(const EmbedExpr *E) {
10040 llvm::report_fatal_error("Not yet implemented for ExprConstant.cpp");
10041 return true;
10042 }
10043
10044 bool VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr *E) {
10045 std::string ResultStr = E->ComputeName(Info.Ctx);
10046
10047 QualType CharTy = Info.Ctx.CharTy.withConst();
10048 APInt Size(Info.Ctx.getTypeSize(Info.Ctx.getSizeType()),
10049 ResultStr.size() + 1);
10050 QualType ArrayTy = Info.Ctx.getConstantArrayType(
10051 CharTy, Size, nullptr, ArraySizeModifier::Normal, 0);
10052
10053 StringLiteral *SL =
10054 StringLiteral::Create(Info.Ctx, ResultStr, StringLiteralKind::Ordinary,
10055 /*Pascal*/ false, ArrayTy, E->getLocation());
10056
10057 evaluateLValue(SL, Result);
10058 Result.addArray(Info, E, cast<ConstantArrayType>(ArrayTy));
10059 return true;
10060 }
10061
10062 // FIXME: Missing: @protocol, @selector
10063 };
10064 } // end anonymous namespace
10065
10066 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
10067 bool InvalidBaseOK) {
10068 assert(!E->isValueDependent());
10069 assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
10070 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
10071 }
10072
10073 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
10074 if (E->getOpcode() != BO_Add &&
10075 E->getOpcode() != BO_Sub)
10076 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10077
10078 const Expr *PExp = E->getLHS();
10079 const Expr *IExp = E->getRHS();
10080 if (IExp->getType()->isPointerType())
10081 std::swap(PExp, IExp);
10082
10083 bool EvalPtrOK = evaluatePointer(PExp, Result);
10084 if (!EvalPtrOK && !Info.noteFailure())
10085 return false;
10086
10087 llvm::APSInt Offset;
10088 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
10089 return false;
10090
10091 if (E->getOpcode() == BO_Sub)
10092 negateAsSigned(Offset);
10093
10094 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
10095 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
10096 }
10097
10098 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
10099 return evaluateLValue(E->getSubExpr(), Result);
10100 }
10101
10102 // Is the provided decl 'std::source_location::current'?
10103 static bool IsDeclSourceLocationCurrent(const FunctionDecl *FD) {
10104 if (!FD)
10105 return false;
10106 const IdentifierInfo *FnII = FD->getIdentifier();
10107 if (!FnII || !FnII->isStr("current"))
10108 return false;
10109
10110 const auto *RD = dyn_cast<RecordDecl>(FD->getParent());
10111 if (!RD)
10112 return false;
10113
10114 const IdentifierInfo *ClassII = RD->getIdentifier();
10115 return RD->isInStdNamespace() && ClassII && ClassII->isStr("source_location");
10116 }
10117
10118 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
10119 const Expr *SubExpr = E->getSubExpr();
10120
10121 switch (E->getCastKind()) {
10122 default:
10123 break;
10124 case CK_BitCast:
10125 case CK_CPointerToObjCPointerCast:
10126 case CK_BlockPointerToObjCPointerCast:
10127 case CK_AnyPointerToBlockPointerCast:
10128 case CK_AddressSpaceConversion:
10129 if (!Visit(SubExpr))
10130 return false;
10131 if (E->getType()->isFunctionPointerType() ||
10132 SubExpr->getType()->isFunctionPointerType()) {
10133 // Casting between two function pointer types, or between a function
10134 // pointer and an object pointer, is always a reinterpret_cast.
10135 CCEDiag(E, diag::note_constexpr_invalid_cast)
10136 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
10137 << Info.Ctx.getLangOpts().CPlusPlus;
10138 Result.Designator.setInvalid();
10139 } else if (!E->getType()->isVoidPointerType()) {
10140 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
10141 // permitted in constant expressions in C++11. Bitcasts from cv void* are
10142 // also static_casts, but we disallow them as a resolution to DR1312.
10143 //
10144 // In some circumstances, we permit casting from void* to cv1 T*, when the
10145 // actual pointee object is actually a cv2 T.
10146 bool HasValidResult = !Result.InvalidBase && !Result.Designator.Invalid &&
10147 !Result.IsNullPtr;
10148 bool VoidPtrCastMaybeOK =
10149 Result.IsNullPtr ||
10150 (HasValidResult &&
10151 Info.Ctx.hasSimilarType(Result.Designator.getType(Info.Ctx),
10152 E->getType()->getPointeeType()));
10153 // 1. We'll allow it in std::allocator::allocate, and anything which that
10154 // calls.
10155 // 2. HACK 2022-03-28: Work around an issue with libstdc++'s
10156 // <source_location> header. Fixed in GCC 12 and later (2022-04-??).
10157 // We'll allow it in the body of std::source_location::current. GCC's
10158 // implementation had a parameter of type `void*`, and casts from
10159 // that back to `const __impl*` in its body.
10160 if (VoidPtrCastMaybeOK &&
10161 (Info.getStdAllocatorCaller("allocate") ||
10162 IsDeclSourceLocationCurrent(Info.CurrentCall->Callee) ||
10163 Info.getLangOpts().CPlusPlus26)) {
10164 // Permitted.
10165 } else {
10166 if (SubExpr->getType()->isVoidPointerType() &&
10167 Info.getLangOpts().CPlusPlus) {
10168 if (HasValidResult)
10169 CCEDiag(E, diag::note_constexpr_invalid_void_star_cast)
10170 << SubExpr->getType() << Info.getLangOpts().CPlusPlus26
10171 << Result.Designator.getType(Info.Ctx).getCanonicalType()
10172 << E->getType()->getPointeeType();
10173 else
10174 CCEDiag(E, diag::note_constexpr_invalid_cast)
10175 << diag::ConstexprInvalidCastKind::CastFrom
10176 << SubExpr->getType();
10177 } else
10178 CCEDiag(E, diag::note_constexpr_invalid_cast)
10179 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
10180 << Info.Ctx.getLangOpts().CPlusPlus;
10181 Result.Designator.setInvalid();
10182 }
10183 }
10184 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
10185 ZeroInitialization(E);
10186 return true;
10187
10188 case CK_DerivedToBase:
10189 case CK_UncheckedDerivedToBase:
10190 if (!evaluatePointer(E->getSubExpr(), Result))
10191 return false;
10192 if (!Result.Base && Result.Offset.isZero())
10193 return true;
10194
10195 // Now figure out the necessary offset to add to the base LV to get from
10196 // the derived class to the base class.
10197 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
10198 castAs<PointerType>()->getPointeeType(),
10199 Result);
10200
10201 case CK_BaseToDerived:
10202 if (!Visit(E->getSubExpr()))
10203 return false;
10204 if (!Result.Base && Result.Offset.isZero())
10205 return true;
10206 return HandleBaseToDerivedCast(Info, E, Result);
10207
10208 case CK_Dynamic:
10209 if (!Visit(E->getSubExpr()))
10210 return false;
10211 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
10212
10213 case CK_NullToPointer:
10214 VisitIgnoredValue(E->getSubExpr());
10215 return ZeroInitialization(E);
10216
10217 case CK_IntegralToPointer: {
10218 CCEDiag(E, diag::note_constexpr_invalid_cast)
10219 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
10220 << Info.Ctx.getLangOpts().CPlusPlus;
10221
10222 APValue Value;
10223 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
10224 break;
10225
10226 if (Value.isInt()) {
10227 unsigned Size = Info.Ctx.getTypeSize(E->getType());
10228 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
10229 if (N == Info.Ctx.getTargetNullPointerValue(E->getType())) {
10230 Result.setNull(Info.Ctx, E->getType());
10231 } else {
10232 Result.Base = (Expr *)nullptr;
10233 Result.InvalidBase = false;
10234 Result.Offset = CharUnits::fromQuantity(N);
10235 Result.Designator.setInvalid();
10236 Result.IsNullPtr = false;
10237 }
10238 return true;
10239 } else {
10240 // In rare instances, the value isn't an lvalue.
10241 // For example, when the value is the difference between the addresses of
10242 // two labels. We reject that as a constant expression because we can't
10243 // compute a valid offset to convert into a pointer.
10244 if (!Value.isLValue())
10245 return false;
10246
10247 // Cast is of an lvalue, no need to change value.
10248 Result.setFrom(Info.Ctx, Value);
10249 return true;
10250 }
10251 }
10252
10253 case CK_ArrayToPointerDecay: {
10254 if (SubExpr->isGLValue()) {
10255 if (!evaluateLValue(SubExpr, Result))
10256 return false;
10257 } else {
10258 APValue &Value = Info.CurrentCall->createTemporary(
10259 SubExpr, SubExpr->getType(), ScopeKind::FullExpression, Result);
10260 if (!EvaluateInPlace(Value, Info, Result, SubExpr))
10261 return false;
10262 }
10263 // The result is a pointer to the first element of the array.
10264 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
10265 if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
10266 Result.addArray(Info, E, CAT);
10267 else
10268 Result.addUnsizedArray(Info, E, AT->getElementType());
10269 return true;
10270 }
10271
10272 case CK_FunctionToPointerDecay:
10273 return evaluateLValue(SubExpr, Result);
10274
10275 case CK_LValueToRValue: {
10276 LValue LVal;
10277 if (!evaluateLValue(E->getSubExpr(), LVal))
10278 return false;
10279
10280 APValue RVal;
10281 // Note, we use the subexpression's type in order to retain cv-qualifiers.
10282 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
10283 LVal, RVal))
10284 return InvalidBaseOK &&
10285 evaluateLValueAsAllocSize(Info, LVal.Base, Result);
10286 return Success(RVal, E);
10287 }
10288 }
10289
10290 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10291 }
10292
10293 static CharUnits GetAlignOfType(const ASTContext &Ctx, QualType T,
10294 UnaryExprOrTypeTrait ExprKind) {
10295 // C++ [expr.alignof]p3:
10296 // When alignof is applied to a reference type, the result is the
10297 // alignment of the referenced type.
10298 T = T.getNonReferenceType();
10299
10300 if (T.getQualifiers().hasUnaligned())
10301 return CharUnits::One();
10302
10303 const bool AlignOfReturnsPreferred =
10304 Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
10305
10306 // __alignof is defined to return the preferred alignment.
10307 // Before 8, clang returned the preferred alignment for alignof and _Alignof
10308 // as well.
10309 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
10310 return Ctx.toCharUnitsFromBits(Ctx.getPreferredTypeAlign(T.getTypePtr()));
10311 // alignof and _Alignof are defined to return the ABI alignment.
10312 else if (ExprKind == UETT_AlignOf)
10313 return Ctx.getTypeAlignInChars(T.getTypePtr());
10314 else
10315 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
10316 }
10317
10318 CharUnits GetAlignOfExpr(const ASTContext &Ctx, const Expr *E,
10319 UnaryExprOrTypeTrait ExprKind) {
10320 E = E->IgnoreParens();
10321
10322 // The kinds of expressions that we have special-case logic here for
10323 // should be kept up to date with the special checks for those
10324 // expressions in Sema.
10325
10326 // alignof decl is always accepted, even if it doesn't make sense: we default
10327 // to 1 in those cases.
10328 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
10329 return Ctx.getDeclAlign(DRE->getDecl(),
10330 /*RefAsPointee*/ true);
10331
10332 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
10333 return Ctx.getDeclAlign(ME->getMemberDecl(),
10334 /*RefAsPointee*/ true);
10335
10336 return GetAlignOfType(Ctx, E->getType(), ExprKind);
10337 }
10338
10339 static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) {
10340 if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>())
10341 return Info.Ctx.getDeclAlign(VD);
10342 if (const auto *E = Value.Base.dyn_cast<const Expr *>())
10343 return GetAlignOfExpr(Info.Ctx, E, UETT_AlignOf);
10344 return GetAlignOfType(Info.Ctx, Value.Base.getTypeInfoType(), UETT_AlignOf);
10345 }
10346
10347 /// Evaluate the value of the alignment argument to __builtin_align_{up,down},
10348 /// __builtin_is_aligned and __builtin_assume_aligned.
10349 static bool getAlignmentArgument(const Expr *E, QualType ForType,
10350 EvalInfo &Info, APSInt &Alignment) {
10351 if (!EvaluateInteger(E, Alignment, Info))
10352 return false;
10353 if (Alignment < 0 || !Alignment.isPowerOf2()) {
10354 Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment;
10355 return false;
10356 }
10357 unsigned SrcWidth = Info.Ctx.getIntWidth(ForType);
10358 APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1));
10359 if (APSInt::compareValues(Alignment, MaxValue) > 0) {
10360 Info.FFDiag(E, diag::note_constexpr_alignment_too_big)
10361 << MaxValue << ForType << Alignment;
10362 return false;
10363 }
10364 // Ensure both alignment and source value have the same bit width so that we
10365 // don't assert when computing the resulting value.
10366 APSInt ExtAlignment =
10367 APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true);
10368 assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 &&
10369 "Alignment should not be changed by ext/trunc");
10370 Alignment = ExtAlignment;
10371 assert(Alignment.getBitWidth() == SrcWidth);
10372 return true;
10373 }
10374
10375 // To be clear: this happily visits unsupported builtins. Better name welcomed.
10376 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
10377 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
10378 return true;
10379
10380 if (!(InvalidBaseOK && E->getCalleeAllocSizeAttr()))
10381 return false;
10382
10383 Result.setInvalid(E);
10384 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
10385 Result.addUnsizedArray(Info, E, PointeeTy);
10386 return true;
10387 }
10388
10389 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
10390 if (!IsConstantEvaluatedBuiltinCall(E))
10391 return visitNonBuiltinCallExpr(E);
10392 return VisitBuiltinCallExpr(E, E->getBuiltinCallee());
10393 }
10394
10395 // Determine if T is a character type for which we guarantee that
10396 // sizeof(T) == 1.
10397 static bool isOneByteCharacterType(QualType T) {
10398 return T->isCharType() || T->isChar8Type();
10399 }
10400
10401 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
10402 unsigned BuiltinOp) {
10403 if (IsOpaqueConstantCall(E))
10404 return Success(E);
10405
10406 switch (BuiltinOp) {
10407 case Builtin::BIaddressof:
10408 case Builtin::BI__addressof:
10409 case Builtin::BI__builtin_addressof:
10410 return evaluateLValue(E->getArg(0), Result);
10411 case Builtin::BI__builtin_assume_aligned: {
10412 // We need to be very careful here because: if the pointer does not have the
10413 // asserted alignment, then the behavior is undefined, and undefined
10414 // behavior is non-constant.
10415 if (!evaluatePointer(E->getArg(0), Result))
10416 return false;
10417
10418 LValue OffsetResult(Result);
10419 APSInt Alignment;
10420 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
10421 Alignment))
10422 return false;
10423 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
10424
10425 if (E->getNumArgs() > 2) {
10426 APSInt Offset;
10427 if (!EvaluateInteger(E->getArg(2), Offset, Info))
10428 return false;
10429
10430 int64_t AdditionalOffset = -Offset.getZExtValue();
10431 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
10432 }
10433
10434 // If there is a base object, then it must have the correct alignment.
10435 if (OffsetResult.Base) {
10436 CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult);
10437
10438 if (BaseAlignment < Align) {
10439 Result.Designator.setInvalid();
10440 CCEDiag(E->getArg(0), diag::note_constexpr_baa_insufficient_alignment)
10441 << 0 << BaseAlignment.getQuantity() << Align.getQuantity();
10442 return false;
10443 }
10444 }
10445
10446 // The offset must also have the correct alignment.
10447 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
10448 Result.Designator.setInvalid();
10449
10450 (OffsetResult.Base
10451 ? CCEDiag(E->getArg(0),
10452 diag::note_constexpr_baa_insufficient_alignment)
10453 << 1
10454 : CCEDiag(E->getArg(0),
10455 diag::note_constexpr_baa_value_insufficient_alignment))
10456 << OffsetResult.Offset.getQuantity() << Align.getQuantity();
10457 return false;
10458 }
10459
10460 return true;
10461 }
10462 case Builtin::BI__builtin_align_up:
10463 case Builtin::BI__builtin_align_down: {
10464 if (!evaluatePointer(E->getArg(0), Result))
10465 return false;
10466 APSInt Alignment;
10467 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
10468 Alignment))
10469 return false;
10470 CharUnits BaseAlignment = getBaseAlignment(Info, Result);
10471 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset);
10472 // For align_up/align_down, we can return the same value if the alignment
10473 // is known to be greater or equal to the requested value.
10474 if (PtrAlign.getQuantity() >= Alignment)
10475 return true;
10476
10477 // The alignment could be greater than the minimum at run-time, so we cannot
10478 // infer much about the resulting pointer value. One case is possible:
10479 // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we
10480 // can infer the correct index if the requested alignment is smaller than
10481 // the base alignment so we can perform the computation on the offset.
10482 if (BaseAlignment.getQuantity() >= Alignment) {
10483 assert(Alignment.getBitWidth() <= 64 &&
10484 "Cannot handle > 64-bit address-space");
10485 uint64_t Alignment64 = Alignment.getZExtValue();
10486 CharUnits NewOffset = CharUnits::fromQuantity(
10487 BuiltinOp == Builtin::BI__builtin_align_down
10488 ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64)
10489 : llvm::alignTo(Result.Offset.getQuantity(), Alignment64));
10490 Result.adjustOffset(NewOffset - Result.Offset);
10491 // TODO: diagnose out-of-bounds values/only allow for arrays?
10492 return true;
10493 }
10494 // Otherwise, we cannot constant-evaluate the result.
10495 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust)
10496 << Alignment;
10497 return false;
10498 }
10499 case Builtin::BI__builtin_operator_new:
10500 return HandleOperatorNewCall(Info, E, Result);
10501 case Builtin::BI__builtin_launder:
10502 return evaluatePointer(E->getArg(0), Result);
10503 case Builtin::BIstrchr:
10504 case Builtin::BIwcschr:
10505 case Builtin::BImemchr:
10506 case Builtin::BIwmemchr:
10507 if (Info.getLangOpts().CPlusPlus11)
10508 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
10509 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
10510 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
10511 else
10512 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
10513 [[fallthrough]];
10514 case Builtin::BI__builtin_strchr:
10515 case Builtin::BI__builtin_wcschr:
10516 case Builtin::BI__builtin_memchr:
10517 case Builtin::BI__builtin_char_memchr:
10518 case Builtin::BI__builtin_wmemchr: {
10519 if (!Visit(E->getArg(0)))
10520 return false;
10521 APSInt Desired;
10522 if (!EvaluateInteger(E->getArg(1), Desired, Info))
10523 return false;
10524 uint64_t MaxLength = uint64_t(-1);
10525 if (BuiltinOp != Builtin::BIstrchr &&
10526 BuiltinOp != Builtin::BIwcschr &&
10527 BuiltinOp != Builtin::BI__builtin_strchr &&
10528 BuiltinOp != Builtin::BI__builtin_wcschr) {
10529 APSInt N;
10530 if (!EvaluateInteger(E->getArg(2), N, Info))
10531 return false;
10532 MaxLength = N.getZExtValue();
10533 }
10534 // We cannot find the value if there are no candidates to match against.
10535 if (MaxLength == 0u)
10536 return ZeroInitialization(E);
10537 if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
10538 Result.Designator.Invalid)
10539 return false;
10540 QualType CharTy = Result.Designator.getType(Info.Ctx);
10541 bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
10542 BuiltinOp == Builtin::BI__builtin_memchr;
10543 assert(IsRawByte ||
10544 Info.Ctx.hasSameUnqualifiedType(
10545 CharTy, E->getArg(0)->getType()->getPointeeType()));
10546 // Pointers to const void may point to objects of incomplete type.
10547 if (IsRawByte && CharTy->isIncompleteType()) {
10548 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
10549 return false;
10550 }
10551 // Give up on byte-oriented matching against multibyte elements.
10552 // FIXME: We can compare the bytes in the correct order.
10553 if (IsRawByte && !isOneByteCharacterType(CharTy)) {
10554 Info.FFDiag(E, diag::note_constexpr_memchr_unsupported)
10555 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp) << CharTy;
10556 return false;
10557 }
10558 // Figure out what value we're actually looking for (after converting to
10559 // the corresponding unsigned type if necessary).
10560 uint64_t DesiredVal;
10561 bool StopAtNull = false;
10562 switch (BuiltinOp) {
10563 case Builtin::BIstrchr:
10564 case Builtin::BI__builtin_strchr:
10565 // strchr compares directly to the passed integer, and therefore
10566 // always fails if given an int that is not a char.
10567 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
10568 E->getArg(1)->getType(),
10569 Desired),
10570 Desired))
10571 return ZeroInitialization(E);
10572 StopAtNull = true;
10573 [[fallthrough]];
10574 case Builtin::BImemchr:
10575 case Builtin::BI__builtin_memchr:
10576 case Builtin::BI__builtin_char_memchr:
10577 // memchr compares by converting both sides to unsigned char. That's also
10578 // correct for strchr if we get this far (to cope with plain char being
10579 // unsigned in the strchr case).
10580 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
10581 break;
10582
10583 case Builtin::BIwcschr:
10584 case Builtin::BI__builtin_wcschr:
10585 StopAtNull = true;
10586 [[fallthrough]];
10587 case Builtin::BIwmemchr:
10588 case Builtin::BI__builtin_wmemchr:
10589 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
10590 DesiredVal = Desired.getZExtValue();
10591 break;
10592 }
10593
10594 for (; MaxLength; --MaxLength) {
10595 APValue Char;
10596 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
10597 !Char.isInt())
10598 return false;
10599 if (Char.getInt().getZExtValue() == DesiredVal)
10600 return true;
10601 if (StopAtNull && !Char.getInt())
10602 break;
10603 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
10604 return false;
10605 }
10606 // Not found: return nullptr.
10607 return ZeroInitialization(E);
10608 }
10609
10610 case Builtin::BImemcpy:
10611 case Builtin::BImemmove:
10612 case Builtin::BIwmemcpy:
10613 case Builtin::BIwmemmove:
10614 if (Info.getLangOpts().CPlusPlus11)
10615 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
10616 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
10617 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
10618 else
10619 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
10620 [[fallthrough]];
10621 case Builtin::BI__builtin_memcpy:
10622 case Builtin::BI__builtin_memmove:
10623 case Builtin::BI__builtin_wmemcpy:
10624 case Builtin::BI__builtin_wmemmove: {
10625 bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
10626 BuiltinOp == Builtin::BIwmemmove ||
10627 BuiltinOp == Builtin::BI__builtin_wmemcpy ||
10628 BuiltinOp == Builtin::BI__builtin_wmemmove;
10629 bool Move = BuiltinOp == Builtin::BImemmove ||
10630 BuiltinOp == Builtin::BIwmemmove ||
10631 BuiltinOp == Builtin::BI__builtin_memmove ||
10632 BuiltinOp == Builtin::BI__builtin_wmemmove;
10633
10634 // The result of mem* is the first argument.
10635 if (!Visit(E->getArg(0)))
10636 return false;
10637 LValue Dest = Result;
10638
10639 LValue Src;
10640 if (!EvaluatePointer(E->getArg(1), Src, Info))
10641 return false;
10642
10643 APSInt N;
10644 if (!EvaluateInteger(E->getArg(2), N, Info))
10645 return false;
10646 assert(!N.isSigned() && "memcpy and friends take an unsigned size");
10647
10648 // If the size is zero, we treat this as always being a valid no-op.
10649 // (Even if one of the src and dest pointers is null.)
10650 if (!N)
10651 return true;
10652
10653 // Otherwise, if either of the operands is null, we can't proceed. Don't
10654 // try to determine the type of the copied objects, because there aren't
10655 // any.
10656 if (!Src.Base || !Dest.Base) {
10657 APValue Val;
10658 (!Src.Base ? Src : Dest).moveInto(Val);
10659 Info.FFDiag(E, diag::note_constexpr_memcpy_null)
10660 << Move << WChar << !!Src.Base
10661 << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
10662 return false;
10663 }
10664 if (Src.Designator.Invalid || Dest.Designator.Invalid)
10665 return false;
10666
10667 // We require that Src and Dest are both pointers to arrays of
10668 // trivially-copyable type. (For the wide version, the designator will be
10669 // invalid if the designated object is not a wchar_t.)
10670 QualType T = Dest.Designator.getType(Info.Ctx);
10671 QualType SrcT = Src.Designator.getType(Info.Ctx);
10672 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
10673 // FIXME: Consider using our bit_cast implementation to support this.
10674 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
10675 return false;
10676 }
10677 if (T->isIncompleteType()) {
10678 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
10679 return false;
10680 }
10681 if (!T.isTriviallyCopyableType(Info.Ctx)) {
10682 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
10683 return false;
10684 }
10685
10686 // Figure out how many T's we're copying.
10687 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
10688 if (TSize == 0)
10689 return false;
10690 if (!WChar) {
10691 uint64_t Remainder;
10692 llvm::APInt OrigN = N;
10693 llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
10694 if (Remainder) {
10695 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
10696 << Move << WChar << 0 << T << toString(OrigN, 10, /*Signed*/false)
10697 << (unsigned)TSize;
10698 return false;
10699 }
10700 }
10701
10702 // Check that the copying will remain within the arrays, just so that we
10703 // can give a more meaningful diagnostic. This implicitly also checks that
10704 // N fits into 64 bits.
10705 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
10706 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
10707 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
10708 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
10709 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
10710 << toString(N, 10, /*Signed*/false);
10711 return false;
10712 }
10713 uint64_t NElems = N.getZExtValue();
10714 uint64_t NBytes = NElems * TSize;
10715
10716 // Check for overlap.
10717 int Direction = 1;
10718 if (HasSameBase(Src, Dest)) {
10719 uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
10720 uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
10721 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
10722 // Dest is inside the source region.
10723 if (!Move) {
10724 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
10725 return false;
10726 }
10727 // For memmove and friends, copy backwards.
10728 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
10729 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
10730 return false;
10731 Direction = -1;
10732 } else if (!Move && SrcOffset >= DestOffset &&
10733 SrcOffset - DestOffset < NBytes) {
10734 // Src is inside the destination region for memcpy: invalid.
10735 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
10736 return false;
10737 }
10738 }
10739
10740 while (true) {
10741 APValue Val;
10742 // FIXME: Set WantObjectRepresentation to true if we're copying a
10743 // char-like type?
10744 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
10745 !handleAssignment(Info, E, Dest, T, Val))
10746 return false;
10747 // Do not iterate past the last element; if we're copying backwards, that
10748 // might take us off the start of the array.
10749 if (--NElems == 0)
10750 return true;
10751 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
10752 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
10753 return false;
10754 }
10755 }
10756
10757 default:
10758 return false;
10759 }
10760 }
10761
10762 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
10763 APValue &Result, const InitListExpr *ILE,
10764 QualType AllocType);
10765 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
10766 APValue &Result,
10767 const CXXConstructExpr *CCE,
10768 QualType AllocType);
10769
10770 bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) {
10771 if (!Info.getLangOpts().CPlusPlus20)
10772 Info.CCEDiag(E, diag::note_constexpr_new);
10773
10774 // We cannot speculatively evaluate a delete expression.
10775 if (Info.SpeculativeEvaluationDepth)
10776 return false;
10777
10778 FunctionDecl *OperatorNew = E->getOperatorNew();
10779 QualType AllocType = E->getAllocatedType();
10780 QualType TargetType = AllocType;
10781
10782 bool IsNothrow = false;
10783 bool IsPlacement = false;
10784
10785 if (E->getNumPlacementArgs() == 1 &&
10786 E->getPlacementArg(0)->getType()->isNothrowT()) {
10787 // The only new-placement list we support is of the form (std::nothrow).
10788 //
10789 // FIXME: There is no restriction on this, but it's not clear that any
10790 // other form makes any sense. We get here for cases such as:
10791 //
10792 // new (std::align_val_t{N}) X(int)
10793 //
10794 // (which should presumably be valid only if N is a multiple of
10795 // alignof(int), and in any case can't be deallocated unless N is
10796 // alignof(X) and X has new-extended alignment).
10797 LValue Nothrow;
10798 if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info))
10799 return false;
10800 IsNothrow = true;
10801 } else if (OperatorNew->isReservedGlobalPlacementOperator()) {
10802 if (Info.CurrentCall->isStdFunction() || Info.getLangOpts().CPlusPlus26 ||
10803 (Info.CurrentCall->CanEvalMSConstexpr &&
10804 OperatorNew->hasAttr<MSConstexprAttr>())) {
10805 if (!EvaluatePointer(E->getPlacementArg(0), Result, Info))
10806 return false;
10807 if (Result.Designator.Invalid)
10808 return false;
10809 TargetType = E->getPlacementArg(0)->getType();
10810 IsPlacement = true;
10811 } else {
10812 Info.FFDiag(E, diag::note_constexpr_new_placement)
10813 << /*C++26 feature*/ 1 << E->getSourceRange();
10814 return false;
10815 }
10816 } else if (E->getNumPlacementArgs()) {
10817 Info.FFDiag(E, diag::note_constexpr_new_placement)
10818 << /*Unsupported*/ 0 << E->getSourceRange();
10819 return false;
10820 } else if (!OperatorNew
10821 ->isUsableAsGlobalAllocationFunctionInConstantEvaluation()) {
10822 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
10823 << isa<CXXMethodDecl>(OperatorNew) << OperatorNew;
10824 return false;
10825 }
10826
10827 const Expr *Init = E->getInitializer();
10828 const InitListExpr *ResizedArrayILE = nullptr;
10829 const CXXConstructExpr *ResizedArrayCCE = nullptr;
10830 bool ValueInit = false;
10831
10832 if (std::optional<const Expr *> ArraySize = E->getArraySize()) {
10833 const Expr *Stripped = *ArraySize;
10834 for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
10835 Stripped = ICE->getSubExpr())
10836 if (ICE->getCastKind() != CK_NoOp &&
10837 ICE->getCastKind() != CK_IntegralCast)
10838 break;
10839
10840 llvm::APSInt ArrayBound;
10841 if (!EvaluateInteger(Stripped, ArrayBound, Info))
10842 return false;
10843
10844 // C++ [expr.new]p9:
10845 // The expression is erroneous if:
10846 // -- [...] its value before converting to size_t [or] applying the
10847 // second standard conversion sequence is less than zero
10848 if (ArrayBound.isSigned() && ArrayBound.isNegative()) {
10849 if (IsNothrow)
10850 return ZeroInitialization(E);
10851
10852 Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative)
10853 << ArrayBound << (*ArraySize)->getSourceRange();
10854 return false;
10855 }
10856
10857 // -- its value is such that the size of the allocated object would
10858 // exceed the implementation-defined limit
10859 if (!Info.CheckArraySize(ArraySize.value()->getExprLoc(),
10860 ConstantArrayType::getNumAddressingBits(
10861 Info.Ctx, AllocType, ArrayBound),
10862 ArrayBound.getZExtValue(), /*Diag=*/!IsNothrow)) {
10863 if (IsNothrow)
10864 return ZeroInitialization(E);
10865 return false;
10866 }
10867
10868 // -- the new-initializer is a braced-init-list and the number of
10869 // array elements for which initializers are provided [...]
10870 // exceeds the number of elements to initialize
10871 if (!Init) {
10872 // No initialization is performed.
10873 } else if (isa<CXXScalarValueInitExpr>(Init) ||
10874 isa<ImplicitValueInitExpr>(Init)) {
10875 ValueInit = true;
10876 } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) {
10877 ResizedArrayCCE = CCE;
10878 } else {
10879 auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType());
10880 assert(CAT && "unexpected type for array initializer");
10881
10882 unsigned Bits =
10883 std::max(CAT->getSizeBitWidth(), ArrayBound.getBitWidth());
10884 llvm::APInt InitBound = CAT->getSize().zext(Bits);
10885 llvm::APInt AllocBound = ArrayBound.zext(Bits);
10886 if (InitBound.ugt(AllocBound)) {
10887 if (IsNothrow)
10888 return ZeroInitialization(E);
10889
10890 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small)
10891 << toString(AllocBound, 10, /*Signed=*/false)
10892 << toString(InitBound, 10, /*Signed=*/false)
10893 << (*ArraySize)->getSourceRange();
10894 return false;
10895 }
10896
10897 // If the sizes differ, we must have an initializer list, and we need
10898 // special handling for this case when we initialize.
10899 if (InitBound != AllocBound)
10900 ResizedArrayILE = cast<InitListExpr>(Init);
10901 }
10902
10903 AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr,
10904 ArraySizeModifier::Normal, 0);
10905 } else {
10906 assert(!AllocType->isArrayType() &&
10907 "array allocation with non-array new");
10908 }
10909
10910 APValue *Val;
10911 if (IsPlacement) {
10912 AccessKinds AK = AK_Construct;
10913 struct FindObjectHandler {
10914 EvalInfo &Info;
10915 const Expr *E;
10916 QualType AllocType;
10917 const AccessKinds AccessKind;
10918 APValue *Value;
10919
10920 typedef bool result_type;
10921 bool failed() { return false; }
10922 bool checkConst(QualType QT) {
10923 if (QT.isConstQualified()) {
10924 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
10925 return false;
10926 }
10927 return true;
10928 }
10929 bool found(APValue &Subobj, QualType SubobjType) {
10930 if (!checkConst(SubobjType))
10931 return false;
10932 // FIXME: Reject the cases where [basic.life]p8 would not permit the
10933 // old name of the object to be used to name the new object.
10934 unsigned SubobjectSize = 1;
10935 unsigned AllocSize = 1;
10936 if (auto *CAT = dyn_cast<ConstantArrayType>(AllocType))
10937 AllocSize = CAT->getZExtSize();
10938 if (auto *CAT = dyn_cast<ConstantArrayType>(SubobjType))
10939 SubobjectSize = CAT->getZExtSize();
10940 if (SubobjectSize < AllocSize ||
10941 !Info.Ctx.hasSimilarType(Info.Ctx.getBaseElementType(SubobjType),
10942 Info.Ctx.getBaseElementType(AllocType))) {
10943 Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type)
10944 << SubobjType << AllocType;
10945 return false;
10946 }
10947 Value = &Subobj;
10948 return true;
10949 }
10950 bool found(APSInt &Value, QualType SubobjType) {
10951 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
10952 return false;
10953 }
10954 bool found(APFloat &Value, QualType SubobjType) {
10955 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
10956 return false;
10957 }
10958 } Handler = {Info, E, AllocType, AK, nullptr};
10959
10960 CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType);
10961 if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler))
10962 return false;
10963
10964 Val = Handler.Value;
10965
10966 // [basic.life]p1:
10967 // The lifetime of an object o of type T ends when [...] the storage
10968 // which the object occupies is [...] reused by an object that is not
10969 // nested within o (6.6.2).
10970 *Val = APValue();
10971 } else {
10972 // Perform the allocation and obtain a pointer to the resulting object.
10973 Val = Info.createHeapAlloc(E, AllocType, Result);
10974 if (!Val)
10975 return false;
10976 }
10977
10978 if (ValueInit) {
10979 ImplicitValueInitExpr VIE(AllocType);
10980 if (!EvaluateInPlace(*Val, Info, Result, &VIE))
10981 return false;
10982 } else if (ResizedArrayILE) {
10983 if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE,
10984 AllocType))
10985 return false;
10986 } else if (ResizedArrayCCE) {
10987 if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE,
10988 AllocType))
10989 return false;
10990 } else if (Init) {
10991 if (!EvaluateInPlace(*Val, Info, Result, Init))
10992 return false;
10993 } else if (!handleDefaultInitValue(AllocType, *Val)) {
10994 return false;
10995 }
10996
10997 // Array new returns a pointer to the first element, not a pointer to the
10998 // array.
10999 if (auto *AT = AllocType->getAsArrayTypeUnsafe())
11000 Result.addArray(Info, E, cast<ConstantArrayType>(AT));
11001
11002 return true;
11003 }
11004 //===----------------------------------------------------------------------===//
11005 // Member Pointer Evaluation
11006 //===----------------------------------------------------------------------===//
11007
11008 namespace {
11009 class MemberPointerExprEvaluator
11010 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
11011 MemberPtr &Result;
11012
11013 bool Success(const ValueDecl *D) {
11014 Result = MemberPtr(D);
11015 return true;
11016 }
11017 public:
11018
11019 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
11020 : ExprEvaluatorBaseTy(Info), Result(Result) {}
11021
11022 bool Success(const APValue &V, const Expr *E) {
11023 Result.setFrom(V);
11024 return true;
11025 }
11026 bool ZeroInitialization(const Expr *E) {
11027 return Success((const ValueDecl*)nullptr);
11028 }
11029
11030 bool VisitCastExpr(const CastExpr *E);
11031 bool VisitUnaryAddrOf(const UnaryOperator *E);
11032 };
11033 } // end anonymous namespace
11034
11035 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
11036 EvalInfo &Info) {
11037 assert(!E->isValueDependent());
11038 assert(E->isPRValue() && E->getType()->isMemberPointerType());
11039 return MemberPointerExprEvaluator(Info, Result).Visit(E);
11040 }
11041
11042 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
11043 switch (E->getCastKind()) {
11044 default:
11045 return ExprEvaluatorBaseTy::VisitCastExpr(E);
11046
11047 case CK_NullToMemberPointer:
11048 VisitIgnoredValue(E->getSubExpr());
11049 return ZeroInitialization(E);
11050
11051 case CK_BaseToDerivedMemberPointer: {
11052 if (!Visit(E->getSubExpr()))
11053 return false;
11054 if (E->path_empty())
11055 return true;
11056 // Base-to-derived member pointer casts store the path in derived-to-base
11057 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
11058 // the wrong end of the derived->base arc, so stagger the path by one class.
11059 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
11060 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
11061 PathI != PathE; ++PathI) {
11062 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
11063 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
11064 if (!Result.castToDerived(Derived))
11065 return Error(E);
11066 }
11067 if (!Result.castToDerived(E->getType()
11068 ->castAs<MemberPointerType>()
11069 ->getMostRecentCXXRecordDecl()))
11070 return Error(E);
11071 return true;
11072 }
11073
11074 case CK_DerivedToBaseMemberPointer:
11075 if (!Visit(E->getSubExpr()))
11076 return false;
11077 for (CastExpr::path_const_iterator PathI = E->path_begin(),
11078 PathE = E->path_end(); PathI != PathE; ++PathI) {
11079 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
11080 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
11081 if (!Result.castToBase(Base))
11082 return Error(E);
11083 }
11084 return true;
11085 }
11086 }
11087
11088 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
11089 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
11090 // member can be formed.
11091 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
11092 }
11093
11094 //===----------------------------------------------------------------------===//
11095 // Record Evaluation
11096 //===----------------------------------------------------------------------===//
11097
11098 namespace {
11099 class RecordExprEvaluator
11100 : public ExprEvaluatorBase<RecordExprEvaluator> {
11101 const LValue &This;
11102 APValue &Result;
11103 public:
11104
11105 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
11106 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
11107
11108 bool Success(const APValue &V, const Expr *E) {
11109 Result = V;
11110 return true;
11111 }
11112 bool ZeroInitialization(const Expr *E) {
11113 return ZeroInitialization(E, E->getType());
11114 }
11115 bool ZeroInitialization(const Expr *E, QualType T);
11116
11117 bool VisitCallExpr(const CallExpr *E) {
11118 return handleCallExpr(E, Result, &This);
11119 }
11120 bool VisitCastExpr(const CastExpr *E);
11121 bool VisitInitListExpr(const InitListExpr *E);
11122 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
11123 return VisitCXXConstructExpr(E, E->getType());
11124 }
11125 bool VisitLambdaExpr(const LambdaExpr *E);
11126 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
11127 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
11128 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
11129 bool VisitBinCmp(const BinaryOperator *E);
11130 bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E);
11131 bool VisitCXXParenListOrInitListExpr(const Expr *ExprToVisit,
11132 ArrayRef<Expr *> Args);
11133 };
11134 }
11135
11136 /// Perform zero-initialization on an object of non-union class type.
11137 /// C++11 [dcl.init]p5:
11138 /// To zero-initialize an object or reference of type T means:
11139 /// [...]
11140 /// -- if T is a (possibly cv-qualified) non-union class type,
11141 /// each non-static data member and each base-class subobject is
11142 /// zero-initialized
11143 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
11144 const RecordDecl *RD,
11145 const LValue &This, APValue &Result) {
11146 assert(!RD->isUnion() && "Expected non-union class type");
11147 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
11148 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
11149 RD->getNumFields());
11150
11151 if (RD->isInvalidDecl()) return false;
11152 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
11153
11154 if (CD) {
11155 unsigned Index = 0;
11156 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
11157 End = CD->bases_end(); I != End; ++I, ++Index) {
11158 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
11159 LValue Subobject = This;
11160 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
11161 return false;
11162 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
11163 Result.getStructBase(Index)))
11164 return false;
11165 }
11166 }
11167
11168 for (const auto *I : RD->fields()) {
11169 // -- if T is a reference type, no initialization is performed.
11170 if (I->isUnnamedBitField() || I->getType()->isReferenceType())
11171 continue;
11172
11173 LValue Subobject = This;
11174 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
11175 return false;
11176
11177 ImplicitValueInitExpr VIE(I->getType());
11178 if (!EvaluateInPlace(
11179 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
11180 return false;
11181 }
11182
11183 return true;
11184 }
11185
11186 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
11187 const auto *RD = T->castAsRecordDecl();
11188 if (RD->isInvalidDecl()) return false;
11189 if (RD->isUnion()) {
11190 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
11191 // object's first non-static named data member is zero-initialized
11192 RecordDecl::field_iterator I = RD->field_begin();
11193 while (I != RD->field_end() && (*I)->isUnnamedBitField())
11194 ++I;
11195 if (I == RD->field_end()) {
11196 Result = APValue((const FieldDecl*)nullptr);
11197 return true;
11198 }
11199
11200 LValue Subobject = This;
11201 if (!HandleLValueMember(Info, E, Subobject, *I))
11202 return false;
11203 Result = APValue(*I);
11204 ImplicitValueInitExpr VIE(I->getType());
11205 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
11206 }
11207
11208 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
11209 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
11210 return false;
11211 }
11212
11213 return HandleClassZeroInitialization(Info, E, RD, This, Result);
11214 }
11215
11216 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
11217 switch (E->getCastKind()) {
11218 default:
11219 return ExprEvaluatorBaseTy::VisitCastExpr(E);
11220
11221 case CK_ConstructorConversion:
11222 return Visit(E->getSubExpr());
11223
11224 case CK_DerivedToBase:
11225 case CK_UncheckedDerivedToBase: {
11226 APValue DerivedObject;
11227 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
11228 return false;
11229 if (!DerivedObject.isStruct())
11230 return Error(E->getSubExpr());
11231
11232 // Derived-to-base rvalue conversion: just slice off the derived part.
11233 APValue *Value = &DerivedObject;
11234 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
11235 for (CastExpr::path_const_iterator PathI = E->path_begin(),
11236 PathE = E->path_end(); PathI != PathE; ++PathI) {
11237 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
11238 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
11239 Value = &Value->getStructBase(getBaseIndex(RD, Base));
11240 RD = Base;
11241 }
11242 Result = *Value;
11243 return true;
11244 }
11245 case CK_HLSLAggregateSplatCast: {
11246 APValue Val;
11247 QualType ValTy;
11248
11249 if (!hlslAggSplatHelper(Info, E->getSubExpr(), Val, ValTy))
11250 return false;
11251
11252 unsigned NEls = elementwiseSize(Info, E->getType());
11253 // splat our Val
11254 SmallVector<APValue> SplatEls(NEls, Val);
11255 SmallVector<QualType> SplatType(NEls, ValTy);
11256
11257 // cast the elements and construct our struct result
11258 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
11259 if (!constructAggregate(Info, FPO, E, Result, E->getType(), SplatEls,
11260 SplatType))
11261 return false;
11262
11263 return true;
11264 }
11265 case CK_HLSLElementwiseCast: {
11266 SmallVector<APValue> SrcEls;
11267 SmallVector<QualType> SrcTypes;
11268
11269 if (!hlslElementwiseCastHelper(Info, E->getSubExpr(), E->getType(), SrcEls,
11270 SrcTypes))
11271 return false;
11272
11273 // cast the elements and construct our struct result
11274 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
11275 if (!constructAggregate(Info, FPO, E, Result, E->getType(), SrcEls,
11276 SrcTypes))
11277 return false;
11278
11279 return true;
11280 }
11281 }
11282 }
11283
11284 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
11285 if (E->isTransparent())
11286 return Visit(E->getInit(0));
11287 return VisitCXXParenListOrInitListExpr(E, E->inits());
11288 }
11289
11290 bool RecordExprEvaluator::VisitCXXParenListOrInitListExpr(
11291 const Expr *ExprToVisit, ArrayRef<Expr *> Args) {
11292 const auto *RD = ExprToVisit->getType()->castAsRecordDecl();
11293 if (RD->isInvalidDecl()) return false;
11294 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
11295 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
11296
11297 EvalInfo::EvaluatingConstructorRAII EvalObj(
11298 Info,
11299 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
11300 CXXRD && CXXRD->getNumBases());
11301
11302 if (RD->isUnion()) {
11303 const FieldDecl *Field;
11304 if (auto *ILE = dyn_cast<InitListExpr>(ExprToVisit)) {
11305 Field = ILE->getInitializedFieldInUnion();
11306 } else if (auto *PLIE = dyn_cast<CXXParenListInitExpr>(ExprToVisit)) {
11307 Field = PLIE->getInitializedFieldInUnion();
11308 } else {
11309 llvm_unreachable(
11310 "Expression is neither an init list nor a C++ paren list");
11311 }
11312
11313 Result = APValue(Field);
11314 if (!Field)
11315 return true;
11316
11317 // If the initializer list for a union does not contain any elements, the
11318 // first element of the union is value-initialized.
11319 // FIXME: The element should be initialized from an initializer list.
11320 // Is this difference ever observable for initializer lists which
11321 // we don't build?
11322 ImplicitValueInitExpr VIE(Field->getType());
11323 const Expr *InitExpr = Args.empty() ? &VIE : Args[0];
11324
11325 LValue Subobject = This;
11326 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
11327 return false;
11328
11329 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
11330 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
11331 isa<CXXDefaultInitExpr>(InitExpr));
11332
11333 if (EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr)) {
11334 if (Field->isBitField())
11335 return truncateBitfieldValue(Info, InitExpr, Result.getUnionValue(),
11336 Field);
11337 return true;
11338 }
11339
11340 return false;
11341 }
11342
11343 if (!Result.hasValue())
11344 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
11345 RD->getNumFields());
11346 unsigned ElementNo = 0;
11347 bool Success = true;
11348
11349 // Initialize base classes.
11350 if (CXXRD && CXXRD->getNumBases()) {
11351 for (const auto &Base : CXXRD->bases()) {
11352 assert(ElementNo < Args.size() && "missing init for base class");
11353 const Expr *Init = Args[ElementNo];
11354
11355 LValue Subobject = This;
11356 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
11357 return false;
11358
11359 APValue &FieldVal = Result.getStructBase(ElementNo);
11360 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
11361 if (!Info.noteFailure())
11362 return false;
11363 Success = false;
11364 }
11365 ++ElementNo;
11366 }
11367
11368 EvalObj.finishedConstructingBases();
11369 }
11370
11371 // Initialize members.
11372 for (const auto *Field : RD->fields()) {
11373 // Anonymous bit-fields are not considered members of the class for
11374 // purposes of aggregate initialization.
11375 if (Field->isUnnamedBitField())
11376 continue;
11377
11378 LValue Subobject = This;
11379
11380 bool HaveInit = ElementNo < Args.size();
11381
11382 // FIXME: Diagnostics here should point to the end of the initializer
11383 // list, not the start.
11384 if (!HandleLValueMember(Info, HaveInit ? Args[ElementNo] : ExprToVisit,
11385 Subobject, Field, &Layout))
11386 return false;
11387
11388 // Perform an implicit value-initialization for members beyond the end of
11389 // the initializer list.
11390 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
11391 const Expr *Init = HaveInit ? Args[ElementNo++] : &VIE;
11392
11393 if (Field->getType()->isIncompleteArrayType()) {
11394 if (auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType())) {
11395 if (!CAT->isZeroSize()) {
11396 // Bail out for now. This might sort of "work", but the rest of the
11397 // code isn't really prepared to handle it.
11398 Info.FFDiag(Init, diag::note_constexpr_unsupported_flexible_array);
11399 return false;
11400 }
11401 }
11402 }
11403
11404 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
11405 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
11406 isa<CXXDefaultInitExpr>(Init));
11407
11408 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
11409 if (Field->getType()->isReferenceType()) {
11410 LValue Result;
11411 if (!EvaluateInitForDeclOfReferenceType(Info, Field, Init, Result,
11412 FieldVal)) {
11413 if (!Info.noteFailure())
11414 return false;
11415 Success = false;
11416 }
11417 } else if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
11418 (Field->isBitField() &&
11419 !truncateBitfieldValue(Info, Init, FieldVal, Field))) {
11420 if (!Info.noteFailure())
11421 return false;
11422 Success = false;
11423 }
11424 }
11425
11426 EvalObj.finishedConstructingFields();
11427
11428 return Success;
11429 }
11430
11431 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
11432 QualType T) {
11433 // Note that E's type is not necessarily the type of our class here; we might
11434 // be initializing an array element instead.
11435 const CXXConstructorDecl *FD = E->getConstructor();
11436 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
11437
11438 bool ZeroInit = E->requiresZeroInitialization();
11439 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
11440 if (ZeroInit)
11441 return ZeroInitialization(E, T);
11442
11443 return handleDefaultInitValue(T, Result);
11444 }
11445
11446 const FunctionDecl *Definition = nullptr;
11447 auto Body = FD->getBody(Definition);
11448
11449 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
11450 return false;
11451
11452 // Avoid materializing a temporary for an elidable copy/move constructor.
11453 if (E->isElidable() && !ZeroInit) {
11454 // FIXME: This only handles the simplest case, where the source object
11455 // is passed directly as the first argument to the constructor.
11456 // This should also handle stepping though implicit casts and
11457 // and conversion sequences which involve two steps, with a
11458 // conversion operator followed by a converting constructor.
11459 const Expr *SrcObj = E->getArg(0);
11460 assert(SrcObj->isTemporaryObject(Info.Ctx, FD->getParent()));
11461 assert(Info.Ctx.hasSameUnqualifiedType(E->getType(), SrcObj->getType()));
11462 if (const MaterializeTemporaryExpr *ME =
11463 dyn_cast<MaterializeTemporaryExpr>(SrcObj))
11464 return Visit(ME->getSubExpr());
11465 }
11466
11467 if (ZeroInit && !ZeroInitialization(E, T))
11468 return false;
11469
11470 auto Args = ArrayRef(E->getArgs(), E->getNumArgs());
11471 return HandleConstructorCall(E, This, Args,
11472 cast<CXXConstructorDecl>(Definition), Info,
11473 Result);
11474 }
11475
11476 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
11477 const CXXInheritedCtorInitExpr *E) {
11478 if (!Info.CurrentCall) {
11479 assert(Info.checkingPotentialConstantExpression());
11480 return false;
11481 }
11482
11483 const CXXConstructorDecl *FD = E->getConstructor();
11484 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
11485 return false;
11486
11487 const FunctionDecl *Definition = nullptr;
11488 auto Body = FD->getBody(Definition);
11489
11490 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
11491 return false;
11492
11493 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
11494 cast<CXXConstructorDecl>(Definition), Info,
11495 Result);
11496 }
11497
11498 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
11499 const CXXStdInitializerListExpr *E) {
11500 const ConstantArrayType *ArrayType =
11501 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
11502
11503 LValue Array;
11504 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
11505 return false;
11506
11507 assert(ArrayType && "unexpected type for array initializer");
11508
11509 // Get a pointer to the first element of the array.
11510 Array.addArray(Info, E, ArrayType);
11511
11512 // FIXME: What if the initializer_list type has base classes, etc?
11513 Result = APValue(APValue::UninitStruct(), 0, 2);
11514 Array.moveInto(Result.getStructField(0));
11515
11516 auto *Record = E->getType()->castAsRecordDecl();
11517 RecordDecl::field_iterator Field = Record->field_begin();
11518 assert(Field != Record->field_end() &&
11519 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
11520 ArrayType->getElementType()) &&
11521 "Expected std::initializer_list first field to be const E *");
11522 ++Field;
11523 assert(Field != Record->field_end() &&
11524 "Expected std::initializer_list to have two fields");
11525
11526 if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType())) {
11527 // Length.
11528 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
11529 } else {
11530 // End pointer.
11531 assert(Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
11532 ArrayType->getElementType()) &&
11533 "Expected std::initializer_list second field to be const E *");
11534 if (!HandleLValueArrayAdjustment(Info, E, Array,
11535 ArrayType->getElementType(),
11536 ArrayType->getZExtSize()))
11537 return false;
11538 Array.moveInto(Result.getStructField(1));
11539 }
11540
11541 assert(++Field == Record->field_end() &&
11542 "Expected std::initializer_list to only have two fields");
11543
11544 return true;
11545 }
11546
11547 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
11548 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
11549 if (ClosureClass->isInvalidDecl())
11550 return false;
11551
11552 const size_t NumFields = ClosureClass->getNumFields();
11553
11554 assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
11555 E->capture_init_end()) &&
11556 "The number of lambda capture initializers should equal the number of "
11557 "fields within the closure type");
11558
11559 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
11560 // Iterate through all the lambda's closure object's fields and initialize
11561 // them.
11562 auto *CaptureInitIt = E->capture_init_begin();
11563 bool Success = true;
11564 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(ClosureClass);
11565 for (const auto *Field : ClosureClass->fields()) {
11566 assert(CaptureInitIt != E->capture_init_end());
11567 // Get the initializer for this field
11568 Expr *const CurFieldInit = *CaptureInitIt++;
11569
11570 // If there is no initializer, either this is a VLA or an error has
11571 // occurred.
11572 if (!CurFieldInit || CurFieldInit->containsErrors())
11573 return Error(E);
11574
11575 LValue Subobject = This;
11576
11577 if (!HandleLValueMember(Info, E, Subobject, Field, &Layout))
11578 return false;
11579
11580 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
11581 if (!EvaluateInPlace(FieldVal, Info, Subobject, CurFieldInit)) {
11582 if (!Info.keepEvaluatingAfterFailure())
11583 return false;
11584 Success = false;
11585 }
11586 }
11587 return Success;
11588 }
11589
11590 static bool EvaluateRecord(const Expr *E, const LValue &This,
11591 APValue &Result, EvalInfo &Info) {
11592 assert(!E->isValueDependent());
11593 assert(E->isPRValue() && E->getType()->isRecordType() &&
11594 "can't evaluate expression as a record rvalue");
11595 return RecordExprEvaluator(Info, This, Result).Visit(E);
11596 }
11597
11598 //===----------------------------------------------------------------------===//
11599 // Temporary Evaluation
11600 //
11601 // Temporaries are represented in the AST as rvalues, but generally behave like
11602 // lvalues. The full-object of which the temporary is a subobject is implicitly
11603 // materialized so that a reference can bind to it.
11604 //===----------------------------------------------------------------------===//
11605 namespace {
11606 class TemporaryExprEvaluator
11607 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
11608 public:
11609 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
11610 LValueExprEvaluatorBaseTy(Info, Result, false) {}
11611
11612 /// Visit an expression which constructs the value of this temporary.
11613 bool VisitConstructExpr(const Expr *E) {
11614 APValue &Value = Info.CurrentCall->createTemporary(
11615 E, E->getType(), ScopeKind::FullExpression, Result);
11616 return EvaluateInPlace(Value, Info, Result, E);
11617 }
11618
11619 bool VisitCastExpr(const CastExpr *E) {
11620 switch (E->getCastKind()) {
11621 default:
11622 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
11623
11624 case CK_ConstructorConversion:
11625 return VisitConstructExpr(E->getSubExpr());
11626 }
11627 }
11628 bool VisitInitListExpr(const InitListExpr *E) {
11629 return VisitConstructExpr(E);
11630 }
11631 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
11632 return VisitConstructExpr(E);
11633 }
11634 bool VisitCallExpr(const CallExpr *E) {
11635 return VisitConstructExpr(E);
11636 }
11637 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
11638 return VisitConstructExpr(E);
11639 }
11640 bool VisitLambdaExpr(const LambdaExpr *E) {
11641 return VisitConstructExpr(E);
11642 }
11643 };
11644 } // end anonymous namespace
11645
11646 /// Evaluate an expression of record type as a temporary.
11647 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
11648 assert(!E->isValueDependent());
11649 assert(E->isPRValue() && E->getType()->isRecordType());
11650 return TemporaryExprEvaluator(Info, Result).Visit(E);
11651 }
11652
11653 //===----------------------------------------------------------------------===//
11654 // Vector Evaluation
11655 //===----------------------------------------------------------------------===//
11656
11657 namespace {
11658 class VectorExprEvaluator
11659 : public ExprEvaluatorBase<VectorExprEvaluator> {
11660 APValue &Result;
11661 public:
11662
11663 VectorExprEvaluator(EvalInfo &info, APValue &Result)
11664 : ExprEvaluatorBaseTy(info), Result(Result) {}
11665
11666 bool Success(ArrayRef<APValue> V, const Expr *E) {
11667 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
11668 // FIXME: remove this APValue copy.
11669 Result = APValue(V.data(), V.size());
11670 return true;
11671 }
11672 bool Success(const APValue &V, const Expr *E) {
11673 assert(V.isVector());
11674 Result = V;
11675 return true;
11676 }
11677 bool ZeroInitialization(const Expr *E);
11678
11679 bool VisitUnaryReal(const UnaryOperator *E)
11680 { return Visit(E->getSubExpr()); }
11681 bool VisitCastExpr(const CastExpr* E);
11682 bool VisitInitListExpr(const InitListExpr *E);
11683 bool VisitUnaryImag(const UnaryOperator *E);
11684 bool VisitBinaryOperator(const BinaryOperator *E);
11685 bool VisitUnaryOperator(const UnaryOperator *E);
11686 bool VisitCallExpr(const CallExpr *E);
11687 bool VisitConvertVectorExpr(const ConvertVectorExpr *E);
11688 bool VisitShuffleVectorExpr(const ShuffleVectorExpr *E);
11689
11690 // FIXME: Missing: conditional operator (for GNU
11691 // conditional select), ExtVectorElementExpr
11692 };
11693 } // end anonymous namespace
11694
11695 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
11696 assert(E->isPRValue() && E->getType()->isVectorType() &&
11697 "not a vector prvalue");
11698 return VectorExprEvaluator(Info, Result).Visit(E);
11699 }
11700
11701 static llvm::APInt ConvertBoolVectorToInt(const APValue &Val) {
11702 assert(Val.isVector() && "expected vector APValue");
11703 unsigned NumElts = Val.getVectorLength();
11704
11705 // Each element is one bit, so create an integer with NumElts bits.
11706 llvm::APInt Result(NumElts, 0);
11707
11708 for (unsigned I = 0; I < NumElts; ++I) {
11709 const APValue &Elt = Val.getVectorElt(I);
11710 assert(Elt.isInt() && "expected integer element in bool vector");
11711
11712 if (Elt.getInt().getBoolValue())
11713 Result.setBit(I);
11714 }
11715
11716 return Result;
11717 }
11718
11719 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
11720 const VectorType *VTy = E->getType()->castAs<VectorType>();
11721 unsigned NElts = VTy->getNumElements();
11722
11723 const Expr *SE = E->getSubExpr();
11724 QualType SETy = SE->getType();
11725
11726 switch (E->getCastKind()) {
11727 case CK_VectorSplat: {
11728 APValue Val = APValue();
11729 if (SETy->isIntegerType()) {
11730 APSInt IntResult;
11731 if (!EvaluateInteger(SE, IntResult, Info))
11732 return false;
11733 Val = APValue(std::move(IntResult));
11734 } else if (SETy->isRealFloatingType()) {
11735 APFloat FloatResult(0.0);
11736 if (!EvaluateFloat(SE, FloatResult, Info))
11737 return false;
11738 Val = APValue(std::move(FloatResult));
11739 } else {
11740 return Error(E);
11741 }
11742
11743 // Splat and create vector APValue.
11744 SmallVector<APValue, 4> Elts(NElts, Val);
11745 return Success(Elts, E);
11746 }
11747 case CK_BitCast: {
11748 APValue SVal;
11749 if (!Evaluate(SVal, Info, SE))
11750 return false;
11751
11752 if (!SVal.isInt() && !SVal.isFloat() && !SVal.isVector()) {
11753 // Give up if the input isn't an int, float, or vector. For example, we
11754 // reject "(v4i16)(intptr_t)&a".
11755 Info.FFDiag(E, diag::note_constexpr_invalid_cast)
11756 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
11757 << Info.Ctx.getLangOpts().CPlusPlus;
11758 return false;
11759 }
11760
11761 if (!handleRValueToRValueBitCast(Info, Result, SVal, E))
11762 return false;
11763
11764 return true;
11765 }
11766 case CK_HLSLVectorTruncation: {
11767 APValue Val;
11768 SmallVector<APValue, 4> Elements;
11769 if (!EvaluateVector(SE, Val, Info))
11770 return Error(E);
11771 for (unsigned I = 0; I < NElts; I++)
11772 Elements.push_back(Val.getVectorElt(I));
11773 return Success(Elements, E);
11774 }
11775 case CK_HLSLMatrixTruncation: {
11776 // TODO: See #168935. Add matrix truncation support to expr constant.
11777 return Error(E);
11778 }
11779 case CK_HLSLAggregateSplatCast: {
11780 APValue Val;
11781 QualType ValTy;
11782
11783 if (!hlslAggSplatHelper(Info, SE, Val, ValTy))
11784 return false;
11785
11786 // cast our Val once.
11787 APValue Result;
11788 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
11789 if (!handleScalarCast(Info, FPO, E, ValTy, VTy->getElementType(), Val,
11790 Result))
11791 return false;
11792
11793 SmallVector<APValue, 4> SplatEls(NElts, Result);
11794 return Success(SplatEls, E);
11795 }
11796 case CK_HLSLElementwiseCast: {
11797 SmallVector<APValue> SrcVals;
11798 SmallVector<QualType> SrcTypes;
11799
11800 if (!hlslElementwiseCastHelper(Info, SE, E->getType(), SrcVals, SrcTypes))
11801 return false;
11802
11803 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
11804 SmallVector<QualType, 4> DestTypes(NElts, VTy->getElementType());
11805 SmallVector<APValue, 4> ResultEls(NElts);
11806 if (!handleElementwiseCast(Info, E, FPO, SrcVals, SrcTypes, DestTypes,
11807 ResultEls))
11808 return false;
11809 return Success(ResultEls, E);
11810 }
11811 default:
11812 return ExprEvaluatorBaseTy::VisitCastExpr(E);
11813 }
11814 }
11815
11816 bool
11817 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
11818 const VectorType *VT = E->getType()->castAs<VectorType>();
11819 unsigned NumInits = E->getNumInits();
11820 unsigned NumElements = VT->getNumElements();
11821
11822 QualType EltTy = VT->getElementType();
11823 SmallVector<APValue, 4> Elements;
11824
11825 // MFloat8 type doesn't have constants and thus constant folding
11826 // is impossible.
11827 if (EltTy->isMFloat8Type())
11828 return false;
11829
11830 // The number of initializers can be less than the number of
11831 // vector elements. For OpenCL, this can be due to nested vector
11832 // initialization. For GCC compatibility, missing trailing elements
11833 // should be initialized with zeroes.
11834 unsigned CountInits = 0, CountElts = 0;
11835 while (CountElts < NumElements) {
11836 // Handle nested vector initialization.
11837 if (CountInits < NumInits
11838 && E->getInit(CountInits)->getType()->isVectorType()) {
11839 APValue v;
11840 if (!EvaluateVector(E->getInit(CountInits), v, Info))
11841 return Error(E);
11842 unsigned vlen = v.getVectorLength();
11843 for (unsigned j = 0; j < vlen; j++)
11844 Elements.push_back(v.getVectorElt(j));
11845 CountElts += vlen;
11846 } else if (EltTy->isIntegerType()) {
11847 llvm::APSInt sInt(32);
11848 if (CountInits < NumInits) {
11849 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
11850 return false;
11851 } else // trailing integer zero.
11852 sInt = Info.Ctx.MakeIntValue(0, EltTy);
11853 Elements.push_back(APValue(sInt));
11854 CountElts++;
11855 } else {
11856 llvm::APFloat f(0.0);
11857 if (CountInits < NumInits) {
11858 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
11859 return false;
11860 } else // trailing float zero.
11861 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
11862 Elements.push_back(APValue(f));
11863 CountElts++;
11864 }
11865 CountInits++;
11866 }
11867 return Success(Elements, E);
11868 }
11869
11870 bool
11871 VectorExprEvaluator::ZeroInitialization(const Expr *E) {
11872 const auto *VT = E->getType()->castAs<VectorType>();
11873 QualType EltTy = VT->getElementType();
11874 APValue ZeroElement;
11875 if (EltTy->isIntegerType())
11876 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
11877 else
11878 ZeroElement =
11879 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
11880
11881 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
11882 return Success(Elements, E);
11883 }
11884
11885 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
11886 VisitIgnoredValue(E->getSubExpr());
11887 return ZeroInitialization(E);
11888 }
11889
11890 bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
11891 BinaryOperatorKind Op = E->getOpcode();
11892 assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp &&
11893 "Operation not supported on vector types");
11894
11895 if (Op == BO_Comma)
11896 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
11897
11898 Expr *LHS = E->getLHS();
11899 Expr *RHS = E->getRHS();
11900
11901 assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() &&
11902 "Must both be vector types");
11903 // Checking JUST the types are the same would be fine, except shifts don't
11904 // need to have their types be the same (since you always shift by an int).
11905 assert(LHS->getType()->castAs<VectorType>()->getNumElements() ==
11906 E->getType()->castAs<VectorType>()->getNumElements() &&
11907 RHS->getType()->castAs<VectorType>()->getNumElements() ==
11908 E->getType()->castAs<VectorType>()->getNumElements() &&
11909 "All operands must be the same size.");
11910
11911 APValue LHSValue;
11912 APValue RHSValue;
11913 bool LHSOK = Evaluate(LHSValue, Info, LHS);
11914 if (!LHSOK && !Info.noteFailure())
11915 return false;
11916 if (!Evaluate(RHSValue, Info, RHS) || !LHSOK)
11917 return false;
11918
11919 if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue))
11920 return false;
11921
11922 return Success(LHSValue, E);
11923 }
11924
11925 static std::optional<APValue> handleVectorUnaryOperator(ASTContext &Ctx,
11926 QualType ResultTy,
11927 UnaryOperatorKind Op,
11928 APValue Elt) {
11929 switch (Op) {
11930 case UO_Plus:
11931 // Nothing to do here.
11932 return Elt;
11933 case UO_Minus:
11934 if (Elt.getKind() == APValue::Int) {
11935 Elt.getInt().negate();
11936 } else {
11937 assert(Elt.getKind() == APValue::Float &&
11938 "Vector can only be int or float type");
11939 Elt.getFloat().changeSign();
11940 }
11941 return Elt;
11942 case UO_Not:
11943 // This is only valid for integral types anyway, so we don't have to handle
11944 // float here.
11945 assert(Elt.getKind() == APValue::Int &&
11946 "Vector operator ~ can only be int");
11947 Elt.getInt().flipAllBits();
11948 return Elt;
11949 case UO_LNot: {
11950 if (Elt.getKind() == APValue::Int) {
11951 Elt.getInt() = !Elt.getInt();
11952 // operator ! on vectors returns -1 for 'truth', so negate it.
11953 Elt.getInt().negate();
11954 return Elt;
11955 }
11956 assert(Elt.getKind() == APValue::Float &&
11957 "Vector can only be int or float type");
11958 // Float types result in an int of the same size, but -1 for true, or 0 for
11959 // false.
11960 APSInt EltResult{Ctx.getIntWidth(ResultTy),
11961 ResultTy->isUnsignedIntegerType()};
11962 if (Elt.getFloat().isZero())
11963 EltResult.setAllBits();
11964 else
11965 EltResult.clearAllBits();
11966
11967 return APValue{EltResult};
11968 }
11969 default:
11970 // FIXME: Implement the rest of the unary operators.
11971 return std::nullopt;
11972 }
11973 }
11974
11975 bool VectorExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
11976 Expr *SubExpr = E->getSubExpr();
11977 const auto *VD = SubExpr->getType()->castAs<VectorType>();
11978 // This result element type differs in the case of negating a floating point
11979 // vector, since the result type is the a vector of the equivilant sized
11980 // integer.
11981 const QualType ResultEltTy = VD->getElementType();
11982 UnaryOperatorKind Op = E->getOpcode();
11983
11984 APValue SubExprValue;
11985 if (!Evaluate(SubExprValue, Info, SubExpr))
11986 return false;
11987
11988 // FIXME: This vector evaluator someday needs to be changed to be LValue
11989 // aware/keep LValue information around, rather than dealing with just vector
11990 // types directly. Until then, we cannot handle cases where the operand to
11991 // these unary operators is an LValue. The only case I've been able to see
11992 // cause this is operator++ assigning to a member expression (only valid in
11993 // altivec compilations) in C mode, so this shouldn't limit us too much.
11994 if (SubExprValue.isLValue())
11995 return false;
11996
11997 assert(SubExprValue.getVectorLength() == VD->getNumElements() &&
11998 "Vector length doesn't match type?");
11999
12000 SmallVector<APValue, 4> ResultElements;
12001 for (unsigned EltNum = 0; EltNum < VD->getNumElements(); ++EltNum) {
12002 std::optional<APValue> Elt = handleVectorUnaryOperator(
12003 Info.Ctx, ResultEltTy, Op, SubExprValue.getVectorElt(EltNum));
12004 if (!Elt)
12005 return false;
12006 ResultElements.push_back(*Elt);
12007 }
12008 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12009 }
12010
12011 static bool handleVectorElementCast(EvalInfo &Info, const FPOptions FPO,
12012 const Expr *E, QualType SourceTy,
12013 QualType DestTy, APValue const &Original,
12014 APValue &Result) {
12015 if (SourceTy->isIntegerType()) {
12016 if (DestTy->isRealFloatingType()) {
12017 Result = APValue(APFloat(0.0));
12018 return HandleIntToFloatCast(Info, E, FPO, SourceTy, Original.getInt(),
12019 DestTy, Result.getFloat());
12020 }
12021 if (DestTy->isIntegerType()) {
12022 Result = APValue(
12023 HandleIntToIntCast(Info, E, DestTy, SourceTy, Original.getInt()));
12024 return true;
12025 }
12026 } else if (SourceTy->isRealFloatingType()) {
12027 if (DestTy->isRealFloatingType()) {
12028 Result = Original;
12029 return HandleFloatToFloatCast(Info, E, SourceTy, DestTy,
12030 Result.getFloat());
12031 }
12032 if (DestTy->isIntegerType()) {
12033 Result = APValue(APSInt());
12034 return HandleFloatToIntCast(Info, E, SourceTy, Original.getFloat(),
12035 DestTy, Result.getInt());
12036 }
12037 }
12038
12039 Info.FFDiag(E, diag::err_convertvector_constexpr_unsupported_vector_cast)
12040 << SourceTy << DestTy;
12041 return false;
12042 }
12043
12044 static bool evalPackBuiltin(const CallExpr *E, EvalInfo &Info, APValue &Result,
12045 llvm::function_ref<APInt(const APSInt &)> PackFn) {
12046 APValue LHS, RHS;
12047 if (!EvaluateAsRValue(Info, E->getArg(0), LHS) ||
12048 !EvaluateAsRValue(Info, E->getArg(1), RHS))
12049 return false;
12050
12051 unsigned LHSVecLen = LHS.getVectorLength();
12052 unsigned RHSVecLen = RHS.getVectorLength();
12053
12054 assert(LHSVecLen != 0 && LHSVecLen == RHSVecLen &&
12055 "pack builtin LHSVecLen must equal to RHSVecLen");
12056
12057 const VectorType *VT0 = E->getArg(0)->getType()->castAs<VectorType>();
12058 const unsigned SrcBits = Info.Ctx.getIntWidth(VT0->getElementType());
12059
12060 const VectorType *DstVT = E->getType()->castAs<VectorType>();
12061 QualType DstElemTy = DstVT->getElementType();
12062 const bool DstIsUnsigned = DstElemTy->isUnsignedIntegerType();
12063
12064 const unsigned SrcPerLane = 128 / SrcBits;
12065 const unsigned Lanes = LHSVecLen * SrcBits / 128;
12066
12067 SmallVector<APValue, 64> Out;
12068 Out.reserve(LHSVecLen + RHSVecLen);
12069
12070 for (unsigned Lane = 0; Lane != Lanes; ++Lane) {
12071 unsigned base = Lane * SrcPerLane;
12072 for (unsigned I = 0; I != SrcPerLane; ++I)
12073 Out.emplace_back(APValue(
12074 APSInt(PackFn(LHS.getVectorElt(base + I).getInt()), DstIsUnsigned)));
12075 for (unsigned I = 0; I != SrcPerLane; ++I)
12076 Out.emplace_back(APValue(
12077 APSInt(PackFn(RHS.getVectorElt(base + I).getInt()), DstIsUnsigned)));
12078 }
12079
12080 Result = APValue(Out.data(), Out.size());
12081 return true;
12082 }
12083
12084 static bool evalShuffleGeneric(
12085 EvalInfo &Info, const CallExpr *Call, APValue &Out,
12086 llvm::function_ref<std::pair<unsigned, int>(unsigned, unsigned)>
12087 GetSourceIndex) {
12088
12089 const auto *VT = Call->getType()->getAs<VectorType>();
12090 if (!VT)
12091 return false;
12092
12093 unsigned ShuffleMask = 0;
12094 APValue A, MaskVector, B;
12095 bool IsVectorMask = false;
12096 bool IsSingleOperand = (Call->getNumArgs() == 2);
12097
12098 if (IsSingleOperand) {
12099 QualType MaskType = Call->getArg(1)->getType();
12100 if (MaskType->isVectorType()) {
12101 IsVectorMask = true;
12102 if (!EvaluateAsRValue(Info, Call->getArg(0), A) ||
12103 !EvaluateAsRValue(Info, Call->getArg(1), MaskVector))
12104 return false;
12105 B = A;
12106 } else if (MaskType->isIntegerType()) {
12107 APSInt MaskImm;
12108 if (!EvaluateInteger(Call->getArg(1), MaskImm, Info))
12109 return false;
12110 ShuffleMask = static_cast<unsigned>(MaskImm.getZExtValue());
12111 if (!EvaluateAsRValue(Info, Call->getArg(0), A))
12112 return false;
12113 B = A;
12114 } else {
12115 return false;
12116 }
12117 } else {
12118 QualType Arg2Type = Call->getArg(2)->getType();
12119 if (Arg2Type->isVectorType()) {
12120 IsVectorMask = true;
12121 if (!EvaluateAsRValue(Info, Call->getArg(0), A) ||
12122 !EvaluateAsRValue(Info, Call->getArg(1), MaskVector) ||
12123 !EvaluateAsRValue(Info, Call->getArg(2), B))
12124 return false;
12125 } else if (Arg2Type->isIntegerType()) {
12126 APSInt MaskImm;
12127 if (!EvaluateInteger(Call->getArg(2), MaskImm, Info))
12128 return false;
12129 ShuffleMask = static_cast<unsigned>(MaskImm.getZExtValue());
12130 if (!EvaluateAsRValue(Info, Call->getArg(0), A) ||
12131 !EvaluateAsRValue(Info, Call->getArg(1), B))
12132 return false;
12133 } else {
12134 return false;
12135 }
12136 }
12137
12138 unsigned NumElts = VT->getNumElements();
12139 SmallVector<APValue, 64> ResultElements;
12140 ResultElements.reserve(NumElts);
12141
12142 for (unsigned DstIdx = 0; DstIdx != NumElts; ++DstIdx) {
12143 if (IsVectorMask) {
12144 ShuffleMask = static_cast<unsigned>(
12145 MaskVector.getVectorElt(DstIdx).getInt().getZExtValue());
12146 }
12147 auto [SrcVecIdx, SrcIdx] = GetSourceIndex(DstIdx, ShuffleMask);
12148
12149 if (SrcIdx < 0) {
12150 // Zero out this element
12151 QualType ElemTy = VT->getElementType();
12152 if (ElemTy->isRealFloatingType()) {
12153 ResultElements.push_back(
12154 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy))));
12155 } else if (ElemTy->isIntegerType()) {
12156 APValue Zero(Info.Ctx.MakeIntValue(0, ElemTy));
12157 ResultElements.push_back(APValue(Zero));
12158 } else {
12159 // Other types of fallback logic
12160 ResultElements.push_back(APValue());
12161 }
12162 } else {
12163 const APValue &Src = (SrcVecIdx == 0) ? A : B;
12164 ResultElements.push_back(Src.getVectorElt(SrcIdx));
12165 }
12166 }
12167
12168 Out = APValue(ResultElements.data(), ResultElements.size());
12169 return true;
12170 }
12171 static bool ConvertDoubleToFloatStrict(EvalInfo &Info, const Expr *E,
12172 APFloat OrigVal, APValue &Result) {
12173
12174 if (OrigVal.isInfinity()) {
12175 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << 0;
12176 return false;
12177 }
12178 if (OrigVal.isNaN()) {
12179 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << 1;
12180 return false;
12181 }
12182
12183 APFloat Val = OrigVal;
12184 bool LosesInfo = false;
12185 APFloat::opStatus Status = Val.convert(
12186 APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, &LosesInfo);
12187
12188 if (LosesInfo || Val.isDenormal()) {
12189 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic_strict);
12190 return false;
12191 }
12192
12193 if (Status != APFloat::opOK) {
12194 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
12195 return false;
12196 }
12197
12198 Result = APValue(Val);
12199 return true;
12200 }
12201 static bool evalShiftWithCount(
12202 EvalInfo &Info, const CallExpr *Call, APValue &Out,
12203 llvm::function_ref<APInt(const APInt &, uint64_t)> ShiftOp,
12204 llvm::function_ref<APInt(const APInt &, unsigned)> OverflowOp) {
12205
12206 APValue Source, Count;
12207 if (!EvaluateAsRValue(Info, Call->getArg(0), Source) ||
12208 !EvaluateAsRValue(Info, Call->getArg(1), Count))
12209 return false;
12210
12211 assert(Call->getNumArgs() == 2);
12212
12213 QualType SourceTy = Call->getArg(0)->getType();
12214 assert(SourceTy->isVectorType() &&
12215 Call->getArg(1)->getType()->isVectorType());
12216
12217 QualType DestEltTy = SourceTy->castAs<VectorType>()->getElementType();
12218 unsigned DestEltWidth = Source.getVectorElt(0).getInt().getBitWidth();
12219 unsigned DestLen = Source.getVectorLength();
12220 bool IsDestUnsigned = DestEltTy->isUnsignedIntegerType();
12221 unsigned CountEltWidth = Count.getVectorElt(0).getInt().getBitWidth();
12222 unsigned NumBitsInQWord = 64;
12223 unsigned NumCountElts = NumBitsInQWord / CountEltWidth;
12224 SmallVector<APValue, 64> Result;
12225 Result.reserve(DestLen);
12226
12227 uint64_t CountLQWord = 0;
12228 for (unsigned EltIdx = 0; EltIdx != NumCountElts; ++EltIdx) {
12229 uint64_t Elt = Count.getVectorElt(EltIdx).getInt().getZExtValue();
12230 CountLQWord |= (Elt << (EltIdx * CountEltWidth));
12231 }
12232
12233 for (unsigned EltIdx = 0; EltIdx != DestLen; ++EltIdx) {
12234 APInt Elt = Source.getVectorElt(EltIdx).getInt();
12235 if (CountLQWord < DestEltWidth) {
12236 Result.push_back(
12237 APValue(APSInt(ShiftOp(Elt, CountLQWord), IsDestUnsigned)));
12238 } else {
12239 Result.push_back(
12240 APValue(APSInt(OverflowOp(Elt, DestEltWidth), IsDestUnsigned)));
12241 }
12242 }
12243 Out = APValue(Result.data(), Result.size());
12244 return true;
12245 }
12246
12247 bool VectorExprEvaluator::VisitCallExpr(const CallExpr *E) {
12248 if (!IsConstantEvaluatedBuiltinCall(E))
12249 return ExprEvaluatorBaseTy::VisitCallExpr(E);
12250
12251 auto EvaluateBinOpExpr =
12252 [&](llvm::function_ref<APInt(const APSInt &, const APSInt &)> Fn) {
12253 APValue SourceLHS, SourceRHS;
12254 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
12255 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
12256 return false;
12257
12258 auto *DestTy = E->getType()->castAs<VectorType>();
12259 QualType DestEltTy = DestTy->getElementType();
12260 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
12261 unsigned SourceLen = SourceLHS.getVectorLength();
12262 SmallVector<APValue, 4> ResultElements;
12263 ResultElements.reserve(SourceLen);
12264
12265 if (SourceRHS.isInt()) {
12266 const APSInt &RHS = SourceRHS.getInt();
12267 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12268 const APSInt &LHS = SourceLHS.getVectorElt(EltNum).getInt();
12269 ResultElements.push_back(
12270 APValue(APSInt(Fn(LHS, RHS), DestUnsigned)));
12271 }
12272 } else {
12273 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12274 const APSInt &LHS = SourceLHS.getVectorElt(EltNum).getInt();
12275 const APSInt &RHS = SourceRHS.getVectorElt(EltNum).getInt();
12276 ResultElements.push_back(
12277 APValue(APSInt(Fn(LHS, RHS), DestUnsigned)));
12278 }
12279 }
12280 return Success(APValue(ResultElements.data(), SourceLen), E);
12281 };
12282
12283 auto EvaluateFpBinOpExpr =
12284 [&](llvm::function_ref<APFloat(const APFloat &, const APFloat &,
12285 std::optional<APSInt>)>
12286 Fn) {
12287 assert(E->getNumArgs() == 2 || E->getNumArgs() == 3);
12288 APValue A, B;
12289 if (!EvaluateAsRValue(Info, E->getArg(0), A) ||
12290 !EvaluateAsRValue(Info, E->getArg(1), B))
12291 return false;
12292
12293 assert(A.isVector() && B.isVector());
12294 assert(A.getVectorLength() == B.getVectorLength());
12295
12296 std::optional<APSInt> RoundingMode;
12297 if (E->getNumArgs() == 3) {
12298 APSInt Imm;
12299 if (!EvaluateInteger(E->getArg(2), Imm, Info))
12300 return false;
12301 RoundingMode = Imm;
12302 }
12303
12304 unsigned NumElems = A.getVectorLength();
12305 SmallVector<APValue, 4> ResultElements;
12306 ResultElements.reserve(NumElems);
12307
12308 for (unsigned EltNum = 0; EltNum < NumElems; ++EltNum) {
12309 const APFloat &EltA = A.getVectorElt(EltNum).getFloat();
12310 const APFloat &EltB = B.getVectorElt(EltNum).getFloat();
12311 if (EltA.isNaN() || EltA.isInfinity() || EltA.isDenormal() ||
12312 EltB.isNaN() || EltB.isInfinity() || EltB.isDenormal())
12313 return false;
12314 ResultElements.push_back(APValue(Fn(EltA, EltB, RoundingMode)));
12315 }
12316 return Success(APValue(ResultElements.data(), NumElems), E);
12317 };
12318
12319 auto EvalSelectScalar = [&](unsigned Len) -> bool {
12320 APSInt Mask;
12321 APValue AVal, WVal;
12322 if (!EvaluateInteger(E->getArg(0), Mask, Info) ||
12323 !EvaluateAsRValue(Info, E->getArg(1), AVal) ||
12324 !EvaluateAsRValue(Info, E->getArg(2), WVal))
12325 return false;
12326
12327 bool TakeA0 = (Mask.getZExtValue() & 1u) != 0;
12328 SmallVector<APValue, 4> Res;
12329 Res.reserve(Len);
12330 Res.push_back(TakeA0 ? AVal.getVectorElt(0) : WVal.getVectorElt(0));
12331 for (unsigned I = 1; I < Len; ++I)
12332 Res.push_back(WVal.getVectorElt(I));
12333 APValue V(Res.data(), Res.size());
12334 return Success(V, E);
12335 };
12336
12337 switch (E->getBuiltinCallee()) {
12338 default:
12339 return false;
12340 case Builtin::BI__builtin_elementwise_popcount:
12341 case Builtin::BI__builtin_elementwise_bitreverse: {
12342 APValue Source;
12343 if (!EvaluateAsRValue(Info, E->getArg(0), Source))
12344 return false;
12345
12346 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
12347 unsigned SourceLen = Source.getVectorLength();
12348 SmallVector<APValue, 4> ResultElements;
12349 ResultElements.reserve(SourceLen);
12350
12351 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12352 APSInt Elt = Source.getVectorElt(EltNum).getInt();
12353 switch (E->getBuiltinCallee()) {
12354 case Builtin::BI__builtin_elementwise_popcount:
12355 ResultElements.push_back(APValue(
12356 APSInt(APInt(Info.Ctx.getIntWidth(DestEltTy), Elt.popcount()),
12357 DestEltTy->isUnsignedIntegerOrEnumerationType())));
12358 break;
12359 case Builtin::BI__builtin_elementwise_bitreverse:
12360 ResultElements.push_back(
12361 APValue(APSInt(Elt.reverseBits(),
12362 DestEltTy->isUnsignedIntegerOrEnumerationType())));
12363 break;
12364 }
12365 }
12366
12367 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12368 }
12369 case Builtin::BI__builtin_elementwise_abs: {
12370 APValue Source;
12371 if (!EvaluateAsRValue(Info, E->getArg(0), Source))
12372 return false;
12373
12374 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
12375 unsigned SourceLen = Source.getVectorLength();
12376 SmallVector<APValue, 4> ResultElements;
12377 ResultElements.reserve(SourceLen);
12378
12379 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12380 APValue CurrentEle = Source.getVectorElt(EltNum);
12381 APValue Val = DestEltTy->isFloatingType()
12382 ? APValue(llvm::abs(CurrentEle.getFloat()))
12383 : APValue(APSInt(
12384 CurrentEle.getInt().abs(),
12385 DestEltTy->isUnsignedIntegerOrEnumerationType()));
12386 ResultElements.push_back(Val);
12387 }
12388
12389 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12390 }
12391
12392 case Builtin::BI__builtin_elementwise_add_sat:
12393 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
12394 return LHS.isSigned() ? LHS.sadd_sat(RHS) : LHS.uadd_sat(RHS);
12395 });
12396
12397 case Builtin::BI__builtin_elementwise_sub_sat:
12398 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
12399 return LHS.isSigned() ? LHS.ssub_sat(RHS) : LHS.usub_sat(RHS);
12400 });
12401
12402 case X86::BI__builtin_ia32_extract128i256:
12403 case X86::BI__builtin_ia32_vextractf128_pd256:
12404 case X86::BI__builtin_ia32_vextractf128_ps256:
12405 case X86::BI__builtin_ia32_vextractf128_si256: {
12406 APValue SourceVec, SourceImm;
12407 if (!EvaluateAsRValue(Info, E->getArg(0), SourceVec) ||
12408 !EvaluateAsRValue(Info, E->getArg(1), SourceImm))
12409 return false;
12410
12411 if (!SourceVec.isVector())
12412 return false;
12413
12414 const auto *RetVT = E->getType()->castAs<VectorType>();
12415 unsigned RetLen = RetVT->getNumElements();
12416 unsigned Idx = SourceImm.getInt().getZExtValue() & 1;
12417
12418 SmallVector<APValue, 32> ResultElements;
12419 ResultElements.reserve(RetLen);
12420
12421 for (unsigned I = 0; I < RetLen; I++)
12422 ResultElements.push_back(SourceVec.getVectorElt(Idx * RetLen + I));
12423
12424 return Success(APValue(ResultElements.data(), RetLen), E);
12425 }
12426
12427 case clang::X86::BI__builtin_ia32_cvtmask2b128:
12428 case clang::X86::BI__builtin_ia32_cvtmask2b256:
12429 case clang::X86::BI__builtin_ia32_cvtmask2b512:
12430 case clang::X86::BI__builtin_ia32_cvtmask2w128:
12431 case clang::X86::BI__builtin_ia32_cvtmask2w256:
12432 case clang::X86::BI__builtin_ia32_cvtmask2w512:
12433 case clang::X86::BI__builtin_ia32_cvtmask2d128:
12434 case clang::X86::BI__builtin_ia32_cvtmask2d256:
12435 case clang::X86::BI__builtin_ia32_cvtmask2d512:
12436 case clang::X86::BI__builtin_ia32_cvtmask2q128:
12437 case clang::X86::BI__builtin_ia32_cvtmask2q256:
12438 case clang::X86::BI__builtin_ia32_cvtmask2q512: {
12439 assert(E->getNumArgs() == 1);
12440 APSInt Mask;
12441 if (!EvaluateInteger(E->getArg(0), Mask, Info))
12442 return false;
12443
12444 QualType VecTy = E->getType();
12445 const VectorType *VT = VecTy->castAs<VectorType>();
12446 unsigned VectorLen = VT->getNumElements();
12447 QualType ElemTy = VT->getElementType();
12448 unsigned ElemWidth = Info.Ctx.getTypeSize(ElemTy);
12449
12450 SmallVector<APValue, 16> Elems;
12451 for (unsigned I = 0; I != VectorLen; ++I) {
12452 bool BitSet = Mask[I];
12453 APSInt ElemVal(ElemWidth, /*isUnsigned=*/false);
12454 if (BitSet) {
12455 ElemVal.setAllBits();
12456 }
12457 Elems.push_back(APValue(ElemVal));
12458 }
12459 return Success(APValue(Elems.data(), VectorLen), E);
12460 }
12461
12462 case X86::BI__builtin_ia32_extracti32x4_256_mask:
12463 case X86::BI__builtin_ia32_extractf32x4_256_mask:
12464 case X86::BI__builtin_ia32_extracti32x4_mask:
12465 case X86::BI__builtin_ia32_extractf32x4_mask:
12466 case X86::BI__builtin_ia32_extracti32x8_mask:
12467 case X86::BI__builtin_ia32_extractf32x8_mask:
12468 case X86::BI__builtin_ia32_extracti64x2_256_mask:
12469 case X86::BI__builtin_ia32_extractf64x2_256_mask:
12470 case X86::BI__builtin_ia32_extracti64x2_512_mask:
12471 case X86::BI__builtin_ia32_extractf64x2_512_mask:
12472 case X86::BI__builtin_ia32_extracti64x4_mask:
12473 case X86::BI__builtin_ia32_extractf64x4_mask: {
12474 APValue SourceVec, MergeVec;
12475 APSInt Imm, MaskImm;
12476
12477 if (!EvaluateAsRValue(Info, E->getArg(0), SourceVec) ||
12478 !EvaluateInteger(E->getArg(1), Imm, Info) ||
12479 !EvaluateAsRValue(Info, E->getArg(2), MergeVec) ||
12480 !EvaluateInteger(E->getArg(3), MaskImm, Info))
12481 return false;
12482
12483 const auto *RetVT = E->getType()->castAs<VectorType>();
12484 unsigned RetLen = RetVT->getNumElements();
12485
12486 if (!SourceVec.isVector() || !MergeVec.isVector())
12487 return false;
12488 unsigned SrcLen = SourceVec.getVectorLength();
12489 unsigned Lanes = SrcLen / RetLen;
12490 unsigned Lane = static_cast<unsigned>(Imm.getZExtValue() % Lanes);
12491 unsigned Base = Lane * RetLen;
12492
12493 SmallVector<APValue, 32> ResultElements;
12494 ResultElements.reserve(RetLen);
12495 for (unsigned I = 0; I < RetLen; ++I) {
12496 if (MaskImm[I])
12497 ResultElements.push_back(SourceVec.getVectorElt(Base + I));
12498 else
12499 ResultElements.push_back(MergeVec.getVectorElt(I));
12500 }
12501 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12502 }
12503
12504 case clang::X86::BI__builtin_ia32_pavgb128:
12505 case clang::X86::BI__builtin_ia32_pavgw128:
12506 case clang::X86::BI__builtin_ia32_pavgb256:
12507 case clang::X86::BI__builtin_ia32_pavgw256:
12508 case clang::X86::BI__builtin_ia32_pavgb512:
12509 case clang::X86::BI__builtin_ia32_pavgw512:
12510 return EvaluateBinOpExpr(llvm::APIntOps::avgCeilU);
12511
12512 case clang::X86::BI__builtin_ia32_pmulhrsw128:
12513 case clang::X86::BI__builtin_ia32_pmulhrsw256:
12514 case clang::X86::BI__builtin_ia32_pmulhrsw512:
12515 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
12516 return (llvm::APIntOps::mulsExtended(LHS, RHS).ashr(14) + 1)
12517 .extractBits(16, 1);
12518 });
12519
12520 case clang::X86::BI__builtin_ia32_pmaddubsw128:
12521 case clang::X86::BI__builtin_ia32_pmaddubsw256:
12522 case clang::X86::BI__builtin_ia32_pmaddubsw512:
12523 case clang::X86::BI__builtin_ia32_pmaddwd128:
12524 case clang::X86::BI__builtin_ia32_pmaddwd256:
12525 case clang::X86::BI__builtin_ia32_pmaddwd512: {
12526 APValue SourceLHS, SourceRHS;
12527 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
12528 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
12529 return false;
12530
12531 auto *DestTy = E->getType()->castAs<VectorType>();
12532 QualType DestEltTy = DestTy->getElementType();
12533 unsigned SourceLen = SourceLHS.getVectorLength();
12534 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
12535 SmallVector<APValue, 4> ResultElements;
12536 ResultElements.reserve(SourceLen / 2);
12537
12538 for (unsigned EltNum = 0; EltNum < SourceLen; EltNum += 2) {
12539 const APSInt &LoLHS = SourceLHS.getVectorElt(EltNum).getInt();
12540 const APSInt &HiLHS = SourceLHS.getVectorElt(EltNum + 1).getInt();
12541 const APSInt &LoRHS = SourceRHS.getVectorElt(EltNum).getInt();
12542 const APSInt &HiRHS = SourceRHS.getVectorElt(EltNum + 1).getInt();
12543 unsigned BitWidth = 2 * LoLHS.getBitWidth();
12544
12545 switch (E->getBuiltinCallee()) {
12546 case clang::X86::BI__builtin_ia32_pmaddubsw128:
12547 case clang::X86::BI__builtin_ia32_pmaddubsw256:
12548 case clang::X86::BI__builtin_ia32_pmaddubsw512:
12549 ResultElements.push_back(APValue(
12550 APSInt((LoLHS.zext(BitWidth) * LoRHS.sext(BitWidth))
12551 .sadd_sat((HiLHS.zext(BitWidth) * HiRHS.sext(BitWidth))),
12552 DestUnsigned)));
12553 break;
12554 case clang::X86::BI__builtin_ia32_pmaddwd128:
12555 case clang::X86::BI__builtin_ia32_pmaddwd256:
12556 case clang::X86::BI__builtin_ia32_pmaddwd512:
12557 ResultElements.push_back(
12558 APValue(APSInt((LoLHS.sext(BitWidth) * LoRHS.sext(BitWidth)) +
12559 (HiLHS.sext(BitWidth) * HiRHS.sext(BitWidth)),
12560 DestUnsigned)));
12561 break;
12562 }
12563 }
12564
12565 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12566 }
12567
12568 case clang::X86::BI__builtin_ia32_pmulhuw128:
12569 case clang::X86::BI__builtin_ia32_pmulhuw256:
12570 case clang::X86::BI__builtin_ia32_pmulhuw512:
12571 return EvaluateBinOpExpr(llvm::APIntOps::mulhu);
12572
12573 case clang::X86::BI__builtin_ia32_pmulhw128:
12574 case clang::X86::BI__builtin_ia32_pmulhw256:
12575 case clang::X86::BI__builtin_ia32_pmulhw512:
12576 return EvaluateBinOpExpr(llvm::APIntOps::mulhs);
12577
12578 case clang::X86::BI__builtin_ia32_psllv2di:
12579 case clang::X86::BI__builtin_ia32_psllv4di:
12580 case clang::X86::BI__builtin_ia32_psllv4si:
12581 case clang::X86::BI__builtin_ia32_psllv8di:
12582 case clang::X86::BI__builtin_ia32_psllv8hi:
12583 case clang::X86::BI__builtin_ia32_psllv8si:
12584 case clang::X86::BI__builtin_ia32_psllv16hi:
12585 case clang::X86::BI__builtin_ia32_psllv16si:
12586 case clang::X86::BI__builtin_ia32_psllv32hi:
12587 case clang::X86::BI__builtin_ia32_psllwi128:
12588 case clang::X86::BI__builtin_ia32_pslldi128:
12589 case clang::X86::BI__builtin_ia32_psllqi128:
12590 case clang::X86::BI__builtin_ia32_psllwi256:
12591 case clang::X86::BI__builtin_ia32_pslldi256:
12592 case clang::X86::BI__builtin_ia32_psllqi256:
12593 case clang::X86::BI__builtin_ia32_psllwi512:
12594 case clang::X86::BI__builtin_ia32_pslldi512:
12595 case clang::X86::BI__builtin_ia32_psllqi512:
12596 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
12597 if (RHS.uge(LHS.getBitWidth())) {
12598 return APInt::getZero(LHS.getBitWidth());
12599 }
12600 return LHS.shl(RHS.getZExtValue());
12601 });
12602
12603 case clang::X86::BI__builtin_ia32_psrav4si:
12604 case clang::X86::BI__builtin_ia32_psrav8di:
12605 case clang::X86::BI__builtin_ia32_psrav8hi:
12606 case clang::X86::BI__builtin_ia32_psrav8si:
12607 case clang::X86::BI__builtin_ia32_psrav16hi:
12608 case clang::X86::BI__builtin_ia32_psrav16si:
12609 case clang::X86::BI__builtin_ia32_psrav32hi:
12610 case clang::X86::BI__builtin_ia32_psravq128:
12611 case clang::X86::BI__builtin_ia32_psravq256:
12612 case clang::X86::BI__builtin_ia32_psrawi128:
12613 case clang::X86::BI__builtin_ia32_psradi128:
12614 case clang::X86::BI__builtin_ia32_psraqi128:
12615 case clang::X86::BI__builtin_ia32_psrawi256:
12616 case clang::X86::BI__builtin_ia32_psradi256:
12617 case clang::X86::BI__builtin_ia32_psraqi256:
12618 case clang::X86::BI__builtin_ia32_psrawi512:
12619 case clang::X86::BI__builtin_ia32_psradi512:
12620 case clang::X86::BI__builtin_ia32_psraqi512:
12621 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
12622 if (RHS.uge(LHS.getBitWidth())) {
12623 return LHS.ashr(LHS.getBitWidth() - 1);
12624 }
12625 return LHS.ashr(RHS.getZExtValue());
12626 });
12627
12628 case clang::X86::BI__builtin_ia32_psrlv2di:
12629 case clang::X86::BI__builtin_ia32_psrlv4di:
12630 case clang::X86::BI__builtin_ia32_psrlv4si:
12631 case clang::X86::BI__builtin_ia32_psrlv8di:
12632 case clang::X86::BI__builtin_ia32_psrlv8hi:
12633 case clang::X86::BI__builtin_ia32_psrlv8si:
12634 case clang::X86::BI__builtin_ia32_psrlv16hi:
12635 case clang::X86::BI__builtin_ia32_psrlv16si:
12636 case clang::X86::BI__builtin_ia32_psrlv32hi:
12637 case clang::X86::BI__builtin_ia32_psrlwi128:
12638 case clang::X86::BI__builtin_ia32_psrldi128:
12639 case clang::X86::BI__builtin_ia32_psrlqi128:
12640 case clang::X86::BI__builtin_ia32_psrlwi256:
12641 case clang::X86::BI__builtin_ia32_psrldi256:
12642 case clang::X86::BI__builtin_ia32_psrlqi256:
12643 case clang::X86::BI__builtin_ia32_psrlwi512:
12644 case clang::X86::BI__builtin_ia32_psrldi512:
12645 case clang::X86::BI__builtin_ia32_psrlqi512:
12646 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
12647 if (RHS.uge(LHS.getBitWidth())) {
12648 return APInt::getZero(LHS.getBitWidth());
12649 }
12650 return LHS.lshr(RHS.getZExtValue());
12651 });
12652 case X86::BI__builtin_ia32_packsswb128:
12653 case X86::BI__builtin_ia32_packsswb256:
12654 case X86::BI__builtin_ia32_packsswb512:
12655 case X86::BI__builtin_ia32_packssdw128:
12656 case X86::BI__builtin_ia32_packssdw256:
12657 case X86::BI__builtin_ia32_packssdw512:
12658 return evalPackBuiltin(E, Info, Result, [](const APSInt &Src) {
12659 return APSInt(Src).truncSSat(Src.getBitWidth() / 2);
12660 });
12661 case X86::BI__builtin_ia32_packusdw128:
12662 case X86::BI__builtin_ia32_packusdw256:
12663 case X86::BI__builtin_ia32_packusdw512:
12664 case X86::BI__builtin_ia32_packuswb128:
12665 case X86::BI__builtin_ia32_packuswb256:
12666 case X86::BI__builtin_ia32_packuswb512:
12667 return evalPackBuiltin(E, Info, Result, [](const APSInt &Src) {
12668 unsigned DstBits = Src.getBitWidth() / 2;
12669 if (Src.isNegative())
12670 return APInt::getZero(DstBits);
12671 if (Src.isIntN(DstBits))
12672 return APInt((Src).trunc(DstBits));
12673 return APInt::getAllOnes(DstBits);
12674 });
12675 case clang::X86::BI__builtin_ia32_selectss_128:
12676 return EvalSelectScalar(4);
12677 case clang::X86::BI__builtin_ia32_selectsd_128:
12678 return EvalSelectScalar(2);
12679 case clang::X86::BI__builtin_ia32_selectsh_128:
12680 case clang::X86::BI__builtin_ia32_selectsbf_128:
12681 return EvalSelectScalar(8);
12682 case clang::X86::BI__builtin_ia32_pmuldq128:
12683 case clang::X86::BI__builtin_ia32_pmuldq256:
12684 case clang::X86::BI__builtin_ia32_pmuldq512:
12685 case clang::X86::BI__builtin_ia32_pmuludq128:
12686 case clang::X86::BI__builtin_ia32_pmuludq256:
12687 case clang::X86::BI__builtin_ia32_pmuludq512: {
12688 APValue SourceLHS, SourceRHS;
12689 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
12690 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
12691 return false;
12692
12693 unsigned SourceLen = SourceLHS.getVectorLength();
12694 SmallVector<APValue, 4> ResultElements;
12695 ResultElements.reserve(SourceLen / 2);
12696
12697 for (unsigned EltNum = 0; EltNum < SourceLen; EltNum += 2) {
12698 APSInt LHS = SourceLHS.getVectorElt(EltNum).getInt();
12699 APSInt RHS = SourceRHS.getVectorElt(EltNum).getInt();
12700
12701 switch (E->getBuiltinCallee()) {
12702 case clang::X86::BI__builtin_ia32_pmuludq128:
12703 case clang::X86::BI__builtin_ia32_pmuludq256:
12704 case clang::X86::BI__builtin_ia32_pmuludq512:
12705 ResultElements.push_back(
12706 APValue(APSInt(llvm::APIntOps::muluExtended(LHS, RHS), true)));
12707 break;
12708 case clang::X86::BI__builtin_ia32_pmuldq128:
12709 case clang::X86::BI__builtin_ia32_pmuldq256:
12710 case clang::X86::BI__builtin_ia32_pmuldq512:
12711 ResultElements.push_back(
12712 APValue(APSInt(llvm::APIntOps::mulsExtended(LHS, RHS), false)));
12713 break;
12714 }
12715 }
12716
12717 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12718 }
12719
12720 case X86::BI__builtin_ia32_vpmadd52luq128:
12721 case X86::BI__builtin_ia32_vpmadd52luq256:
12722 case X86::BI__builtin_ia32_vpmadd52luq512: {
12723 APValue A, B, C;
12724 if (!EvaluateAsRValue(Info, E->getArg(0), A) ||
12725 !EvaluateAsRValue(Info, E->getArg(1), B) ||
12726 !EvaluateAsRValue(Info, E->getArg(2), C))
12727 return false;
12728
12729 unsigned ALen = A.getVectorLength();
12730 SmallVector<APValue, 4> ResultElements;
12731 ResultElements.reserve(ALen);
12732
12733 for (unsigned EltNum = 0; EltNum < ALen; EltNum += 1) {
12734 APInt AElt = A.getVectorElt(EltNum).getInt();
12735 APInt BElt = B.getVectorElt(EltNum).getInt().trunc(52);
12736 APInt CElt = C.getVectorElt(EltNum).getInt().trunc(52);
12737 APSInt ResElt(AElt + (BElt * CElt).zext(64), false);
12738 ResultElements.push_back(APValue(ResElt));
12739 }
12740
12741 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12742 }
12743 case X86::BI__builtin_ia32_vpmadd52huq128:
12744 case X86::BI__builtin_ia32_vpmadd52huq256:
12745 case X86::BI__builtin_ia32_vpmadd52huq512: {
12746 APValue A, B, C;
12747 if (!EvaluateAsRValue(Info, E->getArg(0), A) ||
12748 !EvaluateAsRValue(Info, E->getArg(1), B) ||
12749 !EvaluateAsRValue(Info, E->getArg(2), C))
12750 return false;
12751
12752 unsigned ALen = A.getVectorLength();
12753 SmallVector<APValue, 4> ResultElements;
12754 ResultElements.reserve(ALen);
12755
12756 for (unsigned EltNum = 0; EltNum < ALen; EltNum += 1) {
12757 APInt AElt = A.getVectorElt(EltNum).getInt();
12758 APInt BElt = B.getVectorElt(EltNum).getInt().trunc(52);
12759 APInt CElt = C.getVectorElt(EltNum).getInt().trunc(52);
12760 APSInt ResElt(AElt + llvm::APIntOps::mulhu(BElt, CElt).zext(64), false);
12761 ResultElements.push_back(APValue(ResElt));
12762 }
12763
12764 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12765 }
12766
12767 case clang::X86::BI__builtin_ia32_vprotbi:
12768 case clang::X86::BI__builtin_ia32_vprotdi:
12769 case clang::X86::BI__builtin_ia32_vprotqi:
12770 case clang::X86::BI__builtin_ia32_vprotwi:
12771 case clang::X86::BI__builtin_ia32_prold128:
12772 case clang::X86::BI__builtin_ia32_prold256:
12773 case clang::X86::BI__builtin_ia32_prold512:
12774 case clang::X86::BI__builtin_ia32_prolq128:
12775 case clang::X86::BI__builtin_ia32_prolq256:
12776 case clang::X86::BI__builtin_ia32_prolq512:
12777 return EvaluateBinOpExpr(
12778 [](const APSInt &LHS, const APSInt &RHS) { return LHS.rotl(RHS); });
12779
12780 case clang::X86::BI__builtin_ia32_prord128:
12781 case clang::X86::BI__builtin_ia32_prord256:
12782 case clang::X86::BI__builtin_ia32_prord512:
12783 case clang::X86::BI__builtin_ia32_prorq128:
12784 case clang::X86::BI__builtin_ia32_prorq256:
12785 case clang::X86::BI__builtin_ia32_prorq512:
12786 return EvaluateBinOpExpr(
12787 [](const APSInt &LHS, const APSInt &RHS) { return LHS.rotr(RHS); });
12788
12789 case Builtin::BI__builtin_elementwise_max:
12790 case Builtin::BI__builtin_elementwise_min: {
12791 APValue SourceLHS, SourceRHS;
12792 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
12793 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
12794 return false;
12795
12796 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
12797
12798 if (!DestEltTy->isIntegerType())
12799 return false;
12800
12801 unsigned SourceLen = SourceLHS.getVectorLength();
12802 SmallVector<APValue, 4> ResultElements;
12803 ResultElements.reserve(SourceLen);
12804
12805 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12806 APSInt LHS = SourceLHS.getVectorElt(EltNum).getInt();
12807 APSInt RHS = SourceRHS.getVectorElt(EltNum).getInt();
12808 switch (E->getBuiltinCallee()) {
12809 case Builtin::BI__builtin_elementwise_max:
12810 ResultElements.push_back(
12811 APValue(APSInt(std::max(LHS, RHS),
12812 DestEltTy->isUnsignedIntegerOrEnumerationType())));
12813 break;
12814 case Builtin::BI__builtin_elementwise_min:
12815 ResultElements.push_back(
12816 APValue(APSInt(std::min(LHS, RHS),
12817 DestEltTy->isUnsignedIntegerOrEnumerationType())));
12818 break;
12819 }
12820 }
12821
12822 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12823 }
12824 case X86::BI__builtin_ia32_vpshldd128:
12825 case X86::BI__builtin_ia32_vpshldd256:
12826 case X86::BI__builtin_ia32_vpshldd512:
12827 case X86::BI__builtin_ia32_vpshldq128:
12828 case X86::BI__builtin_ia32_vpshldq256:
12829 case X86::BI__builtin_ia32_vpshldq512:
12830 case X86::BI__builtin_ia32_vpshldw128:
12831 case X86::BI__builtin_ia32_vpshldw256:
12832 case X86::BI__builtin_ia32_vpshldw512: {
12833 APValue SourceHi, SourceLo, SourceAmt;
12834 if (!EvaluateAsRValue(Info, E->getArg(0), SourceHi) ||
12835 !EvaluateAsRValue(Info, E->getArg(1), SourceLo) ||
12836 !EvaluateAsRValue(Info, E->getArg(2), SourceAmt))
12837 return false;
12838
12839 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
12840 unsigned SourceLen = SourceHi.getVectorLength();
12841 SmallVector<APValue, 32> ResultElements;
12842 ResultElements.reserve(SourceLen);
12843
12844 APInt Amt = SourceAmt.getInt();
12845 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12846 APInt Hi = SourceHi.getVectorElt(EltNum).getInt();
12847 APInt Lo = SourceLo.getVectorElt(EltNum).getInt();
12848 APInt R = llvm::APIntOps::fshl(Hi, Lo, Amt);
12849 ResultElements.push_back(
12850 APValue(APSInt(R, DestEltTy->isUnsignedIntegerOrEnumerationType())));
12851 }
12852
12853 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12854 }
12855 case X86::BI__builtin_ia32_vpshrdd128:
12856 case X86::BI__builtin_ia32_vpshrdd256:
12857 case X86::BI__builtin_ia32_vpshrdd512:
12858 case X86::BI__builtin_ia32_vpshrdq128:
12859 case X86::BI__builtin_ia32_vpshrdq256:
12860 case X86::BI__builtin_ia32_vpshrdq512:
12861 case X86::BI__builtin_ia32_vpshrdw128:
12862 case X86::BI__builtin_ia32_vpshrdw256:
12863 case X86::BI__builtin_ia32_vpshrdw512: {
12864 // NOTE: Reversed Hi/Lo operands.
12865 APValue SourceHi, SourceLo, SourceAmt;
12866 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLo) ||
12867 !EvaluateAsRValue(Info, E->getArg(1), SourceHi) ||
12868 !EvaluateAsRValue(Info, E->getArg(2), SourceAmt))
12869 return false;
12870
12871 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
12872 unsigned SourceLen = SourceHi.getVectorLength();
12873 SmallVector<APValue, 32> ResultElements;
12874 ResultElements.reserve(SourceLen);
12875
12876 APInt Amt = SourceAmt.getInt();
12877 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12878 APInt Hi = SourceHi.getVectorElt(EltNum).getInt();
12879 APInt Lo = SourceLo.getVectorElt(EltNum).getInt();
12880 APInt R = llvm::APIntOps::fshr(Hi, Lo, Amt);
12881 ResultElements.push_back(
12882 APValue(APSInt(R, DestEltTy->isUnsignedIntegerOrEnumerationType())));
12883 }
12884
12885 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12886 }
12887 case X86::BI__builtin_ia32_vpconflictsi_128:
12888 case X86::BI__builtin_ia32_vpconflictsi_256:
12889 case X86::BI__builtin_ia32_vpconflictsi_512:
12890 case X86::BI__builtin_ia32_vpconflictdi_128:
12891 case X86::BI__builtin_ia32_vpconflictdi_256:
12892 case X86::BI__builtin_ia32_vpconflictdi_512: {
12893 APValue Source;
12894
12895 if (!EvaluateAsRValue(Info, E->getArg(0), Source))
12896 return false;
12897
12898 unsigned SourceLen = Source.getVectorLength();
12899 SmallVector<APValue, 32> ResultElements;
12900 ResultElements.reserve(SourceLen);
12901
12902 const auto *VecT = E->getType()->castAs<VectorType>();
12903 bool DestUnsigned =
12904 VecT->getElementType()->isUnsignedIntegerOrEnumerationType();
12905
12906 for (unsigned I = 0; I != SourceLen; ++I) {
12907 const APValue &EltI = Source.getVectorElt(I);
12908
12909 APInt ConflictMask(EltI.getInt().getBitWidth(), 0);
12910 for (unsigned J = 0; J != I; ++J) {
12911 const APValue &EltJ = Source.getVectorElt(J);
12912 ConflictMask.setBitVal(J, EltI.getInt() == EltJ.getInt());
12913 }
12914 ResultElements.push_back(APValue(APSInt(ConflictMask, DestUnsigned)));
12915 }
12916 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12917 }
12918 case X86::BI__builtin_ia32_blendpd:
12919 case X86::BI__builtin_ia32_blendpd256:
12920 case X86::BI__builtin_ia32_blendps:
12921 case X86::BI__builtin_ia32_blendps256:
12922 case X86::BI__builtin_ia32_pblendw128:
12923 case X86::BI__builtin_ia32_pblendw256:
12924 case X86::BI__builtin_ia32_pblendd128:
12925 case X86::BI__builtin_ia32_pblendd256: {
12926 APValue SourceF, SourceT, SourceC;
12927 if (!EvaluateAsRValue(Info, E->getArg(0), SourceF) ||
12928 !EvaluateAsRValue(Info, E->getArg(1), SourceT) ||
12929 !EvaluateAsRValue(Info, E->getArg(2), SourceC))
12930 return false;
12931
12932 const APInt &C = SourceC.getInt();
12933 unsigned SourceLen = SourceF.getVectorLength();
12934 SmallVector<APValue, 32> ResultElements;
12935 ResultElements.reserve(SourceLen);
12936 for (unsigned EltNum = 0; EltNum != SourceLen; ++EltNum) {
12937 const APValue &F = SourceF.getVectorElt(EltNum);
12938 const APValue &T = SourceT.getVectorElt(EltNum);
12939 ResultElements.push_back(C[EltNum % 8] ? T : F);
12940 }
12941
12942 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12943 }
12944
12945 case X86::BI__builtin_ia32_psignb128:
12946 case X86::BI__builtin_ia32_psignb256:
12947 case X86::BI__builtin_ia32_psignw128:
12948 case X86::BI__builtin_ia32_psignw256:
12949 case X86::BI__builtin_ia32_psignd128:
12950 case X86::BI__builtin_ia32_psignd256:
12951 return EvaluateBinOpExpr([](const APInt &AElem, const APInt &BElem) {
12952 if (BElem.isZero())
12953 return APInt::getZero(AElem.getBitWidth());
12954 if (BElem.isNegative())
12955 return -AElem;
12956 return AElem;
12957 });
12958
12959 case X86::BI__builtin_ia32_blendvpd:
12960 case X86::BI__builtin_ia32_blendvpd256:
12961 case X86::BI__builtin_ia32_blendvps:
12962 case X86::BI__builtin_ia32_blendvps256:
12963 case X86::BI__builtin_ia32_pblendvb128:
12964 case X86::BI__builtin_ia32_pblendvb256: {
12965 // SSE blendv by mask signbit: "Result = C[] < 0 ? T[] : F[]".
12966 APValue SourceF, SourceT, SourceC;
12967 if (!EvaluateAsRValue(Info, E->getArg(0), SourceF) ||
12968 !EvaluateAsRValue(Info, E->getArg(1), SourceT) ||
12969 !EvaluateAsRValue(Info, E->getArg(2), SourceC))
12970 return false;
12971
12972 unsigned SourceLen = SourceF.getVectorLength();
12973 SmallVector<APValue, 32> ResultElements;
12974 ResultElements.reserve(SourceLen);
12975
12976 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12977 const APValue &F = SourceF.getVectorElt(EltNum);
12978 const APValue &T = SourceT.getVectorElt(EltNum);
12979 const APValue &C = SourceC.getVectorElt(EltNum);
12980 APInt M = C.isInt() ? (APInt)C.getInt() : C.getFloat().bitcastToAPInt();
12981 ResultElements.push_back(M.isNegative() ? T : F);
12982 }
12983
12984 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12985 }
12986 case X86::BI__builtin_ia32_selectb_128:
12987 case X86::BI__builtin_ia32_selectb_256:
12988 case X86::BI__builtin_ia32_selectb_512:
12989 case X86::BI__builtin_ia32_selectw_128:
12990 case X86::BI__builtin_ia32_selectw_256:
12991 case X86::BI__builtin_ia32_selectw_512:
12992 case X86::BI__builtin_ia32_selectd_128:
12993 case X86::BI__builtin_ia32_selectd_256:
12994 case X86::BI__builtin_ia32_selectd_512:
12995 case X86::BI__builtin_ia32_selectq_128:
12996 case X86::BI__builtin_ia32_selectq_256:
12997 case X86::BI__builtin_ia32_selectq_512:
12998 case X86::BI__builtin_ia32_selectph_128:
12999 case X86::BI__builtin_ia32_selectph_256:
13000 case X86::BI__builtin_ia32_selectph_512:
13001 case X86::BI__builtin_ia32_selectpbf_128:
13002 case X86::BI__builtin_ia32_selectpbf_256:
13003 case X86::BI__builtin_ia32_selectpbf_512:
13004 case X86::BI__builtin_ia32_selectps_128:
13005 case X86::BI__builtin_ia32_selectps_256:
13006 case X86::BI__builtin_ia32_selectps_512:
13007 case X86::BI__builtin_ia32_selectpd_128:
13008 case X86::BI__builtin_ia32_selectpd_256:
13009 case X86::BI__builtin_ia32_selectpd_512: {
13010 // AVX512 predicated move: "Result = Mask[] ? LHS[] : RHS[]".
13011 APValue SourceMask, SourceLHS, SourceRHS;
13012 if (!EvaluateAsRValue(Info, E->getArg(0), SourceMask) ||
13013 !EvaluateAsRValue(Info, E->getArg(1), SourceLHS) ||
13014 !EvaluateAsRValue(Info, E->getArg(2), SourceRHS))
13015 return false;
13016
13017 APSInt Mask = SourceMask.getInt();
13018 unsigned SourceLen = SourceLHS.getVectorLength();
13019 SmallVector<APValue, 4> ResultElements;
13020 ResultElements.reserve(SourceLen);
13021
13022 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
13023 const APValue &LHS = SourceLHS.getVectorElt(EltNum);
13024 const APValue &RHS = SourceRHS.getVectorElt(EltNum);
13025 ResultElements.push_back(Mask[EltNum] ? LHS : RHS);
13026 }
13027
13028 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13029 }
13030
13031 case X86::BI__builtin_ia32_cvtsd2ss: {
13032 APValue VecA, VecB;
13033 if (!EvaluateAsRValue(Info, E->getArg(0), VecA) ||
13034 !EvaluateAsRValue(Info, E->getArg(1), VecB))
13035 return false;
13036
13037 SmallVector<APValue, 4> Elements;
13038
13039 APValue ResultVal;
13040 if (!ConvertDoubleToFloatStrict(Info, E, VecB.getVectorElt(0).getFloat(),
13041 ResultVal))
13042 return false;
13043
13044 Elements.push_back(ResultVal);
13045
13046 unsigned NumEltsA = VecA.getVectorLength();
13047 for (unsigned I = 1; I < NumEltsA; ++I) {
13048 Elements.push_back(VecA.getVectorElt(I));
13049 }
13050
13051 return Success(Elements, E);
13052 }
13053 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: {
13054 APValue VecA, VecB, VecSrc, MaskValue;
13055
13056 if (!EvaluateAsRValue(Info, E->getArg(0), VecA) ||
13057 !EvaluateAsRValue(Info, E->getArg(1), VecB) ||
13058 !EvaluateAsRValue(Info, E->getArg(2), VecSrc) ||
13059 !EvaluateAsRValue(Info, E->getArg(3), MaskValue))
13060 return false;
13061
13062 unsigned Mask = MaskValue.getInt().getZExtValue();
13063 SmallVector<APValue, 4> Elements;
13064
13065 if (Mask & 1) {
13066 APValue ResultVal;
13067 if (!ConvertDoubleToFloatStrict(Info, E, VecB.getVectorElt(0).getFloat(),
13068 ResultVal))
13069 return false;
13070 Elements.push_back(ResultVal);
13071 } else {
13072 Elements.push_back(VecSrc.getVectorElt(0));
13073 }
13074
13075 unsigned NumEltsA = VecA.getVectorLength();
13076 for (unsigned I = 1; I < NumEltsA; ++I) {
13077 Elements.push_back(VecA.getVectorElt(I));
13078 }
13079
13080 return Success(Elements, E);
13081 }
13082 case X86::BI__builtin_ia32_cvtpd2ps:
13083 case X86::BI__builtin_ia32_cvtpd2ps256:
13084 case X86::BI__builtin_ia32_cvtpd2ps_mask:
13085 case X86::BI__builtin_ia32_cvtpd2ps512_mask: {
13086
13087 const auto BuiltinID = E->getBuiltinCallee();
13088 bool IsMasked = (BuiltinID == X86::BI__builtin_ia32_cvtpd2ps_mask ||
13089 BuiltinID == X86::BI__builtin_ia32_cvtpd2ps512_mask);
13090
13091 APValue InputValue;
13092 if (!EvaluateAsRValue(Info, E->getArg(0), InputValue))
13093 return false;
13094
13095 APValue MergeValue;
13096 unsigned Mask = 0xFFFFFFFF;
13097 bool NeedsMerge = false;
13098 if (IsMasked) {
13099 APValue MaskValue;
13100 if (!EvaluateAsRValue(Info, E->getArg(2), MaskValue))
13101 return false;
13102 Mask = MaskValue.getInt().getZExtValue();
13103 auto NumEltsResult = E->getType()->getAs<VectorType>()->getNumElements();
13104 for (unsigned I = 0; I < NumEltsResult; ++I) {
13105 if (!((Mask >> I) & 1)) {
13106 NeedsMerge = true;
13107 break;
13108 }
13109 }
13110 if (NeedsMerge) {
13111 if (!EvaluateAsRValue(Info, E->getArg(1), MergeValue))
13112 return false;
13113 }
13114 }
13115
13116 unsigned NumEltsResult =
13117 E->getType()->getAs<VectorType>()->getNumElements();
13118 unsigned NumEltsInput = InputValue.getVectorLength();
13119 SmallVector<APValue, 8> Elements;
13120 for (unsigned I = 0; I < NumEltsResult; ++I) {
13121 if (IsMasked && !((Mask >> I) & 1)) {
13122 if (!NeedsMerge) {
13123 return false;
13124 }
13125 Elements.push_back(MergeValue.getVectorElt(I));
13126 continue;
13127 }
13128
13129 if (I >= NumEltsInput) {
13130 Elements.push_back(APValue(APFloat::getZero(APFloat::IEEEsingle())));
13131 continue;
13132 }
13133
13134 APValue ResultVal;
13135 if (!ConvertDoubleToFloatStrict(
13136 Info, E, InputValue.getVectorElt(I).getFloat(), ResultVal))
13137 return false;
13138
13139 Elements.push_back(ResultVal);
13140 }
13141 return Success(Elements, E);
13142 }
13143
13144 case X86::BI__builtin_ia32_shufps:
13145 case X86::BI__builtin_ia32_shufps256:
13146 case X86::BI__builtin_ia32_shufps512: {
13147 APValue R;
13148 if (!evalShuffleGeneric(
13149 Info, E, R,
13150 [](unsigned DstIdx,
13151 unsigned ShuffleMask) -> std::pair<unsigned, int> {
13152 constexpr unsigned LaneBits = 128u;
13153 unsigned NumElemPerLane = LaneBits / 32;
13154 unsigned NumSelectableElems = NumElemPerLane / 2;
13155 unsigned BitsPerElem = 2;
13156 unsigned IndexMask = (1u << BitsPerElem) - 1;
13157 unsigned MaskBits = 8;
13158 unsigned Lane = DstIdx / NumElemPerLane;
13159 unsigned ElemInLane = DstIdx % NumElemPerLane;
13160 unsigned LaneOffset = Lane * NumElemPerLane;
13161 unsigned BitIndex = (DstIdx * BitsPerElem) % MaskBits;
13162 unsigned SrcIdx = (ElemInLane < NumSelectableElems) ? 0 : 1;
13163 unsigned Index = (ShuffleMask >> BitIndex) & IndexMask;
13164 return {SrcIdx, static_cast<int>(LaneOffset + Index)};
13165 }))
13166 return false;
13167 return Success(R, E);
13168 }
13169 case X86::BI__builtin_ia32_shufpd:
13170 case X86::BI__builtin_ia32_shufpd256:
13171 case X86::BI__builtin_ia32_shufpd512: {
13172 APValue R;
13173 if (!evalShuffleGeneric(
13174 Info, E, R,
13175 [](unsigned DstIdx,
13176 unsigned ShuffleMask) -> std::pair<unsigned, int> {
13177 constexpr unsigned LaneBits = 128u;
13178 unsigned NumElemPerLane = LaneBits / 64;
13179 unsigned NumSelectableElems = NumElemPerLane / 2;
13180 unsigned BitsPerElem = 1;
13181 unsigned IndexMask = (1u << BitsPerElem) - 1;
13182 unsigned MaskBits = 8;
13183 unsigned Lane = DstIdx / NumElemPerLane;
13184 unsigned ElemInLane = DstIdx % NumElemPerLane;
13185 unsigned LaneOffset = Lane * NumElemPerLane;
13186 unsigned BitIndex = (DstIdx * BitsPerElem) % MaskBits;
13187 unsigned SrcIdx = (ElemInLane < NumSelectableElems) ? 0 : 1;
13188 unsigned Index = (ShuffleMask >> BitIndex) & IndexMask;
13189 return {SrcIdx, static_cast<int>(LaneOffset + Index)};
13190 }))
13191 return false;
13192 return Success(R, E);
13193 }
13194 case X86::BI__builtin_ia32_insertps128: {
13195 APValue R;
13196 if (!evalShuffleGeneric(
13197 Info, E, R,
13198 [](unsigned DstIdx, unsigned Mask) -> std::pair<unsigned, int> {
13199 // Bits [3:0]: zero mask - if bit is set, zero this element
13200 if ((Mask & (1 << DstIdx)) != 0) {
13201 return {0, -1};
13202 }
13203 // Bits [7:6]: select element from source vector Y (0-3)
13204 // Bits [5:4]: select destination position (0-3)
13205 unsigned SrcElem = (Mask >> 6) & 0x3;
13206 unsigned DstElem = (Mask >> 4) & 0x3;
13207 if (DstIdx == DstElem) {
13208 // Insert element from source vector (B) at this position
13209 return {1, static_cast<int>(SrcElem)};
13210 } else {
13211 // Copy from destination vector (A)
13212 return {0, static_cast<int>(DstIdx)};
13213 }
13214 }))
13215 return false;
13216 return Success(R, E);
13217 }
13218 case X86::BI__builtin_ia32_pshufb128:
13219 case X86::BI__builtin_ia32_pshufb256:
13220 case X86::BI__builtin_ia32_pshufb512: {
13221 APValue R;
13222 if (!evalShuffleGeneric(
13223 Info, E, R,
13224 [](unsigned DstIdx,
13225 unsigned ShuffleMask) -> std::pair<unsigned, int> {
13226 uint8_t Ctlb = static_cast<uint8_t>(ShuffleMask);
13227 if (Ctlb & 0x80)
13228 return std::make_pair(0, -1);
13229
13230 unsigned LaneBase = (DstIdx / 16) * 16;
13231 unsigned SrcOffset = Ctlb & 0x0F;
13232 unsigned SrcIdx = LaneBase + SrcOffset;
13233 return std::make_pair(0, static_cast<int>(SrcIdx));
13234 }))
13235 return false;
13236 return Success(R, E);
13237 }
13238
13239 case X86::BI__builtin_ia32_pshuflw:
13240 case X86::BI__builtin_ia32_pshuflw256:
13241 case X86::BI__builtin_ia32_pshuflw512: {
13242 APValue R;
13243 if (!evalShuffleGeneric(
13244 Info, E, R,
13245 [](unsigned DstIdx, unsigned Mask) -> std::pair<unsigned, int> {
13246 constexpr unsigned LaneBits = 128u;
13247 constexpr unsigned ElemBits = 16u;
13248 constexpr unsigned LaneElts = LaneBits / ElemBits;
13249 constexpr unsigned HalfSize = 4;
13250 unsigned LaneBase = (DstIdx / LaneElts) * LaneElts;
13251 unsigned LaneIdx = DstIdx % LaneElts;
13252 if (LaneIdx < HalfSize) {
13253 unsigned Sel = (Mask >> (2 * LaneIdx)) & 0x3;
13254 return std::make_pair(0, static_cast<int>(LaneBase + Sel));
13255 }
13256 return std::make_pair(0, static_cast<int>(DstIdx));
13257 }))
13258 return false;
13259 return Success(R, E);
13260 }
13261
13262 case X86::BI__builtin_ia32_pshufhw:
13263 case X86::BI__builtin_ia32_pshufhw256:
13264 case X86::BI__builtin_ia32_pshufhw512: {
13265 APValue R;
13266 if (!evalShuffleGeneric(
13267 Info, E, R,
13268 [](unsigned DstIdx, unsigned Mask) -> std::pair<unsigned, int> {
13269 constexpr unsigned LaneBits = 128u;
13270 constexpr unsigned ElemBits = 16u;
13271 constexpr unsigned LaneElts = LaneBits / ElemBits;
13272 constexpr unsigned HalfSize = 4;
13273 unsigned LaneBase = (DstIdx / LaneElts) * LaneElts;
13274 unsigned LaneIdx = DstIdx % LaneElts;
13275 if (LaneIdx >= HalfSize) {
13276 unsigned Rel = LaneIdx - HalfSize;
13277 unsigned Sel = (Mask >> (2 * Rel)) & 0x3;
13278 return std::make_pair(
13279 0, static_cast<int>(LaneBase + HalfSize + Sel));
13280 }
13281 return std::make_pair(0, static_cast<int>(DstIdx));
13282 }))
13283 return false;
13284 return Success(R, E);
13285 }
13286
13287 case X86::BI__builtin_ia32_pshufd:
13288 case X86::BI__builtin_ia32_pshufd256:
13289 case X86::BI__builtin_ia32_pshufd512:
13290 case X86::BI__builtin_ia32_vpermilps:
13291 case X86::BI__builtin_ia32_vpermilps256:
13292 case X86::BI__builtin_ia32_vpermilps512: {
13293 APValue R;
13294 if (!evalShuffleGeneric(
13295 Info, E, R,
13296 [](unsigned DstIdx, unsigned Mask) -> std::pair<unsigned, int> {
13297 constexpr unsigned LaneBits = 128u;
13298 constexpr unsigned ElemBits = 32u;
13299 constexpr unsigned LaneElts = LaneBits / ElemBits;
13300 unsigned LaneBase = (DstIdx / LaneElts) * LaneElts;
13301 unsigned LaneIdx = DstIdx % LaneElts;
13302 unsigned Sel = (Mask >> (2 * LaneIdx)) & 0x3;
13303 return std::make_pair(0, static_cast<int>(LaneBase + Sel));
13304 }))
13305 return false;
13306 return Success(R, E);
13307 }
13308
13309 case X86::BI__builtin_ia32_vpermilvarpd:
13310 case X86::BI__builtin_ia32_vpermilvarpd256:
13311 case X86::BI__builtin_ia32_vpermilvarpd512: {
13312 APValue R;
13313 if (!evalShuffleGeneric(
13314 Info, E, R,
13315 [](unsigned DstIdx, unsigned Mask) -> std::pair<unsigned, int> {
13316 unsigned NumElemPerLane = 2;
13317 unsigned Lane = DstIdx / NumElemPerLane;
13318 unsigned Offset = Mask & 0b10 ? 1 : 0;
13319 return std::make_pair(
13320 0, static_cast<int>(Lane * NumElemPerLane + Offset));
13321 }))
13322 return false;
13323 return Success(R, E);
13324 }
13325
13326 case X86::BI__builtin_ia32_vpermilpd:
13327 case X86::BI__builtin_ia32_vpermilpd256:
13328 case X86::BI__builtin_ia32_vpermilpd512: {
13329 APValue R;
13330 if (!evalShuffleGeneric(Info, E, R, [](unsigned DstIdx, unsigned Control) {
13331 unsigned NumElemPerLane = 2;
13332 unsigned BitsPerElem = 1;
13333 unsigned MaskBits = 8;
13334 unsigned IndexMask = 0x1;
13335 unsigned Lane = DstIdx / NumElemPerLane;
13336 unsigned LaneOffset = Lane * NumElemPerLane;
13337 unsigned BitIndex = (DstIdx * BitsPerElem) % MaskBits;
13338 unsigned Index = (Control >> BitIndex) & IndexMask;
13339 return std::make_pair(0, static_cast<int>(LaneOffset + Index));
13340 }))
13341 return false;
13342 return Success(R, E);
13343 }
13344
13345 case X86::BI__builtin_ia32_permdf256:
13346 case X86::BI__builtin_ia32_permdi256: {
13347 APValue R;
13348 if (!evalShuffleGeneric(Info, E, R, [](unsigned DstIdx, unsigned Control) {
13349 // permute4x64 operates on 4 64-bit elements
13350 // For element i (0-3), extract bits [2*i+1:2*i] from Control
13351 unsigned Index = (Control >> (2 * DstIdx)) & 0x3;
13352 return std::make_pair(0, static_cast<int>(Index));
13353 }))
13354 return false;
13355 return Success(R, E);
13356 }
13357
13358 case X86::BI__builtin_ia32_vpermilvarps:
13359 case X86::BI__builtin_ia32_vpermilvarps256:
13360 case X86::BI__builtin_ia32_vpermilvarps512: {
13361 APValue R;
13362 if (!evalShuffleGeneric(
13363 Info, E, R,
13364 [](unsigned DstIdx, unsigned Mask) -> std::pair<unsigned, int> {
13365 unsigned NumElemPerLane = 4;
13366 unsigned Lane = DstIdx / NumElemPerLane;
13367 unsigned Offset = Mask & 0b11;
13368 return std::make_pair(
13369 0, static_cast<int>(Lane * NumElemPerLane + Offset));
13370 }))
13371 return false;
13372 return Success(R, E);
13373 }
13374
13375 case X86::BI__builtin_ia32_vpmultishiftqb128:
13376 case X86::BI__builtin_ia32_vpmultishiftqb256:
13377 case X86::BI__builtin_ia32_vpmultishiftqb512: {
13378 assert(E->getNumArgs() == 2);
13379
13380 APValue A, B;
13381 if (!Evaluate(A, Info, E->getArg(0)) || !Evaluate(B, Info, E->getArg(1)))
13382 return false;
13383
13384 assert(A.getVectorLength() == B.getVectorLength());
13385 unsigned NumBytesInQWord = 8;
13386 unsigned NumBitsInByte = 8;
13387 unsigned NumBytes = A.getVectorLength();
13388 unsigned NumQWords = NumBytes / NumBytesInQWord;
13389 SmallVector<APValue, 64> Result;
13390 Result.reserve(NumBytes);
13391
13392 for (unsigned QWordId = 0; QWordId != NumQWords; ++QWordId) {
13393 APInt BQWord(64, 0);
13394 for (unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
13395 unsigned Idx = QWordId * NumBytesInQWord + ByteIdx;
13396 uint64_t Byte = B.getVectorElt(Idx).getInt().getZExtValue();
13397 BQWord.insertBits(APInt(8, Byte & 0xFF), ByteIdx * NumBitsInByte);
13398 }
13399
13400 for (unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
13401 unsigned Idx = QWordId * NumBytesInQWord + ByteIdx;
13402 uint64_t Ctrl = A.getVectorElt(Idx).getInt().getZExtValue() & 0x3F;
13403
13404 APInt Byte(8, 0);
13405 for (unsigned BitIdx = 0; BitIdx != NumBitsInByte; ++BitIdx) {
13406 Byte.setBitVal(BitIdx, BQWord[(Ctrl + BitIdx) & 0x3F]);
13407 }
13408 Result.push_back(APValue(APSInt(Byte, /*isUnsigned*/ true)));
13409 }
13410 }
13411 return Success(APValue(Result.data(), Result.size()), E);
13412 }
13413
13414 case X86::BI__builtin_ia32_phminposuw128: {
13415 APValue Source;
13416 if (!Evaluate(Source, Info, E->getArg(0)))
13417 return false;
13418 unsigned SourceLen = Source.getVectorLength();
13419 const VectorType *VT = E->getArg(0)->getType()->castAs<VectorType>();
13420 QualType ElemQT = VT->getElementType();
13421 unsigned ElemBitWidth = Info.Ctx.getTypeSize(ElemQT);
13422
13423 APInt MinIndex(ElemBitWidth, 0);
13424 APInt MinVal = Source.getVectorElt(0).getInt();
13425 for (unsigned I = 1; I != SourceLen; ++I) {
13426 APInt Val = Source.getVectorElt(I).getInt();
13427 if (MinVal.ugt(Val)) {
13428 MinVal = Val;
13429 MinIndex = I;
13430 }
13431 }
13432
13433 bool ResultUnsigned = E->getCallReturnType(Info.Ctx)
13434 ->castAs<VectorType>()
13435 ->getElementType()
13436 ->isUnsignedIntegerOrEnumerationType();
13437
13438 SmallVector<APValue, 8> Result;
13439 Result.reserve(SourceLen);
13440 Result.emplace_back(APSInt(MinVal, ResultUnsigned));
13441 Result.emplace_back(APSInt(MinIndex, ResultUnsigned));
13442 for (unsigned I = 0; I != SourceLen - 2; ++I) {
13443 Result.emplace_back(APSInt(APInt(ElemBitWidth, 0), ResultUnsigned));
13444 }
13445 return Success(APValue(Result.data(), Result.size()), E);
13446 }
13447
13448 case X86::BI__builtin_ia32_psraq128:
13449 case X86::BI__builtin_ia32_psraq256:
13450 case X86::BI__builtin_ia32_psraq512:
13451 case X86::BI__builtin_ia32_psrad128:
13452 case X86::BI__builtin_ia32_psrad256:
13453 case X86::BI__builtin_ia32_psrad512:
13454 case X86::BI__builtin_ia32_psraw128:
13455 case X86::BI__builtin_ia32_psraw256:
13456 case X86::BI__builtin_ia32_psraw512: {
13457 APValue R;
13458 if (!evalShiftWithCount(
13459 Info, E, R,
13460 [](const APInt &Elt, uint64_t Count) { return Elt.ashr(Count); },
13461 [](const APInt &Elt, unsigned Width) {
13462 return Elt.ashr(Width - 1);
13463 }))
13464 return false;
13465 return Success(R, E);
13466 }
13467
13468 case X86::BI__builtin_ia32_psllq128:
13469 case X86::BI__builtin_ia32_psllq256:
13470 case X86::BI__builtin_ia32_psllq512:
13471 case X86::BI__builtin_ia32_pslld128:
13472 case X86::BI__builtin_ia32_pslld256:
13473 case X86::BI__builtin_ia32_pslld512:
13474 case X86::BI__builtin_ia32_psllw128:
13475 case X86::BI__builtin_ia32_psllw256:
13476 case X86::BI__builtin_ia32_psllw512: {
13477 APValue R;
13478 if (!evalShiftWithCount(
13479 Info, E, R,
13480 [](const APInt &Elt, uint64_t Count) { return Elt.shl(Count); },
13481 [](const APInt &Elt, unsigned Width) {
13482 return APInt::getZero(Width);
13483 }))
13484 return false;
13485 return Success(R, E);
13486 }
13487
13488 case X86::BI__builtin_ia32_psrlq128:
13489 case X86::BI__builtin_ia32_psrlq256:
13490 case X86::BI__builtin_ia32_psrlq512:
13491 case X86::BI__builtin_ia32_psrld128:
13492 case X86::BI__builtin_ia32_psrld256:
13493 case X86::BI__builtin_ia32_psrld512:
13494 case X86::BI__builtin_ia32_psrlw128:
13495 case X86::BI__builtin_ia32_psrlw256:
13496 case X86::BI__builtin_ia32_psrlw512: {
13497 APValue R;
13498 if (!evalShiftWithCount(
13499 Info, E, R,
13500 [](const APInt &Elt, uint64_t Count) { return Elt.lshr(Count); },
13501 [](const APInt &Elt, unsigned Width) {
13502 return APInt::getZero(Width);
13503 }))
13504 return false;
13505 return Success(R, E);
13506 }
13507
13508 case X86::BI__builtin_ia32_pternlogd128_mask:
13509 case X86::BI__builtin_ia32_pternlogd256_mask:
13510 case X86::BI__builtin_ia32_pternlogd512_mask:
13511 case X86::BI__builtin_ia32_pternlogq128_mask:
13512 case X86::BI__builtin_ia32_pternlogq256_mask:
13513 case X86::BI__builtin_ia32_pternlogq512_mask: {
13514 APValue AValue, BValue, CValue, ImmValue, UValue;
13515 if (!EvaluateAsRValue(Info, E->getArg(0), AValue) ||
13516 !EvaluateAsRValue(Info, E->getArg(1), BValue) ||
13517 !EvaluateAsRValue(Info, E->getArg(2), CValue) ||
13518 !EvaluateAsRValue(Info, E->getArg(3), ImmValue) ||
13519 !EvaluateAsRValue(Info, E->getArg(4), UValue))
13520 return false;
13521
13522 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
13523 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
13524 APInt Imm = ImmValue.getInt();
13525 APInt U = UValue.getInt();
13526 unsigned ResultLen = AValue.getVectorLength();
13527 SmallVector<APValue, 16> ResultElements;
13528 ResultElements.reserve(ResultLen);
13529
13530 for (unsigned EltNum = 0; EltNum < ResultLen; ++EltNum) {
13531 APInt ALane = AValue.getVectorElt(EltNum).getInt();
13532 APInt BLane = BValue.getVectorElt(EltNum).getInt();
13533 APInt CLane = CValue.getVectorElt(EltNum).getInt();
13534
13535 if (U[EltNum]) {
13536 unsigned BitWidth = ALane.getBitWidth();
13537 APInt ResLane(BitWidth, 0);
13538
13539 for (unsigned Bit = 0; Bit < BitWidth; ++Bit) {
13540 unsigned ABit = ALane[Bit];
13541 unsigned BBit = BLane[Bit];
13542 unsigned CBit = CLane[Bit];
13543
13544 unsigned Idx = (ABit << 2) | (BBit << 1) | CBit;
13545 ResLane.setBitVal(Bit, Imm[Idx]);
13546 }
13547 ResultElements.push_back(APValue(APSInt(ResLane, DestUnsigned)));
13548 } else {
13549 ResultElements.push_back(APValue(APSInt(ALane, DestUnsigned)));
13550 }
13551 }
13552 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13553 }
13554 case X86::BI__builtin_ia32_pternlogd128_maskz:
13555 case X86::BI__builtin_ia32_pternlogd256_maskz:
13556 case X86::BI__builtin_ia32_pternlogd512_maskz:
13557 case X86::BI__builtin_ia32_pternlogq128_maskz:
13558 case X86::BI__builtin_ia32_pternlogq256_maskz:
13559 case X86::BI__builtin_ia32_pternlogq512_maskz: {
13560 APValue AValue, BValue, CValue, ImmValue, UValue;
13561 if (!EvaluateAsRValue(Info, E->getArg(0), AValue) ||
13562 !EvaluateAsRValue(Info, E->getArg(1), BValue) ||
13563 !EvaluateAsRValue(Info, E->getArg(2), CValue) ||
13564 !EvaluateAsRValue(Info, E->getArg(3), ImmValue) ||
13565 !EvaluateAsRValue(Info, E->getArg(4), UValue))
13566 return false;
13567
13568 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
13569 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
13570 APInt Imm = ImmValue.getInt();
13571 APInt U = UValue.getInt();
13572 unsigned ResultLen = AValue.getVectorLength();
13573 SmallVector<APValue, 16> ResultElements;
13574 ResultElements.reserve(ResultLen);
13575
13576 for (unsigned EltNum = 0; EltNum < ResultLen; ++EltNum) {
13577 APInt ALane = AValue.getVectorElt(EltNum).getInt();
13578 APInt BLane = BValue.getVectorElt(EltNum).getInt();
13579 APInt CLane = CValue.getVectorElt(EltNum).getInt();
13580
13581 unsigned BitWidth = ALane.getBitWidth();
13582 APInt ResLane(BitWidth, 0);
13583
13584 if (U[EltNum]) {
13585 for (unsigned Bit = 0; Bit < BitWidth; ++Bit) {
13586 unsigned ABit = ALane[Bit];
13587 unsigned BBit = BLane[Bit];
13588 unsigned CBit = CLane[Bit];
13589
13590 unsigned Idx = (ABit << 2) | (BBit << 1) | CBit;
13591 ResLane.setBitVal(Bit, Imm[Idx]);
13592 }
13593 }
13594 ResultElements.push_back(APValue(APSInt(ResLane, DestUnsigned)));
13595 }
13596 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13597 }
13598
13599 case Builtin::BI__builtin_elementwise_clzg:
13600 case Builtin::BI__builtin_elementwise_ctzg: {
13601 APValue SourceLHS;
13602 std::optional<APValue> Fallback;
13603 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS))
13604 return false;
13605 if (E->getNumArgs() > 1) {
13606 APValue FallbackTmp;
13607 if (!EvaluateAsRValue(Info, E->getArg(1), FallbackTmp))
13608 return false;
13609 Fallback = FallbackTmp;
13610 }
13611
13612 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
13613 unsigned SourceLen = SourceLHS.getVectorLength();
13614 SmallVector<APValue, 4> ResultElements;
13615 ResultElements.reserve(SourceLen);
13616
13617 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
13618 APSInt LHS = SourceLHS.getVectorElt(EltNum).getInt();
13619 if (!LHS) {
13620 // Without a fallback, a zero element is undefined
13621 if (!Fallback) {
13622 Info.FFDiag(E, diag::note_constexpr_countzeroes_zero)
13623 << /*IsTrailing=*/(E->getBuiltinCallee() ==
13624 Builtin::BI__builtin_elementwise_ctzg);
13625 return false;
13626 }
13627 ResultElements.push_back(Fallback->getVectorElt(EltNum));
13628 continue;
13629 }
13630 switch (E->getBuiltinCallee()) {
13631 case Builtin::BI__builtin_elementwise_clzg:
13632 ResultElements.push_back(APValue(
13633 APSInt(APInt(Info.Ctx.getIntWidth(DestEltTy), LHS.countl_zero()),
13634 DestEltTy->isUnsignedIntegerOrEnumerationType())));
13635 break;
13636 case Builtin::BI__builtin_elementwise_ctzg:
13637 ResultElements.push_back(APValue(
13638 APSInt(APInt(Info.Ctx.getIntWidth(DestEltTy), LHS.countr_zero()),
13639 DestEltTy->isUnsignedIntegerOrEnumerationType())));
13640 break;
13641 }
13642 }
13643
13644 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13645 }
13646
13647 case Builtin::BI__builtin_elementwise_fma: {
13648 APValue SourceX, SourceY, SourceZ;
13649 if (!EvaluateAsRValue(Info, E->getArg(0), SourceX) ||
13650 !EvaluateAsRValue(Info, E->getArg(1), SourceY) ||
13651 !EvaluateAsRValue(Info, E->getArg(2), SourceZ))
13652 return false;
13653
13654 unsigned SourceLen = SourceX.getVectorLength();
13655 SmallVector<APValue> ResultElements;
13656 ResultElements.reserve(SourceLen);
13657 llvm::RoundingMode RM = getActiveRoundingMode(getEvalInfo(), E);
13658 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
13659 const APFloat &X = SourceX.getVectorElt(EltNum).getFloat();
13660 const APFloat &Y = SourceY.getVectorElt(EltNum).getFloat();
13661 const APFloat &Z = SourceZ.getVectorElt(EltNum).getFloat();
13662 APFloat Result(X);
13663 (void)Result.fusedMultiplyAdd(Y, Z, RM);
13664 ResultElements.push_back(APValue(Result));
13665 }
13666 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13667 }
13668
13669 case clang::X86::BI__builtin_ia32_phaddw128:
13670 case clang::X86::BI__builtin_ia32_phaddw256:
13671 case clang::X86::BI__builtin_ia32_phaddd128:
13672 case clang::X86::BI__builtin_ia32_phaddd256:
13673 case clang::X86::BI__builtin_ia32_phaddsw128:
13674 case clang::X86::BI__builtin_ia32_phaddsw256:
13675
13676 case clang::X86::BI__builtin_ia32_phsubw128:
13677 case clang::X86::BI__builtin_ia32_phsubw256:
13678 case clang::X86::BI__builtin_ia32_phsubd128:
13679 case clang::X86::BI__builtin_ia32_phsubd256:
13680 case clang::X86::BI__builtin_ia32_phsubsw128:
13681 case clang::X86::BI__builtin_ia32_phsubsw256: {
13682 APValue SourceLHS, SourceRHS;
13683 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
13684 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
13685 return false;
13686 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
13687 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
13688
13689 unsigned NumElts = SourceLHS.getVectorLength();
13690 unsigned EltBits = Info.Ctx.getIntWidth(DestEltTy);
13691 unsigned EltsPerLane = 128 / EltBits;
13692 SmallVector<APValue, 4> ResultElements;
13693 ResultElements.reserve(NumElts);
13694
13695 for (unsigned LaneStart = 0; LaneStart != NumElts;
13696 LaneStart += EltsPerLane) {
13697 for (unsigned I = 0; I != EltsPerLane; I += 2) {
13698 APSInt LHSA = SourceLHS.getVectorElt(LaneStart + I).getInt();
13699 APSInt LHSB = SourceLHS.getVectorElt(LaneStart + I + 1).getInt();
13700 switch (E->getBuiltinCallee()) {
13701 case clang::X86::BI__builtin_ia32_phaddw128:
13702 case clang::X86::BI__builtin_ia32_phaddw256:
13703 case clang::X86::BI__builtin_ia32_phaddd128:
13704 case clang::X86::BI__builtin_ia32_phaddd256: {
13705 APSInt Res(LHSA + LHSB, DestUnsigned);
13706 ResultElements.push_back(APValue(Res));
13707 break;
13708 }
13709 case clang::X86::BI__builtin_ia32_phaddsw128:
13710 case clang::X86::BI__builtin_ia32_phaddsw256: {
13711 APSInt Res(LHSA.sadd_sat(LHSB));
13712 ResultElements.push_back(APValue(Res));
13713 break;
13714 }
13715 case clang::X86::BI__builtin_ia32_phsubw128:
13716 case clang::X86::BI__builtin_ia32_phsubw256:
13717 case clang::X86::BI__builtin_ia32_phsubd128:
13718 case clang::X86::BI__builtin_ia32_phsubd256: {
13719 APSInt Res(LHSA - LHSB, DestUnsigned);
13720 ResultElements.push_back(APValue(Res));
13721 break;
13722 }
13723 case clang::X86::BI__builtin_ia32_phsubsw128:
13724 case clang::X86::BI__builtin_ia32_phsubsw256: {
13725 APSInt Res(LHSA.ssub_sat(LHSB));
13726 ResultElements.push_back(APValue(Res));
13727 break;
13728 }
13729 }
13730 }
13731 for (unsigned I = 0; I != EltsPerLane; I += 2) {
13732 APSInt RHSA = SourceRHS.getVectorElt(LaneStart + I).getInt();
13733 APSInt RHSB = SourceRHS.getVectorElt(LaneStart + I + 1).getInt();
13734 switch (E->getBuiltinCallee()) {
13735 case clang::X86::BI__builtin_ia32_phaddw128:
13736 case clang::X86::BI__builtin_ia32_phaddw256:
13737 case clang::X86::BI__builtin_ia32_phaddd128:
13738 case clang::X86::BI__builtin_ia32_phaddd256: {
13739 APSInt Res(RHSA + RHSB, DestUnsigned);
13740 ResultElements.push_back(APValue(Res));
13741 break;
13742 }
13743 case clang::X86::BI__builtin_ia32_phaddsw128:
13744 case clang::X86::BI__builtin_ia32_phaddsw256: {
13745 APSInt Res(RHSA.sadd_sat(RHSB));
13746 ResultElements.push_back(APValue(Res));
13747 break;
13748 }
13749 case clang::X86::BI__builtin_ia32_phsubw128:
13750 case clang::X86::BI__builtin_ia32_phsubw256:
13751 case clang::X86::BI__builtin_ia32_phsubd128:
13752 case clang::X86::BI__builtin_ia32_phsubd256: {
13753 APSInt Res(RHSA - RHSB, DestUnsigned);
13754 ResultElements.push_back(APValue(Res));
13755 break;
13756 }
13757 case clang::X86::BI__builtin_ia32_phsubsw128:
13758 case clang::X86::BI__builtin_ia32_phsubsw256: {
13759 APSInt Res(RHSA.ssub_sat(RHSB));
13760 ResultElements.push_back(APValue(Res));
13761 break;
13762 }
13763 }
13764 }
13765 }
13766 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13767 }
13768 case clang::X86::BI__builtin_ia32_haddpd:
13769 case clang::X86::BI__builtin_ia32_haddps:
13770 case clang::X86::BI__builtin_ia32_haddps256:
13771 case clang::X86::BI__builtin_ia32_haddpd256:
13772 case clang::X86::BI__builtin_ia32_hsubpd:
13773 case clang::X86::BI__builtin_ia32_hsubps:
13774 case clang::X86::BI__builtin_ia32_hsubps256:
13775 case clang::X86::BI__builtin_ia32_hsubpd256: {
13776 APValue SourceLHS, SourceRHS;
13777 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
13778 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
13779 return false;
13780 unsigned NumElts = SourceLHS.getVectorLength();
13781 SmallVector<APValue, 4> ResultElements;
13782 ResultElements.reserve(NumElts);
13783 llvm::RoundingMode RM = getActiveRoundingMode(getEvalInfo(), E);
13784 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
13785 unsigned EltBits = Info.Ctx.getTypeSize(DestEltTy);
13786 unsigned NumLanes = NumElts * EltBits / 128;
13787 unsigned NumElemsPerLane = NumElts / NumLanes;
13788 unsigned HalfElemsPerLane = NumElemsPerLane / 2;
13789
13790 for (unsigned L = 0; L != NumElts; L += NumElemsPerLane) {
13791 for (unsigned I = 0; I != HalfElemsPerLane; ++I) {
13792 APFloat LHSA = SourceLHS.getVectorElt(L + (2 * I) + 0).getFloat();
13793 APFloat LHSB = SourceLHS.getVectorElt(L + (2 * I) + 1).getFloat();
13794 switch (E->getBuiltinCallee()) {
13795 case clang::X86::BI__builtin_ia32_haddpd:
13796 case clang::X86::BI__builtin_ia32_haddps:
13797 case clang::X86::BI__builtin_ia32_haddps256:
13798 case clang::X86::BI__builtin_ia32_haddpd256:
13799 LHSA.add(LHSB, RM);
13800 break;
13801 case clang::X86::BI__builtin_ia32_hsubpd:
13802 case clang::X86::BI__builtin_ia32_hsubps:
13803 case clang::X86::BI__builtin_ia32_hsubps256:
13804 case clang::X86::BI__builtin_ia32_hsubpd256:
13805 LHSA.subtract(LHSB, RM);
13806 break;
13807 }
13808 ResultElements.push_back(APValue(LHSA));
13809 }
13810 for (unsigned I = 0; I != HalfElemsPerLane; ++I) {
13811 APFloat RHSA = SourceRHS.getVectorElt(L + (2 * I) + 0).getFloat();
13812 APFloat RHSB = SourceRHS.getVectorElt(L + (2 * I) + 1).getFloat();
13813 switch (E->getBuiltinCallee()) {
13814 case clang::X86::BI__builtin_ia32_haddpd:
13815 case clang::X86::BI__builtin_ia32_haddps:
13816 case clang::X86::BI__builtin_ia32_haddps256:
13817 case clang::X86::BI__builtin_ia32_haddpd256:
13818 RHSA.add(RHSB, RM);
13819 break;
13820 case clang::X86::BI__builtin_ia32_hsubpd:
13821 case clang::X86::BI__builtin_ia32_hsubps:
13822 case clang::X86::BI__builtin_ia32_hsubps256:
13823 case clang::X86::BI__builtin_ia32_hsubpd256:
13824 RHSA.subtract(RHSB, RM);
13825 break;
13826 }
13827 ResultElements.push_back(APValue(RHSA));
13828 }
13829 }
13830 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13831 }
13832 case clang::X86::BI__builtin_ia32_addsubpd:
13833 case clang::X86::BI__builtin_ia32_addsubps:
13834 case clang::X86::BI__builtin_ia32_addsubpd256:
13835 case clang::X86::BI__builtin_ia32_addsubps256: {
13836 // Addsub: alternates between subtraction and addition
13837 // Result[i] = (i % 2 == 0) ? (a[i] - b[i]) : (a[i] + b[i])
13838 APValue SourceLHS, SourceRHS;
13839 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
13840 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
13841 return false;
13842 unsigned NumElems = SourceLHS.getVectorLength();
13843 SmallVector<APValue, 8> ResultElements;
13844 ResultElements.reserve(NumElems);
13845 llvm::RoundingMode RM = getActiveRoundingMode(getEvalInfo(), E);
13846
13847 for (unsigned I = 0; I != NumElems; ++I) {
13848 APFloat LHS = SourceLHS.getVectorElt(I).getFloat();
13849 APFloat RHS = SourceRHS.getVectorElt(I).getFloat();
13850 if (I % 2 == 0) {
13851 // Even indices: subtract
13852 LHS.subtract(RHS, RM);
13853 } else {
13854 // Odd indices: add
13855 LHS.add(RHS, RM);
13856 }
13857 ResultElements.push_back(APValue(LHS));
13858 }
13859 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13860 }
13861 case clang::X86::BI__builtin_ia32_pclmulqdq128:
13862 case clang::X86::BI__builtin_ia32_pclmulqdq256:
13863 case clang::X86::BI__builtin_ia32_pclmulqdq512: {
13864 // PCLMULQDQ: carry-less multiplication of selected 64-bit halves
13865 // imm8 bit 0: selects lower (0) or upper (1) 64 bits of first operand
13866 // imm8 bit 4: selects lower (0) or upper (1) 64 bits of second operand
13867 APValue SourceLHS, SourceRHS;
13868 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
13869 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
13870 return false;
13871
13872 APSInt Imm8;
13873 if (!EvaluateInteger(E->getArg(2), Imm8, Info))
13874 return false;
13875
13876 // Extract bits 0 and 4 from imm8
13877 bool SelectUpperA = (Imm8 & 0x01) != 0;
13878 bool SelectUpperB = (Imm8 & 0x10) != 0;
13879
13880 unsigned NumElems = SourceLHS.getVectorLength();
13881 SmallVector<APValue, 8> ResultElements;
13882 ResultElements.reserve(NumElems);
13883 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
13884 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
13885
13886 // Process each 128-bit lane
13887 for (unsigned Lane = 0; Lane < NumElems; Lane += 2) {
13888 // Get the two 64-bit halves of the first operand
13889 APSInt A0 = SourceLHS.getVectorElt(Lane + 0).getInt();
13890 APSInt A1 = SourceLHS.getVectorElt(Lane + 1).getInt();
13891 // Get the two 64-bit halves of the second operand
13892 APSInt B0 = SourceRHS.getVectorElt(Lane + 0).getInt();
13893 APSInt B1 = SourceRHS.getVectorElt(Lane + 1).getInt();
13894
13895 // Select the appropriate 64-bit values based on imm8
13896 APInt A = SelectUpperA ? A1 : A0;
13897 APInt B = SelectUpperB ? B1 : B0;
13898
13899 // Extend both operands to 128 bits for carry-less multiplication
13900 APInt A128 = A.zext(128);
13901 APInt B128 = B.zext(128);
13902
13903 // Use APIntOps::clmul for carry-less multiplication
13904 APInt Result = llvm::APIntOps::clmul(A128, B128);
13905
13906 // Split the 128-bit result into two 64-bit halves
13907 APSInt ResultLow(Result.extractBits(64, 0), DestUnsigned);
13908 APSInt ResultHigh(Result.extractBits(64, 64), DestUnsigned);
13909
13910 ResultElements.push_back(APValue(ResultLow));
13911 ResultElements.push_back(APValue(ResultHigh));
13912 }
13913
13914 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13915 }
13916 case Builtin::BI__builtin_elementwise_fshl:
13917 case Builtin::BI__builtin_elementwise_fshr: {
13918 APValue SourceHi, SourceLo, SourceShift;
13919 if (!EvaluateAsRValue(Info, E->getArg(0), SourceHi) ||
13920 !EvaluateAsRValue(Info, E->getArg(1), SourceLo) ||
13921 !EvaluateAsRValue(Info, E->getArg(2), SourceShift))
13922 return false;
13923
13924 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
13925 if (!DestEltTy->isIntegerType())
13926 return false;
13927
13928 unsigned SourceLen = SourceHi.getVectorLength();
13929 SmallVector<APValue> ResultElements;
13930 ResultElements.reserve(SourceLen);
13931 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
13932 const APSInt &Hi = SourceHi.getVectorElt(EltNum).getInt();
13933 const APSInt &Lo = SourceLo.getVectorElt(EltNum).getInt();
13934 const APSInt &Shift = SourceShift.getVectorElt(EltNum).getInt();
13935 switch (E->getBuiltinCallee()) {
13936 case Builtin::BI__builtin_elementwise_fshl:
13937 ResultElements.push_back(APValue(
13938 APSInt(llvm::APIntOps::fshl(Hi, Lo, Shift), Hi.isUnsigned())));
13939 break;
13940 case Builtin::BI__builtin_elementwise_fshr:
13941 ResultElements.push_back(APValue(
13942 APSInt(llvm::APIntOps::fshr(Hi, Lo, Shift), Hi.isUnsigned())));
13943 break;
13944 }
13945 }
13946
13947 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13948 }
13949
13950 case X86::BI__builtin_ia32_shuf_f32x4_256:
13951 case X86::BI__builtin_ia32_shuf_i32x4_256:
13952 case X86::BI__builtin_ia32_shuf_f64x2_256:
13953 case X86::BI__builtin_ia32_shuf_i64x2_256:
13954 case X86::BI__builtin_ia32_shuf_f32x4:
13955 case X86::BI__builtin_ia32_shuf_i32x4:
13956 case X86::BI__builtin_ia32_shuf_f64x2:
13957 case X86::BI__builtin_ia32_shuf_i64x2: {
13958 APValue SourceA, SourceB;
13959 if (!EvaluateAsRValue(Info, E->getArg(0), SourceA) ||
13960 !EvaluateAsRValue(Info, E->getArg(1), SourceB))
13961 return false;
13962
13963 APSInt Imm;
13964 if (!EvaluateInteger(E->getArg(2), Imm, Info))
13965 return false;
13966
13967 // Destination and sources A, B all have the same type.
13968 unsigned NumElems = SourceA.getVectorLength();
13969 const VectorType *VT = E->getArg(0)->getType()->castAs<VectorType>();
13970 QualType ElemQT = VT->getElementType();
13971 unsigned ElemBits = Info.Ctx.getTypeSize(ElemQT);
13972 unsigned LaneBits = 128u;
13973 unsigned NumLanes = (NumElems * ElemBits) / LaneBits;
13974 unsigned NumElemsPerLane = LaneBits / ElemBits;
13975
13976 unsigned DstLen = SourceA.getVectorLength();
13977 SmallVector<APValue, 16> ResultElements;
13978 ResultElements.reserve(DstLen);
13979
13980 APValue R;
13981 if (!evalShuffleGeneric(
13982 Info, E, R,
13983 [NumLanes, NumElemsPerLane](unsigned DstIdx, unsigned ShuffleMask)
13984 -> std::pair<unsigned, int> {
13985 // DstIdx determines source. ShuffleMask selects lane in source.
13986 unsigned BitsPerElem = NumLanes / 2;
13987 unsigned IndexMask = (1u << BitsPerElem) - 1;
13988 unsigned Lane = DstIdx / NumElemsPerLane;
13989 unsigned SrcIdx = (Lane < NumLanes / 2) ? 0 : 1;
13990 unsigned BitIdx = BitsPerElem * Lane;
13991 unsigned SrcLaneIdx = (ShuffleMask >> BitIdx) & IndexMask;
13992 unsigned ElemInLane = DstIdx % NumElemsPerLane;
13993 unsigned IdxToPick = SrcLaneIdx * NumElemsPerLane + ElemInLane;
13994 return {SrcIdx, IdxToPick};
13995 }))
13996 return false;
13997 return Success(R, E);
13998 }
13999
14000 case X86::BI__builtin_ia32_vgf2p8affineinvqb_v16qi:
14001 case X86::BI__builtin_ia32_vgf2p8affineinvqb_v32qi:
14002 case X86::BI__builtin_ia32_vgf2p8affineinvqb_v64qi:
14003 case X86::BI__builtin_ia32_vgf2p8affineqb_v16qi:
14004 case X86::BI__builtin_ia32_vgf2p8affineqb_v32qi:
14005 case X86::BI__builtin_ia32_vgf2p8affineqb_v64qi: {
14006
14007 APValue X, A;
14008 APSInt Imm;
14009 if (!EvaluateAsRValue(Info, E->getArg(0), X) ||
14010 !EvaluateAsRValue(Info, E->getArg(1), A) ||
14011 !EvaluateInteger(E->getArg(2), Imm, Info))
14012 return false;
14013
14014 assert(X.isVector() && A.isVector());
14015 assert(X.getVectorLength() == A.getVectorLength());
14016
14017 bool IsInverse = false;
14018 switch (E->getBuiltinCallee()) {
14019 case X86::BI__builtin_ia32_vgf2p8affineinvqb_v16qi:
14020 case X86::BI__builtin_ia32_vgf2p8affineinvqb_v32qi:
14021 case X86::BI__builtin_ia32_vgf2p8affineinvqb_v64qi: {
14022 IsInverse = true;
14023 }
14024 }
14025
14026 unsigned NumBitsInByte = 8;
14027 unsigned NumBytesInQWord = 8;
14028 unsigned NumBitsInQWord = 64;
14029 unsigned NumBytes = A.getVectorLength();
14030 unsigned NumQWords = NumBytes / NumBytesInQWord;
14031 SmallVector<APValue, 64> Result;
14032 Result.reserve(NumBytes);
14033
14034 // computing A*X + Imm
14035 for (unsigned QWordIdx = 0; QWordIdx != NumQWords; ++QWordIdx) {
14036 // Extract the QWords from X, A
14037 APInt XQWord(NumBitsInQWord, 0);
14038 APInt AQWord(NumBitsInQWord, 0);
14039 for (unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
14040 unsigned Idx = QWordIdx * NumBytesInQWord + ByteIdx;
14041 APInt XByte = X.getVectorElt(Idx).getInt();
14042 APInt AByte = A.getVectorElt(Idx).getInt();
14043 XQWord.insertBits(XByte, ByteIdx * NumBitsInByte);
14044 AQWord.insertBits(AByte, ByteIdx * NumBitsInByte);
14045 }
14046
14047 for (unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
14048 uint8_t XByte =
14049 XQWord.lshr(ByteIdx * NumBitsInByte).getLoBits(8).getZExtValue();
14050 Result.push_back(APValue(APSInt(
14051 APInt(8, GFNIAffine(XByte, AQWord, Imm, IsInverse)), false)));
14052 }
14053 }
14054
14055 return Success(APValue(Result.data(), Result.size()), E);
14056 }
14057
14058 case X86::BI__builtin_ia32_vgf2p8mulb_v16qi:
14059 case X86::BI__builtin_ia32_vgf2p8mulb_v32qi:
14060 case X86::BI__builtin_ia32_vgf2p8mulb_v64qi: {
14061 APValue A, B;
14062 if (!EvaluateAsRValue(Info, E->getArg(0), A) ||
14063 !EvaluateAsRValue(Info, E->getArg(1), B))
14064 return false;
14065
14066 assert(A.isVector() && B.isVector());
14067 assert(A.getVectorLength() == B.getVectorLength());
14068
14069 unsigned NumBytes = A.getVectorLength();
14070 SmallVector<APValue, 64> Result;
14071 Result.reserve(NumBytes);
14072
14073 for (unsigned ByteIdx = 0; ByteIdx != NumBytes; ++ByteIdx) {
14074 uint8_t AByte = A.getVectorElt(ByteIdx).getInt().getZExtValue();
14075 uint8_t BByte = B.getVectorElt(ByteIdx).getInt().getZExtValue();
14076 Result.push_back(APValue(
14077 APSInt(APInt(8, GFNIMul(AByte, BByte)), /*IsUnsigned=*/false)));
14078 }
14079
14080 return Success(APValue(Result.data(), Result.size()), E);
14081 }
14082
14083 case X86::BI__builtin_ia32_insertf32x4_256:
14084 case X86::BI__builtin_ia32_inserti32x4_256:
14085 case X86::BI__builtin_ia32_insertf64x2_256:
14086 case X86::BI__builtin_ia32_inserti64x2_256:
14087 case X86::BI__builtin_ia32_insertf32x4:
14088 case X86::BI__builtin_ia32_inserti32x4:
14089 case X86::BI__builtin_ia32_insertf64x2_512:
14090 case X86::BI__builtin_ia32_inserti64x2_512:
14091 case X86::BI__builtin_ia32_insertf32x8:
14092 case X86::BI__builtin_ia32_inserti32x8:
14093 case X86::BI__builtin_ia32_insertf64x4:
14094 case X86::BI__builtin_ia32_inserti64x4:
14095 case X86::BI__builtin_ia32_vinsertf128_ps256:
14096 case X86::BI__builtin_ia32_vinsertf128_pd256:
14097 case X86::BI__builtin_ia32_vinsertf128_si256:
14098 case X86::BI__builtin_ia32_insert128i256: {
14099 APValue SourceDst, SourceSub;
14100 if (!EvaluateAsRValue(Info, E->getArg(0), SourceDst) ||
14101 !EvaluateAsRValue(Info, E->getArg(1), SourceSub))
14102 return false;
14103
14104 APSInt Imm;
14105 if (!EvaluateInteger(E->getArg(2), Imm, Info))
14106 return false;
14107
14108 assert(SourceDst.isVector() && SourceSub.isVector());
14109 unsigned DstLen = SourceDst.getVectorLength();
14110 unsigned SubLen = SourceSub.getVectorLength();
14111 assert(SubLen != 0 && DstLen != 0 && (DstLen % SubLen) == 0);
14112 unsigned NumLanes = DstLen / SubLen;
14113 unsigned LaneIdx = (Imm.getZExtValue() % NumLanes) * SubLen;
14114
14115 SmallVector<APValue, 16> ResultElements;
14116 ResultElements.reserve(DstLen);
14117
14118 for (unsigned EltNum = 0; EltNum < DstLen; ++EltNum) {
14119 if (EltNum >= LaneIdx && EltNum < LaneIdx + SubLen)
14120 ResultElements.push_back(SourceSub.getVectorElt(EltNum - LaneIdx));
14121 else
14122 ResultElements.push_back(SourceDst.getVectorElt(EltNum));
14123 }
14124
14125 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
14126 }
14127
14128 case clang::X86::BI__builtin_ia32_vec_set_v4hi:
14129 case clang::X86::BI__builtin_ia32_vec_set_v16qi:
14130 case clang::X86::BI__builtin_ia32_vec_set_v8hi:
14131 case clang::X86::BI__builtin_ia32_vec_set_v4si:
14132 case clang::X86::BI__builtin_ia32_vec_set_v2di:
14133 case clang::X86::BI__builtin_ia32_vec_set_v32qi:
14134 case clang::X86::BI__builtin_ia32_vec_set_v16hi:
14135 case clang::X86::BI__builtin_ia32_vec_set_v8si:
14136 case clang::X86::BI__builtin_ia32_vec_set_v4di: {
14137 APValue VecVal;
14138 APSInt Scalar, IndexAPS;
14139 if (!EvaluateVector(E->getArg(0), VecVal, Info) ||
14140 !EvaluateInteger(E->getArg(1), Scalar, Info) ||
14141 !EvaluateInteger(E->getArg(2), IndexAPS, Info))
14142 return false;
14143
14144 QualType ElemTy = E->getType()->castAs<VectorType>()->getElementType();
14145 unsigned ElemWidth = Info.Ctx.getIntWidth(ElemTy);
14146 bool ElemUnsigned = ElemTy->isUnsignedIntegerOrEnumerationType();
14147 Scalar.setIsUnsigned(ElemUnsigned);
14148 APSInt ElemAPS = Scalar.extOrTrunc(ElemWidth);
14149 APValue ElemAV(ElemAPS);
14150
14151 unsigned NumElems = VecVal.getVectorLength();
14152 unsigned Index =
14153 static_cast<unsigned>(IndexAPS.getZExtValue() & (NumElems - 1));
14154
14155 SmallVector<APValue, 4> Elems;
14156 Elems.reserve(NumElems);
14157 for (unsigned ElemNum = 0; ElemNum != NumElems; ++ElemNum)
14158 Elems.push_back(ElemNum == Index ? ElemAV : VecVal.getVectorElt(ElemNum));
14159
14160 return Success(APValue(Elems.data(), NumElems), E);
14161 }
14162
14163 case X86::BI__builtin_ia32_pslldqi128_byteshift:
14164 case X86::BI__builtin_ia32_pslldqi256_byteshift:
14165 case X86::BI__builtin_ia32_pslldqi512_byteshift: {
14166 APValue R;
14167 if (!evalShuffleGeneric(
14168 Info, E, R,
14169 [](unsigned DstIdx, unsigned Shift) -> std::pair<unsigned, int> {
14170 unsigned LaneBase = (DstIdx / 16) * 16;
14171 unsigned LaneIdx = DstIdx % 16;
14172 if (LaneIdx < Shift)
14173 return std::make_pair(0, -1);
14174
14175 return std::make_pair(
14176 0, static_cast<int>(LaneBase + LaneIdx - Shift));
14177 }))
14178 return false;
14179 return Success(R, E);
14180 }
14181
14182 case X86::BI__builtin_ia32_psrldqi128_byteshift:
14183 case X86::BI__builtin_ia32_psrldqi256_byteshift:
14184 case X86::BI__builtin_ia32_psrldqi512_byteshift: {
14185 APValue R;
14186 if (!evalShuffleGeneric(
14187 Info, E, R,
14188 [](unsigned DstIdx, unsigned Shift) -> std::pair<unsigned, int> {
14189 unsigned LaneBase = (DstIdx / 16) * 16;
14190 unsigned LaneIdx = DstIdx % 16;
14191 if (LaneIdx + Shift < 16)
14192 return std::make_pair(
14193 0, static_cast<int>(LaneBase + LaneIdx + Shift));
14194
14195 return std::make_pair(0, -1);
14196 }))
14197 return false;
14198 return Success(R, E);
14199 }
14200
14201 case X86::BI__builtin_ia32_palignr128:
14202 case X86::BI__builtin_ia32_palignr256:
14203 case X86::BI__builtin_ia32_palignr512: {
14204 APValue R;
14205 if (!evalShuffleGeneric(Info, E, R, [](unsigned DstIdx, unsigned Shift) {
14206 // Default to -1 → zero-fill this destination element
14207 unsigned VecIdx = 1;
14208 int ElemIdx = -1;
14209
14210 int Lane = DstIdx / 16;
14211 int Offset = DstIdx % 16;
14212
14213 // Elements come from VecB first, then VecA after the shift boundary
14214 unsigned ShiftedIdx = Offset + (Shift & 0xFF);
14215 if (ShiftedIdx < 16) { // from VecB
14216 ElemIdx = ShiftedIdx + (Lane * 16);
14217 } else if (ShiftedIdx < 32) { // from VecA
14218 VecIdx = 0;
14219 ElemIdx = (ShiftedIdx - 16) + (Lane * 16);
14220 }
14221
14222 return std::pair<unsigned, int>{VecIdx, ElemIdx};
14223 }))
14224 return false;
14225 return Success(R, E);
14226 }
14227 case X86::BI__builtin_ia32_alignd128:
14228 case X86::BI__builtin_ia32_alignd256:
14229 case X86::BI__builtin_ia32_alignd512:
14230 case X86::BI__builtin_ia32_alignq128:
14231 case X86::BI__builtin_ia32_alignq256:
14232 case X86::BI__builtin_ia32_alignq512: {
14233 APValue R;
14234 unsigned NumElems = E->getType()->castAs<VectorType>()->getNumElements();
14235 if (!evalShuffleGeneric(Info, E, R,
14236 [NumElems](unsigned DstIdx, unsigned Shift) {
14237 unsigned Imm = Shift & 0xFF;
14238 unsigned EffectiveShift = Imm & (NumElems - 1);
14239 unsigned SourcePos = DstIdx + EffectiveShift;
14240 unsigned VecIdx = SourcePos < NumElems ? 1 : 0;
14241 unsigned ElemIdx = SourcePos & (NumElems - 1);
14242
14243 return std::pair<unsigned, int>{
14244 VecIdx, static_cast<int>(ElemIdx)};
14245 }))
14246 return false;
14247 return Success(R, E);
14248 }
14249 case X86::BI__builtin_ia32_permvarsi256:
14250 case X86::BI__builtin_ia32_permvarsf256:
14251 case X86::BI__builtin_ia32_permvardf512:
14252 case X86::BI__builtin_ia32_permvardi512:
14253 case X86::BI__builtin_ia32_permvarhi128: {
14254 APValue R;
14255 if (!evalShuffleGeneric(Info, E, R,
14256 [](unsigned DstIdx, unsigned ShuffleMask) {
14257 int Offset = ShuffleMask & 0x7;
14258 return std::pair<unsigned, int>{0, Offset};
14259 }))
14260 return false;
14261 return Success(R, E);
14262 }
14263 case X86::BI__builtin_ia32_permvarqi128:
14264 case X86::BI__builtin_ia32_permvarhi256:
14265 case X86::BI__builtin_ia32_permvarsi512:
14266 case X86::BI__builtin_ia32_permvarsf512: {
14267 APValue R;
14268 if (!evalShuffleGeneric(Info, E, R,
14269 [](unsigned DstIdx, unsigned ShuffleMask) {
14270 int Offset = ShuffleMask & 0xF;
14271 return std::pair<unsigned, int>{0, Offset};
14272 }))
14273 return false;
14274 return Success(R, E);
14275 }
14276 case X86::BI__builtin_ia32_permvardi256:
14277 case X86::BI__builtin_ia32_permvardf256: {
14278 APValue R;
14279 if (!evalShuffleGeneric(Info, E, R,
14280 [](unsigned DstIdx, unsigned ShuffleMask) {
14281 int Offset = ShuffleMask & 0x3;
14282 return std::pair<unsigned, int>{0, Offset};
14283 }))
14284 return false;
14285 return Success(R, E);
14286 }
14287 case X86::BI__builtin_ia32_permvarqi256:
14288 case X86::BI__builtin_ia32_permvarhi512: {
14289 APValue R;
14290 if (!evalShuffleGeneric(Info, E, R,
14291 [](unsigned DstIdx, unsigned ShuffleMask) {
14292 int Offset = ShuffleMask & 0x1F;
14293 return std::pair<unsigned, int>{0, Offset};
14294 }))
14295 return false;
14296 return Success(R, E);
14297 }
14298 case X86::BI__builtin_ia32_permvarqi512: {
14299 APValue R;
14300 if (!evalShuffleGeneric(Info, E, R,
14301 [](unsigned DstIdx, unsigned ShuffleMask) {
14302 int Offset = ShuffleMask & 0x3F;
14303 return std::pair<unsigned, int>{0, Offset};
14304 }))
14305 return false;
14306 return Success(R, E);
14307 }
14308 case X86::BI__builtin_ia32_vpermi2varq128:
14309 case X86::BI__builtin_ia32_vpermi2varpd128: {
14310 APValue R;
14311 if (!evalShuffleGeneric(Info, E, R,
14312 [](unsigned DstIdx, unsigned ShuffleMask) {
14313 int Offset = ShuffleMask & 0x1;
14314 unsigned SrcIdx = (ShuffleMask >> 1) & 0x1;
14315 return std::pair<unsigned, int>{SrcIdx, Offset};
14316 }))
14317 return false;
14318 return Success(R, E);
14319 }
14320 case X86::BI__builtin_ia32_vpermi2vard128:
14321 case X86::BI__builtin_ia32_vpermi2varps128:
14322 case X86::BI__builtin_ia32_vpermi2varq256:
14323 case X86::BI__builtin_ia32_vpermi2varpd256: {
14324 APValue R;
14325 if (!evalShuffleGeneric(Info, E, R,
14326 [](unsigned DstIdx, unsigned ShuffleMask) {
14327 int Offset = ShuffleMask & 0x3;
14328 unsigned SrcIdx = (ShuffleMask >> 2) & 0x1;
14329 return std::pair<unsigned, int>{SrcIdx, Offset};
14330 }))
14331 return false;
14332 return Success(R, E);
14333 }
14334 case X86::BI__builtin_ia32_vpermi2varhi128:
14335 case X86::BI__builtin_ia32_vpermi2vard256:
14336 case X86::BI__builtin_ia32_vpermi2varps256:
14337 case X86::BI__builtin_ia32_vpermi2varq512:
14338 case X86::BI__builtin_ia32_vpermi2varpd512: {
14339 APValue R;
14340 if (!evalShuffleGeneric(Info, E, R,
14341 [](unsigned DstIdx, unsigned ShuffleMask) {
14342 int Offset = ShuffleMask & 0x7;
14343 unsigned SrcIdx = (ShuffleMask >> 3) & 0x1;
14344 return std::pair<unsigned, int>{SrcIdx, Offset};
14345 }))
14346 return false;
14347 return Success(R, E);
14348 }
14349 case X86::BI__builtin_ia32_vpermi2varqi128:
14350 case X86::BI__builtin_ia32_vpermi2varhi256:
14351 case X86::BI__builtin_ia32_vpermi2vard512:
14352 case X86::BI__builtin_ia32_vpermi2varps512: {
14353 APValue R;
14354 if (!evalShuffleGeneric(Info, E, R,
14355 [](unsigned DstIdx, unsigned ShuffleMask) {
14356 int Offset = ShuffleMask & 0xF;
14357 unsigned SrcIdx = (ShuffleMask >> 4) & 0x1;
14358 return std::pair<unsigned, int>{SrcIdx, Offset};
14359 }))
14360 return false;
14361 return Success(R, E);
14362 }
14363 case X86::BI__builtin_ia32_vpermi2varqi256:
14364 case X86::BI__builtin_ia32_vpermi2varhi512: {
14365 APValue R;
14366 if (!evalShuffleGeneric(Info, E, R,
14367 [](unsigned DstIdx, unsigned ShuffleMask) {
14368 int Offset = ShuffleMask & 0x1F;
14369 unsigned SrcIdx = (ShuffleMask >> 5) & 0x1;
14370 return std::pair<unsigned, int>{SrcIdx, Offset};
14371 }))
14372 return false;
14373 return Success(R, E);
14374 }
14375 case X86::BI__builtin_ia32_vpermi2varqi512: {
14376 APValue R;
14377 if (!evalShuffleGeneric(Info, E, R,
14378 [](unsigned DstIdx, unsigned ShuffleMask) {
14379 int Offset = ShuffleMask & 0x3F;
14380 unsigned SrcIdx = (ShuffleMask >> 6) & 0x1;
14381 return std::pair<unsigned, int>{SrcIdx, Offset};
14382 }))
14383 return false;
14384 return Success(R, E);
14385 }
14386
14387 case clang::X86::BI__builtin_ia32_minps:
14388 case clang::X86::BI__builtin_ia32_minpd:
14389 case clang::X86::BI__builtin_ia32_minps256:
14390 case clang::X86::BI__builtin_ia32_minpd256:
14391 case clang::X86::BI__builtin_ia32_minps512:
14392 case clang::X86::BI__builtin_ia32_minpd512:
14393 case clang::X86::BI__builtin_ia32_minph128:
14394 case clang::X86::BI__builtin_ia32_minph256:
14395 case clang::X86::BI__builtin_ia32_minph512:
14396 return EvaluateFpBinOpExpr(
14397 [](const APFloat &A, const APFloat &B, std::optional<APSInt>) {
14398 if (A.isZero() && B.isZero())
14399 return B;
14400 return llvm::minimum(A, B);
14401 });
14402
14403 case clang::X86::BI__builtin_ia32_maxps:
14404 case clang::X86::BI__builtin_ia32_maxpd:
14405 case clang::X86::BI__builtin_ia32_maxps256:
14406 case clang::X86::BI__builtin_ia32_maxpd256:
14407 case clang::X86::BI__builtin_ia32_maxps512:
14408 case clang::X86::BI__builtin_ia32_maxpd512:
14409 case clang::X86::BI__builtin_ia32_maxph128:
14410 case clang::X86::BI__builtin_ia32_maxph256:
14411 case clang::X86::BI__builtin_ia32_maxph512:
14412 return EvaluateFpBinOpExpr(
14413 [](const APFloat &A, const APFloat &B, std::optional<APSInt>) {
14414 if (A.isZero() && B.isZero())
14415 return B;
14416 return llvm::maximum(A, B);
14417 });
14418
14419 case clang::X86::BI__builtin_ia32_vcvtps2ph:
14420 case clang::X86::BI__builtin_ia32_vcvtps2ph256: {
14421 APValue SrcVec;
14422 if (!EvaluateAsRValue(Info, E->getArg(0), SrcVec))
14423 return false;
14424
14425 APSInt Imm;
14426 if (!EvaluateInteger(E->getArg(1), Imm, Info))
14427 return false;
14428
14429 const auto *SrcVTy = E->getArg(0)->getType()->castAs<VectorType>();
14430 unsigned SrcNumElems = SrcVTy->getNumElements();
14431 const auto *DstVTy = E->getType()->castAs<VectorType>();
14432 unsigned DstNumElems = DstVTy->getNumElements();
14433 QualType DstElemTy = DstVTy->getElementType();
14434
14435 const llvm::fltSemantics &HalfSem =
14436 Info.Ctx.getFloatTypeSemantics(Info.Ctx.HalfTy);
14437
14438 int ImmVal = Imm.getZExtValue();
14439 bool UseMXCSR = (ImmVal & 4) != 0;
14440 bool IsFPConstrained =
14441 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained();
14442
14443 llvm::RoundingMode RM;
14444 if (!UseMXCSR) {
14445 switch (ImmVal & 3) {
14446 case 0:
14447 RM = llvm::RoundingMode::NearestTiesToEven;
14448 break;
14449 case 1:
14450 RM = llvm::RoundingMode::TowardNegative;
14451 break;
14452 case 2:
14453 RM = llvm::RoundingMode::TowardPositive;
14454 break;
14455 case 3:
14456 RM = llvm::RoundingMode::TowardZero;
14457 break;
14458 default:
14459 llvm_unreachable("Invalid immediate rounding mode");
14460 }
14461 } else {
14462 RM = llvm::RoundingMode::NearestTiesToEven;
14463 }
14464
14465 SmallVector<APValue, 8> ResultElements;
14466 ResultElements.reserve(DstNumElems);
14467
14468 for (unsigned I = 0; I < SrcNumElems; ++I) {
14469 APFloat SrcVal = SrcVec.getVectorElt(I).getFloat();
14470
14471 bool LostInfo;
14472 APFloat::opStatus St = SrcVal.convert(HalfSem, RM, &LostInfo);
14473
14474 if (UseMXCSR && IsFPConstrained && St != APFloat::opOK) {
14475 Info.FFDiag(E, diag::note_constexpr_dynamic_rounding);
14476 return false;
14477 }
14478
14479 APSInt DstInt(SrcVal.bitcastToAPInt(),
14480 DstElemTy->isUnsignedIntegerOrEnumerationType());
14481 ResultElements.push_back(APValue(DstInt));
14482 }
14483
14484 if (DstNumElems > SrcNumElems) {
14485 APSInt Zero = Info.Ctx.MakeIntValue(0, DstElemTy);
14486 for (unsigned I = SrcNumElems; I < DstNumElems; ++I) {
14487 ResultElements.push_back(APValue(Zero));
14488 }
14489 }
14490
14491 return Success(ResultElements, E);
14492 }
14493 case X86::BI__builtin_ia32_vperm2f128_pd256:
14494 case X86::BI__builtin_ia32_vperm2f128_ps256:
14495 case X86::BI__builtin_ia32_vperm2f128_si256:
14496 case X86::BI__builtin_ia32_permti256: {
14497 unsigned NumElements =
14498 E->getArg(0)->getType()->getAs<VectorType>()->getNumElements();
14499 unsigned PreservedBitsCnt = NumElements >> 2;
14500 APValue R;
14501 if (!evalShuffleGeneric(
14502 Info, E, R,
14503 [PreservedBitsCnt](unsigned DstIdx, unsigned ShuffleMask) {
14504 unsigned ControlBitsCnt = DstIdx >> PreservedBitsCnt << 2;
14505 unsigned ControlBits = ShuffleMask >> ControlBitsCnt;
14506
14507 if (ControlBits & 0b1000)
14508 return std::make_pair(0u, -1);
14509
14510 unsigned SrcVecIdx = (ControlBits & 0b10) >> 1;
14511 unsigned PreservedBitsMask = (1 << PreservedBitsCnt) - 1;
14512 int SrcIdx = ((ControlBits & 0b1) << PreservedBitsCnt) |
14513 (DstIdx & PreservedBitsMask);
14514 return std::make_pair(SrcVecIdx, SrcIdx);
14515 }))
14516 return false;
14517 return Success(R, E);
14518 }
14519 }
14520 }
14521
14522 bool VectorExprEvaluator::VisitConvertVectorExpr(const ConvertVectorExpr *E) {
14523 APValue Source;
14524 QualType SourceVecType = E->getSrcExpr()->getType();
14525 if (!EvaluateAsRValue(Info, E->getSrcExpr(), Source))
14526 return false;
14527
14528 QualType DestTy = E->getType()->castAs<VectorType>()->getElementType();
14529 QualType SourceTy = SourceVecType->castAs<VectorType>()->getElementType();
14530
14531 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
14532
14533 auto SourceLen = Source.getVectorLength();
14534 SmallVector<APValue, 4> ResultElements;
14535 ResultElements.reserve(SourceLen);
14536 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
14537 APValue Elt;
14538 if (!handleVectorElementCast(Info, FPO, E, SourceTy, DestTy,
14539 Source.getVectorElt(EltNum), Elt))
14540 return false;
14541 ResultElements.push_back(std::move(Elt));
14542 }
14543
14544 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
14545 }
14546
14547 static bool handleVectorShuffle(EvalInfo &Info, const ShuffleVectorExpr *E,
14548 QualType ElemType, APValue const &VecVal1,
14549 APValue const &VecVal2, unsigned EltNum,
14550 APValue &Result) {
14551 unsigned const TotalElementsInInputVector1 = VecVal1.getVectorLength();
14552 unsigned const TotalElementsInInputVector2 = VecVal2.getVectorLength();
14553
14554 APSInt IndexVal = E->getShuffleMaskIdx(EltNum);
14555 int64_t index = IndexVal.getExtValue();
14556 // The spec says that -1 should be treated as undef for optimizations,
14557 // but in constexpr we'd have to produce an APValue::Indeterminate,
14558 // which is prohibited from being a top-level constant value. Emit a
14559 // diagnostic instead.
14560 if (index == -1) {
14561 Info.FFDiag(
14562 E, diag::err_shufflevector_minus_one_is_undefined_behavior_constexpr)
14563 << EltNum;
14564 return false;
14565 }
14566
14567 if (index < 0 ||
14568 index >= TotalElementsInInputVector1 + TotalElementsInInputVector2)
14569 llvm_unreachable("Out of bounds shuffle index");
14570
14571 if (index >= TotalElementsInInputVector1)
14572 Result = VecVal2.getVectorElt(index - TotalElementsInInputVector1);
14573 else
14574 Result = VecVal1.getVectorElt(index);
14575 return true;
14576 }
14577
14578 bool VectorExprEvaluator::VisitShuffleVectorExpr(const ShuffleVectorExpr *E) {
14579 // FIXME: Unary shuffle with mask not currently supported.
14580 if (E->getNumSubExprs() == 2)
14581 return Error(E);
14582 APValue VecVal1;
14583 const Expr *Vec1 = E->getExpr(0);
14584 if (!EvaluateAsRValue(Info, Vec1, VecVal1))
14585 return false;
14586 APValue VecVal2;
14587 const Expr *Vec2 = E->getExpr(1);
14588 if (!EvaluateAsRValue(Info, Vec2, VecVal2))
14589 return false;
14590
14591 VectorType const *DestVecTy = E->getType()->castAs<VectorType>();
14592 QualType DestElTy = DestVecTy->getElementType();
14593
14594 auto TotalElementsInOutputVector = DestVecTy->getNumElements();
14595
14596 SmallVector<APValue, 4> ResultElements;
14597 ResultElements.reserve(TotalElementsInOutputVector);
14598 for (unsigned EltNum = 0; EltNum < TotalElementsInOutputVector; ++EltNum) {
14599 APValue Elt;
14600 if (!handleVectorShuffle(Info, E, DestElTy, VecVal1, VecVal2, EltNum, Elt))
14601 return false;
14602 ResultElements.push_back(std::move(Elt));
14603 }
14604
14605 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
14606 }
14607
14608 //===----------------------------------------------------------------------===//
14609 // Array Evaluation
14610 //===----------------------------------------------------------------------===//
14611
14612 namespace {
14613 class ArrayExprEvaluator
14614 : public ExprEvaluatorBase<ArrayExprEvaluator> {
14615 const LValue &This;
14616 APValue &Result;
14617 public:
14618
14619 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
14620 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
14621
14622 bool Success(const APValue &V, const Expr *E) {
14623 assert(V.isArray() && "expected array");
14624 Result = V;
14625 return true;
14626 }
14627
14628 bool ZeroInitialization(const Expr *E) {
14629 const ConstantArrayType *CAT =
14630 Info.Ctx.getAsConstantArrayType(E->getType());
14631 if (!CAT) {
14632 if (E->getType()->isIncompleteArrayType()) {
14633 // We can be asked to zero-initialize a flexible array member; this
14634 // is represented as an ImplicitValueInitExpr of incomplete array
14635 // type. In this case, the array has zero elements.
14636 Result = APValue(APValue::UninitArray(), 0, 0);
14637 return true;
14638 }
14639 // FIXME: We could handle VLAs here.
14640 return Error(E);
14641 }
14642
14643 Result = APValue(APValue::UninitArray(), 0, CAT->getZExtSize());
14644 if (!Result.hasArrayFiller())
14645 return true;
14646
14647 // Zero-initialize all elements.
14648 LValue Subobject = This;
14649 Subobject.addArray(Info, E, CAT);
14650 ImplicitValueInitExpr VIE(CAT->getElementType());
14651 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
14652 }
14653
14654 bool VisitCallExpr(const CallExpr *E) {
14655 return handleCallExpr(E, Result, &This);
14656 }
14657 bool VisitCastExpr(const CastExpr *E);
14658 bool VisitInitListExpr(const InitListExpr *E,
14659 QualType AllocType = QualType());
14660 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
14661 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
14662 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
14663 const LValue &Subobject,
14664 APValue *Value, QualType Type);
14665 bool VisitStringLiteral(const StringLiteral *E,
14666 QualType AllocType = QualType()) {
14667 expandStringLiteral(Info, E, Result, AllocType);
14668 return true;
14669 }
14670 bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E);
14671 bool VisitCXXParenListOrInitListExpr(const Expr *ExprToVisit,
14672 ArrayRef<Expr *> Args,
14673 const Expr *ArrayFiller,
14674 QualType AllocType = QualType());
14675 };
14676 } // end anonymous namespace
14677
14678 static bool EvaluateArray(const Expr *E, const LValue &This,
14679 APValue &Result, EvalInfo &Info) {
14680 assert(!E->isValueDependent());
14681 assert(E->isPRValue() && E->getType()->isArrayType() &&
14682 "not an array prvalue");
14683 return ArrayExprEvaluator(Info, This, Result).Visit(E);
14684 }
14685
14686 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
14687 APValue &Result, const InitListExpr *ILE,
14688 QualType AllocType) {
14689 assert(!ILE->isValueDependent());
14690 assert(ILE->isPRValue() && ILE->getType()->isArrayType() &&
14691 "not an array prvalue");
14692 return ArrayExprEvaluator(Info, This, Result)
14693 .VisitInitListExpr(ILE, AllocType);
14694 }
14695
14696 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
14697 APValue &Result,
14698 const CXXConstructExpr *CCE,
14699 QualType AllocType) {
14700 assert(!CCE->isValueDependent());
14701 assert(CCE->isPRValue() && CCE->getType()->isArrayType() &&
14702 "not an array prvalue");
14703 return ArrayExprEvaluator(Info, This, Result)
14704 .VisitCXXConstructExpr(CCE, This, &Result, AllocType);
14705 }
14706
14707 // Return true iff the given array filler may depend on the element index.
14708 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
14709 // For now, just allow non-class value-initialization and initialization
14710 // lists comprised of them.
14711 if (isa<ImplicitValueInitExpr>(FillerExpr))
14712 return false;
14713 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
14714 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
14715 if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
14716 return true;
14717 }
14718
14719 if (ILE->hasArrayFiller() &&
14720 MaybeElementDependentArrayFiller(ILE->getArrayFiller()))
14721 return true;
14722
14723 return false;
14724 }
14725 return true;
14726 }
14727
14728 bool ArrayExprEvaluator::VisitCastExpr(const CastExpr *E) {
14729 const Expr *SE = E->getSubExpr();
14730
14731 switch (E->getCastKind()) {
14732 default:
14733 return ExprEvaluatorBaseTy::VisitCastExpr(E);
14734 case CK_HLSLAggregateSplatCast: {
14735 APValue Val;
14736 QualType ValTy;
14737
14738 if (!hlslAggSplatHelper(Info, SE, Val, ValTy))
14739 return false;
14740
14741 unsigned NEls = elementwiseSize(Info, E->getType());
14742
14743 SmallVector<APValue> SplatEls(NEls, Val);
14744 SmallVector<QualType> SplatType(NEls, ValTy);
14745
14746 // cast the elements
14747 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
14748 if (!constructAggregate(Info, FPO, E, Result, E->getType(), SplatEls,
14749 SplatType))
14750 return false;
14751
14752 return true;
14753 }
14754 case CK_HLSLElementwiseCast: {
14755 SmallVector<APValue> SrcEls;
14756 SmallVector<QualType> SrcTypes;
14757
14758 if (!hlslElementwiseCastHelper(Info, SE, E->getType(), SrcEls, SrcTypes))
14759 return false;
14760
14761 // cast the elements
14762 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
14763 if (!constructAggregate(Info, FPO, E, Result, E->getType(), SrcEls,
14764 SrcTypes))
14765 return false;
14766 return true;
14767 }
14768 }
14769 }
14770
14771 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E,
14772 QualType AllocType) {
14773 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
14774 AllocType.isNull() ? E->getType() : AllocType);
14775 if (!CAT)
14776 return Error(E);
14777
14778 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
14779 // an appropriately-typed string literal enclosed in braces.
14780 if (E->isStringLiteralInit()) {
14781 auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParenImpCasts());
14782 // FIXME: Support ObjCEncodeExpr here once we support it in
14783 // ArrayExprEvaluator generally.
14784 if (!SL)
14785 return Error(E);
14786 return VisitStringLiteral(SL, AllocType);
14787 }
14788 // Any other transparent list init will need proper handling of the
14789 // AllocType; we can't just recurse to the inner initializer.
14790 assert(!E->isTransparent() &&
14791 "transparent array list initialization is not string literal init?");
14792
14793 return VisitCXXParenListOrInitListExpr(E, E->inits(), E->getArrayFiller(),
14794 AllocType);
14795 }
14796
14797 bool ArrayExprEvaluator::VisitCXXParenListOrInitListExpr(
14798 const Expr *ExprToVisit, ArrayRef<Expr *> Args, const Expr *ArrayFiller,
14799 QualType AllocType) {
14800 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
14801 AllocType.isNull() ? ExprToVisit->getType() : AllocType);
14802
14803 bool Success = true;
14804
14805 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
14806 "zero-initialized array shouldn't have any initialized elts");
14807 APValue Filler;
14808 if (Result.isArray() && Result.hasArrayFiller())
14809 Filler = Result.getArrayFiller();
14810
14811 unsigned NumEltsToInit = Args.size();
14812 unsigned NumElts = CAT->getZExtSize();
14813
14814 // If the initializer might depend on the array index, run it for each
14815 // array element.
14816 if (NumEltsToInit != NumElts &&
14817 MaybeElementDependentArrayFiller(ArrayFiller)) {
14818 NumEltsToInit = NumElts;
14819 } else {
14820 for (auto *Init : Args) {
14821 if (auto *EmbedS = dyn_cast<EmbedExpr>(Init->IgnoreParenImpCasts()))
14822 NumEltsToInit += EmbedS->getDataElementCount() - 1;
14823 }
14824 if (NumEltsToInit > NumElts)
14825 NumEltsToInit = NumElts;
14826 }
14827
14828 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
14829 << NumEltsToInit << ".\n");
14830
14831 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
14832
14833 // If the array was previously zero-initialized, preserve the
14834 // zero-initialized values.
14835 if (Filler.hasValue()) {
14836 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
14837 Result.getArrayInitializedElt(I) = Filler;
14838 if (Result.hasArrayFiller())
14839 Result.getArrayFiller() = Filler;
14840 }
14841
14842 LValue Subobject = This;
14843 Subobject.addArray(Info, ExprToVisit, CAT);
14844 auto Eval = [&](const Expr *Init, unsigned ArrayIndex) {
14845 if (Init->isValueDependent())
14846 return EvaluateDependentExpr(Init, Info);
14847
14848 if (!EvaluateInPlace(Result.getArrayInitializedElt(ArrayIndex), Info,
14849 Subobject, Init) ||
14850 !HandleLValueArrayAdjustment(Info, Init, Subobject,
14851 CAT->getElementType(), 1)) {
14852 if (!Info.noteFailure())
14853 return false;
14854 Success = false;
14855 }
14856 return true;
14857 };
14858 unsigned ArrayIndex = 0;
14859 QualType DestTy = CAT->getElementType();
14860 APSInt Value(Info.Ctx.getTypeSize(DestTy), DestTy->isUnsignedIntegerType());
14861 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
14862 const Expr *Init = Index < Args.size() ? Args[Index] : ArrayFiller;
14863 if (ArrayIndex >= NumEltsToInit)
14864 break;
14865 if (auto *EmbedS = dyn_cast<EmbedExpr>(Init->IgnoreParenImpCasts())) {
14866 StringLiteral *SL = EmbedS->getDataStringLiteral();
14867 for (unsigned I = EmbedS->getStartingElementPos(),
14868 N = EmbedS->getDataElementCount();
14869 I != EmbedS->getStartingElementPos() + N; ++I) {
14870 Value = SL->getCodeUnit(I);
14871 if (DestTy->isIntegerType()) {
14872 Result.getArrayInitializedElt(ArrayIndex) = APValue(Value);
14873 } else {
14874 assert(DestTy->isFloatingType() && "unexpected type");
14875 const FPOptions FPO =
14876 Init->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
14877 APFloat FValue(0.0);
14878 if (!HandleIntToFloatCast(Info, Init, FPO, EmbedS->getType(), Value,
14879 DestTy, FValue))
14880 return false;
14881 Result.getArrayInitializedElt(ArrayIndex) = APValue(FValue);
14882 }
14883 ArrayIndex++;
14884 }
14885 } else {
14886 if (!Eval(Init, ArrayIndex))
14887 return false;
14888 ++ArrayIndex;
14889 }
14890 }
14891
14892 if (!Result.hasArrayFiller())
14893 return Success;
14894
14895 // If we get here, we have a trivial filler, which we can just evaluate
14896 // once and splat over the rest of the array elements.
14897 assert(ArrayFiller && "no array filler for incomplete init list");
14898 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
14899 ArrayFiller) &&
14900 Success;
14901 }
14902
14903 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
14904 LValue CommonLV;
14905 if (E->getCommonExpr() &&
14906 !Evaluate(Info.CurrentCall->createTemporary(
14907 E->getCommonExpr(),
14908 getStorageType(Info.Ctx, E->getCommonExpr()),
14909 ScopeKind::FullExpression, CommonLV),
14910 Info, E->getCommonExpr()->getSourceExpr()))
14911 return false;
14912
14913 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
14914
14915 uint64_t Elements = CAT->getZExtSize();
14916 Result = APValue(APValue::UninitArray(), Elements, Elements);
14917
14918 LValue Subobject = This;
14919 Subobject.addArray(Info, E, CAT);
14920
14921 bool Success = true;
14922 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
14923 // C++ [class.temporary]/5
14924 // There are four contexts in which temporaries are destroyed at a different
14925 // point than the end of the full-expression. [...] The second context is
14926 // when a copy constructor is called to copy an element of an array while
14927 // the entire array is copied [...]. In either case, if the constructor has
14928 // one or more default arguments, the destruction of every temporary created
14929 // in a default argument is sequenced before the construction of the next
14930 // array element, if any.
14931 FullExpressionRAII Scope(Info);
14932
14933 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
14934 Info, Subobject, E->getSubExpr()) ||
14935 !HandleLValueArrayAdjustment(Info, E, Subobject,
14936 CAT->getElementType(), 1)) {
14937 if (!Info.noteFailure())
14938 return false;
14939 Success = false;
14940 }
14941
14942 // Make sure we run the destructors too.
14943 Scope.destroy();
14944 }
14945
14946 return Success;
14947 }
14948
14949 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
14950 return VisitCXXConstructExpr(E, This, &Result, E->getType());
14951 }
14952
14953 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
14954 const LValue &Subobject,
14955 APValue *Value,
14956 QualType Type) {
14957 bool HadZeroInit = Value->hasValue();
14958
14959 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
14960 unsigned FinalSize = CAT->getZExtSize();
14961
14962 // Preserve the array filler if we had prior zero-initialization.
14963 APValue Filler =
14964 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
14965 : APValue();
14966
14967 *Value = APValue(APValue::UninitArray(), 0, FinalSize);
14968 if (FinalSize == 0)
14969 return true;
14970
14971 bool HasTrivialConstructor = CheckTrivialDefaultConstructor(
14972 Info, E->getExprLoc(), E->getConstructor(),
14973 E->requiresZeroInitialization());
14974 LValue ArrayElt = Subobject;
14975 ArrayElt.addArray(Info, E, CAT);
14976 // We do the whole initialization in two passes, first for just one element,
14977 // then for the whole array. It's possible we may find out we can't do const
14978 // init in the first pass, in which case we avoid allocating a potentially
14979 // large array. We don't do more passes because expanding array requires
14980 // copying the data, which is wasteful.
14981 for (const unsigned N : {1u, FinalSize}) {
14982 unsigned OldElts = Value->getArrayInitializedElts();
14983 if (OldElts == N)
14984 break;
14985
14986 // Expand the array to appropriate size.
14987 APValue NewValue(APValue::UninitArray(), N, FinalSize);
14988 for (unsigned I = 0; I < OldElts; ++I)
14989 NewValue.getArrayInitializedElt(I).swap(
14990 Value->getArrayInitializedElt(I));
14991 Value->swap(NewValue);
14992
14993 if (HadZeroInit)
14994 for (unsigned I = OldElts; I < N; ++I)
14995 Value->getArrayInitializedElt(I) = Filler;
14996
14997 if (HasTrivialConstructor && N == FinalSize && FinalSize != 1) {
14998 // If we have a trivial constructor, only evaluate it once and copy
14999 // the result into all the array elements.
15000 APValue &FirstResult = Value->getArrayInitializedElt(0);
15001 for (unsigned I = OldElts; I < FinalSize; ++I)
15002 Value->getArrayInitializedElt(I) = FirstResult;
15003 } else {
15004 for (unsigned I = OldElts; I < N; ++I) {
15005 if (!VisitCXXConstructExpr(E, ArrayElt,
15006 &Value->getArrayInitializedElt(I),
15007 CAT->getElementType()) ||
15008 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
15009 CAT->getElementType(), 1))
15010 return false;
15011 // When checking for const initilization any diagnostic is considered
15012 // an error.
15013 if (Info.EvalStatus.Diag && !Info.EvalStatus.Diag->empty() &&
15014 !Info.keepEvaluatingAfterFailure())
15015 return false;
15016 }
15017 }
15018 }
15019
15020 return true;
15021 }
15022
15023 if (!Type->isRecordType())
15024 return Error(E);
15025
15026 return RecordExprEvaluator(Info, Subobject, *Value)
15027 .VisitCXXConstructExpr(E, Type);
15028 }
15029
15030 bool ArrayExprEvaluator::VisitCXXParenListInitExpr(
15031 const CXXParenListInitExpr *E) {
15032 assert(E->getType()->isConstantArrayType() &&
15033 "Expression result is not a constant array type");
15034
15035 return VisitCXXParenListOrInitListExpr(E, E->getInitExprs(),
15036 E->getArrayFiller());
15037 }
15038
15039 //===----------------------------------------------------------------------===//
15040 // Integer Evaluation
15041 //
15042 // As a GNU extension, we support casting pointers to sufficiently-wide integer
15043 // types and back in constant folding. Integer values are thus represented
15044 // either as an integer-valued APValue, or as an lvalue-valued APValue.
15045 //===----------------------------------------------------------------------===//
15046
15047 namespace {
15048 class IntExprEvaluator
15049 : public ExprEvaluatorBase<IntExprEvaluator> {
15050 APValue &Result;
15051 public:
15052 IntExprEvaluator(EvalInfo &info, APValue &result)
15053 : ExprEvaluatorBaseTy(info), Result(result) {}
15054
15055 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
15056 assert(E->getType()->isIntegralOrEnumerationType() &&
15057 "Invalid evaluation result.");
15058 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
15059 "Invalid evaluation result.");
15060 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
15061 "Invalid evaluation result.");
15062 Result = APValue(SI);
15063 return true;
15064 }
15065 bool Success(const llvm::APSInt &SI, const Expr *E) {
15066 return Success(SI, E, Result);
15067 }
15068
15069 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
15070 assert(E->getType()->isIntegralOrEnumerationType() &&
15071 "Invalid evaluation result.");
15072 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
15073 "Invalid evaluation result.");
15074 Result = APValue(APSInt(I));
15075 Result.getInt().setIsUnsigned(
15076 E->getType()->isUnsignedIntegerOrEnumerationType());
15077 return true;
15078 }
15079 bool Success(const llvm::APInt &I, const Expr *E) {
15080 return Success(I, E, Result);
15081 }
15082
15083 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
15084 assert(E->getType()->isIntegralOrEnumerationType() &&
15085 "Invalid evaluation result.");
15086 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
15087 return true;
15088 }
15089 bool Success(uint64_t Value, const Expr *E) {
15090 return Success(Value, E, Result);
15091 }
15092
15093 bool Success(CharUnits Size, const Expr *E) {
15094 return Success(Size.getQuantity(), E);
15095 }
15096
15097 bool Success(const APValue &V, const Expr *E) {
15098 // C++23 [expr.const]p8 If we have a variable that is unknown reference or
15099 // pointer allow further evaluation of the value.
15100 if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate() ||
15101 V.allowConstexprUnknown()) {
15102 Result = V;
15103 return true;
15104 }
15105 return Success(V.getInt(), E);
15106 }
15107
15108 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
15109
15110 friend std::optional<bool> EvaluateBuiltinIsWithinLifetime(IntExprEvaluator &,
15111 const CallExpr *);
15112
15113 //===--------------------------------------------------------------------===//
15114 // Visitor Methods
15115 //===--------------------------------------------------------------------===//
15116
15117 bool VisitIntegerLiteral(const IntegerLiteral *E) {
15118 return Success(E->getValue(), E);
15119 }
15120 bool VisitCharacterLiteral(const CharacterLiteral *E) {
15121 return Success(E->getValue(), E);
15122 }
15123
15124 bool CheckReferencedDecl(const Expr *E, const Decl *D);
15125 bool VisitDeclRefExpr(const DeclRefExpr *E) {
15126 if (CheckReferencedDecl(E, E->getDecl()))
15127 return true;
15128
15129 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
15130 }
15131 bool VisitMemberExpr(const MemberExpr *E) {
15132 if (CheckReferencedDecl(E, E->getMemberDecl())) {
15133 VisitIgnoredBaseExpression(E->getBase());
15134 return true;
15135 }
15136
15137 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
15138 }
15139
15140 bool VisitCallExpr(const CallExpr *E);
15141 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
15142 bool VisitBinaryOperator(const BinaryOperator *E);
15143 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
15144 bool VisitUnaryOperator(const UnaryOperator *E);
15145
15146 bool VisitCastExpr(const CastExpr* E);
15147 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
15148
15149 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
15150 return Success(E->getValue(), E);
15151 }
15152
15153 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
15154 return Success(E->getValue(), E);
15155 }
15156
15157 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
15158 if (Info.ArrayInitIndex == uint64_t(-1)) {
15159 // We were asked to evaluate this subexpression independent of the
15160 // enclosing ArrayInitLoopExpr. We can't do that.
15161 Info.FFDiag(E);
15162 return false;
15163 }
15164 return Success(Info.ArrayInitIndex, E);
15165 }
15166
15167 // Note, GNU defines __null as an integer, not a pointer.
15168 bool VisitGNUNullExpr(const GNUNullExpr *E) {
15169 return ZeroInitialization(E);
15170 }
15171
15172 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
15173 if (E->isStoredAsBoolean())
15174 return Success(E->getBoolValue(), E);
15175 if (E->getAPValue().isAbsent())
15176 return false;
15177 assert(E->getAPValue().isInt() && "APValue type not supported");
15178 return Success(E->getAPValue().getInt(), E);
15179 }
15180
15181 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
15182 return Success(E->getValue(), E);
15183 }
15184
15185 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
15186 return Success(E->getValue(), E);
15187 }
15188
15189 bool VisitOpenACCAsteriskSizeExpr(const OpenACCAsteriskSizeExpr *E) {
15190 // This should not be evaluated during constant expr evaluation, as it
15191 // should always be in an unevaluated context (the args list of a 'gang' or
15192 // 'tile' clause).
15193 return Error(E);
15194 }
15195
15196 bool VisitUnaryReal(const UnaryOperator *E);
15197 bool VisitUnaryImag(const UnaryOperator *E);
15198
15199 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
15200 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
15201 bool VisitSourceLocExpr(const SourceLocExpr *E);
15202 bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E);
15203 bool VisitRequiresExpr(const RequiresExpr *E);
15204 // FIXME: Missing: array subscript of vector, member of vector
15205 };
15206
15207 class FixedPointExprEvaluator
15208 : public ExprEvaluatorBase<FixedPointExprEvaluator> {
15209 APValue &Result;
15210
15211 public:
15212 FixedPointExprEvaluator(EvalInfo &info, APValue &result)
15213 : ExprEvaluatorBaseTy(info), Result(result) {}
15214
15215 bool Success(const llvm::APInt &I, const Expr *E) {
15216 return Success(
15217 APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
15218 }
15219
15220 bool Success(uint64_t Value, const Expr *E) {
15221 return Success(
15222 APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
15223 }
15224
15225 bool Success(const APValue &V, const Expr *E) {
15226 return Success(V.getFixedPoint(), E);
15227 }
15228
15229 bool Success(const APFixedPoint &V, const Expr *E) {
15230 assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
15231 assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
15232 "Invalid evaluation result.");
15233 Result = APValue(V);
15234 return true;
15235 }
15236
15237 bool ZeroInitialization(const Expr *E) {
15238 return Success(0, E);
15239 }
15240
15241 //===--------------------------------------------------------------------===//
15242 // Visitor Methods
15243 //===--------------------------------------------------------------------===//
15244
15245 bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
15246 return Success(E->getValue(), E);
15247 }
15248
15249 bool VisitCastExpr(const CastExpr *E);
15250 bool VisitUnaryOperator(const UnaryOperator *E);
15251 bool VisitBinaryOperator(const BinaryOperator *E);
15252 };
15253 } // end anonymous namespace
15254
15255 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
15256 /// produce either the integer value or a pointer.
15257 ///
15258 /// GCC has a heinous extension which folds casts between pointer types and
15259 /// pointer-sized integral types. We support this by allowing the evaluation of
15260 /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
15261 /// Some simple arithmetic on such values is supported (they are treated much
15262 /// like char*).
15263 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
15264 EvalInfo &Info) {
15265 assert(!E->isValueDependent());
15266 assert(E->isPRValue() && E->getType()->isIntegralOrEnumerationType());
15267 return IntExprEvaluator(Info, Result).Visit(E);
15268 }
15269
15270 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
15271 assert(!E->isValueDependent());
15272 APValue Val;
15273 if (!EvaluateIntegerOrLValue(E, Val, Info))
15274 return false;
15275 if (!Val.isInt()) {
15276 // FIXME: It would be better to produce the diagnostic for casting
15277 // a pointer to an integer.
15278 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
15279 return false;
15280 }
15281 Result = Val.getInt();
15282 return true;
15283 }
15284
15285 bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
15286 APValue Evaluated = E->EvaluateInContext(
15287 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
15288 return Success(Evaluated, E);
15289 }
15290
15291 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
15292 EvalInfo &Info) {
15293 assert(!E->isValueDependent());
15294 if (E->getType()->isFixedPointType()) {
15295 APValue Val;
15296 if (!FixedPointExprEvaluator(Info, Val).Visit(E))
15297 return false;
15298 if (!Val.isFixedPoint())
15299 return false;
15300
15301 Result = Val.getFixedPoint();
15302 return true;
15303 }
15304 return false;
15305 }
15306
15307 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
15308 EvalInfo &Info) {
15309 assert(!E->isValueDependent());
15310 if (E->getType()->isIntegerType()) {
15311 auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
15312 APSInt Val;
15313 if (!EvaluateInteger(E, Val, Info))
15314 return false;
15315 Result = APFixedPoint(Val, FXSema);
15316 return true;
15317 } else if (E->getType()->isFixedPointType()) {
15318 return EvaluateFixedPoint(E, Result, Info);
15319 }
15320 return false;
15321 }
15322
15323 /// Check whether the given declaration can be directly converted to an integral
15324 /// rvalue. If not, no diagnostic is produced; there are other things we can
15325 /// try.
15326 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
15327 // Enums are integer constant exprs.
15328 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
15329 // Check for signedness/width mismatches between E type and ECD value.
15330 bool SameSign = (ECD->getInitVal().isSigned()
15331 == E->getType()->isSignedIntegerOrEnumerationType());
15332 bool SameWidth = (ECD->getInitVal().getBitWidth()
15333 == Info.Ctx.getIntWidth(E->getType()));
15334 if (SameSign && SameWidth)
15335 return Success(ECD->getInitVal(), E);
15336 else {
15337 // Get rid of mismatch (otherwise Success assertions will fail)
15338 // by computing a new value matching the type of E.
15339 llvm::APSInt Val = ECD->getInitVal();
15340 if (!SameSign)
15341 Val.setIsSigned(!ECD->getInitVal().isSigned());
15342 if (!SameWidth)
15343 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
15344 return Success(Val, E);
15345 }
15346 }
15347 return false;
15348 }
15349
15350 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
15351 /// as GCC.
15352 GCCTypeClass EvaluateBuiltinClassifyType(QualType T,
15353 const LangOptions &LangOpts) {
15354 assert(!T->isDependentType() && "unexpected dependent type");
15355
15356 QualType CanTy = T.getCanonicalType();
15357
15358 switch (CanTy->getTypeClass()) {
15359 #define TYPE(ID, BASE)
15360 #define DEPENDENT_TYPE(ID, BASE) case Type::ID:
15361 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
15362 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
15363 #include "clang/AST/TypeNodes.inc"
15364 case Type::Auto:
15365 case Type::DeducedTemplateSpecialization:
15366 llvm_unreachable("unexpected non-canonical or dependent type");
15367
15368 case Type::Builtin:
15369 switch (cast<BuiltinType>(CanTy)->getKind()) {
15370 #define BUILTIN_TYPE(ID, SINGLETON_ID)
15371 #define SIGNED_TYPE(ID, SINGLETON_ID) \
15372 case BuiltinType::ID: return GCCTypeClass::Integer;
15373 #define FLOATING_TYPE(ID, SINGLETON_ID) \
15374 case BuiltinType::ID: return GCCTypeClass::RealFloat;
15375 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
15376 case BuiltinType::ID: break;
15377 #include "clang/AST/BuiltinTypes.def"
15378 case BuiltinType::Void:
15379 return GCCTypeClass::Void;
15380
15381 case BuiltinType::Bool:
15382 return GCCTypeClass::Bool;
15383
15384 case BuiltinType::Char_U:
15385 case BuiltinType::UChar:
15386 case BuiltinType::WChar_U:
15387 case BuiltinType::Char8:
15388 case BuiltinType::Char16:
15389 case BuiltinType::Char32:
15390 case BuiltinType::UShort:
15391 case BuiltinType::UInt:
15392 case BuiltinType::ULong:
15393 case BuiltinType::ULongLong:
15394 case BuiltinType::UInt128:
15395 return GCCTypeClass::Integer;
15396
15397 case BuiltinType::UShortAccum:
15398 case BuiltinType::UAccum:
15399 case BuiltinType::ULongAccum:
15400 case BuiltinType::UShortFract:
15401 case BuiltinType::UFract:
15402 case BuiltinType::ULongFract:
15403 case BuiltinType::SatUShortAccum:
15404 case BuiltinType::SatUAccum:
15405 case BuiltinType::SatULongAccum:
15406 case BuiltinType::SatUShortFract:
15407 case BuiltinType::SatUFract:
15408 case BuiltinType::SatULongFract:
15409 return GCCTypeClass::None;
15410
15411 case BuiltinType::NullPtr:
15412
15413 case BuiltinType::ObjCId:
15414 case BuiltinType::ObjCClass:
15415 case BuiltinType::ObjCSel:
15416 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
15417 case BuiltinType::Id:
15418 #include "clang/Basic/OpenCLImageTypes.def"
15419 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
15420 case BuiltinType::Id:
15421 #include "clang/Basic/OpenCLExtensionTypes.def"
15422 case BuiltinType::OCLSampler:
15423 case BuiltinType::OCLEvent:
15424 case BuiltinType::OCLClkEvent:
15425 case BuiltinType::OCLQueue:
15426 case BuiltinType::OCLReserveID:
15427 #define SVE_TYPE(Name, Id, SingletonId) \
15428 case BuiltinType::Id:
15429 #include "clang/Basic/AArch64ACLETypes.def"
15430 #define PPC_VECTOR_TYPE(Name, Id, Size) \
15431 case BuiltinType::Id:
15432 #include "clang/Basic/PPCTypes.def"
15433 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
15434 #include "clang/Basic/RISCVVTypes.def"
15435 #define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
15436 #include "clang/Basic/WebAssemblyReferenceTypes.def"
15437 #define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
15438 #include "clang/Basic/AMDGPUTypes.def"
15439 #define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
15440 #include "clang/Basic/HLSLIntangibleTypes.def"
15441 return GCCTypeClass::None;
15442
15443 case BuiltinType::Dependent:
15444 llvm_unreachable("unexpected dependent type");
15445 };
15446 llvm_unreachable("unexpected placeholder type");
15447
15448 case Type::Enum:
15449 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
15450
15451 case Type::Pointer:
15452 case Type::ConstantArray:
15453 case Type::VariableArray:
15454 case Type::IncompleteArray:
15455 case Type::FunctionNoProto:
15456 case Type::FunctionProto:
15457 case Type::ArrayParameter:
15458 return GCCTypeClass::Pointer;
15459
15460 case Type::MemberPointer:
15461 return CanTy->isMemberDataPointerType()
15462 ? GCCTypeClass::PointerToDataMember
15463 : GCCTypeClass::PointerToMemberFunction;
15464
15465 case Type::Complex:
15466 return GCCTypeClass::Complex;
15467
15468 case Type::Record:
15469 return CanTy->isUnionType() ? GCCTypeClass::Union
15470 : GCCTypeClass::ClassOrStruct;
15471
15472 case Type::Atomic:
15473 // GCC classifies _Atomic T the same as T.
15474 return EvaluateBuiltinClassifyType(
15475 CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
15476
15477 case Type::Vector:
15478 case Type::ExtVector:
15479 return GCCTypeClass::Vector;
15480
15481 case Type::BlockPointer:
15482 case Type::ConstantMatrix:
15483 case Type::ObjCObject:
15484 case Type::ObjCInterface:
15485 case Type::ObjCObjectPointer:
15486 case Type::Pipe:
15487 case Type::HLSLAttributedResource:
15488 case Type::HLSLInlineSpirv:
15489 // Classify all other types that don't fit into the regular
15490 // classification the same way.
15491 return GCCTypeClass::None;
15492
15493 case Type::BitInt:
15494 return GCCTypeClass::BitInt;
15495
15496 case Type::LValueReference:
15497 case Type::RValueReference:
15498 llvm_unreachable("invalid type for expression");
15499 }
15500
15501 llvm_unreachable("unexpected type class");
15502 }
15503
15504 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
15505 /// as GCC.
15506 static GCCTypeClass
15507 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
15508 // If no argument was supplied, default to None. This isn't
15509 // ideal, however it is what gcc does.
15510 if (E->getNumArgs() == 0)
15511 return GCCTypeClass::None;
15512
15513 // FIXME: Bizarrely, GCC treats a call with more than one argument as not
15514 // being an ICE, but still folds it to a constant using the type of the first
15515 // argument.
15516 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
15517 }
15518
15519 /// EvaluateBuiltinConstantPForLValue - Determine the result of
15520 /// __builtin_constant_p when applied to the given pointer.
15521 ///
15522 /// A pointer is only "constant" if it is null (or a pointer cast to integer)
15523 /// or it points to the first character of a string literal.
15524 static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) {
15525 APValue::LValueBase Base = LV.getLValueBase();
15526 if (Base.isNull()) {
15527 // A null base is acceptable.
15528 return true;
15529 } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
15530 if (!isa<StringLiteral>(E))
15531 return false;
15532 return LV.getLValueOffset().isZero();
15533 } else if (Base.is<TypeInfoLValue>()) {
15534 // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
15535 // evaluate to true.
15536 return true;
15537 } else {
15538 // Any other base is not constant enough for GCC.
15539 return false;
15540 }
15541 }
15542
15543 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
15544 /// GCC as we can manage.
15545 static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
15546 // This evaluation is not permitted to have side-effects, so evaluate it in
15547 // a speculative evaluation context.
15548 SpeculativeEvaluationRAII SpeculativeEval(Info);
15549
15550 // Constant-folding is always enabled for the operand of __builtin_constant_p
15551 // (even when the enclosing evaluation context otherwise requires a strict
15552 // language-specific constant expression).
15553 FoldConstant Fold(Info, true);
15554
15555 QualType ArgType = Arg->getType();
15556
15557 // __builtin_constant_p always has one operand. The rules which gcc follows
15558 // are not precisely documented, but are as follows:
15559 //
15560 // - If the operand is of integral, floating, complex or enumeration type,
15561 // and can be folded to a known value of that type, it returns 1.
15562 // - If the operand can be folded to a pointer to the first character
15563 // of a string literal (or such a pointer cast to an integral type)
15564 // or to a null pointer or an integer cast to a pointer, it returns 1.
15565 //
15566 // Otherwise, it returns 0.
15567 //
15568 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
15569 // its support for this did not work prior to GCC 9 and is not yet well
15570 // understood.
15571 if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
15572 ArgType->isAnyComplexType() || ArgType->isPointerType() ||
15573 ArgType->isNullPtrType()) {
15574 APValue V;
15575 if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) {
15576 Fold.keepDiagnostics();
15577 return false;
15578 }
15579
15580 // For a pointer (possibly cast to integer), there are special rules.
15581 if (V.getKind() == APValue::LValue)
15582 return EvaluateBuiltinConstantPForLValue(V);
15583
15584 // Otherwise, any constant value is good enough.
15585 return V.hasValue();
15586 }
15587
15588 // Anything else isn't considered to be sufficiently constant.
15589 return false;
15590 }
15591
15592 /// Retrieves the "underlying object type" of the given expression,
15593 /// as used by __builtin_object_size.
15594 static QualType getObjectType(APValue::LValueBase B) {
15595 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
15596 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
15597 return VD->getType();
15598 } else if (const Expr *E = B.dyn_cast<const Expr*>()) {
15599 if (isa<CompoundLiteralExpr>(E))
15600 return E->getType();
15601 } else if (B.is<TypeInfoLValue>()) {
15602 return B.getTypeInfoType();
15603 } else if (B.is<DynamicAllocLValue>()) {
15604 return B.getDynamicAllocType();
15605 }
15606
15607 return QualType();
15608 }
15609
15610 /// A more selective version of E->IgnoreParenCasts for
15611 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
15612 /// to change the type of E.
15613 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
15614 ///
15615 /// Always returns an RValue with a pointer representation.
15616 static const Expr *ignorePointerCastsAndParens(const Expr *E) {
15617 assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
15618
15619 const Expr *NoParens = E->IgnoreParens();
15620 const auto *Cast = dyn_cast<CastExpr>(NoParens);
15621 if (Cast == nullptr)
15622 return NoParens;
15623
15624 // We only conservatively allow a few kinds of casts, because this code is
15625 // inherently a simple solution that seeks to support the common case.
15626 auto CastKind = Cast->getCastKind();
15627 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
15628 CastKind != CK_AddressSpaceConversion)
15629 return NoParens;
15630
15631 const auto *SubExpr = Cast->getSubExpr();
15632 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isPRValue())
15633 return NoParens;
15634 return ignorePointerCastsAndParens(SubExpr);
15635 }
15636
15637 /// Checks to see if the given LValue's Designator is at the end of the LValue's
15638 /// record layout. e.g.
15639 /// struct { struct { int a, b; } fst, snd; } obj;
15640 /// obj.fst // no
15641 /// obj.snd // yes
15642 /// obj.fst.a // no
15643 /// obj.fst.b // no
15644 /// obj.snd.a // no
15645 /// obj.snd.b // yes
15646 ///
15647 /// Please note: this function is specialized for how __builtin_object_size
15648 /// views "objects".
15649 ///
15650 /// If this encounters an invalid RecordDecl or otherwise cannot determine the
15651 /// correct result, it will always return true.
15652 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
15653 assert(!LVal.Designator.Invalid);
15654
15655 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD) {
15656 const RecordDecl *Parent = FD->getParent();
15657 if (Parent->isInvalidDecl() || Parent->isUnion())
15658 return true;
15659 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
15660 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
15661 };
15662
15663 auto &Base = LVal.getLValueBase();
15664 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
15665 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
15666 if (!IsLastOrInvalidFieldDecl(FD))
15667 return false;
15668 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
15669 for (auto *FD : IFD->chain()) {
15670 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD)))
15671 return false;
15672 }
15673 }
15674 }
15675
15676 unsigned I = 0;
15677 QualType BaseType = getType(Base);
15678 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
15679 // If we don't know the array bound, conservatively assume we're looking at
15680 // the final array element.
15681 ++I;
15682 if (BaseType->isIncompleteArrayType())
15683 BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
15684 else
15685 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
15686 }
15687
15688 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
15689 const auto &Entry = LVal.Designator.Entries[I];
15690 if (BaseType->isArrayType()) {
15691 // Because __builtin_object_size treats arrays as objects, we can ignore
15692 // the index iff this is the last array in the Designator.
15693 if (I + 1 == E)
15694 return true;
15695 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
15696 uint64_t Index = Entry.getAsArrayIndex();
15697 if (Index + 1 != CAT->getZExtSize())
15698 return false;
15699 BaseType = CAT->getElementType();
15700 } else if (BaseType->isAnyComplexType()) {
15701 const auto *CT = BaseType->castAs<ComplexType>();
15702 uint64_t Index = Entry.getAsArrayIndex();
15703 if (Index != 1)
15704 return false;
15705 BaseType = CT->getElementType();
15706 } else if (auto *FD = getAsField(Entry)) {
15707 if (!IsLastOrInvalidFieldDecl(FD))
15708 return false;
15709 BaseType = FD->getType();
15710 } else {
15711 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
15712 return false;
15713 }
15714 }
15715 return true;
15716 }
15717
15718 /// Tests to see if the LValue has a user-specified designator (that isn't
15719 /// necessarily valid). Note that this always returns 'true' if the LValue has
15720 /// an unsized array as its first designator entry, because there's currently no
15721 /// way to tell if the user typed *foo or foo[0].
15722 static bool refersToCompleteObject(const LValue &LVal) {
15723 if (LVal.Designator.Invalid)
15724 return false;
15725
15726 if (!LVal.Designator.Entries.empty())
15727 return LVal.Designator.isMostDerivedAnUnsizedArray();
15728
15729 if (!LVal.InvalidBase)
15730 return true;
15731
15732 // If `E` is a MemberExpr, then the first part of the designator is hiding in
15733 // the LValueBase.
15734 const auto *E = LVal.Base.dyn_cast<const Expr *>();
15735 return !E || !isa<MemberExpr>(E);
15736 }
15737
15738 /// Attempts to detect a user writing into a piece of memory that's impossible
15739 /// to figure out the size of by just using types.
15740 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
15741 const SubobjectDesignator &Designator = LVal.Designator;
15742 // Notes:
15743 // - Users can only write off of the end when we have an invalid base. Invalid
15744 // bases imply we don't know where the memory came from.
15745 // - We used to be a bit more aggressive here; we'd only be conservative if
15746 // the array at the end was flexible, or if it had 0 or 1 elements. This
15747 // broke some common standard library extensions (PR30346), but was
15748 // otherwise seemingly fine. It may be useful to reintroduce this behavior
15749 // with some sort of list. OTOH, it seems that GCC is always
15750 // conservative with the last element in structs (if it's an array), so our
15751 // current behavior is more compatible than an explicit list approach would
15752 // be.
15753 auto isFlexibleArrayMember = [&] {
15754 using FAMKind = LangOptions::StrictFlexArraysLevelKind;
15755 FAMKind StrictFlexArraysLevel =
15756 Ctx.getLangOpts().getStrictFlexArraysLevel();
15757
15758 if (Designator.isMostDerivedAnUnsizedArray())
15759 return true;
15760
15761 if (StrictFlexArraysLevel == FAMKind::Default)
15762 return true;
15763
15764 if (Designator.getMostDerivedArraySize() == 0 &&
15765 StrictFlexArraysLevel != FAMKind::IncompleteOnly)
15766 return true;
15767
15768 if (Designator.getMostDerivedArraySize() == 1 &&
15769 StrictFlexArraysLevel == FAMKind::OneZeroOrIncomplete)
15770 return true;
15771
15772 return false;
15773 };
15774
15775 return LVal.InvalidBase &&
15776 Designator.Entries.size() == Designator.MostDerivedPathLength &&
15777 Designator.MostDerivedIsArrayElement && isFlexibleArrayMember() &&
15778 isDesignatorAtObjectEnd(Ctx, LVal);
15779 }
15780
15781 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
15782 /// Fails if the conversion would cause loss of precision.
15783 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
15784 CharUnits &Result) {
15785 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
15786 if (Int.ugt(CharUnitsMax))
15787 return false;
15788 Result = CharUnits::fromQuantity(Int.getZExtValue());
15789 return true;
15790 }
15791
15792 /// If we're evaluating the object size of an instance of a struct that
15793 /// contains a flexible array member, add the size of the initializer.
15794 static void addFlexibleArrayMemberInitSize(EvalInfo &Info, const QualType &T,
15795 const LValue &LV, CharUnits &Size) {
15796 if (!T.isNull() && T->isStructureType() &&
15797 T->castAsRecordDecl()->hasFlexibleArrayMember())
15798 if (const auto *V = LV.getLValueBase().dyn_cast<const ValueDecl *>())
15799 if (const auto *VD = dyn_cast<VarDecl>(V))
15800 if (VD->hasInit())
15801 Size += VD->getFlexibleArrayInitChars(Info.Ctx);
15802 }
15803
15804 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
15805 /// determine how many bytes exist from the beginning of the object to either
15806 /// the end of the current subobject, or the end of the object itself, depending
15807 /// on what the LValue looks like + the value of Type.
15808 ///
15809 /// If this returns false, the value of Result is undefined.
15810 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
15811 unsigned Type, const LValue &LVal,
15812 CharUnits &EndOffset) {
15813 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
15814
15815 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
15816 if (Ty.isNull())
15817 return false;
15818
15819 Ty = Ty.getNonReferenceType();
15820
15821 if (Ty->isIncompleteType() || Ty->isFunctionType())
15822 return false;
15823
15824 return HandleSizeof(Info, ExprLoc, Ty, Result);
15825 };
15826
15827 // We want to evaluate the size of the entire object. This is a valid fallback
15828 // for when Type=1 and the designator is invalid, because we're asked for an
15829 // upper-bound.
15830 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
15831 // Type=3 wants a lower bound, so we can't fall back to this.
15832 if (Type == 3 && !DetermineForCompleteObject)
15833 return false;
15834
15835 llvm::APInt APEndOffset;
15836 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
15837 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
15838 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
15839
15840 if (LVal.InvalidBase)
15841 return false;
15842
15843 QualType BaseTy = getObjectType(LVal.getLValueBase());
15844 const bool Ret = CheckedHandleSizeof(BaseTy, EndOffset);
15845 addFlexibleArrayMemberInitSize(Info, BaseTy, LVal, EndOffset);
15846 return Ret;
15847 }
15848
15849 // We want to evaluate the size of a subobject.
15850 const SubobjectDesignator &Designator = LVal.Designator;
15851
15852 // The following is a moderately common idiom in C:
15853 //
15854 // struct Foo { int a; char c[1]; };
15855 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
15856 // strcpy(&F->c[0], Bar);
15857 //
15858 // In order to not break too much legacy code, we need to support it.
15859 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
15860 // If we can resolve this to an alloc_size call, we can hand that back,
15861 // because we know for certain how many bytes there are to write to.
15862 llvm::APInt APEndOffset;
15863 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
15864 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
15865 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
15866
15867 // If we cannot determine the size of the initial allocation, then we can't
15868 // given an accurate upper-bound. However, we are still able to give
15869 // conservative lower-bounds for Type=3.
15870 if (Type == 1)
15871 return false;
15872 }
15873
15874 CharUnits BytesPerElem;
15875 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
15876 return false;
15877
15878 // According to the GCC documentation, we want the size of the subobject
15879 // denoted by the pointer. But that's not quite right -- what we actually
15880 // want is the size of the immediately-enclosing array, if there is one.
15881 int64_t ElemsRemaining;
15882 if (Designator.MostDerivedIsArrayElement &&
15883 Designator.Entries.size() == Designator.MostDerivedPathLength) {
15884 uint64_t ArraySize = Designator.getMostDerivedArraySize();
15885 uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
15886 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
15887 } else {
15888 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
15889 }
15890
15891 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
15892 return true;
15893 }
15894
15895 /// Tries to evaluate the __builtin_object_size for @p E. If successful,
15896 /// returns true and stores the result in @p Size.
15897 ///
15898 /// If @p WasError is non-null, this will report whether the failure to evaluate
15899 /// is to be treated as an Error in IntExprEvaluator.
15900 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
15901 EvalInfo &Info, uint64_t &Size) {
15902 // Determine the denoted object.
15903 LValue LVal;
15904 {
15905 // The operand of __builtin_object_size is never evaluated for side-effects.
15906 // If there are any, but we can determine the pointed-to object anyway, then
15907 // ignore the side-effects.
15908 SpeculativeEvaluationRAII SpeculativeEval(Info);
15909 IgnoreSideEffectsRAII Fold(Info);
15910
15911 if (E->isGLValue()) {
15912 // It's possible for us to be given GLValues if we're called via
15913 // Expr::tryEvaluateObjectSize.
15914 APValue RVal;
15915 if (!EvaluateAsRValue(Info, E, RVal))
15916 return false;
15917 LVal.setFrom(Info.Ctx, RVal);
15918 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
15919 /*InvalidBaseOK=*/true))
15920 return false;
15921 }
15922
15923 // If we point to before the start of the object, there are no accessible
15924 // bytes.
15925 if (LVal.getLValueOffset().isNegative()) {
15926 Size = 0;
15927 return true;
15928 }
15929
15930 CharUnits EndOffset;
15931 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
15932 return false;
15933
15934 // If we've fallen outside of the end offset, just pretend there's nothing to
15935 // write to/read from.
15936 if (EndOffset <= LVal.getLValueOffset())
15937 Size = 0;
15938 else
15939 Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
15940 return true;
15941 }
15942
15943 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
15944 if (!IsConstantEvaluatedBuiltinCall(E))
15945 return ExprEvaluatorBaseTy::VisitCallExpr(E);
15946 return VisitBuiltinCallExpr(E, E->getBuiltinCallee());
15947 }
15948
15949 static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info,
15950 APValue &Val, APSInt &Alignment) {
15951 QualType SrcTy = E->getArg(0)->getType();
15952 if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment))
15953 return false;
15954 // Even though we are evaluating integer expressions we could get a pointer
15955 // argument for the __builtin_is_aligned() case.
15956 if (SrcTy->isPointerType()) {
15957 LValue Ptr;
15958 if (!EvaluatePointer(E->getArg(0), Ptr, Info))
15959 return false;
15960 Ptr.moveInto(Val);
15961 } else if (!SrcTy->isIntegralOrEnumerationType()) {
15962 Info.FFDiag(E->getArg(0));
15963 return false;
15964 } else {
15965 APSInt SrcInt;
15966 if (!EvaluateInteger(E->getArg(0), SrcInt, Info))
15967 return false;
15968 assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() &&
15969 "Bit widths must be the same");
15970 Val = APValue(SrcInt);
15971 }
15972 assert(Val.hasValue());
15973 return true;
15974 }
15975
15976 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
15977 unsigned BuiltinOp) {
15978 auto EvalTestOp = [&](llvm::function_ref<bool(const APInt &, const APInt &)>
15979 Fn) {
15980 APValue SourceLHS, SourceRHS;
15981 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
15982 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
15983 return false;
15984
15985 unsigned SourceLen = SourceLHS.getVectorLength();
15986 const VectorType *VT = E->getArg(0)->getType()->castAs<VectorType>();
15987 QualType ElemQT = VT->getElementType();
15988 unsigned LaneWidth = Info.Ctx.getTypeSize(ElemQT);
15989
15990 APInt AWide(LaneWidth * SourceLen, 0);
15991 APInt BWide(LaneWidth * SourceLen, 0);
15992
15993 for (unsigned I = 0; I != SourceLen; ++I) {
15994 APInt ALane;
15995 APInt BLane;
15996 if (ElemQT->isIntegerType()) { // Get value.
15997 ALane = SourceLHS.getVectorElt(I).getInt();
15998 BLane = SourceRHS.getVectorElt(I).getInt();
15999 } else if (ElemQT->isFloatingType()) { // Get only sign bit.
16000 ALane =
16001 SourceLHS.getVectorElt(I).getFloat().bitcastToAPInt().isNegative();
16002 BLane =
16003 SourceRHS.getVectorElt(I).getFloat().bitcastToAPInt().isNegative();
16004 } else { // Must be integer or floating type.
16005 return false;
16006 }
16007 AWide.insertBits(ALane, I * LaneWidth);
16008 BWide.insertBits(BLane, I * LaneWidth);
16009 }
16010 return Success(Fn(AWide, BWide), E);
16011 };
16012
16013 auto HandleMaskBinOp =
16014 [&](llvm::function_ref<APSInt(const APSInt &, const APSInt &)> Fn)
16015 -> bool {
16016 APValue LHS, RHS;
16017 if (!Evaluate(LHS, Info, E->getArg(0)) ||
16018 !Evaluate(RHS, Info, E->getArg(1)))
16019 return false;
16020
16021 APSInt ResultInt = Fn(LHS.getInt(), RHS.getInt());
16022
16023 return Success(APValue(ResultInt), E);
16024 };
16025
16026 switch (BuiltinOp) {
16027 default:
16028 return false;
16029
16030 case Builtin::BI__builtin_dynamic_object_size:
16031 case Builtin::BI__builtin_object_size: {
16032 // The type was checked when we built the expression.
16033 unsigned Type =
16034 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
16035 assert(Type <= 3 && "unexpected type");
16036
16037 uint64_t Size;
16038 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
16039 return Success(Size, E);
16040
16041 if (E->getArg(0)->HasSideEffects(Info.Ctx))
16042 return Success((Type & 2) ? 0 : -1, E);
16043
16044 // Expression had no side effects, but we couldn't statically determine the
16045 // size of the referenced object.
16046 switch (Info.EvalMode) {
16047 case EvaluationMode::ConstantExpression:
16048 case EvaluationMode::ConstantFold:
16049 case EvaluationMode::IgnoreSideEffects:
16050 // Leave it to IR generation.
16051 return Error(E);
16052 case EvaluationMode::ConstantExpressionUnevaluated:
16053 // Reduce it to a constant now.
16054 return Success((Type & 2) ? 0 : -1, E);
16055 }
16056
16057 llvm_unreachable("unexpected EvalMode");
16058 }
16059
16060 case Builtin::BI__builtin_os_log_format_buffer_size: {
16061 analyze_os_log::OSLogBufferLayout Layout;
16062 analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
16063 return Success(Layout.size().getQuantity(), E);
16064 }
16065
16066 case Builtin::BI__builtin_is_aligned: {
16067 APValue Src;
16068 APSInt Alignment;
16069 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
16070 return false;
16071 if (Src.isLValue()) {
16072 // If we evaluated a pointer, check the minimum known alignment.
16073 LValue Ptr;
16074 Ptr.setFrom(Info.Ctx, Src);
16075 CharUnits BaseAlignment = getBaseAlignment(Info, Ptr);
16076 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset);
16077 // We can return true if the known alignment at the computed offset is
16078 // greater than the requested alignment.
16079 assert(PtrAlign.isPowerOfTwo());
16080 assert(Alignment.isPowerOf2());
16081 if (PtrAlign.getQuantity() >= Alignment)
16082 return Success(1, E);
16083 // If the alignment is not known to be sufficient, some cases could still
16084 // be aligned at run time. However, if the requested alignment is less or
16085 // equal to the base alignment and the offset is not aligned, we know that
16086 // the run-time value can never be aligned.
16087 if (BaseAlignment.getQuantity() >= Alignment &&
16088 PtrAlign.getQuantity() < Alignment)
16089 return Success(0, E);
16090 // Otherwise we can't infer whether the value is sufficiently aligned.
16091 // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N)
16092 // in cases where we can't fully evaluate the pointer.
16093 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute)
16094 << Alignment;
16095 return false;
16096 }
16097 assert(Src.isInt());
16098 return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E);
16099 }
16100 case Builtin::BI__builtin_align_up: {
16101 APValue Src;
16102 APSInt Alignment;
16103 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
16104 return false;
16105 if (!Src.isInt())
16106 return Error(E);
16107 APSInt AlignedVal =
16108 APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1),
16109 Src.getInt().isUnsigned());
16110 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
16111 return Success(AlignedVal, E);
16112 }
16113 case Builtin::BI__builtin_align_down: {
16114 APValue Src;
16115 APSInt Alignment;
16116 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
16117 return false;
16118 if (!Src.isInt())
16119 return Error(E);
16120 APSInt AlignedVal =
16121 APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned());
16122 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
16123 return Success(AlignedVal, E);
16124 }
16125
16126 case Builtin::BI__builtin_bitreverse8:
16127 case Builtin::BI__builtin_bitreverse16:
16128 case Builtin::BI__builtin_bitreverse32:
16129 case Builtin::BI__builtin_bitreverse64:
16130 case Builtin::BI__builtin_elementwise_bitreverse: {
16131 APSInt Val;
16132 if (!EvaluateInteger(E->getArg(0), Val, Info))
16133 return false;
16134
16135 return Success(Val.reverseBits(), E);
16136 }
16137 case Builtin::BI__builtin_bswapg:
16138 case Builtin::BI__builtin_bswap16:
16139 case Builtin::BI__builtin_bswap32:
16140 case Builtin::BI__builtin_bswap64: {
16141 APSInt Val;
16142 if (!EvaluateInteger(E->getArg(0), Val, Info))
16143 return false;
16144 if (Val.getBitWidth() == 8)
16145 return Success(Val, E);
16146
16147 return Success(Val.byteSwap(), E);
16148 }
16149
16150 case Builtin::BI__builtin_classify_type:
16151 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
16152
16153 case Builtin::BI__builtin_clrsb:
16154 case Builtin::BI__builtin_clrsbl:
16155 case Builtin::BI__builtin_clrsbll: {
16156 APSInt Val;
16157 if (!EvaluateInteger(E->getArg(0), Val, Info))
16158 return false;
16159
16160 return Success(Val.getBitWidth() - Val.getSignificantBits(), E);
16161 }
16162
16163 case Builtin::BI__builtin_clz:
16164 case Builtin::BI__builtin_clzl:
16165 case Builtin::BI__builtin_clzll:
16166 case Builtin::BI__builtin_clzs:
16167 case Builtin::BI__builtin_clzg:
16168 case Builtin::BI__builtin_elementwise_clzg:
16169 case Builtin::BI__lzcnt16: // Microsoft variants of count leading-zeroes
16170 case Builtin::BI__lzcnt:
16171 case Builtin::BI__lzcnt64: {
16172 APSInt Val;
16173 if (E->getArg(0)->getType()->isExtVectorBoolType()) {
16174 APValue Vec;
16175 if (!EvaluateVector(E->getArg(0), Vec, Info))
16176 return false;
16177 Val = ConvertBoolVectorToInt(Vec);
16178 } else if (!EvaluateInteger(E->getArg(0), Val, Info)) {
16179 return false;
16180 }
16181
16182 std::optional<APSInt> Fallback;
16183 if ((BuiltinOp == Builtin::BI__builtin_clzg ||
16184 BuiltinOp == Builtin::BI__builtin_elementwise_clzg) &&
16185 E->getNumArgs() > 1) {
16186 APSInt FallbackTemp;
16187 if (!EvaluateInteger(E->getArg(1), FallbackTemp, Info))
16188 return false;
16189 Fallback = FallbackTemp;
16190 }
16191
16192 if (!Val) {
16193 if (Fallback)
16194 return Success(*Fallback, E);
16195
16196 // When the argument is 0, the result of GCC builtins is undefined,
16197 // whereas for Microsoft intrinsics, the result is the bit-width of the
16198 // argument.
16199 bool ZeroIsUndefined = BuiltinOp != Builtin::BI__lzcnt16 &&
16200 BuiltinOp != Builtin::BI__lzcnt &&
16201 BuiltinOp != Builtin::BI__lzcnt64;
16202
16203 if (BuiltinOp == Builtin::BI__builtin_elementwise_clzg) {
16204 Info.FFDiag(E, diag::note_constexpr_countzeroes_zero)
16205 << /*IsTrailing=*/false;
16206 }
16207
16208 if (ZeroIsUndefined)
16209 return Error(E);
16210 }
16211
16212 return Success(Val.countl_zero(), E);
16213 }
16214
16215 case Builtin::BI__builtin_constant_p: {
16216 const Expr *Arg = E->getArg(0);
16217 if (EvaluateBuiltinConstantP(Info, Arg))
16218 return Success(true, E);
16219 if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
16220 // Outside a constant context, eagerly evaluate to false in the presence
16221 // of side-effects in order to avoid -Wunsequenced false-positives in
16222 // a branch on __builtin_constant_p(expr).
16223 return Success(false, E);
16224 }
16225 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
16226 return false;
16227 }
16228
16229 case Builtin::BI__noop:
16230 // __noop always evaluates successfully and returns 0.
16231 return Success(0, E);
16232
16233 case Builtin::BI__builtin_is_constant_evaluated: {
16234 const auto *Callee = Info.CurrentCall->getCallee();
16235 if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression &&
16236 (Info.CallStackDepth == 1 ||
16237 (Info.CallStackDepth == 2 && Callee->isInStdNamespace() &&
16238 Callee->getIdentifier() &&
16239 Callee->getIdentifier()->isStr("is_constant_evaluated")))) {
16240 // FIXME: Find a better way to avoid duplicated diagnostics.
16241 if (Info.EvalStatus.Diag)
16242 Info.report((Info.CallStackDepth == 1)
16243 ? E->getExprLoc()
16244 : Info.CurrentCall->getCallRange().getBegin(),
16245 diag::warn_is_constant_evaluated_always_true_constexpr)
16246 << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated"
16247 : "std::is_constant_evaluated");
16248 }
16249
16250 return Success(Info.InConstantContext, E);
16251 }
16252
16253 case Builtin::BI__builtin_is_within_lifetime:
16254 if (auto result = EvaluateBuiltinIsWithinLifetime(*this, E))
16255 return Success(*result, E);
16256 return false;
16257
16258 case Builtin::BI__builtin_ctz:
16259 case Builtin::BI__builtin_ctzl:
16260 case Builtin::BI__builtin_ctzll:
16261 case Builtin::BI__builtin_ctzs:
16262 case Builtin::BI__builtin_ctzg:
16263 case Builtin::BI__builtin_elementwise_ctzg: {
16264 APSInt Val;
16265 if (E->getArg(0)->getType()->isExtVectorBoolType()) {
16266 APValue Vec;
16267 if (!EvaluateVector(E->getArg(0), Vec, Info))
16268 return false;
16269 Val = ConvertBoolVectorToInt(Vec);
16270 } else if (!EvaluateInteger(E->getArg(0), Val, Info)) {
16271 return false;
16272 }
16273
16274 std::optional<APSInt> Fallback;
16275 if ((BuiltinOp == Builtin::BI__builtin_ctzg ||
16276 BuiltinOp == Builtin::BI__builtin_elementwise_ctzg) &&
16277 E->getNumArgs() > 1) {
16278 APSInt FallbackTemp;
16279 if (!EvaluateInteger(E->getArg(1), FallbackTemp, Info))
16280 return false;
16281 Fallback = FallbackTemp;
16282 }
16283
16284 if (!Val) {
16285 if (Fallback)
16286 return Success(*Fallback, E);
16287
16288 if (BuiltinOp == Builtin::BI__builtin_elementwise_ctzg) {
16289 Info.FFDiag(E, diag::note_constexpr_countzeroes_zero)
16290 << /*IsTrailing=*/true;
16291 }
16292 return Error(E);
16293 }
16294
16295 return Success(Val.countr_zero(), E);
16296 }
16297
16298 case Builtin::BI__builtin_eh_return_data_regno: {
16299 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
16300 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
16301 return Success(Operand, E);
16302 }
16303
16304 case Builtin::BI__builtin_elementwise_abs: {
16305 APSInt Val;
16306 if (!EvaluateInteger(E->getArg(0), Val, Info))
16307 return false;
16308
16309 return Success(Val.abs(), E);
16310 }
16311
16312 case Builtin::BI__builtin_expect:
16313 case Builtin::BI__builtin_expect_with_probability:
16314 return Visit(E->getArg(0));
16315
16316 case Builtin::BI__builtin_ptrauth_string_discriminator: {
16317 const auto *Literal =
16318 cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts());
16319 uint64_t Result = getPointerAuthStableSipHash(Literal->getString());
16320 return Success(Result, E);
16321 }
16322
16323 case Builtin::BI__builtin_infer_alloc_token: {
16324 // If we fail to infer a type, this fails to be a constant expression; this
16325 // can be checked with __builtin_constant_p(...).
16326 QualType AllocType = infer_alloc::inferPossibleType(E, Info.Ctx, nullptr);
16327 if (AllocType.isNull())
16328 return Error(
16329 E, diag::note_constexpr_infer_alloc_token_type_inference_failed);
16330 auto ATMD = infer_alloc::getAllocTokenMetadata(AllocType, Info.Ctx);
16331 if (!ATMD)
16332 return Error(E, diag::note_constexpr_infer_alloc_token_no_metadata);
16333 auto Mode =
16334 Info.getLangOpts().AllocTokenMode.value_or(llvm::DefaultAllocTokenMode);
16335 uint64_t BitWidth = Info.Ctx.getTypeSize(Info.Ctx.getSizeType());
16336 auto MaxTokensOpt = Info.getLangOpts().AllocTokenMax;
16337 uint64_t MaxTokens =
16338 MaxTokensOpt.value_or(0) ? *MaxTokensOpt : (~0ULL >> (64 - BitWidth));
16339 auto MaybeToken = llvm::getAllocToken(Mode, *ATMD, MaxTokens);
16340 if (!MaybeToken)
16341 return Error(E, diag::note_constexpr_infer_alloc_token_stateful_mode);
16342 return Success(llvm::APInt(BitWidth, *MaybeToken), E);
16343 }
16344
16345 case Builtin::BI__builtin_ffs:
16346 case Builtin::BI__builtin_ffsl:
16347 case Builtin::BI__builtin_ffsll: {
16348 APSInt Val;
16349 if (!EvaluateInteger(E->getArg(0), Val, Info))
16350 return false;
16351
16352 unsigned N = Val.countr_zero();
16353 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
16354 }
16355
16356 case Builtin::BI__builtin_fpclassify: {
16357 APFloat Val(0.0);
16358 if (!EvaluateFloat(E->getArg(5), Val, Info))
16359 return false;
16360 unsigned Arg;
16361 switch (Val.getCategory()) {
16362 case APFloat::fcNaN: Arg = 0; break;
16363 case APFloat::fcInfinity: Arg = 1; break;
16364 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
16365 case APFloat::fcZero: Arg = 4; break;
16366 }
16367 return Visit(E->getArg(Arg));
16368 }
16369
16370 case Builtin::BI__builtin_isinf_sign: {
16371 APFloat Val(0.0);
16372 return EvaluateFloat(E->getArg(0), Val, Info) &&
16373 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
16374 }
16375
16376 case Builtin::BI__builtin_isinf: {
16377 APFloat Val(0.0);
16378 return EvaluateFloat(E->getArg(0), Val, Info) &&
16379 Success(Val.isInfinity() ? 1 : 0, E);
16380 }
16381
16382 case Builtin::BI__builtin_isfinite: {
16383 APFloat Val(0.0);
16384 return EvaluateFloat(E->getArg(0), Val, Info) &&
16385 Success(Val.isFinite() ? 1 : 0, E);
16386 }
16387
16388 case Builtin::BI__builtin_isnan: {
16389 APFloat Val(0.0);
16390 return EvaluateFloat(E->getArg(0), Val, Info) &&
16391 Success(Val.isNaN() ? 1 : 0, E);
16392 }
16393
16394 case Builtin::BI__builtin_isnormal: {
16395 APFloat Val(0.0);
16396 return EvaluateFloat(E->getArg(0), Val, Info) &&
16397 Success(Val.isNormal() ? 1 : 0, E);
16398 }
16399
16400 case Builtin::BI__builtin_issubnormal: {
16401 APFloat Val(0.0);
16402 return EvaluateFloat(E->getArg(0), Val, Info) &&
16403 Success(Val.isDenormal() ? 1 : 0, E);
16404 }
16405
16406 case Builtin::BI__builtin_iszero: {
16407 APFloat Val(0.0);
16408 return EvaluateFloat(E->getArg(0), Val, Info) &&
16409 Success(Val.isZero() ? 1 : 0, E);
16410 }
16411
16412 case Builtin::BI__builtin_signbit:
16413 case Builtin::BI__builtin_signbitf:
16414 case Builtin::BI__builtin_signbitl: {
16415 APFloat Val(0.0);
16416 return EvaluateFloat(E->getArg(0), Val, Info) &&
16417 Success(Val.isNegative() ? 1 : 0, E);
16418 }
16419
16420 case Builtin::BI__builtin_isgreater:
16421 case Builtin::BI__builtin_isgreaterequal:
16422 case Builtin::BI__builtin_isless:
16423 case Builtin::BI__builtin_islessequal:
16424 case Builtin::BI__builtin_islessgreater:
16425 case Builtin::BI__builtin_isunordered: {
16426 APFloat LHS(0.0);
16427 APFloat RHS(0.0);
16428 if (!EvaluateFloat(E->getArg(0), LHS, Info) ||
16429 !EvaluateFloat(E->getArg(1), RHS, Info))
16430 return false;
16431
16432 return Success(
16433 [&] {
16434 switch (BuiltinOp) {
16435 case Builtin::BI__builtin_isgreater:
16436 return LHS > RHS;
16437 case Builtin::BI__builtin_isgreaterequal:
16438 return LHS >= RHS;
16439 case Builtin::BI__builtin_isless:
16440 return LHS < RHS;
16441 case Builtin::BI__builtin_islessequal:
16442 return LHS <= RHS;
16443 case Builtin::BI__builtin_islessgreater: {
16444 APFloat::cmpResult cmp = LHS.compare(RHS);
16445 return cmp == APFloat::cmpResult::cmpLessThan ||
16446 cmp == APFloat::cmpResult::cmpGreaterThan;
16447 }
16448 case Builtin::BI__builtin_isunordered:
16449 return LHS.compare(RHS) == APFloat::cmpResult::cmpUnordered;
16450 default:
16451 llvm_unreachable("Unexpected builtin ID: Should be a floating "
16452 "point comparison function");
16453 }
16454 }()
16455 ? 1
16456 : 0,
16457 E);
16458 }
16459
16460 case Builtin::BI__builtin_issignaling: {
16461 APFloat Val(0.0);
16462 return EvaluateFloat(E->getArg(0), Val, Info) &&
16463 Success(Val.isSignaling() ? 1 : 0, E);
16464 }
16465
16466 case Builtin::BI__builtin_isfpclass: {
16467 APSInt MaskVal;
16468 if (!EvaluateInteger(E->getArg(1), MaskVal, Info))
16469 return false;
16470 unsigned Test = static_cast<llvm::FPClassTest>(MaskVal.getZExtValue());
16471 APFloat Val(0.0);
16472 return EvaluateFloat(E->getArg(0), Val, Info) &&
16473 Success((Val.classify() & Test) ? 1 : 0, E);
16474 }
16475
16476 case Builtin::BI__builtin_parity:
16477 case Builtin::BI__builtin_parityl:
16478 case Builtin::BI__builtin_parityll: {
16479 APSInt Val;
16480 if (!EvaluateInteger(E->getArg(0), Val, Info))
16481 return false;
16482
16483 return Success(Val.popcount() % 2, E);
16484 }
16485
16486 case Builtin::BI__builtin_abs:
16487 case Builtin::BI__builtin_labs:
16488 case Builtin::BI__builtin_llabs: {
16489 APSInt Val;
16490 if (!EvaluateInteger(E->getArg(0), Val, Info))
16491 return false;
16492 if (Val == APSInt(APInt::getSignedMinValue(Val.getBitWidth()),
16493 /*IsUnsigned=*/false))
16494 return false;
16495 if (Val.isNegative())
16496 Val.negate();
16497 return Success(Val, E);
16498 }
16499
16500 case Builtin::BI__builtin_popcount:
16501 case Builtin::BI__builtin_popcountl:
16502 case Builtin::BI__builtin_popcountll:
16503 case Builtin::BI__builtin_popcountg:
16504 case Builtin::BI__builtin_elementwise_popcount:
16505 case Builtin::BI__popcnt16: // Microsoft variants of popcount
16506 case Builtin::BI__popcnt:
16507 case Builtin::BI__popcnt64: {
16508 APSInt Val;
16509 if (E->getArg(0)->getType()->isExtVectorBoolType()) {
16510 APValue Vec;
16511 if (!EvaluateVector(E->getArg(0), Vec, Info))
16512 return false;
16513 Val = ConvertBoolVectorToInt(Vec);
16514 } else if (!EvaluateInteger(E->getArg(0), Val, Info)) {
16515 return false;
16516 }
16517
16518 return Success(Val.popcount(), E);
16519 }
16520
16521 case Builtin::BI__builtin_rotateleft8:
16522 case Builtin::BI__builtin_rotateleft16:
16523 case Builtin::BI__builtin_rotateleft32:
16524 case Builtin::BI__builtin_rotateleft64:
16525 case Builtin::BI_rotl8: // Microsoft variants of rotate right
16526 case Builtin::BI_rotl16:
16527 case Builtin::BI_rotl:
16528 case Builtin::BI_lrotl:
16529 case Builtin::BI_rotl64: {
16530 APSInt Val, Amt;
16531 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
16532 !EvaluateInteger(E->getArg(1), Amt, Info))
16533 return false;
16534
16535 return Success(Val.rotl(Amt), E);
16536 }
16537
16538 case Builtin::BI__builtin_rotateright8:
16539 case Builtin::BI__builtin_rotateright16:
16540 case Builtin::BI__builtin_rotateright32:
16541 case Builtin::BI__builtin_rotateright64:
16542 case Builtin::BI_rotr8: // Microsoft variants of rotate right
16543 case Builtin::BI_rotr16:
16544 case Builtin::BI_rotr:
16545 case Builtin::BI_lrotr:
16546 case Builtin::BI_rotr64: {
16547 APSInt Val, Amt;
16548 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
16549 !EvaluateInteger(E->getArg(1), Amt, Info))
16550 return false;
16551
16552 return Success(Val.rotr(Amt), E);
16553 }
16554
16555 case Builtin::BI__builtin_elementwise_add_sat: {
16556 APSInt LHS, RHS;
16557 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
16558 !EvaluateInteger(E->getArg(1), RHS, Info))
16559 return false;
16560
16561 APInt Result = LHS.isSigned() ? LHS.sadd_sat(RHS) : LHS.uadd_sat(RHS);
16562 return Success(APSInt(Result, !LHS.isSigned()), E);
16563 }
16564 case Builtin::BI__builtin_elementwise_sub_sat: {
16565 APSInt LHS, RHS;
16566 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
16567 !EvaluateInteger(E->getArg(1), RHS, Info))
16568 return false;
16569
16570 APInt Result = LHS.isSigned() ? LHS.ssub_sat(RHS) : LHS.usub_sat(RHS);
16571 return Success(APSInt(Result, !LHS.isSigned()), E);
16572 }
16573 case Builtin::BI__builtin_elementwise_max: {
16574 APSInt LHS, RHS;
16575 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
16576 !EvaluateInteger(E->getArg(1), RHS, Info))
16577 return false;
16578
16579 APInt Result = std::max(LHS, RHS);
16580 return Success(APSInt(Result, !LHS.isSigned()), E);
16581 }
16582 case Builtin::BI__builtin_elementwise_min: {
16583 APSInt LHS, RHS;
16584 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
16585 !EvaluateInteger(E->getArg(1), RHS, Info))
16586 return false;
16587
16588 APInt Result = std::min(LHS, RHS);
16589 return Success(APSInt(Result, !LHS.isSigned()), E);
16590 }
16591 case Builtin::BI__builtin_elementwise_fshl:
16592 case Builtin::BI__builtin_elementwise_fshr: {
16593 APSInt Hi, Lo, Shift;
16594 if (!EvaluateInteger(E->getArg(0), Hi, Info) ||
16595 !EvaluateInteger(E->getArg(1), Lo, Info) ||
16596 !EvaluateInteger(E->getArg(2), Shift, Info))
16597 return false;
16598
16599 switch (BuiltinOp) {
16600 case Builtin::BI__builtin_elementwise_fshl: {
16601 APSInt Result(llvm::APIntOps::fshl(Hi, Lo, Shift), Hi.isUnsigned());
16602 return Success(Result, E);
16603 }
16604 case Builtin::BI__builtin_elementwise_fshr: {
16605 APSInt Result(llvm::APIntOps::fshr(Hi, Lo, Shift), Hi.isUnsigned());
16606 return Success(Result, E);
16607 }
16608 }
16609 llvm_unreachable("Fully covered switch above");
16610 }
16611 case Builtin::BIstrlen:
16612 case Builtin::BIwcslen:
16613 // A call to strlen is not a constant expression.
16614 if (Info.getLangOpts().CPlusPlus11)
16615 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
16616 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
16617 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
16618 else
16619 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
16620 [[fallthrough]];
16621 case Builtin::BI__builtin_strlen:
16622 case Builtin::BI__builtin_wcslen: {
16623 // As an extension, we support __builtin_strlen() as a constant expression,
16624 // and support folding strlen() to a constant.
16625 uint64_t StrLen;
16626 if (EvaluateBuiltinStrLen(E->getArg(0), StrLen, Info))
16627 return Success(StrLen, E);
16628 return false;
16629 }
16630
16631 case Builtin::BIstrcmp:
16632 case Builtin::BIwcscmp:
16633 case Builtin::BIstrncmp:
16634 case Builtin::BIwcsncmp:
16635 case Builtin::BImemcmp:
16636 case Builtin::BIbcmp:
16637 case Builtin::BIwmemcmp:
16638 // A call to strlen is not a constant expression.
16639 if (Info.getLangOpts().CPlusPlus11)
16640 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
16641 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
16642 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
16643 else
16644 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
16645 [[fallthrough]];
16646 case Builtin::BI__builtin_strcmp:
16647 case Builtin::BI__builtin_wcscmp:
16648 case Builtin::BI__builtin_strncmp:
16649 case Builtin::BI__builtin_wcsncmp:
16650 case Builtin::BI__builtin_memcmp:
16651 case Builtin::BI__builtin_bcmp:
16652 case Builtin::BI__builtin_wmemcmp: {
16653 LValue String1, String2;
16654 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
16655 !EvaluatePointer(E->getArg(1), String2, Info))
16656 return false;
16657
16658 uint64_t MaxLength = uint64_t(-1);
16659 if (BuiltinOp != Builtin::BIstrcmp &&
16660 BuiltinOp != Builtin::BIwcscmp &&
16661 BuiltinOp != Builtin::BI__builtin_strcmp &&
16662 BuiltinOp != Builtin::BI__builtin_wcscmp) {
16663 APSInt N;
16664 if (!EvaluateInteger(E->getArg(2), N, Info))
16665 return false;
16666 MaxLength = N.getZExtValue();
16667 }
16668
16669 // Empty substrings compare equal by definition.
16670 if (MaxLength == 0u)
16671 return Success(0, E);
16672
16673 if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
16674 !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
16675 String1.Designator.Invalid || String2.Designator.Invalid)
16676 return false;
16677
16678 QualType CharTy1 = String1.Designator.getType(Info.Ctx);
16679 QualType CharTy2 = String2.Designator.getType(Info.Ctx);
16680
16681 bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
16682 BuiltinOp == Builtin::BIbcmp ||
16683 BuiltinOp == Builtin::BI__builtin_memcmp ||
16684 BuiltinOp == Builtin::BI__builtin_bcmp;
16685
16686 assert(IsRawByte ||
16687 (Info.Ctx.hasSameUnqualifiedType(
16688 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
16689 Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
16690
16691 // For memcmp, allow comparing any arrays of '[[un]signed] char' or
16692 // 'char8_t', but no other types.
16693 if (IsRawByte &&
16694 !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) {
16695 // FIXME: Consider using our bit_cast implementation to support this.
16696 Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported)
16697 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp) << CharTy1
16698 << CharTy2;
16699 return false;
16700 }
16701
16702 const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
16703 return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
16704 handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
16705 Char1.isInt() && Char2.isInt();
16706 };
16707 const auto &AdvanceElems = [&] {
16708 return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
16709 HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
16710 };
16711
16712 bool StopAtNull =
16713 (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
16714 BuiltinOp != Builtin::BIwmemcmp &&
16715 BuiltinOp != Builtin::BI__builtin_memcmp &&
16716 BuiltinOp != Builtin::BI__builtin_bcmp &&
16717 BuiltinOp != Builtin::BI__builtin_wmemcmp);
16718 bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
16719 BuiltinOp == Builtin::BIwcsncmp ||
16720 BuiltinOp == Builtin::BIwmemcmp ||
16721 BuiltinOp == Builtin::BI__builtin_wcscmp ||
16722 BuiltinOp == Builtin::BI__builtin_wcsncmp ||
16723 BuiltinOp == Builtin::BI__builtin_wmemcmp;
16724
16725 for (; MaxLength; --MaxLength) {
16726 APValue Char1, Char2;
16727 if (!ReadCurElems(Char1, Char2))
16728 return false;
16729 if (Char1.getInt().ne(Char2.getInt())) {
16730 if (IsWide) // wmemcmp compares with wchar_t signedness.
16731 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
16732 // memcmp always compares unsigned chars.
16733 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
16734 }
16735 if (StopAtNull && !Char1.getInt())
16736 return Success(0, E);
16737 assert(!(StopAtNull && !Char2.getInt()));
16738 if (!AdvanceElems())
16739 return false;
16740 }
16741 // We hit the strncmp / memcmp limit.
16742 return Success(0, E);
16743 }
16744
16745 case Builtin::BI__atomic_always_lock_free:
16746 case Builtin::BI__atomic_is_lock_free:
16747 case Builtin::BI__c11_atomic_is_lock_free: {
16748 APSInt SizeVal;
16749 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
16750 return false;
16751
16752 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
16753 // of two less than or equal to the maximum inline atomic width, we know it
16754 // is lock-free. If the size isn't a power of two, or greater than the
16755 // maximum alignment where we promote atomics, we know it is not lock-free
16756 // (at least not in the sense of atomic_is_lock_free). Otherwise,
16757 // the answer can only be determined at runtime; for example, 16-byte
16758 // atomics have lock-free implementations on some, but not all,
16759 // x86-64 processors.
16760
16761 // Check power-of-two.
16762 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
16763 if (Size.isPowerOfTwo()) {
16764 // Check against inlining width.
16765 unsigned InlineWidthBits =
16766 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
16767 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
16768 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
16769 Size == CharUnits::One())
16770 return Success(1, E);
16771
16772 // If the pointer argument can be evaluated to a compile-time constant
16773 // integer (or nullptr), check if that value is appropriately aligned.
16774 const Expr *PtrArg = E->getArg(1);
16775 Expr::EvalResult ExprResult;
16776 APSInt IntResult;
16777 if (PtrArg->EvaluateAsRValue(ExprResult, Info.Ctx) &&
16778 ExprResult.Val.toIntegralConstant(IntResult, PtrArg->getType(),
16779 Info.Ctx) &&
16780 IntResult.isAligned(Size.getAsAlign()))
16781 return Success(1, E);
16782
16783 // Otherwise, check if the type's alignment against Size.
16784 if (auto *ICE = dyn_cast<ImplicitCastExpr>(PtrArg)) {
16785 // Drop the potential implicit-cast to 'const volatile void*', getting
16786 // the underlying type.
16787 if (ICE->getCastKind() == CK_BitCast)
16788 PtrArg = ICE->getSubExpr();
16789 }
16790
16791 if (auto PtrTy = PtrArg->getType()->getAs<PointerType>()) {
16792 QualType PointeeType = PtrTy->getPointeeType();
16793 if (!PointeeType->isIncompleteType() &&
16794 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
16795 // OK, we will inline operations on this object.
16796 return Success(1, E);
16797 }
16798 }
16799 }
16800 }
16801
16802 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
16803 Success(0, E) : Error(E);
16804 }
16805 case Builtin::BI__builtin_addcb:
16806 case Builtin::BI__builtin_addcs:
16807 case Builtin::BI__builtin_addc:
16808 case Builtin::BI__builtin_addcl:
16809 case Builtin::BI__builtin_addcll:
16810 case Builtin::BI__builtin_subcb:
16811 case Builtin::BI__builtin_subcs:
16812 case Builtin::BI__builtin_subc:
16813 case Builtin::BI__builtin_subcl:
16814 case Builtin::BI__builtin_subcll: {
16815 LValue CarryOutLValue;
16816 APSInt LHS, RHS, CarryIn, CarryOut, Result;
16817 QualType ResultType = E->getArg(0)->getType();
16818 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
16819 !EvaluateInteger(E->getArg(1), RHS, Info) ||
16820 !EvaluateInteger(E->getArg(2), CarryIn, Info) ||
16821 !EvaluatePointer(E->getArg(3), CarryOutLValue, Info))
16822 return false;
16823 // Copy the number of bits and sign.
16824 Result = LHS;
16825 CarryOut = LHS;
16826
16827 bool FirstOverflowed = false;
16828 bool SecondOverflowed = false;
16829 switch (BuiltinOp) {
16830 default:
16831 llvm_unreachable("Invalid value for BuiltinOp");
16832 case Builtin::BI__builtin_addcb:
16833 case Builtin::BI__builtin_addcs:
16834 case Builtin::BI__builtin_addc:
16835 case Builtin::BI__builtin_addcl:
16836 case Builtin::BI__builtin_addcll:
16837 Result =
16838 LHS.uadd_ov(RHS, FirstOverflowed).uadd_ov(CarryIn, SecondOverflowed);
16839 break;
16840 case Builtin::BI__builtin_subcb:
16841 case Builtin::BI__builtin_subcs:
16842 case Builtin::BI__builtin_subc:
16843 case Builtin::BI__builtin_subcl:
16844 case Builtin::BI__builtin_subcll:
16845 Result =
16846 LHS.usub_ov(RHS, FirstOverflowed).usub_ov(CarryIn, SecondOverflowed);
16847 break;
16848 }
16849
16850 // It is possible for both overflows to happen but CGBuiltin uses an OR so
16851 // this is consistent.
16852 CarryOut = (uint64_t)(FirstOverflowed | SecondOverflowed);
16853 APValue APV{CarryOut};
16854 if (!handleAssignment(Info, E, CarryOutLValue, ResultType, APV))
16855 return false;
16856 return Success(Result, E);
16857 }
16858 case Builtin::BI__builtin_add_overflow:
16859 case Builtin::BI__builtin_sub_overflow:
16860 case Builtin::BI__builtin_mul_overflow:
16861 case Builtin::BI__builtin_sadd_overflow:
16862 case Builtin::BI__builtin_uadd_overflow:
16863 case Builtin::BI__builtin_uaddl_overflow:
16864 case Builtin::BI__builtin_uaddll_overflow:
16865 case Builtin::BI__builtin_usub_overflow:
16866 case Builtin::BI__builtin_usubl_overflow:
16867 case Builtin::BI__builtin_usubll_overflow:
16868 case Builtin::BI__builtin_umul_overflow:
16869 case Builtin::BI__builtin_umull_overflow:
16870 case Builtin::BI__builtin_umulll_overflow:
16871 case Builtin::BI__builtin_saddl_overflow:
16872 case Builtin::BI__builtin_saddll_overflow:
16873 case Builtin::BI__builtin_ssub_overflow:
16874 case Builtin::BI__builtin_ssubl_overflow:
16875 case Builtin::BI__builtin_ssubll_overflow:
16876 case Builtin::BI__builtin_smul_overflow:
16877 case Builtin::BI__builtin_smull_overflow:
16878 case Builtin::BI__builtin_smulll_overflow: {
16879 LValue ResultLValue;
16880 APSInt LHS, RHS;
16881
16882 QualType ResultType = E->getArg(2)->getType()->getPointeeType();
16883 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
16884 !EvaluateInteger(E->getArg(1), RHS, Info) ||
16885 !EvaluatePointer(E->getArg(2), ResultLValue, Info))
16886 return false;
16887
16888 APSInt Result;
16889 bool DidOverflow = false;
16890
16891 // If the types don't have to match, enlarge all 3 to the largest of them.
16892 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
16893 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
16894 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
16895 bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
16896 ResultType->isSignedIntegerOrEnumerationType();
16897 bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
16898 ResultType->isSignedIntegerOrEnumerationType();
16899 uint64_t LHSSize = LHS.getBitWidth();
16900 uint64_t RHSSize = RHS.getBitWidth();
16901 uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
16902 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
16903
16904 // Add an additional bit if the signedness isn't uniformly agreed to. We
16905 // could do this ONLY if there is a signed and an unsigned that both have
16906 // MaxBits, but the code to check that is pretty nasty. The issue will be
16907 // caught in the shrink-to-result later anyway.
16908 if (IsSigned && !AllSigned)
16909 ++MaxBits;
16910
16911 LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
16912 RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
16913 Result = APSInt(MaxBits, !IsSigned);
16914 }
16915
16916 // Find largest int.
16917 switch (BuiltinOp) {
16918 default:
16919 llvm_unreachable("Invalid value for BuiltinOp");
16920 case Builtin::BI__builtin_add_overflow:
16921 case Builtin::BI__builtin_sadd_overflow:
16922 case Builtin::BI__builtin_saddl_overflow:
16923 case Builtin::BI__builtin_saddll_overflow:
16924 case Builtin::BI__builtin_uadd_overflow:
16925 case Builtin::BI__builtin_uaddl_overflow:
16926 case Builtin::BI__builtin_uaddll_overflow:
16927 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
16928 : LHS.uadd_ov(RHS, DidOverflow);
16929 break;
16930 case Builtin::BI__builtin_sub_overflow:
16931 case Builtin::BI__builtin_ssub_overflow:
16932 case Builtin::BI__builtin_ssubl_overflow:
16933 case Builtin::BI__builtin_ssubll_overflow:
16934 case Builtin::BI__builtin_usub_overflow:
16935 case Builtin::BI__builtin_usubl_overflow:
16936 case Builtin::BI__builtin_usubll_overflow:
16937 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
16938 : LHS.usub_ov(RHS, DidOverflow);
16939 break;
16940 case Builtin::BI__builtin_mul_overflow:
16941 case Builtin::BI__builtin_smul_overflow:
16942 case Builtin::BI__builtin_smull_overflow:
16943 case Builtin::BI__builtin_smulll_overflow:
16944 case Builtin::BI__builtin_umul_overflow:
16945 case Builtin::BI__builtin_umull_overflow:
16946 case Builtin::BI__builtin_umulll_overflow:
16947 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
16948 : LHS.umul_ov(RHS, DidOverflow);
16949 break;
16950 }
16951
16952 // In the case where multiple sizes are allowed, truncate and see if
16953 // the values are the same.
16954 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
16955 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
16956 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
16957 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
16958 // since it will give us the behavior of a TruncOrSelf in the case where
16959 // its parameter <= its size. We previously set Result to be at least the
16960 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
16961 // will work exactly like TruncOrSelf.
16962 APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
16963 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
16964
16965 if (!APSInt::isSameValue(Temp, Result))
16966 DidOverflow = true;
16967 Result = Temp;
16968 }
16969
16970 APValue APV{Result};
16971 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
16972 return false;
16973 return Success(DidOverflow, E);
16974 }
16975
16976 case Builtin::BI__builtin_reduce_add:
16977 case Builtin::BI__builtin_reduce_mul:
16978 case Builtin::BI__builtin_reduce_and:
16979 case Builtin::BI__builtin_reduce_or:
16980 case Builtin::BI__builtin_reduce_xor:
16981 case Builtin::BI__builtin_reduce_min:
16982 case Builtin::BI__builtin_reduce_max: {
16983 APValue Source;
16984 if (!EvaluateAsRValue(Info, E->getArg(0), Source))
16985 return false;
16986
16987 unsigned SourceLen = Source.getVectorLength();
16988 APSInt Reduced = Source.getVectorElt(0).getInt();
16989 for (unsigned EltNum = 1; EltNum < SourceLen; ++EltNum) {
16990 switch (BuiltinOp) {
16991 default:
16992 return false;
16993 case Builtin::BI__builtin_reduce_add: {
16994 if (!CheckedIntArithmetic(
16995 Info, E, Reduced, Source.getVectorElt(EltNum).getInt(),
16996 Reduced.getBitWidth() + 1, std::plus<APSInt>(), Reduced))
16997 return false;
16998 break;
16999 }
17000 case Builtin::BI__builtin_reduce_mul: {
17001 if (!CheckedIntArithmetic(
17002 Info, E, Reduced, Source.getVectorElt(EltNum).getInt(),
17003 Reduced.getBitWidth() * 2, std::multiplies<APSInt>(), Reduced))
17004 return false;
17005 break;
17006 }
17007 case Builtin::BI__builtin_reduce_and: {
17008 Reduced &= Source.getVectorElt(EltNum).getInt();
17009 break;
17010 }
17011 case Builtin::BI__builtin_reduce_or: {
17012 Reduced |= Source.getVectorElt(EltNum).getInt();
17013 break;
17014 }
17015 case Builtin::BI__builtin_reduce_xor: {
17016 Reduced ^= Source.getVectorElt(EltNum).getInt();
17017 break;
17018 }
17019 case Builtin::BI__builtin_reduce_min: {
17020 Reduced = std::min(Reduced, Source.getVectorElt(EltNum).getInt());
17021 break;
17022 }
17023 case Builtin::BI__builtin_reduce_max: {
17024 Reduced = std::max(Reduced, Source.getVectorElt(EltNum).getInt());
17025 break;
17026 }
17027 }
17028 }
17029
17030 return Success(Reduced, E);
17031 }
17032
17033 case clang::X86::BI__builtin_ia32_addcarryx_u32:
17034 case clang::X86::BI__builtin_ia32_addcarryx_u64:
17035 case clang::X86::BI__builtin_ia32_subborrow_u32:
17036 case clang::X86::BI__builtin_ia32_subborrow_u64: {
17037 LValue ResultLValue;
17038 APSInt CarryIn, LHS, RHS;
17039 QualType ResultType = E->getArg(3)->getType()->getPointeeType();
17040 if (!EvaluateInteger(E->getArg(0), CarryIn, Info) ||
17041 !EvaluateInteger(E->getArg(1), LHS, Info) ||
17042 !EvaluateInteger(E->getArg(2), RHS, Info) ||
17043 !EvaluatePointer(E->getArg(3), ResultLValue, Info))
17044 return false;
17045
17046 bool IsAdd = BuiltinOp == clang::X86::BI__builtin_ia32_addcarryx_u32 ||
17047 BuiltinOp == clang::X86::BI__builtin_ia32_addcarryx_u64;
17048
17049 unsigned BitWidth = LHS.getBitWidth();
17050 unsigned CarryInBit = CarryIn.ugt(0) ? 1 : 0;
17051 APInt ExResult =
17052 IsAdd
17053 ? (LHS.zext(BitWidth + 1) + (RHS.zext(BitWidth + 1) + CarryInBit))
17054 : (LHS.zext(BitWidth + 1) - (RHS.zext(BitWidth + 1) + CarryInBit));
17055
17056 APInt Result = ExResult.extractBits(BitWidth, 0);
17057 uint64_t CarryOut = ExResult.extractBitsAsZExtValue(1, BitWidth);
17058
17059 APValue APV{APSInt(Result, /*isUnsigned=*/true)};
17060 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
17061 return false;
17062 return Success(CarryOut, E);
17063 }
17064
17065 case clang::X86::BI__builtin_ia32_movmskps:
17066 case clang::X86::BI__builtin_ia32_movmskpd:
17067 case clang::X86::BI__builtin_ia32_pmovmskb128:
17068 case clang::X86::BI__builtin_ia32_pmovmskb256:
17069 case clang::X86::BI__builtin_ia32_movmskps256:
17070 case clang::X86::BI__builtin_ia32_movmskpd256: {
17071 APValue Source;
17072 if (!Evaluate(Source, Info, E->getArg(0)))
17073 return false;
17074 unsigned SourceLen = Source.getVectorLength();
17075 const VectorType *VT = E->getArg(0)->getType()->castAs<VectorType>();
17076 QualType ElemQT = VT->getElementType();
17077 unsigned ResultLen = Info.Ctx.getTypeSize(
17078 E->getCallReturnType(Info.Ctx)); // Always 32-bit integer.
17079 APInt Result(ResultLen, 0);
17080
17081 for (unsigned I = 0; I != SourceLen; ++I) {
17082 APInt Elem;
17083 if (ElemQT->isIntegerType()) {
17084 Elem = Source.getVectorElt(I).getInt();
17085 } else if (ElemQT->isRealFloatingType()) {
17086 Elem = Source.getVectorElt(I).getFloat().bitcastToAPInt();
17087 } else {
17088 return false;
17089 }
17090 Result.setBitVal(I, Elem.isNegative());
17091 }
17092 return Success(Result, E);
17093 }
17094
17095 case clang::X86::BI__builtin_ia32_bextr_u32:
17096 case clang::X86::BI__builtin_ia32_bextr_u64:
17097 case clang::X86::BI__builtin_ia32_bextri_u32:
17098 case clang::X86::BI__builtin_ia32_bextri_u64: {
17099 APSInt Val, Idx;
17100 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
17101 !EvaluateInteger(E->getArg(1), Idx, Info))
17102 return false;
17103
17104 unsigned BitWidth = Val.getBitWidth();
17105 uint64_t Shift = Idx.extractBitsAsZExtValue(8, 0);
17106 uint64_t Length = Idx.extractBitsAsZExtValue(8, 8);
17107 Length = Length > BitWidth ? BitWidth : Length;
17108
17109 // Handle out of bounds cases.
17110 if (Length == 0 || Shift >= BitWidth)
17111 return Success(0, E);
17112
17113 uint64_t Result = Val.getZExtValue() >> Shift;
17114 Result &= llvm::maskTrailingOnes<uint64_t>(Length);
17115 return Success(Result, E);
17116 }
17117
17118 case clang::X86::BI__builtin_ia32_bzhi_si:
17119 case clang::X86::BI__builtin_ia32_bzhi_di: {
17120 APSInt Val, Idx;
17121 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
17122 !EvaluateInteger(E->getArg(1), Idx, Info))
17123 return false;
17124
17125 unsigned BitWidth = Val.getBitWidth();
17126 unsigned Index = Idx.extractBitsAsZExtValue(8, 0);
17127 if (Index < BitWidth)
17128 Val.clearHighBits(BitWidth - Index);
17129 return Success(Val, E);
17130 }
17131
17132 case clang::X86::BI__builtin_ia32_ktestcqi:
17133 case clang::X86::BI__builtin_ia32_ktestchi:
17134 case clang::X86::BI__builtin_ia32_ktestcsi:
17135 case clang::X86::BI__builtin_ia32_ktestcdi: {
17136 APSInt A, B;
17137 if (!EvaluateInteger(E->getArg(0), A, Info) ||
17138 !EvaluateInteger(E->getArg(1), B, Info))
17139 return false;
17140
17141 return Success((~A & B) == 0, E);
17142 }
17143
17144 case clang::X86::BI__builtin_ia32_ktestzqi:
17145 case clang::X86::BI__builtin_ia32_ktestzhi:
17146 case clang::X86::BI__builtin_ia32_ktestzsi:
17147 case clang::X86::BI__builtin_ia32_ktestzdi: {
17148 APSInt A, B;
17149 if (!EvaluateInteger(E->getArg(0), A, Info) ||
17150 !EvaluateInteger(E->getArg(1), B, Info))
17151 return false;
17152
17153 return Success((A & B) == 0, E);
17154 }
17155
17156 case clang::X86::BI__builtin_ia32_kortestcqi:
17157 case clang::X86::BI__builtin_ia32_kortestchi:
17158 case clang::X86::BI__builtin_ia32_kortestcsi:
17159 case clang::X86::BI__builtin_ia32_kortestcdi: {
17160 APSInt A, B;
17161 if (!EvaluateInteger(E->getArg(0), A, Info) ||
17162 !EvaluateInteger(E->getArg(1), B, Info))
17163 return false;
17164
17165 return Success(~(A | B) == 0, E);
17166 }
17167
17168 case clang::X86::BI__builtin_ia32_kortestzqi:
17169 case clang::X86::BI__builtin_ia32_kortestzhi:
17170 case clang::X86::BI__builtin_ia32_kortestzsi:
17171 case clang::X86::BI__builtin_ia32_kortestzdi: {
17172 APSInt A, B;
17173 if (!EvaluateInteger(E->getArg(0), A, Info) ||
17174 !EvaluateInteger(E->getArg(1), B, Info))
17175 return false;
17176
17177 return Success((A | B) == 0, E);
17178 }
17179
17180 case clang::X86::BI__builtin_ia32_kunpckhi:
17181 case clang::X86::BI__builtin_ia32_kunpckdi:
17182 case clang::X86::BI__builtin_ia32_kunpcksi: {
17183 APSInt A, B;
17184 if (!EvaluateInteger(E->getArg(0), A, Info) ||
17185 !EvaluateInteger(E->getArg(1), B, Info))
17186 return false;
17187
17188 // Generic kunpack: extract lower half of each operand and concatenate
17189 // Result = A[HalfWidth-1:0] concat B[HalfWidth-1:0]
17190 unsigned BW = A.getBitWidth();
17191 APSInt Result(A.trunc(BW / 2).concat(B.trunc(BW / 2)), A.isUnsigned());
17192 return Success(Result, E);
17193 }
17194
17195 case clang::X86::BI__builtin_ia32_lzcnt_u16:
17196 case clang::X86::BI__builtin_ia32_lzcnt_u32:
17197 case clang::X86::BI__builtin_ia32_lzcnt_u64: {
17198 APSInt Val;
17199 if (!EvaluateInteger(E->getArg(0), Val, Info))
17200 return false;
17201 return Success(Val.countLeadingZeros(), E);
17202 }
17203
17204 case clang::X86::BI__builtin_ia32_tzcnt_u16:
17205 case clang::X86::BI__builtin_ia32_tzcnt_u32:
17206 case clang::X86::BI__builtin_ia32_tzcnt_u64: {
17207 APSInt Val;
17208 if (!EvaluateInteger(E->getArg(0), Val, Info))
17209 return false;
17210 return Success(Val.countTrailingZeros(), E);
17211 }
17212
17213 case clang::X86::BI__builtin_ia32_pdep_si:
17214 case clang::X86::BI__builtin_ia32_pdep_di: {
17215 APSInt Val, Msk;
17216 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
17217 !EvaluateInteger(E->getArg(1), Msk, Info))
17218 return false;
17219
17220 unsigned BitWidth = Val.getBitWidth();
17221 APInt Result = APInt::getZero(BitWidth);
17222 for (unsigned I = 0, P = 0; I != BitWidth; ++I)
17223 if (Msk[I])
17224 Result.setBitVal(I, Val[P++]);
17225 return Success(Result, E);
17226 }
17227
17228 case clang::X86::BI__builtin_ia32_pext_si:
17229 case clang::X86::BI__builtin_ia32_pext_di: {
17230 APSInt Val, Msk;
17231 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
17232 !EvaluateInteger(E->getArg(1), Msk, Info))
17233 return false;
17234
17235 unsigned BitWidth = Val.getBitWidth();
17236 APInt Result = APInt::getZero(BitWidth);
17237 for (unsigned I = 0, P = 0; I != BitWidth; ++I)
17238 if (Msk[I])
17239 Result.setBitVal(P++, Val[I]);
17240 return Success(Result, E);
17241 }
17242 case X86::BI__builtin_ia32_ptestz128:
17243 case X86::BI__builtin_ia32_ptestz256:
17244 case X86::BI__builtin_ia32_vtestzps:
17245 case X86::BI__builtin_ia32_vtestzps256:
17246 case X86::BI__builtin_ia32_vtestzpd:
17247 case X86::BI__builtin_ia32_vtestzpd256: {
17248 return EvalTestOp(
17249 [](const APInt &A, const APInt &B) { return (A & B) == 0; });
17250 }
17251 case X86::BI__builtin_ia32_ptestc128:
17252 case X86::BI__builtin_ia32_ptestc256:
17253 case X86::BI__builtin_ia32_vtestcps:
17254 case X86::BI__builtin_ia32_vtestcps256:
17255 case X86::BI__builtin_ia32_vtestcpd:
17256 case X86::BI__builtin_ia32_vtestcpd256: {
17257 return EvalTestOp(
17258 [](const APInt &A, const APInt &B) { return (~A & B) == 0; });
17259 }
17260 case X86::BI__builtin_ia32_ptestnzc128:
17261 case X86::BI__builtin_ia32_ptestnzc256:
17262 case X86::BI__builtin_ia32_vtestnzcps:
17263 case X86::BI__builtin_ia32_vtestnzcps256:
17264 case X86::BI__builtin_ia32_vtestnzcpd:
17265 case X86::BI__builtin_ia32_vtestnzcpd256: {
17266 return EvalTestOp([](const APInt &A, const APInt &B) {
17267 return ((A & B) != 0) && ((~A & B) != 0);
17268 });
17269 }
17270 case X86::BI__builtin_ia32_kandqi:
17271 case X86::BI__builtin_ia32_kandhi:
17272 case X86::BI__builtin_ia32_kandsi:
17273 case X86::BI__builtin_ia32_kanddi: {
17274 return HandleMaskBinOp(
17275 [](const APSInt &LHS, const APSInt &RHS) { return LHS & RHS; });
17276 }
17277
17278 case X86::BI__builtin_ia32_kandnqi:
17279 case X86::BI__builtin_ia32_kandnhi:
17280 case X86::BI__builtin_ia32_kandnsi:
17281 case X86::BI__builtin_ia32_kandndi: {
17282 return HandleMaskBinOp(
17283 [](const APSInt &LHS, const APSInt &RHS) { return ~LHS & RHS; });
17284 }
17285
17286 case X86::BI__builtin_ia32_korqi:
17287 case X86::BI__builtin_ia32_korhi:
17288 case X86::BI__builtin_ia32_korsi:
17289 case X86::BI__builtin_ia32_kordi: {
17290 return HandleMaskBinOp(
17291 [](const APSInt &LHS, const APSInt &RHS) { return LHS | RHS; });
17292 }
17293
17294 case X86::BI__builtin_ia32_kxnorqi:
17295 case X86::BI__builtin_ia32_kxnorhi:
17296 case X86::BI__builtin_ia32_kxnorsi:
17297 case X86::BI__builtin_ia32_kxnordi: {
17298 return HandleMaskBinOp(
17299 [](const APSInt &LHS, const APSInt &RHS) { return ~(LHS ^ RHS); });
17300 }
17301
17302 case X86::BI__builtin_ia32_kxorqi:
17303 case X86::BI__builtin_ia32_kxorhi:
17304 case X86::BI__builtin_ia32_kxorsi:
17305 case X86::BI__builtin_ia32_kxordi: {
17306 return HandleMaskBinOp(
17307 [](const APSInt &LHS, const APSInt &RHS) { return LHS ^ RHS; });
17308 }
17309
17310 case X86::BI__builtin_ia32_knotqi:
17311 case X86::BI__builtin_ia32_knothi:
17312 case X86::BI__builtin_ia32_knotsi:
17313 case X86::BI__builtin_ia32_knotdi: {
17314 APSInt Val;
17315 if (!EvaluateInteger(E->getArg(0), Val, Info))
17316 return false;
17317 APSInt Result = ~Val;
17318 return Success(APValue(Result), E);
17319 }
17320
17321 case X86::BI__builtin_ia32_kaddqi:
17322 case X86::BI__builtin_ia32_kaddhi:
17323 case X86::BI__builtin_ia32_kaddsi:
17324 case X86::BI__builtin_ia32_kadddi: {
17325 return HandleMaskBinOp(
17326 [](const APSInt &LHS, const APSInt &RHS) { return LHS + RHS; });
17327 }
17328
17329 case X86::BI__builtin_ia32_kmovb:
17330 case X86::BI__builtin_ia32_kmovw:
17331 case X86::BI__builtin_ia32_kmovd:
17332 case X86::BI__builtin_ia32_kmovq: {
17333 APSInt Val;
17334 if (!EvaluateInteger(E->getArg(0), Val, Info))
17335 return false;
17336 return Success(Val, E);
17337 }
17338
17339 case X86::BI__builtin_ia32_kshiftliqi:
17340 case X86::BI__builtin_ia32_kshiftlihi:
17341 case X86::BI__builtin_ia32_kshiftlisi:
17342 case X86::BI__builtin_ia32_kshiftlidi: {
17343 return HandleMaskBinOp([](const APSInt &LHS, const APSInt &RHS) {
17344 unsigned Amt = RHS.getZExtValue() & 0xFF;
17345 if (Amt >= LHS.getBitWidth())
17346 return APSInt(APInt::getZero(LHS.getBitWidth()), LHS.isUnsigned());
17347 return APSInt(LHS.shl(Amt), LHS.isUnsigned());
17348 });
17349 }
17350
17351 case X86::BI__builtin_ia32_kshiftriqi:
17352 case X86::BI__builtin_ia32_kshiftrihi:
17353 case X86::BI__builtin_ia32_kshiftrisi:
17354 case X86::BI__builtin_ia32_kshiftridi: {
17355 return HandleMaskBinOp([](const APSInt &LHS, const APSInt &RHS) {
17356 unsigned Amt = RHS.getZExtValue() & 0xFF;
17357 if (Amt >= LHS.getBitWidth())
17358 return APSInt(APInt::getZero(LHS.getBitWidth()), LHS.isUnsigned());
17359 return APSInt(LHS.lshr(Amt), LHS.isUnsigned());
17360 });
17361 }
17362
17363 case clang::X86::BI__builtin_ia32_vec_ext_v4hi:
17364 case clang::X86::BI__builtin_ia32_vec_ext_v16qi:
17365 case clang::X86::BI__builtin_ia32_vec_ext_v8hi:
17366 case clang::X86::BI__builtin_ia32_vec_ext_v4si:
17367 case clang::X86::BI__builtin_ia32_vec_ext_v2di:
17368 case clang::X86::BI__builtin_ia32_vec_ext_v32qi:
17369 case clang::X86::BI__builtin_ia32_vec_ext_v16hi:
17370 case clang::X86::BI__builtin_ia32_vec_ext_v8si:
17371 case clang::X86::BI__builtin_ia32_vec_ext_v4di: {
17372 APValue Vec;
17373 APSInt IdxAPS;
17374 if (!EvaluateVector(E->getArg(0), Vec, Info) ||
17375 !EvaluateInteger(E->getArg(1), IdxAPS, Info))
17376 return false;
17377 unsigned N = Vec.getVectorLength();
17378 unsigned Idx = static_cast<unsigned>(IdxAPS.getZExtValue() & (N - 1));
17379 return Success(Vec.getVectorElt(Idx).getInt(), E);
17380 }
17381
17382 case clang::X86::BI__builtin_ia32_cvtb2mask128:
17383 case clang::X86::BI__builtin_ia32_cvtb2mask256:
17384 case clang::X86::BI__builtin_ia32_cvtb2mask512:
17385 case clang::X86::BI__builtin_ia32_cvtw2mask128:
17386 case clang::X86::BI__builtin_ia32_cvtw2mask256:
17387 case clang::X86::BI__builtin_ia32_cvtw2mask512:
17388 case clang::X86::BI__builtin_ia32_cvtd2mask128:
17389 case clang::X86::BI__builtin_ia32_cvtd2mask256:
17390 case clang::X86::BI__builtin_ia32_cvtd2mask512:
17391 case clang::X86::BI__builtin_ia32_cvtq2mask128:
17392 case clang::X86::BI__builtin_ia32_cvtq2mask256:
17393 case clang::X86::BI__builtin_ia32_cvtq2mask512: {
17394 assert(E->getNumArgs() == 1);
17395 APValue Vec;
17396 if (!EvaluateVector(E->getArg(0), Vec, Info))
17397 return false;
17398
17399 unsigned VectorLen = Vec.getVectorLength();
17400 unsigned RetWidth = Info.Ctx.getIntWidth(E->getType());
17401 llvm::APInt Bits(RetWidth, 0);
17402
17403 for (unsigned ElemNum = 0; ElemNum != VectorLen; ++ElemNum) {
17404 const APSInt &A = Vec.getVectorElt(ElemNum).getInt();
17405 unsigned MSB = A[A.getBitWidth() - 1];
17406 Bits.setBitVal(ElemNum, MSB);
17407 }
17408
17409 APSInt RetMask(Bits, /*isUnsigned=*/true);
17410 return Success(APValue(RetMask), E);
17411 }
17412
17413 case clang::X86::BI__builtin_ia32_cmpb128_mask:
17414 case clang::X86::BI__builtin_ia32_cmpw128_mask:
17415 case clang::X86::BI__builtin_ia32_cmpd128_mask:
17416 case clang::X86::BI__builtin_ia32_cmpq128_mask:
17417 case clang::X86::BI__builtin_ia32_cmpb256_mask:
17418 case clang::X86::BI__builtin_ia32_cmpw256_mask:
17419 case clang::X86::BI__builtin_ia32_cmpd256_mask:
17420 case clang::X86::BI__builtin_ia32_cmpq256_mask:
17421 case clang::X86::BI__builtin_ia32_cmpb512_mask:
17422 case clang::X86::BI__builtin_ia32_cmpw512_mask:
17423 case clang::X86::BI__builtin_ia32_cmpd512_mask:
17424 case clang::X86::BI__builtin_ia32_cmpq512_mask:
17425 case clang::X86::BI__builtin_ia32_ucmpb128_mask:
17426 case clang::X86::BI__builtin_ia32_ucmpw128_mask:
17427 case clang::X86::BI__builtin_ia32_ucmpd128_mask:
17428 case clang::X86::BI__builtin_ia32_ucmpq128_mask:
17429 case clang::X86::BI__builtin_ia32_ucmpb256_mask:
17430 case clang::X86::BI__builtin_ia32_ucmpw256_mask:
17431 case clang::X86::BI__builtin_ia32_ucmpd256_mask:
17432 case clang::X86::BI__builtin_ia32_ucmpq256_mask:
17433 case clang::X86::BI__builtin_ia32_ucmpb512_mask:
17434 case clang::X86::BI__builtin_ia32_ucmpw512_mask:
17435 case clang::X86::BI__builtin_ia32_ucmpd512_mask:
17436 case clang::X86::BI__builtin_ia32_ucmpq512_mask: {
17437 assert(E->getNumArgs() == 4);
17438
17439 bool IsUnsigned =
17440 (BuiltinOp >= clang::X86::BI__builtin_ia32_ucmpb128_mask &&
17441 BuiltinOp <= clang::X86::BI__builtin_ia32_ucmpw512_mask);
17442
17443 APValue LHS, RHS;
17444 APSInt Mask, Opcode;
17445 if (!EvaluateVector(E->getArg(0), LHS, Info) ||
17446 !EvaluateVector(E->getArg(1), RHS, Info) ||
17447 !EvaluateInteger(E->getArg(2), Opcode, Info) ||
17448 !EvaluateInteger(E->getArg(3), Mask, Info))
17449 return false;
17450
17451 assert(LHS.getVectorLength() == RHS.getVectorLength());
17452
17453 unsigned VectorLen = LHS.getVectorLength();
17454 unsigned RetWidth = Mask.getBitWidth();
17455
17456 APSInt RetMask(llvm::APInt(RetWidth, 0), /*isUnsigned=*/true);
17457
17458 for (unsigned ElemNum = 0; ElemNum < VectorLen; ++ElemNum) {
17459 const APSInt &A = LHS.getVectorElt(ElemNum).getInt();
17460 const APSInt &B = RHS.getVectorElt(ElemNum).getInt();
17461 bool Result = false;
17462
17463 switch (Opcode.getExtValue() & 0x7) {
17464 case 0: // _MM_CMPINT_EQ
17465 Result = (A == B);
17466 break;
17467 case 1: // _MM_CMPINT_LT
17468 Result = IsUnsigned ? A.ult(B) : A.slt(B);
17469 break;
17470 case 2: // _MM_CMPINT_LE
17471 Result = IsUnsigned ? A.ule(B) : A.sle(B);
17472 break;
17473 case 3: // _MM_CMPINT_FALSE
17474 Result = false;
17475 break;
17476 case 4: // _MM_CMPINT_NE
17477 Result = (A != B);
17478 break;
17479 case 5: // _MM_CMPINT_NLT (>=)
17480 Result = IsUnsigned ? A.uge(B) : A.sge(B);
17481 break;
17482 case 6: // _MM_CMPINT_NLE (>)
17483 Result = IsUnsigned ? A.ugt(B) : A.sgt(B);
17484 break;
17485 case 7: // _MM_CMPINT_TRUE
17486 Result = true;
17487 break;
17488 }
17489
17490 RetMask.setBitVal(ElemNum, Mask[ElemNum] && Result);
17491 }
17492
17493 return Success(APValue(RetMask), E);
17494 }
17495 case X86::BI__builtin_ia32_vpshufbitqmb128_mask:
17496 case X86::BI__builtin_ia32_vpshufbitqmb256_mask:
17497 case X86::BI__builtin_ia32_vpshufbitqmb512_mask: {
17498 assert(E->getNumArgs() == 3);
17499
17500 APValue Source, ShuffleMask;
17501 APSInt ZeroMask;
17502 if (!EvaluateVector(E->getArg(0), Source, Info) ||
17503 !EvaluateVector(E->getArg(1), ShuffleMask, Info) ||
17504 !EvaluateInteger(E->getArg(2), ZeroMask, Info))
17505 return false;
17506
17507 assert(Source.getVectorLength() == ShuffleMask.getVectorLength());
17508 assert(ZeroMask.getBitWidth() == Source.getVectorLength());
17509
17510 unsigned NumBytesInQWord = 8;
17511 unsigned NumBitsInByte = 8;
17512 unsigned NumBytes = Source.getVectorLength();
17513 unsigned NumQWords = NumBytes / NumBytesInQWord;
17514 unsigned RetWidth = ZeroMask.getBitWidth();
17515 APSInt RetMask(llvm::APInt(RetWidth, 0), /*isUnsigned=*/true);
17516
17517 for (unsigned QWordId = 0; QWordId != NumQWords; ++QWordId) {
17518 APInt SourceQWord(64, 0);
17519 for (unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
17520 uint64_t Byte = Source.getVectorElt(QWordId * NumBytesInQWord + ByteIdx)
17521 .getInt()
17522 .getZExtValue();
17523 SourceQWord.insertBits(APInt(8, Byte & 0xFF), ByteIdx * NumBitsInByte);
17524 }
17525
17526 for (unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
17527 unsigned SelIdx = QWordId * NumBytesInQWord + ByteIdx;
17528 unsigned M =
17529 ShuffleMask.getVectorElt(SelIdx).getInt().getZExtValue() & 0x3F;
17530 if (ZeroMask[SelIdx]) {
17531 RetMask.setBitVal(SelIdx, SourceQWord[M]);
17532 }
17533 }
17534 }
17535 return Success(APValue(RetMask), E);
17536 }
17537 }
17538 }
17539
17540 /// Determine whether this is a pointer past the end of the complete
17541 /// object referred to by the lvalue.
17542 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
17543 const LValue &LV) {
17544 // A null pointer can be viewed as being "past the end" but we don't
17545 // choose to look at it that way here.
17546 if (!LV.getLValueBase())
17547 return false;
17548
17549 // If the designator is valid and refers to a subobject, we're not pointing
17550 // past the end.
17551 if (!LV.getLValueDesignator().Invalid &&
17552 !LV.getLValueDesignator().isOnePastTheEnd())
17553 return false;
17554
17555 // A pointer to an incomplete type might be past-the-end if the type's size is
17556 // zero. We cannot tell because the type is incomplete.
17557 QualType Ty = getType(LV.getLValueBase());
17558 if (Ty->isIncompleteType())
17559 return true;
17560
17561 // Can't be past the end of an invalid object.
17562 if (LV.getLValueDesignator().Invalid)
17563 return false;
17564
17565 // We're a past-the-end pointer if we point to the byte after the object,
17566 // no matter what our type or path is.
17567 auto Size = Ctx.getTypeSizeInChars(Ty);
17568 return LV.getLValueOffset() == Size;
17569 }
17570
17571 namespace {
17572
17573 /// Data recursive integer evaluator of certain binary operators.
17574 ///
17575 /// We use a data recursive algorithm for binary operators so that we are able
17576 /// to handle extreme cases of chained binary operators without causing stack
17577 /// overflow.
17578 class DataRecursiveIntBinOpEvaluator {
17579 struct EvalResult {
17580 APValue Val;
17581 bool Failed = false;
17582
17583 EvalResult() = default;
17584
17585 void swap(EvalResult &RHS) {
17586 Val.swap(RHS.Val);
17587 Failed = RHS.Failed;
17588 RHS.Failed = false;
17589 }
17590 };
17591
17592 struct Job {
17593 const Expr *E;
17594 EvalResult LHSResult; // meaningful only for binary operator expression.
17595 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
17596
17597 Job() = default;
17598 Job(Job &&) = default;
17599
17600 void startSpeculativeEval(EvalInfo &Info) {
17601 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
17602 }
17603
17604 private:
17605 SpeculativeEvaluationRAII SpecEvalRAII;
17606 };
17607
17608 SmallVector<Job, 16> Queue;
17609
17610 IntExprEvaluator &IntEval;
17611 EvalInfo &Info;
17612 APValue &FinalResult;
17613
17614 public:
17615 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
17616 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
17617
17618 /// True if \param E is a binary operator that we are going to handle
17619 /// data recursively.
17620 /// We handle binary operators that are comma, logical, or that have operands
17621 /// with integral or enumeration type.
17622 static bool shouldEnqueue(const BinaryOperator *E) {
17623 return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
17624 (E->isPRValue() && E->getType()->isIntegralOrEnumerationType() &&
17625 E->getLHS()->getType()->isIntegralOrEnumerationType() &&
17626 E->getRHS()->getType()->isIntegralOrEnumerationType());
17627 }
17628
17629 bool Traverse(const BinaryOperator *E) {
17630 enqueue(E);
17631 EvalResult PrevResult;
17632 while (!Queue.empty())
17633 process(PrevResult);
17634
17635 if (PrevResult.Failed) return false;
17636
17637 FinalResult.swap(PrevResult.Val);
17638 return true;
17639 }
17640
17641 private:
17642 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
17643 return IntEval.Success(Value, E, Result);
17644 }
17645 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
17646 return IntEval.Success(Value, E, Result);
17647 }
17648 bool Error(const Expr *E) {
17649 return IntEval.Error(E);
17650 }
17651 bool Error(const Expr *E, diag::kind D) {
17652 return IntEval.Error(E, D);
17653 }
17654
17655 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
17656 return Info.CCEDiag(E, D);
17657 }
17658
17659 // Returns true if visiting the RHS is necessary, false otherwise.
17660 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
17661 bool &SuppressRHSDiags);
17662
17663 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
17664 const BinaryOperator *E, APValue &Result);
17665
17666 void EvaluateExpr(const Expr *E, EvalResult &Result) {
17667 Result.Failed = !Evaluate(Result.Val, Info, E);
17668 if (Result.Failed)
17669 Result.Val = APValue();
17670 }
17671
17672 void process(EvalResult &Result);
17673
17674 void enqueue(const Expr *E) {
17675 E = E->IgnoreParens();
17676 Queue.resize(Queue.size()+1);
17677 Queue.back().E = E;
17678 Queue.back().Kind = Job::AnyExprKind;
17679 }
17680 };
17681
17682 }
17683
17684 bool DataRecursiveIntBinOpEvaluator::
17685 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
17686 bool &SuppressRHSDiags) {
17687 if (E->getOpcode() == BO_Comma) {
17688 // Ignore LHS but note if we could not evaluate it.
17689 if (LHSResult.Failed)
17690 return Info.noteSideEffect();
17691 return true;
17692 }
17693
17694 if (E->isLogicalOp()) {
17695 bool LHSAsBool;
17696 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
17697 // We were able to evaluate the LHS, see if we can get away with not
17698 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
17699 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
17700 Success(LHSAsBool, E, LHSResult.Val);
17701 return false; // Ignore RHS
17702 }
17703 } else {
17704 LHSResult.Failed = true;
17705
17706 // Since we weren't able to evaluate the left hand side, it
17707 // might have had side effects.
17708 if (!Info.noteSideEffect())
17709 return false;
17710
17711 // We can't evaluate the LHS; however, sometimes the result
17712 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
17713 // Don't ignore RHS and suppress diagnostics from this arm.
17714 SuppressRHSDiags = true;
17715 }
17716
17717 return true;
17718 }
17719
17720 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
17721 E->getRHS()->getType()->isIntegralOrEnumerationType());
17722
17723 if (LHSResult.Failed && !Info.noteFailure())
17724 return false; // Ignore RHS;
17725
17726 return true;
17727 }
17728
17729 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
17730 bool IsSub) {
17731 // Compute the new offset in the appropriate width, wrapping at 64 bits.
17732 // FIXME: When compiling for a 32-bit target, we should use 32-bit
17733 // offsets.
17734 assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
17735 CharUnits &Offset = LVal.getLValueOffset();
17736 uint64_t Offset64 = Offset.getQuantity();
17737 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
17738 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
17739 : Offset64 + Index64);
17740 }
17741
17742 bool DataRecursiveIntBinOpEvaluator::
17743 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
17744 const BinaryOperator *E, APValue &Result) {
17745 if (E->getOpcode() == BO_Comma) {
17746 if (RHSResult.Failed)
17747 return false;
17748 Result = RHSResult.Val;
17749 return true;
17750 }
17751
17752 if (E->isLogicalOp()) {
17753 bool lhsResult, rhsResult;
17754 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
17755 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
17756
17757 if (LHSIsOK) {
17758 if (RHSIsOK) {
17759 if (E->getOpcode() == BO_LOr)
17760 return Success(lhsResult || rhsResult, E, Result);
17761 else
17762 return Success(lhsResult && rhsResult, E, Result);
17763 }
17764 } else {
17765 if (RHSIsOK) {
17766 // We can't evaluate the LHS; however, sometimes the result
17767 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
17768 if (rhsResult == (E->getOpcode() == BO_LOr))
17769 return Success(rhsResult, E, Result);
17770 }
17771 }
17772
17773 return false;
17774 }
17775
17776 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
17777 E->getRHS()->getType()->isIntegralOrEnumerationType());
17778
17779 if (LHSResult.Failed || RHSResult.Failed)
17780 return false;
17781
17782 const APValue &LHSVal = LHSResult.Val;
17783 const APValue &RHSVal = RHSResult.Val;
17784
17785 // Handle cases like (unsigned long)&a + 4.
17786 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
17787 Result = LHSVal;
17788 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
17789 return true;
17790 }
17791
17792 // Handle cases like 4 + (unsigned long)&a
17793 if (E->getOpcode() == BO_Add &&
17794 RHSVal.isLValue() && LHSVal.isInt()) {
17795 Result = RHSVal;
17796 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
17797 return true;
17798 }
17799
17800 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
17801 // Handle (intptr_t)&&A - (intptr_t)&&B.
17802 if (!LHSVal.getLValueOffset().isZero() ||
17803 !RHSVal.getLValueOffset().isZero())
17804 return false;
17805 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
17806 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
17807 if (!LHSExpr || !RHSExpr)
17808 return false;
17809 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
17810 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
17811 if (!LHSAddrExpr || !RHSAddrExpr)
17812 return false;
17813 // Make sure both labels come from the same function.
17814 if (LHSAddrExpr->getLabel()->getDeclContext() !=
17815 RHSAddrExpr->getLabel()->getDeclContext())
17816 return false;
17817 Result = APValue(LHSAddrExpr, RHSAddrExpr);
17818 return true;
17819 }
17820
17821 // All the remaining cases expect both operands to be an integer
17822 if (!LHSVal.isInt() || !RHSVal.isInt())
17823 return Error(E);
17824
17825 // Set up the width and signedness manually, in case it can't be deduced
17826 // from the operation we're performing.
17827 // FIXME: Don't do this in the cases where we can deduce it.
17828 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
17829 E->getType()->isUnsignedIntegerOrEnumerationType());
17830 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
17831 RHSVal.getInt(), Value))
17832 return false;
17833 return Success(Value, E, Result);
17834 }
17835
17836 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
17837 Job &job = Queue.back();
17838
17839 switch (job.Kind) {
17840 case Job::AnyExprKind: {
17841 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
17842 if (shouldEnqueue(Bop)) {
17843 job.Kind = Job::BinOpKind;
17844 enqueue(Bop->getLHS());
17845 return;
17846 }
17847 }
17848
17849 EvaluateExpr(job.E, Result);
17850 Queue.pop_back();
17851 return;
17852 }
17853
17854 case Job::BinOpKind: {
17855 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
17856 bool SuppressRHSDiags = false;
17857 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
17858 Queue.pop_back();
17859 return;
17860 }
17861 if (SuppressRHSDiags)
17862 job.startSpeculativeEval(Info);
17863 job.LHSResult.swap(Result);
17864 job.Kind = Job::BinOpVisitedLHSKind;
17865 enqueue(Bop->getRHS());
17866 return;
17867 }
17868
17869 case Job::BinOpVisitedLHSKind: {
17870 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
17871 EvalResult RHS;
17872 RHS.swap(Result);
17873 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
17874 Queue.pop_back();
17875 return;
17876 }
17877 }
17878
17879 llvm_unreachable("Invalid Job::Kind!");
17880 }
17881
17882 namespace {
17883 enum class CmpResult {
17884 Unequal,
17885 Less,
17886 Equal,
17887 Greater,
17888 Unordered,
17889 };
17890 }
17891
17892 template <class SuccessCB, class AfterCB>
17893 static bool
17894 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
17895 SuccessCB &&Success, AfterCB &&DoAfter) {
17896 assert(!E->isValueDependent());
17897 assert(E->isComparisonOp() && "expected comparison operator");
17898 assert((E->getOpcode() == BO_Cmp ||
17899 E->getType()->isIntegralOrEnumerationType()) &&
17900 "unsupported binary expression evaluation");
17901 auto Error = [&](const Expr *E) {
17902 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
17903 return false;
17904 };
17905
17906 bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp;
17907 bool IsEquality = E->isEqualityOp();
17908
17909 QualType LHSTy = E->getLHS()->getType();
17910 QualType RHSTy = E->getRHS()->getType();
17911
17912 if (LHSTy->isIntegralOrEnumerationType() &&
17913 RHSTy->isIntegralOrEnumerationType()) {
17914 APSInt LHS, RHS;
17915 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
17916 if (!LHSOK && !Info.noteFailure())
17917 return false;
17918 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
17919 return false;
17920 if (LHS < RHS)
17921 return Success(CmpResult::Less, E);
17922 if (LHS > RHS)
17923 return Success(CmpResult::Greater, E);
17924 return Success(CmpResult::Equal, E);
17925 }
17926
17927 if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
17928 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
17929 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
17930
17931 bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
17932 if (!LHSOK && !Info.noteFailure())
17933 return false;
17934 if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
17935 return false;
17936 if (LHSFX < RHSFX)
17937 return Success(CmpResult::Less, E);
17938 if (LHSFX > RHSFX)
17939 return Success(CmpResult::Greater, E);
17940 return Success(CmpResult::Equal, E);
17941 }
17942
17943 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
17944 ComplexValue LHS, RHS;
17945 bool LHSOK;
17946 if (E->isAssignmentOp()) {
17947 LValue LV;
17948 EvaluateLValue(E->getLHS(), LV, Info);
17949 LHSOK = false;
17950 } else if (LHSTy->isRealFloatingType()) {
17951 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
17952 if (LHSOK) {
17953 LHS.makeComplexFloat();
17954 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
17955 }
17956 } else {
17957 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
17958 }
17959 if (!LHSOK && !Info.noteFailure())
17960 return false;
17961
17962 if (E->getRHS()->getType()->isRealFloatingType()) {
17963 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
17964 return false;
17965 RHS.makeComplexFloat();
17966 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
17967 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
17968 return false;
17969
17970 if (LHS.isComplexFloat()) {
17971 APFloat::cmpResult CR_r =
17972 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
17973 APFloat::cmpResult CR_i =
17974 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
17975 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
17976 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
17977 } else {
17978 assert(IsEquality && "invalid complex comparison");
17979 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
17980 LHS.getComplexIntImag() == RHS.getComplexIntImag();
17981 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
17982 }
17983 }
17984
17985 if (LHSTy->isRealFloatingType() &&
17986 RHSTy->isRealFloatingType()) {
17987 APFloat RHS(0.0), LHS(0.0);
17988
17989 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
17990 if (!LHSOK && !Info.noteFailure())
17991 return false;
17992
17993 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
17994 return false;
17995
17996 assert(E->isComparisonOp() && "Invalid binary operator!");
17997 llvm::APFloatBase::cmpResult APFloatCmpResult = LHS.compare(RHS);
17998 if (!Info.InConstantContext &&
17999 APFloatCmpResult == APFloat::cmpUnordered &&
18000 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained()) {
18001 // Note: Compares may raise invalid in some cases involving NaN or sNaN.
18002 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
18003 return false;
18004 }
18005 auto GetCmpRes = [&]() {
18006 switch (APFloatCmpResult) {
18007 case APFloat::cmpEqual:
18008 return CmpResult::Equal;
18009 case APFloat::cmpLessThan:
18010 return CmpResult::Less;
18011 case APFloat::cmpGreaterThan:
18012 return CmpResult::Greater;
18013 case APFloat::cmpUnordered:
18014 return CmpResult::Unordered;
18015 }
18016 llvm_unreachable("Unrecognised APFloat::cmpResult enum");
18017 };
18018 return Success(GetCmpRes(), E);
18019 }
18020
18021 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
18022 LValue LHSValue, RHSValue;
18023
18024 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
18025 if (!LHSOK && !Info.noteFailure())
18026 return false;
18027
18028 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
18029 return false;
18030
18031 // Reject differing bases from the normal codepath; we special-case
18032 // comparisons to null.
18033 if (!HasSameBase(LHSValue, RHSValue)) {
18034 // Bail out early if we're checking potential constant expression.
18035 // Otherwise, prefer to diagnose other issues.
18036 if (Info.checkingPotentialConstantExpression() &&
18037 (LHSValue.AllowConstexprUnknown || RHSValue.AllowConstexprUnknown))
18038 return false;
18039 auto DiagComparison = [&] (unsigned DiagID, bool Reversed = false) {
18040 std::string LHS = LHSValue.toString(Info.Ctx, E->getLHS()->getType());
18041 std::string RHS = RHSValue.toString(Info.Ctx, E->getRHS()->getType());
18042 Info.FFDiag(E, DiagID)
18043 << (Reversed ? RHS : LHS) << (Reversed ? LHS : RHS);
18044 return false;
18045 };
18046 // Inequalities and subtractions between unrelated pointers have
18047 // unspecified or undefined behavior.
18048 if (!IsEquality)
18049 return DiagComparison(
18050 diag::note_constexpr_pointer_comparison_unspecified);
18051 // A constant address may compare equal to the address of a symbol.
18052 // The one exception is that address of an object cannot compare equal
18053 // to a null pointer constant.
18054 // TODO: Should we restrict this to actual null pointers, and exclude the
18055 // case of zero cast to pointer type?
18056 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
18057 (!RHSValue.Base && !RHSValue.Offset.isZero()))
18058 return DiagComparison(diag::note_constexpr_pointer_constant_comparison,
18059 !RHSValue.Base);
18060 // C++2c [intro.object]/10:
18061 // Two objects [...] may have the same address if [...] they are both
18062 // potentially non-unique objects.
18063 // C++2c [intro.object]/9:
18064 // An object is potentially non-unique if it is a string literal object,
18065 // the backing array of an initializer list, or a subobject thereof.
18066 //
18067 // This makes the comparison result unspecified, so it's not a constant
18068 // expression.
18069 //
18070 // TODO: Do we need to handle the initializer list case here?
18071 if (ArePotentiallyOverlappingStringLiterals(Info, LHSValue, RHSValue))
18072 return DiagComparison(diag::note_constexpr_literal_comparison);
18073 if (IsOpaqueConstantCall(LHSValue) || IsOpaqueConstantCall(RHSValue))
18074 return DiagComparison(diag::note_constexpr_opaque_call_comparison,
18075 !IsOpaqueConstantCall(LHSValue));
18076 // We can't tell whether weak symbols will end up pointing to the same
18077 // object.
18078 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
18079 return DiagComparison(diag::note_constexpr_pointer_weak_comparison,
18080 !IsWeakLValue(LHSValue));
18081 // We can't compare the address of the start of one object with the
18082 // past-the-end address of another object, per C++ DR1652.
18083 if (LHSValue.Base && LHSValue.Offset.isZero() &&
18084 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue))
18085 return DiagComparison(diag::note_constexpr_pointer_comparison_past_end,
18086 true);
18087 if (RHSValue.Base && RHSValue.Offset.isZero() &&
18088 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue))
18089 return DiagComparison(diag::note_constexpr_pointer_comparison_past_end,
18090 false);
18091 // We can't tell whether an object is at the same address as another
18092 // zero sized object.
18093 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
18094 (LHSValue.Base && isZeroSized(RHSValue)))
18095 return DiagComparison(
18096 diag::note_constexpr_pointer_comparison_zero_sized);
18097 if (LHSValue.AllowConstexprUnknown || RHSValue.AllowConstexprUnknown)
18098 return DiagComparison(
18099 diag::note_constexpr_pointer_comparison_unspecified);
18100 // FIXME: Verify both variables are live.
18101 return Success(CmpResult::Unequal, E);
18102 }
18103
18104 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
18105 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
18106
18107 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
18108 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
18109
18110 // C++11 [expr.rel]p2:
18111 // - If two pointers point to non-static data members of the same object,
18112 // or to subobjects or array elements fo such members, recursively, the
18113 // pointer to the later declared member compares greater provided the
18114 // two members have the same access control and provided their class is
18115 // not a union.
18116 // [...]
18117 // - Otherwise pointer comparisons are unspecified.
18118 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
18119 bool WasArrayIndex;
18120 unsigned Mismatch = FindDesignatorMismatch(
18121 LHSValue.Base.isNull() ? QualType()
18122 : getType(LHSValue.Base).getNonReferenceType(),
18123 LHSDesignator, RHSDesignator, WasArrayIndex);
18124 // At the point where the designators diverge, the comparison has a
18125 // specified value if:
18126 // - we are comparing array indices
18127 // - we are comparing fields of a union, or fields with the same access
18128 // Otherwise, the result is unspecified and thus the comparison is not a
18129 // constant expression.
18130 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
18131 Mismatch < RHSDesignator.Entries.size()) {
18132 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
18133 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
18134 if (!LF && !RF)
18135 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
18136 else if (!LF)
18137 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
18138 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
18139 << RF->getParent() << RF;
18140 else if (!RF)
18141 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
18142 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
18143 << LF->getParent() << LF;
18144 else if (!LF->getParent()->isUnion() &&
18145 LF->getAccess() != RF->getAccess())
18146 Info.CCEDiag(E,
18147 diag::note_constexpr_pointer_comparison_differing_access)
18148 << LF << LF->getAccess() << RF << RF->getAccess()
18149 << LF->getParent();
18150 }
18151 }
18152
18153 // The comparison here must be unsigned, and performed with the same
18154 // width as the pointer.
18155 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
18156 uint64_t CompareLHS = LHSOffset.getQuantity();
18157 uint64_t CompareRHS = RHSOffset.getQuantity();
18158 assert(PtrSize <= 64 && "Unexpected pointer width");
18159 uint64_t Mask = ~0ULL >> (64 - PtrSize);
18160 CompareLHS &= Mask;
18161 CompareRHS &= Mask;
18162
18163 // If there is a base and this is a relational operator, we can only
18164 // compare pointers within the object in question; otherwise, the result
18165 // depends on where the object is located in memory.
18166 if (!LHSValue.Base.isNull() && IsRelational) {
18167 QualType BaseTy = getType(LHSValue.Base).getNonReferenceType();
18168 if (BaseTy->isIncompleteType())
18169 return Error(E);
18170 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
18171 uint64_t OffsetLimit = Size.getQuantity();
18172 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
18173 return Error(E);
18174 }
18175
18176 if (CompareLHS < CompareRHS)
18177 return Success(CmpResult::Less, E);
18178 if (CompareLHS > CompareRHS)
18179 return Success(CmpResult::Greater, E);
18180 return Success(CmpResult::Equal, E);
18181 }
18182
18183 if (LHSTy->isMemberPointerType()) {
18184 assert(IsEquality && "unexpected member pointer operation");
18185 assert(RHSTy->isMemberPointerType() && "invalid comparison");
18186
18187 MemberPtr LHSValue, RHSValue;
18188
18189 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
18190 if (!LHSOK && !Info.noteFailure())
18191 return false;
18192
18193 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
18194 return false;
18195
18196 // If either operand is a pointer to a weak function, the comparison is not
18197 // constant.
18198 if (LHSValue.getDecl() && LHSValue.getDecl()->isWeak()) {
18199 Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison)
18200 << LHSValue.getDecl();
18201 return false;
18202 }
18203 if (RHSValue.getDecl() && RHSValue.getDecl()->isWeak()) {
18204 Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison)
18205 << RHSValue.getDecl();
18206 return false;
18207 }
18208
18209 // C++11 [expr.eq]p2:
18210 // If both operands are null, they compare equal. Otherwise if only one is
18211 // null, they compare unequal.
18212 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
18213 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
18214 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
18215 }
18216
18217 // Otherwise if either is a pointer to a virtual member function, the
18218 // result is unspecified.
18219 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
18220 if (MD->isVirtual())
18221 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
18222 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
18223 if (MD->isVirtual())
18224 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
18225
18226 // Otherwise they compare equal if and only if they would refer to the
18227 // same member of the same most derived object or the same subobject if
18228 // they were dereferenced with a hypothetical object of the associated
18229 // class type.
18230 bool Equal = LHSValue == RHSValue;
18231 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
18232 }
18233
18234 if (LHSTy->isNullPtrType()) {
18235 assert(E->isComparisonOp() && "unexpected nullptr operation");
18236 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
18237 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
18238 // are compared, the result is true of the operator is <=, >= or ==, and
18239 // false otherwise.
18240 LValue Res;
18241 if (!EvaluatePointer(E->getLHS(), Res, Info) ||
18242 !EvaluatePointer(E->getRHS(), Res, Info))
18243 return false;
18244 return Success(CmpResult::Equal, E);
18245 }
18246
18247 return DoAfter();
18248 }
18249
18250 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
18251 if (!CheckLiteralType(Info, E))
18252 return false;
18253
18254 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
18255 ComparisonCategoryResult CCR;
18256 switch (CR) {
18257 case CmpResult::Unequal:
18258 llvm_unreachable("should never produce Unequal for three-way comparison");
18259 case CmpResult::Less:
18260 CCR = ComparisonCategoryResult::Less;
18261 break;
18262 case CmpResult::Equal:
18263 CCR = ComparisonCategoryResult::Equal;
18264 break;
18265 case CmpResult::Greater:
18266 CCR = ComparisonCategoryResult::Greater;
18267 break;
18268 case CmpResult::Unordered:
18269 CCR = ComparisonCategoryResult::Unordered;
18270 break;
18271 }
18272 // Evaluation succeeded. Lookup the information for the comparison category
18273 // type and fetch the VarDecl for the result.
18274 const ComparisonCategoryInfo &CmpInfo =
18275 Info.Ctx.CompCategories.getInfoForType(E->getType());
18276 const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD;
18277 // Check and evaluate the result as a constant expression.
18278 LValue LV;
18279 LV.set(VD);
18280 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
18281 return false;
18282 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
18283 ConstantExprKind::Normal);
18284 };
18285 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
18286 return ExprEvaluatorBaseTy::VisitBinCmp(E);
18287 });
18288 }
18289
18290 bool RecordExprEvaluator::VisitCXXParenListInitExpr(
18291 const CXXParenListInitExpr *E) {
18292 return VisitCXXParenListOrInitListExpr(E, E->getInitExprs());
18293 }
18294
18295 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
18296 // We don't support assignment in C. C++ assignments don't get here because
18297 // assignment is an lvalue in C++.
18298 if (E->isAssignmentOp()) {
18299 Error(E);
18300 if (!Info.noteFailure())
18301 return false;
18302 }
18303
18304 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
18305 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
18306
18307 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
18308 !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
18309 "DataRecursiveIntBinOpEvaluator should have handled integral types");
18310
18311 if (E->isComparisonOp()) {
18312 // Evaluate builtin binary comparisons by evaluating them as three-way
18313 // comparisons and then translating the result.
18314 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
18315 assert((CR != CmpResult::Unequal || E->isEqualityOp()) &&
18316 "should only produce Unequal for equality comparisons");
18317 bool IsEqual = CR == CmpResult::Equal,
18318 IsLess = CR == CmpResult::Less,
18319 IsGreater = CR == CmpResult::Greater;
18320 auto Op = E->getOpcode();
18321 switch (Op) {
18322 default:
18323 llvm_unreachable("unsupported binary operator");
18324 case BO_EQ:
18325 case BO_NE:
18326 return Success(IsEqual == (Op == BO_EQ), E);
18327 case BO_LT:
18328 return Success(IsLess, E);
18329 case BO_GT:
18330 return Success(IsGreater, E);
18331 case BO_LE:
18332 return Success(IsEqual || IsLess, E);
18333 case BO_GE:
18334 return Success(IsEqual || IsGreater, E);
18335 }
18336 };
18337 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
18338 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
18339 });
18340 }
18341
18342 QualType LHSTy = E->getLHS()->getType();
18343 QualType RHSTy = E->getRHS()->getType();
18344
18345 if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
18346 E->getOpcode() == BO_Sub) {
18347 LValue LHSValue, RHSValue;
18348
18349 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
18350 if (!LHSOK && !Info.noteFailure())
18351 return false;
18352
18353 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
18354 return false;
18355
18356 // Reject differing bases from the normal codepath; we special-case
18357 // comparisons to null.
18358 if (!HasSameBase(LHSValue, RHSValue)) {
18359 if (Info.checkingPotentialConstantExpression() &&
18360 (LHSValue.AllowConstexprUnknown || RHSValue.AllowConstexprUnknown))
18361 return false;
18362
18363 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
18364 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
18365
18366 auto DiagArith = [&](unsigned DiagID) {
18367 std::string LHS = LHSValue.toString(Info.Ctx, E->getLHS()->getType());
18368 std::string RHS = RHSValue.toString(Info.Ctx, E->getRHS()->getType());
18369 Info.FFDiag(E, DiagID) << LHS << RHS;
18370 if (LHSExpr && LHSExpr == RHSExpr)
18371 Info.Note(LHSExpr->getExprLoc(),
18372 diag::note_constexpr_repeated_literal_eval)
18373 << LHSExpr->getSourceRange();
18374 return false;
18375 };
18376
18377 if (!LHSExpr || !RHSExpr)
18378 return DiagArith(diag::note_constexpr_pointer_arith_unspecified);
18379
18380 if (ArePotentiallyOverlappingStringLiterals(Info, LHSValue, RHSValue))
18381 return DiagArith(diag::note_constexpr_literal_arith);
18382
18383 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
18384 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
18385 if (!LHSAddrExpr || !RHSAddrExpr)
18386 return Error(E);
18387 // Make sure both labels come from the same function.
18388 if (LHSAddrExpr->getLabel()->getDeclContext() !=
18389 RHSAddrExpr->getLabel()->getDeclContext())
18390 return Error(E);
18391 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
18392 }
18393 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
18394 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
18395
18396 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
18397 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
18398
18399 // C++11 [expr.add]p6:
18400 // Unless both pointers point to elements of the same array object, or
18401 // one past the last element of the array object, the behavior is
18402 // undefined.
18403 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
18404 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
18405 RHSDesignator))
18406 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
18407
18408 QualType Type = E->getLHS()->getType();
18409 QualType ElementType = Type->castAs<PointerType>()->getPointeeType();
18410
18411 CharUnits ElementSize;
18412 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
18413 return false;
18414
18415 // As an extension, a type may have zero size (empty struct or union in
18416 // C, array of zero length). Pointer subtraction in such cases has
18417 // undefined behavior, so is not constant.
18418 if (ElementSize.isZero()) {
18419 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
18420 << ElementType;
18421 return false;
18422 }
18423
18424 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
18425 // and produce incorrect results when it overflows. Such behavior
18426 // appears to be non-conforming, but is common, so perhaps we should
18427 // assume the standard intended for such cases to be undefined behavior
18428 // and check for them.
18429
18430 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
18431 // overflow in the final conversion to ptrdiff_t.
18432 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
18433 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
18434 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
18435 false);
18436 APSInt TrueResult = (LHS - RHS) / ElemSize;
18437 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
18438
18439 if (Result.extend(65) != TrueResult &&
18440 !HandleOverflow(Info, E, TrueResult, E->getType()))
18441 return false;
18442 return Success(Result, E);
18443 }
18444
18445 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
18446 }
18447
18448 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
18449 /// a result as the expression's type.
18450 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
18451 const UnaryExprOrTypeTraitExpr *E) {
18452 switch(E->getKind()) {
18453 case UETT_PreferredAlignOf:
18454 case UETT_AlignOf: {
18455 if (E->isArgumentType())
18456 return Success(
18457 GetAlignOfType(Info.Ctx, E->getArgumentType(), E->getKind()), E);
18458 else
18459 return Success(
18460 GetAlignOfExpr(Info.Ctx, E->getArgumentExpr(), E->getKind()), E);
18461 }
18462
18463 case UETT_PtrAuthTypeDiscriminator: {
18464 if (E->getArgumentType()->isDependentType())
18465 return false;
18466 return Success(
18467 Info.Ctx.getPointerAuthTypeDiscriminator(E->getArgumentType()), E);
18468 }
18469 case UETT_VecStep: {
18470 QualType Ty = E->getTypeOfArgument();
18471
18472 if (Ty->isVectorType()) {
18473 unsigned n = Ty->castAs<VectorType>()->getNumElements();
18474
18475 // The vec_step built-in functions that take a 3-component
18476 // vector return 4. (OpenCL 1.1 spec 6.11.12)
18477 if (n == 3)
18478 n = 4;
18479
18480 return Success(n, E);
18481 } else
18482 return Success(1, E);
18483 }
18484
18485 case UETT_DataSizeOf:
18486 case UETT_SizeOf: {
18487 QualType SrcTy = E->getTypeOfArgument();
18488 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
18489 // the result is the size of the referenced type."
18490 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
18491 SrcTy = Ref->getPointeeType();
18492
18493 CharUnits Sizeof;
18494 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof,
18495 E->getKind() == UETT_DataSizeOf ? SizeOfType::DataSizeOf
18496 : SizeOfType::SizeOf)) {
18497 return false;
18498 }
18499 return Success(Sizeof, E);
18500 }
18501 case UETT_OpenMPRequiredSimdAlign:
18502 assert(E->isArgumentType());
18503 return Success(
18504 Info.Ctx.toCharUnitsFromBits(
18505 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
18506 .getQuantity(),
18507 E);
18508 case UETT_VectorElements: {
18509 QualType Ty = E->getTypeOfArgument();
18510 // If the vector has a fixed size, we can determine the number of elements
18511 // at compile time.
18512 if (const auto *VT = Ty->getAs<VectorType>())
18513 return Success(VT->getNumElements(), E);
18514
18515 assert(Ty->isSizelessVectorType());
18516 if (Info.InConstantContext)
18517 Info.CCEDiag(E, diag::note_constexpr_non_const_vectorelements)
18518 << E->getSourceRange();
18519
18520 return false;
18521 }
18522 case UETT_CountOf: {
18523 QualType Ty = E->getTypeOfArgument();
18524 assert(Ty->isArrayType());
18525
18526 // We don't need to worry about array element qualifiers, so getting the
18527 // unsafe array type is fine.
18528 if (const auto *CAT =
18529 dyn_cast<ConstantArrayType>(Ty->getAsArrayTypeUnsafe())) {
18530 return Success(CAT->getSize(), E);
18531 }
18532
18533 assert(!Ty->isConstantSizeType());
18534
18535 // If it's a variable-length array type, we need to check whether it is a
18536 // multidimensional array. If so, we need to check the size expression of
18537 // the VLA to see if it's a constant size. If so, we can return that value.
18538 const auto *VAT = Info.Ctx.getAsVariableArrayType(Ty);
18539 assert(VAT);
18540 if (VAT->getElementType()->isArrayType()) {
18541 // Variable array size expression could be missing (e.g. int a[*][10]) In
18542 // that case, it can't be a constant expression.
18543 if (!VAT->getSizeExpr()) {
18544 Info.FFDiag(E->getBeginLoc());
18545 return false;
18546 }
18547
18548 std::optional<APSInt> Res =
18549 VAT->getSizeExpr()->getIntegerConstantExpr(Info.Ctx);
18550 if (Res) {
18551 // The resulting value always has type size_t, so we need to make the
18552 // returned APInt have the correct sign and bit-width.
18553 APInt Val{
18554 static_cast<unsigned>(Info.Ctx.getTypeSize(Info.Ctx.getSizeType())),
18555 Res->getZExtValue()};
18556 return Success(Val, E);
18557 }
18558 }
18559
18560 // Definitely a variable-length type, which is not an ICE.
18561 // FIXME: Better diagnostic.
18562 Info.FFDiag(E->getBeginLoc());
18563 return false;
18564 }
18565 }
18566
18567 llvm_unreachable("unknown expr/type trait");
18568 }
18569
18570 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
18571 CharUnits Result;
18572 unsigned n = OOE->getNumComponents();
18573 if (n == 0)
18574 return Error(OOE);
18575 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
18576 for (unsigned i = 0; i != n; ++i) {
18577 OffsetOfNode ON = OOE->getComponent(i);
18578 switch (ON.getKind()) {
18579 case OffsetOfNode::Array: {
18580 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
18581 APSInt IdxResult;
18582 if (!EvaluateInteger(Idx, IdxResult, Info))
18583 return false;
18584 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
18585 if (!AT)
18586 return Error(OOE);
18587 CurrentType = AT->getElementType();
18588 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
18589 Result += IdxResult.getSExtValue() * ElementSize;
18590 break;
18591 }
18592
18593 case OffsetOfNode::Field: {
18594 FieldDecl *MemberDecl = ON.getField();
18595 const auto *RD = CurrentType->getAsRecordDecl();
18596 if (!RD)
18597 return Error(OOE);
18598 if (RD->isInvalidDecl()) return false;
18599 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
18600 unsigned i = MemberDecl->getFieldIndex();
18601 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
18602 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
18603 CurrentType = MemberDecl->getType().getNonReferenceType();
18604 break;
18605 }
18606
18607 case OffsetOfNode::Identifier:
18608 llvm_unreachable("dependent __builtin_offsetof");
18609
18610 case OffsetOfNode::Base: {
18611 CXXBaseSpecifier *BaseSpec = ON.getBase();
18612 if (BaseSpec->isVirtual())
18613 return Error(OOE);
18614
18615 // Find the layout of the class whose base we are looking into.
18616 const auto *RD = CurrentType->getAsCXXRecordDecl();
18617 if (!RD)
18618 return Error(OOE);
18619 if (RD->isInvalidDecl()) return false;
18620 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
18621
18622 // Find the base class itself.
18623 CurrentType = BaseSpec->getType();
18624 const auto *BaseRD = CurrentType->getAsCXXRecordDecl();
18625 if (!BaseRD)
18626 return Error(OOE);
18627
18628 // Add the offset to the base.
18629 Result += RL.getBaseClassOffset(BaseRD);
18630 break;
18631 }
18632 }
18633 }
18634 return Success(Result, OOE);
18635 }
18636
18637 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
18638 switch (E->getOpcode()) {
18639 default:
18640 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
18641 // See C99 6.6p3.
18642 return Error(E);
18643 case UO_Extension:
18644 // FIXME: Should extension allow i-c-e extension expressions in its scope?
18645 // If so, we could clear the diagnostic ID.
18646 return Visit(E->getSubExpr());
18647 case UO_Plus:
18648 // The result is just the value.
18649 return Visit(E->getSubExpr());
18650 case UO_Minus: {
18651 if (!Visit(E->getSubExpr()))
18652 return false;
18653 if (!Result.isInt()) return Error(E);
18654 const APSInt &Value = Result.getInt();
18655 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow()) {
18656 if (Info.checkingForUndefinedBehavior())
18657 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
18658 diag::warn_integer_constant_overflow)
18659 << toString(Value, 10, Value.isSigned(), /*formatAsCLiteral=*/false,
18660 /*UpperCase=*/true, /*InsertSeparators=*/true)
18661 << E->getType() << E->getSourceRange();
18662
18663 if (!HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
18664 E->getType()))
18665 return false;
18666 }
18667 return Success(-Value, E);
18668 }
18669 case UO_Not: {
18670 if (!Visit(E->getSubExpr()))
18671 return false;
18672 if (!Result.isInt()) return Error(E);
18673 return Success(~Result.getInt(), E);
18674 }
18675 case UO_LNot: {
18676 bool bres;
18677 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
18678 return false;
18679 return Success(!bres, E);
18680 }
18681 }
18682 }
18683
18684 /// HandleCast - This is used to evaluate implicit or explicit casts where the
18685 /// result type is integer.
18686 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
18687 const Expr *SubExpr = E->getSubExpr();
18688 QualType DestType = E->getType();
18689 QualType SrcType = SubExpr->getType();
18690
18691 switch (E->getCastKind()) {
18692 case CK_BaseToDerived:
18693 case CK_DerivedToBase:
18694 case CK_UncheckedDerivedToBase:
18695 case CK_Dynamic:
18696 case CK_ToUnion:
18697 case CK_ArrayToPointerDecay:
18698 case CK_FunctionToPointerDecay:
18699 case CK_NullToPointer:
18700 case CK_NullToMemberPointer:
18701 case CK_BaseToDerivedMemberPointer:
18702 case CK_DerivedToBaseMemberPointer:
18703 case CK_ReinterpretMemberPointer:
18704 case CK_ConstructorConversion:
18705 case CK_IntegralToPointer:
18706 case CK_ToVoid:
18707 case CK_VectorSplat:
18708 case CK_IntegralToFloating:
18709 case CK_FloatingCast:
18710 case CK_CPointerToObjCPointerCast:
18711 case CK_BlockPointerToObjCPointerCast:
18712 case CK_AnyPointerToBlockPointerCast:
18713 case CK_ObjCObjectLValueCast:
18714 case CK_FloatingRealToComplex:
18715 case CK_FloatingComplexToReal:
18716 case CK_FloatingComplexCast:
18717 case CK_FloatingComplexToIntegralComplex:
18718 case CK_IntegralRealToComplex:
18719 case CK_IntegralComplexCast:
18720 case CK_IntegralComplexToFloatingComplex:
18721 case CK_BuiltinFnToFnPtr:
18722 case CK_ZeroToOCLOpaqueType:
18723 case CK_NonAtomicToAtomic:
18724 case CK_AddressSpaceConversion:
18725 case CK_IntToOCLSampler:
18726 case CK_FloatingToFixedPoint:
18727 case CK_FixedPointToFloating:
18728 case CK_FixedPointCast:
18729 case CK_IntegralToFixedPoint:
18730 case CK_MatrixCast:
18731 case CK_HLSLAggregateSplatCast:
18732 llvm_unreachable("invalid cast kind for integral value");
18733
18734 case CK_BitCast:
18735 case CK_Dependent:
18736 case CK_LValueBitCast:
18737 case CK_ARCProduceObject:
18738 case CK_ARCConsumeObject:
18739 case CK_ARCReclaimReturnedObject:
18740 case CK_ARCExtendBlockObject:
18741 case CK_CopyAndAutoreleaseBlockObject:
18742 return Error(E);
18743
18744 case CK_UserDefinedConversion:
18745 case CK_LValueToRValue:
18746 case CK_AtomicToNonAtomic:
18747 case CK_NoOp:
18748 case CK_LValueToRValueBitCast:
18749 case CK_HLSLArrayRValue:
18750 return ExprEvaluatorBaseTy::VisitCastExpr(E);
18751
18752 case CK_MemberPointerToBoolean:
18753 case CK_PointerToBoolean:
18754 case CK_IntegralToBoolean:
18755 case CK_FloatingToBoolean:
18756 case CK_BooleanToSignedIntegral:
18757 case CK_FloatingComplexToBoolean:
18758 case CK_IntegralComplexToBoolean: {
18759 bool BoolResult;
18760 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
18761 return false;
18762 uint64_t IntResult = BoolResult;
18763 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
18764 IntResult = (uint64_t)-1;
18765 return Success(IntResult, E);
18766 }
18767
18768 case CK_FixedPointToIntegral: {
18769 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
18770 if (!EvaluateFixedPoint(SubExpr, Src, Info))
18771 return false;
18772 bool Overflowed;
18773 llvm::APSInt Result = Src.convertToInt(
18774 Info.Ctx.getIntWidth(DestType),
18775 DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
18776 if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
18777 return false;
18778 return Success(Result, E);
18779 }
18780
18781 case CK_FixedPointToBoolean: {
18782 // Unsigned padding does not affect this.
18783 APValue Val;
18784 if (!Evaluate(Val, Info, SubExpr))
18785 return false;
18786 return Success(Val.getFixedPoint().getBoolValue(), E);
18787 }
18788
18789 case CK_IntegralCast: {
18790 if (!Visit(SubExpr))
18791 return false;
18792
18793 if (!Result.isInt()) {
18794 // Allow casts of address-of-label differences if they are no-ops
18795 // or narrowing, if the result is at least 32 bits wide.
18796 // (The narrowing case isn't actually guaranteed to
18797 // be constant-evaluatable except in some narrow cases which are hard
18798 // to detect here. We let it through on the assumption the user knows
18799 // what they are doing.)
18800 if (Result.isAddrLabelDiff()) {
18801 unsigned DestBits = Info.Ctx.getTypeSize(DestType);
18802 return DestBits >= 32 && DestBits <= Info.Ctx.getTypeSize(SrcType);
18803 }
18804 // Only allow casts of lvalues if they are lossless.
18805 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
18806 }
18807
18808 if (Info.Ctx.getLangOpts().CPlusPlus && DestType->isEnumeralType()) {
18809 const auto *ED = DestType->getAsEnumDecl();
18810 // Check that the value is within the range of the enumeration values.
18811 //
18812 // This corressponds to [expr.static.cast]p10 which says:
18813 // A value of integral or enumeration type can be explicitly converted
18814 // to a complete enumeration type ... If the enumeration type does not
18815 // have a fixed underlying type, the value is unchanged if the original
18816 // value is within the range of the enumeration values ([dcl.enum]), and
18817 // otherwise, the behavior is undefined.
18818 //
18819 // This was resolved as part of DR2338 which has CD5 status.
18820 if (!ED->isFixed()) {
18821 llvm::APInt Min;
18822 llvm::APInt Max;
18823
18824 ED->getValueRange(Max, Min);
18825 --Max;
18826
18827 if (ED->getNumNegativeBits() &&
18828 (Max.slt(Result.getInt().getSExtValue()) ||
18829 Min.sgt(Result.getInt().getSExtValue())))
18830 Info.CCEDiag(E, diag::note_constexpr_unscoped_enum_out_of_range)
18831 << llvm::toString(Result.getInt(), 10) << Min.getSExtValue()
18832 << Max.getSExtValue() << ED;
18833 else if (!ED->getNumNegativeBits() &&
18834 Max.ult(Result.getInt().getZExtValue()))
18835 Info.CCEDiag(E, diag::note_constexpr_unscoped_enum_out_of_range)
18836 << llvm::toString(Result.getInt(), 10) << Min.getZExtValue()
18837 << Max.getZExtValue() << ED;
18838 }
18839 }
18840
18841 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
18842 Result.getInt()), E);
18843 }
18844
18845 case CK_PointerToIntegral: {
18846 CCEDiag(E, diag::note_constexpr_invalid_cast)
18847 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
18848 << Info.Ctx.getLangOpts().CPlusPlus << E->getSourceRange();
18849
18850 LValue LV;
18851 if (!EvaluatePointer(SubExpr, LV, Info))
18852 return false;
18853
18854 if (LV.getLValueBase()) {
18855 // Only allow based lvalue casts if they are lossless.
18856 // FIXME: Allow a larger integer size than the pointer size, and allow
18857 // narrowing back down to pointer width in subsequent integral casts.
18858 // FIXME: Check integer type's active bits, not its type size.
18859 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
18860 return Error(E);
18861
18862 LV.Designator.setInvalid();
18863 LV.moveInto(Result);
18864 return true;
18865 }
18866
18867 APSInt AsInt;
18868 APValue V;
18869 LV.moveInto(V);
18870 if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
18871 llvm_unreachable("Can't cast this!");
18872
18873 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
18874 }
18875
18876 case CK_IntegralComplexToReal: {
18877 ComplexValue C;
18878 if (!EvaluateComplex(SubExpr, C, Info))
18879 return false;
18880 return Success(C.getComplexIntReal(), E);
18881 }
18882
18883 case CK_FloatingToIntegral: {
18884 APFloat F(0.0);
18885 if (!EvaluateFloat(SubExpr, F, Info))
18886 return false;
18887
18888 APSInt Value;
18889 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
18890 return false;
18891 return Success(Value, E);
18892 }
18893 case CK_HLSLVectorTruncation: {
18894 APValue Val;
18895 if (!EvaluateVector(SubExpr, Val, Info))
18896 return Error(E);
18897 return Success(Val.getVectorElt(0), E);
18898 }
18899 case CK_HLSLMatrixTruncation: {
18900 // TODO: See #168935. Add matrix truncation support to expr constant.
18901 return Error(E);
18902 }
18903 case CK_HLSLElementwiseCast: {
18904 SmallVector<APValue> SrcVals;
18905 SmallVector<QualType> SrcTypes;
18906
18907 if (!hlslElementwiseCastHelper(Info, SubExpr, DestType, SrcVals, SrcTypes))
18908 return false;
18909
18910 // cast our single element
18911 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
18912 APValue ResultVal;
18913 if (!handleScalarCast(Info, FPO, E, SrcTypes[0], DestType, SrcVals[0],
18914 ResultVal))
18915 return false;
18916 return Success(ResultVal, E);
18917 }
18918 }
18919
18920 llvm_unreachable("unknown cast resulting in integral value");
18921 }
18922
18923 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
18924 if (E->getSubExpr()->getType()->isAnyComplexType()) {
18925 ComplexValue LV;
18926 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
18927 return false;
18928 if (!LV.isComplexInt())
18929 return Error(E);
18930 return Success(LV.getComplexIntReal(), E);
18931 }
18932
18933 return Visit(E->getSubExpr());
18934 }
18935
18936 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
18937 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
18938 ComplexValue LV;
18939 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
18940 return false;
18941 if (!LV.isComplexInt())
18942 return Error(E);
18943 return Success(LV.getComplexIntImag(), E);
18944 }
18945
18946 VisitIgnoredValue(E->getSubExpr());
18947 return Success(0, E);
18948 }
18949
18950 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
18951 return Success(E->getPackLength(), E);
18952 }
18953
18954 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
18955 return Success(E->getValue(), E);
18956 }
18957
18958 bool IntExprEvaluator::VisitConceptSpecializationExpr(
18959 const ConceptSpecializationExpr *E) {
18960 return Success(E->isSatisfied(), E);
18961 }
18962
18963 bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) {
18964 return Success(E->isSatisfied(), E);
18965 }
18966
18967 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
18968 switch (E->getOpcode()) {
18969 default:
18970 // Invalid unary operators
18971 return Error(E);
18972 case UO_Plus:
18973 // The result is just the value.
18974 return Visit(E->getSubExpr());
18975 case UO_Minus: {
18976 if (!Visit(E->getSubExpr())) return false;
18977 if (!Result.isFixedPoint())
18978 return Error(E);
18979 bool Overflowed;
18980 APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
18981 if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
18982 return false;
18983 return Success(Negated, E);
18984 }
18985 case UO_LNot: {
18986 bool bres;
18987 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
18988 return false;
18989 return Success(!bres, E);
18990 }
18991 }
18992 }
18993
18994 bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
18995 const Expr *SubExpr = E->getSubExpr();
18996 QualType DestType = E->getType();
18997 assert(DestType->isFixedPointType() &&
18998 "Expected destination type to be a fixed point type");
18999 auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
19000
19001 switch (E->getCastKind()) {
19002 case CK_FixedPointCast: {
19003 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
19004 if (!EvaluateFixedPoint(SubExpr, Src, Info))
19005 return false;
19006 bool Overflowed;
19007 APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
19008 if (Overflowed) {
19009 if (Info.checkingForUndefinedBehavior())
19010 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
19011 diag::warn_fixedpoint_constant_overflow)
19012 << Result.toString() << E->getType();
19013 if (!HandleOverflow(Info, E, Result, E->getType()))
19014 return false;
19015 }
19016 return Success(Result, E);
19017 }
19018 case CK_IntegralToFixedPoint: {
19019 APSInt Src;
19020 if (!EvaluateInteger(SubExpr, Src, Info))
19021 return false;
19022
19023 bool Overflowed;
19024 APFixedPoint IntResult = APFixedPoint::getFromIntValue(
19025 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
19026
19027 if (Overflowed) {
19028 if (Info.checkingForUndefinedBehavior())
19029 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
19030 diag::warn_fixedpoint_constant_overflow)
19031 << IntResult.toString() << E->getType();
19032 if (!HandleOverflow(Info, E, IntResult, E->getType()))
19033 return false;
19034 }
19035
19036 return Success(IntResult, E);
19037 }
19038 case CK_FloatingToFixedPoint: {
19039 APFloat Src(0.0);
19040 if (!EvaluateFloat(SubExpr, Src, Info))
19041 return false;
19042
19043 bool Overflowed;
19044 APFixedPoint Result = APFixedPoint::getFromFloatValue(
19045 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
19046
19047 if (Overflowed) {
19048 if (Info.checkingForUndefinedBehavior())
19049 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
19050 diag::warn_fixedpoint_constant_overflow)
19051 << Result.toString() << E->getType();
19052 if (!HandleOverflow(Info, E, Result, E->getType()))
19053 return false;
19054 }
19055
19056 return Success(Result, E);
19057 }
19058 case CK_NoOp:
19059 case CK_LValueToRValue:
19060 return ExprEvaluatorBaseTy::VisitCastExpr(E);
19061 default:
19062 return Error(E);
19063 }
19064 }
19065
19066 bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
19067 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
19068 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
19069
19070 const Expr *LHS = E->getLHS();
19071 const Expr *RHS = E->getRHS();
19072 FixedPointSemantics ResultFXSema =
19073 Info.Ctx.getFixedPointSemantics(E->getType());
19074
19075 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
19076 if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
19077 return false;
19078 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
19079 if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
19080 return false;
19081
19082 bool OpOverflow = false, ConversionOverflow = false;
19083 APFixedPoint Result(LHSFX.getSemantics());
19084 switch (E->getOpcode()) {
19085 case BO_Add: {
19086 Result = LHSFX.add(RHSFX, &OpOverflow)
19087 .convert(ResultFXSema, &ConversionOverflow);
19088 break;
19089 }
19090 case BO_Sub: {
19091 Result = LHSFX.sub(RHSFX, &OpOverflow)
19092 .convert(ResultFXSema, &ConversionOverflow);
19093 break;
19094 }
19095 case BO_Mul: {
19096 Result = LHSFX.mul(RHSFX, &OpOverflow)
19097 .convert(ResultFXSema, &ConversionOverflow);
19098 break;
19099 }
19100 case BO_Div: {
19101 if (RHSFX.getValue() == 0) {
19102 Info.FFDiag(E, diag::note_expr_divide_by_zero);
19103 return false;
19104 }
19105 Result = LHSFX.div(RHSFX, &OpOverflow)
19106 .convert(ResultFXSema, &ConversionOverflow);
19107 break;
19108 }
19109 case BO_Shl:
19110 case BO_Shr: {
19111 FixedPointSemantics LHSSema = LHSFX.getSemantics();
19112 llvm::APSInt RHSVal = RHSFX.getValue();
19113
19114 unsigned ShiftBW =
19115 LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding();
19116 unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1);
19117 // Embedded-C 4.1.6.2.2:
19118 // The right operand must be nonnegative and less than the total number
19119 // of (nonpadding) bits of the fixed-point operand ...
19120 if (RHSVal.isNegative())
19121 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal;
19122 else if (Amt != RHSVal)
19123 Info.CCEDiag(E, diag::note_constexpr_large_shift)
19124 << RHSVal << E->getType() << ShiftBW;
19125
19126 if (E->getOpcode() == BO_Shl)
19127 Result = LHSFX.shl(Amt, &OpOverflow);
19128 else
19129 Result = LHSFX.shr(Amt, &OpOverflow);
19130 break;
19131 }
19132 default:
19133 return false;
19134 }
19135 if (OpOverflow || ConversionOverflow) {
19136 if (Info.checkingForUndefinedBehavior())
19137 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
19138 diag::warn_fixedpoint_constant_overflow)
19139 << Result.toString() << E->getType();
19140 if (!HandleOverflow(Info, E, Result, E->getType()))
19141 return false;
19142 }
19143 return Success(Result, E);
19144 }
19145
19146 //===----------------------------------------------------------------------===//
19147 // Float Evaluation
19148 //===----------------------------------------------------------------------===//
19149
19150 namespace {
19151 class FloatExprEvaluator
19152 : public ExprEvaluatorBase<FloatExprEvaluator> {
19153 APFloat &Result;
19154 public:
19155 FloatExprEvaluator(EvalInfo &info, APFloat &result)
19156 : ExprEvaluatorBaseTy(info), Result(result) {}
19157
19158 bool Success(const APValue &V, const Expr *e) {
19159 Result = V.getFloat();
19160 return true;
19161 }
19162
19163 bool ZeroInitialization(const Expr *E) {
19164 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
19165 return true;
19166 }
19167
19168 bool VisitCallExpr(const CallExpr *E);
19169
19170 bool VisitUnaryOperator(const UnaryOperator *E);
19171 bool VisitBinaryOperator(const BinaryOperator *E);
19172 bool VisitFloatingLiteral(const FloatingLiteral *E);
19173 bool VisitCastExpr(const CastExpr *E);
19174
19175 bool VisitUnaryReal(const UnaryOperator *E);
19176 bool VisitUnaryImag(const UnaryOperator *E);
19177
19178 // FIXME: Missing: array subscript of vector, member of vector
19179 };
19180 } // end anonymous namespace
19181
19182 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
19183 assert(!E->isValueDependent());
19184 assert(E->isPRValue() && E->getType()->isRealFloatingType());
19185 return FloatExprEvaluator(Info, Result).Visit(E);
19186 }
19187
19188 static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
19189 QualType ResultTy,
19190 const Expr *Arg,
19191 bool SNaN,
19192 llvm::APFloat &Result) {
19193 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
19194 if (!S) return false;
19195
19196 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
19197
19198 llvm::APInt fill;
19199
19200 // Treat empty strings as if they were zero.
19201 if (S->getString().empty())
19202 fill = llvm::APInt(32, 0);
19203 else if (S->getString().getAsInteger(0, fill))
19204 return false;
19205
19206 if (Context.getTargetInfo().isNan2008()) {
19207 if (SNaN)
19208 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
19209 else
19210 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
19211 } else {
19212 // Prior to IEEE 754-2008, architectures were allowed to choose whether
19213 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
19214 // a different encoding to what became a standard in 2008, and for pre-
19215 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
19216 // sNaN. This is now known as "legacy NaN" encoding.
19217 if (SNaN)
19218 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
19219 else
19220 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
19221 }
19222
19223 return true;
19224 }
19225
19226 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
19227 if (!IsConstantEvaluatedBuiltinCall(E))
19228 return ExprEvaluatorBaseTy::VisitCallExpr(E);
19229
19230 switch (E->getBuiltinCallee()) {
19231 default:
19232 return false;
19233
19234 case Builtin::BI__builtin_huge_val:
19235 case Builtin::BI__builtin_huge_valf:
19236 case Builtin::BI__builtin_huge_vall:
19237 case Builtin::BI__builtin_huge_valf16:
19238 case Builtin::BI__builtin_huge_valf128:
19239 case Builtin::BI__builtin_inf:
19240 case Builtin::BI__builtin_inff:
19241 case Builtin::BI__builtin_infl:
19242 case Builtin::BI__builtin_inff16:
19243 case Builtin::BI__builtin_inff128: {
19244 const llvm::fltSemantics &Sem =
19245 Info.Ctx.getFloatTypeSemantics(E->getType());
19246 Result = llvm::APFloat::getInf(Sem);
19247 return true;
19248 }
19249
19250 case Builtin::BI__builtin_nans:
19251 case Builtin::BI__builtin_nansf:
19252 case Builtin::BI__builtin_nansl:
19253 case Builtin::BI__builtin_nansf16:
19254 case Builtin::BI__builtin_nansf128:
19255 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
19256 true, Result))
19257 return Error(E);
19258 return true;
19259
19260 case Builtin::BI__builtin_nan:
19261 case Builtin::BI__builtin_nanf:
19262 case Builtin::BI__builtin_nanl:
19263 case Builtin::BI__builtin_nanf16:
19264 case Builtin::BI__builtin_nanf128:
19265 // If this is __builtin_nan() turn this into a nan, otherwise we
19266 // can't constant fold it.
19267 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
19268 false, Result))
19269 return Error(E);
19270 return true;
19271
19272 case Builtin::BI__builtin_elementwise_abs:
19273 case Builtin::BI__builtin_fabs:
19274 case Builtin::BI__builtin_fabsf:
19275 case Builtin::BI__builtin_fabsl:
19276 case Builtin::BI__builtin_fabsf128:
19277 // The C standard says "fabs raises no floating-point exceptions,
19278 // even if x is a signaling NaN. The returned value is independent of
19279 // the current rounding direction mode." Therefore constant folding can
19280 // proceed without regard to the floating point settings.
19281 // Reference, WG14 N2478 F.10.4.3
19282 if (!EvaluateFloat(E->getArg(0), Result, Info))
19283 return false;
19284
19285 if (Result.isNegative())
19286 Result.changeSign();
19287 return true;
19288
19289 case Builtin::BI__arithmetic_fence:
19290 return EvaluateFloat(E->getArg(0), Result, Info);
19291
19292 // FIXME: Builtin::BI__builtin_powi
19293 // FIXME: Builtin::BI__builtin_powif
19294 // FIXME: Builtin::BI__builtin_powil
19295
19296 case Builtin::BI__builtin_copysign:
19297 case Builtin::BI__builtin_copysignf:
19298 case Builtin::BI__builtin_copysignl:
19299 case Builtin::BI__builtin_copysignf128: {
19300 APFloat RHS(0.);
19301 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
19302 !EvaluateFloat(E->getArg(1), RHS, Info))
19303 return false;
19304 Result.copySign(RHS);
19305 return true;
19306 }
19307
19308 case Builtin::BI__builtin_fmax:
19309 case Builtin::BI__builtin_fmaxf:
19310 case Builtin::BI__builtin_fmaxl:
19311 case Builtin::BI__builtin_fmaxf16:
19312 case Builtin::BI__builtin_fmaxf128: {
19313 APFloat RHS(0.);
19314 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
19315 !EvaluateFloat(E->getArg(1), RHS, Info))
19316 return false;
19317 Result = maxnum(Result, RHS);
19318 return true;
19319 }
19320
19321 case Builtin::BI__builtin_fmin:
19322 case Builtin::BI__builtin_fminf:
19323 case Builtin::BI__builtin_fminl:
19324 case Builtin::BI__builtin_fminf16:
19325 case Builtin::BI__builtin_fminf128: {
19326 APFloat RHS(0.);
19327 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
19328 !EvaluateFloat(E->getArg(1), RHS, Info))
19329 return false;
19330 Result = minnum(Result, RHS);
19331 return true;
19332 }
19333
19334 case Builtin::BI__builtin_fmaximum_num:
19335 case Builtin::BI__builtin_fmaximum_numf:
19336 case Builtin::BI__builtin_fmaximum_numl:
19337 case Builtin::BI__builtin_fmaximum_numf16:
19338 case Builtin::BI__builtin_fmaximum_numf128: {
19339 APFloat RHS(0.);
19340 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
19341 !EvaluateFloat(E->getArg(1), RHS, Info))
19342 return false;
19343 Result = maximumnum(Result, RHS);
19344 return true;
19345 }
19346
19347 case Builtin::BI__builtin_fminimum_num:
19348 case Builtin::BI__builtin_fminimum_numf:
19349 case Builtin::BI__builtin_fminimum_numl:
19350 case Builtin::BI__builtin_fminimum_numf16:
19351 case Builtin::BI__builtin_fminimum_numf128: {
19352 APFloat RHS(0.);
19353 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
19354 !EvaluateFloat(E->getArg(1), RHS, Info))
19355 return false;
19356 Result = minimumnum(Result, RHS);
19357 return true;
19358 }
19359
19360 case Builtin::BI__builtin_elementwise_fma: {
19361 if (!E->getArg(0)->isPRValue() || !E->getArg(1)->isPRValue() ||
19362 !E->getArg(2)->isPRValue()) {
19363 return false;
19364 }
19365 APFloat SourceY(0.), SourceZ(0.);
19366 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
19367 !EvaluateFloat(E->getArg(1), SourceY, Info) ||
19368 !EvaluateFloat(E->getArg(2), SourceZ, Info))
19369 return false;
19370 llvm::RoundingMode RM = getActiveRoundingMode(getEvalInfo(), E);
19371 (void)Result.fusedMultiplyAdd(SourceY, SourceZ, RM);
19372 return true;
19373 }
19374
19375 case clang::X86::BI__builtin_ia32_vec_ext_v4sf: {
19376 APValue Vec;
19377 APSInt IdxAPS;
19378 if (!EvaluateVector(E->getArg(0), Vec, Info) ||
19379 !EvaluateInteger(E->getArg(1), IdxAPS, Info))
19380 return false;
19381 unsigned N = Vec.getVectorLength();
19382 unsigned Idx = static_cast<unsigned>(IdxAPS.getZExtValue() & (N - 1));
19383 return Success(Vec.getVectorElt(Idx), E);
19384 }
19385 }
19386 }
19387
19388 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
19389 if (E->getSubExpr()->getType()->isAnyComplexType()) {
19390 ComplexValue CV;
19391 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
19392 return false;
19393 Result = CV.FloatReal;
19394 return true;
19395 }
19396
19397 return Visit(E->getSubExpr());
19398 }
19399
19400 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
19401 if (E->getSubExpr()->getType()->isAnyComplexType()) {
19402 ComplexValue CV;
19403 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
19404 return false;
19405 Result = CV.FloatImag;
19406 return true;
19407 }
19408
19409 VisitIgnoredValue(E->getSubExpr());
19410 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
19411 Result = llvm::APFloat::getZero(Sem);
19412 return true;
19413 }
19414
19415 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
19416 switch (E->getOpcode()) {
19417 default: return Error(E);
19418 case UO_Plus:
19419 return EvaluateFloat(E->getSubExpr(), Result, Info);
19420 case UO_Minus:
19421 // In C standard, WG14 N2478 F.3 p4
19422 // "the unary - raises no floating point exceptions,
19423 // even if the operand is signalling."
19424 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
19425 return false;
19426 Result.changeSign();
19427 return true;
19428 }
19429 }
19430
19431 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
19432 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
19433 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
19434
19435 APFloat RHS(0.0);
19436 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
19437 if (!LHSOK && !Info.noteFailure())
19438 return false;
19439 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
19440 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
19441 }
19442
19443 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
19444 Result = E->getValue();
19445 return true;
19446 }
19447
19448 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
19449 const Expr* SubExpr = E->getSubExpr();
19450
19451 switch (E->getCastKind()) {
19452 default:
19453 return ExprEvaluatorBaseTy::VisitCastExpr(E);
19454
19455 case CK_HLSLAggregateSplatCast:
19456 llvm_unreachable("invalid cast kind for floating value");
19457
19458 case CK_IntegralToFloating: {
19459 APSInt IntResult;
19460 const FPOptions FPO = E->getFPFeaturesInEffect(
19461 Info.Ctx.getLangOpts());
19462 return EvaluateInteger(SubExpr, IntResult, Info) &&
19463 HandleIntToFloatCast(Info, E, FPO, SubExpr->getType(),
19464 IntResult, E->getType(), Result);
19465 }
19466
19467 case CK_FixedPointToFloating: {
19468 APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
19469 if (!EvaluateFixedPoint(SubExpr, FixResult, Info))
19470 return false;
19471 Result =
19472 FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->getType()));
19473 return true;
19474 }
19475
19476 case CK_FloatingCast: {
19477 if (!Visit(SubExpr))
19478 return false;
19479 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
19480 Result);
19481 }
19482
19483 case CK_FloatingComplexToReal: {
19484 ComplexValue V;
19485 if (!EvaluateComplex(SubExpr, V, Info))
19486 return false;
19487 Result = V.getComplexFloatReal();
19488 return true;
19489 }
19490 case CK_HLSLVectorTruncation: {
19491 APValue Val;
19492 if (!EvaluateVector(SubExpr, Val, Info))
19493 return Error(E);
19494 return Success(Val.getVectorElt(0), E);
19495 }
19496 case CK_HLSLMatrixTruncation: {
19497 // TODO: See #168935. Add matrix truncation support to expr constant.
19498 return Error(E);
19499 }
19500 case CK_HLSLElementwiseCast: {
19501 SmallVector<APValue> SrcVals;
19502 SmallVector<QualType> SrcTypes;
19503
19504 if (!hlslElementwiseCastHelper(Info, SubExpr, E->getType(), SrcVals,
19505 SrcTypes))
19506 return false;
19507 APValue Val;
19508
19509 // cast our single element
19510 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
19511 APValue ResultVal;
19512 if (!handleScalarCast(Info, FPO, E, SrcTypes[0], E->getType(), SrcVals[0],
19513 ResultVal))
19514 return false;
19515 return Success(ResultVal, E);
19516 }
19517 }
19518 }
19519
19520 //===----------------------------------------------------------------------===//
19521 // Complex Evaluation (for float and integer)
19522 //===----------------------------------------------------------------------===//
19523
19524 namespace {
19525 class ComplexExprEvaluator
19526 : public ExprEvaluatorBase<ComplexExprEvaluator> {
19527 ComplexValue &Result;
19528
19529 public:
19530 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
19531 : ExprEvaluatorBaseTy(info), Result(Result) {}
19532
19533 bool Success(const APValue &V, const Expr *e) {
19534 Result.setFrom(V);
19535 return true;
19536 }
19537
19538 bool ZeroInitialization(const Expr *E);
19539
19540 //===--------------------------------------------------------------------===//
19541 // Visitor Methods
19542 //===--------------------------------------------------------------------===//
19543
19544 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
19545 bool VisitCastExpr(const CastExpr *E);
19546 bool VisitBinaryOperator(const BinaryOperator *E);
19547 bool VisitUnaryOperator(const UnaryOperator *E);
19548 bool VisitInitListExpr(const InitListExpr *E);
19549 bool VisitCallExpr(const CallExpr *E);
19550 };
19551 } // end anonymous namespace
19552
19553 static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
19554 EvalInfo &Info) {
19555 assert(!E->isValueDependent());
19556 assert(E->isPRValue() && E->getType()->isAnyComplexType());
19557 return ComplexExprEvaluator(Info, Result).Visit(E);
19558 }
19559
19560 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
19561 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
19562 if (ElemTy->isRealFloatingType()) {
19563 Result.makeComplexFloat();
19564 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
19565 Result.FloatReal = Zero;
19566 Result.FloatImag = Zero;
19567 } else {
19568 Result.makeComplexInt();
19569 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
19570 Result.IntReal = Zero;
19571 Result.IntImag = Zero;
19572 }
19573 return true;
19574 }
19575
19576 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
19577 const Expr* SubExpr = E->getSubExpr();
19578
19579 if (SubExpr->getType()->isRealFloatingType()) {
19580 Result.makeComplexFloat();
19581 APFloat &Imag = Result.FloatImag;
19582 if (!EvaluateFloat(SubExpr, Imag, Info))
19583 return false;
19584
19585 Result.FloatReal = APFloat(Imag.getSemantics());
19586 return true;
19587 } else {
19588 assert(SubExpr->getType()->isIntegerType() &&
19589 "Unexpected imaginary literal.");
19590
19591 Result.makeComplexInt();
19592 APSInt &Imag = Result.IntImag;
19593 if (!EvaluateInteger(SubExpr, Imag, Info))
19594 return false;
19595
19596 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
19597 return true;
19598 }
19599 }
19600
19601 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
19602
19603 switch (E->getCastKind()) {
19604 case CK_BitCast:
19605 case CK_BaseToDerived:
19606 case CK_DerivedToBase:
19607 case CK_UncheckedDerivedToBase:
19608 case CK_Dynamic:
19609 case CK_ToUnion:
19610 case CK_ArrayToPointerDecay:
19611 case CK_FunctionToPointerDecay:
19612 case CK_NullToPointer:
19613 case CK_NullToMemberPointer:
19614 case CK_BaseToDerivedMemberPointer:
19615 case CK_DerivedToBaseMemberPointer:
19616 case CK_MemberPointerToBoolean:
19617 case CK_ReinterpretMemberPointer:
19618 case CK_ConstructorConversion:
19619 case CK_IntegralToPointer:
19620 case CK_PointerToIntegral:
19621 case CK_PointerToBoolean:
19622 case CK_ToVoid:
19623 case CK_VectorSplat:
19624 case CK_IntegralCast:
19625 case CK_BooleanToSignedIntegral:
19626 case CK_IntegralToBoolean:
19627 case CK_IntegralToFloating:
19628 case CK_FloatingToIntegral:
19629 case CK_FloatingToBoolean:
19630 case CK_FloatingCast:
19631 case CK_CPointerToObjCPointerCast:
19632 case CK_BlockPointerToObjCPointerCast:
19633 case CK_AnyPointerToBlockPointerCast:
19634 case CK_ObjCObjectLValueCast:
19635 case CK_FloatingComplexToReal:
19636 case CK_FloatingComplexToBoolean:
19637 case CK_IntegralComplexToReal:
19638 case CK_IntegralComplexToBoolean:
19639 case CK_ARCProduceObject:
19640 case CK_ARCConsumeObject:
19641 case CK_ARCReclaimReturnedObject:
19642 case CK_ARCExtendBlockObject:
19643 case CK_CopyAndAutoreleaseBlockObject:
19644 case CK_BuiltinFnToFnPtr:
19645 case CK_ZeroToOCLOpaqueType:
19646 case CK_NonAtomicToAtomic:
19647 case CK_AddressSpaceConversion:
19648 case CK_IntToOCLSampler:
19649 case CK_FloatingToFixedPoint:
19650 case CK_FixedPointToFloating:
19651 case CK_FixedPointCast:
19652 case CK_FixedPointToBoolean:
19653 case CK_FixedPointToIntegral:
19654 case CK_IntegralToFixedPoint:
19655 case CK_MatrixCast:
19656 case CK_HLSLVectorTruncation:
19657 case CK_HLSLMatrixTruncation:
19658 case CK_HLSLElementwiseCast:
19659 case CK_HLSLAggregateSplatCast:
19660 llvm_unreachable("invalid cast kind for complex value");
19661
19662 case CK_LValueToRValue:
19663 case CK_AtomicToNonAtomic:
19664 case CK_NoOp:
19665 case CK_LValueToRValueBitCast:
19666 case CK_HLSLArrayRValue:
19667 return ExprEvaluatorBaseTy::VisitCastExpr(E);
19668
19669 case CK_Dependent:
19670 case CK_LValueBitCast:
19671 case CK_UserDefinedConversion:
19672 return Error(E);
19673
19674 case CK_FloatingRealToComplex: {
19675 APFloat &Real = Result.FloatReal;
19676 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
19677 return false;
19678
19679 Result.makeComplexFloat();
19680 Result.FloatImag = APFloat(Real.getSemantics());
19681 return true;
19682 }
19683
19684 case CK_FloatingComplexCast: {
19685 if (!Visit(E->getSubExpr()))
19686 return false;
19687
19688 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
19689 QualType From
19690 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
19691
19692 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
19693 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
19694 }
19695
19696 case CK_FloatingComplexToIntegralComplex: {
19697 if (!Visit(E->getSubExpr()))
19698 return false;
19699
19700 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
19701 QualType From
19702 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
19703 Result.makeComplexInt();
19704 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
19705 To, Result.IntReal) &&
19706 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
19707 To, Result.IntImag);
19708 }
19709
19710 case CK_IntegralRealToComplex: {
19711 APSInt &Real = Result.IntReal;
19712 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
19713 return false;
19714
19715 Result.makeComplexInt();
19716 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
19717 return true;
19718 }
19719
19720 case CK_IntegralComplexCast: {
19721 if (!Visit(E->getSubExpr()))
19722 return false;
19723
19724 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
19725 QualType From
19726 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
19727
19728 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
19729 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
19730 return true;
19731 }
19732
19733 case CK_IntegralComplexToFloatingComplex: {
19734 if (!Visit(E->getSubExpr()))
19735 return false;
19736
19737 const FPOptions FPO = E->getFPFeaturesInEffect(
19738 Info.Ctx.getLangOpts());
19739 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
19740 QualType From
19741 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
19742 Result.makeComplexFloat();
19743 return HandleIntToFloatCast(Info, E, FPO, From, Result.IntReal,
19744 To, Result.FloatReal) &&
19745 HandleIntToFloatCast(Info, E, FPO, From, Result.IntImag,
19746 To, Result.FloatImag);
19747 }
19748 }
19749
19750 llvm_unreachable("unknown cast resulting in complex value");
19751 }
19752
19753 uint8_t GFNIMultiplicativeInverse(uint8_t Byte) {
19754 // Lookup Table for Multiplicative Inverse in GF(2^8)
19755 const uint8_t GFInv[256] = {
19756 0x00, 0x01, 0x8d, 0xf6, 0xcb, 0x52, 0x7b, 0xd1, 0xe8, 0x4f, 0x29, 0xc0,
19757 0xb0, 0xe1, 0xe5, 0xc7, 0x74, 0xb4, 0xaa, 0x4b, 0x99, 0x2b, 0x60, 0x5f,
19758 0x58, 0x3f, 0xfd, 0xcc, 0xff, 0x40, 0xee, 0xb2, 0x3a, 0x6e, 0x5a, 0xf1,
19759 0x55, 0x4d, 0xa8, 0xc9, 0xc1, 0x0a, 0x98, 0x15, 0x30, 0x44, 0xa2, 0xc2,
19760 0x2c, 0x45, 0x92, 0x6c, 0xf3, 0x39, 0x66, 0x42, 0xf2, 0x35, 0x20, 0x6f,
19761 0x77, 0xbb, 0x59, 0x19, 0x1d, 0xfe, 0x37, 0x67, 0x2d, 0x31, 0xf5, 0x69,
19762 0xa7, 0x64, 0xab, 0x13, 0x54, 0x25, 0xe9, 0x09, 0xed, 0x5c, 0x05, 0xca,
19763 0x4c, 0x24, 0x87, 0xbf, 0x18, 0x3e, 0x22, 0xf0, 0x51, 0xec, 0x61, 0x17,
19764 0x16, 0x5e, 0xaf, 0xd3, 0x49, 0xa6, 0x36, 0x43, 0xf4, 0x47, 0x91, 0xdf,
19765 0x33, 0x93, 0x21, 0x3b, 0x79, 0xb7, 0x97, 0x85, 0x10, 0xb5, 0xba, 0x3c,
19766 0xb6, 0x70, 0xd0, 0x06, 0xa1, 0xfa, 0x81, 0x82, 0x83, 0x7e, 0x7f, 0x80,
19767 0x96, 0x73, 0xbe, 0x56, 0x9b, 0x9e, 0x95, 0xd9, 0xf7, 0x02, 0xb9, 0xa4,
19768 0xde, 0x6a, 0x32, 0x6d, 0xd8, 0x8a, 0x84, 0x72, 0x2a, 0x14, 0x9f, 0x88,
19769 0xf9, 0xdc, 0x89, 0x9a, 0xfb, 0x7c, 0x2e, 0xc3, 0x8f, 0xb8, 0x65, 0x48,
19770 0x26, 0xc8, 0x12, 0x4a, 0xce, 0xe7, 0xd2, 0x62, 0x0c, 0xe0, 0x1f, 0xef,
19771 0x11, 0x75, 0x78, 0x71, 0xa5, 0x8e, 0x76, 0x3d, 0xbd, 0xbc, 0x86, 0x57,
19772 0x0b, 0x28, 0x2f, 0xa3, 0xda, 0xd4, 0xe4, 0x0f, 0xa9, 0x27, 0x53, 0x04,
19773 0x1b, 0xfc, 0xac, 0xe6, 0x7a, 0x07, 0xae, 0x63, 0xc5, 0xdb, 0xe2, 0xea,
19774 0x94, 0x8b, 0xc4, 0xd5, 0x9d, 0xf8, 0x90, 0x6b, 0xb1, 0x0d, 0xd6, 0xeb,
19775 0xc6, 0x0e, 0xcf, 0xad, 0x08, 0x4e, 0xd7, 0xe3, 0x5d, 0x50, 0x1e, 0xb3,
19776 0x5b, 0x23, 0x38, 0x34, 0x68, 0x46, 0x03, 0x8c, 0xdd, 0x9c, 0x7d, 0xa0,
19777 0xcd, 0x1a, 0x41, 0x1c};
19778
19779 return GFInv[Byte];
19780 }
19781
19782 uint8_t GFNIAffine(uint8_t XByte, const APInt &AQword, const APSInt &Imm,
19783 bool Inverse) {
19784 unsigned NumBitsInByte = 8;
19785 // Computing the affine transformation
19786 uint8_t RetByte = 0;
19787 for (uint32_t BitIdx = 0; BitIdx != NumBitsInByte; ++BitIdx) {
19788 uint8_t AByte =
19789 AQword.lshr((7 - static_cast<int32_t>(BitIdx)) * NumBitsInByte)
19790 .getLoBits(8)
19791 .getZExtValue();
19792 uint8_t Product;
19793 if (Inverse) {
19794 Product = AByte & GFNIMultiplicativeInverse(XByte);
19795 } else {
19796 Product = AByte & XByte;
19797 }
19798 uint8_t Parity = 0;
19799
19800 // Dot product in GF(2) uses XOR instead of addition
19801 for (unsigned PBitIdx = 0; PBitIdx != NumBitsInByte; ++PBitIdx) {
19802 Parity = Parity ^ ((Product >> PBitIdx) & 0x1);
19803 }
19804
19805 uint8_t Temp = Imm[BitIdx] ? 1 : 0;
19806 RetByte |= (Temp ^ Parity) << BitIdx;
19807 }
19808 return RetByte;
19809 }
19810
19811 uint8_t GFNIMul(uint8_t AByte, uint8_t BByte) {
19812 // Multiplying two polynomials of degree 7
19813 // Polynomial of degree 7
19814 // x^7 + x^6 + x^5 + x^4 + x^3 + x^2 + x + 1
19815 uint16_t TWord = 0;
19816 unsigned NumBitsInByte = 8;
19817 for (unsigned BitIdx = 0; BitIdx != NumBitsInByte; ++BitIdx) {
19818 if ((BByte >> BitIdx) & 0x1) {
19819 TWord = TWord ^ (AByte << BitIdx);
19820 }
19821 }
19822
19823 // When multiplying two polynomials of degree 7
19824 // results in a polynomial of degree 14
19825 // so the result has to be reduced to 7
19826 // Reduction polynomial is x^8 + x^4 + x^3 + x + 1 i.e. 0x11B
19827 for (int32_t BitIdx = 14; BitIdx > 7; --BitIdx) {
19828 if ((TWord >> BitIdx) & 0x1) {
19829 TWord = TWord ^ (0x11B << (BitIdx - 8));
19830 }
19831 }
19832 return (TWord & 0xFF);
19833 }
19834
19835 void HandleComplexComplexMul(APFloat A, APFloat B, APFloat C, APFloat D,
19836 APFloat &ResR, APFloat &ResI) {
19837 // This is an implementation of complex multiplication according to the
19838 // constraints laid out in C11 Annex G. The implementation uses the
19839 // following naming scheme:
19840 // (a + ib) * (c + id)
19841
19842 APFloat AC = A * C;
19843 APFloat BD = B * D;
19844 APFloat AD = A * D;
19845 APFloat BC = B * C;
19846 ResR = AC - BD;
19847 ResI = AD + BC;
19848 if (ResR.isNaN() && ResI.isNaN()) {
19849 bool Recalc = false;
19850 if (A.isInfinity() || B.isInfinity()) {
19851 A = APFloat::copySign(APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0),
19852 A);
19853 B = APFloat::copySign(APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0),
19854 B);
19855 if (C.isNaN())
19856 C = APFloat::copySign(APFloat(C.getSemantics()), C);
19857 if (D.isNaN())
19858 D = APFloat::copySign(APFloat(D.getSemantics()), D);
19859 Recalc = true;
19860 }
19861 if (C.isInfinity() || D.isInfinity()) {
19862 C = APFloat::copySign(APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0),
19863 C);
19864 D = APFloat::copySign(APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0),
19865 D);
19866 if (A.isNaN())
19867 A = APFloat::copySign(APFloat(A.getSemantics()), A);
19868 if (B.isNaN())
19869 B = APFloat::copySign(APFloat(B.getSemantics()), B);
19870 Recalc = true;
19871 }
19872 if (!Recalc && (AC.isInfinity() || BD.isInfinity() || AD.isInfinity() ||
19873 BC.isInfinity())) {
19874 if (A.isNaN())
19875 A = APFloat::copySign(APFloat(A.getSemantics()), A);
19876 if (B.isNaN())
19877 B = APFloat::copySign(APFloat(B.getSemantics()), B);
19878 if (C.isNaN())
19879 C = APFloat::copySign(APFloat(C.getSemantics()), C);
19880 if (D.isNaN())
19881 D = APFloat::copySign(APFloat(D.getSemantics()), D);
19882 Recalc = true;
19883 }
19884 if (Recalc) {
19885 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
19886 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
19887 }
19888 }
19889 }
19890
19891 void HandleComplexComplexDiv(APFloat A, APFloat B, APFloat C, APFloat D,
19892 APFloat &ResR, APFloat &ResI) {
19893 // This is an implementation of complex division according to the
19894 // constraints laid out in C11 Annex G. The implementation uses the
19895 // following naming scheme:
19896 // (a + ib) / (c + id)
19897
19898 int DenomLogB = 0;
19899 APFloat MaxCD = maxnum(abs(C), abs(D));
19900 if (MaxCD.isFinite()) {
19901 DenomLogB = ilogb(MaxCD);
19902 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
19903 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
19904 }
19905 APFloat Denom = C * C + D * D;
19906 ResR =
19907 scalbn((A * C + B * D) / Denom, -DenomLogB, APFloat::rmNearestTiesToEven);
19908 ResI =
19909 scalbn((B * C - A * D) / Denom, -DenomLogB, APFloat::rmNearestTiesToEven);
19910 if (ResR.isNaN() && ResI.isNaN()) {
19911 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
19912 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
19913 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
19914 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
19915 D.isFinite()) {
19916 A = APFloat::copySign(APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0),
19917 A);
19918 B = APFloat::copySign(APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0),
19919 B);
19920 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
19921 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
19922 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
19923 C = APFloat::copySign(APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0),
19924 C);
19925 D = APFloat::copySign(APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0),
19926 D);
19927 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
19928 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
19929 }
19930 }
19931 }
19932
19933 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
19934 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
19935 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
19936
19937 // Track whether the LHS or RHS is real at the type system level. When this is
19938 // the case we can simplify our evaluation strategy.
19939 bool LHSReal = false, RHSReal = false;
19940
19941 bool LHSOK;
19942 if (E->getLHS()->getType()->isRealFloatingType()) {
19943 LHSReal = true;
19944 APFloat &Real = Result.FloatReal;
19945 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
19946 if (LHSOK) {
19947 Result.makeComplexFloat();
19948 Result.FloatImag = APFloat(Real.getSemantics());
19949 }
19950 } else {
19951 LHSOK = Visit(E->getLHS());
19952 }
19953 if (!LHSOK && !Info.noteFailure())
19954 return false;
19955
19956 ComplexValue RHS;
19957 if (E->getRHS()->getType()->isRealFloatingType()) {
19958 RHSReal = true;
19959 APFloat &Real = RHS.FloatReal;
19960 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
19961 return false;
19962 RHS.makeComplexFloat();
19963 RHS.FloatImag = APFloat(Real.getSemantics());
19964 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
19965 return false;
19966
19967 assert(!(LHSReal && RHSReal) &&
19968 "Cannot have both operands of a complex operation be real.");
19969 switch (E->getOpcode()) {
19970 default: return Error(E);
19971 case BO_Add:
19972 if (Result.isComplexFloat()) {
19973 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
19974 APFloat::rmNearestTiesToEven);
19975 if (LHSReal)
19976 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
19977 else if (!RHSReal)
19978 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
19979 APFloat::rmNearestTiesToEven);
19980 } else {
19981 Result.getComplexIntReal() += RHS.getComplexIntReal();
19982 Result.getComplexIntImag() += RHS.getComplexIntImag();
19983 }
19984 break;
19985 case BO_Sub:
19986 if (Result.isComplexFloat()) {
19987 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
19988 APFloat::rmNearestTiesToEven);
19989 if (LHSReal) {
19990 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
19991 Result.getComplexFloatImag().changeSign();
19992 } else if (!RHSReal) {
19993 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
19994 APFloat::rmNearestTiesToEven);
19995 }
19996 } else {
19997 Result.getComplexIntReal() -= RHS.getComplexIntReal();
19998 Result.getComplexIntImag() -= RHS.getComplexIntImag();
19999 }
20000 break;
20001 case BO_Mul:
20002 if (Result.isComplexFloat()) {
20003 // This is an implementation of complex multiplication according to the
20004 // constraints laid out in C11 Annex G. The implementation uses the
20005 // following naming scheme:
20006 // (a + ib) * (c + id)
20007 ComplexValue LHS = Result;
20008 APFloat &A = LHS.getComplexFloatReal();
20009 APFloat &B = LHS.getComplexFloatImag();
20010 APFloat &C = RHS.getComplexFloatReal();
20011 APFloat &D = RHS.getComplexFloatImag();
20012 APFloat &ResR = Result.getComplexFloatReal();
20013 APFloat &ResI = Result.getComplexFloatImag();
20014 if (LHSReal) {
20015 assert(!RHSReal && "Cannot have two real operands for a complex op!");
20016 ResR = A;
20017 ResI = A;
20018 // ResR = A * C;
20019 // ResI = A * D;
20020 if (!handleFloatFloatBinOp(Info, E, ResR, BO_Mul, C) ||
20021 !handleFloatFloatBinOp(Info, E, ResI, BO_Mul, D))
20022 return false;
20023 } else if (RHSReal) {
20024 // ResR = C * A;
20025 // ResI = C * B;
20026 ResR = C;
20027 ResI = C;
20028 if (!handleFloatFloatBinOp(Info, E, ResR, BO_Mul, A) ||
20029 !handleFloatFloatBinOp(Info, E, ResI, BO_Mul, B))
20030 return false;
20031 } else {
20032 HandleComplexComplexMul(A, B, C, D, ResR, ResI);
20033 }
20034 } else {
20035 ComplexValue LHS = Result;
20036 Result.getComplexIntReal() =
20037 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
20038 LHS.getComplexIntImag() * RHS.getComplexIntImag());
20039 Result.getComplexIntImag() =
20040 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
20041 LHS.getComplexIntImag() * RHS.getComplexIntReal());
20042 }
20043 break;
20044 case BO_Div:
20045 if (Result.isComplexFloat()) {
20046 // This is an implementation of complex division according to the
20047 // constraints laid out in C11 Annex G. The implementation uses the
20048 // following naming scheme:
20049 // (a + ib) / (c + id)
20050 ComplexValue LHS = Result;
20051 APFloat &A = LHS.getComplexFloatReal();
20052 APFloat &B = LHS.getComplexFloatImag();
20053 APFloat &C = RHS.getComplexFloatReal();
20054 APFloat &D = RHS.getComplexFloatImag();
20055 APFloat &ResR = Result.getComplexFloatReal();
20056 APFloat &ResI = Result.getComplexFloatImag();
20057 if (RHSReal) {
20058 ResR = A;
20059 ResI = B;
20060 // ResR = A / C;
20061 // ResI = B / C;
20062 if (!handleFloatFloatBinOp(Info, E, ResR, BO_Div, C) ||
20063 !handleFloatFloatBinOp(Info, E, ResI, BO_Div, C))
20064 return false;
20065 } else {
20066 if (LHSReal) {
20067 // No real optimizations we can do here, stub out with zero.
20068 B = APFloat::getZero(A.getSemantics());
20069 }
20070 HandleComplexComplexDiv(A, B, C, D, ResR, ResI);
20071 }
20072 } else {
20073 ComplexValue LHS = Result;
20074 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
20075 RHS.getComplexIntImag() * RHS.getComplexIntImag();
20076 if (Den.isZero())
20077 return Error(E, diag::note_expr_divide_by_zero);
20078
20079 Result.getComplexIntReal() =
20080 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
20081 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
20082 Result.getComplexIntImag() =
20083 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
20084 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
20085 }
20086 break;
20087 }
20088
20089 return true;
20090 }
20091
20092 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
20093 // Get the operand value into 'Result'.
20094 if (!Visit(E->getSubExpr()))
20095 return false;
20096
20097 switch (E->getOpcode()) {
20098 default:
20099 return Error(E);
20100 case UO_Extension:
20101 return true;
20102 case UO_Plus:
20103 // The result is always just the subexpr.
20104 return true;
20105 case UO_Minus:
20106 if (Result.isComplexFloat()) {
20107 Result.getComplexFloatReal().changeSign();
20108 Result.getComplexFloatImag().changeSign();
20109 }
20110 else {
20111 Result.getComplexIntReal() = -Result.getComplexIntReal();
20112 Result.getComplexIntImag() = -Result.getComplexIntImag();
20113 }
20114 return true;
20115 case UO_Not:
20116 if (Result.isComplexFloat())
20117 Result.getComplexFloatImag().changeSign();
20118 else
20119 Result.getComplexIntImag() = -Result.getComplexIntImag();
20120 return true;
20121 }
20122 }
20123
20124 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
20125 if (E->getNumInits() == 2) {
20126 if (E->getType()->isComplexType()) {
20127 Result.makeComplexFloat();
20128 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
20129 return false;
20130 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
20131 return false;
20132 } else {
20133 Result.makeComplexInt();
20134 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
20135 return false;
20136 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
20137 return false;
20138 }
20139 return true;
20140 }
20141 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
20142 }
20143
20144 bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) {
20145 if (!IsConstantEvaluatedBuiltinCall(E))
20146 return ExprEvaluatorBaseTy::VisitCallExpr(E);
20147
20148 switch (E->getBuiltinCallee()) {
20149 case Builtin::BI__builtin_complex:
20150 Result.makeComplexFloat();
20151 if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info))
20152 return false;
20153 if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info))
20154 return false;
20155 return true;
20156
20157 default:
20158 return false;
20159 }
20160 }
20161
20162 //===----------------------------------------------------------------------===//
20163 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
20164 // implicit conversion.
20165 //===----------------------------------------------------------------------===//
20166
20167 namespace {
20168 class AtomicExprEvaluator :
20169 public ExprEvaluatorBase<AtomicExprEvaluator> {
20170 const LValue *This;
20171 APValue &Result;
20172 public:
20173 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
20174 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
20175
20176 bool Success(const APValue &V, const Expr *E) {
20177 Result = V;
20178 return true;
20179 }
20180
20181 bool ZeroInitialization(const Expr *E) {
20182 ImplicitValueInitExpr VIE(
20183 E->getType()->castAs<AtomicType>()->getValueType());
20184 // For atomic-qualified class (and array) types in C++, initialize the
20185 // _Atomic-wrapped subobject directly, in-place.
20186 return This ? EvaluateInPlace(Result, Info, *This, &VIE)
20187 : Evaluate(Result, Info, &VIE);
20188 }
20189
20190 bool VisitCastExpr(const CastExpr *E) {
20191 switch (E->getCastKind()) {
20192 default:
20193 return ExprEvaluatorBaseTy::VisitCastExpr(E);
20194 case CK_NullToPointer:
20195 VisitIgnoredValue(E->getSubExpr());
20196 return ZeroInitialization(E);
20197 case CK_NonAtomicToAtomic:
20198 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
20199 : Evaluate(Result, Info, E->getSubExpr());
20200 }
20201 }
20202 };
20203 } // end anonymous namespace
20204
20205 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
20206 EvalInfo &Info) {
20207 assert(!E->isValueDependent());
20208 assert(E->isPRValue() && E->getType()->isAtomicType());
20209 return AtomicExprEvaluator(Info, This, Result).Visit(E);
20210 }
20211
20212 //===----------------------------------------------------------------------===//
20213 // Void expression evaluation, primarily for a cast to void on the LHS of a
20214 // comma operator
20215 //===----------------------------------------------------------------------===//
20216
20217 namespace {
20218 class VoidExprEvaluator
20219 : public ExprEvaluatorBase<VoidExprEvaluator> {
20220 public:
20221 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
20222
20223 bool Success(const APValue &V, const Expr *e) { return true; }
20224
20225 bool ZeroInitialization(const Expr *E) { return true; }
20226
20227 bool VisitCastExpr(const CastExpr *E) {
20228 switch (E->getCastKind()) {
20229 default:
20230 return ExprEvaluatorBaseTy::VisitCastExpr(E);
20231 case CK_ToVoid:
20232 VisitIgnoredValue(E->getSubExpr());
20233 return true;
20234 }
20235 }
20236
20237 bool VisitCallExpr(const CallExpr *E) {
20238 if (!IsConstantEvaluatedBuiltinCall(E))
20239 return ExprEvaluatorBaseTy::VisitCallExpr(E);
20240
20241 switch (E->getBuiltinCallee()) {
20242 case Builtin::BI__assume:
20243 case Builtin::BI__builtin_assume:
20244 // The argument is not evaluated!
20245 return true;
20246
20247 case Builtin::BI__builtin_operator_delete:
20248 return HandleOperatorDeleteCall(Info, E);
20249
20250 default:
20251 return false;
20252 }
20253 }
20254
20255 bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
20256 };
20257 } // end anonymous namespace
20258
20259 bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
20260 // We cannot speculatively evaluate a delete expression.
20261 if (Info.SpeculativeEvaluationDepth)
20262 return false;
20263
20264 FunctionDecl *OperatorDelete = E->getOperatorDelete();
20265 if (!OperatorDelete
20266 ->isUsableAsGlobalAllocationFunctionInConstantEvaluation()) {
20267 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
20268 << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;
20269 return false;
20270 }
20271
20272 const Expr *Arg = E->getArgument();
20273
20274 LValue Pointer;
20275 if (!EvaluatePointer(Arg, Pointer, Info))
20276 return false;
20277 if (Pointer.Designator.Invalid)
20278 return false;
20279
20280 // Deleting a null pointer has no effect.
20281 if (Pointer.isNullPointer()) {
20282 // This is the only case where we need to produce an extension warning:
20283 // the only other way we can succeed is if we find a dynamic allocation,
20284 // and we will have warned when we allocated it in that case.
20285 if (!Info.getLangOpts().CPlusPlus20)
20286 Info.CCEDiag(E, diag::note_constexpr_new);
20287 return true;
20288 }
20289
20290 std::optional<DynAlloc *> Alloc = CheckDeleteKind(
20291 Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New);
20292 if (!Alloc)
20293 return false;
20294 QualType AllocType = Pointer.Base.getDynamicAllocType();
20295
20296 // For the non-array case, the designator must be empty if the static type
20297 // does not have a virtual destructor.
20298 if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 &&
20299 !hasVirtualDestructor(Arg->getType()->getPointeeType())) {
20300 Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor)
20301 << Arg->getType()->getPointeeType() << AllocType;
20302 return false;
20303 }
20304
20305 // For a class type with a virtual destructor, the selected operator delete
20306 // is the one looked up when building the destructor.
20307 if (!E->isArrayForm() && !E->isGlobalDelete()) {
20308 const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType);
20309 if (VirtualDelete &&
20310 !VirtualDelete
20311 ->isUsableAsGlobalAllocationFunctionInConstantEvaluation()) {
20312 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
20313 << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete;
20314 return false;
20315 }
20316 }
20317
20318 if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(),
20319 (*Alloc)->Value, AllocType))
20320 return false;
20321
20322 if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) {
20323 // The element was already erased. This means the destructor call also
20324 // deleted the object.
20325 // FIXME: This probably results in undefined behavior before we get this
20326 // far, and should be diagnosed elsewhere first.
20327 Info.FFDiag(E, diag::note_constexpr_double_delete);
20328 return false;
20329 }
20330
20331 return true;
20332 }
20333
20334 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
20335 assert(!E->isValueDependent());
20336 assert(E->isPRValue() && E->getType()->isVoidType());
20337 return VoidExprEvaluator(Info).Visit(E);
20338 }
20339
20340 //===----------------------------------------------------------------------===//
20341 // Top level Expr::EvaluateAsRValue method.
20342 //===----------------------------------------------------------------------===//
20343
20344 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
20345 assert(!E->isValueDependent());
20346 // In C, function designators are not lvalues, but we evaluate them as if they
20347 // are.
20348 QualType T = E->getType();
20349 if (E->isGLValue() || T->isFunctionType()) {
20350 LValue LV;
20351 if (!EvaluateLValue(E, LV, Info))
20352 return false;
20353 LV.moveInto(Result);
20354 } else if (T->isVectorType()) {
20355 if (!EvaluateVector(E, Result, Info))
20356 return false;
20357 } else if (T->isIntegralOrEnumerationType()) {
20358 if (!IntExprEvaluator(Info, Result).Visit(E))
20359 return false;
20360 } else if (T->hasPointerRepresentation()) {
20361 LValue LV;
20362 if (!EvaluatePointer(E, LV, Info))
20363 return false;
20364 LV.moveInto(Result);
20365 } else if (T->isRealFloatingType()) {
20366 llvm::APFloat F(0.0);
20367 if (!EvaluateFloat(E, F, Info))
20368 return false;
20369 Result = APValue(F);
20370 } else if (T->isAnyComplexType()) {
20371 ComplexValue C;
20372 if (!EvaluateComplex(E, C, Info))
20373 return false;
20374 C.moveInto(Result);
20375 } else if (T->isFixedPointType()) {
20376 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
20377 } else if (T->isMemberPointerType()) {
20378 MemberPtr P;
20379 if (!EvaluateMemberPointer(E, P, Info))
20380 return false;
20381 P.moveInto(Result);
20382 return true;
20383 } else if (T->isArrayType()) {
20384 LValue LV;
20385 APValue &Value =
20386 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
20387 if (!EvaluateArray(E, LV, Value, Info))
20388 return false;
20389 Result = Value;
20390 } else if (T->isRecordType()) {
20391 LValue LV;
20392 APValue &Value =
20393 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
20394 if (!EvaluateRecord(E, LV, Value, Info))
20395 return false;
20396 Result = Value;
20397 } else if (T->isVoidType()) {
20398 if (!Info.getLangOpts().CPlusPlus11)
20399 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
20400 << E->getType();
20401 if (!EvaluateVoid(E, Info))
20402 return false;
20403 } else if (T->isAtomicType()) {
20404 QualType Unqual = T.getAtomicUnqualifiedType();
20405 if (Unqual->isArrayType() || Unqual->isRecordType()) {
20406 LValue LV;
20407 APValue &Value = Info.CurrentCall->createTemporary(
20408 E, Unqual, ScopeKind::FullExpression, LV);
20409 if (!EvaluateAtomic(E, &LV, Value, Info))
20410 return false;
20411 Result = Value;
20412 } else {
20413 if (!EvaluateAtomic(E, nullptr, Result, Info))
20414 return false;
20415 }
20416 } else if (Info.getLangOpts().CPlusPlus11) {
20417 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
20418 return false;
20419 } else {
20420 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
20421 return false;
20422 }
20423
20424 return true;
20425 }
20426
20427 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
20428 /// cases, the in-place evaluation is essential, since later initializers for
20429 /// an object can indirectly refer to subobjects which were initialized earlier.
20430 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
20431 const Expr *E, bool AllowNonLiteralTypes) {
20432 assert(!E->isValueDependent());
20433
20434 // Normally expressions passed to EvaluateInPlace have a type, but not when
20435 // a VarDecl initializer is evaluated before the untyped ParenListExpr is
20436 // replaced with a CXXConstructExpr. This can happen in LLDB.
20437 if (E->getType().isNull())
20438 return false;
20439
20440 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
20441 return false;
20442
20443 if (E->isPRValue()) {
20444 // Evaluate arrays and record types in-place, so that later initializers can
20445 // refer to earlier-initialized members of the object.
20446 QualType T = E->getType();
20447 if (T->isArrayType())
20448 return EvaluateArray(E, This, Result, Info);
20449 else if (T->isRecordType())
20450 return EvaluateRecord(E, This, Result, Info);
20451 else if (T->isAtomicType()) {
20452 QualType Unqual = T.getAtomicUnqualifiedType();
20453 if (Unqual->isArrayType() || Unqual->isRecordType())
20454 return EvaluateAtomic(E, &This, Result, Info);
20455 }
20456 }
20457
20458 // For any other type, in-place evaluation is unimportant.
20459 return Evaluate(Result, Info, E);
20460 }
20461
20462 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
20463 /// lvalue-to-rvalue cast if it is an lvalue.
20464 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
20465 assert(!E->isValueDependent());
20466
20467 if (E->getType().isNull())
20468 return false;
20469
20470 if (!CheckLiteralType(Info, E))
20471 return false;
20472
20473 if (Info.EnableNewConstInterp) {
20474 if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result))
20475 return false;
20476 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
20477 ConstantExprKind::Normal);
20478 }
20479
20480 if (!::Evaluate(Result, Info, E))
20481 return false;
20482
20483 // Implicit lvalue-to-rvalue cast.
20484 if (E->isGLValue()) {
20485 LValue LV;
20486 LV.setFrom(Info.Ctx, Result);
20487 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
20488 return false;
20489 }
20490
20491 // Check this core constant expression is a constant expression.
20492 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
20493 ConstantExprKind::Normal) &&
20494 CheckMemoryLeaks(Info);
20495 }
20496
20497 static bool FastEvaluateAsRValue(const Expr *Exp, APValue &Result,
20498 const ASTContext &Ctx, bool &IsConst) {
20499 // Fast-path evaluations of integer literals, since we sometimes see files
20500 // containing vast quantities of these.
20501 if (const auto *L = dyn_cast<IntegerLiteral>(Exp)) {
20502 Result =
20503 APValue(APSInt(L->getValue(), L->getType()->isUnsignedIntegerType()));
20504 IsConst = true;
20505 return true;
20506 }
20507
20508 if (const auto *L = dyn_cast<CXXBoolLiteralExpr>(Exp)) {
20509 Result = APValue(APSInt(APInt(1, L->getValue())));
20510 IsConst = true;
20511 return true;
20512 }
20513
20514 if (const auto *FL = dyn_cast<FloatingLiteral>(Exp)) {
20515 Result = APValue(FL->getValue());
20516 IsConst = true;
20517 return true;
20518 }
20519
20520 if (const auto *L = dyn_cast<CharacterLiteral>(Exp)) {
20521 Result = APValue(Ctx.MakeIntValue(L->getValue(), L->getType()));
20522 IsConst = true;
20523 return true;
20524 }
20525
20526 if (const auto *CE = dyn_cast<ConstantExpr>(Exp)) {
20527 if (CE->hasAPValueResult()) {
20528 APValue APV = CE->getAPValueResult();
20529 if (!APV.isLValue()) {
20530 Result = std::move(APV);
20531 IsConst = true;
20532 return true;
20533 }
20534 }
20535
20536 // The SubExpr is usually just an IntegerLiteral.
20537 return FastEvaluateAsRValue(CE->getSubExpr(), Result, Ctx, IsConst);
20538 }
20539
20540 // This case should be rare, but we need to check it before we check on
20541 // the type below.
20542 if (Exp->getType().isNull()) {
20543 IsConst = false;
20544 return true;
20545 }
20546
20547 return false;
20548 }
20549
20550 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
20551 Expr::SideEffectsKind SEK) {
20552 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
20553 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
20554 }
20555
20556 static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
20557 const ASTContext &Ctx, EvalInfo &Info) {
20558 assert(!E->isValueDependent());
20559 bool IsConst;
20560 if (FastEvaluateAsRValue(E, Result.Val, Ctx, IsConst))
20561 return IsConst;
20562
20563 return EvaluateAsRValue(Info, E, Result.Val);
20564 }
20565
20566 static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
20567 const ASTContext &Ctx,
20568 Expr::SideEffectsKind AllowSideEffects,
20569 EvalInfo &Info) {
20570 assert(!E->isValueDependent());
20571 if (!E->getType()->isIntegralOrEnumerationType())
20572 return false;
20573
20574 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
20575 !ExprResult.Val.isInt() ||
20576 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
20577 return false;
20578
20579 return true;
20580 }
20581
20582 static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult,
20583 const ASTContext &Ctx,
20584 Expr::SideEffectsKind AllowSideEffects,
20585 EvalInfo &Info) {
20586 assert(!E->isValueDependent());
20587 if (!E->getType()->isFixedPointType())
20588 return false;
20589
20590 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
20591 return false;
20592
20593 if (!ExprResult.Val.isFixedPoint() ||
20594 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
20595 return false;
20596
20597 return true;
20598 }
20599
20600 /// EvaluateAsRValue - Return true if this is a constant which we can fold using
20601 /// any crazy technique (that has nothing to do with language standards) that
20602 /// we want to. If this function returns true, it returns the folded constant
20603 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
20604 /// will be applied to the result.
20605 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
20606 bool InConstantContext) const {
20607 assert(!isValueDependent() &&
20608 "Expression evaluator can't be called on a dependent expression.");
20609 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsRValue");
20610 EvalInfo Info(Ctx, Result, EvaluationMode::IgnoreSideEffects);
20611 Info.InConstantContext = InConstantContext;
20612 return ::EvaluateAsRValue(this, Result, Ctx, Info);
20613 }
20614
20615 bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
20616 bool InConstantContext) const {
20617 assert(!isValueDependent() &&
20618 "Expression evaluator can't be called on a dependent expression.");
20619 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsBooleanCondition");
20620 EvalResult Scratch;
20621 return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
20622 HandleConversionToBool(Scratch.Val, Result);
20623 }
20624
20625 bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
20626 SideEffectsKind AllowSideEffects,
20627 bool InConstantContext) const {
20628 assert(!isValueDependent() &&
20629 "Expression evaluator can't be called on a dependent expression.");
20630 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsInt");
20631 EvalInfo Info(Ctx, Result, EvaluationMode::IgnoreSideEffects);
20632 Info.InConstantContext = InConstantContext;
20633 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
20634 }
20635
20636 bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
20637 SideEffectsKind AllowSideEffects,
20638 bool InConstantContext) const {
20639 assert(!isValueDependent() &&
20640 "Expression evaluator can't be called on a dependent expression.");
20641 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFixedPoint");
20642 EvalInfo Info(Ctx, Result, EvaluationMode::IgnoreSideEffects);
20643 Info.InConstantContext = InConstantContext;
20644 return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
20645 }
20646
20647 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
20648 SideEffectsKind AllowSideEffects,
20649 bool InConstantContext) const {
20650 assert(!isValueDependent() &&
20651 "Expression evaluator can't be called on a dependent expression.");
20652
20653 if (!getType()->isRealFloatingType())
20654 return false;
20655
20656 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFloat");
20657 EvalResult ExprResult;
20658 if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
20659 !ExprResult.Val.isFloat() ||
20660 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
20661 return false;
20662
20663 Result = ExprResult.Val.getFloat();
20664 return true;
20665 }
20666
20667 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
20668 bool InConstantContext) const {
20669 assert(!isValueDependent() &&
20670 "Expression evaluator can't be called on a dependent expression.");
20671
20672 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsLValue");
20673 EvalInfo Info(Ctx, Result, EvaluationMode::ConstantFold);
20674 Info.InConstantContext = InConstantContext;
20675 LValue LV;
20676 CheckedTemporaries CheckedTemps;
20677
20678 if (Info.EnableNewConstInterp) {
20679 if (!Info.Ctx.getInterpContext().evaluate(Info, this, Result.Val,
20680 ConstantExprKind::Normal))
20681 return false;
20682
20683 LV.setFrom(Ctx, Result.Val);
20684 return CheckLValueConstantExpression(
20685 Info, getExprLoc(), Ctx.getLValueReferenceType(getType()), LV,
20686 ConstantExprKind::Normal, CheckedTemps);
20687 }
20688
20689 if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() ||
20690 Result.HasSideEffects ||
20691 !CheckLValueConstantExpression(Info, getExprLoc(),
20692 Ctx.getLValueReferenceType(getType()), LV,
20693 ConstantExprKind::Normal, CheckedTemps))
20694 return false;
20695
20696 LV.moveInto(Result.Val);
20697 return true;
20698 }
20699
20700 static bool EvaluateDestruction(const ASTContext &Ctx, APValue::LValueBase Base,
20701 APValue DestroyedValue, QualType Type,
20702 SourceLocation Loc, Expr::EvalStatus &EStatus,
20703 bool IsConstantDestruction) {
20704 EvalInfo Info(Ctx, EStatus,
20705 IsConstantDestruction ? EvaluationMode::ConstantExpression
20706 : EvaluationMode::ConstantFold);
20707 Info.setEvaluatingDecl(Base, DestroyedValue,
20708 EvalInfo::EvaluatingDeclKind::Dtor);
20709 Info.InConstantContext = IsConstantDestruction;
20710
20711 LValue LVal;
20712 LVal.set(Base);
20713
20714 if (!HandleDestruction(Info, Loc, Base, DestroyedValue, Type) ||
20715 EStatus.HasSideEffects)
20716 return false;
20717
20718 if (!Info.discardCleanups())
20719 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
20720
20721 return true;
20722 }
20723
20724 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx,
20725 ConstantExprKind Kind) const {
20726 assert(!isValueDependent() &&
20727 "Expression evaluator can't be called on a dependent expression.");
20728 bool IsConst;
20729 if (FastEvaluateAsRValue(this, Result.Val, Ctx, IsConst) &&
20730 Result.Val.hasValue())
20731 return true;
20732
20733 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsConstantExpr");
20734 EvaluationMode EM = EvaluationMode::ConstantExpression;
20735 EvalInfo Info(Ctx, Result, EM);
20736 Info.InConstantContext = true;
20737
20738 if (Info.EnableNewConstInterp) {
20739 if (!Info.Ctx.getInterpContext().evaluate(Info, this, Result.Val, Kind))
20740 return false;
20741 return CheckConstantExpression(Info, getExprLoc(),
20742 getStorageType(Ctx, this), Result.Val, Kind);
20743 }
20744
20745 // The type of the object we're initializing is 'const T' for a class NTTP.
20746 QualType T = getType();
20747 if (Kind == ConstantExprKind::ClassTemplateArgument)
20748 T.addConst();
20749
20750 // If we're evaluating a prvalue, fake up a MaterializeTemporaryExpr to
20751 // represent the result of the evaluation. CheckConstantExpression ensures
20752 // this doesn't escape.
20753 MaterializeTemporaryExpr BaseMTE(T, const_cast<Expr*>(this), true);
20754 APValue::LValueBase Base(&BaseMTE);
20755 Info.setEvaluatingDecl(Base, Result.Val);
20756
20757 LValue LVal;
20758 LVal.set(Base);
20759 // C++23 [intro.execution]/p5
20760 // A full-expression is [...] a constant-expression
20761 // So we need to make sure temporary objects are destroyed after having
20762 // evaluating the expression (per C++23 [class.temporary]/p4).
20763 FullExpressionRAII Scope(Info);
20764 if (!::EvaluateInPlace(Result.Val, Info, LVal, this) ||
20765 Result.HasSideEffects || !Scope.destroy())
20766 return false;
20767
20768 if (!Info.discardCleanups())
20769 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
20770
20771 if (!CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this),
20772 Result.Val, Kind))
20773 return false;
20774 if (!CheckMemoryLeaks(Info))
20775 return false;
20776
20777 // If this is a class template argument, it's required to have constant
20778 // destruction too.
20779 if (Kind == ConstantExprKind::ClassTemplateArgument &&
20780 (!EvaluateDestruction(Ctx, Base, Result.Val, T, getBeginLoc(), Result,
20781 true) ||
20782 Result.HasSideEffects)) {
20783 // FIXME: Prefix a note to indicate that the problem is lack of constant
20784 // destruction.
20785 return false;
20786 }
20787
20788 return true;
20789 }
20790
20791 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
20792 const VarDecl *VD,
20793 SmallVectorImpl<PartialDiagnosticAt> &Notes,
20794 bool IsConstantInitialization) const {
20795 assert(!isValueDependent() &&
20796 "Expression evaluator can't be called on a dependent expression.");
20797 assert(VD && "Need a valid VarDecl");
20798
20799 llvm::TimeTraceScope TimeScope("EvaluateAsInitializer", [&] {
20800 std::string Name;
20801 llvm::raw_string_ostream OS(Name);
20802 VD->printQualifiedName(OS);
20803 return Name;
20804 });
20805
20806 Expr::EvalStatus EStatus;
20807 EStatus.Diag = &Notes;
20808
20809 EvalInfo Info(Ctx, EStatus,
20810 (IsConstantInitialization &&
20811 (Ctx.getLangOpts().CPlusPlus || Ctx.getLangOpts().C23))
20812 ? EvaluationMode::ConstantExpression
20813 : EvaluationMode::ConstantFold);
20814 Info.setEvaluatingDecl(VD, Value);
20815 Info.InConstantContext = IsConstantInitialization;
20816
20817 SourceLocation DeclLoc = VD->getLocation();
20818 QualType DeclTy = VD->getType();
20819
20820 if (Info.EnableNewConstInterp) {
20821 auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext();
20822 if (!InterpCtx.evaluateAsInitializer(Info, VD, this, Value))
20823 return false;
20824
20825 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value,
20826 ConstantExprKind::Normal);
20827 } else {
20828 LValue LVal;
20829 LVal.set(VD);
20830
20831 {
20832 // C++23 [intro.execution]/p5
20833 // A full-expression is ... an init-declarator ([dcl.decl]) or a
20834 // mem-initializer.
20835 // So we need to make sure temporary objects are destroyed after having
20836 // evaluated the expression (per C++23 [class.temporary]/p4).
20837 //
20838 // FIXME: Otherwise this may break test/Modules/pr68702.cpp because the
20839 // serialization code calls ParmVarDecl::getDefaultArg() which strips the
20840 // outermost FullExpr, such as ExprWithCleanups.
20841 FullExpressionRAII Scope(Info);
20842 if (!EvaluateInPlace(Value, Info, LVal, this,
20843 /*AllowNonLiteralTypes=*/true) ||
20844 EStatus.HasSideEffects)
20845 return false;
20846 }
20847
20848 // At this point, any lifetime-extended temporaries are completely
20849 // initialized.
20850 Info.performLifetimeExtension();
20851
20852 if (!Info.discardCleanups())
20853 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
20854 }
20855
20856 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value,
20857 ConstantExprKind::Normal) &&
20858 CheckMemoryLeaks(Info);
20859 }
20860
20861 bool VarDecl::evaluateDestruction(
20862 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
20863 Expr::EvalStatus EStatus;
20864 EStatus.Diag = &Notes;
20865
20866 // Only treat the destruction as constant destruction if we formally have
20867 // constant initialization (or are usable in a constant expression).
20868 bool IsConstantDestruction = hasConstantInitialization();
20869
20870 // Make a copy of the value for the destructor to mutate, if we know it.
20871 // Otherwise, treat the value as default-initialized; if the destructor works
20872 // anyway, then the destruction is constant (and must be essentially empty).
20873 APValue DestroyedValue;
20874 if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent())
20875 DestroyedValue = *getEvaluatedValue();
20876 else if (!handleDefaultInitValue(getType(), DestroyedValue))
20877 return false;
20878
20879 if (!EvaluateDestruction(getASTContext(), this, std::move(DestroyedValue),
20880 getType(), getLocation(), EStatus,
20881 IsConstantDestruction) ||
20882 EStatus.HasSideEffects)
20883 return false;
20884
20885 ensureEvaluatedStmt()->HasConstantDestruction = true;
20886 return true;
20887 }
20888
20889 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
20890 /// constant folded, but discard the result.
20891 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
20892 assert(!isValueDependent() &&
20893 "Expression evaluator can't be called on a dependent expression.");
20894
20895 EvalResult Result;
20896 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
20897 !hasUnacceptableSideEffect(Result, SEK);
20898 }
20899
20900 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
20901 assert(!isValueDependent() &&
20902 "Expression evaluator can't be called on a dependent expression.");
20903
20904 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstInt");
20905 EvalResult EVResult;
20906 EvalInfo Info(Ctx, EVResult, EvaluationMode::IgnoreSideEffects);
20907 Info.InConstantContext = true;
20908
20909 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
20910 (void)Result;
20911 assert(Result && "Could not evaluate expression");
20912 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
20913
20914 return EVResult.Val.getInt();
20915 }
20916
20917 APSInt Expr::EvaluateKnownConstIntCheckOverflow(
20918 const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
20919 assert(!isValueDependent() &&
20920 "Expression evaluator can't be called on a dependent expression.");
20921
20922 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstIntCheckOverflow");
20923 EvalResult EVResult;
20924 EVResult.Diag = Diag;
20925 EvalInfo Info(Ctx, EVResult, EvaluationMode::IgnoreSideEffects);
20926 Info.InConstantContext = true;
20927 Info.CheckingForUndefinedBehavior = true;
20928
20929 bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
20930 (void)Result;
20931 assert(Result && "Could not evaluate expression");
20932 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
20933
20934 return EVResult.Val.getInt();
20935 }
20936
20937 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
20938 assert(!isValueDependent() &&
20939 "Expression evaluator can't be called on a dependent expression.");
20940
20941 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateForOverflow");
20942 bool IsConst;
20943 EvalResult EVResult;
20944 if (!FastEvaluateAsRValue(this, EVResult.Val, Ctx, IsConst)) {
20945 EvalInfo Info(Ctx, EVResult, EvaluationMode::IgnoreSideEffects);
20946 Info.CheckingForUndefinedBehavior = true;
20947 (void)::EvaluateAsRValue(Info, this, EVResult.Val);
20948 }
20949 }
20950
20951 bool Expr::EvalResult::isGlobalLValue() const {
20952 assert(Val.isLValue());
20953 return IsGlobalLValue(Val.getLValueBase());
20954 }
20955
20956 /// isIntegerConstantExpr - this recursive routine will test if an expression is
20957 /// an integer constant expression.
20958
20959 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
20960 /// comma, etc
20961
20962 // CheckICE - This function does the fundamental ICE checking: the returned
20963 // ICEDiag contains an ICEKind indicating whether the expression is an ICE.
20964 //
20965 // Note that to reduce code duplication, this helper does no evaluation
20966 // itself; the caller checks whether the expression is evaluatable, and
20967 // in the rare cases where CheckICE actually cares about the evaluated
20968 // value, it calls into Evaluate.
20969
20970 namespace {
20971
20972 enum ICEKind {
20973 /// This expression is an ICE.
20974 IK_ICE,
20975 /// This expression is not an ICE, but if it isn't evaluated, it's
20976 /// a legal subexpression for an ICE. This return value is used to handle
20977 /// the comma operator in C99 mode, and non-constant subexpressions.
20978 IK_ICEIfUnevaluated,
20979 /// This expression is not an ICE, and is not a legal subexpression for one.
20980 IK_NotICE
20981 };
20982
20983 struct ICEDiag {
20984 ICEKind Kind;
20985 SourceLocation Loc;
20986
20987 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
20988 };
20989
20990 }
20991
20992 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
20993
20994 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
20995
20996 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
20997 Expr::EvalResult EVResult;
20998 Expr::EvalStatus Status;
20999 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantExpression);
21000
21001 Info.InConstantContext = true;
21002 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
21003 !EVResult.Val.isInt())
21004 return ICEDiag(IK_NotICE, E->getBeginLoc());
21005
21006 return NoDiag();
21007 }
21008
21009 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
21010 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
21011 if (!E->getType()->isIntegralOrEnumerationType())
21012 return ICEDiag(IK_NotICE, E->getBeginLoc());
21013
21014 switch (E->getStmtClass()) {
21015 #define ABSTRACT_STMT(Node)
21016 #define STMT(Node, Base) case Expr::Node##Class:
21017 #define EXPR(Node, Base)
21018 #include "clang/AST/StmtNodes.inc"
21019 case Expr::PredefinedExprClass:
21020 case Expr::FloatingLiteralClass:
21021 case Expr::ImaginaryLiteralClass:
21022 case Expr::StringLiteralClass:
21023 case Expr::ArraySubscriptExprClass:
21024 case Expr::MatrixSingleSubscriptExprClass:
21025 case Expr::MatrixSubscriptExprClass:
21026 case Expr::ArraySectionExprClass:
21027 case Expr::OMPArrayShapingExprClass:
21028 case Expr::OMPIteratorExprClass:
21029 case Expr::MemberExprClass:
21030 case Expr::CompoundAssignOperatorClass:
21031 case Expr::CompoundLiteralExprClass:
21032 case Expr::ExtVectorElementExprClass:
21033 case Expr::DesignatedInitExprClass:
21034 case Expr::ArrayInitLoopExprClass:
21035 case Expr::ArrayInitIndexExprClass:
21036 case Expr::NoInitExprClass:
21037 case Expr::DesignatedInitUpdateExprClass:
21038 case Expr::ImplicitValueInitExprClass:
21039 case Expr::ParenListExprClass:
21040 case Expr::VAArgExprClass:
21041 case Expr::AddrLabelExprClass:
21042 case Expr::StmtExprClass:
21043 case Expr::CXXMemberCallExprClass:
21044 case Expr::CUDAKernelCallExprClass:
21045 case Expr::CXXAddrspaceCastExprClass:
21046 case Expr::CXXDynamicCastExprClass:
21047 case Expr::CXXTypeidExprClass:
21048 case Expr::CXXUuidofExprClass:
21049 case Expr::MSPropertyRefExprClass:
21050 case Expr::MSPropertySubscriptExprClass:
21051 case Expr::CXXNullPtrLiteralExprClass:
21052 case Expr::UserDefinedLiteralClass:
21053 case Expr::CXXThisExprClass:
21054 case Expr::CXXThrowExprClass:
21055 case Expr::CXXNewExprClass:
21056 case Expr::CXXDeleteExprClass:
21057 case Expr::CXXPseudoDestructorExprClass:
21058 case Expr::UnresolvedLookupExprClass:
21059 case Expr::RecoveryExprClass:
21060 case Expr::DependentScopeDeclRefExprClass:
21061 case Expr::CXXConstructExprClass:
21062 case Expr::CXXInheritedCtorInitExprClass:
21063 case Expr::CXXStdInitializerListExprClass:
21064 case Expr::CXXBindTemporaryExprClass:
21065 case Expr::ExprWithCleanupsClass:
21066 case Expr::CXXTemporaryObjectExprClass:
21067 case Expr::CXXUnresolvedConstructExprClass:
21068 case Expr::CXXDependentScopeMemberExprClass:
21069 case Expr::UnresolvedMemberExprClass:
21070 case Expr::ObjCStringLiteralClass:
21071 case Expr::ObjCBoxedExprClass:
21072 case Expr::ObjCArrayLiteralClass:
21073 case Expr::ObjCDictionaryLiteralClass:
21074 case Expr::ObjCEncodeExprClass:
21075 case Expr::ObjCMessageExprClass:
21076 case Expr::ObjCSelectorExprClass:
21077 case Expr::ObjCProtocolExprClass:
21078 case Expr::ObjCIvarRefExprClass:
21079 case Expr::ObjCPropertyRefExprClass:
21080 case Expr::ObjCSubscriptRefExprClass:
21081 case Expr::ObjCIsaExprClass:
21082 case Expr::ObjCAvailabilityCheckExprClass:
21083 case Expr::ShuffleVectorExprClass:
21084 case Expr::ConvertVectorExprClass:
21085 case Expr::BlockExprClass:
21086 case Expr::NoStmtClass:
21087 case Expr::OpaqueValueExprClass:
21088 case Expr::PackExpansionExprClass:
21089 case Expr::SubstNonTypeTemplateParmPackExprClass:
21090 case Expr::FunctionParmPackExprClass:
21091 case Expr::AsTypeExprClass:
21092 case Expr::ObjCIndirectCopyRestoreExprClass:
21093 case Expr::MaterializeTemporaryExprClass:
21094 case Expr::PseudoObjectExprClass:
21095 case Expr::AtomicExprClass:
21096 case Expr::LambdaExprClass:
21097 case Expr::CXXFoldExprClass:
21098 case Expr::CoawaitExprClass:
21099 case Expr::DependentCoawaitExprClass:
21100 case Expr::CoyieldExprClass:
21101 case Expr::SYCLUniqueStableNameExprClass:
21102 case Expr::CXXParenListInitExprClass:
21103 case Expr::HLSLOutArgExprClass:
21104 return ICEDiag(IK_NotICE, E->getBeginLoc());
21105
21106 case Expr::InitListExprClass: {
21107 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
21108 // form "T x = { a };" is equivalent to "T x = a;".
21109 // Unless we're initializing a reference, T is a scalar as it is known to be
21110 // of integral or enumeration type.
21111 if (E->isPRValue())
21112 if (cast<InitListExpr>(E)->getNumInits() == 1)
21113 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
21114 return ICEDiag(IK_NotICE, E->getBeginLoc());
21115 }
21116
21117 case Expr::SizeOfPackExprClass:
21118 case Expr::GNUNullExprClass:
21119 case Expr::SourceLocExprClass:
21120 case Expr::EmbedExprClass:
21121 case Expr::OpenACCAsteriskSizeExprClass:
21122 return NoDiag();
21123
21124 case Expr::PackIndexingExprClass:
21125 return CheckICE(cast<PackIndexingExpr>(E)->getSelectedExpr(), Ctx);
21126
21127 case Expr::SubstNonTypeTemplateParmExprClass:
21128 return
21129 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
21130
21131 case Expr::ConstantExprClass:
21132 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
21133
21134 case Expr::ParenExprClass:
21135 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
21136 case Expr::GenericSelectionExprClass:
21137 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
21138 case Expr::IntegerLiteralClass:
21139 case Expr::FixedPointLiteralClass:
21140 case Expr::CharacterLiteralClass:
21141 case Expr::ObjCBoolLiteralExprClass:
21142 case Expr::CXXBoolLiteralExprClass:
21143 case Expr::CXXScalarValueInitExprClass:
21144 case Expr::TypeTraitExprClass:
21145 case Expr::ConceptSpecializationExprClass:
21146 case Expr::RequiresExprClass:
21147 case Expr::ArrayTypeTraitExprClass:
21148 case Expr::ExpressionTraitExprClass:
21149 case Expr::CXXNoexceptExprClass:
21150 return NoDiag();
21151 case Expr::CallExprClass:
21152 case Expr::CXXOperatorCallExprClass: {
21153 // C99 6.6/3 allows function calls within unevaluated subexpressions of
21154 // constant expressions, but they can never be ICEs because an ICE cannot
21155 // contain an operand of (pointer to) function type.
21156 const CallExpr *CE = cast<CallExpr>(E);
21157 if (CE->getBuiltinCallee())
21158 return CheckEvalInICE(E, Ctx);
21159 return ICEDiag(IK_NotICE, E->getBeginLoc());
21160 }
21161 case Expr::CXXRewrittenBinaryOperatorClass:
21162 return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(),
21163 Ctx);
21164 case Expr::DeclRefExprClass: {
21165 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
21166 if (isa<EnumConstantDecl>(D))
21167 return NoDiag();
21168
21169 // C++ and OpenCL (FIXME: spec reference?) allow reading const-qualified
21170 // integer variables in constant expressions:
21171 //
21172 // C++ 7.1.5.1p2
21173 // A variable of non-volatile const-qualified integral or enumeration
21174 // type initialized by an ICE can be used in ICEs.
21175 //
21176 // We sometimes use CheckICE to check the C++98 rules in C++11 mode. In
21177 // that mode, use of reference variables should not be allowed.
21178 const VarDecl *VD = dyn_cast<VarDecl>(D);
21179 if (VD && VD->isUsableInConstantExpressions(Ctx) &&
21180 !VD->getType()->isReferenceType())
21181 return NoDiag();
21182
21183 return ICEDiag(IK_NotICE, E->getBeginLoc());
21184 }
21185 case Expr::UnaryOperatorClass: {
21186 const UnaryOperator *Exp = cast<UnaryOperator>(E);
21187 switch (Exp->getOpcode()) {
21188 case UO_PostInc:
21189 case UO_PostDec:
21190 case UO_PreInc:
21191 case UO_PreDec:
21192 case UO_AddrOf:
21193 case UO_Deref:
21194 case UO_Coawait:
21195 // C99 6.6/3 allows increment and decrement within unevaluated
21196 // subexpressions of constant expressions, but they can never be ICEs
21197 // because an ICE cannot contain an lvalue operand.
21198 return ICEDiag(IK_NotICE, E->getBeginLoc());
21199 case UO_Extension:
21200 case UO_LNot:
21201 case UO_Plus:
21202 case UO_Minus:
21203 case UO_Not:
21204 case UO_Real:
21205 case UO_Imag:
21206 return CheckICE(Exp->getSubExpr(), Ctx);
21207 }
21208 llvm_unreachable("invalid unary operator class");
21209 }
21210 case Expr::OffsetOfExprClass: {
21211 // Note that per C99, offsetof must be an ICE. And AFAIK, using
21212 // EvaluateAsRValue matches the proposed gcc behavior for cases like
21213 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
21214 // compliance: we should warn earlier for offsetof expressions with
21215 // array subscripts that aren't ICEs, and if the array subscripts
21216 // are ICEs, the value of the offsetof must be an integer constant.
21217 return CheckEvalInICE(E, Ctx);
21218 }
21219 case Expr::UnaryExprOrTypeTraitExprClass: {
21220 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
21221 if ((Exp->getKind() == UETT_SizeOf) &&
21222 Exp->getTypeOfArgument()->isVariableArrayType())
21223 return ICEDiag(IK_NotICE, E->getBeginLoc());
21224 if (Exp->getKind() == UETT_CountOf) {
21225 QualType ArgTy = Exp->getTypeOfArgument();
21226 if (ArgTy->isVariableArrayType()) {
21227 // We need to look whether the array is multidimensional. If it is,
21228 // then we want to check the size expression manually to see whether
21229 // it is an ICE or not.
21230 const auto *VAT = Ctx.getAsVariableArrayType(ArgTy);
21231 if (VAT->getElementType()->isArrayType())
21232 // Variable array size expression could be missing (e.g. int a[*][10])
21233 // In that case, it can't be a constant expression.
21234 return VAT->getSizeExpr() ? CheckICE(VAT->getSizeExpr(), Ctx)
21235 : ICEDiag(IK_NotICE, E->getBeginLoc());
21236
21237 // Otherwise, this is a regular VLA, which is definitely not an ICE.
21238 return ICEDiag(IK_NotICE, E->getBeginLoc());
21239 }
21240 }
21241 return NoDiag();
21242 }
21243 case Expr::BinaryOperatorClass: {
21244 const BinaryOperator *Exp = cast<BinaryOperator>(E);
21245 switch (Exp->getOpcode()) {
21246 case BO_PtrMemD:
21247 case BO_PtrMemI:
21248 case BO_Assign:
21249 case BO_MulAssign:
21250 case BO_DivAssign:
21251 case BO_RemAssign:
21252 case BO_AddAssign:
21253 case BO_SubAssign:
21254 case BO_ShlAssign:
21255 case BO_ShrAssign:
21256 case BO_AndAssign:
21257 case BO_XorAssign:
21258 case BO_OrAssign:
21259 // C99 6.6/3 allows assignments within unevaluated subexpressions of
21260 // constant expressions, but they can never be ICEs because an ICE cannot
21261 // contain an lvalue operand.
21262 return ICEDiag(IK_NotICE, E->getBeginLoc());
21263
21264 case BO_Mul:
21265 case BO_Div:
21266 case BO_Rem:
21267 case BO_Add:
21268 case BO_Sub:
21269 case BO_Shl:
21270 case BO_Shr:
21271 case BO_LT:
21272 case BO_GT:
21273 case BO_LE:
21274 case BO_GE:
21275 case BO_EQ:
21276 case BO_NE:
21277 case BO_And:
21278 case BO_Xor:
21279 case BO_Or:
21280 case BO_Comma:
21281 case BO_Cmp: {
21282 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
21283 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
21284 if (Exp->getOpcode() == BO_Div ||
21285 Exp->getOpcode() == BO_Rem) {
21286 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
21287 // we don't evaluate one.
21288 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
21289 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
21290 if (REval == 0)
21291 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
21292 if (REval.isSigned() && REval.isAllOnes()) {
21293 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
21294 if (LEval.isMinSignedValue())
21295 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
21296 }
21297 }
21298 }
21299 if (Exp->getOpcode() == BO_Comma) {
21300 if (Ctx.getLangOpts().C99) {
21301 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
21302 // if it isn't evaluated.
21303 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
21304 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
21305 } else {
21306 // In both C89 and C++, commas in ICEs are illegal.
21307 return ICEDiag(IK_NotICE, E->getBeginLoc());
21308 }
21309 }
21310 return Worst(LHSResult, RHSResult);
21311 }
21312 case BO_LAnd:
21313 case BO_LOr: {
21314 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
21315 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
21316 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
21317 // Rare case where the RHS has a comma "side-effect"; we need
21318 // to actually check the condition to see whether the side
21319 // with the comma is evaluated.
21320 if ((Exp->getOpcode() == BO_LAnd) !=
21321 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
21322 return RHSResult;
21323 return NoDiag();
21324 }
21325
21326 return Worst(LHSResult, RHSResult);
21327 }
21328 }
21329 llvm_unreachable("invalid binary operator kind");
21330 }
21331 case Expr::ImplicitCastExprClass:
21332 case Expr::CStyleCastExprClass:
21333 case Expr::CXXFunctionalCastExprClass:
21334 case Expr::CXXStaticCastExprClass:
21335 case Expr::CXXReinterpretCastExprClass:
21336 case Expr::CXXConstCastExprClass:
21337 case Expr::ObjCBridgedCastExprClass: {
21338 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
21339 if (isa<ExplicitCastExpr>(E)) {
21340 if (const FloatingLiteral *FL
21341 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
21342 unsigned DestWidth = Ctx.getIntWidth(E->getType());
21343 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
21344 APSInt IgnoredVal(DestWidth, !DestSigned);
21345 bool Ignored;
21346 // If the value does not fit in the destination type, the behavior is
21347 // undefined, so we are not required to treat it as a constant
21348 // expression.
21349 if (FL->getValue().convertToInteger(IgnoredVal,
21350 llvm::APFloat::rmTowardZero,
21351 &Ignored) & APFloat::opInvalidOp)
21352 return ICEDiag(IK_NotICE, E->getBeginLoc());
21353 return NoDiag();
21354 }
21355 }
21356 switch (cast<CastExpr>(E)->getCastKind()) {
21357 case CK_LValueToRValue:
21358 case CK_AtomicToNonAtomic:
21359 case CK_NonAtomicToAtomic:
21360 case CK_NoOp:
21361 case CK_IntegralToBoolean:
21362 case CK_IntegralCast:
21363 return CheckICE(SubExpr, Ctx);
21364 default:
21365 return ICEDiag(IK_NotICE, E->getBeginLoc());
21366 }
21367 }
21368 case Expr::BinaryConditionalOperatorClass: {
21369 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
21370 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
21371 if (CommonResult.Kind == IK_NotICE) return CommonResult;
21372 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
21373 if (FalseResult.Kind == IK_NotICE) return FalseResult;
21374 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
21375 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
21376 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
21377 return FalseResult;
21378 }
21379 case Expr::ConditionalOperatorClass: {
21380 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
21381 // If the condition (ignoring parens) is a __builtin_constant_p call,
21382 // then only the true side is actually considered in an integer constant
21383 // expression, and it is fully evaluated. This is an important GNU
21384 // extension. See GCC PR38377 for discussion.
21385 if (const CallExpr *CallCE
21386 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
21387 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
21388 return CheckEvalInICE(E, Ctx);
21389 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
21390 if (CondResult.Kind == IK_NotICE)
21391 return CondResult;
21392
21393 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
21394 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
21395
21396 if (TrueResult.Kind == IK_NotICE)
21397 return TrueResult;
21398 if (FalseResult.Kind == IK_NotICE)
21399 return FalseResult;
21400 if (CondResult.Kind == IK_ICEIfUnevaluated)
21401 return CondResult;
21402 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
21403 return NoDiag();
21404 // Rare case where the diagnostics depend on which side is evaluated
21405 // Note that if we get here, CondResult is 0, and at least one of
21406 // TrueResult and FalseResult is non-zero.
21407 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
21408 return FalseResult;
21409 return TrueResult;
21410 }
21411 case Expr::CXXDefaultArgExprClass:
21412 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
21413 case Expr::CXXDefaultInitExprClass:
21414 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
21415 case Expr::ChooseExprClass: {
21416 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
21417 }
21418 case Expr::BuiltinBitCastExprClass: {
21419 if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
21420 return ICEDiag(IK_NotICE, E->getBeginLoc());
21421 return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
21422 }
21423 }
21424
21425 llvm_unreachable("Invalid StmtClass!");
21426 }
21427
21428 /// Evaluate an expression as a C++11 integral constant expression.
21429 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
21430 const Expr *E,
21431 llvm::APSInt *Value) {
21432 if (!E->getType()->isIntegralOrUnscopedEnumerationType())
21433 return false;
21434
21435 APValue Result;
21436 if (!E->isCXX11ConstantExpr(Ctx, &Result))
21437 return false;
21438
21439 if (!Result.isInt())
21440 return false;
21441
21442 if (Value) *Value = Result.getInt();
21443 return true;
21444 }
21445
21446 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx) const {
21447 assert(!isValueDependent() &&
21448 "Expression evaluator can't be called on a dependent expression.");
21449
21450 ExprTimeTraceScope TimeScope(this, Ctx, "isIntegerConstantExpr");
21451
21452 if (Ctx.getLangOpts().CPlusPlus11)
21453 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr);
21454
21455 ICEDiag D = CheckICE(this, Ctx);
21456 if (D.Kind != IK_ICE)
21457 return false;
21458 return true;
21459 }
21460
21461 std::optional<llvm::APSInt>
21462 Expr::getIntegerConstantExpr(const ASTContext &Ctx) const {
21463 if (isValueDependent()) {
21464 // Expression evaluator can't succeed on a dependent expression.
21465 return std::nullopt;
21466 }
21467
21468 if (Ctx.getLangOpts().CPlusPlus11) {
21469 APSInt Value;
21470 if (EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value))
21471 return Value;
21472 return std::nullopt;
21473 }
21474
21475 if (!isIntegerConstantExpr(Ctx))
21476 return std::nullopt;
21477
21478 // The only possible side-effects here are due to UB discovered in the
21479 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
21480 // required to treat the expression as an ICE, so we produce the folded
21481 // value.
21482 EvalResult ExprResult;
21483 Expr::EvalStatus Status;
21484 EvalInfo Info(Ctx, Status, EvaluationMode::IgnoreSideEffects);
21485 Info.InConstantContext = true;
21486
21487 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
21488 llvm_unreachable("ICE cannot be evaluated!");
21489
21490 return ExprResult.Val.getInt();
21491 }
21492
21493 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
21494 assert(!isValueDependent() &&
21495 "Expression evaluator can't be called on a dependent expression.");
21496
21497 return CheckICE(this, Ctx).Kind == IK_ICE;
21498 }
21499
21500 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result) const {
21501 assert(!isValueDependent() &&
21502 "Expression evaluator can't be called on a dependent expression.");
21503
21504 // We support this checking in C++98 mode in order to diagnose compatibility
21505 // issues.
21506 assert(Ctx.getLangOpts().CPlusPlus);
21507
21508 bool IsConst;
21509 APValue Scratch;
21510 if (FastEvaluateAsRValue(this, Scratch, Ctx, IsConst) && Scratch.hasValue()) {
21511 if (Result)
21512 *Result = Scratch;
21513 return true;
21514 }
21515
21516 // Build evaluation settings.
21517 Expr::EvalStatus Status;
21518 SmallVector<PartialDiagnosticAt, 8> Diags;
21519 Status.Diag = &Diags;
21520 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantExpression);
21521
21522 bool IsConstExpr =
21523 ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) &&
21524 // FIXME: We don't produce a diagnostic for this, but the callers that
21525 // call us on arbitrary full-expressions should generally not care.
21526 Info.discardCleanups() && !Status.HasSideEffects;
21527
21528 return IsConstExpr && Diags.empty();
21529 }
21530
21531 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
21532 const FunctionDecl *Callee,
21533 ArrayRef<const Expr*> Args,
21534 const Expr *This) const {
21535 assert(!isValueDependent() &&
21536 "Expression evaluator can't be called on a dependent expression.");
21537
21538 llvm::TimeTraceScope TimeScope("EvaluateWithSubstitution", [&] {
21539 std::string Name;
21540 llvm::raw_string_ostream OS(Name);
21541 Callee->getNameForDiagnostic(OS, Ctx.getPrintingPolicy(),
21542 /*Qualified=*/true);
21543 return Name;
21544 });
21545
21546 Expr::EvalStatus Status;
21547 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantExpressionUnevaluated);
21548 Info.InConstantContext = true;
21549
21550 LValue ThisVal;
21551 const LValue *ThisPtr = nullptr;
21552 if (This) {
21553 #ifndef NDEBUG
21554 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
21555 assert(MD && "Don't provide `this` for non-methods.");
21556 assert(MD->isImplicitObjectMemberFunction() &&
21557 "Don't provide `this` for methods without an implicit object.");
21558 #endif
21559 if (!This->isValueDependent() &&
21560 EvaluateObjectArgument(Info, This, ThisVal) &&
21561 !Info.EvalStatus.HasSideEffects)
21562 ThisPtr = &ThisVal;
21563
21564 // Ignore any side-effects from a failed evaluation. This is safe because
21565 // they can't interfere with any other argument evaluation.
21566 Info.EvalStatus.HasSideEffects = false;
21567 }
21568
21569 CallRef Call = Info.CurrentCall->createCall(Callee);
21570 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
21571 I != E; ++I) {
21572 unsigned Idx = I - Args.begin();
21573 if (Idx >= Callee->getNumParams())
21574 break;
21575 const ParmVarDecl *PVD = Callee->getParamDecl(Idx);
21576 if ((*I)->isValueDependent() ||
21577 !EvaluateCallArg(PVD, *I, Call, Info) ||
21578 Info.EvalStatus.HasSideEffects) {
21579 // If evaluation fails, throw away the argument entirely.
21580 if (APValue *Slot = Info.getParamSlot(Call, PVD))
21581 *Slot = APValue();
21582 }
21583
21584 // Ignore any side-effects from a failed evaluation. This is safe because
21585 // they can't interfere with any other argument evaluation.
21586 Info.EvalStatus.HasSideEffects = false;
21587 }
21588
21589 // Parameter cleanups happen in the caller and are not part of this
21590 // evaluation.
21591 Info.discardCleanups();
21592 Info.EvalStatus.HasSideEffects = false;
21593
21594 // Build fake call to Callee.
21595 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, This,
21596 Call);
21597 // FIXME: Missing ExprWithCleanups in enable_if conditions?
21598 FullExpressionRAII Scope(Info);
21599 return Evaluate(Value, Info, this) && Scope.destroy() &&
21600 !Info.EvalStatus.HasSideEffects;
21601 }
21602
21603 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
21604 SmallVectorImpl<
21605 PartialDiagnosticAt> &Diags) {
21606 // FIXME: It would be useful to check constexpr function templates, but at the
21607 // moment the constant expression evaluator cannot cope with the non-rigorous
21608 // ASTs which we build for dependent expressions.
21609 if (FD->isDependentContext())
21610 return true;
21611
21612 llvm::TimeTraceScope TimeScope("isPotentialConstantExpr", [&] {
21613 std::string Name;
21614 llvm::raw_string_ostream OS(Name);
21615 FD->getNameForDiagnostic(OS, FD->getASTContext().getPrintingPolicy(),
21616 /*Qualified=*/true);
21617 return Name;
21618 });
21619
21620 Expr::EvalStatus Status;
21621 Status.Diag = &Diags;
21622
21623 EvalInfo Info(FD->getASTContext(), Status,
21624 EvaluationMode::ConstantExpression);
21625 Info.InConstantContext = true;
21626 Info.CheckingPotentialConstantExpression = true;
21627
21628 // The constexpr VM attempts to compile all methods to bytecode here.
21629 if (Info.EnableNewConstInterp) {
21630 Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD);
21631 return Diags.empty();
21632 }
21633
21634 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
21635 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
21636
21637 // Fabricate an arbitrary expression on the stack and pretend that it
21638 // is a temporary being used as the 'this' pointer.
21639 LValue This;
21640 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getCanonicalTagType(RD)
21641 : Info.Ctx.IntTy);
21642 This.set({&VIE, Info.CurrentCall->Index});
21643
21644 ArrayRef<const Expr*> Args;
21645
21646 APValue Scratch;
21647 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
21648 // Evaluate the call as a constant initializer, to allow the construction
21649 // of objects of non-literal types.
21650 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
21651 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
21652 } else {
21653 SourceLocation Loc = FD->getLocation();
21654 HandleFunctionCall(
21655 Loc, FD, (MD && MD->isImplicitObjectMemberFunction()) ? &This : nullptr,
21656 &VIE, Args, CallRef(), FD->getBody(), Info, Scratch,
21657 /*ResultSlot=*/nullptr);
21658 }
21659
21660 return Diags.empty();
21661 }
21662
21663 bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
21664 const FunctionDecl *FD,
21665 SmallVectorImpl<
21666 PartialDiagnosticAt> &Diags) {
21667 assert(!E->isValueDependent() &&
21668 "Expression evaluator can't be called on a dependent expression.");
21669
21670 Expr::EvalStatus Status;
21671 Status.Diag = &Diags;
21672
21673 EvalInfo Info(FD->getASTContext(), Status,
21674 EvaluationMode::ConstantExpressionUnevaluated);
21675 Info.InConstantContext = true;
21676 Info.CheckingPotentialConstantExpression = true;
21677
21678 if (Info.EnableNewConstInterp) {
21679 Info.Ctx.getInterpContext().isPotentialConstantExprUnevaluated(Info, E, FD);
21680 return Diags.empty();
21681 }
21682
21683 // Fabricate a call stack frame to give the arguments a plausible cover story.
21684 CallStackFrame Frame(Info, SourceLocation(), FD, /*This=*/nullptr,
21685 /*CallExpr=*/nullptr, CallRef());
21686
21687 APValue ResultScratch;
21688 Evaluate(ResultScratch, Info, E);
21689 return Diags.empty();
21690 }
21691
21692 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
21693 unsigned Type) const {
21694 if (!getType()->isPointerType())
21695 return false;
21696
21697 Expr::EvalStatus Status;
21698 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantFold);
21699 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
21700 }
21701
21702 static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,
21703 EvalInfo &Info, std::string *StringResult) {
21704 if (!E->getType()->hasPointerRepresentation() || !E->isPRValue())
21705 return false;
21706
21707 LValue String;
21708
21709 if (!EvaluatePointer(E, String, Info))
21710 return false;
21711
21712 QualType CharTy = E->getType()->getPointeeType();
21713
21714 // Fast path: if it's a string literal, search the string value.
21715 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
21716 String.getLValueBase().dyn_cast<const Expr *>())) {
21717 StringRef Str = S->getBytes();
21718 int64_t Off = String.Offset.getQuantity();
21719 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
21720 S->getCharByteWidth() == 1 &&
21721 // FIXME: Add fast-path for wchar_t too.
21722 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
21723 Str = Str.substr(Off);
21724
21725 StringRef::size_type Pos = Str.find(0);
21726 if (Pos != StringRef::npos)
21727 Str = Str.substr(0, Pos);
21728
21729 Result = Str.size();
21730 if (StringResult)
21731 *StringResult = Str;
21732 return true;
21733 }
21734
21735 // Fall through to slow path.
21736 }
21737
21738 // Slow path: scan the bytes of the string looking for the terminating 0.
21739 for (uint64_t Strlen = 0; /**/; ++Strlen) {
21740 APValue Char;
21741 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
21742 !Char.isInt())
21743 return false;
21744 if (!Char.getInt()) {
21745 Result = Strlen;
21746 return true;
21747 } else if (StringResult)
21748 StringResult->push_back(Char.getInt().getExtValue());
21749 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
21750 return false;
21751 }
21752 }
21753
21754 std::optional<std::string> Expr::tryEvaluateString(ASTContext &Ctx) const {
21755 Expr::EvalStatus Status;
21756 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantFold);
21757 uint64_t Result;
21758 std::string StringResult;
21759
21760 if (Info.EnableNewConstInterp) {
21761 if (!Info.Ctx.getInterpContext().evaluateString(Info, this, StringResult))
21762 return std::nullopt;
21763 return StringResult;
21764 }
21765
21766 if (EvaluateBuiltinStrLen(this, Result, Info, &StringResult))
21767 return StringResult;
21768 return std::nullopt;
21769 }
21770
21771 template <typename T>
21772 static bool EvaluateCharRangeAsStringImpl(const Expr *, T &Result,
21773 const Expr *SizeExpression,
21774 const Expr *PtrExpression,
21775 ASTContext &Ctx,
21776 Expr::EvalResult &Status) {
21777 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantExpression);
21778 Info.InConstantContext = true;
21779
21780 if (Info.EnableNewConstInterp)
21781 return Info.Ctx.getInterpContext().evaluateCharRange(Info, SizeExpression,
21782 PtrExpression, Result);
21783
21784 LValue String;
21785 FullExpressionRAII Scope(Info);
21786 APSInt SizeValue;
21787 if (!::EvaluateInteger(SizeExpression, SizeValue, Info))
21788 return false;
21789
21790 uint64_t Size = SizeValue.getZExtValue();
21791
21792 // FIXME: better protect against invalid or excessive sizes
21793 if constexpr (std::is_same_v<APValue, T>)
21794 Result = APValue(APValue::UninitArray{}, Size, Size);
21795 else {
21796 if (Size < Result.max_size())
21797 Result.reserve(Size);
21798 }
21799 if (!::EvaluatePointer(PtrExpression, String, Info))
21800 return false;
21801
21802 QualType CharTy = PtrExpression->getType()->getPointeeType();
21803 for (uint64_t I = 0; I < Size; ++I) {
21804 APValue Char;
21805 if (!handleLValueToRValueConversion(Info, PtrExpression, CharTy, String,
21806 Char))
21807 return false;
21808
21809 if constexpr (std::is_same_v<APValue, T>) {
21810 Result.getArrayInitializedElt(I) = std::move(Char);
21811 } else {
21812 APSInt C = Char.getInt();
21813
21814 assert(C.getBitWidth() <= 8 &&
21815 "string element not representable in char");
21816
21817 Result.push_back(static_cast<char>(C.getExtValue()));
21818 }
21819
21820 if (!HandleLValueArrayAdjustment(Info, PtrExpression, String, CharTy, 1))
21821 return false;
21822 }
21823
21824 return Scope.destroy() && CheckMemoryLeaks(Info);
21825 }
21826
21827 bool Expr::EvaluateCharRangeAsString(std::string &Result,
21828 const Expr *SizeExpression,
21829 const Expr *PtrExpression, ASTContext &Ctx,
21830 EvalResult &Status) const {
21831 return EvaluateCharRangeAsStringImpl(this, Result, SizeExpression,
21832 PtrExpression, Ctx, Status);
21833 }
21834
21835 bool Expr::EvaluateCharRangeAsString(APValue &Result,
21836 const Expr *SizeExpression,
21837 const Expr *PtrExpression, ASTContext &Ctx,
21838 EvalResult &Status) const {
21839 return EvaluateCharRangeAsStringImpl(this, Result, SizeExpression,
21840 PtrExpression, Ctx, Status);
21841 }
21842
21843 bool Expr::tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const {
21844 Expr::EvalStatus Status;
21845 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantFold);
21846
21847 if (Info.EnableNewConstInterp)
21848 return Info.Ctx.getInterpContext().evaluateStrlen(Info, this, Result);
21849
21850 return EvaluateBuiltinStrLen(this, Result, Info);
21851 }
21852
21853 namespace {
21854 struct IsWithinLifetimeHandler {
21855 EvalInfo &Info;
21856 static constexpr AccessKinds AccessKind = AccessKinds::AK_IsWithinLifetime;
21857 using result_type = std::optional<bool>;
21858 std::optional<bool> failed() { return std::nullopt; }
21859 template <typename T>
21860 std::optional<bool> found(T &Subobj, QualType SubobjType) {
21861 return true;
21862 }
21863 };
21864
21865 std::optional<bool> EvaluateBuiltinIsWithinLifetime(IntExprEvaluator &IEE,
21866 const CallExpr *E) {
21867 EvalInfo &Info = IEE.Info;
21868 // Sometimes this is called during some sorts of constant folding / early
21869 // evaluation. These are meant for non-constant expressions and are not
21870 // necessary since this consteval builtin will never be evaluated at runtime.
21871 // Just fail to evaluate when not in a constant context.
21872 if (!Info.InConstantContext)
21873 return std::nullopt;
21874 assert(E->getBuiltinCallee() == Builtin::BI__builtin_is_within_lifetime);
21875 const Expr *Arg = E->getArg(0);
21876 if (Arg->isValueDependent())
21877 return std::nullopt;
21878 LValue Val;
21879 if (!EvaluatePointer(Arg, Val, Info))
21880 return std::nullopt;
21881
21882 if (Val.allowConstexprUnknown())
21883 return true;
21884
21885 auto Error = [&](int Diag) {
21886 bool CalledFromStd = false;
21887 const auto *Callee = Info.CurrentCall->getCallee();
21888 if (Callee && Callee->isInStdNamespace()) {
21889 const IdentifierInfo *Identifier = Callee->getIdentifier();
21890 CalledFromStd = Identifier && Identifier->isStr("is_within_lifetime");
21891 }
21892 Info.CCEDiag(CalledFromStd ? Info.CurrentCall->getCallRange().getBegin()
21893 : E->getExprLoc(),
21894 diag::err_invalid_is_within_lifetime)
21895 << (CalledFromStd ? "std::is_within_lifetime"
21896 : "__builtin_is_within_lifetime")
21897 << Diag;
21898 return std::nullopt;
21899 };
21900 // C++2c [meta.const.eval]p4:
21901 // During the evaluation of an expression E as a core constant expression, a
21902 // call to this function is ill-formed unless p points to an object that is
21903 // usable in constant expressions or whose complete object's lifetime began
21904 // within E.
21905
21906 // Make sure it points to an object
21907 // nullptr does not point to an object
21908 if (Val.isNullPointer() || Val.getLValueBase().isNull())
21909 return Error(0);
21910 QualType T = Val.getLValueBase().getType();
21911 assert(!T->isFunctionType() &&
21912 "Pointers to functions should have been typed as function pointers "
21913 "which would have been rejected earlier");
21914 assert(T->isObjectType());
21915 // Hypothetical array element is not an object
21916 if (Val.getLValueDesignator().isOnePastTheEnd())
21917 return Error(1);
21918 assert(Val.getLValueDesignator().isValidSubobject() &&
21919 "Unchecked case for valid subobject");
21920 // All other ill-formed values should have failed EvaluatePointer, so the
21921 // object should be a pointer to an object that is usable in a constant
21922 // expression or whose complete lifetime began within the expression
21923 CompleteObject CO =
21924 findCompleteObject(Info, E, AccessKinds::AK_IsWithinLifetime, Val, T);
21925 // The lifetime hasn't begun yet if we are still evaluating the
21926 // initializer ([basic.life]p(1.2))
21927 if (Info.EvaluatingDeclValue && CO.Value == Info.EvaluatingDeclValue)
21928 return Error(2);
21929
21930 if (!CO)
21931 return false;
21932 IsWithinLifetimeHandler handler{Info};
21933 return findSubobject(Info, E, CO, Val.getLValueDesignator(), handler);
21934 }
21935 } // namespace