clang 23.0.0git
ExprConstant.cpp
Go to the documentation of this file.
1//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the Expr constant evaluator.
10//
11// Constant expression evaluation produces four main results:
12//
13// * A success/failure flag indicating whether constant folding was successful.
14// This is the 'bool' return value used by most of the code in this file. A
15// 'false' return value indicates that constant folding has failed, and any
16// appropriate diagnostic has already been produced.
17//
18// * An evaluated result, valid only if constant folding has not failed.
19//
20// * A flag indicating if evaluation encountered (unevaluated) side-effects.
21// These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
22// where it is possible to determine the evaluated result regardless.
23//
24// * A set of notes indicating why the evaluation was not a constant expression
25// (under the C++11 / C++1y rules only, at the moment), or, if folding failed
26// too, why the expression could not be folded.
27//
28// If we are checking for a potential constant expression, failure to constant
29// fold a potential constant sub-expression will be indicated by a 'false'
30// return value (the expression could not be folded) and no diagnostic (the
31// expression is not necessarily non-constant).
32//
33//===----------------------------------------------------------------------===//
34
35#include "ByteCode/Context.h"
36#include "ByteCode/Frame.h"
37#include "ByteCode/State.h"
38#include "ExprConstShared.h"
39#include "clang/AST/APValue.h"
41#include "clang/AST/ASTLambda.h"
42#include "clang/AST/Attr.h"
44#include "clang/AST/CharUnits.h"
46#include "clang/AST/Expr.h"
48#include "clang/AST/OSLog.h"
52#include "clang/AST/Type.h"
53#include "clang/AST/TypeLoc.h"
58#include "llvm/ADT/APFixedPoint.h"
59#include "llvm/ADT/Sequence.h"
60#include "llvm/ADT/SmallBitVector.h"
61#include "llvm/ADT/StringExtras.h"
62#include "llvm/Support/Casting.h"
63#include "llvm/Support/Debug.h"
64#include "llvm/Support/SaveAndRestore.h"
65#include "llvm/Support/SipHash.h"
66#include "llvm/Support/TimeProfiler.h"
67#include "llvm/Support/raw_ostream.h"
68#include <cstring>
69#include <functional>
70#include <limits>
71#include <optional>
72
73#define DEBUG_TYPE "exprconstant"
74
75using namespace clang;
76using llvm::APFixedPoint;
77using llvm::APInt;
78using llvm::APSInt;
79using llvm::APFloat;
80using llvm::FixedPointSemantics;
81
82namespace {
83 struct LValue;
84 class CallStackFrame;
85 class EvalInfo;
86
87 using SourceLocExprScopeGuard =
89
91 return B.getType();
92 }
93
94 /// Get an LValue path entry, which is known to not be an array index, as a
95 /// field declaration.
96 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
97 return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer());
98 }
99 /// Get an LValue path entry, which is known to not be an array index, as a
100 /// base class declaration.
101 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
102 return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer());
103 }
104 /// Determine whether this LValue path entry for a base class names a virtual
105 /// base class.
106 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
107 return E.getAsBaseOrMember().getInt();
108 }
109
110 /// Given an expression, determine the type used to store the result of
111 /// evaluating that expression.
112 static QualType getStorageType(const ASTContext &Ctx, const Expr *E) {
113 if (E->isPRValue())
114 return E->getType();
115 return Ctx.getLValueReferenceType(E->getType());
116 }
117
118 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
119 /// This will look through a single cast.
120 ///
121 /// Returns null if we couldn't unwrap a function with alloc_size.
122 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
123 if (!E->getType()->isPointerType())
124 return nullptr;
125
126 E = E->IgnoreParens();
127 // If we're doing a variable assignment from e.g. malloc(N), there will
128 // probably be a cast of some kind. In exotic cases, we might also see a
129 // top-level ExprWithCleanups. Ignore them either way.
130 if (const auto *FE = dyn_cast<FullExpr>(E))
131 E = FE->getSubExpr()->IgnoreParens();
132
133 if (const auto *Cast = dyn_cast<CastExpr>(E))
134 E = Cast->getSubExpr()->IgnoreParens();
135
136 if (const auto *CE = dyn_cast<CallExpr>(E))
137 return CE->getCalleeAllocSizeAttr() ? CE : nullptr;
138 return nullptr;
139 }
140
141 /// Determines whether or not the given Base contains a call to a function
142 /// with the alloc_size attribute.
143 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
144 const auto *E = Base.dyn_cast<const Expr *>();
145 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
146 }
147
148 /// Determines whether the given kind of constant expression is only ever
149 /// used for name mangling. If so, it's permitted to reference things that we
150 /// can't generate code for (in particular, dllimported functions).
151 static bool isForManglingOnly(ConstantExprKind Kind) {
152 switch (Kind) {
153 case ConstantExprKind::Normal:
154 case ConstantExprKind::ClassTemplateArgument:
155 case ConstantExprKind::ImmediateInvocation:
156 // Note that non-type template arguments of class type are emitted as
157 // template parameter objects.
158 return false;
159
160 case ConstantExprKind::NonClassTemplateArgument:
161 return true;
162 }
163 llvm_unreachable("unknown ConstantExprKind");
164 }
165
166 static bool isTemplateArgument(ConstantExprKind Kind) {
167 switch (Kind) {
168 case ConstantExprKind::Normal:
169 case ConstantExprKind::ImmediateInvocation:
170 return false;
171
172 case ConstantExprKind::ClassTemplateArgument:
173 case ConstantExprKind::NonClassTemplateArgument:
174 return true;
175 }
176 llvm_unreachable("unknown ConstantExprKind");
177 }
178
179 /// The bound to claim that an array of unknown bound has.
180 /// The value in MostDerivedArraySize is undefined in this case. So, set it
181 /// to an arbitrary value that's likely to loudly break things if it's used.
182 static const uint64_t AssumedSizeForUnsizedArray =
183 std::numeric_limits<uint64_t>::max() / 2;
184
185 /// Determines if an LValue with the given LValueBase will have an unsized
186 /// array in its designator.
187 /// Find the path length and type of the most-derived subobject in the given
188 /// path, and find the size of the containing array, if any.
189 static unsigned
190 findMostDerivedSubobject(const ASTContext &Ctx, APValue::LValueBase Base,
192 uint64_t &ArraySize, QualType &Type, bool &IsArray,
193 bool &FirstEntryIsUnsizedArray) {
194 // This only accepts LValueBases from APValues, and APValues don't support
195 // arrays that lack size info.
196 assert(!isBaseAnAllocSizeCall(Base) &&
197 "Unsized arrays shouldn't appear here");
198 unsigned MostDerivedLength = 0;
199 // The type of Base is a reference type if the base is a constexpr-unknown
200 // variable. In that case, look through the reference type.
201 Type = getType(Base).getNonReferenceType();
202
203 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
204 if (Type->isArrayType()) {
205 const ArrayType *AT = Ctx.getAsArrayType(Type);
206 Type = AT->getElementType();
207 MostDerivedLength = I + 1;
208 IsArray = true;
209
210 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
211 ArraySize = CAT->getZExtSize();
212 } else {
213 assert(I == 0 && "unexpected unsized array designator");
214 FirstEntryIsUnsizedArray = true;
215 ArraySize = AssumedSizeForUnsizedArray;
216 }
217 } else if (Type->isAnyComplexType()) {
218 const ComplexType *CT = Type->castAs<ComplexType>();
219 Type = CT->getElementType();
220 ArraySize = 2;
221 MostDerivedLength = I + 1;
222 IsArray = true;
223 } else if (const auto *VT = Type->getAs<VectorType>()) {
224 Type = VT->getElementType();
225 ArraySize = VT->getNumElements();
226 MostDerivedLength = I + 1;
227 IsArray = true;
228 } else if (const FieldDecl *FD = getAsField(Path[I])) {
229 Type = FD->getType();
230 ArraySize = 0;
231 MostDerivedLength = I + 1;
232 IsArray = false;
233 } else {
234 // Path[I] describes a base class.
235 ArraySize = 0;
236 IsArray = false;
237 }
238 }
239 return MostDerivedLength;
240 }
241
242 /// A path from a glvalue to a subobject of that glvalue.
243 struct SubobjectDesignator {
244 /// True if the subobject was named in a manner not supported by C++11. Such
245 /// lvalues can still be folded, but they are not core constant expressions
246 /// and we cannot perform lvalue-to-rvalue conversions on them.
247 LLVM_PREFERRED_TYPE(bool)
248 unsigned Invalid : 1;
249
250 /// Is this a pointer one past the end of an object?
251 LLVM_PREFERRED_TYPE(bool)
252 unsigned IsOnePastTheEnd : 1;
253
254 /// Indicator of whether the first entry is an unsized array.
255 LLVM_PREFERRED_TYPE(bool)
256 unsigned FirstEntryIsAnUnsizedArray : 1;
257
258 /// Indicator of whether the most-derived object is an array element.
259 LLVM_PREFERRED_TYPE(bool)
260 unsigned MostDerivedIsArrayElement : 1;
261
262 /// The length of the path to the most-derived object of which this is a
263 /// subobject.
264 unsigned MostDerivedPathLength : 28;
265
266 /// The size of the array of which the most-derived object is an element.
267 /// This will always be 0 if the most-derived object is not an array
268 /// element. 0 is not an indicator of whether or not the most-derived object
269 /// is an array, however, because 0-length arrays are allowed.
270 ///
271 /// If the current array is an unsized array, the value of this is
272 /// undefined.
273 uint64_t MostDerivedArraySize;
274 /// The type of the most derived object referred to by this address.
275 QualType MostDerivedType;
276
277 typedef APValue::LValuePathEntry PathEntry;
278
279 /// The entries on the path from the glvalue to the designated subobject.
281
282 SubobjectDesignator() : Invalid(true) {}
283
284 explicit SubobjectDesignator(QualType T)
285 : Invalid(false), IsOnePastTheEnd(false),
286 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
287 MostDerivedPathLength(0), MostDerivedArraySize(0),
288 MostDerivedType(T.isNull() ? QualType() : T.getNonReferenceType()) {}
289
290 SubobjectDesignator(const ASTContext &Ctx, const APValue &V)
291 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
292 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
293 MostDerivedPathLength(0), MostDerivedArraySize(0) {
294 assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
295 if (!Invalid) {
296 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
297 llvm::append_range(Entries, V.getLValuePath());
298 if (V.getLValueBase()) {
299 bool IsArray = false;
300 bool FirstIsUnsizedArray = false;
301 MostDerivedPathLength = findMostDerivedSubobject(
302 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
303 MostDerivedType, IsArray, FirstIsUnsizedArray);
304 MostDerivedIsArrayElement = IsArray;
305 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
306 }
307 }
308 }
309
310 void truncate(ASTContext &Ctx, APValue::LValueBase Base,
311 unsigned NewLength) {
312 if (Invalid)
313 return;
314
315 assert(Base && "cannot truncate path for null pointer");
316 assert(NewLength <= Entries.size() && "not a truncation");
317
318 if (NewLength == Entries.size())
319 return;
320 Entries.resize(NewLength);
321
322 bool IsArray = false;
323 bool FirstIsUnsizedArray = false;
324 MostDerivedPathLength = findMostDerivedSubobject(
325 Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray,
326 FirstIsUnsizedArray);
327 MostDerivedIsArrayElement = IsArray;
328 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
329 }
330
331 void setInvalid() {
332 Invalid = true;
333 Entries.clear();
334 }
335
336 /// Determine whether the most derived subobject is an array without a
337 /// known bound.
338 bool isMostDerivedAnUnsizedArray() const {
339 assert(!Invalid && "Calling this makes no sense on invalid designators");
340 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
341 }
342
343 /// Determine what the most derived array's size is. Results in an assertion
344 /// failure if the most derived array lacks a size.
345 uint64_t getMostDerivedArraySize() const {
346 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
347 return MostDerivedArraySize;
348 }
349
350 /// Determine whether this is a one-past-the-end pointer.
351 bool isOnePastTheEnd() const {
352 assert(!Invalid);
353 if (IsOnePastTheEnd)
354 return true;
355 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
356 Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==
357 MostDerivedArraySize)
358 return true;
359 return false;
360 }
361
362 /// Get the range of valid index adjustments in the form
363 /// {maximum value that can be subtracted from this pointer,
364 /// maximum value that can be added to this pointer}
365 std::pair<uint64_t, uint64_t> validIndexAdjustments() {
366 if (Invalid || isMostDerivedAnUnsizedArray())
367 return {0, 0};
368
369 // [expr.add]p4: For the purposes of these operators, a pointer to a
370 // nonarray object behaves the same as a pointer to the first element of
371 // an array of length one with the type of the object as its element type.
372 bool IsArray = MostDerivedPathLength == Entries.size() &&
373 MostDerivedIsArrayElement;
374 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
375 : (uint64_t)IsOnePastTheEnd;
376 uint64_t ArraySize =
377 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
378 return {ArrayIndex, ArraySize - ArrayIndex};
379 }
380
381 /// Check that this refers to a valid subobject.
382 bool isValidSubobject() const {
383 if (Invalid)
384 return false;
385 return !isOnePastTheEnd();
386 }
387 /// Check that this refers to a valid subobject, and if not, produce a
388 /// relevant diagnostic and set the designator as invalid.
389 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
390
391 /// Get the type of the designated object.
392 QualType getType(ASTContext &Ctx) const {
393 assert(!Invalid && "invalid designator has no subobject type");
394 return MostDerivedPathLength == Entries.size()
395 ? MostDerivedType
396 : Ctx.getCanonicalTagType(getAsBaseClass(Entries.back()));
397 }
398
399 /// Update this designator to refer to the first element within this array.
400 void addArrayUnchecked(const ConstantArrayType *CAT) {
401 Entries.push_back(PathEntry::ArrayIndex(0));
402
403 // This is a most-derived object.
404 MostDerivedType = CAT->getElementType();
405 MostDerivedIsArrayElement = true;
406 MostDerivedArraySize = CAT->getZExtSize();
407 MostDerivedPathLength = Entries.size();
408 }
409 /// Update this designator to refer to the first element within the array of
410 /// elements of type T. This is an array of unknown size.
411 void addUnsizedArrayUnchecked(QualType ElemTy) {
412 Entries.push_back(PathEntry::ArrayIndex(0));
413
414 MostDerivedType = ElemTy;
415 MostDerivedIsArrayElement = true;
416 // The value in MostDerivedArraySize is undefined in this case. So, set it
417 // to an arbitrary value that's likely to loudly break things if it's
418 // used.
419 MostDerivedArraySize = AssumedSizeForUnsizedArray;
420 MostDerivedPathLength = Entries.size();
421 }
422 /// Update this designator to refer to the given base or member of this
423 /// object.
424 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
425 Entries.push_back(APValue::BaseOrMemberType(D, Virtual));
426
427 // If this isn't a base class, it's a new most-derived object.
428 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
429 MostDerivedType = FD->getType();
430 MostDerivedIsArrayElement = false;
431 MostDerivedArraySize = 0;
432 MostDerivedPathLength = Entries.size();
433 }
434 }
435 /// Update this designator to refer to the given complex component.
436 void addComplexUnchecked(QualType EltTy, bool Imag) {
437 Entries.push_back(PathEntry::ArrayIndex(Imag));
438
439 // This is technically a most-derived object, though in practice this
440 // is unlikely to matter.
441 MostDerivedType = EltTy;
442 MostDerivedIsArrayElement = true;
443 MostDerivedArraySize = 2;
444 MostDerivedPathLength = Entries.size();
445 }
446
447 void addVectorElementUnchecked(QualType EltTy, uint64_t Size,
448 uint64_t Idx) {
449 Entries.push_back(PathEntry::ArrayIndex(Idx));
450 MostDerivedType = EltTy;
451 MostDerivedPathLength = Entries.size();
452 MostDerivedArraySize = 0;
453 MostDerivedIsArrayElement = false;
454 }
455
456 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
457 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
458 const APSInt &N);
459 /// Add N to the address of this subobject.
460 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N, const LValue &LV);
461 };
462
463 /// A scope at the end of which an object can need to be destroyed.
464 enum class ScopeKind {
465 Block,
466 FullExpression,
467 Call
468 };
469
470 /// A reference to a particular call and its arguments.
471 struct CallRef {
472 CallRef() : OrigCallee(), CallIndex(0), Version() {}
473 CallRef(const FunctionDecl *Callee, unsigned CallIndex, unsigned Version)
474 : OrigCallee(Callee), CallIndex(CallIndex), Version(Version) {}
475
476 explicit operator bool() const { return OrigCallee; }
477
478 /// Get the parameter that the caller initialized, corresponding to the
479 /// given parameter in the callee.
480 const ParmVarDecl *getOrigParam(const ParmVarDecl *PVD) const {
481 return OrigCallee ? OrigCallee->getParamDecl(PVD->getFunctionScopeIndex())
482 : PVD;
483 }
484
485 /// The callee at the point where the arguments were evaluated. This might
486 /// be different from the actual callee (a different redeclaration, or a
487 /// virtual override), but this function's parameters are the ones that
488 /// appear in the parameter map.
489 const FunctionDecl *OrigCallee;
490 /// The call index of the frame that holds the argument values.
491 unsigned CallIndex;
492 /// The version of the parameters corresponding to this call.
493 unsigned Version;
494 };
495
496 /// A stack frame in the constexpr call stack.
497 class CallStackFrame : public interp::Frame {
498 public:
499 EvalInfo &Info;
500
501 /// Parent - The caller of this stack frame.
502 CallStackFrame *Caller;
503
504 /// Callee - The function which was called.
505 const FunctionDecl *Callee;
506
507 /// This - The binding for the this pointer in this call, if any.
508 const LValue *This;
509
510 /// CallExpr - The syntactical structure of member function calls
511 const Expr *CallExpr;
512
513 /// Information on how to find the arguments to this call. Our arguments
514 /// are stored in our parent's CallStackFrame, using the ParmVarDecl* as a
515 /// key and this value as the version.
516 CallRef Arguments;
517
518 /// Source location information about the default argument or default
519 /// initializer expression we're evaluating, if any.
520 CurrentSourceLocExprScope CurSourceLocExprScope;
521
522 // Note that we intentionally use std::map here so that references to
523 // values are stable.
524 typedef std::pair<const void *, unsigned> MapKeyTy;
525 typedef std::map<MapKeyTy, APValue> MapTy;
526 /// Temporaries - Temporary lvalues materialized within this stack frame.
527 MapTy Temporaries;
528
529 /// CallRange - The source range of the call expression for this call.
530 SourceRange CallRange;
531
532 /// Index - The call index of this call.
533 unsigned Index;
534
535 /// The stack of integers for tracking version numbers for temporaries.
536 SmallVector<unsigned, 2> TempVersionStack = {1};
537 unsigned CurTempVersion = TempVersionStack.back();
538
539 unsigned getTempVersion() const { return TempVersionStack.back(); }
540
541 void pushTempVersion() {
542 TempVersionStack.push_back(++CurTempVersion);
543 }
544
545 void popTempVersion() {
546 TempVersionStack.pop_back();
547 }
548
549 CallRef createCall(const FunctionDecl *Callee) {
550 return {Callee, Index, ++CurTempVersion};
551 }
552
553 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
554 // on the overall stack usage of deeply-recursing constexpr evaluations.
555 // (We should cache this map rather than recomputing it repeatedly.)
556 // But let's try this and see how it goes; we can look into caching the map
557 // as a later change.
558
559 /// LambdaCaptureFields - Mapping from captured variables/this to
560 /// corresponding data members in the closure class.
561 llvm::DenseMap<const ValueDecl *, FieldDecl *> LambdaCaptureFields;
562 FieldDecl *LambdaThisCaptureField = nullptr;
563
564 CallStackFrame(EvalInfo &Info, SourceRange CallRange,
565 const FunctionDecl *Callee, const LValue *This,
566 const Expr *CallExpr, CallRef Arguments);
567 ~CallStackFrame();
568
569 // Return the temporary for Key whose version number is Version.
570 APValue *getTemporary(const void *Key, unsigned Version) {
571 MapKeyTy KV(Key, Version);
572 auto LB = Temporaries.lower_bound(KV);
573 if (LB != Temporaries.end() && LB->first == KV)
574 return &LB->second;
575 return nullptr;
576 }
577
578 // Return the current temporary for Key in the map.
579 APValue *getCurrentTemporary(const void *Key) {
580 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
581 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
582 return &std::prev(UB)->second;
583 return nullptr;
584 }
585
586 // Return the version number of the current temporary for Key.
587 unsigned getCurrentTemporaryVersion(const void *Key) const {
588 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
589 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
590 return std::prev(UB)->first.second;
591 return 0;
592 }
593
594 /// Allocate storage for an object of type T in this stack frame.
595 /// Populates LV with a handle to the created object. Key identifies
596 /// the temporary within the stack frame, and must not be reused without
597 /// bumping the temporary version number.
598 template<typename KeyT>
599 APValue &createTemporary(const KeyT *Key, QualType T,
600 ScopeKind Scope, LValue &LV);
601
602 /// Allocate storage for a parameter of a function call made in this frame.
603 APValue &createParam(CallRef Args, const ParmVarDecl *PVD, LValue &LV);
604
605 void describe(llvm::raw_ostream &OS) const override;
606
607 Frame *getCaller() const override { return Caller; }
608 SourceRange getCallRange() const override { return CallRange; }
609 const FunctionDecl *getCallee() const override { return Callee; }
610
611 bool isStdFunction() const {
612 for (const DeclContext *DC = Callee; DC; DC = DC->getParent())
613 if (DC->isStdNamespace())
614 return true;
615 return false;
616 }
617
618 /// Whether we're in a context where [[msvc::constexpr]] evaluation is
619 /// permitted. See MSConstexprDocs for description of permitted contexts.
620 bool CanEvalMSConstexpr = false;
621
622 private:
623 APValue &createLocal(APValue::LValueBase Base, const void *Key, QualType T,
624 ScopeKind Scope);
625 };
626
627 /// Temporarily override 'this'.
628 class ThisOverrideRAII {
629 public:
630 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
631 : Frame(Frame), OldThis(Frame.This) {
632 if (Enable)
633 Frame.This = NewThis;
634 }
635 ~ThisOverrideRAII() {
636 Frame.This = OldThis;
637 }
638 private:
639 CallStackFrame &Frame;
640 const LValue *OldThis;
641 };
642
643 // A shorthand time trace scope struct, prints source range, for example
644 // {"name":"EvaluateAsRValue","args":{"detail":"<test.cc:8:21, col:25>"}}}
645 class ExprTimeTraceScope {
646 public:
647 ExprTimeTraceScope(const Expr *E, const ASTContext &Ctx, StringRef Name)
648 : TimeScope(Name, [E, &Ctx] {
650 }) {}
651
652 private:
653 llvm::TimeTraceScope TimeScope;
654 };
655
656 /// RAII object used to change the current ability of
657 /// [[msvc::constexpr]] evaulation.
658 struct MSConstexprContextRAII {
659 CallStackFrame &Frame;
660 bool OldValue;
661 explicit MSConstexprContextRAII(CallStackFrame &Frame, bool Value)
662 : Frame(Frame), OldValue(Frame.CanEvalMSConstexpr) {
663 Frame.CanEvalMSConstexpr = Value;
664 }
665
666 ~MSConstexprContextRAII() { Frame.CanEvalMSConstexpr = OldValue; }
667 };
668}
669
670static bool HandleDestruction(EvalInfo &Info, const Expr *E,
671 const LValue &This, QualType ThisType);
672static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
674 QualType T);
675
676namespace {
677 /// A cleanup, and a flag indicating whether it is lifetime-extended.
678 class Cleanup {
679 llvm::PointerIntPair<APValue*, 2, ScopeKind> Value;
680 APValue::LValueBase Base;
681 QualType T;
682
683 public:
684 Cleanup(APValue *Val, APValue::LValueBase Base, QualType T,
685 ScopeKind Scope)
686 : Value(Val, Scope), Base(Base), T(T) {}
687
688 /// Determine whether this cleanup should be performed at the end of the
689 /// given kind of scope.
690 bool isDestroyedAtEndOf(ScopeKind K) const {
691 return (int)Value.getInt() >= (int)K;
692 }
693 bool endLifetime(EvalInfo &Info, bool RunDestructors) {
694 if (RunDestructors) {
695 SourceLocation Loc;
696 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>())
697 Loc = VD->getLocation();
698 else if (const Expr *E = Base.dyn_cast<const Expr*>())
699 Loc = E->getExprLoc();
700 return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T);
701 }
702 *Value.getPointer() = APValue();
703 return true;
704 }
705
706 bool hasSideEffect() {
707 return T.isDestructedType();
708 }
709 };
710
711 /// A reference to an object whose construction we are currently evaluating.
712 struct ObjectUnderConstruction {
713 APValue::LValueBase Base;
714 ArrayRef<APValue::LValuePathEntry> Path;
715 friend bool operator==(const ObjectUnderConstruction &LHS,
716 const ObjectUnderConstruction &RHS) {
717 return LHS.Base == RHS.Base && LHS.Path == RHS.Path;
718 }
719 friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {
720 return llvm::hash_combine(Obj.Base, Obj.Path);
721 }
722 };
723 enum class ConstructionPhase {
724 None,
725 Bases,
726 AfterBases,
727 AfterFields,
728 Destroying,
729 DestroyingBases
730 };
731}
732
733namespace llvm {
734template<> struct DenseMapInfo<ObjectUnderConstruction> {
735 using Base = DenseMapInfo<APValue::LValueBase>;
736 static ObjectUnderConstruction getEmptyKey() {
737 return {Base::getEmptyKey(), {}}; }
738 static ObjectUnderConstruction getTombstoneKey() {
739 return {Base::getTombstoneKey(), {}};
740 }
741 static unsigned getHashValue(const ObjectUnderConstruction &Object) {
742 return hash_value(Object);
743 }
744 static bool isEqual(const ObjectUnderConstruction &LHS,
745 const ObjectUnderConstruction &RHS) {
746 return LHS == RHS;
747 }
748};
749}
750
751namespace {
752 /// A dynamically-allocated heap object.
753 struct DynAlloc {
754 /// The value of this heap-allocated object.
755 APValue Value;
756 /// The allocating expression; used for diagnostics. Either a CXXNewExpr
757 /// or a CallExpr (the latter is for direct calls to operator new inside
758 /// std::allocator<T>::allocate).
759 const Expr *AllocExpr = nullptr;
760
761 enum Kind {
762 New,
763 ArrayNew,
764 StdAllocator
765 };
766
767 /// Get the kind of the allocation. This must match between allocation
768 /// and deallocation.
769 Kind getKind() const {
770 if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr))
771 return NE->isArray() ? ArrayNew : New;
772 assert(isa<CallExpr>(AllocExpr));
773 return StdAllocator;
774 }
775 };
776
777 struct DynAllocOrder {
778 bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const {
779 return L.getIndex() < R.getIndex();
780 }
781 };
782
783 /// EvalInfo - This is a private struct used by the evaluator to capture
784 /// information about a subexpression as it is folded. It retains information
785 /// about the AST context, but also maintains information about the folded
786 /// expression.
787 ///
788 /// If an expression could be evaluated, it is still possible it is not a C
789 /// "integer constant expression" or constant expression. If not, this struct
790 /// captures information about how and why not.
791 ///
792 /// One bit of information passed *into* the request for constant folding
793 /// indicates whether the subexpression is "evaluated" or not according to C
794 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
795 /// evaluate the expression regardless of what the RHS is, but C only allows
796 /// certain things in certain situations.
797 class EvalInfo : 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
1391bool 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
1407void 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
1414void 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
1429CallStackFrame::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
1439CallStackFrame::~CallStackFrame() {
1440 assert(Info.CurrentCall == this && "calls retired out of order");
1441 --Info.CallStackDepth;
1442 Info.CurrentCall = Caller;
1443}
1444
1445static bool isRead(AccessKinds AK) {
1446 return AK == AK_Read || AK == AK_ReadObjectRepresentation ||
1447 AK == AK_IsWithinLifetime || AK == AK_Dereference;
1448}
1449
1451 switch (AK) {
1452 case AK_Read:
1454 case AK_MemberCall:
1455 case AK_DynamicCast:
1456 case AK_TypeId:
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
1470static bool isAnyAccess(AccessKinds AK) {
1471 return isRead(AK) || isModification(AK);
1472}
1473
1474/// Is this an access per the C++ definition?
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?
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
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
1507namespace {
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 =
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
1825void 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
1873static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1874static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1875 const LValue &This, const Expr *E,
1876 bool AllowNonLiteralTypes = false);
1877static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1878 bool InvalidBaseOK = false);
1879static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1880 bool InvalidBaseOK = false);
1881static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1882 EvalInfo &Info);
1883static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1884static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1885static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1886 EvalInfo &Info);
1887static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1888static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1889static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1890 EvalInfo &Info);
1891static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1892static 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.
1897static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1898 EvalInfo &Info);
1899
1900/// Evaluate only a fixed point expression into an APResult.
1901static 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).
1910static 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
1918template<typename KeyT>
1919APValue &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.
1928APValue &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
1939APValue &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
1959APValue *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++);
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.
1975void CallStackFrame::describe(raw_ostream &Out) const {
1976 bool IsMemberCall = false;
1977 bool ExplicitInstanceParam = false;
1978 if (const auto *MD = dyn_cast<CXXMethodDecl>(Callee)) {
1979 IsMemberCall = !isa<CXXConstructorDecl>(MD) && !MD->isStatic();
1980 ExplicitInstanceParam = MD->isExplicitObjectMemberFunction();
1981 }
1982
1983 if (!IsMemberCall)
1984 Callee->getNameForDiagnostic(Out, Info.Ctx.getPrintingPolicy(),
1985 /*Qualified=*/false);
1986
1987 if (This && IsMemberCall) {
1988 if (const auto *MCE = dyn_cast_if_present<CXXMemberCallExpr>(CallExpr)) {
1989 const Expr *Object = MCE->getImplicitObjectArgument();
1990 Object->printPretty(Out, /*Helper=*/nullptr, Info.Ctx.getPrintingPolicy(),
1991 /*Indentation=*/0);
1992 if (Object->getType()->isPointerType())
1993 Out << "->";
1994 else
1995 Out << ".";
1996 } else if (const auto *OCE =
1997 dyn_cast_if_present<CXXOperatorCallExpr>(CallExpr)) {
1998 OCE->getArg(0)->printPretty(Out, /*Helper=*/nullptr,
1999 Info.Ctx.getPrintingPolicy(),
2000 /*Indentation=*/0);
2001 Out << ".";
2002 } else {
2003 APValue Val;
2004 This->moveInto(Val);
2005 Val.printPretty(
2006 Out, Info.Ctx,
2007 Info.Ctx.getLValueReferenceType(This->Designator.MostDerivedType));
2008 Out << ".";
2009 }
2010 Callee->getNameForDiagnostic(Out, Info.Ctx.getPrintingPolicy(),
2011 /*Qualified=*/false);
2012 }
2013
2014 Out << '(';
2015
2016 llvm::ListSeparator Comma;
2017 for (const ParmVarDecl *Param :
2018 Callee->parameters().slice(ExplicitInstanceParam)) {
2019 Out << Comma;
2020 const APValue *V = Info.getParamSlot(Arguments, Param);
2021 if (V)
2022 V->printPretty(Out, Info.Ctx, Param->getType());
2023 else
2024 Out << "<...>";
2025 }
2026
2027 Out << ')';
2028}
2029
2030/// Evaluate an expression to see if it had side-effects, and discard its
2031/// result.
2032/// \return \c true if the caller should keep evaluating.
2033static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
2034 assert(!E->isValueDependent());
2035 APValue Scratch;
2036 if (!Evaluate(Scratch, Info, E))
2037 // We don't need the value, but we might have skipped a side effect here.
2038 return Info.noteSideEffect();
2039 return true;
2040}
2041
2042/// Should this call expression be treated as forming an opaque constant?
2043static bool IsOpaqueConstantCall(const CallExpr *E) {
2044 unsigned Builtin = E->getBuiltinCallee();
2045 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
2046 Builtin == Builtin::BI__builtin___NSStringMakeConstantString ||
2047 Builtin == Builtin::BI__builtin_ptrauth_sign_constant ||
2048 Builtin == Builtin::BI__builtin_function_start);
2049}
2050
2051static bool IsOpaqueConstantCall(const LValue &LVal) {
2052 const auto *BaseExpr =
2053 llvm::dyn_cast_if_present<CallExpr>(LVal.Base.dyn_cast<const Expr *>());
2054 return BaseExpr && IsOpaqueConstantCall(BaseExpr);
2055}
2056
2058 // C++11 [expr.const]p3 An address constant expression is a prvalue core
2059 // constant expression of pointer type that evaluates to...
2060
2061 // ... a null pointer value, or a prvalue core constant expression of type
2062 // std::nullptr_t.
2063 if (!B)
2064 return true;
2065
2066 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
2067 // ... the address of an object with static storage duration,
2068 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
2069 return VD->hasGlobalStorage();
2071 return true;
2072 // ... the address of a function,
2073 // ... the address of a GUID [MS extension],
2074 // ... the address of an unnamed global constant
2076 }
2077
2078 if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>())
2079 return true;
2080
2081 const Expr *E = B.get<const Expr*>();
2082 switch (E->getStmtClass()) {
2083 default:
2084 return false;
2085 case Expr::CompoundLiteralExprClass: {
2087 return CLE->isFileScope() && CLE->isLValue();
2088 }
2089 case Expr::MaterializeTemporaryExprClass:
2090 // A materialized temporary might have been lifetime-extended to static
2091 // storage duration.
2092 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
2093 // A string literal has static storage duration.
2094 case Expr::StringLiteralClass:
2095 case Expr::PredefinedExprClass:
2096 case Expr::ObjCStringLiteralClass:
2097 case Expr::ObjCEncodeExprClass:
2098 return true;
2099 case Expr::ObjCBoxedExprClass:
2100 return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
2101 case Expr::CallExprClass:
2103 // For GCC compatibility, &&label has static storage duration.
2104 case Expr::AddrLabelExprClass:
2105 return true;
2106 // A Block literal expression may be used as the initialization value for
2107 // Block variables at global or local static scope.
2108 case Expr::BlockExprClass:
2109 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
2110 // The APValue generated from a __builtin_source_location will be emitted as a
2111 // literal.
2112 case Expr::SourceLocExprClass:
2113 return true;
2114 case Expr::ImplicitValueInitExprClass:
2115 // FIXME:
2116 // We can never form an lvalue with an implicit value initialization as its
2117 // base through expression evaluation, so these only appear in one case: the
2118 // implicit variable declaration we invent when checking whether a constexpr
2119 // constructor can produce a constant expression. We must assume that such
2120 // an expression might be a global lvalue.
2121 return true;
2122 }
2123}
2124
2125static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
2126 return LVal.Base.dyn_cast<const ValueDecl*>();
2127}
2128
2129// Information about an LValueBase that is some kind of string.
2132 StringRef Bytes;
2134};
2135
2136// Gets the lvalue base of LVal as a string.
2137static bool GetLValueBaseAsString(const EvalInfo &Info, const LValue &LVal,
2138 LValueBaseString &AsString) {
2139 const auto *BaseExpr = LVal.Base.dyn_cast<const Expr *>();
2140 if (!BaseExpr)
2141 return false;
2142
2143 // For ObjCEncodeExpr, we need to compute and store the string.
2144 if (const auto *EE = dyn_cast<ObjCEncodeExpr>(BaseExpr)) {
2145 Info.Ctx.getObjCEncodingForType(EE->getEncodedType(),
2146 AsString.ObjCEncodeStorage);
2147 AsString.Bytes = AsString.ObjCEncodeStorage;
2148 AsString.CharWidth = 1;
2149 return true;
2150 }
2151
2152 // Otherwise, we have a StringLiteral.
2153 const auto *Lit = dyn_cast<StringLiteral>(BaseExpr);
2154 if (const auto *PE = dyn_cast<PredefinedExpr>(BaseExpr))
2155 Lit = PE->getFunctionName();
2156
2157 if (!Lit)
2158 return false;
2159
2160 AsString.Bytes = Lit->getBytes();
2161 AsString.CharWidth = Lit->getCharByteWidth();
2162 return true;
2163}
2164
2165// Determine whether two string literals potentially overlap. This will be the
2166// case if they agree on the values of all the bytes on the overlapping region
2167// between them.
2168//
2169// The overlapping region is the portion of the two string literals that must
2170// overlap in memory if the pointers actually point to the same address at
2171// runtime. For example, if LHS is "abcdef" + 3 and RHS is "cdef\0gh" + 1 then
2172// the overlapping region is "cdef\0", which in this case does agree, so the
2173// strings are potentially overlapping. Conversely, for "foobar" + 3 versus
2174// "bazbar" + 3, the overlapping region contains all of both strings, so they
2175// are not potentially overlapping, even though they agree from the given
2176// addresses onwards.
2177//
2178// See open core issue CWG2765 which is discussing the desired rule here.
2179static bool ArePotentiallyOverlappingStringLiterals(const EvalInfo &Info,
2180 const LValue &LHS,
2181 const LValue &RHS) {
2182 LValueBaseString LHSString, RHSString;
2183 if (!GetLValueBaseAsString(Info, LHS, LHSString) ||
2184 !GetLValueBaseAsString(Info, RHS, RHSString))
2185 return false;
2186
2187 // This is the byte offset to the location of the first character of LHS
2188 // within RHS. We don't need to look at the characters of one string that
2189 // would appear before the start of the other string if they were merged.
2190 CharUnits Offset = RHS.Offset - LHS.Offset;
2191 if (Offset.isNegative()) {
2192 if (LHSString.Bytes.size() < (size_t)-Offset.getQuantity())
2193 return false;
2194 LHSString.Bytes = LHSString.Bytes.drop_front(-Offset.getQuantity());
2195 } else {
2196 if (RHSString.Bytes.size() < (size_t)Offset.getQuantity())
2197 return false;
2198 RHSString.Bytes = RHSString.Bytes.drop_front(Offset.getQuantity());
2199 }
2200
2201 bool LHSIsLonger = LHSString.Bytes.size() > RHSString.Bytes.size();
2202 StringRef Longer = LHSIsLonger ? LHSString.Bytes : RHSString.Bytes;
2203 StringRef Shorter = LHSIsLonger ? RHSString.Bytes : LHSString.Bytes;
2204 int ShorterCharWidth = (LHSIsLonger ? RHSString : LHSString).CharWidth;
2205
2206 // The null terminator isn't included in the string data, so check for it
2207 // manually. If the longer string doesn't have a null terminator where the
2208 // shorter string ends, they aren't potentially overlapping.
2209 for (int NullByte : llvm::seq(ShorterCharWidth)) {
2210 if (Shorter.size() + NullByte >= Longer.size())
2211 break;
2212 if (Longer[Shorter.size() + NullByte])
2213 return false;
2214 }
2215
2216 // Otherwise, they're potentially overlapping if and only if the overlapping
2217 // region is the same.
2218 return Shorter == Longer.take_front(Shorter.size());
2219}
2220
2221static bool IsWeakLValue(const LValue &Value) {
2223 return Decl && Decl->isWeak();
2224}
2225
2226static bool isZeroSized(const LValue &Value) {
2228 if (isa_and_nonnull<VarDecl>(Decl)) {
2229 QualType Ty = Decl->getType();
2230 if (Ty->isArrayType())
2231 return Ty->isIncompleteType() ||
2232 Decl->getASTContext().getTypeSize(Ty) == 0;
2233 }
2234 return false;
2235}
2236
2237static bool HasSameBase(const LValue &A, const LValue &B) {
2238 if (!A.getLValueBase())
2239 return !B.getLValueBase();
2240 if (!B.getLValueBase())
2241 return false;
2242
2243 if (A.getLValueBase().getOpaqueValue() !=
2244 B.getLValueBase().getOpaqueValue())
2245 return false;
2246
2247 return A.getLValueCallIndex() == B.getLValueCallIndex() &&
2248 A.getLValueVersion() == B.getLValueVersion();
2249}
2250
2251static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
2252 assert(Base && "no location for a null lvalue");
2253 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2254
2255 // For a parameter, find the corresponding call stack frame (if it still
2256 // exists), and point at the parameter of the function definition we actually
2257 // invoked.
2258 if (auto *PVD = dyn_cast_or_null<ParmVarDecl>(VD)) {
2259 unsigned Idx = PVD->getFunctionScopeIndex();
2260 for (CallStackFrame *F = Info.CurrentCall; F; F = F->Caller) {
2261 if (F->Arguments.CallIndex == Base.getCallIndex() &&
2262 F->Arguments.Version == Base.getVersion() && F->Callee &&
2263 Idx < F->Callee->getNumParams()) {
2264 VD = F->Callee->getParamDecl(Idx);
2265 break;
2266 }
2267 }
2268 }
2269
2270 if (VD)
2271 Info.Note(VD->getLocation(), diag::note_declared_at);
2272 else if (const Expr *E = Base.dyn_cast<const Expr*>())
2273 Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
2274 else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
2275 // FIXME: Produce a note for dangling pointers too.
2276 if (std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA))
2277 Info.Note((*Alloc)->AllocExpr->getExprLoc(),
2278 diag::note_constexpr_dynamic_alloc_here);
2279 }
2280
2281 // We have no information to show for a typeid(T) object.
2282}
2283
2288
2289/// Materialized temporaries that we've already checked to determine if they're
2290/// initializsed by a constant expression.
2293
2295 EvalInfo &Info, SourceLocation DiagLoc,
2296 QualType Type, const APValue &Value,
2297 ConstantExprKind Kind,
2298 const FieldDecl *SubobjectDecl,
2299 CheckedTemporaries &CheckedTemps);
2300
2301/// Check that this reference or pointer core constant expression is a valid
2302/// value for an address or reference constant expression. Return true if we
2303/// can fold this expression, whether or not it's a constant expression.
2304static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
2305 QualType Type, const LValue &LVal,
2306 ConstantExprKind Kind,
2307 CheckedTemporaries &CheckedTemps) {
2308 bool IsReferenceType = Type->isReferenceType();
2309
2310 APValue::LValueBase Base = LVal.getLValueBase();
2311 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
2312
2313 const Expr *BaseE = Base.dyn_cast<const Expr *>();
2314 const ValueDecl *BaseVD = Base.dyn_cast<const ValueDecl*>();
2315
2316 // Additional restrictions apply in a template argument. We only enforce the
2317 // C++20 restrictions here; additional syntactic and semantic restrictions
2318 // are applied elsewhere.
2319 if (isTemplateArgument(Kind)) {
2320 int InvalidBaseKind = -1;
2321 StringRef Ident;
2322 if (Base.is<TypeInfoLValue>())
2323 InvalidBaseKind = 0;
2324 else if (isa_and_nonnull<StringLiteral>(BaseE))
2325 InvalidBaseKind = 1;
2326 else if (isa_and_nonnull<MaterializeTemporaryExpr>(BaseE) ||
2327 isa_and_nonnull<LifetimeExtendedTemporaryDecl>(BaseVD))
2328 InvalidBaseKind = 2;
2329 else if (auto *PE = dyn_cast_or_null<PredefinedExpr>(BaseE)) {
2330 InvalidBaseKind = 3;
2331 Ident = PE->getIdentKindName();
2332 }
2333
2334 if (InvalidBaseKind != -1) {
2335 Info.FFDiag(Loc, diag::note_constexpr_invalid_template_arg)
2336 << IsReferenceType << !Designator.Entries.empty() << InvalidBaseKind
2337 << Ident;
2338 return false;
2339 }
2340 }
2341
2342 if (auto *FD = dyn_cast_or_null<FunctionDecl>(BaseVD);
2343 FD && FD->isImmediateFunction()) {
2344 Info.FFDiag(Loc, diag::note_consteval_address_accessible)
2345 << !Type->isAnyPointerType();
2346 Info.Note(FD->getLocation(), diag::note_declared_at);
2347 return false;
2348 }
2349
2350 // Check that the object is a global. Note that the fake 'this' object we
2351 // manufacture when checking potential constant expressions is conservatively
2352 // assumed to be global here.
2353 if (!IsGlobalLValue(Base)) {
2354 if (Info.getLangOpts().CPlusPlus11) {
2355 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
2356 << IsReferenceType << !Designator.Entries.empty() << !!BaseVD
2357 << BaseVD;
2358 auto *VarD = dyn_cast_or_null<VarDecl>(BaseVD);
2359 if (VarD && VarD->isConstexpr()) {
2360 // Non-static local constexpr variables have unintuitive semantics:
2361 // constexpr int a = 1;
2362 // constexpr const int *p = &a;
2363 // ... is invalid because the address of 'a' is not constant. Suggest
2364 // adding a 'static' in this case.
2365 Info.Note(VarD->getLocation(), diag::note_constexpr_not_static)
2366 << VarD
2367 << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static ");
2368 } else {
2369 NoteLValueLocation(Info, Base);
2370 }
2371 } else {
2372 Info.FFDiag(Loc);
2373 }
2374 // Don't allow references to temporaries to escape.
2375 return false;
2376 }
2377 assert((Info.checkingPotentialConstantExpression() ||
2378 LVal.getLValueCallIndex() == 0) &&
2379 "have call index for global lvalue");
2380
2381 if (LVal.allowConstexprUnknown()) {
2382 if (BaseVD) {
2383 Info.FFDiag(Loc, diag::note_constexpr_var_init_non_constant, 1) << BaseVD;
2384 NoteLValueLocation(Info, Base);
2385 } else {
2386 Info.FFDiag(Loc);
2387 }
2388 return false;
2389 }
2390
2391 if (Base.is<DynamicAllocLValue>()) {
2392 Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc)
2393 << IsReferenceType << !Designator.Entries.empty();
2394 NoteLValueLocation(Info, Base);
2395 return false;
2396 }
2397
2398 if (BaseVD) {
2399 if (const VarDecl *Var = dyn_cast<const VarDecl>(BaseVD)) {
2400 // Check if this is a thread-local variable.
2401 if (Var->getTLSKind())
2402 // FIXME: Diagnostic!
2403 return false;
2404
2405 // A dllimport variable never acts like a constant, unless we're
2406 // evaluating a value for use only in name mangling, and unless it's a
2407 // static local. For the latter case, we'd still need to evaluate the
2408 // constant expression in case we're inside a (inlined) function.
2409 if (!isForManglingOnly(Kind) && Var->hasAttr<DLLImportAttr>() &&
2410 !Var->isStaticLocal())
2411 return false;
2412
2413 // In CUDA/HIP device compilation, only device side variables have
2414 // constant addresses.
2415 if (Info.getASTContext().getLangOpts().CUDA &&
2416 Info.getASTContext().getLangOpts().CUDAIsDevice &&
2417 Info.getASTContext().CUDAConstantEvalCtx.NoWrongSidedVars) {
2418 if ((!Var->hasAttr<CUDADeviceAttr>() &&
2419 !Var->hasAttr<CUDAConstantAttr>() &&
2420 !Var->getType()->isCUDADeviceBuiltinSurfaceType() &&
2421 !Var->getType()->isCUDADeviceBuiltinTextureType()) ||
2422 Var->hasAttr<HIPManagedAttr>())
2423 return false;
2424 }
2425 }
2426 if (const auto *FD = dyn_cast<const FunctionDecl>(BaseVD)) {
2427 // __declspec(dllimport) must be handled very carefully:
2428 // We must never initialize an expression with the thunk in C++.
2429 // Doing otherwise would allow the same id-expression to yield
2430 // different addresses for the same function in different translation
2431 // units. However, this means that we must dynamically initialize the
2432 // expression with the contents of the import address table at runtime.
2433 //
2434 // The C language has no notion of ODR; furthermore, it has no notion of
2435 // dynamic initialization. This means that we are permitted to
2436 // perform initialization with the address of the thunk.
2437 if (Info.getLangOpts().CPlusPlus && !isForManglingOnly(Kind) &&
2438 FD->hasAttr<DLLImportAttr>())
2439 // FIXME: Diagnostic!
2440 return false;
2441 }
2442 } else if (const auto *MTE =
2443 dyn_cast_or_null<MaterializeTemporaryExpr>(BaseE)) {
2444 if (CheckedTemps.insert(MTE).second) {
2445 QualType TempType = getType(Base);
2446 if (TempType.isDestructedType()) {
2447 Info.FFDiag(MTE->getExprLoc(),
2448 diag::note_constexpr_unsupported_temporary_nontrivial_dtor)
2449 << TempType;
2450 return false;
2451 }
2452
2453 APValue *V = MTE->getOrCreateValue(false);
2454 assert(V && "evasluation result refers to uninitialised temporary");
2456 Info, MTE->getExprLoc(), TempType, *V, Kind,
2457 /*SubobjectDecl=*/nullptr, CheckedTemps))
2458 return false;
2459 }
2460 }
2461
2462 // Allow address constant expressions to be past-the-end pointers. This is
2463 // an extension: the standard requires them to point to an object.
2464 if (!IsReferenceType)
2465 return true;
2466
2467 // A reference constant expression must refer to an object.
2468 if (!Base) {
2469 // FIXME: diagnostic
2470 Info.CCEDiag(Loc);
2471 return true;
2472 }
2473
2474 // Does this refer one past the end of some object?
2475 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
2476 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
2477 << !Designator.Entries.empty() << !!BaseVD << BaseVD;
2478 NoteLValueLocation(Info, Base);
2479 }
2480
2481 return true;
2482}
2483
2484/// Member pointers are constant expressions unless they point to a
2485/// non-virtual dllimport member function.
2486static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
2487 SourceLocation Loc,
2488 QualType Type,
2489 const APValue &Value,
2490 ConstantExprKind Kind) {
2491 const ValueDecl *Member = Value.getMemberPointerDecl();
2492 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
2493 if (!FD)
2494 return true;
2495 if (FD->isImmediateFunction()) {
2496 Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0;
2497 Info.Note(FD->getLocation(), diag::note_declared_at);
2498 return false;
2499 }
2500 return isForManglingOnly(Kind) || FD->isVirtual() ||
2501 !FD->hasAttr<DLLImportAttr>();
2502}
2503
2504/// Check that this core constant expression is of literal type, and if not,
2505/// produce an appropriate diagnostic.
2506static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
2507 const LValue *This = nullptr) {
2508 // The restriction to literal types does not exist in C++23 anymore.
2509 if (Info.getLangOpts().CPlusPlus23)
2510 return true;
2511
2512 if (!E->isPRValue() || E->getType()->isLiteralType(Info.Ctx))
2513 return true;
2514
2515 // C++1y: A constant initializer for an object o [...] may also invoke
2516 // constexpr constructors for o and its subobjects even if those objects
2517 // are of non-literal class types.
2518 //
2519 // C++11 missed this detail for aggregates, so classes like this:
2520 // struct foo_t { union { int i; volatile int j; } u; };
2521 // are not (obviously) initializable like so:
2522 // __attribute__((__require_constant_initialization__))
2523 // static const foo_t x = {{0}};
2524 // because "i" is a subobject with non-literal initialization (due to the
2525 // volatile member of the union). See:
2526 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2527 // Therefore, we use the C++1y behavior.
2528 if (This && Info.EvaluatingDecl == This->getLValueBase())
2529 return true;
2530
2531 // Prvalue constant expressions must be of literal types.
2532 if (Info.getLangOpts().CPlusPlus11)
2533 Info.FFDiag(E, diag::note_constexpr_nonliteral)
2534 << E->getType();
2535 else
2536 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2537 return false;
2538}
2539
2541 EvalInfo &Info, SourceLocation DiagLoc,
2542 QualType Type, const APValue &Value,
2543 ConstantExprKind Kind,
2544 const FieldDecl *SubobjectDecl,
2545 CheckedTemporaries &CheckedTemps) {
2546 if (!Value.hasValue()) {
2547 if (SubobjectDecl) {
2548 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2549 << /*(name)*/ 1 << SubobjectDecl;
2550 Info.Note(SubobjectDecl->getLocation(),
2551 diag::note_constexpr_subobject_declared_here);
2552 } else {
2553 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2554 << /*of type*/ 0 << Type;
2555 }
2556 return false;
2557 }
2558
2559 // We allow _Atomic(T) to be initialized from anything that T can be
2560 // initialized from.
2561 if (const AtomicType *AT = Type->getAs<AtomicType>())
2562 Type = AT->getValueType();
2563
2564 // Core issue 1454: For a literal constant expression of array or class type,
2565 // each subobject of its value shall have been initialized by a constant
2566 // expression.
2567 if (Value.isArray()) {
2569 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
2570 if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2571 Value.getArrayInitializedElt(I), Kind,
2572 SubobjectDecl, CheckedTemps))
2573 return false;
2574 }
2575 if (!Value.hasArrayFiller())
2576 return true;
2577 return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2578 Value.getArrayFiller(), Kind, SubobjectDecl,
2579 CheckedTemps);
2580 }
2581 if (Value.isUnion() && Value.getUnionField()) {
2582 return CheckEvaluationResult(
2583 CERK, Info, DiagLoc, Value.getUnionField()->getType(),
2584 Value.getUnionValue(), Kind, Value.getUnionField(), CheckedTemps);
2585 }
2586 if (Value.isStruct()) {
2587 auto *RD = Type->castAsRecordDecl();
2588 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2589 unsigned BaseIndex = 0;
2590 for (const CXXBaseSpecifier &BS : CD->bases()) {
2591 const APValue &BaseValue = Value.getStructBase(BaseIndex);
2592 if (!BaseValue.hasValue()) {
2593 SourceLocation TypeBeginLoc = BS.getBaseTypeLoc();
2594 Info.FFDiag(TypeBeginLoc, diag::note_constexpr_uninitialized_base)
2595 << BS.getType() << SourceRange(TypeBeginLoc, BS.getEndLoc());
2596 return false;
2597 }
2598 if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(), BaseValue,
2599 Kind, /*SubobjectDecl=*/nullptr,
2600 CheckedTemps))
2601 return false;
2602 ++BaseIndex;
2603 }
2604 }
2605 for (const auto *I : RD->fields()) {
2606 if (I->isUnnamedBitField())
2607 continue;
2608
2609 if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),
2610 Value.getStructField(I->getFieldIndex()), Kind,
2611 I, CheckedTemps))
2612 return false;
2613 }
2614 }
2615
2616 if (Value.isLValue() &&
2618 LValue LVal;
2619 LVal.setFrom(Info.Ctx, Value);
2620 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Kind,
2621 CheckedTemps);
2622 }
2623
2624 if (Value.isMemberPointer() &&
2626 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Kind);
2627
2628 // Everything else is fine.
2629 return true;
2630}
2631
2632/// Check that this core constant expression value is a valid value for a
2633/// constant expression. If not, report an appropriate diagnostic. Does not
2634/// check that the expression is of literal type.
2635static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
2636 QualType Type, const APValue &Value,
2637 ConstantExprKind Kind) {
2638 // Nothing to check for a constant expression of type 'cv void'.
2639 if (Type->isVoidType())
2640 return true;
2641
2642 CheckedTemporaries CheckedTemps;
2644 Info, DiagLoc, Type, Value, Kind,
2645 /*SubobjectDecl=*/nullptr, CheckedTemps);
2646}
2647
2648/// Check that this evaluated value is fully-initialized and can be loaded by
2649/// an lvalue-to-rvalue conversion.
2650static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,
2651 QualType Type, const APValue &Value) {
2652 CheckedTemporaries CheckedTemps;
2653 return CheckEvaluationResult(
2655 ConstantExprKind::Normal, /*SubobjectDecl=*/nullptr, CheckedTemps);
2656}
2657
2658/// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless
2659/// "the allocated storage is deallocated within the evaluation".
2660static bool CheckMemoryLeaks(EvalInfo &Info) {
2661 if (!Info.HeapAllocs.empty()) {
2662 // We can still fold to a constant despite a compile-time memory leak,
2663 // so long as the heap allocation isn't referenced in the result (we check
2664 // that in CheckConstantExpression).
2665 Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr,
2666 diag::note_constexpr_memory_leak)
2667 << unsigned(Info.HeapAllocs.size() - 1);
2668 }
2669 return true;
2670}
2671
2672static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
2673 // A null base expression indicates a null pointer. These are always
2674 // evaluatable, and they are false unless the offset is zero.
2675 if (!Value.getLValueBase()) {
2676 // TODO: Should a non-null pointer with an offset of zero evaluate to true?
2677 Result = !Value.getLValueOffset().isZero();
2678 return true;
2679 }
2680
2681 // We have a non-null base. These are generally known to be true, but if it's
2682 // a weak declaration it can be null at runtime.
2683 Result = true;
2684 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
2685 return !Decl || !Decl->isWeak();
2686}
2687
2688static bool HandleConversionToBool(const APValue &Val, bool &Result) {
2689 // TODO: This function should produce notes if it fails.
2690 switch (Val.getKind()) {
2691 case APValue::None:
2693 return false;
2694 case APValue::Int:
2695 Result = Val.getInt().getBoolValue();
2696 return true;
2698 Result = Val.getFixedPoint().getBoolValue();
2699 return true;
2700 case APValue::Float:
2701 Result = !Val.getFloat().isZero();
2702 return true;
2704 Result = Val.getComplexIntReal().getBoolValue() ||
2705 Val.getComplexIntImag().getBoolValue();
2706 return true;
2708 Result = !Val.getComplexFloatReal().isZero() ||
2709 !Val.getComplexFloatImag().isZero();
2710 return true;
2711 case APValue::LValue:
2712 return EvalPointerValueAsBool(Val, Result);
2714 if (Val.getMemberPointerDecl() && Val.getMemberPointerDecl()->isWeak()) {
2715 return false;
2716 }
2717 Result = Val.getMemberPointerDecl();
2718 return true;
2719 case APValue::Vector:
2720 case APValue::Array:
2721 case APValue::Struct:
2722 case APValue::Union:
2724 return false;
2725 }
2726
2727 llvm_unreachable("unknown APValue kind");
2728}
2729
2730static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2731 EvalInfo &Info) {
2732 assert(!E->isValueDependent());
2733 assert(E->isPRValue() && "missing lvalue-to-rvalue conv in bool condition");
2734 APValue Val;
2735 if (!Evaluate(Val, Info, E))
2736 return false;
2737 return HandleConversionToBool(Val, Result);
2738}
2739
2740template<typename T>
2741static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2742 const T &SrcValue, QualType DestType) {
2743 Info.CCEDiag(E, diag::note_constexpr_overflow)
2744 << SrcValue << DestType;
2745 return Info.noteUndefinedBehavior();
2746}
2747
2748static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2749 QualType SrcType, const APFloat &Value,
2750 QualType DestType, APSInt &Result) {
2751 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2752 // Determine whether we are converting to unsigned or signed.
2753 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2754
2755 Result = APSInt(DestWidth, !DestSigned);
2756 bool ignored;
2757 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2758 & APFloat::opInvalidOp)
2759 return HandleOverflow(Info, E, Value, DestType);
2760 return true;
2761}
2762
2763/// Get rounding mode to use in evaluation of the specified expression.
2764///
2765/// If rounding mode is unknown at compile time, still try to evaluate the
2766/// expression. If the result is exact, it does not depend on rounding mode.
2767/// So return "tonearest" mode instead of "dynamic".
2768static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E) {
2769 llvm::RoundingMode RM =
2771 if (RM == llvm::RoundingMode::Dynamic)
2772 RM = llvm::RoundingMode::NearestTiesToEven;
2773 return RM;
2774}
2775
2776/// Check if the given evaluation result is allowed for constant evaluation.
2777static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E,
2778 APFloat::opStatus St) {
2779 // In a constant context, assume that any dynamic rounding mode or FP
2780 // exception state matches the default floating-point environment.
2781 if (Info.InConstantContext)
2782 return true;
2783
2784 FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
2785 if ((St & APFloat::opInexact) &&
2786 FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) {
2787 // Inexact result means that it depends on rounding mode. If the requested
2788 // mode is dynamic, the evaluation cannot be made in compile time.
2789 Info.FFDiag(E, diag::note_constexpr_dynamic_rounding);
2790 return false;
2791 }
2792
2793 if ((St != APFloat::opOK) &&
2794 (FPO.getRoundingMode() == llvm::RoundingMode::Dynamic ||
2796 FPO.getAllowFEnvAccess())) {
2797 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
2798 return false;
2799 }
2800
2801 if ((St & APFloat::opStatus::opInvalidOp) &&
2803 // There is no usefully definable result.
2804 Info.FFDiag(E);
2805 return false;
2806 }
2807
2808 // FIXME: if:
2809 // - evaluation triggered other FP exception, and
2810 // - exception mode is not "ignore", and
2811 // - the expression being evaluated is not a part of global variable
2812 // initializer,
2813 // the evaluation probably need to be rejected.
2814 return true;
2815}
2816
2817static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2818 QualType SrcType, QualType DestType,
2819 APFloat &Result) {
2820 assert((isa<CastExpr>(E) || isa<CompoundAssignOperator>(E) ||
2822 "HandleFloatToFloatCast has been checked with only CastExpr, "
2823 "CompoundAssignOperator and ConvertVectorExpr. Please either validate "
2824 "the new expression or address the root cause of this usage.");
2825 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2826 APFloat::opStatus St;
2827 APFloat Value = Result;
2828 bool ignored;
2829 St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored);
2830 return checkFloatingPointResult(Info, E, St);
2831}
2832
2833static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2834 QualType DestType, QualType SrcType,
2835 const APSInt &Value) {
2836 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2837 // Figure out if this is a truncate, extend or noop cast.
2838 // If the input is signed, do a sign extend, noop, or truncate.
2839 APSInt Result = Value.extOrTrunc(DestWidth);
2840 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2841 if (DestType->isBooleanType())
2842 Result = Value.getBoolValue();
2843 return Result;
2844}
2845
2846static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2847 const FPOptions FPO,
2848 QualType SrcType, const APSInt &Value,
2849 QualType DestType, APFloat &Result) {
2850 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2851 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2852 APFloat::opStatus St = Result.convertFromAPInt(Value, Value.isSigned(), RM);
2853 return checkFloatingPointResult(Info, E, St);
2854}
2855
2856static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2857 APValue &Value, const FieldDecl *FD) {
2858 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2859
2860 if (!Value.isInt()) {
2861 // Trying to store a pointer-cast-to-integer into a bitfield.
2862 // FIXME: In this case, we should provide the diagnostic for casting
2863 // a pointer to an integer.
2864 assert(Value.isLValue() && "integral value neither int nor lvalue?");
2865 Info.FFDiag(E);
2866 return false;
2867 }
2868
2869 APSInt &Int = Value.getInt();
2870 unsigned OldBitWidth = Int.getBitWidth();
2871 unsigned NewBitWidth = FD->getBitWidthValue();
2872 if (NewBitWidth < OldBitWidth)
2873 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2874 return true;
2875}
2876
2877/// Perform the given integer operation, which is known to need at most BitWidth
2878/// bits, and check for overflow in the original type (if that type was not an
2879/// unsigned type).
2880template<typename Operation>
2881static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2882 const APSInt &LHS, const APSInt &RHS,
2883 unsigned BitWidth, Operation Op,
2884 APSInt &Result) {
2885 if (LHS.isUnsigned()) {
2886 Result = Op(LHS, RHS);
2887 return true;
2888 }
2889
2890 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2891 Result = Value.trunc(LHS.getBitWidth());
2892 if (Result.extend(BitWidth) != Value) {
2893 if (Info.checkingForUndefinedBehavior())
2894 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2895 diag::warn_integer_constant_overflow)
2896 << toString(Result, 10, Result.isSigned(), /*formatAsCLiteral=*/false,
2897 /*UpperCase=*/true, /*InsertSeparators=*/true)
2898 << E->getType() << E->getSourceRange();
2899 return HandleOverflow(Info, E, Value, E->getType());
2900 }
2901 return true;
2902}
2903
2904/// Perform the given binary integer operation.
2905static bool handleIntIntBinOp(EvalInfo &Info, const BinaryOperator *E,
2906 const APSInt &LHS, BinaryOperatorKind Opcode,
2907 APSInt RHS, APSInt &Result) {
2908 bool HandleOverflowResult = true;
2909 switch (Opcode) {
2910 default:
2911 Info.FFDiag(E);
2912 return false;
2913 case BO_Mul:
2914 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2915 std::multiplies<APSInt>(), Result);
2916 case BO_Add:
2917 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2918 std::plus<APSInt>(), Result);
2919 case BO_Sub:
2920 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2921 std::minus<APSInt>(), Result);
2922 case BO_And: Result = LHS & RHS; return true;
2923 case BO_Xor: Result = LHS ^ RHS; return true;
2924 case BO_Or: Result = LHS | RHS; return true;
2925 case BO_Div:
2926 case BO_Rem:
2927 if (RHS == 0) {
2928 Info.FFDiag(E, diag::note_expr_divide_by_zero)
2929 << E->getRHS()->getSourceRange();
2930 return false;
2931 }
2932 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2933 // this operation and gives the two's complement result.
2934 if (RHS.isNegative() && RHS.isAllOnes() && LHS.isSigned() &&
2935 LHS.isMinSignedValue())
2936 HandleOverflowResult = HandleOverflow(
2937 Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
2938 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2939 return HandleOverflowResult;
2940 case BO_Shl: {
2941 if (Info.getLangOpts().OpenCL)
2942 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2943 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2944 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2945 RHS.isUnsigned());
2946 else if (RHS.isSigned() && RHS.isNegative()) {
2947 // During constant-folding, a negative shift is an opposite shift. Such
2948 // a shift is not a constant expression.
2949 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2950 if (!Info.noteUndefinedBehavior())
2951 return false;
2952 RHS = -RHS;
2953 goto shift_right;
2954 }
2955 shift_left:
2956 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2957 // the shifted type.
2958 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2959 if (SA != RHS) {
2960 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2961 << RHS << E->getType() << LHS.getBitWidth();
2962 if (!Info.noteUndefinedBehavior())
2963 return false;
2964 } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) {
2965 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2966 // operand, and must not overflow the corresponding unsigned type.
2967 // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2968 // E1 x 2^E2 module 2^N.
2969 if (LHS.isNegative()) {
2970 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2971 if (!Info.noteUndefinedBehavior())
2972 return false;
2973 } else if (LHS.countl_zero() < SA) {
2974 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2975 if (!Info.noteUndefinedBehavior())
2976 return false;
2977 }
2978 }
2979 Result = LHS << SA;
2980 return true;
2981 }
2982 case BO_Shr: {
2983 if (Info.getLangOpts().OpenCL)
2984 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2985 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2986 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2987 RHS.isUnsigned());
2988 else if (RHS.isSigned() && RHS.isNegative()) {
2989 // During constant-folding, a negative shift is an opposite shift. Such a
2990 // shift is not a constant expression.
2991 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2992 if (!Info.noteUndefinedBehavior())
2993 return false;
2994 RHS = -RHS;
2995 goto shift_left;
2996 }
2997 shift_right:
2998 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2999 // shifted type.
3000 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
3001 if (SA != RHS) {
3002 Info.CCEDiag(E, diag::note_constexpr_large_shift)
3003 << RHS << E->getType() << LHS.getBitWidth();
3004 if (!Info.noteUndefinedBehavior())
3005 return false;
3006 }
3007
3008 Result = LHS >> SA;
3009 return true;
3010 }
3011
3012 case BO_LT: Result = LHS < RHS; return true;
3013 case BO_GT: Result = LHS > RHS; return true;
3014 case BO_LE: Result = LHS <= RHS; return true;
3015 case BO_GE: Result = LHS >= RHS; return true;
3016 case BO_EQ: Result = LHS == RHS; return true;
3017 case BO_NE: Result = LHS != RHS; return true;
3018 case BO_Cmp:
3019 llvm_unreachable("BO_Cmp should be handled elsewhere");
3020 }
3021}
3022
3023/// Perform the given binary floating-point operation, in-place, on LHS.
3024static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E,
3025 APFloat &LHS, BinaryOperatorKind Opcode,
3026 const APFloat &RHS) {
3027 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
3028 APFloat::opStatus St;
3029 switch (Opcode) {
3030 default:
3031 Info.FFDiag(E);
3032 return false;
3033 case BO_Mul:
3034 St = LHS.multiply(RHS, RM);
3035 break;
3036 case BO_Add:
3037 St = LHS.add(RHS, RM);
3038 break;
3039 case BO_Sub:
3040 St = LHS.subtract(RHS, RM);
3041 break;
3042 case BO_Div:
3043 // [expr.mul]p4:
3044 // If the second operand of / or % is zero the behavior is undefined.
3045 if (RHS.isZero())
3046 Info.CCEDiag(E, diag::note_expr_divide_by_zero);
3047 St = LHS.divide(RHS, RM);
3048 break;
3049 }
3050
3051 // [expr.pre]p4:
3052 // If during the evaluation of an expression, the result is not
3053 // mathematically defined [...], the behavior is undefined.
3054 // FIXME: C++ rules require us to not conform to IEEE 754 here.
3055 if (LHS.isNaN()) {
3056 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
3057 return Info.noteUndefinedBehavior();
3058 }
3059
3060 return checkFloatingPointResult(Info, E, St);
3061}
3062
3063static bool handleLogicalOpForVector(const APInt &LHSValue,
3064 BinaryOperatorKind Opcode,
3065 const APInt &RHSValue, APInt &Result) {
3066 bool LHS = (LHSValue != 0);
3067 bool RHS = (RHSValue != 0);
3068
3069 if (Opcode == BO_LAnd)
3070 Result = LHS && RHS;
3071 else
3072 Result = LHS || RHS;
3073 return true;
3074}
3075static bool handleLogicalOpForVector(const APFloat &LHSValue,
3076 BinaryOperatorKind Opcode,
3077 const APFloat &RHSValue, APInt &Result) {
3078 bool LHS = !LHSValue.isZero();
3079 bool RHS = !RHSValue.isZero();
3080
3081 if (Opcode == BO_LAnd)
3082 Result = LHS && RHS;
3083 else
3084 Result = LHS || RHS;
3085 return true;
3086}
3087
3088static bool handleLogicalOpForVector(const APValue &LHSValue,
3089 BinaryOperatorKind Opcode,
3090 const APValue &RHSValue, APInt &Result) {
3091 // The result is always an int type, however operands match the first.
3092 if (LHSValue.getKind() == APValue::Int)
3093 return handleLogicalOpForVector(LHSValue.getInt(), Opcode,
3094 RHSValue.getInt(), Result);
3095 assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
3096 return handleLogicalOpForVector(LHSValue.getFloat(), Opcode,
3097 RHSValue.getFloat(), Result);
3098}
3099
3100template <typename APTy>
3101static bool
3103 const APTy &RHSValue, APInt &Result) {
3104 switch (Opcode) {
3105 default:
3106 llvm_unreachable("unsupported binary operator");
3107 case BO_EQ:
3108 Result = (LHSValue == RHSValue);
3109 break;
3110 case BO_NE:
3111 Result = (LHSValue != RHSValue);
3112 break;
3113 case BO_LT:
3114 Result = (LHSValue < RHSValue);
3115 break;
3116 case BO_GT:
3117 Result = (LHSValue > RHSValue);
3118 break;
3119 case BO_LE:
3120 Result = (LHSValue <= RHSValue);
3121 break;
3122 case BO_GE:
3123 Result = (LHSValue >= RHSValue);
3124 break;
3125 }
3126
3127 // The boolean operations on these vector types use an instruction that
3128 // results in a mask of '-1' for the 'truth' value. Ensure that we negate 1
3129 // to -1 to make sure that we produce the correct value.
3130 Result.negate();
3131
3132 return true;
3133}
3134
3135static bool handleCompareOpForVector(const APValue &LHSValue,
3136 BinaryOperatorKind Opcode,
3137 const APValue &RHSValue, APInt &Result) {
3138 // The result is always an int type, however operands match the first.
3139 if (LHSValue.getKind() == APValue::Int)
3140 return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode,
3141 RHSValue.getInt(), Result);
3142 assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
3143 return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode,
3144 RHSValue.getFloat(), Result);
3145}
3146
3147// Perform binary operations for vector types, in place on the LHS.
3148static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E,
3149 BinaryOperatorKind Opcode,
3150 APValue &LHSValue,
3151 const APValue &RHSValue) {
3152 assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI &&
3153 "Operation not supported on vector types");
3154
3155 const auto *VT = E->getType()->castAs<VectorType>();
3156 unsigned NumElements = VT->getNumElements();
3157 QualType EltTy = VT->getElementType();
3158
3159 // In the cases (typically C as I've observed) where we aren't evaluating
3160 // constexpr but are checking for cases where the LHS isn't yet evaluatable,
3161 // just give up.
3162 if (!LHSValue.isVector()) {
3163 assert(LHSValue.isLValue() &&
3164 "A vector result that isn't a vector OR uncalculated LValue");
3165 Info.FFDiag(E);
3166 return false;
3167 }
3168
3169 assert(LHSValue.getVectorLength() == NumElements &&
3170 RHSValue.getVectorLength() == NumElements && "Different vector sizes");
3171
3172 SmallVector<APValue, 4> ResultElements;
3173
3174 for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) {
3175 APValue LHSElt = LHSValue.getVectorElt(EltNum);
3176 APValue RHSElt = RHSValue.getVectorElt(EltNum);
3177
3178 if (EltTy->isIntegerType()) {
3179 APSInt EltResult{Info.Ctx.getIntWidth(EltTy),
3180 EltTy->isUnsignedIntegerType()};
3181 bool Success = true;
3182
3183 if (BinaryOperator::isLogicalOp(Opcode))
3184 Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3185 else if (BinaryOperator::isComparisonOp(Opcode))
3186 Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3187 else
3188 Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode,
3189 RHSElt.getInt(), EltResult);
3190
3191 if (!Success) {
3192 Info.FFDiag(E);
3193 return false;
3194 }
3195 ResultElements.emplace_back(EltResult);
3196
3197 } else if (EltTy->isFloatingType()) {
3198 assert(LHSElt.getKind() == APValue::Float &&
3199 RHSElt.getKind() == APValue::Float &&
3200 "Mismatched LHS/RHS/Result Type");
3201 APFloat LHSFloat = LHSElt.getFloat();
3202
3203 if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode,
3204 RHSElt.getFloat())) {
3205 Info.FFDiag(E);
3206 return false;
3207 }
3208
3209 ResultElements.emplace_back(LHSFloat);
3210 }
3211 }
3212
3213 LHSValue = APValue(ResultElements.data(), ResultElements.size());
3214 return true;
3215}
3216
3217/// Cast an lvalue referring to a base subobject to a derived class, by
3218/// truncating the lvalue's path to the given length.
3219static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
3220 const RecordDecl *TruncatedType,
3221 unsigned TruncatedElements) {
3222 SubobjectDesignator &D = Result.Designator;
3223
3224 // Check we actually point to a derived class object.
3225 if (TruncatedElements == D.Entries.size())
3226 return true;
3227 assert(TruncatedElements >= D.MostDerivedPathLength &&
3228 "not casting to a derived class");
3229 if (!Result.checkSubobject(Info, E, CSK_Derived))
3230 return false;
3231
3232 // Truncate the path to the subobject, and remove any derived-to-base offsets.
3233 const RecordDecl *RD = TruncatedType;
3234 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
3235 if (RD->isInvalidDecl()) return false;
3236 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3237 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
3238 if (isVirtualBaseClass(D.Entries[I]))
3239 Result.Offset -= Layout.getVBaseClassOffset(Base);
3240 else
3241 Result.Offset -= Layout.getBaseClassOffset(Base);
3242 RD = Base;
3243 }
3244 D.Entries.resize(TruncatedElements);
3245 return true;
3246}
3247
3248static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3249 const CXXRecordDecl *Derived,
3250 const CXXRecordDecl *Base,
3251 const ASTRecordLayout *RL = nullptr) {
3252 if (!RL) {
3253 if (Derived->isInvalidDecl()) return false;
3254 RL = &Info.Ctx.getASTRecordLayout(Derived);
3255 }
3256
3257 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
3258 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
3259 return true;
3260}
3261
3262static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3263 const CXXRecordDecl *DerivedDecl,
3264 const CXXBaseSpecifier *Base) {
3265 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
3266
3267 if (!Base->isVirtual())
3268 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
3269
3270 SubobjectDesignator &D = Obj.Designator;
3271 if (D.Invalid)
3272 return false;
3273
3274 // Extract most-derived object and corresponding type.
3275 // FIXME: After implementing P2280R4 it became possible to get references
3276 // here. We do MostDerivedType->getAsCXXRecordDecl() in several other
3277 // locations and if we see crashes in those locations in the future
3278 // it may make more sense to move this fix into Lvalue::set.
3279 DerivedDecl = D.MostDerivedType.getNonReferenceType()->getAsCXXRecordDecl();
3280 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
3281 return false;
3282
3283 // Find the virtual base class.
3284 if (DerivedDecl->isInvalidDecl()) return false;
3285 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
3286 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
3287 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
3288 return true;
3289}
3290
3291static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
3292 QualType Type, LValue &Result) {
3293 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3294 PathE = E->path_end();
3295 PathI != PathE; ++PathI) {
3296 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3297 *PathI))
3298 return false;
3299 Type = (*PathI)->getType();
3300 }
3301 return true;
3302}
3303
3304/// Cast an lvalue referring to a derived class to a known base subobject.
3305static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
3306 const CXXRecordDecl *DerivedRD,
3307 const CXXRecordDecl *BaseRD) {
3308 CXXBasePaths Paths(/*FindAmbiguities=*/false,
3309 /*RecordPaths=*/true, /*DetectVirtual=*/false);
3310 if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
3311 llvm_unreachable("Class must be derived from the passed in base class!");
3312
3313 for (CXXBasePathElement &Elem : Paths.front())
3314 if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
3315 return false;
3316 return true;
3317}
3318
3319/// Update LVal to refer to the given field, which must be a member of the type
3320/// currently described by LVal.
3321static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
3322 const FieldDecl *FD,
3323 const ASTRecordLayout *RL = nullptr) {
3324 if (!RL) {
3325 if (FD->getParent()->isInvalidDecl()) return false;
3326 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
3327 }
3328
3329 unsigned I = FD->getFieldIndex();
3330 LVal.addDecl(Info, E, FD);
3331 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
3332 return true;
3333}
3334
3335/// Update LVal to refer to the given indirect field.
3336static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
3337 LValue &LVal,
3338 const IndirectFieldDecl *IFD) {
3339 for (const auto *C : IFD->chain())
3340 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
3341 return false;
3342 return true;
3343}
3344
3349
3350/// Get the size of the given type in char units.
3351static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, QualType Type,
3353 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
3354 // extension.
3355 if (Type->isVoidType() || Type->isFunctionType()) {
3356 Size = CharUnits::One();
3357 return true;
3358 }
3359
3360 if (Type->isDependentType()) {
3361 Info.FFDiag(Loc);
3362 return false;
3363 }
3364
3365 if (!Type->isConstantSizeType()) {
3366 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
3367 // FIXME: Better diagnostic.
3368 Info.FFDiag(Loc);
3369 return false;
3370 }
3371
3372 if (SOT == SizeOfType::SizeOf)
3373 Size = Info.Ctx.getTypeSizeInChars(Type);
3374 else
3375 Size = Info.Ctx.getTypeInfoDataSizeInChars(Type).Width;
3376 return true;
3377}
3378
3379/// Update a pointer value to model pointer arithmetic.
3380/// \param Info - Information about the ongoing evaluation.
3381/// \param E - The expression being evaluated, for diagnostic purposes.
3382/// \param LVal - The pointer value to be updated.
3383/// \param EltTy - The pointee type represented by LVal.
3384/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
3385static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3386 LValue &LVal, QualType EltTy,
3387 APSInt Adjustment) {
3388 CharUnits SizeOfPointee;
3389 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
3390 return false;
3391
3392 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
3393 return true;
3394}
3395
3396static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3397 LValue &LVal, QualType EltTy,
3398 int64_t Adjustment) {
3399 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
3400 APSInt::get(Adjustment));
3401}
3402
3403/// Update an lvalue to refer to a component of a complex number.
3404/// \param Info - Information about the ongoing evaluation.
3405/// \param LVal - The lvalue to be updated.
3406/// \param EltTy - The complex number's component type.
3407/// \param Imag - False for the real component, true for the imaginary.
3408static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
3409 LValue &LVal, QualType EltTy,
3410 bool Imag) {
3411 if (Imag) {
3412 CharUnits SizeOfComponent;
3413 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
3414 return false;
3415 LVal.Offset += SizeOfComponent;
3416 }
3417 LVal.addComplex(Info, E, EltTy, Imag);
3418 return true;
3419}
3420
3421static bool HandleLValueVectorElement(EvalInfo &Info, const Expr *E,
3422 LValue &LVal, QualType EltTy,
3423 uint64_t Size, uint64_t Idx) {
3424 if (Idx) {
3425 CharUnits SizeOfElement;
3426 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfElement))
3427 return false;
3428 LVal.Offset += SizeOfElement * Idx;
3429 }
3430 LVal.addVectorElement(Info, E, EltTy, Size, Idx);
3431 return true;
3432}
3433
3434/// Try to evaluate the initializer for a variable declaration.
3435///
3436/// \param Info Information about the ongoing evaluation.
3437/// \param E An expression to be used when printing diagnostics.
3438/// \param VD The variable whose initializer should be obtained.
3439/// \param Version The version of the variable within the frame.
3440/// \param Frame The frame in which the variable was created. Must be null
3441/// if this variable is not local to the evaluation.
3442/// \param Result Filled in with a pointer to the value of the variable.
3443static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
3444 const VarDecl *VD, CallStackFrame *Frame,
3445 unsigned Version, APValue *&Result) {
3446 // C++23 [expr.const]p8 If we have a reference type allow unknown references
3447 // and pointers.
3448 bool AllowConstexprUnknown =
3449 Info.getLangOpts().CPlusPlus23 && VD->getType()->isReferenceType();
3450
3451 APValue::LValueBase Base(VD, Frame ? Frame->Index : 0, Version);
3452
3453 auto CheckUninitReference = [&](bool IsLocalVariable) {
3454 if (!Result || (!Result->hasValue() && VD->getType()->isReferenceType())) {
3455 // C++23 [expr.const]p8
3456 // ... For such an object that is not usable in constant expressions, the
3457 // dynamic type of the object is constexpr-unknown. For such a reference
3458 // that is not usable in constant expressions, the reference is treated
3459 // as binding to an unspecified object of the referenced type whose
3460 // lifetime and that of all subobjects includes the entire constant
3461 // evaluation and whose dynamic type is constexpr-unknown.
3462 //
3463 // Variables that are part of the current evaluation are not
3464 // constexpr-unknown.
3465 if (!AllowConstexprUnknown || IsLocalVariable) {
3466 if (!Info.checkingPotentialConstantExpression())
3467 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
3468 return false;
3469 }
3470 Result = nullptr;
3471 }
3472 return true;
3473 };
3474
3475 // If this is a local variable, dig out its value.
3476 if (Frame) {
3477 Result = Frame->getTemporary(VD, Version);
3478 if (Result)
3479 return CheckUninitReference(/*IsLocalVariable=*/true);
3480
3481 if (!isa<ParmVarDecl>(VD)) {
3482 // Assume variables referenced within a lambda's call operator that were
3483 // not declared within the call operator are captures and during checking
3484 // of a potential constant expression, assume they are unknown constant
3485 // expressions.
3486 assert(isLambdaCallOperator(Frame->Callee) &&
3487 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
3488 "missing value for local variable");
3489 if (Info.checkingPotentialConstantExpression())
3490 return false;
3491 // FIXME: This diagnostic is bogus; we do support captures. Is this code
3492 // still reachable at all?
3493 Info.FFDiag(E->getBeginLoc(),
3494 diag::note_unimplemented_constexpr_lambda_feature_ast)
3495 << "captures not currently allowed";
3496 return false;
3497 }
3498 }
3499
3500 // If we're currently evaluating the initializer of this declaration, use that
3501 // in-flight value.
3502 if (Info.EvaluatingDecl == Base) {
3503 Result = Info.EvaluatingDeclValue;
3504 return CheckUninitReference(/*IsLocalVariable=*/false);
3505 }
3506
3507 // P2280R4 struck the restriction that variable of reference type lifetime
3508 // should begin within the evaluation of E
3509 // Used to be C++20 [expr.const]p5.12.2:
3510 // ... its lifetime began within the evaluation of E;
3511 if (isa<ParmVarDecl>(VD)) {
3512 if (AllowConstexprUnknown) {
3513 Result = nullptr;
3514 return true;
3515 }
3516
3517 // Assume parameters of a potential constant expression are usable in
3518 // constant expressions.
3519 if (!Info.checkingPotentialConstantExpression() ||
3520 !Info.CurrentCall->Callee ||
3521 !Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
3522 if (Info.getLangOpts().CPlusPlus11) {
3523 Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown)
3524 << VD;
3525 NoteLValueLocation(Info, Base);
3526 } else {
3527 Info.FFDiag(E);
3528 }
3529 }
3530 return false;
3531 }
3532
3533 if (E->isValueDependent())
3534 return false;
3535
3536 // Dig out the initializer, and use the declaration which it's attached to.
3537 // FIXME: We should eventually check whether the variable has a reachable
3538 // initializing declaration.
3539 const Expr *Init = VD->getAnyInitializer(VD);
3540 // P2280R4 struck the restriction that variable of reference type should have
3541 // a preceding initialization.
3542 // Used to be C++20 [expr.const]p5.12:
3543 // ... reference has a preceding initialization and either ...
3544 if (!Init && !AllowConstexprUnknown) {
3545 // Don't diagnose during potential constant expression checking; an
3546 // initializer might be added later.
3547 if (!Info.checkingPotentialConstantExpression()) {
3548 Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1)
3549 << VD;
3550 NoteLValueLocation(Info, Base);
3551 }
3552 return false;
3553 }
3554
3555 // P2280R4 struck the initialization requirement for variables of reference
3556 // type so we can no longer assume we have an Init.
3557 // Used to be C++20 [expr.const]p5.12:
3558 // ... reference has a preceding initialization and either ...
3559 if (Init && Init->isValueDependent()) {
3560 // The DeclRefExpr is not value-dependent, but the variable it refers to
3561 // has a value-dependent initializer. This should only happen in
3562 // constant-folding cases, where the variable is not actually of a suitable
3563 // type for use in a constant expression (otherwise the DeclRefExpr would
3564 // have been value-dependent too), so diagnose that.
3565 assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx));
3566 if (!Info.checkingPotentialConstantExpression()) {
3567 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
3568 ? diag::note_constexpr_ltor_non_constexpr
3569 : diag::note_constexpr_ltor_non_integral, 1)
3570 << VD << VD->getType();
3571 NoteLValueLocation(Info, Base);
3572 }
3573 return false;
3574 }
3575
3576 // Check that we can fold the initializer. In C++, we will have already done
3577 // this in the cases where it matters for conformance.
3578 // P2280R4 struck the initialization requirement for variables of reference
3579 // type so we can no longer assume we have an Init.
3580 // Used to be C++20 [expr.const]p5.12:
3581 // ... reference has a preceding initialization and either ...
3582 if (Init && !VD->evaluateValue() && !AllowConstexprUnknown) {
3583 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3584 NoteLValueLocation(Info, Base);
3585 return false;
3586 }
3587
3588 // Check that the variable is actually usable in constant expressions. For a
3589 // const integral variable or a reference, we might have a non-constant
3590 // initializer that we can nonetheless evaluate the initializer for. Such
3591 // variables are not usable in constant expressions. In C++98, the
3592 // initializer also syntactically needs to be an ICE.
3593 //
3594 // FIXME: We don't diagnose cases that aren't potentially usable in constant
3595 // expressions here; doing so would regress diagnostics for things like
3596 // reading from a volatile constexpr variable.
3597 if ((Info.getLangOpts().CPlusPlus && !VD->hasConstantInitialization() &&
3598 VD->mightBeUsableInConstantExpressions(Info.Ctx) &&
3599 !AllowConstexprUnknown) ||
3600 ((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) &&
3601 !Info.getLangOpts().CPlusPlus11 && !VD->hasICEInitializer(Info.Ctx))) {
3602 if (Init) {
3603 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3604 NoteLValueLocation(Info, Base);
3605 } else {
3606 Info.CCEDiag(E);
3607 }
3608 }
3609
3610 // Never use the initializer of a weak variable, not even for constant
3611 // folding. We can't be sure that this is the definition that will be used.
3612 if (VD->isWeak()) {
3613 Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD;
3614 NoteLValueLocation(Info, Base);
3615 return false;
3616 }
3617
3618 Result = VD->getEvaluatedValue();
3619
3620 if (!Result && !AllowConstexprUnknown)
3621 return false;
3622
3623 return CheckUninitReference(/*IsLocalVariable=*/false);
3624}
3625
3626/// Get the base index of the given base class within an APValue representing
3627/// the given derived class.
3628static unsigned getBaseIndex(const CXXRecordDecl *Derived,
3629 const CXXRecordDecl *Base) {
3630 Base = Base->getCanonicalDecl();
3631 unsigned Index = 0;
3633 E = Derived->bases_end(); I != E; ++I, ++Index) {
3634 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
3635 return Index;
3636 }
3637
3638 llvm_unreachable("base class missing from derived class's bases list");
3639}
3640
3641/// Extract the value of a character from a string literal.
3642static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
3643 uint64_t Index) {
3644 assert(!isa<SourceLocExpr>(Lit) &&
3645 "SourceLocExpr should have already been converted to a StringLiteral");
3646
3647 // FIXME: Support MakeStringConstant
3648 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
3649 std::string Str;
3650 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
3651 assert(Index <= Str.size() && "Index too large");
3652 return APSInt::getUnsigned(Str.c_str()[Index]);
3653 }
3654
3655 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
3656 Lit = PE->getFunctionName();
3657 const StringLiteral *S = cast<StringLiteral>(Lit);
3658 const ConstantArrayType *CAT =
3659 Info.Ctx.getAsConstantArrayType(S->getType());
3660 assert(CAT && "string literal isn't an array");
3661 QualType CharType = CAT->getElementType();
3662 assert(CharType->isIntegerType() && "unexpected character type");
3663 APSInt Value(Info.Ctx.getTypeSize(CharType),
3664 CharType->isUnsignedIntegerType());
3665 if (Index < S->getLength())
3666 Value = S->getCodeUnit(Index);
3667 return Value;
3668}
3669
3670// Expand a string literal into an array of characters.
3671//
3672// FIXME: This is inefficient; we should probably introduce something similar
3673// to the LLVM ConstantDataArray to make this cheaper.
3674static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
3675 APValue &Result,
3676 QualType AllocType = QualType()) {
3677 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
3678 AllocType.isNull() ? S->getType() : AllocType);
3679 assert(CAT && "string literal isn't an array");
3680 QualType CharType = CAT->getElementType();
3681 assert(CharType->isIntegerType() && "unexpected character type");
3682
3683 unsigned Elts = CAT->getZExtSize();
3684 Result = APValue(APValue::UninitArray(),
3685 std::min(S->getLength(), Elts), Elts);
3686 APSInt Value(Info.Ctx.getTypeSize(CharType),
3687 CharType->isUnsignedIntegerType());
3688 if (Result.hasArrayFiller())
3689 Result.getArrayFiller() = APValue(Value);
3690 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
3691 Value = S->getCodeUnit(I);
3692 Result.getArrayInitializedElt(I) = APValue(Value);
3693 }
3694}
3695
3696// Expand an array so that it has more than Index filled elements.
3697static void expandArray(APValue &Array, unsigned Index) {
3698 unsigned Size = Array.getArraySize();
3699 assert(Index < Size);
3700
3701 // Always at least double the number of elements for which we store a value.
3702 unsigned OldElts = Array.getArrayInitializedElts();
3703 unsigned NewElts = std::max(Index+1, OldElts * 2);
3704 NewElts = std::min(Size, std::max(NewElts, 8u));
3705
3706 // Copy the data across.
3707 APValue NewValue(APValue::UninitArray(), NewElts, Size);
3708 for (unsigned I = 0; I != OldElts; ++I)
3709 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
3710 for (unsigned I = OldElts; I != NewElts; ++I)
3711 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
3712 if (NewValue.hasArrayFiller())
3713 NewValue.getArrayFiller() = Array.getArrayFiller();
3714 Array.swap(NewValue);
3715}
3716
3717/// Determine whether a type would actually be read by an lvalue-to-rvalue
3718/// conversion. If it's of class type, we may assume that the copy operation
3719/// is trivial. Note that this is never true for a union type with fields
3720/// (because the copy always "reads" the active member) and always true for
3721/// a non-class type.
3722static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD);
3724 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3725 return !RD || isReadByLvalueToRvalueConversion(RD);
3726}
3728 // FIXME: A trivial copy of a union copies the object representation, even if
3729 // the union is empty.
3730 if (RD->isUnion())
3731 return !RD->field_empty();
3732 if (RD->isEmpty())
3733 return false;
3734
3735 for (auto *Field : RD->fields())
3736 if (!Field->isUnnamedBitField() &&
3737 isReadByLvalueToRvalueConversion(Field->getType()))
3738 return true;
3739
3740 for (auto &BaseSpec : RD->bases())
3741 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
3742 return true;
3743
3744 return false;
3745}
3746
3747/// Diagnose an attempt to read from any unreadable field within the specified
3748/// type, which might be a class type.
3749static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK,
3750 QualType T) {
3751 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3752 if (!RD)
3753 return false;
3754
3755 if (!RD->hasMutableFields())
3756 return false;
3757
3758 for (auto *Field : RD->fields()) {
3759 // If we're actually going to read this field in some way, then it can't
3760 // be mutable. If we're in a union, then assigning to a mutable field
3761 // (even an empty one) can change the active member, so that's not OK.
3762 // FIXME: Add core issue number for the union case.
3763 if (Field->isMutable() &&
3764 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
3765 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field;
3766 Info.Note(Field->getLocation(), diag::note_declared_at);
3767 return true;
3768 }
3769
3770 if (diagnoseMutableFields(Info, E, AK, Field->getType()))
3771 return true;
3772 }
3773
3774 for (auto &BaseSpec : RD->bases())
3775 if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType()))
3776 return true;
3777
3778 // All mutable fields were empty, and thus not actually read.
3779 return false;
3780}
3781
3782static bool lifetimeStartedInEvaluation(EvalInfo &Info,
3784 bool MutableSubobject = false) {
3785 // A temporary or transient heap allocation we created.
3786 if (Base.getCallIndex() || Base.is<DynamicAllocLValue>())
3787 return true;
3788
3789 switch (Info.IsEvaluatingDecl) {
3790 case EvalInfo::EvaluatingDeclKind::None:
3791 return false;
3792
3793 case EvalInfo::EvaluatingDeclKind::Ctor:
3794 // The variable whose initializer we're evaluating.
3795 if (Info.EvaluatingDecl == Base)
3796 return true;
3797
3798 // A temporary lifetime-extended by the variable whose initializer we're
3799 // evaluating.
3800 if (auto *BaseE = Base.dyn_cast<const Expr *>())
3801 if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
3802 return Info.EvaluatingDecl == BaseMTE->getExtendingDecl();
3803 return false;
3804
3805 case EvalInfo::EvaluatingDeclKind::Dtor:
3806 // C++2a [expr.const]p6:
3807 // [during constant destruction] the lifetime of a and its non-mutable
3808 // subobjects (but not its mutable subobjects) [are] considered to start
3809 // within e.
3810 if (MutableSubobject || Base != Info.EvaluatingDecl)
3811 return false;
3812 // FIXME: We can meaningfully extend this to cover non-const objects, but
3813 // we will need special handling: we should be able to access only
3814 // subobjects of such objects that are themselves declared const.
3816 return T.isConstQualified() || T->isReferenceType();
3817 }
3818
3819 llvm_unreachable("unknown evaluating decl kind");
3820}
3821
3822static bool CheckArraySize(EvalInfo &Info, const ConstantArrayType *CAT,
3823 SourceLocation CallLoc = {}) {
3824 return Info.CheckArraySize(
3825 CAT->getSizeExpr() ? CAT->getSizeExpr()->getBeginLoc() : CallLoc,
3826 CAT->getNumAddressingBits(Info.Ctx), CAT->getZExtSize(),
3827 /*Diag=*/true);
3828}
3829
3830static bool handleScalarCast(EvalInfo &Info, const FPOptions FPO, const Expr *E,
3831 QualType SourceTy, QualType DestTy,
3832 APValue const &Original, APValue &Result) {
3833 // boolean must be checked before integer
3834 // since IsIntegerType() is true for bool
3835 if (SourceTy->isBooleanType()) {
3836 if (DestTy->isBooleanType()) {
3837 Result = Original;
3838 return true;
3839 }
3840 if (DestTy->isIntegerType() || DestTy->isRealFloatingType()) {
3841 bool BoolResult;
3842 if (!HandleConversionToBool(Original, BoolResult))
3843 return false;
3844 uint64_t IntResult = BoolResult;
3845 QualType IntType = DestTy->isIntegerType()
3846 ? DestTy
3847 : Info.Ctx.getIntTypeForBitwidth(64, false);
3848 Result = APValue(Info.Ctx.MakeIntValue(IntResult, IntType));
3849 }
3850 if (DestTy->isRealFloatingType()) {
3851 APValue Result2 = APValue(APFloat(0.0));
3852 if (!HandleIntToFloatCast(Info, E, FPO,
3853 Info.Ctx.getIntTypeForBitwidth(64, false),
3854 Result.getInt(), DestTy, Result2.getFloat()))
3855 return false;
3856 Result = Result2;
3857 }
3858 return true;
3859 }
3860 if (SourceTy->isIntegerType()) {
3861 if (DestTy->isRealFloatingType()) {
3862 Result = APValue(APFloat(0.0));
3863 return HandleIntToFloatCast(Info, E, FPO, SourceTy, Original.getInt(),
3864 DestTy, Result.getFloat());
3865 }
3866 if (DestTy->isBooleanType()) {
3867 bool BoolResult;
3868 if (!HandleConversionToBool(Original, BoolResult))
3869 return false;
3870 uint64_t IntResult = BoolResult;
3871 Result = APValue(Info.Ctx.MakeIntValue(IntResult, DestTy));
3872 return true;
3873 }
3874 if (DestTy->isIntegerType()) {
3875 Result = APValue(
3876 HandleIntToIntCast(Info, E, DestTy, SourceTy, Original.getInt()));
3877 return true;
3878 }
3879 } else if (SourceTy->isRealFloatingType()) {
3880 if (DestTy->isRealFloatingType()) {
3881 Result = Original;
3882 return HandleFloatToFloatCast(Info, E, SourceTy, DestTy,
3883 Result.getFloat());
3884 }
3885 if (DestTy->isBooleanType()) {
3886 bool BoolResult;
3887 if (!HandleConversionToBool(Original, BoolResult))
3888 return false;
3889 uint64_t IntResult = BoolResult;
3890 Result = APValue(Info.Ctx.MakeIntValue(IntResult, DestTy));
3891 return true;
3892 }
3893 if (DestTy->isIntegerType()) {
3894 Result = APValue(APSInt());
3895 return HandleFloatToIntCast(Info, E, SourceTy, Original.getFloat(),
3896 DestTy, Result.getInt());
3897 }
3898 }
3899
3900 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3901 return false;
3902}
3903
3904// do the heavy lifting for casting to aggregate types
3905// because we have to deal with bitfields specially
3906static bool constructAggregate(EvalInfo &Info, const FPOptions FPO,
3907 const Expr *E, APValue &Result,
3908 QualType ResultType,
3909 SmallVectorImpl<APValue> &Elements,
3910 SmallVectorImpl<QualType> &ElTypes) {
3911
3913 {&Result, ResultType, 0}};
3914
3915 unsigned ElI = 0;
3916 while (!WorkList.empty() && ElI < Elements.size()) {
3917 auto [Res, Type, BitWidth] = WorkList.pop_back_val();
3918
3919 if (Type->isRealFloatingType()) {
3920 if (!handleScalarCast(Info, FPO, E, ElTypes[ElI], Type, Elements[ElI],
3921 *Res))
3922 return false;
3923 ElI++;
3924 continue;
3925 }
3926 if (Type->isIntegerType()) {
3927 if (!handleScalarCast(Info, FPO, E, ElTypes[ElI], Type, Elements[ElI],
3928 *Res))
3929 return false;
3930 if (BitWidth > 0) {
3931 if (!Res->isInt())
3932 return false;
3933 APSInt &Int = Res->getInt();
3934 unsigned OldBitWidth = Int.getBitWidth();
3935 unsigned NewBitWidth = BitWidth;
3936 if (NewBitWidth < OldBitWidth)
3937 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
3938 }
3939 ElI++;
3940 continue;
3941 }
3942 if (Type->isVectorType()) {
3943 QualType ElTy = Type->castAs<VectorType>()->getElementType();
3944 unsigned NumEl = Type->castAs<VectorType>()->getNumElements();
3945 SmallVector<APValue> Vals(NumEl);
3946 for (unsigned I = 0; I < NumEl; ++I) {
3947 if (!handleScalarCast(Info, FPO, E, ElTypes[ElI], ElTy, Elements[ElI],
3948 Vals[I]))
3949 return false;
3950 ElI++;
3951 }
3952 *Res = APValue(Vals.data(), NumEl);
3953 continue;
3954 }
3955 if (Type->isConstantArrayType()) {
3957 ->getElementType();
3958 uint64_t Size =
3959 cast<ConstantArrayType>(Info.Ctx.getAsArrayType(Type))->getZExtSize();
3960 *Res = APValue(APValue::UninitArray(), Size, Size);
3961 for (int64_t I = Size - 1; I > -1; --I)
3962 WorkList.emplace_back(&Res->getArrayInitializedElt(I), ElTy, 0u);
3963 continue;
3964 }
3965 if (Type->isRecordType()) {
3966 const RecordDecl *RD = Type->getAsRecordDecl();
3967
3968 unsigned NumBases = 0;
3969 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
3970 NumBases = CXXRD->getNumBases();
3971
3972 *Res = APValue(APValue::UninitStruct(), NumBases, RD->getNumFields());
3973
3975 // we need to traverse backwards
3976 // Visit the base classes.
3977 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3978 if (CXXRD->getNumBases() > 0) {
3979 assert(CXXRD->getNumBases() == 1);
3980 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[0];
3981 ReverseList.emplace_back(&Res->getStructBase(0), BS.getType(), 0u);
3982 }
3983 }
3984
3985 // Visit the fields.
3986 for (FieldDecl *FD : RD->fields()) {
3987 unsigned FDBW = 0;
3988 if (FD->isUnnamedBitField())
3989 continue;
3990 if (FD->isBitField()) {
3991 FDBW = FD->getBitWidthValue();
3992 }
3993
3994 ReverseList.emplace_back(&Res->getStructField(FD->getFieldIndex()),
3995 FD->getType(), FDBW);
3996 }
3997
3998 std::reverse(ReverseList.begin(), ReverseList.end());
3999 llvm::append_range(WorkList, ReverseList);
4000 continue;
4001 }
4002 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
4003 return false;
4004 }
4005 return true;
4006}
4007
4008static bool handleElementwiseCast(EvalInfo &Info, const Expr *E,
4009 const FPOptions FPO,
4010 SmallVectorImpl<APValue> &Elements,
4011 SmallVectorImpl<QualType> &SrcTypes,
4012 SmallVectorImpl<QualType> &DestTypes,
4013 SmallVectorImpl<APValue> &Results) {
4014
4015 assert((Elements.size() == SrcTypes.size()) &&
4016 (Elements.size() == DestTypes.size()));
4017
4018 for (unsigned I = 0, ESz = Elements.size(); I < ESz; ++I) {
4019 APValue Original = Elements[I];
4020 QualType SourceTy = SrcTypes[I];
4021 QualType DestTy = DestTypes[I];
4022
4023 if (!handleScalarCast(Info, FPO, E, SourceTy, DestTy, Original, Results[I]))
4024 return false;
4025 }
4026 return true;
4027}
4028
4029static unsigned elementwiseSize(EvalInfo &Info, QualType BaseTy) {
4030
4031 SmallVector<QualType> WorkList = {BaseTy};
4032
4033 unsigned Size = 0;
4034 while (!WorkList.empty()) {
4035 QualType Type = WorkList.pop_back_val();
4037 Type->isBooleanType()) {
4038 ++Size;
4039 continue;
4040 }
4041 if (Type->isVectorType()) {
4042 unsigned NumEl = Type->castAs<VectorType>()->getNumElements();
4043 Size += NumEl;
4044 continue;
4045 }
4046 if (Type->isConstantArrayType()) {
4048 ->getElementType();
4049 uint64_t ArrSize =
4050 cast<ConstantArrayType>(Info.Ctx.getAsArrayType(Type))->getZExtSize();
4051 for (uint64_t I = 0; I < ArrSize; ++I) {
4052 WorkList.push_back(ElTy);
4053 }
4054 continue;
4055 }
4056 if (Type->isRecordType()) {
4057 const RecordDecl *RD = Type->getAsRecordDecl();
4058
4059 // Visit the base classes.
4060 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
4061 if (CXXRD->getNumBases() > 0) {
4062 assert(CXXRD->getNumBases() == 1);
4063 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[0];
4064 WorkList.push_back(BS.getType());
4065 }
4066 }
4067
4068 // visit the fields.
4069 for (FieldDecl *FD : RD->fields()) {
4070 if (FD->isUnnamedBitField())
4071 continue;
4072 WorkList.push_back(FD->getType());
4073 }
4074 continue;
4075 }
4076 }
4077 return Size;
4078}
4079
4080static bool hlslAggSplatHelper(EvalInfo &Info, const Expr *E, APValue &SrcVal,
4081 QualType &SrcTy) {
4082 SrcTy = E->getType();
4083
4084 if (!Evaluate(SrcVal, Info, E))
4085 return false;
4086
4087 assert((SrcVal.isFloat() || SrcVal.isInt() ||
4088 (SrcVal.isVector() && SrcVal.getVectorLength() == 1)) &&
4089 "Not a valid HLSLAggregateSplatCast.");
4090
4091 if (SrcVal.isVector()) {
4092 assert(SrcTy->isVectorType() && "Type mismatch.");
4093 SrcTy = SrcTy->castAs<VectorType>()->getElementType();
4094 SrcVal = SrcVal.getVectorElt(0);
4095 }
4096 return true;
4097}
4098
4099static bool flattenAPValue(EvalInfo &Info, const Expr *E, APValue Value,
4100 QualType BaseTy, SmallVectorImpl<APValue> &Elements,
4101 SmallVectorImpl<QualType> &Types, unsigned Size) {
4102
4103 SmallVector<std::pair<APValue, QualType>> WorkList = {{Value, BaseTy}};
4104 unsigned Populated = 0;
4105 while (!WorkList.empty() && Populated < Size) {
4106 auto [Work, Type] = WorkList.pop_back_val();
4107
4108 if (Work.isFloat() || Work.isInt()) {
4109 Elements.push_back(Work);
4110 Types.push_back(Type);
4111 Populated++;
4112 continue;
4113 }
4114 if (Work.isVector()) {
4115 assert(Type->isVectorType() && "Type mismatch.");
4116 QualType ElTy = Type->castAs<VectorType>()->getElementType();
4117 for (unsigned I = 0; I < Work.getVectorLength() && Populated < Size;
4118 I++) {
4119 Elements.push_back(Work.getVectorElt(I));
4120 Types.push_back(ElTy);
4121 Populated++;
4122 }
4123 continue;
4124 }
4125 if (Work.isArray()) {
4126 assert(Type->isConstantArrayType() && "Type mismatch.");
4128 ->getElementType();
4129 for (int64_t I = Work.getArraySize() - 1; I > -1; --I) {
4130 WorkList.emplace_back(Work.getArrayInitializedElt(I), ElTy);
4131 }
4132 continue;
4133 }
4134
4135 if (Work.isStruct()) {
4136 assert(Type->isRecordType() && "Type mismatch.");
4137
4138 const RecordDecl *RD = Type->getAsRecordDecl();
4139
4141 // Visit the fields.
4142 for (FieldDecl *FD : RD->fields()) {
4143 if (FD->isUnnamedBitField())
4144 continue;
4145 ReverseList.emplace_back(Work.getStructField(FD->getFieldIndex()),
4146 FD->getType());
4147 }
4148
4149 std::reverse(ReverseList.begin(), ReverseList.end());
4150 llvm::append_range(WorkList, ReverseList);
4151
4152 // Visit the base classes.
4153 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
4154 if (CXXRD->getNumBases() > 0) {
4155 assert(CXXRD->getNumBases() == 1);
4156 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[0];
4157 const APValue &Base = Work.getStructBase(0);
4158
4159 // Can happen in error cases.
4160 if (!Base.isStruct())
4161 return false;
4162
4163 WorkList.emplace_back(Base, BS.getType());
4164 }
4165 }
4166 continue;
4167 }
4168 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
4169 return false;
4170 }
4171 return true;
4172}
4173
4174namespace {
4175/// A handle to a complete object (an object that is not a subobject of
4176/// another object).
4177struct CompleteObject {
4178 /// The identity of the object.
4179 APValue::LValueBase Base;
4180 /// The value of the complete object.
4181 APValue *Value;
4182 /// The type of the complete object.
4183 QualType Type;
4184
4185 CompleteObject() : Value(nullptr) {}
4186 CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
4187 : Base(Base), Value(Value), Type(Type) {}
4188
4189 bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const {
4190 // If this isn't a "real" access (eg, if it's just accessing the type
4191 // info), allow it. We assume the type doesn't change dynamically for
4192 // subobjects of constexpr objects (even though we'd hit UB here if it
4193 // did). FIXME: Is this right?
4194 if (!isAnyAccess(AK))
4195 return true;
4196
4197 // In C++14 onwards, it is permitted to read a mutable member whose
4198 // lifetime began within the evaluation.
4199 // FIXME: Should we also allow this in C++11?
4200 if (!Info.getLangOpts().CPlusPlus14 &&
4201 AK != AccessKinds::AK_IsWithinLifetime)
4202 return false;
4203 return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);
4204 }
4205
4206 explicit operator bool() const { return !Type.isNull(); }
4207};
4208} // end anonymous namespace
4209
4210static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
4211 bool IsMutable = false) {
4212 // C++ [basic.type.qualifier]p1:
4213 // - A const object is an object of type const T or a non-mutable subobject
4214 // of a const object.
4215 if (ObjType.isConstQualified() && !IsMutable)
4216 SubobjType.addConst();
4217 // - A volatile object is an object of type const T or a subobject of a
4218 // volatile object.
4219 if (ObjType.isVolatileQualified())
4220 SubobjType.addVolatile();
4221 return SubobjType;
4222}
4223
4224/// Find the designated sub-object of an rvalue.
4225template <typename SubobjectHandler>
4226static typename SubobjectHandler::result_type
4227findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
4228 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
4229 if (Sub.Invalid)
4230 // A diagnostic will have already been produced.
4231 return handler.failed();
4232 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
4233 if (Info.getLangOpts().CPlusPlus11)
4234 Info.FFDiag(E, Sub.isOnePastTheEnd()
4235 ? diag::note_constexpr_access_past_end
4236 : diag::note_constexpr_access_unsized_array)
4237 << handler.AccessKind;
4238 else
4239 Info.FFDiag(E);
4240 return handler.failed();
4241 }
4242
4243 APValue *O = Obj.Value;
4244 QualType ObjType = Obj.Type;
4245 const FieldDecl *LastField = nullptr;
4246 const FieldDecl *VolatileField = nullptr;
4247
4248 // Walk the designator's path to find the subobject.
4249 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
4250 // Reading an indeterminate value is undefined, but assigning over one is OK.
4251 if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) ||
4252 (O->isIndeterminate() &&
4253 !isValidIndeterminateAccess(handler.AccessKind))) {
4254 // Object has ended lifetime.
4255 // If I is non-zero, some subobject (member or array element) of a
4256 // complete object has ended its lifetime, so this is valid for
4257 // IsWithinLifetime, resulting in false.
4258 if (I != 0 && handler.AccessKind == AK_IsWithinLifetime)
4259 return false;
4260 if (!Info.checkingPotentialConstantExpression())
4261 Info.FFDiag(E, diag::note_constexpr_access_uninit)
4262 << handler.AccessKind << O->isIndeterminate()
4263 << E->getSourceRange();
4264 return handler.failed();
4265 }
4266
4267 // C++ [class.ctor]p5, C++ [class.dtor]p5:
4268 // const and volatile semantics are not applied on an object under
4269 // {con,de}struction.
4270 if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
4271 ObjType->isRecordType() &&
4272 Info.isEvaluatingCtorDtor(
4273 Obj.Base, ArrayRef(Sub.Entries.begin(), Sub.Entries.begin() + I)) !=
4274 ConstructionPhase::None) {
4275 ObjType = Info.Ctx.getCanonicalType(ObjType);
4276 ObjType.removeLocalConst();
4277 ObjType.removeLocalVolatile();
4278 }
4279
4280 // If this is our last pass, check that the final object type is OK.
4281 if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
4282 // Accesses to volatile objects are prohibited.
4283 if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
4284 if (Info.getLangOpts().CPlusPlus) {
4285 int DiagKind;
4286 SourceLocation Loc;
4287 const NamedDecl *Decl = nullptr;
4288 if (VolatileField) {
4289 DiagKind = 2;
4290 Loc = VolatileField->getLocation();
4291 Decl = VolatileField;
4292 } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
4293 DiagKind = 1;
4294 Loc = VD->getLocation();
4295 Decl = VD;
4296 } else {
4297 DiagKind = 0;
4298 if (auto *E = Obj.Base.dyn_cast<const Expr *>())
4299 Loc = E->getExprLoc();
4300 }
4301 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
4302 << handler.AccessKind << DiagKind << Decl;
4303 Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
4304 } else {
4305 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
4306 }
4307 return handler.failed();
4308 }
4309
4310 // If we are reading an object of class type, there may still be more
4311 // things we need to check: if there are any mutable subobjects, we
4312 // cannot perform this read. (This only happens when performing a trivial
4313 // copy or assignment.)
4314 if (ObjType->isRecordType() &&
4315 !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
4316 diagnoseMutableFields(Info, E, handler.AccessKind, ObjType))
4317 return handler.failed();
4318 }
4319
4320 if (I == N) {
4321 if (!handler.found(*O, ObjType))
4322 return false;
4323
4324 // If we modified a bit-field, truncate it to the right width.
4325 if (isModification(handler.AccessKind) &&
4326 LastField && LastField->isBitField() &&
4327 !truncateBitfieldValue(Info, E, *O, LastField))
4328 return false;
4329
4330 return true;
4331 }
4332
4333 LastField = nullptr;
4334 if (ObjType->isArrayType()) {
4335 // Next subobject is an array element.
4336 const ArrayType *AT = Info.Ctx.getAsArrayType(ObjType);
4338 "vla in literal type?");
4339 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
4340 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT);
4341 CAT && CAT->getSize().ule(Index)) {
4342 // Note, it should not be possible to form a pointer with a valid
4343 // designator which points more than one past the end of the array.
4344 if (Info.getLangOpts().CPlusPlus11)
4345 Info.FFDiag(E, diag::note_constexpr_access_past_end)
4346 << handler.AccessKind;
4347 else
4348 Info.FFDiag(E);
4349 return handler.failed();
4350 }
4351
4352 ObjType = AT->getElementType();
4353
4354 if (O->getArrayInitializedElts() > Index)
4355 O = &O->getArrayInitializedElt(Index);
4356 else if (!isRead(handler.AccessKind)) {
4357 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT);
4358 CAT && !CheckArraySize(Info, CAT, E->getExprLoc()))
4359 return handler.failed();
4360
4361 expandArray(*O, Index);
4362 O = &O->getArrayInitializedElt(Index);
4363 } else
4364 O = &O->getArrayFiller();
4365 } else if (ObjType->isAnyComplexType()) {
4366 // Next subobject is a complex number.
4367 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
4368 if (Index > 1) {
4369 if (Info.getLangOpts().CPlusPlus11)
4370 Info.FFDiag(E, diag::note_constexpr_access_past_end)
4371 << handler.AccessKind;
4372 else
4373 Info.FFDiag(E);
4374 return handler.failed();
4375 }
4376
4377 ObjType = getSubobjectType(
4378 ObjType, ObjType->castAs<ComplexType>()->getElementType());
4379
4380 assert(I == N - 1 && "extracting subobject of scalar?");
4381 if (O->isComplexInt()) {
4382 return handler.found(Index ? O->getComplexIntImag()
4383 : O->getComplexIntReal(), ObjType);
4384 } else {
4385 assert(O->isComplexFloat());
4386 return handler.found(Index ? O->getComplexFloatImag()
4387 : O->getComplexFloatReal(), ObjType);
4388 }
4389 } else if (const auto *VT = ObjType->getAs<VectorType>()) {
4390 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
4391 unsigned NumElements = VT->getNumElements();
4392 if (Index == NumElements) {
4393 if (Info.getLangOpts().CPlusPlus11)
4394 Info.FFDiag(E, diag::note_constexpr_access_past_end)
4395 << handler.AccessKind;
4396 else
4397 Info.FFDiag(E);
4398 return handler.failed();
4399 }
4400
4401 if (Index > NumElements) {
4402 Info.CCEDiag(E, diag::note_constexpr_array_index)
4403 << Index << /*array*/ 0 << NumElements;
4404 return handler.failed();
4405 }
4406
4407 ObjType = VT->getElementType();
4408 assert(I == N - 1 && "extracting subobject of scalar?");
4409 return handler.found(O->getVectorElt(Index), ObjType);
4410 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
4411 if (Field->isMutable() &&
4412 !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) {
4413 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
4414 << handler.AccessKind << Field;
4415 Info.Note(Field->getLocation(), diag::note_declared_at);
4416 return handler.failed();
4417 }
4418
4419 // Next subobject is a class, struct or union field.
4420 RecordDecl *RD = ObjType->castAsCanonical<RecordType>()->getDecl();
4421 if (RD->isUnion()) {
4422 const FieldDecl *UnionField = O->getUnionField();
4423 if (!UnionField ||
4424 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
4425 if (I == N - 1 && handler.AccessKind == AK_Construct) {
4426 // Placement new onto an inactive union member makes it active.
4427 O->setUnion(Field, APValue());
4428 } else {
4429 // Pointer to/into inactive union member: Not within lifetime
4430 if (handler.AccessKind == AK_IsWithinLifetime)
4431 return false;
4432 // FIXME: If O->getUnionValue() is absent, report that there's no
4433 // active union member rather than reporting the prior active union
4434 // member. We'll need to fix nullptr_t to not use APValue() as its
4435 // representation first.
4436 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
4437 << handler.AccessKind << Field << !UnionField << UnionField;
4438 return handler.failed();
4439 }
4440 }
4441 O = &O->getUnionValue();
4442 } else
4443 O = &O->getStructField(Field->getFieldIndex());
4444
4445 ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
4446 LastField = Field;
4447 if (Field->getType().isVolatileQualified())
4448 VolatileField = Field;
4449 } else {
4450 // Next subobject is a base class.
4451 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
4452 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
4453 O = &O->getStructBase(getBaseIndex(Derived, Base));
4454
4455 ObjType = getSubobjectType(ObjType, Info.Ctx.getCanonicalTagType(Base));
4456 }
4457 }
4458}
4459
4460namespace {
4461struct ExtractSubobjectHandler {
4462 EvalInfo &Info;
4463 const Expr *E;
4464 APValue &Result;
4465 const AccessKinds AccessKind;
4466
4467 typedef bool result_type;
4468 bool failed() { return false; }
4469 bool found(APValue &Subobj, QualType SubobjType) {
4470 Result = Subobj;
4471 if (AccessKind == AK_ReadObjectRepresentation)
4472 return true;
4473 return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
4474 }
4475 bool found(APSInt &Value, QualType SubobjType) {
4476 Result = APValue(Value);
4477 return true;
4478 }
4479 bool found(APFloat &Value, QualType SubobjType) {
4480 Result = APValue(Value);
4481 return true;
4482 }
4483};
4484} // end anonymous namespace
4485
4486/// Extract the designated sub-object of an rvalue.
4487static bool extractSubobject(EvalInfo &Info, const Expr *E,
4488 const CompleteObject &Obj,
4489 const SubobjectDesignator &Sub, APValue &Result,
4490 AccessKinds AK = AK_Read) {
4491 assert(AK == AK_Read || AK == AK_ReadObjectRepresentation);
4492 ExtractSubobjectHandler Handler = {Info, E, Result, AK};
4493 return findSubobject(Info, E, Obj, Sub, Handler);
4494}
4495
4496namespace {
4497struct ModifySubobjectHandler {
4498 EvalInfo &Info;
4499 APValue &NewVal;
4500 const Expr *E;
4501
4502 typedef bool result_type;
4503 static const AccessKinds AccessKind = AK_Assign;
4504
4505 bool checkConst(QualType QT) {
4506 // Assigning to a const object has undefined behavior.
4507 if (QT.isConstQualified()) {
4508 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4509 return false;
4510 }
4511 return true;
4512 }
4513
4514 bool failed() { return false; }
4515 bool found(APValue &Subobj, QualType SubobjType) {
4516 if (!checkConst(SubobjType))
4517 return false;
4518 // We've been given ownership of NewVal, so just swap it in.
4519 Subobj.swap(NewVal);
4520 return true;
4521 }
4522 bool found(APSInt &Value, QualType SubobjType) {
4523 if (!checkConst(SubobjType))
4524 return false;
4525 if (!NewVal.isInt()) {
4526 // Maybe trying to write a cast pointer value into a complex?
4527 Info.FFDiag(E);
4528 return false;
4529 }
4530 Value = NewVal.getInt();
4531 return true;
4532 }
4533 bool found(APFloat &Value, QualType SubobjType) {
4534 if (!checkConst(SubobjType))
4535 return false;
4536 Value = NewVal.getFloat();
4537 return true;
4538 }
4539};
4540} // end anonymous namespace
4541
4542const AccessKinds ModifySubobjectHandler::AccessKind;
4543
4544/// Update the designated sub-object of an rvalue to the given value.
4545static bool modifySubobject(EvalInfo &Info, const Expr *E,
4546 const CompleteObject &Obj,
4547 const SubobjectDesignator &Sub,
4548 APValue &NewVal) {
4549 ModifySubobjectHandler Handler = { Info, NewVal, E };
4550 return findSubobject(Info, E, Obj, Sub, Handler);
4551}
4552
4553/// Find the position where two subobject designators diverge, or equivalently
4554/// the length of the common initial subsequence.
4555static unsigned FindDesignatorMismatch(QualType ObjType,
4556 const SubobjectDesignator &A,
4557 const SubobjectDesignator &B,
4558 bool &WasArrayIndex) {
4559 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
4560 for (/**/; I != N; ++I) {
4561 if (!ObjType.isNull() &&
4562 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
4563 // Next subobject is an array element.
4564 if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
4565 WasArrayIndex = true;
4566 return I;
4567 }
4568 if (ObjType->isAnyComplexType())
4569 ObjType = ObjType->castAs<ComplexType>()->getElementType();
4570 else
4571 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
4572 } else {
4573 if (A.Entries[I].getAsBaseOrMember() !=
4574 B.Entries[I].getAsBaseOrMember()) {
4575 WasArrayIndex = false;
4576 return I;
4577 }
4578 if (const FieldDecl *FD = getAsField(A.Entries[I]))
4579 // Next subobject is a field.
4580 ObjType = FD->getType();
4581 else
4582 // Next subobject is a base class.
4583 ObjType = QualType();
4584 }
4585 }
4586 WasArrayIndex = false;
4587 return I;
4588}
4589
4590/// Determine whether the given subobject designators refer to elements of the
4591/// same array object.
4593 const SubobjectDesignator &A,
4594 const SubobjectDesignator &B) {
4595 if (A.Entries.size() != B.Entries.size())
4596 return false;
4597
4598 bool IsArray = A.MostDerivedIsArrayElement;
4599 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
4600 // A is a subobject of the array element.
4601 return false;
4602
4603 // If A (and B) designates an array element, the last entry will be the array
4604 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
4605 // of length 1' case, and the entire path must match.
4606 bool WasArrayIndex;
4607 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
4608 return CommonLength >= A.Entries.size() - IsArray;
4609}
4610
4611/// Find the complete object to which an LValue refers.
4612static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
4613 AccessKinds AK, const LValue &LVal,
4614 QualType LValType) {
4615 if (LVal.InvalidBase) {
4616 Info.FFDiag(E);
4617 return CompleteObject();
4618 }
4619
4620 if (!LVal.Base) {
4622 Info.FFDiag(E, diag::note_constexpr_dereferencing_null);
4623 else
4624 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
4625 return CompleteObject();
4626 }
4627
4628 CallStackFrame *Frame = nullptr;
4629 unsigned Depth = 0;
4630 if (LVal.getLValueCallIndex()) {
4631 std::tie(Frame, Depth) =
4632 Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
4633 if (!Frame) {
4634 Info.FFDiag(E, diag::note_constexpr_access_uninit, 1)
4635 << AK << /*Indeterminate=*/false << E->getSourceRange();
4636 NoteLValueLocation(Info, LVal.Base);
4637 return CompleteObject();
4638 }
4639 }
4640
4641 bool IsAccess = isAnyAccess(AK);
4642
4643 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
4644 // is not a constant expression (even if the object is non-volatile). We also
4645 // apply this rule to C++98, in order to conform to the expected 'volatile'
4646 // semantics.
4647 if (isFormalAccess(AK) && LValType.isVolatileQualified()) {
4648 if (Info.getLangOpts().CPlusPlus)
4649 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
4650 << AK << LValType;
4651 else
4652 Info.FFDiag(E);
4653 return CompleteObject();
4654 }
4655
4656 // Compute value storage location and type of base object.
4657 APValue *BaseVal = nullptr;
4658 QualType BaseType = getType(LVal.Base);
4659
4660 if (Info.getLangOpts().CPlusPlus14 && LVal.Base == Info.EvaluatingDecl &&
4661 lifetimeStartedInEvaluation(Info, LVal.Base)) {
4662 // This is the object whose initializer we're evaluating, so its lifetime
4663 // started in the current evaluation.
4664 BaseVal = Info.EvaluatingDeclValue;
4665 } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) {
4666 // Allow reading from a GUID declaration.
4667 if (auto *GD = dyn_cast<MSGuidDecl>(D)) {
4668 if (isModification(AK)) {
4669 // All the remaining cases do not permit modification of the object.
4670 Info.FFDiag(E, diag::note_constexpr_modify_global);
4671 return CompleteObject();
4672 }
4673 APValue &V = GD->getAsAPValue();
4674 if (V.isAbsent()) {
4675 Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
4676 << GD->getType();
4677 return CompleteObject();
4678 }
4679 return CompleteObject(LVal.Base, &V, GD->getType());
4680 }
4681
4682 // Allow reading the APValue from an UnnamedGlobalConstantDecl.
4683 if (auto *GCD = dyn_cast<UnnamedGlobalConstantDecl>(D)) {
4684 if (isModification(AK)) {
4685 Info.FFDiag(E, diag::note_constexpr_modify_global);
4686 return CompleteObject();
4687 }
4688 return CompleteObject(LVal.Base, const_cast<APValue *>(&GCD->getValue()),
4689 GCD->getType());
4690 }
4691
4692 // Allow reading from template parameter objects.
4693 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) {
4694 if (isModification(AK)) {
4695 Info.FFDiag(E, diag::note_constexpr_modify_global);
4696 return CompleteObject();
4697 }
4698 return CompleteObject(LVal.Base, const_cast<APValue *>(&TPO->getValue()),
4699 TPO->getType());
4700 }
4701
4702 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
4703 // In C++11, constexpr, non-volatile variables initialized with constant
4704 // expressions are constant expressions too. Inside constexpr functions,
4705 // parameters are constant expressions even if they're non-const.
4706 // In C++1y, objects local to a constant expression (those with a Frame) are
4707 // both readable and writable inside constant expressions.
4708 // In C, such things can also be folded, although they are not ICEs.
4709 const VarDecl *VD = dyn_cast<VarDecl>(D);
4710 if (VD) {
4711 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
4712 VD = VDef;
4713 }
4714 if (!VD || VD->isInvalidDecl()) {
4715 Info.FFDiag(E);
4716 return CompleteObject();
4717 }
4718
4719 bool IsConstant = BaseType.isConstant(Info.Ctx);
4720 bool ConstexprVar = false;
4721 if (const auto *VD = dyn_cast_if_present<VarDecl>(
4722 Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()))
4723 ConstexprVar = VD->isConstexpr();
4724
4725 // Unless we're looking at a local variable or argument in a constexpr call,
4726 // the variable we're reading must be const (unless we are binding to a
4727 // reference).
4728 if (AK != clang::AK_Dereference && !Frame) {
4729 if (IsAccess && isa<ParmVarDecl>(VD)) {
4730 // Access of a parameter that's not associated with a frame isn't going
4731 // to work out, but we can leave it to evaluateVarDeclInit to provide a
4732 // suitable diagnostic.
4733 } else if (Info.getLangOpts().CPlusPlus14 &&
4734 lifetimeStartedInEvaluation(Info, LVal.Base)) {
4735 // OK, we can read and modify an object if we're in the process of
4736 // evaluating its initializer, because its lifetime began in this
4737 // evaluation.
4738 } else if (isModification(AK)) {
4739 // All the remaining cases do not permit modification of the object.
4740 Info.FFDiag(E, diag::note_constexpr_modify_global);
4741 return CompleteObject();
4742 } else if (VD->isConstexpr()) {
4743 // OK, we can read this variable.
4744 } else if (Info.getLangOpts().C23 && ConstexprVar) {
4745 Info.FFDiag(E);
4746 return CompleteObject();
4747 } else if (BaseType->isIntegralOrEnumerationType()) {
4748 if (!IsConstant) {
4749 if (!IsAccess)
4750 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4751 if (Info.getLangOpts().CPlusPlus) {
4752 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
4753 Info.Note(VD->getLocation(), diag::note_declared_at);
4754 } else {
4755 Info.FFDiag(E);
4756 }
4757 return CompleteObject();
4758 }
4759 } else if (!IsAccess) {
4760 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4761 } else if ((IsConstant || BaseType->isReferenceType()) &&
4762 Info.checkingPotentialConstantExpression() &&
4763 BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) {
4764 // This variable might end up being constexpr. Don't diagnose it yet.
4765 } else if (IsConstant) {
4766 // Keep evaluating to see what we can do. In particular, we support
4767 // folding of const floating-point types, in order to make static const
4768 // data members of such types (supported as an extension) more useful.
4769 if (Info.getLangOpts().CPlusPlus) {
4770 Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11
4771 ? diag::note_constexpr_ltor_non_constexpr
4772 : diag::note_constexpr_ltor_non_integral, 1)
4773 << VD << BaseType;
4774 Info.Note(VD->getLocation(), diag::note_declared_at);
4775 } else {
4776 Info.CCEDiag(E);
4777 }
4778 } else {
4779 // Never allow reading a non-const value.
4780 if (Info.getLangOpts().CPlusPlus) {
4781 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
4782 ? diag::note_constexpr_ltor_non_constexpr
4783 : diag::note_constexpr_ltor_non_integral, 1)
4784 << VD << BaseType;
4785 Info.Note(VD->getLocation(), diag::note_declared_at);
4786 } else {
4787 Info.FFDiag(E);
4788 }
4789 return CompleteObject();
4790 }
4791 }
4792
4793 // When binding to a reference, the variable does not need to be constexpr
4794 // or have constant initalization.
4795 if (AK != clang::AK_Dereference &&
4796 !evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(),
4797 BaseVal))
4798 return CompleteObject();
4799 // If evaluateVarDeclInit sees a constexpr-unknown variable, it returns
4800 // a null BaseVal. Any constexpr-unknown variable seen here is an error:
4801 // we can't access a constexpr-unknown object.
4802 if (AK != clang::AK_Dereference && !BaseVal) {
4803 if (!Info.checkingPotentialConstantExpression()) {
4804 Info.FFDiag(E, diag::note_constexpr_access_unknown_variable, 1)
4805 << AK << VD;
4806 Info.Note(VD->getLocation(), diag::note_declared_at);
4807 }
4808 return CompleteObject();
4809 }
4810 } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) {
4811 std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
4812 if (!Alloc) {
4813 Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK;
4814 return CompleteObject();
4815 }
4816 return CompleteObject(LVal.Base, &(*Alloc)->Value,
4817 LVal.Base.getDynamicAllocType());
4818 }
4819 // When binding to a reference, the variable does not need to be
4820 // within its lifetime.
4821 else if (AK != clang::AK_Dereference) {
4822 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4823
4824 if (!Frame) {
4825 if (const MaterializeTemporaryExpr *MTE =
4826 dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
4827 assert(MTE->getStorageDuration() == SD_Static &&
4828 "should have a frame for a non-global materialized temporary");
4829
4830 // C++20 [expr.const]p4: [DR2126]
4831 // An object or reference is usable in constant expressions if it is
4832 // - a temporary object of non-volatile const-qualified literal type
4833 // whose lifetime is extended to that of a variable that is usable
4834 // in constant expressions
4835 //
4836 // C++20 [expr.const]p5:
4837 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
4838 // - a non-volatile glvalue that refers to an object that is usable
4839 // in constant expressions, or
4840 // - a non-volatile glvalue of literal type that refers to a
4841 // non-volatile object whose lifetime began within the evaluation
4842 // of E;
4843 //
4844 // C++11 misses the 'began within the evaluation of e' check and
4845 // instead allows all temporaries, including things like:
4846 // int &&r = 1;
4847 // int x = ++r;
4848 // constexpr int k = r;
4849 // Therefore we use the C++14-onwards rules in C++11 too.
4850 //
4851 // Note that temporaries whose lifetimes began while evaluating a
4852 // variable's constructor are not usable while evaluating the
4853 // corresponding destructor, not even if they're of const-qualified
4854 // types.
4855 if (!MTE->isUsableInConstantExpressions(Info.Ctx) &&
4856 !lifetimeStartedInEvaluation(Info, LVal.Base)) {
4857 if (!IsAccess)
4858 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4859 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
4860 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
4861 return CompleteObject();
4862 }
4863
4864 BaseVal = MTE->getOrCreateValue(false);
4865 assert(BaseVal && "got reference to unevaluated temporary");
4866 } else if (const CompoundLiteralExpr *CLE =
4867 dyn_cast_or_null<CompoundLiteralExpr>(Base)) {
4868 // According to GCC info page:
4869 //
4870 // 6.28 Compound Literals
4871 //
4872 // As an optimization, G++ sometimes gives array compound literals
4873 // longer lifetimes: when the array either appears outside a function or
4874 // has a const-qualified type. If foo and its initializer had elements
4875 // of type char *const rather than char *, or if foo were a global
4876 // variable, the array would have static storage duration. But it is
4877 // probably safest just to avoid the use of array compound literals in
4878 // C++ code.
4879 //
4880 // Obey that rule by checking constness for converted array types.
4881 if (QualType CLETy = CLE->getType(); CLETy->isArrayType() &&
4882 !LValType->isArrayType() &&
4883 !CLETy.isConstant(Info.Ctx)) {
4884 Info.FFDiag(E);
4885 Info.Note(CLE->getExprLoc(), diag::note_declared_at);
4886 return CompleteObject();
4887 }
4888
4889 BaseVal = &CLE->getStaticValue();
4890 } else {
4891 if (!IsAccess)
4892 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4893 APValue Val;
4894 LVal.moveInto(Val);
4895 Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
4896 << AK
4897 << Val.getAsString(Info.Ctx,
4898 Info.Ctx.getLValueReferenceType(LValType));
4899 NoteLValueLocation(Info, LVal.Base);
4900 return CompleteObject();
4901 }
4902 } else if (AK != clang::AK_Dereference) {
4903 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
4904 assert(BaseVal && "missing value for temporary");
4905 }
4906 }
4907
4908 // In C++14, we can't safely access any mutable state when we might be
4909 // evaluating after an unmodeled side effect. Parameters are modeled as state
4910 // in the caller, but aren't visible once the call returns, so they can be
4911 // modified in a speculatively-evaluated call.
4912 //
4913 // FIXME: Not all local state is mutable. Allow local constant subobjects
4914 // to be read here (but take care with 'mutable' fields).
4915 unsigned VisibleDepth = Depth;
4916 if (llvm::isa_and_nonnull<ParmVarDecl>(
4917 LVal.Base.dyn_cast<const ValueDecl *>()))
4918 ++VisibleDepth;
4919 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
4920 Info.EvalStatus.HasSideEffects) ||
4921 (isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth))
4922 return CompleteObject();
4923
4924 return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
4925}
4926
4927/// Perform an lvalue-to-rvalue conversion on the given glvalue. This
4928/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
4929/// glvalue referred to by an entity of reference type.
4930///
4931/// \param Info - Information about the ongoing evaluation.
4932/// \param Conv - The expression for which we are performing the conversion.
4933/// Used for diagnostics.
4934/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
4935/// case of a non-class type).
4936/// \param LVal - The glvalue on which we are attempting to perform this action.
4937/// \param RVal - The produced value will be placed here.
4938/// \param WantObjectRepresentation - If true, we're looking for the object
4939/// representation rather than the value, and in particular,
4940/// there is no requirement that the result be fully initialized.
4941static bool
4943 const LValue &LVal, APValue &RVal,
4944 bool WantObjectRepresentation = false) {
4945 if (LVal.Designator.Invalid)
4946 return false;
4947
4948 // Check for special cases where there is no existing APValue to look at.
4949 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4950
4951 AccessKinds AK =
4952 WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;
4953
4954 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
4956 // Special-case character extraction so we don't have to construct an
4957 // APValue for the whole string.
4958 assert(LVal.Designator.Entries.size() <= 1 &&
4959 "Can only read characters from string literals");
4960 if (LVal.Designator.Entries.empty()) {
4961 // Fail for now for LValue to RValue conversion of an array.
4962 // (This shouldn't show up in C/C++, but it could be triggered by a
4963 // weird EvaluateAsRValue call from a tool.)
4964 Info.FFDiag(Conv);
4965 return false;
4966 }
4967 if (LVal.Designator.isOnePastTheEnd()) {
4968 if (Info.getLangOpts().CPlusPlus11)
4969 Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
4970 else
4971 Info.FFDiag(Conv);
4972 return false;
4973 }
4974 uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
4975 RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
4976 return true;
4977 }
4978 }
4979
4980 CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
4981 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
4982}
4983
4984static bool hlslElementwiseCastHelper(EvalInfo &Info, const Expr *E,
4985 QualType DestTy,
4986 SmallVectorImpl<APValue> &SrcVals,
4987 SmallVectorImpl<QualType> &SrcTypes) {
4988 APValue Val;
4989 if (!Evaluate(Val, Info, E))
4990 return false;
4991
4992 // must be dealing with a record
4993 if (Val.isLValue()) {
4994 LValue LVal;
4995 LVal.setFrom(Info.Ctx, Val);
4996 if (!handleLValueToRValueConversion(Info, E, E->getType(), LVal, Val))
4997 return false;
4998 }
4999
5000 unsigned NEls = elementwiseSize(Info, DestTy);
5001 // flatten the source
5002 if (!flattenAPValue(Info, E, Val, E->getType(), SrcVals, SrcTypes, NEls))
5003 return false;
5004
5005 return true;
5006}
5007
5008/// Perform an assignment of Val to LVal. Takes ownership of Val.
5009static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
5010 QualType LValType, APValue &Val) {
5011 if (LVal.Designator.Invalid)
5012 return false;
5013
5014 if (!Info.getLangOpts().CPlusPlus14) {
5015 Info.FFDiag(E);
5016 return false;
5017 }
5018
5019 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
5020 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
5021}
5022
5023namespace {
5024struct CompoundAssignSubobjectHandler {
5025 EvalInfo &Info;
5026 const CompoundAssignOperator *E;
5027 QualType PromotedLHSType;
5029 const APValue &RHS;
5030
5031 static const AccessKinds AccessKind = AK_Assign;
5032
5033 typedef bool result_type;
5034
5035 bool checkConst(QualType QT) {
5036 // Assigning to a const object has undefined behavior.
5037 if (QT.isConstQualified()) {
5038 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
5039 return false;
5040 }
5041 return true;
5042 }
5043
5044 bool failed() { return false; }
5045 bool found(APValue &Subobj, QualType SubobjType) {
5046 switch (Subobj.getKind()) {
5047 case APValue::Int:
5048 return found(Subobj.getInt(), SubobjType);
5049 case APValue::Float:
5050 return found(Subobj.getFloat(), SubobjType);
5053 // FIXME: Implement complex compound assignment.
5054 Info.FFDiag(E);
5055 return false;
5056 case APValue::LValue:
5057 return foundPointer(Subobj, SubobjType);
5058 case APValue::Vector:
5059 return foundVector(Subobj, SubobjType);
5061 Info.FFDiag(E, diag::note_constexpr_access_uninit)
5062 << /*read of=*/0 << /*uninitialized object=*/1
5063 << E->getLHS()->getSourceRange();
5064 return false;
5065 default:
5066 // FIXME: can this happen?
5067 Info.FFDiag(E);
5068 return false;
5069 }
5070 }
5071
5072 bool foundVector(APValue &Value, QualType SubobjType) {
5073 if (!checkConst(SubobjType))
5074 return false;
5075
5076 if (!SubobjType->isVectorType()) {
5077 Info.FFDiag(E);
5078 return false;
5079 }
5080 return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS);
5081 }
5082
5083 bool found(APSInt &Value, QualType SubobjType) {
5084 if (!checkConst(SubobjType))
5085 return false;
5086
5087 if (!SubobjType->isIntegerType()) {
5088 // We don't support compound assignment on integer-cast-to-pointer
5089 // values.
5090 Info.FFDiag(E);
5091 return false;
5092 }
5093
5094 if (RHS.isInt()) {
5095 APSInt LHS =
5096 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
5097 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
5098 return false;
5099 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
5100 return true;
5101 } else if (RHS.isFloat()) {
5102 const FPOptions FPO = E->getFPFeaturesInEffect(
5103 Info.Ctx.getLangOpts());
5104 APFloat FValue(0.0);
5105 return HandleIntToFloatCast(Info, E, FPO, SubobjType, Value,
5106 PromotedLHSType, FValue) &&
5107 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
5108 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
5109 Value);
5110 }
5111
5112 Info.FFDiag(E);
5113 return false;
5114 }
5115 bool found(APFloat &Value, QualType SubobjType) {
5116 return checkConst(SubobjType) &&
5117 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
5118 Value) &&
5119 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
5120 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
5121 }
5122 bool foundPointer(APValue &Subobj, QualType SubobjType) {
5123 if (!checkConst(SubobjType))
5124 return false;
5125
5126 QualType PointeeType;
5127 if (const PointerType *PT = SubobjType->getAs<PointerType>())
5128 PointeeType = PT->getPointeeType();
5129
5130 if (PointeeType.isNull() || !RHS.isInt() ||
5131 (Opcode != BO_Add && Opcode != BO_Sub)) {
5132 Info.FFDiag(E);
5133 return false;
5134 }
5135
5136 APSInt Offset = RHS.getInt();
5137 if (Opcode == BO_Sub)
5138 negateAsSigned(Offset);
5139
5140 LValue LVal;
5141 LVal.setFrom(Info.Ctx, Subobj);
5142 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
5143 return false;
5144 LVal.moveInto(Subobj);
5145 return true;
5146 }
5147};
5148} // end anonymous namespace
5149
5150const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
5151
5152/// Perform a compound assignment of LVal <op>= RVal.
5153static bool handleCompoundAssignment(EvalInfo &Info,
5154 const CompoundAssignOperator *E,
5155 const LValue &LVal, QualType LValType,
5156 QualType PromotedLValType,
5157 BinaryOperatorKind Opcode,
5158 const APValue &RVal) {
5159 if (LVal.Designator.Invalid)
5160 return false;
5161
5162 if (!Info.getLangOpts().CPlusPlus14) {
5163 Info.FFDiag(E);
5164 return false;
5165 }
5166
5167 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
5168 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
5169 RVal };
5170 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
5171}
5172
5173namespace {
5174struct IncDecSubobjectHandler {
5175 EvalInfo &Info;
5176 const UnaryOperator *E;
5178 APValue *Old;
5179
5180 typedef bool result_type;
5181
5182 bool checkConst(QualType QT) {
5183 // Assigning to a const object has undefined behavior.
5184 if (QT.isConstQualified()) {
5185 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
5186 return false;
5187 }
5188 return true;
5189 }
5190
5191 bool failed() { return false; }
5192 bool found(APValue &Subobj, QualType SubobjType) {
5193 // Stash the old value. Also clear Old, so we don't clobber it later
5194 // if we're post-incrementing a complex.
5195 if (Old) {
5196 *Old = Subobj;
5197 Old = nullptr;
5198 }
5199
5200 switch (Subobj.getKind()) {
5201 case APValue::Int:
5202 return found(Subobj.getInt(), SubobjType);
5203 case APValue::Float:
5204 return found(Subobj.getFloat(), SubobjType);
5206 return found(Subobj.getComplexIntReal(),
5207 SubobjType->castAs<ComplexType>()->getElementType()
5208 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
5210 return found(Subobj.getComplexFloatReal(),
5211 SubobjType->castAs<ComplexType>()->getElementType()
5212 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
5213 case APValue::LValue:
5214 return foundPointer(Subobj, SubobjType);
5215 default:
5216 // FIXME: can this happen?
5217 Info.FFDiag(E);
5218 return false;
5219 }
5220 }
5221 bool found(APSInt &Value, QualType SubobjType) {
5222 if (!checkConst(SubobjType))
5223 return false;
5224
5225 if (!SubobjType->isIntegerType()) {
5226 // We don't support increment / decrement on integer-cast-to-pointer
5227 // values.
5228 Info.FFDiag(E);
5229 return false;
5230 }
5231
5232 if (Old) *Old = APValue(Value);
5233
5234 // bool arithmetic promotes to int, and the conversion back to bool
5235 // doesn't reduce mod 2^n, so special-case it.
5236 if (SubobjType->isBooleanType()) {
5237 if (AccessKind == AK_Increment)
5238 Value = 1;
5239 else
5240 Value = !Value;
5241 return true;
5242 }
5243
5244 bool WasNegative = Value.isNegative();
5245 if (AccessKind == AK_Increment) {
5246 ++Value;
5247
5248 if (!WasNegative && Value.isNegative() && E->canOverflow()) {
5249 APSInt ActualValue(Value, /*IsUnsigned*/true);
5250 return HandleOverflow(Info, E, ActualValue, SubobjType);
5251 }
5252 } else {
5253 --Value;
5254
5255 if (WasNegative && !Value.isNegative() && E->canOverflow()) {
5256 unsigned BitWidth = Value.getBitWidth();
5257 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
5258 ActualValue.setBit(BitWidth);
5259 return HandleOverflow(Info, E, ActualValue, SubobjType);
5260 }
5261 }
5262 return true;
5263 }
5264 bool found(APFloat &Value, QualType SubobjType) {
5265 if (!checkConst(SubobjType))
5266 return false;
5267
5268 if (Old) *Old = APValue(Value);
5269
5270 APFloat One(Value.getSemantics(), 1);
5271 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
5272 APFloat::opStatus St;
5273 if (AccessKind == AK_Increment)
5274 St = Value.add(One, RM);
5275 else
5276 St = Value.subtract(One, RM);
5277 return checkFloatingPointResult(Info, E, St);
5278 }
5279 bool foundPointer(APValue &Subobj, QualType SubobjType) {
5280 if (!checkConst(SubobjType))
5281 return false;
5282
5283 QualType PointeeType;
5284 if (const PointerType *PT = SubobjType->getAs<PointerType>())
5285 PointeeType = PT->getPointeeType();
5286 else {
5287 Info.FFDiag(E);
5288 return false;
5289 }
5290
5291 LValue LVal;
5292 LVal.setFrom(Info.Ctx, Subobj);
5293 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
5294 AccessKind == AK_Increment ? 1 : -1))
5295 return false;
5296 LVal.moveInto(Subobj);
5297 return true;
5298 }
5299};
5300} // end anonymous namespace
5301
5302/// Perform an increment or decrement on LVal.
5303static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
5304 QualType LValType, bool IsIncrement, APValue *Old) {
5305 if (LVal.Designator.Invalid)
5306 return false;
5307
5308 if (!Info.getLangOpts().CPlusPlus14) {
5309 Info.FFDiag(E);
5310 return false;
5311 }
5312
5313 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
5314 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
5315 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
5316 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
5317}
5318
5319/// Build an lvalue for the object argument of a member function call.
5320static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
5321 LValue &This) {
5322 if (Object->getType()->isPointerType() && Object->isPRValue())
5323 return EvaluatePointer(Object, This, Info);
5324
5325 if (Object->isGLValue())
5326 return EvaluateLValue(Object, This, Info);
5327
5328 if (Object->getType()->isLiteralType(Info.Ctx))
5329 return EvaluateTemporary(Object, This, Info);
5330
5331 if (Object->getType()->isRecordType() && Object->isPRValue())
5332 return EvaluateTemporary(Object, This, Info);
5333
5334 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
5335 return false;
5336}
5337
5338/// HandleMemberPointerAccess - Evaluate a member access operation and build an
5339/// lvalue referring to the result.
5340///
5341/// \param Info - Information about the ongoing evaluation.
5342/// \param LV - An lvalue referring to the base of the member pointer.
5343/// \param RHS - The member pointer expression.
5344/// \param IncludeMember - Specifies whether the member itself is included in
5345/// the resulting LValue subobject designator. This is not possible when
5346/// creating a bound member function.
5347/// \return The field or method declaration to which the member pointer refers,
5348/// or 0 if evaluation fails.
5349static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
5350 QualType LVType,
5351 LValue &LV,
5352 const Expr *RHS,
5353 bool IncludeMember = true) {
5354 MemberPtr MemPtr;
5355 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
5356 return nullptr;
5357
5358 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
5359 // member value, the behavior is undefined.
5360 if (!MemPtr.getDecl()) {
5361 // FIXME: Specific diagnostic.
5362 Info.FFDiag(RHS);
5363 return nullptr;
5364 }
5365
5366 if (MemPtr.isDerivedMember()) {
5367 // This is a member of some derived class. Truncate LV appropriately.
5368 // The end of the derived-to-base path for the base object must match the
5369 // derived-to-base path for the member pointer.
5370 // C++23 [expr.mptr.oper]p4:
5371 // If the result of E1 is an object [...] whose most derived object does
5372 // not contain the member to which E2 refers, the behavior is undefined.
5373 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
5374 LV.Designator.Entries.size()) {
5375 Info.FFDiag(RHS);
5376 return nullptr;
5377 }
5378 unsigned PathLengthToMember =
5379 LV.Designator.Entries.size() - MemPtr.Path.size();
5380 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
5381 const CXXRecordDecl *LVDecl = getAsBaseClass(
5382 LV.Designator.Entries[PathLengthToMember + I]);
5383 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
5384 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
5385 Info.FFDiag(RHS);
5386 return nullptr;
5387 }
5388 }
5389 // MemPtr.Path only contains the base classes of the class directly
5390 // containing the member E2. It is still necessary to check that the class
5391 // directly containing the member E2 lies on the derived-to-base path of E1
5392 // to avoid incorrectly permitting member pointer access into a sibling
5393 // class of the class containing the member E2. If this class would
5394 // correspond to the most-derived class of E1, it either isn't contained in
5395 // LV.Designator.Entries or the corresponding entry refers to an array
5396 // element instead. Therefore get the most derived class directly in this
5397 // case. Otherwise the previous entry should correpond to this class.
5398 const CXXRecordDecl *LastLVDecl =
5399 (PathLengthToMember > LV.Designator.MostDerivedPathLength)
5400 ? getAsBaseClass(LV.Designator.Entries[PathLengthToMember - 1])
5401 : LV.Designator.MostDerivedType->getAsCXXRecordDecl();
5402 const CXXRecordDecl *LastMPDecl = MemPtr.getContainingRecord();
5403 if (LastLVDecl->getCanonicalDecl() != LastMPDecl->getCanonicalDecl()) {
5404 Info.FFDiag(RHS);
5405 return nullptr;
5406 }
5407
5408 // Truncate the lvalue to the appropriate derived class.
5409 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
5410 PathLengthToMember))
5411 return nullptr;
5412 } else if (!MemPtr.Path.empty()) {
5413 // Extend the LValue path with the member pointer's path.
5414 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
5415 MemPtr.Path.size() + IncludeMember);
5416
5417 // Walk down to the appropriate base class.
5418 if (const PointerType *PT = LVType->getAs<PointerType>())
5419 LVType = PT->getPointeeType();
5420 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
5421 assert(RD && "member pointer access on non-class-type expression");
5422 // The first class in the path is that of the lvalue.
5423 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
5424 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
5425 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
5426 return nullptr;
5427 RD = Base;
5428 }
5429 // Finally cast to the class containing the member.
5430 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
5431 MemPtr.getContainingRecord()))
5432 return nullptr;
5433 }
5434
5435 // Add the member. Note that we cannot build bound member functions here.
5436 if (IncludeMember) {
5437 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
5438 if (!HandleLValueMember(Info, RHS, LV, FD))
5439 return nullptr;
5440 } else if (const IndirectFieldDecl *IFD =
5441 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
5442 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
5443 return nullptr;
5444 } else {
5445 llvm_unreachable("can't construct reference to bound member function");
5446 }
5447 }
5448
5449 return MemPtr.getDecl();
5450}
5451
5452static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
5453 const BinaryOperator *BO,
5454 LValue &LV,
5455 bool IncludeMember = true) {
5456 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
5457
5458 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
5459 if (Info.noteFailure()) {
5460 MemberPtr MemPtr;
5461 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
5462 }
5463 return nullptr;
5464 }
5465
5466 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
5467 BO->getRHS(), IncludeMember);
5468}
5469
5470/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
5471/// the provided lvalue, which currently refers to the base object.
5472static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
5473 LValue &Result) {
5474 SubobjectDesignator &D = Result.Designator;
5475 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
5476 return false;
5477
5478 QualType TargetQT = E->getType();
5479 if (const PointerType *PT = TargetQT->getAs<PointerType>())
5480 TargetQT = PT->getPointeeType();
5481
5482 auto InvalidCast = [&]() {
5483 if (!Info.checkingPotentialConstantExpression() ||
5484 !Result.AllowConstexprUnknown) {
5485 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
5486 << D.MostDerivedType << TargetQT;
5487 }
5488 return false;
5489 };
5490
5491 // Check this cast lands within the final derived-to-base subobject path.
5492 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size())
5493 return InvalidCast();
5494
5495 // Check the type of the final cast. We don't need to check the path,
5496 // since a cast can only be formed if the path is unique.
5497 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
5498 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
5499 const CXXRecordDecl *FinalType;
5500 if (NewEntriesSize == D.MostDerivedPathLength)
5501 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
5502 else
5503 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
5504 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl())
5505 return InvalidCast();
5506
5507 // Truncate the lvalue to the appropriate derived class.
5508 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
5509}
5510
5511/// Get the value to use for a default-initialized object of type T.
5512/// Return false if it encounters something invalid.
5514 bool Success = true;
5515
5516 // If there is already a value present don't overwrite it.
5517 if (!Result.isAbsent())
5518 return true;
5519
5520 if (auto *RD = T->getAsCXXRecordDecl()) {
5521 if (RD->isInvalidDecl()) {
5522 Result = APValue();
5523 return false;
5524 }
5525 if (RD->isUnion()) {
5526 Result = APValue((const FieldDecl *)nullptr);
5527 return true;
5528 }
5529 Result =
5530 APValue(APValue::UninitStruct(), RD->getNumBases(), RD->getNumFields());
5531
5532 unsigned Index = 0;
5533 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
5534 End = RD->bases_end();
5535 I != End; ++I, ++Index)
5536 Success &=
5537 handleDefaultInitValue(I->getType(), Result.getStructBase(Index));
5538
5539 for (const auto *I : RD->fields()) {
5540 if (I->isUnnamedBitField())
5541 continue;
5543 I->getType(), Result.getStructField(I->getFieldIndex()));
5544 }
5545 return Success;
5546 }
5547
5548 if (auto *AT =
5549 dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
5550 Result = APValue(APValue::UninitArray(), 0, AT->getZExtSize());
5551 if (Result.hasArrayFiller())
5552 Success &=
5553 handleDefaultInitValue(AT->getElementType(), Result.getArrayFiller());
5554
5555 return Success;
5556 }
5557
5558 Result = APValue::IndeterminateValue();
5559 return true;
5560}
5561
5562namespace {
5563enum EvalStmtResult {
5564 /// Evaluation failed.
5565 ESR_Failed,
5566 /// Hit a 'return' statement.
5567 ESR_Returned,
5568 /// Evaluation succeeded.
5569 ESR_Succeeded,
5570 /// Hit a 'continue' statement.
5571 ESR_Continue,
5572 /// Hit a 'break' statement.
5573 ESR_Break,
5574 /// Still scanning for 'case' or 'default' statement.
5575 ESR_CaseNotFound
5576};
5577}
5578/// Evaluates the initializer of a reference.
5579static bool EvaluateInitForDeclOfReferenceType(EvalInfo &Info,
5580 const ValueDecl *D,
5581 const Expr *Init, LValue &Result,
5582 APValue &Val) {
5583 assert(Init->isGLValue() && D->getType()->isReferenceType());
5584 // A reference is an lvalue.
5585 if (!EvaluateLValue(Init, Result, Info))
5586 return false;
5587 // [C++26][decl.ref]
5588 // The object designated by such a glvalue can be outside its lifetime
5589 // Because a null pointer value or a pointer past the end of an object
5590 // does not point to an object, a reference in a well-defined program cannot
5591 // refer to such things;
5592 if (!Result.Designator.Invalid && Result.Designator.isOnePastTheEnd()) {
5593 Info.FFDiag(Init, diag::note_constexpr_access_past_end) << AK_Dereference;
5594 return false;
5595 }
5596
5597 // Save the result.
5598 Result.moveInto(Val);
5599 return true;
5600}
5601
5602static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
5603 if (VD->isInvalidDecl())
5604 return false;
5605 // We don't need to evaluate the initializer for a static local.
5606 if (!VD->hasLocalStorage())
5607 return true;
5608
5609 LValue Result;
5610 APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(),
5611 ScopeKind::Block, Result);
5612
5613 const Expr *InitE = VD->getInit();
5614 if (!InitE) {
5615 if (VD->getType()->isDependentType())
5616 return Info.noteSideEffect();
5617 return handleDefaultInitValue(VD->getType(), Val);
5618 }
5619 if (InitE->isValueDependent())
5620 return false;
5621
5622 // For references to objects, check they do not designate a one-past-the-end
5623 // object.
5624 if (VD->getType()->isReferenceType()) {
5625 return EvaluateInitForDeclOfReferenceType(Info, VD, InitE, Result, Val);
5626 } else if (!EvaluateInPlace(Val, Info, Result, InitE)) {
5627 // Wipe out any partially-computed value, to allow tracking that this
5628 // evaluation failed.
5629 Val = APValue();
5630 return false;
5631 }
5632
5633 return true;
5634}
5635
5636static bool EvaluateDecompositionDeclInit(EvalInfo &Info,
5637 const DecompositionDecl *DD);
5638
5639static bool EvaluateDecl(EvalInfo &Info, const Decl *D,
5640 bool EvaluateConditionDecl = false) {
5641 bool OK = true;
5642 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
5643 OK &= EvaluateVarDecl(Info, VD);
5644
5645 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D);
5646 EvaluateConditionDecl && DD)
5647 OK &= EvaluateDecompositionDeclInit(Info, DD);
5648
5649 return OK;
5650}
5651
5652static bool EvaluateDecompositionDeclInit(EvalInfo &Info,
5653 const DecompositionDecl *DD) {
5654 bool OK = true;
5655 for (auto *BD : DD->flat_bindings())
5656 if (auto *VD = BD->getHoldingVar())
5657 OK &= EvaluateDecl(Info, VD, /*EvaluateConditionDecl=*/true);
5658
5659 return OK;
5660}
5661
5662static bool MaybeEvaluateDeferredVarDeclInit(EvalInfo &Info,
5663 const VarDecl *VD) {
5664 if (auto *DD = dyn_cast_if_present<DecompositionDecl>(VD)) {
5665 if (!EvaluateDecompositionDeclInit(Info, DD))
5666 return false;
5667 }
5668 return true;
5669}
5670
5671static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info) {
5672 assert(E->isValueDependent());
5673 if (Info.noteSideEffect())
5674 return true;
5675 assert(E->containsErrors() && "valid value-dependent expression should never "
5676 "reach invalid code path.");
5677 return false;
5678}
5679
5680/// Evaluate a condition (either a variable declaration or an expression).
5681static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
5682 const Expr *Cond, bool &Result) {
5683 if (Cond->isValueDependent())
5684 return false;
5685 FullExpressionRAII Scope(Info);
5686 if (CondDecl && !EvaluateDecl(Info, CondDecl))
5687 return false;
5688 if (!EvaluateAsBooleanCondition(Cond, Result, Info))
5689 return false;
5690 if (!MaybeEvaluateDeferredVarDeclInit(Info, CondDecl))
5691 return false;
5692 return Scope.destroy();
5693}
5694
5695namespace {
5696/// A location where the result (returned value) of evaluating a
5697/// statement should be stored.
5698struct StmtResult {
5699 /// The APValue that should be filled in with the returned value.
5700 APValue &Value;
5701 /// The location containing the result, if any (used to support RVO).
5702 const LValue *Slot;
5703};
5704
5705struct TempVersionRAII {
5706 CallStackFrame &Frame;
5707
5708 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
5709 Frame.pushTempVersion();
5710 }
5711
5712 ~TempVersionRAII() {
5713 Frame.popTempVersion();
5714 }
5715};
5716
5717}
5718
5719static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
5720 const Stmt *S,
5721 const SwitchCase *SC = nullptr);
5722
5723/// Helper to implement named break/continue. Returns 'true' if the evaluation
5724/// result should be propagated up. Otherwise, it sets the evaluation result
5725/// to either Continue to continue the current loop, or Succeeded to break it.
5726static bool ShouldPropagateBreakContinue(EvalInfo &Info,
5727 const Stmt *LoopOrSwitch,
5729 EvalStmtResult &ESR) {
5730 bool IsSwitch = isa<SwitchStmt>(LoopOrSwitch);
5731
5732 // For loops, map Succeeded to Continue so we don't have to check for both.
5733 if (!IsSwitch && ESR == ESR_Succeeded) {
5734 ESR = ESR_Continue;
5735 return false;
5736 }
5737
5738 if (ESR != ESR_Break && ESR != ESR_Continue)
5739 return false;
5740
5741 // Are we breaking out of or continuing this statement?
5742 bool CanBreakOrContinue = !IsSwitch || ESR == ESR_Break;
5743 const Stmt *StackTop = Info.BreakContinueStack.back();
5744 if (CanBreakOrContinue && (StackTop == nullptr || StackTop == LoopOrSwitch)) {
5745 Info.BreakContinueStack.pop_back();
5746 if (ESR == ESR_Break)
5747 ESR = ESR_Succeeded;
5748 return false;
5749 }
5750
5751 // We're not. Propagate the result up.
5752 for (BlockScopeRAII *S : Scopes) {
5753 if (!S->destroy()) {
5754 ESR = ESR_Failed;
5755 break;
5756 }
5757 }
5758 return true;
5759}
5760
5761/// Evaluate the body of a loop, and translate the result as appropriate.
5762static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
5763 const Stmt *Body,
5764 const SwitchCase *Case = nullptr) {
5765 BlockScopeRAII Scope(Info);
5766
5767 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case);
5768 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
5769 ESR = ESR_Failed;
5770
5771 return ESR;
5772}
5773
5774/// Evaluate a switch statement.
5775static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
5776 const SwitchStmt *SS) {
5777 BlockScopeRAII Scope(Info);
5778
5779 // Evaluate the switch condition.
5780 APSInt Value;
5781 {
5782 if (const Stmt *Init = SS->getInit()) {
5783 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
5784 if (ESR != ESR_Succeeded) {
5785 if (ESR != ESR_Failed && !Scope.destroy())
5786 ESR = ESR_Failed;
5787 return ESR;
5788 }
5789 }
5790
5791 FullExpressionRAII CondScope(Info);
5792 if (SS->getConditionVariable() &&
5793 !EvaluateDecl(Info, SS->getConditionVariable()))
5794 return ESR_Failed;
5795 if (SS->getCond()->isValueDependent()) {
5796 // We don't know what the value is, and which branch should jump to.
5797 EvaluateDependentExpr(SS->getCond(), Info);
5798 return ESR_Failed;
5799 }
5800 if (!EvaluateInteger(SS->getCond(), Value, Info))
5801 return ESR_Failed;
5802
5804 return ESR_Failed;
5805
5806 if (!CondScope.destroy())
5807 return ESR_Failed;
5808 }
5809
5810 // Find the switch case corresponding to the value of the condition.
5811 // FIXME: Cache this lookup.
5812 const SwitchCase *Found = nullptr;
5813 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
5814 SC = SC->getNextSwitchCase()) {
5815 if (isa<DefaultStmt>(SC)) {
5816 Found = SC;
5817 continue;
5818 }
5819
5820 const CaseStmt *CS = cast<CaseStmt>(SC);
5821 const Expr *LHS = CS->getLHS();
5822 const Expr *RHS = CS->getRHS();
5823 if (LHS->isValueDependent() || (RHS && RHS->isValueDependent()))
5824 return ESR_Failed;
5825 APSInt LHSValue = LHS->EvaluateKnownConstInt(Info.Ctx);
5826 APSInt RHSValue = RHS ? RHS->EvaluateKnownConstInt(Info.Ctx) : LHSValue;
5827 if (LHSValue <= Value && Value <= RHSValue) {
5828 Found = SC;
5829 break;
5830 }
5831 }
5832
5833 if (!Found)
5834 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5835
5836 // Search the switch body for the switch case and evaluate it from there.
5837 EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found);
5838 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
5839 return ESR_Failed;
5840 if (ShouldPropagateBreakContinue(Info, SS, /*Scopes=*/{}, ESR))
5841 return ESR;
5842
5843 switch (ESR) {
5844 case ESR_Break:
5845 llvm_unreachable("Should have been converted to Succeeded");
5846 case ESR_Succeeded:
5847 case ESR_Continue:
5848 case ESR_Failed:
5849 case ESR_Returned:
5850 return ESR;
5851 case ESR_CaseNotFound:
5852 // This can only happen if the switch case is nested within a statement
5853 // expression. We have no intention of supporting that.
5854 Info.FFDiag(Found->getBeginLoc(),
5855 diag::note_constexpr_stmt_expr_unsupported);
5856 return ESR_Failed;
5857 }
5858 llvm_unreachable("Invalid EvalStmtResult!");
5859}
5860
5861static bool CheckLocalVariableDeclaration(EvalInfo &Info, const VarDecl *VD) {
5862 // An expression E is a core constant expression unless the evaluation of E
5863 // would evaluate one of the following: [C++23] - a control flow that passes
5864 // through a declaration of a variable with static or thread storage duration
5865 // unless that variable is usable in constant expressions.
5866 if (VD->isLocalVarDecl() && VD->isStaticLocal() &&
5867 !VD->isUsableInConstantExpressions(Info.Ctx)) {
5868 Info.CCEDiag(VD->getLocation(), diag::note_constexpr_static_local)
5869 << (VD->getTSCSpec() == TSCS_unspecified ? 0 : 1) << VD;
5870 return false;
5871 }
5872 return true;
5873}
5874
5875// Evaluate a statement.
5876static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
5877 const Stmt *S, const SwitchCase *Case) {
5878 if (!Info.nextStep(S))
5879 return ESR_Failed;
5880
5881 // If we're hunting down a 'case' or 'default' label, recurse through
5882 // substatements until we hit the label.
5883 if (Case) {
5884 switch (S->getStmtClass()) {
5885 case Stmt::CompoundStmtClass:
5886 // FIXME: Precompute which substatement of a compound statement we
5887 // would jump to, and go straight there rather than performing a
5888 // linear scan each time.
5889 case Stmt::LabelStmtClass:
5890 case Stmt::AttributedStmtClass:
5891 case Stmt::DoStmtClass:
5892 break;
5893
5894 case Stmt::CaseStmtClass:
5895 case Stmt::DefaultStmtClass:
5896 if (Case == S)
5897 Case = nullptr;
5898 break;
5899
5900 case Stmt::IfStmtClass: {
5901 // FIXME: Precompute which side of an 'if' we would jump to, and go
5902 // straight there rather than scanning both sides.
5903 const IfStmt *IS = cast<IfStmt>(S);
5904
5905 // Wrap the evaluation in a block scope, in case it's a DeclStmt
5906 // preceded by our switch label.
5907 BlockScopeRAII Scope(Info);
5908
5909 // Step into the init statement in case it brings an (uninitialized)
5910 // variable into scope.
5911 if (const Stmt *Init = IS->getInit()) {
5912 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5913 if (ESR != ESR_CaseNotFound) {
5914 assert(ESR != ESR_Succeeded);
5915 return ESR;
5916 }
5917 }
5918
5919 // Condition variable must be initialized if it exists.
5920 // FIXME: We can skip evaluating the body if there's a condition
5921 // variable, as there can't be any case labels within it.
5922 // (The same is true for 'for' statements.)
5923
5924 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
5925 if (ESR == ESR_Failed)
5926 return ESR;
5927 if (ESR != ESR_CaseNotFound)
5928 return Scope.destroy() ? ESR : ESR_Failed;
5929 if (!IS->getElse())
5930 return ESR_CaseNotFound;
5931
5932 ESR = EvaluateStmt(Result, Info, IS->getElse(), Case);
5933 if (ESR == ESR_Failed)
5934 return ESR;
5935 if (ESR != ESR_CaseNotFound)
5936 return Scope.destroy() ? ESR : ESR_Failed;
5937 return ESR_CaseNotFound;
5938 }
5939
5940 case Stmt::WhileStmtClass: {
5941 EvalStmtResult ESR =
5942 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
5943 if (ShouldPropagateBreakContinue(Info, S, /*Scopes=*/{}, ESR))
5944 return ESR;
5945 if (ESR != ESR_Continue)
5946 return ESR;
5947 break;
5948 }
5949
5950 case Stmt::ForStmtClass: {
5951 const ForStmt *FS = cast<ForStmt>(S);
5952 BlockScopeRAII Scope(Info);
5953
5954 // Step into the init statement in case it brings an (uninitialized)
5955 // variable into scope.
5956 if (const Stmt *Init = FS->getInit()) {
5957 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5958 if (ESR != ESR_CaseNotFound) {
5959 assert(ESR != ESR_Succeeded);
5960 return ESR;
5961 }
5962 }
5963
5964 EvalStmtResult ESR =
5965 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
5966 if (ShouldPropagateBreakContinue(Info, FS, /*Scopes=*/{}, ESR))
5967 return ESR;
5968 if (ESR != ESR_Continue)
5969 return ESR;
5970 if (const auto *Inc = FS->getInc()) {
5971 if (Inc->isValueDependent()) {
5972 if (!EvaluateDependentExpr(Inc, Info))
5973 return ESR_Failed;
5974 } else {
5975 FullExpressionRAII IncScope(Info);
5976 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5977 return ESR_Failed;
5978 }
5979 }
5980 break;
5981 }
5982
5983 case Stmt::DeclStmtClass: {
5984 // Start the lifetime of any uninitialized variables we encounter. They
5985 // might be used by the selected branch of the switch.
5986 const DeclStmt *DS = cast<DeclStmt>(S);
5987 for (const auto *D : DS->decls()) {
5988 if (const auto *VD = dyn_cast<VarDecl>(D)) {
5989 if (!CheckLocalVariableDeclaration(Info, VD))
5990 return ESR_Failed;
5991 if (VD->hasLocalStorage() && !VD->getInit())
5992 if (!EvaluateVarDecl(Info, VD))
5993 return ESR_Failed;
5994 // FIXME: If the variable has initialization that can't be jumped
5995 // over, bail out of any immediately-surrounding compound-statement
5996 // too. There can't be any case labels here.
5997 }
5998 }
5999 return ESR_CaseNotFound;
6000 }
6001
6002 default:
6003 return ESR_CaseNotFound;
6004 }
6005 }
6006
6007 switch (S->getStmtClass()) {
6008 default:
6009 if (const Expr *E = dyn_cast<Expr>(S)) {
6010 if (E->isValueDependent()) {
6011 if (!EvaluateDependentExpr(E, Info))
6012 return ESR_Failed;
6013 } else {
6014 // Don't bother evaluating beyond an expression-statement which couldn't
6015 // be evaluated.
6016 // FIXME: Do we need the FullExpressionRAII object here?
6017 // VisitExprWithCleanups should create one when necessary.
6018 FullExpressionRAII Scope(Info);
6019 if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy())
6020 return ESR_Failed;
6021 }
6022 return ESR_Succeeded;
6023 }
6024
6025 Info.FFDiag(S->getBeginLoc()) << S->getSourceRange();
6026 return ESR_Failed;
6027
6028 case Stmt::NullStmtClass:
6029 return ESR_Succeeded;
6030
6031 case Stmt::DeclStmtClass: {
6032 const DeclStmt *DS = cast<DeclStmt>(S);
6033 for (const auto *D : DS->decls()) {
6034 const VarDecl *VD = dyn_cast_or_null<VarDecl>(D);
6035 if (VD && !CheckLocalVariableDeclaration(Info, VD))
6036 return ESR_Failed;
6037 // Each declaration initialization is its own full-expression.
6038 FullExpressionRAII Scope(Info);
6039 if (!EvaluateDecl(Info, D, /*EvaluateConditionDecl=*/true) &&
6040 !Info.noteFailure())
6041 return ESR_Failed;
6042 if (!Scope.destroy())
6043 return ESR_Failed;
6044 }
6045 return ESR_Succeeded;
6046 }
6047
6048 case Stmt::ReturnStmtClass: {
6049 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
6050 FullExpressionRAII Scope(Info);
6051 if (RetExpr && RetExpr->isValueDependent()) {
6052 EvaluateDependentExpr(RetExpr, Info);
6053 // We know we returned, but we don't know what the value is.
6054 return ESR_Failed;
6055 }
6056 if (RetExpr &&
6057 !(Result.Slot
6058 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
6059 : Evaluate(Result.Value, Info, RetExpr)))
6060 return ESR_Failed;
6061 return Scope.destroy() ? ESR_Returned : ESR_Failed;
6062 }
6063
6064 case Stmt::CompoundStmtClass: {
6065 BlockScopeRAII Scope(Info);
6066
6067 const CompoundStmt *CS = cast<CompoundStmt>(S);
6068 for (const auto *BI : CS->body()) {
6069 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
6070 if (ESR == ESR_Succeeded)
6071 Case = nullptr;
6072 else if (ESR != ESR_CaseNotFound) {
6073 if (ESR != ESR_Failed && !Scope.destroy())
6074 return ESR_Failed;
6075 return ESR;
6076 }
6077 }
6078 if (Case)
6079 return ESR_CaseNotFound;
6080 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
6081 }
6082
6083 case Stmt::IfStmtClass: {
6084 const IfStmt *IS = cast<IfStmt>(S);
6085
6086 // Evaluate the condition, as either a var decl or as an expression.
6087 BlockScopeRAII Scope(Info);
6088 if (const Stmt *Init = IS->getInit()) {
6089 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
6090 if (ESR != ESR_Succeeded) {
6091 if (ESR != ESR_Failed && !Scope.destroy())
6092 return ESR_Failed;
6093 return ESR;
6094 }
6095 }
6096 bool Cond;
6097 if (IS->isConsteval()) {
6099 // If we are not in a constant context, if consteval should not evaluate
6100 // to true.
6101 if (!Info.InConstantContext)
6102 Cond = !Cond;
6103 } else if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(),
6104 Cond))
6105 return ESR_Failed;
6106
6107 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
6108 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
6109 if (ESR != ESR_Succeeded) {
6110 if (ESR != ESR_Failed && !Scope.destroy())
6111 return ESR_Failed;
6112 return ESR;
6113 }
6114 }
6115 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
6116 }
6117
6118 case Stmt::WhileStmtClass: {
6119 const WhileStmt *WS = cast<WhileStmt>(S);
6120 while (true) {
6121 BlockScopeRAII Scope(Info);
6122 bool Continue;
6123 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
6124 Continue))
6125 return ESR_Failed;
6126 if (!Continue)
6127 break;
6128
6129 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
6130 if (ShouldPropagateBreakContinue(Info, WS, &Scope, ESR))
6131 return ESR;
6132
6133 if (ESR != ESR_Continue) {
6134 if (ESR != ESR_Failed && !Scope.destroy())
6135 return ESR_Failed;
6136 return ESR;
6137 }
6138 if (!Scope.destroy())
6139 return ESR_Failed;
6140 }
6141 return ESR_Succeeded;
6142 }
6143
6144 case Stmt::DoStmtClass: {
6145 const DoStmt *DS = cast<DoStmt>(S);
6146 bool Continue;
6147 do {
6148 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
6149 if (ShouldPropagateBreakContinue(Info, DS, /*Scopes=*/{}, ESR))
6150 return ESR;
6151 if (ESR != ESR_Continue)
6152 return ESR;
6153 Case = nullptr;
6154
6155 if (DS->getCond()->isValueDependent()) {
6156 EvaluateDependentExpr(DS->getCond(), Info);
6157 // Bailout as we don't know whether to keep going or terminate the loop.
6158 return ESR_Failed;
6159 }
6160 FullExpressionRAII CondScope(Info);
6161 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) ||
6162 !CondScope.destroy())
6163 return ESR_Failed;
6164 } while (Continue);
6165 return ESR_Succeeded;
6166 }
6167
6168 case Stmt::ForStmtClass: {
6169 const ForStmt *FS = cast<ForStmt>(S);
6170 BlockScopeRAII ForScope(Info);
6171 if (FS->getInit()) {
6172 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
6173 if (ESR != ESR_Succeeded) {
6174 if (ESR != ESR_Failed && !ForScope.destroy())
6175 return ESR_Failed;
6176 return ESR;
6177 }
6178 }
6179 while (true) {
6180 BlockScopeRAII IterScope(Info);
6181 bool Continue = true;
6182 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
6183 FS->getCond(), Continue))
6184 return ESR_Failed;
6185
6186 if (!Continue) {
6187 if (!IterScope.destroy())
6188 return ESR_Failed;
6189 break;
6190 }
6191
6192 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
6193 if (ShouldPropagateBreakContinue(Info, FS, {&IterScope, &ForScope}, ESR))
6194 return ESR;
6195 if (ESR != ESR_Continue) {
6196 if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))
6197 return ESR_Failed;
6198 return ESR;
6199 }
6200
6201 if (const auto *Inc = FS->getInc()) {
6202 if (Inc->isValueDependent()) {
6203 if (!EvaluateDependentExpr(Inc, Info))
6204 return ESR_Failed;
6205 } else {
6206 FullExpressionRAII IncScope(Info);
6207 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
6208 return ESR_Failed;
6209 }
6210 }
6211
6212 if (!IterScope.destroy())
6213 return ESR_Failed;
6214 }
6215 return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;
6216 }
6217
6218 case Stmt::CXXForRangeStmtClass: {
6220 BlockScopeRAII Scope(Info);
6221
6222 // Evaluate the init-statement if present.
6223 if (FS->getInit()) {
6224 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
6225 if (ESR != ESR_Succeeded) {
6226 if (ESR != ESR_Failed && !Scope.destroy())
6227 return ESR_Failed;
6228 return ESR;
6229 }
6230 }
6231
6232 // Initialize the __range variable.
6233 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
6234 if (ESR != ESR_Succeeded) {
6235 if (ESR != ESR_Failed && !Scope.destroy())
6236 return ESR_Failed;
6237 return ESR;
6238 }
6239
6240 // In error-recovery cases it's possible to get here even if we failed to
6241 // synthesize the __begin and __end variables.
6242 if (!FS->getBeginStmt() || !FS->getEndStmt() || !FS->getCond())
6243 return ESR_Failed;
6244
6245 // Create the __begin and __end iterators.
6246 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
6247 if (ESR != ESR_Succeeded) {
6248 if (ESR != ESR_Failed && !Scope.destroy())
6249 return ESR_Failed;
6250 return ESR;
6251 }
6252 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
6253 if (ESR != ESR_Succeeded) {
6254 if (ESR != ESR_Failed && !Scope.destroy())
6255 return ESR_Failed;
6256 return ESR;
6257 }
6258
6259 while (true) {
6260 // Condition: __begin != __end.
6261 {
6262 if (FS->getCond()->isValueDependent()) {
6263 EvaluateDependentExpr(FS->getCond(), Info);
6264 // We don't know whether to keep going or terminate the loop.
6265 return ESR_Failed;
6266 }
6267 bool Continue = true;
6268 FullExpressionRAII CondExpr(Info);
6269 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
6270 return ESR_Failed;
6271 if (!Continue)
6272 break;
6273 }
6274
6275 // User's variable declaration, initialized by *__begin.
6276 BlockScopeRAII InnerScope(Info);
6277 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
6278 if (ESR != ESR_Succeeded) {
6279 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
6280 return ESR_Failed;
6281 return ESR;
6282 }
6283
6284 // Loop body.
6285 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
6286 if (ShouldPropagateBreakContinue(Info, FS, {&InnerScope, &Scope}, ESR))
6287 return ESR;
6288 if (ESR != ESR_Continue) {
6289 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
6290 return ESR_Failed;
6291 return ESR;
6292 }
6293 if (FS->getInc()->isValueDependent()) {
6294 if (!EvaluateDependentExpr(FS->getInc(), Info))
6295 return ESR_Failed;
6296 } else {
6297 // Increment: ++__begin
6298 if (!EvaluateIgnoredValue(Info, FS->getInc()))
6299 return ESR_Failed;
6300 }
6301
6302 if (!InnerScope.destroy())
6303 return ESR_Failed;
6304 }
6305
6306 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
6307 }
6308
6309 case Stmt::SwitchStmtClass:
6310 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
6311
6312 case Stmt::ContinueStmtClass:
6313 case Stmt::BreakStmtClass: {
6314 auto *B = cast<LoopControlStmt>(S);
6315 Info.BreakContinueStack.push_back(B->getNamedLoopOrSwitch());
6316 return isa<ContinueStmt>(S) ? ESR_Continue : ESR_Break;
6317 }
6318
6319 case Stmt::LabelStmtClass:
6320 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
6321
6322 case Stmt::AttributedStmtClass: {
6323 const auto *AS = cast<AttributedStmt>(S);
6324 const auto *SS = AS->getSubStmt();
6325 MSConstexprContextRAII ConstexprContext(
6326 *Info.CurrentCall, hasSpecificAttr<MSConstexprAttr>(AS->getAttrs()) &&
6327 isa<ReturnStmt>(SS));
6328
6329 auto LO = Info.getASTContext().getLangOpts();
6330 if (LO.CXXAssumptions && !LO.MSVCCompat) {
6331 for (auto *Attr : AS->getAttrs()) {
6332 auto *AA = dyn_cast<CXXAssumeAttr>(Attr);
6333 if (!AA)
6334 continue;
6335
6336 auto *Assumption = AA->getAssumption();
6337 if (Assumption->isValueDependent())
6338 return ESR_Failed;
6339
6340 if (Assumption->HasSideEffects(Info.getASTContext()))
6341 continue;
6342
6343 bool Value;
6344 if (!EvaluateAsBooleanCondition(Assumption, Value, Info))
6345 return ESR_Failed;
6346 if (!Value) {
6347 Info.CCEDiag(Assumption->getExprLoc(),
6348 diag::note_constexpr_assumption_failed);
6349 return ESR_Failed;
6350 }
6351 }
6352 }
6353
6354 return EvaluateStmt(Result, Info, SS, Case);
6355 }
6356
6357 case Stmt::CaseStmtClass:
6358 case Stmt::DefaultStmtClass:
6359 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
6360 case Stmt::CXXTryStmtClass:
6361 // Evaluate try blocks by evaluating all sub statements.
6362 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
6363 }
6364}
6365
6366/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
6367/// default constructor. If so, we'll fold it whether or not it's marked as
6368/// constexpr. If it is marked as constexpr, we will never implicitly define it,
6369/// so we need special handling.
6370static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
6371 const CXXConstructorDecl *CD,
6372 bool IsValueInitialization) {
6373 if (!CD->isTrivial() || !CD->isDefaultConstructor())
6374 return false;
6375
6376 // Value-initialization does not call a trivial default constructor, so such a
6377 // call is a core constant expression whether or not the constructor is
6378 // constexpr.
6379 if (!CD->isConstexpr() && !IsValueInitialization) {
6380 if (Info.getLangOpts().CPlusPlus11) {
6381 // FIXME: If DiagDecl is an implicitly-declared special member function,
6382 // we should be much more explicit about why it's not constexpr.
6383 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
6384 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
6385 Info.Note(CD->getLocation(), diag::note_declared_at);
6386 } else {
6387 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
6388 }
6389 }
6390 return true;
6391}
6392
6393/// CheckConstexprFunction - Check that a function can be called in a constant
6394/// expression.
6395static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
6397 const FunctionDecl *Definition,
6398 const Stmt *Body) {
6399 // Potential constant expressions can contain calls to declared, but not yet
6400 // defined, constexpr functions.
6401 if (Info.checkingPotentialConstantExpression() && !Definition &&
6402 Declaration->isConstexpr())
6403 return false;
6404
6405 // Bail out if the function declaration itself is invalid. We will
6406 // have produced a relevant diagnostic while parsing it, so just
6407 // note the problematic sub-expression.
6408 if (Declaration->isInvalidDecl()) {
6409 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
6410 return false;
6411 }
6412
6413 // DR1872: An instantiated virtual constexpr function can't be called in a
6414 // constant expression (prior to C++20). We can still constant-fold such a
6415 // call.
6416 if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) &&
6417 cast<CXXMethodDecl>(Declaration)->isVirtual())
6418 Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
6419
6420 if (Definition && Definition->isInvalidDecl()) {
6421 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
6422 return false;
6423 }
6424
6425 // Can we evaluate this function call?
6426 if (Definition && Body &&
6427 (Definition->isConstexpr() || (Info.CurrentCall->CanEvalMSConstexpr &&
6428 Definition->hasAttr<MSConstexprAttr>())))
6429 return true;
6430
6431 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
6432 // Special note for the assert() macro, as the normal error message falsely
6433 // implies we cannot use an assertion during constant evaluation.
6434 if (CallLoc.isMacroID() && DiagDecl->getIdentifier()) {
6435 // FIXME: Instead of checking for an implementation-defined function,
6436 // check and evaluate the assert() macro.
6437 StringRef Name = DiagDecl->getName();
6438 bool AssertFailed =
6439 Name == "__assert_rtn" || Name == "__assert_fail" || Name == "_wassert";
6440 if (AssertFailed) {
6441 Info.FFDiag(CallLoc, diag::note_constexpr_assert_failed);
6442 return false;
6443 }
6444 }
6445
6446 if (Info.getLangOpts().CPlusPlus11) {
6447 // If this function is not constexpr because it is an inherited
6448 // non-constexpr constructor, diagnose that directly.
6449 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
6450 if (CD && CD->isInheritingConstructor()) {
6451 auto *Inherited = CD->getInheritedConstructor().getConstructor();
6452 if (!Inherited->isConstexpr())
6453 DiagDecl = CD = Inherited;
6454 }
6455
6456 // FIXME: If DiagDecl is an implicitly-declared special member function
6457 // or an inheriting constructor, we should be much more explicit about why
6458 // it's not constexpr.
6459 if (CD && CD->isInheritingConstructor())
6460 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
6461 << CD->getInheritedConstructor().getConstructor()->getParent();
6462 else
6463 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
6464 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
6465 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
6466 } else {
6467 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
6468 }
6469 return false;
6470}
6471
6472namespace {
6473struct CheckDynamicTypeHandler {
6475 typedef bool result_type;
6476 bool failed() { return false; }
6477 bool found(APValue &Subobj, QualType SubobjType) { return true; }
6478 bool found(APSInt &Value, QualType SubobjType) { return true; }
6479 bool found(APFloat &Value, QualType SubobjType) { return true; }
6480};
6481} // end anonymous namespace
6482
6483/// Check that we can access the notional vptr of an object / determine its
6484/// dynamic type.
6485static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
6486 AccessKinds AK, bool Polymorphic) {
6487 if (This.Designator.Invalid)
6488 return false;
6489
6490 CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
6491
6492 if (!Obj)
6493 return false;
6494
6495 if (!Obj.Value) {
6496 // The object is not usable in constant expressions, so we can't inspect
6497 // its value to see if it's in-lifetime or what the active union members
6498 // are. We can still check for a one-past-the-end lvalue.
6499 if (This.Designator.isOnePastTheEnd() ||
6500 This.Designator.isMostDerivedAnUnsizedArray()) {
6501 Info.FFDiag(E, This.Designator.isOnePastTheEnd()
6502 ? diag::note_constexpr_access_past_end
6503 : diag::note_constexpr_access_unsized_array)
6504 << AK;
6505 return false;
6506 } else if (Polymorphic) {
6507 // Conservatively refuse to perform a polymorphic operation if we would
6508 // not be able to read a notional 'vptr' value.
6509 if (!Info.checkingPotentialConstantExpression() ||
6510 !This.AllowConstexprUnknown) {
6511 APValue Val;
6512 This.moveInto(Val);
6513 QualType StarThisType =
6514 Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
6515 Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
6516 << AK << Val.getAsString(Info.Ctx, StarThisType);
6517 }
6518 return false;
6519 }
6520 return true;
6521 }
6522
6523 CheckDynamicTypeHandler Handler{AK};
6524 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
6525}
6526
6527/// Check that the pointee of the 'this' pointer in a member function call is
6528/// either within its lifetime or in its period of construction or destruction.
6529static bool
6531 const LValue &This,
6532 const CXXMethodDecl *NamedMember) {
6533 return checkDynamicType(
6534 Info, E, This,
6535 isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false);
6536}
6537
6539 /// The dynamic class type of the object.
6541 /// The corresponding path length in the lvalue.
6542 unsigned PathLength;
6543};
6544
6545static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
6546 unsigned PathLength) {
6547 assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
6548 Designator.Entries.size() && "invalid path length");
6549 return (PathLength == Designator.MostDerivedPathLength)
6550 ? Designator.MostDerivedType->getAsCXXRecordDecl()
6551 : getAsBaseClass(Designator.Entries[PathLength - 1]);
6552}
6553
6554/// Determine the dynamic type of an object.
6555static std::optional<DynamicType> ComputeDynamicType(EvalInfo &Info,
6556 const Expr *E,
6557 LValue &This,
6558 AccessKinds AK) {
6559 // If we don't have an lvalue denoting an object of class type, there is no
6560 // meaningful dynamic type. (We consider objects of non-class type to have no
6561 // dynamic type.)
6562 if (!checkDynamicType(Info, E, This, AK,
6563 AK != AK_TypeId || This.AllowConstexprUnknown))
6564 return std::nullopt;
6565
6566 if (This.Designator.Invalid)
6567 return std::nullopt;
6568
6569 // Refuse to compute a dynamic type in the presence of virtual bases. This
6570 // shouldn't happen other than in constant-folding situations, since literal
6571 // types can't have virtual bases.
6572 //
6573 // Note that consumers of DynamicType assume that the type has no virtual
6574 // bases, and will need modifications if this restriction is relaxed.
6575 const CXXRecordDecl *Class =
6576 This.Designator.MostDerivedType->getAsCXXRecordDecl();
6577 if (!Class || Class->getNumVBases()) {
6578 Info.FFDiag(E);
6579 return std::nullopt;
6580 }
6581
6582 // FIXME: For very deep class hierarchies, it might be beneficial to use a
6583 // binary search here instead. But the overwhelmingly common case is that
6584 // we're not in the middle of a constructor, so it probably doesn't matter
6585 // in practice.
6586 ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
6587 for (unsigned PathLength = This.Designator.MostDerivedPathLength;
6588 PathLength <= Path.size(); ++PathLength) {
6589 switch (Info.isEvaluatingCtorDtor(This.getLValueBase(),
6590 Path.slice(0, PathLength))) {
6591 case ConstructionPhase::Bases:
6592 case ConstructionPhase::DestroyingBases:
6593 // We're constructing or destroying a base class. This is not the dynamic
6594 // type.
6595 break;
6596
6597 case ConstructionPhase::None:
6598 case ConstructionPhase::AfterBases:
6599 case ConstructionPhase::AfterFields:
6600 case ConstructionPhase::Destroying:
6601 // We've finished constructing the base classes and not yet started
6602 // destroying them again, so this is the dynamic type.
6603 return DynamicType{getBaseClassType(This.Designator, PathLength),
6604 PathLength};
6605 }
6606 }
6607
6608 // CWG issue 1517: we're constructing a base class of the object described by
6609 // 'This', so that object has not yet begun its period of construction and
6610 // any polymorphic operation on it results in undefined behavior.
6611 Info.FFDiag(E);
6612 return std::nullopt;
6613}
6614
6615/// Perform virtual dispatch.
6617 EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
6618 llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
6619 std::optional<DynamicType> DynType = ComputeDynamicType(
6620 Info, E, This,
6622 if (!DynType)
6623 return nullptr;
6624
6625 // Find the final overrider. It must be declared in one of the classes on the
6626 // path from the dynamic type to the static type.
6627 // FIXME: If we ever allow literal types to have virtual base classes, that
6628 // won't be true.
6629 const CXXMethodDecl *Callee = Found;
6630 unsigned PathLength = DynType->PathLength;
6631 for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
6632 const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
6633 const CXXMethodDecl *Overrider =
6634 Found->getCorrespondingMethodDeclaredInClass(Class, false);
6635 if (Overrider) {
6636 Callee = Overrider;
6637 break;
6638 }
6639 }
6640
6641 // C++2a [class.abstract]p6:
6642 // the effect of making a virtual call to a pure virtual function [...] is
6643 // undefined
6644 if (Callee->isPureVirtual()) {
6645 Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
6646 Info.Note(Callee->getLocation(), diag::note_declared_at);
6647 return nullptr;
6648 }
6649
6650 // If necessary, walk the rest of the path to determine the sequence of
6651 // covariant adjustment steps to apply.
6652 if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
6653 Found->getReturnType())) {
6654 CovariantAdjustmentPath.push_back(Callee->getReturnType());
6655 for (unsigned CovariantPathLength = PathLength + 1;
6656 CovariantPathLength != This.Designator.Entries.size();
6657 ++CovariantPathLength) {
6658 const CXXRecordDecl *NextClass =
6659 getBaseClassType(This.Designator, CovariantPathLength);
6660 const CXXMethodDecl *Next =
6661 Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
6662 if (Next && !Info.Ctx.hasSameUnqualifiedType(
6663 Next->getReturnType(), CovariantAdjustmentPath.back()))
6664 CovariantAdjustmentPath.push_back(Next->getReturnType());
6665 }
6666 if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
6667 CovariantAdjustmentPath.back()))
6668 CovariantAdjustmentPath.push_back(Found->getReturnType());
6669 }
6670
6671 // Perform 'this' adjustment.
6672 if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
6673 return nullptr;
6674
6675 return Callee;
6676}
6677
6678/// Perform the adjustment from a value returned by a virtual function to
6679/// a value of the statically expected type, which may be a pointer or
6680/// reference to a base class of the returned type.
6681static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
6682 APValue &Result,
6683 ArrayRef<QualType> Path) {
6684 assert(Result.isLValue() &&
6685 "unexpected kind of APValue for covariant return");
6686 if (Result.isNullPointer())
6687 return true;
6688
6689 LValue LVal;
6690 LVal.setFrom(Info.Ctx, Result);
6691
6692 const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
6693 for (unsigned I = 1; I != Path.size(); ++I) {
6694 const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
6695 assert(OldClass && NewClass && "unexpected kind of covariant return");
6696 if (OldClass != NewClass &&
6697 !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
6698 return false;
6699 OldClass = NewClass;
6700 }
6701
6702 LVal.moveInto(Result);
6703 return true;
6704}
6705
6706/// Determine whether \p Base, which is known to be a direct base class of
6707/// \p Derived, is a public base class.
6708static bool isBaseClassPublic(const CXXRecordDecl *Derived,
6709 const CXXRecordDecl *Base) {
6710 for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
6711 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
6712 if (BaseClass && declaresSameEntity(BaseClass, Base))
6713 return BaseSpec.getAccessSpecifier() == AS_public;
6714 }
6715 llvm_unreachable("Base is not a direct base of Derived");
6716}
6717
6718/// Apply the given dynamic cast operation on the provided lvalue.
6719///
6720/// This implements the hard case of dynamic_cast, requiring a "runtime check"
6721/// to find a suitable target subobject.
6722static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
6723 LValue &Ptr) {
6724 // We can't do anything with a non-symbolic pointer value.
6725 SubobjectDesignator &D = Ptr.Designator;
6726 if (D.Invalid)
6727 return false;
6728
6729 // C++ [expr.dynamic.cast]p6:
6730 // If v is a null pointer value, the result is a null pointer value.
6731 if (Ptr.isNullPointer() && !E->isGLValue())
6732 return true;
6733
6734 // For all the other cases, we need the pointer to point to an object within
6735 // its lifetime / period of construction / destruction, and we need to know
6736 // its dynamic type.
6737 std::optional<DynamicType> DynType =
6738 ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
6739 if (!DynType)
6740 return false;
6741
6742 // C++ [expr.dynamic.cast]p7:
6743 // If T is "pointer to cv void", then the result is a pointer to the most
6744 // derived object
6745 if (E->getType()->isVoidPointerType())
6746 return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
6747
6749 assert(C && "dynamic_cast target is not void pointer nor class");
6750 CanQualType CQT = Info.Ctx.getCanonicalTagType(C);
6751
6752 auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
6753 // C++ [expr.dynamic.cast]p9:
6754 if (!E->isGLValue()) {
6755 // The value of a failed cast to pointer type is the null pointer value
6756 // of the required result type.
6757 Ptr.setNull(Info.Ctx, E->getType());
6758 return true;
6759 }
6760
6761 // A failed cast to reference type throws [...] std::bad_cast.
6762 unsigned DiagKind;
6763 if (!Paths && (declaresSameEntity(DynType->Type, C) ||
6764 DynType->Type->isDerivedFrom(C)))
6765 DiagKind = 0;
6766 else if (!Paths || Paths->begin() == Paths->end())
6767 DiagKind = 1;
6768 else if (Paths->isAmbiguous(CQT))
6769 DiagKind = 2;
6770 else {
6771 assert(Paths->front().Access != AS_public && "why did the cast fail?");
6772 DiagKind = 3;
6773 }
6774 Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
6775 << DiagKind << Ptr.Designator.getType(Info.Ctx)
6776 << Info.Ctx.getCanonicalTagType(DynType->Type)
6777 << E->getType().getUnqualifiedType();
6778 return false;
6779 };
6780
6781 // Runtime check, phase 1:
6782 // Walk from the base subobject towards the derived object looking for the
6783 // target type.
6784 for (int PathLength = Ptr.Designator.Entries.size();
6785 PathLength >= (int)DynType->PathLength; --PathLength) {
6786 const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
6787 if (declaresSameEntity(Class, C))
6788 return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
6789 // We can only walk across public inheritance edges.
6790 if (PathLength > (int)DynType->PathLength &&
6791 !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
6792 Class))
6793 return RuntimeCheckFailed(nullptr);
6794 }
6795
6796 // Runtime check, phase 2:
6797 // Search the dynamic type for an unambiguous public base of type C.
6798 CXXBasePaths Paths(/*FindAmbiguities=*/true,
6799 /*RecordPaths=*/true, /*DetectVirtual=*/false);
6800 if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
6801 Paths.front().Access == AS_public) {
6802 // Downcast to the dynamic type...
6803 if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
6804 return false;
6805 // ... then upcast to the chosen base class subobject.
6806 for (CXXBasePathElement &Elem : Paths.front())
6807 if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
6808 return false;
6809 return true;
6810 }
6811
6812 // Otherwise, the runtime check fails.
6813 return RuntimeCheckFailed(&Paths);
6814}
6815
6816namespace {
6817struct StartLifetimeOfUnionMemberHandler {
6818 EvalInfo &Info;
6819 const Expr *LHSExpr;
6820 const FieldDecl *Field;
6821 bool DuringInit;
6822 bool Failed = false;
6823 static const AccessKinds AccessKind = AK_Assign;
6824
6825 typedef bool result_type;
6826 bool failed() { return Failed; }
6827 bool found(APValue &Subobj, QualType SubobjType) {
6828 // We are supposed to perform no initialization but begin the lifetime of
6829 // the object. We interpret that as meaning to do what default
6830 // initialization of the object would do if all constructors involved were
6831 // trivial:
6832 // * All base, non-variant member, and array element subobjects' lifetimes
6833 // begin
6834 // * No variant members' lifetimes begin
6835 // * All scalar subobjects whose lifetimes begin have indeterminate values
6836 assert(SubobjType->isUnionType());
6837 if (declaresSameEntity(Subobj.getUnionField(), Field)) {
6838 // This union member is already active. If it's also in-lifetime, there's
6839 // nothing to do.
6840 if (Subobj.getUnionValue().hasValue())
6841 return true;
6842 } else if (DuringInit) {
6843 // We're currently in the process of initializing a different union
6844 // member. If we carried on, that initialization would attempt to
6845 // store to an inactive union member, resulting in undefined behavior.
6846 Info.FFDiag(LHSExpr,
6847 diag::note_constexpr_union_member_change_during_init);
6848 return false;
6849 }
6851 Failed = !handleDefaultInitValue(Field->getType(), Result);
6852 Subobj.setUnion(Field, Result);
6853 return true;
6854 }
6855 bool found(APSInt &Value, QualType SubobjType) {
6856 llvm_unreachable("wrong value kind for union object");
6857 }
6858 bool found(APFloat &Value, QualType SubobjType) {
6859 llvm_unreachable("wrong value kind for union object");
6860 }
6861};
6862} // end anonymous namespace
6863
6864const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
6865
6866/// Handle a builtin simple-assignment or a call to a trivial assignment
6867/// operator whose left-hand side might involve a union member access. If it
6868/// does, implicitly start the lifetime of any accessed union elements per
6869/// C++20 [class.union]5.
6870static bool MaybeHandleUnionActiveMemberChange(EvalInfo &Info,
6871 const Expr *LHSExpr,
6872 const LValue &LHS) {
6873 if (LHS.InvalidBase || LHS.Designator.Invalid)
6874 return false;
6875
6877 // C++ [class.union]p5:
6878 // define the set S(E) of subexpressions of E as follows:
6879 unsigned PathLength = LHS.Designator.Entries.size();
6880 for (const Expr *E = LHSExpr; E != nullptr;) {
6881 // -- If E is of the form A.B, S(E) contains the elements of S(A)...
6882 if (auto *ME = dyn_cast<MemberExpr>(E)) {
6883 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
6884 // Note that we can't implicitly start the lifetime of a reference,
6885 // so we don't need to proceed any further if we reach one.
6886 if (!FD || FD->getType()->isReferenceType())
6887 break;
6888
6889 // ... and also contains A.B if B names a union member ...
6890 if (FD->getParent()->isUnion()) {
6891 // ... of a non-class, non-array type, or of a class type with a
6892 // trivial default constructor that is not deleted, or an array of
6893 // such types.
6894 auto *RD =
6895 FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6896 if (!RD || RD->hasTrivialDefaultConstructor())
6897 UnionPathLengths.push_back({PathLength - 1, FD});
6898 }
6899
6900 E = ME->getBase();
6901 --PathLength;
6902 assert(declaresSameEntity(FD,
6903 LHS.Designator.Entries[PathLength]
6904 .getAsBaseOrMember().getPointer()));
6905
6906 // -- If E is of the form A[B] and is interpreted as a built-in array
6907 // subscripting operator, S(E) is [S(the array operand, if any)].
6908 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
6909 // Step over an ArrayToPointerDecay implicit cast.
6910 auto *Base = ASE->getBase()->IgnoreImplicit();
6911 if (!Base->getType()->isArrayType())
6912 break;
6913
6914 E = Base;
6915 --PathLength;
6916
6917 } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6918 // Step over a derived-to-base conversion.
6919 E = ICE->getSubExpr();
6920 if (ICE->getCastKind() == CK_NoOp)
6921 continue;
6922 if (ICE->getCastKind() != CK_DerivedToBase &&
6923 ICE->getCastKind() != CK_UncheckedDerivedToBase)
6924 break;
6925 // Walk path backwards as we walk up from the base to the derived class.
6926 for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
6927 if (Elt->isVirtual()) {
6928 // A class with virtual base classes never has a trivial default
6929 // constructor, so S(E) is empty in this case.
6930 E = nullptr;
6931 break;
6932 }
6933
6934 --PathLength;
6935 assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
6936 LHS.Designator.Entries[PathLength]
6937 .getAsBaseOrMember().getPointer()));
6938 }
6939
6940 // -- Otherwise, S(E) is empty.
6941 } else {
6942 break;
6943 }
6944 }
6945
6946 // Common case: no unions' lifetimes are started.
6947 if (UnionPathLengths.empty())
6948 return true;
6949
6950 // if modification of X [would access an inactive union member], an object
6951 // of the type of X is implicitly created
6952 CompleteObject Obj =
6953 findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
6954 if (!Obj)
6955 return false;
6956 for (std::pair<unsigned, const FieldDecl *> LengthAndField :
6957 llvm::reverse(UnionPathLengths)) {
6958 // Form a designator for the union object.
6959 SubobjectDesignator D = LHS.Designator;
6960 D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
6961
6962 bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) ==
6963 ConstructionPhase::AfterBases;
6964 StartLifetimeOfUnionMemberHandler StartLifetime{
6965 Info, LHSExpr, LengthAndField.second, DuringInit};
6966 if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
6967 return false;
6968 }
6969
6970 return true;
6971}
6972
6973static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg,
6974 CallRef Call, EvalInfo &Info, bool NonNull = false,
6975 APValue **EvaluatedArg = nullptr) {
6976 LValue LV;
6977 // Create the parameter slot and register its destruction. For a vararg
6978 // argument, create a temporary.
6979 // FIXME: For calling conventions that destroy parameters in the callee,
6980 // should we consider performing destruction when the function returns
6981 // instead?
6982 APValue &V = PVD ? Info.CurrentCall->createParam(Call, PVD, LV)
6983 : Info.CurrentCall->createTemporary(Arg, Arg->getType(),
6984 ScopeKind::Call, LV);
6985 if (!EvaluateInPlace(V, Info, LV, Arg))
6986 return false;
6987
6988 // Passing a null pointer to an __attribute__((nonnull)) parameter results in
6989 // undefined behavior, so is non-constant.
6990 if (NonNull && V.isLValue() && V.isNullPointer()) {
6991 Info.CCEDiag(Arg, diag::note_non_null_attribute_failed);
6992 return false;
6993 }
6994
6995 if (EvaluatedArg)
6996 *EvaluatedArg = &V;
6997
6998 return true;
6999}
7000
7001/// Evaluate the arguments to a function call.
7002static bool EvaluateArgs(ArrayRef<const Expr *> Args, CallRef Call,
7003 EvalInfo &Info, const FunctionDecl *Callee,
7004 bool RightToLeft = false,
7005 LValue *ObjectArg = nullptr) {
7006 bool Success = true;
7007 llvm::SmallBitVector ForbiddenNullArgs;
7008 if (Callee->hasAttr<NonNullAttr>()) {
7009 ForbiddenNullArgs.resize(Args.size());
7010 for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
7011 if (!Attr->args_size()) {
7012 ForbiddenNullArgs.set();
7013 break;
7014 } else
7015 for (auto Idx : Attr->args()) {
7016 unsigned ASTIdx = Idx.getASTIndex();
7017 if (ASTIdx >= Args.size())
7018 continue;
7019 ForbiddenNullArgs[ASTIdx] = true;
7020 }
7021 }
7022 }
7023 for (unsigned I = 0; I < Args.size(); I++) {
7024 unsigned Idx = RightToLeft ? Args.size() - I - 1 : I;
7025 const ParmVarDecl *PVD =
7026 Idx < Callee->getNumParams() ? Callee->getParamDecl(Idx) : nullptr;
7027 bool NonNull = !ForbiddenNullArgs.empty() && ForbiddenNullArgs[Idx];
7028 APValue *That = nullptr;
7029 if (!EvaluateCallArg(PVD, Args[Idx], Call, Info, NonNull, &That)) {
7030 // If we're checking for a potential constant expression, evaluate all
7031 // initializers even if some of them fail.
7032 if (!Info.noteFailure())
7033 return false;
7034 Success = false;
7035 }
7036 if (PVD && PVD->isExplicitObjectParameter() && That && That->isLValue())
7037 ObjectArg->setFrom(Info.Ctx, *That);
7038 }
7039 return Success;
7040}
7041
7042/// Perform a trivial copy from Param, which is the parameter of a copy or move
7043/// constructor or assignment operator.
7044static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param,
7045 const Expr *E, APValue &Result,
7046 bool CopyObjectRepresentation) {
7047 // Find the reference argument.
7048 CallStackFrame *Frame = Info.CurrentCall;
7049 APValue *RefValue = Info.getParamSlot(Frame->Arguments, Param);
7050 if (!RefValue) {
7051 Info.FFDiag(E);
7052 return false;
7053 }
7054
7055 // Copy out the contents of the RHS object.
7056 LValue RefLValue;
7057 RefLValue.setFrom(Info.Ctx, *RefValue);
7059 Info, E, Param->getType().getNonReferenceType(), RefLValue, Result,
7060 CopyObjectRepresentation);
7061}
7062
7063/// Evaluate a function call.
7065 const FunctionDecl *Callee,
7066 const LValue *ObjectArg, const Expr *E,
7067 ArrayRef<const Expr *> Args, CallRef Call,
7068 const Stmt *Body, EvalInfo &Info,
7069 APValue &Result, const LValue *ResultSlot) {
7070 if (!Info.CheckCallLimit(CallLoc))
7071 return false;
7072
7073 CallStackFrame Frame(Info, E->getSourceRange(), Callee, ObjectArg, E, Call);
7074
7075 // For a trivial copy or move assignment, perform an APValue copy. This is
7076 // essential for unions, where the operations performed by the assignment
7077 // operator cannot be represented as statements.
7078 //
7079 // Skip this for non-union classes with no fields; in that case, the defaulted
7080 // copy/move does not actually read the object.
7081 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
7082 if (MD && MD->isDefaulted() &&
7083 (MD->getParent()->isUnion() ||
7084 (MD->isTrivial() &&
7086 unsigned ExplicitOffset = MD->isExplicitObjectMemberFunction() ? 1 : 0;
7087 assert(ObjectArg &&
7089 APValue RHSValue;
7090 if (!handleTrivialCopy(Info, MD->getParamDecl(0), Args[0], RHSValue,
7091 MD->getParent()->isUnion()))
7092 return false;
7093
7094 LValue Obj;
7095 if (!handleAssignment(Info, Args[ExplicitOffset], *ObjectArg,
7097 RHSValue))
7098 return false;
7099 ObjectArg->moveInto(Result);
7100 return true;
7101 } else if (MD && isLambdaCallOperator(MD)) {
7102 // We're in a lambda; determine the lambda capture field maps unless we're
7103 // just constexpr checking a lambda's call operator. constexpr checking is
7104 // done before the captures have been added to the closure object (unless
7105 // we're inferring constexpr-ness), so we don't have access to them in this
7106 // case. But since we don't need the captures to constexpr check, we can
7107 // just ignore them.
7108 if (!Info.checkingPotentialConstantExpression())
7109 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
7110 Frame.LambdaThisCaptureField);
7111 }
7112
7113 StmtResult Ret = {Result, ResultSlot};
7114 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
7115 if (ESR == ESR_Succeeded) {
7116 if (Callee->getReturnType()->isVoidType())
7117 return true;
7118 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
7119 }
7120 return ESR == ESR_Returned;
7121}
7122
7123/// Evaluate a constructor call.
7124static bool HandleConstructorCall(const Expr *E, const LValue &This,
7125 CallRef Call,
7127 EvalInfo &Info, APValue &Result) {
7128 SourceLocation CallLoc = E->getExprLoc();
7129 if (!Info.CheckCallLimit(CallLoc))
7130 return false;
7131
7132 const CXXRecordDecl *RD = Definition->getParent();
7133 if (RD->getNumVBases()) {
7134 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
7135 return false;
7136 }
7137
7138 EvalInfo::EvaluatingConstructorRAII EvalObj(
7139 Info,
7140 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
7141 RD->getNumBases());
7142 CallStackFrame Frame(Info, E->getSourceRange(), Definition, &This, E, Call);
7143
7144 // FIXME: Creating an APValue just to hold a nonexistent return value is
7145 // wasteful.
7146 APValue RetVal;
7147 StmtResult Ret = {RetVal, nullptr};
7148
7149 // If it's a delegating constructor, delegate.
7150 if (Definition->isDelegatingConstructor()) {
7152 if ((*I)->getInit()->isValueDependent()) {
7153 if (!EvaluateDependentExpr((*I)->getInit(), Info))
7154 return false;
7155 } else {
7156 FullExpressionRAII InitScope(Info);
7157 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) ||
7158 !InitScope.destroy())
7159 return false;
7160 }
7161 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
7162 }
7163
7164 // For a trivial copy or move constructor, perform an APValue copy. This is
7165 // essential for unions (or classes with anonymous union members), where the
7166 // operations performed by the constructor cannot be represented by
7167 // ctor-initializers.
7168 //
7169 // Skip this for empty non-union classes; we should not perform an
7170 // lvalue-to-rvalue conversion on them because their copy constructor does not
7171 // actually read them.
7172 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
7173 (Definition->getParent()->isUnion() ||
7174 (Definition->isTrivial() &&
7176 return handleTrivialCopy(Info, Definition->getParamDecl(0), E, Result,
7177 Definition->getParent()->isUnion());
7178 }
7179
7180 // Reserve space for the struct members.
7181 if (!Result.hasValue()) {
7182 if (!RD->isUnion())
7183 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
7184 RD->getNumFields());
7185 else
7186 // A union starts with no active member.
7187 Result = APValue((const FieldDecl*)nullptr);
7188 }
7189
7190 if (RD->isInvalidDecl()) return false;
7191 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7192
7193 // A scope for temporaries lifetime-extended by reference members.
7194 BlockScopeRAII LifetimeExtendedScope(Info);
7195
7196 bool Success = true;
7197 unsigned BasesSeen = 0;
7198#ifndef NDEBUG
7200#endif
7202 auto SkipToField = [&](FieldDecl *FD, bool Indirect) {
7203 // We might be initializing the same field again if this is an indirect
7204 // field initialization.
7205 if (FieldIt == RD->field_end() ||
7206 FieldIt->getFieldIndex() > FD->getFieldIndex()) {
7207 assert(Indirect && "fields out of order?");
7208 return;
7209 }
7210
7211 // Default-initialize any fields with no explicit initializer.
7212 for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
7213 assert(FieldIt != RD->field_end() && "missing field?");
7214 if (!FieldIt->isUnnamedBitField())
7216 FieldIt->getType(),
7217 Result.getStructField(FieldIt->getFieldIndex()));
7218 }
7219 ++FieldIt;
7220 };
7221 for (const auto *I : Definition->inits()) {
7222 LValue Subobject = This;
7223 LValue SubobjectParent = This;
7224 APValue *Value = &Result;
7225
7226 // Determine the subobject to initialize.
7227 FieldDecl *FD = nullptr;
7228 if (I->isBaseInitializer()) {
7229 QualType BaseType(I->getBaseClass(), 0);
7230#ifndef NDEBUG
7231 // Non-virtual base classes are initialized in the order in the class
7232 // definition. We have already checked for virtual base classes.
7233 assert(!BaseIt->isVirtual() && "virtual base for literal type");
7234 assert(Info.Ctx.hasSameUnqualifiedType(BaseIt->getType(), BaseType) &&
7235 "base class initializers not in expected order");
7236 ++BaseIt;
7237#endif
7238 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
7239 BaseType->getAsCXXRecordDecl(), &Layout))
7240 return false;
7241 Value = &Result.getStructBase(BasesSeen++);
7242 } else if ((FD = I->getMember())) {
7243 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
7244 return false;
7245 if (RD->isUnion()) {
7246 Result = APValue(FD);
7247 Value = &Result.getUnionValue();
7248 } else {
7249 SkipToField(FD, false);
7250 Value = &Result.getStructField(FD->getFieldIndex());
7251 }
7252 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
7253 // Walk the indirect field decl's chain to find the object to initialize,
7254 // and make sure we've initialized every step along it.
7255 auto IndirectFieldChain = IFD->chain();
7256 for (auto *C : IndirectFieldChain) {
7257 FD = cast<FieldDecl>(C);
7259 // Switch the union field if it differs. This happens if we had
7260 // preceding zero-initialization, and we're now initializing a union
7261 // subobject other than the first.
7262 // FIXME: In this case, the values of the other subobjects are
7263 // specified, since zero-initialization sets all padding bits to zero.
7264 if (!Value->hasValue() ||
7265 (Value->isUnion() &&
7266 !declaresSameEntity(Value->getUnionField(), FD))) {
7267 if (CD->isUnion())
7268 *Value = APValue(FD);
7269 else
7270 // FIXME: This immediately starts the lifetime of all members of
7271 // an anonymous struct. It would be preferable to strictly start
7272 // member lifetime in initialization order.
7274 *Value);
7275 }
7276 // Store Subobject as its parent before updating it for the last element
7277 // in the chain.
7278 if (C == IndirectFieldChain.back())
7279 SubobjectParent = Subobject;
7280 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
7281 return false;
7282 if (CD->isUnion())
7283 Value = &Value->getUnionValue();
7284 else {
7285 if (C == IndirectFieldChain.front() && !RD->isUnion())
7286 SkipToField(FD, true);
7287 Value = &Value->getStructField(FD->getFieldIndex());
7288 }
7289 }
7290 } else {
7291 llvm_unreachable("unknown base initializer kind");
7292 }
7293
7294 // Need to override This for implicit field initializers as in this case
7295 // This refers to innermost anonymous struct/union containing initializer,
7296 // not to currently constructed class.
7297 const Expr *Init = I->getInit();
7298 if (Init->isValueDependent()) {
7299 if (!EvaluateDependentExpr(Init, Info))
7300 return false;
7301 } else {
7302 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
7304 FullExpressionRAII InitScope(Info);
7305 if (FD && FD->getType()->isReferenceType() &&
7306 !FD->getType()->isFunctionReferenceType()) {
7307 LValue Result;
7308 if (!EvaluateInitForDeclOfReferenceType(Info, FD, Init, Result,
7309 *Value)) {
7310 if (!Info.noteFailure())
7311 return false;
7312 Success = false;
7313 }
7314 } else if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
7315 (FD && FD->isBitField() &&
7316 !truncateBitfieldValue(Info, Init, *Value, FD))) {
7317 // If we're checking for a potential constant expression, evaluate all
7318 // initializers even if some of them fail.
7319 if (!Info.noteFailure())
7320 return false;
7321 Success = false;
7322 }
7323 }
7324
7325 // This is the point at which the dynamic type of the object becomes this
7326 // class type.
7327 if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
7328 EvalObj.finishedConstructingBases();
7329 }
7330
7331 // Default-initialize any remaining fields.
7332 if (!RD->isUnion()) {
7333 for (; FieldIt != RD->field_end(); ++FieldIt) {
7334 if (!FieldIt->isUnnamedBitField())
7336 FieldIt->getType(),
7337 Result.getStructField(FieldIt->getFieldIndex()));
7338 }
7339 }
7340
7341 EvalObj.finishedConstructingFields();
7342
7343 return Success &&
7344 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed &&
7345 LifetimeExtendedScope.destroy();
7346}
7347
7348static bool HandleConstructorCall(const Expr *E, const LValue &This,
7351 EvalInfo &Info, APValue &Result) {
7352 CallScopeRAII CallScope(Info);
7353 CallRef Call = Info.CurrentCall->createCall(Definition);
7354 if (!EvaluateArgs(Args, Call, Info, Definition))
7355 return false;
7356
7357 return HandleConstructorCall(E, This, Call, Definition, Info, Result) &&
7358 CallScope.destroy();
7359}
7360
7361static bool HandleDestructionImpl(EvalInfo &Info, SourceRange CallRange,
7362 const LValue &This, APValue &Value,
7363 QualType T) {
7364 // Objects can only be destroyed while they're within their lifetimes.
7365 // FIXME: We have no representation for whether an object of type nullptr_t
7366 // is in its lifetime; it usually doesn't matter. Perhaps we should model it
7367 // as indeterminate instead?
7368 if (Value.isAbsent() && !T->isNullPtrType()) {
7369 APValue Printable;
7370 This.moveInto(Printable);
7371 Info.FFDiag(CallRange.getBegin(),
7372 diag::note_constexpr_destroy_out_of_lifetime)
7373 << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T));
7374 return false;
7375 }
7376
7377 // Invent an expression for location purposes.
7378 // FIXME: We shouldn't need to do this.
7379 OpaqueValueExpr LocE(CallRange.getBegin(), Info.Ctx.IntTy, VK_PRValue);
7380
7381 // For arrays, destroy elements right-to-left.
7382 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) {
7383 uint64_t Size = CAT->getZExtSize();
7384 QualType ElemT = CAT->getElementType();
7385
7386 if (!CheckArraySize(Info, CAT, CallRange.getBegin()))
7387 return false;
7388
7389 LValue ElemLV = This;
7390 ElemLV.addArray(Info, &LocE, CAT);
7391 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size))
7392 return false;
7393
7394 // Ensure that we have actual array elements available to destroy; the
7395 // destructors might mutate the value, so we can't run them on the array
7396 // filler.
7397 if (Size && Size > Value.getArrayInitializedElts())
7398 expandArray(Value, Value.getArraySize() - 1);
7399
7400 // The size of the array might have been reduced by
7401 // a placement new.
7402 for (Size = Value.getArraySize(); Size != 0; --Size) {
7403 APValue &Elem = Value.getArrayInitializedElt(Size - 1);
7404 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) ||
7405 !HandleDestructionImpl(Info, CallRange, ElemLV, Elem, ElemT))
7406 return false;
7407 }
7408
7409 // End the lifetime of this array now.
7410 Value = APValue();
7411 return true;
7412 }
7413
7414 const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
7415 if (!RD) {
7416 if (T.isDestructedType()) {
7417 Info.FFDiag(CallRange.getBegin(),
7418 diag::note_constexpr_unsupported_destruction)
7419 << T;
7420 return false;
7421 }
7422
7423 Value = APValue();
7424 return true;
7425 }
7426
7427 if (RD->getNumVBases()) {
7428 Info.FFDiag(CallRange.getBegin(), diag::note_constexpr_virtual_base) << RD;
7429 return false;
7430 }
7431
7432 const CXXDestructorDecl *DD = RD->getDestructor();
7433 if (!DD && !RD->hasTrivialDestructor()) {
7434 Info.FFDiag(CallRange.getBegin());
7435 return false;
7436 }
7437
7438 if (!DD || DD->isTrivial() ||
7439 (RD->isAnonymousStructOrUnion() && RD->isUnion())) {
7440 // A trivial destructor just ends the lifetime of the object. Check for
7441 // this case before checking for a body, because we might not bother
7442 // building a body for a trivial destructor. Note that it doesn't matter
7443 // whether the destructor is constexpr in this case; all trivial
7444 // destructors are constexpr.
7445 //
7446 // If an anonymous union would be destroyed, some enclosing destructor must
7447 // have been explicitly defined, and the anonymous union destruction should
7448 // have no effect.
7449 Value = APValue();
7450 return true;
7451 }
7452
7453 if (!Info.CheckCallLimit(CallRange.getBegin()))
7454 return false;
7455
7456 const FunctionDecl *Definition = nullptr;
7457 const Stmt *Body = DD->getBody(Definition);
7458
7459 if (!CheckConstexprFunction(Info, CallRange.getBegin(), DD, Definition, Body))
7460 return false;
7461
7462 CallStackFrame Frame(Info, CallRange, Definition, &This, /*CallExpr=*/nullptr,
7463 CallRef());
7464
7465 // We're now in the period of destruction of this object.
7466 unsigned BasesLeft = RD->getNumBases();
7467 EvalInfo::EvaluatingDestructorRAII EvalObj(
7468 Info,
7469 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries});
7470 if (!EvalObj.DidInsert) {
7471 // C++2a [class.dtor]p19:
7472 // the behavior is undefined if the destructor is invoked for an object
7473 // whose lifetime has ended
7474 // (Note that formally the lifetime ends when the period of destruction
7475 // begins, even though certain uses of the object remain valid until the
7476 // period of destruction ends.)
7477 Info.FFDiag(CallRange.getBegin(), diag::note_constexpr_double_destroy);
7478 return false;
7479 }
7480
7481 // FIXME: Creating an APValue just to hold a nonexistent return value is
7482 // wasteful.
7483 APValue RetVal;
7484 StmtResult Ret = {RetVal, nullptr};
7485 if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed)
7486 return false;
7487
7488 // A union destructor does not implicitly destroy its members.
7489 if (RD->isUnion())
7490 return true;
7491
7492 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7493
7494 // We don't have a good way to iterate fields in reverse, so collect all the
7495 // fields first and then walk them backwards.
7496 SmallVector<FieldDecl*, 16> Fields(RD->fields());
7497 for (const FieldDecl *FD : llvm::reverse(Fields)) {
7498 if (FD->isUnnamedBitField())
7499 continue;
7500
7501 LValue Subobject = This;
7502 if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout))
7503 return false;
7504
7505 APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex());
7506 if (!HandleDestructionImpl(Info, CallRange, Subobject, *SubobjectValue,
7507 FD->getType()))
7508 return false;
7509 }
7510
7511 if (BasesLeft != 0)
7512 EvalObj.startedDestroyingBases();
7513
7514 // Destroy base classes in reverse order.
7515 for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) {
7516 --BasesLeft;
7517
7518 QualType BaseType = Base.getType();
7519 LValue Subobject = This;
7520 if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD,
7521 BaseType->getAsCXXRecordDecl(), &Layout))
7522 return false;
7523
7524 APValue *SubobjectValue = &Value.getStructBase(BasesLeft);
7525 if (!HandleDestructionImpl(Info, CallRange, Subobject, *SubobjectValue,
7526 BaseType))
7527 return false;
7528 }
7529 assert(BasesLeft == 0 && "NumBases was wrong?");
7530
7531 // The period of destruction ends now. The object is gone.
7532 Value = APValue();
7533 return true;
7534}
7535
7536namespace {
7537struct DestroyObjectHandler {
7538 EvalInfo &Info;
7539 const Expr *E;
7540 const LValue &This;
7541 const AccessKinds AccessKind;
7542
7543 typedef bool result_type;
7544 bool failed() { return false; }
7545 bool found(APValue &Subobj, QualType SubobjType) {
7546 return HandleDestructionImpl(Info, E->getSourceRange(), This, Subobj,
7547 SubobjType);
7548 }
7549 bool found(APSInt &Value, QualType SubobjType) {
7550 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
7551 return false;
7552 }
7553 bool found(APFloat &Value, QualType SubobjType) {
7554 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
7555 return false;
7556 }
7557};
7558}
7559
7560/// Perform a destructor or pseudo-destructor call on the given object, which
7561/// might in general not be a complete object.
7562static bool HandleDestruction(EvalInfo &Info, const Expr *E,
7563 const LValue &This, QualType ThisType) {
7564 CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType);
7565 DestroyObjectHandler Handler = {Info, E, This, AK_Destroy};
7566 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
7567}
7568
7569/// Destroy and end the lifetime of the given complete object.
7570static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
7572 QualType T) {
7573 // If we've had an unmodeled side-effect, we can't rely on mutable state
7574 // (such as the object we're about to destroy) being correct.
7575 if (Info.EvalStatus.HasSideEffects)
7576 return false;
7577
7578 LValue LV;
7579 LV.set({LVBase});
7580 return HandleDestructionImpl(Info, Loc, LV, Value, T);
7581}
7582
7583/// Perform a call to 'operator new' or to `__builtin_operator_new'.
7584static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E,
7585 LValue &Result) {
7586 if (Info.checkingPotentialConstantExpression() ||
7587 Info.SpeculativeEvaluationDepth)
7588 return false;
7589
7590 // This is permitted only within a call to std::allocator<T>::allocate.
7591 auto Caller = Info.getStdAllocatorCaller("allocate");
7592 if (!Caller) {
7593 Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20
7594 ? diag::note_constexpr_new_untyped
7595 : diag::note_constexpr_new);
7596 return false;
7597 }
7598
7599 QualType ElemType = Caller.ElemType;
7600 if (ElemType->isIncompleteType() || ElemType->isFunctionType()) {
7601 Info.FFDiag(E->getExprLoc(),
7602 diag::note_constexpr_new_not_complete_object_type)
7603 << (ElemType->isIncompleteType() ? 0 : 1) << ElemType;
7604 return false;
7605 }
7606
7607 APSInt ByteSize;
7608 if (!EvaluateInteger(E->getArg(0), ByteSize, Info))
7609 return false;
7610 bool IsNothrow = false;
7611 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) {
7612 EvaluateIgnoredValue(Info, E->getArg(I));
7613 IsNothrow |= E->getType()->isNothrowT();
7614 }
7615
7616 CharUnits ElemSize;
7617 if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize))
7618 return false;
7619 APInt Size, Remainder;
7620 APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity());
7621 APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder);
7622 if (Remainder != 0) {
7623 // This likely indicates a bug in the implementation of 'std::allocator'.
7624 Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size)
7625 << ByteSize << APSInt(ElemSizeAP, true) << ElemType;
7626 return false;
7627 }
7628
7629 if (!Info.CheckArraySize(E->getBeginLoc(), ByteSize.getActiveBits(),
7630 Size.getZExtValue(), /*Diag=*/!IsNothrow)) {
7631 if (IsNothrow) {
7632 Result.setNull(Info.Ctx, E->getType());
7633 return true;
7634 }
7635 return false;
7636 }
7637
7638 QualType AllocType = Info.Ctx.getConstantArrayType(
7639 ElemType, Size, nullptr, ArraySizeModifier::Normal, 0);
7640 APValue *Val = Info.createHeapAlloc(Caller.Call, AllocType, Result);
7641 *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue());
7642 Result.addArray(Info, E, cast<ConstantArrayType>(AllocType));
7643 return true;
7644}
7645
7647 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
7648 if (CXXDestructorDecl *DD = RD->getDestructor())
7649 return DD->isVirtual();
7650 return false;
7651}
7652
7654 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
7655 if (CXXDestructorDecl *DD = RD->getDestructor())
7656 return DD->isVirtual() ? DD->getOperatorDelete() : nullptr;
7657 return nullptr;
7658}
7659
7660/// Check that the given object is a suitable pointer to a heap allocation that
7661/// still exists and is of the right kind for the purpose of a deletion.
7662///
7663/// On success, returns the heap allocation to deallocate. On failure, produces
7664/// a diagnostic and returns std::nullopt.
7665static std::optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E,
7666 const LValue &Pointer,
7667 DynAlloc::Kind DeallocKind) {
7668 auto PointerAsString = [&] {
7669 return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy);
7670 };
7671
7672 DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>();
7673 if (!DA) {
7674 Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc)
7675 << PointerAsString();
7676 if (Pointer.Base)
7677 NoteLValueLocation(Info, Pointer.Base);
7678 return std::nullopt;
7679 }
7680
7681 std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
7682 if (!Alloc) {
7683 Info.FFDiag(E, diag::note_constexpr_double_delete);
7684 return std::nullopt;
7685 }
7686
7687 if (DeallocKind != (*Alloc)->getKind()) {
7688 QualType AllocType = Pointer.Base.getDynamicAllocType();
7689 Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch)
7690 << DeallocKind << (*Alloc)->getKind() << AllocType;
7691 NoteLValueLocation(Info, Pointer.Base);
7692 return std::nullopt;
7693 }
7694
7695 bool Subobject = false;
7696 if (DeallocKind == DynAlloc::New) {
7697 Subobject = Pointer.Designator.MostDerivedPathLength != 0 ||
7698 Pointer.Designator.isOnePastTheEnd();
7699 } else {
7700 Subobject = Pointer.Designator.Entries.size() != 1 ||
7701 Pointer.Designator.Entries[0].getAsArrayIndex() != 0;
7702 }
7703 if (Subobject) {
7704 Info.FFDiag(E, diag::note_constexpr_delete_subobject)
7705 << PointerAsString() << Pointer.Designator.isOnePastTheEnd();
7706 return std::nullopt;
7707 }
7708
7709 return Alloc;
7710}
7711
7712// Perform a call to 'operator delete' or '__builtin_operator_delete'.
7713static bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) {
7714 if (Info.checkingPotentialConstantExpression() ||
7715 Info.SpeculativeEvaluationDepth)
7716 return false;
7717
7718 // This is permitted only within a call to std::allocator<T>::deallocate.
7719 if (!Info.getStdAllocatorCaller("deallocate")) {
7720 Info.FFDiag(E->getExprLoc());
7721 return true;
7722 }
7723
7724 LValue Pointer;
7725 if (!EvaluatePointer(E->getArg(0), Pointer, Info))
7726 return false;
7727 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
7728 EvaluateIgnoredValue(Info, E->getArg(I));
7729
7730 if (Pointer.Designator.Invalid)
7731 return false;
7732
7733 // Deleting a null pointer would have no effect, but it's not permitted by
7734 // std::allocator<T>::deallocate's contract.
7735 if (Pointer.isNullPointer()) {
7736 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_deallocate_null);
7737 return true;
7738 }
7739
7740 if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator))
7741 return false;
7742
7743 Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>());
7744 return true;
7745}
7746
7747//===----------------------------------------------------------------------===//
7748// Generic Evaluation
7749//===----------------------------------------------------------------------===//
7750namespace {
7751
7752class BitCastBuffer {
7753 // FIXME: We're going to need bit-level granularity when we support
7754 // bit-fields.
7755 // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
7756 // we don't support a host or target where that is the case. Still, we should
7757 // use a more generic type in case we ever do.
7758 SmallVector<std::optional<unsigned char>, 32> Bytes;
7759
7760 static_assert(std::numeric_limits<unsigned char>::digits >= 8,
7761 "Need at least 8 bit unsigned char");
7762
7763 bool TargetIsLittleEndian;
7764
7765public:
7766 BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
7767 : Bytes(Width.getQuantity()),
7768 TargetIsLittleEndian(TargetIsLittleEndian) {}
7769
7770 [[nodiscard]] bool readObject(CharUnits Offset, CharUnits Width,
7771 SmallVectorImpl<unsigned char> &Output) const {
7772 for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
7773 // If a byte of an integer is uninitialized, then the whole integer is
7774 // uninitialized.
7775 if (!Bytes[I.getQuantity()])
7776 return false;
7777 Output.push_back(*Bytes[I.getQuantity()]);
7778 }
7779 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
7780 std::reverse(Output.begin(), Output.end());
7781 return true;
7782 }
7783
7784 void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
7785 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
7786 std::reverse(Input.begin(), Input.end());
7787
7788 size_t Index = 0;
7789 for (unsigned char Byte : Input) {
7790 assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
7791 Bytes[Offset.getQuantity() + Index] = Byte;
7792 ++Index;
7793 }
7794 }
7795
7796 size_t size() { return Bytes.size(); }
7797};
7798
7799/// Traverse an APValue to produce an BitCastBuffer, emulating how the current
7800/// target would represent the value at runtime.
7801class APValueToBufferConverter {
7802 EvalInfo &Info;
7803 BitCastBuffer Buffer;
7804 const CastExpr *BCE;
7805
7806 APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
7807 const CastExpr *BCE)
7808 : Info(Info),
7809 Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
7810 BCE(BCE) {}
7811
7812 bool visit(const APValue &Val, QualType Ty) {
7813 return visit(Val, Ty, CharUnits::fromQuantity(0));
7814 }
7815
7816 // Write out Val with type Ty into Buffer starting at Offset.
7817 bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
7818 assert((size_t)Offset.getQuantity() <= Buffer.size());
7819
7820 // As a special case, nullptr_t has an indeterminate value.
7821 if (Ty->isNullPtrType())
7822 return true;
7823
7824 // Dig through Src to find the byte at SrcOffset.
7825 switch (Val.getKind()) {
7827 case APValue::None:
7828 return true;
7829
7830 case APValue::Int:
7831 return visitInt(Val.getInt(), Ty, Offset);
7832 case APValue::Float:
7833 return visitFloat(Val.getFloat(), Ty, Offset);
7834 case APValue::Array:
7835 return visitArray(Val, Ty, Offset);
7836 case APValue::Struct:
7837 return visitRecord(Val, Ty, Offset);
7838 case APValue::Vector:
7839 return visitVector(Val, Ty, Offset);
7840
7843 return visitComplex(Val, Ty, Offset);
7845 // FIXME: We should support these.
7846
7847 case APValue::Union:
7850 Info.FFDiag(BCE->getBeginLoc(),
7851 diag::note_constexpr_bit_cast_unsupported_type)
7852 << Ty;
7853 return false;
7854 }
7855
7856 case APValue::LValue:
7857 llvm_unreachable("LValue subobject in bit_cast?");
7858 }
7859 llvm_unreachable("Unhandled APValue::ValueKind");
7860 }
7861
7862 bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
7863 const RecordDecl *RD = Ty->getAsRecordDecl();
7864 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7865
7866 // Visit the base classes.
7867 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
7868 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
7869 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
7870 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
7871 const APValue &Base = Val.getStructBase(I);
7872
7873 // Can happen in error cases.
7874 if (!Base.isStruct())
7875 return false;
7876
7877 if (!visitRecord(Base, BS.getType(),
7878 Layout.getBaseClassOffset(BaseDecl) + Offset))
7879 return false;
7880 }
7881 }
7882
7883 // Visit the fields.
7884 unsigned FieldIdx = 0;
7885 for (FieldDecl *FD : RD->fields()) {
7886 if (FD->isBitField()) {
7887 Info.FFDiag(BCE->getBeginLoc(),
7888 diag::note_constexpr_bit_cast_unsupported_bitfield);
7889 return false;
7890 }
7891
7892 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
7893
7894 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
7895 "only bit-fields can have sub-char alignment");
7896 CharUnits FieldOffset =
7897 Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
7898 QualType FieldTy = FD->getType();
7899 if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
7900 return false;
7901 ++FieldIdx;
7902 }
7903
7904 return true;
7905 }
7906
7907 bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
7908 const auto *CAT =
7909 dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
7910 if (!CAT)
7911 return false;
7912
7913 CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
7914 unsigned NumInitializedElts = Val.getArrayInitializedElts();
7915 unsigned ArraySize = Val.getArraySize();
7916 // First, initialize the initialized elements.
7917 for (unsigned I = 0; I != NumInitializedElts; ++I) {
7918 const APValue &SubObj = Val.getArrayInitializedElt(I);
7919 if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
7920 return false;
7921 }
7922
7923 // Next, initialize the rest of the array using the filler.
7924 if (Val.hasArrayFiller()) {
7925 const APValue &Filler = Val.getArrayFiller();
7926 for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
7927 if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
7928 return false;
7929 }
7930 }
7931
7932 return true;
7933 }
7934
7935 bool visitComplex(const APValue &Val, QualType Ty, CharUnits Offset) {
7936 const ComplexType *ComplexTy = Ty->castAs<ComplexType>();
7937 QualType EltTy = ComplexTy->getElementType();
7938 CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
7939 bool IsInt = Val.isComplexInt();
7940
7941 if (IsInt) {
7942 if (!visitInt(Val.getComplexIntReal(), EltTy,
7943 Offset + (0 * EltSizeChars)))
7944 return false;
7945 if (!visitInt(Val.getComplexIntImag(), EltTy,
7946 Offset + (1 * EltSizeChars)))
7947 return false;
7948 } else {
7949 if (!visitFloat(Val.getComplexFloatReal(), EltTy,
7950 Offset + (0 * EltSizeChars)))
7951 return false;
7952 if (!visitFloat(Val.getComplexFloatImag(), EltTy,
7953 Offset + (1 * EltSizeChars)))
7954 return false;
7955 }
7956
7957 return true;
7958 }
7959
7960 bool visitVector(const APValue &Val, QualType Ty, CharUnits Offset) {
7961 const VectorType *VTy = Ty->castAs<VectorType>();
7962 QualType EltTy = VTy->getElementType();
7963 unsigned NElts = VTy->getNumElements();
7964
7965 if (VTy->isPackedVectorBoolType(Info.Ctx)) {
7966 // Special handling for OpenCL bool vectors:
7967 // Since these vectors are stored as packed bits, but we can't write
7968 // individual bits to the BitCastBuffer, we'll buffer all of the elements
7969 // together into an appropriately sized APInt and write them all out at
7970 // once. Because we don't accept vectors where NElts * EltSize isn't a
7971 // multiple of the char size, there will be no padding space, so we don't
7972 // have to worry about writing data which should have been left
7973 // uninitialized.
7974 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
7975
7976 llvm::APInt Res = llvm::APInt::getZero(NElts);
7977 for (unsigned I = 0; I < NElts; ++I) {
7978 const llvm::APSInt &EltAsInt = Val.getVectorElt(I).getInt();
7979 assert(EltAsInt.isUnsigned() && EltAsInt.getBitWidth() == 1 &&
7980 "bool vector element must be 1-bit unsigned integer!");
7981
7982 Res.insertBits(EltAsInt, BigEndian ? (NElts - I - 1) : I);
7983 }
7984
7985 SmallVector<uint8_t, 8> Bytes(NElts / 8);
7986 llvm::StoreIntToMemory(Res, &*Bytes.begin(), NElts / 8);
7987 Buffer.writeObject(Offset, Bytes);
7988 } else {
7989 // Iterate over each of the elements and write them out to the buffer at
7990 // the appropriate offset.
7991 CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
7992 for (unsigned I = 0; I < NElts; ++I) {
7993 if (!visit(Val.getVectorElt(I), EltTy, Offset + I * EltSizeChars))
7994 return false;
7995 }
7996 }
7997
7998 return true;
7999 }
8000
8001 bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
8002 APSInt AdjustedVal = Val;
8003 unsigned Width = AdjustedVal.getBitWidth();
8004 if (Ty->isBooleanType()) {
8005 Width = Info.Ctx.getTypeSize(Ty);
8006 AdjustedVal = AdjustedVal.extend(Width);
8007 }
8008
8009 SmallVector<uint8_t, 8> Bytes(Width / 8);
8010 llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8);
8011 Buffer.writeObject(Offset, Bytes);
8012 return true;
8013 }
8014
8015 bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
8016 APSInt AsInt(Val.bitcastToAPInt());
8017 return visitInt(AsInt, Ty, Offset);
8018 }
8019
8020public:
8021 static std::optional<BitCastBuffer>
8022 convert(EvalInfo &Info, const APValue &Src, const CastExpr *BCE) {
8023 CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
8024 APValueToBufferConverter Converter(Info, DstSize, BCE);
8025 if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
8026 return std::nullopt;
8027 return Converter.Buffer;
8028 }
8029};
8030
8031/// Write an BitCastBuffer into an APValue.
8032class BufferToAPValueConverter {
8033 EvalInfo &Info;
8034 const BitCastBuffer &Buffer;
8035 const CastExpr *BCE;
8036
8037 BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
8038 const CastExpr *BCE)
8039 : Info(Info), Buffer(Buffer), BCE(BCE) {}
8040
8041 // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
8042 // with an invalid type, so anything left is a deficiency on our part (FIXME).
8043 // Ideally this will be unreachable.
8044 std::nullopt_t unsupportedType(QualType Ty) {
8045 Info.FFDiag(BCE->getBeginLoc(),
8046 diag::note_constexpr_bit_cast_unsupported_type)
8047 << Ty;
8048 return std::nullopt;
8049 }
8050
8051 std::nullopt_t unrepresentableValue(QualType Ty, const APSInt &Val) {
8052 Info.FFDiag(BCE->getBeginLoc(),
8053 diag::note_constexpr_bit_cast_unrepresentable_value)
8054 << Ty << toString(Val, /*Radix=*/10);
8055 return std::nullopt;
8056 }
8057
8058 std::optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
8059 const EnumType *EnumSugar = nullptr) {
8060 if (T->isNullPtrType()) {
8061 uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
8062 return APValue((Expr *)nullptr,
8063 /*Offset=*/CharUnits::fromQuantity(NullValue),
8064 APValue::NoLValuePath{}, /*IsNullPtr=*/true);
8065 }
8066
8067 CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
8068
8069 // Work around floating point types that contain unused padding bytes. This
8070 // is really just `long double` on x86, which is the only fundamental type
8071 // with padding bytes.
8072 if (T->isRealFloatingType()) {
8073 const llvm::fltSemantics &Semantics =
8074 Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
8075 unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics);
8076 assert(NumBits % 8 == 0);
8077 CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8);
8078 if (NumBytes != SizeOf)
8079 SizeOf = NumBytes;
8080 }
8081
8082 SmallVector<uint8_t, 8> Bytes;
8083 if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
8084 // If this is std::byte or unsigned char, then its okay to store an
8085 // indeterminate value.
8086 bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
8087 bool IsUChar =
8088 !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
8089 T->isSpecificBuiltinType(BuiltinType::Char_U));
8090 if (!IsStdByte && !IsUChar) {
8091 QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
8092 Info.FFDiag(BCE->getExprLoc(),
8093 diag::note_constexpr_bit_cast_indet_dest)
8094 << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
8095 return std::nullopt;
8096 }
8097
8099 }
8100
8101 APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
8102 llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
8103
8105 Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
8106
8107 unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0));
8108 if (IntWidth != Val.getBitWidth()) {
8109 APSInt Truncated = Val.trunc(IntWidth);
8110 if (Truncated.extend(Val.getBitWidth()) != Val)
8111 return unrepresentableValue(QualType(T, 0), Val);
8112 Val = Truncated;
8113 }
8114
8115 return APValue(Val);
8116 }
8117
8118 if (T->isRealFloatingType()) {
8119 const llvm::fltSemantics &Semantics =
8120 Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
8121 return APValue(APFloat(Semantics, Val));
8122 }
8123
8124 return unsupportedType(QualType(T, 0));
8125 }
8126
8127 std::optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
8128 const RecordDecl *RD = RTy->getAsRecordDecl();
8129 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
8130
8131 unsigned NumBases = 0;
8132 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
8133 NumBases = CXXRD->getNumBases();
8134
8135 APValue ResultVal(APValue::UninitStruct(), NumBases, RD->getNumFields());
8136
8137 // Visit the base classes.
8138 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
8139 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
8140 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
8141 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
8142
8143 std::optional<APValue> SubObj = visitType(
8144 BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
8145 if (!SubObj)
8146 return std::nullopt;
8147 ResultVal.getStructBase(I) = *SubObj;
8148 }
8149 }
8150
8151 // Visit the fields.
8152 unsigned FieldIdx = 0;
8153 for (FieldDecl *FD : RD->fields()) {
8154 // FIXME: We don't currently support bit-fields. A lot of the logic for
8155 // this is in CodeGen, so we need to factor it around.
8156 if (FD->isBitField()) {
8157 Info.FFDiag(BCE->getBeginLoc(),
8158 diag::note_constexpr_bit_cast_unsupported_bitfield);
8159 return std::nullopt;
8160 }
8161
8162 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
8163 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
8164
8165 CharUnits FieldOffset =
8166 CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
8167 Offset;
8168 QualType FieldTy = FD->getType();
8169 std::optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
8170 if (!SubObj)
8171 return std::nullopt;
8172 ResultVal.getStructField(FieldIdx) = *SubObj;
8173 ++FieldIdx;
8174 }
8175
8176 return ResultVal;
8177 }
8178
8179 std::optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
8180 QualType RepresentationType =
8181 Ty->getDecl()->getDefinitionOrSelf()->getIntegerType();
8182 assert(!RepresentationType.isNull() &&
8183 "enum forward decl should be caught by Sema");
8184 const auto *AsBuiltin =
8185 RepresentationType.getCanonicalType()->castAs<BuiltinType>();
8186 // Recurse into the underlying type. Treat std::byte transparently as
8187 // unsigned char.
8188 return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
8189 }
8190
8191 std::optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
8192 size_t Size = Ty->getLimitedSize();
8193 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
8194
8195 APValue ArrayValue(APValue::UninitArray(), Size, Size);
8196 for (size_t I = 0; I != Size; ++I) {
8197 std::optional<APValue> ElementValue =
8198 visitType(Ty->getElementType(), Offset + I * ElementWidth);
8199 if (!ElementValue)
8200 return std::nullopt;
8201 ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
8202 }
8203
8204 return ArrayValue;
8205 }
8206
8207 std::optional<APValue> visit(const ComplexType *Ty, CharUnits Offset) {
8208 QualType ElementType = Ty->getElementType();
8209 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(ElementType);
8210 bool IsInt = ElementType->isIntegerType();
8211
8212 std::optional<APValue> Values[2];
8213 for (unsigned I = 0; I != 2; ++I) {
8214 Values[I] = visitType(Ty->getElementType(), Offset + I * ElementWidth);
8215 if (!Values[I])
8216 return std::nullopt;
8217 }
8218
8219 if (IsInt)
8220 return APValue(Values[0]->getInt(), Values[1]->getInt());
8221 return APValue(Values[0]->getFloat(), Values[1]->getFloat());
8222 }
8223
8224 std::optional<APValue> visit(const VectorType *VTy, CharUnits Offset) {
8225 QualType EltTy = VTy->getElementType();
8226 unsigned NElts = VTy->getNumElements();
8227 unsigned EltSize =
8228 VTy->isPackedVectorBoolType(Info.Ctx) ? 1 : Info.Ctx.getTypeSize(EltTy);
8229
8230 SmallVector<APValue, 4> Elts;
8231 Elts.reserve(NElts);
8232 if (VTy->isPackedVectorBoolType(Info.Ctx)) {
8233 // Special handling for OpenCL bool vectors:
8234 // Since these vectors are stored as packed bits, but we can't read
8235 // individual bits from the BitCastBuffer, we'll buffer all of the
8236 // elements together into an appropriately sized APInt and write them all
8237 // out at once. Because we don't accept vectors where NElts * EltSize
8238 // isn't a multiple of the char size, there will be no padding space, so
8239 // we don't have to worry about reading any padding data which didn't
8240 // actually need to be accessed.
8241 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
8242
8243 SmallVector<uint8_t, 8> Bytes;
8244 Bytes.reserve(NElts / 8);
8245 if (!Buffer.readObject(Offset, CharUnits::fromQuantity(NElts / 8), Bytes))
8246 return std::nullopt;
8247
8248 APSInt SValInt(NElts, true);
8249 llvm::LoadIntFromMemory(SValInt, &*Bytes.begin(), Bytes.size());
8250
8251 for (unsigned I = 0; I < NElts; ++I) {
8252 llvm::APInt Elt =
8253 SValInt.extractBits(1, (BigEndian ? NElts - I - 1 : I) * EltSize);
8254 Elts.emplace_back(
8255 APSInt(std::move(Elt), !EltTy->isSignedIntegerType()));
8256 }
8257 } else {
8258 // Iterate over each of the elements and read them from the buffer at
8259 // the appropriate offset.
8260 CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
8261 for (unsigned I = 0; I < NElts; ++I) {
8262 std::optional<APValue> EltValue =
8263 visitType(EltTy, Offset + I * EltSizeChars);
8264 if (!EltValue)
8265 return std::nullopt;
8266 Elts.push_back(std::move(*EltValue));
8267 }
8268 }
8269
8270 return APValue(Elts.data(), Elts.size());
8271 }
8272
8273 std::optional<APValue> visit(const Type *Ty, CharUnits Offset) {
8274 return unsupportedType(QualType(Ty, 0));
8275 }
8276
8277 std::optional<APValue> visitType(QualType Ty, CharUnits Offset) {
8278 QualType Can = Ty.getCanonicalType();
8279
8280 switch (Can->getTypeClass()) {
8281#define TYPE(Class, Base) \
8282 case Type::Class: \
8283 return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
8284#define ABSTRACT_TYPE(Class, Base)
8285#define NON_CANONICAL_TYPE(Class, Base) \
8286 case Type::Class: \
8287 llvm_unreachable("non-canonical type should be impossible!");
8288#define DEPENDENT_TYPE(Class, Base) \
8289 case Type::Class: \
8290 llvm_unreachable( \
8291 "dependent types aren't supported in the constant evaluator!");
8292#define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base) \
8293 case Type::Class: \
8294 llvm_unreachable("either dependent or not canonical!");
8295#include "clang/AST/TypeNodes.inc"
8296 }
8297 llvm_unreachable("Unhandled Type::TypeClass");
8298 }
8299
8300public:
8301 // Pull out a full value of type DstType.
8302 static std::optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
8303 const CastExpr *BCE) {
8304 BufferToAPValueConverter Converter(Info, Buffer, BCE);
8305 return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
8306 }
8307};
8308
8309static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
8310 QualType Ty, EvalInfo *Info,
8311 const ASTContext &Ctx,
8312 bool CheckingDest) {
8313 Ty = Ty.getCanonicalType();
8314
8315 auto diag = [&](int Reason) {
8316 if (Info)
8317 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
8318 << CheckingDest << (Reason == 4) << Reason;
8319 return false;
8320 };
8321 auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
8322 if (Info)
8323 Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
8324 << NoteTy << Construct << Ty;
8325 return false;
8326 };
8327
8328 if (Ty->isUnionType())
8329 return diag(0);
8330 if (Ty->isPointerType())
8331 return diag(1);
8332 if (Ty->isMemberPointerType())
8333 return diag(2);
8334 if (Ty.isVolatileQualified())
8335 return diag(3);
8336
8337 if (RecordDecl *Record = Ty->getAsRecordDecl()) {
8338 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
8339 for (CXXBaseSpecifier &BS : CXXRD->bases())
8340 if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
8341 CheckingDest))
8342 return note(1, BS.getType(), BS.getBeginLoc());
8343 }
8344 for (FieldDecl *FD : Record->fields()) {
8345 if (FD->getType()->isReferenceType())
8346 return diag(4);
8347 if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
8348 CheckingDest))
8349 return note(0, FD->getType(), FD->getBeginLoc());
8350 }
8351 }
8352
8353 if (Ty->isArrayType() &&
8354 !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
8355 Info, Ctx, CheckingDest))
8356 return false;
8357
8358 if (const auto *VTy = Ty->getAs<VectorType>()) {
8359 QualType EltTy = VTy->getElementType();
8360 unsigned NElts = VTy->getNumElements();
8361 unsigned EltSize =
8362 VTy->isPackedVectorBoolType(Ctx) ? 1 : Ctx.getTypeSize(EltTy);
8363
8364 if ((NElts * EltSize) % Ctx.getCharWidth() != 0) {
8365 // The vector's size in bits is not a multiple of the target's byte size,
8366 // so its layout is unspecified. For now, we'll simply treat these cases
8367 // as unsupported (this should only be possible with OpenCL bool vectors
8368 // whose element count isn't a multiple of the byte size).
8369 if (Info)
8370 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_vector)
8371 << QualType(VTy, 0) << EltSize << NElts << Ctx.getCharWidth();
8372 return false;
8373 }
8374
8375 if (EltTy->isRealFloatingType() &&
8376 &Ctx.getFloatTypeSemantics(EltTy) == &APFloat::x87DoubleExtended()) {
8377 // The layout for x86_fp80 vectors seems to be handled very inconsistently
8378 // by both clang and LLVM, so for now we won't allow bit_casts involving
8379 // it in a constexpr context.
8380 if (Info)
8381 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_unsupported_type)
8382 << EltTy;
8383 return false;
8384 }
8385 }
8386
8387 return true;
8388}
8389
8390static bool checkBitCastConstexprEligibility(EvalInfo *Info,
8391 const ASTContext &Ctx,
8392 const CastExpr *BCE) {
8393 bool DestOK = checkBitCastConstexprEligibilityType(
8394 BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
8395 bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
8396 BCE->getBeginLoc(),
8397 BCE->getSubExpr()->getType(), Info, Ctx, false);
8398 return SourceOK;
8399}
8400
8401static bool handleRValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
8402 const APValue &SourceRValue,
8403 const CastExpr *BCE) {
8404 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
8405 "no host or target supports non 8-bit chars");
8406
8407 if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
8408 return false;
8409
8410 // Read out SourceValue into a char buffer.
8411 std::optional<BitCastBuffer> Buffer =
8412 APValueToBufferConverter::convert(Info, SourceRValue, BCE);
8413 if (!Buffer)
8414 return false;
8415
8416 // Write out the buffer into a new APValue.
8417 std::optional<APValue> MaybeDestValue =
8418 BufferToAPValueConverter::convert(Info, *Buffer, BCE);
8419 if (!MaybeDestValue)
8420 return false;
8421
8422 DestValue = std::move(*MaybeDestValue);
8423 return true;
8424}
8425
8426static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
8427 APValue &SourceValue,
8428 const CastExpr *BCE) {
8429 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
8430 "no host or target supports non 8-bit chars");
8431 assert(SourceValue.isLValue() &&
8432 "LValueToRValueBitcast requires an lvalue operand!");
8433
8434 LValue SourceLValue;
8435 APValue SourceRValue;
8436 SourceLValue.setFrom(Info.Ctx, SourceValue);
8438 Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,
8439 SourceRValue, /*WantObjectRepresentation=*/true))
8440 return false;
8441
8442 return handleRValueToRValueBitCast(Info, DestValue, SourceRValue, BCE);
8443}
8444
8445template <class Derived>
8446class ExprEvaluatorBase
8447 : public ConstStmtVisitor<Derived, bool> {
8448private:
8449 Derived &getDerived() { return static_cast<Derived&>(*this); }
8450 bool DerivedSuccess(const APValue &V, const Expr *E) {
8451 return getDerived().Success(V, E);
8452 }
8453 bool DerivedZeroInitialization(const Expr *E) {
8454 return getDerived().ZeroInitialization(E);
8455 }
8456
8457 // Check whether a conditional operator with a non-constant condition is a
8458 // potential constant expression. If neither arm is a potential constant
8459 // expression, then the conditional operator is not either.
8460 template<typename ConditionalOperator>
8461 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
8462 assert(Info.checkingPotentialConstantExpression());
8463
8464 // Speculatively evaluate both arms.
8465 SmallVector<PartialDiagnosticAt, 8> Diag;
8466 {
8467 SpeculativeEvaluationRAII Speculate(Info, &Diag);
8468 StmtVisitorTy::Visit(E->getFalseExpr());
8469 if (Diag.empty())
8470 return;
8471 }
8472
8473 {
8474 SpeculativeEvaluationRAII Speculate(Info, &Diag);
8475 Diag.clear();
8476 StmtVisitorTy::Visit(E->getTrueExpr());
8477 if (Diag.empty())
8478 return;
8479 }
8480
8481 Error(E, diag::note_constexpr_conditional_never_const);
8482 }
8483
8484
8485 template<typename ConditionalOperator>
8486 bool HandleConditionalOperator(const ConditionalOperator *E) {
8487 bool BoolResult;
8488 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
8489 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
8490 CheckPotentialConstantConditional(E);
8491 return false;
8492 }
8493 if (Info.noteFailure()) {
8494 StmtVisitorTy::Visit(E->getTrueExpr());
8495 StmtVisitorTy::Visit(E->getFalseExpr());
8496 }
8497 return false;
8498 }
8499
8500 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
8501 return StmtVisitorTy::Visit(EvalExpr);
8502 }
8503
8504protected:
8505 EvalInfo &Info;
8506 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
8507 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
8508
8509 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
8510 return Info.CCEDiag(E, D);
8511 }
8512
8513 bool ZeroInitialization(const Expr *E) { return Error(E); }
8514
8515 bool IsConstantEvaluatedBuiltinCall(const CallExpr *E) {
8516 unsigned BuiltinOp = E->getBuiltinCallee();
8517 return BuiltinOp != 0 &&
8518 Info.Ctx.BuiltinInfo.isConstantEvaluated(BuiltinOp);
8519 }
8520
8521public:
8522 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
8523
8524 EvalInfo &getEvalInfo() { return Info; }
8525
8526 /// Report an evaluation error. This should only be called when an error is
8527 /// first discovered. When propagating an error, just return false.
8528 bool Error(const Expr *E, diag::kind D) {
8529 Info.FFDiag(E, D) << E->getSourceRange();
8530 return false;
8531 }
8532 bool Error(const Expr *E) {
8533 return Error(E, diag::note_invalid_subexpr_in_const_expr);
8534 }
8535
8536 bool VisitStmt(const Stmt *) {
8537 llvm_unreachable("Expression evaluator should not be called on stmts");
8538 }
8539 bool VisitExpr(const Expr *E) {
8540 return Error(E);
8541 }
8542
8543 bool VisitEmbedExpr(const EmbedExpr *E) {
8544 const auto It = E->begin();
8545 return StmtVisitorTy::Visit(*It);
8546 }
8547
8548 bool VisitPredefinedExpr(const PredefinedExpr *E) {
8549 return StmtVisitorTy::Visit(E->getFunctionName());
8550 }
8551 bool VisitConstantExpr(const ConstantExpr *E) {
8552 if (E->hasAPValueResult())
8553 return DerivedSuccess(E->getAPValueResult(), E);
8554
8555 return StmtVisitorTy::Visit(E->getSubExpr());
8556 }
8557
8558 bool VisitParenExpr(const ParenExpr *E)
8559 { return StmtVisitorTy::Visit(E->getSubExpr()); }
8560 bool VisitUnaryExtension(const UnaryOperator *E)
8561 { return StmtVisitorTy::Visit(E->getSubExpr()); }
8562 bool VisitUnaryPlus(const UnaryOperator *E)
8563 { return StmtVisitorTy::Visit(E->getSubExpr()); }
8564 bool VisitChooseExpr(const ChooseExpr *E)
8565 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
8566 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
8567 { return StmtVisitorTy::Visit(E->getResultExpr()); }
8568 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
8569 { return StmtVisitorTy::Visit(E->getReplacement()); }
8570 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
8571 TempVersionRAII RAII(*Info.CurrentCall);
8572 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
8573 return StmtVisitorTy::Visit(E->getExpr());
8574 }
8575 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
8576 TempVersionRAII RAII(*Info.CurrentCall);
8577 // The initializer may not have been parsed yet, or might be erroneous.
8578 if (!E->getExpr())
8579 return Error(E);
8580 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
8581 return StmtVisitorTy::Visit(E->getExpr());
8582 }
8583
8584 bool VisitExprWithCleanups(const ExprWithCleanups *E) {
8585 FullExpressionRAII Scope(Info);
8586 return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy();
8587 }
8588
8589 // Temporaries are registered when created, so we don't care about
8590 // CXXBindTemporaryExpr.
8591 bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
8592 return StmtVisitorTy::Visit(E->getSubExpr());
8593 }
8594
8595 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
8596 CCEDiag(E, diag::note_constexpr_invalid_cast)
8597 << diag::ConstexprInvalidCastKind::Reinterpret;
8598 return static_cast<Derived*>(this)->VisitCastExpr(E);
8599 }
8600 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
8601 if (!Info.Ctx.getLangOpts().CPlusPlus20)
8602 CCEDiag(E, diag::note_constexpr_invalid_cast)
8603 << diag::ConstexprInvalidCastKind::Dynamic;
8604 return static_cast<Derived*>(this)->VisitCastExpr(E);
8605 }
8606 bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
8607 return static_cast<Derived*>(this)->VisitCastExpr(E);
8608 }
8609
8610 bool VisitBinaryOperator(const BinaryOperator *E) {
8611 switch (E->getOpcode()) {
8612 default:
8613 return Error(E);
8614
8615 case BO_Comma:
8616 VisitIgnoredValue(E->getLHS());
8617 return StmtVisitorTy::Visit(E->getRHS());
8618
8619 case BO_PtrMemD:
8620 case BO_PtrMemI: {
8621 LValue Obj;
8622 if (!HandleMemberPointerAccess(Info, E, Obj))
8623 return false;
8625 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
8626 return false;
8627 return DerivedSuccess(Result, E);
8628 }
8629 }
8630 }
8631
8632 bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) {
8633 return StmtVisitorTy::Visit(E->getSemanticForm());
8634 }
8635
8636 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
8637 // Evaluate and cache the common expression. We treat it as a temporary,
8638 // even though it's not quite the same thing.
8639 LValue CommonLV;
8640 if (!Evaluate(Info.CurrentCall->createTemporary(
8641 E->getOpaqueValue(),
8642 getStorageType(Info.Ctx, E->getOpaqueValue()),
8643 ScopeKind::FullExpression, CommonLV),
8644 Info, E->getCommon()))
8645 return false;
8646
8647 return HandleConditionalOperator(E);
8648 }
8649
8650 bool VisitConditionalOperator(const ConditionalOperator *E) {
8651 bool IsBcpCall = false;
8652 // If the condition (ignoring parens) is a __builtin_constant_p call,
8653 // the result is a constant expression if it can be folded without
8654 // side-effects. This is an important GNU extension. See GCC PR38377
8655 // for discussion.
8656 if (const CallExpr *CallCE =
8657 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
8658 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
8659 IsBcpCall = true;
8660
8661 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
8662 // constant expression; we can't check whether it's potentially foldable.
8663 // FIXME: We should instead treat __builtin_constant_p as non-constant if
8664 // it would return 'false' in this mode.
8665 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
8666 return false;
8667
8668 FoldConstant Fold(Info, IsBcpCall);
8669 if (!HandleConditionalOperator(E)) {
8670 Fold.keepDiagnostics();
8671 return false;
8672 }
8673
8674 return true;
8675 }
8676
8677 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
8678 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E);
8679 Value && !Value->isAbsent())
8680 return DerivedSuccess(*Value, E);
8681
8682 const Expr *Source = E->getSourceExpr();
8683 if (!Source)
8684 return Error(E);
8685 if (Source == E) {
8686 assert(0 && "OpaqueValueExpr recursively refers to itself");
8687 return Error(E);
8688 }
8689 return StmtVisitorTy::Visit(Source);
8690 }
8691
8692 bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
8693 for (const Expr *SemE : E->semantics()) {
8694 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
8695 // FIXME: We can't handle the case where an OpaqueValueExpr is also the
8696 // result expression: there could be two different LValues that would
8697 // refer to the same object in that case, and we can't model that.
8698 if (SemE == E->getResultExpr())
8699 return Error(E);
8700
8701 // Unique OVEs get evaluated if and when we encounter them when
8702 // emitting the rest of the semantic form, rather than eagerly.
8703 if (OVE->isUnique())
8704 continue;
8705
8706 LValue LV;
8707 if (!Evaluate(Info.CurrentCall->createTemporary(
8708 OVE, getStorageType(Info.Ctx, OVE),
8709 ScopeKind::FullExpression, LV),
8710 Info, OVE->getSourceExpr()))
8711 return false;
8712 } else if (SemE == E->getResultExpr()) {
8713 if (!StmtVisitorTy::Visit(SemE))
8714 return false;
8715 } else {
8716 if (!EvaluateIgnoredValue(Info, SemE))
8717 return false;
8718 }
8719 }
8720 return true;
8721 }
8722
8723 bool VisitCallExpr(const CallExpr *E) {
8725 if (!handleCallExpr(E, Result, nullptr))
8726 return false;
8727 return DerivedSuccess(Result, E);
8728 }
8729
8730 bool handleCallExpr(const CallExpr *E, APValue &Result,
8731 const LValue *ResultSlot) {
8732 CallScopeRAII CallScope(Info);
8733
8734 const Expr *Callee = E->getCallee()->IgnoreParens();
8735 QualType CalleeType = Callee->getType();
8736
8737 const FunctionDecl *FD = nullptr;
8738 LValue *This = nullptr, ObjectArg;
8739 auto Args = ArrayRef(E->getArgs(), E->getNumArgs());
8740 bool HasQualifier = false;
8741
8742 CallRef Call;
8743
8744 // Extract function decl and 'this' pointer from the callee.
8745 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
8746 const CXXMethodDecl *Member = nullptr;
8747 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
8748 // Explicit bound member calls, such as x.f() or p->g();
8749 if (!EvaluateObjectArgument(Info, ME->getBase(), ObjectArg))
8750 return false;
8751 Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
8752 if (!Member)
8753 return Error(Callee);
8754 This = &ObjectArg;
8755 HasQualifier = ME->hasQualifier();
8756 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
8757 // Indirect bound member calls ('.*' or '->*').
8758 const ValueDecl *D =
8759 HandleMemberPointerAccess(Info, BE, ObjectArg, false);
8760 if (!D)
8761 return false;
8762 Member = dyn_cast<CXXMethodDecl>(D);
8763 if (!Member)
8764 return Error(Callee);
8765 This = &ObjectArg;
8766 } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
8767 if (!Info.getLangOpts().CPlusPlus20)
8768 Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
8769 return EvaluateObjectArgument(Info, PDE->getBase(), ObjectArg) &&
8770 HandleDestruction(Info, PDE, ObjectArg, PDE->getDestroyedType());
8771 } else
8772 return Error(Callee);
8773 FD = Member;
8774 } else if (CalleeType->isFunctionPointerType()) {
8775 LValue CalleeLV;
8776 if (!EvaluatePointer(Callee, CalleeLV, Info))
8777 return false;
8778
8779 if (!CalleeLV.getLValueOffset().isZero())
8780 return Error(Callee);
8781 if (CalleeLV.isNullPointer()) {
8782 Info.FFDiag(Callee, diag::note_constexpr_null_callee)
8783 << const_cast<Expr *>(Callee);
8784 return false;
8785 }
8786 FD = dyn_cast_or_null<FunctionDecl>(
8787 CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>());
8788 if (!FD)
8789 return Error(Callee);
8790 // Don't call function pointers which have been cast to some other type.
8791 // Per DR (no number yet), the caller and callee can differ in noexcept.
8793 CalleeType->getPointeeType(), FD->getType())) {
8794 return Error(E);
8795 }
8796
8797 // For an (overloaded) assignment expression, evaluate the RHS before the
8798 // LHS.
8799 auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
8800 if (OCE && OCE->isAssignmentOp()) {
8801 assert(Args.size() == 2 && "wrong number of arguments in assignment");
8802 Call = Info.CurrentCall->createCall(FD);
8803 bool HasThis = false;
8804 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
8805 HasThis = MD->isImplicitObjectMemberFunction();
8806 if (!EvaluateArgs(HasThis ? Args.slice(1) : Args, Call, Info, FD,
8807 /*RightToLeft=*/true, &ObjectArg))
8808 return false;
8809 }
8810
8811 // Overloaded operator calls to member functions are represented as normal
8812 // calls with '*this' as the first argument.
8813 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8814 if (MD &&
8815 (MD->isImplicitObjectMemberFunction() || (OCE && MD->isStatic()))) {
8816 // FIXME: When selecting an implicit conversion for an overloaded
8817 // operator delete, we sometimes try to evaluate calls to conversion
8818 // operators without a 'this' parameter!
8819 if (Args.empty())
8820 return Error(E);
8821
8822 if (!EvaluateObjectArgument(Info, Args[0], ObjectArg))
8823 return false;
8824
8825 // If we are calling a static operator, the 'this' argument needs to be
8826 // ignored after being evaluated.
8827 if (MD->isInstance())
8828 This = &ObjectArg;
8829
8830 // If this is syntactically a simple assignment using a trivial
8831 // assignment operator, start the lifetimes of union members as needed,
8832 // per C++20 [class.union]5.
8833 if (Info.getLangOpts().CPlusPlus20 && OCE &&
8834 OCE->getOperator() == OO_Equal && MD->isTrivial() &&
8835 !MaybeHandleUnionActiveMemberChange(Info, Args[0], ObjectArg))
8836 return false;
8837
8838 Args = Args.slice(1);
8839 } else if (MD && MD->isLambdaStaticInvoker()) {
8840 // Map the static invoker for the lambda back to the call operator.
8841 // Conveniently, we don't have to slice out the 'this' argument (as is
8842 // being done for the non-static case), since a static member function
8843 // doesn't have an implicit argument passed in.
8844 const CXXRecordDecl *ClosureClass = MD->getParent();
8845 assert(
8846 ClosureClass->captures().empty() &&
8847 "Number of captures must be zero for conversion to function-ptr");
8848
8849 const CXXMethodDecl *LambdaCallOp =
8850 ClosureClass->getLambdaCallOperator();
8851
8852 // Set 'FD', the function that will be called below, to the call
8853 // operator. If the closure object represents a generic lambda, find
8854 // the corresponding specialization of the call operator.
8855
8856 if (ClosureClass->isGenericLambda()) {
8857 assert(MD->isFunctionTemplateSpecialization() &&
8858 "A generic lambda's static-invoker function must be a "
8859 "template specialization");
8860 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
8861 FunctionTemplateDecl *CallOpTemplate =
8862 LambdaCallOp->getDescribedFunctionTemplate();
8863 void *InsertPos = nullptr;
8864 FunctionDecl *CorrespondingCallOpSpecialization =
8865 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
8866 assert(CorrespondingCallOpSpecialization &&
8867 "We must always have a function call operator specialization "
8868 "that corresponds to our static invoker specialization");
8869 assert(isa<CXXMethodDecl>(CorrespondingCallOpSpecialization));
8870 FD = CorrespondingCallOpSpecialization;
8871 } else
8872 FD = LambdaCallOp;
8874 if (FD->getDeclName().isAnyOperatorNew()) {
8875 LValue Ptr;
8876 if (!HandleOperatorNewCall(Info, E, Ptr))
8877 return false;
8878 Ptr.moveInto(Result);
8879 return CallScope.destroy();
8880 } else {
8881 return HandleOperatorDeleteCall(Info, E) && CallScope.destroy();
8882 }
8883 }
8884 } else
8885 return Error(E);
8886
8887 // Evaluate the arguments now if we've not already done so.
8888 if (!Call) {
8889 Call = Info.CurrentCall->createCall(FD);
8890 if (!EvaluateArgs(Args, Call, Info, FD, /*RightToLeft*/ false,
8891 &ObjectArg))
8892 return false;
8893 }
8894
8895 SmallVector<QualType, 4> CovariantAdjustmentPath;
8896 if (This) {
8897 auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
8898 if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
8899 // Perform virtual dispatch, if necessary.
8900 FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
8901 CovariantAdjustmentPath);
8902 if (!FD)
8903 return false;
8904 } else if (NamedMember && NamedMember->isImplicitObjectMemberFunction()) {
8905 // Check that the 'this' pointer points to an object of the right type.
8906 // FIXME: If this is an assignment operator call, we may need to change
8907 // the active union member before we check this.
8908 if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
8909 return false;
8910 }
8911 }
8912
8913 // Destructor calls are different enough that they have their own codepath.
8914 if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
8915 assert(This && "no 'this' pointer for destructor call");
8916 return HandleDestruction(Info, E, *This,
8917 Info.Ctx.getCanonicalTagType(DD->getParent())) &&
8918 CallScope.destroy();
8919 }
8920
8921 const FunctionDecl *Definition = nullptr;
8922 Stmt *Body = FD->getBody(Definition);
8923 SourceLocation Loc = E->getExprLoc();
8924
8925 // Treat the object argument as `this` when evaluating defaulted
8926 // special menmber functions
8928 This = &ObjectArg;
8929
8930 if (!CheckConstexprFunction(Info, Loc, FD, Definition, Body) ||
8931 !HandleFunctionCall(Loc, Definition, This, E, Args, Call, Body, Info,
8932 Result, ResultSlot))
8933 return false;
8934
8935 if (!CovariantAdjustmentPath.empty() &&
8937 CovariantAdjustmentPath))
8938 return false;
8939
8940 return CallScope.destroy();
8941 }
8942
8943 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
8944 return StmtVisitorTy::Visit(E->getInitializer());
8945 }
8946 bool VisitInitListExpr(const InitListExpr *E) {
8947 if (E->getNumInits() == 0)
8948 return DerivedZeroInitialization(E);
8949 if (E->getNumInits() == 1)
8950 return StmtVisitorTy::Visit(E->getInit(0));
8951 return Error(E);
8952 }
8953 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
8954 return DerivedZeroInitialization(E);
8955 }
8956 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
8957 return DerivedZeroInitialization(E);
8958 }
8959 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
8960 return DerivedZeroInitialization(E);
8961 }
8962
8963 /// A member expression where the object is a prvalue is itself a prvalue.
8964 bool VisitMemberExpr(const MemberExpr *E) {
8965 assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
8966 "missing temporary materialization conversion");
8967 assert(!E->isArrow() && "missing call to bound member function?");
8968
8969 APValue Val;
8970 if (!Evaluate(Val, Info, E->getBase()))
8971 return false;
8972
8973 QualType BaseTy = E->getBase()->getType();
8974
8975 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
8976 if (!FD) return Error(E);
8977 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
8978 assert(BaseTy->castAsCanonical<RecordType>()->getDecl() ==
8979 FD->getParent()->getCanonicalDecl() &&
8980 "record / field mismatch");
8981
8982 // Note: there is no lvalue base here. But this case should only ever
8983 // happen in C or in C++98, where we cannot be evaluating a constexpr
8984 // constructor, which is the only case the base matters.
8985 CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
8986 SubobjectDesignator Designator(BaseTy);
8987 Designator.addDeclUnchecked(FD);
8988
8990 return extractSubobject(Info, E, Obj, Designator, Result) &&
8991 DerivedSuccess(Result, E);
8992 }
8993
8994 bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) {
8995 APValue Val;
8996 if (!Evaluate(Val, Info, E->getBase()))
8997 return false;
8998
8999 if (Val.isVector()) {
9000 SmallVector<uint32_t, 4> Indices;
9001 E->getEncodedElementAccess(Indices);
9002 if (Indices.size() == 1) {
9003 // Return scalar.
9004 return DerivedSuccess(Val.getVectorElt(Indices[0]), E);
9005 } else {
9006 // Construct new APValue vector.
9007 SmallVector<APValue, 4> Elts;
9008 for (unsigned I = 0; I < Indices.size(); ++I) {
9009 Elts.push_back(Val.getVectorElt(Indices[I]));
9010 }
9011 APValue VecResult(Elts.data(), Indices.size());
9012 return DerivedSuccess(VecResult, E);
9013 }
9014 }
9015
9016 return false;
9017 }
9018
9019 bool VisitCastExpr(const CastExpr *E) {
9020 switch (E->getCastKind()) {
9021 default:
9022 break;
9023
9024 case CK_AtomicToNonAtomic: {
9025 APValue AtomicVal;
9026 // This does not need to be done in place even for class/array types:
9027 // atomic-to-non-atomic conversion implies copying the object
9028 // representation.
9029 if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
9030 return false;
9031 return DerivedSuccess(AtomicVal, E);
9032 }
9033
9034 case CK_NoOp:
9035 case CK_UserDefinedConversion:
9036 return StmtVisitorTy::Visit(E->getSubExpr());
9037
9038 case CK_HLSLArrayRValue: {
9039 const Expr *SubExpr = E->getSubExpr();
9040 if (!SubExpr->isGLValue()) {
9041 APValue Val;
9042 if (!Evaluate(Val, Info, SubExpr))
9043 return false;
9044 return DerivedSuccess(Val, E);
9045 }
9046
9047 LValue LVal;
9048 if (!EvaluateLValue(SubExpr, LVal, Info))
9049 return false;
9050 APValue RVal;
9051 // Note, we use the subexpression's type in order to retain cv-qualifiers.
9052 if (!handleLValueToRValueConversion(Info, E, SubExpr->getType(), LVal,
9053 RVal))
9054 return false;
9055 return DerivedSuccess(RVal, E);
9056 }
9057 case CK_LValueToRValue: {
9058 LValue LVal;
9059 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
9060 return false;
9061 APValue RVal;
9062 // Note, we use the subexpression's type in order to retain cv-qualifiers.
9064 LVal, RVal))
9065 return false;
9066 return DerivedSuccess(RVal, E);
9067 }
9068 case CK_LValueToRValueBitCast: {
9069 APValue DestValue, SourceValue;
9070 if (!Evaluate(SourceValue, Info, E->getSubExpr()))
9071 return false;
9072 if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
9073 return false;
9074 return DerivedSuccess(DestValue, E);
9075 }
9076
9077 case CK_AddressSpaceConversion: {
9078 APValue Value;
9079 if (!Evaluate(Value, Info, E->getSubExpr()))
9080 return false;
9081 return DerivedSuccess(Value, E);
9082 }
9083 }
9084
9085 return Error(E);
9086 }
9087
9088 bool VisitUnaryPostInc(const UnaryOperator *UO) {
9089 return VisitUnaryPostIncDec(UO);
9090 }
9091 bool VisitUnaryPostDec(const UnaryOperator *UO) {
9092 return VisitUnaryPostIncDec(UO);
9093 }
9094 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
9095 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9096 return Error(UO);
9097
9098 LValue LVal;
9099 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
9100 return false;
9101 APValue RVal;
9102 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
9103 UO->isIncrementOp(), &RVal))
9104 return false;
9105 return DerivedSuccess(RVal, UO);
9106 }
9107
9108 bool VisitStmtExpr(const StmtExpr *E) {
9109 // We will have checked the full-expressions inside the statement expression
9110 // when they were completed, and don't need to check them again now.
9111 llvm::SaveAndRestore NotCheckingForUB(Info.CheckingForUndefinedBehavior,
9112 false);
9113
9114 const CompoundStmt *CS = E->getSubStmt();
9115 if (CS->body_empty())
9116 return true;
9117
9118 BlockScopeRAII Scope(Info);
9120 BE = CS->body_end();
9121 /**/; ++BI) {
9122 if (BI + 1 == BE) {
9123 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
9124 if (!FinalExpr) {
9125 Info.FFDiag((*BI)->getBeginLoc(),
9126 diag::note_constexpr_stmt_expr_unsupported);
9127 return false;
9128 }
9129 return this->Visit(FinalExpr) && Scope.destroy();
9130 }
9131
9133 StmtResult Result = { ReturnValue, nullptr };
9134 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
9135 if (ESR != ESR_Succeeded) {
9136 // FIXME: If the statement-expression terminated due to 'return',
9137 // 'break', or 'continue', it would be nice to propagate that to
9138 // the outer statement evaluation rather than bailing out.
9139 if (ESR != ESR_Failed)
9140 Info.FFDiag((*BI)->getBeginLoc(),
9141 diag::note_constexpr_stmt_expr_unsupported);
9142 return false;
9143 }
9144 }
9145
9146 llvm_unreachable("Return from function from the loop above.");
9147 }
9148
9149 bool VisitPackIndexingExpr(const PackIndexingExpr *E) {
9150 return StmtVisitorTy::Visit(E->getSelectedExpr());
9151 }
9152
9153 /// Visit a value which is evaluated, but whose value is ignored.
9154 void VisitIgnoredValue(const Expr *E) {
9155 EvaluateIgnoredValue(Info, E);
9156 }
9157
9158 /// Potentially visit a MemberExpr's base expression.
9159 void VisitIgnoredBaseExpression(const Expr *E) {
9160 // While MSVC doesn't evaluate the base expression, it does diagnose the
9161 // presence of side-effecting behavior.
9162 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
9163 return;
9164 VisitIgnoredValue(E);
9165 }
9166};
9167
9168} // namespace
9169
9170//===----------------------------------------------------------------------===//
9171// Common base class for lvalue and temporary evaluation.
9172//===----------------------------------------------------------------------===//
9173namespace {
9174template<class Derived>
9175class LValueExprEvaluatorBase
9176 : public ExprEvaluatorBase<Derived> {
9177protected:
9178 LValue &Result;
9179 bool InvalidBaseOK;
9180 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
9181 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
9182
9183 bool Success(APValue::LValueBase B) {
9184 Result.set(B);
9185 return true;
9186 }
9187
9188 bool evaluatePointer(const Expr *E, LValue &Result) {
9189 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
9190 }
9191
9192public:
9193 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
9194 : ExprEvaluatorBaseTy(Info), Result(Result),
9195 InvalidBaseOK(InvalidBaseOK) {}
9196
9197 bool Success(const APValue &V, const Expr *E) {
9198 Result.setFrom(this->Info.Ctx, V);
9199 return true;
9200 }
9201
9202 bool VisitMemberExpr(const MemberExpr *E) {
9203 // Handle non-static data members.
9204 QualType BaseTy;
9205 bool EvalOK;
9206 if (E->isArrow()) {
9207 EvalOK = evaluatePointer(E->getBase(), Result);
9208 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
9209 } else if (E->getBase()->isPRValue()) {
9210 assert(E->getBase()->getType()->isRecordType());
9211 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
9212 BaseTy = E->getBase()->getType();
9213 } else {
9214 EvalOK = this->Visit(E->getBase());
9215 BaseTy = E->getBase()->getType();
9216 }
9217 if (!EvalOK) {
9218 if (!InvalidBaseOK)
9219 return false;
9220 Result.setInvalid(E);
9221 return true;
9222 }
9223
9224 const ValueDecl *MD = E->getMemberDecl();
9225 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
9226 assert(BaseTy->castAsCanonical<RecordType>()->getDecl() ==
9227 FD->getParent()->getCanonicalDecl() &&
9228 "record / field mismatch");
9229 (void)BaseTy;
9230 if (!HandleLValueMember(this->Info, E, Result, FD))
9231 return false;
9232 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
9233 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
9234 return false;
9235 } else
9236 return this->Error(E);
9237
9238 if (MD->getType()->isReferenceType()) {
9239 APValue RefValue;
9240 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
9241 RefValue))
9242 return false;
9243 return Success(RefValue, E);
9244 }
9245 return true;
9246 }
9247
9248 bool VisitBinaryOperator(const BinaryOperator *E) {
9249 switch (E->getOpcode()) {
9250 default:
9251 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9252
9253 case BO_PtrMemD:
9254 case BO_PtrMemI:
9255 return HandleMemberPointerAccess(this->Info, E, Result);
9256 }
9257 }
9258
9259 bool VisitCastExpr(const CastExpr *E) {
9260 switch (E->getCastKind()) {
9261 default:
9262 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9263
9264 case CK_DerivedToBase:
9265 case CK_UncheckedDerivedToBase:
9266 if (!this->Visit(E->getSubExpr()))
9267 return false;
9268
9269 // Now figure out the necessary offset to add to the base LV to get from
9270 // the derived class to the base class.
9271 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
9272 Result);
9273 }
9274 }
9275};
9276}
9277
9278//===----------------------------------------------------------------------===//
9279// LValue Evaluation
9280//
9281// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
9282// function designators (in C), decl references to void objects (in C), and
9283// temporaries (if building with -Wno-address-of-temporary).
9284//
9285// LValue evaluation produces values comprising a base expression of one of the
9286// following types:
9287// - Declarations
9288// * VarDecl
9289// * FunctionDecl
9290// - Literals
9291// * CompoundLiteralExpr in C (and in global scope in C++)
9292// * StringLiteral
9293// * PredefinedExpr
9294// * ObjCStringLiteralExpr
9295// * ObjCEncodeExpr
9296// * AddrLabelExpr
9297// * BlockExpr
9298// * CallExpr for a MakeStringConstant builtin
9299// - typeid(T) expressions, as TypeInfoLValues
9300// - Locals and temporaries
9301// * MaterializeTemporaryExpr
9302// * Any Expr, with a CallIndex indicating the function in which the temporary
9303// was evaluated, for cases where the MaterializeTemporaryExpr is missing
9304// from the AST (FIXME).
9305// * A MaterializeTemporaryExpr that has static storage duration, with no
9306// CallIndex, for a lifetime-extended temporary.
9307// * The ConstantExpr that is currently being evaluated during evaluation of an
9308// immediate invocation.
9309// plus an offset in bytes.
9310//===----------------------------------------------------------------------===//
9311namespace {
9312class LValueExprEvaluator
9313 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
9314public:
9315 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
9316 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
9317
9318 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
9319 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
9320
9321 bool VisitCallExpr(const CallExpr *E);
9322 bool VisitDeclRefExpr(const DeclRefExpr *E);
9323 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
9324 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
9325 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
9326 bool VisitMemberExpr(const MemberExpr *E);
9327 bool VisitStringLiteral(const StringLiteral *E) {
9328 return Success(APValue::LValueBase(
9329 E, 0, Info.getASTContext().getNextStringLiteralVersion()));
9330 }
9331 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
9332 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
9333 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
9334 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
9335 bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E);
9336 bool VisitUnaryDeref(const UnaryOperator *E);
9337 bool VisitUnaryReal(const UnaryOperator *E);
9338 bool VisitUnaryImag(const UnaryOperator *E);
9339 bool VisitUnaryPreInc(const UnaryOperator *UO) {
9340 return VisitUnaryPreIncDec(UO);
9341 }
9342 bool VisitUnaryPreDec(const UnaryOperator *UO) {
9343 return VisitUnaryPreIncDec(UO);
9344 }
9345 bool VisitBinAssign(const BinaryOperator *BO);
9346 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
9347
9348 bool VisitCastExpr(const CastExpr *E) {
9349 switch (E->getCastKind()) {
9350 default:
9351 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
9352
9353 case CK_LValueBitCast:
9354 this->CCEDiag(E, diag::note_constexpr_invalid_cast)
9355 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
9356 << Info.Ctx.getLangOpts().CPlusPlus;
9357 if (!Visit(E->getSubExpr()))
9358 return false;
9359 Result.Designator.setInvalid();
9360 return true;
9361
9362 case CK_BaseToDerived:
9363 if (!Visit(E->getSubExpr()))
9364 return false;
9365 return HandleBaseToDerivedCast(Info, E, Result);
9366
9367 case CK_Dynamic:
9368 if (!Visit(E->getSubExpr()))
9369 return false;
9371 }
9372 }
9373};
9374} // end anonymous namespace
9375
9376/// Get an lvalue to a field of a lambda's closure type.
9377static bool HandleLambdaCapture(EvalInfo &Info, const Expr *E, LValue &Result,
9378 const CXXMethodDecl *MD, const FieldDecl *FD,
9379 bool LValueToRValueConversion) {
9380 // Static lambda function call operators can't have captures. We already
9381 // diagnosed this, so bail out here.
9382 if (MD->isStatic()) {
9383 assert(Info.CurrentCall->This == nullptr &&
9384 "This should not be set for a static call operator");
9385 return false;
9386 }
9387
9388 // Start with 'Result' referring to the complete closure object...
9390 // Self may be passed by reference or by value.
9391 const ParmVarDecl *Self = MD->getParamDecl(0);
9392 if (Self->getType()->isReferenceType()) {
9393 APValue *RefValue = Info.getParamSlot(Info.CurrentCall->Arguments, Self);
9394 if (!RefValue->allowConstexprUnknown() || RefValue->hasValue())
9395 Result.setFrom(Info.Ctx, *RefValue);
9396 } else {
9397 const ParmVarDecl *VD = Info.CurrentCall->Arguments.getOrigParam(Self);
9398 CallStackFrame *Frame =
9399 Info.getCallFrameAndDepth(Info.CurrentCall->Arguments.CallIndex)
9400 .first;
9401 unsigned Version = Info.CurrentCall->Arguments.Version;
9402 Result.set({VD, Frame->Index, Version});
9403 }
9404 } else
9405 Result = *Info.CurrentCall->This;
9406
9407 // ... then update it to refer to the field of the closure object
9408 // that represents the capture.
9409 if (!HandleLValueMember(Info, E, Result, FD))
9410 return false;
9411
9412 // And if the field is of reference type (or if we captured '*this' by
9413 // reference), update 'Result' to refer to what
9414 // the field refers to.
9415 if (LValueToRValueConversion) {
9416 APValue RVal;
9417 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result, RVal))
9418 return false;
9419 Result.setFrom(Info.Ctx, RVal);
9420 }
9421 return true;
9422}
9423
9424/// Evaluate an expression as an lvalue. This can be legitimately called on
9425/// expressions which are not glvalues, in three cases:
9426/// * function designators in C, and
9427/// * "extern void" objects
9428/// * @selector() expressions in Objective-C
9429static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
9430 bool InvalidBaseOK) {
9431 assert(!E->isValueDependent());
9432 assert(E->isGLValue() || E->getType()->isFunctionType() ||
9434 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
9435}
9436
9437bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
9438 const ValueDecl *D = E->getDecl();
9439
9440 // If we are within a lambda's call operator, check whether the 'VD' referred
9441 // to within 'E' actually represents a lambda-capture that maps to a
9442 // data-member/field within the closure object, and if so, evaluate to the
9443 // field or what the field refers to.
9444 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
9446 // We don't always have a complete capture-map when checking or inferring if
9447 // the function call operator meets the requirements of a constexpr function
9448 // - but we don't need to evaluate the captures to determine constexprness
9449 // (dcl.constexpr C++17).
9450 if (Info.checkingPotentialConstantExpression())
9451 return false;
9452
9453 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(D)) {
9454 const auto *MD = cast<CXXMethodDecl>(Info.CurrentCall->Callee);
9455 return HandleLambdaCapture(Info, E, Result, MD, FD,
9456 FD->getType()->isReferenceType());
9457 }
9458 }
9459
9460 if (isa<FunctionDecl, MSGuidDecl, TemplateParamObjectDecl,
9461 UnnamedGlobalConstantDecl>(D))
9462 return Success(cast<ValueDecl>(D));
9463 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
9464 return VisitVarDecl(E, VD);
9465 if (const BindingDecl *BD = dyn_cast<BindingDecl>(D))
9466 return Visit(BD->getBinding());
9467 return Error(E);
9468}
9469
9470bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
9471 CallStackFrame *Frame = nullptr;
9472 unsigned Version = 0;
9473 if (VD->hasLocalStorage()) {
9474 // Only if a local variable was declared in the function currently being
9475 // evaluated, do we expect to be able to find its value in the current
9476 // frame. (Otherwise it was likely declared in an enclosing context and
9477 // could either have a valid evaluatable value (for e.g. a constexpr
9478 // variable) or be ill-formed (and trigger an appropriate evaluation
9479 // diagnostic)).
9480 CallStackFrame *CurrFrame = Info.CurrentCall;
9481 if (CurrFrame->Callee && CurrFrame->Callee->Equals(VD->getDeclContext())) {
9482 // Function parameters are stored in some caller's frame. (Usually the
9483 // immediate caller, but for an inherited constructor they may be more
9484 // distant.)
9485 if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) {
9486 if (CurrFrame->Arguments) {
9487 VD = CurrFrame->Arguments.getOrigParam(PVD);
9488 Frame =
9489 Info.getCallFrameAndDepth(CurrFrame->Arguments.CallIndex).first;
9490 Version = CurrFrame->Arguments.Version;
9491 }
9492 } else {
9493 Frame = CurrFrame;
9494 Version = CurrFrame->getCurrentTemporaryVersion(VD);
9495 }
9496 }
9497 }
9498
9499 if (!VD->getType()->isReferenceType()) {
9500 if (Frame) {
9501 Result.set({VD, Frame->Index, Version});
9502 return true;
9503 }
9504 return Success(VD);
9505 }
9506
9507 if (!Info.getLangOpts().CPlusPlus11) {
9508 Info.CCEDiag(E, diag::note_constexpr_ltor_non_integral, 1)
9509 << VD << VD->getType();
9510 Info.Note(VD->getLocation(), diag::note_declared_at);
9511 }
9512
9513 APValue *V;
9514 if (!evaluateVarDeclInit(Info, E, VD, Frame, Version, V))
9515 return false;
9516
9517 if (!V) {
9518 Result.set(VD);
9519 Result.AllowConstexprUnknown = true;
9520 return true;
9521 }
9522
9523 return Success(*V, E);
9524}
9525
9526bool LValueExprEvaluator::VisitCallExpr(const CallExpr *E) {
9527 if (!IsConstantEvaluatedBuiltinCall(E))
9528 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9529
9530 switch (E->getBuiltinCallee()) {
9531 default:
9532 return false;
9533 case Builtin::BIas_const:
9534 case Builtin::BIforward:
9535 case Builtin::BIforward_like:
9536 case Builtin::BImove:
9537 case Builtin::BImove_if_noexcept:
9538 if (cast<FunctionDecl>(E->getCalleeDecl())->isConstexpr())
9539 return Visit(E->getArg(0));
9540 break;
9541 }
9542
9543 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9544}
9545
9546bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
9547 const MaterializeTemporaryExpr *E) {
9548 // Walk through the expression to find the materialized temporary itself.
9551 const Expr *Inner =
9552 E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
9553
9554 // If we passed any comma operators, evaluate their LHSs.
9555 for (const Expr *E : CommaLHSs)
9556 if (!EvaluateIgnoredValue(Info, E))
9557 return false;
9558
9559 // A materialized temporary with static storage duration can appear within the
9560 // result of a constant expression evaluation, so we need to preserve its
9561 // value for use outside this evaluation.
9562 APValue *Value;
9563 if (E->getStorageDuration() == SD_Static) {
9564 if (Info.EvalMode == EvaluationMode::ConstantFold)
9565 return false;
9566 // FIXME: What about SD_Thread?
9567 Value = E->getOrCreateValue(true);
9568 *Value = APValue();
9569 Result.set(E);
9570 } else {
9571 Value = &Info.CurrentCall->createTemporary(
9572 E, Inner->getType(),
9573 E->getStorageDuration() == SD_FullExpression ? ScopeKind::FullExpression
9574 : ScopeKind::Block,
9575 Result);
9576 }
9577
9578 QualType Type = Inner->getType();
9579
9580 // Materialize the temporary itself.
9581 if (!EvaluateInPlace(*Value, Info, Result, Inner)) {
9582 *Value = APValue();
9583 return false;
9584 }
9585
9586 // Adjust our lvalue to refer to the desired subobject.
9587 for (unsigned I = Adjustments.size(); I != 0; /**/) {
9588 --I;
9589 switch (Adjustments[I].Kind) {
9591 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
9592 Type, Result))
9593 return false;
9594 Type = Adjustments[I].DerivedToBase.BasePath->getType();
9595 break;
9596
9598 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
9599 return false;
9600 Type = Adjustments[I].Field->getType();
9601 break;
9602
9604 if (!HandleMemberPointerAccess(this->Info, Type, Result,
9605 Adjustments[I].Ptr.RHS))
9606 return false;
9607 Type = Adjustments[I].Ptr.MPT->getPointeeType();
9608 break;
9609 }
9610 }
9611
9612 return true;
9613}
9614
9615bool
9616LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
9617 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
9618 "lvalue compound literal in c++?");
9619 APValue *Lit;
9620 // If CompountLiteral has static storage, its value can be used outside
9621 // this expression. So evaluate it once and store it in ASTContext.
9622 if (E->hasStaticStorage()) {
9623 Lit = &E->getOrCreateStaticValue(Info.Ctx);
9624 Result.set(E);
9625 // Reset any previously evaluated state, otherwise evaluation below might
9626 // fail.
9627 // FIXME: Should we just re-use the previously evaluated value instead?
9628 *Lit = APValue();
9629 } else {
9630 assert(!Info.getLangOpts().CPlusPlus);
9631 Lit = &Info.CurrentCall->createTemporary(E, E->getInitializer()->getType(),
9632 ScopeKind::Block, Result);
9633 }
9634 // FIXME: Evaluating in place isn't always right. We should figure out how to
9635 // use appropriate evaluation context here, see
9636 // clang/test/AST/static-compound-literals-reeval.cpp for a failure.
9637 if (!EvaluateInPlace(*Lit, Info, Result, E->getInitializer())) {
9638 *Lit = APValue();
9639 return false;
9640 }
9641 return true;
9642}
9643
9644bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
9645 TypeInfoLValue TypeInfo;
9646
9647 if (!E->isPotentiallyEvaluated()) {
9648 if (E->isTypeOperand())
9649 TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
9650 else
9651 TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
9652 } else {
9653 if (!Info.Ctx.getLangOpts().CPlusPlus20) {
9654 Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
9655 << E->getExprOperand()->getType()
9656 << E->getExprOperand()->getSourceRange();
9657 }
9658
9659 if (!Visit(E->getExprOperand()))
9660 return false;
9661
9662 std::optional<DynamicType> DynType =
9664 if (!DynType)
9665 return false;
9666
9667 TypeInfo = TypeInfoLValue(
9668 Info.Ctx.getCanonicalTagType(DynType->Type).getTypePtr());
9669 }
9670
9671 return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
9672}
9673
9674bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
9675 return Success(E->getGuidDecl());
9676}
9677
9678bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
9679 // Handle static data members.
9680 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
9681 VisitIgnoredBaseExpression(E->getBase());
9682 return VisitVarDecl(E, VD);
9683 }
9684
9685 // Handle static member functions.
9686 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
9687 if (MD->isStatic()) {
9688 VisitIgnoredBaseExpression(E->getBase());
9689 return Success(MD);
9690 }
9691 }
9692
9693 // Handle non-static data members.
9694 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
9695}
9696
9697bool LValueExprEvaluator::VisitExtVectorElementExpr(
9698 const ExtVectorElementExpr *E) {
9699 bool Success = true;
9700
9701 APValue Val;
9702 if (!Evaluate(Val, Info, E->getBase())) {
9703 if (!Info.noteFailure())
9704 return false;
9705 Success = false;
9706 }
9707
9709 E->getEncodedElementAccess(Indices);
9710 // FIXME: support accessing more than one element
9711 if (Indices.size() > 1)
9712 return false;
9713
9714 if (Success) {
9715 Result.setFrom(Info.Ctx, Val);
9716 QualType BaseType = E->getBase()->getType();
9717 if (E->isArrow())
9718 BaseType = BaseType->getPointeeType();
9719 const auto *VT = BaseType->castAs<VectorType>();
9720 HandleLValueVectorElement(Info, E, Result, VT->getElementType(),
9721 VT->getNumElements(), Indices[0]);
9722 }
9723
9724 return Success;
9725}
9726
9727bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
9728 if (E->getBase()->getType()->isSveVLSBuiltinType())
9729 return Error(E);
9730
9731 APSInt Index;
9732 bool Success = true;
9733
9734 if (const auto *VT = E->getBase()->getType()->getAs<VectorType>()) {
9735 APValue Val;
9736 if (!Evaluate(Val, Info, E->getBase())) {
9737 if (!Info.noteFailure())
9738 return false;
9739 Success = false;
9740 }
9741
9742 if (!EvaluateInteger(E->getIdx(), Index, Info)) {
9743 if (!Info.noteFailure())
9744 return false;
9745 Success = false;
9746 }
9747
9748 if (Success) {
9749 Result.setFrom(Info.Ctx, Val);
9750 HandleLValueVectorElement(Info, E, Result, VT->getElementType(),
9751 VT->getNumElements(), Index.getExtValue());
9752 }
9753
9754 return Success;
9755 }
9756
9757 // C++17's rules require us to evaluate the LHS first, regardless of which
9758 // side is the base.
9759 for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) {
9760 if (SubExpr == E->getBase() ? !evaluatePointer(SubExpr, Result)
9761 : !EvaluateInteger(SubExpr, Index, Info)) {
9762 if (!Info.noteFailure())
9763 return false;
9764 Success = false;
9765 }
9766 }
9767
9768 return Success &&
9769 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
9770}
9771
9772bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
9773 bool Success = evaluatePointer(E->getSubExpr(), Result);
9774 // [C++26][expr.unary.op]
9775 // If the operand points to an object or function, the result
9776 // denotes that object or function; otherwise, the behavior is undefined.
9777 // Because &(*(type*)0) is a common pattern, we do not fail the evaluation
9778 // immediately.
9780 return Success;
9782 E->getType())) ||
9783 Info.noteUndefinedBehavior();
9784}
9785
9786bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
9787 if (!Visit(E->getSubExpr()))
9788 return false;
9789 // __real is a no-op on scalar lvalues.
9790 if (E->getSubExpr()->getType()->isAnyComplexType())
9791 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
9792 return true;
9793}
9794
9795bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
9796 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
9797 "lvalue __imag__ on scalar?");
9798 if (!Visit(E->getSubExpr()))
9799 return false;
9800 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
9801 return true;
9802}
9803
9804bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
9805 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9806 return Error(UO);
9807
9808 if (!this->Visit(UO->getSubExpr()))
9809 return false;
9810
9811 return handleIncDec(
9812 this->Info, UO, Result, UO->getSubExpr()->getType(),
9813 UO->isIncrementOp(), nullptr);
9814}
9815
9816bool LValueExprEvaluator::VisitCompoundAssignOperator(
9817 const CompoundAssignOperator *CAO) {
9818 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9819 return Error(CAO);
9820
9821 bool Success = true;
9822
9823 // C++17 onwards require that we evaluate the RHS first.
9824 APValue RHS;
9825 if (!Evaluate(RHS, this->Info, CAO->getRHS())) {
9826 if (!Info.noteFailure())
9827 return false;
9828 Success = false;
9829 }
9830
9831 // The overall lvalue result is the result of evaluating the LHS.
9832 if (!this->Visit(CAO->getLHS()) || !Success)
9833 return false;
9834
9836 this->Info, CAO,
9837 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
9838 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
9839}
9840
9841bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
9842 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9843 return Error(E);
9844
9845 bool Success = true;
9846
9847 // C++17 onwards require that we evaluate the RHS first.
9848 APValue NewVal;
9849 if (!Evaluate(NewVal, this->Info, E->getRHS())) {
9850 if (!Info.noteFailure())
9851 return false;
9852 Success = false;
9853 }
9854
9855 if (!this->Visit(E->getLHS()) || !Success)
9856 return false;
9857
9858 if (Info.getLangOpts().CPlusPlus20 &&
9860 return false;
9861
9862 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
9863 NewVal);
9864}
9865
9866//===----------------------------------------------------------------------===//
9867// Pointer Evaluation
9868//===----------------------------------------------------------------------===//
9869
9870/// Convenience function. LVal's base must be a call to an alloc_size
9871/// function.
9873 const LValue &LVal,
9874 llvm::APInt &Result) {
9875 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
9876 "Can't get the size of a non alloc_size function");
9877 const auto *Base = LVal.getLValueBase().get<const Expr *>();
9878 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
9879 std::optional<llvm::APInt> Size =
9880 CE->evaluateBytesReturnedByAllocSizeCall(Ctx);
9881 if (!Size)
9882 return false;
9883
9884 Result = std::move(*Size);
9885 return true;
9886}
9887
9888/// Attempts to evaluate the given LValueBase as the result of a call to
9889/// a function with the alloc_size attribute. If it was possible to do so, this
9890/// function will return true, make Result's Base point to said function call,
9891/// and mark Result's Base as invalid.
9893 LValue &Result) {
9894 if (Base.isNull())
9895 return false;
9896
9897 // Because we do no form of static analysis, we only support const variables.
9898 //
9899 // Additionally, we can't support parameters, nor can we support static
9900 // variables (in the latter case, use-before-assign isn't UB; in the former,
9901 // we have no clue what they'll be assigned to).
9902 const auto *VD =
9903 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
9904 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
9905 return false;
9906
9907 const Expr *Init = VD->getAnyInitializer();
9908 if (!Init || Init->getType().isNull())
9909 return false;
9910
9911 const Expr *E = Init->IgnoreParens();
9912 if (!tryUnwrapAllocSizeCall(E))
9913 return false;
9914
9915 // Store E instead of E unwrapped so that the type of the LValue's base is
9916 // what the user wanted.
9917 Result.setInvalid(E);
9918
9919 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
9920 Result.addUnsizedArray(Info, E, Pointee);
9921 return true;
9922}
9923
9924namespace {
9925class PointerExprEvaluator
9926 : public ExprEvaluatorBase<PointerExprEvaluator> {
9927 LValue &Result;
9928 bool InvalidBaseOK;
9929
9930 bool Success(const Expr *E) {
9931 Result.set(E);
9932 return true;
9933 }
9934
9935 bool evaluateLValue(const Expr *E, LValue &Result) {
9936 return EvaluateLValue(E, Result, Info, InvalidBaseOK);
9937 }
9938
9939 bool evaluatePointer(const Expr *E, LValue &Result) {
9940 return EvaluatePointer(E, Result, Info, InvalidBaseOK);
9941 }
9942
9943 bool visitNonBuiltinCallExpr(const CallExpr *E);
9944public:
9945
9946 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
9947 : ExprEvaluatorBaseTy(info), Result(Result),
9948 InvalidBaseOK(InvalidBaseOK) {}
9949
9950 bool Success(const APValue &V, const Expr *E) {
9951 Result.setFrom(Info.Ctx, V);
9952 return true;
9953 }
9954 bool ZeroInitialization(const Expr *E) {
9955 Result.setNull(Info.Ctx, E->getType());
9956 return true;
9957 }
9958
9959 bool VisitBinaryOperator(const BinaryOperator *E);
9960 bool VisitCastExpr(const CastExpr* E);
9961 bool VisitUnaryAddrOf(const UnaryOperator *E);
9962 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
9963 { return Success(E); }
9964 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
9966 return Success(E);
9967 if (Info.noteFailure())
9968 EvaluateIgnoredValue(Info, E->getSubExpr());
9969 return Error(E);
9970 }
9971 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
9972 { return Success(E); }
9973 bool VisitCallExpr(const CallExpr *E);
9974 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
9975 bool VisitBlockExpr(const BlockExpr *E) {
9976 if (!E->getBlockDecl()->hasCaptures())
9977 return Success(E);
9978 return Error(E);
9979 }
9980 bool VisitCXXThisExpr(const CXXThisExpr *E) {
9981 auto DiagnoseInvalidUseOfThis = [&] {
9982 if (Info.getLangOpts().CPlusPlus11)
9983 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
9984 else
9985 Info.FFDiag(E);
9986 };
9987
9988 // Can't look at 'this' when checking a potential constant expression.
9989 if (Info.checkingPotentialConstantExpression())
9990 return false;
9991
9992 bool IsExplicitLambda =
9993 isLambdaCallWithExplicitObjectParameter(Info.CurrentCall->Callee);
9994 if (!IsExplicitLambda) {
9995 if (!Info.CurrentCall->This) {
9996 DiagnoseInvalidUseOfThis();
9997 return false;
9998 }
9999
10000 Result = *Info.CurrentCall->This;
10001 }
10002
10003 if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
10004 // Ensure we actually have captured 'this'. If something was wrong with
10005 // 'this' capture, the error would have been previously reported.
10006 // Otherwise we can be inside of a default initialization of an object
10007 // declared by lambda's body, so no need to return false.
10008 if (!Info.CurrentCall->LambdaThisCaptureField) {
10009 if (IsExplicitLambda && !Info.CurrentCall->This) {
10010 DiagnoseInvalidUseOfThis();
10011 return false;
10012 }
10013
10014 return true;
10015 }
10016
10017 const auto *MD = cast<CXXMethodDecl>(Info.CurrentCall->Callee);
10018 return HandleLambdaCapture(
10019 Info, E, Result, MD, Info.CurrentCall->LambdaThisCaptureField,
10020 Info.CurrentCall->LambdaThisCaptureField->getType()->isPointerType());
10021 }
10022 return true;
10023 }
10024
10025 bool VisitCXXNewExpr(const CXXNewExpr *E);
10026
10027 bool VisitSourceLocExpr(const SourceLocExpr *E) {
10028 assert(!E->isIntType() && "SourceLocExpr isn't a pointer type?");
10029 APValue LValResult = E->EvaluateInContext(
10030 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
10031 Result.setFrom(Info.Ctx, LValResult);
10032 return true;
10033 }
10034
10035 bool VisitEmbedExpr(const EmbedExpr *E) {
10036 llvm::report_fatal_error("Not yet implemented for ExprConstant.cpp");
10037 return true;
10038 }
10039
10040 bool VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr *E) {
10041 std::string ResultStr = E->ComputeName(Info.Ctx);
10042
10043 QualType CharTy = Info.Ctx.CharTy.withConst();
10044 APInt Size(Info.Ctx.getTypeSize(Info.Ctx.getSizeType()),
10045 ResultStr.size() + 1);
10046 QualType ArrayTy = Info.Ctx.getConstantArrayType(
10047 CharTy, Size, nullptr, ArraySizeModifier::Normal, 0);
10048
10049 StringLiteral *SL =
10050 StringLiteral::Create(Info.Ctx, ResultStr, StringLiteralKind::Ordinary,
10051 /*Pascal*/ false, ArrayTy, E->getLocation());
10052
10053 evaluateLValue(SL, Result);
10054 Result.addArray(Info, E, cast<ConstantArrayType>(ArrayTy));
10055 return true;
10056 }
10057
10058 // FIXME: Missing: @protocol, @selector
10059};
10060} // end anonymous namespace
10061
10062static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
10063 bool InvalidBaseOK) {
10064 assert(!E->isValueDependent());
10065 assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
10066 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
10067}
10068
10069bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
10070 if (E->getOpcode() != BO_Add &&
10071 E->getOpcode() != BO_Sub)
10072 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10073
10074 const Expr *PExp = E->getLHS();
10075 const Expr *IExp = E->getRHS();
10076 if (IExp->getType()->isPointerType())
10077 std::swap(PExp, IExp);
10078
10079 bool EvalPtrOK = evaluatePointer(PExp, Result);
10080 if (!EvalPtrOK && !Info.noteFailure())
10081 return false;
10082
10083 llvm::APSInt Offset;
10084 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
10085 return false;
10086
10087 if (E->getOpcode() == BO_Sub)
10088 negateAsSigned(Offset);
10089
10090 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
10091 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
10092}
10093
10094bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
10095 return evaluateLValue(E->getSubExpr(), Result);
10096}
10097
10098// Is the provided decl 'std::source_location::current'?
10100 if (!FD)
10101 return false;
10102 const IdentifierInfo *FnII = FD->getIdentifier();
10103 if (!FnII || !FnII->isStr("current"))
10104 return false;
10105
10106 const auto *RD = dyn_cast<RecordDecl>(FD->getParent());
10107 if (!RD)
10108 return false;
10109
10110 const IdentifierInfo *ClassII = RD->getIdentifier();
10111 return RD->isInStdNamespace() && ClassII && ClassII->isStr("source_location");
10112}
10113
10114bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
10115 const Expr *SubExpr = E->getSubExpr();
10116
10117 switch (E->getCastKind()) {
10118 default:
10119 break;
10120 case CK_BitCast:
10121 case CK_CPointerToObjCPointerCast:
10122 case CK_BlockPointerToObjCPointerCast:
10123 case CK_AnyPointerToBlockPointerCast:
10124 case CK_AddressSpaceConversion:
10125 if (!Visit(SubExpr))
10126 return false;
10127 if (E->getType()->isFunctionPointerType() ||
10128 SubExpr->getType()->isFunctionPointerType()) {
10129 // Casting between two function pointer types, or between a function
10130 // pointer and an object pointer, is always a reinterpret_cast.
10131 CCEDiag(E, diag::note_constexpr_invalid_cast)
10132 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
10133 << Info.Ctx.getLangOpts().CPlusPlus;
10134 Result.Designator.setInvalid();
10135 } else if (!E->getType()->isVoidPointerType()) {
10136 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
10137 // permitted in constant expressions in C++11. Bitcasts from cv void* are
10138 // also static_casts, but we disallow them as a resolution to DR1312.
10139 //
10140 // In some circumstances, we permit casting from void* to cv1 T*, when the
10141 // actual pointee object is actually a cv2 T.
10142 bool HasValidResult = !Result.InvalidBase && !Result.Designator.Invalid &&
10143 !Result.IsNullPtr;
10144 bool VoidPtrCastMaybeOK =
10145 Result.IsNullPtr ||
10146 (HasValidResult &&
10147 Info.Ctx.hasSimilarType(Result.Designator.getType(Info.Ctx),
10148 E->getType()->getPointeeType()));
10149 // 1. We'll allow it in std::allocator::allocate, and anything which that
10150 // calls.
10151 // 2. HACK 2022-03-28: Work around an issue with libstdc++'s
10152 // <source_location> header. Fixed in GCC 12 and later (2022-04-??).
10153 // We'll allow it in the body of std::source_location::current. GCC's
10154 // implementation had a parameter of type `void*`, and casts from
10155 // that back to `const __impl*` in its body.
10156 if (VoidPtrCastMaybeOK &&
10157 (Info.getStdAllocatorCaller("allocate") ||
10158 IsDeclSourceLocationCurrent(Info.CurrentCall->Callee) ||
10159 Info.getLangOpts().CPlusPlus26)) {
10160 // Permitted.
10161 } else {
10162 if (SubExpr->getType()->isVoidPointerType() &&
10163 Info.getLangOpts().CPlusPlus) {
10164 if (HasValidResult)
10165 CCEDiag(E, diag::note_constexpr_invalid_void_star_cast)
10166 << SubExpr->getType() << Info.getLangOpts().CPlusPlus26
10167 << Result.Designator.getType(Info.Ctx).getCanonicalType()
10168 << E->getType()->getPointeeType();
10169 else
10170 CCEDiag(E, diag::note_constexpr_invalid_cast)
10171 << diag::ConstexprInvalidCastKind::CastFrom
10172 << SubExpr->getType();
10173 } else
10174 CCEDiag(E, diag::note_constexpr_invalid_cast)
10175 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
10176 << Info.Ctx.getLangOpts().CPlusPlus;
10177 Result.Designator.setInvalid();
10178 }
10179 }
10180 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
10181 ZeroInitialization(E);
10182 return true;
10183
10184 case CK_DerivedToBase:
10185 case CK_UncheckedDerivedToBase:
10186 if (!evaluatePointer(E->getSubExpr(), Result))
10187 return false;
10188 if (!Result.Base && Result.Offset.isZero())
10189 return true;
10190
10191 // Now figure out the necessary offset to add to the base LV to get from
10192 // the derived class to the base class.
10193 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
10194 castAs<PointerType>()->getPointeeType(),
10195 Result);
10196
10197 case CK_BaseToDerived:
10198 if (!Visit(E->getSubExpr()))
10199 return false;
10200 if (!Result.Base && Result.Offset.isZero())
10201 return true;
10202 return HandleBaseToDerivedCast(Info, E, Result);
10203
10204 case CK_Dynamic:
10205 if (!Visit(E->getSubExpr()))
10206 return false;
10208
10209 case CK_NullToPointer:
10210 VisitIgnoredValue(E->getSubExpr());
10211 return ZeroInitialization(E);
10212
10213 case CK_IntegralToPointer: {
10214 CCEDiag(E, diag::note_constexpr_invalid_cast)
10215 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
10216 << Info.Ctx.getLangOpts().CPlusPlus;
10217
10218 APValue Value;
10219 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
10220 break;
10221
10222 if (Value.isInt()) {
10223 unsigned Size = Info.Ctx.getTypeSize(E->getType());
10224 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
10225 if (N == Info.Ctx.getTargetNullPointerValue(E->getType())) {
10226 Result.setNull(Info.Ctx, E->getType());
10227 } else {
10228 Result.Base = (Expr *)nullptr;
10229 Result.InvalidBase = false;
10230 Result.Offset = CharUnits::fromQuantity(N);
10231 Result.Designator.setInvalid();
10232 Result.IsNullPtr = false;
10233 }
10234 return true;
10235 } else {
10236 // In rare instances, the value isn't an lvalue.
10237 // For example, when the value is the difference between the addresses of
10238 // two labels. We reject that as a constant expression because we can't
10239 // compute a valid offset to convert into a pointer.
10240 if (!Value.isLValue())
10241 return false;
10242
10243 // Cast is of an lvalue, no need to change value.
10244 Result.setFrom(Info.Ctx, Value);
10245 return true;
10246 }
10247 }
10248
10249 case CK_ArrayToPointerDecay: {
10250 if (SubExpr->isGLValue()) {
10251 if (!evaluateLValue(SubExpr, Result))
10252 return false;
10253 } else {
10254 APValue &Value = Info.CurrentCall->createTemporary(
10255 SubExpr, SubExpr->getType(), ScopeKind::FullExpression, Result);
10256 if (!EvaluateInPlace(Value, Info, Result, SubExpr))
10257 return false;
10258 }
10259 // The result is a pointer to the first element of the array.
10260 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
10261 if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
10262 Result.addArray(Info, E, CAT);
10263 else
10264 Result.addUnsizedArray(Info, E, AT->getElementType());
10265 return true;
10266 }
10267
10268 case CK_FunctionToPointerDecay:
10269 return evaluateLValue(SubExpr, Result);
10270
10271 case CK_LValueToRValue: {
10272 LValue LVal;
10273 if (!evaluateLValue(E->getSubExpr(), LVal))
10274 return false;
10275
10276 APValue RVal;
10277 // Note, we use the subexpression's type in order to retain cv-qualifiers.
10279 LVal, RVal))
10280 return InvalidBaseOK &&
10281 evaluateLValueAsAllocSize(Info, LVal.Base, Result);
10282 return Success(RVal, E);
10283 }
10284 }
10285
10286 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10287}
10288
10290 UnaryExprOrTypeTrait ExprKind) {
10291 // C++ [expr.alignof]p3:
10292 // When alignof is applied to a reference type, the result is the
10293 // alignment of the referenced type.
10294 T = T.getNonReferenceType();
10295
10296 if (T.getQualifiers().hasUnaligned())
10297 return CharUnits::One();
10298
10299 const bool AlignOfReturnsPreferred =
10300 Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
10301
10302 // __alignof is defined to return the preferred alignment.
10303 // Before 8, clang returned the preferred alignment for alignof and _Alignof
10304 // as well.
10305 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
10306 return Ctx.toCharUnitsFromBits(Ctx.getPreferredTypeAlign(T.getTypePtr()));
10307 // alignof and _Alignof are defined to return the ABI alignment.
10308 else if (ExprKind == UETT_AlignOf)
10309 return Ctx.getTypeAlignInChars(T.getTypePtr());
10310 else
10311 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
10312}
10313
10315 UnaryExprOrTypeTrait ExprKind) {
10316 E = E->IgnoreParens();
10317
10318 // The kinds of expressions that we have special-case logic here for
10319 // should be kept up to date with the special checks for those
10320 // expressions in Sema.
10321
10322 // alignof decl is always accepted, even if it doesn't make sense: we default
10323 // to 1 in those cases.
10324 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
10325 return Ctx.getDeclAlign(DRE->getDecl(),
10326 /*RefAsPointee*/ true);
10327
10328 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
10329 return Ctx.getDeclAlign(ME->getMemberDecl(),
10330 /*RefAsPointee*/ true);
10331
10332 return GetAlignOfType(Ctx, E->getType(), ExprKind);
10333}
10334
10335static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) {
10336 if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>())
10337 return Info.Ctx.getDeclAlign(VD);
10338 if (const auto *E = Value.Base.dyn_cast<const Expr *>())
10339 return GetAlignOfExpr(Info.Ctx, E, UETT_AlignOf);
10340 return GetAlignOfType(Info.Ctx, Value.Base.getTypeInfoType(), UETT_AlignOf);
10341}
10342
10343/// Evaluate the value of the alignment argument to __builtin_align_{up,down},
10344/// __builtin_is_aligned and __builtin_assume_aligned.
10345static bool getAlignmentArgument(const Expr *E, QualType ForType,
10346 EvalInfo &Info, APSInt &Alignment) {
10347 if (!EvaluateInteger(E, Alignment, Info))
10348 return false;
10349 if (Alignment < 0 || !Alignment.isPowerOf2()) {
10350 Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment;
10351 return false;
10352 }
10353 unsigned SrcWidth = Info.Ctx.getIntWidth(ForType);
10354 APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1));
10355 if (APSInt::compareValues(Alignment, MaxValue) > 0) {
10356 Info.FFDiag(E, diag::note_constexpr_alignment_too_big)
10357 << MaxValue << ForType << Alignment;
10358 return false;
10359 }
10360 // Ensure both alignment and source value have the same bit width so that we
10361 // don't assert when computing the resulting value.
10362 APSInt ExtAlignment =
10363 APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true);
10364 assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 &&
10365 "Alignment should not be changed by ext/trunc");
10366 Alignment = ExtAlignment;
10367 assert(Alignment.getBitWidth() == SrcWidth);
10368 return true;
10369}
10370
10371// To be clear: this happily visits unsupported builtins. Better name welcomed.
10372bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
10373 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
10374 return true;
10375
10376 if (!(InvalidBaseOK && E->getCalleeAllocSizeAttr()))
10377 return false;
10378
10379 Result.setInvalid(E);
10380 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
10381 Result.addUnsizedArray(Info, E, PointeeTy);
10382 return true;
10383}
10384
10385bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
10386 if (!IsConstantEvaluatedBuiltinCall(E))
10387 return visitNonBuiltinCallExpr(E);
10388 return VisitBuiltinCallExpr(E, E->getBuiltinCallee());
10389}
10390
10391// Determine if T is a character type for which we guarantee that
10392// sizeof(T) == 1.
10394 return T->isCharType() || T->isChar8Type();
10395}
10396
10397bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
10398 unsigned BuiltinOp) {
10399 if (IsOpaqueConstantCall(E))
10400 return Success(E);
10401
10402 switch (BuiltinOp) {
10403 case Builtin::BIaddressof:
10404 case Builtin::BI__addressof:
10405 case Builtin::BI__builtin_addressof:
10406 return evaluateLValue(E->getArg(0), Result);
10407 case Builtin::BI__builtin_assume_aligned: {
10408 // We need to be very careful here because: if the pointer does not have the
10409 // asserted alignment, then the behavior is undefined, and undefined
10410 // behavior is non-constant.
10411 if (!evaluatePointer(E->getArg(0), Result))
10412 return false;
10413
10414 LValue OffsetResult(Result);
10415 APSInt Alignment;
10416 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
10417 Alignment))
10418 return false;
10419 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
10420
10421 if (E->getNumArgs() > 2) {
10422 APSInt Offset;
10423 if (!EvaluateInteger(E->getArg(2), Offset, Info))
10424 return false;
10425
10426 int64_t AdditionalOffset = -Offset.getZExtValue();
10427 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
10428 }
10429
10430 // If there is a base object, then it must have the correct alignment.
10431 if (OffsetResult.Base) {
10432 CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult);
10433
10434 if (BaseAlignment < Align) {
10435 Result.Designator.setInvalid();
10436 CCEDiag(E->getArg(0), diag::note_constexpr_baa_insufficient_alignment)
10437 << 0 << BaseAlignment.getQuantity() << Align.getQuantity();
10438 return false;
10439 }
10440 }
10441
10442 // The offset must also have the correct alignment.
10443 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
10444 Result.Designator.setInvalid();
10445
10446 (OffsetResult.Base
10447 ? CCEDiag(E->getArg(0),
10448 diag::note_constexpr_baa_insufficient_alignment)
10449 << 1
10450 : CCEDiag(E->getArg(0),
10451 diag::note_constexpr_baa_value_insufficient_alignment))
10452 << OffsetResult.Offset.getQuantity() << Align.getQuantity();
10453 return false;
10454 }
10455
10456 return true;
10457 }
10458 case Builtin::BI__builtin_align_up:
10459 case Builtin::BI__builtin_align_down: {
10460 if (!evaluatePointer(E->getArg(0), Result))
10461 return false;
10462 APSInt Alignment;
10463 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
10464 Alignment))
10465 return false;
10466 CharUnits BaseAlignment = getBaseAlignment(Info, Result);
10467 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset);
10468 // For align_up/align_down, we can return the same value if the alignment
10469 // is known to be greater or equal to the requested value.
10470 if (PtrAlign.getQuantity() >= Alignment)
10471 return true;
10472
10473 // The alignment could be greater than the minimum at run-time, so we cannot
10474 // infer much about the resulting pointer value. One case is possible:
10475 // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we
10476 // can infer the correct index if the requested alignment is smaller than
10477 // the base alignment so we can perform the computation on the offset.
10478 if (BaseAlignment.getQuantity() >= Alignment) {
10479 assert(Alignment.getBitWidth() <= 64 &&
10480 "Cannot handle > 64-bit address-space");
10481 uint64_t Alignment64 = Alignment.getZExtValue();
10482 CharUnits NewOffset = CharUnits::fromQuantity(
10483 BuiltinOp == Builtin::BI__builtin_align_down
10484 ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64)
10485 : llvm::alignTo(Result.Offset.getQuantity(), Alignment64));
10486 Result.adjustOffset(NewOffset - Result.Offset);
10487 // TODO: diagnose out-of-bounds values/only allow for arrays?
10488 return true;
10489 }
10490 // Otherwise, we cannot constant-evaluate the result.
10491 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust)
10492 << Alignment;
10493 return false;
10494 }
10495 case Builtin::BI__builtin_operator_new:
10496 return HandleOperatorNewCall(Info, E, Result);
10497 case Builtin::BI__builtin_launder:
10498 return evaluatePointer(E->getArg(0), Result);
10499 case Builtin::BIstrchr:
10500 case Builtin::BIwcschr:
10501 case Builtin::BImemchr:
10502 case Builtin::BIwmemchr:
10503 if (Info.getLangOpts().CPlusPlus11)
10504 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
10505 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
10506 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
10507 else
10508 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
10509 [[fallthrough]];
10510 case Builtin::BI__builtin_strchr:
10511 case Builtin::BI__builtin_wcschr:
10512 case Builtin::BI__builtin_memchr:
10513 case Builtin::BI__builtin_char_memchr:
10514 case Builtin::BI__builtin_wmemchr: {
10515 if (!Visit(E->getArg(0)))
10516 return false;
10517 APSInt Desired;
10518 if (!EvaluateInteger(E->getArg(1), Desired, Info))
10519 return false;
10520 uint64_t MaxLength = uint64_t(-1);
10521 if (BuiltinOp != Builtin::BIstrchr &&
10522 BuiltinOp != Builtin::BIwcschr &&
10523 BuiltinOp != Builtin::BI__builtin_strchr &&
10524 BuiltinOp != Builtin::BI__builtin_wcschr) {
10525 APSInt N;
10526 if (!EvaluateInteger(E->getArg(2), N, Info))
10527 return false;
10528 MaxLength = N.getZExtValue();
10529 }
10530 // We cannot find the value if there are no candidates to match against.
10531 if (MaxLength == 0u)
10532 return ZeroInitialization(E);
10533 if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
10534 Result.Designator.Invalid)
10535 return false;
10536 QualType CharTy = Result.Designator.getType(Info.Ctx);
10537 bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
10538 BuiltinOp == Builtin::BI__builtin_memchr;
10539 assert(IsRawByte ||
10540 Info.Ctx.hasSameUnqualifiedType(
10541 CharTy, E->getArg(0)->getType()->getPointeeType()));
10542 // Pointers to const void may point to objects of incomplete type.
10543 if (IsRawByte && CharTy->isIncompleteType()) {
10544 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
10545 return false;
10546 }
10547 // Give up on byte-oriented matching against multibyte elements.
10548 // FIXME: We can compare the bytes in the correct order.
10549 if (IsRawByte && !isOneByteCharacterType(CharTy)) {
10550 Info.FFDiag(E, diag::note_constexpr_memchr_unsupported)
10551 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp) << CharTy;
10552 return false;
10553 }
10554 // Figure out what value we're actually looking for (after converting to
10555 // the corresponding unsigned type if necessary).
10556 uint64_t DesiredVal;
10557 bool StopAtNull = false;
10558 switch (BuiltinOp) {
10559 case Builtin::BIstrchr:
10560 case Builtin::BI__builtin_strchr:
10561 // strchr compares directly to the passed integer, and therefore
10562 // always fails if given an int that is not a char.
10563 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
10564 E->getArg(1)->getType(),
10565 Desired),
10566 Desired))
10567 return ZeroInitialization(E);
10568 StopAtNull = true;
10569 [[fallthrough]];
10570 case Builtin::BImemchr:
10571 case Builtin::BI__builtin_memchr:
10572 case Builtin::BI__builtin_char_memchr:
10573 // memchr compares by converting both sides to unsigned char. That's also
10574 // correct for strchr if we get this far (to cope with plain char being
10575 // unsigned in the strchr case).
10576 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
10577 break;
10578
10579 case Builtin::BIwcschr:
10580 case Builtin::BI__builtin_wcschr:
10581 StopAtNull = true;
10582 [[fallthrough]];
10583 case Builtin::BIwmemchr:
10584 case Builtin::BI__builtin_wmemchr:
10585 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
10586 DesiredVal = Desired.getZExtValue();
10587 break;
10588 }
10589
10590 for (; MaxLength; --MaxLength) {
10591 APValue Char;
10592 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
10593 !Char.isInt())
10594 return false;
10595 if (Char.getInt().getZExtValue() == DesiredVal)
10596 return true;
10597 if (StopAtNull && !Char.getInt())
10598 break;
10599 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
10600 return false;
10601 }
10602 // Not found: return nullptr.
10603 return ZeroInitialization(E);
10604 }
10605
10606 case Builtin::BImemcpy:
10607 case Builtin::BImemmove:
10608 case Builtin::BIwmemcpy:
10609 case Builtin::BIwmemmove:
10610 if (Info.getLangOpts().CPlusPlus11)
10611 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
10612 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
10613 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
10614 else
10615 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
10616 [[fallthrough]];
10617 case Builtin::BI__builtin_memcpy:
10618 case Builtin::BI__builtin_memmove:
10619 case Builtin::BI__builtin_wmemcpy:
10620 case Builtin::BI__builtin_wmemmove: {
10621 bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
10622 BuiltinOp == Builtin::BIwmemmove ||
10623 BuiltinOp == Builtin::BI__builtin_wmemcpy ||
10624 BuiltinOp == Builtin::BI__builtin_wmemmove;
10625 bool Move = BuiltinOp == Builtin::BImemmove ||
10626 BuiltinOp == Builtin::BIwmemmove ||
10627 BuiltinOp == Builtin::BI__builtin_memmove ||
10628 BuiltinOp == Builtin::BI__builtin_wmemmove;
10629
10630 // The result of mem* is the first argument.
10631 if (!Visit(E->getArg(0)))
10632 return false;
10633 LValue Dest = Result;
10634
10635 LValue Src;
10636 if (!EvaluatePointer(E->getArg(1), Src, Info))
10637 return false;
10638
10639 APSInt N;
10640 if (!EvaluateInteger(E->getArg(2), N, Info))
10641 return false;
10642 assert(!N.isSigned() && "memcpy and friends take an unsigned size");
10643
10644 // If the size is zero, we treat this as always being a valid no-op.
10645 // (Even if one of the src and dest pointers is null.)
10646 if (!N)
10647 return true;
10648
10649 // Otherwise, if either of the operands is null, we can't proceed. Don't
10650 // try to determine the type of the copied objects, because there aren't
10651 // any.
10652 if (!Src.Base || !Dest.Base) {
10653 APValue Val;
10654 (!Src.Base ? Src : Dest).moveInto(Val);
10655 Info.FFDiag(E, diag::note_constexpr_memcpy_null)
10656 << Move << WChar << !!Src.Base
10657 << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
10658 return false;
10659 }
10660 if (Src.Designator.Invalid || Dest.Designator.Invalid)
10661 return false;
10662
10663 // We require that Src and Dest are both pointers to arrays of
10664 // trivially-copyable type. (For the wide version, the designator will be
10665 // invalid if the designated object is not a wchar_t.)
10666 QualType T = Dest.Designator.getType(Info.Ctx);
10667 QualType SrcT = Src.Designator.getType(Info.Ctx);
10668 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
10669 // FIXME: Consider using our bit_cast implementation to support this.
10670 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
10671 return false;
10672 }
10673 if (T->isIncompleteType()) {
10674 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
10675 return false;
10676 }
10677 if (!T.isTriviallyCopyableType(Info.Ctx)) {
10678 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
10679 return false;
10680 }
10681
10682 // Figure out how many T's we're copying.
10683 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
10684 if (TSize == 0)
10685 return false;
10686 if (!WChar) {
10687 uint64_t Remainder;
10688 llvm::APInt OrigN = N;
10689 llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
10690 if (Remainder) {
10691 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
10692 << Move << WChar << 0 << T << toString(OrigN, 10, /*Signed*/false)
10693 << (unsigned)TSize;
10694 return false;
10695 }
10696 }
10697
10698 // Check that the copying will remain within the arrays, just so that we
10699 // can give a more meaningful diagnostic. This implicitly also checks that
10700 // N fits into 64 bits.
10701 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
10702 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
10703 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
10704 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
10705 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
10706 << toString(N, 10, /*Signed*/false);
10707 return false;
10708 }
10709 uint64_t NElems = N.getZExtValue();
10710 uint64_t NBytes = NElems * TSize;
10711
10712 // Check for overlap.
10713 int Direction = 1;
10714 if (HasSameBase(Src, Dest)) {
10715 uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
10716 uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
10717 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
10718 // Dest is inside the source region.
10719 if (!Move) {
10720 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
10721 return false;
10722 }
10723 // For memmove and friends, copy backwards.
10724 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
10725 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
10726 return false;
10727 Direction = -1;
10728 } else if (!Move && SrcOffset >= DestOffset &&
10729 SrcOffset - DestOffset < NBytes) {
10730 // Src is inside the destination region for memcpy: invalid.
10731 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
10732 return false;
10733 }
10734 }
10735
10736 while (true) {
10737 APValue Val;
10738 // FIXME: Set WantObjectRepresentation to true if we're copying a
10739 // char-like type?
10740 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
10741 !handleAssignment(Info, E, Dest, T, Val))
10742 return false;
10743 // Do not iterate past the last element; if we're copying backwards, that
10744 // might take us off the start of the array.
10745 if (--NElems == 0)
10746 return true;
10747 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
10748 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
10749 return false;
10750 }
10751 }
10752
10753 default:
10754 return false;
10755 }
10756}
10757
10758static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
10759 APValue &Result, const InitListExpr *ILE,
10760 QualType AllocType);
10761static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
10762 APValue &Result,
10763 const CXXConstructExpr *CCE,
10764 QualType AllocType);
10765
10766bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) {
10767 if (!Info.getLangOpts().CPlusPlus20)
10768 Info.CCEDiag(E, diag::note_constexpr_new);
10769
10770 // We cannot speculatively evaluate a delete expression.
10771 if (Info.SpeculativeEvaluationDepth)
10772 return false;
10773
10774 FunctionDecl *OperatorNew = E->getOperatorNew();
10775 QualType AllocType = E->getAllocatedType();
10776 QualType TargetType = AllocType;
10777
10778 bool IsNothrow = false;
10779 bool IsPlacement = false;
10780
10781 if (E->getNumPlacementArgs() == 1 &&
10782 E->getPlacementArg(0)->getType()->isNothrowT()) {
10783 // The only new-placement list we support is of the form (std::nothrow).
10784 //
10785 // FIXME: There is no restriction on this, but it's not clear that any
10786 // other form makes any sense. We get here for cases such as:
10787 //
10788 // new (std::align_val_t{N}) X(int)
10789 //
10790 // (which should presumably be valid only if N is a multiple of
10791 // alignof(int), and in any case can't be deallocated unless N is
10792 // alignof(X) and X has new-extended alignment).
10793 LValue Nothrow;
10794 if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info))
10795 return false;
10796 IsNothrow = true;
10797 } else if (OperatorNew->isReservedGlobalPlacementOperator()) {
10798 if (Info.CurrentCall->isStdFunction() || Info.getLangOpts().CPlusPlus26 ||
10799 (Info.CurrentCall->CanEvalMSConstexpr &&
10800 OperatorNew->hasAttr<MSConstexprAttr>())) {
10801 if (!EvaluatePointer(E->getPlacementArg(0), Result, Info))
10802 return false;
10803 if (Result.Designator.Invalid)
10804 return false;
10805 TargetType = E->getPlacementArg(0)->getType();
10806 IsPlacement = true;
10807 } else {
10808 Info.FFDiag(E, diag::note_constexpr_new_placement)
10809 << /*C++26 feature*/ 1 << E->getSourceRange();
10810 return false;
10811 }
10812 } else if (E->getNumPlacementArgs()) {
10813 Info.FFDiag(E, diag::note_constexpr_new_placement)
10814 << /*Unsupported*/ 0 << E->getSourceRange();
10815 return false;
10816 } else if (!OperatorNew
10817 ->isUsableAsGlobalAllocationFunctionInConstantEvaluation()) {
10818 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
10819 << isa<CXXMethodDecl>(OperatorNew) << OperatorNew;
10820 return false;
10821 }
10822
10823 const Expr *Init = E->getInitializer();
10824 const InitListExpr *ResizedArrayILE = nullptr;
10825 const CXXConstructExpr *ResizedArrayCCE = nullptr;
10826 bool ValueInit = false;
10827
10828 if (std::optional<const Expr *> ArraySize = E->getArraySize()) {
10829 const Expr *Stripped = *ArraySize;
10830 for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
10831 Stripped = ICE->getSubExpr())
10832 if (ICE->getCastKind() != CK_NoOp &&
10833 ICE->getCastKind() != CK_IntegralCast)
10834 break;
10835
10836 llvm::APSInt ArrayBound;
10837 if (!EvaluateInteger(Stripped, ArrayBound, Info))
10838 return false;
10839
10840 // C++ [expr.new]p9:
10841 // The expression is erroneous if:
10842 // -- [...] its value before converting to size_t [or] applying the
10843 // second standard conversion sequence is less than zero
10844 if (ArrayBound.isSigned() && ArrayBound.isNegative()) {
10845 if (IsNothrow)
10846 return ZeroInitialization(E);
10847
10848 Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative)
10849 << ArrayBound << (*ArraySize)->getSourceRange();
10850 return false;
10851 }
10852
10853 // -- its value is such that the size of the allocated object would
10854 // exceed the implementation-defined limit
10855 if (!Info.CheckArraySize(ArraySize.value()->getExprLoc(),
10857 Info.Ctx, AllocType, ArrayBound),
10858 ArrayBound.getZExtValue(), /*Diag=*/!IsNothrow)) {
10859 if (IsNothrow)
10860 return ZeroInitialization(E);
10861 return false;
10862 }
10863
10864 // -- the new-initializer is a braced-init-list and the number of
10865 // array elements for which initializers are provided [...]
10866 // exceeds the number of elements to initialize
10867 if (!Init) {
10868 // No initialization is performed.
10869 } else if (isa<CXXScalarValueInitExpr>(Init) ||
10871 ValueInit = true;
10872 } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) {
10873 ResizedArrayCCE = CCE;
10874 } else {
10875 auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType());
10876 assert(CAT && "unexpected type for array initializer");
10877
10878 unsigned Bits =
10879 std::max(CAT->getSizeBitWidth(), ArrayBound.getBitWidth());
10880 llvm::APInt InitBound = CAT->getSize().zext(Bits);
10881 llvm::APInt AllocBound = ArrayBound.zext(Bits);
10882 if (InitBound.ugt(AllocBound)) {
10883 if (IsNothrow)
10884 return ZeroInitialization(E);
10885
10886 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small)
10887 << toString(AllocBound, 10, /*Signed=*/false)
10888 << toString(InitBound, 10, /*Signed=*/false)
10889 << (*ArraySize)->getSourceRange();
10890 return false;
10891 }
10892
10893 // If the sizes differ, we must have an initializer list, and we need
10894 // special handling for this case when we initialize.
10895 if (InitBound != AllocBound)
10896 ResizedArrayILE = cast<InitListExpr>(Init);
10897 }
10898
10899 AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr,
10900 ArraySizeModifier::Normal, 0);
10901 } else {
10902 assert(!AllocType->isArrayType() &&
10903 "array allocation with non-array new");
10904 }
10905
10906 APValue *Val;
10907 if (IsPlacement) {
10909 struct FindObjectHandler {
10910 EvalInfo &Info;
10911 const Expr *E;
10912 QualType AllocType;
10913 const AccessKinds AccessKind;
10914 APValue *Value;
10915
10916 typedef bool result_type;
10917 bool failed() { return false; }
10918 bool checkConst(QualType QT) {
10919 if (QT.isConstQualified()) {
10920 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
10921 return false;
10922 }
10923 return true;
10924 }
10925 bool found(APValue &Subobj, QualType SubobjType) {
10926 if (!checkConst(SubobjType))
10927 return false;
10928 // FIXME: Reject the cases where [basic.life]p8 would not permit the
10929 // old name of the object to be used to name the new object.
10930 unsigned SubobjectSize = 1;
10931 unsigned AllocSize = 1;
10932 if (auto *CAT = dyn_cast<ConstantArrayType>(AllocType))
10933 AllocSize = CAT->getZExtSize();
10934 if (auto *CAT = dyn_cast<ConstantArrayType>(SubobjType))
10935 SubobjectSize = CAT->getZExtSize();
10936 if (SubobjectSize < AllocSize ||
10937 !Info.Ctx.hasSimilarType(Info.Ctx.getBaseElementType(SubobjType),
10938 Info.Ctx.getBaseElementType(AllocType))) {
10939 Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type)
10940 << SubobjType << AllocType;
10941 return false;
10942 }
10943 Value = &Subobj;
10944 return true;
10945 }
10946 bool found(APSInt &Value, QualType SubobjType) {
10947 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
10948 return false;
10949 }
10950 bool found(APFloat &Value, QualType SubobjType) {
10951 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
10952 return false;
10953 }
10954 } Handler = {Info, E, AllocType, AK, nullptr};
10955
10956 CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType);
10957 if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler))
10958 return false;
10959
10960 Val = Handler.Value;
10961
10962 // [basic.life]p1:
10963 // The lifetime of an object o of type T ends when [...] the storage
10964 // which the object occupies is [...] reused by an object that is not
10965 // nested within o (6.6.2).
10966 *Val = APValue();
10967 } else {
10968 // Perform the allocation and obtain a pointer to the resulting object.
10969 Val = Info.createHeapAlloc(E, AllocType, Result);
10970 if (!Val)
10971 return false;
10972 }
10973
10974 if (ValueInit) {
10975 ImplicitValueInitExpr VIE(AllocType);
10976 if (!EvaluateInPlace(*Val, Info, Result, &VIE))
10977 return false;
10978 } else if (ResizedArrayILE) {
10979 if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE,
10980 AllocType))
10981 return false;
10982 } else if (ResizedArrayCCE) {
10983 if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE,
10984 AllocType))
10985 return false;
10986 } else if (Init) {
10987 if (!EvaluateInPlace(*Val, Info, Result, Init))
10988 return false;
10989 } else if (!handleDefaultInitValue(AllocType, *Val)) {
10990 return false;
10991 }
10992
10993 // Array new returns a pointer to the first element, not a pointer to the
10994 // array.
10995 if (auto *AT = AllocType->getAsArrayTypeUnsafe())
10996 Result.addArray(Info, E, cast<ConstantArrayType>(AT));
10997
10998 return true;
10999}
11000//===----------------------------------------------------------------------===//
11001// Member Pointer Evaluation
11002//===----------------------------------------------------------------------===//
11003
11004namespace {
11005class MemberPointerExprEvaluator
11006 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
11007 MemberPtr &Result;
11008
11009 bool Success(const ValueDecl *D) {
11010 Result = MemberPtr(D);
11011 return true;
11012 }
11013public:
11014
11015 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
11016 : ExprEvaluatorBaseTy(Info), Result(Result) {}
11017
11018 bool Success(const APValue &V, const Expr *E) {
11019 Result.setFrom(V);
11020 return true;
11021 }
11022 bool ZeroInitialization(const Expr *E) {
11023 return Success((const ValueDecl*)nullptr);
11024 }
11025
11026 bool VisitCastExpr(const CastExpr *E);
11027 bool VisitUnaryAddrOf(const UnaryOperator *E);
11028};
11029} // end anonymous namespace
11030
11031static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
11032 EvalInfo &Info) {
11033 assert(!E->isValueDependent());
11034 assert(E->isPRValue() && E->getType()->isMemberPointerType());
11035 return MemberPointerExprEvaluator(Info, Result).Visit(E);
11036}
11037
11038bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
11039 switch (E->getCastKind()) {
11040 default:
11041 return ExprEvaluatorBaseTy::VisitCastExpr(E);
11042
11043 case CK_NullToMemberPointer:
11044 VisitIgnoredValue(E->getSubExpr());
11045 return ZeroInitialization(E);
11046
11047 case CK_BaseToDerivedMemberPointer: {
11048 if (!Visit(E->getSubExpr()))
11049 return false;
11050 if (E->path_empty())
11051 return true;
11052 // Base-to-derived member pointer casts store the path in derived-to-base
11053 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
11054 // the wrong end of the derived->base arc, so stagger the path by one class.
11055 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
11056 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
11057 PathI != PathE; ++PathI) {
11058 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
11059 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
11060 if (!Result.castToDerived(Derived))
11061 return Error(E);
11062 }
11063 if (!Result.castToDerived(E->getType()
11064 ->castAs<MemberPointerType>()
11065 ->getMostRecentCXXRecordDecl()))
11066 return Error(E);
11067 return true;
11068 }
11069
11070 case CK_DerivedToBaseMemberPointer:
11071 if (!Visit(E->getSubExpr()))
11072 return false;
11073 for (CastExpr::path_const_iterator PathI = E->path_begin(),
11074 PathE = E->path_end(); PathI != PathE; ++PathI) {
11075 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
11076 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
11077 if (!Result.castToBase(Base))
11078 return Error(E);
11079 }
11080 return true;
11081 }
11082}
11083
11084bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
11085 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
11086 // member can be formed.
11087 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
11088}
11089
11090//===----------------------------------------------------------------------===//
11091// Record Evaluation
11092//===----------------------------------------------------------------------===//
11093
11094namespace {
11095 class RecordExprEvaluator
11096 : public ExprEvaluatorBase<RecordExprEvaluator> {
11097 const LValue &This;
11098 APValue &Result;
11099 public:
11100
11101 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
11102 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
11103
11104 bool Success(const APValue &V, const Expr *E) {
11105 Result = V;
11106 return true;
11107 }
11108 bool ZeroInitialization(const Expr *E) {
11109 return ZeroInitialization(E, E->getType());
11110 }
11111 bool ZeroInitialization(const Expr *E, QualType T);
11112
11113 bool VisitCallExpr(const CallExpr *E) {
11114 return handleCallExpr(E, Result, &This);
11115 }
11116 bool VisitCastExpr(const CastExpr *E);
11117 bool VisitInitListExpr(const InitListExpr *E);
11118 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
11119 return VisitCXXConstructExpr(E, E->getType());
11120 }
11121 bool VisitLambdaExpr(const LambdaExpr *E);
11122 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
11123 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
11124 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
11125 bool VisitBinCmp(const BinaryOperator *E);
11126 bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E);
11127 bool VisitCXXParenListOrInitListExpr(const Expr *ExprToVisit,
11128 ArrayRef<Expr *> Args);
11129 };
11130}
11131
11132/// Perform zero-initialization on an object of non-union class type.
11133/// C++11 [dcl.init]p5:
11134/// To zero-initialize an object or reference of type T means:
11135/// [...]
11136/// -- if T is a (possibly cv-qualified) non-union class type,
11137/// each non-static data member and each base-class subobject is
11138/// zero-initialized
11139static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
11140 const RecordDecl *RD,
11141 const LValue &This, APValue &Result) {
11142 assert(!RD->isUnion() && "Expected non-union class type");
11143 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
11144 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
11145 RD->getNumFields());
11146
11147 if (RD->isInvalidDecl()) return false;
11148 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
11149
11150 if (CD) {
11151 unsigned Index = 0;
11153 End = CD->bases_end(); I != End; ++I, ++Index) {
11154 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
11155 LValue Subobject = This;
11156 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
11157 return false;
11158 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
11159 Result.getStructBase(Index)))
11160 return false;
11161 }
11162 }
11163
11164 for (const auto *I : RD->fields()) {
11165 // -- if T is a reference type, no initialization is performed.
11166 if (I->isUnnamedBitField() || I->getType()->isReferenceType())
11167 continue;
11168
11169 LValue Subobject = This;
11170 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
11171 return false;
11172
11173 ImplicitValueInitExpr VIE(I->getType());
11174 if (!EvaluateInPlace(
11175 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
11176 return false;
11177 }
11178
11179 return true;
11180}
11181
11182bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
11183 const auto *RD = T->castAsRecordDecl();
11184 if (RD->isInvalidDecl()) return false;
11185 if (RD->isUnion()) {
11186 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
11187 // object's first non-static named data member is zero-initialized
11189 while (I != RD->field_end() && (*I)->isUnnamedBitField())
11190 ++I;
11191 if (I == RD->field_end()) {
11192 Result = APValue((const FieldDecl*)nullptr);
11193 return true;
11194 }
11195
11196 LValue Subobject = This;
11197 if (!HandleLValueMember(Info, E, Subobject, *I))
11198 return false;
11199 Result = APValue(*I);
11200 ImplicitValueInitExpr VIE(I->getType());
11201 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
11202 }
11203
11204 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
11205 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
11206 return false;
11207 }
11208
11209 return HandleClassZeroInitialization(Info, E, RD, This, Result);
11210}
11211
11212bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
11213 switch (E->getCastKind()) {
11214 default:
11215 return ExprEvaluatorBaseTy::VisitCastExpr(E);
11216
11217 case CK_ConstructorConversion:
11218 return Visit(E->getSubExpr());
11219
11220 case CK_DerivedToBase:
11221 case CK_UncheckedDerivedToBase: {
11222 APValue DerivedObject;
11223 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
11224 return false;
11225 if (!DerivedObject.isStruct())
11226 return Error(E->getSubExpr());
11227
11228 // Derived-to-base rvalue conversion: just slice off the derived part.
11229 APValue *Value = &DerivedObject;
11230 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
11231 for (CastExpr::path_const_iterator PathI = E->path_begin(),
11232 PathE = E->path_end(); PathI != PathE; ++PathI) {
11233 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
11234 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
11235 Value = &Value->getStructBase(getBaseIndex(RD, Base));
11236 RD = Base;
11237 }
11238 Result = *Value;
11239 return true;
11240 }
11241 case CK_HLSLAggregateSplatCast: {
11242 APValue Val;
11243 QualType ValTy;
11244
11245 if (!hlslAggSplatHelper(Info, E->getSubExpr(), Val, ValTy))
11246 return false;
11247
11248 unsigned NEls = elementwiseSize(Info, E->getType());
11249 // splat our Val
11250 SmallVector<APValue> SplatEls(NEls, Val);
11251 SmallVector<QualType> SplatType(NEls, ValTy);
11252
11253 // cast the elements and construct our struct result
11254 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
11255 if (!constructAggregate(Info, FPO, E, Result, E->getType(), SplatEls,
11256 SplatType))
11257 return false;
11258
11259 return true;
11260 }
11261 case CK_HLSLElementwiseCast: {
11262 SmallVector<APValue> SrcEls;
11263 SmallVector<QualType> SrcTypes;
11264
11265 if (!hlslElementwiseCastHelper(Info, E->getSubExpr(), E->getType(), SrcEls,
11266 SrcTypes))
11267 return false;
11268
11269 // cast the elements and construct our struct result
11270 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
11271 if (!constructAggregate(Info, FPO, E, Result, E->getType(), SrcEls,
11272 SrcTypes))
11273 return false;
11274
11275 return true;
11276 }
11277 }
11278}
11279
11280bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
11281 if (E->isTransparent())
11282 return Visit(E->getInit(0));
11283 return VisitCXXParenListOrInitListExpr(E, E->inits());
11284}
11285
11286bool RecordExprEvaluator::VisitCXXParenListOrInitListExpr(
11287 const Expr *ExprToVisit, ArrayRef<Expr *> Args) {
11288 const auto *RD = ExprToVisit->getType()->castAsRecordDecl();
11289 if (RD->isInvalidDecl()) return false;
11290 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
11291 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
11292
11293 EvalInfo::EvaluatingConstructorRAII EvalObj(
11294 Info,
11295 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
11296 CXXRD && CXXRD->getNumBases());
11297
11298 if (RD->isUnion()) {
11299 const FieldDecl *Field;
11300 if (auto *ILE = dyn_cast<InitListExpr>(ExprToVisit)) {
11301 Field = ILE->getInitializedFieldInUnion();
11302 } else if (auto *PLIE = dyn_cast<CXXParenListInitExpr>(ExprToVisit)) {
11303 Field = PLIE->getInitializedFieldInUnion();
11304 } else {
11305 llvm_unreachable(
11306 "Expression is neither an init list nor a C++ paren list");
11307 }
11308
11309 Result = APValue(Field);
11310 if (!Field)
11311 return true;
11312
11313 // If the initializer list for a union does not contain any elements, the
11314 // first element of the union is value-initialized.
11315 // FIXME: The element should be initialized from an initializer list.
11316 // Is this difference ever observable for initializer lists which
11317 // we don't build?
11318 ImplicitValueInitExpr VIE(Field->getType());
11319 const Expr *InitExpr = Args.empty() ? &VIE : Args[0];
11320
11321 LValue Subobject = This;
11322 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
11323 return false;
11324
11325 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
11326 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
11327 isa<CXXDefaultInitExpr>(InitExpr));
11328
11329 if (EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr)) {
11330 if (Field->isBitField())
11331 return truncateBitfieldValue(Info, InitExpr, Result.getUnionValue(),
11332 Field);
11333 return true;
11334 }
11335
11336 return false;
11337 }
11338
11339 if (!Result.hasValue())
11340 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
11341 RD->getNumFields());
11342 unsigned ElementNo = 0;
11343 bool Success = true;
11344
11345 // Initialize base classes.
11346 if (CXXRD && CXXRD->getNumBases()) {
11347 for (const auto &Base : CXXRD->bases()) {
11348 assert(ElementNo < Args.size() && "missing init for base class");
11349 const Expr *Init = Args[ElementNo];
11350
11351 LValue Subobject = This;
11352 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
11353 return false;
11354
11355 APValue &FieldVal = Result.getStructBase(ElementNo);
11356 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
11357 if (!Info.noteFailure())
11358 return false;
11359 Success = false;
11360 }
11361 ++ElementNo;
11362 }
11363
11364 EvalObj.finishedConstructingBases();
11365 }
11366
11367 // Initialize members.
11368 for (const auto *Field : RD->fields()) {
11369 // Anonymous bit-fields are not considered members of the class for
11370 // purposes of aggregate initialization.
11371 if (Field->isUnnamedBitField())
11372 continue;
11373
11374 LValue Subobject = This;
11375
11376 bool HaveInit = ElementNo < Args.size();
11377
11378 // FIXME: Diagnostics here should point to the end of the initializer
11379 // list, not the start.
11380 if (!HandleLValueMember(Info, HaveInit ? Args[ElementNo] : ExprToVisit,
11381 Subobject, Field, &Layout))
11382 return false;
11383
11384 // Perform an implicit value-initialization for members beyond the end of
11385 // the initializer list.
11386 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
11387 const Expr *Init = HaveInit ? Args[ElementNo++] : &VIE;
11388
11389 if (Field->getType()->isIncompleteArrayType()) {
11390 if (auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType())) {
11391 if (!CAT->isZeroSize()) {
11392 // Bail out for now. This might sort of "work", but the rest of the
11393 // code isn't really prepared to handle it.
11394 Info.FFDiag(Init, diag::note_constexpr_unsupported_flexible_array);
11395 return false;
11396 }
11397 }
11398 }
11399
11400 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
11401 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
11403
11404 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
11405 if (Field->getType()->isReferenceType()) {
11406 LValue Result;
11408 FieldVal)) {
11409 if (!Info.noteFailure())
11410 return false;
11411 Success = false;
11412 }
11413 } else if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
11414 (Field->isBitField() &&
11415 !truncateBitfieldValue(Info, Init, FieldVal, Field))) {
11416 if (!Info.noteFailure())
11417 return false;
11418 Success = false;
11419 }
11420 }
11421
11422 EvalObj.finishedConstructingFields();
11423
11424 return Success;
11425}
11426
11427bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
11428 QualType T) {
11429 // Note that E's type is not necessarily the type of our class here; we might
11430 // be initializing an array element instead.
11431 const CXXConstructorDecl *FD = E->getConstructor();
11432 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
11433
11434 bool ZeroInit = E->requiresZeroInitialization();
11435 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
11436 if (ZeroInit)
11437 return ZeroInitialization(E, T);
11438
11440 }
11441
11442 const FunctionDecl *Definition = nullptr;
11443 auto Body = FD->getBody(Definition);
11444
11445 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
11446 return false;
11447
11448 // Avoid materializing a temporary for an elidable copy/move constructor.
11449 if (E->isElidable() && !ZeroInit) {
11450 // FIXME: This only handles the simplest case, where the source object
11451 // is passed directly as the first argument to the constructor.
11452 // This should also handle stepping though implicit casts and
11453 // and conversion sequences which involve two steps, with a
11454 // conversion operator followed by a converting constructor.
11455 const Expr *SrcObj = E->getArg(0);
11456 assert(SrcObj->isTemporaryObject(Info.Ctx, FD->getParent()));
11457 assert(Info.Ctx.hasSameUnqualifiedType(E->getType(), SrcObj->getType()));
11458 if (const MaterializeTemporaryExpr *ME =
11459 dyn_cast<MaterializeTemporaryExpr>(SrcObj))
11460 return Visit(ME->getSubExpr());
11461 }
11462
11463 if (ZeroInit && !ZeroInitialization(E, T))
11464 return false;
11465
11466 auto Args = ArrayRef(E->getArgs(), E->getNumArgs());
11467 return HandleConstructorCall(E, This, Args,
11469 Result);
11470}
11471
11472bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
11473 const CXXInheritedCtorInitExpr *E) {
11474 if (!Info.CurrentCall) {
11475 assert(Info.checkingPotentialConstantExpression());
11476 return false;
11477 }
11478
11479 const CXXConstructorDecl *FD = E->getConstructor();
11480 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
11481 return false;
11482
11483 const FunctionDecl *Definition = nullptr;
11484 auto Body = FD->getBody(Definition);
11485
11486 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
11487 return false;
11488
11489 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
11491 Result);
11492}
11493
11494bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
11495 const CXXStdInitializerListExpr *E) {
11496 const ConstantArrayType *ArrayType =
11497 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
11498
11499 LValue Array;
11500 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
11501 return false;
11502
11503 assert(ArrayType && "unexpected type for array initializer");
11504
11505 // Get a pointer to the first element of the array.
11506 Array.addArray(Info, E, ArrayType);
11507
11508 // FIXME: What if the initializer_list type has base classes, etc?
11509 Result = APValue(APValue::UninitStruct(), 0, 2);
11510 Array.moveInto(Result.getStructField(0));
11511
11512 auto *Record = E->getType()->castAsRecordDecl();
11513 RecordDecl::field_iterator Field = Record->field_begin();
11514 assert(Field != Record->field_end() &&
11515 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
11516 ArrayType->getElementType()) &&
11517 "Expected std::initializer_list first field to be const E *");
11518 ++Field;
11519 assert(Field != Record->field_end() &&
11520 "Expected std::initializer_list to have two fields");
11521
11522 if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType())) {
11523 // Length.
11524 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
11525 } else {
11526 // End pointer.
11527 assert(Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
11528 ArrayType->getElementType()) &&
11529 "Expected std::initializer_list second field to be const E *");
11530 if (!HandleLValueArrayAdjustment(Info, E, Array,
11531 ArrayType->getElementType(),
11532 ArrayType->getZExtSize()))
11533 return false;
11534 Array.moveInto(Result.getStructField(1));
11535 }
11536
11537 assert(++Field == Record->field_end() &&
11538 "Expected std::initializer_list to only have two fields");
11539
11540 return true;
11541}
11542
11543bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
11544 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
11545 if (ClosureClass->isInvalidDecl())
11546 return false;
11547
11548 const size_t NumFields = ClosureClass->getNumFields();
11549
11550 assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
11551 E->capture_init_end()) &&
11552 "The number of lambda capture initializers should equal the number of "
11553 "fields within the closure type");
11554
11555 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
11556 // Iterate through all the lambda's closure object's fields and initialize
11557 // them.
11558 auto *CaptureInitIt = E->capture_init_begin();
11559 bool Success = true;
11560 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(ClosureClass);
11561 for (const auto *Field : ClosureClass->fields()) {
11562 assert(CaptureInitIt != E->capture_init_end());
11563 // Get the initializer for this field
11564 Expr *const CurFieldInit = *CaptureInitIt++;
11565
11566 // If there is no initializer, either this is a VLA or an error has
11567 // occurred.
11568 if (!CurFieldInit || CurFieldInit->containsErrors())
11569 return Error(E);
11570
11571 LValue Subobject = This;
11572
11573 if (!HandleLValueMember(Info, E, Subobject, Field, &Layout))
11574 return false;
11575
11576 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
11577 if (!EvaluateInPlace(FieldVal, Info, Subobject, CurFieldInit)) {
11578 if (!Info.keepEvaluatingAfterFailure())
11579 return false;
11580 Success = false;
11581 }
11582 }
11583 return Success;
11584}
11585
11586static bool EvaluateRecord(const Expr *E, const LValue &This,
11587 APValue &Result, EvalInfo &Info) {
11588 assert(!E->isValueDependent());
11589 assert(E->isPRValue() && E->getType()->isRecordType() &&
11590 "can't evaluate expression as a record rvalue");
11591 return RecordExprEvaluator(Info, This, Result).Visit(E);
11592}
11593
11594//===----------------------------------------------------------------------===//
11595// Temporary Evaluation
11596//
11597// Temporaries are represented in the AST as rvalues, but generally behave like
11598// lvalues. The full-object of which the temporary is a subobject is implicitly
11599// materialized so that a reference can bind to it.
11600//===----------------------------------------------------------------------===//
11601namespace {
11602class TemporaryExprEvaluator
11603 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
11604public:
11605 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
11606 LValueExprEvaluatorBaseTy(Info, Result, false) {}
11607
11608 /// Visit an expression which constructs the value of this temporary.
11609 bool VisitConstructExpr(const Expr *E) {
11610 APValue &Value = Info.CurrentCall->createTemporary(
11611 E, E->getType(), ScopeKind::FullExpression, Result);
11612 return EvaluateInPlace(Value, Info, Result, E);
11613 }
11614
11615 bool VisitCastExpr(const CastExpr *E) {
11616 switch (E->getCastKind()) {
11617 default:
11618 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
11619
11620 case CK_ConstructorConversion:
11621 return VisitConstructExpr(E->getSubExpr());
11622 }
11623 }
11624 bool VisitInitListExpr(const InitListExpr *E) {
11625 return VisitConstructExpr(E);
11626 }
11627 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
11628 return VisitConstructExpr(E);
11629 }
11630 bool VisitCallExpr(const CallExpr *E) {
11631 return VisitConstructExpr(E);
11632 }
11633 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
11634 return VisitConstructExpr(E);
11635 }
11636 bool VisitLambdaExpr(const LambdaExpr *E) {
11637 return VisitConstructExpr(E);
11638 }
11639};
11640} // end anonymous namespace
11641
11642/// Evaluate an expression of record type as a temporary.
11643static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
11644 assert(!E->isValueDependent());
11645 assert(E->isPRValue() && E->getType()->isRecordType());
11646 return TemporaryExprEvaluator(Info, Result).Visit(E);
11647}
11648
11649//===----------------------------------------------------------------------===//
11650// Vector Evaluation
11651//===----------------------------------------------------------------------===//
11652
11653namespace {
11654 class VectorExprEvaluator
11655 : public ExprEvaluatorBase<VectorExprEvaluator> {
11656 APValue &Result;
11657 public:
11658
11659 VectorExprEvaluator(EvalInfo &info, APValue &Result)
11660 : ExprEvaluatorBaseTy(info), Result(Result) {}
11661
11662 bool Success(ArrayRef<APValue> V, const Expr *E) {
11663 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
11664 // FIXME: remove this APValue copy.
11665 Result = APValue(V.data(), V.size());
11666 return true;
11667 }
11668 bool Success(const APValue &V, const Expr *E) {
11669 assert(V.isVector());
11670 Result = V;
11671 return true;
11672 }
11673 bool ZeroInitialization(const Expr *E);
11674
11675 bool VisitUnaryReal(const UnaryOperator *E)
11676 { return Visit(E->getSubExpr()); }
11677 bool VisitCastExpr(const CastExpr* E);
11678 bool VisitInitListExpr(const InitListExpr *E);
11679 bool VisitUnaryImag(const UnaryOperator *E);
11680 bool VisitBinaryOperator(const BinaryOperator *E);
11681 bool VisitUnaryOperator(const UnaryOperator *E);
11682 bool VisitCallExpr(const CallExpr *E);
11683 bool VisitConvertVectorExpr(const ConvertVectorExpr *E);
11684 bool VisitShuffleVectorExpr(const ShuffleVectorExpr *E);
11685
11686 // FIXME: Missing: conditional operator (for GNU
11687 // conditional select), ExtVectorElementExpr
11688 };
11689} // end anonymous namespace
11690
11691static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
11692 assert(E->isPRValue() && E->getType()->isVectorType() &&
11693 "not a vector prvalue");
11694 return VectorExprEvaluator(Info, Result).Visit(E);
11695}
11696
11697static llvm::APInt ConvertBoolVectorToInt(const APValue &Val) {
11698 assert(Val.isVector() && "expected vector APValue");
11699 unsigned NumElts = Val.getVectorLength();
11700
11701 // Each element is one bit, so create an integer with NumElts bits.
11702 llvm::APInt Result(NumElts, 0);
11703
11704 for (unsigned I = 0; I < NumElts; ++I) {
11705 const APValue &Elt = Val.getVectorElt(I);
11706 assert(Elt.isInt() && "expected integer element in bool vector");
11707
11708 if (Elt.getInt().getBoolValue())
11709 Result.setBit(I);
11710 }
11711
11712 return Result;
11713}
11714
11715bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
11716 const VectorType *VTy = E->getType()->castAs<VectorType>();
11717 unsigned NElts = VTy->getNumElements();
11718
11719 const Expr *SE = E->getSubExpr();
11720 QualType SETy = SE->getType();
11721
11722 switch (E->getCastKind()) {
11723 case CK_VectorSplat: {
11724 APValue Val = APValue();
11725 if (SETy->isIntegerType()) {
11726 APSInt IntResult;
11727 if (!EvaluateInteger(SE, IntResult, Info))
11728 return false;
11729 Val = APValue(std::move(IntResult));
11730 } else if (SETy->isRealFloatingType()) {
11731 APFloat FloatResult(0.0);
11732 if (!EvaluateFloat(SE, FloatResult, Info))
11733 return false;
11734 Val = APValue(std::move(FloatResult));
11735 } else {
11736 return Error(E);
11737 }
11738
11739 // Splat and create vector APValue.
11740 SmallVector<APValue, 4> Elts(NElts, Val);
11741 return Success(Elts, E);
11742 }
11743 case CK_BitCast: {
11744 APValue SVal;
11745 if (!Evaluate(SVal, Info, SE))
11746 return false;
11747
11748 if (!SVal.isInt() && !SVal.isFloat() && !SVal.isVector()) {
11749 // Give up if the input isn't an int, float, or vector. For example, we
11750 // reject "(v4i16)(intptr_t)&a".
11751 Info.FFDiag(E, diag::note_constexpr_invalid_cast)
11752 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
11753 << Info.Ctx.getLangOpts().CPlusPlus;
11754 return false;
11755 }
11756
11757 if (!handleRValueToRValueBitCast(Info, Result, SVal, E))
11758 return false;
11759
11760 return true;
11761 }
11762 case CK_HLSLVectorTruncation: {
11763 APValue Val;
11764 SmallVector<APValue, 4> Elements;
11765 if (!EvaluateVector(SE, Val, Info))
11766 return Error(E);
11767 for (unsigned I = 0; I < NElts; I++)
11768 Elements.push_back(Val.getVectorElt(I));
11769 return Success(Elements, E);
11770 }
11771 case CK_HLSLMatrixTruncation: {
11772 // TODO: See #168935. Add matrix truncation support to expr constant.
11773 return Error(E);
11774 }
11775 case CK_HLSLAggregateSplatCast: {
11776 APValue Val;
11777 QualType ValTy;
11778
11779 if (!hlslAggSplatHelper(Info, SE, Val, ValTy))
11780 return false;
11781
11782 // cast our Val once.
11784 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
11785 if (!handleScalarCast(Info, FPO, E, ValTy, VTy->getElementType(), Val,
11786 Result))
11787 return false;
11788
11789 SmallVector<APValue, 4> SplatEls(NElts, Result);
11790 return Success(SplatEls, E);
11791 }
11792 case CK_HLSLElementwiseCast: {
11793 SmallVector<APValue> SrcVals;
11794 SmallVector<QualType> SrcTypes;
11795
11796 if (!hlslElementwiseCastHelper(Info, SE, E->getType(), SrcVals, SrcTypes))
11797 return false;
11798
11799 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
11800 SmallVector<QualType, 4> DestTypes(NElts, VTy->getElementType());
11801 SmallVector<APValue, 4> ResultEls(NElts);
11802 if (!handleElementwiseCast(Info, E, FPO, SrcVals, SrcTypes, DestTypes,
11803 ResultEls))
11804 return false;
11805 return Success(ResultEls, E);
11806 }
11807 default:
11808 return ExprEvaluatorBaseTy::VisitCastExpr(E);
11809 }
11810}
11811
11812bool
11813VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
11814 const VectorType *VT = E->getType()->castAs<VectorType>();
11815 unsigned NumInits = E->getNumInits();
11816 unsigned NumElements = VT->getNumElements();
11817
11818 QualType EltTy = VT->getElementType();
11819 SmallVector<APValue, 4> Elements;
11820
11821 // MFloat8 type doesn't have constants and thus constant folding
11822 // is impossible.
11823 if (EltTy->isMFloat8Type())
11824 return false;
11825
11826 // The number of initializers can be less than the number of
11827 // vector elements. For OpenCL, this can be due to nested vector
11828 // initialization. For GCC compatibility, missing trailing elements
11829 // should be initialized with zeroes.
11830 unsigned CountInits = 0, CountElts = 0;
11831 while (CountElts < NumElements) {
11832 // Handle nested vector initialization.
11833 if (CountInits < NumInits
11834 && E->getInit(CountInits)->getType()->isVectorType()) {
11835 APValue v;
11836 if (!EvaluateVector(E->getInit(CountInits), v, Info))
11837 return Error(E);
11838 unsigned vlen = v.getVectorLength();
11839 for (unsigned j = 0; j < vlen; j++)
11840 Elements.push_back(v.getVectorElt(j));
11841 CountElts += vlen;
11842 } else if (EltTy->isIntegerType()) {
11843 llvm::APSInt sInt(32);
11844 if (CountInits < NumInits) {
11845 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
11846 return false;
11847 } else // trailing integer zero.
11848 sInt = Info.Ctx.MakeIntValue(0, EltTy);
11849 Elements.push_back(APValue(sInt));
11850 CountElts++;
11851 } else {
11852 llvm::APFloat f(0.0);
11853 if (CountInits < NumInits) {
11854 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
11855 return false;
11856 } else // trailing float zero.
11857 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
11858 Elements.push_back(APValue(f));
11859 CountElts++;
11860 }
11861 CountInits++;
11862 }
11863 return Success(Elements, E);
11864}
11865
11866bool
11867VectorExprEvaluator::ZeroInitialization(const Expr *E) {
11868 const auto *VT = E->getType()->castAs<VectorType>();
11869 QualType EltTy = VT->getElementType();
11870 APValue ZeroElement;
11871 if (EltTy->isIntegerType())
11872 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
11873 else
11874 ZeroElement =
11875 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
11876
11877 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
11878 return Success(Elements, E);
11879}
11880
11881bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
11882 VisitIgnoredValue(E->getSubExpr());
11883 return ZeroInitialization(E);
11884}
11885
11886bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
11887 BinaryOperatorKind Op = E->getOpcode();
11888 assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp &&
11889 "Operation not supported on vector types");
11890
11891 if (Op == BO_Comma)
11892 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
11893
11894 Expr *LHS = E->getLHS();
11895 Expr *RHS = E->getRHS();
11896
11897 assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() &&
11898 "Must both be vector types");
11899 // Checking JUST the types are the same would be fine, except shifts don't
11900 // need to have their types be the same (since you always shift by an int).
11901 assert(LHS->getType()->castAs<VectorType>()->getNumElements() ==
11902 E->getType()->castAs<VectorType>()->getNumElements() &&
11903 RHS->getType()->castAs<VectorType>()->getNumElements() ==
11904 E->getType()->castAs<VectorType>()->getNumElements() &&
11905 "All operands must be the same size.");
11906
11907 APValue LHSValue;
11908 APValue RHSValue;
11909 bool LHSOK = Evaluate(LHSValue, Info, LHS);
11910 if (!LHSOK && !Info.noteFailure())
11911 return false;
11912 if (!Evaluate(RHSValue, Info, RHS) || !LHSOK)
11913 return false;
11914
11915 if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue))
11916 return false;
11917
11918 return Success(LHSValue, E);
11919}
11920
11921static std::optional<APValue> handleVectorUnaryOperator(ASTContext &Ctx,
11922 QualType ResultTy,
11924 APValue Elt) {
11925 switch (Op) {
11926 case UO_Plus:
11927 // Nothing to do here.
11928 return Elt;
11929 case UO_Minus:
11930 if (Elt.getKind() == APValue::Int) {
11931 Elt.getInt().negate();
11932 } else {
11933 assert(Elt.getKind() == APValue::Float &&
11934 "Vector can only be int or float type");
11935 Elt.getFloat().changeSign();
11936 }
11937 return Elt;
11938 case UO_Not:
11939 // This is only valid for integral types anyway, so we don't have to handle
11940 // float here.
11941 assert(Elt.getKind() == APValue::Int &&
11942 "Vector operator ~ can only be int");
11943 Elt.getInt().flipAllBits();
11944 return Elt;
11945 case UO_LNot: {
11946 if (Elt.getKind() == APValue::Int) {
11947 Elt.getInt() = !Elt.getInt();
11948 // operator ! on vectors returns -1 for 'truth', so negate it.
11949 Elt.getInt().negate();
11950 return Elt;
11951 }
11952 assert(Elt.getKind() == APValue::Float &&
11953 "Vector can only be int or float type");
11954 // Float types result in an int of the same size, but -1 for true, or 0 for
11955 // false.
11956 APSInt EltResult{Ctx.getIntWidth(ResultTy),
11957 ResultTy->isUnsignedIntegerType()};
11958 if (Elt.getFloat().isZero())
11959 EltResult.setAllBits();
11960 else
11961 EltResult.clearAllBits();
11962
11963 return APValue{EltResult};
11964 }
11965 default:
11966 // FIXME: Implement the rest of the unary operators.
11967 return std::nullopt;
11968 }
11969}
11970
11971bool VectorExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
11972 Expr *SubExpr = E->getSubExpr();
11973 const auto *VD = SubExpr->getType()->castAs<VectorType>();
11974 // This result element type differs in the case of negating a floating point
11975 // vector, since the result type is the a vector of the equivilant sized
11976 // integer.
11977 const QualType ResultEltTy = VD->getElementType();
11978 UnaryOperatorKind Op = E->getOpcode();
11979
11980 APValue SubExprValue;
11981 if (!Evaluate(SubExprValue, Info, SubExpr))
11982 return false;
11983
11984 // FIXME: This vector evaluator someday needs to be changed to be LValue
11985 // aware/keep LValue information around, rather than dealing with just vector
11986 // types directly. Until then, we cannot handle cases where the operand to
11987 // these unary operators is an LValue. The only case I've been able to see
11988 // cause this is operator++ assigning to a member expression (only valid in
11989 // altivec compilations) in C mode, so this shouldn't limit us too much.
11990 if (SubExprValue.isLValue())
11991 return false;
11992
11993 assert(SubExprValue.getVectorLength() == VD->getNumElements() &&
11994 "Vector length doesn't match type?");
11995
11996 SmallVector<APValue, 4> ResultElements;
11997 for (unsigned EltNum = 0; EltNum < VD->getNumElements(); ++EltNum) {
11998 std::optional<APValue> Elt = handleVectorUnaryOperator(
11999 Info.Ctx, ResultEltTy, Op, SubExprValue.getVectorElt(EltNum));
12000 if (!Elt)
12001 return false;
12002 ResultElements.push_back(*Elt);
12003 }
12004 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12005}
12006
12007static bool handleVectorElementCast(EvalInfo &Info, const FPOptions FPO,
12008 const Expr *E, QualType SourceTy,
12009 QualType DestTy, APValue const &Original,
12010 APValue &Result) {
12011 if (SourceTy->isIntegerType()) {
12012 if (DestTy->isRealFloatingType()) {
12013 Result = APValue(APFloat(0.0));
12014 return HandleIntToFloatCast(Info, E, FPO, SourceTy, Original.getInt(),
12015 DestTy, Result.getFloat());
12016 }
12017 if (DestTy->isIntegerType()) {
12018 Result = APValue(
12019 HandleIntToIntCast(Info, E, DestTy, SourceTy, Original.getInt()));
12020 return true;
12021 }
12022 } else if (SourceTy->isRealFloatingType()) {
12023 if (DestTy->isRealFloatingType()) {
12024 Result = Original;
12025 return HandleFloatToFloatCast(Info, E, SourceTy, DestTy,
12026 Result.getFloat());
12027 }
12028 if (DestTy->isIntegerType()) {
12029 Result = APValue(APSInt());
12030 return HandleFloatToIntCast(Info, E, SourceTy, Original.getFloat(),
12031 DestTy, Result.getInt());
12032 }
12033 }
12034
12035 Info.FFDiag(E, diag::err_convertvector_constexpr_unsupported_vector_cast)
12036 << SourceTy << DestTy;
12037 return false;
12038}
12039
12040static bool evalPackBuiltin(const CallExpr *E, EvalInfo &Info, APValue &Result,
12041 llvm::function_ref<APInt(const APSInt &)> PackFn) {
12042 APValue LHS, RHS;
12043 if (!EvaluateAsRValue(Info, E->getArg(0), LHS) ||
12044 !EvaluateAsRValue(Info, E->getArg(1), RHS))
12045 return false;
12046
12047 unsigned LHSVecLen = LHS.getVectorLength();
12048 unsigned RHSVecLen = RHS.getVectorLength();
12049
12050 assert(LHSVecLen != 0 && LHSVecLen == RHSVecLen &&
12051 "pack builtin LHSVecLen must equal to RHSVecLen");
12052
12053 const VectorType *VT0 = E->getArg(0)->getType()->castAs<VectorType>();
12054 const unsigned SrcBits = Info.Ctx.getIntWidth(VT0->getElementType());
12055
12056 const VectorType *DstVT = E->getType()->castAs<VectorType>();
12057 QualType DstElemTy = DstVT->getElementType();
12058 const bool DstIsUnsigned = DstElemTy->isUnsignedIntegerType();
12059
12060 const unsigned SrcPerLane = 128 / SrcBits;
12061 const unsigned Lanes = LHSVecLen * SrcBits / 128;
12062
12064 Out.reserve(LHSVecLen + RHSVecLen);
12065
12066 for (unsigned Lane = 0; Lane != Lanes; ++Lane) {
12067 unsigned base = Lane * SrcPerLane;
12068 for (unsigned I = 0; I != SrcPerLane; ++I)
12069 Out.emplace_back(APValue(
12070 APSInt(PackFn(LHS.getVectorElt(base + I).getInt()), DstIsUnsigned)));
12071 for (unsigned I = 0; I != SrcPerLane; ++I)
12072 Out.emplace_back(APValue(
12073 APSInt(PackFn(RHS.getVectorElt(base + I).getInt()), DstIsUnsigned)));
12074 }
12075
12076 Result = APValue(Out.data(), Out.size());
12077 return true;
12078}
12079
12081 EvalInfo &Info, const CallExpr *Call, APValue &Out,
12082 llvm::function_ref<std::pair<unsigned, int>(unsigned, unsigned)>
12083 GetSourceIndex) {
12084
12085 const auto *VT = Call->getType()->getAs<VectorType>();
12086 if (!VT)
12087 return false;
12088
12089 unsigned ShuffleMask = 0;
12090 APValue A, MaskVector, B;
12091 bool IsVectorMask = false;
12092 bool IsSingleOperand = (Call->getNumArgs() == 2);
12093
12094 if (IsSingleOperand) {
12095 QualType MaskType = Call->getArg(1)->getType();
12096 if (MaskType->isVectorType()) {
12097 IsVectorMask = true;
12098 if (!EvaluateAsRValue(Info, Call->getArg(0), A) ||
12099 !EvaluateAsRValue(Info, Call->getArg(1), MaskVector))
12100 return false;
12101 B = A;
12102 } else if (MaskType->isIntegerType()) {
12103 APSInt MaskImm;
12104 if (!EvaluateInteger(Call->getArg(1), MaskImm, Info))
12105 return false;
12106 ShuffleMask = static_cast<unsigned>(MaskImm.getZExtValue());
12107 if (!EvaluateAsRValue(Info, Call->getArg(0), A))
12108 return false;
12109 B = A;
12110 } else {
12111 return false;
12112 }
12113 } else {
12114 QualType Arg2Type = Call->getArg(2)->getType();
12115 if (Arg2Type->isVectorType()) {
12116 IsVectorMask = true;
12117 if (!EvaluateAsRValue(Info, Call->getArg(0), A) ||
12118 !EvaluateAsRValue(Info, Call->getArg(1), MaskVector) ||
12119 !EvaluateAsRValue(Info, Call->getArg(2), B))
12120 return false;
12121 } else if (Arg2Type->isIntegerType()) {
12122 APSInt MaskImm;
12123 if (!EvaluateInteger(Call->getArg(2), MaskImm, Info))
12124 return false;
12125 ShuffleMask = static_cast<unsigned>(MaskImm.getZExtValue());
12126 if (!EvaluateAsRValue(Info, Call->getArg(0), A) ||
12127 !EvaluateAsRValue(Info, Call->getArg(1), B))
12128 return false;
12129 } else {
12130 return false;
12131 }
12132 }
12133
12134 unsigned NumElts = VT->getNumElements();
12135 SmallVector<APValue, 64> ResultElements;
12136 ResultElements.reserve(NumElts);
12137
12138 for (unsigned DstIdx = 0; DstIdx != NumElts; ++DstIdx) {
12139 if (IsVectorMask) {
12140 ShuffleMask = static_cast<unsigned>(
12141 MaskVector.getVectorElt(DstIdx).getInt().getZExtValue());
12142 }
12143 auto [SrcVecIdx, SrcIdx] = GetSourceIndex(DstIdx, ShuffleMask);
12144
12145 if (SrcIdx < 0) {
12146 // Zero out this element
12147 QualType ElemTy = VT->getElementType();
12148 if (ElemTy->isRealFloatingType()) {
12149 ResultElements.push_back(
12150 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy))));
12151 } else if (ElemTy->isIntegerType()) {
12152 APValue Zero(Info.Ctx.MakeIntValue(0, ElemTy));
12153 ResultElements.push_back(APValue(Zero));
12154 } else {
12155 // Other types of fallback logic
12156 ResultElements.push_back(APValue());
12157 }
12158 } else {
12159 const APValue &Src = (SrcVecIdx == 0) ? A : B;
12160 ResultElements.push_back(Src.getVectorElt(SrcIdx));
12161 }
12162 }
12163
12164 Out = APValue(ResultElements.data(), ResultElements.size());
12165 return true;
12166}
12167static bool ConvertDoubleToFloatStrict(EvalInfo &Info, const Expr *E,
12168 APFloat OrigVal, APValue &Result) {
12169
12170 if (OrigVal.isInfinity()) {
12171 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << 0;
12172 return false;
12173 }
12174 if (OrigVal.isNaN()) {
12175 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << 1;
12176 return false;
12177 }
12178
12179 APFloat Val = OrigVal;
12180 bool LosesInfo = false;
12181 APFloat::opStatus Status = Val.convert(
12182 APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, &LosesInfo);
12183
12184 if (LosesInfo || Val.isDenormal()) {
12185 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic_strict);
12186 return false;
12187 }
12188
12189 if (Status != APFloat::opOK) {
12190 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
12191 return false;
12192 }
12193
12194 Result = APValue(Val);
12195 return true;
12196}
12198 EvalInfo &Info, const CallExpr *Call, APValue &Out,
12199 llvm::function_ref<APInt(const APInt &, uint64_t)> ShiftOp,
12200 llvm::function_ref<APInt(const APInt &, unsigned)> OverflowOp) {
12201
12202 APValue Source, Count;
12203 if (!EvaluateAsRValue(Info, Call->getArg(0), Source) ||
12204 !EvaluateAsRValue(Info, Call->getArg(1), Count))
12205 return false;
12206
12207 assert(Call->getNumArgs() == 2);
12208
12209 QualType SourceTy = Call->getArg(0)->getType();
12210 assert(SourceTy->isVectorType() &&
12211 Call->getArg(1)->getType()->isVectorType());
12212
12213 QualType DestEltTy = SourceTy->castAs<VectorType>()->getElementType();
12214 unsigned DestEltWidth = Source.getVectorElt(0).getInt().getBitWidth();
12215 unsigned DestLen = Source.getVectorLength();
12216 bool IsDestUnsigned = DestEltTy->isUnsignedIntegerType();
12217 unsigned CountEltWidth = Count.getVectorElt(0).getInt().getBitWidth();
12218 unsigned NumBitsInQWord = 64;
12219 unsigned NumCountElts = NumBitsInQWord / CountEltWidth;
12221 Result.reserve(DestLen);
12222
12223 uint64_t CountLQWord = 0;
12224 for (unsigned EltIdx = 0; EltIdx != NumCountElts; ++EltIdx) {
12225 uint64_t Elt = Count.getVectorElt(EltIdx).getInt().getZExtValue();
12226 CountLQWord |= (Elt << (EltIdx * CountEltWidth));
12227 }
12228
12229 for (unsigned EltIdx = 0; EltIdx != DestLen; ++EltIdx) {
12230 APInt Elt = Source.getVectorElt(EltIdx).getInt();
12231 if (CountLQWord < DestEltWidth) {
12232 Result.push_back(
12233 APValue(APSInt(ShiftOp(Elt, CountLQWord), IsDestUnsigned)));
12234 } else {
12235 Result.push_back(
12236 APValue(APSInt(OverflowOp(Elt, DestEltWidth), IsDestUnsigned)));
12237 }
12238 }
12239 Out = APValue(Result.data(), Result.size());
12240 return true;
12241}
12242
12243bool VectorExprEvaluator::VisitCallExpr(const CallExpr *E) {
12244 if (!IsConstantEvaluatedBuiltinCall(E))
12245 return ExprEvaluatorBaseTy::VisitCallExpr(E);
12246
12247 auto EvaluateBinOpExpr =
12248 [&](llvm::function_ref<APInt(const APSInt &, const APSInt &)> Fn) {
12249 APValue SourceLHS, SourceRHS;
12250 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
12251 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
12252 return false;
12253
12254 auto *DestTy = E->getType()->castAs<VectorType>();
12255 QualType DestEltTy = DestTy->getElementType();
12256 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
12257 unsigned SourceLen = SourceLHS.getVectorLength();
12258 SmallVector<APValue, 4> ResultElements;
12259 ResultElements.reserve(SourceLen);
12260
12261 if (SourceRHS.isInt()) {
12262 const APSInt &RHS = SourceRHS.getInt();
12263 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12264 const APSInt &LHS = SourceLHS.getVectorElt(EltNum).getInt();
12265 ResultElements.push_back(
12266 APValue(APSInt(Fn(LHS, RHS), DestUnsigned)));
12267 }
12268 } else {
12269 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12270 const APSInt &LHS = SourceLHS.getVectorElt(EltNum).getInt();
12271 const APSInt &RHS = SourceRHS.getVectorElt(EltNum).getInt();
12272 ResultElements.push_back(
12273 APValue(APSInt(Fn(LHS, RHS), DestUnsigned)));
12274 }
12275 }
12276 return Success(APValue(ResultElements.data(), SourceLen), E);
12277 };
12278
12279 auto EvaluateFpBinOpExpr =
12280 [&](llvm::function_ref<std::optional<APFloat>(
12281 const APFloat &, const APFloat &, std::optional<APSInt>)>
12282 Fn) {
12283 assert(E->getNumArgs() == 2 || E->getNumArgs() == 3);
12284 APValue A, B;
12285 if (!EvaluateAsRValue(Info, E->getArg(0), A) ||
12286 !EvaluateAsRValue(Info, E->getArg(1), B))
12287 return false;
12288
12289 assert(A.isVector() && B.isVector());
12290 assert(A.getVectorLength() == B.getVectorLength());
12291
12292 std::optional<APSInt> RoundingMode;
12293 if (E->getNumArgs() == 3) {
12294 APSInt Imm;
12295 if (!EvaluateInteger(E->getArg(2), Imm, Info))
12296 return false;
12297 RoundingMode = Imm;
12298 }
12299
12300 unsigned NumElems = A.getVectorLength();
12301 SmallVector<APValue, 4> ResultElements;
12302 ResultElements.reserve(NumElems);
12303
12304 for (unsigned EltNum = 0; EltNum < NumElems; ++EltNum) {
12305 const APFloat &EltA = A.getVectorElt(EltNum).getFloat();
12306 const APFloat &EltB = B.getVectorElt(EltNum).getFloat();
12307 std::optional<APFloat> Result = Fn(EltA, EltB, RoundingMode);
12308 if (!Result)
12309 return false;
12310 ResultElements.push_back(APValue(*Result));
12311 }
12312 return Success(APValue(ResultElements.data(), NumElems), E);
12313 };
12314
12315 auto EvalSelectScalar = [&](unsigned Len) -> bool {
12316 APSInt Mask;
12317 APValue AVal, WVal;
12318 if (!EvaluateInteger(E->getArg(0), Mask, Info) ||
12319 !EvaluateAsRValue(Info, E->getArg(1), AVal) ||
12320 !EvaluateAsRValue(Info, E->getArg(2), WVal))
12321 return false;
12322
12323 bool TakeA0 = (Mask.getZExtValue() & 1u) != 0;
12325 Res.reserve(Len);
12326 Res.push_back(TakeA0 ? AVal.getVectorElt(0) : WVal.getVectorElt(0));
12327 for (unsigned I = 1; I < Len; ++I)
12328 Res.push_back(WVal.getVectorElt(I));
12329 APValue V(Res.data(), Res.size());
12330 return Success(V, E);
12331 };
12332
12333 switch (E->getBuiltinCallee()) {
12334 default:
12335 return false;
12336 case Builtin::BI__builtin_elementwise_popcount:
12337 case Builtin::BI__builtin_elementwise_bitreverse: {
12338 APValue Source;
12339 if (!EvaluateAsRValue(Info, E->getArg(0), Source))
12340 return false;
12341
12342 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
12343 unsigned SourceLen = Source.getVectorLength();
12344 SmallVector<APValue, 4> ResultElements;
12345 ResultElements.reserve(SourceLen);
12346
12347 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12348 APSInt Elt = Source.getVectorElt(EltNum).getInt();
12349 switch (E->getBuiltinCallee()) {
12350 case Builtin::BI__builtin_elementwise_popcount:
12351 ResultElements.push_back(APValue(
12352 APSInt(APInt(Info.Ctx.getIntWidth(DestEltTy), Elt.popcount()),
12353 DestEltTy->isUnsignedIntegerOrEnumerationType())));
12354 break;
12355 case Builtin::BI__builtin_elementwise_bitreverse:
12356 ResultElements.push_back(
12357 APValue(APSInt(Elt.reverseBits(),
12358 DestEltTy->isUnsignedIntegerOrEnumerationType())));
12359 break;
12360 }
12361 }
12362
12363 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12364 }
12365 case Builtin::BI__builtin_elementwise_abs: {
12366 APValue Source;
12367 if (!EvaluateAsRValue(Info, E->getArg(0), Source))
12368 return false;
12369
12370 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
12371 unsigned SourceLen = Source.getVectorLength();
12372 SmallVector<APValue, 4> ResultElements;
12373 ResultElements.reserve(SourceLen);
12374
12375 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12376 APValue CurrentEle = Source.getVectorElt(EltNum);
12377 APValue Val = DestEltTy->isFloatingType()
12378 ? APValue(llvm::abs(CurrentEle.getFloat()))
12379 : APValue(APSInt(
12380 CurrentEle.getInt().abs(),
12381 DestEltTy->isUnsignedIntegerOrEnumerationType()));
12382 ResultElements.push_back(Val);
12383 }
12384
12385 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12386 }
12387
12388 case Builtin::BI__builtin_elementwise_add_sat:
12389 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
12390 return LHS.isSigned() ? LHS.sadd_sat(RHS) : LHS.uadd_sat(RHS);
12391 });
12392
12393 case Builtin::BI__builtin_elementwise_sub_sat:
12394 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
12395 return LHS.isSigned() ? LHS.ssub_sat(RHS) : LHS.usub_sat(RHS);
12396 });
12397
12398 case X86::BI__builtin_ia32_extract128i256:
12399 case X86::BI__builtin_ia32_vextractf128_pd256:
12400 case X86::BI__builtin_ia32_vextractf128_ps256:
12401 case X86::BI__builtin_ia32_vextractf128_si256: {
12402 APValue SourceVec, SourceImm;
12403 if (!EvaluateAsRValue(Info, E->getArg(0), SourceVec) ||
12404 !EvaluateAsRValue(Info, E->getArg(1), SourceImm))
12405 return false;
12406
12407 if (!SourceVec.isVector())
12408 return false;
12409
12410 const auto *RetVT = E->getType()->castAs<VectorType>();
12411 unsigned RetLen = RetVT->getNumElements();
12412 unsigned Idx = SourceImm.getInt().getZExtValue() & 1;
12413
12414 SmallVector<APValue, 32> ResultElements;
12415 ResultElements.reserve(RetLen);
12416
12417 for (unsigned I = 0; I < RetLen; I++)
12418 ResultElements.push_back(SourceVec.getVectorElt(Idx * RetLen + I));
12419
12420 return Success(APValue(ResultElements.data(), RetLen), E);
12421 }
12422
12423 case clang::X86::BI__builtin_ia32_cvtmask2b128:
12424 case clang::X86::BI__builtin_ia32_cvtmask2b256:
12425 case clang::X86::BI__builtin_ia32_cvtmask2b512:
12426 case clang::X86::BI__builtin_ia32_cvtmask2w128:
12427 case clang::X86::BI__builtin_ia32_cvtmask2w256:
12428 case clang::X86::BI__builtin_ia32_cvtmask2w512:
12429 case clang::X86::BI__builtin_ia32_cvtmask2d128:
12430 case clang::X86::BI__builtin_ia32_cvtmask2d256:
12431 case clang::X86::BI__builtin_ia32_cvtmask2d512:
12432 case clang::X86::BI__builtin_ia32_cvtmask2q128:
12433 case clang::X86::BI__builtin_ia32_cvtmask2q256:
12434 case clang::X86::BI__builtin_ia32_cvtmask2q512: {
12435 assert(E->getNumArgs() == 1);
12436 APSInt Mask;
12437 if (!EvaluateInteger(E->getArg(0), Mask, Info))
12438 return false;
12439
12440 QualType VecTy = E->getType();
12441 const VectorType *VT = VecTy->castAs<VectorType>();
12442 unsigned VectorLen = VT->getNumElements();
12443 QualType ElemTy = VT->getElementType();
12444 unsigned ElemWidth = Info.Ctx.getTypeSize(ElemTy);
12445
12447 for (unsigned I = 0; I != VectorLen; ++I) {
12448 bool BitSet = Mask[I];
12449 APSInt ElemVal(ElemWidth, /*isUnsigned=*/false);
12450 if (BitSet) {
12451 ElemVal.setAllBits();
12452 }
12453 Elems.push_back(APValue(ElemVal));
12454 }
12455 return Success(APValue(Elems.data(), VectorLen), E);
12456 }
12457
12458 case X86::BI__builtin_ia32_extracti32x4_256_mask:
12459 case X86::BI__builtin_ia32_extractf32x4_256_mask:
12460 case X86::BI__builtin_ia32_extracti32x4_mask:
12461 case X86::BI__builtin_ia32_extractf32x4_mask:
12462 case X86::BI__builtin_ia32_extracti32x8_mask:
12463 case X86::BI__builtin_ia32_extractf32x8_mask:
12464 case X86::BI__builtin_ia32_extracti64x2_256_mask:
12465 case X86::BI__builtin_ia32_extractf64x2_256_mask:
12466 case X86::BI__builtin_ia32_extracti64x2_512_mask:
12467 case X86::BI__builtin_ia32_extractf64x2_512_mask:
12468 case X86::BI__builtin_ia32_extracti64x4_mask:
12469 case X86::BI__builtin_ia32_extractf64x4_mask: {
12470 APValue SourceVec, MergeVec;
12471 APSInt Imm, MaskImm;
12472
12473 if (!EvaluateAsRValue(Info, E->getArg(0), SourceVec) ||
12474 !EvaluateInteger(E->getArg(1), Imm, Info) ||
12475 !EvaluateAsRValue(Info, E->getArg(2), MergeVec) ||
12476 !EvaluateInteger(E->getArg(3), MaskImm, Info))
12477 return false;
12478
12479 const auto *RetVT = E->getType()->castAs<VectorType>();
12480 unsigned RetLen = RetVT->getNumElements();
12481
12482 if (!SourceVec.isVector() || !MergeVec.isVector())
12483 return false;
12484 unsigned SrcLen = SourceVec.getVectorLength();
12485 unsigned Lanes = SrcLen / RetLen;
12486 unsigned Lane = static_cast<unsigned>(Imm.getZExtValue() % Lanes);
12487 unsigned Base = Lane * RetLen;
12488
12489 SmallVector<APValue, 32> ResultElements;
12490 ResultElements.reserve(RetLen);
12491 for (unsigned I = 0; I < RetLen; ++I) {
12492 if (MaskImm[I])
12493 ResultElements.push_back(SourceVec.getVectorElt(Base + I));
12494 else
12495 ResultElements.push_back(MergeVec.getVectorElt(I));
12496 }
12497 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12498 }
12499
12500 case clang::X86::BI__builtin_ia32_pavgb128:
12501 case clang::X86::BI__builtin_ia32_pavgw128:
12502 case clang::X86::BI__builtin_ia32_pavgb256:
12503 case clang::X86::BI__builtin_ia32_pavgw256:
12504 case clang::X86::BI__builtin_ia32_pavgb512:
12505 case clang::X86::BI__builtin_ia32_pavgw512:
12506 return EvaluateBinOpExpr(llvm::APIntOps::avgCeilU);
12507
12508 case clang::X86::BI__builtin_ia32_pmulhrsw128:
12509 case clang::X86::BI__builtin_ia32_pmulhrsw256:
12510 case clang::X86::BI__builtin_ia32_pmulhrsw512:
12511 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
12512 return (llvm::APIntOps::mulsExtended(LHS, RHS).ashr(14) + 1)
12513 .extractBits(16, 1);
12514 });
12515
12516 case clang::X86::BI__builtin_ia32_pmaddubsw128:
12517 case clang::X86::BI__builtin_ia32_pmaddubsw256:
12518 case clang::X86::BI__builtin_ia32_pmaddubsw512:
12519 case clang::X86::BI__builtin_ia32_pmaddwd128:
12520 case clang::X86::BI__builtin_ia32_pmaddwd256:
12521 case clang::X86::BI__builtin_ia32_pmaddwd512: {
12522 APValue SourceLHS, SourceRHS;
12523 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
12524 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
12525 return false;
12526
12527 auto *DestTy = E->getType()->castAs<VectorType>();
12528 QualType DestEltTy = DestTy->getElementType();
12529 unsigned SourceLen = SourceLHS.getVectorLength();
12530 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
12531 SmallVector<APValue, 4> ResultElements;
12532 ResultElements.reserve(SourceLen / 2);
12533
12534 for (unsigned EltNum = 0; EltNum < SourceLen; EltNum += 2) {
12535 const APSInt &LoLHS = SourceLHS.getVectorElt(EltNum).getInt();
12536 const APSInt &HiLHS = SourceLHS.getVectorElt(EltNum + 1).getInt();
12537 const APSInt &LoRHS = SourceRHS.getVectorElt(EltNum).getInt();
12538 const APSInt &HiRHS = SourceRHS.getVectorElt(EltNum + 1).getInt();
12539 unsigned BitWidth = 2 * LoLHS.getBitWidth();
12540
12541 switch (E->getBuiltinCallee()) {
12542 case clang::X86::BI__builtin_ia32_pmaddubsw128:
12543 case clang::X86::BI__builtin_ia32_pmaddubsw256:
12544 case clang::X86::BI__builtin_ia32_pmaddubsw512:
12545 ResultElements.push_back(APValue(
12546 APSInt((LoLHS.zext(BitWidth) * LoRHS.sext(BitWidth))
12547 .sadd_sat((HiLHS.zext(BitWidth) * HiRHS.sext(BitWidth))),
12548 DestUnsigned)));
12549 break;
12550 case clang::X86::BI__builtin_ia32_pmaddwd128:
12551 case clang::X86::BI__builtin_ia32_pmaddwd256:
12552 case clang::X86::BI__builtin_ia32_pmaddwd512:
12553 ResultElements.push_back(
12554 APValue(APSInt((LoLHS.sext(BitWidth) * LoRHS.sext(BitWidth)) +
12555 (HiLHS.sext(BitWidth) * HiRHS.sext(BitWidth)),
12556 DestUnsigned)));
12557 break;
12558 }
12559 }
12560
12561 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12562 }
12563
12564 case clang::X86::BI__builtin_ia32_pmulhuw128:
12565 case clang::X86::BI__builtin_ia32_pmulhuw256:
12566 case clang::X86::BI__builtin_ia32_pmulhuw512:
12567 return EvaluateBinOpExpr(llvm::APIntOps::mulhu);
12568
12569 case clang::X86::BI__builtin_ia32_pmulhw128:
12570 case clang::X86::BI__builtin_ia32_pmulhw256:
12571 case clang::X86::BI__builtin_ia32_pmulhw512:
12572 return EvaluateBinOpExpr(llvm::APIntOps::mulhs);
12573
12574 case clang::X86::BI__builtin_ia32_psllv2di:
12575 case clang::X86::BI__builtin_ia32_psllv4di:
12576 case clang::X86::BI__builtin_ia32_psllv4si:
12577 case clang::X86::BI__builtin_ia32_psllv8di:
12578 case clang::X86::BI__builtin_ia32_psllv8hi:
12579 case clang::X86::BI__builtin_ia32_psllv8si:
12580 case clang::X86::BI__builtin_ia32_psllv16hi:
12581 case clang::X86::BI__builtin_ia32_psllv16si:
12582 case clang::X86::BI__builtin_ia32_psllv32hi:
12583 case clang::X86::BI__builtin_ia32_psllwi128:
12584 case clang::X86::BI__builtin_ia32_pslldi128:
12585 case clang::X86::BI__builtin_ia32_psllqi128:
12586 case clang::X86::BI__builtin_ia32_psllwi256:
12587 case clang::X86::BI__builtin_ia32_pslldi256:
12588 case clang::X86::BI__builtin_ia32_psllqi256:
12589 case clang::X86::BI__builtin_ia32_psllwi512:
12590 case clang::X86::BI__builtin_ia32_pslldi512:
12591 case clang::X86::BI__builtin_ia32_psllqi512:
12592 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
12593 if (RHS.uge(LHS.getBitWidth())) {
12594 return APInt::getZero(LHS.getBitWidth());
12595 }
12596 return LHS.shl(RHS.getZExtValue());
12597 });
12598
12599 case clang::X86::BI__builtin_ia32_psrav4si:
12600 case clang::X86::BI__builtin_ia32_psrav8di:
12601 case clang::X86::BI__builtin_ia32_psrav8hi:
12602 case clang::X86::BI__builtin_ia32_psrav8si:
12603 case clang::X86::BI__builtin_ia32_psrav16hi:
12604 case clang::X86::BI__builtin_ia32_psrav16si:
12605 case clang::X86::BI__builtin_ia32_psrav32hi:
12606 case clang::X86::BI__builtin_ia32_psravq128:
12607 case clang::X86::BI__builtin_ia32_psravq256:
12608 case clang::X86::BI__builtin_ia32_psrawi128:
12609 case clang::X86::BI__builtin_ia32_psradi128:
12610 case clang::X86::BI__builtin_ia32_psraqi128:
12611 case clang::X86::BI__builtin_ia32_psrawi256:
12612 case clang::X86::BI__builtin_ia32_psradi256:
12613 case clang::X86::BI__builtin_ia32_psraqi256:
12614 case clang::X86::BI__builtin_ia32_psrawi512:
12615 case clang::X86::BI__builtin_ia32_psradi512:
12616 case clang::X86::BI__builtin_ia32_psraqi512:
12617 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
12618 if (RHS.uge(LHS.getBitWidth())) {
12619 return LHS.ashr(LHS.getBitWidth() - 1);
12620 }
12621 return LHS.ashr(RHS.getZExtValue());
12622 });
12623
12624 case clang::X86::BI__builtin_ia32_psrlv2di:
12625 case clang::X86::BI__builtin_ia32_psrlv4di:
12626 case clang::X86::BI__builtin_ia32_psrlv4si:
12627 case clang::X86::BI__builtin_ia32_psrlv8di:
12628 case clang::X86::BI__builtin_ia32_psrlv8hi:
12629 case clang::X86::BI__builtin_ia32_psrlv8si:
12630 case clang::X86::BI__builtin_ia32_psrlv16hi:
12631 case clang::X86::BI__builtin_ia32_psrlv16si:
12632 case clang::X86::BI__builtin_ia32_psrlv32hi:
12633 case clang::X86::BI__builtin_ia32_psrlwi128:
12634 case clang::X86::BI__builtin_ia32_psrldi128:
12635 case clang::X86::BI__builtin_ia32_psrlqi128:
12636 case clang::X86::BI__builtin_ia32_psrlwi256:
12637 case clang::X86::BI__builtin_ia32_psrldi256:
12638 case clang::X86::BI__builtin_ia32_psrlqi256:
12639 case clang::X86::BI__builtin_ia32_psrlwi512:
12640 case clang::X86::BI__builtin_ia32_psrldi512:
12641 case clang::X86::BI__builtin_ia32_psrlqi512:
12642 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
12643 if (RHS.uge(LHS.getBitWidth())) {
12644 return APInt::getZero(LHS.getBitWidth());
12645 }
12646 return LHS.lshr(RHS.getZExtValue());
12647 });
12648 case X86::BI__builtin_ia32_packsswb128:
12649 case X86::BI__builtin_ia32_packsswb256:
12650 case X86::BI__builtin_ia32_packsswb512:
12651 case X86::BI__builtin_ia32_packssdw128:
12652 case X86::BI__builtin_ia32_packssdw256:
12653 case X86::BI__builtin_ia32_packssdw512:
12654 return evalPackBuiltin(E, Info, Result, [](const APSInt &Src) {
12655 return APSInt(Src).truncSSat(Src.getBitWidth() / 2);
12656 });
12657 case X86::BI__builtin_ia32_packusdw128:
12658 case X86::BI__builtin_ia32_packusdw256:
12659 case X86::BI__builtin_ia32_packusdw512:
12660 case X86::BI__builtin_ia32_packuswb128:
12661 case X86::BI__builtin_ia32_packuswb256:
12662 case X86::BI__builtin_ia32_packuswb512:
12663 return evalPackBuiltin(E, Info, Result, [](const APSInt &Src) {
12664 return APSInt(Src).truncSSatU(Src.getBitWidth() / 2);
12665 });
12666 case clang::X86::BI__builtin_ia32_selectss_128:
12667 return EvalSelectScalar(4);
12668 case clang::X86::BI__builtin_ia32_selectsd_128:
12669 return EvalSelectScalar(2);
12670 case clang::X86::BI__builtin_ia32_selectsh_128:
12671 case clang::X86::BI__builtin_ia32_selectsbf_128:
12672 return EvalSelectScalar(8);
12673 case clang::X86::BI__builtin_ia32_pmuldq128:
12674 case clang::X86::BI__builtin_ia32_pmuldq256:
12675 case clang::X86::BI__builtin_ia32_pmuldq512:
12676 case clang::X86::BI__builtin_ia32_pmuludq128:
12677 case clang::X86::BI__builtin_ia32_pmuludq256:
12678 case clang::X86::BI__builtin_ia32_pmuludq512: {
12679 APValue SourceLHS, SourceRHS;
12680 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
12681 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
12682 return false;
12683
12684 unsigned SourceLen = SourceLHS.getVectorLength();
12685 SmallVector<APValue, 4> ResultElements;
12686 ResultElements.reserve(SourceLen / 2);
12687
12688 for (unsigned EltNum = 0; EltNum < SourceLen; EltNum += 2) {
12689 APSInt LHS = SourceLHS.getVectorElt(EltNum).getInt();
12690 APSInt RHS = SourceRHS.getVectorElt(EltNum).getInt();
12691
12692 switch (E->getBuiltinCallee()) {
12693 case clang::X86::BI__builtin_ia32_pmuludq128:
12694 case clang::X86::BI__builtin_ia32_pmuludq256:
12695 case clang::X86::BI__builtin_ia32_pmuludq512:
12696 ResultElements.push_back(
12697 APValue(APSInt(llvm::APIntOps::muluExtended(LHS, RHS), true)));
12698 break;
12699 case clang::X86::BI__builtin_ia32_pmuldq128:
12700 case clang::X86::BI__builtin_ia32_pmuldq256:
12701 case clang::X86::BI__builtin_ia32_pmuldq512:
12702 ResultElements.push_back(
12703 APValue(APSInt(llvm::APIntOps::mulsExtended(LHS, RHS), false)));
12704 break;
12705 }
12706 }
12707
12708 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12709 }
12710
12711 case X86::BI__builtin_ia32_vpmadd52luq128:
12712 case X86::BI__builtin_ia32_vpmadd52luq256:
12713 case X86::BI__builtin_ia32_vpmadd52luq512: {
12714 APValue A, B, C;
12715 if (!EvaluateAsRValue(Info, E->getArg(0), A) ||
12716 !EvaluateAsRValue(Info, E->getArg(1), B) ||
12717 !EvaluateAsRValue(Info, E->getArg(2), C))
12718 return false;
12719
12720 unsigned ALen = A.getVectorLength();
12721 SmallVector<APValue, 4> ResultElements;
12722 ResultElements.reserve(ALen);
12723
12724 for (unsigned EltNum = 0; EltNum < ALen; EltNum += 1) {
12725 APInt AElt = A.getVectorElt(EltNum).getInt();
12726 APInt BElt = B.getVectorElt(EltNum).getInt().trunc(52);
12727 APInt CElt = C.getVectorElt(EltNum).getInt().trunc(52);
12728 APSInt ResElt(AElt + (BElt * CElt).zext(64), false);
12729 ResultElements.push_back(APValue(ResElt));
12730 }
12731
12732 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12733 }
12734 case X86::BI__builtin_ia32_vpmadd52huq128:
12735 case X86::BI__builtin_ia32_vpmadd52huq256:
12736 case X86::BI__builtin_ia32_vpmadd52huq512: {
12737 APValue A, B, C;
12738 if (!EvaluateAsRValue(Info, E->getArg(0), A) ||
12739 !EvaluateAsRValue(Info, E->getArg(1), B) ||
12740 !EvaluateAsRValue(Info, E->getArg(2), C))
12741 return false;
12742
12743 unsigned ALen = A.getVectorLength();
12744 SmallVector<APValue, 4> ResultElements;
12745 ResultElements.reserve(ALen);
12746
12747 for (unsigned EltNum = 0; EltNum < ALen; EltNum += 1) {
12748 APInt AElt = A.getVectorElt(EltNum).getInt();
12749 APInt BElt = B.getVectorElt(EltNum).getInt().trunc(52);
12750 APInt CElt = C.getVectorElt(EltNum).getInt().trunc(52);
12751 APSInt ResElt(AElt + llvm::APIntOps::mulhu(BElt, CElt).zext(64), false);
12752 ResultElements.push_back(APValue(ResElt));
12753 }
12754
12755 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12756 }
12757
12758 case clang::X86::BI__builtin_ia32_vprotbi:
12759 case clang::X86::BI__builtin_ia32_vprotdi:
12760 case clang::X86::BI__builtin_ia32_vprotqi:
12761 case clang::X86::BI__builtin_ia32_vprotwi:
12762 case clang::X86::BI__builtin_ia32_prold128:
12763 case clang::X86::BI__builtin_ia32_prold256:
12764 case clang::X86::BI__builtin_ia32_prold512:
12765 case clang::X86::BI__builtin_ia32_prolq128:
12766 case clang::X86::BI__builtin_ia32_prolq256:
12767 case clang::X86::BI__builtin_ia32_prolq512:
12768 return EvaluateBinOpExpr(
12769 [](const APSInt &LHS, const APSInt &RHS) { return LHS.rotl(RHS); });
12770
12771 case clang::X86::BI__builtin_ia32_prord128:
12772 case clang::X86::BI__builtin_ia32_prord256:
12773 case clang::X86::BI__builtin_ia32_prord512:
12774 case clang::X86::BI__builtin_ia32_prorq128:
12775 case clang::X86::BI__builtin_ia32_prorq256:
12776 case clang::X86::BI__builtin_ia32_prorq512:
12777 return EvaluateBinOpExpr(
12778 [](const APSInt &LHS, const APSInt &RHS) { return LHS.rotr(RHS); });
12779
12780 case Builtin::BI__builtin_elementwise_max:
12781 case Builtin::BI__builtin_elementwise_min: {
12782 APValue SourceLHS, SourceRHS;
12783 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
12784 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
12785 return false;
12786
12787 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
12788
12789 if (!DestEltTy->isIntegerType())
12790 return false;
12791
12792 unsigned SourceLen = SourceLHS.getVectorLength();
12793 SmallVector<APValue, 4> ResultElements;
12794 ResultElements.reserve(SourceLen);
12795
12796 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12797 APSInt LHS = SourceLHS.getVectorElt(EltNum).getInt();
12798 APSInt RHS = SourceRHS.getVectorElt(EltNum).getInt();
12799 switch (E->getBuiltinCallee()) {
12800 case Builtin::BI__builtin_elementwise_max:
12801 ResultElements.push_back(
12802 APValue(APSInt(std::max(LHS, RHS),
12803 DestEltTy->isUnsignedIntegerOrEnumerationType())));
12804 break;
12805 case Builtin::BI__builtin_elementwise_min:
12806 ResultElements.push_back(
12807 APValue(APSInt(std::min(LHS, RHS),
12808 DestEltTy->isUnsignedIntegerOrEnumerationType())));
12809 break;
12810 }
12811 }
12812
12813 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12814 }
12815 case X86::BI__builtin_ia32_vpshldd128:
12816 case X86::BI__builtin_ia32_vpshldd256:
12817 case X86::BI__builtin_ia32_vpshldd512:
12818 case X86::BI__builtin_ia32_vpshldq128:
12819 case X86::BI__builtin_ia32_vpshldq256:
12820 case X86::BI__builtin_ia32_vpshldq512:
12821 case X86::BI__builtin_ia32_vpshldw128:
12822 case X86::BI__builtin_ia32_vpshldw256:
12823 case X86::BI__builtin_ia32_vpshldw512: {
12824 APValue SourceHi, SourceLo, SourceAmt;
12825 if (!EvaluateAsRValue(Info, E->getArg(0), SourceHi) ||
12826 !EvaluateAsRValue(Info, E->getArg(1), SourceLo) ||
12827 !EvaluateAsRValue(Info, E->getArg(2), SourceAmt))
12828 return false;
12829
12830 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
12831 unsigned SourceLen = SourceHi.getVectorLength();
12832 SmallVector<APValue, 32> ResultElements;
12833 ResultElements.reserve(SourceLen);
12834
12835 APInt Amt = SourceAmt.getInt();
12836 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12837 APInt Hi = SourceHi.getVectorElt(EltNum).getInt();
12838 APInt Lo = SourceLo.getVectorElt(EltNum).getInt();
12839 APInt R = llvm::APIntOps::fshl(Hi, Lo, Amt);
12840 ResultElements.push_back(
12842 }
12843
12844 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12845 }
12846 case X86::BI__builtin_ia32_vpshrdd128:
12847 case X86::BI__builtin_ia32_vpshrdd256:
12848 case X86::BI__builtin_ia32_vpshrdd512:
12849 case X86::BI__builtin_ia32_vpshrdq128:
12850 case X86::BI__builtin_ia32_vpshrdq256:
12851 case X86::BI__builtin_ia32_vpshrdq512:
12852 case X86::BI__builtin_ia32_vpshrdw128:
12853 case X86::BI__builtin_ia32_vpshrdw256:
12854 case X86::BI__builtin_ia32_vpshrdw512: {
12855 // NOTE: Reversed Hi/Lo operands.
12856 APValue SourceHi, SourceLo, SourceAmt;
12857 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLo) ||
12858 !EvaluateAsRValue(Info, E->getArg(1), SourceHi) ||
12859 !EvaluateAsRValue(Info, E->getArg(2), SourceAmt))
12860 return false;
12861
12862 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
12863 unsigned SourceLen = SourceHi.getVectorLength();
12864 SmallVector<APValue, 32> ResultElements;
12865 ResultElements.reserve(SourceLen);
12866
12867 APInt Amt = SourceAmt.getInt();
12868 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12869 APInt Hi = SourceHi.getVectorElt(EltNum).getInt();
12870 APInt Lo = SourceLo.getVectorElt(EltNum).getInt();
12871 APInt R = llvm::APIntOps::fshr(Hi, Lo, Amt);
12872 ResultElements.push_back(
12874 }
12875
12876 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12877 }
12878 case X86::BI__builtin_ia32_vpconflictsi_128:
12879 case X86::BI__builtin_ia32_vpconflictsi_256:
12880 case X86::BI__builtin_ia32_vpconflictsi_512:
12881 case X86::BI__builtin_ia32_vpconflictdi_128:
12882 case X86::BI__builtin_ia32_vpconflictdi_256:
12883 case X86::BI__builtin_ia32_vpconflictdi_512: {
12884 APValue Source;
12885
12886 if (!EvaluateAsRValue(Info, E->getArg(0), Source))
12887 return false;
12888
12889 unsigned SourceLen = Source.getVectorLength();
12890 SmallVector<APValue, 32> ResultElements;
12891 ResultElements.reserve(SourceLen);
12892
12893 const auto *VecT = E->getType()->castAs<VectorType>();
12894 bool DestUnsigned =
12895 VecT->getElementType()->isUnsignedIntegerOrEnumerationType();
12896
12897 for (unsigned I = 0; I != SourceLen; ++I) {
12898 const APValue &EltI = Source.getVectorElt(I);
12899
12900 APInt ConflictMask(EltI.getInt().getBitWidth(), 0);
12901 for (unsigned J = 0; J != I; ++J) {
12902 const APValue &EltJ = Source.getVectorElt(J);
12903 ConflictMask.setBitVal(J, EltI.getInt() == EltJ.getInt());
12904 }
12905 ResultElements.push_back(APValue(APSInt(ConflictMask, DestUnsigned)));
12906 }
12907 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12908 }
12909 case X86::BI__builtin_ia32_blendpd:
12910 case X86::BI__builtin_ia32_blendpd256:
12911 case X86::BI__builtin_ia32_blendps:
12912 case X86::BI__builtin_ia32_blendps256:
12913 case X86::BI__builtin_ia32_pblendw128:
12914 case X86::BI__builtin_ia32_pblendw256:
12915 case X86::BI__builtin_ia32_pblendd128:
12916 case X86::BI__builtin_ia32_pblendd256: {
12917 APValue SourceF, SourceT, SourceC;
12918 if (!EvaluateAsRValue(Info, E->getArg(0), SourceF) ||
12919 !EvaluateAsRValue(Info, E->getArg(1), SourceT) ||
12920 !EvaluateAsRValue(Info, E->getArg(2), SourceC))
12921 return false;
12922
12923 const APInt &C = SourceC.getInt();
12924 unsigned SourceLen = SourceF.getVectorLength();
12925 SmallVector<APValue, 32> ResultElements;
12926 ResultElements.reserve(SourceLen);
12927 for (unsigned EltNum = 0; EltNum != SourceLen; ++EltNum) {
12928 const APValue &F = SourceF.getVectorElt(EltNum);
12929 const APValue &T = SourceT.getVectorElt(EltNum);
12930 ResultElements.push_back(C[EltNum % 8] ? T : F);
12931 }
12932
12933 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12934 }
12935
12936 case X86::BI__builtin_ia32_psignb128:
12937 case X86::BI__builtin_ia32_psignb256:
12938 case X86::BI__builtin_ia32_psignw128:
12939 case X86::BI__builtin_ia32_psignw256:
12940 case X86::BI__builtin_ia32_psignd128:
12941 case X86::BI__builtin_ia32_psignd256:
12942 return EvaluateBinOpExpr([](const APInt &AElem, const APInt &BElem) {
12943 if (BElem.isZero())
12944 return APInt::getZero(AElem.getBitWidth());
12945 if (BElem.isNegative())
12946 return -AElem;
12947 return AElem;
12948 });
12949
12950 case X86::BI__builtin_ia32_blendvpd:
12951 case X86::BI__builtin_ia32_blendvpd256:
12952 case X86::BI__builtin_ia32_blendvps:
12953 case X86::BI__builtin_ia32_blendvps256:
12954 case X86::BI__builtin_ia32_pblendvb128:
12955 case X86::BI__builtin_ia32_pblendvb256: {
12956 // SSE blendv by mask signbit: "Result = C[] < 0 ? T[] : F[]".
12957 APValue SourceF, SourceT, SourceC;
12958 if (!EvaluateAsRValue(Info, E->getArg(0), SourceF) ||
12959 !EvaluateAsRValue(Info, E->getArg(1), SourceT) ||
12960 !EvaluateAsRValue(Info, E->getArg(2), SourceC))
12961 return false;
12962
12963 unsigned SourceLen = SourceF.getVectorLength();
12964 SmallVector<APValue, 32> ResultElements;
12965 ResultElements.reserve(SourceLen);
12966
12967 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12968 const APValue &F = SourceF.getVectorElt(EltNum);
12969 const APValue &T = SourceT.getVectorElt(EltNum);
12970 const APValue &C = SourceC.getVectorElt(EltNum);
12971 APInt M = C.isInt() ? (APInt)C.getInt() : C.getFloat().bitcastToAPInt();
12972 ResultElements.push_back(M.isNegative() ? T : F);
12973 }
12974
12975 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12976 }
12977 case X86::BI__builtin_ia32_selectb_128:
12978 case X86::BI__builtin_ia32_selectb_256:
12979 case X86::BI__builtin_ia32_selectb_512:
12980 case X86::BI__builtin_ia32_selectw_128:
12981 case X86::BI__builtin_ia32_selectw_256:
12982 case X86::BI__builtin_ia32_selectw_512:
12983 case X86::BI__builtin_ia32_selectd_128:
12984 case X86::BI__builtin_ia32_selectd_256:
12985 case X86::BI__builtin_ia32_selectd_512:
12986 case X86::BI__builtin_ia32_selectq_128:
12987 case X86::BI__builtin_ia32_selectq_256:
12988 case X86::BI__builtin_ia32_selectq_512:
12989 case X86::BI__builtin_ia32_selectph_128:
12990 case X86::BI__builtin_ia32_selectph_256:
12991 case X86::BI__builtin_ia32_selectph_512:
12992 case X86::BI__builtin_ia32_selectpbf_128:
12993 case X86::BI__builtin_ia32_selectpbf_256:
12994 case X86::BI__builtin_ia32_selectpbf_512:
12995 case X86::BI__builtin_ia32_selectps_128:
12996 case X86::BI__builtin_ia32_selectps_256:
12997 case X86::BI__builtin_ia32_selectps_512:
12998 case X86::BI__builtin_ia32_selectpd_128:
12999 case X86::BI__builtin_ia32_selectpd_256:
13000 case X86::BI__builtin_ia32_selectpd_512: {
13001 // AVX512 predicated move: "Result = Mask[] ? LHS[] : RHS[]".
13002 APValue SourceMask, SourceLHS, SourceRHS;
13003 if (!EvaluateAsRValue(Info, E->getArg(0), SourceMask) ||
13004 !EvaluateAsRValue(Info, E->getArg(1), SourceLHS) ||
13005 !EvaluateAsRValue(Info, E->getArg(2), SourceRHS))
13006 return false;
13007
13008 APSInt Mask = SourceMask.getInt();
13009 unsigned SourceLen = SourceLHS.getVectorLength();
13010 SmallVector<APValue, 4> ResultElements;
13011 ResultElements.reserve(SourceLen);
13012
13013 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
13014 const APValue &LHS = SourceLHS.getVectorElt(EltNum);
13015 const APValue &RHS = SourceRHS.getVectorElt(EltNum);
13016 ResultElements.push_back(Mask[EltNum] ? LHS : RHS);
13017 }
13018
13019 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13020 }
13021
13022 case X86::BI__builtin_ia32_cvtsd2ss: {
13023 APValue VecA, VecB;
13024 if (!EvaluateAsRValue(Info, E->getArg(0), VecA) ||
13025 !EvaluateAsRValue(Info, E->getArg(1), VecB))
13026 return false;
13027
13028 SmallVector<APValue, 4> Elements;
13029
13030 APValue ResultVal;
13031 if (!ConvertDoubleToFloatStrict(Info, E, VecB.getVectorElt(0).getFloat(),
13032 ResultVal))
13033 return false;
13034
13035 Elements.push_back(ResultVal);
13036
13037 unsigned NumEltsA = VecA.getVectorLength();
13038 for (unsigned I = 1; I < NumEltsA; ++I) {
13039 Elements.push_back(VecA.getVectorElt(I));
13040 }
13041
13042 return Success(Elements, E);
13043 }
13044 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: {
13045 APValue VecA, VecB, VecSrc, MaskValue;
13046
13047 if (!EvaluateAsRValue(Info, E->getArg(0), VecA) ||
13048 !EvaluateAsRValue(Info, E->getArg(1), VecB) ||
13049 !EvaluateAsRValue(Info, E->getArg(2), VecSrc) ||
13050 !EvaluateAsRValue(Info, E->getArg(3), MaskValue))
13051 return false;
13052
13053 unsigned Mask = MaskValue.getInt().getZExtValue();
13054 SmallVector<APValue, 4> Elements;
13055
13056 if (Mask & 1) {
13057 APValue ResultVal;
13058 if (!ConvertDoubleToFloatStrict(Info, E, VecB.getVectorElt(0).getFloat(),
13059 ResultVal))
13060 return false;
13061 Elements.push_back(ResultVal);
13062 } else {
13063 Elements.push_back(VecSrc.getVectorElt(0));
13064 }
13065
13066 unsigned NumEltsA = VecA.getVectorLength();
13067 for (unsigned I = 1; I < NumEltsA; ++I) {
13068 Elements.push_back(VecA.getVectorElt(I));
13069 }
13070
13071 return Success(Elements, E);
13072 }
13073 case X86::BI__builtin_ia32_cvtpd2ps:
13074 case X86::BI__builtin_ia32_cvtpd2ps256:
13075 case X86::BI__builtin_ia32_cvtpd2ps_mask:
13076 case X86::BI__builtin_ia32_cvtpd2ps512_mask: {
13077
13078 const auto BuiltinID = E->getBuiltinCallee();
13079 bool IsMasked = (BuiltinID == X86::BI__builtin_ia32_cvtpd2ps_mask ||
13080 BuiltinID == X86::BI__builtin_ia32_cvtpd2ps512_mask);
13081
13082 APValue InputValue;
13083 if (!EvaluateAsRValue(Info, E->getArg(0), InputValue))
13084 return false;
13085
13086 APValue MergeValue;
13087 unsigned Mask = 0xFFFFFFFF;
13088 bool NeedsMerge = false;
13089 if (IsMasked) {
13090 APValue MaskValue;
13091 if (!EvaluateAsRValue(Info, E->getArg(2), MaskValue))
13092 return false;
13093 Mask = MaskValue.getInt().getZExtValue();
13094 auto NumEltsResult = E->getType()->getAs<VectorType>()->getNumElements();
13095 for (unsigned I = 0; I < NumEltsResult; ++I) {
13096 if (!((Mask >> I) & 1)) {
13097 NeedsMerge = true;
13098 break;
13099 }
13100 }
13101 if (NeedsMerge) {
13102 if (!EvaluateAsRValue(Info, E->getArg(1), MergeValue))
13103 return false;
13104 }
13105 }
13106
13107 unsigned NumEltsResult =
13108 E->getType()->getAs<VectorType>()->getNumElements();
13109 unsigned NumEltsInput = InputValue.getVectorLength();
13110 SmallVector<APValue, 8> Elements;
13111 for (unsigned I = 0; I < NumEltsResult; ++I) {
13112 if (IsMasked && !((Mask >> I) & 1)) {
13113 if (!NeedsMerge) {
13114 return false;
13115 }
13116 Elements.push_back(MergeValue.getVectorElt(I));
13117 continue;
13118 }
13119
13120 if (I >= NumEltsInput) {
13121 Elements.push_back(APValue(APFloat::getZero(APFloat::IEEEsingle())));
13122 continue;
13123 }
13124
13125 APValue ResultVal;
13127 Info, E, InputValue.getVectorElt(I).getFloat(), ResultVal))
13128 return false;
13129
13130 Elements.push_back(ResultVal);
13131 }
13132 return Success(Elements, E);
13133 }
13134
13135 case X86::BI__builtin_ia32_shufps:
13136 case X86::BI__builtin_ia32_shufps256:
13137 case X86::BI__builtin_ia32_shufps512: {
13138 APValue R;
13139 if (!evalShuffleGeneric(
13140 Info, E, R,
13141 [](unsigned DstIdx,
13142 unsigned ShuffleMask) -> std::pair<unsigned, int> {
13143 constexpr unsigned LaneBits = 128u;
13144 unsigned NumElemPerLane = LaneBits / 32;
13145 unsigned NumSelectableElems = NumElemPerLane / 2;
13146 unsigned BitsPerElem = 2;
13147 unsigned IndexMask = (1u << BitsPerElem) - 1;
13148 unsigned MaskBits = 8;
13149 unsigned Lane = DstIdx / NumElemPerLane;
13150 unsigned ElemInLane = DstIdx % NumElemPerLane;
13151 unsigned LaneOffset = Lane * NumElemPerLane;
13152 unsigned BitIndex = (DstIdx * BitsPerElem) % MaskBits;
13153 unsigned SrcIdx = (ElemInLane < NumSelectableElems) ? 0 : 1;
13154 unsigned Index = (ShuffleMask >> BitIndex) & IndexMask;
13155 return {SrcIdx, static_cast<int>(LaneOffset + Index)};
13156 }))
13157 return false;
13158 return Success(R, E);
13159 }
13160 case X86::BI__builtin_ia32_shufpd:
13161 case X86::BI__builtin_ia32_shufpd256:
13162 case X86::BI__builtin_ia32_shufpd512: {
13163 APValue R;
13164 if (!evalShuffleGeneric(
13165 Info, E, R,
13166 [](unsigned DstIdx,
13167 unsigned ShuffleMask) -> std::pair<unsigned, int> {
13168 constexpr unsigned LaneBits = 128u;
13169 unsigned NumElemPerLane = LaneBits / 64;
13170 unsigned NumSelectableElems = NumElemPerLane / 2;
13171 unsigned BitsPerElem = 1;
13172 unsigned IndexMask = (1u << BitsPerElem) - 1;
13173 unsigned MaskBits = 8;
13174 unsigned Lane = DstIdx / NumElemPerLane;
13175 unsigned ElemInLane = DstIdx % NumElemPerLane;
13176 unsigned LaneOffset = Lane * NumElemPerLane;
13177 unsigned BitIndex = (DstIdx * BitsPerElem) % MaskBits;
13178 unsigned SrcIdx = (ElemInLane < NumSelectableElems) ? 0 : 1;
13179 unsigned Index = (ShuffleMask >> BitIndex) & IndexMask;
13180 return {SrcIdx, static_cast<int>(LaneOffset + Index)};
13181 }))
13182 return false;
13183 return Success(R, E);
13184 }
13185 case X86::BI__builtin_ia32_insertps128: {
13186 APValue R;
13187 if (!evalShuffleGeneric(
13188 Info, E, R,
13189 [](unsigned DstIdx, unsigned Mask) -> std::pair<unsigned, int> {
13190 // Bits [3:0]: zero mask - if bit is set, zero this element
13191 if ((Mask & (1 << DstIdx)) != 0) {
13192 return {0, -1};
13193 }
13194 // Bits [7:6]: select element from source vector Y (0-3)
13195 // Bits [5:4]: select destination position (0-3)
13196 unsigned SrcElem = (Mask >> 6) & 0x3;
13197 unsigned DstElem = (Mask >> 4) & 0x3;
13198 if (DstIdx == DstElem) {
13199 // Insert element from source vector (B) at this position
13200 return {1, static_cast<int>(SrcElem)};
13201 } else {
13202 // Copy from destination vector (A)
13203 return {0, static_cast<int>(DstIdx)};
13204 }
13205 }))
13206 return false;
13207 return Success(R, E);
13208 }
13209 case X86::BI__builtin_ia32_pshufb128:
13210 case X86::BI__builtin_ia32_pshufb256:
13211 case X86::BI__builtin_ia32_pshufb512: {
13212 APValue R;
13213 if (!evalShuffleGeneric(
13214 Info, E, R,
13215 [](unsigned DstIdx,
13216 unsigned ShuffleMask) -> std::pair<unsigned, int> {
13217 uint8_t Ctlb = static_cast<uint8_t>(ShuffleMask);
13218 if (Ctlb & 0x80)
13219 return std::make_pair(0, -1);
13220
13221 unsigned LaneBase = (DstIdx / 16) * 16;
13222 unsigned SrcOffset = Ctlb & 0x0F;
13223 unsigned SrcIdx = LaneBase + SrcOffset;
13224 return std::make_pair(0, static_cast<int>(SrcIdx));
13225 }))
13226 return false;
13227 return Success(R, E);
13228 }
13229
13230 case X86::BI__builtin_ia32_pshuflw:
13231 case X86::BI__builtin_ia32_pshuflw256:
13232 case X86::BI__builtin_ia32_pshuflw512: {
13233 APValue R;
13234 if (!evalShuffleGeneric(
13235 Info, E, R,
13236 [](unsigned DstIdx, unsigned Mask) -> std::pair<unsigned, int> {
13237 constexpr unsigned LaneBits = 128u;
13238 constexpr unsigned ElemBits = 16u;
13239 constexpr unsigned LaneElts = LaneBits / ElemBits;
13240 constexpr unsigned HalfSize = 4;
13241 unsigned LaneBase = (DstIdx / LaneElts) * LaneElts;
13242 unsigned LaneIdx = DstIdx % LaneElts;
13243 if (LaneIdx < HalfSize) {
13244 unsigned Sel = (Mask >> (2 * LaneIdx)) & 0x3;
13245 return std::make_pair(0, static_cast<int>(LaneBase + Sel));
13246 }
13247 return std::make_pair(0, static_cast<int>(DstIdx));
13248 }))
13249 return false;
13250 return Success(R, E);
13251 }
13252
13253 case X86::BI__builtin_ia32_pshufhw:
13254 case X86::BI__builtin_ia32_pshufhw256:
13255 case X86::BI__builtin_ia32_pshufhw512: {
13256 APValue R;
13257 if (!evalShuffleGeneric(
13258 Info, E, R,
13259 [](unsigned DstIdx, unsigned Mask) -> std::pair<unsigned, int> {
13260 constexpr unsigned LaneBits = 128u;
13261 constexpr unsigned ElemBits = 16u;
13262 constexpr unsigned LaneElts = LaneBits / ElemBits;
13263 constexpr unsigned HalfSize = 4;
13264 unsigned LaneBase = (DstIdx / LaneElts) * LaneElts;
13265 unsigned LaneIdx = DstIdx % LaneElts;
13266 if (LaneIdx >= HalfSize) {
13267 unsigned Rel = LaneIdx - HalfSize;
13268 unsigned Sel = (Mask >> (2 * Rel)) & 0x3;
13269 return std::make_pair(
13270 0, static_cast<int>(LaneBase + HalfSize + Sel));
13271 }
13272 return std::make_pair(0, static_cast<int>(DstIdx));
13273 }))
13274 return false;
13275 return Success(R, E);
13276 }
13277
13278 case X86::BI__builtin_ia32_pshufd:
13279 case X86::BI__builtin_ia32_pshufd256:
13280 case X86::BI__builtin_ia32_pshufd512:
13281 case X86::BI__builtin_ia32_vpermilps:
13282 case X86::BI__builtin_ia32_vpermilps256:
13283 case X86::BI__builtin_ia32_vpermilps512: {
13284 APValue R;
13285 if (!evalShuffleGeneric(
13286 Info, E, R,
13287 [](unsigned DstIdx, unsigned Mask) -> std::pair<unsigned, int> {
13288 constexpr unsigned LaneBits = 128u;
13289 constexpr unsigned ElemBits = 32u;
13290 constexpr unsigned LaneElts = LaneBits / ElemBits;
13291 unsigned LaneBase = (DstIdx / LaneElts) * LaneElts;
13292 unsigned LaneIdx = DstIdx % LaneElts;
13293 unsigned Sel = (Mask >> (2 * LaneIdx)) & 0x3;
13294 return std::make_pair(0, static_cast<int>(LaneBase + Sel));
13295 }))
13296 return false;
13297 return Success(R, E);
13298 }
13299
13300 case X86::BI__builtin_ia32_vpermilvarpd:
13301 case X86::BI__builtin_ia32_vpermilvarpd256:
13302 case X86::BI__builtin_ia32_vpermilvarpd512: {
13303 APValue R;
13304 if (!evalShuffleGeneric(
13305 Info, E, R,
13306 [](unsigned DstIdx, unsigned Mask) -> std::pair<unsigned, int> {
13307 unsigned NumElemPerLane = 2;
13308 unsigned Lane = DstIdx / NumElemPerLane;
13309 unsigned Offset = Mask & 0b10 ? 1 : 0;
13310 return std::make_pair(
13311 0, static_cast<int>(Lane * NumElemPerLane + Offset));
13312 }))
13313 return false;
13314 return Success(R, E);
13315 }
13316
13317 case X86::BI__builtin_ia32_vpermilpd:
13318 case X86::BI__builtin_ia32_vpermilpd256:
13319 case X86::BI__builtin_ia32_vpermilpd512: {
13320 APValue R;
13321 if (!evalShuffleGeneric(Info, E, R, [](unsigned DstIdx, unsigned Control) {
13322 unsigned NumElemPerLane = 2;
13323 unsigned BitsPerElem = 1;
13324 unsigned MaskBits = 8;
13325 unsigned IndexMask = 0x1;
13326 unsigned Lane = DstIdx / NumElemPerLane;
13327 unsigned LaneOffset = Lane * NumElemPerLane;
13328 unsigned BitIndex = (DstIdx * BitsPerElem) % MaskBits;
13329 unsigned Index = (Control >> BitIndex) & IndexMask;
13330 return std::make_pair(0, static_cast<int>(LaneOffset + Index));
13331 }))
13332 return false;
13333 return Success(R, E);
13334 }
13335
13336 case X86::BI__builtin_ia32_permdf256:
13337 case X86::BI__builtin_ia32_permdi256: {
13338 APValue R;
13339 if (!evalShuffleGeneric(Info, E, R, [](unsigned DstIdx, unsigned Control) {
13340 // permute4x64 operates on 4 64-bit elements
13341 // For element i (0-3), extract bits [2*i+1:2*i] from Control
13342 unsigned Index = (Control >> (2 * DstIdx)) & 0x3;
13343 return std::make_pair(0, static_cast<int>(Index));
13344 }))
13345 return false;
13346 return Success(R, E);
13347 }
13348
13349 case X86::BI__builtin_ia32_vpermilvarps:
13350 case X86::BI__builtin_ia32_vpermilvarps256:
13351 case X86::BI__builtin_ia32_vpermilvarps512: {
13352 APValue R;
13353 if (!evalShuffleGeneric(
13354 Info, E, R,
13355 [](unsigned DstIdx, unsigned Mask) -> std::pair<unsigned, int> {
13356 unsigned NumElemPerLane = 4;
13357 unsigned Lane = DstIdx / NumElemPerLane;
13358 unsigned Offset = Mask & 0b11;
13359 return std::make_pair(
13360 0, static_cast<int>(Lane * NumElemPerLane + Offset));
13361 }))
13362 return false;
13363 return Success(R, E);
13364 }
13365
13366 case X86::BI__builtin_ia32_vpmultishiftqb128:
13367 case X86::BI__builtin_ia32_vpmultishiftqb256:
13368 case X86::BI__builtin_ia32_vpmultishiftqb512: {
13369 assert(E->getNumArgs() == 2);
13370
13371 APValue A, B;
13372 if (!Evaluate(A, Info, E->getArg(0)) || !Evaluate(B, Info, E->getArg(1)))
13373 return false;
13374
13375 assert(A.getVectorLength() == B.getVectorLength());
13376 unsigned NumBytesInQWord = 8;
13377 unsigned NumBitsInByte = 8;
13378 unsigned NumBytes = A.getVectorLength();
13379 unsigned NumQWords = NumBytes / NumBytesInQWord;
13381 Result.reserve(NumBytes);
13382
13383 for (unsigned QWordId = 0; QWordId != NumQWords; ++QWordId) {
13384 APInt BQWord(64, 0);
13385 for (unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
13386 unsigned Idx = QWordId * NumBytesInQWord + ByteIdx;
13387 uint64_t Byte = B.getVectorElt(Idx).getInt().getZExtValue();
13388 BQWord.insertBits(APInt(8, Byte & 0xFF), ByteIdx * NumBitsInByte);
13389 }
13390
13391 for (unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
13392 unsigned Idx = QWordId * NumBytesInQWord + ByteIdx;
13393 uint64_t Ctrl = A.getVectorElt(Idx).getInt().getZExtValue() & 0x3F;
13394
13395 APInt Byte(8, 0);
13396 for (unsigned BitIdx = 0; BitIdx != NumBitsInByte; ++BitIdx) {
13397 Byte.setBitVal(BitIdx, BQWord[(Ctrl + BitIdx) & 0x3F]);
13398 }
13399 Result.push_back(APValue(APSInt(Byte, /*isUnsigned*/ true)));
13400 }
13401 }
13402 return Success(APValue(Result.data(), Result.size()), E);
13403 }
13404
13405 case X86::BI__builtin_ia32_phminposuw128: {
13406 APValue Source;
13407 if (!Evaluate(Source, Info, E->getArg(0)))
13408 return false;
13409 unsigned SourceLen = Source.getVectorLength();
13410 const VectorType *VT = E->getArg(0)->getType()->castAs<VectorType>();
13411 QualType ElemQT = VT->getElementType();
13412 unsigned ElemBitWidth = Info.Ctx.getTypeSize(ElemQT);
13413
13414 APInt MinIndex(ElemBitWidth, 0);
13415 APInt MinVal = Source.getVectorElt(0).getInt();
13416 for (unsigned I = 1; I != SourceLen; ++I) {
13417 APInt Val = Source.getVectorElt(I).getInt();
13418 if (MinVal.ugt(Val)) {
13419 MinVal = Val;
13420 MinIndex = I;
13421 }
13422 }
13423
13424 bool ResultUnsigned = E->getCallReturnType(Info.Ctx)
13425 ->castAs<VectorType>()
13426 ->getElementType()
13427 ->isUnsignedIntegerOrEnumerationType();
13428
13430 Result.reserve(SourceLen);
13431 Result.emplace_back(APSInt(MinVal, ResultUnsigned));
13432 Result.emplace_back(APSInt(MinIndex, ResultUnsigned));
13433 for (unsigned I = 0; I != SourceLen - 2; ++I) {
13434 Result.emplace_back(APSInt(APInt(ElemBitWidth, 0), ResultUnsigned));
13435 }
13436 return Success(APValue(Result.data(), Result.size()), E);
13437 }
13438
13439 case X86::BI__builtin_ia32_psraq128:
13440 case X86::BI__builtin_ia32_psraq256:
13441 case X86::BI__builtin_ia32_psraq512:
13442 case X86::BI__builtin_ia32_psrad128:
13443 case X86::BI__builtin_ia32_psrad256:
13444 case X86::BI__builtin_ia32_psrad512:
13445 case X86::BI__builtin_ia32_psraw128:
13446 case X86::BI__builtin_ia32_psraw256:
13447 case X86::BI__builtin_ia32_psraw512: {
13448 APValue R;
13449 if (!evalShiftWithCount(
13450 Info, E, R,
13451 [](const APInt &Elt, uint64_t Count) { return Elt.ashr(Count); },
13452 [](const APInt &Elt, unsigned Width) {
13453 return Elt.ashr(Width - 1);
13454 }))
13455 return false;
13456 return Success(R, E);
13457 }
13458
13459 case X86::BI__builtin_ia32_psllq128:
13460 case X86::BI__builtin_ia32_psllq256:
13461 case X86::BI__builtin_ia32_psllq512:
13462 case X86::BI__builtin_ia32_pslld128:
13463 case X86::BI__builtin_ia32_pslld256:
13464 case X86::BI__builtin_ia32_pslld512:
13465 case X86::BI__builtin_ia32_psllw128:
13466 case X86::BI__builtin_ia32_psllw256:
13467 case X86::BI__builtin_ia32_psllw512: {
13468 APValue R;
13469 if (!evalShiftWithCount(
13470 Info, E, R,
13471 [](const APInt &Elt, uint64_t Count) { return Elt.shl(Count); },
13472 [](const APInt &Elt, unsigned Width) {
13473 return APInt::getZero(Width);
13474 }))
13475 return false;
13476 return Success(R, E);
13477 }
13478
13479 case X86::BI__builtin_ia32_psrlq128:
13480 case X86::BI__builtin_ia32_psrlq256:
13481 case X86::BI__builtin_ia32_psrlq512:
13482 case X86::BI__builtin_ia32_psrld128:
13483 case X86::BI__builtin_ia32_psrld256:
13484 case X86::BI__builtin_ia32_psrld512:
13485 case X86::BI__builtin_ia32_psrlw128:
13486 case X86::BI__builtin_ia32_psrlw256:
13487 case X86::BI__builtin_ia32_psrlw512: {
13488 APValue R;
13489 if (!evalShiftWithCount(
13490 Info, E, R,
13491 [](const APInt &Elt, uint64_t Count) { return Elt.lshr(Count); },
13492 [](const APInt &Elt, unsigned Width) {
13493 return APInt::getZero(Width);
13494 }))
13495 return false;
13496 return Success(R, E);
13497 }
13498
13499 case X86::BI__builtin_ia32_pternlogd128_mask:
13500 case X86::BI__builtin_ia32_pternlogd256_mask:
13501 case X86::BI__builtin_ia32_pternlogd512_mask:
13502 case X86::BI__builtin_ia32_pternlogq128_mask:
13503 case X86::BI__builtin_ia32_pternlogq256_mask:
13504 case X86::BI__builtin_ia32_pternlogq512_mask: {
13505 APValue AValue, BValue, CValue, ImmValue, UValue;
13506 if (!EvaluateAsRValue(Info, E->getArg(0), AValue) ||
13507 !EvaluateAsRValue(Info, E->getArg(1), BValue) ||
13508 !EvaluateAsRValue(Info, E->getArg(2), CValue) ||
13509 !EvaluateAsRValue(Info, E->getArg(3), ImmValue) ||
13510 !EvaluateAsRValue(Info, E->getArg(4), UValue))
13511 return false;
13512
13513 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
13514 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
13515 APInt Imm = ImmValue.getInt();
13516 APInt U = UValue.getInt();
13517 unsigned ResultLen = AValue.getVectorLength();
13518 SmallVector<APValue, 16> ResultElements;
13519 ResultElements.reserve(ResultLen);
13520
13521 for (unsigned EltNum = 0; EltNum < ResultLen; ++EltNum) {
13522 APInt ALane = AValue.getVectorElt(EltNum).getInt();
13523 APInt BLane = BValue.getVectorElt(EltNum).getInt();
13524 APInt CLane = CValue.getVectorElt(EltNum).getInt();
13525
13526 if (U[EltNum]) {
13527 unsigned BitWidth = ALane.getBitWidth();
13528 APInt ResLane(BitWidth, 0);
13529
13530 for (unsigned Bit = 0; Bit < BitWidth; ++Bit) {
13531 unsigned ABit = ALane[Bit];
13532 unsigned BBit = BLane[Bit];
13533 unsigned CBit = CLane[Bit];
13534
13535 unsigned Idx = (ABit << 2) | (BBit << 1) | CBit;
13536 ResLane.setBitVal(Bit, Imm[Idx]);
13537 }
13538 ResultElements.push_back(APValue(APSInt(ResLane, DestUnsigned)));
13539 } else {
13540 ResultElements.push_back(APValue(APSInt(ALane, DestUnsigned)));
13541 }
13542 }
13543 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13544 }
13545 case X86::BI__builtin_ia32_pternlogd128_maskz:
13546 case X86::BI__builtin_ia32_pternlogd256_maskz:
13547 case X86::BI__builtin_ia32_pternlogd512_maskz:
13548 case X86::BI__builtin_ia32_pternlogq128_maskz:
13549 case X86::BI__builtin_ia32_pternlogq256_maskz:
13550 case X86::BI__builtin_ia32_pternlogq512_maskz: {
13551 APValue AValue, BValue, CValue, ImmValue, UValue;
13552 if (!EvaluateAsRValue(Info, E->getArg(0), AValue) ||
13553 !EvaluateAsRValue(Info, E->getArg(1), BValue) ||
13554 !EvaluateAsRValue(Info, E->getArg(2), CValue) ||
13555 !EvaluateAsRValue(Info, E->getArg(3), ImmValue) ||
13556 !EvaluateAsRValue(Info, E->getArg(4), UValue))
13557 return false;
13558
13559 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
13560 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
13561 APInt Imm = ImmValue.getInt();
13562 APInt U = UValue.getInt();
13563 unsigned ResultLen = AValue.getVectorLength();
13564 SmallVector<APValue, 16> ResultElements;
13565 ResultElements.reserve(ResultLen);
13566
13567 for (unsigned EltNum = 0; EltNum < ResultLen; ++EltNum) {
13568 APInt ALane = AValue.getVectorElt(EltNum).getInt();
13569 APInt BLane = BValue.getVectorElt(EltNum).getInt();
13570 APInt CLane = CValue.getVectorElt(EltNum).getInt();
13571
13572 unsigned BitWidth = ALane.getBitWidth();
13573 APInt ResLane(BitWidth, 0);
13574
13575 if (U[EltNum]) {
13576 for (unsigned Bit = 0; Bit < BitWidth; ++Bit) {
13577 unsigned ABit = ALane[Bit];
13578 unsigned BBit = BLane[Bit];
13579 unsigned CBit = CLane[Bit];
13580
13581 unsigned Idx = (ABit << 2) | (BBit << 1) | CBit;
13582 ResLane.setBitVal(Bit, Imm[Idx]);
13583 }
13584 }
13585 ResultElements.push_back(APValue(APSInt(ResLane, DestUnsigned)));
13586 }
13587 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13588 }
13589
13590 case Builtin::BI__builtin_elementwise_clzg:
13591 case Builtin::BI__builtin_elementwise_ctzg: {
13592 APValue SourceLHS;
13593 std::optional<APValue> Fallback;
13594 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS))
13595 return false;
13596 if (E->getNumArgs() > 1) {
13597 APValue FallbackTmp;
13598 if (!EvaluateAsRValue(Info, E->getArg(1), FallbackTmp))
13599 return false;
13600 Fallback = FallbackTmp;
13601 }
13602
13603 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
13604 unsigned SourceLen = SourceLHS.getVectorLength();
13605 SmallVector<APValue, 4> ResultElements;
13606 ResultElements.reserve(SourceLen);
13607
13608 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
13609 APSInt LHS = SourceLHS.getVectorElt(EltNum).getInt();
13610 if (!LHS) {
13611 // Without a fallback, a zero element is undefined
13612 if (!Fallback) {
13613 Info.FFDiag(E, diag::note_constexpr_countzeroes_zero)
13614 << /*IsTrailing=*/(E->getBuiltinCallee() ==
13615 Builtin::BI__builtin_elementwise_ctzg);
13616 return false;
13617 }
13618 ResultElements.push_back(Fallback->getVectorElt(EltNum));
13619 continue;
13620 }
13621 switch (E->getBuiltinCallee()) {
13622 case Builtin::BI__builtin_elementwise_clzg:
13623 ResultElements.push_back(APValue(
13624 APSInt(APInt(Info.Ctx.getIntWidth(DestEltTy), LHS.countl_zero()),
13625 DestEltTy->isUnsignedIntegerOrEnumerationType())));
13626 break;
13627 case Builtin::BI__builtin_elementwise_ctzg:
13628 ResultElements.push_back(APValue(
13629 APSInt(APInt(Info.Ctx.getIntWidth(DestEltTy), LHS.countr_zero()),
13630 DestEltTy->isUnsignedIntegerOrEnumerationType())));
13631 break;
13632 }
13633 }
13634
13635 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13636 }
13637
13638 case Builtin::BI__builtin_elementwise_fma: {
13639 APValue SourceX, SourceY, SourceZ;
13640 if (!EvaluateAsRValue(Info, E->getArg(0), SourceX) ||
13641 !EvaluateAsRValue(Info, E->getArg(1), SourceY) ||
13642 !EvaluateAsRValue(Info, E->getArg(2), SourceZ))
13643 return false;
13644
13645 unsigned SourceLen = SourceX.getVectorLength();
13646 SmallVector<APValue> ResultElements;
13647 ResultElements.reserve(SourceLen);
13648 llvm::RoundingMode RM = getActiveRoundingMode(getEvalInfo(), E);
13649 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
13650 const APFloat &X = SourceX.getVectorElt(EltNum).getFloat();
13651 const APFloat &Y = SourceY.getVectorElt(EltNum).getFloat();
13652 const APFloat &Z = SourceZ.getVectorElt(EltNum).getFloat();
13653 APFloat Result(X);
13654 (void)Result.fusedMultiplyAdd(Y, Z, RM);
13655 ResultElements.push_back(APValue(Result));
13656 }
13657 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13658 }
13659
13660 case clang::X86::BI__builtin_ia32_phaddw128:
13661 case clang::X86::BI__builtin_ia32_phaddw256:
13662 case clang::X86::BI__builtin_ia32_phaddd128:
13663 case clang::X86::BI__builtin_ia32_phaddd256:
13664 case clang::X86::BI__builtin_ia32_phaddsw128:
13665 case clang::X86::BI__builtin_ia32_phaddsw256:
13666
13667 case clang::X86::BI__builtin_ia32_phsubw128:
13668 case clang::X86::BI__builtin_ia32_phsubw256:
13669 case clang::X86::BI__builtin_ia32_phsubd128:
13670 case clang::X86::BI__builtin_ia32_phsubd256:
13671 case clang::X86::BI__builtin_ia32_phsubsw128:
13672 case clang::X86::BI__builtin_ia32_phsubsw256: {
13673 APValue SourceLHS, SourceRHS;
13674 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
13675 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
13676 return false;
13677 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
13678 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
13679
13680 unsigned NumElts = SourceLHS.getVectorLength();
13681 unsigned EltBits = Info.Ctx.getIntWidth(DestEltTy);
13682 unsigned EltsPerLane = 128 / EltBits;
13683 SmallVector<APValue, 4> ResultElements;
13684 ResultElements.reserve(NumElts);
13685
13686 for (unsigned LaneStart = 0; LaneStart != NumElts;
13687 LaneStart += EltsPerLane) {
13688 for (unsigned I = 0; I != EltsPerLane; I += 2) {
13689 APSInt LHSA = SourceLHS.getVectorElt(LaneStart + I).getInt();
13690 APSInt LHSB = SourceLHS.getVectorElt(LaneStart + I + 1).getInt();
13691 switch (E->getBuiltinCallee()) {
13692 case clang::X86::BI__builtin_ia32_phaddw128:
13693 case clang::X86::BI__builtin_ia32_phaddw256:
13694 case clang::X86::BI__builtin_ia32_phaddd128:
13695 case clang::X86::BI__builtin_ia32_phaddd256: {
13696 APSInt Res(LHSA + LHSB, DestUnsigned);
13697 ResultElements.push_back(APValue(Res));
13698 break;
13699 }
13700 case clang::X86::BI__builtin_ia32_phaddsw128:
13701 case clang::X86::BI__builtin_ia32_phaddsw256: {
13702 APSInt Res(LHSA.sadd_sat(LHSB));
13703 ResultElements.push_back(APValue(Res));
13704 break;
13705 }
13706 case clang::X86::BI__builtin_ia32_phsubw128:
13707 case clang::X86::BI__builtin_ia32_phsubw256:
13708 case clang::X86::BI__builtin_ia32_phsubd128:
13709 case clang::X86::BI__builtin_ia32_phsubd256: {
13710 APSInt Res(LHSA - LHSB, DestUnsigned);
13711 ResultElements.push_back(APValue(Res));
13712 break;
13713 }
13714 case clang::X86::BI__builtin_ia32_phsubsw128:
13715 case clang::X86::BI__builtin_ia32_phsubsw256: {
13716 APSInt Res(LHSA.ssub_sat(LHSB));
13717 ResultElements.push_back(APValue(Res));
13718 break;
13719 }
13720 }
13721 }
13722 for (unsigned I = 0; I != EltsPerLane; I += 2) {
13723 APSInt RHSA = SourceRHS.getVectorElt(LaneStart + I).getInt();
13724 APSInt RHSB = SourceRHS.getVectorElt(LaneStart + I + 1).getInt();
13725 switch (E->getBuiltinCallee()) {
13726 case clang::X86::BI__builtin_ia32_phaddw128:
13727 case clang::X86::BI__builtin_ia32_phaddw256:
13728 case clang::X86::BI__builtin_ia32_phaddd128:
13729 case clang::X86::BI__builtin_ia32_phaddd256: {
13730 APSInt Res(RHSA + RHSB, DestUnsigned);
13731 ResultElements.push_back(APValue(Res));
13732 break;
13733 }
13734 case clang::X86::BI__builtin_ia32_phaddsw128:
13735 case clang::X86::BI__builtin_ia32_phaddsw256: {
13736 APSInt Res(RHSA.sadd_sat(RHSB));
13737 ResultElements.push_back(APValue(Res));
13738 break;
13739 }
13740 case clang::X86::BI__builtin_ia32_phsubw128:
13741 case clang::X86::BI__builtin_ia32_phsubw256:
13742 case clang::X86::BI__builtin_ia32_phsubd128:
13743 case clang::X86::BI__builtin_ia32_phsubd256: {
13744 APSInt Res(RHSA - RHSB, DestUnsigned);
13745 ResultElements.push_back(APValue(Res));
13746 break;
13747 }
13748 case clang::X86::BI__builtin_ia32_phsubsw128:
13749 case clang::X86::BI__builtin_ia32_phsubsw256: {
13750 APSInt Res(RHSA.ssub_sat(RHSB));
13751 ResultElements.push_back(APValue(Res));
13752 break;
13753 }
13754 }
13755 }
13756 }
13757 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13758 }
13759 case clang::X86::BI__builtin_ia32_haddpd:
13760 case clang::X86::BI__builtin_ia32_haddps:
13761 case clang::X86::BI__builtin_ia32_haddps256:
13762 case clang::X86::BI__builtin_ia32_haddpd256:
13763 case clang::X86::BI__builtin_ia32_hsubpd:
13764 case clang::X86::BI__builtin_ia32_hsubps:
13765 case clang::X86::BI__builtin_ia32_hsubps256:
13766 case clang::X86::BI__builtin_ia32_hsubpd256: {
13767 APValue SourceLHS, SourceRHS;
13768 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
13769 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
13770 return false;
13771 unsigned NumElts = SourceLHS.getVectorLength();
13772 SmallVector<APValue, 4> ResultElements;
13773 ResultElements.reserve(NumElts);
13774 llvm::RoundingMode RM = getActiveRoundingMode(getEvalInfo(), E);
13775 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
13776 unsigned EltBits = Info.Ctx.getTypeSize(DestEltTy);
13777 unsigned NumLanes = NumElts * EltBits / 128;
13778 unsigned NumElemsPerLane = NumElts / NumLanes;
13779 unsigned HalfElemsPerLane = NumElemsPerLane / 2;
13780
13781 for (unsigned L = 0; L != NumElts; L += NumElemsPerLane) {
13782 for (unsigned I = 0; I != HalfElemsPerLane; ++I) {
13783 APFloat LHSA = SourceLHS.getVectorElt(L + (2 * I) + 0).getFloat();
13784 APFloat LHSB = SourceLHS.getVectorElt(L + (2 * I) + 1).getFloat();
13785 switch (E->getBuiltinCallee()) {
13786 case clang::X86::BI__builtin_ia32_haddpd:
13787 case clang::X86::BI__builtin_ia32_haddps:
13788 case clang::X86::BI__builtin_ia32_haddps256:
13789 case clang::X86::BI__builtin_ia32_haddpd256:
13790 LHSA.add(LHSB, RM);
13791 break;
13792 case clang::X86::BI__builtin_ia32_hsubpd:
13793 case clang::X86::BI__builtin_ia32_hsubps:
13794 case clang::X86::BI__builtin_ia32_hsubps256:
13795 case clang::X86::BI__builtin_ia32_hsubpd256:
13796 LHSA.subtract(LHSB, RM);
13797 break;
13798 }
13799 ResultElements.push_back(APValue(LHSA));
13800 }
13801 for (unsigned I = 0; I != HalfElemsPerLane; ++I) {
13802 APFloat RHSA = SourceRHS.getVectorElt(L + (2 * I) + 0).getFloat();
13803 APFloat RHSB = SourceRHS.getVectorElt(L + (2 * I) + 1).getFloat();
13804 switch (E->getBuiltinCallee()) {
13805 case clang::X86::BI__builtin_ia32_haddpd:
13806 case clang::X86::BI__builtin_ia32_haddps:
13807 case clang::X86::BI__builtin_ia32_haddps256:
13808 case clang::X86::BI__builtin_ia32_haddpd256:
13809 RHSA.add(RHSB, RM);
13810 break;
13811 case clang::X86::BI__builtin_ia32_hsubpd:
13812 case clang::X86::BI__builtin_ia32_hsubps:
13813 case clang::X86::BI__builtin_ia32_hsubps256:
13814 case clang::X86::BI__builtin_ia32_hsubpd256:
13815 RHSA.subtract(RHSB, RM);
13816 break;
13817 }
13818 ResultElements.push_back(APValue(RHSA));
13819 }
13820 }
13821 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13822 }
13823 case clang::X86::BI__builtin_ia32_addsubpd:
13824 case clang::X86::BI__builtin_ia32_addsubps:
13825 case clang::X86::BI__builtin_ia32_addsubpd256:
13826 case clang::X86::BI__builtin_ia32_addsubps256: {
13827 // Addsub: alternates between subtraction and addition
13828 // Result[i] = (i % 2 == 0) ? (a[i] - b[i]) : (a[i] + b[i])
13829 APValue SourceLHS, SourceRHS;
13830 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
13831 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
13832 return false;
13833 unsigned NumElems = SourceLHS.getVectorLength();
13834 SmallVector<APValue, 8> ResultElements;
13835 ResultElements.reserve(NumElems);
13836 llvm::RoundingMode RM = getActiveRoundingMode(getEvalInfo(), E);
13837
13838 for (unsigned I = 0; I != NumElems; ++I) {
13839 APFloat LHS = SourceLHS.getVectorElt(I).getFloat();
13840 APFloat RHS = SourceRHS.getVectorElt(I).getFloat();
13841 if (I % 2 == 0) {
13842 // Even indices: subtract
13843 LHS.subtract(RHS, RM);
13844 } else {
13845 // Odd indices: add
13846 LHS.add(RHS, RM);
13847 }
13848 ResultElements.push_back(APValue(LHS));
13849 }
13850 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13851 }
13852 case clang::X86::BI__builtin_ia32_pclmulqdq128:
13853 case clang::X86::BI__builtin_ia32_pclmulqdq256:
13854 case clang::X86::BI__builtin_ia32_pclmulqdq512: {
13855 // PCLMULQDQ: carry-less multiplication of selected 64-bit halves
13856 // imm8 bit 0: selects lower (0) or upper (1) 64 bits of first operand
13857 // imm8 bit 4: selects lower (0) or upper (1) 64 bits of second operand
13858 APValue SourceLHS, SourceRHS;
13859 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
13860 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
13861 return false;
13862
13863 APSInt Imm8;
13864 if (!EvaluateInteger(E->getArg(2), Imm8, Info))
13865 return false;
13866
13867 // Extract bits 0 and 4 from imm8
13868 bool SelectUpperA = (Imm8 & 0x01) != 0;
13869 bool SelectUpperB = (Imm8 & 0x10) != 0;
13870
13871 unsigned NumElems = SourceLHS.getVectorLength();
13872 SmallVector<APValue, 8> ResultElements;
13873 ResultElements.reserve(NumElems);
13874 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
13875 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
13876
13877 // Process each 128-bit lane
13878 for (unsigned Lane = 0; Lane < NumElems; Lane += 2) {
13879 // Get the two 64-bit halves of the first operand
13880 APSInt A0 = SourceLHS.getVectorElt(Lane + 0).getInt();
13881 APSInt A1 = SourceLHS.getVectorElt(Lane + 1).getInt();
13882 // Get the two 64-bit halves of the second operand
13883 APSInt B0 = SourceRHS.getVectorElt(Lane + 0).getInt();
13884 APSInt B1 = SourceRHS.getVectorElt(Lane + 1).getInt();
13885
13886 // Select the appropriate 64-bit values based on imm8
13887 APInt A = SelectUpperA ? A1 : A0;
13888 APInt B = SelectUpperB ? B1 : B0;
13889
13890 // Extend both operands to 128 bits for carry-less multiplication
13891 APInt A128 = A.zext(128);
13892 APInt B128 = B.zext(128);
13893
13894 // Use APIntOps::clmul for carry-less multiplication
13895 APInt Result = llvm::APIntOps::clmul(A128, B128);
13896
13897 // Split the 128-bit result into two 64-bit halves
13898 APSInt ResultLow(Result.extractBits(64, 0), DestUnsigned);
13899 APSInt ResultHigh(Result.extractBits(64, 64), DestUnsigned);
13900
13901 ResultElements.push_back(APValue(ResultLow));
13902 ResultElements.push_back(APValue(ResultHigh));
13903 }
13904
13905 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13906 }
13907 case Builtin::BI__builtin_elementwise_fshl:
13908 case Builtin::BI__builtin_elementwise_fshr: {
13909 APValue SourceHi, SourceLo, SourceShift;
13910 if (!EvaluateAsRValue(Info, E->getArg(0), SourceHi) ||
13911 !EvaluateAsRValue(Info, E->getArg(1), SourceLo) ||
13912 !EvaluateAsRValue(Info, E->getArg(2), SourceShift))
13913 return false;
13914
13915 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
13916 if (!DestEltTy->isIntegerType())
13917 return false;
13918
13919 unsigned SourceLen = SourceHi.getVectorLength();
13920 SmallVector<APValue> ResultElements;
13921 ResultElements.reserve(SourceLen);
13922 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
13923 const APSInt &Hi = SourceHi.getVectorElt(EltNum).getInt();
13924 const APSInt &Lo = SourceLo.getVectorElt(EltNum).getInt();
13925 const APSInt &Shift = SourceShift.getVectorElt(EltNum).getInt();
13926 switch (E->getBuiltinCallee()) {
13927 case Builtin::BI__builtin_elementwise_fshl:
13928 ResultElements.push_back(APValue(
13929 APSInt(llvm::APIntOps::fshl(Hi, Lo, Shift), Hi.isUnsigned())));
13930 break;
13931 case Builtin::BI__builtin_elementwise_fshr:
13932 ResultElements.push_back(APValue(
13933 APSInt(llvm::APIntOps::fshr(Hi, Lo, Shift), Hi.isUnsigned())));
13934 break;
13935 }
13936 }
13937
13938 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13939 }
13940
13941 case X86::BI__builtin_ia32_shuf_f32x4_256:
13942 case X86::BI__builtin_ia32_shuf_i32x4_256:
13943 case X86::BI__builtin_ia32_shuf_f64x2_256:
13944 case X86::BI__builtin_ia32_shuf_i64x2_256:
13945 case X86::BI__builtin_ia32_shuf_f32x4:
13946 case X86::BI__builtin_ia32_shuf_i32x4:
13947 case X86::BI__builtin_ia32_shuf_f64x2:
13948 case X86::BI__builtin_ia32_shuf_i64x2: {
13949 APValue SourceA, SourceB;
13950 if (!EvaluateAsRValue(Info, E->getArg(0), SourceA) ||
13951 !EvaluateAsRValue(Info, E->getArg(1), SourceB))
13952 return false;
13953
13954 APSInt Imm;
13955 if (!EvaluateInteger(E->getArg(2), Imm, Info))
13956 return false;
13957
13958 // Destination and sources A, B all have the same type.
13959 unsigned NumElems = SourceA.getVectorLength();
13960 const VectorType *VT = E->getArg(0)->getType()->castAs<VectorType>();
13961 QualType ElemQT = VT->getElementType();
13962 unsigned ElemBits = Info.Ctx.getTypeSize(ElemQT);
13963 unsigned LaneBits = 128u;
13964 unsigned NumLanes = (NumElems * ElemBits) / LaneBits;
13965 unsigned NumElemsPerLane = LaneBits / ElemBits;
13966
13967 unsigned DstLen = SourceA.getVectorLength();
13968 SmallVector<APValue, 16> ResultElements;
13969 ResultElements.reserve(DstLen);
13970
13971 APValue R;
13972 if (!evalShuffleGeneric(
13973 Info, E, R,
13974 [NumLanes, NumElemsPerLane](unsigned DstIdx, unsigned ShuffleMask)
13975 -> std::pair<unsigned, int> {
13976 // DstIdx determines source. ShuffleMask selects lane in source.
13977 unsigned BitsPerElem = NumLanes / 2;
13978 unsigned IndexMask = (1u << BitsPerElem) - 1;
13979 unsigned Lane = DstIdx / NumElemsPerLane;
13980 unsigned SrcIdx = (Lane < NumLanes / 2) ? 0 : 1;
13981 unsigned BitIdx = BitsPerElem * Lane;
13982 unsigned SrcLaneIdx = (ShuffleMask >> BitIdx) & IndexMask;
13983 unsigned ElemInLane = DstIdx % NumElemsPerLane;
13984 unsigned IdxToPick = SrcLaneIdx * NumElemsPerLane + ElemInLane;
13985 return {SrcIdx, IdxToPick};
13986 }))
13987 return false;
13988 return Success(R, E);
13989 }
13990
13991 case X86::BI__builtin_ia32_vgf2p8affineinvqb_v16qi:
13992 case X86::BI__builtin_ia32_vgf2p8affineinvqb_v32qi:
13993 case X86::BI__builtin_ia32_vgf2p8affineinvqb_v64qi:
13994 case X86::BI__builtin_ia32_vgf2p8affineqb_v16qi:
13995 case X86::BI__builtin_ia32_vgf2p8affineqb_v32qi:
13996 case X86::BI__builtin_ia32_vgf2p8affineqb_v64qi: {
13997
13998 APValue X, A;
13999 APSInt Imm;
14000 if (!EvaluateAsRValue(Info, E->getArg(0), X) ||
14001 !EvaluateAsRValue(Info, E->getArg(1), A) ||
14002 !EvaluateInteger(E->getArg(2), Imm, Info))
14003 return false;
14004
14005 assert(X.isVector() && A.isVector());
14006 assert(X.getVectorLength() == A.getVectorLength());
14007
14008 bool IsInverse = false;
14009 switch (E->getBuiltinCallee()) {
14010 case X86::BI__builtin_ia32_vgf2p8affineinvqb_v16qi:
14011 case X86::BI__builtin_ia32_vgf2p8affineinvqb_v32qi:
14012 case X86::BI__builtin_ia32_vgf2p8affineinvqb_v64qi: {
14013 IsInverse = true;
14014 }
14015 }
14016
14017 unsigned NumBitsInByte = 8;
14018 unsigned NumBytesInQWord = 8;
14019 unsigned NumBitsInQWord = 64;
14020 unsigned NumBytes = A.getVectorLength();
14021 unsigned NumQWords = NumBytes / NumBytesInQWord;
14023 Result.reserve(NumBytes);
14024
14025 // computing A*X + Imm
14026 for (unsigned QWordIdx = 0; QWordIdx != NumQWords; ++QWordIdx) {
14027 // Extract the QWords from X, A
14028 APInt XQWord(NumBitsInQWord, 0);
14029 APInt AQWord(NumBitsInQWord, 0);
14030 for (unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
14031 unsigned Idx = QWordIdx * NumBytesInQWord + ByteIdx;
14032 APInt XByte = X.getVectorElt(Idx).getInt();
14033 APInt AByte = A.getVectorElt(Idx).getInt();
14034 XQWord.insertBits(XByte, ByteIdx * NumBitsInByte);
14035 AQWord.insertBits(AByte, ByteIdx * NumBitsInByte);
14036 }
14037
14038 for (unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
14039 uint8_t XByte =
14040 XQWord.lshr(ByteIdx * NumBitsInByte).getLoBits(8).getZExtValue();
14041 Result.push_back(APValue(APSInt(
14042 APInt(8, GFNIAffine(XByte, AQWord, Imm, IsInverse)), false)));
14043 }
14044 }
14045
14046 return Success(APValue(Result.data(), Result.size()), E);
14047 }
14048
14049 case X86::BI__builtin_ia32_vgf2p8mulb_v16qi:
14050 case X86::BI__builtin_ia32_vgf2p8mulb_v32qi:
14051 case X86::BI__builtin_ia32_vgf2p8mulb_v64qi: {
14052 APValue A, B;
14053 if (!EvaluateAsRValue(Info, E->getArg(0), A) ||
14054 !EvaluateAsRValue(Info, E->getArg(1), B))
14055 return false;
14056
14057 assert(A.isVector() && B.isVector());
14058 assert(A.getVectorLength() == B.getVectorLength());
14059
14060 unsigned NumBytes = A.getVectorLength();
14062 Result.reserve(NumBytes);
14063
14064 for (unsigned ByteIdx = 0; ByteIdx != NumBytes; ++ByteIdx) {
14065 uint8_t AByte = A.getVectorElt(ByteIdx).getInt().getZExtValue();
14066 uint8_t BByte = B.getVectorElt(ByteIdx).getInt().getZExtValue();
14067 Result.push_back(APValue(
14068 APSInt(APInt(8, GFNIMul(AByte, BByte)), /*IsUnsigned=*/false)));
14069 }
14070
14071 return Success(APValue(Result.data(), Result.size()), E);
14072 }
14073
14074 case X86::BI__builtin_ia32_insertf32x4_256:
14075 case X86::BI__builtin_ia32_inserti32x4_256:
14076 case X86::BI__builtin_ia32_insertf64x2_256:
14077 case X86::BI__builtin_ia32_inserti64x2_256:
14078 case X86::BI__builtin_ia32_insertf32x4:
14079 case X86::BI__builtin_ia32_inserti32x4:
14080 case X86::BI__builtin_ia32_insertf64x2_512:
14081 case X86::BI__builtin_ia32_inserti64x2_512:
14082 case X86::BI__builtin_ia32_insertf32x8:
14083 case X86::BI__builtin_ia32_inserti32x8:
14084 case X86::BI__builtin_ia32_insertf64x4:
14085 case X86::BI__builtin_ia32_inserti64x4:
14086 case X86::BI__builtin_ia32_vinsertf128_ps256:
14087 case X86::BI__builtin_ia32_vinsertf128_pd256:
14088 case X86::BI__builtin_ia32_vinsertf128_si256:
14089 case X86::BI__builtin_ia32_insert128i256: {
14090 APValue SourceDst, SourceSub;
14091 if (!EvaluateAsRValue(Info, E->getArg(0), SourceDst) ||
14092 !EvaluateAsRValue(Info, E->getArg(1), SourceSub))
14093 return false;
14094
14095 APSInt Imm;
14096 if (!EvaluateInteger(E->getArg(2), Imm, Info))
14097 return false;
14098
14099 assert(SourceDst.isVector() && SourceSub.isVector());
14100 unsigned DstLen = SourceDst.getVectorLength();
14101 unsigned SubLen = SourceSub.getVectorLength();
14102 assert(SubLen != 0 && DstLen != 0 && (DstLen % SubLen) == 0);
14103 unsigned NumLanes = DstLen / SubLen;
14104 unsigned LaneIdx = (Imm.getZExtValue() % NumLanes) * SubLen;
14105
14106 SmallVector<APValue, 16> ResultElements;
14107 ResultElements.reserve(DstLen);
14108
14109 for (unsigned EltNum = 0; EltNum < DstLen; ++EltNum) {
14110 if (EltNum >= LaneIdx && EltNum < LaneIdx + SubLen)
14111 ResultElements.push_back(SourceSub.getVectorElt(EltNum - LaneIdx));
14112 else
14113 ResultElements.push_back(SourceDst.getVectorElt(EltNum));
14114 }
14115
14116 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
14117 }
14118
14119 case clang::X86::BI__builtin_ia32_vec_set_v4hi:
14120 case clang::X86::BI__builtin_ia32_vec_set_v16qi:
14121 case clang::X86::BI__builtin_ia32_vec_set_v8hi:
14122 case clang::X86::BI__builtin_ia32_vec_set_v4si:
14123 case clang::X86::BI__builtin_ia32_vec_set_v2di:
14124 case clang::X86::BI__builtin_ia32_vec_set_v32qi:
14125 case clang::X86::BI__builtin_ia32_vec_set_v16hi:
14126 case clang::X86::BI__builtin_ia32_vec_set_v8si:
14127 case clang::X86::BI__builtin_ia32_vec_set_v4di: {
14128 APValue VecVal;
14129 APSInt Scalar, IndexAPS;
14130 if (!EvaluateVector(E->getArg(0), VecVal, Info) ||
14131 !EvaluateInteger(E->getArg(1), Scalar, Info) ||
14132 !EvaluateInteger(E->getArg(2), IndexAPS, Info))
14133 return false;
14134
14135 QualType ElemTy = E->getType()->castAs<VectorType>()->getElementType();
14136 unsigned ElemWidth = Info.Ctx.getIntWidth(ElemTy);
14137 bool ElemUnsigned = ElemTy->isUnsignedIntegerOrEnumerationType();
14138 Scalar.setIsUnsigned(ElemUnsigned);
14139 APSInt ElemAPS = Scalar.extOrTrunc(ElemWidth);
14140 APValue ElemAV(ElemAPS);
14141
14142 unsigned NumElems = VecVal.getVectorLength();
14143 unsigned Index =
14144 static_cast<unsigned>(IndexAPS.getZExtValue() & (NumElems - 1));
14145
14147 Elems.reserve(NumElems);
14148 for (unsigned ElemNum = 0; ElemNum != NumElems; ++ElemNum)
14149 Elems.push_back(ElemNum == Index ? ElemAV : VecVal.getVectorElt(ElemNum));
14150
14151 return Success(APValue(Elems.data(), NumElems), E);
14152 }
14153
14154 case X86::BI__builtin_ia32_pslldqi128_byteshift:
14155 case X86::BI__builtin_ia32_pslldqi256_byteshift:
14156 case X86::BI__builtin_ia32_pslldqi512_byteshift: {
14157 APValue R;
14158 if (!evalShuffleGeneric(
14159 Info, E, R,
14160 [](unsigned DstIdx, unsigned Shift) -> std::pair<unsigned, int> {
14161 unsigned LaneBase = (DstIdx / 16) * 16;
14162 unsigned LaneIdx = DstIdx % 16;
14163 if (LaneIdx < Shift)
14164 return std::make_pair(0, -1);
14165
14166 return std::make_pair(
14167 0, static_cast<int>(LaneBase + LaneIdx - Shift));
14168 }))
14169 return false;
14170 return Success(R, E);
14171 }
14172
14173 case X86::BI__builtin_ia32_psrldqi128_byteshift:
14174 case X86::BI__builtin_ia32_psrldqi256_byteshift:
14175 case X86::BI__builtin_ia32_psrldqi512_byteshift: {
14176 APValue R;
14177 if (!evalShuffleGeneric(
14178 Info, E, R,
14179 [](unsigned DstIdx, unsigned Shift) -> std::pair<unsigned, int> {
14180 unsigned LaneBase = (DstIdx / 16) * 16;
14181 unsigned LaneIdx = DstIdx % 16;
14182 if (LaneIdx + Shift < 16)
14183 return std::make_pair(
14184 0, static_cast<int>(LaneBase + LaneIdx + Shift));
14185
14186 return std::make_pair(0, -1);
14187 }))
14188 return false;
14189 return Success(R, E);
14190 }
14191
14192 case X86::BI__builtin_ia32_palignr128:
14193 case X86::BI__builtin_ia32_palignr256:
14194 case X86::BI__builtin_ia32_palignr512: {
14195 APValue R;
14196 if (!evalShuffleGeneric(Info, E, R, [](unsigned DstIdx, unsigned Shift) {
14197 // Default to -1 → zero-fill this destination element
14198 unsigned VecIdx = 1;
14199 int ElemIdx = -1;
14200
14201 int Lane = DstIdx / 16;
14202 int Offset = DstIdx % 16;
14203
14204 // Elements come from VecB first, then VecA after the shift boundary
14205 unsigned ShiftedIdx = Offset + (Shift & 0xFF);
14206 if (ShiftedIdx < 16) { // from VecB
14207 ElemIdx = ShiftedIdx + (Lane * 16);
14208 } else if (ShiftedIdx < 32) { // from VecA
14209 VecIdx = 0;
14210 ElemIdx = (ShiftedIdx - 16) + (Lane * 16);
14211 }
14212
14213 return std::pair<unsigned, int>{VecIdx, ElemIdx};
14214 }))
14215 return false;
14216 return Success(R, E);
14217 }
14218 case X86::BI__builtin_ia32_alignd128:
14219 case X86::BI__builtin_ia32_alignd256:
14220 case X86::BI__builtin_ia32_alignd512:
14221 case X86::BI__builtin_ia32_alignq128:
14222 case X86::BI__builtin_ia32_alignq256:
14223 case X86::BI__builtin_ia32_alignq512: {
14224 APValue R;
14225 unsigned NumElems = E->getType()->castAs<VectorType>()->getNumElements();
14226 if (!evalShuffleGeneric(Info, E, R,
14227 [NumElems](unsigned DstIdx, unsigned Shift) {
14228 unsigned Imm = Shift & 0xFF;
14229 unsigned EffectiveShift = Imm & (NumElems - 1);
14230 unsigned SourcePos = DstIdx + EffectiveShift;
14231 unsigned VecIdx = SourcePos < NumElems ? 1 : 0;
14232 unsigned ElemIdx = SourcePos & (NumElems - 1);
14233
14234 return std::pair<unsigned, int>{
14235 VecIdx, static_cast<int>(ElemIdx)};
14236 }))
14237 return false;
14238 return Success(R, E);
14239 }
14240 case X86::BI__builtin_ia32_permvarsi256:
14241 case X86::BI__builtin_ia32_permvarsf256:
14242 case X86::BI__builtin_ia32_permvardf512:
14243 case X86::BI__builtin_ia32_permvardi512:
14244 case X86::BI__builtin_ia32_permvarhi128: {
14245 APValue R;
14246 if (!evalShuffleGeneric(Info, E, R,
14247 [](unsigned DstIdx, unsigned ShuffleMask) {
14248 int Offset = ShuffleMask & 0x7;
14249 return std::pair<unsigned, int>{0, Offset};
14250 }))
14251 return false;
14252 return Success(R, E);
14253 }
14254 case X86::BI__builtin_ia32_permvarqi128:
14255 case X86::BI__builtin_ia32_permvarhi256:
14256 case X86::BI__builtin_ia32_permvarsi512:
14257 case X86::BI__builtin_ia32_permvarsf512: {
14258 APValue R;
14259 if (!evalShuffleGeneric(Info, E, R,
14260 [](unsigned DstIdx, unsigned ShuffleMask) {
14261 int Offset = ShuffleMask & 0xF;
14262 return std::pair<unsigned, int>{0, Offset};
14263 }))
14264 return false;
14265 return Success(R, E);
14266 }
14267 case X86::BI__builtin_ia32_permvardi256:
14268 case X86::BI__builtin_ia32_permvardf256: {
14269 APValue R;
14270 if (!evalShuffleGeneric(Info, E, R,
14271 [](unsigned DstIdx, unsigned ShuffleMask) {
14272 int Offset = ShuffleMask & 0x3;
14273 return std::pair<unsigned, int>{0, Offset};
14274 }))
14275 return false;
14276 return Success(R, E);
14277 }
14278 case X86::BI__builtin_ia32_permvarqi256:
14279 case X86::BI__builtin_ia32_permvarhi512: {
14280 APValue R;
14281 if (!evalShuffleGeneric(Info, E, R,
14282 [](unsigned DstIdx, unsigned ShuffleMask) {
14283 int Offset = ShuffleMask & 0x1F;
14284 return std::pair<unsigned, int>{0, Offset};
14285 }))
14286 return false;
14287 return Success(R, E);
14288 }
14289 case X86::BI__builtin_ia32_permvarqi512: {
14290 APValue R;
14291 if (!evalShuffleGeneric(Info, E, R,
14292 [](unsigned DstIdx, unsigned ShuffleMask) {
14293 int Offset = ShuffleMask & 0x3F;
14294 return std::pair<unsigned, int>{0, Offset};
14295 }))
14296 return false;
14297 return Success(R, E);
14298 }
14299 case X86::BI__builtin_ia32_vpermi2varq128:
14300 case X86::BI__builtin_ia32_vpermi2varpd128: {
14301 APValue R;
14302 if (!evalShuffleGeneric(Info, E, R,
14303 [](unsigned DstIdx, unsigned ShuffleMask) {
14304 int Offset = ShuffleMask & 0x1;
14305 unsigned SrcIdx = (ShuffleMask >> 1) & 0x1;
14306 return std::pair<unsigned, int>{SrcIdx, Offset};
14307 }))
14308 return false;
14309 return Success(R, E);
14310 }
14311 case X86::BI__builtin_ia32_vpermi2vard128:
14312 case X86::BI__builtin_ia32_vpermi2varps128:
14313 case X86::BI__builtin_ia32_vpermi2varq256:
14314 case X86::BI__builtin_ia32_vpermi2varpd256: {
14315 APValue R;
14316 if (!evalShuffleGeneric(Info, E, R,
14317 [](unsigned DstIdx, unsigned ShuffleMask) {
14318 int Offset = ShuffleMask & 0x3;
14319 unsigned SrcIdx = (ShuffleMask >> 2) & 0x1;
14320 return std::pair<unsigned, int>{SrcIdx, Offset};
14321 }))
14322 return false;
14323 return Success(R, E);
14324 }
14325 case X86::BI__builtin_ia32_vpermi2varhi128:
14326 case X86::BI__builtin_ia32_vpermi2vard256:
14327 case X86::BI__builtin_ia32_vpermi2varps256:
14328 case X86::BI__builtin_ia32_vpermi2varq512:
14329 case X86::BI__builtin_ia32_vpermi2varpd512: {
14330 APValue R;
14331 if (!evalShuffleGeneric(Info, E, R,
14332 [](unsigned DstIdx, unsigned ShuffleMask) {
14333 int Offset = ShuffleMask & 0x7;
14334 unsigned SrcIdx = (ShuffleMask >> 3) & 0x1;
14335 return std::pair<unsigned, int>{SrcIdx, Offset};
14336 }))
14337 return false;
14338 return Success(R, E);
14339 }
14340 case X86::BI__builtin_ia32_vpermi2varqi128:
14341 case X86::BI__builtin_ia32_vpermi2varhi256:
14342 case X86::BI__builtin_ia32_vpermi2vard512:
14343 case X86::BI__builtin_ia32_vpermi2varps512: {
14344 APValue R;
14345 if (!evalShuffleGeneric(Info, E, R,
14346 [](unsigned DstIdx, unsigned ShuffleMask) {
14347 int Offset = ShuffleMask & 0xF;
14348 unsigned SrcIdx = (ShuffleMask >> 4) & 0x1;
14349 return std::pair<unsigned, int>{SrcIdx, Offset};
14350 }))
14351 return false;
14352 return Success(R, E);
14353 }
14354 case X86::BI__builtin_ia32_vpermi2varqi256:
14355 case X86::BI__builtin_ia32_vpermi2varhi512: {
14356 APValue R;
14357 if (!evalShuffleGeneric(Info, E, R,
14358 [](unsigned DstIdx, unsigned ShuffleMask) {
14359 int Offset = ShuffleMask & 0x1F;
14360 unsigned SrcIdx = (ShuffleMask >> 5) & 0x1;
14361 return std::pair<unsigned, int>{SrcIdx, Offset};
14362 }))
14363 return false;
14364 return Success(R, E);
14365 }
14366 case X86::BI__builtin_ia32_vpermi2varqi512: {
14367 APValue R;
14368 if (!evalShuffleGeneric(Info, E, R,
14369 [](unsigned DstIdx, unsigned ShuffleMask) {
14370 int Offset = ShuffleMask & 0x3F;
14371 unsigned SrcIdx = (ShuffleMask >> 6) & 0x1;
14372 return std::pair<unsigned, int>{SrcIdx, Offset};
14373 }))
14374 return false;
14375 return Success(R, E);
14376 }
14377
14378 case clang::X86::BI__builtin_ia32_minps:
14379 case clang::X86::BI__builtin_ia32_minpd:
14380 case clang::X86::BI__builtin_ia32_minps256:
14381 case clang::X86::BI__builtin_ia32_minpd256:
14382 case clang::X86::BI__builtin_ia32_minps512:
14383 case clang::X86::BI__builtin_ia32_minpd512:
14384 case clang::X86::BI__builtin_ia32_minph128:
14385 case clang::X86::BI__builtin_ia32_minph256:
14386 case clang::X86::BI__builtin_ia32_minph512:
14387 return EvaluateFpBinOpExpr(
14388 [](const APFloat &A, const APFloat &B,
14389 std::optional<APSInt>) -> std::optional<APFloat> {
14390 if (A.isNaN() || A.isInfinity() || A.isDenormal() || B.isNaN() ||
14391 B.isInfinity() || B.isDenormal())
14392 return std::nullopt;
14393 if (A.isZero() && B.isZero())
14394 return B;
14395 return llvm::minimum(A, B);
14396 });
14397
14398 case clang::X86::BI__builtin_ia32_maxps:
14399 case clang::X86::BI__builtin_ia32_maxpd:
14400 case clang::X86::BI__builtin_ia32_maxps256:
14401 case clang::X86::BI__builtin_ia32_maxpd256:
14402 case clang::X86::BI__builtin_ia32_maxps512:
14403 case clang::X86::BI__builtin_ia32_maxpd512:
14404 case clang::X86::BI__builtin_ia32_maxph128:
14405 case clang::X86::BI__builtin_ia32_maxph256:
14406 case clang::X86::BI__builtin_ia32_maxph512:
14407 return EvaluateFpBinOpExpr(
14408 [](const APFloat &A, const APFloat &B,
14409 std::optional<APSInt>) -> std::optional<APFloat> {
14410 if (A.isNaN() || A.isInfinity() || A.isDenormal() || B.isNaN() ||
14411 B.isInfinity() || B.isDenormal())
14412 return std::nullopt;
14413 if (A.isZero() && B.isZero())
14414 return B;
14415 return llvm::maximum(A, B);
14416 });
14417
14418 case clang::X86::BI__builtin_ia32_vcvtps2ph:
14419 case clang::X86::BI__builtin_ia32_vcvtps2ph256: {
14420 APValue SrcVec;
14421 if (!EvaluateAsRValue(Info, E->getArg(0), SrcVec))
14422 return false;
14423
14424 APSInt Imm;
14425 if (!EvaluateInteger(E->getArg(1), Imm, Info))
14426 return false;
14427
14428 const auto *SrcVTy = E->getArg(0)->getType()->castAs<VectorType>();
14429 unsigned SrcNumElems = SrcVTy->getNumElements();
14430 const auto *DstVTy = E->getType()->castAs<VectorType>();
14431 unsigned DstNumElems = DstVTy->getNumElements();
14432 QualType DstElemTy = DstVTy->getElementType();
14433
14434 const llvm::fltSemantics &HalfSem =
14435 Info.Ctx.getFloatTypeSemantics(Info.Ctx.HalfTy);
14436
14437 int ImmVal = Imm.getZExtValue();
14438 bool UseMXCSR = (ImmVal & 4) != 0;
14439 bool IsFPConstrained =
14441
14442 llvm::RoundingMode RM;
14443 if (!UseMXCSR) {
14444 switch (ImmVal & 3) {
14445 case 0:
14446 RM = llvm::RoundingMode::NearestTiesToEven;
14447 break;
14448 case 1:
14449 RM = llvm::RoundingMode::TowardNegative;
14450 break;
14451 case 2:
14452 RM = llvm::RoundingMode::TowardPositive;
14453 break;
14454 case 3:
14455 RM = llvm::RoundingMode::TowardZero;
14456 break;
14457 default:
14458 llvm_unreachable("Invalid immediate rounding mode");
14459 }
14460 } else {
14461 RM = llvm::RoundingMode::NearestTiesToEven;
14462 }
14463
14464 SmallVector<APValue, 8> ResultElements;
14465 ResultElements.reserve(DstNumElems);
14466
14467 for (unsigned I = 0; I < SrcNumElems; ++I) {
14468 APFloat SrcVal = SrcVec.getVectorElt(I).getFloat();
14469
14470 bool LostInfo;
14471 APFloat::opStatus St = SrcVal.convert(HalfSem, RM, &LostInfo);
14472
14473 if (UseMXCSR && IsFPConstrained && St != APFloat::opOK) {
14474 Info.FFDiag(E, diag::note_constexpr_dynamic_rounding);
14475 return false;
14476 }
14477
14478 APSInt DstInt(SrcVal.bitcastToAPInt(),
14480 ResultElements.push_back(APValue(DstInt));
14481 }
14482
14483 if (DstNumElems > SrcNumElems) {
14484 APSInt Zero = Info.Ctx.MakeIntValue(0, DstElemTy);
14485 for (unsigned I = SrcNumElems; I < DstNumElems; ++I) {
14486 ResultElements.push_back(APValue(Zero));
14487 }
14488 }
14489
14490 return Success(ResultElements, E);
14491 }
14492 case X86::BI__builtin_ia32_vperm2f128_pd256:
14493 case X86::BI__builtin_ia32_vperm2f128_ps256:
14494 case X86::BI__builtin_ia32_vperm2f128_si256:
14495 case X86::BI__builtin_ia32_permti256: {
14496 unsigned NumElements =
14497 E->getArg(0)->getType()->getAs<VectorType>()->getNumElements();
14498 unsigned PreservedBitsCnt = NumElements >> 2;
14499 APValue R;
14500 if (!evalShuffleGeneric(
14501 Info, E, R,
14502 [PreservedBitsCnt](unsigned DstIdx, unsigned ShuffleMask) {
14503 unsigned ControlBitsCnt = DstIdx >> PreservedBitsCnt << 2;
14504 unsigned ControlBits = ShuffleMask >> ControlBitsCnt;
14505
14506 if (ControlBits & 0b1000)
14507 return std::make_pair(0u, -1);
14508
14509 unsigned SrcVecIdx = (ControlBits & 0b10) >> 1;
14510 unsigned PreservedBitsMask = (1 << PreservedBitsCnt) - 1;
14511 int SrcIdx = ((ControlBits & 0b1) << PreservedBitsCnt) |
14512 (DstIdx & PreservedBitsMask);
14513 return std::make_pair(SrcVecIdx, SrcIdx);
14514 }))
14515 return false;
14516 return Success(R, E);
14517 }
14518 }
14519}
14520
14521bool VectorExprEvaluator::VisitConvertVectorExpr(const ConvertVectorExpr *E) {
14522 APValue Source;
14523 QualType SourceVecType = E->getSrcExpr()->getType();
14524 if (!EvaluateAsRValue(Info, E->getSrcExpr(), Source))
14525 return false;
14526
14527 QualType DestTy = E->getType()->castAs<VectorType>()->getElementType();
14528 QualType SourceTy = SourceVecType->castAs<VectorType>()->getElementType();
14529
14530 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
14531
14532 auto SourceLen = Source.getVectorLength();
14533 SmallVector<APValue, 4> ResultElements;
14534 ResultElements.reserve(SourceLen);
14535 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
14536 APValue Elt;
14537 if (!handleVectorElementCast(Info, FPO, E, SourceTy, DestTy,
14538 Source.getVectorElt(EltNum), Elt))
14539 return false;
14540 ResultElements.push_back(std::move(Elt));
14541 }
14542
14543 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
14544}
14545
14546static bool handleVectorShuffle(EvalInfo &Info, const ShuffleVectorExpr *E,
14547 QualType ElemType, APValue const &VecVal1,
14548 APValue const &VecVal2, unsigned EltNum,
14549 APValue &Result) {
14550 unsigned const TotalElementsInInputVector1 = VecVal1.getVectorLength();
14551 unsigned const TotalElementsInInputVector2 = VecVal2.getVectorLength();
14552
14553 APSInt IndexVal = E->getShuffleMaskIdx(EltNum);
14554 int64_t index = IndexVal.getExtValue();
14555 // The spec says that -1 should be treated as undef for optimizations,
14556 // but in constexpr we'd have to produce an APValue::Indeterminate,
14557 // which is prohibited from being a top-level constant value. Emit a
14558 // diagnostic instead.
14559 if (index == -1) {
14560 Info.FFDiag(
14561 E, diag::err_shufflevector_minus_one_is_undefined_behavior_constexpr)
14562 << EltNum;
14563 return false;
14564 }
14565
14566 if (index < 0 ||
14567 index >= TotalElementsInInputVector1 + TotalElementsInInputVector2)
14568 llvm_unreachable("Out of bounds shuffle index");
14569
14570 if (index >= TotalElementsInInputVector1)
14571 Result = VecVal2.getVectorElt(index - TotalElementsInInputVector1);
14572 else
14573 Result = VecVal1.getVectorElt(index);
14574 return true;
14575}
14576
14577bool VectorExprEvaluator::VisitShuffleVectorExpr(const ShuffleVectorExpr *E) {
14578 // FIXME: Unary shuffle with mask not currently supported.
14579 if (E->getNumSubExprs() == 2)
14580 return Error(E);
14581 APValue VecVal1;
14582 const Expr *Vec1 = E->getExpr(0);
14583 if (!EvaluateAsRValue(Info, Vec1, VecVal1))
14584 return false;
14585 APValue VecVal2;
14586 const Expr *Vec2 = E->getExpr(1);
14587 if (!EvaluateAsRValue(Info, Vec2, VecVal2))
14588 return false;
14589
14590 VectorType const *DestVecTy = E->getType()->castAs<VectorType>();
14591 QualType DestElTy = DestVecTy->getElementType();
14592
14593 auto TotalElementsInOutputVector = DestVecTy->getNumElements();
14594
14595 SmallVector<APValue, 4> ResultElements;
14596 ResultElements.reserve(TotalElementsInOutputVector);
14597 for (unsigned EltNum = 0; EltNum < TotalElementsInOutputVector; ++EltNum) {
14598 APValue Elt;
14599 if (!handleVectorShuffle(Info, E, DestElTy, VecVal1, VecVal2, EltNum, Elt))
14600 return false;
14601 ResultElements.push_back(std::move(Elt));
14602 }
14603
14604 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
14605}
14606
14607//===----------------------------------------------------------------------===//
14608// Array Evaluation
14609//===----------------------------------------------------------------------===//
14610
14611namespace {
14612 class ArrayExprEvaluator
14613 : public ExprEvaluatorBase<ArrayExprEvaluator> {
14614 const LValue &This;
14615 APValue &Result;
14616 public:
14617
14618 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
14619 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
14620
14621 bool Success(const APValue &V, const Expr *E) {
14622 assert(V.isArray() && "expected array");
14623 Result = V;
14624 return true;
14625 }
14626
14627 bool ZeroInitialization(const Expr *E) {
14628 const ConstantArrayType *CAT =
14629 Info.Ctx.getAsConstantArrayType(E->getType());
14630 if (!CAT) {
14631 if (E->getType()->isIncompleteArrayType()) {
14632 // We can be asked to zero-initialize a flexible array member; this
14633 // is represented as an ImplicitValueInitExpr of incomplete array
14634 // type. In this case, the array has zero elements.
14635 Result = APValue(APValue::UninitArray(), 0, 0);
14636 return true;
14637 }
14638 // FIXME: We could handle VLAs here.
14639 return Error(E);
14640 }
14641
14642 Result = APValue(APValue::UninitArray(), 0, CAT->getZExtSize());
14643 if (!Result.hasArrayFiller())
14644 return true;
14645
14646 // Zero-initialize all elements.
14647 LValue Subobject = This;
14648 Subobject.addArray(Info, E, CAT);
14649 ImplicitValueInitExpr VIE(CAT->getElementType());
14650 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
14651 }
14652
14653 bool VisitCallExpr(const CallExpr *E) {
14654 return handleCallExpr(E, Result, &This);
14655 }
14656 bool VisitCastExpr(const CastExpr *E);
14657 bool VisitInitListExpr(const InitListExpr *E,
14658 QualType AllocType = QualType());
14659 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
14660 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
14661 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
14662 const LValue &Subobject,
14663 APValue *Value, QualType Type);
14664 bool VisitStringLiteral(const StringLiteral *E,
14665 QualType AllocType = QualType()) {
14666 expandStringLiteral(Info, E, Result, AllocType);
14667 return true;
14668 }
14669 bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E);
14670 bool VisitCXXParenListOrInitListExpr(const Expr *ExprToVisit,
14671 ArrayRef<Expr *> Args,
14672 const Expr *ArrayFiller,
14673 QualType AllocType = QualType());
14674 };
14675} // end anonymous namespace
14676
14677static bool EvaluateArray(const Expr *E, const LValue &This,
14678 APValue &Result, EvalInfo &Info) {
14679 assert(!E->isValueDependent());
14680 assert(E->isPRValue() && E->getType()->isArrayType() &&
14681 "not an array prvalue");
14682 return ArrayExprEvaluator(Info, This, Result).Visit(E);
14683}
14684
14685static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
14686 APValue &Result, const InitListExpr *ILE,
14687 QualType AllocType) {
14688 assert(!ILE->isValueDependent());
14689 assert(ILE->isPRValue() && ILE->getType()->isArrayType() &&
14690 "not an array prvalue");
14691 return ArrayExprEvaluator(Info, This, Result)
14692 .VisitInitListExpr(ILE, AllocType);
14693}
14694
14695static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
14696 APValue &Result,
14697 const CXXConstructExpr *CCE,
14698 QualType AllocType) {
14699 assert(!CCE->isValueDependent());
14700 assert(CCE->isPRValue() && CCE->getType()->isArrayType() &&
14701 "not an array prvalue");
14702 return ArrayExprEvaluator(Info, This, Result)
14703 .VisitCXXConstructExpr(CCE, This, &Result, AllocType);
14704}
14705
14706// Return true iff the given array filler may depend on the element index.
14707static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
14708 // For now, just allow non-class value-initialization and initialization
14709 // lists comprised of them.
14710 if (isa<ImplicitValueInitExpr>(FillerExpr))
14711 return false;
14712 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
14713 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
14714 if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
14715 return true;
14716 }
14717
14718 if (ILE->hasArrayFiller() &&
14719 MaybeElementDependentArrayFiller(ILE->getArrayFiller()))
14720 return true;
14721
14722 return false;
14723 }
14724 return true;
14725}
14726
14727bool ArrayExprEvaluator::VisitCastExpr(const CastExpr *E) {
14728 const Expr *SE = E->getSubExpr();
14729
14730 switch (E->getCastKind()) {
14731 default:
14732 return ExprEvaluatorBaseTy::VisitCastExpr(E);
14733 case CK_HLSLAggregateSplatCast: {
14734 APValue Val;
14735 QualType ValTy;
14736
14737 if (!hlslAggSplatHelper(Info, SE, Val, ValTy))
14738 return false;
14739
14740 unsigned NEls = elementwiseSize(Info, E->getType());
14741
14742 SmallVector<APValue> SplatEls(NEls, Val);
14743 SmallVector<QualType> SplatType(NEls, ValTy);
14744
14745 // cast the elements
14746 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
14747 if (!constructAggregate(Info, FPO, E, Result, E->getType(), SplatEls,
14748 SplatType))
14749 return false;
14750
14751 return true;
14752 }
14753 case CK_HLSLElementwiseCast: {
14754 SmallVector<APValue> SrcEls;
14755 SmallVector<QualType> SrcTypes;
14756
14757 if (!hlslElementwiseCastHelper(Info, SE, E->getType(), SrcEls, SrcTypes))
14758 return false;
14759
14760 // cast the elements
14761 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
14762 if (!constructAggregate(Info, FPO, E, Result, E->getType(), SrcEls,
14763 SrcTypes))
14764 return false;
14765 return true;
14766 }
14767 }
14768}
14769
14770bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E,
14771 QualType AllocType) {
14772 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
14773 AllocType.isNull() ? E->getType() : AllocType);
14774 if (!CAT)
14775 return Error(E);
14776
14777 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
14778 // an appropriately-typed string literal enclosed in braces.
14779 if (E->isStringLiteralInit()) {
14780 auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParenImpCasts());
14781 // FIXME: Support ObjCEncodeExpr here once we support it in
14782 // ArrayExprEvaluator generally.
14783 if (!SL)
14784 return Error(E);
14785 return VisitStringLiteral(SL, AllocType);
14786 }
14787 // Any other transparent list init will need proper handling of the
14788 // AllocType; we can't just recurse to the inner initializer.
14789 assert(!E->isTransparent() &&
14790 "transparent array list initialization is not string literal init?");
14791
14792 return VisitCXXParenListOrInitListExpr(E, E->inits(), E->getArrayFiller(),
14793 AllocType);
14794}
14795
14796bool ArrayExprEvaluator::VisitCXXParenListOrInitListExpr(
14797 const Expr *ExprToVisit, ArrayRef<Expr *> Args, const Expr *ArrayFiller,
14798 QualType AllocType) {
14799 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
14800 AllocType.isNull() ? ExprToVisit->getType() : AllocType);
14801
14802 bool Success = true;
14803
14804 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
14805 "zero-initialized array shouldn't have any initialized elts");
14806 APValue Filler;
14807 if (Result.isArray() && Result.hasArrayFiller())
14808 Filler = Result.getArrayFiller();
14809
14810 unsigned NumEltsToInit = Args.size();
14811 unsigned NumElts = CAT->getZExtSize();
14812
14813 // If the initializer might depend on the array index, run it for each
14814 // array element.
14815 if (NumEltsToInit != NumElts &&
14816 MaybeElementDependentArrayFiller(ArrayFiller)) {
14817 NumEltsToInit = NumElts;
14818 } else {
14819 for (auto *Init : Args) {
14820 if (auto *EmbedS = dyn_cast<EmbedExpr>(Init->IgnoreParenImpCasts()))
14821 NumEltsToInit += EmbedS->getDataElementCount() - 1;
14822 }
14823 if (NumEltsToInit > NumElts)
14824 NumEltsToInit = NumElts;
14825 }
14826
14827 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
14828 << NumEltsToInit << ".\n");
14829
14830 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
14831
14832 // If the array was previously zero-initialized, preserve the
14833 // zero-initialized values.
14834 if (Filler.hasValue()) {
14835 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
14836 Result.getArrayInitializedElt(I) = Filler;
14837 if (Result.hasArrayFiller())
14838 Result.getArrayFiller() = Filler;
14839 }
14840
14841 LValue Subobject = This;
14842 Subobject.addArray(Info, ExprToVisit, CAT);
14843 auto Eval = [&](const Expr *Init, unsigned ArrayIndex) {
14844 if (Init->isValueDependent())
14845 return EvaluateDependentExpr(Init, Info);
14846
14847 if (!EvaluateInPlace(Result.getArrayInitializedElt(ArrayIndex), Info,
14848 Subobject, Init) ||
14849 !HandleLValueArrayAdjustment(Info, Init, Subobject,
14850 CAT->getElementType(), 1)) {
14851 if (!Info.noteFailure())
14852 return false;
14853 Success = false;
14854 }
14855 return true;
14856 };
14857 unsigned ArrayIndex = 0;
14858 QualType DestTy = CAT->getElementType();
14859 APSInt Value(Info.Ctx.getTypeSize(DestTy), DestTy->isUnsignedIntegerType());
14860 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
14861 const Expr *Init = Index < Args.size() ? Args[Index] : ArrayFiller;
14862 if (ArrayIndex >= NumEltsToInit)
14863 break;
14864 if (auto *EmbedS = dyn_cast<EmbedExpr>(Init->IgnoreParenImpCasts())) {
14865 StringLiteral *SL = EmbedS->getDataStringLiteral();
14866 for (unsigned I = EmbedS->getStartingElementPos(),
14867 N = EmbedS->getDataElementCount();
14868 I != EmbedS->getStartingElementPos() + N; ++I) {
14869 Value = SL->getCodeUnit(I);
14870 if (DestTy->isIntegerType()) {
14871 Result.getArrayInitializedElt(ArrayIndex) = APValue(Value);
14872 } else {
14873 assert(DestTy->isFloatingType() && "unexpected type");
14874 const FPOptions FPO =
14875 Init->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
14876 APFloat FValue(0.0);
14877 if (!HandleIntToFloatCast(Info, Init, FPO, EmbedS->getType(), Value,
14878 DestTy, FValue))
14879 return false;
14880 Result.getArrayInitializedElt(ArrayIndex) = APValue(FValue);
14881 }
14882 ArrayIndex++;
14883 }
14884 } else {
14885 if (!Eval(Init, ArrayIndex))
14886 return false;
14887 ++ArrayIndex;
14888 }
14889 }
14890
14891 if (!Result.hasArrayFiller())
14892 return Success;
14893
14894 // If we get here, we have a trivial filler, which we can just evaluate
14895 // once and splat over the rest of the array elements.
14896 assert(ArrayFiller && "no array filler for incomplete init list");
14897 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
14898 ArrayFiller) &&
14899 Success;
14900}
14901
14902bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
14903 LValue CommonLV;
14904 if (E->getCommonExpr() &&
14905 !Evaluate(Info.CurrentCall->createTemporary(
14906 E->getCommonExpr(),
14907 getStorageType(Info.Ctx, E->getCommonExpr()),
14908 ScopeKind::FullExpression, CommonLV),
14909 Info, E->getCommonExpr()->getSourceExpr()))
14910 return false;
14911
14913
14914 uint64_t Elements = CAT->getZExtSize();
14915 Result = APValue(APValue::UninitArray(), Elements, Elements);
14916
14917 LValue Subobject = This;
14918 Subobject.addArray(Info, E, CAT);
14919
14920 bool Success = true;
14921 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
14922 // C++ [class.temporary]/5
14923 // There are four contexts in which temporaries are destroyed at a different
14924 // point than the end of the full-expression. [...] The second context is
14925 // when a copy constructor is called to copy an element of an array while
14926 // the entire array is copied [...]. In either case, if the constructor has
14927 // one or more default arguments, the destruction of every temporary created
14928 // in a default argument is sequenced before the construction of the next
14929 // array element, if any.
14930 FullExpressionRAII Scope(Info);
14931
14932 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
14933 Info, Subobject, E->getSubExpr()) ||
14934 !HandleLValueArrayAdjustment(Info, E, Subobject,
14935 CAT->getElementType(), 1)) {
14936 if (!Info.noteFailure())
14937 return false;
14938 Success = false;
14939 }
14940
14941 // Make sure we run the destructors too.
14942 Scope.destroy();
14943 }
14944
14945 return Success;
14946}
14947
14948bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
14949 return VisitCXXConstructExpr(E, This, &Result, E->getType());
14950}
14951
14952bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
14953 const LValue &Subobject,
14954 APValue *Value,
14955 QualType Type) {
14956 bool HadZeroInit = Value->hasValue();
14957
14958 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
14959 unsigned FinalSize = CAT->getZExtSize();
14960
14961 // Preserve the array filler if we had prior zero-initialization.
14962 APValue Filler =
14963 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
14964 : APValue();
14965
14966 *Value = APValue(APValue::UninitArray(), 0, FinalSize);
14967 if (FinalSize == 0)
14968 return true;
14969
14970 bool HasTrivialConstructor = CheckTrivialDefaultConstructor(
14971 Info, E->getExprLoc(), E->getConstructor(),
14973 LValue ArrayElt = Subobject;
14974 ArrayElt.addArray(Info, E, CAT);
14975 // We do the whole initialization in two passes, first for just one element,
14976 // then for the whole array. It's possible we may find out we can't do const
14977 // init in the first pass, in which case we avoid allocating a potentially
14978 // large array. We don't do more passes because expanding array requires
14979 // copying the data, which is wasteful.
14980 for (const unsigned N : {1u, FinalSize}) {
14981 unsigned OldElts = Value->getArrayInitializedElts();
14982 if (OldElts == N)
14983 break;
14984
14985 // Expand the array to appropriate size.
14986 APValue NewValue(APValue::UninitArray(), N, FinalSize);
14987 for (unsigned I = 0; I < OldElts; ++I)
14988 NewValue.getArrayInitializedElt(I).swap(
14989 Value->getArrayInitializedElt(I));
14990 Value->swap(NewValue);
14991
14992 if (HadZeroInit)
14993 for (unsigned I = OldElts; I < N; ++I)
14994 Value->getArrayInitializedElt(I) = Filler;
14995
14996 if (HasTrivialConstructor && N == FinalSize && FinalSize != 1) {
14997 // If we have a trivial constructor, only evaluate it once and copy
14998 // the result into all the array elements.
14999 APValue &FirstResult = Value->getArrayInitializedElt(0);
15000 for (unsigned I = OldElts; I < FinalSize; ++I)
15001 Value->getArrayInitializedElt(I) = FirstResult;
15002 } else {
15003 for (unsigned I = OldElts; I < N; ++I) {
15004 if (!VisitCXXConstructExpr(E, ArrayElt,
15005 &Value->getArrayInitializedElt(I),
15006 CAT->getElementType()) ||
15007 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
15008 CAT->getElementType(), 1))
15009 return false;
15010 // When checking for const initilization any diagnostic is considered
15011 // an error.
15012 if (Info.EvalStatus.Diag && !Info.EvalStatus.Diag->empty() &&
15013 !Info.keepEvaluatingAfterFailure())
15014 return false;
15015 }
15016 }
15017 }
15018
15019 return true;
15020 }
15021
15022 if (!Type->isRecordType())
15023 return Error(E);
15024
15025 return RecordExprEvaluator(Info, Subobject, *Value)
15026 .VisitCXXConstructExpr(E, Type);
15027}
15028
15029bool ArrayExprEvaluator::VisitCXXParenListInitExpr(
15030 const CXXParenListInitExpr *E) {
15031 assert(E->getType()->isConstantArrayType() &&
15032 "Expression result is not a constant array type");
15033
15034 return VisitCXXParenListOrInitListExpr(E, E->getInitExprs(),
15035 E->getArrayFiller());
15036}
15037
15038//===----------------------------------------------------------------------===//
15039// Integer Evaluation
15040//
15041// As a GNU extension, we support casting pointers to sufficiently-wide integer
15042// types and back in constant folding. Integer values are thus represented
15043// either as an integer-valued APValue, or as an lvalue-valued APValue.
15044//===----------------------------------------------------------------------===//
15045
15046namespace {
15047class IntExprEvaluator
15048 : public ExprEvaluatorBase<IntExprEvaluator> {
15049 APValue &Result;
15050public:
15051 IntExprEvaluator(EvalInfo &info, APValue &result)
15052 : ExprEvaluatorBaseTy(info), Result(result) {}
15053
15054 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
15055 assert(E->getType()->isIntegralOrEnumerationType() &&
15056 "Invalid evaluation result.");
15057 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
15058 "Invalid evaluation result.");
15059 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
15060 "Invalid evaluation result.");
15061 Result = APValue(SI);
15062 return true;
15063 }
15064 bool Success(const llvm::APSInt &SI, const Expr *E) {
15065 return Success(SI, E, Result);
15066 }
15067
15068 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
15069 assert(E->getType()->isIntegralOrEnumerationType() &&
15070 "Invalid evaluation result.");
15071 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
15072 "Invalid evaluation result.");
15073 Result = APValue(APSInt(I));
15074 Result.getInt().setIsUnsigned(
15076 return true;
15077 }
15078 bool Success(const llvm::APInt &I, const Expr *E) {
15079 return Success(I, E, Result);
15080 }
15081
15082 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
15083 assert(E->getType()->isIntegralOrEnumerationType() &&
15084 "Invalid evaluation result.");
15085 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
15086 return true;
15087 }
15088 bool Success(uint64_t Value, const Expr *E) {
15089 return Success(Value, E, Result);
15090 }
15091
15092 bool Success(CharUnits Size, const Expr *E) {
15093 return Success(Size.getQuantity(), E);
15094 }
15095
15096 bool Success(const APValue &V, const Expr *E) {
15097 // C++23 [expr.const]p8 If we have a variable that is unknown reference or
15098 // pointer allow further evaluation of the value.
15099 if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate() ||
15100 V.allowConstexprUnknown()) {
15101 Result = V;
15102 return true;
15103 }
15104 return Success(V.getInt(), E);
15105 }
15106
15107 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
15108
15109 friend std::optional<bool> EvaluateBuiltinIsWithinLifetime(IntExprEvaluator &,
15110 const CallExpr *);
15111
15112 //===--------------------------------------------------------------------===//
15113 // Visitor Methods
15114 //===--------------------------------------------------------------------===//
15115
15116 bool VisitIntegerLiteral(const IntegerLiteral *E) {
15117 return Success(E->getValue(), E);
15118 }
15119 bool VisitCharacterLiteral(const CharacterLiteral *E) {
15120 return Success(E->getValue(), E);
15121 }
15122
15123 bool CheckReferencedDecl(const Expr *E, const Decl *D);
15124 bool VisitDeclRefExpr(const DeclRefExpr *E) {
15125 if (CheckReferencedDecl(E, E->getDecl()))
15126 return true;
15127
15128 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
15129 }
15130 bool VisitMemberExpr(const MemberExpr *E) {
15131 if (CheckReferencedDecl(E, E->getMemberDecl())) {
15132 VisitIgnoredBaseExpression(E->getBase());
15133 return true;
15134 }
15135
15136 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
15137 }
15138
15139 bool VisitCallExpr(const CallExpr *E);
15140 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
15141 bool VisitBinaryOperator(const BinaryOperator *E);
15142 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
15143 bool VisitUnaryOperator(const UnaryOperator *E);
15144
15145 bool VisitCastExpr(const CastExpr* E);
15146 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
15147
15148 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
15149 return Success(E->getValue(), E);
15150 }
15151
15152 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
15153 return Success(E->getValue(), E);
15154 }
15155
15156 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
15157 if (Info.ArrayInitIndex == uint64_t(-1)) {
15158 // We were asked to evaluate this subexpression independent of the
15159 // enclosing ArrayInitLoopExpr. We can't do that.
15160 Info.FFDiag(E);
15161 return false;
15162 }
15163 return Success(Info.ArrayInitIndex, E);
15164 }
15165
15166 // Note, GNU defines __null as an integer, not a pointer.
15167 bool VisitGNUNullExpr(const GNUNullExpr *E) {
15168 return ZeroInitialization(E);
15169 }
15170
15171 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
15172 if (E->isStoredAsBoolean())
15173 return Success(E->getBoolValue(), E);
15174 if (E->getAPValue().isAbsent())
15175 return false;
15176 assert(E->getAPValue().isInt() && "APValue type not supported");
15177 return Success(E->getAPValue().getInt(), E);
15178 }
15179
15180 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
15181 return Success(E->getValue(), E);
15182 }
15183
15184 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
15185 return Success(E->getValue(), E);
15186 }
15187
15188 bool VisitOpenACCAsteriskSizeExpr(const OpenACCAsteriskSizeExpr *E) {
15189 // This should not be evaluated during constant expr evaluation, as it
15190 // should always be in an unevaluated context (the args list of a 'gang' or
15191 // 'tile' clause).
15192 return Error(E);
15193 }
15194
15195 bool VisitUnaryReal(const UnaryOperator *E);
15196 bool VisitUnaryImag(const UnaryOperator *E);
15197
15198 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
15199 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
15200 bool VisitSourceLocExpr(const SourceLocExpr *E);
15201 bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E);
15202 bool VisitRequiresExpr(const RequiresExpr *E);
15203 // FIXME: Missing: array subscript of vector, member of vector
15204};
15205
15206class FixedPointExprEvaluator
15207 : public ExprEvaluatorBase<FixedPointExprEvaluator> {
15208 APValue &Result;
15209
15210 public:
15211 FixedPointExprEvaluator(EvalInfo &info, APValue &result)
15212 : ExprEvaluatorBaseTy(info), Result(result) {}
15213
15214 bool Success(const llvm::APInt &I, const Expr *E) {
15215 return Success(
15216 APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
15217 }
15218
15219 bool Success(uint64_t Value, const Expr *E) {
15220 return Success(
15221 APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
15222 }
15223
15224 bool Success(const APValue &V, const Expr *E) {
15225 return Success(V.getFixedPoint(), E);
15226 }
15227
15228 bool Success(const APFixedPoint &V, const Expr *E) {
15229 assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
15230 assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
15231 "Invalid evaluation result.");
15232 Result = APValue(V);
15233 return true;
15234 }
15235
15236 bool ZeroInitialization(const Expr *E) {
15237 return Success(0, E);
15238 }
15239
15240 //===--------------------------------------------------------------------===//
15241 // Visitor Methods
15242 //===--------------------------------------------------------------------===//
15243
15244 bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
15245 return Success(E->getValue(), E);
15246 }
15247
15248 bool VisitCastExpr(const CastExpr *E);
15249 bool VisitUnaryOperator(const UnaryOperator *E);
15250 bool VisitBinaryOperator(const BinaryOperator *E);
15251};
15252} // end anonymous namespace
15253
15254/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
15255/// produce either the integer value or a pointer.
15256///
15257/// GCC has a heinous extension which folds casts between pointer types and
15258/// pointer-sized integral types. We support this by allowing the evaluation of
15259/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
15260/// Some simple arithmetic on such values is supported (they are treated much
15261/// like char*).
15262static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
15263 EvalInfo &Info) {
15264 assert(!E->isValueDependent());
15265 assert(E->isPRValue() && E->getType()->isIntegralOrEnumerationType());
15266 return IntExprEvaluator(Info, Result).Visit(E);
15267}
15268
15269static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
15270 assert(!E->isValueDependent());
15271 APValue Val;
15272 if (!EvaluateIntegerOrLValue(E, Val, Info))
15273 return false;
15274 if (!Val.isInt()) {
15275 // FIXME: It would be better to produce the diagnostic for casting
15276 // a pointer to an integer.
15277 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
15278 return false;
15279 }
15280 Result = Val.getInt();
15281 return true;
15282}
15283
15284bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
15286 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
15287 return Success(Evaluated, E);
15288}
15289
15290static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
15291 EvalInfo &Info) {
15292 assert(!E->isValueDependent());
15293 if (E->getType()->isFixedPointType()) {
15294 APValue Val;
15295 if (!FixedPointExprEvaluator(Info, Val).Visit(E))
15296 return false;
15297 if (!Val.isFixedPoint())
15298 return false;
15299
15300 Result = Val.getFixedPoint();
15301 return true;
15302 }
15303 return false;
15304}
15305
15306static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
15307 EvalInfo &Info) {
15308 assert(!E->isValueDependent());
15309 if (E->getType()->isIntegerType()) {
15310 auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
15311 APSInt Val;
15312 if (!EvaluateInteger(E, Val, Info))
15313 return false;
15314 Result = APFixedPoint(Val, FXSema);
15315 return true;
15316 } else if (E->getType()->isFixedPointType()) {
15317 return EvaluateFixedPoint(E, Result, Info);
15318 }
15319 return false;
15320}
15321
15322/// Check whether the given declaration can be directly converted to an integral
15323/// rvalue. If not, no diagnostic is produced; there are other things we can
15324/// try.
15325bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
15326 // Enums are integer constant exprs.
15327 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
15328 // Check for signedness/width mismatches between E type and ECD value.
15329 bool SameSign = (ECD->getInitVal().isSigned()
15331 bool SameWidth = (ECD->getInitVal().getBitWidth()
15332 == Info.Ctx.getIntWidth(E->getType()));
15333 if (SameSign && SameWidth)
15334 return Success(ECD->getInitVal(), E);
15335 else {
15336 // Get rid of mismatch (otherwise Success assertions will fail)
15337 // by computing a new value matching the type of E.
15338 llvm::APSInt Val = ECD->getInitVal();
15339 if (!SameSign)
15340 Val.setIsSigned(!ECD->getInitVal().isSigned());
15341 if (!SameWidth)
15342 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
15343 return Success(Val, E);
15344 }
15345 }
15346 return false;
15347}
15348
15349/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
15350/// as GCC.
15352 const LangOptions &LangOpts) {
15353 assert(!T->isDependentType() && "unexpected dependent type");
15354
15355 QualType CanTy = T.getCanonicalType();
15356
15357 switch (CanTy->getTypeClass()) {
15358#define TYPE(ID, BASE)
15359#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
15360#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
15361#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
15362#include "clang/AST/TypeNodes.inc"
15363 case Type::Auto:
15364 case Type::DeducedTemplateSpecialization:
15365 llvm_unreachable("unexpected non-canonical or dependent type");
15366
15367 case Type::Builtin:
15368 switch (cast<BuiltinType>(CanTy)->getKind()) {
15369#define BUILTIN_TYPE(ID, SINGLETON_ID)
15370#define SIGNED_TYPE(ID, SINGLETON_ID) \
15371 case BuiltinType::ID: return GCCTypeClass::Integer;
15372#define FLOATING_TYPE(ID, SINGLETON_ID) \
15373 case BuiltinType::ID: return GCCTypeClass::RealFloat;
15374#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
15375 case BuiltinType::ID: break;
15376#include "clang/AST/BuiltinTypes.def"
15377 case BuiltinType::Void:
15378 return GCCTypeClass::Void;
15379
15380 case BuiltinType::Bool:
15381 return GCCTypeClass::Bool;
15382
15383 case BuiltinType::Char_U:
15384 case BuiltinType::UChar:
15385 case BuiltinType::WChar_U:
15386 case BuiltinType::Char8:
15387 case BuiltinType::Char16:
15388 case BuiltinType::Char32:
15389 case BuiltinType::UShort:
15390 case BuiltinType::UInt:
15391 case BuiltinType::ULong:
15392 case BuiltinType::ULongLong:
15393 case BuiltinType::UInt128:
15394 return GCCTypeClass::Integer;
15395
15396 case BuiltinType::UShortAccum:
15397 case BuiltinType::UAccum:
15398 case BuiltinType::ULongAccum:
15399 case BuiltinType::UShortFract:
15400 case BuiltinType::UFract:
15401 case BuiltinType::ULongFract:
15402 case BuiltinType::SatUShortAccum:
15403 case BuiltinType::SatUAccum:
15404 case BuiltinType::SatULongAccum:
15405 case BuiltinType::SatUShortFract:
15406 case BuiltinType::SatUFract:
15407 case BuiltinType::SatULongFract:
15408 return GCCTypeClass::None;
15409
15410 case BuiltinType::NullPtr:
15411
15412 case BuiltinType::ObjCId:
15413 case BuiltinType::ObjCClass:
15414 case BuiltinType::ObjCSel:
15415#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
15416 case BuiltinType::Id:
15417#include "clang/Basic/OpenCLImageTypes.def"
15418#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
15419 case BuiltinType::Id:
15420#include "clang/Basic/OpenCLExtensionTypes.def"
15421 case BuiltinType::OCLSampler:
15422 case BuiltinType::OCLEvent:
15423 case BuiltinType::OCLClkEvent:
15424 case BuiltinType::OCLQueue:
15425 case BuiltinType::OCLReserveID:
15426#define SVE_TYPE(Name, Id, SingletonId) \
15427 case BuiltinType::Id:
15428#include "clang/Basic/AArch64ACLETypes.def"
15429#define PPC_VECTOR_TYPE(Name, Id, Size) \
15430 case BuiltinType::Id:
15431#include "clang/Basic/PPCTypes.def"
15432#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
15433#include "clang/Basic/RISCVVTypes.def"
15434#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
15435#include "clang/Basic/WebAssemblyReferenceTypes.def"
15436#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
15437#include "clang/Basic/AMDGPUTypes.def"
15438#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
15439#include "clang/Basic/HLSLIntangibleTypes.def"
15440 return GCCTypeClass::None;
15441
15442 case BuiltinType::Dependent:
15443 llvm_unreachable("unexpected dependent type");
15444 };
15445 llvm_unreachable("unexpected placeholder type");
15446
15447 case Type::Enum:
15448 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
15449
15450 case Type::Pointer:
15451 case Type::ConstantArray:
15452 case Type::VariableArray:
15453 case Type::IncompleteArray:
15454 case Type::FunctionNoProto:
15455 case Type::FunctionProto:
15456 case Type::ArrayParameter:
15457 return GCCTypeClass::Pointer;
15458
15459 case Type::MemberPointer:
15460 return CanTy->isMemberDataPointerType()
15463
15464 case Type::Complex:
15465 return GCCTypeClass::Complex;
15466
15467 case Type::Record:
15468 return CanTy->isUnionType() ? GCCTypeClass::Union
15470
15471 case Type::Atomic:
15472 // GCC classifies _Atomic T the same as T.
15474 CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
15475
15476 case Type::Vector:
15477 case Type::ExtVector:
15478 return GCCTypeClass::Vector;
15479
15480 case Type::BlockPointer:
15481 case Type::ConstantMatrix:
15482 case Type::ObjCObject:
15483 case Type::ObjCInterface:
15484 case Type::ObjCObjectPointer:
15485 case Type::Pipe:
15486 case Type::HLSLAttributedResource:
15487 case Type::HLSLInlineSpirv:
15488 // Classify all other types that don't fit into the regular
15489 // classification the same way.
15490 return GCCTypeClass::None;
15491
15492 case Type::BitInt:
15493 return GCCTypeClass::BitInt;
15494
15495 case Type::LValueReference:
15496 case Type::RValueReference:
15497 llvm_unreachable("invalid type for expression");
15498 }
15499
15500 llvm_unreachable("unexpected type class");
15501}
15502
15503/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
15504/// as GCC.
15505static GCCTypeClass
15507 // If no argument was supplied, default to None. This isn't
15508 // ideal, however it is what gcc does.
15509 if (E->getNumArgs() == 0)
15510 return GCCTypeClass::None;
15511
15512 // FIXME: Bizarrely, GCC treats a call with more than one argument as not
15513 // being an ICE, but still folds it to a constant using the type of the first
15514 // argument.
15515 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
15516}
15517
15518/// EvaluateBuiltinConstantPForLValue - Determine the result of
15519/// __builtin_constant_p when applied to the given pointer.
15520///
15521/// A pointer is only "constant" if it is null (or a pointer cast to integer)
15522/// or it points to the first character of a string literal.
15525 if (Base.isNull()) {
15526 // A null base is acceptable.
15527 return true;
15528 } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
15529 if (!isa<StringLiteral>(E))
15530 return false;
15531 return LV.getLValueOffset().isZero();
15532 } else if (Base.is<TypeInfoLValue>()) {
15533 // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
15534 // evaluate to true.
15535 return true;
15536 } else {
15537 // Any other base is not constant enough for GCC.
15538 return false;
15539 }
15540}
15541
15542/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
15543/// GCC as we can manage.
15544static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
15545 // This evaluation is not permitted to have side-effects, so evaluate it in
15546 // a speculative evaluation context.
15547 SpeculativeEvaluationRAII SpeculativeEval(Info);
15548
15549 // Constant-folding is always enabled for the operand of __builtin_constant_p
15550 // (even when the enclosing evaluation context otherwise requires a strict
15551 // language-specific constant expression).
15552 FoldConstant Fold(Info, true);
15553
15554 QualType ArgType = Arg->getType();
15555
15556 // __builtin_constant_p always has one operand. The rules which gcc follows
15557 // are not precisely documented, but are as follows:
15558 //
15559 // - If the operand is of integral, floating, complex or enumeration type,
15560 // and can be folded to a known value of that type, it returns 1.
15561 // - If the operand can be folded to a pointer to the first character
15562 // of a string literal (or such a pointer cast to an integral type)
15563 // or to a null pointer or an integer cast to a pointer, it returns 1.
15564 //
15565 // Otherwise, it returns 0.
15566 //
15567 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
15568 // its support for this did not work prior to GCC 9 and is not yet well
15569 // understood.
15570 if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
15571 ArgType->isAnyComplexType() || ArgType->isPointerType() ||
15572 ArgType->isNullPtrType()) {
15573 APValue V;
15574 if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) {
15575 Fold.keepDiagnostics();
15576 return false;
15577 }
15578
15579 // For a pointer (possibly cast to integer), there are special rules.
15580 if (V.getKind() == APValue::LValue)
15582
15583 // Otherwise, any constant value is good enough.
15584 return V.hasValue();
15585 }
15586
15587 // Anything else isn't considered to be sufficiently constant.
15588 return false;
15589}
15590
15591/// Retrieves the "underlying object type" of the given expression,
15592/// as used by __builtin_object_size.
15594 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
15595 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
15596 return VD->getType();
15597 } else if (const Expr *E = B.dyn_cast<const Expr*>()) {
15599 return E->getType();
15600 } else if (B.is<TypeInfoLValue>()) {
15601 return B.getTypeInfoType();
15602 } else if (B.is<DynamicAllocLValue>()) {
15603 return B.getDynamicAllocType();
15604 }
15605
15606 return QualType();
15607}
15608
15609/// A more selective version of E->IgnoreParenCasts for
15610/// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
15611/// to change the type of E.
15612/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
15613///
15614/// Always returns an RValue with a pointer representation.
15615static const Expr *ignorePointerCastsAndParens(const Expr *E) {
15616 assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
15617
15618 const Expr *NoParens = E->IgnoreParens();
15619 const auto *Cast = dyn_cast<CastExpr>(NoParens);
15620 if (Cast == nullptr)
15621 return NoParens;
15622
15623 // We only conservatively allow a few kinds of casts, because this code is
15624 // inherently a simple solution that seeks to support the common case.
15625 auto CastKind = Cast->getCastKind();
15626 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
15627 CastKind != CK_AddressSpaceConversion)
15628 return NoParens;
15629
15630 const auto *SubExpr = Cast->getSubExpr();
15631 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isPRValue())
15632 return NoParens;
15633 return ignorePointerCastsAndParens(SubExpr);
15634}
15635
15636/// Checks to see if the given LValue's Designator is at the end of the LValue's
15637/// record layout. e.g.
15638/// struct { struct { int a, b; } fst, snd; } obj;
15639/// obj.fst // no
15640/// obj.snd // yes
15641/// obj.fst.a // no
15642/// obj.fst.b // no
15643/// obj.snd.a // no
15644/// obj.snd.b // yes
15645///
15646/// Please note: this function is specialized for how __builtin_object_size
15647/// views "objects".
15648///
15649/// If this encounters an invalid RecordDecl or otherwise cannot determine the
15650/// correct result, it will always return true.
15651static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
15652 assert(!LVal.Designator.Invalid);
15653
15654 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD) {
15655 const RecordDecl *Parent = FD->getParent();
15656 if (Parent->isInvalidDecl() || Parent->isUnion())
15657 return true;
15658 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
15659 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
15660 };
15661
15662 auto &Base = LVal.getLValueBase();
15663 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
15664 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
15665 if (!IsLastOrInvalidFieldDecl(FD))
15666 return false;
15667 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
15668 for (auto *FD : IFD->chain()) {
15669 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD)))
15670 return false;
15671 }
15672 }
15673 }
15674
15675 unsigned I = 0;
15676 QualType BaseType = getType(Base);
15677 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
15678 // If we don't know the array bound, conservatively assume we're looking at
15679 // the final array element.
15680 ++I;
15681 if (BaseType->isIncompleteArrayType())
15682 BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
15683 else
15684 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
15685 }
15686
15687 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
15688 const auto &Entry = LVal.Designator.Entries[I];
15689 if (BaseType->isArrayType()) {
15690 // Because __builtin_object_size treats arrays as objects, we can ignore
15691 // the index iff this is the last array in the Designator.
15692 if (I + 1 == E)
15693 return true;
15694 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
15695 uint64_t Index = Entry.getAsArrayIndex();
15696 if (Index + 1 != CAT->getZExtSize())
15697 return false;
15698 BaseType = CAT->getElementType();
15699 } else if (BaseType->isAnyComplexType()) {
15700 const auto *CT = BaseType->castAs<ComplexType>();
15701 uint64_t Index = Entry.getAsArrayIndex();
15702 if (Index != 1)
15703 return false;
15704 BaseType = CT->getElementType();
15705 } else if (auto *FD = getAsField(Entry)) {
15706 if (!IsLastOrInvalidFieldDecl(FD))
15707 return false;
15708 BaseType = FD->getType();
15709 } else {
15710 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
15711 return false;
15712 }
15713 }
15714 return true;
15715}
15716
15717/// Tests to see if the LValue has a user-specified designator (that isn't
15718/// necessarily valid). Note that this always returns 'true' if the LValue has
15719/// an unsized array as its first designator entry, because there's currently no
15720/// way to tell if the user typed *foo or foo[0].
15721static bool refersToCompleteObject(const LValue &LVal) {
15722 if (LVal.Designator.Invalid)
15723 return false;
15724
15725 if (!LVal.Designator.Entries.empty())
15726 return LVal.Designator.isMostDerivedAnUnsizedArray();
15727
15728 if (!LVal.InvalidBase)
15729 return true;
15730
15731 // If `E` is a MemberExpr, then the first part of the designator is hiding in
15732 // the LValueBase.
15733 const auto *E = LVal.Base.dyn_cast<const Expr *>();
15734 return !E || !isa<MemberExpr>(E);
15735}
15736
15737/// Attempts to detect a user writing into a piece of memory that's impossible
15738/// to figure out the size of by just using types.
15739static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
15740 const SubobjectDesignator &Designator = LVal.Designator;
15741 // Notes:
15742 // - Users can only write off of the end when we have an invalid base. Invalid
15743 // bases imply we don't know where the memory came from.
15744 // - We used to be a bit more aggressive here; we'd only be conservative if
15745 // the array at the end was flexible, or if it had 0 or 1 elements. This
15746 // broke some common standard library extensions (PR30346), but was
15747 // otherwise seemingly fine. It may be useful to reintroduce this behavior
15748 // with some sort of list. OTOH, it seems that GCC is always
15749 // conservative with the last element in structs (if it's an array), so our
15750 // current behavior is more compatible than an explicit list approach would
15751 // be.
15752 auto isFlexibleArrayMember = [&] {
15754 FAMKind StrictFlexArraysLevel =
15755 Ctx.getLangOpts().getStrictFlexArraysLevel();
15756
15757 if (Designator.isMostDerivedAnUnsizedArray())
15758 return true;
15759
15760 if (StrictFlexArraysLevel == FAMKind::Default)
15761 return true;
15762
15763 if (Designator.getMostDerivedArraySize() == 0 &&
15764 StrictFlexArraysLevel != FAMKind::IncompleteOnly)
15765 return true;
15766
15767 if (Designator.getMostDerivedArraySize() == 1 &&
15768 StrictFlexArraysLevel == FAMKind::OneZeroOrIncomplete)
15769 return true;
15770
15771 return false;
15772 };
15773
15774 return LVal.InvalidBase &&
15775 Designator.Entries.size() == Designator.MostDerivedPathLength &&
15776 Designator.MostDerivedIsArrayElement && isFlexibleArrayMember() &&
15777 isDesignatorAtObjectEnd(Ctx, LVal);
15778}
15779
15780/// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
15781/// Fails if the conversion would cause loss of precision.
15782static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
15783 CharUnits &Result) {
15784 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
15785 if (Int.ugt(CharUnitsMax))
15786 return false;
15787 Result = CharUnits::fromQuantity(Int.getZExtValue());
15788 return true;
15789}
15790
15791/// If we're evaluating the object size of an instance of a struct that
15792/// contains a flexible array member, add the size of the initializer.
15793static void addFlexibleArrayMemberInitSize(EvalInfo &Info, const QualType &T,
15794 const LValue &LV, CharUnits &Size) {
15795 if (!T.isNull() && T->isStructureType() &&
15796 T->castAsRecordDecl()->hasFlexibleArrayMember())
15797 if (const auto *V = LV.getLValueBase().dyn_cast<const ValueDecl *>())
15798 if (const auto *VD = dyn_cast<VarDecl>(V))
15799 if (VD->hasInit())
15800 Size += VD->getFlexibleArrayInitChars(Info.Ctx);
15801}
15802
15803/// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
15804/// determine how many bytes exist from the beginning of the object to either
15805/// the end of the current subobject, or the end of the object itself, depending
15806/// on what the LValue looks like + the value of Type.
15807///
15808/// If this returns false, the value of Result is undefined.
15809static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
15810 unsigned Type, const LValue &LVal,
15811 CharUnits &EndOffset) {
15812 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
15813
15814 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
15815 if (Ty.isNull())
15816 return false;
15817
15818 Ty = Ty.getNonReferenceType();
15819
15820 if (Ty->isIncompleteType() || Ty->isFunctionType())
15821 return false;
15822
15823 return HandleSizeof(Info, ExprLoc, Ty, Result);
15824 };
15825
15826 // We want to evaluate the size of the entire object. This is a valid fallback
15827 // for when Type=1 and the designator is invalid, because we're asked for an
15828 // upper-bound.
15829 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
15830 // Type=3 wants a lower bound, so we can't fall back to this.
15831 if (Type == 3 && !DetermineForCompleteObject)
15832 return false;
15833
15834 llvm::APInt APEndOffset;
15835 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
15836 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
15837 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
15838
15839 if (LVal.InvalidBase)
15840 return false;
15841
15842 QualType BaseTy = getObjectType(LVal.getLValueBase());
15843 const bool Ret = CheckedHandleSizeof(BaseTy, EndOffset);
15844 addFlexibleArrayMemberInitSize(Info, BaseTy, LVal, EndOffset);
15845 return Ret;
15846 }
15847
15848 // We want to evaluate the size of a subobject.
15849 const SubobjectDesignator &Designator = LVal.Designator;
15850
15851 // The following is a moderately common idiom in C:
15852 //
15853 // struct Foo { int a; char c[1]; };
15854 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
15855 // strcpy(&F->c[0], Bar);
15856 //
15857 // In order to not break too much legacy code, we need to support it.
15858 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
15859 // If we can resolve this to an alloc_size call, we can hand that back,
15860 // because we know for certain how many bytes there are to write to.
15861 llvm::APInt APEndOffset;
15862 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
15863 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
15864 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
15865
15866 // If we cannot determine the size of the initial allocation, then we can't
15867 // given an accurate upper-bound. However, we are still able to give
15868 // conservative lower-bounds for Type=3.
15869 if (Type == 1)
15870 return false;
15871 }
15872
15873 CharUnits BytesPerElem;
15874 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
15875 return false;
15876
15877 // According to the GCC documentation, we want the size of the subobject
15878 // denoted by the pointer. But that's not quite right -- what we actually
15879 // want is the size of the immediately-enclosing array, if there is one.
15880 int64_t ElemsRemaining;
15881 if (Designator.MostDerivedIsArrayElement &&
15882 Designator.Entries.size() == Designator.MostDerivedPathLength) {
15883 uint64_t ArraySize = Designator.getMostDerivedArraySize();
15884 uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
15885 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
15886 } else {
15887 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
15888 }
15889
15890 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
15891 return true;
15892}
15893
15894/// Tries to evaluate the __builtin_object_size for @p E. If successful,
15895/// returns true and stores the result in @p Size.
15896///
15897/// If @p WasError is non-null, this will report whether the failure to evaluate
15898/// is to be treated as an Error in IntExprEvaluator.
15899static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
15900 EvalInfo &Info, uint64_t &Size) {
15901 // Determine the denoted object.
15902 LValue LVal;
15903 {
15904 // The operand of __builtin_object_size is never evaluated for side-effects.
15905 // If there are any, but we can determine the pointed-to object anyway, then
15906 // ignore the side-effects.
15907 SpeculativeEvaluationRAII SpeculativeEval(Info);
15908 IgnoreSideEffectsRAII Fold(Info);
15909
15910 if (E->isGLValue()) {
15911 // It's possible for us to be given GLValues if we're called via
15912 // Expr::tryEvaluateObjectSize.
15913 APValue RVal;
15914 if (!EvaluateAsRValue(Info, E, RVal))
15915 return false;
15916 LVal.setFrom(Info.Ctx, RVal);
15917 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
15918 /*InvalidBaseOK=*/true))
15919 return false;
15920 }
15921
15922 // If we point to before the start of the object, there are no accessible
15923 // bytes.
15924 if (LVal.getLValueOffset().isNegative()) {
15925 Size = 0;
15926 return true;
15927 }
15928
15929 CharUnits EndOffset;
15930 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
15931 return false;
15932
15933 // If we've fallen outside of the end offset, just pretend there's nothing to
15934 // write to/read from.
15935 if (EndOffset <= LVal.getLValueOffset())
15936 Size = 0;
15937 else
15938 Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
15939 return true;
15940}
15941
15942bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
15943 if (!IsConstantEvaluatedBuiltinCall(E))
15944 return ExprEvaluatorBaseTy::VisitCallExpr(E);
15945 return VisitBuiltinCallExpr(E, E->getBuiltinCallee());
15946}
15947
15948static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info,
15949 APValue &Val, APSInt &Alignment) {
15950 QualType SrcTy = E->getArg(0)->getType();
15951 if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment))
15952 return false;
15953 // Even though we are evaluating integer expressions we could get a pointer
15954 // argument for the __builtin_is_aligned() case.
15955 if (SrcTy->isPointerType()) {
15956 LValue Ptr;
15957 if (!EvaluatePointer(E->getArg(0), Ptr, Info))
15958 return false;
15959 Ptr.moveInto(Val);
15960 } else if (!SrcTy->isIntegralOrEnumerationType()) {
15961 Info.FFDiag(E->getArg(0));
15962 return false;
15963 } else {
15964 APSInt SrcInt;
15965 if (!EvaluateInteger(E->getArg(0), SrcInt, Info))
15966 return false;
15967 assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() &&
15968 "Bit widths must be the same");
15969 Val = APValue(SrcInt);
15970 }
15971 assert(Val.hasValue());
15972 return true;
15973}
15974
15975bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
15976 unsigned BuiltinOp) {
15977 auto EvalTestOp = [&](llvm::function_ref<bool(const APInt &, const APInt &)>
15978 Fn) {
15979 APValue SourceLHS, SourceRHS;
15980 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
15981 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
15982 return false;
15983
15984 unsigned SourceLen = SourceLHS.getVectorLength();
15985 const VectorType *VT = E->getArg(0)->getType()->castAs<VectorType>();
15986 QualType ElemQT = VT->getElementType();
15987 unsigned LaneWidth = Info.Ctx.getTypeSize(ElemQT);
15988
15989 APInt AWide(LaneWidth * SourceLen, 0);
15990 APInt BWide(LaneWidth * SourceLen, 0);
15991
15992 for (unsigned I = 0; I != SourceLen; ++I) {
15993 APInt ALane;
15994 APInt BLane;
15995 if (ElemQT->isIntegerType()) { // Get value.
15996 ALane = SourceLHS.getVectorElt(I).getInt();
15997 BLane = SourceRHS.getVectorElt(I).getInt();
15998 } else if (ElemQT->isFloatingType()) { // Get only sign bit.
15999 ALane =
16000 SourceLHS.getVectorElt(I).getFloat().bitcastToAPInt().isNegative();
16001 BLane =
16002 SourceRHS.getVectorElt(I).getFloat().bitcastToAPInt().isNegative();
16003 } else { // Must be integer or floating type.
16004 return false;
16005 }
16006 AWide.insertBits(ALane, I * LaneWidth);
16007 BWide.insertBits(BLane, I * LaneWidth);
16008 }
16009 return Success(Fn(AWide, BWide), E);
16010 };
16011
16012 auto HandleMaskBinOp =
16013 [&](llvm::function_ref<APSInt(const APSInt &, const APSInt &)> Fn)
16014 -> bool {
16015 APValue LHS, RHS;
16016 if (!Evaluate(LHS, Info, E->getArg(0)) ||
16017 !Evaluate(RHS, Info, E->getArg(1)))
16018 return false;
16019
16020 APSInt ResultInt = Fn(LHS.getInt(), RHS.getInt());
16021
16022 return Success(APValue(ResultInt), E);
16023 };
16024
16025 auto HandleCRC32 = [&](unsigned DataBytes) -> bool {
16026 APSInt CRC, Data;
16027 if (!EvaluateInteger(E->getArg(0), CRC, Info) ||
16028 !EvaluateInteger(E->getArg(1), Data, Info))
16029 return false;
16030
16031 uint64_t CRCVal = CRC.getZExtValue();
16032 uint64_t DataVal = Data.getZExtValue();
16033
16034 // CRC32C polynomial (iSCSI polynomial, bit-reversed)
16035 static const uint32_t CRC32C_POLY = 0x82F63B78;
16036
16037 // Process each byte
16038 uint32_t Result = static_cast<uint32_t>(CRCVal);
16039 for (unsigned I = 0; I != DataBytes; ++I) {
16040 uint8_t Byte = static_cast<uint8_t>((DataVal >> (I * 8)) & 0xFF);
16041 Result ^= Byte;
16042 for (int J = 0; J != 8; ++J) {
16043 Result = (Result >> 1) ^ ((Result & 1) ? CRC32C_POLY : 0);
16044 }
16045 }
16046
16047 return Success(Result, E);
16048 };
16049
16050 switch (BuiltinOp) {
16051 default:
16052 return false;
16053
16054 case X86::BI__builtin_ia32_crc32qi:
16055 return HandleCRC32(1);
16056 case X86::BI__builtin_ia32_crc32hi:
16057 return HandleCRC32(2);
16058 case X86::BI__builtin_ia32_crc32si:
16059 return HandleCRC32(4);
16060 case X86::BI__builtin_ia32_crc32di:
16061 return HandleCRC32(8);
16062
16063 case Builtin::BI__builtin_dynamic_object_size:
16064 case Builtin::BI__builtin_object_size: {
16065 // The type was checked when we built the expression.
16066 unsigned Type =
16067 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
16068 assert(Type <= 3 && "unexpected type");
16069
16070 uint64_t Size;
16071 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
16072 return Success(Size, E);
16073
16074 if (E->getArg(0)->HasSideEffects(Info.Ctx))
16075 return Success((Type & 2) ? 0 : -1, E);
16076
16077 // Expression had no side effects, but we couldn't statically determine the
16078 // size of the referenced object.
16079 switch (Info.EvalMode) {
16080 case EvaluationMode::ConstantExpression:
16081 case EvaluationMode::ConstantFold:
16082 case EvaluationMode::IgnoreSideEffects:
16083 // Leave it to IR generation.
16084 return Error(E);
16085 case EvaluationMode::ConstantExpressionUnevaluated:
16086 // Reduce it to a constant now.
16087 return Success((Type & 2) ? 0 : -1, E);
16088 }
16089
16090 llvm_unreachable("unexpected EvalMode");
16091 }
16092
16093 case Builtin::BI__builtin_os_log_format_buffer_size: {
16094 analyze_os_log::OSLogBufferLayout Layout;
16095 analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
16096 return Success(Layout.size().getQuantity(), E);
16097 }
16098
16099 case Builtin::BI__builtin_is_aligned: {
16100 APValue Src;
16101 APSInt Alignment;
16102 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
16103 return false;
16104 if (Src.isLValue()) {
16105 // If we evaluated a pointer, check the minimum known alignment.
16106 LValue Ptr;
16107 Ptr.setFrom(Info.Ctx, Src);
16108 CharUnits BaseAlignment = getBaseAlignment(Info, Ptr);
16109 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset);
16110 // We can return true if the known alignment at the computed offset is
16111 // greater than the requested alignment.
16112 assert(PtrAlign.isPowerOfTwo());
16113 assert(Alignment.isPowerOf2());
16114 if (PtrAlign.getQuantity() >= Alignment)
16115 return Success(1, E);
16116 // If the alignment is not known to be sufficient, some cases could still
16117 // be aligned at run time. However, if the requested alignment is less or
16118 // equal to the base alignment and the offset is not aligned, we know that
16119 // the run-time value can never be aligned.
16120 if (BaseAlignment.getQuantity() >= Alignment &&
16121 PtrAlign.getQuantity() < Alignment)
16122 return Success(0, E);
16123 // Otherwise we can't infer whether the value is sufficiently aligned.
16124 // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N)
16125 // in cases where we can't fully evaluate the pointer.
16126 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute)
16127 << Alignment;
16128 return false;
16129 }
16130 assert(Src.isInt());
16131 return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E);
16132 }
16133 case Builtin::BI__builtin_align_up: {
16134 APValue Src;
16135 APSInt Alignment;
16136 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
16137 return false;
16138 if (!Src.isInt())
16139 return Error(E);
16140 APSInt AlignedVal =
16141 APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1),
16142 Src.getInt().isUnsigned());
16143 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
16144 return Success(AlignedVal, E);
16145 }
16146 case Builtin::BI__builtin_align_down: {
16147 APValue Src;
16148 APSInt Alignment;
16149 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
16150 return false;
16151 if (!Src.isInt())
16152 return Error(E);
16153 APSInt AlignedVal =
16154 APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned());
16155 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
16156 return Success(AlignedVal, E);
16157 }
16158
16159 case Builtin::BI__builtin_bitreverse8:
16160 case Builtin::BI__builtin_bitreverse16:
16161 case Builtin::BI__builtin_bitreverse32:
16162 case Builtin::BI__builtin_bitreverse64:
16163 case Builtin::BI__builtin_elementwise_bitreverse: {
16164 APSInt Val;
16165 if (!EvaluateInteger(E->getArg(0), Val, Info))
16166 return false;
16167
16168 return Success(Val.reverseBits(), E);
16169 }
16170 case Builtin::BI__builtin_bswapg:
16171 case Builtin::BI__builtin_bswap16:
16172 case Builtin::BI__builtin_bswap32:
16173 case Builtin::BI__builtin_bswap64: {
16174 APSInt Val;
16175 if (!EvaluateInteger(E->getArg(0), Val, Info))
16176 return false;
16177 if (Val.getBitWidth() == 8)
16178 return Success(Val, E);
16179
16180 return Success(Val.byteSwap(), E);
16181 }
16182
16183 case Builtin::BI__builtin_classify_type:
16184 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
16185
16186 case Builtin::BI__builtin_clrsb:
16187 case Builtin::BI__builtin_clrsbl:
16188 case Builtin::BI__builtin_clrsbll: {
16189 APSInt Val;
16190 if (!EvaluateInteger(E->getArg(0), Val, Info))
16191 return false;
16192
16193 return Success(Val.getBitWidth() - Val.getSignificantBits(), E);
16194 }
16195
16196 case Builtin::BI__builtin_clz:
16197 case Builtin::BI__builtin_clzl:
16198 case Builtin::BI__builtin_clzll:
16199 case Builtin::BI__builtin_clzs:
16200 case Builtin::BI__builtin_clzg:
16201 case Builtin::BI__builtin_elementwise_clzg:
16202 case Builtin::BI__lzcnt16: // Microsoft variants of count leading-zeroes
16203 case Builtin::BI__lzcnt:
16204 case Builtin::BI__lzcnt64: {
16205 APSInt Val;
16206 if (E->getArg(0)->getType()->isExtVectorBoolType()) {
16207 APValue Vec;
16208 if (!EvaluateVector(E->getArg(0), Vec, Info))
16209 return false;
16210 Val = ConvertBoolVectorToInt(Vec);
16211 } else if (!EvaluateInteger(E->getArg(0), Val, Info)) {
16212 return false;
16213 }
16214
16215 std::optional<APSInt> Fallback;
16216 if ((BuiltinOp == Builtin::BI__builtin_clzg ||
16217 BuiltinOp == Builtin::BI__builtin_elementwise_clzg) &&
16218 E->getNumArgs() > 1) {
16219 APSInt FallbackTemp;
16220 if (!EvaluateInteger(E->getArg(1), FallbackTemp, Info))
16221 return false;
16222 Fallback = FallbackTemp;
16223 }
16224
16225 if (!Val) {
16226 if (Fallback)
16227 return Success(*Fallback, E);
16228
16229 // When the argument is 0, the result of GCC builtins is undefined,
16230 // whereas for Microsoft intrinsics, the result is the bit-width of the
16231 // argument.
16232 bool ZeroIsUndefined = BuiltinOp != Builtin::BI__lzcnt16 &&
16233 BuiltinOp != Builtin::BI__lzcnt &&
16234 BuiltinOp != Builtin::BI__lzcnt64;
16235
16236 if (BuiltinOp == Builtin::BI__builtin_elementwise_clzg) {
16237 Info.FFDiag(E, diag::note_constexpr_countzeroes_zero)
16238 << /*IsTrailing=*/false;
16239 }
16240
16241 if (ZeroIsUndefined)
16242 return Error(E);
16243 }
16244
16245 return Success(Val.countl_zero(), E);
16246 }
16247
16248 case Builtin::BI__builtin_constant_p: {
16249 const Expr *Arg = E->getArg(0);
16250 if (EvaluateBuiltinConstantP(Info, Arg))
16251 return Success(true, E);
16252 if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
16253 // Outside a constant context, eagerly evaluate to false in the presence
16254 // of side-effects in order to avoid -Wunsequenced false-positives in
16255 // a branch on __builtin_constant_p(expr).
16256 return Success(false, E);
16257 }
16258 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
16259 return false;
16260 }
16261
16262 case Builtin::BI__noop:
16263 // __noop always evaluates successfully and returns 0.
16264 return Success(0, E);
16265
16266 case Builtin::BI__builtin_is_constant_evaluated: {
16267 const auto *Callee = Info.CurrentCall->getCallee();
16268 if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression &&
16269 (Info.CallStackDepth == 1 ||
16270 (Info.CallStackDepth == 2 && Callee->isInStdNamespace() &&
16271 Callee->getIdentifier() &&
16272 Callee->getIdentifier()->isStr("is_constant_evaluated")))) {
16273 // FIXME: Find a better way to avoid duplicated diagnostics.
16274 if (Info.EvalStatus.Diag)
16275 Info.report((Info.CallStackDepth == 1)
16276 ? E->getExprLoc()
16277 : Info.CurrentCall->getCallRange().getBegin(),
16278 diag::warn_is_constant_evaluated_always_true_constexpr)
16279 << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated"
16280 : "std::is_constant_evaluated");
16281 }
16282
16283 return Success(Info.InConstantContext, E);
16284 }
16285
16286 case Builtin::BI__builtin_is_within_lifetime:
16287 if (auto result = EvaluateBuiltinIsWithinLifetime(*this, E))
16288 return Success(*result, E);
16289 return false;
16290
16291 case Builtin::BI__builtin_ctz:
16292 case Builtin::BI__builtin_ctzl:
16293 case Builtin::BI__builtin_ctzll:
16294 case Builtin::BI__builtin_ctzs:
16295 case Builtin::BI__builtin_ctzg:
16296 case Builtin::BI__builtin_elementwise_ctzg: {
16297 APSInt Val;
16298 if (E->getArg(0)->getType()->isExtVectorBoolType()) {
16299 APValue Vec;
16300 if (!EvaluateVector(E->getArg(0), Vec, Info))
16301 return false;
16302 Val = ConvertBoolVectorToInt(Vec);
16303 } else if (!EvaluateInteger(E->getArg(0), Val, Info)) {
16304 return false;
16305 }
16306
16307 std::optional<APSInt> Fallback;
16308 if ((BuiltinOp == Builtin::BI__builtin_ctzg ||
16309 BuiltinOp == Builtin::BI__builtin_elementwise_ctzg) &&
16310 E->getNumArgs() > 1) {
16311 APSInt FallbackTemp;
16312 if (!EvaluateInteger(E->getArg(1), FallbackTemp, Info))
16313 return false;
16314 Fallback = FallbackTemp;
16315 }
16316
16317 if (!Val) {
16318 if (Fallback)
16319 return Success(*Fallback, E);
16320
16321 if (BuiltinOp == Builtin::BI__builtin_elementwise_ctzg) {
16322 Info.FFDiag(E, diag::note_constexpr_countzeroes_zero)
16323 << /*IsTrailing=*/true;
16324 }
16325 return Error(E);
16326 }
16327
16328 return Success(Val.countr_zero(), E);
16329 }
16330
16331 case Builtin::BI__builtin_eh_return_data_regno: {
16332 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
16333 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
16334 return Success(Operand, E);
16335 }
16336
16337 case Builtin::BI__builtin_elementwise_abs: {
16338 APSInt Val;
16339 if (!EvaluateInteger(E->getArg(0), Val, Info))
16340 return false;
16341
16342 return Success(Val.abs(), E);
16343 }
16344
16345 case Builtin::BI__builtin_expect:
16346 case Builtin::BI__builtin_expect_with_probability:
16347 return Visit(E->getArg(0));
16348
16349 case Builtin::BI__builtin_ptrauth_string_discriminator: {
16350 const auto *Literal =
16352 uint64_t Result = getPointerAuthStableSipHash(Literal->getString());
16353 return Success(Result, E);
16354 }
16355
16356 case Builtin::BI__builtin_infer_alloc_token: {
16357 // If we fail to infer a type, this fails to be a constant expression; this
16358 // can be checked with __builtin_constant_p(...).
16359 QualType AllocType = infer_alloc::inferPossibleType(E, Info.Ctx, nullptr);
16360 if (AllocType.isNull())
16361 return Error(
16362 E, diag::note_constexpr_infer_alloc_token_type_inference_failed);
16363 auto ATMD = infer_alloc::getAllocTokenMetadata(AllocType, Info.Ctx);
16364 if (!ATMD)
16365 return Error(E, diag::note_constexpr_infer_alloc_token_no_metadata);
16366 auto Mode =
16367 Info.getLangOpts().AllocTokenMode.value_or(llvm::DefaultAllocTokenMode);
16368 uint64_t BitWidth = Info.Ctx.getTypeSize(Info.Ctx.getSizeType());
16369 auto MaxTokensOpt = Info.getLangOpts().AllocTokenMax;
16370 uint64_t MaxTokens =
16371 MaxTokensOpt.value_or(0) ? *MaxTokensOpt : (~0ULL >> (64 - BitWidth));
16372 auto MaybeToken = llvm::getAllocToken(Mode, *ATMD, MaxTokens);
16373 if (!MaybeToken)
16374 return Error(E, diag::note_constexpr_infer_alloc_token_stateful_mode);
16375 return Success(llvm::APInt(BitWidth, *MaybeToken), E);
16376 }
16377
16378 case Builtin::BI__builtin_ffs:
16379 case Builtin::BI__builtin_ffsl:
16380 case Builtin::BI__builtin_ffsll: {
16381 APSInt Val;
16382 if (!EvaluateInteger(E->getArg(0), Val, Info))
16383 return false;
16384
16385 unsigned N = Val.countr_zero();
16386 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
16387 }
16388
16389 case Builtin::BI__builtin_fpclassify: {
16390 APFloat Val(0.0);
16391 if (!EvaluateFloat(E->getArg(5), Val, Info))
16392 return false;
16393 unsigned Arg;
16394 switch (Val.getCategory()) {
16395 case APFloat::fcNaN: Arg = 0; break;
16396 case APFloat::fcInfinity: Arg = 1; break;
16397 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
16398 case APFloat::fcZero: Arg = 4; break;
16399 }
16400 return Visit(E->getArg(Arg));
16401 }
16402
16403 case Builtin::BI__builtin_isinf_sign: {
16404 APFloat Val(0.0);
16405 return EvaluateFloat(E->getArg(0), Val, Info) &&
16406 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
16407 }
16408
16409 case Builtin::BI__builtin_isinf: {
16410 APFloat Val(0.0);
16411 return EvaluateFloat(E->getArg(0), Val, Info) &&
16412 Success(Val.isInfinity() ? 1 : 0, E);
16413 }
16414
16415 case Builtin::BI__builtin_isfinite: {
16416 APFloat Val(0.0);
16417 return EvaluateFloat(E->getArg(0), Val, Info) &&
16418 Success(Val.isFinite() ? 1 : 0, E);
16419 }
16420
16421 case Builtin::BI__builtin_isnan: {
16422 APFloat Val(0.0);
16423 return EvaluateFloat(E->getArg(0), Val, Info) &&
16424 Success(Val.isNaN() ? 1 : 0, E);
16425 }
16426
16427 case Builtin::BI__builtin_isnormal: {
16428 APFloat Val(0.0);
16429 return EvaluateFloat(E->getArg(0), Val, Info) &&
16430 Success(Val.isNormal() ? 1 : 0, E);
16431 }
16432
16433 case Builtin::BI__builtin_issubnormal: {
16434 APFloat Val(0.0);
16435 return EvaluateFloat(E->getArg(0), Val, Info) &&
16436 Success(Val.isDenormal() ? 1 : 0, E);
16437 }
16438
16439 case Builtin::BI__builtin_iszero: {
16440 APFloat Val(0.0);
16441 return EvaluateFloat(E->getArg(0), Val, Info) &&
16442 Success(Val.isZero() ? 1 : 0, E);
16443 }
16444
16445 case Builtin::BI__builtin_signbit:
16446 case Builtin::BI__builtin_signbitf:
16447 case Builtin::BI__builtin_signbitl: {
16448 APFloat Val(0.0);
16449 return EvaluateFloat(E->getArg(0), Val, Info) &&
16450 Success(Val.isNegative() ? 1 : 0, E);
16451 }
16452
16453 case Builtin::BI__builtin_isgreater:
16454 case Builtin::BI__builtin_isgreaterequal:
16455 case Builtin::BI__builtin_isless:
16456 case Builtin::BI__builtin_islessequal:
16457 case Builtin::BI__builtin_islessgreater:
16458 case Builtin::BI__builtin_isunordered: {
16459 APFloat LHS(0.0);
16460 APFloat RHS(0.0);
16461 if (!EvaluateFloat(E->getArg(0), LHS, Info) ||
16462 !EvaluateFloat(E->getArg(1), RHS, Info))
16463 return false;
16464
16465 return Success(
16466 [&] {
16467 switch (BuiltinOp) {
16468 case Builtin::BI__builtin_isgreater:
16469 return LHS > RHS;
16470 case Builtin::BI__builtin_isgreaterequal:
16471 return LHS >= RHS;
16472 case Builtin::BI__builtin_isless:
16473 return LHS < RHS;
16474 case Builtin::BI__builtin_islessequal:
16475 return LHS <= RHS;
16476 case Builtin::BI__builtin_islessgreater: {
16477 APFloat::cmpResult cmp = LHS.compare(RHS);
16478 return cmp == APFloat::cmpResult::cmpLessThan ||
16479 cmp == APFloat::cmpResult::cmpGreaterThan;
16480 }
16481 case Builtin::BI__builtin_isunordered:
16482 return LHS.compare(RHS) == APFloat::cmpResult::cmpUnordered;
16483 default:
16484 llvm_unreachable("Unexpected builtin ID: Should be a floating "
16485 "point comparison function");
16486 }
16487 }()
16488 ? 1
16489 : 0,
16490 E);
16491 }
16492
16493 case Builtin::BI__builtin_issignaling: {
16494 APFloat Val(0.0);
16495 return EvaluateFloat(E->getArg(0), Val, Info) &&
16496 Success(Val.isSignaling() ? 1 : 0, E);
16497 }
16498
16499 case Builtin::BI__builtin_isfpclass: {
16500 APSInt MaskVal;
16501 if (!EvaluateInteger(E->getArg(1), MaskVal, Info))
16502 return false;
16503 unsigned Test = static_cast<llvm::FPClassTest>(MaskVal.getZExtValue());
16504 APFloat Val(0.0);
16505 return EvaluateFloat(E->getArg(0), Val, Info) &&
16506 Success((Val.classify() & Test) ? 1 : 0, E);
16507 }
16508
16509 case Builtin::BI__builtin_parity:
16510 case Builtin::BI__builtin_parityl:
16511 case Builtin::BI__builtin_parityll: {
16512 APSInt Val;
16513 if (!EvaluateInteger(E->getArg(0), Val, Info))
16514 return false;
16515
16516 return Success(Val.popcount() % 2, E);
16517 }
16518
16519 case Builtin::BI__builtin_abs:
16520 case Builtin::BI__builtin_labs:
16521 case Builtin::BI__builtin_llabs: {
16522 APSInt Val;
16523 if (!EvaluateInteger(E->getArg(0), Val, Info))
16524 return false;
16525 if (Val == APSInt(APInt::getSignedMinValue(Val.getBitWidth()),
16526 /*IsUnsigned=*/false))
16527 return false;
16528 if (Val.isNegative())
16529 Val.negate();
16530 return Success(Val, E);
16531 }
16532
16533 case Builtin::BI__builtin_popcount:
16534 case Builtin::BI__builtin_popcountl:
16535 case Builtin::BI__builtin_popcountll:
16536 case Builtin::BI__builtin_popcountg:
16537 case Builtin::BI__builtin_elementwise_popcount:
16538 case Builtin::BI__popcnt16: // Microsoft variants of popcount
16539 case Builtin::BI__popcnt:
16540 case Builtin::BI__popcnt64: {
16541 APSInt Val;
16542 if (E->getArg(0)->getType()->isExtVectorBoolType()) {
16543 APValue Vec;
16544 if (!EvaluateVector(E->getArg(0), Vec, Info))
16545 return false;
16546 Val = ConvertBoolVectorToInt(Vec);
16547 } else if (!EvaluateInteger(E->getArg(0), Val, Info)) {
16548 return false;
16549 }
16550
16551 return Success(Val.popcount(), E);
16552 }
16553
16554 case Builtin::BI__builtin_rotateleft8:
16555 case Builtin::BI__builtin_rotateleft16:
16556 case Builtin::BI__builtin_rotateleft32:
16557 case Builtin::BI__builtin_rotateleft64:
16558 case Builtin::BI__builtin_rotateright8:
16559 case Builtin::BI__builtin_rotateright16:
16560 case Builtin::BI__builtin_rotateright32:
16561 case Builtin::BI__builtin_rotateright64:
16562 case Builtin::BI__builtin_stdc_rotate_left:
16563 case Builtin::BI__builtin_stdc_rotate_right:
16564 case Builtin::BI_rotl8: // Microsoft variants of rotate left
16565 case Builtin::BI_rotl16:
16566 case Builtin::BI_rotl:
16567 case Builtin::BI_lrotl:
16568 case Builtin::BI_rotl64:
16569 case Builtin::BI_rotr8: // Microsoft variants of rotate right
16570 case Builtin::BI_rotr16:
16571 case Builtin::BI_rotr:
16572 case Builtin::BI_lrotr:
16573 case Builtin::BI_rotr64: {
16574 APSInt Value, Amount;
16575 if (!EvaluateInteger(E->getArg(0), Value, Info) ||
16576 !EvaluateInteger(E->getArg(1), Amount, Info))
16577 return false;
16578
16579 Amount = NormalizeRotateAmount(Value, Amount);
16580
16581 switch (BuiltinOp) {
16582 case Builtin::BI__builtin_rotateright8:
16583 case Builtin::BI__builtin_rotateright16:
16584 case Builtin::BI__builtin_rotateright32:
16585 case Builtin::BI__builtin_rotateright64:
16586 case Builtin::BI__builtin_stdc_rotate_right:
16587 case Builtin::BI_rotr8:
16588 case Builtin::BI_rotr16:
16589 case Builtin::BI_rotr:
16590 case Builtin::BI_lrotr:
16591 case Builtin::BI_rotr64:
16592 return Success(
16593 APSInt(Value.rotr(Amount.getZExtValue()), Value.isUnsigned()), E);
16594 default:
16595 return Success(
16596 APSInt(Value.rotl(Amount.getZExtValue()), Value.isUnsigned()), E);
16597 }
16598 }
16599
16600 case Builtin::BI__builtin_elementwise_add_sat: {
16601 APSInt LHS, RHS;
16602 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
16603 !EvaluateInteger(E->getArg(1), RHS, Info))
16604 return false;
16605
16606 APInt Result = LHS.isSigned() ? LHS.sadd_sat(RHS) : LHS.uadd_sat(RHS);
16607 return Success(APSInt(Result, !LHS.isSigned()), E);
16608 }
16609 case Builtin::BI__builtin_elementwise_sub_sat: {
16610 APSInt LHS, RHS;
16611 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
16612 !EvaluateInteger(E->getArg(1), RHS, Info))
16613 return false;
16614
16615 APInt Result = LHS.isSigned() ? LHS.ssub_sat(RHS) : LHS.usub_sat(RHS);
16616 return Success(APSInt(Result, !LHS.isSigned()), E);
16617 }
16618 case Builtin::BI__builtin_elementwise_max: {
16619 APSInt LHS, RHS;
16620 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
16621 !EvaluateInteger(E->getArg(1), RHS, Info))
16622 return false;
16623
16624 APInt Result = std::max(LHS, RHS);
16625 return Success(APSInt(Result, !LHS.isSigned()), E);
16626 }
16627 case Builtin::BI__builtin_elementwise_min: {
16628 APSInt LHS, RHS;
16629 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
16630 !EvaluateInteger(E->getArg(1), RHS, Info))
16631 return false;
16632
16633 APInt Result = std::min(LHS, RHS);
16634 return Success(APSInt(Result, !LHS.isSigned()), E);
16635 }
16636 case Builtin::BI__builtin_elementwise_fshl:
16637 case Builtin::BI__builtin_elementwise_fshr: {
16638 APSInt Hi, Lo, Shift;
16639 if (!EvaluateInteger(E->getArg(0), Hi, Info) ||
16640 !EvaluateInteger(E->getArg(1), Lo, Info) ||
16641 !EvaluateInteger(E->getArg(2), Shift, Info))
16642 return false;
16643
16644 switch (BuiltinOp) {
16645 case Builtin::BI__builtin_elementwise_fshl: {
16646 APSInt Result(llvm::APIntOps::fshl(Hi, Lo, Shift), Hi.isUnsigned());
16647 return Success(Result, E);
16648 }
16649 case Builtin::BI__builtin_elementwise_fshr: {
16650 APSInt Result(llvm::APIntOps::fshr(Hi, Lo, Shift), Hi.isUnsigned());
16651 return Success(Result, E);
16652 }
16653 }
16654 llvm_unreachable("Fully covered switch above");
16655 }
16656 case Builtin::BIstrlen:
16657 case Builtin::BIwcslen:
16658 // A call to strlen is not a constant expression.
16659 if (Info.getLangOpts().CPlusPlus11)
16660 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
16661 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
16662 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
16663 else
16664 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
16665 [[fallthrough]];
16666 case Builtin::BI__builtin_strlen:
16667 case Builtin::BI__builtin_wcslen: {
16668 // As an extension, we support __builtin_strlen() as a constant expression,
16669 // and support folding strlen() to a constant.
16670 uint64_t StrLen;
16671 if (EvaluateBuiltinStrLen(E->getArg(0), StrLen, Info))
16672 return Success(StrLen, E);
16673 return false;
16674 }
16675
16676 case Builtin::BIstrcmp:
16677 case Builtin::BIwcscmp:
16678 case Builtin::BIstrncmp:
16679 case Builtin::BIwcsncmp:
16680 case Builtin::BImemcmp:
16681 case Builtin::BIbcmp:
16682 case Builtin::BIwmemcmp:
16683 // A call to strlen is not a constant expression.
16684 if (Info.getLangOpts().CPlusPlus11)
16685 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
16686 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
16687 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
16688 else
16689 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
16690 [[fallthrough]];
16691 case Builtin::BI__builtin_strcmp:
16692 case Builtin::BI__builtin_wcscmp:
16693 case Builtin::BI__builtin_strncmp:
16694 case Builtin::BI__builtin_wcsncmp:
16695 case Builtin::BI__builtin_memcmp:
16696 case Builtin::BI__builtin_bcmp:
16697 case Builtin::BI__builtin_wmemcmp: {
16698 LValue String1, String2;
16699 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
16700 !EvaluatePointer(E->getArg(1), String2, Info))
16701 return false;
16702
16703 uint64_t MaxLength = uint64_t(-1);
16704 if (BuiltinOp != Builtin::BIstrcmp &&
16705 BuiltinOp != Builtin::BIwcscmp &&
16706 BuiltinOp != Builtin::BI__builtin_strcmp &&
16707 BuiltinOp != Builtin::BI__builtin_wcscmp) {
16708 APSInt N;
16709 if (!EvaluateInteger(E->getArg(2), N, Info))
16710 return false;
16711 MaxLength = N.getZExtValue();
16712 }
16713
16714 // Empty substrings compare equal by definition.
16715 if (MaxLength == 0u)
16716 return Success(0, E);
16717
16718 if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
16719 !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
16720 String1.Designator.Invalid || String2.Designator.Invalid)
16721 return false;
16722
16723 QualType CharTy1 = String1.Designator.getType(Info.Ctx);
16724 QualType CharTy2 = String2.Designator.getType(Info.Ctx);
16725
16726 bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
16727 BuiltinOp == Builtin::BIbcmp ||
16728 BuiltinOp == Builtin::BI__builtin_memcmp ||
16729 BuiltinOp == Builtin::BI__builtin_bcmp;
16730
16731 assert(IsRawByte ||
16732 (Info.Ctx.hasSameUnqualifiedType(
16733 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
16734 Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
16735
16736 // For memcmp, allow comparing any arrays of '[[un]signed] char' or
16737 // 'char8_t', but no other types.
16738 if (IsRawByte &&
16739 !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) {
16740 // FIXME: Consider using our bit_cast implementation to support this.
16741 Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported)
16742 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp) << CharTy1
16743 << CharTy2;
16744 return false;
16745 }
16746
16747 const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
16748 return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
16749 handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
16750 Char1.isInt() && Char2.isInt();
16751 };
16752 const auto &AdvanceElems = [&] {
16753 return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
16754 HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
16755 };
16756
16757 bool StopAtNull =
16758 (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
16759 BuiltinOp != Builtin::BIwmemcmp &&
16760 BuiltinOp != Builtin::BI__builtin_memcmp &&
16761 BuiltinOp != Builtin::BI__builtin_bcmp &&
16762 BuiltinOp != Builtin::BI__builtin_wmemcmp);
16763 bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
16764 BuiltinOp == Builtin::BIwcsncmp ||
16765 BuiltinOp == Builtin::BIwmemcmp ||
16766 BuiltinOp == Builtin::BI__builtin_wcscmp ||
16767 BuiltinOp == Builtin::BI__builtin_wcsncmp ||
16768 BuiltinOp == Builtin::BI__builtin_wmemcmp;
16769
16770 for (; MaxLength; --MaxLength) {
16771 APValue Char1, Char2;
16772 if (!ReadCurElems(Char1, Char2))
16773 return false;
16774 if (Char1.getInt().ne(Char2.getInt())) {
16775 if (IsWide) // wmemcmp compares with wchar_t signedness.
16776 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
16777 // memcmp always compares unsigned chars.
16778 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
16779 }
16780 if (StopAtNull && !Char1.getInt())
16781 return Success(0, E);
16782 assert(!(StopAtNull && !Char2.getInt()));
16783 if (!AdvanceElems())
16784 return false;
16785 }
16786 // We hit the strncmp / memcmp limit.
16787 return Success(0, E);
16788 }
16789
16790 case Builtin::BI__atomic_always_lock_free:
16791 case Builtin::BI__atomic_is_lock_free:
16792 case Builtin::BI__c11_atomic_is_lock_free: {
16793 APSInt SizeVal;
16794 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
16795 return false;
16796
16797 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
16798 // of two less than or equal to the maximum inline atomic width, we know it
16799 // is lock-free. If the size isn't a power of two, or greater than the
16800 // maximum alignment where we promote atomics, we know it is not lock-free
16801 // (at least not in the sense of atomic_is_lock_free). Otherwise,
16802 // the answer can only be determined at runtime; for example, 16-byte
16803 // atomics have lock-free implementations on some, but not all,
16804 // x86-64 processors.
16805
16806 // Check power-of-two.
16807 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
16808 if (Size.isPowerOfTwo()) {
16809 // Check against inlining width.
16810 unsigned InlineWidthBits =
16812 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
16813 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
16814 Size == CharUnits::One())
16815 return Success(1, E);
16816
16817 // If the pointer argument can be evaluated to a compile-time constant
16818 // integer (or nullptr), check if that value is appropriately aligned.
16819 const Expr *PtrArg = E->getArg(1);
16820 Expr::EvalResult ExprResult;
16821 APSInt IntResult;
16822 if (PtrArg->EvaluateAsRValue(ExprResult, Info.Ctx) &&
16823 ExprResult.Val.toIntegralConstant(IntResult, PtrArg->getType(),
16824 Info.Ctx) &&
16825 IntResult.isAligned(Size.getAsAlign()))
16826 return Success(1, E);
16827
16828 // Otherwise, check if the type's alignment against Size.
16829 if (auto *ICE = dyn_cast<ImplicitCastExpr>(PtrArg)) {
16830 // Drop the potential implicit-cast to 'const volatile void*', getting
16831 // the underlying type.
16832 if (ICE->getCastKind() == CK_BitCast)
16833 PtrArg = ICE->getSubExpr();
16834 }
16835
16836 if (auto PtrTy = PtrArg->getType()->getAs<PointerType>()) {
16837 QualType PointeeType = PtrTy->getPointeeType();
16838 if (!PointeeType->isIncompleteType() &&
16839 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
16840 // OK, we will inline operations on this object.
16841 return Success(1, E);
16842 }
16843 }
16844 }
16845 }
16846
16847 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
16848 Success(0, E) : Error(E);
16849 }
16850 case Builtin::BI__builtin_addcb:
16851 case Builtin::BI__builtin_addcs:
16852 case Builtin::BI__builtin_addc:
16853 case Builtin::BI__builtin_addcl:
16854 case Builtin::BI__builtin_addcll:
16855 case Builtin::BI__builtin_subcb:
16856 case Builtin::BI__builtin_subcs:
16857 case Builtin::BI__builtin_subc:
16858 case Builtin::BI__builtin_subcl:
16859 case Builtin::BI__builtin_subcll: {
16860 LValue CarryOutLValue;
16861 APSInt LHS, RHS, CarryIn, CarryOut, Result;
16862 QualType ResultType = E->getArg(0)->getType();
16863 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
16864 !EvaluateInteger(E->getArg(1), RHS, Info) ||
16865 !EvaluateInteger(E->getArg(2), CarryIn, Info) ||
16866 !EvaluatePointer(E->getArg(3), CarryOutLValue, Info))
16867 return false;
16868 // Copy the number of bits and sign.
16869 Result = LHS;
16870 CarryOut = LHS;
16871
16872 bool FirstOverflowed = false;
16873 bool SecondOverflowed = false;
16874 switch (BuiltinOp) {
16875 default:
16876 llvm_unreachable("Invalid value for BuiltinOp");
16877 case Builtin::BI__builtin_addcb:
16878 case Builtin::BI__builtin_addcs:
16879 case Builtin::BI__builtin_addc:
16880 case Builtin::BI__builtin_addcl:
16881 case Builtin::BI__builtin_addcll:
16882 Result =
16883 LHS.uadd_ov(RHS, FirstOverflowed).uadd_ov(CarryIn, SecondOverflowed);
16884 break;
16885 case Builtin::BI__builtin_subcb:
16886 case Builtin::BI__builtin_subcs:
16887 case Builtin::BI__builtin_subc:
16888 case Builtin::BI__builtin_subcl:
16889 case Builtin::BI__builtin_subcll:
16890 Result =
16891 LHS.usub_ov(RHS, FirstOverflowed).usub_ov(CarryIn, SecondOverflowed);
16892 break;
16893 }
16894
16895 // It is possible for both overflows to happen but CGBuiltin uses an OR so
16896 // this is consistent.
16897 CarryOut = (uint64_t)(FirstOverflowed | SecondOverflowed);
16898 APValue APV{CarryOut};
16899 if (!handleAssignment(Info, E, CarryOutLValue, ResultType, APV))
16900 return false;
16901 return Success(Result, E);
16902 }
16903 case Builtin::BI__builtin_add_overflow:
16904 case Builtin::BI__builtin_sub_overflow:
16905 case Builtin::BI__builtin_mul_overflow:
16906 case Builtin::BI__builtin_sadd_overflow:
16907 case Builtin::BI__builtin_uadd_overflow:
16908 case Builtin::BI__builtin_uaddl_overflow:
16909 case Builtin::BI__builtin_uaddll_overflow:
16910 case Builtin::BI__builtin_usub_overflow:
16911 case Builtin::BI__builtin_usubl_overflow:
16912 case Builtin::BI__builtin_usubll_overflow:
16913 case Builtin::BI__builtin_umul_overflow:
16914 case Builtin::BI__builtin_umull_overflow:
16915 case Builtin::BI__builtin_umulll_overflow:
16916 case Builtin::BI__builtin_saddl_overflow:
16917 case Builtin::BI__builtin_saddll_overflow:
16918 case Builtin::BI__builtin_ssub_overflow:
16919 case Builtin::BI__builtin_ssubl_overflow:
16920 case Builtin::BI__builtin_ssubll_overflow:
16921 case Builtin::BI__builtin_smul_overflow:
16922 case Builtin::BI__builtin_smull_overflow:
16923 case Builtin::BI__builtin_smulll_overflow: {
16924 LValue ResultLValue;
16925 APSInt LHS, RHS;
16926
16927 QualType ResultType = E->getArg(2)->getType()->getPointeeType();
16928 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
16929 !EvaluateInteger(E->getArg(1), RHS, Info) ||
16930 !EvaluatePointer(E->getArg(2), ResultLValue, Info))
16931 return false;
16932
16933 APSInt Result;
16934 bool DidOverflow = false;
16935
16936 // If the types don't have to match, enlarge all 3 to the largest of them.
16937 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
16938 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
16939 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
16940 bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
16942 bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
16944 uint64_t LHSSize = LHS.getBitWidth();
16945 uint64_t RHSSize = RHS.getBitWidth();
16946 uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
16947 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
16948
16949 // Add an additional bit if the signedness isn't uniformly agreed to. We
16950 // could do this ONLY if there is a signed and an unsigned that both have
16951 // MaxBits, but the code to check that is pretty nasty. The issue will be
16952 // caught in the shrink-to-result later anyway.
16953 if (IsSigned && !AllSigned)
16954 ++MaxBits;
16955
16956 LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
16957 RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
16958 Result = APSInt(MaxBits, !IsSigned);
16959 }
16960
16961 // Find largest int.
16962 switch (BuiltinOp) {
16963 default:
16964 llvm_unreachable("Invalid value for BuiltinOp");
16965 case Builtin::BI__builtin_add_overflow:
16966 case Builtin::BI__builtin_sadd_overflow:
16967 case Builtin::BI__builtin_saddl_overflow:
16968 case Builtin::BI__builtin_saddll_overflow:
16969 case Builtin::BI__builtin_uadd_overflow:
16970 case Builtin::BI__builtin_uaddl_overflow:
16971 case Builtin::BI__builtin_uaddll_overflow:
16972 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
16973 : LHS.uadd_ov(RHS, DidOverflow);
16974 break;
16975 case Builtin::BI__builtin_sub_overflow:
16976 case Builtin::BI__builtin_ssub_overflow:
16977 case Builtin::BI__builtin_ssubl_overflow:
16978 case Builtin::BI__builtin_ssubll_overflow:
16979 case Builtin::BI__builtin_usub_overflow:
16980 case Builtin::BI__builtin_usubl_overflow:
16981 case Builtin::BI__builtin_usubll_overflow:
16982 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
16983 : LHS.usub_ov(RHS, DidOverflow);
16984 break;
16985 case Builtin::BI__builtin_mul_overflow:
16986 case Builtin::BI__builtin_smul_overflow:
16987 case Builtin::BI__builtin_smull_overflow:
16988 case Builtin::BI__builtin_smulll_overflow:
16989 case Builtin::BI__builtin_umul_overflow:
16990 case Builtin::BI__builtin_umull_overflow:
16991 case Builtin::BI__builtin_umulll_overflow:
16992 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
16993 : LHS.umul_ov(RHS, DidOverflow);
16994 break;
16995 }
16996
16997 // In the case where multiple sizes are allowed, truncate and see if
16998 // the values are the same.
16999 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
17000 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
17001 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
17002 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
17003 // since it will give us the behavior of a TruncOrSelf in the case where
17004 // its parameter <= its size. We previously set Result to be at least the
17005 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
17006 // will work exactly like TruncOrSelf.
17007 APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
17008 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
17009
17010 if (!APSInt::isSameValue(Temp, Result))
17011 DidOverflow = true;
17012 Result = Temp;
17013 }
17014
17015 APValue APV{Result};
17016 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
17017 return false;
17018 return Success(DidOverflow, E);
17019 }
17020
17021 case Builtin::BI__builtin_reduce_add:
17022 case Builtin::BI__builtin_reduce_mul:
17023 case Builtin::BI__builtin_reduce_and:
17024 case Builtin::BI__builtin_reduce_or:
17025 case Builtin::BI__builtin_reduce_xor:
17026 case Builtin::BI__builtin_reduce_min:
17027 case Builtin::BI__builtin_reduce_max: {
17028 APValue Source;
17029 if (!EvaluateAsRValue(Info, E->getArg(0), Source))
17030 return false;
17031
17032 unsigned SourceLen = Source.getVectorLength();
17033 APSInt Reduced = Source.getVectorElt(0).getInt();
17034 for (unsigned EltNum = 1; EltNum < SourceLen; ++EltNum) {
17035 switch (BuiltinOp) {
17036 default:
17037 return false;
17038 case Builtin::BI__builtin_reduce_add: {
17040 Info, E, Reduced, Source.getVectorElt(EltNum).getInt(),
17041 Reduced.getBitWidth() + 1, std::plus<APSInt>(), Reduced))
17042 return false;
17043 break;
17044 }
17045 case Builtin::BI__builtin_reduce_mul: {
17047 Info, E, Reduced, Source.getVectorElt(EltNum).getInt(),
17048 Reduced.getBitWidth() * 2, std::multiplies<APSInt>(), Reduced))
17049 return false;
17050 break;
17051 }
17052 case Builtin::BI__builtin_reduce_and: {
17053 Reduced &= Source.getVectorElt(EltNum).getInt();
17054 break;
17055 }
17056 case Builtin::BI__builtin_reduce_or: {
17057 Reduced |= Source.getVectorElt(EltNum).getInt();
17058 break;
17059 }
17060 case Builtin::BI__builtin_reduce_xor: {
17061 Reduced ^= Source.getVectorElt(EltNum).getInt();
17062 break;
17063 }
17064 case Builtin::BI__builtin_reduce_min: {
17065 Reduced = std::min(Reduced, Source.getVectorElt(EltNum).getInt());
17066 break;
17067 }
17068 case Builtin::BI__builtin_reduce_max: {
17069 Reduced = std::max(Reduced, Source.getVectorElt(EltNum).getInt());
17070 break;
17071 }
17072 }
17073 }
17074
17075 return Success(Reduced, E);
17076 }
17077
17078 case clang::X86::BI__builtin_ia32_addcarryx_u32:
17079 case clang::X86::BI__builtin_ia32_addcarryx_u64:
17080 case clang::X86::BI__builtin_ia32_subborrow_u32:
17081 case clang::X86::BI__builtin_ia32_subborrow_u64: {
17082 LValue ResultLValue;
17083 APSInt CarryIn, LHS, RHS;
17084 QualType ResultType = E->getArg(3)->getType()->getPointeeType();
17085 if (!EvaluateInteger(E->getArg(0), CarryIn, Info) ||
17086 !EvaluateInteger(E->getArg(1), LHS, Info) ||
17087 !EvaluateInteger(E->getArg(2), RHS, Info) ||
17088 !EvaluatePointer(E->getArg(3), ResultLValue, Info))
17089 return false;
17090
17091 bool IsAdd = BuiltinOp == clang::X86::BI__builtin_ia32_addcarryx_u32 ||
17092 BuiltinOp == clang::X86::BI__builtin_ia32_addcarryx_u64;
17093
17094 unsigned BitWidth = LHS.getBitWidth();
17095 unsigned CarryInBit = CarryIn.ugt(0) ? 1 : 0;
17096 APInt ExResult =
17097 IsAdd
17098 ? (LHS.zext(BitWidth + 1) + (RHS.zext(BitWidth + 1) + CarryInBit))
17099 : (LHS.zext(BitWidth + 1) - (RHS.zext(BitWidth + 1) + CarryInBit));
17100
17101 APInt Result = ExResult.extractBits(BitWidth, 0);
17102 uint64_t CarryOut = ExResult.extractBitsAsZExtValue(1, BitWidth);
17103
17104 APValue APV{APSInt(Result, /*isUnsigned=*/true)};
17105 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
17106 return false;
17107 return Success(CarryOut, E);
17108 }
17109
17110 case clang::X86::BI__builtin_ia32_movmskps:
17111 case clang::X86::BI__builtin_ia32_movmskpd:
17112 case clang::X86::BI__builtin_ia32_pmovmskb128:
17113 case clang::X86::BI__builtin_ia32_pmovmskb256:
17114 case clang::X86::BI__builtin_ia32_movmskps256:
17115 case clang::X86::BI__builtin_ia32_movmskpd256: {
17116 APValue Source;
17117 if (!Evaluate(Source, Info, E->getArg(0)))
17118 return false;
17119 unsigned SourceLen = Source.getVectorLength();
17120 const VectorType *VT = E->getArg(0)->getType()->castAs<VectorType>();
17121 QualType ElemQT = VT->getElementType();
17122 unsigned ResultLen = Info.Ctx.getTypeSize(
17123 E->getCallReturnType(Info.Ctx)); // Always 32-bit integer.
17124 APInt Result(ResultLen, 0);
17125
17126 for (unsigned I = 0; I != SourceLen; ++I) {
17127 APInt Elem;
17128 if (ElemQT->isIntegerType()) {
17129 Elem = Source.getVectorElt(I).getInt();
17130 } else if (ElemQT->isRealFloatingType()) {
17131 Elem = Source.getVectorElt(I).getFloat().bitcastToAPInt();
17132 } else {
17133 return false;
17134 }
17135 Result.setBitVal(I, Elem.isNegative());
17136 }
17137 return Success(Result, E);
17138 }
17139
17140 case clang::X86::BI__builtin_ia32_bextr_u32:
17141 case clang::X86::BI__builtin_ia32_bextr_u64:
17142 case clang::X86::BI__builtin_ia32_bextri_u32:
17143 case clang::X86::BI__builtin_ia32_bextri_u64: {
17144 APSInt Val, Idx;
17145 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
17146 !EvaluateInteger(E->getArg(1), Idx, Info))
17147 return false;
17148
17149 unsigned BitWidth = Val.getBitWidth();
17150 uint64_t Shift = Idx.extractBitsAsZExtValue(8, 0);
17151 uint64_t Length = Idx.extractBitsAsZExtValue(8, 8);
17152 Length = Length > BitWidth ? BitWidth : Length;
17153
17154 // Handle out of bounds cases.
17155 if (Length == 0 || Shift >= BitWidth)
17156 return Success(0, E);
17157
17158 uint64_t Result = Val.getZExtValue() >> Shift;
17159 Result &= llvm::maskTrailingOnes<uint64_t>(Length);
17160 return Success(Result, E);
17161 }
17162
17163 case clang::X86::BI__builtin_ia32_bzhi_si:
17164 case clang::X86::BI__builtin_ia32_bzhi_di: {
17165 APSInt Val, Idx;
17166 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
17167 !EvaluateInteger(E->getArg(1), Idx, Info))
17168 return false;
17169
17170 unsigned BitWidth = Val.getBitWidth();
17171 unsigned Index = Idx.extractBitsAsZExtValue(8, 0);
17172 if (Index < BitWidth)
17173 Val.clearHighBits(BitWidth - Index);
17174 return Success(Val, E);
17175 }
17176
17177 case clang::X86::BI__builtin_ia32_ktestcqi:
17178 case clang::X86::BI__builtin_ia32_ktestchi:
17179 case clang::X86::BI__builtin_ia32_ktestcsi:
17180 case clang::X86::BI__builtin_ia32_ktestcdi: {
17181 APSInt A, B;
17182 if (!EvaluateInteger(E->getArg(0), A, Info) ||
17183 !EvaluateInteger(E->getArg(1), B, Info))
17184 return false;
17185
17186 return Success((~A & B) == 0, E);
17187 }
17188
17189 case clang::X86::BI__builtin_ia32_ktestzqi:
17190 case clang::X86::BI__builtin_ia32_ktestzhi:
17191 case clang::X86::BI__builtin_ia32_ktestzsi:
17192 case clang::X86::BI__builtin_ia32_ktestzdi: {
17193 APSInt A, B;
17194 if (!EvaluateInteger(E->getArg(0), A, Info) ||
17195 !EvaluateInteger(E->getArg(1), B, Info))
17196 return false;
17197
17198 return Success((A & B) == 0, E);
17199 }
17200
17201 case clang::X86::BI__builtin_ia32_kortestcqi:
17202 case clang::X86::BI__builtin_ia32_kortestchi:
17203 case clang::X86::BI__builtin_ia32_kortestcsi:
17204 case clang::X86::BI__builtin_ia32_kortestcdi: {
17205 APSInt A, B;
17206 if (!EvaluateInteger(E->getArg(0), A, Info) ||
17207 !EvaluateInteger(E->getArg(1), B, Info))
17208 return false;
17209
17210 return Success(~(A | B) == 0, E);
17211 }
17212
17213 case clang::X86::BI__builtin_ia32_kortestzqi:
17214 case clang::X86::BI__builtin_ia32_kortestzhi:
17215 case clang::X86::BI__builtin_ia32_kortestzsi:
17216 case clang::X86::BI__builtin_ia32_kortestzdi: {
17217 APSInt A, B;
17218 if (!EvaluateInteger(E->getArg(0), A, Info) ||
17219 !EvaluateInteger(E->getArg(1), B, Info))
17220 return false;
17221
17222 return Success((A | B) == 0, E);
17223 }
17224
17225 case clang::X86::BI__builtin_ia32_kunpckhi:
17226 case clang::X86::BI__builtin_ia32_kunpckdi:
17227 case clang::X86::BI__builtin_ia32_kunpcksi: {
17228 APSInt A, B;
17229 if (!EvaluateInteger(E->getArg(0), A, Info) ||
17230 !EvaluateInteger(E->getArg(1), B, Info))
17231 return false;
17232
17233 // Generic kunpack: extract lower half of each operand and concatenate
17234 // Result = A[HalfWidth-1:0] concat B[HalfWidth-1:0]
17235 unsigned BW = A.getBitWidth();
17236 APSInt Result(A.trunc(BW / 2).concat(B.trunc(BW / 2)), A.isUnsigned());
17237 return Success(Result, E);
17238 }
17239
17240 case clang::X86::BI__builtin_ia32_lzcnt_u16:
17241 case clang::X86::BI__builtin_ia32_lzcnt_u32:
17242 case clang::X86::BI__builtin_ia32_lzcnt_u64: {
17243 APSInt Val;
17244 if (!EvaluateInteger(E->getArg(0), Val, Info))
17245 return false;
17246 return Success(Val.countLeadingZeros(), E);
17247 }
17248
17249 case clang::X86::BI__builtin_ia32_tzcnt_u16:
17250 case clang::X86::BI__builtin_ia32_tzcnt_u32:
17251 case clang::X86::BI__builtin_ia32_tzcnt_u64: {
17252 APSInt Val;
17253 if (!EvaluateInteger(E->getArg(0), Val, Info))
17254 return false;
17255 return Success(Val.countTrailingZeros(), E);
17256 }
17257
17258 case clang::X86::BI__builtin_ia32_pdep_si:
17259 case clang::X86::BI__builtin_ia32_pdep_di: {
17260 APSInt Val, Msk;
17261 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
17262 !EvaluateInteger(E->getArg(1), Msk, Info))
17263 return false;
17264
17265 unsigned BitWidth = Val.getBitWidth();
17266 APInt Result = APInt::getZero(BitWidth);
17267 for (unsigned I = 0, P = 0; I != BitWidth; ++I)
17268 if (Msk[I])
17269 Result.setBitVal(I, Val[P++]);
17270 return Success(Result, E);
17271 }
17272
17273 case clang::X86::BI__builtin_ia32_pext_si:
17274 case clang::X86::BI__builtin_ia32_pext_di: {
17275 APSInt Val, Msk;
17276 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
17277 !EvaluateInteger(E->getArg(1), Msk, Info))
17278 return false;
17279
17280 unsigned BitWidth = Val.getBitWidth();
17281 APInt Result = APInt::getZero(BitWidth);
17282 for (unsigned I = 0, P = 0; I != BitWidth; ++I)
17283 if (Msk[I])
17284 Result.setBitVal(P++, Val[I]);
17285 return Success(Result, E);
17286 }
17287 case X86::BI__builtin_ia32_ptestz128:
17288 case X86::BI__builtin_ia32_ptestz256:
17289 case X86::BI__builtin_ia32_vtestzps:
17290 case X86::BI__builtin_ia32_vtestzps256:
17291 case X86::BI__builtin_ia32_vtestzpd:
17292 case X86::BI__builtin_ia32_vtestzpd256: {
17293 return EvalTestOp(
17294 [](const APInt &A, const APInt &B) { return (A & B) == 0; });
17295 }
17296 case X86::BI__builtin_ia32_ptestc128:
17297 case X86::BI__builtin_ia32_ptestc256:
17298 case X86::BI__builtin_ia32_vtestcps:
17299 case X86::BI__builtin_ia32_vtestcps256:
17300 case X86::BI__builtin_ia32_vtestcpd:
17301 case X86::BI__builtin_ia32_vtestcpd256: {
17302 return EvalTestOp(
17303 [](const APInt &A, const APInt &B) { return (~A & B) == 0; });
17304 }
17305 case X86::BI__builtin_ia32_ptestnzc128:
17306 case X86::BI__builtin_ia32_ptestnzc256:
17307 case X86::BI__builtin_ia32_vtestnzcps:
17308 case X86::BI__builtin_ia32_vtestnzcps256:
17309 case X86::BI__builtin_ia32_vtestnzcpd:
17310 case X86::BI__builtin_ia32_vtestnzcpd256: {
17311 return EvalTestOp([](const APInt &A, const APInt &B) {
17312 return ((A & B) != 0) && ((~A & B) != 0);
17313 });
17314 }
17315 case X86::BI__builtin_ia32_kandqi:
17316 case X86::BI__builtin_ia32_kandhi:
17317 case X86::BI__builtin_ia32_kandsi:
17318 case X86::BI__builtin_ia32_kanddi: {
17319 return HandleMaskBinOp(
17320 [](const APSInt &LHS, const APSInt &RHS) { return LHS & RHS; });
17321 }
17322
17323 case X86::BI__builtin_ia32_kandnqi:
17324 case X86::BI__builtin_ia32_kandnhi:
17325 case X86::BI__builtin_ia32_kandnsi:
17326 case X86::BI__builtin_ia32_kandndi: {
17327 return HandleMaskBinOp(
17328 [](const APSInt &LHS, const APSInt &RHS) { return ~LHS & RHS; });
17329 }
17330
17331 case X86::BI__builtin_ia32_korqi:
17332 case X86::BI__builtin_ia32_korhi:
17333 case X86::BI__builtin_ia32_korsi:
17334 case X86::BI__builtin_ia32_kordi: {
17335 return HandleMaskBinOp(
17336 [](const APSInt &LHS, const APSInt &RHS) { return LHS | RHS; });
17337 }
17338
17339 case X86::BI__builtin_ia32_kxnorqi:
17340 case X86::BI__builtin_ia32_kxnorhi:
17341 case X86::BI__builtin_ia32_kxnorsi:
17342 case X86::BI__builtin_ia32_kxnordi: {
17343 return HandleMaskBinOp(
17344 [](const APSInt &LHS, const APSInt &RHS) { return ~(LHS ^ RHS); });
17345 }
17346
17347 case X86::BI__builtin_ia32_kxorqi:
17348 case X86::BI__builtin_ia32_kxorhi:
17349 case X86::BI__builtin_ia32_kxorsi:
17350 case X86::BI__builtin_ia32_kxordi: {
17351 return HandleMaskBinOp(
17352 [](const APSInt &LHS, const APSInt &RHS) { return LHS ^ RHS; });
17353 }
17354
17355 case X86::BI__builtin_ia32_knotqi:
17356 case X86::BI__builtin_ia32_knothi:
17357 case X86::BI__builtin_ia32_knotsi:
17358 case X86::BI__builtin_ia32_knotdi: {
17359 APSInt Val;
17360 if (!EvaluateInteger(E->getArg(0), Val, Info))
17361 return false;
17362 APSInt Result = ~Val;
17363 return Success(APValue(Result), E);
17364 }
17365
17366 case X86::BI__builtin_ia32_kaddqi:
17367 case X86::BI__builtin_ia32_kaddhi:
17368 case X86::BI__builtin_ia32_kaddsi:
17369 case X86::BI__builtin_ia32_kadddi: {
17370 return HandleMaskBinOp(
17371 [](const APSInt &LHS, const APSInt &RHS) { return LHS + RHS; });
17372 }
17373
17374 case X86::BI__builtin_ia32_kmovb:
17375 case X86::BI__builtin_ia32_kmovw:
17376 case X86::BI__builtin_ia32_kmovd:
17377 case X86::BI__builtin_ia32_kmovq: {
17378 APSInt Val;
17379 if (!EvaluateInteger(E->getArg(0), Val, Info))
17380 return false;
17381 return Success(Val, E);
17382 }
17383
17384 case X86::BI__builtin_ia32_kshiftliqi:
17385 case X86::BI__builtin_ia32_kshiftlihi:
17386 case X86::BI__builtin_ia32_kshiftlisi:
17387 case X86::BI__builtin_ia32_kshiftlidi: {
17388 return HandleMaskBinOp([](const APSInt &LHS, const APSInt &RHS) {
17389 unsigned Amt = RHS.getZExtValue() & 0xFF;
17390 if (Amt >= LHS.getBitWidth())
17391 return APSInt(APInt::getZero(LHS.getBitWidth()), LHS.isUnsigned());
17392 return APSInt(LHS.shl(Amt), LHS.isUnsigned());
17393 });
17394 }
17395
17396 case X86::BI__builtin_ia32_kshiftriqi:
17397 case X86::BI__builtin_ia32_kshiftrihi:
17398 case X86::BI__builtin_ia32_kshiftrisi:
17399 case X86::BI__builtin_ia32_kshiftridi: {
17400 return HandleMaskBinOp([](const APSInt &LHS, const APSInt &RHS) {
17401 unsigned Amt = RHS.getZExtValue() & 0xFF;
17402 if (Amt >= LHS.getBitWidth())
17403 return APSInt(APInt::getZero(LHS.getBitWidth()), LHS.isUnsigned());
17404 return APSInt(LHS.lshr(Amt), LHS.isUnsigned());
17405 });
17406 }
17407
17408 case clang::X86::BI__builtin_ia32_vec_ext_v4hi:
17409 case clang::X86::BI__builtin_ia32_vec_ext_v16qi:
17410 case clang::X86::BI__builtin_ia32_vec_ext_v8hi:
17411 case clang::X86::BI__builtin_ia32_vec_ext_v4si:
17412 case clang::X86::BI__builtin_ia32_vec_ext_v2di:
17413 case clang::X86::BI__builtin_ia32_vec_ext_v32qi:
17414 case clang::X86::BI__builtin_ia32_vec_ext_v16hi:
17415 case clang::X86::BI__builtin_ia32_vec_ext_v8si:
17416 case clang::X86::BI__builtin_ia32_vec_ext_v4di: {
17417 APValue Vec;
17418 APSInt IdxAPS;
17419 if (!EvaluateVector(E->getArg(0), Vec, Info) ||
17420 !EvaluateInteger(E->getArg(1), IdxAPS, Info))
17421 return false;
17422 unsigned N = Vec.getVectorLength();
17423 unsigned Idx = static_cast<unsigned>(IdxAPS.getZExtValue() & (N - 1));
17424 return Success(Vec.getVectorElt(Idx).getInt(), E);
17425 }
17426
17427 case clang::X86::BI__builtin_ia32_cvtb2mask128:
17428 case clang::X86::BI__builtin_ia32_cvtb2mask256:
17429 case clang::X86::BI__builtin_ia32_cvtb2mask512:
17430 case clang::X86::BI__builtin_ia32_cvtw2mask128:
17431 case clang::X86::BI__builtin_ia32_cvtw2mask256:
17432 case clang::X86::BI__builtin_ia32_cvtw2mask512:
17433 case clang::X86::BI__builtin_ia32_cvtd2mask128:
17434 case clang::X86::BI__builtin_ia32_cvtd2mask256:
17435 case clang::X86::BI__builtin_ia32_cvtd2mask512:
17436 case clang::X86::BI__builtin_ia32_cvtq2mask128:
17437 case clang::X86::BI__builtin_ia32_cvtq2mask256:
17438 case clang::X86::BI__builtin_ia32_cvtq2mask512: {
17439 assert(E->getNumArgs() == 1);
17440 APValue Vec;
17441 if (!EvaluateVector(E->getArg(0), Vec, Info))
17442 return false;
17443
17444 unsigned VectorLen = Vec.getVectorLength();
17445 unsigned RetWidth = Info.Ctx.getIntWidth(E->getType());
17446 llvm::APInt Bits(RetWidth, 0);
17447
17448 for (unsigned ElemNum = 0; ElemNum != VectorLen; ++ElemNum) {
17449 const APSInt &A = Vec.getVectorElt(ElemNum).getInt();
17450 unsigned MSB = A[A.getBitWidth() - 1];
17451 Bits.setBitVal(ElemNum, MSB);
17452 }
17453
17454 APSInt RetMask(Bits, /*isUnsigned=*/true);
17455 return Success(APValue(RetMask), E);
17456 }
17457
17458 case clang::X86::BI__builtin_ia32_cmpb128_mask:
17459 case clang::X86::BI__builtin_ia32_cmpw128_mask:
17460 case clang::X86::BI__builtin_ia32_cmpd128_mask:
17461 case clang::X86::BI__builtin_ia32_cmpq128_mask:
17462 case clang::X86::BI__builtin_ia32_cmpb256_mask:
17463 case clang::X86::BI__builtin_ia32_cmpw256_mask:
17464 case clang::X86::BI__builtin_ia32_cmpd256_mask:
17465 case clang::X86::BI__builtin_ia32_cmpq256_mask:
17466 case clang::X86::BI__builtin_ia32_cmpb512_mask:
17467 case clang::X86::BI__builtin_ia32_cmpw512_mask:
17468 case clang::X86::BI__builtin_ia32_cmpd512_mask:
17469 case clang::X86::BI__builtin_ia32_cmpq512_mask:
17470 case clang::X86::BI__builtin_ia32_ucmpb128_mask:
17471 case clang::X86::BI__builtin_ia32_ucmpw128_mask:
17472 case clang::X86::BI__builtin_ia32_ucmpd128_mask:
17473 case clang::X86::BI__builtin_ia32_ucmpq128_mask:
17474 case clang::X86::BI__builtin_ia32_ucmpb256_mask:
17475 case clang::X86::BI__builtin_ia32_ucmpw256_mask:
17476 case clang::X86::BI__builtin_ia32_ucmpd256_mask:
17477 case clang::X86::BI__builtin_ia32_ucmpq256_mask:
17478 case clang::X86::BI__builtin_ia32_ucmpb512_mask:
17479 case clang::X86::BI__builtin_ia32_ucmpw512_mask:
17480 case clang::X86::BI__builtin_ia32_ucmpd512_mask:
17481 case clang::X86::BI__builtin_ia32_ucmpq512_mask: {
17482 assert(E->getNumArgs() == 4);
17483
17484 bool IsUnsigned =
17485 (BuiltinOp >= clang::X86::BI__builtin_ia32_ucmpb128_mask &&
17486 BuiltinOp <= clang::X86::BI__builtin_ia32_ucmpw512_mask);
17487
17488 APValue LHS, RHS;
17489 APSInt Mask, Opcode;
17490 if (!EvaluateVector(E->getArg(0), LHS, Info) ||
17491 !EvaluateVector(E->getArg(1), RHS, Info) ||
17492 !EvaluateInteger(E->getArg(2), Opcode, Info) ||
17493 !EvaluateInteger(E->getArg(3), Mask, Info))
17494 return false;
17495
17496 assert(LHS.getVectorLength() == RHS.getVectorLength());
17497
17498 unsigned VectorLen = LHS.getVectorLength();
17499 unsigned RetWidth = Mask.getBitWidth();
17500
17501 APSInt RetMask(llvm::APInt(RetWidth, 0), /*isUnsigned=*/true);
17502
17503 for (unsigned ElemNum = 0; ElemNum < VectorLen; ++ElemNum) {
17504 const APSInt &A = LHS.getVectorElt(ElemNum).getInt();
17505 const APSInt &B = RHS.getVectorElt(ElemNum).getInt();
17506 bool Result = false;
17507
17508 switch (Opcode.getExtValue() & 0x7) {
17509 case 0: // _MM_CMPINT_EQ
17510 Result = (A == B);
17511 break;
17512 case 1: // _MM_CMPINT_LT
17513 Result = IsUnsigned ? A.ult(B) : A.slt(B);
17514 break;
17515 case 2: // _MM_CMPINT_LE
17516 Result = IsUnsigned ? A.ule(B) : A.sle(B);
17517 break;
17518 case 3: // _MM_CMPINT_FALSE
17519 Result = false;
17520 break;
17521 case 4: // _MM_CMPINT_NE
17522 Result = (A != B);
17523 break;
17524 case 5: // _MM_CMPINT_NLT (>=)
17525 Result = IsUnsigned ? A.uge(B) : A.sge(B);
17526 break;
17527 case 6: // _MM_CMPINT_NLE (>)
17528 Result = IsUnsigned ? A.ugt(B) : A.sgt(B);
17529 break;
17530 case 7: // _MM_CMPINT_TRUE
17531 Result = true;
17532 break;
17533 }
17534
17535 RetMask.setBitVal(ElemNum, Mask[ElemNum] && Result);
17536 }
17537
17538 return Success(APValue(RetMask), E);
17539 }
17540 case X86::BI__builtin_ia32_vpshufbitqmb128_mask:
17541 case X86::BI__builtin_ia32_vpshufbitqmb256_mask:
17542 case X86::BI__builtin_ia32_vpshufbitqmb512_mask: {
17543 assert(E->getNumArgs() == 3);
17544
17545 APValue Source, ShuffleMask;
17546 APSInt ZeroMask;
17547 if (!EvaluateVector(E->getArg(0), Source, Info) ||
17548 !EvaluateVector(E->getArg(1), ShuffleMask, Info) ||
17549 !EvaluateInteger(E->getArg(2), ZeroMask, Info))
17550 return false;
17551
17552 assert(Source.getVectorLength() == ShuffleMask.getVectorLength());
17553 assert(ZeroMask.getBitWidth() == Source.getVectorLength());
17554
17555 unsigned NumBytesInQWord = 8;
17556 unsigned NumBitsInByte = 8;
17557 unsigned NumBytes = Source.getVectorLength();
17558 unsigned NumQWords = NumBytes / NumBytesInQWord;
17559 unsigned RetWidth = ZeroMask.getBitWidth();
17560 APSInt RetMask(llvm::APInt(RetWidth, 0), /*isUnsigned=*/true);
17561
17562 for (unsigned QWordId = 0; QWordId != NumQWords; ++QWordId) {
17563 APInt SourceQWord(64, 0);
17564 for (unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
17565 uint64_t Byte = Source.getVectorElt(QWordId * NumBytesInQWord + ByteIdx)
17566 .getInt()
17567 .getZExtValue();
17568 SourceQWord.insertBits(APInt(8, Byte & 0xFF), ByteIdx * NumBitsInByte);
17569 }
17570
17571 for (unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
17572 unsigned SelIdx = QWordId * NumBytesInQWord + ByteIdx;
17573 unsigned M =
17574 ShuffleMask.getVectorElt(SelIdx).getInt().getZExtValue() & 0x3F;
17575 if (ZeroMask[SelIdx]) {
17576 RetMask.setBitVal(SelIdx, SourceQWord[M]);
17577 }
17578 }
17579 }
17580 return Success(APValue(RetMask), E);
17581 }
17582 }
17583}
17584
17585/// Determine whether this is a pointer past the end of the complete
17586/// object referred to by the lvalue.
17588 const LValue &LV) {
17589 // A null pointer can be viewed as being "past the end" but we don't
17590 // choose to look at it that way here.
17591 if (!LV.getLValueBase())
17592 return false;
17593
17594 // If the designator is valid and refers to a subobject, we're not pointing
17595 // past the end.
17596 if (!LV.getLValueDesignator().Invalid &&
17597 !LV.getLValueDesignator().isOnePastTheEnd())
17598 return false;
17599
17600 // A pointer to an incomplete type might be past-the-end if the type's size is
17601 // zero. We cannot tell because the type is incomplete.
17602 QualType Ty = getType(LV.getLValueBase());
17603 if (Ty->isIncompleteType())
17604 return true;
17605
17606 // Can't be past the end of an invalid object.
17607 if (LV.getLValueDesignator().Invalid)
17608 return false;
17609
17610 // We're a past-the-end pointer if we point to the byte after the object,
17611 // no matter what our type or path is.
17612 auto Size = Ctx.getTypeSizeInChars(Ty);
17613 return LV.getLValueOffset() == Size;
17614}
17615
17616namespace {
17617
17618/// Data recursive integer evaluator of certain binary operators.
17619///
17620/// We use a data recursive algorithm for binary operators so that we are able
17621/// to handle extreme cases of chained binary operators without causing stack
17622/// overflow.
17623class DataRecursiveIntBinOpEvaluator {
17624 struct EvalResult {
17625 APValue Val;
17626 bool Failed = false;
17627
17628 EvalResult() = default;
17629
17630 void swap(EvalResult &RHS) {
17631 Val.swap(RHS.Val);
17632 Failed = RHS.Failed;
17633 RHS.Failed = false;
17634 }
17635 };
17636
17637 struct Job {
17638 const Expr *E;
17639 EvalResult LHSResult; // meaningful only for binary operator expression.
17640 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
17641
17642 Job() = default;
17643 Job(Job &&) = default;
17644
17645 void startSpeculativeEval(EvalInfo &Info) {
17646 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
17647 }
17648
17649 private:
17650 SpeculativeEvaluationRAII SpecEvalRAII;
17651 };
17652
17653 SmallVector<Job, 16> Queue;
17654
17655 IntExprEvaluator &IntEval;
17656 EvalInfo &Info;
17657 APValue &FinalResult;
17658
17659public:
17660 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
17661 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
17662
17663 /// True if \param E is a binary operator that we are going to handle
17664 /// data recursively.
17665 /// We handle binary operators that are comma, logical, or that have operands
17666 /// with integral or enumeration type.
17667 static bool shouldEnqueue(const BinaryOperator *E) {
17668 return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
17672 }
17673
17674 bool Traverse(const BinaryOperator *E) {
17675 enqueue(E);
17676 EvalResult PrevResult;
17677 while (!Queue.empty())
17678 process(PrevResult);
17679
17680 if (PrevResult.Failed) return false;
17681
17682 FinalResult.swap(PrevResult.Val);
17683 return true;
17684 }
17685
17686private:
17687 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
17688 return IntEval.Success(Value, E, Result);
17689 }
17690 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
17691 return IntEval.Success(Value, E, Result);
17692 }
17693 bool Error(const Expr *E) {
17694 return IntEval.Error(E);
17695 }
17696 bool Error(const Expr *E, diag::kind D) {
17697 return IntEval.Error(E, D);
17698 }
17699
17700 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
17701 return Info.CCEDiag(E, D);
17702 }
17703
17704 // Returns true if visiting the RHS is necessary, false otherwise.
17705 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
17706 bool &SuppressRHSDiags);
17707
17708 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
17709 const BinaryOperator *E, APValue &Result);
17710
17711 void EvaluateExpr(const Expr *E, EvalResult &Result) {
17712 Result.Failed = !Evaluate(Result.Val, Info, E);
17713 if (Result.Failed)
17714 Result.Val = APValue();
17715 }
17716
17717 void process(EvalResult &Result);
17718
17719 void enqueue(const Expr *E) {
17720 E = E->IgnoreParens();
17721 Queue.resize(Queue.size()+1);
17722 Queue.back().E = E;
17723 Queue.back().Kind = Job::AnyExprKind;
17724 }
17725};
17726
17727}
17728
17729bool DataRecursiveIntBinOpEvaluator::
17730 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
17731 bool &SuppressRHSDiags) {
17732 if (E->getOpcode() == BO_Comma) {
17733 // Ignore LHS but note if we could not evaluate it.
17734 if (LHSResult.Failed)
17735 return Info.noteSideEffect();
17736 return true;
17737 }
17738
17739 if (E->isLogicalOp()) {
17740 bool LHSAsBool;
17741 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
17742 // We were able to evaluate the LHS, see if we can get away with not
17743 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
17744 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
17745 Success(LHSAsBool, E, LHSResult.Val);
17746 return false; // Ignore RHS
17747 }
17748 } else {
17749 LHSResult.Failed = true;
17750
17751 // Since we weren't able to evaluate the left hand side, it
17752 // might have had side effects.
17753 if (!Info.noteSideEffect())
17754 return false;
17755
17756 // We can't evaluate the LHS; however, sometimes the result
17757 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
17758 // Don't ignore RHS and suppress diagnostics from this arm.
17759 SuppressRHSDiags = true;
17760 }
17761
17762 return true;
17763 }
17764
17765 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
17767
17768 if (LHSResult.Failed && !Info.noteFailure())
17769 return false; // Ignore RHS;
17770
17771 return true;
17772}
17773
17774static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
17775 bool IsSub) {
17776 // Compute the new offset in the appropriate width, wrapping at 64 bits.
17777 // FIXME: When compiling for a 32-bit target, we should use 32-bit
17778 // offsets.
17779 assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
17780 CharUnits &Offset = LVal.getLValueOffset();
17781 uint64_t Offset64 = Offset.getQuantity();
17782 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
17783 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
17784 : Offset64 + Index64);
17785}
17786
17787bool DataRecursiveIntBinOpEvaluator::
17788 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
17789 const BinaryOperator *E, APValue &Result) {
17790 if (E->getOpcode() == BO_Comma) {
17791 if (RHSResult.Failed)
17792 return false;
17793 Result = RHSResult.Val;
17794 return true;
17795 }
17796
17797 if (E->isLogicalOp()) {
17798 bool lhsResult, rhsResult;
17799 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
17800 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
17801
17802 if (LHSIsOK) {
17803 if (RHSIsOK) {
17804 if (E->getOpcode() == BO_LOr)
17805 return Success(lhsResult || rhsResult, E, Result);
17806 else
17807 return Success(lhsResult && rhsResult, E, Result);
17808 }
17809 } else {
17810 if (RHSIsOK) {
17811 // We can't evaluate the LHS; however, sometimes the result
17812 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
17813 if (rhsResult == (E->getOpcode() == BO_LOr))
17814 return Success(rhsResult, E, Result);
17815 }
17816 }
17817
17818 return false;
17819 }
17820
17821 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
17823
17824 if (LHSResult.Failed || RHSResult.Failed)
17825 return false;
17826
17827 const APValue &LHSVal = LHSResult.Val;
17828 const APValue &RHSVal = RHSResult.Val;
17829
17830 // Handle cases like (unsigned long)&a + 4.
17831 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
17832 Result = LHSVal;
17833 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
17834 return true;
17835 }
17836
17837 // Handle cases like 4 + (unsigned long)&a
17838 if (E->getOpcode() == BO_Add &&
17839 RHSVal.isLValue() && LHSVal.isInt()) {
17840 Result = RHSVal;
17841 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
17842 return true;
17843 }
17844
17845 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
17846 // Handle (intptr_t)&&A - (intptr_t)&&B.
17847 if (!LHSVal.getLValueOffset().isZero() ||
17848 !RHSVal.getLValueOffset().isZero())
17849 return false;
17850 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
17851 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
17852 if (!LHSExpr || !RHSExpr)
17853 return false;
17854 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
17855 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
17856 if (!LHSAddrExpr || !RHSAddrExpr)
17857 return false;
17858 // Make sure both labels come from the same function.
17859 if (LHSAddrExpr->getLabel()->getDeclContext() !=
17860 RHSAddrExpr->getLabel()->getDeclContext())
17861 return false;
17862 Result = APValue(LHSAddrExpr, RHSAddrExpr);
17863 return true;
17864 }
17865
17866 // All the remaining cases expect both operands to be an integer
17867 if (!LHSVal.isInt() || !RHSVal.isInt())
17868 return Error(E);
17869
17870 // Set up the width and signedness manually, in case it can't be deduced
17871 // from the operation we're performing.
17872 // FIXME: Don't do this in the cases where we can deduce it.
17873 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
17875 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
17876 RHSVal.getInt(), Value))
17877 return false;
17878 return Success(Value, E, Result);
17879}
17880
17881void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
17882 Job &job = Queue.back();
17883
17884 switch (job.Kind) {
17885 case Job::AnyExprKind: {
17886 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
17887 if (shouldEnqueue(Bop)) {
17888 job.Kind = Job::BinOpKind;
17889 enqueue(Bop->getLHS());
17890 return;
17891 }
17892 }
17893
17894 EvaluateExpr(job.E, Result);
17895 Queue.pop_back();
17896 return;
17897 }
17898
17899 case Job::BinOpKind: {
17900 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
17901 bool SuppressRHSDiags = false;
17902 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
17903 Queue.pop_back();
17904 return;
17905 }
17906 if (SuppressRHSDiags)
17907 job.startSpeculativeEval(Info);
17908 job.LHSResult.swap(Result);
17909 job.Kind = Job::BinOpVisitedLHSKind;
17910 enqueue(Bop->getRHS());
17911 return;
17912 }
17913
17914 case Job::BinOpVisitedLHSKind: {
17915 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
17916 EvalResult RHS;
17917 RHS.swap(Result);
17918 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
17919 Queue.pop_back();
17920 return;
17921 }
17922 }
17923
17924 llvm_unreachable("Invalid Job::Kind!");
17925}
17926
17927namespace {
17928enum class CmpResult {
17929 Unequal,
17930 Less,
17931 Equal,
17932 Greater,
17933 Unordered,
17934};
17935}
17936
17937template <class SuccessCB, class AfterCB>
17938static bool
17940 SuccessCB &&Success, AfterCB &&DoAfter) {
17941 assert(!E->isValueDependent());
17942 assert(E->isComparisonOp() && "expected comparison operator");
17943 assert((E->getOpcode() == BO_Cmp ||
17945 "unsupported binary expression evaluation");
17946 auto Error = [&](const Expr *E) {
17947 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
17948 return false;
17949 };
17950
17951 bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp;
17952 bool IsEquality = E->isEqualityOp();
17953
17954 QualType LHSTy = E->getLHS()->getType();
17955 QualType RHSTy = E->getRHS()->getType();
17956
17957 if (LHSTy->isIntegralOrEnumerationType() &&
17958 RHSTy->isIntegralOrEnumerationType()) {
17959 APSInt LHS, RHS;
17960 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
17961 if (!LHSOK && !Info.noteFailure())
17962 return false;
17963 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
17964 return false;
17965 if (LHS < RHS)
17966 return Success(CmpResult::Less, E);
17967 if (LHS > RHS)
17968 return Success(CmpResult::Greater, E);
17969 return Success(CmpResult::Equal, E);
17970 }
17971
17972 if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
17973 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
17974 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
17975
17976 bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
17977 if (!LHSOK && !Info.noteFailure())
17978 return false;
17979 if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
17980 return false;
17981 if (LHSFX < RHSFX)
17982 return Success(CmpResult::Less, E);
17983 if (LHSFX > RHSFX)
17984 return Success(CmpResult::Greater, E);
17985 return Success(CmpResult::Equal, E);
17986 }
17987
17988 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
17989 ComplexValue LHS, RHS;
17990 bool LHSOK;
17991 if (E->isAssignmentOp()) {
17992 LValue LV;
17993 EvaluateLValue(E->getLHS(), LV, Info);
17994 LHSOK = false;
17995 } else if (LHSTy->isRealFloatingType()) {
17996 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
17997 if (LHSOK) {
17998 LHS.makeComplexFloat();
17999 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
18000 }
18001 } else {
18002 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
18003 }
18004 if (!LHSOK && !Info.noteFailure())
18005 return false;
18006
18007 if (E->getRHS()->getType()->isRealFloatingType()) {
18008 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
18009 return false;
18010 RHS.makeComplexFloat();
18011 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
18012 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
18013 return false;
18014
18015 if (LHS.isComplexFloat()) {
18016 APFloat::cmpResult CR_r =
18017 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
18018 APFloat::cmpResult CR_i =
18019 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
18020 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
18021 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
18022 } else {
18023 assert(IsEquality && "invalid complex comparison");
18024 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
18025 LHS.getComplexIntImag() == RHS.getComplexIntImag();
18026 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
18027 }
18028 }
18029
18030 if (LHSTy->isRealFloatingType() &&
18031 RHSTy->isRealFloatingType()) {
18032 APFloat RHS(0.0), LHS(0.0);
18033
18034 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
18035 if (!LHSOK && !Info.noteFailure())
18036 return false;
18037
18038 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
18039 return false;
18040
18041 assert(E->isComparisonOp() && "Invalid binary operator!");
18042 llvm::APFloatBase::cmpResult APFloatCmpResult = LHS.compare(RHS);
18043 if (!Info.InConstantContext &&
18044 APFloatCmpResult == APFloat::cmpUnordered &&
18046 // Note: Compares may raise invalid in some cases involving NaN or sNaN.
18047 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
18048 return false;
18049 }
18050 auto GetCmpRes = [&]() {
18051 switch (APFloatCmpResult) {
18052 case APFloat::cmpEqual:
18053 return CmpResult::Equal;
18054 case APFloat::cmpLessThan:
18055 return CmpResult::Less;
18056 case APFloat::cmpGreaterThan:
18057 return CmpResult::Greater;
18058 case APFloat::cmpUnordered:
18059 return CmpResult::Unordered;
18060 }
18061 llvm_unreachable("Unrecognised APFloat::cmpResult enum");
18062 };
18063 return Success(GetCmpRes(), E);
18064 }
18065
18066 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
18067 LValue LHSValue, RHSValue;
18068
18069 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
18070 if (!LHSOK && !Info.noteFailure())
18071 return false;
18072
18073 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
18074 return false;
18075
18076 // Reject differing bases from the normal codepath; we special-case
18077 // comparisons to null.
18078 if (!HasSameBase(LHSValue, RHSValue)) {
18079 // Bail out early if we're checking potential constant expression.
18080 // Otherwise, prefer to diagnose other issues.
18081 if (Info.checkingPotentialConstantExpression() &&
18082 (LHSValue.AllowConstexprUnknown || RHSValue.AllowConstexprUnknown))
18083 return false;
18084 auto DiagComparison = [&] (unsigned DiagID, bool Reversed = false) {
18085 std::string LHS = LHSValue.toString(Info.Ctx, E->getLHS()->getType());
18086 std::string RHS = RHSValue.toString(Info.Ctx, E->getRHS()->getType());
18087 Info.FFDiag(E, DiagID)
18088 << (Reversed ? RHS : LHS) << (Reversed ? LHS : RHS);
18089 return false;
18090 };
18091 // Inequalities and subtractions between unrelated pointers have
18092 // unspecified or undefined behavior.
18093 if (!IsEquality)
18094 return DiagComparison(
18095 diag::note_constexpr_pointer_comparison_unspecified);
18096 // A constant address may compare equal to the address of a symbol.
18097 // The one exception is that address of an object cannot compare equal
18098 // to a null pointer constant.
18099 // TODO: Should we restrict this to actual null pointers, and exclude the
18100 // case of zero cast to pointer type?
18101 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
18102 (!RHSValue.Base && !RHSValue.Offset.isZero()))
18103 return DiagComparison(diag::note_constexpr_pointer_constant_comparison,
18104 !RHSValue.Base);
18105 // C++2c [intro.object]/10:
18106 // Two objects [...] may have the same address if [...] they are both
18107 // potentially non-unique objects.
18108 // C++2c [intro.object]/9:
18109 // An object is potentially non-unique if it is a string literal object,
18110 // the backing array of an initializer list, or a subobject thereof.
18111 //
18112 // This makes the comparison result unspecified, so it's not a constant
18113 // expression.
18114 //
18115 // TODO: Do we need to handle the initializer list case here?
18116 if (ArePotentiallyOverlappingStringLiterals(Info, LHSValue, RHSValue))
18117 return DiagComparison(diag::note_constexpr_literal_comparison);
18118 if (IsOpaqueConstantCall(LHSValue) || IsOpaqueConstantCall(RHSValue))
18119 return DiagComparison(diag::note_constexpr_opaque_call_comparison,
18120 !IsOpaqueConstantCall(LHSValue));
18121 // We can't tell whether weak symbols will end up pointing to the same
18122 // object.
18123 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
18124 return DiagComparison(diag::note_constexpr_pointer_weak_comparison,
18125 !IsWeakLValue(LHSValue));
18126 // We can't compare the address of the start of one object with the
18127 // past-the-end address of another object, per C++ DR1652.
18128 if (LHSValue.Base && LHSValue.Offset.isZero() &&
18129 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue))
18130 return DiagComparison(diag::note_constexpr_pointer_comparison_past_end,
18131 true);
18132 if (RHSValue.Base && RHSValue.Offset.isZero() &&
18133 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue))
18134 return DiagComparison(diag::note_constexpr_pointer_comparison_past_end,
18135 false);
18136 // We can't tell whether an object is at the same address as another
18137 // zero sized object.
18138 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
18139 (LHSValue.Base && isZeroSized(RHSValue)))
18140 return DiagComparison(
18141 diag::note_constexpr_pointer_comparison_zero_sized);
18142 if (LHSValue.AllowConstexprUnknown || RHSValue.AllowConstexprUnknown)
18143 return DiagComparison(
18144 diag::note_constexpr_pointer_comparison_unspecified);
18145 // FIXME: Verify both variables are live.
18146 return Success(CmpResult::Unequal, E);
18147 }
18148
18149 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
18150 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
18151
18152 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
18153 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
18154
18155 // C++11 [expr.rel]p2:
18156 // - If two pointers point to non-static data members of the same object,
18157 // or to subobjects or array elements fo such members, recursively, the
18158 // pointer to the later declared member compares greater provided the
18159 // two members have the same access control and provided their class is
18160 // not a union.
18161 // [...]
18162 // - Otherwise pointer comparisons are unspecified.
18163 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
18164 bool WasArrayIndex;
18165 unsigned Mismatch = FindDesignatorMismatch(
18166 LHSValue.Base.isNull() ? QualType()
18167 : getType(LHSValue.Base).getNonReferenceType(),
18168 LHSDesignator, RHSDesignator, WasArrayIndex);
18169 // At the point where the designators diverge, the comparison has a
18170 // specified value if:
18171 // - we are comparing array indices
18172 // - we are comparing fields of a union, or fields with the same access
18173 // Otherwise, the result is unspecified and thus the comparison is not a
18174 // constant expression.
18175 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
18176 Mismatch < RHSDesignator.Entries.size()) {
18177 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
18178 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
18179 if (!LF && !RF)
18180 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
18181 else if (!LF)
18182 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
18183 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
18184 << RF->getParent() << RF;
18185 else if (!RF)
18186 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
18187 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
18188 << LF->getParent() << LF;
18189 else if (!LF->getParent()->isUnion() &&
18190 LF->getAccess() != RF->getAccess())
18191 Info.CCEDiag(E,
18192 diag::note_constexpr_pointer_comparison_differing_access)
18193 << LF << LF->getAccess() << RF << RF->getAccess()
18194 << LF->getParent();
18195 }
18196 }
18197
18198 // The comparison here must be unsigned, and performed with the same
18199 // width as the pointer.
18200 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
18201 uint64_t CompareLHS = LHSOffset.getQuantity();
18202 uint64_t CompareRHS = RHSOffset.getQuantity();
18203 assert(PtrSize <= 64 && "Unexpected pointer width");
18204 uint64_t Mask = ~0ULL >> (64 - PtrSize);
18205 CompareLHS &= Mask;
18206 CompareRHS &= Mask;
18207
18208 // If there is a base and this is a relational operator, we can only
18209 // compare pointers within the object in question; otherwise, the result
18210 // depends on where the object is located in memory.
18211 if (!LHSValue.Base.isNull() && IsRelational) {
18212 QualType BaseTy = getType(LHSValue.Base).getNonReferenceType();
18213 if (BaseTy->isIncompleteType())
18214 return Error(E);
18215 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
18216 uint64_t OffsetLimit = Size.getQuantity();
18217 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
18218 return Error(E);
18219 }
18220
18221 if (CompareLHS < CompareRHS)
18222 return Success(CmpResult::Less, E);
18223 if (CompareLHS > CompareRHS)
18224 return Success(CmpResult::Greater, E);
18225 return Success(CmpResult::Equal, E);
18226 }
18227
18228 if (LHSTy->isMemberPointerType()) {
18229 assert(IsEquality && "unexpected member pointer operation");
18230 assert(RHSTy->isMemberPointerType() && "invalid comparison");
18231
18232 MemberPtr LHSValue, RHSValue;
18233
18234 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
18235 if (!LHSOK && !Info.noteFailure())
18236 return false;
18237
18238 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
18239 return false;
18240
18241 // If either operand is a pointer to a weak function, the comparison is not
18242 // constant.
18243 if (LHSValue.getDecl() && LHSValue.getDecl()->isWeak()) {
18244 Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison)
18245 << LHSValue.getDecl();
18246 return false;
18247 }
18248 if (RHSValue.getDecl() && RHSValue.getDecl()->isWeak()) {
18249 Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison)
18250 << RHSValue.getDecl();
18251 return false;
18252 }
18253
18254 // C++11 [expr.eq]p2:
18255 // If both operands are null, they compare equal. Otherwise if only one is
18256 // null, they compare unequal.
18257 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
18258 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
18259 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
18260 }
18261
18262 // Otherwise if either is a pointer to a virtual member function, the
18263 // result is unspecified.
18264 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
18265 if (MD->isVirtual())
18266 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
18267 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
18268 if (MD->isVirtual())
18269 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
18270
18271 // Otherwise they compare equal if and only if they would refer to the
18272 // same member of the same most derived object or the same subobject if
18273 // they were dereferenced with a hypothetical object of the associated
18274 // class type.
18275 bool Equal = LHSValue == RHSValue;
18276 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
18277 }
18278
18279 if (LHSTy->isNullPtrType()) {
18280 assert(E->isComparisonOp() && "unexpected nullptr operation");
18281 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
18282 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
18283 // are compared, the result is true of the operator is <=, >= or ==, and
18284 // false otherwise.
18285 LValue Res;
18286 if (!EvaluatePointer(E->getLHS(), Res, Info) ||
18287 !EvaluatePointer(E->getRHS(), Res, Info))
18288 return false;
18289 return Success(CmpResult::Equal, E);
18290 }
18291
18292 return DoAfter();
18293}
18294
18295bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
18296 if (!CheckLiteralType(Info, E))
18297 return false;
18298
18299 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
18301 switch (CR) {
18302 case CmpResult::Unequal:
18303 llvm_unreachable("should never produce Unequal for three-way comparison");
18304 case CmpResult::Less:
18305 CCR = ComparisonCategoryResult::Less;
18306 break;
18307 case CmpResult::Equal:
18308 CCR = ComparisonCategoryResult::Equal;
18309 break;
18310 case CmpResult::Greater:
18311 CCR = ComparisonCategoryResult::Greater;
18312 break;
18313 case CmpResult::Unordered:
18314 CCR = ComparisonCategoryResult::Unordered;
18315 break;
18316 }
18317 // Evaluation succeeded. Lookup the information for the comparison category
18318 // type and fetch the VarDecl for the result.
18319 const ComparisonCategoryInfo &CmpInfo =
18320 Info.Ctx.CompCategories.getInfoForType(E->getType());
18321 const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD;
18322 // Check and evaluate the result as a constant expression.
18323 LValue LV;
18324 LV.set(VD);
18325 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
18326 return false;
18327 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
18328 ConstantExprKind::Normal);
18329 };
18330 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
18331 return ExprEvaluatorBaseTy::VisitBinCmp(E);
18332 });
18333}
18334
18335bool RecordExprEvaluator::VisitCXXParenListInitExpr(
18336 const CXXParenListInitExpr *E) {
18337 return VisitCXXParenListOrInitListExpr(E, E->getInitExprs());
18338}
18339
18340bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
18341 // We don't support assignment in C. C++ assignments don't get here because
18342 // assignment is an lvalue in C++.
18343 if (E->isAssignmentOp()) {
18344 Error(E);
18345 if (!Info.noteFailure())
18346 return false;
18347 }
18348
18349 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
18350 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
18351
18352 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
18354 "DataRecursiveIntBinOpEvaluator should have handled integral types");
18355
18356 if (E->isComparisonOp()) {
18357 // Evaluate builtin binary comparisons by evaluating them as three-way
18358 // comparisons and then translating the result.
18359 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
18360 assert((CR != CmpResult::Unequal || E->isEqualityOp()) &&
18361 "should only produce Unequal for equality comparisons");
18362 bool IsEqual = CR == CmpResult::Equal,
18363 IsLess = CR == CmpResult::Less,
18364 IsGreater = CR == CmpResult::Greater;
18365 auto Op = E->getOpcode();
18366 switch (Op) {
18367 default:
18368 llvm_unreachable("unsupported binary operator");
18369 case BO_EQ:
18370 case BO_NE:
18371 return Success(IsEqual == (Op == BO_EQ), E);
18372 case BO_LT:
18373 return Success(IsLess, E);
18374 case BO_GT:
18375 return Success(IsGreater, E);
18376 case BO_LE:
18377 return Success(IsEqual || IsLess, E);
18378 case BO_GE:
18379 return Success(IsEqual || IsGreater, E);
18380 }
18381 };
18382 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
18383 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
18384 });
18385 }
18386
18387 QualType LHSTy = E->getLHS()->getType();
18388 QualType RHSTy = E->getRHS()->getType();
18389
18390 if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
18391 E->getOpcode() == BO_Sub) {
18392 LValue LHSValue, RHSValue;
18393
18394 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
18395 if (!LHSOK && !Info.noteFailure())
18396 return false;
18397
18398 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
18399 return false;
18400
18401 // Reject differing bases from the normal codepath; we special-case
18402 // comparisons to null.
18403 if (!HasSameBase(LHSValue, RHSValue)) {
18404 if (Info.checkingPotentialConstantExpression() &&
18405 (LHSValue.AllowConstexprUnknown || RHSValue.AllowConstexprUnknown))
18406 return false;
18407
18408 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
18409 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
18410
18411 auto DiagArith = [&](unsigned DiagID) {
18412 std::string LHS = LHSValue.toString(Info.Ctx, E->getLHS()->getType());
18413 std::string RHS = RHSValue.toString(Info.Ctx, E->getRHS()->getType());
18414 Info.FFDiag(E, DiagID) << LHS << RHS;
18415 if (LHSExpr && LHSExpr == RHSExpr)
18416 Info.Note(LHSExpr->getExprLoc(),
18417 diag::note_constexpr_repeated_literal_eval)
18418 << LHSExpr->getSourceRange();
18419 return false;
18420 };
18421
18422 if (!LHSExpr || !RHSExpr)
18423 return DiagArith(diag::note_constexpr_pointer_arith_unspecified);
18424
18425 if (ArePotentiallyOverlappingStringLiterals(Info, LHSValue, RHSValue))
18426 return DiagArith(diag::note_constexpr_literal_arith);
18427
18428 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
18429 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
18430 if (!LHSAddrExpr || !RHSAddrExpr)
18431 return Error(E);
18432 // Make sure both labels come from the same function.
18433 if (LHSAddrExpr->getLabel()->getDeclContext() !=
18434 RHSAddrExpr->getLabel()->getDeclContext())
18435 return Error(E);
18436 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
18437 }
18438 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
18439 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
18440
18441 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
18442 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
18443
18444 // C++11 [expr.add]p6:
18445 // Unless both pointers point to elements of the same array object, or
18446 // one past the last element of the array object, the behavior is
18447 // undefined.
18448 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
18449 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
18450 RHSDesignator))
18451 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
18452
18453 QualType Type = E->getLHS()->getType();
18454 QualType ElementType = Type->castAs<PointerType>()->getPointeeType();
18455
18456 CharUnits ElementSize;
18457 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
18458 return false;
18459
18460 // As an extension, a type may have zero size (empty struct or union in
18461 // C, array of zero length). Pointer subtraction in such cases has
18462 // undefined behavior, so is not constant.
18463 if (ElementSize.isZero()) {
18464 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
18465 << ElementType;
18466 return false;
18467 }
18468
18469 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
18470 // and produce incorrect results when it overflows. Such behavior
18471 // appears to be non-conforming, but is common, so perhaps we should
18472 // assume the standard intended for such cases to be undefined behavior
18473 // and check for them.
18474
18475 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
18476 // overflow in the final conversion to ptrdiff_t.
18477 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
18478 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
18479 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
18480 false);
18481 APSInt TrueResult = (LHS - RHS) / ElemSize;
18482 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
18483
18484 if (Result.extend(65) != TrueResult &&
18485 !HandleOverflow(Info, E, TrueResult, E->getType()))
18486 return false;
18487 return Success(Result, E);
18488 }
18489
18490 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
18491}
18492
18493/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
18494/// a result as the expression's type.
18495bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
18496 const UnaryExprOrTypeTraitExpr *E) {
18497 switch(E->getKind()) {
18498 case UETT_PreferredAlignOf:
18499 case UETT_AlignOf: {
18500 if (E->isArgumentType())
18501 return Success(
18502 GetAlignOfType(Info.Ctx, E->getArgumentType(), E->getKind()), E);
18503 else
18504 return Success(
18505 GetAlignOfExpr(Info.Ctx, E->getArgumentExpr(), E->getKind()), E);
18506 }
18507
18508 case UETT_PtrAuthTypeDiscriminator: {
18509 if (E->getArgumentType()->isDependentType())
18510 return false;
18511 return Success(
18513 }
18514 case UETT_VecStep: {
18515 QualType Ty = E->getTypeOfArgument();
18516
18517 if (Ty->isVectorType()) {
18518 unsigned n = Ty->castAs<VectorType>()->getNumElements();
18519
18520 // The vec_step built-in functions that take a 3-component
18521 // vector return 4. (OpenCL 1.1 spec 6.11.12)
18522 if (n == 3)
18523 n = 4;
18524
18525 return Success(n, E);
18526 } else
18527 return Success(1, E);
18528 }
18529
18530 case UETT_DataSizeOf:
18531 case UETT_SizeOf: {
18532 QualType SrcTy = E->getTypeOfArgument();
18533 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
18534 // the result is the size of the referenced type."
18535 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
18536 SrcTy = Ref->getPointeeType();
18537
18538 CharUnits Sizeof;
18539 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof,
18540 E->getKind() == UETT_DataSizeOf ? SizeOfType::DataSizeOf
18541 : SizeOfType::SizeOf)) {
18542 return false;
18543 }
18544 return Success(Sizeof, E);
18545 }
18546 case UETT_OpenMPRequiredSimdAlign:
18547 assert(E->isArgumentType());
18548 return Success(
18549 Info.Ctx.toCharUnitsFromBits(
18551 .getQuantity(),
18552 E);
18553 case UETT_VectorElements: {
18554 QualType Ty = E->getTypeOfArgument();
18555 // If the vector has a fixed size, we can determine the number of elements
18556 // at compile time.
18557 if (const auto *VT = Ty->getAs<VectorType>())
18558 return Success(VT->getNumElements(), E);
18559
18560 assert(Ty->isSizelessVectorType());
18561 if (Info.InConstantContext)
18562 Info.CCEDiag(E, diag::note_constexpr_non_const_vectorelements)
18563 << E->getSourceRange();
18564
18565 return false;
18566 }
18567 case UETT_CountOf: {
18568 QualType Ty = E->getTypeOfArgument();
18569 assert(Ty->isArrayType());
18570
18571 // We don't need to worry about array element qualifiers, so getting the
18572 // unsafe array type is fine.
18573 if (const auto *CAT =
18574 dyn_cast<ConstantArrayType>(Ty->getAsArrayTypeUnsafe())) {
18575 return Success(CAT->getSize(), E);
18576 }
18577
18578 assert(!Ty->isConstantSizeType());
18579
18580 // If it's a variable-length array type, we need to check whether it is a
18581 // multidimensional array. If so, we need to check the size expression of
18582 // the VLA to see if it's a constant size. If so, we can return that value.
18583 const auto *VAT = Info.Ctx.getAsVariableArrayType(Ty);
18584 assert(VAT);
18585 if (VAT->getElementType()->isArrayType()) {
18586 // Variable array size expression could be missing (e.g. int a[*][10]) In
18587 // that case, it can't be a constant expression.
18588 if (!VAT->getSizeExpr()) {
18589 Info.FFDiag(E->getBeginLoc());
18590 return false;
18591 }
18592
18593 std::optional<APSInt> Res =
18594 VAT->getSizeExpr()->getIntegerConstantExpr(Info.Ctx);
18595 if (Res) {
18596 // The resulting value always has type size_t, so we need to make the
18597 // returned APInt have the correct sign and bit-width.
18598 APInt Val{
18599 static_cast<unsigned>(Info.Ctx.getTypeSize(Info.Ctx.getSizeType())),
18600 Res->getZExtValue()};
18601 return Success(Val, E);
18602 }
18603 }
18604
18605 // Definitely a variable-length type, which is not an ICE.
18606 // FIXME: Better diagnostic.
18607 Info.FFDiag(E->getBeginLoc());
18608 return false;
18609 }
18610 }
18611
18612 llvm_unreachable("unknown expr/type trait");
18613}
18614
18615bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
18616 CharUnits Result;
18617 unsigned n = OOE->getNumComponents();
18618 if (n == 0)
18619 return Error(OOE);
18620 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
18621 for (unsigned i = 0; i != n; ++i) {
18622 OffsetOfNode ON = OOE->getComponent(i);
18623 switch (ON.getKind()) {
18624 case OffsetOfNode::Array: {
18625 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
18626 APSInt IdxResult;
18627 if (!EvaluateInteger(Idx, IdxResult, Info))
18628 return false;
18629 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
18630 if (!AT)
18631 return Error(OOE);
18632 CurrentType = AT->getElementType();
18633 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
18634 Result += IdxResult.getSExtValue() * ElementSize;
18635 break;
18636 }
18637
18638 case OffsetOfNode::Field: {
18639 FieldDecl *MemberDecl = ON.getField();
18640 const auto *RD = CurrentType->getAsRecordDecl();
18641 if (!RD)
18642 return Error(OOE);
18643 if (RD->isInvalidDecl()) return false;
18644 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
18645 unsigned i = MemberDecl->getFieldIndex();
18646 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
18647 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
18648 CurrentType = MemberDecl->getType().getNonReferenceType();
18649 break;
18650 }
18651
18653 llvm_unreachable("dependent __builtin_offsetof");
18654
18655 case OffsetOfNode::Base: {
18656 CXXBaseSpecifier *BaseSpec = ON.getBase();
18657 if (BaseSpec->isVirtual())
18658 return Error(OOE);
18659
18660 // Find the layout of the class whose base we are looking into.
18661 const auto *RD = CurrentType->getAsCXXRecordDecl();
18662 if (!RD)
18663 return Error(OOE);
18664 if (RD->isInvalidDecl()) return false;
18665 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
18666
18667 // Find the base class itself.
18668 CurrentType = BaseSpec->getType();
18669 const auto *BaseRD = CurrentType->getAsCXXRecordDecl();
18670 if (!BaseRD)
18671 return Error(OOE);
18672
18673 // Add the offset to the base.
18674 Result += RL.getBaseClassOffset(BaseRD);
18675 break;
18676 }
18677 }
18678 }
18679 return Success(Result, OOE);
18680}
18681
18682bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
18683 switch (E->getOpcode()) {
18684 default:
18685 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
18686 // See C99 6.6p3.
18687 return Error(E);
18688 case UO_Extension:
18689 // FIXME: Should extension allow i-c-e extension expressions in its scope?
18690 // If so, we could clear the diagnostic ID.
18691 return Visit(E->getSubExpr());
18692 case UO_Plus:
18693 // The result is just the value.
18694 return Visit(E->getSubExpr());
18695 case UO_Minus: {
18696 if (!Visit(E->getSubExpr()))
18697 return false;
18698 if (!Result.isInt()) return Error(E);
18699 const APSInt &Value = Result.getInt();
18700 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow()) {
18701 if (Info.checkingForUndefinedBehavior())
18702 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
18703 diag::warn_integer_constant_overflow)
18704 << toString(Value, 10, Value.isSigned(), /*formatAsCLiteral=*/false,
18705 /*UpperCase=*/true, /*InsertSeparators=*/true)
18706 << E->getType() << E->getSourceRange();
18707
18708 if (!HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
18709 E->getType()))
18710 return false;
18711 }
18712 return Success(-Value, E);
18713 }
18714 case UO_Not: {
18715 if (!Visit(E->getSubExpr()))
18716 return false;
18717 if (!Result.isInt()) return Error(E);
18718 return Success(~Result.getInt(), E);
18719 }
18720 case UO_LNot: {
18721 bool bres;
18722 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
18723 return false;
18724 return Success(!bres, E);
18725 }
18726 }
18727}
18728
18729/// HandleCast - This is used to evaluate implicit or explicit casts where the
18730/// result type is integer.
18731bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
18732 const Expr *SubExpr = E->getSubExpr();
18733 QualType DestType = E->getType();
18734 QualType SrcType = SubExpr->getType();
18735
18736 switch (E->getCastKind()) {
18737 case CK_BaseToDerived:
18738 case CK_DerivedToBase:
18739 case CK_UncheckedDerivedToBase:
18740 case CK_Dynamic:
18741 case CK_ToUnion:
18742 case CK_ArrayToPointerDecay:
18743 case CK_FunctionToPointerDecay:
18744 case CK_NullToPointer:
18745 case CK_NullToMemberPointer:
18746 case CK_BaseToDerivedMemberPointer:
18747 case CK_DerivedToBaseMemberPointer:
18748 case CK_ReinterpretMemberPointer:
18749 case CK_ConstructorConversion:
18750 case CK_IntegralToPointer:
18751 case CK_ToVoid:
18752 case CK_VectorSplat:
18753 case CK_IntegralToFloating:
18754 case CK_FloatingCast:
18755 case CK_CPointerToObjCPointerCast:
18756 case CK_BlockPointerToObjCPointerCast:
18757 case CK_AnyPointerToBlockPointerCast:
18758 case CK_ObjCObjectLValueCast:
18759 case CK_FloatingRealToComplex:
18760 case CK_FloatingComplexToReal:
18761 case CK_FloatingComplexCast:
18762 case CK_FloatingComplexToIntegralComplex:
18763 case CK_IntegralRealToComplex:
18764 case CK_IntegralComplexCast:
18765 case CK_IntegralComplexToFloatingComplex:
18766 case CK_BuiltinFnToFnPtr:
18767 case CK_ZeroToOCLOpaqueType:
18768 case CK_NonAtomicToAtomic:
18769 case CK_AddressSpaceConversion:
18770 case CK_IntToOCLSampler:
18771 case CK_FloatingToFixedPoint:
18772 case CK_FixedPointToFloating:
18773 case CK_FixedPointCast:
18774 case CK_IntegralToFixedPoint:
18775 case CK_MatrixCast:
18776 case CK_HLSLAggregateSplatCast:
18777 llvm_unreachable("invalid cast kind for integral value");
18778
18779 case CK_BitCast:
18780 case CK_Dependent:
18781 case CK_LValueBitCast:
18782 case CK_ARCProduceObject:
18783 case CK_ARCConsumeObject:
18784 case CK_ARCReclaimReturnedObject:
18785 case CK_ARCExtendBlockObject:
18786 case CK_CopyAndAutoreleaseBlockObject:
18787 return Error(E);
18788
18789 case CK_UserDefinedConversion:
18790 case CK_LValueToRValue:
18791 case CK_AtomicToNonAtomic:
18792 case CK_NoOp:
18793 case CK_LValueToRValueBitCast:
18794 case CK_HLSLArrayRValue:
18795 return ExprEvaluatorBaseTy::VisitCastExpr(E);
18796
18797 case CK_MemberPointerToBoolean:
18798 case CK_PointerToBoolean:
18799 case CK_IntegralToBoolean:
18800 case CK_FloatingToBoolean:
18801 case CK_BooleanToSignedIntegral:
18802 case CK_FloatingComplexToBoolean:
18803 case CK_IntegralComplexToBoolean: {
18804 bool BoolResult;
18805 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
18806 return false;
18807 uint64_t IntResult = BoolResult;
18808 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
18809 IntResult = (uint64_t)-1;
18810 return Success(IntResult, E);
18811 }
18812
18813 case CK_FixedPointToIntegral: {
18814 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
18815 if (!EvaluateFixedPoint(SubExpr, Src, Info))
18816 return false;
18817 bool Overflowed;
18818 llvm::APSInt Result = Src.convertToInt(
18819 Info.Ctx.getIntWidth(DestType),
18820 DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
18821 if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
18822 return false;
18823 return Success(Result, E);
18824 }
18825
18826 case CK_FixedPointToBoolean: {
18827 // Unsigned padding does not affect this.
18828 APValue Val;
18829 if (!Evaluate(Val, Info, SubExpr))
18830 return false;
18831 return Success(Val.getFixedPoint().getBoolValue(), E);
18832 }
18833
18834 case CK_IntegralCast: {
18835 if (!Visit(SubExpr))
18836 return false;
18837
18838 if (!Result.isInt()) {
18839 // Allow casts of address-of-label differences if they are no-ops
18840 // or narrowing, if the result is at least 32 bits wide.
18841 // (The narrowing case isn't actually guaranteed to
18842 // be constant-evaluatable except in some narrow cases which are hard
18843 // to detect here. We let it through on the assumption the user knows
18844 // what they are doing.)
18845 if (Result.isAddrLabelDiff()) {
18846 unsigned DestBits = Info.Ctx.getTypeSize(DestType);
18847 return DestBits >= 32 && DestBits <= Info.Ctx.getTypeSize(SrcType);
18848 }
18849 // Only allow casts of lvalues if they are lossless.
18850 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
18851 }
18852
18853 if (Info.Ctx.getLangOpts().CPlusPlus && DestType->isEnumeralType()) {
18854 const auto *ED = DestType->getAsEnumDecl();
18855 // Check that the value is within the range of the enumeration values.
18856 //
18857 // This corressponds to [expr.static.cast]p10 which says:
18858 // A value of integral or enumeration type can be explicitly converted
18859 // to a complete enumeration type ... If the enumeration type does not
18860 // have a fixed underlying type, the value is unchanged if the original
18861 // value is within the range of the enumeration values ([dcl.enum]), and
18862 // otherwise, the behavior is undefined.
18863 //
18864 // This was resolved as part of DR2338 which has CD5 status.
18865 if (!ED->isFixed()) {
18866 llvm::APInt Min;
18867 llvm::APInt Max;
18868
18869 ED->getValueRange(Max, Min);
18870 --Max;
18871
18872 if (ED->getNumNegativeBits() &&
18873 (Max.slt(Result.getInt().getSExtValue()) ||
18874 Min.sgt(Result.getInt().getSExtValue())))
18875 Info.CCEDiag(E, diag::note_constexpr_unscoped_enum_out_of_range)
18876 << llvm::toString(Result.getInt(), 10) << Min.getSExtValue()
18877 << Max.getSExtValue() << ED;
18878 else if (!ED->getNumNegativeBits() &&
18879 Max.ult(Result.getInt().getZExtValue()))
18880 Info.CCEDiag(E, diag::note_constexpr_unscoped_enum_out_of_range)
18881 << llvm::toString(Result.getInt(), 10) << Min.getZExtValue()
18882 << Max.getZExtValue() << ED;
18883 }
18884 }
18885
18886 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
18887 Result.getInt()), E);
18888 }
18889
18890 case CK_PointerToIntegral: {
18891 CCEDiag(E, diag::note_constexpr_invalid_cast)
18892 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
18893 << Info.Ctx.getLangOpts().CPlusPlus << E->getSourceRange();
18894
18895 LValue LV;
18896 if (!EvaluatePointer(SubExpr, LV, Info))
18897 return false;
18898
18899 if (LV.getLValueBase()) {
18900 // Only allow based lvalue casts if they are lossless.
18901 // FIXME: Allow a larger integer size than the pointer size, and allow
18902 // narrowing back down to pointer width in subsequent integral casts.
18903 // FIXME: Check integer type's active bits, not its type size.
18904 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
18905 return Error(E);
18906
18907 LV.Designator.setInvalid();
18908 LV.moveInto(Result);
18909 return true;
18910 }
18911
18912 APSInt AsInt;
18913 APValue V;
18914 LV.moveInto(V);
18915 if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
18916 llvm_unreachable("Can't cast this!");
18917
18918 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
18919 }
18920
18921 case CK_IntegralComplexToReal: {
18922 ComplexValue C;
18923 if (!EvaluateComplex(SubExpr, C, Info))
18924 return false;
18925 return Success(C.getComplexIntReal(), E);
18926 }
18927
18928 case CK_FloatingToIntegral: {
18929 APFloat F(0.0);
18930 if (!EvaluateFloat(SubExpr, F, Info))
18931 return false;
18932
18933 APSInt Value;
18934 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
18935 return false;
18936 return Success(Value, E);
18937 }
18938 case CK_HLSLVectorTruncation: {
18939 APValue Val;
18940 if (!EvaluateVector(SubExpr, Val, Info))
18941 return Error(E);
18942 return Success(Val.getVectorElt(0), E);
18943 }
18944 case CK_HLSLMatrixTruncation: {
18945 // TODO: See #168935. Add matrix truncation support to expr constant.
18946 return Error(E);
18947 }
18948 case CK_HLSLElementwiseCast: {
18949 SmallVector<APValue> SrcVals;
18950 SmallVector<QualType> SrcTypes;
18951
18952 if (!hlslElementwiseCastHelper(Info, SubExpr, DestType, SrcVals, SrcTypes))
18953 return false;
18954
18955 // cast our single element
18956 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
18957 APValue ResultVal;
18958 if (!handleScalarCast(Info, FPO, E, SrcTypes[0], DestType, SrcVals[0],
18959 ResultVal))
18960 return false;
18961 return Success(ResultVal, E);
18962 }
18963 }
18964
18965 llvm_unreachable("unknown cast resulting in integral value");
18966}
18967
18968bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
18969 if (E->getSubExpr()->getType()->isAnyComplexType()) {
18970 ComplexValue LV;
18971 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
18972 return false;
18973 if (!LV.isComplexInt())
18974 return Error(E);
18975 return Success(LV.getComplexIntReal(), E);
18976 }
18977
18978 return Visit(E->getSubExpr());
18979}
18980
18981bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
18982 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
18983 ComplexValue LV;
18984 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
18985 return false;
18986 if (!LV.isComplexInt())
18987 return Error(E);
18988 return Success(LV.getComplexIntImag(), E);
18989 }
18990
18991 VisitIgnoredValue(E->getSubExpr());
18992 return Success(0, E);
18993}
18994
18995bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
18996 return Success(E->getPackLength(), E);
18997}
18998
18999bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
19000 return Success(E->getValue(), E);
19001}
19002
19003bool IntExprEvaluator::VisitConceptSpecializationExpr(
19004 const ConceptSpecializationExpr *E) {
19005 return Success(E->isSatisfied(), E);
19006}
19007
19008bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) {
19009 return Success(E->isSatisfied(), E);
19010}
19011
19012bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
19013 switch (E->getOpcode()) {
19014 default:
19015 // Invalid unary operators
19016 return Error(E);
19017 case UO_Plus:
19018 // The result is just the value.
19019 return Visit(E->getSubExpr());
19020 case UO_Minus: {
19021 if (!Visit(E->getSubExpr())) return false;
19022 if (!Result.isFixedPoint())
19023 return Error(E);
19024 bool Overflowed;
19025 APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
19026 if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
19027 return false;
19028 return Success(Negated, E);
19029 }
19030 case UO_LNot: {
19031 bool bres;
19032 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
19033 return false;
19034 return Success(!bres, E);
19035 }
19036 }
19037}
19038
19039bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
19040 const Expr *SubExpr = E->getSubExpr();
19041 QualType DestType = E->getType();
19042 assert(DestType->isFixedPointType() &&
19043 "Expected destination type to be a fixed point type");
19044 auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
19045
19046 switch (E->getCastKind()) {
19047 case CK_FixedPointCast: {
19048 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
19049 if (!EvaluateFixedPoint(SubExpr, Src, Info))
19050 return false;
19051 bool Overflowed;
19052 APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
19053 if (Overflowed) {
19054 if (Info.checkingForUndefinedBehavior())
19055 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
19056 diag::warn_fixedpoint_constant_overflow)
19057 << Result.toString() << E->getType();
19058 if (!HandleOverflow(Info, E, Result, E->getType()))
19059 return false;
19060 }
19061 return Success(Result, E);
19062 }
19063 case CK_IntegralToFixedPoint: {
19064 APSInt Src;
19065 if (!EvaluateInteger(SubExpr, Src, Info))
19066 return false;
19067
19068 bool Overflowed;
19069 APFixedPoint IntResult = APFixedPoint::getFromIntValue(
19070 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
19071
19072 if (Overflowed) {
19073 if (Info.checkingForUndefinedBehavior())
19074 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
19075 diag::warn_fixedpoint_constant_overflow)
19076 << IntResult.toString() << E->getType();
19077 if (!HandleOverflow(Info, E, IntResult, E->getType()))
19078 return false;
19079 }
19080
19081 return Success(IntResult, E);
19082 }
19083 case CK_FloatingToFixedPoint: {
19084 APFloat Src(0.0);
19085 if (!EvaluateFloat(SubExpr, Src, Info))
19086 return false;
19087
19088 bool Overflowed;
19089 APFixedPoint Result = APFixedPoint::getFromFloatValue(
19090 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
19091
19092 if (Overflowed) {
19093 if (Info.checkingForUndefinedBehavior())
19094 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
19095 diag::warn_fixedpoint_constant_overflow)
19096 << Result.toString() << E->getType();
19097 if (!HandleOverflow(Info, E, Result, E->getType()))
19098 return false;
19099 }
19100
19101 return Success(Result, E);
19102 }
19103 case CK_NoOp:
19104 case CK_LValueToRValue:
19105 return ExprEvaluatorBaseTy::VisitCastExpr(E);
19106 default:
19107 return Error(E);
19108 }
19109}
19110
19111bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
19112 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
19113 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
19114
19115 const Expr *LHS = E->getLHS();
19116 const Expr *RHS = E->getRHS();
19117 FixedPointSemantics ResultFXSema =
19118 Info.Ctx.getFixedPointSemantics(E->getType());
19119
19120 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
19121 if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
19122 return false;
19123 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
19124 if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
19125 return false;
19126
19127 bool OpOverflow = false, ConversionOverflow = false;
19128 APFixedPoint Result(LHSFX.getSemantics());
19129 switch (E->getOpcode()) {
19130 case BO_Add: {
19131 Result = LHSFX.add(RHSFX, &OpOverflow)
19132 .convert(ResultFXSema, &ConversionOverflow);
19133 break;
19134 }
19135 case BO_Sub: {
19136 Result = LHSFX.sub(RHSFX, &OpOverflow)
19137 .convert(ResultFXSema, &ConversionOverflow);
19138 break;
19139 }
19140 case BO_Mul: {
19141 Result = LHSFX.mul(RHSFX, &OpOverflow)
19142 .convert(ResultFXSema, &ConversionOverflow);
19143 break;
19144 }
19145 case BO_Div: {
19146 if (RHSFX.getValue() == 0) {
19147 Info.FFDiag(E, diag::note_expr_divide_by_zero);
19148 return false;
19149 }
19150 Result = LHSFX.div(RHSFX, &OpOverflow)
19151 .convert(ResultFXSema, &ConversionOverflow);
19152 break;
19153 }
19154 case BO_Shl:
19155 case BO_Shr: {
19156 FixedPointSemantics LHSSema = LHSFX.getSemantics();
19157 llvm::APSInt RHSVal = RHSFX.getValue();
19158
19159 unsigned ShiftBW =
19160 LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding();
19161 unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1);
19162 // Embedded-C 4.1.6.2.2:
19163 // The right operand must be nonnegative and less than the total number
19164 // of (nonpadding) bits of the fixed-point operand ...
19165 if (RHSVal.isNegative())
19166 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal;
19167 else if (Amt != RHSVal)
19168 Info.CCEDiag(E, diag::note_constexpr_large_shift)
19169 << RHSVal << E->getType() << ShiftBW;
19170
19171 if (E->getOpcode() == BO_Shl)
19172 Result = LHSFX.shl(Amt, &OpOverflow);
19173 else
19174 Result = LHSFX.shr(Amt, &OpOverflow);
19175 break;
19176 }
19177 default:
19178 return false;
19179 }
19180 if (OpOverflow || ConversionOverflow) {
19181 if (Info.checkingForUndefinedBehavior())
19182 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
19183 diag::warn_fixedpoint_constant_overflow)
19184 << Result.toString() << E->getType();
19185 if (!HandleOverflow(Info, E, Result, E->getType()))
19186 return false;
19187 }
19188 return Success(Result, E);
19189}
19190
19191//===----------------------------------------------------------------------===//
19192// Float Evaluation
19193//===----------------------------------------------------------------------===//
19194
19195namespace {
19196class FloatExprEvaluator
19197 : public ExprEvaluatorBase<FloatExprEvaluator> {
19198 APFloat &Result;
19199public:
19200 FloatExprEvaluator(EvalInfo &info, APFloat &result)
19201 : ExprEvaluatorBaseTy(info), Result(result) {}
19202
19203 bool Success(const APValue &V, const Expr *e) {
19204 Result = V.getFloat();
19205 return true;
19206 }
19207
19208 bool ZeroInitialization(const Expr *E) {
19209 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
19210 return true;
19211 }
19212
19213 bool VisitCallExpr(const CallExpr *E);
19214
19215 bool VisitUnaryOperator(const UnaryOperator *E);
19216 bool VisitBinaryOperator(const BinaryOperator *E);
19217 bool VisitFloatingLiteral(const FloatingLiteral *E);
19218 bool VisitCastExpr(const CastExpr *E);
19219
19220 bool VisitUnaryReal(const UnaryOperator *E);
19221 bool VisitUnaryImag(const UnaryOperator *E);
19222
19223 // FIXME: Missing: array subscript of vector, member of vector
19224};
19225} // end anonymous namespace
19226
19227static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
19228 assert(!E->isValueDependent());
19229 assert(E->isPRValue() && E->getType()->isRealFloatingType());
19230 return FloatExprEvaluator(Info, Result).Visit(E);
19231}
19232
19233static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
19234 QualType ResultTy,
19235 const Expr *Arg,
19236 bool SNaN,
19237 llvm::APFloat &Result) {
19238 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
19239 if (!S) return false;
19240
19241 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
19242
19243 llvm::APInt fill;
19244
19245 // Treat empty strings as if they were zero.
19246 if (S->getString().empty())
19247 fill = llvm::APInt(32, 0);
19248 else if (S->getString().getAsInteger(0, fill))
19249 return false;
19250
19251 if (Context.getTargetInfo().isNan2008()) {
19252 if (SNaN)
19253 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
19254 else
19255 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
19256 } else {
19257 // Prior to IEEE 754-2008, architectures were allowed to choose whether
19258 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
19259 // a different encoding to what became a standard in 2008, and for pre-
19260 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
19261 // sNaN. This is now known as "legacy NaN" encoding.
19262 if (SNaN)
19263 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
19264 else
19265 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
19266 }
19267
19268 return true;
19269}
19270
19271bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
19272 if (!IsConstantEvaluatedBuiltinCall(E))
19273 return ExprEvaluatorBaseTy::VisitCallExpr(E);
19274
19275 switch (E->getBuiltinCallee()) {
19276 default:
19277 return false;
19278
19279 case Builtin::BI__builtin_huge_val:
19280 case Builtin::BI__builtin_huge_valf:
19281 case Builtin::BI__builtin_huge_vall:
19282 case Builtin::BI__builtin_huge_valf16:
19283 case Builtin::BI__builtin_huge_valf128:
19284 case Builtin::BI__builtin_inf:
19285 case Builtin::BI__builtin_inff:
19286 case Builtin::BI__builtin_infl:
19287 case Builtin::BI__builtin_inff16:
19288 case Builtin::BI__builtin_inff128: {
19289 const llvm::fltSemantics &Sem =
19290 Info.Ctx.getFloatTypeSemantics(E->getType());
19291 Result = llvm::APFloat::getInf(Sem);
19292 return true;
19293 }
19294
19295 case Builtin::BI__builtin_nans:
19296 case Builtin::BI__builtin_nansf:
19297 case Builtin::BI__builtin_nansl:
19298 case Builtin::BI__builtin_nansf16:
19299 case Builtin::BI__builtin_nansf128:
19300 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
19301 true, Result))
19302 return Error(E);
19303 return true;
19304
19305 case Builtin::BI__builtin_nan:
19306 case Builtin::BI__builtin_nanf:
19307 case Builtin::BI__builtin_nanl:
19308 case Builtin::BI__builtin_nanf16:
19309 case Builtin::BI__builtin_nanf128:
19310 // If this is __builtin_nan() turn this into a nan, otherwise we
19311 // can't constant fold it.
19312 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
19313 false, Result))
19314 return Error(E);
19315 return true;
19316
19317 case Builtin::BI__builtin_elementwise_abs:
19318 case Builtin::BI__builtin_fabs:
19319 case Builtin::BI__builtin_fabsf:
19320 case Builtin::BI__builtin_fabsl:
19321 case Builtin::BI__builtin_fabsf128:
19322 // The C standard says "fabs raises no floating-point exceptions,
19323 // even if x is a signaling NaN. The returned value is independent of
19324 // the current rounding direction mode." Therefore constant folding can
19325 // proceed without regard to the floating point settings.
19326 // Reference, WG14 N2478 F.10.4.3
19327 if (!EvaluateFloat(E->getArg(0), Result, Info))
19328 return false;
19329
19330 if (Result.isNegative())
19331 Result.changeSign();
19332 return true;
19333
19334 case Builtin::BI__arithmetic_fence:
19335 return EvaluateFloat(E->getArg(0), Result, Info);
19336
19337 // FIXME: Builtin::BI__builtin_powi
19338 // FIXME: Builtin::BI__builtin_powif
19339 // FIXME: Builtin::BI__builtin_powil
19340
19341 case Builtin::BI__builtin_copysign:
19342 case Builtin::BI__builtin_copysignf:
19343 case Builtin::BI__builtin_copysignl:
19344 case Builtin::BI__builtin_copysignf128: {
19345 APFloat RHS(0.);
19346 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
19347 !EvaluateFloat(E->getArg(1), RHS, Info))
19348 return false;
19349 Result.copySign(RHS);
19350 return true;
19351 }
19352
19353 case Builtin::BI__builtin_fmax:
19354 case Builtin::BI__builtin_fmaxf:
19355 case Builtin::BI__builtin_fmaxl:
19356 case Builtin::BI__builtin_fmaxf16:
19357 case Builtin::BI__builtin_fmaxf128: {
19358 APFloat RHS(0.);
19359 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
19360 !EvaluateFloat(E->getArg(1), RHS, Info))
19361 return false;
19362 Result = maxnum(Result, RHS);
19363 return true;
19364 }
19365
19366 case Builtin::BI__builtin_fmin:
19367 case Builtin::BI__builtin_fminf:
19368 case Builtin::BI__builtin_fminl:
19369 case Builtin::BI__builtin_fminf16:
19370 case Builtin::BI__builtin_fminf128: {
19371 APFloat RHS(0.);
19372 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
19373 !EvaluateFloat(E->getArg(1), RHS, Info))
19374 return false;
19375 Result = minnum(Result, RHS);
19376 return true;
19377 }
19378
19379 case Builtin::BI__builtin_fmaximum_num:
19380 case Builtin::BI__builtin_fmaximum_numf:
19381 case Builtin::BI__builtin_fmaximum_numl:
19382 case Builtin::BI__builtin_fmaximum_numf16:
19383 case Builtin::BI__builtin_fmaximum_numf128: {
19384 APFloat RHS(0.);
19385 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
19386 !EvaluateFloat(E->getArg(1), RHS, Info))
19387 return false;
19388 Result = maximumnum(Result, RHS);
19389 return true;
19390 }
19391
19392 case Builtin::BI__builtin_fminimum_num:
19393 case Builtin::BI__builtin_fminimum_numf:
19394 case Builtin::BI__builtin_fminimum_numl:
19395 case Builtin::BI__builtin_fminimum_numf16:
19396 case Builtin::BI__builtin_fminimum_numf128: {
19397 APFloat RHS(0.);
19398 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
19399 !EvaluateFloat(E->getArg(1), RHS, Info))
19400 return false;
19401 Result = minimumnum(Result, RHS);
19402 return true;
19403 }
19404
19405 case Builtin::BI__builtin_elementwise_fma: {
19406 if (!E->getArg(0)->isPRValue() || !E->getArg(1)->isPRValue() ||
19407 !E->getArg(2)->isPRValue()) {
19408 return false;
19409 }
19410 APFloat SourceY(0.), SourceZ(0.);
19411 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
19412 !EvaluateFloat(E->getArg(1), SourceY, Info) ||
19413 !EvaluateFloat(E->getArg(2), SourceZ, Info))
19414 return false;
19415 llvm::RoundingMode RM = getActiveRoundingMode(getEvalInfo(), E);
19416 (void)Result.fusedMultiplyAdd(SourceY, SourceZ, RM);
19417 return true;
19418 }
19419
19420 case clang::X86::BI__builtin_ia32_vec_ext_v4sf: {
19421 APValue Vec;
19422 APSInt IdxAPS;
19423 if (!EvaluateVector(E->getArg(0), Vec, Info) ||
19424 !EvaluateInteger(E->getArg(1), IdxAPS, Info))
19425 return false;
19426 unsigned N = Vec.getVectorLength();
19427 unsigned Idx = static_cast<unsigned>(IdxAPS.getZExtValue() & (N - 1));
19428 return Success(Vec.getVectorElt(Idx), E);
19429 }
19430 }
19431}
19432
19433bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
19434 if (E->getSubExpr()->getType()->isAnyComplexType()) {
19435 ComplexValue CV;
19436 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
19437 return false;
19438 Result = CV.FloatReal;
19439 return true;
19440 }
19441
19442 return Visit(E->getSubExpr());
19443}
19444
19445bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
19446 if (E->getSubExpr()->getType()->isAnyComplexType()) {
19447 ComplexValue CV;
19448 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
19449 return false;
19450 Result = CV.FloatImag;
19451 return true;
19452 }
19453
19454 VisitIgnoredValue(E->getSubExpr());
19455 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
19456 Result = llvm::APFloat::getZero(Sem);
19457 return true;
19458}
19459
19460bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
19461 switch (E->getOpcode()) {
19462 default: return Error(E);
19463 case UO_Plus:
19464 return EvaluateFloat(E->getSubExpr(), Result, Info);
19465 case UO_Minus:
19466 // In C standard, WG14 N2478 F.3 p4
19467 // "the unary - raises no floating point exceptions,
19468 // even if the operand is signalling."
19469 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
19470 return false;
19471 Result.changeSign();
19472 return true;
19473 }
19474}
19475
19476bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
19477 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
19478 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
19479
19480 APFloat RHS(0.0);
19481 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
19482 if (!LHSOK && !Info.noteFailure())
19483 return false;
19484 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
19485 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
19486}
19487
19488bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
19489 Result = E->getValue();
19490 return true;
19491}
19492
19493bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
19494 const Expr* SubExpr = E->getSubExpr();
19495
19496 switch (E->getCastKind()) {
19497 default:
19498 return ExprEvaluatorBaseTy::VisitCastExpr(E);
19499
19500 case CK_HLSLAggregateSplatCast:
19501 llvm_unreachable("invalid cast kind for floating value");
19502
19503 case CK_IntegralToFloating: {
19504 APSInt IntResult;
19505 const FPOptions FPO = E->getFPFeaturesInEffect(
19506 Info.Ctx.getLangOpts());
19507 return EvaluateInteger(SubExpr, IntResult, Info) &&
19508 HandleIntToFloatCast(Info, E, FPO, SubExpr->getType(),
19509 IntResult, E->getType(), Result);
19510 }
19511
19512 case CK_FixedPointToFloating: {
19513 APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
19514 if (!EvaluateFixedPoint(SubExpr, FixResult, Info))
19515 return false;
19516 Result =
19517 FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->getType()));
19518 return true;
19519 }
19520
19521 case CK_FloatingCast: {
19522 if (!Visit(SubExpr))
19523 return false;
19524 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
19525 Result);
19526 }
19527
19528 case CK_FloatingComplexToReal: {
19529 ComplexValue V;
19530 if (!EvaluateComplex(SubExpr, V, Info))
19531 return false;
19532 Result = V.getComplexFloatReal();
19533 return true;
19534 }
19535 case CK_HLSLVectorTruncation: {
19536 APValue Val;
19537 if (!EvaluateVector(SubExpr, Val, Info))
19538 return Error(E);
19539 return Success(Val.getVectorElt(0), E);
19540 }
19541 case CK_HLSLMatrixTruncation: {
19542 // TODO: See #168935. Add matrix truncation support to expr constant.
19543 return Error(E);
19544 }
19545 case CK_HLSLElementwiseCast: {
19546 SmallVector<APValue> SrcVals;
19547 SmallVector<QualType> SrcTypes;
19548
19549 if (!hlslElementwiseCastHelper(Info, SubExpr, E->getType(), SrcVals,
19550 SrcTypes))
19551 return false;
19552 APValue Val;
19553
19554 // cast our single element
19555 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
19556 APValue ResultVal;
19557 if (!handleScalarCast(Info, FPO, E, SrcTypes[0], E->getType(), SrcVals[0],
19558 ResultVal))
19559 return false;
19560 return Success(ResultVal, E);
19561 }
19562 }
19563}
19564
19565//===----------------------------------------------------------------------===//
19566// Complex Evaluation (for float and integer)
19567//===----------------------------------------------------------------------===//
19568
19569namespace {
19570class ComplexExprEvaluator
19571 : public ExprEvaluatorBase<ComplexExprEvaluator> {
19572 ComplexValue &Result;
19573
19574public:
19575 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
19576 : ExprEvaluatorBaseTy(info), Result(Result) {}
19577
19578 bool Success(const APValue &V, const Expr *e) {
19579 Result.setFrom(V);
19580 return true;
19581 }
19582
19583 bool ZeroInitialization(const Expr *E);
19584
19585 //===--------------------------------------------------------------------===//
19586 // Visitor Methods
19587 //===--------------------------------------------------------------------===//
19588
19589 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
19590 bool VisitCastExpr(const CastExpr *E);
19591 bool VisitBinaryOperator(const BinaryOperator *E);
19592 bool VisitUnaryOperator(const UnaryOperator *E);
19593 bool VisitInitListExpr(const InitListExpr *E);
19594 bool VisitCallExpr(const CallExpr *E);
19595};
19596} // end anonymous namespace
19597
19598static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
19599 EvalInfo &Info) {
19600 assert(!E->isValueDependent());
19601 assert(E->isPRValue() && E->getType()->isAnyComplexType());
19602 return ComplexExprEvaluator(Info, Result).Visit(E);
19603}
19604
19605bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
19606 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
19607 if (ElemTy->isRealFloatingType()) {
19608 Result.makeComplexFloat();
19609 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
19610 Result.FloatReal = Zero;
19611 Result.FloatImag = Zero;
19612 } else {
19613 Result.makeComplexInt();
19614 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
19615 Result.IntReal = Zero;
19616 Result.IntImag = Zero;
19617 }
19618 return true;
19619}
19620
19621bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
19622 const Expr* SubExpr = E->getSubExpr();
19623
19624 if (SubExpr->getType()->isRealFloatingType()) {
19625 Result.makeComplexFloat();
19626 APFloat &Imag = Result.FloatImag;
19627 if (!EvaluateFloat(SubExpr, Imag, Info))
19628 return false;
19629
19630 Result.FloatReal = APFloat(Imag.getSemantics());
19631 return true;
19632 } else {
19633 assert(SubExpr->getType()->isIntegerType() &&
19634 "Unexpected imaginary literal.");
19635
19636 Result.makeComplexInt();
19637 APSInt &Imag = Result.IntImag;
19638 if (!EvaluateInteger(SubExpr, Imag, Info))
19639 return false;
19640
19641 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
19642 return true;
19643 }
19644}
19645
19646bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
19647
19648 switch (E->getCastKind()) {
19649 case CK_BitCast:
19650 case CK_BaseToDerived:
19651 case CK_DerivedToBase:
19652 case CK_UncheckedDerivedToBase:
19653 case CK_Dynamic:
19654 case CK_ToUnion:
19655 case CK_ArrayToPointerDecay:
19656 case CK_FunctionToPointerDecay:
19657 case CK_NullToPointer:
19658 case CK_NullToMemberPointer:
19659 case CK_BaseToDerivedMemberPointer:
19660 case CK_DerivedToBaseMemberPointer:
19661 case CK_MemberPointerToBoolean:
19662 case CK_ReinterpretMemberPointer:
19663 case CK_ConstructorConversion:
19664 case CK_IntegralToPointer:
19665 case CK_PointerToIntegral:
19666 case CK_PointerToBoolean:
19667 case CK_ToVoid:
19668 case CK_VectorSplat:
19669 case CK_IntegralCast:
19670 case CK_BooleanToSignedIntegral:
19671 case CK_IntegralToBoolean:
19672 case CK_IntegralToFloating:
19673 case CK_FloatingToIntegral:
19674 case CK_FloatingToBoolean:
19675 case CK_FloatingCast:
19676 case CK_CPointerToObjCPointerCast:
19677 case CK_BlockPointerToObjCPointerCast:
19678 case CK_AnyPointerToBlockPointerCast:
19679 case CK_ObjCObjectLValueCast:
19680 case CK_FloatingComplexToReal:
19681 case CK_FloatingComplexToBoolean:
19682 case CK_IntegralComplexToReal:
19683 case CK_IntegralComplexToBoolean:
19684 case CK_ARCProduceObject:
19685 case CK_ARCConsumeObject:
19686 case CK_ARCReclaimReturnedObject:
19687 case CK_ARCExtendBlockObject:
19688 case CK_CopyAndAutoreleaseBlockObject:
19689 case CK_BuiltinFnToFnPtr:
19690 case CK_ZeroToOCLOpaqueType:
19691 case CK_NonAtomicToAtomic:
19692 case CK_AddressSpaceConversion:
19693 case CK_IntToOCLSampler:
19694 case CK_FloatingToFixedPoint:
19695 case CK_FixedPointToFloating:
19696 case CK_FixedPointCast:
19697 case CK_FixedPointToBoolean:
19698 case CK_FixedPointToIntegral:
19699 case CK_IntegralToFixedPoint:
19700 case CK_MatrixCast:
19701 case CK_HLSLVectorTruncation:
19702 case CK_HLSLMatrixTruncation:
19703 case CK_HLSLElementwiseCast:
19704 case CK_HLSLAggregateSplatCast:
19705 llvm_unreachable("invalid cast kind for complex value");
19706
19707 case CK_LValueToRValue:
19708 case CK_AtomicToNonAtomic:
19709 case CK_NoOp:
19710 case CK_LValueToRValueBitCast:
19711 case CK_HLSLArrayRValue:
19712 return ExprEvaluatorBaseTy::VisitCastExpr(E);
19713
19714 case CK_Dependent:
19715 case CK_LValueBitCast:
19716 case CK_UserDefinedConversion:
19717 return Error(E);
19718
19719 case CK_FloatingRealToComplex: {
19720 APFloat &Real = Result.FloatReal;
19721 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
19722 return false;
19723
19724 Result.makeComplexFloat();
19725 Result.FloatImag = APFloat(Real.getSemantics());
19726 return true;
19727 }
19728
19729 case CK_FloatingComplexCast: {
19730 if (!Visit(E->getSubExpr()))
19731 return false;
19732
19733 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
19734 QualType From
19735 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
19736
19737 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
19738 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
19739 }
19740
19741 case CK_FloatingComplexToIntegralComplex: {
19742 if (!Visit(E->getSubExpr()))
19743 return false;
19744
19745 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
19746 QualType From
19747 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
19748 Result.makeComplexInt();
19749 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
19750 To, Result.IntReal) &&
19751 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
19752 To, Result.IntImag);
19753 }
19754
19755 case CK_IntegralRealToComplex: {
19756 APSInt &Real = Result.IntReal;
19757 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
19758 return false;
19759
19760 Result.makeComplexInt();
19761 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
19762 return true;
19763 }
19764
19765 case CK_IntegralComplexCast: {
19766 if (!Visit(E->getSubExpr()))
19767 return false;
19768
19769 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
19770 QualType From
19771 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
19772
19773 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
19774 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
19775 return true;
19776 }
19777
19778 case CK_IntegralComplexToFloatingComplex: {
19779 if (!Visit(E->getSubExpr()))
19780 return false;
19781
19782 const FPOptions FPO = E->getFPFeaturesInEffect(
19783 Info.Ctx.getLangOpts());
19784 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
19785 QualType From
19786 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
19787 Result.makeComplexFloat();
19788 return HandleIntToFloatCast(Info, E, FPO, From, Result.IntReal,
19789 To, Result.FloatReal) &&
19790 HandleIntToFloatCast(Info, E, FPO, From, Result.IntImag,
19791 To, Result.FloatImag);
19792 }
19793 }
19794
19795 llvm_unreachable("unknown cast resulting in complex value");
19796}
19797
19798uint8_t GFNIMultiplicativeInverse(uint8_t Byte) {
19799 // Lookup Table for Multiplicative Inverse in GF(2^8)
19800 const uint8_t GFInv[256] = {
19801 0x00, 0x01, 0x8d, 0xf6, 0xcb, 0x52, 0x7b, 0xd1, 0xe8, 0x4f, 0x29, 0xc0,
19802 0xb0, 0xe1, 0xe5, 0xc7, 0x74, 0xb4, 0xaa, 0x4b, 0x99, 0x2b, 0x60, 0x5f,
19803 0x58, 0x3f, 0xfd, 0xcc, 0xff, 0x40, 0xee, 0xb2, 0x3a, 0x6e, 0x5a, 0xf1,
19804 0x55, 0x4d, 0xa8, 0xc9, 0xc1, 0x0a, 0x98, 0x15, 0x30, 0x44, 0xa2, 0xc2,
19805 0x2c, 0x45, 0x92, 0x6c, 0xf3, 0x39, 0x66, 0x42, 0xf2, 0x35, 0x20, 0x6f,
19806 0x77, 0xbb, 0x59, 0x19, 0x1d, 0xfe, 0x37, 0x67, 0x2d, 0x31, 0xf5, 0x69,
19807 0xa7, 0x64, 0xab, 0x13, 0x54, 0x25, 0xe9, 0x09, 0xed, 0x5c, 0x05, 0xca,
19808 0x4c, 0x24, 0x87, 0xbf, 0x18, 0x3e, 0x22, 0xf0, 0x51, 0xec, 0x61, 0x17,
19809 0x16, 0x5e, 0xaf, 0xd3, 0x49, 0xa6, 0x36, 0x43, 0xf4, 0x47, 0x91, 0xdf,
19810 0x33, 0x93, 0x21, 0x3b, 0x79, 0xb7, 0x97, 0x85, 0x10, 0xb5, 0xba, 0x3c,
19811 0xb6, 0x70, 0xd0, 0x06, 0xa1, 0xfa, 0x81, 0x82, 0x83, 0x7e, 0x7f, 0x80,
19812 0x96, 0x73, 0xbe, 0x56, 0x9b, 0x9e, 0x95, 0xd9, 0xf7, 0x02, 0xb9, 0xa4,
19813 0xde, 0x6a, 0x32, 0x6d, 0xd8, 0x8a, 0x84, 0x72, 0x2a, 0x14, 0x9f, 0x88,
19814 0xf9, 0xdc, 0x89, 0x9a, 0xfb, 0x7c, 0x2e, 0xc3, 0x8f, 0xb8, 0x65, 0x48,
19815 0x26, 0xc8, 0x12, 0x4a, 0xce, 0xe7, 0xd2, 0x62, 0x0c, 0xe0, 0x1f, 0xef,
19816 0x11, 0x75, 0x78, 0x71, 0xa5, 0x8e, 0x76, 0x3d, 0xbd, 0xbc, 0x86, 0x57,
19817 0x0b, 0x28, 0x2f, 0xa3, 0xda, 0xd4, 0xe4, 0x0f, 0xa9, 0x27, 0x53, 0x04,
19818 0x1b, 0xfc, 0xac, 0xe6, 0x7a, 0x07, 0xae, 0x63, 0xc5, 0xdb, 0xe2, 0xea,
19819 0x94, 0x8b, 0xc4, 0xd5, 0x9d, 0xf8, 0x90, 0x6b, 0xb1, 0x0d, 0xd6, 0xeb,
19820 0xc6, 0x0e, 0xcf, 0xad, 0x08, 0x4e, 0xd7, 0xe3, 0x5d, 0x50, 0x1e, 0xb3,
19821 0x5b, 0x23, 0x38, 0x34, 0x68, 0x46, 0x03, 0x8c, 0xdd, 0x9c, 0x7d, 0xa0,
19822 0xcd, 0x1a, 0x41, 0x1c};
19823
19824 return GFInv[Byte];
19825}
19826
19827uint8_t GFNIAffine(uint8_t XByte, const APInt &AQword, const APSInt &Imm,
19828 bool Inverse) {
19829 unsigned NumBitsInByte = 8;
19830 // Computing the affine transformation
19831 uint8_t RetByte = 0;
19832 for (uint32_t BitIdx = 0; BitIdx != NumBitsInByte; ++BitIdx) {
19833 uint8_t AByte =
19834 AQword.lshr((7 - static_cast<int32_t>(BitIdx)) * NumBitsInByte)
19835 .getLoBits(8)
19836 .getZExtValue();
19837 uint8_t Product;
19838 if (Inverse) {
19839 Product = AByte & GFNIMultiplicativeInverse(XByte);
19840 } else {
19841 Product = AByte & XByte;
19842 }
19843 uint8_t Parity = 0;
19844
19845 // Dot product in GF(2) uses XOR instead of addition
19846 for (unsigned PBitIdx = 0; PBitIdx != NumBitsInByte; ++PBitIdx) {
19847 Parity = Parity ^ ((Product >> PBitIdx) & 0x1);
19848 }
19849
19850 uint8_t Temp = Imm[BitIdx] ? 1 : 0;
19851 RetByte |= (Temp ^ Parity) << BitIdx;
19852 }
19853 return RetByte;
19854}
19855
19856uint8_t GFNIMul(uint8_t AByte, uint8_t BByte) {
19857 // Multiplying two polynomials of degree 7
19858 // Polynomial of degree 7
19859 // x^7 + x^6 + x^5 + x^4 + x^3 + x^2 + x + 1
19860 uint16_t TWord = 0;
19861 unsigned NumBitsInByte = 8;
19862 for (unsigned BitIdx = 0; BitIdx != NumBitsInByte; ++BitIdx) {
19863 if ((BByte >> BitIdx) & 0x1) {
19864 TWord = TWord ^ (AByte << BitIdx);
19865 }
19866 }
19867
19868 // When multiplying two polynomials of degree 7
19869 // results in a polynomial of degree 14
19870 // so the result has to be reduced to 7
19871 // Reduction polynomial is x^8 + x^4 + x^3 + x + 1 i.e. 0x11B
19872 for (int32_t BitIdx = 14; BitIdx > 7; --BitIdx) {
19873 if ((TWord >> BitIdx) & 0x1) {
19874 TWord = TWord ^ (0x11B << (BitIdx - 8));
19875 }
19876 }
19877 return (TWord & 0xFF);
19878}
19879
19880void HandleComplexComplexMul(APFloat A, APFloat B, APFloat C, APFloat D,
19881 APFloat &ResR, APFloat &ResI) {
19882 // This is an implementation of complex multiplication according to the
19883 // constraints laid out in C11 Annex G. The implementation uses the
19884 // following naming scheme:
19885 // (a + ib) * (c + id)
19886
19887 APFloat AC = A * C;
19888 APFloat BD = B * D;
19889 APFloat AD = A * D;
19890 APFloat BC = B * C;
19891 ResR = AC - BD;
19892 ResI = AD + BC;
19893 if (ResR.isNaN() && ResI.isNaN()) {
19894 bool Recalc = false;
19895 if (A.isInfinity() || B.isInfinity()) {
19896 A = APFloat::copySign(APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0),
19897 A);
19898 B = APFloat::copySign(APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0),
19899 B);
19900 if (C.isNaN())
19901 C = APFloat::copySign(APFloat(C.getSemantics()), C);
19902 if (D.isNaN())
19903 D = APFloat::copySign(APFloat(D.getSemantics()), D);
19904 Recalc = true;
19905 }
19906 if (C.isInfinity() || D.isInfinity()) {
19907 C = APFloat::copySign(APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0),
19908 C);
19909 D = APFloat::copySign(APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0),
19910 D);
19911 if (A.isNaN())
19912 A = APFloat::copySign(APFloat(A.getSemantics()), A);
19913 if (B.isNaN())
19914 B = APFloat::copySign(APFloat(B.getSemantics()), B);
19915 Recalc = true;
19916 }
19917 if (!Recalc && (AC.isInfinity() || BD.isInfinity() || AD.isInfinity() ||
19918 BC.isInfinity())) {
19919 if (A.isNaN())
19920 A = APFloat::copySign(APFloat(A.getSemantics()), A);
19921 if (B.isNaN())
19922 B = APFloat::copySign(APFloat(B.getSemantics()), B);
19923 if (C.isNaN())
19924 C = APFloat::copySign(APFloat(C.getSemantics()), C);
19925 if (D.isNaN())
19926 D = APFloat::copySign(APFloat(D.getSemantics()), D);
19927 Recalc = true;
19928 }
19929 if (Recalc) {
19930 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
19931 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
19932 }
19933 }
19934}
19935
19936void HandleComplexComplexDiv(APFloat A, APFloat B, APFloat C, APFloat D,
19937 APFloat &ResR, APFloat &ResI) {
19938 // This is an implementation of complex division according to the
19939 // constraints laid out in C11 Annex G. The implementation uses the
19940 // following naming scheme:
19941 // (a + ib) / (c + id)
19942
19943 int DenomLogB = 0;
19944 APFloat MaxCD = maxnum(abs(C), abs(D));
19945 if (MaxCD.isFinite()) {
19946 DenomLogB = ilogb(MaxCD);
19947 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
19948 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
19949 }
19950 APFloat Denom = C * C + D * D;
19951 ResR =
19952 scalbn((A * C + B * D) / Denom, -DenomLogB, APFloat::rmNearestTiesToEven);
19953 ResI =
19954 scalbn((B * C - A * D) / Denom, -DenomLogB, APFloat::rmNearestTiesToEven);
19955 if (ResR.isNaN() && ResI.isNaN()) {
19956 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
19957 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
19958 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
19959 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
19960 D.isFinite()) {
19961 A = APFloat::copySign(APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0),
19962 A);
19963 B = APFloat::copySign(APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0),
19964 B);
19965 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
19966 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
19967 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
19968 C = APFloat::copySign(APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0),
19969 C);
19970 D = APFloat::copySign(APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0),
19971 D);
19972 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
19973 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
19974 }
19975 }
19976}
19977
19979 // Normalize shift amount to [0, BitWidth) range to match runtime behavior
19980 APSInt NormAmt = Amount;
19981 unsigned BitWidth = Value.getBitWidth();
19982 unsigned AmtBitWidth = NormAmt.getBitWidth();
19983 if (BitWidth == 1) {
19984 // Rotating a 1-bit value is always a no-op
19985 NormAmt = APSInt(APInt(AmtBitWidth, 0), NormAmt.isUnsigned());
19986 } else if (BitWidth == 2) {
19987 // For 2-bit values: rotation amount is 0 or 1 based on
19988 // whether the amount is even or odd. We can't use srem here because
19989 // the divisor (2) would be misinterpreted as -2 in 2-bit signed arithmetic.
19990 NormAmt =
19991 APSInt(APInt(AmtBitWidth, NormAmt[0] ? 1 : 0), NormAmt.isUnsigned());
19992 } else {
19993 APInt Divisor;
19994 if (AmtBitWidth > BitWidth) {
19995 Divisor = llvm::APInt(AmtBitWidth, BitWidth);
19996 } else {
19997 Divisor = llvm::APInt(BitWidth, BitWidth);
19998 if (AmtBitWidth < BitWidth) {
19999 NormAmt = NormAmt.extend(BitWidth);
20000 }
20001 }
20002
20003 // Normalize to [0, BitWidth)
20004 if (NormAmt.isSigned()) {
20005 NormAmt = APSInt(NormAmt.srem(Divisor), /*isUnsigned=*/false);
20006 if (NormAmt.isNegative()) {
20007 APSInt SignedDivisor(Divisor, /*isUnsigned=*/false);
20008 NormAmt += SignedDivisor;
20009 }
20010 } else {
20011 NormAmt = APSInt(NormAmt.urem(Divisor), /*isUnsigned=*/true);
20012 }
20013 }
20014
20015 return NormAmt;
20016}
20017
20018bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
20019 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
20020 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
20021
20022 // Track whether the LHS or RHS is real at the type system level. When this is
20023 // the case we can simplify our evaluation strategy.
20024 bool LHSReal = false, RHSReal = false;
20025
20026 bool LHSOK;
20027 if (E->getLHS()->getType()->isRealFloatingType()) {
20028 LHSReal = true;
20029 APFloat &Real = Result.FloatReal;
20030 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
20031 if (LHSOK) {
20032 Result.makeComplexFloat();
20033 Result.FloatImag = APFloat(Real.getSemantics());
20034 }
20035 } else {
20036 LHSOK = Visit(E->getLHS());
20037 }
20038 if (!LHSOK && !Info.noteFailure())
20039 return false;
20040
20041 ComplexValue RHS;
20042 if (E->getRHS()->getType()->isRealFloatingType()) {
20043 RHSReal = true;
20044 APFloat &Real = RHS.FloatReal;
20045 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
20046 return false;
20047 RHS.makeComplexFloat();
20048 RHS.FloatImag = APFloat(Real.getSemantics());
20049 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
20050 return false;
20051
20052 assert(!(LHSReal && RHSReal) &&
20053 "Cannot have both operands of a complex operation be real.");
20054 switch (E->getOpcode()) {
20055 default: return Error(E);
20056 case BO_Add:
20057 if (Result.isComplexFloat()) {
20058 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
20059 APFloat::rmNearestTiesToEven);
20060 if (LHSReal)
20061 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
20062 else if (!RHSReal)
20063 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
20064 APFloat::rmNearestTiesToEven);
20065 } else {
20066 Result.getComplexIntReal() += RHS.getComplexIntReal();
20067 Result.getComplexIntImag() += RHS.getComplexIntImag();
20068 }
20069 break;
20070 case BO_Sub:
20071 if (Result.isComplexFloat()) {
20072 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
20073 APFloat::rmNearestTiesToEven);
20074 if (LHSReal) {
20075 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
20076 Result.getComplexFloatImag().changeSign();
20077 } else if (!RHSReal) {
20078 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
20079 APFloat::rmNearestTiesToEven);
20080 }
20081 } else {
20082 Result.getComplexIntReal() -= RHS.getComplexIntReal();
20083 Result.getComplexIntImag() -= RHS.getComplexIntImag();
20084 }
20085 break;
20086 case BO_Mul:
20087 if (Result.isComplexFloat()) {
20088 // This is an implementation of complex multiplication according to the
20089 // constraints laid out in C11 Annex G. The implementation uses the
20090 // following naming scheme:
20091 // (a + ib) * (c + id)
20092 ComplexValue LHS = Result;
20093 APFloat &A = LHS.getComplexFloatReal();
20094 APFloat &B = LHS.getComplexFloatImag();
20095 APFloat &C = RHS.getComplexFloatReal();
20096 APFloat &D = RHS.getComplexFloatImag();
20097 APFloat &ResR = Result.getComplexFloatReal();
20098 APFloat &ResI = Result.getComplexFloatImag();
20099 if (LHSReal) {
20100 assert(!RHSReal && "Cannot have two real operands for a complex op!");
20101 ResR = A;
20102 ResI = A;
20103 // ResR = A * C;
20104 // ResI = A * D;
20105 if (!handleFloatFloatBinOp(Info, E, ResR, BO_Mul, C) ||
20106 !handleFloatFloatBinOp(Info, E, ResI, BO_Mul, D))
20107 return false;
20108 } else if (RHSReal) {
20109 // ResR = C * A;
20110 // ResI = C * B;
20111 ResR = C;
20112 ResI = C;
20113 if (!handleFloatFloatBinOp(Info, E, ResR, BO_Mul, A) ||
20114 !handleFloatFloatBinOp(Info, E, ResI, BO_Mul, B))
20115 return false;
20116 } else {
20117 HandleComplexComplexMul(A, B, C, D, ResR, ResI);
20118 }
20119 } else {
20120 ComplexValue LHS = Result;
20121 Result.getComplexIntReal() =
20122 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
20123 LHS.getComplexIntImag() * RHS.getComplexIntImag());
20124 Result.getComplexIntImag() =
20125 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
20126 LHS.getComplexIntImag() * RHS.getComplexIntReal());
20127 }
20128 break;
20129 case BO_Div:
20130 if (Result.isComplexFloat()) {
20131 // This is an implementation of complex division according to the
20132 // constraints laid out in C11 Annex G. The implementation uses the
20133 // following naming scheme:
20134 // (a + ib) / (c + id)
20135 ComplexValue LHS = Result;
20136 APFloat &A = LHS.getComplexFloatReal();
20137 APFloat &B = LHS.getComplexFloatImag();
20138 APFloat &C = RHS.getComplexFloatReal();
20139 APFloat &D = RHS.getComplexFloatImag();
20140 APFloat &ResR = Result.getComplexFloatReal();
20141 APFloat &ResI = Result.getComplexFloatImag();
20142 if (RHSReal) {
20143 ResR = A;
20144 ResI = B;
20145 // ResR = A / C;
20146 // ResI = B / C;
20147 if (!handleFloatFloatBinOp(Info, E, ResR, BO_Div, C) ||
20148 !handleFloatFloatBinOp(Info, E, ResI, BO_Div, C))
20149 return false;
20150 } else {
20151 if (LHSReal) {
20152 // No real optimizations we can do here, stub out with zero.
20153 B = APFloat::getZero(A.getSemantics());
20154 }
20155 HandleComplexComplexDiv(A, B, C, D, ResR, ResI);
20156 }
20157 } else {
20158 ComplexValue LHS = Result;
20159 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
20160 RHS.getComplexIntImag() * RHS.getComplexIntImag();
20161 if (Den.isZero())
20162 return Error(E, diag::note_expr_divide_by_zero);
20163
20164 Result.getComplexIntReal() =
20165 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
20166 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
20167 Result.getComplexIntImag() =
20168 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
20169 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
20170 }
20171 break;
20172 }
20173
20174 return true;
20175}
20176
20177bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
20178 // Get the operand value into 'Result'.
20179 if (!Visit(E->getSubExpr()))
20180 return false;
20181
20182 switch (E->getOpcode()) {
20183 default:
20184 return Error(E);
20185 case UO_Extension:
20186 return true;
20187 case UO_Plus:
20188 // The result is always just the subexpr.
20189 return true;
20190 case UO_Minus:
20191 if (Result.isComplexFloat()) {
20192 Result.getComplexFloatReal().changeSign();
20193 Result.getComplexFloatImag().changeSign();
20194 }
20195 else {
20196 Result.getComplexIntReal() = -Result.getComplexIntReal();
20197 Result.getComplexIntImag() = -Result.getComplexIntImag();
20198 }
20199 return true;
20200 case UO_Not:
20201 if (Result.isComplexFloat())
20202 Result.getComplexFloatImag().changeSign();
20203 else
20204 Result.getComplexIntImag() = -Result.getComplexIntImag();
20205 return true;
20206 }
20207}
20208
20209bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
20210 if (E->getNumInits() == 2) {
20211 if (E->getType()->isComplexType()) {
20212 Result.makeComplexFloat();
20213 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
20214 return false;
20215 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
20216 return false;
20217 } else {
20218 Result.makeComplexInt();
20219 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
20220 return false;
20221 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
20222 return false;
20223 }
20224 return true;
20225 }
20226 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
20227}
20228
20229bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) {
20230 if (!IsConstantEvaluatedBuiltinCall(E))
20231 return ExprEvaluatorBaseTy::VisitCallExpr(E);
20232
20233 switch (E->getBuiltinCallee()) {
20234 case Builtin::BI__builtin_complex:
20235 Result.makeComplexFloat();
20236 if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info))
20237 return false;
20238 if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info))
20239 return false;
20240 return true;
20241
20242 default:
20243 return false;
20244 }
20245}
20246
20247//===----------------------------------------------------------------------===//
20248// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
20249// implicit conversion.
20250//===----------------------------------------------------------------------===//
20251
20252namespace {
20253class AtomicExprEvaluator :
20254 public ExprEvaluatorBase<AtomicExprEvaluator> {
20255 const LValue *This;
20256 APValue &Result;
20257public:
20258 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
20259 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
20260
20261 bool Success(const APValue &V, const Expr *E) {
20262 Result = V;
20263 return true;
20264 }
20265
20266 bool ZeroInitialization(const Expr *E) {
20267 ImplicitValueInitExpr VIE(
20268 E->getType()->castAs<AtomicType>()->getValueType());
20269 // For atomic-qualified class (and array) types in C++, initialize the
20270 // _Atomic-wrapped subobject directly, in-place.
20271 return This ? EvaluateInPlace(Result, Info, *This, &VIE)
20272 : Evaluate(Result, Info, &VIE);
20273 }
20274
20275 bool VisitCastExpr(const CastExpr *E) {
20276 switch (E->getCastKind()) {
20277 default:
20278 return ExprEvaluatorBaseTy::VisitCastExpr(E);
20279 case CK_NullToPointer:
20280 VisitIgnoredValue(E->getSubExpr());
20281 return ZeroInitialization(E);
20282 case CK_NonAtomicToAtomic:
20283 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
20284 : Evaluate(Result, Info, E->getSubExpr());
20285 }
20286 }
20287};
20288} // end anonymous namespace
20289
20290static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
20291 EvalInfo &Info) {
20292 assert(!E->isValueDependent());
20293 assert(E->isPRValue() && E->getType()->isAtomicType());
20294 return AtomicExprEvaluator(Info, This, Result).Visit(E);
20295}
20296
20297//===----------------------------------------------------------------------===//
20298// Void expression evaluation, primarily for a cast to void on the LHS of a
20299// comma operator
20300//===----------------------------------------------------------------------===//
20301
20302namespace {
20303class VoidExprEvaluator
20304 : public ExprEvaluatorBase<VoidExprEvaluator> {
20305public:
20306 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
20307
20308 bool Success(const APValue &V, const Expr *e) { return true; }
20309
20310 bool ZeroInitialization(const Expr *E) { return true; }
20311
20312 bool VisitCastExpr(const CastExpr *E) {
20313 switch (E->getCastKind()) {
20314 default:
20315 return ExprEvaluatorBaseTy::VisitCastExpr(E);
20316 case CK_ToVoid:
20317 VisitIgnoredValue(E->getSubExpr());
20318 return true;
20319 }
20320 }
20321
20322 bool VisitCallExpr(const CallExpr *E) {
20323 if (!IsConstantEvaluatedBuiltinCall(E))
20324 return ExprEvaluatorBaseTy::VisitCallExpr(E);
20325
20326 switch (E->getBuiltinCallee()) {
20327 case Builtin::BI__assume:
20328 case Builtin::BI__builtin_assume:
20329 // The argument is not evaluated!
20330 return true;
20331
20332 case Builtin::BI__builtin_operator_delete:
20333 return HandleOperatorDeleteCall(Info, E);
20334
20335 default:
20336 return false;
20337 }
20338 }
20339
20340 bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
20341};
20342} // end anonymous namespace
20343
20344bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
20345 // We cannot speculatively evaluate a delete expression.
20346 if (Info.SpeculativeEvaluationDepth)
20347 return false;
20348
20349 FunctionDecl *OperatorDelete = E->getOperatorDelete();
20350 if (!OperatorDelete
20351 ->isUsableAsGlobalAllocationFunctionInConstantEvaluation()) {
20352 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
20353 << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;
20354 return false;
20355 }
20356
20357 const Expr *Arg = E->getArgument();
20358
20359 LValue Pointer;
20360 if (!EvaluatePointer(Arg, Pointer, Info))
20361 return false;
20362 if (Pointer.Designator.Invalid)
20363 return false;
20364
20365 // Deleting a null pointer has no effect.
20366 if (Pointer.isNullPointer()) {
20367 // This is the only case where we need to produce an extension warning:
20368 // the only other way we can succeed is if we find a dynamic allocation,
20369 // and we will have warned when we allocated it in that case.
20370 if (!Info.getLangOpts().CPlusPlus20)
20371 Info.CCEDiag(E, diag::note_constexpr_new);
20372 return true;
20373 }
20374
20375 std::optional<DynAlloc *> Alloc = CheckDeleteKind(
20376 Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New);
20377 if (!Alloc)
20378 return false;
20379 QualType AllocType = Pointer.Base.getDynamicAllocType();
20380
20381 // For the non-array case, the designator must be empty if the static type
20382 // does not have a virtual destructor.
20383 if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 &&
20385 Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor)
20386 << Arg->getType()->getPointeeType() << AllocType;
20387 return false;
20388 }
20389
20390 // For a class type with a virtual destructor, the selected operator delete
20391 // is the one looked up when building the destructor.
20392 if (!E->isArrayForm() && !E->isGlobalDelete()) {
20393 const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType);
20394 if (VirtualDelete &&
20395 !VirtualDelete
20396 ->isUsableAsGlobalAllocationFunctionInConstantEvaluation()) {
20397 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
20398 << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete;
20399 return false;
20400 }
20401 }
20402
20403 if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(),
20404 (*Alloc)->Value, AllocType))
20405 return false;
20406
20407 if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) {
20408 // The element was already erased. This means the destructor call also
20409 // deleted the object.
20410 // FIXME: This probably results in undefined behavior before we get this
20411 // far, and should be diagnosed elsewhere first.
20412 Info.FFDiag(E, diag::note_constexpr_double_delete);
20413 return false;
20414 }
20415
20416 return true;
20417}
20418
20419static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
20420 assert(!E->isValueDependent());
20421 assert(E->isPRValue() && E->getType()->isVoidType());
20422 return VoidExprEvaluator(Info).Visit(E);
20423}
20424
20425//===----------------------------------------------------------------------===//
20426// Top level Expr::EvaluateAsRValue method.
20427//===----------------------------------------------------------------------===//
20428
20429static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
20430 assert(!E->isValueDependent());
20431 // In C, function designators are not lvalues, but we evaluate them as if they
20432 // are.
20433 QualType T = E->getType();
20434 if (E->isGLValue() || T->isFunctionType()) {
20435 LValue LV;
20436 if (!EvaluateLValue(E, LV, Info))
20437 return false;
20438 LV.moveInto(Result);
20439 } else if (T->isVectorType()) {
20440 if (!EvaluateVector(E, Result, Info))
20441 return false;
20442 } else if (T->isIntegralOrEnumerationType()) {
20443 if (!IntExprEvaluator(Info, Result).Visit(E))
20444 return false;
20445 } else if (T->hasPointerRepresentation()) {
20446 LValue LV;
20447 if (!EvaluatePointer(E, LV, Info))
20448 return false;
20449 LV.moveInto(Result);
20450 } else if (T->isRealFloatingType()) {
20451 llvm::APFloat F(0.0);
20452 if (!EvaluateFloat(E, F, Info))
20453 return false;
20454 Result = APValue(F);
20455 } else if (T->isAnyComplexType()) {
20456 ComplexValue C;
20457 if (!EvaluateComplex(E, C, Info))
20458 return false;
20459 C.moveInto(Result);
20460 } else if (T->isFixedPointType()) {
20461 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
20462 } else if (T->isMemberPointerType()) {
20463 MemberPtr P;
20464 if (!EvaluateMemberPointer(E, P, Info))
20465 return false;
20466 P.moveInto(Result);
20467 return true;
20468 } else if (T->isArrayType()) {
20469 LValue LV;
20470 APValue &Value =
20471 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
20472 if (!EvaluateArray(E, LV, Value, Info))
20473 return false;
20474 Result = Value;
20475 } else if (T->isRecordType()) {
20476 LValue LV;
20477 APValue &Value =
20478 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
20479 if (!EvaluateRecord(E, LV, Value, Info))
20480 return false;
20481 Result = Value;
20482 } else if (T->isVoidType()) {
20483 if (!Info.getLangOpts().CPlusPlus11)
20484 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
20485 << E->getType();
20486 if (!EvaluateVoid(E, Info))
20487 return false;
20488 } else if (T->isAtomicType()) {
20489 QualType Unqual = T.getAtomicUnqualifiedType();
20490 if (Unqual->isArrayType() || Unqual->isRecordType()) {
20491 LValue LV;
20492 APValue &Value = Info.CurrentCall->createTemporary(
20493 E, Unqual, ScopeKind::FullExpression, LV);
20494 if (!EvaluateAtomic(E, &LV, Value, Info))
20495 return false;
20496 Result = Value;
20497 } else {
20498 if (!EvaluateAtomic(E, nullptr, Result, Info))
20499 return false;
20500 }
20501 } else if (Info.getLangOpts().CPlusPlus11) {
20502 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
20503 return false;
20504 } else {
20505 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
20506 return false;
20507 }
20508
20509 return true;
20510}
20511
20512/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
20513/// cases, the in-place evaluation is essential, since later initializers for
20514/// an object can indirectly refer to subobjects which were initialized earlier.
20515static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
20516 const Expr *E, bool AllowNonLiteralTypes) {
20517 assert(!E->isValueDependent());
20518
20519 // Normally expressions passed to EvaluateInPlace have a type, but not when
20520 // a VarDecl initializer is evaluated before the untyped ParenListExpr is
20521 // replaced with a CXXConstructExpr. This can happen in LLDB.
20522 if (E->getType().isNull())
20523 return false;
20524
20525 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
20526 return false;
20527
20528 if (E->isPRValue()) {
20529 // Evaluate arrays and record types in-place, so that later initializers can
20530 // refer to earlier-initialized members of the object.
20531 QualType T = E->getType();
20532 if (T->isArrayType())
20533 return EvaluateArray(E, This, Result, Info);
20534 else if (T->isRecordType())
20535 return EvaluateRecord(E, This, Result, Info);
20536 else if (T->isAtomicType()) {
20537 QualType Unqual = T.getAtomicUnqualifiedType();
20538 if (Unqual->isArrayType() || Unqual->isRecordType())
20539 return EvaluateAtomic(E, &This, Result, Info);
20540 }
20541 }
20542
20543 // For any other type, in-place evaluation is unimportant.
20544 return Evaluate(Result, Info, E);
20545}
20546
20547/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
20548/// lvalue-to-rvalue cast if it is an lvalue.
20549static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
20550 assert(!E->isValueDependent());
20551
20552 if (E->getType().isNull())
20553 return false;
20554
20555 if (!CheckLiteralType(Info, E))
20556 return false;
20557
20558 if (Info.EnableNewConstInterp) {
20559 if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result))
20560 return false;
20561 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
20562 ConstantExprKind::Normal);
20563 }
20564
20565 if (!::Evaluate(Result, Info, E))
20566 return false;
20567
20568 // Implicit lvalue-to-rvalue cast.
20569 if (E->isGLValue()) {
20570 LValue LV;
20571 LV.setFrom(Info.Ctx, Result);
20572 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
20573 return false;
20574 }
20575
20576 // Check this core constant expression is a constant expression.
20577 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
20578 ConstantExprKind::Normal) &&
20579 CheckMemoryLeaks(Info);
20580}
20581
20582static bool FastEvaluateAsRValue(const Expr *Exp, APValue &Result,
20583 const ASTContext &Ctx, bool &IsConst) {
20584 // Fast-path evaluations of integer literals, since we sometimes see files
20585 // containing vast quantities of these.
20586 if (const auto *L = dyn_cast<IntegerLiteral>(Exp)) {
20587 Result =
20588 APValue(APSInt(L->getValue(), L->getType()->isUnsignedIntegerType()));
20589 IsConst = true;
20590 return true;
20591 }
20592
20593 if (const auto *L = dyn_cast<CXXBoolLiteralExpr>(Exp)) {
20594 Result = APValue(APSInt(APInt(1, L->getValue())));
20595 IsConst = true;
20596 return true;
20597 }
20598
20599 if (const auto *FL = dyn_cast<FloatingLiteral>(Exp)) {
20600 Result = APValue(FL->getValue());
20601 IsConst = true;
20602 return true;
20603 }
20604
20605 if (const auto *L = dyn_cast<CharacterLiteral>(Exp)) {
20606 Result = APValue(Ctx.MakeIntValue(L->getValue(), L->getType()));
20607 IsConst = true;
20608 return true;
20609 }
20610
20611 if (const auto *CE = dyn_cast<ConstantExpr>(Exp)) {
20612 if (CE->hasAPValueResult()) {
20613 APValue APV = CE->getAPValueResult();
20614 if (!APV.isLValue()) {
20615 Result = std::move(APV);
20616 IsConst = true;
20617 return true;
20618 }
20619 }
20620
20621 // The SubExpr is usually just an IntegerLiteral.
20622 return FastEvaluateAsRValue(CE->getSubExpr(), Result, Ctx, IsConst);
20623 }
20624
20625 // This case should be rare, but we need to check it before we check on
20626 // the type below.
20627 if (Exp->getType().isNull()) {
20628 IsConst = false;
20629 return true;
20630 }
20631
20632 return false;
20633}
20634
20637 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
20638 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
20639}
20640
20641static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
20642 const ASTContext &Ctx, EvalInfo &Info) {
20643 assert(!E->isValueDependent());
20644 bool IsConst;
20645 if (FastEvaluateAsRValue(E, Result.Val, Ctx, IsConst))
20646 return IsConst;
20647
20648 return EvaluateAsRValue(Info, E, Result.Val);
20649}
20650
20652 const ASTContext &Ctx,
20653 Expr::SideEffectsKind AllowSideEffects,
20654 EvalInfo &Info) {
20655 assert(!E->isValueDependent());
20657 return false;
20658
20659 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
20660 !ExprResult.Val.isInt() ||
20661 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
20662 return false;
20663
20664 return true;
20665}
20666
20668 const ASTContext &Ctx,
20669 Expr::SideEffectsKind AllowSideEffects,
20670 EvalInfo &Info) {
20671 assert(!E->isValueDependent());
20672 if (!E->getType()->isFixedPointType())
20673 return false;
20674
20675 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
20676 return false;
20677
20678 if (!ExprResult.Val.isFixedPoint() ||
20679 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
20680 return false;
20681
20682 return true;
20683}
20684
20685/// EvaluateAsRValue - Return true if this is a constant which we can fold using
20686/// any crazy technique (that has nothing to do with language standards) that
20687/// we want to. If this function returns true, it returns the folded constant
20688/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
20689/// will be applied to the result.
20691 bool InConstantContext) const {
20692 assert(!isValueDependent() &&
20693 "Expression evaluator can't be called on a dependent expression.");
20694 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsRValue");
20695 EvalInfo Info(Ctx, Result, EvaluationMode::IgnoreSideEffects);
20696 Info.InConstantContext = InConstantContext;
20697 return ::EvaluateAsRValue(this, Result, Ctx, Info);
20698}
20699
20701 bool InConstantContext) const {
20702 assert(!isValueDependent() &&
20703 "Expression evaluator can't be called on a dependent expression.");
20704 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsBooleanCondition");
20705 EvalResult Scratch;
20706 return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
20707 HandleConversionToBool(Scratch.Val, Result);
20708}
20709
20711 SideEffectsKind AllowSideEffects,
20712 bool InConstantContext) const {
20713 assert(!isValueDependent() &&
20714 "Expression evaluator can't be called on a dependent expression.");
20715 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsInt");
20716 EvalInfo Info(Ctx, Result, EvaluationMode::IgnoreSideEffects);
20717 Info.InConstantContext = InConstantContext;
20718 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
20719}
20720
20722 SideEffectsKind AllowSideEffects,
20723 bool InConstantContext) const {
20724 assert(!isValueDependent() &&
20725 "Expression evaluator can't be called on a dependent expression.");
20726 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFixedPoint");
20727 EvalInfo Info(Ctx, Result, EvaluationMode::IgnoreSideEffects);
20728 Info.InConstantContext = InConstantContext;
20729 return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
20730}
20731
20732bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
20733 SideEffectsKind AllowSideEffects,
20734 bool InConstantContext) const {
20735 assert(!isValueDependent() &&
20736 "Expression evaluator can't be called on a dependent expression.");
20737
20738 if (!getType()->isRealFloatingType())
20739 return false;
20740
20741 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFloat");
20743 if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
20744 !ExprResult.Val.isFloat() ||
20745 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
20746 return false;
20747
20748 Result = ExprResult.Val.getFloat();
20749 return true;
20750}
20751
20753 bool InConstantContext) const {
20754 assert(!isValueDependent() &&
20755 "Expression evaluator can't be called on a dependent expression.");
20756
20757 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsLValue");
20758 EvalInfo Info(Ctx, Result, EvaluationMode::ConstantFold);
20759 Info.InConstantContext = InConstantContext;
20760 LValue LV;
20761 CheckedTemporaries CheckedTemps;
20762
20763 if (Info.EnableNewConstInterp) {
20764 if (!Info.Ctx.getInterpContext().evaluate(Info, this, Result.Val,
20765 ConstantExprKind::Normal))
20766 return false;
20767
20768 LV.setFrom(Ctx, Result.Val);
20770 Info, getExprLoc(), Ctx.getLValueReferenceType(getType()), LV,
20771 ConstantExprKind::Normal, CheckedTemps);
20772 }
20773
20774 if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() ||
20775 Result.HasSideEffects ||
20778 ConstantExprKind::Normal, CheckedTemps))
20779 return false;
20780
20781 LV.moveInto(Result.Val);
20782 return true;
20783}
20784
20786 APValue DestroyedValue, QualType Type,
20787 SourceLocation Loc, Expr::EvalStatus &EStatus,
20788 bool IsConstantDestruction) {
20789 EvalInfo Info(Ctx, EStatus,
20790 IsConstantDestruction ? EvaluationMode::ConstantExpression
20792 Info.setEvaluatingDecl(Base, DestroyedValue,
20793 EvalInfo::EvaluatingDeclKind::Dtor);
20794 Info.InConstantContext = IsConstantDestruction;
20795
20796 LValue LVal;
20797 LVal.set(Base);
20798
20799 if (!HandleDestruction(Info, Loc, Base, DestroyedValue, Type) ||
20800 EStatus.HasSideEffects)
20801 return false;
20802
20803 if (!Info.discardCleanups())
20804 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
20805
20806 return true;
20807}
20808
20810 ConstantExprKind Kind) const {
20811 assert(!isValueDependent() &&
20812 "Expression evaluator can't be called on a dependent expression.");
20813 bool IsConst;
20814 if (FastEvaluateAsRValue(this, Result.Val, Ctx, IsConst) &&
20815 Result.Val.hasValue())
20816 return true;
20817
20818 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsConstantExpr");
20820 EvalInfo Info(Ctx, Result, EM);
20821 Info.InConstantContext = true;
20822
20823 if (Info.EnableNewConstInterp) {
20824 if (!Info.Ctx.getInterpContext().evaluate(Info, this, Result.Val, Kind))
20825 return false;
20826 return CheckConstantExpression(Info, getExprLoc(),
20827 getStorageType(Ctx, this), Result.Val, Kind);
20828 }
20829
20830 // The type of the object we're initializing is 'const T' for a class NTTP.
20831 QualType T = getType();
20832 if (Kind == ConstantExprKind::ClassTemplateArgument)
20833 T.addConst();
20834
20835 // If we're evaluating a prvalue, fake up a MaterializeTemporaryExpr to
20836 // represent the result of the evaluation. CheckConstantExpression ensures
20837 // this doesn't escape.
20838 MaterializeTemporaryExpr BaseMTE(T, const_cast<Expr*>(this), true);
20839 APValue::LValueBase Base(&BaseMTE);
20840 Info.setEvaluatingDecl(Base, Result.Val);
20841
20842 LValue LVal;
20843 LVal.set(Base);
20844 // C++23 [intro.execution]/p5
20845 // A full-expression is [...] a constant-expression
20846 // So we need to make sure temporary objects are destroyed after having
20847 // evaluating the expression (per C++23 [class.temporary]/p4).
20848 FullExpressionRAII Scope(Info);
20849 if (!::EvaluateInPlace(Result.Val, Info, LVal, this) ||
20850 Result.HasSideEffects || !Scope.destroy())
20851 return false;
20852
20853 if (!Info.discardCleanups())
20854 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
20855
20856 if (!CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this),
20857 Result.Val, Kind))
20858 return false;
20859 if (!CheckMemoryLeaks(Info))
20860 return false;
20861
20862 // If this is a class template argument, it's required to have constant
20863 // destruction too.
20864 if (Kind == ConstantExprKind::ClassTemplateArgument &&
20866 true) ||
20867 Result.HasSideEffects)) {
20868 // FIXME: Prefix a note to indicate that the problem is lack of constant
20869 // destruction.
20870 return false;
20871 }
20872
20873 return true;
20874}
20875
20877 const VarDecl *VD,
20879 bool IsConstantInitialization) const {
20880 assert(!isValueDependent() &&
20881 "Expression evaluator can't be called on a dependent expression.");
20882 assert(VD && "Need a valid VarDecl");
20883
20884 llvm::TimeTraceScope TimeScope("EvaluateAsInitializer", [&] {
20885 std::string Name;
20886 llvm::raw_string_ostream OS(Name);
20887 VD->printQualifiedName(OS);
20888 return Name;
20889 });
20890
20891 Expr::EvalStatus EStatus;
20892 EStatus.Diag = &Notes;
20893
20894 EvalInfo Info(Ctx, EStatus,
20895 (IsConstantInitialization &&
20896 (Ctx.getLangOpts().CPlusPlus || Ctx.getLangOpts().C23))
20899 Info.setEvaluatingDecl(VD, Value);
20900 Info.InConstantContext = IsConstantInitialization;
20901
20902 SourceLocation DeclLoc = VD->getLocation();
20903 QualType DeclTy = VD->getType();
20904
20905 if (Info.EnableNewConstInterp) {
20906 auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext();
20907 if (!InterpCtx.evaluateAsInitializer(Info, VD, this, Value))
20908 return false;
20909
20910 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value,
20911 ConstantExprKind::Normal);
20912 } else {
20913 LValue LVal;
20914 LVal.set(VD);
20915
20916 {
20917 // C++23 [intro.execution]/p5
20918 // A full-expression is ... an init-declarator ([dcl.decl]) or a
20919 // mem-initializer.
20920 // So we need to make sure temporary objects are destroyed after having
20921 // evaluated the expression (per C++23 [class.temporary]/p4).
20922 //
20923 // FIXME: Otherwise this may break test/Modules/pr68702.cpp because the
20924 // serialization code calls ParmVarDecl::getDefaultArg() which strips the
20925 // outermost FullExpr, such as ExprWithCleanups.
20926 FullExpressionRAII Scope(Info);
20927 if (!EvaluateInPlace(Value, Info, LVal, this,
20928 /*AllowNonLiteralTypes=*/true) ||
20929 EStatus.HasSideEffects)
20930 return false;
20931 }
20932
20933 // At this point, any lifetime-extended temporaries are completely
20934 // initialized.
20935 Info.performLifetimeExtension();
20936
20937 if (!Info.discardCleanups())
20938 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
20939 }
20940
20941 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value,
20942 ConstantExprKind::Normal) &&
20943 CheckMemoryLeaks(Info);
20944}
20945
20948 Expr::EvalStatus EStatus;
20949 EStatus.Diag = &Notes;
20950
20951 // Only treat the destruction as constant destruction if we formally have
20952 // constant initialization (or are usable in a constant expression).
20953 bool IsConstantDestruction = hasConstantInitialization();
20954
20955 // Make a copy of the value for the destructor to mutate, if we know it.
20956 // Otherwise, treat the value as default-initialized; if the destructor works
20957 // anyway, then the destruction is constant (and must be essentially empty).
20958 APValue DestroyedValue;
20959 if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent())
20960 DestroyedValue = *getEvaluatedValue();
20961 else if (!handleDefaultInitValue(getType(), DestroyedValue))
20962 return false;
20963
20964 if (!EvaluateDestruction(getASTContext(), this, std::move(DestroyedValue),
20965 getType(), getLocation(), EStatus,
20966 IsConstantDestruction) ||
20967 EStatus.HasSideEffects)
20968 return false;
20969
20970 ensureEvaluatedStmt()->HasConstantDestruction = true;
20971 return true;
20972}
20973
20974/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
20975/// constant folded, but discard the result.
20977 assert(!isValueDependent() &&
20978 "Expression evaluator can't be called on a dependent expression.");
20979
20981 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
20983}
20984
20985APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
20986 assert(!isValueDependent() &&
20987 "Expression evaluator can't be called on a dependent expression.");
20988
20989 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstInt");
20990 EvalResult EVResult;
20991 EvalInfo Info(Ctx, EVResult, EvaluationMode::IgnoreSideEffects);
20992 Info.InConstantContext = true;
20993
20994 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
20995 (void)Result;
20996 assert(Result && "Could not evaluate expression");
20997 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
20998
20999 return EVResult.Val.getInt();
21000}
21001
21004 assert(!isValueDependent() &&
21005 "Expression evaluator can't be called on a dependent expression.");
21006
21007 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstIntCheckOverflow");
21008 EvalResult EVResult;
21009 EVResult.Diag = Diag;
21010 EvalInfo Info(Ctx, EVResult, EvaluationMode::IgnoreSideEffects);
21011 Info.InConstantContext = true;
21012 Info.CheckingForUndefinedBehavior = true;
21013
21014 bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
21015 (void)Result;
21016 assert(Result && "Could not evaluate expression");
21017 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
21018
21019 return EVResult.Val.getInt();
21020}
21021
21023 assert(!isValueDependent() &&
21024 "Expression evaluator can't be called on a dependent expression.");
21025
21026 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateForOverflow");
21027 bool IsConst;
21028 EvalResult EVResult;
21029 if (!FastEvaluateAsRValue(this, EVResult.Val, Ctx, IsConst)) {
21030 EvalInfo Info(Ctx, EVResult, EvaluationMode::IgnoreSideEffects);
21031 Info.CheckingForUndefinedBehavior = true;
21032 (void)::EvaluateAsRValue(Info, this, EVResult.Val);
21033 }
21034}
21035
21037 assert(Val.isLValue());
21038 return IsGlobalLValue(Val.getLValueBase());
21039}
21040
21041/// isIntegerConstantExpr - this recursive routine will test if an expression is
21042/// an integer constant expression.
21043
21044/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
21045/// comma, etc
21046
21047// CheckICE - This function does the fundamental ICE checking: the returned
21048// ICEDiag contains an ICEKind indicating whether the expression is an ICE.
21049//
21050// Note that to reduce code duplication, this helper does no evaluation
21051// itself; the caller checks whether the expression is evaluatable, and
21052// in the rare cases where CheckICE actually cares about the evaluated
21053// value, it calls into Evaluate.
21054
21055namespace {
21056
21057enum ICEKind {
21058 /// This expression is an ICE.
21059 IK_ICE,
21060 /// This expression is not an ICE, but if it isn't evaluated, it's
21061 /// a legal subexpression for an ICE. This return value is used to handle
21062 /// the comma operator in C99 mode, and non-constant subexpressions.
21063 IK_ICEIfUnevaluated,
21064 /// This expression is not an ICE, and is not a legal subexpression for one.
21065 IK_NotICE
21066};
21067
21068struct ICEDiag {
21069 ICEKind Kind;
21070 SourceLocation Loc;
21071
21072 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
21073};
21074
21075}
21076
21077static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
21078
21079static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
21080
21081static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
21082 Expr::EvalResult EVResult;
21083 Expr::EvalStatus Status;
21084 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantExpression);
21085
21086 Info.InConstantContext = true;
21087 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
21088 !EVResult.Val.isInt())
21089 return ICEDiag(IK_NotICE, E->getBeginLoc());
21090
21091 return NoDiag();
21092}
21093
21094static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
21095 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
21097 return ICEDiag(IK_NotICE, E->getBeginLoc());
21098
21099 switch (E->getStmtClass()) {
21100#define ABSTRACT_STMT(Node)
21101#define STMT(Node, Base) case Expr::Node##Class:
21102#define EXPR(Node, Base)
21103#include "clang/AST/StmtNodes.inc"
21104 case Expr::PredefinedExprClass:
21105 case Expr::FloatingLiteralClass:
21106 case Expr::ImaginaryLiteralClass:
21107 case Expr::StringLiteralClass:
21108 case Expr::ArraySubscriptExprClass:
21109 case Expr::MatrixSingleSubscriptExprClass:
21110 case Expr::MatrixSubscriptExprClass:
21111 case Expr::ArraySectionExprClass:
21112 case Expr::OMPArrayShapingExprClass:
21113 case Expr::OMPIteratorExprClass:
21114 case Expr::MemberExprClass:
21115 case Expr::CompoundAssignOperatorClass:
21116 case Expr::CompoundLiteralExprClass:
21117 case Expr::ExtVectorElementExprClass:
21118 case Expr::DesignatedInitExprClass:
21119 case Expr::ArrayInitLoopExprClass:
21120 case Expr::ArrayInitIndexExprClass:
21121 case Expr::NoInitExprClass:
21122 case Expr::DesignatedInitUpdateExprClass:
21123 case Expr::ImplicitValueInitExprClass:
21124 case Expr::ParenListExprClass:
21125 case Expr::VAArgExprClass:
21126 case Expr::AddrLabelExprClass:
21127 case Expr::StmtExprClass:
21128 case Expr::CXXMemberCallExprClass:
21129 case Expr::CUDAKernelCallExprClass:
21130 case Expr::CXXAddrspaceCastExprClass:
21131 case Expr::CXXDynamicCastExprClass:
21132 case Expr::CXXTypeidExprClass:
21133 case Expr::CXXUuidofExprClass:
21134 case Expr::MSPropertyRefExprClass:
21135 case Expr::MSPropertySubscriptExprClass:
21136 case Expr::CXXNullPtrLiteralExprClass:
21137 case Expr::UserDefinedLiteralClass:
21138 case Expr::CXXThisExprClass:
21139 case Expr::CXXThrowExprClass:
21140 case Expr::CXXNewExprClass:
21141 case Expr::CXXDeleteExprClass:
21142 case Expr::CXXPseudoDestructorExprClass:
21143 case Expr::UnresolvedLookupExprClass:
21144 case Expr::RecoveryExprClass:
21145 case Expr::DependentScopeDeclRefExprClass:
21146 case Expr::CXXConstructExprClass:
21147 case Expr::CXXInheritedCtorInitExprClass:
21148 case Expr::CXXStdInitializerListExprClass:
21149 case Expr::CXXBindTemporaryExprClass:
21150 case Expr::ExprWithCleanupsClass:
21151 case Expr::CXXTemporaryObjectExprClass:
21152 case Expr::CXXUnresolvedConstructExprClass:
21153 case Expr::CXXDependentScopeMemberExprClass:
21154 case Expr::UnresolvedMemberExprClass:
21155 case Expr::ObjCStringLiteralClass:
21156 case Expr::ObjCBoxedExprClass:
21157 case Expr::ObjCArrayLiteralClass:
21158 case Expr::ObjCDictionaryLiteralClass:
21159 case Expr::ObjCEncodeExprClass:
21160 case Expr::ObjCMessageExprClass:
21161 case Expr::ObjCSelectorExprClass:
21162 case Expr::ObjCProtocolExprClass:
21163 case Expr::ObjCIvarRefExprClass:
21164 case Expr::ObjCPropertyRefExprClass:
21165 case Expr::ObjCSubscriptRefExprClass:
21166 case Expr::ObjCIsaExprClass:
21167 case Expr::ObjCAvailabilityCheckExprClass:
21168 case Expr::ShuffleVectorExprClass:
21169 case Expr::ConvertVectorExprClass:
21170 case Expr::BlockExprClass:
21171 case Expr::NoStmtClass:
21172 case Expr::OpaqueValueExprClass:
21173 case Expr::PackExpansionExprClass:
21174 case Expr::SubstNonTypeTemplateParmPackExprClass:
21175 case Expr::FunctionParmPackExprClass:
21176 case Expr::AsTypeExprClass:
21177 case Expr::ObjCIndirectCopyRestoreExprClass:
21178 case Expr::MaterializeTemporaryExprClass:
21179 case Expr::PseudoObjectExprClass:
21180 case Expr::AtomicExprClass:
21181 case Expr::LambdaExprClass:
21182 case Expr::CXXFoldExprClass:
21183 case Expr::CoawaitExprClass:
21184 case Expr::DependentCoawaitExprClass:
21185 case Expr::CoyieldExprClass:
21186 case Expr::SYCLUniqueStableNameExprClass:
21187 case Expr::CXXParenListInitExprClass:
21188 case Expr::HLSLOutArgExprClass:
21189 return ICEDiag(IK_NotICE, E->getBeginLoc());
21190
21191 case Expr::InitListExprClass: {
21192 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
21193 // form "T x = { a };" is equivalent to "T x = a;".
21194 // Unless we're initializing a reference, T is a scalar as it is known to be
21195 // of integral or enumeration type.
21196 if (E->isPRValue())
21197 if (cast<InitListExpr>(E)->getNumInits() == 1)
21198 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
21199 return ICEDiag(IK_NotICE, E->getBeginLoc());
21200 }
21201
21202 case Expr::SizeOfPackExprClass:
21203 case Expr::GNUNullExprClass:
21204 case Expr::SourceLocExprClass:
21205 case Expr::EmbedExprClass:
21206 case Expr::OpenACCAsteriskSizeExprClass:
21207 return NoDiag();
21208
21209 case Expr::PackIndexingExprClass:
21210 return CheckICE(cast<PackIndexingExpr>(E)->getSelectedExpr(), Ctx);
21211
21212 case Expr::SubstNonTypeTemplateParmExprClass:
21213 return
21214 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
21215
21216 case Expr::ConstantExprClass:
21217 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
21218
21219 case Expr::ParenExprClass:
21220 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
21221 case Expr::GenericSelectionExprClass:
21222 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
21223 case Expr::IntegerLiteralClass:
21224 case Expr::FixedPointLiteralClass:
21225 case Expr::CharacterLiteralClass:
21226 case Expr::ObjCBoolLiteralExprClass:
21227 case Expr::CXXBoolLiteralExprClass:
21228 case Expr::CXXScalarValueInitExprClass:
21229 case Expr::TypeTraitExprClass:
21230 case Expr::ConceptSpecializationExprClass:
21231 case Expr::RequiresExprClass:
21232 case Expr::ArrayTypeTraitExprClass:
21233 case Expr::ExpressionTraitExprClass:
21234 case Expr::CXXNoexceptExprClass:
21235 return NoDiag();
21236 case Expr::CallExprClass:
21237 case Expr::CXXOperatorCallExprClass: {
21238 // C99 6.6/3 allows function calls within unevaluated subexpressions of
21239 // constant expressions, but they can never be ICEs because an ICE cannot
21240 // contain an operand of (pointer to) function type.
21241 const CallExpr *CE = cast<CallExpr>(E);
21242 if (CE->getBuiltinCallee())
21243 return CheckEvalInICE(E, Ctx);
21244 return ICEDiag(IK_NotICE, E->getBeginLoc());
21245 }
21246 case Expr::CXXRewrittenBinaryOperatorClass:
21247 return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(),
21248 Ctx);
21249 case Expr::DeclRefExprClass: {
21250 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
21251 if (isa<EnumConstantDecl>(D))
21252 return NoDiag();
21253
21254 // C++ and OpenCL (FIXME: spec reference?) allow reading const-qualified
21255 // integer variables in constant expressions:
21256 //
21257 // C++ 7.1.5.1p2
21258 // A variable of non-volatile const-qualified integral or enumeration
21259 // type initialized by an ICE can be used in ICEs.
21260 //
21261 // We sometimes use CheckICE to check the C++98 rules in C++11 mode. In
21262 // that mode, use of reference variables should not be allowed.
21263 const VarDecl *VD = dyn_cast<VarDecl>(D);
21264 if (VD && VD->isUsableInConstantExpressions(Ctx) &&
21265 !VD->getType()->isReferenceType())
21266 return NoDiag();
21267
21268 return ICEDiag(IK_NotICE, E->getBeginLoc());
21269 }
21270 case Expr::UnaryOperatorClass: {
21271 const UnaryOperator *Exp = cast<UnaryOperator>(E);
21272 switch (Exp->getOpcode()) {
21273 case UO_PostInc:
21274 case UO_PostDec:
21275 case UO_PreInc:
21276 case UO_PreDec:
21277 case UO_AddrOf:
21278 case UO_Deref:
21279 case UO_Coawait:
21280 // C99 6.6/3 allows increment and decrement within unevaluated
21281 // subexpressions of constant expressions, but they can never be ICEs
21282 // because an ICE cannot contain an lvalue operand.
21283 return ICEDiag(IK_NotICE, E->getBeginLoc());
21284 case UO_Extension:
21285 case UO_LNot:
21286 case UO_Plus:
21287 case UO_Minus:
21288 case UO_Not:
21289 case UO_Real:
21290 case UO_Imag:
21291 return CheckICE(Exp->getSubExpr(), Ctx);
21292 }
21293 llvm_unreachable("invalid unary operator class");
21294 }
21295 case Expr::OffsetOfExprClass: {
21296 // Note that per C99, offsetof must be an ICE. And AFAIK, using
21297 // EvaluateAsRValue matches the proposed gcc behavior for cases like
21298 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
21299 // compliance: we should warn earlier for offsetof expressions with
21300 // array subscripts that aren't ICEs, and if the array subscripts
21301 // are ICEs, the value of the offsetof must be an integer constant.
21302 return CheckEvalInICE(E, Ctx);
21303 }
21304 case Expr::UnaryExprOrTypeTraitExprClass: {
21306 if ((Exp->getKind() == UETT_SizeOf) &&
21308 return ICEDiag(IK_NotICE, E->getBeginLoc());
21309 if (Exp->getKind() == UETT_CountOf) {
21310 QualType ArgTy = Exp->getTypeOfArgument();
21311 if (ArgTy->isVariableArrayType()) {
21312 // We need to look whether the array is multidimensional. If it is,
21313 // then we want to check the size expression manually to see whether
21314 // it is an ICE or not.
21315 const auto *VAT = Ctx.getAsVariableArrayType(ArgTy);
21316 if (VAT->getElementType()->isArrayType())
21317 // Variable array size expression could be missing (e.g. int a[*][10])
21318 // In that case, it can't be a constant expression.
21319 return VAT->getSizeExpr() ? CheckICE(VAT->getSizeExpr(), Ctx)
21320 : ICEDiag(IK_NotICE, E->getBeginLoc());
21321
21322 // Otherwise, this is a regular VLA, which is definitely not an ICE.
21323 return ICEDiag(IK_NotICE, E->getBeginLoc());
21324 }
21325 }
21326 return NoDiag();
21327 }
21328 case Expr::BinaryOperatorClass: {
21329 const BinaryOperator *Exp = cast<BinaryOperator>(E);
21330 switch (Exp->getOpcode()) {
21331 case BO_PtrMemD:
21332 case BO_PtrMemI:
21333 case BO_Assign:
21334 case BO_MulAssign:
21335 case BO_DivAssign:
21336 case BO_RemAssign:
21337 case BO_AddAssign:
21338 case BO_SubAssign:
21339 case BO_ShlAssign:
21340 case BO_ShrAssign:
21341 case BO_AndAssign:
21342 case BO_XorAssign:
21343 case BO_OrAssign:
21344 // C99 6.6/3 allows assignments within unevaluated subexpressions of
21345 // constant expressions, but they can never be ICEs because an ICE cannot
21346 // contain an lvalue operand.
21347 return ICEDiag(IK_NotICE, E->getBeginLoc());
21348
21349 case BO_Mul:
21350 case BO_Div:
21351 case BO_Rem:
21352 case BO_Add:
21353 case BO_Sub:
21354 case BO_Shl:
21355 case BO_Shr:
21356 case BO_LT:
21357 case BO_GT:
21358 case BO_LE:
21359 case BO_GE:
21360 case BO_EQ:
21361 case BO_NE:
21362 case BO_And:
21363 case BO_Xor:
21364 case BO_Or:
21365 case BO_Comma:
21366 case BO_Cmp: {
21367 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
21368 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
21369 if (Exp->getOpcode() == BO_Div ||
21370 Exp->getOpcode() == BO_Rem) {
21371 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
21372 // we don't evaluate one.
21373 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
21374 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
21375 if (REval == 0)
21376 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
21377 if (REval.isSigned() && REval.isAllOnes()) {
21378 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
21379 if (LEval.isMinSignedValue())
21380 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
21381 }
21382 }
21383 }
21384 if (Exp->getOpcode() == BO_Comma) {
21385 if (Ctx.getLangOpts().C99) {
21386 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
21387 // if it isn't evaluated.
21388 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
21389 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
21390 } else {
21391 // In both C89 and C++, commas in ICEs are illegal.
21392 return ICEDiag(IK_NotICE, E->getBeginLoc());
21393 }
21394 }
21395 return Worst(LHSResult, RHSResult);
21396 }
21397 case BO_LAnd:
21398 case BO_LOr: {
21399 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
21400 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
21401 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
21402 // Rare case where the RHS has a comma "side-effect"; we need
21403 // to actually check the condition to see whether the side
21404 // with the comma is evaluated.
21405 if ((Exp->getOpcode() == BO_LAnd) !=
21406 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
21407 return RHSResult;
21408 return NoDiag();
21409 }
21410
21411 return Worst(LHSResult, RHSResult);
21412 }
21413 }
21414 llvm_unreachable("invalid binary operator kind");
21415 }
21416 case Expr::ImplicitCastExprClass:
21417 case Expr::CStyleCastExprClass:
21418 case Expr::CXXFunctionalCastExprClass:
21419 case Expr::CXXStaticCastExprClass:
21420 case Expr::CXXReinterpretCastExprClass:
21421 case Expr::CXXConstCastExprClass:
21422 case Expr::ObjCBridgedCastExprClass: {
21423 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
21424 if (isa<ExplicitCastExpr>(E)) {
21425 if (const FloatingLiteral *FL
21426 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
21427 unsigned DestWidth = Ctx.getIntWidth(E->getType());
21428 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
21429 APSInt IgnoredVal(DestWidth, !DestSigned);
21430 bool Ignored;
21431 // If the value does not fit in the destination type, the behavior is
21432 // undefined, so we are not required to treat it as a constant
21433 // expression.
21434 if (FL->getValue().convertToInteger(IgnoredVal,
21435 llvm::APFloat::rmTowardZero,
21436 &Ignored) & APFloat::opInvalidOp)
21437 return ICEDiag(IK_NotICE, E->getBeginLoc());
21438 return NoDiag();
21439 }
21440 }
21441 switch (cast<CastExpr>(E)->getCastKind()) {
21442 case CK_LValueToRValue:
21443 case CK_AtomicToNonAtomic:
21444 case CK_NonAtomicToAtomic:
21445 case CK_NoOp:
21446 case CK_IntegralToBoolean:
21447 case CK_IntegralCast:
21448 return CheckICE(SubExpr, Ctx);
21449 default:
21450 return ICEDiag(IK_NotICE, E->getBeginLoc());
21451 }
21452 }
21453 case Expr::BinaryConditionalOperatorClass: {
21455 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
21456 if (CommonResult.Kind == IK_NotICE) return CommonResult;
21457 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
21458 if (FalseResult.Kind == IK_NotICE) return FalseResult;
21459 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
21460 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
21461 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
21462 return FalseResult;
21463 }
21464 case Expr::ConditionalOperatorClass: {
21466 // If the condition (ignoring parens) is a __builtin_constant_p call,
21467 // then only the true side is actually considered in an integer constant
21468 // expression, and it is fully evaluated. This is an important GNU
21469 // extension. See GCC PR38377 for discussion.
21470 if (const CallExpr *CallCE
21471 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
21472 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
21473 return CheckEvalInICE(E, Ctx);
21474 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
21475 if (CondResult.Kind == IK_NotICE)
21476 return CondResult;
21477
21478 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
21479 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
21480
21481 if (TrueResult.Kind == IK_NotICE)
21482 return TrueResult;
21483 if (FalseResult.Kind == IK_NotICE)
21484 return FalseResult;
21485 if (CondResult.Kind == IK_ICEIfUnevaluated)
21486 return CondResult;
21487 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
21488 return NoDiag();
21489 // Rare case where the diagnostics depend on which side is evaluated
21490 // Note that if we get here, CondResult is 0, and at least one of
21491 // TrueResult and FalseResult is non-zero.
21492 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
21493 return FalseResult;
21494 return TrueResult;
21495 }
21496 case Expr::CXXDefaultArgExprClass:
21497 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
21498 case Expr::CXXDefaultInitExprClass:
21499 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
21500 case Expr::ChooseExprClass: {
21501 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
21502 }
21503 case Expr::BuiltinBitCastExprClass: {
21504 if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
21505 return ICEDiag(IK_NotICE, E->getBeginLoc());
21506 return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
21507 }
21508 }
21509
21510 llvm_unreachable("Invalid StmtClass!");
21511}
21512
21513/// Evaluate an expression as a C++11 integral constant expression.
21515 const Expr *E,
21516 llvm::APSInt *Value) {
21518 return false;
21519
21520 APValue Result;
21521 if (!E->isCXX11ConstantExpr(Ctx, &Result))
21522 return false;
21523
21524 if (!Result.isInt())
21525 return false;
21526
21527 if (Value) *Value = Result.getInt();
21528 return true;
21529}
21530
21532 assert(!isValueDependent() &&
21533 "Expression evaluator can't be called on a dependent expression.");
21534
21535 ExprTimeTraceScope TimeScope(this, Ctx, "isIntegerConstantExpr");
21536
21537 if (Ctx.getLangOpts().CPlusPlus11)
21538 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr);
21539
21540 ICEDiag D = CheckICE(this, Ctx);
21541 if (D.Kind != IK_ICE)
21542 return false;
21543 return true;
21544}
21545
21546std::optional<llvm::APSInt>
21548 if (isValueDependent()) {
21549 // Expression evaluator can't succeed on a dependent expression.
21550 return std::nullopt;
21551 }
21552
21553 if (Ctx.getLangOpts().CPlusPlus11) {
21554 APSInt Value;
21556 return Value;
21557 return std::nullopt;
21558 }
21559
21560 if (!isIntegerConstantExpr(Ctx))
21561 return std::nullopt;
21562
21563 // The only possible side-effects here are due to UB discovered in the
21564 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
21565 // required to treat the expression as an ICE, so we produce the folded
21566 // value.
21568 Expr::EvalStatus Status;
21569 EvalInfo Info(Ctx, Status, EvaluationMode::IgnoreSideEffects);
21570 Info.InConstantContext = true;
21571
21572 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
21573 llvm_unreachable("ICE cannot be evaluated!");
21574
21575 return ExprResult.Val.getInt();
21576}
21577
21579 assert(!isValueDependent() &&
21580 "Expression evaluator can't be called on a dependent expression.");
21581
21582 return CheckICE(this, Ctx).Kind == IK_ICE;
21583}
21584
21586 assert(!isValueDependent() &&
21587 "Expression evaluator can't be called on a dependent expression.");
21588
21589 // We support this checking in C++98 mode in order to diagnose compatibility
21590 // issues.
21591 assert(Ctx.getLangOpts().CPlusPlus);
21592
21593 bool IsConst;
21594 APValue Scratch;
21595 if (FastEvaluateAsRValue(this, Scratch, Ctx, IsConst) && Scratch.hasValue()) {
21596 if (Result)
21597 *Result = Scratch;
21598 return true;
21599 }
21600
21601 // Build evaluation settings.
21602 Expr::EvalStatus Status;
21604 Status.Diag = &Diags;
21605 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantExpression);
21606
21607 bool IsConstExpr =
21608 ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) &&
21609 // FIXME: We don't produce a diagnostic for this, but the callers that
21610 // call us on arbitrary full-expressions should generally not care.
21611 Info.discardCleanups() && !Status.HasSideEffects;
21612
21613 return IsConstExpr && Diags.empty();
21614}
21615
21617 const FunctionDecl *Callee,
21619 const Expr *This) const {
21620 assert(!isValueDependent() &&
21621 "Expression evaluator can't be called on a dependent expression.");
21622
21623 llvm::TimeTraceScope TimeScope("EvaluateWithSubstitution", [&] {
21624 std::string Name;
21625 llvm::raw_string_ostream OS(Name);
21626 Callee->getNameForDiagnostic(OS, Ctx.getPrintingPolicy(),
21627 /*Qualified=*/true);
21628 return Name;
21629 });
21630
21631 Expr::EvalStatus Status;
21632 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantExpressionUnevaluated);
21633 Info.InConstantContext = true;
21634
21635 LValue ThisVal;
21636 const LValue *ThisPtr = nullptr;
21637 if (This) {
21638#ifndef NDEBUG
21639 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
21640 assert(MD && "Don't provide `this` for non-methods.");
21641 assert(MD->isImplicitObjectMemberFunction() &&
21642 "Don't provide `this` for methods without an implicit object.");
21643#endif
21644 if (!This->isValueDependent() &&
21645 EvaluateObjectArgument(Info, This, ThisVal) &&
21646 !Info.EvalStatus.HasSideEffects)
21647 ThisPtr = &ThisVal;
21648
21649 // Ignore any side-effects from a failed evaluation. This is safe because
21650 // they can't interfere with any other argument evaluation.
21651 Info.EvalStatus.HasSideEffects = false;
21652 }
21653
21654 CallRef Call = Info.CurrentCall->createCall(Callee);
21655 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
21656 I != E; ++I) {
21657 unsigned Idx = I - Args.begin();
21658 if (Idx >= Callee->getNumParams())
21659 break;
21660 const ParmVarDecl *PVD = Callee->getParamDecl(Idx);
21661 if ((*I)->isValueDependent() ||
21662 !EvaluateCallArg(PVD, *I, Call, Info) ||
21663 Info.EvalStatus.HasSideEffects) {
21664 // If evaluation fails, throw away the argument entirely.
21665 if (APValue *Slot = Info.getParamSlot(Call, PVD))
21666 *Slot = APValue();
21667 }
21668
21669 // Ignore any side-effects from a failed evaluation. This is safe because
21670 // they can't interfere with any other argument evaluation.
21671 Info.EvalStatus.HasSideEffects = false;
21672 }
21673
21674 // Parameter cleanups happen in the caller and are not part of this
21675 // evaluation.
21676 Info.discardCleanups();
21677 Info.EvalStatus.HasSideEffects = false;
21678
21679 // Build fake call to Callee.
21680 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, This,
21681 Call);
21682 // FIXME: Missing ExprWithCleanups in enable_if conditions?
21683 FullExpressionRAII Scope(Info);
21684 return Evaluate(Value, Info, this) && Scope.destroy() &&
21685 !Info.EvalStatus.HasSideEffects;
21686}
21687
21690 PartialDiagnosticAt> &Diags) {
21691 // FIXME: It would be useful to check constexpr function templates, but at the
21692 // moment the constant expression evaluator cannot cope with the non-rigorous
21693 // ASTs which we build for dependent expressions.
21694 if (FD->isDependentContext())
21695 return true;
21696
21697 llvm::TimeTraceScope TimeScope("isPotentialConstantExpr", [&] {
21698 std::string Name;
21699 llvm::raw_string_ostream OS(Name);
21701 /*Qualified=*/true);
21702 return Name;
21703 });
21704
21705 Expr::EvalStatus Status;
21706 Status.Diag = &Diags;
21707
21708 EvalInfo Info(FD->getASTContext(), Status,
21710 Info.InConstantContext = true;
21711 Info.CheckingPotentialConstantExpression = true;
21712
21713 // The constexpr VM attempts to compile all methods to bytecode here.
21714 if (Info.EnableNewConstInterp) {
21715 Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD);
21716 return Diags.empty();
21717 }
21718
21719 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
21720 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
21721
21722 // Fabricate an arbitrary expression on the stack and pretend that it
21723 // is a temporary being used as the 'this' pointer.
21724 LValue This;
21725 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getCanonicalTagType(RD)
21726 : Info.Ctx.IntTy);
21727 This.set({&VIE, Info.CurrentCall->Index});
21728
21730
21731 APValue Scratch;
21732 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
21733 // Evaluate the call as a constant initializer, to allow the construction
21734 // of objects of non-literal types.
21735 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
21736 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
21737 } else {
21738 SourceLocation Loc = FD->getLocation();
21740 Loc, FD, (MD && MD->isImplicitObjectMemberFunction()) ? &This : nullptr,
21741 &VIE, Args, CallRef(), FD->getBody(), Info, Scratch,
21742 /*ResultSlot=*/nullptr);
21743 }
21744
21745 return Diags.empty();
21746}
21747
21749 const FunctionDecl *FD,
21751 PartialDiagnosticAt> &Diags) {
21752 assert(!E->isValueDependent() &&
21753 "Expression evaluator can't be called on a dependent expression.");
21754
21755 Expr::EvalStatus Status;
21756 Status.Diag = &Diags;
21757
21758 EvalInfo Info(FD->getASTContext(), Status,
21760 Info.InConstantContext = true;
21761 Info.CheckingPotentialConstantExpression = true;
21762
21763 if (Info.EnableNewConstInterp) {
21765 return Diags.empty();
21766 }
21767
21768 // Fabricate a call stack frame to give the arguments a plausible cover story.
21769 CallStackFrame Frame(Info, SourceLocation(), FD, /*This=*/nullptr,
21770 /*CallExpr=*/nullptr, CallRef());
21771
21772 APValue ResultScratch;
21773 Evaluate(ResultScratch, Info, E);
21774 return Diags.empty();
21775}
21776
21778 unsigned Type) const {
21779 if (!getType()->isPointerType())
21780 return false;
21781
21782 Expr::EvalStatus Status;
21783 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantFold);
21784 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
21785}
21786
21787static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,
21788 EvalInfo &Info, std::string *StringResult) {
21789 if (!E->getType()->hasPointerRepresentation() || !E->isPRValue())
21790 return false;
21791
21792 LValue String;
21793
21794 if (!EvaluatePointer(E, String, Info))
21795 return false;
21796
21797 QualType CharTy = E->getType()->getPointeeType();
21798
21799 // Fast path: if it's a string literal, search the string value.
21800 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
21801 String.getLValueBase().dyn_cast<const Expr *>())) {
21802 StringRef Str = S->getBytes();
21803 int64_t Off = String.Offset.getQuantity();
21804 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
21805 S->getCharByteWidth() == 1 &&
21806 // FIXME: Add fast-path for wchar_t too.
21807 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
21808 Str = Str.substr(Off);
21809
21810 StringRef::size_type Pos = Str.find(0);
21811 if (Pos != StringRef::npos)
21812 Str = Str.substr(0, Pos);
21813
21814 Result = Str.size();
21815 if (StringResult)
21816 *StringResult = Str;
21817 return true;
21818 }
21819
21820 // Fall through to slow path.
21821 }
21822
21823 // Slow path: scan the bytes of the string looking for the terminating 0.
21824 for (uint64_t Strlen = 0; /**/; ++Strlen) {
21825 APValue Char;
21826 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
21827 !Char.isInt())
21828 return false;
21829 if (!Char.getInt()) {
21830 Result = Strlen;
21831 return true;
21832 } else if (StringResult)
21833 StringResult->push_back(Char.getInt().getExtValue());
21834 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
21835 return false;
21836 }
21837}
21838
21839std::optional<std::string> Expr::tryEvaluateString(ASTContext &Ctx) const {
21840 Expr::EvalStatus Status;
21841 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantFold);
21842 uint64_t Result;
21843 std::string StringResult;
21844
21845 if (Info.EnableNewConstInterp) {
21846 if (!Info.Ctx.getInterpContext().evaluateString(Info, this, StringResult))
21847 return std::nullopt;
21848 return StringResult;
21849 }
21850
21851 if (EvaluateBuiltinStrLen(this, Result, Info, &StringResult))
21852 return StringResult;
21853 return std::nullopt;
21854}
21855
21856template <typename T>
21857static bool EvaluateCharRangeAsStringImpl(const Expr *, T &Result,
21858 const Expr *SizeExpression,
21859 const Expr *PtrExpression,
21860 ASTContext &Ctx,
21861 Expr::EvalResult &Status) {
21862 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantExpression);
21863 Info.InConstantContext = true;
21864
21865 if (Info.EnableNewConstInterp)
21866 return Info.Ctx.getInterpContext().evaluateCharRange(Info, SizeExpression,
21867 PtrExpression, Result);
21868
21869 LValue String;
21870 FullExpressionRAII Scope(Info);
21871 APSInt SizeValue;
21872 if (!::EvaluateInteger(SizeExpression, SizeValue, Info))
21873 return false;
21874
21875 uint64_t Size = SizeValue.getZExtValue();
21876
21877 // FIXME: better protect against invalid or excessive sizes
21878 if constexpr (std::is_same_v<APValue, T>)
21879 Result = APValue(APValue::UninitArray{}, Size, Size);
21880 else {
21881 if (Size < Result.max_size())
21882 Result.reserve(Size);
21883 }
21884 if (!::EvaluatePointer(PtrExpression, String, Info))
21885 return false;
21886
21887 QualType CharTy = PtrExpression->getType()->getPointeeType();
21888 for (uint64_t I = 0; I < Size; ++I) {
21889 APValue Char;
21890 if (!handleLValueToRValueConversion(Info, PtrExpression, CharTy, String,
21891 Char))
21892 return false;
21893
21894 if constexpr (std::is_same_v<APValue, T>) {
21895 Result.getArrayInitializedElt(I) = std::move(Char);
21896 } else {
21897 APSInt C = Char.getInt();
21898
21899 assert(C.getBitWidth() <= 8 &&
21900 "string element not representable in char");
21901
21902 Result.push_back(static_cast<char>(C.getExtValue()));
21903 }
21904
21905 if (!HandleLValueArrayAdjustment(Info, PtrExpression, String, CharTy, 1))
21906 return false;
21907 }
21908
21909 return Scope.destroy() && CheckMemoryLeaks(Info);
21910}
21911
21913 const Expr *SizeExpression,
21914 const Expr *PtrExpression, ASTContext &Ctx,
21915 EvalResult &Status) const {
21916 return EvaluateCharRangeAsStringImpl(this, Result, SizeExpression,
21917 PtrExpression, Ctx, Status);
21918}
21919
21921 const Expr *SizeExpression,
21922 const Expr *PtrExpression, ASTContext &Ctx,
21923 EvalResult &Status) const {
21924 return EvaluateCharRangeAsStringImpl(this, Result, SizeExpression,
21925 PtrExpression, Ctx, Status);
21926}
21927
21928bool Expr::tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const {
21929 Expr::EvalStatus Status;
21930 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantFold);
21931
21932 if (Info.EnableNewConstInterp)
21933 return Info.Ctx.getInterpContext().evaluateStrlen(Info, this, Result);
21934
21935 return EvaluateBuiltinStrLen(this, Result, Info);
21936}
21937
21938namespace {
21939struct IsWithinLifetimeHandler {
21940 EvalInfo &Info;
21941 static constexpr AccessKinds AccessKind = AccessKinds::AK_IsWithinLifetime;
21942 using result_type = std::optional<bool>;
21943 std::optional<bool> failed() { return std::nullopt; }
21944 template <typename T>
21945 std::optional<bool> found(T &Subobj, QualType SubobjType) {
21946 return true;
21947 }
21948};
21949
21950std::optional<bool> EvaluateBuiltinIsWithinLifetime(IntExprEvaluator &IEE,
21951 const CallExpr *E) {
21952 EvalInfo &Info = IEE.Info;
21953 // Sometimes this is called during some sorts of constant folding / early
21954 // evaluation. These are meant for non-constant expressions and are not
21955 // necessary since this consteval builtin will never be evaluated at runtime.
21956 // Just fail to evaluate when not in a constant context.
21957 if (!Info.InConstantContext)
21958 return std::nullopt;
21959 assert(E->getBuiltinCallee() == Builtin::BI__builtin_is_within_lifetime);
21960 const Expr *Arg = E->getArg(0);
21961 if (Arg->isValueDependent())
21962 return std::nullopt;
21963 LValue Val;
21964 if (!EvaluatePointer(Arg, Val, Info))
21965 return std::nullopt;
21966
21967 if (Val.allowConstexprUnknown())
21968 return true;
21969
21970 auto Error = [&](int Diag) {
21971 bool CalledFromStd = false;
21972 const auto *Callee = Info.CurrentCall->getCallee();
21973 if (Callee && Callee->isInStdNamespace()) {
21974 const IdentifierInfo *Identifier = Callee->getIdentifier();
21975 CalledFromStd = Identifier && Identifier->isStr("is_within_lifetime");
21976 }
21977 Info.CCEDiag(CalledFromStd ? Info.CurrentCall->getCallRange().getBegin()
21978 : E->getExprLoc(),
21979 diag::err_invalid_is_within_lifetime)
21980 << (CalledFromStd ? "std::is_within_lifetime"
21981 : "__builtin_is_within_lifetime")
21982 << Diag;
21983 return std::nullopt;
21984 };
21985 // C++2c [meta.const.eval]p4:
21986 // During the evaluation of an expression E as a core constant expression, a
21987 // call to this function is ill-formed unless p points to an object that is
21988 // usable in constant expressions or whose complete object's lifetime began
21989 // within E.
21990
21991 // Make sure it points to an object
21992 // nullptr does not point to an object
21993 if (Val.isNullPointer() || Val.getLValueBase().isNull())
21994 return Error(0);
21995 QualType T = Val.getLValueBase().getType();
21996 assert(!T->isFunctionType() &&
21997 "Pointers to functions should have been typed as function pointers "
21998 "which would have been rejected earlier");
21999 assert(T->isObjectType());
22000 // Hypothetical array element is not an object
22001 if (Val.getLValueDesignator().isOnePastTheEnd())
22002 return Error(1);
22003 assert(Val.getLValueDesignator().isValidSubobject() &&
22004 "Unchecked case for valid subobject");
22005 // All other ill-formed values should have failed EvaluatePointer, so the
22006 // object should be a pointer to an object that is usable in a constant
22007 // expression or whose complete lifetime began within the expression
22008 CompleteObject CO =
22009 findCompleteObject(Info, E, AccessKinds::AK_IsWithinLifetime, Val, T);
22010 // The lifetime hasn't begun yet if we are still evaluating the
22011 // initializer ([basic.life]p(1.2))
22012 if (Info.EvaluatingDeclValue && CO.Value == Info.EvaluatingDeclValue)
22013 return Error(2);
22014
22015 if (!CO)
22016 return false;
22017 IsWithinLifetimeHandler handler{Info};
22018 return findSubobject(Info, E, CO, Val.getLValueDesignator(), handler);
22019}
22020} // namespace
Defines the clang::ASTContext interface.
#define V(N, I)
This file provides some common utility functions for processing Lambda related AST Constructs.
Defines enum values for all the target-independent builtin functions.
static Address castToBase(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy, Address OriginalBaseAddress, llvm::Value *Addr)
static uint32_t getBitWidth(const Expr *E)
llvm::APSInt APSInt
Definition Compiler.cpp:24
static Decl::Kind getKind(const Decl *D)
GCCTypeClass
Values returned by __builtin_classify_type, chosen to match the values produced by GCC's builtin.
static bool isRead(AccessKinds AK)
static bool EvaluateCharRangeAsStringImpl(const Expr *, T &Result, const Expr *SizeExpression, const Expr *PtrExpression, ASTContext &Ctx, Expr::EvalResult &Status)
static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result, EvalInfo &Info, std::string *StringResult=nullptr)
static bool isValidIndeterminateAccess(AccessKinds AK)
Is this kind of access valid on an indeterminate object value?
static unsigned elementwiseSize(EvalInfo &Info, QualType BaseTy)
static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, EvalInfo &Info)
static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result, Expr::SideEffectsKind SEK)
static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, AccessKinds AK, const LValue &LVal, QualType LValType)
Find the complete object to which an LValue refers.
static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base, LValue &Result)
Attempts to evaluate the given LValueBase as the result of a call to a function with the alloc_size a...
static const CXXMethodDecl * HandleVirtualDispatch(EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found, llvm::SmallVectorImpl< QualType > &CovariantAdjustmentPath)
Perform virtual dispatch.
static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD)
static bool CheckEvaluationResult(CheckEvaluationResultKind CERK, EvalInfo &Info, SourceLocation DiagLoc, QualType Type, const APValue &Value, ConstantExprKind Kind, const FieldDecl *SubobjectDecl, CheckedTemporaries &CheckedTemps)
static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E, LValue &LVal, QualType EltTy, bool Imag)
Update an lvalue to refer to a component of a complex number.
static bool evalPackBuiltin(const CallExpr *E, EvalInfo &Info, APValue &Result, llvm::function_ref< APInt(const APSInt &)> PackFn)
static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, QualType Type, CharUnits &Size, SizeOfType SOT=SizeOfType::SizeOf)
Get the size of the given type in char units.
static bool HandleConstructorCall(const Expr *E, const LValue &This, CallRef Call, const CXXConstructorDecl *Definition, EvalInfo &Info, APValue &Result)
Evaluate a constructor call.
static bool hlslElementwiseCastHelper(EvalInfo &Info, const Expr *E, QualType DestTy, SmallVectorImpl< APValue > &SrcVals, SmallVectorImpl< QualType > &SrcTypes)
static bool ShouldPropagateBreakContinue(EvalInfo &Info, const Stmt *LoopOrSwitch, ArrayRef< BlockScopeRAII * > Scopes, EvalStmtResult &ESR)
Helper to implement named break/continue.
static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info, const Stmt *Body, const SwitchCase *Case=nullptr)
Evaluate the body of a loop, and translate the result as appropriate.
static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info, bool InvalidBaseOK=false)
static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc, const CXXConstructorDecl *CD, bool IsValueInitialization)
CheckTrivialDefaultConstructor - Check whether a constructor is a trivial default constructor.
static bool EvaluateVector(const Expr *E, APValue &Result, EvalInfo &Info)
static const ValueDecl * GetLValueBaseDecl(const LValue &LVal)
SizeOfType
static bool TryEvaluateBuiltinNaN(const ASTContext &Context, QualType ResultTy, const Expr *Arg, bool SNaN, llvm::APFloat &Result)
static const Expr * ignorePointerCastsAndParens(const Expr *E)
A more selective version of E->IgnoreParenCasts for tryEvaluateBuiltinObjectSize. This ignores some c...
static bool isAnyAccess(AccessKinds AK)
static bool EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E, SuccessCB &&Success, AfterCB &&DoAfter)
static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E, const RecordDecl *RD, const LValue &This, APValue &Result)
Perform zero-initialization on an object of non-union class type. C++11 [dcl.init]p5: To zero-initial...
static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info)
static bool CheckMemoryLeaks(EvalInfo &Info)
Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless "the allocated storage is dea...
static bool handleScalarCast(EvalInfo &Info, const FPOptions FPO, const Expr *E, QualType SourceTy, QualType DestTy, APValue const &Original, APValue &Result)
static ICEDiag CheckEvalInICE(const Expr *E, const ASTContext &Ctx)
static llvm::APInt ConvertBoolVectorToInt(const APValue &Val)
static bool flattenAPValue(EvalInfo &Info, const Expr *E, APValue Value, QualType BaseTy, SmallVectorImpl< APValue > &Elements, SmallVectorImpl< QualType > &Types, unsigned Size)
static bool hlslAggSplatHelper(EvalInfo &Info, const Expr *E, APValue &SrcVal, QualType &SrcTy)
static bool isBaseClassPublic(const CXXRecordDecl *Derived, const CXXRecordDecl *Base)
Determine whether Base, which is known to be a direct base class of Derived, is a public base class.
static bool hasVirtualDestructor(QualType T)
static bool HandleOverflow(EvalInfo &Info, const Expr *E, const T &SrcValue, QualType DestType)
static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value)
static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E, LValue &LVal, const IndirectFieldDecl *IFD)
Update LVal to refer to the given indirect field.
static bool ConvertDoubleToFloatStrict(EvalInfo &Info, const Expr *E, APFloat OrigVal, APValue &Result)
static ICEDiag Worst(ICEDiag A, ICEDiag B)
static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E, const VarDecl *VD, CallStackFrame *Frame, unsigned Version, APValue *&Result)
Try to evaluate the initializer for a variable declaration.
static bool handleDefaultInitValue(QualType T, APValue &Result)
Get the value to use for a default-initialized object of type T.
static bool HandleLValueVectorElement(EvalInfo &Info, const Expr *E, LValue &LVal, QualType EltTy, uint64_t Size, uint64_t Idx)
static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base)
static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc, QualType Type, const LValue &LVal, ConstantExprKind Kind, CheckedTemporaries &CheckedTemps)
Check that this reference or pointer core constant expression is a valid value for an address or refe...
static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E, const APSInt &LHS, const APSInt &RHS, unsigned BitWidth, Operation Op, APSInt &Result)
Perform the given integer operation, which is known to need at most BitWidth bits,...
static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info)
Evaluate an expression of record type as a temporary.
static bool EvaluateArray(const Expr *E, const LValue &This, APValue &Result, EvalInfo &Info)
static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E, APValue &Value, const FieldDecl *FD)
static bool handleVectorShuffle(EvalInfo &Info, const ShuffleVectorExpr *E, QualType ElemType, APValue const &VecVal1, APValue const &VecVal2, unsigned EltNum, APValue &Result)
static bool handleVectorElementCast(EvalInfo &Info, const FPOptions FPO, const Expr *E, QualType SourceTy, QualType DestTy, APValue const &Original, APValue &Result)
static const ValueDecl * HandleMemberPointerAccess(EvalInfo &Info, QualType LVType, LValue &LV, const Expr *RHS, bool IncludeMember=true)
HandleMemberPointerAccess - Evaluate a member access operation and build an lvalue referring to the r...
static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E, LValue &Result)
HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on the provided lvalue,...
static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info)
static bool IsOpaqueConstantCall(const CallExpr *E)
Should this call expression be treated as forming an opaque constant?
static bool CheckMemberPointerConstantExpression(EvalInfo &Info, SourceLocation Loc, QualType Type, const APValue &Value, ConstantExprKind Kind)
Member pointers are constant expressions unless they point to a non-virtual dllimport member function...
static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult, const ASTContext &Ctx, Expr::SideEffectsKind AllowSideEffects, EvalInfo &Info)
static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type, const LValue &LVal, APValue &RVal, bool WantObjectRepresentation=false)
Perform an lvalue-to-rvalue conversion on the given glvalue.
static bool handleElementwiseCast(EvalInfo &Info, const Expr *E, const FPOptions FPO, SmallVectorImpl< APValue > &Elements, SmallVectorImpl< QualType > &SrcTypes, SmallVectorImpl< QualType > &DestTypes, SmallVectorImpl< APValue > &Results)
static bool refersToCompleteObject(const LValue &LVal)
Tests to see if the LValue has a user-specified designator (that isn't necessarily valid)....
static bool AreElementsOfSameArray(QualType ObjType, const SubobjectDesignator &A, const SubobjectDesignator &B)
Determine whether the given subobject designators refer to elements of the same array object.
static bool EvaluateDecompositionDeclInit(EvalInfo &Info, const DecompositionDecl *DD)
static bool IsWeakLValue(const LValue &Value)
static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This, APValue &Result, const CXXConstructExpr *CCE, QualType AllocType)
static bool EvaluateRecord(const Expr *E, const LValue &This, APValue &Result, EvalInfo &Info)
static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal, QualType LValType, APValue &Val)
Perform an assignment of Val to LVal. Takes ownership of Val.
static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result, const RecordDecl *TruncatedType, unsigned TruncatedElements)
Cast an lvalue referring to a base subobject to a derived class, by truncating the lvalue's path to t...
static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E)
Evaluate an expression to see if it had side-effects, and discard its result.
static bool constructAggregate(EvalInfo &Info, const FPOptions FPO, const Expr *E, APValue &Result, QualType ResultType, SmallVectorImpl< APValue > &Elements, SmallVectorImpl< QualType > &ElTypes)
static void addFlexibleArrayMemberInitSize(EvalInfo &Info, const QualType &T, const LValue &LV, CharUnits &Size)
If we're evaluating the object size of an instance of a struct that contains a flexible array member,...
static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E, QualType Type, LValue &Result)
static bool evalShuffleGeneric(EvalInfo &Info, const CallExpr *Call, APValue &Out, llvm::function_ref< std::pair< unsigned, int >(unsigned, unsigned)> GetSourceIndex)
static QualType getSubobjectType(QualType ObjType, QualType SubobjType, bool IsMutable=false)
static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result, EvalInfo &Info)
Evaluate an integer or fixed point expression into an APResult.
static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E, const FPOptions FPO, QualType SrcType, const APSInt &Value, QualType DestType, APFloat &Result)
static const CXXRecordDecl * getBaseClassType(SubobjectDesignator &Designator, unsigned PathLength)
static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result, const CXXRecordDecl *DerivedRD, const CXXRecordDecl *BaseRD)
Cast an lvalue referring to a derived class to a known base subobject.
static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj, const CXXRecordDecl *DerivedDecl, const CXXBaseSpecifier *Base)
static bool HandleConversionToBool(const APValue &Val, bool &Result)
CharUnits GetAlignOfExpr(const ASTContext &Ctx, const Expr *E, UnaryExprOrTypeTrait ExprKind)
static bool isModification(AccessKinds AK)
static bool handleCompareOpForVector(const APValue &LHSValue, BinaryOperatorKind Opcode, const APValue &RHSValue, APInt &Result)
static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr)
static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object, LValue &This)
Build an lvalue for the object argument of a member function call.
static bool CheckLiteralType(EvalInfo &Info, const Expr *E, const LValue *This=nullptr)
Check that this core constant expression is of literal type, and if not, produce an appropriate diagn...
static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info)
CheckEvaluationResultKind
static bool isZeroSized(const LValue &Value)
static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit, uint64_t Index)
Extract the value of a character from a string literal.
static bool modifySubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj, const SubobjectDesignator &Sub, APValue &NewVal)
Update the designated sub-object of an rvalue to the given value.
static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx, const Expr *E, llvm::APSInt *Value)
Evaluate an expression as a C++11 integral constant expression.
static CharUnits GetAlignOfType(const ASTContext &Ctx, QualType T, UnaryExprOrTypeTrait ExprKind)
static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info, APValue &Val, APSInt &Alignment)
static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, LValue &LVal, QualType EltTy, APSInt Adjustment)
Update a pointer value to model pointer arithmetic.
static bool extractSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj, const SubobjectDesignator &Sub, APValue &Result, AccessKinds AK=AK_Read)
Extract the designated sub-object of an rvalue.
static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal, const FieldDecl *FD, const ASTRecordLayout *RL=nullptr)
Update LVal to refer to the given field, which must be a member of the type currently described by LV...
static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index, bool IsSub)
static bool IsDeclSourceLocationCurrent(const FunctionDecl *FD)
void HandleComplexComplexDiv(APFloat A, APFloat B, APFloat C, APFloat D, APFloat &ResR, APFloat &ResI)
static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param, const Expr *E, APValue &Result, bool CopyObjectRepresentation)
Perform a trivial copy from Param, which is the parameter of a copy or move constructor or assignment...
static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E, APFloat::opStatus St)
Check if the given evaluation result is allowed for constant evaluation.
static bool EvaluateBuiltinConstantPForLValue(const APValue &LV)
EvaluateBuiltinConstantPForLValue - Determine the result of __builtin_constant_p when applied to the ...
static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg)
EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to GCC as we can manage.
static bool checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E, const LValue &This, const CXXMethodDecl *NamedMember)
Check that the pointee of the 'this' pointer in a member function call is either within its lifetime ...
static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type, const APValue &Value, ConstantExprKind Kind)
Check that this core constant expression value is a valid value for a constant expression.
static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result, EvalInfo &Info)
static std::optional< DynamicType > ComputeDynamicType(EvalInfo &Info, const Expr *E, LValue &This, AccessKinds AK)
Determine the dynamic type of an object.
static bool EvaluateDecl(EvalInfo &Info, const Decl *D, bool EvaluateConditionDecl=false)
static void expandArray(APValue &Array, unsigned Index)
static bool handleLogicalOpForVector(const APInt &LHSValue, BinaryOperatorKind Opcode, const APInt &RHSValue, APInt &Result)
static unsigned FindDesignatorMismatch(QualType ObjType, const SubobjectDesignator &A, const SubobjectDesignator &B, bool &WasArrayIndex)
Find the position where two subobject designators diverge, or equivalently the length of the common i...
static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx, const LValue &LV)
Determine whether this is a pointer past the end of the complete object referred to by the lvalue.
static unsigned getBaseIndex(const CXXRecordDecl *Derived, const CXXRecordDecl *Base)
Get the base index of the given base class within an APValue representing the given derived class.
static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result, EvalInfo &Info)
Evaluate only a fixed point expression into an APResult.
void HandleComplexComplexMul(APFloat A, APFloat B, APFloat C, APFloat D, APFloat &ResR, APFloat &ResI)
static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type, EvalInfo &Info, uint64_t &Size)
Tries to evaluate the __builtin_object_size for E. If successful, returns true and stores the result ...
static bool EvalPointerValueAsBool(const APValue &Value, bool &Result)
static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E, BinaryOperatorKind Opcode, APValue &LHSValue, const APValue &RHSValue)
static const FunctionDecl * getVirtualOperatorDelete(QualType T)
static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal)
Checks to see if the given LValue's Designator is at the end of the LValue's record layout....
static bool CheckArraySize(EvalInfo &Info, const ConstantArrayType *CAT, SourceLocation CallLoc={})
static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This, const Expr *E, bool AllowNonLiteralTypes=false)
EvaluateInPlace - Evaluate an expression in-place in an APValue. In some cases, the in-place evaluati...
static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E, APFloat &LHS, BinaryOperatorKind Opcode, const APFloat &RHS)
Perform the given binary floating-point operation, in-place, on LHS.
static std::optional< DynAlloc * > CheckDeleteKind(EvalInfo &Info, const Expr *E, const LValue &Pointer, DynAlloc::Kind DeallocKind)
Check that the given object is a suitable pointer to a heap allocation that still exists and is of th...
static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, bool InvalidBaseOK=false)
Evaluate an expression as an lvalue. This can be legitimately called on expressions which are not glv...
static bool FastEvaluateAsRValue(const Expr *Exp, APValue &Result, const ASTContext &Ctx, bool &IsConst)
static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E, APValue &Result, ArrayRef< QualType > Path)
Perform the adjustment from a value returned by a virtual function to a value of the statically expec...
static bool evalShiftWithCount(EvalInfo &Info, const CallExpr *Call, APValue &Out, llvm::function_ref< APInt(const APInt &, uint64_t)> ShiftOp, llvm::function_ref< APInt(const APInt &, unsigned)> OverflowOp)
static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info, const SwitchStmt *SS)
Evaluate a switch statement.
static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S, APValue &Result, QualType AllocType=QualType())
static bool EvaluateArgs(ArrayRef< const Expr * > Args, CallRef Call, EvalInfo &Info, const FunctionDecl *Callee, bool RightToLeft=false, LValue *ObjectArg=nullptr)
Evaluate the arguments to a function call.
static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, EvalInfo &Info)
static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, const LValue &LVal, llvm::APInt &Result)
Convenience function. LVal's base must be a call to an alloc_size function.
static bool handleIntIntBinOp(EvalInfo &Info, const BinaryOperator *E, const APSInt &LHS, BinaryOperatorKind Opcode, APSInt RHS, APSInt &Result)
Perform the given binary integer operation.
static bool EvaluateInitForDeclOfReferenceType(EvalInfo &Info, const ValueDecl *D, const Expr *Init, LValue &Result, APValue &Val)
Evaluates the initializer of a reference.
static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This, AccessKinds AK, bool Polymorphic)
Check that we can access the notional vptr of an object / determine its dynamic type.
static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E, QualType SrcType, const APFloat &Value, QualType DestType, APSInt &Result)
static bool getAlignmentArgument(const Expr *E, QualType ForType, EvalInfo &Info, APSInt &Alignment)
Evaluate the value of the alignment argument to __builtin_align_{up,down}, __builtin_is_aligned and _...
static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc, QualType Type, const APValue &Value)
Check that this evaluated value is fully-initialized and can be loaded by an lvalue-to-rvalue convers...
static SubobjectHandler::result_type findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj, const SubobjectDesignator &Sub, SubobjectHandler &handler)
Find the designated sub-object of an rvalue.
static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc, unsigned Type, const LValue &LVal, CharUnits &EndOffset)
Helper for tryEvaluateBuiltinObjectSize – Given an LValue, this will determine how many bytes exist f...
static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int, CharUnits &Result)
Converts the given APInt to CharUnits, assuming the APInt is unsigned. Fails if the conversion would ...
static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg, CallRef Call, EvalInfo &Info, bool NonNull=false, APValue **EvaluatedArg=nullptr)
llvm::SmallPtrSet< const MaterializeTemporaryExpr *, 8 > CheckedTemporaries
Materialized temporaries that we've already checked to determine if they're initializsed by a constan...
GCCTypeClass EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts)
EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way as GCC.
static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info)
static bool MaybeEvaluateDeferredVarDeclInit(EvalInfo &Info, const VarDecl *VD)
static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E, QualType DestType, QualType SrcType, const APSInt &Value)
static std::optional< APValue > handleVectorUnaryOperator(ASTContext &Ctx, QualType ResultTy, UnaryOperatorKind Op, APValue Elt)
static bool lifetimeStartedInEvaluation(EvalInfo &Info, APValue::LValueBase Base, bool MutableSubobject=false)
static bool isOneByteCharacterType(QualType T)
static bool HandleLambdaCapture(EvalInfo &Info, const Expr *E, LValue &Result, const CXXMethodDecl *MD, const FieldDecl *FD, bool LValueToRValueConversion)
Get an lvalue to a field of a lambda's closure type.
static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl, const Expr *Cond, bool &Result)
Evaluate a condition (either a variable declaration or an expression).
static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult, const ASTContext &Ctx, Expr::SideEffectsKind AllowSideEffects, EvalInfo &Info)
static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result)
EvaluateAsRValue - Try to evaluate this expression, performing an implicit lvalue-to-rvalue cast if i...
static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK, QualType T)
Diagnose an attempt to read from any unreadable field within the specified type, which might be a cla...
static ICEDiag CheckICE(const Expr *E, const ASTContext &Ctx)
static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc, const FunctionDecl *Declaration, const FunctionDecl *Definition, const Stmt *Body)
CheckConstexprFunction - Check that a function can be called in a constant expression.
static bool EvaluateDestruction(const ASTContext &Ctx, APValue::LValueBase Base, APValue DestroyedValue, QualType Type, SourceLocation Loc, Expr::EvalStatus &EStatus, bool IsConstantDestruction)
static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, const Stmt *S, const SwitchCase *SC=nullptr)
static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This, APValue &Result, const InitListExpr *ILE, QualType AllocType)
static bool HasSameBase(const LValue &A, const LValue &B)
static bool CheckLocalVariableDeclaration(EvalInfo &Info, const VarDecl *VD)
static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj, const CXXRecordDecl *Derived, const CXXRecordDecl *Base, const ASTRecordLayout *RL=nullptr)
static bool IsGlobalLValue(APValue::LValueBase B)
static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E)
Get rounding mode to use in evaluation of the specified expression.
static QualType getObjectType(APValue::LValueBase B)
Retrieves the "underlying object type" of the given expression, as used by __builtin_object_size.
static bool handleCompareOpForVectorHelper(const APTy &LHSValue, BinaryOperatorKind Opcode, const APTy &RHSValue, APInt &Result)
static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E)
static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD)
Determine whether a type would actually be read by an lvalue-to-rvalue conversion.
static void negateAsSigned(APSInt &Int)
Negate an APSInt in place, converting it to a signed form if necessary, and preserving its value (by ...
static bool HandleFunctionCall(SourceLocation CallLoc, const FunctionDecl *Callee, const LValue *ObjectArg, const Expr *E, ArrayRef< const Expr * > Args, CallRef Call, const Stmt *Body, EvalInfo &Info, APValue &Result, const LValue *ResultSlot)
Evaluate a function call.
static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal)
Attempts to detect a user writing into a piece of memory that's impossible to figure out the size of ...
static bool GetLValueBaseAsString(const EvalInfo &Info, const LValue &LVal, LValueBaseString &AsString)
static bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E)
static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, EvalInfo &Info)
EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and produce either the intege...
static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E, LValue &Ptr)
Apply the given dynamic cast operation on the provided lvalue.
static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E, LValue &Result)
Perform a call to 'operator new' or to ‘__builtin_operator_new’.
static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E, QualType SrcType, QualType DestType, APFloat &Result)
static bool MaybeHandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr, const LValue &LHS)
Handle a builtin simple-assignment or a call to a trivial assignment operator whose left-hand side mi...
uint8_t GFNIMul(uint8_t AByte, uint8_t BByte)
static bool isFormalAccess(AccessKinds AK)
Is this an access per the C++ definition?
static bool handleCompoundAssignment(EvalInfo &Info, const CompoundAssignOperator *E, const LValue &LVal, QualType LValType, QualType PromotedLValType, BinaryOperatorKind Opcode, const APValue &RVal)
Perform a compound assignment of LVal <op>= RVal.
static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal, QualType LValType, bool IsIncrement, APValue *Old)
Perform an increment or decrement on LVal.
static ICEDiag NoDiag()
static bool EvaluateVoid(const Expr *E, EvalInfo &Info)
static bool HandleDestruction(EvalInfo &Info, const Expr *E, const LValue &This, QualType ThisType)
Perform a destructor or pseudo-destructor call on the given object, which might in general not be a c...
static bool HandleDestructionImpl(EvalInfo &Info, SourceRange CallRange, const LValue &This, APValue &Value, QualType T)
static bool ArePotentiallyOverlappingStringLiterals(const EvalInfo &Info, const LValue &LHS, const LValue &RHS)
uint8_t GFNIMultiplicativeInverse(uint8_t Byte)
uint8_t GFNIAffine(uint8_t XByte, const APInt &AQword, const APSInt &Imm, bool Inverse)
APSInt NormalizeRotateAmount(const APSInt &Value, const APSInt &Amount)
TokenType getType() const
Returns the token's type, e.g.
FormatToken * Next
The next token in the unwrapped line.
tooling::Replacements cleanup(const FormatStyle &Style, StringRef Code, ArrayRef< tooling::Range > Ranges, StringRef FileName="<stdin>")
Clean up any erroneous/redundant code in the given Ranges in Code.
#define X(type, name)
Definition Value.h:97
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Record Record
Definition MachO.h:31
Implements a partial diagnostic which may not be emitted.
llvm::DenseMap< Stmt *, Stmt * > MapTy
Definition ParentMap.cpp:21
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
Expr * getExpr()
Get 'expr' part of the associated expression/statement.
static QualType getPointeeType(const MemRegion *R)
Enumerates target-specific builtins in their own namespaces within namespace clang.
Defines the clang::TypeLoc interface and its subclasses.
C Language Family Type Representation.
__DEVICE__ long long abs(long long __n)
a trap message and trap category.
llvm::APInt getValue() const
QualType getType() const
Definition APValue.cpp:63
unsigned getVersion() const
Definition APValue.cpp:113
QualType getDynamicAllocType() const
Definition APValue.cpp:122
QualType getTypeInfoType() const
Definition APValue.cpp:117
static LValueBase getTypeInfo(TypeInfoLValue LV, QualType TypeInfo)
Definition APValue.cpp:55
static LValueBase getDynamicAlloc(DynamicAllocLValue LV, QualType Type)
Definition APValue.cpp:47
A non-discriminated union of a base, field, or array index.
Definition APValue.h:207
BaseOrMemberType getAsBaseOrMember() const
Definition APValue.h:221
static LValuePathEntry ArrayIndex(uint64_t Index)
Definition APValue.h:215
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:122
bool hasArrayFiller() const
Definition APValue.h:584
const LValueBase getLValueBase() const
Definition APValue.cpp:983
APValue & getArrayInitializedElt(unsigned I)
Definition APValue.h:576
void swap(APValue &RHS)
Swaps the contents of this and the given APValue.
Definition APValue.cpp:474
APSInt & getInt()
Definition APValue.h:489
APValue & getStructField(unsigned i)
Definition APValue.h:617
const FieldDecl * getUnionField() const
Definition APValue.h:629
bool isVector() const
Definition APValue.h:473
APSInt & getComplexIntImag()
Definition APValue.h:527
bool isAbsent() const
Definition APValue.h:463
bool isComplexInt() const
Definition APValue.h:470
llvm::PointerIntPair< const Decl *, 1, bool > BaseOrMemberType
A FieldDecl or CXXRecordDecl, along with a flag indicating whether we mean a virtual or non-virtual b...
Definition APValue.h:204
ValueKind getKind() const
Definition APValue.h:461
unsigned getArrayInitializedElts() const
Definition APValue.h:595
static APValue IndeterminateValue()
Definition APValue.h:432
bool isFloat() const
Definition APValue.h:468
APFixedPoint & getFixedPoint()
Definition APValue.h:511
bool hasValue() const
Definition APValue.h:465
bool hasLValuePath() const
Definition APValue.cpp:998
const ValueDecl * getMemberPointerDecl() const
Definition APValue.cpp:1066
APValue & getUnionValue()
Definition APValue.h:633
CharUnits & getLValueOffset()
Definition APValue.cpp:993
void printPretty(raw_ostream &OS, const ASTContext &Ctx, QualType Ty) const
Definition APValue.cpp:703
bool isComplexFloat() const
Definition APValue.h:471
APValue & getVectorElt(unsigned I)
Definition APValue.h:563
APValue & getArrayFiller()
Definition APValue.h:587
unsigned getVectorLength() const
Definition APValue.h:571
bool isLValue() const
Definition APValue.h:472
void setUnion(const FieldDecl *Field, const APValue &Value)
Definition APValue.cpp:1059
bool isIndeterminate() const
Definition APValue.h:464
bool isInt() const
Definition APValue.h:467
unsigned getArraySize() const
Definition APValue.h:599
bool allowConstexprUnknown() const
Definition APValue.h:318
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition APValue.cpp:956
bool isFixedPoint() const
Definition APValue.h:469
@ Indeterminate
This object has an indeterminate value (C++ [basic.indet]).
Definition APValue.h:131
@ None
There is no such object (it's outside its lifetime).
Definition APValue.h:129
bool isStruct() const
Definition APValue.h:475
APSInt & getComplexIntReal()
Definition APValue.h:519
APFloat & getComplexFloatImag()
Definition APValue.h:543
APFloat & getComplexFloatReal()
Definition APValue.h:535
APFloat & getFloat()
Definition APValue.h:503
APValue & getStructBase(unsigned i)
Definition APValue.h:612
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:220
SourceManager & getSourceManager()
Definition ASTContext.h:851
const ConstantArrayType * getAsConstantArrayType(QualType T) const
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
unsigned getIntWidth(QualType T) const
const llvm::fltSemantics & getFloatTypeSemantics(QualType T) const
Return the APFloat 'semantics' for the specified scalar floating point type.
static CanQualType getCanonicalType(QualType T)
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
void getObjCEncodingForType(QualType T, std::string &S, const FieldDecl *Field=nullptr, QualType *NotEncodedT=nullptr) const
Emit the Objective-CC type encoding for the given type T into S.
uint64_t getTargetNullPointerValue(QualType QT) const
Get target-dependent integer value for null pointer which is used for constant folding.
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D,...
unsigned getPreferredTypeAlign(QualType T) const
Return the "preferred" alignment of the specified type T for the current target, in bits.
CanQualType VoidPtrTy
bool hasSameFunctionTypeIgnoringExceptionSpec(QualType T, QualType U) const
Determine whether two function types are the same, ignoring exception specifications in cases where t...
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type.
Builtin::Context & BuiltinInfo
Definition ASTContext.h:792
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, const Expr *SizeExpr, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type.
const LangOptions & getLangOpts() const
Definition ASTContext.h:944
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
ComparisonCategories CompCategories
Types and expressions required to build C++2a three-way comparisons using operator<=>,...
QualType getIntTypeForBitwidth(unsigned DestWidth, unsigned Signed) const
getIntTypeForBitwidth - sets integer QualTy according to specified details: bitwidth,...
CanQualType CharTy
unsigned getOpenMPDefaultSimdAlign(QualType T) const
Get default simd alignment of the specified complete type in bits.
CanQualType IntTy
TypeInfoChars getTypeInfoDataSizeInChars(QualType T) const
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
const clang::PrintingPolicy & getPrintingPolicy() const
Definition ASTContext.h:843
llvm::FixedPointSemantics getFixedPointSemantics(QualType Ty) const
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
static bool hasSameType(QualType T1, QualType T2)
Determine whether the given types T1 and T2 are equivalent.
llvm::APSInt MakeIntValue(uint64_t Value, QualType Type) const
Make an APSInt of the appropriate width and signedness for the given Value and integer Type.
const VariableArrayType * getAsVariableArrayType(QualType T) const
bool hasSimilarType(QualType T1, QualType T2) const
Determine if two types are similar, according to the C++ rules.
DiagnosticsEngine & getDiagnostics() const
interp::Context & getInterpContext()
Returns the clang bytecode interpreter context.
QualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:909
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
CanQualType getCanonicalTagType(const TagDecl *TD) const
static bool hasSameUnqualifiedType(QualType T1, QualType T2)
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
uint16_t getPointerAuthTypeDiscriminator(QualType T)
Return the "other" type-specific discriminator for the given type.
CanQualType HalfTy
uint64_t getCharWidth() const
Return the size of the character type, in bits.
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
unsigned getFieldCount() const
getFieldCount - Get the number of fields in the layout.
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
CharUnits getBaseClassOffset(const CXXRecordDecl *Base) const
getBaseClassOffset - Get the offset, in chars, for the given base class.
CharUnits getVBaseClassOffset(const CXXRecordDecl *VBase) const
getVBaseClassOffset - Get the offset, in chars, for the given base class.
LabelDecl * getLabel() const
Definition Expr.h:4573
OpaqueValueExpr * getCommonExpr() const
Get the common subexpression shared by all initializations (the source array).
Definition Expr.h:5983
Expr * getSubExpr() const
Get the initializer to use for each array element.
Definition Expr.h:5988
Expr * getLHS()
An array access can be written A[4] or 4[A] (both are equivalent).
Definition Expr.h:2750
uint64_t getValue() const
Definition ExprCXX.h:3044
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3723
QualType getElementType() const
Definition TypeBase.h:3735
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition TypeBase.h:8091
Attr - This represents one attribute.
Definition Attr.h:46
BinaryConditionalOperator - The GNU extension to the conditional operator which allows the middle ope...
Definition Expr.h:4453
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression which will be evaluated if the condition evaluates to false; ...
Definition Expr.h:4507
OpaqueValueExpr * getOpaqueValue() const
getOpaqueValue - Return the opaque value placeholder.
Definition Expr.h:4491
Expr * getCommon() const
getCommon - Return the common expression, written to the left of the condition.
Definition Expr.h:4488
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:4038
static bool isLogicalOp(Opcode Opc)
Definition Expr.h:4171
Expr * getLHS() const
Definition Expr.h:4088
static bool isRelationalOp(Opcode Opc)
Definition Expr.h:4132
static bool isComparisonOp(Opcode Opc)
Definition Expr.h:4138
static Opcode getOpForCompoundAssignment(Opcode Opc)
Definition Expr.h:4185
SourceLocation getExprLoc() const
Definition Expr.h:4079
Expr * getRHS() const
Definition Expr.h:4090
static bool isAdditiveOp(Opcode Opc)
Definition Expr.h:4124
static bool isPtrMemOp(Opcode Opc)
predicates to categorize the respective opcodes.
Definition Expr.h:4115
static bool isAssignmentOp(Opcode Opc)
Definition Expr.h:4174
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operator.
Definition Expr.h:4251
Opcode getOpcode() const
Definition Expr.h:4083
static bool isEqualityOp(Opcode Opc)
Definition Expr.h:4135
bool hasCaptures() const
True if this block (or its nested blocks) captures anything of local storage from its enclosing scope...
Definition Decl.h:4790
const BlockDecl * getBlockDecl() const
Definition Expr.h:6636
std::string getQuotedName(unsigned ID) const
Return the identifier name for the specified builtin inside single quotes for a diagnostic,...
Definition Builtins.cpp:85
bool isConstantEvaluated(unsigned ID) const
Return true if this function can be constant evaluated by Clang frontend.
Definition Builtins.h:459
AccessSpecifier Access
The access along this inheritance path.
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
CXXBasePath & front()
bool isAmbiguous(CanQualType BaseType) const
Determine whether the path from the most-derived type to the given base type is ambiguous (i....
Represents a base class of a C++ class.
Definition DeclCXX.h:146
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclCXX.h:194
bool isVirtual() const
Determines whether the base class is a virtual base class (or not).
Definition DeclCXX.h:203
QualType getType() const
Retrieves the type of the base class.
Definition DeclCXX.h:249
const Expr * getSubExpr() const
Definition ExprCXX.h:1515
bool getValue() const
Definition ExprCXX.h:740
Represents a call to a C++ constructor.
Definition ExprCXX.h:1548
bool isElidable() const
Whether this construction is elidable.
Definition ExprCXX.h:1617
Expr * getArg(unsigned Arg)
Return the specified argument.
Definition ExprCXX.h:1691
bool requiresZeroInitialization() const
Whether this construction first requires zero-initialization before the initializer is called.
Definition ExprCXX.h:1650
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition ExprCXX.h:1611
unsigned getNumArgs() const
Return the number of arguments to the constructor call.
Definition ExprCXX.h:1688
Represents a C++ constructor within a class.
Definition DeclCXX.h:2604
bool isDefaultConstructor() const
Whether this constructor is a default constructor (C++ [class.ctor]p5), which can be used to default-...
Definition DeclCXX.cpp:2999
CXXCtorInitializer *const * init_const_iterator
Iterates through the member/base initializer list.
Definition DeclCXX.h:2690
Expr * getExpr()
Get the initialization expression that will be used.
Definition ExprCXX.cpp:1105
FunctionDecl * getOperatorDelete() const
Definition ExprCXX.h:2665
bool isArrayForm() const
Definition ExprCXX.h:2652
bool isGlobalDelete() const
Definition ExprCXX.h:2651
Represents a C++ destructor within a class.
Definition DeclCXX.h:2869
CXXForRangeStmt - This represents C++0x [stmt.ranged]'s ranged for statement, represented as 'for (ra...
Definition StmtCXX.h:135
DeclStmt * getBeginStmt()
Definition StmtCXX.h:163
DeclStmt * getLoopVarStmt()
Definition StmtCXX.h:169
DeclStmt * getEndStmt()
Definition StmtCXX.h:166
DeclStmt * getRangeStmt()
Definition StmtCXX.h:162
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will call.
Definition ExprCXX.h:1788
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2129
bool isExplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An explicit object member function is a non-static member function with an explic...
Definition DeclCXX.cpp:2703
bool isImplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An implicit object member function is a non-static member function without an exp...
Definition DeclCXX.cpp:2710
QualType getFunctionObjectParameterReferenceType() const
Return the type of the object pointed by this.
Definition DeclCXX.cpp:2820
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2255
bool isInstance() const
Definition DeclCXX.h:2156
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition DeclCXX.cpp:2735
bool isStatic() const
Definition DeclCXX.cpp:2401
bool isCopyAssignmentOperator() const
Determine whether this is a copy-assignment operator, regardless of whether it was declared implicitl...
Definition DeclCXX.cpp:2714
bool isLambdaStaticInvoker() const
Determine whether this is a lambda closure type's static member function that is used for the result ...
Definition DeclCXX.cpp:2845
QualType getAllocatedType() const
Definition ExprCXX.h:2434
std::optional< Expr * > getArraySize()
This might return std::nullopt even if isArray() returns true, since there might not be an array size...
Definition ExprCXX.h:2469
Expr * getPlacementArg(unsigned I)
Definition ExprCXX.h:2503
unsigned getNumPlacementArgs() const
Definition ExprCXX.h:2494
SourceRange getSourceRange() const
Definition ExprCXX.h:2610
FunctionDecl * getOperatorNew() const
Definition ExprCXX.h:2459
Expr * getInitializer()
The initializer of this new-expression.
Definition ExprCXX.h:2533
bool getValue() const
Definition ExprCXX.h:4332
MutableArrayRef< Expr * > getInitExprs()
Definition ExprCXX.h:5181
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
bool hasMutableFields() const
Determine whether this class, or any of its class subobjects, contains a mutable field.
Definition DeclCXX.h:1233
bool isGenericLambda() const
Determine whether this class describes a generic lambda function object (i.e.
Definition DeclCXX.cpp:1673
base_class_iterator bases_end()
Definition DeclCXX.h:617
bool hasTrivialDestructor() const
Determine whether this class has a trivial destructor (C++ [class.dtor]p3)
Definition DeclCXX.h:1366
base_class_range bases()
Definition DeclCXX.h:608
void getCaptureFields(llvm::DenseMap< const ValueDecl *, FieldDecl * > &Captures, FieldDecl *&ThisCapture) const
For a closure type, retrieve the mapping from captured variables and this to the non-static data memb...
Definition DeclCXX.cpp:1784
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition DeclCXX.h:602
base_class_iterator bases_begin()
Definition DeclCXX.h:615
const CXXBaseSpecifier * base_class_const_iterator
Iterator that traverses the base classes of a class.
Definition DeclCXX.h:520
capture_const_range captures() const
Definition DeclCXX.h:1097
bool isEmpty() const
Determine whether this is an empty class in the sense of (C++11 [meta.unary.prop]).
Definition DeclCXX.h:1186
CXXDestructorDecl * getDestructor() const
Returns the destructor decl for this class.
Definition DeclCXX.cpp:2121
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition DeclCXX.cpp:1736
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:522
unsigned getNumVBases() const
Retrieves the number of virtual base classes of this class.
Definition DeclCXX.h:623
bool isDerivedFrom(const CXXRecordDecl *Base) const
Determine whether this class is derived from the class Base.
Expr * getSemanticForm()
Get an equivalent semantic form for this expression.
Definition ExprCXX.h:304
bool isImplicit() const
Definition ExprCXX.h:1177
bool isTypeOperand() const
Definition ExprCXX.h:884
QualType getTypeOperand(const ASTContext &Context) const
Retrieves the type operand of this typeid() expression after various required adjustments (removing r...
Definition ExprCXX.cpp:161
Expr * getExprOperand() const
Definition ExprCXX.h:895
bool isPotentiallyEvaluated() const
Determine whether this typeid has a type operand which is potentially evaluated, per C++11 [expr....
Definition ExprCXX.cpp:134
MSGuidDecl * getGuidDecl() const
Definition ExprCXX.h:1114
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2943
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3147
SourceLocation getBeginLoc() const
Definition Expr.h:3277
const AllocSizeAttr * getCalleeAllocSizeAttr() const
Try to get the alloc_size attribute of the callee. May return null.
Definition Expr.cpp:3573
unsigned getBuiltinCallee() const
getBuiltinCallee - If this is a call to a builtin, return the builtin ID of the callee.
Definition Expr.cpp:1591
Expr * getCallee()
Definition Expr.h:3090
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition Expr.h:3134
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operator.
Definition Expr.h:3236
Expr ** getArgs()
Retrieve the call arguments.
Definition Expr.h:3137
Decl * getCalleeDecl()
Definition Expr.h:3120
QualType getCallReturnType(const ASTContext &Ctx) const
getCallReturnType - Get the return type of the call expr.
Definition Expr.cpp:1602
QualType withConst() const
Retrieves a version of this type with const applied.
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
CaseStmt - Represent a case statement.
Definition Stmt.h:1912
Expr * getLHS()
Definition Stmt.h:1995
Expr * getRHS()
Definition Stmt.h:2007
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition Expr.h:3676
path_iterator path_begin()
Definition Expr.h:3746
unsigned path_size() const
Definition Expr.h:3745
CastKind getCastKind() const
Definition Expr.h:3720
path_iterator path_end()
Definition Expr.h:3747
const CXXBaseSpecifier *const * path_const_iterator
Definition Expr.h:3743
bool path_empty() const
Definition Expr.h:3744
Expr * getSubExpr()
Definition Expr.h:3726
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operation.
Definition Expr.h:3790
CharUnits - This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
bool isPowerOfTwo() const
isPowerOfTwo - Test whether the quantity is a power of two.
Definition CharUnits.h:135
CharUnits alignmentAtOffset(CharUnits offset) const
Given that this is a non-zero alignment value, what is the alignment at the given offset?
Definition CharUnits.h:207
bool isZero() const
isZero - Test whether the quantity equals zero.
Definition CharUnits.h:122
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition CharUnits.h:185
static CharUnits One()
One - Construct a CharUnits quantity of one.
Definition CharUnits.h:58
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition CharUnits.h:63
unsigned getValue() const
Definition Expr.h:1629
Expr * getChosenSubExpr() const
getChosenSubExpr - Return the subexpression chosen according to the condition.
Definition Expr.h:4884
const ComparisonCategoryInfo & getInfoForType(QualType Ty) const
Return the comparison category information as specified by getCategoryForType(Ty).
const ValueInfo * getValueInfo(ComparisonCategoryResult ValueKind) const
ComparisonCategoryResult makeWeakResult(ComparisonCategoryResult Res) const
Converts the specified result kind into the correct result kind for this category.
Complex values, per C99 6.2.5p11.
Definition TypeBase.h:3276
QualType getElementType() const
Definition TypeBase.h:3286
CompoundAssignOperator - For compound assignments (e.g.
Definition Expr.h:4300
QualType getComputationLHSType() const
Definition Expr.h:4334
CompoundLiteralExpr - [C99 6.5.2.5].
Definition Expr.h:3605
bool hasStaticStorage() const
Definition Expr.h:3650
APValue & getOrCreateStaticValue(ASTContext &Ctx) const
Definition Expr.cpp:5572
bool isFileScope() const
Definition Expr.h:3637
const Expr * getInitializer() const
Definition Expr.h:3633
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition Stmt.h:1732
bool body_empty() const
Definition Stmt.h:1776
Stmt *const * const_body_iterator
Definition Stmt.h:1804
body_iterator body_end()
Definition Stmt.h:1797
body_range body()
Definition Stmt.h:1795
body_iterator body_begin()
Definition Stmt.h:1796
bool isSatisfied() const
Whether or not the concept with the given arguments was satisfied when the expression was created.
ConditionalOperator - The ?
Definition Expr.h:4391
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression representing the value of the expression if the condition eva...
Definition Expr.h:4423
Expr * getCond() const
getCond - Return the expression representing the condition for the ?
Definition Expr.h:4414
Expr * getTrueExpr() const
getTrueExpr - Return the subexpression representing the value of the expression if the condition eval...
Definition Expr.h:4418
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3761
unsigned getSizeBitWidth() const
Return the bit width of the size type.
Definition TypeBase.h:3824
static unsigned getNumAddressingBits(const ASTContext &Context, QualType ElementType, const llvm::APInt &NumElements)
Determine the number of bits required to address a member of.
Definition Type.cpp:215
static unsigned getMaxSizeBits(const ASTContext &Context)
Determine the maximum number of active bits that an array's size can require, which limits the maximu...
Definition Type.cpp:255
uint64_t getLimitedSize() const
Return the size zero-extended to uint64_t or UINT64_MAX if the value is larger than UINT64_MAX.
Definition TypeBase.h:3850
bool isZeroSize() const
Return true if the size is zero.
Definition TypeBase.h:3831
const Expr * getSizeExpr() const
Return a pointer to the size expression.
Definition TypeBase.h:3857
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3817
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition TypeBase.h:3837
APValue getAPValueResult() const
Definition Expr.cpp:412
bool hasAPValueResult() const
Definition Expr.h:1157
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operator.
Definition Expr.h:4796
Expr * getSrcExpr() const
getSrcExpr - Return the Expr to be converted.
Definition Expr.h:4809
Represents the current source location and context used to determine the value of the source location...
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1449
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2109
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition DeclBase.h:2238
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1270
bool refersToEnclosingVariableOrCapture() const
Does this DeclRefExpr refer to an enclosing local or a captured variable?
Definition Expr.h:1474
ValueDecl * getDecl()
Definition Expr.h:1338
DeclStmt - Adaptor class for mixing declarations with statements and expressions.
Definition Stmt.h:1623
decl_range decls()
Definition Stmt.h:1671
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
bool isInStdNamespace() const
Definition DeclBase.cpp:449
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:546
bool isInvalidDecl() const
Definition DeclBase.h:588
SourceLocation getLocation() const
Definition DeclBase.h:439
DeclContext * getDeclContext()
Definition DeclBase.h:448
AccessSpecifier getAccess() const
Definition DeclBase.h:507
A decomposition declaration.
Definition DeclCXX.h:4245
auto flat_bindings() const
Definition DeclCXX.h:4288
Designator - A designator in a C99 designated initializer.
Definition Designator.h:38
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
DoStmt - This represents a 'do/while' stmt.
Definition Stmt.h:2824
Stmt * getBody()
Definition Stmt.h:2849
Expr * getCond()
Definition Stmt.h:2842
Symbolic representation of a dynamic allocation.
Definition APValue.h:65
static unsigned getMaxIndex()
Definition APValue.h:85
ChildElementIter< false > begin()
Definition Expr.h:5232
ExplicitCastExpr - An explicit cast written in the source code.
Definition Expr.h:3928
QualType getTypeAsWritten() const
getTypeAsWritten - Returns the type that this expression is casting to, as written in the source code...
Definition Expr.h:3955
This represents one expression.
Definition Expr.h:112
const Expr * skipRValueSubobjectAdjustments(SmallVectorImpl< const Expr * > &CommaLHS, SmallVectorImpl< SubobjectAdjustment > &Adjustments) const
Walk outwards from an expression we want to bind a reference to and find the expression whose lifetim...
Definition Expr.cpp:83
bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsInt - Return true if this is a constant which we can fold and convert to an integer,...
static bool isPotentialConstantExpr(const FunctionDecl *FD, SmallVectorImpl< PartialDiagnosticAt > &Diags)
isPotentialConstantExpr - Return true if this function's definition might be usable in a constant exp...
bool isIntegerConstantExpr(const ASTContext &Ctx) const
static bool isPotentialConstantExprUnevaluated(Expr *E, const FunctionDecl *FD, SmallVectorImpl< PartialDiagnosticAt > &Diags)
isPotentialConstantExprUnevaluated - Return true if this expression might be usable in a constant exp...
bool isGLValue() const
Definition Expr.h:287
SideEffectsKind
Definition Expr.h:670
@ SE_AllowSideEffects
Allow any unmodeled side effect.
Definition Expr.h:674
@ SE_AllowUndefinedBehavior
Allow UB that we can give a value, but not arbitrary unmodeled side effects.
Definition Expr.h:672
bool isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result=nullptr) const
isCXX11ConstantExpr - Return true if this expression is a constant expression in C++11.
bool EvaluateCharRangeAsString(std::string &Result, const Expr *SizeExpression, const Expr *PtrExpression, ASTContext &Ctx, EvalResult &Status) const
llvm::APSInt EvaluateKnownConstIntCheckOverflow(const ASTContext &Ctx, SmallVectorImpl< PartialDiagnosticAt > *Diag=nullptr) const
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition Expr.cpp:3094
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:177
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
bool tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const
If the current Expr is a pointer, this will try to statically determine the strlen of the string poin...
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Returns the set of floating point options that apply to this expression.
Definition Expr.cpp:3968
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3089
bool containsErrors() const
Whether this expression contains subexpressions which had errors.
Definition Expr.h:246
bool EvaluateAsFloat(llvm::APFloat &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsFloat - Return true if this is a constant which we can fold and convert to a floating point...
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3085
bool EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsLValue - Evaluate an expression to see if we can fold it to an lvalue with link time known ...
bool EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsFixedPoint - Return true if this is a constant which we can fold and convert to a fixed poi...
bool isEvaluatable(const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects) const
isEvaluatable - Call EvaluateAsRValue to see if this expression can be constant folded without side-e...
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
bool isPRValue() const
Definition Expr.h:285
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition Expr.h:284
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
bool HasSideEffects(const ASTContext &Ctx, bool IncludePossibleEffects=true) const
HasSideEffects - This routine returns true for all those expressions which have any effect other than...
Definition Expr.cpp:3669
bool EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx, ConstantExprKind Kind=ConstantExprKind::Normal) const
Evaluate an expression that is required to be a constant expression.
std::optional< std::string > tryEvaluateString(ASTContext &Ctx) const
If the current Expr can be evaluated to a pointer to a null-terminated constant string,...
bool EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsBooleanCondition - Return true if this is a constant which we can fold and convert to a boo...
bool isTemporaryObject(ASTContext &Ctx, const CXXRecordDecl *TempTy) const
Determine whether the result of this expression is a temporary object of the given class type.
Definition Expr.cpp:3252
Expr()=delete
ConstantExprKind
Definition Expr.h:749
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:276
QualType getType() const
Definition Expr.h:144
bool tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx, unsigned Type) const
If the current Expr is a pointer, this will try to statically determine the number of bytes available...
bool isCXX98IntegralConstantExpr(const ASTContext &Ctx) const
isCXX98IntegralConstantExpr - Return true if this expression is an integral constant expression in C+...
bool EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx, const FunctionDecl *Callee, ArrayRef< const Expr * > Args, const Expr *This=nullptr) const
EvaluateWithSubstitution - Evaluate an expression as if from the context of a call to the given funct...
bool EvaluateAsInitializer(APValue &Result, const ASTContext &Ctx, const VarDecl *VD, SmallVectorImpl< PartialDiagnosticAt > &Notes, bool IsConstantInitializer) const
EvaluateAsInitializer - Evaluate an expression as if it were the initializer of the given declaration...
void EvaluateForOverflow(const ASTContext &Ctx) const
bool isArrow() const
isArrow - Return true if the base expression is a pointer to vector, return false if the base express...
Definition Expr.cpp:4415
void getEncodedElementAccess(SmallVectorImpl< uint32_t > &Elts) const
getEncodedElementAccess - Encode the elements accessed into an llvm aggregate Constant of ConstantInt...
Definition Expr.cpp:4447
const Expr * getBase() const
Definition Expr.h:6581
bool isFPConstrained() const
LangOptions::FPExceptionModeKind getExceptionMode() const
RoundingMode getRoundingMode() const
Represents a member of a struct/union/class.
Definition Decl.h:3160
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3263
unsigned getBitWidthValue() const
Computes the bit width of this field, if this is a bit field.
Definition Decl.cpp:4752
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition Decl.h:3245
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3396
FieldDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this field.
Definition Decl.h:3407
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition Diagnostic.h:103
llvm::APInt getValue() const
Returns an internal integer representation of the literal.
Definition Expr.h:1575
llvm::APFloat getValue() const
Definition Expr.h:1666
ForStmt - This represents a 'for (init;cond;inc)' stmt.
Definition Stmt.h:2880
Stmt * getInit()
Definition Stmt.h:2895
VarDecl * getConditionVariable() const
Retrieve the variable declared in this "for" statement, if any.
Definition Stmt.cpp:1115
Stmt * getBody()
Definition Stmt.h:2924
Expr * getInc()
Definition Stmt.h:2923
Expr * getCond()
Definition Stmt.h:2922
const Expr * getSubExpr() const
Definition Expr.h:1062
Represents a function declaration or definition.
Definition Decl.h:2000
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2797
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition Decl.cpp:3279
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition Decl.cpp:4205
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition Decl.cpp:4193
bool hasCXXExplicitFunctionObjectParameter() const
Definition Decl.cpp:3865
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition Decl.h:2377
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition Decl.cpp:4329
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition Decl.h:2470
bool isUsableAsGlobalAllocationFunctionInConstantEvaluation(UnsignedOrNone *AlignmentParam=nullptr, bool *IsNothrow=nullptr) const
Determines whether this function is one of the replaceable global allocation functions described in i...
Definition Decl.cpp:3426
bool isDefaulted() const
Whether this function is defaulted.
Definition Decl.h:2385
void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const override
Appends a human-readable name for this declaration into the given stream.
Definition Decl.cpp:3125
FunctionDecl * findSpecialization(ArrayRef< TemplateArgument > Args, void *&InsertPos)
Return the specialization with the provided arguments if it exists, otherwise return the insertion po...
Expr * getResultExpr()
Return the result expression of this controlling expression.
Definition Expr.h:6462
One of these records is kept for each identifier that is lexed.
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
IfStmt - This represents an if/then/else.
Definition Stmt.h:2251
Stmt * getThen()
Definition Stmt.h:2340
Stmt * getInit()
Definition Stmt.h:2401
bool isNonNegatedConsteval() const
Definition Stmt.h:2436
Expr * getCond()
Definition Stmt.h:2328
Stmt * getElse()
Definition Stmt.h:2349
bool isConsteval() const
Definition Stmt.h:2431
VarDecl * getConditionVariable()
Retrieve the variable declared in this "if" statement, if any.
Definition Stmt.cpp:1063
const Expr * getSubExpr() const
Definition Expr.h:1743
Represents an implicitly-generated value initialization of an object of a given type.
Definition Expr.h:6057
Represents a field injected from an anonymous union/struct into the parent scope.
Definition Decl.h:3467
ArrayRef< NamedDecl * > chain() const
Definition Decl.h:3488
Describes an C or C++ initializer list.
Definition Expr.h:5299
bool isTransparent() const
Is this a transparent initializer list (that is, an InitListExpr that is purely syntactic,...
Definition Expr.cpp:2461
bool isStringLiteralInit() const
Is this an initializer for an array of characters, initialized by a string literal or an @encode?
Definition Expr.cpp:2447
unsigned getNumInits() const
Definition Expr.h:5329
Expr * getArrayFiller()
If this initializer list initializes an array with more elements than there are initializers in the l...
Definition Expr.h:5401
const Expr * getInit(unsigned Init) const
Definition Expr.h:5353
ArrayRef< Expr * > inits()
Definition Expr.h:5349
capture_init_iterator capture_init_end()
Retrieve the iterator pointing one past the last initialization argument for this lambda expression.
Definition ExprCXX.h:2106
capture_init_iterator capture_init_begin()
Retrieve the first initialization argument for this lambda expression (which initializes the first ca...
Definition ExprCXX.h:2094
CXXRecordDecl * getLambdaClass() const
Retrieve the class that corresponds to the lambda.
Definition ExprCXX.cpp:1400
@ FPE_Ignore
Assume that floating-point exceptions are masked.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Represents a prvalue temporary that is written into memory so that a reference can bind to it.
Definition ExprCXX.h:4920
StorageDuration getStorageDuration() const
Retrieve the storage duration for the materialized temporary.
Definition ExprCXX.h:4945
Expr * getSubExpr() const
Retrieve the temporary-generating subexpression whose value will be materialized into a glvalue.
Definition ExprCXX.h:4937
APValue * getOrCreateValue(bool MayCreate) const
Get the storage for the constant value of a materialized temporary of static storage duration.
Definition ExprCXX.h:4953
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3364
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3447
Expr * getBase() const
Definition Expr.h:3441
bool isArrow() const
Definition Expr.h:3548
This represents a decl that may have a name.
Definition Decl.h:274
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:295
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:301
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:340
void printQualifiedName(raw_ostream &OS) const
Returns a human-readable qualified name for this declaration, like A::B::i, for i being member of nam...
Definition Decl.cpp:1687
bool isExpressibleAsConstantInitializer() const
Definition ExprObjC.h:153
Expr * getIndexExpr(unsigned Idx)
Definition Expr.h:2586
const OffsetOfNode & getComponent(unsigned Idx) const
Definition Expr.h:2574
TypeSourceInfo * getTypeSourceInfo() const
Definition Expr.h:2567
unsigned getNumComponents() const
Definition Expr.h:2582
unsigned getArrayExprIndex() const
For an array element node, returns the index into the array of expressions.
Definition Expr.h:2479
FieldDecl * getField() const
For a field offsetof node, returns the field.
Definition Expr.h:2485
@ Array
An index into an array.
Definition Expr.h:2426
@ Identifier
A field in a dependent type, known only by its name.
Definition Expr.h:2430
@ Field
A field.
Definition Expr.h:2428
@ Base
An implicit indirection through a C++ base class, when the field found is in a base class.
Definition Expr.h:2433
Kind getKind() const
Determine what kind of offsetof node this is.
Definition Expr.h:2475
CXXBaseSpecifier * getBase() const
For a base class node, returns the base specifier.
Definition Expr.h:2495
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition Expr.h:1178
Expr * getSourceExpr() const
The source expression of an opaque value expression is the expression which originally generated the ...
Definition Expr.h:1228
Expr * getSelectedExpr() const
Definition ExprCXX.h:4639
const Expr * getSubExpr() const
Definition Expr.h:2199
Represents a parameter to a function.
Definition Decl.h:1790
unsigned getFunctionScopeIndex() const
Returns the index of this parameter in its prototype or method scope.
Definition Decl.h:1850
bool isExplicitObjectParameter() const
Definition Decl.h:1878
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3329
StringLiteral * getFunctionName()
Definition Expr.h:2049
Expr * getResultExpr()
Return the result-bearing expression, or null if there is none.
Definition Expr.h:6804
ArrayRef< Expr * > semantics()
Definition Expr.h:6828
A (possibly-)qualified type.
Definition TypeBase.h:937
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8376
QualType withConst() const
Definition TypeBase.h:1159
void addConst()
Add the const type qualifier to this QualType.
Definition TypeBase.h:1156
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1004
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8292
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition TypeBase.h:8477
QualType getCanonicalType() const
Definition TypeBase.h:8344
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8386
void removeLocalVolatile()
Definition TypeBase.h:8408
void addVolatile()
Add the volatile type qualifier to this QualType.
Definition TypeBase.h:1164
void removeLocalConst()
Definition TypeBase.h:8400
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8365
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition TypeBase.h:1545
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition TypeBase.h:8338
Represents a struct/union/class.
Definition Decl.h:4324
unsigned getNumFields() const
Returns the number of fields (non-static data members) in this record.
Definition Decl.h:4540
field_iterator field_end() const
Definition Decl.h:4530
field_range fields() const
Definition Decl.h:4527
specific_decl_iterator< FieldDecl > field_iterator
Definition Decl.h:4524
bool isAnonymousStructOrUnion() const
Whether this is an anonymous struct or union.
Definition Decl.h:4376
bool field_empty() const
Definition Decl.h:4535
field_iterator field_begin() const
Definition Decl.cpp:5270
bool isSatisfied() const
Whether or not the requires clause is satisfied.
SourceLocation getLocation() const
Definition Expr.h:2155
std::string ComputeName(ASTContext &Context) const
Definition Expr.cpp:586
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
ShuffleVectorExpr - clang-specific builtin-in function __builtin_shufflevector.
Definition Expr.h:4643
llvm::APSInt getShuffleMaskIdx(unsigned N) const
Definition Expr.h:4695
unsigned getNumSubExprs() const
getNumSubExprs - Return the size of the SubExprs array.
Definition Expr.h:4676
Expr * getExpr(unsigned Index)
getExpr - Return the Expr at the specified index.
Definition Expr.h:4682
unsigned getPackLength() const
Retrieve the length of the parameter pack.
Definition ExprCXX.h:4515
APValue EvaluateInContext(const ASTContext &Ctx, const Expr *DefaultExpr) const
Return the result of evaluating this SourceLocExpr in the specified (and possibly null) default argum...
Definition Expr.cpp:2281
bool isIntType() const
Definition Expr.h:5041
Encodes a location in the source.
A trivial tuple used to represent a source range.
SourceLocation getBegin() const
std::string printToString(const SourceManager &SM) const
CompoundStmt * getSubStmt()
Definition Expr.h:4612
Stmt - This represents one statement.
Definition Stmt.h:86
@ NoStmtClass
Definition Stmt.h:89
StmtClass getStmtClass() const
Definition Stmt.h:1485
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:338
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:350
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1799
unsigned getLength() const
Definition Expr.h:1909
StringRef getBytes() const
Allow access to clients that need the byte representation, such as ASTWriterStmt::VisitStringLiteral(...
Definition Expr.h:1875
uint32_t getCodeUnit(size_t i) const
Definition Expr.h:1882
StringRef getString() const
Definition Expr.h:1867
unsigned getCharByteWidth() const
Definition Expr.h:1910
const SwitchCase * getNextSwitchCase() const
Definition Stmt.h:1885
SwitchStmt - This represents a 'switch' stmt.
Definition Stmt.h:2501
Expr * getCond()
Definition Stmt.h:2564
Stmt * getBody()
Definition Stmt.h:2576
VarDecl * getConditionVariable()
Retrieve the variable declared in this "switch" statement, if any.
Definition Stmt.cpp:1181
Stmt * getInit()
Definition Stmt.h:2581
SwitchCase * getSwitchCaseList()
Definition Stmt.h:2632
TagDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:4899
bool isUnion() const
Definition Decl.h:3925
unsigned getMaxAtomicInlineWidth() const
Return the maximum width lock-free atomic operation which can be inlined given the supported features...
Definition TargetInfo.h:858
bool isBigEndian() const
virtual int getEHDataRegisterNumber(unsigned RegNo) const
Return the register number that __builtin_eh_return_regno would return with the specified argument.
unsigned getCharWidth() const
Definition TargetInfo.h:520
unsigned size() const
Retrieve the number of template arguments in this template argument list.
ArrayRef< TemplateArgument > asArray() const
Produce this as an array ref.
@ Type
The template argument is a type.
Symbolic representation of typeid(T) for some type T.
Definition APValue.h:44
QualType getType() const
Return the type wrapped by this type source info.
Definition TypeBase.h:8274
bool getBoolValue() const
Definition ExprCXX.h:2947
const APValue & getAPValue() const
Definition ExprCXX.h:2952
bool isStoredAsBoolean() const
Definition ExprCXX.h:2943
The base class of the type hierarchy.
Definition TypeBase.h:1833
bool isVoidType() const
Definition TypeBase.h:8891
bool isBooleanType() const
Definition TypeBase.h:9021
bool isFunctionReferenceType() const
Definition TypeBase.h:8603
bool isMFloat8Type() const
Definition TypeBase.h:8916
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2226
bool isPackedVectorBoolType(const ASTContext &ctx) const
Definition Type.cpp:419
bool isLiteralType(const ASTContext &Ctx) const
Return true if this is a literal type (C++11 [basic.types]p10)
Definition Type.cpp:2994
bool isIncompleteArrayType() const
Definition TypeBase.h:8636
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2206
bool isComplexType() const
isComplexType() does not include complex integers (a GCC extension).
Definition Type.cpp:725
const ArrayType * castAsArrayTypeUnsafe() const
A variant of castAs<> for array type which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9187
bool isUnsignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is unsigned or an enumeration types whose underlying ...
Definition Type.cpp:2274
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition Type.cpp:2116
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
bool isConstantArrayType() const
Definition TypeBase.h:8632
bool isNothrowT() const
Definition Type.cpp:3171
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition Type.h:41
bool isVoidPointerType() const
Definition Type.cpp:713
bool isConstantSizeType() const
Return true if this is not a variable sized type, according to the rules of C99 6....
Definition Type.cpp:2426
bool isArrayType() const
Definition TypeBase.h:8628
bool isFunctionPointerType() const
Definition TypeBase.h:8596
bool isPointerType() const
Definition TypeBase.h:8529
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:8935
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9178
bool isReferenceType() const
Definition TypeBase.h:8553
bool isEnumeralType() const
Definition TypeBase.h:8660
const CXXRecordDecl * getPointeeCXXRecordDecl() const
If this is a pointer or reference to a RecordType, return the CXXRecordDecl that the type refers to.
Definition Type.cpp:1910
bool isVariableArrayType() const
Definition TypeBase.h:8640
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition Type.cpp:2608
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:753
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:9009
bool isExtVectorBoolType() const
Definition TypeBase.h:8676
bool isMemberDataPointerType() const
Definition TypeBase.h:8621
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition TypeBase.h:8860
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2783
RecordDecl * castAsRecordDecl() const
Definition Type.h:48
bool isAnyComplexType() const
Definition TypeBase.h:8664
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:8947
bool isMemberPointerType() const
Definition TypeBase.h:8610
bool isAtomicType() const
Definition TypeBase.h:8717
bool isComplexIntegerType() const
Definition Type.cpp:731
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9164
bool isObjectType() const
Determine whether this type is an object type.
Definition TypeBase.h:2510
EnumDecl * getAsEnumDecl() const
Retrieves the EnumDecl this type refers to.
Definition Type.h:53
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2436
bool isFunctionType() const
Definition TypeBase.h:8525
bool isVectorType() const
Definition TypeBase.h:8668
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2321
bool isFloatingType() const
Definition Type.cpp:2305
bool isUnsignedIntegerType() const
Return true if this is an integer type that is unsigned, according to C99 6.2.5p6 [which returns true...
Definition Type.cpp:2254
const T * castAsCanonical() const
Return this type's canonical type cast to the specified type.
Definition TypeBase.h:2929
bool isAnyPointerType() const
Definition TypeBase.h:8537
TypeClass getTypeClass() const
Definition TypeBase.h:2385
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9111
bool isNullPtrType() const
Definition TypeBase.h:8928
bool isRecordType() const
Definition TypeBase.h:8656
bool isUnionType() const
Definition Type.cpp:719
bool isSizelessVectorType() const
Returns true for all scalable vector types.
Definition Type.cpp:2570
bool hasPointerRepresentation() const
Whether this type is represented natively as a pointer.
Definition TypeBase.h:9055
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand.
Definition Expr.h:2625
QualType getArgumentType() const
Definition Expr.h:2668
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:2704
QualType getTypeOfArgument() const
Gets the argument type, or the type of the argument expression, whichever is appropriate.
Definition Expr.h:2694
UnaryExprOrTypeTrait getKind() const
Definition Expr.h:2657
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2244
SourceLocation getExprLoc() const
Definition Expr.h:2368
Expr * getSubExpr() const
Definition Expr.h:2285
Opcode getOpcode() const
Definition Expr.h:2280
static bool isIncrementOp(Opcode Op)
Definition Expr.h:2326
bool canOverflow() const
Returns true if the unary operator can cause an overflow.
Definition Expr.h:2298
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:712
QualType getType() const
Definition Decl.h:723
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr.
Definition Decl.cpp:5576
QualType getType() const
Definition Value.cpp:237
bool hasValue() const
Definition Value.h:135
Represents a variable declaration or definition.
Definition Decl.h:926
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition Decl.h:1569
bool hasInit() const
Definition Decl.cpp:2409
bool hasICEInitializer(const ASTContext &Context) const
Determine whether the initializer of this variable is an integer constant expression.
Definition Decl.cpp:2647
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition Decl.h:1578
APValue * evaluateValue() const
Attempt to evaluate the value of the initializer attached to this declaration, and produce notes expl...
Definition Decl.cpp:2586
CharUnits getFlexibleArrayInitChars(const ASTContext &Ctx) const
If hasFlexibleArrayInit is true, compute the number of additional bytes necessary to store those elem...
Definition Decl.cpp:2888
bool hasConstantInitialization() const
Determine whether this variable has constant initialization.
Definition Decl.cpp:2659
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
Definition Decl.cpp:2377
bool mightBeUsableInConstantExpressions(const ASTContext &C) const
Determine whether this variable's value might be usable in a constant expression, according to the re...
Definition Decl.cpp:2497
EvaluatedStmt * ensureEvaluatedStmt() const
Convert the initializer for this declaration to the elaborated EvaluatedStmt form,...
Definition Decl.cpp:2568
bool evaluateDestruction(SmallVectorImpl< PartialDiagnosticAt > &Notes) const
Evaluate the destruction of this variable to determine if it constitutes constant destruction.
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition Decl.h:1208
ThreadStorageClassSpecifier getTSCSpec() const
Definition Decl.h:1177
const Expr * getInit() const
Definition Decl.h:1368
APValue * getEvaluatedValue() const
Return the already-evaluated value of this variable's initializer, or NULL if the value is not yet kn...
Definition Decl.cpp:2639
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition Decl.h:1184
DefinitionKind hasDefinition(ASTContext &) const
Check whether this variable is defined in this translation unit.
Definition Decl.cpp:2386
bool isLocalVarDecl() const
Returns true for local variable declarations other than parameters.
Definition Decl.h:1253
bool isUsableInConstantExpressions(const ASTContext &C) const
Determine whether this variable's value can be used in a constant expression, according to the releva...
Definition Decl.cpp:2539
const Expr * getAnyInitializer() const
Get the initializer for this variable, no matter which declaration it is attached to.
Definition Decl.h:1358
Expr * getSizeExpr() const
Definition TypeBase.h:3981
Represents a GCC generic vector type.
Definition TypeBase.h:4176
unsigned getNumElements() const
Definition TypeBase.h:4191
QualType getElementType() const
Definition TypeBase.h:4190
WhileStmt - This represents a 'while' stmt.
Definition Stmt.h:2689
Expr * getCond()
Definition Stmt.h:2741
VarDecl * getConditionVariable()
Retrieve the variable declared in this "while" statement, if any.
Definition Stmt.cpp:1242
Stmt * getBody()
Definition Stmt.h:2753
bool evaluateCharRange(State &Parent, const Expr *SizeExpr, const Expr *PtrExpr, APValue &Result)
Definition Context.cpp:226
bool evaluateString(State &Parent, const Expr *E, std::string &Result)
Evaluate.
Definition Context.cpp:242
bool evaluateStrlen(State &Parent, const Expr *E, uint64_t &Result)
Evalute.
Definition Context.cpp:288
void isPotentialConstantExprUnevaluated(State &Parent, const Expr *E, const FunctionDecl *FD)
Definition Context.cpp:59
bool isPotentialConstantExpr(State &Parent, const FunctionDecl *FD)
Checks if a function is a potential constant expression.
Definition Context.cpp:39
bool evaluateAsRValue(State &Parent, const Expr *E, APValue &Result)
Evaluates a toplevel expression as an rvalue.
Definition Context.cpp:72
bool evaluate(State &Parent, const Expr *E, APValue &Result, ConstantExprKind Kind)
Like evaluateAsRvalue(), but does no implicit lvalue-to-rvalue conversion.
Definition Context.cpp:102
Base class for stack frames, shared between VM and walker.
Definition Frame.h:25
Interface for the VM to interact with the AST walker's context.
Definition State.h:80
#define bool
Definition gpuintrin.h:32
Defines the clang::TargetInfo interface.
#define CHAR_BIT
Definition limits.h:71
#define UINT_MAX
Definition limits.h:64
bool computeOSLogBufferLayout(clang::ASTContext &Ctx, const clang::CallExpr *E, OSLogBufferLayout &layout)
Definition OSLog.cpp:192
static const FunctionDecl * getCallee(const CXXConstructExpr &D)
uint32_t Literal
Literals are represented as positive integers.
Definition CNFFormula.h:35
unsigned kind
All of the diagnostics that can be emitted by the frontend.
std::optional< llvm::AllocTokenMetadata > getAllocTokenMetadata(QualType T, const ASTContext &Ctx)
Get the information required for construction of an allocation token ID.
QualType inferPossibleType(const CallExpr *E, const ASTContext &Ctx, const CastExpr *CastE)
Infer the possible allocated type from an allocation call expression.
bool NE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1296
llvm::FixedPointSemantics FixedPointSemantics
Definition Interp.h:42
bool This(InterpState &S, CodePtr OpPC)
Definition Interp.h:2830
llvm::APFloat APFloat
Definition Floating.h:27
llvm::APInt APInt
Definition FixedPoint.h:19
bool Alloc(InterpState &S, CodePtr OpPC, const Descriptor *Desc)
Definition Interp.h:3480
std::variant< struct RequiresDecl, struct HeaderDecl, struct UmbrellaDirDecl, struct ModuleDecl, struct ExcludeDecl, struct ExportDecl, struct ExportAsDecl, struct ExternModuleDecl, struct UseDecl, struct LinkDecl, struct ConfigMacrosDecl, struct ConflictDecl > Decl
All declarations that can appear in a module declaration.
AccessKind
This enum distinguishes between different ways to access (read or write) a variable.
ASTEdit note(RangeSelector Anchor, TextGenerator Note)
Generates a single, no-op edit with the associated note anchored at the start location of the specifi...
The JSON file list parser is used to communicate input to InstallAPI.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
bool isa(CodeGen::Address addr)
Definition Address.h:330
bool hasSpecificAttr(const Container &container)
@ NonNull
Values of this type can never be null.
Definition Specifiers.h:350
@ Success
Annotation was successful.
Definition Parser.h:65
Expr::ConstantExprKind ConstantExprKind
Definition Expr.h:1042
@ Self
'self' clause, allowed on Compute and Combined Constructs, plus 'update'.
bool operator==(const CallGraphNode::CallRecord &LHS, const CallGraphNode::CallRecord &RHS)
Definition CallGraph.h:206
@ AS_public
Definition Specifiers.h:124
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
bool isLambdaCallWithExplicitObjectParameter(const DeclContext *DC)
Definition ASTLambda.h:45
@ TSCS_unspecified
Definition Specifiers.h:236
Expr * Cond
};
UnaryExprOrTypeTrait
Names for the "expression or type" traits.
Definition TypeTraits.h:51
ComparisonCategoryResult
An enumeration representing the possible results of a three-way comparison.
CheckSubobjectKind
The order of this enum is important for diagnostics.
Definition State.h:43
@ CSK_ArrayToPointer
Definition State.h:47
@ CSK_Derived
Definition State.h:45
@ CSK_Base
Definition State.h:44
@ CSK_Real
Definition State.h:49
@ CSK_ArrayIndex
Definition State.h:48
@ CSK_Imag
Definition State.h:50
@ CSK_VectorElement
Definition State.h:51
@ CSK_Field
Definition State.h:46
@ SD_Static
Static storage duration.
Definition Specifiers.h:343
@ SD_FullExpression
Full-expression storage duration (for temporaries).
Definition Specifiers.h:340
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition ASTLambda.h:28
@ Result
The result type of a method or function.
Definition TypeBase.h:905
AccessKinds
Kinds of access we can perform on an object, for diagnostics.
Definition State.h:27
@ AK_TypeId
Definition State.h:35
@ AK_Construct
Definition State.h:36
@ AK_Increment
Definition State.h:31
@ AK_DynamicCast
Definition State.h:34
@ AK_Read
Definition State.h:28
@ AK_Assign
Definition State.h:30
@ AK_IsWithinLifetime
Definition State.h:38
@ AK_MemberCall
Definition State.h:33
@ AK_ReadObjectRepresentation
Definition State.h:29
@ AK_Dereference
Definition State.h:39
@ AK_Destroy
Definition State.h:37
@ AK_Decrement
Definition State.h:32
const FunctionProtoType * T
@ Type
The name was classified as a type.
Definition Sema.h:564
CastKind
CastKind - The kind of operation required for a conversion.
llvm::hash_code hash_value(const CustomizableOptional< T > &O)
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:135
EvaluationMode
Definition State.h:54
@ ConstantFold
Fold the expression to a constant.
Definition State.h:68
@ ConstantExpressionUnevaluated
Evaluate as a constant expression.
Definition State.h:64
@ ConstantExpression
Evaluate as a constant expression.
Definition State.h:57
@ IgnoreSideEffects
Evaluate in any way we know how.
Definition State.h:72
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition DeclBase.h:1288
U cast(CodeGen::Address addr)
Definition Address.h:327
@ None
The alignment was not explicit in code.
Definition ASTContext.h:178
@ ArrayBound
Array bound in array declarator or new-expression.
Definition Sema.h:832
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5879
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ Other
Other implicit parameter.
Definition Decl.h:1746
ActionResult< Stmt * > StmtResult
Definition Ownership.h:250
unsigned long uint64_t
long int64_t
unsigned int uint32_t
Diagnostic wrappers for TextAPI types for error reporting.
Definition Dominators.h:30
hash_code hash_value(const clang::dependencies::ModuleID &ID)
#define false
Definition stdbool.h:26
unsigned PathLength
The corresponding path length in the lvalue.
const CXXRecordDecl * Type
The dynamic class type of the object.
std::string ObjCEncodeStorage
Represents an element in a path from a derived class to a base class.
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:645
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:647
bool isGlobalLValue() const
Return true if the evaluated lvalue expression is global.
EvalStatus is a struct with detailed info about an evaluation in progress.
Definition Expr.h:609
SmallVectorImpl< PartialDiagnosticAt > * Diag
Diag - If this is non-null, it will be filled in with a stack of notes indicating why evaluation fail...
Definition Expr.h:633
bool HasSideEffects
Whether the evaluated expression has side effects.
Definition Expr.h:612
static ObjectUnderConstruction getTombstoneKey()
DenseMapInfo< APValue::LValueBase > Base
static ObjectUnderConstruction getEmptyKey()
static unsigned getHashValue(const ObjectUnderConstruction &Object)
static bool isEqual(const ObjectUnderConstruction &LHS, const ObjectUnderConstruction &RHS)
#define ilogb(__x)
Definition tgmath.h:851
#define scalbn(__x, __y)
Definition tgmath.h:1165