clang 22.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 unsigned ArgIndex = 0;
1977 bool IsMemberCall =
1978 isa<CXXMethodDecl>(Callee) && !isa<CXXConstructorDecl>(Callee) &&
1979 cast<CXXMethodDecl>(Callee)->isImplicitObjectMemberFunction();
1980
1981 if (!IsMemberCall)
1982 Callee->getNameForDiagnostic(Out, Info.Ctx.getPrintingPolicy(),
1983 /*Qualified=*/false);
1984
1985 if (This && IsMemberCall) {
1986 if (const auto *MCE = dyn_cast_if_present<CXXMemberCallExpr>(CallExpr)) {
1987 const Expr *Object = MCE->getImplicitObjectArgument();
1988 Object->printPretty(Out, /*Helper=*/nullptr, Info.Ctx.getPrintingPolicy(),
1989 /*Indentation=*/0);
1990 if (Object->getType()->isPointerType())
1991 Out << "->";
1992 else
1993 Out << ".";
1994 } else if (const auto *OCE =
1995 dyn_cast_if_present<CXXOperatorCallExpr>(CallExpr)) {
1996 OCE->getArg(0)->printPretty(Out, /*Helper=*/nullptr,
1997 Info.Ctx.getPrintingPolicy(),
1998 /*Indentation=*/0);
1999 Out << ".";
2000 } else {
2001 APValue Val;
2002 This->moveInto(Val);
2003 Val.printPretty(
2004 Out, Info.Ctx,
2005 Info.Ctx.getLValueReferenceType(This->Designator.MostDerivedType));
2006 Out << ".";
2007 }
2008 Callee->getNameForDiagnostic(Out, Info.Ctx.getPrintingPolicy(),
2009 /*Qualified=*/false);
2010 IsMemberCall = false;
2011 }
2012
2013 Out << '(';
2014
2015 for (FunctionDecl::param_const_iterator I = Callee->param_begin(),
2016 E = Callee->param_end(); I != E; ++I, ++ArgIndex) {
2017 if (ArgIndex > (unsigned)IsMemberCall)
2018 Out << ", ";
2019
2020 const ParmVarDecl *Param = *I;
2021 APValue *V = Info.getParamSlot(Arguments, Param);
2022 if (V)
2023 V->printPretty(Out, Info.Ctx, Param->getType());
2024 else
2025 Out << "<...>";
2026
2027 if (ArgIndex == 0 && IsMemberCall)
2028 Out << "->" << *Callee << '(';
2029 }
2030
2031 Out << ')';
2032}
2033
2034/// Evaluate an expression to see if it had side-effects, and discard its
2035/// result.
2036/// \return \c true if the caller should keep evaluating.
2037static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
2038 assert(!E->isValueDependent());
2039 APValue Scratch;
2040 if (!Evaluate(Scratch, Info, E))
2041 // We don't need the value, but we might have skipped a side effect here.
2042 return Info.noteSideEffect();
2043 return true;
2044}
2045
2046/// Should this call expression be treated as forming an opaque constant?
2047static bool IsOpaqueConstantCall(const CallExpr *E) {
2048 unsigned Builtin = E->getBuiltinCallee();
2049 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
2050 Builtin == Builtin::BI__builtin___NSStringMakeConstantString ||
2051 Builtin == Builtin::BI__builtin_ptrauth_sign_constant ||
2052 Builtin == Builtin::BI__builtin_function_start);
2053}
2054
2055static bool IsOpaqueConstantCall(const LValue &LVal) {
2056 const auto *BaseExpr =
2057 llvm::dyn_cast_if_present<CallExpr>(LVal.Base.dyn_cast<const Expr *>());
2058 return BaseExpr && IsOpaqueConstantCall(BaseExpr);
2059}
2060
2062 // C++11 [expr.const]p3 An address constant expression is a prvalue core
2063 // constant expression of pointer type that evaluates to...
2064
2065 // ... a null pointer value, or a prvalue core constant expression of type
2066 // std::nullptr_t.
2067 if (!B)
2068 return true;
2069
2070 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
2071 // ... the address of an object with static storage duration,
2072 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
2073 return VD->hasGlobalStorage();
2075 return true;
2076 // ... the address of a function,
2077 // ... the address of a GUID [MS extension],
2078 // ... the address of an unnamed global constant
2080 }
2081
2082 if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>())
2083 return true;
2084
2085 const Expr *E = B.get<const Expr*>();
2086 switch (E->getStmtClass()) {
2087 default:
2088 return false;
2089 case Expr::CompoundLiteralExprClass: {
2091 return CLE->isFileScope() && CLE->isLValue();
2092 }
2093 case Expr::MaterializeTemporaryExprClass:
2094 // A materialized temporary might have been lifetime-extended to static
2095 // storage duration.
2096 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
2097 // A string literal has static storage duration.
2098 case Expr::StringLiteralClass:
2099 case Expr::PredefinedExprClass:
2100 case Expr::ObjCStringLiteralClass:
2101 case Expr::ObjCEncodeExprClass:
2102 return true;
2103 case Expr::ObjCBoxedExprClass:
2104 return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
2105 case Expr::CallExprClass:
2107 // For GCC compatibility, &&label has static storage duration.
2108 case Expr::AddrLabelExprClass:
2109 return true;
2110 // A Block literal expression may be used as the initialization value for
2111 // Block variables at global or local static scope.
2112 case Expr::BlockExprClass:
2113 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
2114 // The APValue generated from a __builtin_source_location will be emitted as a
2115 // literal.
2116 case Expr::SourceLocExprClass:
2117 return true;
2118 case Expr::ImplicitValueInitExprClass:
2119 // FIXME:
2120 // We can never form an lvalue with an implicit value initialization as its
2121 // base through expression evaluation, so these only appear in one case: the
2122 // implicit variable declaration we invent when checking whether a constexpr
2123 // constructor can produce a constant expression. We must assume that such
2124 // an expression might be a global lvalue.
2125 return true;
2126 }
2127}
2128
2129static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
2130 return LVal.Base.dyn_cast<const ValueDecl*>();
2131}
2132
2133// Information about an LValueBase that is some kind of string.
2136 StringRef Bytes;
2138};
2139
2140// Gets the lvalue base of LVal as a string.
2141static bool GetLValueBaseAsString(const EvalInfo &Info, const LValue &LVal,
2142 LValueBaseString &AsString) {
2143 const auto *BaseExpr = LVal.Base.dyn_cast<const Expr *>();
2144 if (!BaseExpr)
2145 return false;
2146
2147 // For ObjCEncodeExpr, we need to compute and store the string.
2148 if (const auto *EE = dyn_cast<ObjCEncodeExpr>(BaseExpr)) {
2149 Info.Ctx.getObjCEncodingForType(EE->getEncodedType(),
2150 AsString.ObjCEncodeStorage);
2151 AsString.Bytes = AsString.ObjCEncodeStorage;
2152 AsString.CharWidth = 1;
2153 return true;
2154 }
2155
2156 // Otherwise, we have a StringLiteral.
2157 const auto *Lit = dyn_cast<StringLiteral>(BaseExpr);
2158 if (const auto *PE = dyn_cast<PredefinedExpr>(BaseExpr))
2159 Lit = PE->getFunctionName();
2160
2161 if (!Lit)
2162 return false;
2163
2164 AsString.Bytes = Lit->getBytes();
2165 AsString.CharWidth = Lit->getCharByteWidth();
2166 return true;
2167}
2168
2169// Determine whether two string literals potentially overlap. This will be the
2170// case if they agree on the values of all the bytes on the overlapping region
2171// between them.
2172//
2173// The overlapping region is the portion of the two string literals that must
2174// overlap in memory if the pointers actually point to the same address at
2175// runtime. For example, if LHS is "abcdef" + 3 and RHS is "cdef\0gh" + 1 then
2176// the overlapping region is "cdef\0", which in this case does agree, so the
2177// strings are potentially overlapping. Conversely, for "foobar" + 3 versus
2178// "bazbar" + 3, the overlapping region contains all of both strings, so they
2179// are not potentially overlapping, even though they agree from the given
2180// addresses onwards.
2181//
2182// See open core issue CWG2765 which is discussing the desired rule here.
2183static bool ArePotentiallyOverlappingStringLiterals(const EvalInfo &Info,
2184 const LValue &LHS,
2185 const LValue &RHS) {
2186 LValueBaseString LHSString, RHSString;
2187 if (!GetLValueBaseAsString(Info, LHS, LHSString) ||
2188 !GetLValueBaseAsString(Info, RHS, RHSString))
2189 return false;
2190
2191 // This is the byte offset to the location of the first character of LHS
2192 // within RHS. We don't need to look at the characters of one string that
2193 // would appear before the start of the other string if they were merged.
2194 CharUnits Offset = RHS.Offset - LHS.Offset;
2195 if (Offset.isNegative()) {
2196 if (LHSString.Bytes.size() < (size_t)-Offset.getQuantity())
2197 return false;
2198 LHSString.Bytes = LHSString.Bytes.drop_front(-Offset.getQuantity());
2199 } else {
2200 if (RHSString.Bytes.size() < (size_t)Offset.getQuantity())
2201 return false;
2202 RHSString.Bytes = RHSString.Bytes.drop_front(Offset.getQuantity());
2203 }
2204
2205 bool LHSIsLonger = LHSString.Bytes.size() > RHSString.Bytes.size();
2206 StringRef Longer = LHSIsLonger ? LHSString.Bytes : RHSString.Bytes;
2207 StringRef Shorter = LHSIsLonger ? RHSString.Bytes : LHSString.Bytes;
2208 int ShorterCharWidth = (LHSIsLonger ? RHSString : LHSString).CharWidth;
2209
2210 // The null terminator isn't included in the string data, so check for it
2211 // manually. If the longer string doesn't have a null terminator where the
2212 // shorter string ends, they aren't potentially overlapping.
2213 for (int NullByte : llvm::seq(ShorterCharWidth)) {
2214 if (Shorter.size() + NullByte >= Longer.size())
2215 break;
2216 if (Longer[Shorter.size() + NullByte])
2217 return false;
2218 }
2219
2220 // Otherwise, they're potentially overlapping if and only if the overlapping
2221 // region is the same.
2222 return Shorter == Longer.take_front(Shorter.size());
2223}
2224
2225static bool IsWeakLValue(const LValue &Value) {
2227 return Decl && Decl->isWeak();
2228}
2229
2230static bool isZeroSized(const LValue &Value) {
2232 if (isa_and_nonnull<VarDecl>(Decl)) {
2233 QualType Ty = Decl->getType();
2234 if (Ty->isArrayType())
2235 return Ty->isIncompleteType() ||
2236 Decl->getASTContext().getTypeSize(Ty) == 0;
2237 }
2238 return false;
2239}
2240
2241static bool HasSameBase(const LValue &A, const LValue &B) {
2242 if (!A.getLValueBase())
2243 return !B.getLValueBase();
2244 if (!B.getLValueBase())
2245 return false;
2246
2247 if (A.getLValueBase().getOpaqueValue() !=
2248 B.getLValueBase().getOpaqueValue())
2249 return false;
2250
2251 return A.getLValueCallIndex() == B.getLValueCallIndex() &&
2252 A.getLValueVersion() == B.getLValueVersion();
2253}
2254
2255static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
2256 assert(Base && "no location for a null lvalue");
2257 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2258
2259 // For a parameter, find the corresponding call stack frame (if it still
2260 // exists), and point at the parameter of the function definition we actually
2261 // invoked.
2262 if (auto *PVD = dyn_cast_or_null<ParmVarDecl>(VD)) {
2263 unsigned Idx = PVD->getFunctionScopeIndex();
2264 for (CallStackFrame *F = Info.CurrentCall; F; F = F->Caller) {
2265 if (F->Arguments.CallIndex == Base.getCallIndex() &&
2266 F->Arguments.Version == Base.getVersion() && F->Callee &&
2267 Idx < F->Callee->getNumParams()) {
2268 VD = F->Callee->getParamDecl(Idx);
2269 break;
2270 }
2271 }
2272 }
2273
2274 if (VD)
2275 Info.Note(VD->getLocation(), diag::note_declared_at);
2276 else if (const Expr *E = Base.dyn_cast<const Expr*>())
2277 Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
2278 else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
2279 // FIXME: Produce a note for dangling pointers too.
2280 if (std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA))
2281 Info.Note((*Alloc)->AllocExpr->getExprLoc(),
2282 diag::note_constexpr_dynamic_alloc_here);
2283 }
2284
2285 // We have no information to show for a typeid(T) object.
2286}
2287
2292
2293/// Materialized temporaries that we've already checked to determine if they're
2294/// initializsed by a constant expression.
2297
2299 EvalInfo &Info, SourceLocation DiagLoc,
2300 QualType Type, const APValue &Value,
2301 ConstantExprKind Kind,
2302 const FieldDecl *SubobjectDecl,
2303 CheckedTemporaries &CheckedTemps);
2304
2305/// Check that this reference or pointer core constant expression is a valid
2306/// value for an address or reference constant expression. Return true if we
2307/// can fold this expression, whether or not it's a constant expression.
2308static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
2309 QualType Type, const LValue &LVal,
2310 ConstantExprKind Kind,
2311 CheckedTemporaries &CheckedTemps) {
2312 bool IsReferenceType = Type->isReferenceType();
2313
2314 APValue::LValueBase Base = LVal.getLValueBase();
2315 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
2316
2317 const Expr *BaseE = Base.dyn_cast<const Expr *>();
2318 const ValueDecl *BaseVD = Base.dyn_cast<const ValueDecl*>();
2319
2320 // Additional restrictions apply in a template argument. We only enforce the
2321 // C++20 restrictions here; additional syntactic and semantic restrictions
2322 // are applied elsewhere.
2323 if (isTemplateArgument(Kind)) {
2324 int InvalidBaseKind = -1;
2325 StringRef Ident;
2326 if (Base.is<TypeInfoLValue>())
2327 InvalidBaseKind = 0;
2328 else if (isa_and_nonnull<StringLiteral>(BaseE))
2329 InvalidBaseKind = 1;
2330 else if (isa_and_nonnull<MaterializeTemporaryExpr>(BaseE) ||
2331 isa_and_nonnull<LifetimeExtendedTemporaryDecl>(BaseVD))
2332 InvalidBaseKind = 2;
2333 else if (auto *PE = dyn_cast_or_null<PredefinedExpr>(BaseE)) {
2334 InvalidBaseKind = 3;
2335 Ident = PE->getIdentKindName();
2336 }
2337
2338 if (InvalidBaseKind != -1) {
2339 Info.FFDiag(Loc, diag::note_constexpr_invalid_template_arg)
2340 << IsReferenceType << !Designator.Entries.empty() << InvalidBaseKind
2341 << Ident;
2342 return false;
2343 }
2344 }
2345
2346 if (auto *FD = dyn_cast_or_null<FunctionDecl>(BaseVD);
2347 FD && FD->isImmediateFunction()) {
2348 Info.FFDiag(Loc, diag::note_consteval_address_accessible)
2349 << !Type->isAnyPointerType();
2350 Info.Note(FD->getLocation(), diag::note_declared_at);
2351 return false;
2352 }
2353
2354 // Check that the object is a global. Note that the fake 'this' object we
2355 // manufacture when checking potential constant expressions is conservatively
2356 // assumed to be global here.
2357 if (!IsGlobalLValue(Base)) {
2358 if (Info.getLangOpts().CPlusPlus11) {
2359 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
2360 << IsReferenceType << !Designator.Entries.empty() << !!BaseVD
2361 << BaseVD;
2362 auto *VarD = dyn_cast_or_null<VarDecl>(BaseVD);
2363 if (VarD && VarD->isConstexpr()) {
2364 // Non-static local constexpr variables have unintuitive semantics:
2365 // constexpr int a = 1;
2366 // constexpr const int *p = &a;
2367 // ... is invalid because the address of 'a' is not constant. Suggest
2368 // adding a 'static' in this case.
2369 Info.Note(VarD->getLocation(), diag::note_constexpr_not_static)
2370 << VarD
2371 << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static ");
2372 } else {
2373 NoteLValueLocation(Info, Base);
2374 }
2375 } else {
2376 Info.FFDiag(Loc);
2377 }
2378 // Don't allow references to temporaries to escape.
2379 return false;
2380 }
2381 assert((Info.checkingPotentialConstantExpression() ||
2382 LVal.getLValueCallIndex() == 0) &&
2383 "have call index for global lvalue");
2384
2385 if (LVal.allowConstexprUnknown()) {
2386 if (BaseVD) {
2387 Info.FFDiag(Loc, diag::note_constexpr_var_init_non_constant, 1) << BaseVD;
2388 NoteLValueLocation(Info, Base);
2389 } else {
2390 Info.FFDiag(Loc);
2391 }
2392 return false;
2393 }
2394
2395 if (Base.is<DynamicAllocLValue>()) {
2396 Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc)
2397 << IsReferenceType << !Designator.Entries.empty();
2398 NoteLValueLocation(Info, Base);
2399 return false;
2400 }
2401
2402 if (BaseVD) {
2403 if (const VarDecl *Var = dyn_cast<const VarDecl>(BaseVD)) {
2404 // Check if this is a thread-local variable.
2405 if (Var->getTLSKind())
2406 // FIXME: Diagnostic!
2407 return false;
2408
2409 // A dllimport variable never acts like a constant, unless we're
2410 // evaluating a value for use only in name mangling.
2411 if (!isForManglingOnly(Kind) && Var->hasAttr<DLLImportAttr>())
2412 // FIXME: Diagnostic!
2413 return false;
2414
2415 // In CUDA/HIP device compilation, only device side variables have
2416 // constant addresses.
2417 if (Info.getASTContext().getLangOpts().CUDA &&
2418 Info.getASTContext().getLangOpts().CUDAIsDevice &&
2419 Info.getASTContext().CUDAConstantEvalCtx.NoWrongSidedVars) {
2420 if ((!Var->hasAttr<CUDADeviceAttr>() &&
2421 !Var->hasAttr<CUDAConstantAttr>() &&
2422 !Var->getType()->isCUDADeviceBuiltinSurfaceType() &&
2423 !Var->getType()->isCUDADeviceBuiltinTextureType()) ||
2424 Var->hasAttr<HIPManagedAttr>())
2425 return false;
2426 }
2427 }
2428 if (const auto *FD = dyn_cast<const FunctionDecl>(BaseVD)) {
2429 // __declspec(dllimport) must be handled very carefully:
2430 // We must never initialize an expression with the thunk in C++.
2431 // Doing otherwise would allow the same id-expression to yield
2432 // different addresses for the same function in different translation
2433 // units. However, this means that we must dynamically initialize the
2434 // expression with the contents of the import address table at runtime.
2435 //
2436 // The C language has no notion of ODR; furthermore, it has no notion of
2437 // dynamic initialization. This means that we are permitted to
2438 // perform initialization with the address of the thunk.
2439 if (Info.getLangOpts().CPlusPlus && !isForManglingOnly(Kind) &&
2440 FD->hasAttr<DLLImportAttr>())
2441 // FIXME: Diagnostic!
2442 return false;
2443 }
2444 } else if (const auto *MTE =
2445 dyn_cast_or_null<MaterializeTemporaryExpr>(BaseE)) {
2446 if (CheckedTemps.insert(MTE).second) {
2447 QualType TempType = getType(Base);
2448 if (TempType.isDestructedType()) {
2449 Info.FFDiag(MTE->getExprLoc(),
2450 diag::note_constexpr_unsupported_temporary_nontrivial_dtor)
2451 << TempType;
2452 return false;
2453 }
2454
2455 APValue *V = MTE->getOrCreateValue(false);
2456 assert(V && "evasluation result refers to uninitialised temporary");
2458 Info, MTE->getExprLoc(), TempType, *V, Kind,
2459 /*SubobjectDecl=*/nullptr, CheckedTemps))
2460 return false;
2461 }
2462 }
2463
2464 // Allow address constant expressions to be past-the-end pointers. This is
2465 // an extension: the standard requires them to point to an object.
2466 if (!IsReferenceType)
2467 return true;
2468
2469 // A reference constant expression must refer to an object.
2470 if (!Base) {
2471 // FIXME: diagnostic
2472 Info.CCEDiag(Loc);
2473 return true;
2474 }
2475
2476 // Does this refer one past the end of some object?
2477 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
2478 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
2479 << !Designator.Entries.empty() << !!BaseVD << BaseVD;
2480 NoteLValueLocation(Info, Base);
2481 }
2482
2483 return true;
2484}
2485
2486/// Member pointers are constant expressions unless they point to a
2487/// non-virtual dllimport member function.
2488static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
2489 SourceLocation Loc,
2490 QualType Type,
2491 const APValue &Value,
2492 ConstantExprKind Kind) {
2493 const ValueDecl *Member = Value.getMemberPointerDecl();
2494 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
2495 if (!FD)
2496 return true;
2497 if (FD->isImmediateFunction()) {
2498 Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0;
2499 Info.Note(FD->getLocation(), diag::note_declared_at);
2500 return false;
2501 }
2502 return isForManglingOnly(Kind) || FD->isVirtual() ||
2503 !FD->hasAttr<DLLImportAttr>();
2504}
2505
2506/// Check that this core constant expression is of literal type, and if not,
2507/// produce an appropriate diagnostic.
2508static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
2509 const LValue *This = nullptr) {
2510 // The restriction to literal types does not exist in C++23 anymore.
2511 if (Info.getLangOpts().CPlusPlus23)
2512 return true;
2513
2514 if (!E->isPRValue() || E->getType()->isLiteralType(Info.Ctx))
2515 return true;
2516
2517 // C++1y: A constant initializer for an object o [...] may also invoke
2518 // constexpr constructors for o and its subobjects even if those objects
2519 // are of non-literal class types.
2520 //
2521 // C++11 missed this detail for aggregates, so classes like this:
2522 // struct foo_t { union { int i; volatile int j; } u; };
2523 // are not (obviously) initializable like so:
2524 // __attribute__((__require_constant_initialization__))
2525 // static const foo_t x = {{0}};
2526 // because "i" is a subobject with non-literal initialization (due to the
2527 // volatile member of the union). See:
2528 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2529 // Therefore, we use the C++1y behavior.
2530 if (This && Info.EvaluatingDecl == This->getLValueBase())
2531 return true;
2532
2533 // Prvalue constant expressions must be of literal types.
2534 if (Info.getLangOpts().CPlusPlus11)
2535 Info.FFDiag(E, diag::note_constexpr_nonliteral)
2536 << E->getType();
2537 else
2538 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2539 return false;
2540}
2541
2543 EvalInfo &Info, SourceLocation DiagLoc,
2544 QualType Type, const APValue &Value,
2545 ConstantExprKind Kind,
2546 const FieldDecl *SubobjectDecl,
2547 CheckedTemporaries &CheckedTemps) {
2548 if (!Value.hasValue()) {
2549 if (SubobjectDecl) {
2550 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2551 << /*(name)*/ 1 << SubobjectDecl;
2552 Info.Note(SubobjectDecl->getLocation(),
2553 diag::note_constexpr_subobject_declared_here);
2554 } else {
2555 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2556 << /*of type*/ 0 << Type;
2557 }
2558 return false;
2559 }
2560
2561 // We allow _Atomic(T) to be initialized from anything that T can be
2562 // initialized from.
2563 if (const AtomicType *AT = Type->getAs<AtomicType>())
2564 Type = AT->getValueType();
2565
2566 // Core issue 1454: For a literal constant expression of array or class type,
2567 // each subobject of its value shall have been initialized by a constant
2568 // expression.
2569 if (Value.isArray()) {
2571 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
2572 if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2573 Value.getArrayInitializedElt(I), Kind,
2574 SubobjectDecl, CheckedTemps))
2575 return false;
2576 }
2577 if (!Value.hasArrayFiller())
2578 return true;
2579 return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2580 Value.getArrayFiller(), Kind, SubobjectDecl,
2581 CheckedTemps);
2582 }
2583 if (Value.isUnion() && Value.getUnionField()) {
2584 return CheckEvaluationResult(
2585 CERK, Info, DiagLoc, Value.getUnionField()->getType(),
2586 Value.getUnionValue(), Kind, Value.getUnionField(), CheckedTemps);
2587 }
2588 if (Value.isStruct()) {
2589 auto *RD = Type->castAsRecordDecl();
2590 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2591 unsigned BaseIndex = 0;
2592 for (const CXXBaseSpecifier &BS : CD->bases()) {
2593 const APValue &BaseValue = Value.getStructBase(BaseIndex);
2594 if (!BaseValue.hasValue()) {
2595 SourceLocation TypeBeginLoc = BS.getBaseTypeLoc();
2596 Info.FFDiag(TypeBeginLoc, diag::note_constexpr_uninitialized_base)
2597 << BS.getType() << SourceRange(TypeBeginLoc, BS.getEndLoc());
2598 return false;
2599 }
2600 if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(), BaseValue,
2601 Kind, /*SubobjectDecl=*/nullptr,
2602 CheckedTemps))
2603 return false;
2604 ++BaseIndex;
2605 }
2606 }
2607 for (const auto *I : RD->fields()) {
2608 if (I->isUnnamedBitField())
2609 continue;
2610
2611 if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),
2612 Value.getStructField(I->getFieldIndex()), Kind,
2613 I, CheckedTemps))
2614 return false;
2615 }
2616 }
2617
2618 if (Value.isLValue() &&
2620 LValue LVal;
2621 LVal.setFrom(Info.Ctx, Value);
2622 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Kind,
2623 CheckedTemps);
2624 }
2625
2626 if (Value.isMemberPointer() &&
2628 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Kind);
2629
2630 // Everything else is fine.
2631 return true;
2632}
2633
2634/// Check that this core constant expression value is a valid value for a
2635/// constant expression. If not, report an appropriate diagnostic. Does not
2636/// check that the expression is of literal type.
2637static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
2638 QualType Type, const APValue &Value,
2639 ConstantExprKind Kind) {
2640 // Nothing to check for a constant expression of type 'cv void'.
2641 if (Type->isVoidType())
2642 return true;
2643
2644 CheckedTemporaries CheckedTemps;
2646 Info, DiagLoc, Type, Value, Kind,
2647 /*SubobjectDecl=*/nullptr, CheckedTemps);
2648}
2649
2650/// Check that this evaluated value is fully-initialized and can be loaded by
2651/// an lvalue-to-rvalue conversion.
2652static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,
2653 QualType Type, const APValue &Value) {
2654 CheckedTemporaries CheckedTemps;
2655 return CheckEvaluationResult(
2657 ConstantExprKind::Normal, /*SubobjectDecl=*/nullptr, CheckedTemps);
2658}
2659
2660/// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless
2661/// "the allocated storage is deallocated within the evaluation".
2662static bool CheckMemoryLeaks(EvalInfo &Info) {
2663 if (!Info.HeapAllocs.empty()) {
2664 // We can still fold to a constant despite a compile-time memory leak,
2665 // so long as the heap allocation isn't referenced in the result (we check
2666 // that in CheckConstantExpression).
2667 Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr,
2668 diag::note_constexpr_memory_leak)
2669 << unsigned(Info.HeapAllocs.size() - 1);
2670 }
2671 return true;
2672}
2673
2674static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
2675 // A null base expression indicates a null pointer. These are always
2676 // evaluatable, and they are false unless the offset is zero.
2677 if (!Value.getLValueBase()) {
2678 // TODO: Should a non-null pointer with an offset of zero evaluate to true?
2679 Result = !Value.getLValueOffset().isZero();
2680 return true;
2681 }
2682
2683 // We have a non-null base. These are generally known to be true, but if it's
2684 // a weak declaration it can be null at runtime.
2685 Result = true;
2686 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
2687 return !Decl || !Decl->isWeak();
2688}
2689
2690static bool HandleConversionToBool(const APValue &Val, bool &Result) {
2691 // TODO: This function should produce notes if it fails.
2692 switch (Val.getKind()) {
2693 case APValue::None:
2695 return false;
2696 case APValue::Int:
2697 Result = Val.getInt().getBoolValue();
2698 return true;
2700 Result = Val.getFixedPoint().getBoolValue();
2701 return true;
2702 case APValue::Float:
2703 Result = !Val.getFloat().isZero();
2704 return true;
2706 Result = Val.getComplexIntReal().getBoolValue() ||
2707 Val.getComplexIntImag().getBoolValue();
2708 return true;
2710 Result = !Val.getComplexFloatReal().isZero() ||
2711 !Val.getComplexFloatImag().isZero();
2712 return true;
2713 case APValue::LValue:
2714 return EvalPointerValueAsBool(Val, Result);
2716 if (Val.getMemberPointerDecl() && Val.getMemberPointerDecl()->isWeak()) {
2717 return false;
2718 }
2719 Result = Val.getMemberPointerDecl();
2720 return true;
2721 case APValue::Vector:
2722 case APValue::Array:
2723 case APValue::Struct:
2724 case APValue::Union:
2726 return false;
2727 }
2728
2729 llvm_unreachable("unknown APValue kind");
2730}
2731
2732static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2733 EvalInfo &Info) {
2734 assert(!E->isValueDependent());
2735 assert(E->isPRValue() && "missing lvalue-to-rvalue conv in bool condition");
2736 APValue Val;
2737 if (!Evaluate(Val, Info, E))
2738 return false;
2739 return HandleConversionToBool(Val, Result);
2740}
2741
2742template<typename T>
2743static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2744 const T &SrcValue, QualType DestType) {
2745 Info.CCEDiag(E, diag::note_constexpr_overflow)
2746 << SrcValue << DestType;
2747 return Info.noteUndefinedBehavior();
2748}
2749
2750static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2751 QualType SrcType, const APFloat &Value,
2752 QualType DestType, APSInt &Result) {
2753 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2754 // Determine whether we are converting to unsigned or signed.
2755 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2756
2757 Result = APSInt(DestWidth, !DestSigned);
2758 bool ignored;
2759 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2760 & APFloat::opInvalidOp)
2761 return HandleOverflow(Info, E, Value, DestType);
2762 return true;
2763}
2764
2765/// Get rounding mode to use in evaluation of the specified expression.
2766///
2767/// If rounding mode is unknown at compile time, still try to evaluate the
2768/// expression. If the result is exact, it does not depend on rounding mode.
2769/// So return "tonearest" mode instead of "dynamic".
2770static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E) {
2771 llvm::RoundingMode RM =
2773 if (RM == llvm::RoundingMode::Dynamic)
2774 RM = llvm::RoundingMode::NearestTiesToEven;
2775 return RM;
2776}
2777
2778/// Check if the given evaluation result is allowed for constant evaluation.
2779static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E,
2780 APFloat::opStatus St) {
2781 // In a constant context, assume that any dynamic rounding mode or FP
2782 // exception state matches the default floating-point environment.
2783 if (Info.InConstantContext)
2784 return true;
2785
2786 FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
2787 if ((St & APFloat::opInexact) &&
2788 FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) {
2789 // Inexact result means that it depends on rounding mode. If the requested
2790 // mode is dynamic, the evaluation cannot be made in compile time.
2791 Info.FFDiag(E, diag::note_constexpr_dynamic_rounding);
2792 return false;
2793 }
2794
2795 if ((St != APFloat::opOK) &&
2796 (FPO.getRoundingMode() == llvm::RoundingMode::Dynamic ||
2798 FPO.getAllowFEnvAccess())) {
2799 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
2800 return false;
2801 }
2802
2803 if ((St & APFloat::opStatus::opInvalidOp) &&
2805 // There is no usefully definable result.
2806 Info.FFDiag(E);
2807 return false;
2808 }
2809
2810 // FIXME: if:
2811 // - evaluation triggered other FP exception, and
2812 // - exception mode is not "ignore", and
2813 // - the expression being evaluated is not a part of global variable
2814 // initializer,
2815 // the evaluation probably need to be rejected.
2816 return true;
2817}
2818
2819static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2820 QualType SrcType, QualType DestType,
2821 APFloat &Result) {
2822 assert((isa<CastExpr>(E) || isa<CompoundAssignOperator>(E) ||
2824 "HandleFloatToFloatCast has been checked with only CastExpr, "
2825 "CompoundAssignOperator and ConvertVectorExpr. Please either validate "
2826 "the new expression or address the root cause of this usage.");
2827 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2828 APFloat::opStatus St;
2829 APFloat Value = Result;
2830 bool ignored;
2831 St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored);
2832 return checkFloatingPointResult(Info, E, St);
2833}
2834
2835static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2836 QualType DestType, QualType SrcType,
2837 const APSInt &Value) {
2838 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2839 // Figure out if this is a truncate, extend or noop cast.
2840 // If the input is signed, do a sign extend, noop, or truncate.
2841 APSInt Result = Value.extOrTrunc(DestWidth);
2842 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2843 if (DestType->isBooleanType())
2844 Result = Value.getBoolValue();
2845 return Result;
2846}
2847
2848static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2849 const FPOptions FPO,
2850 QualType SrcType, const APSInt &Value,
2851 QualType DestType, APFloat &Result) {
2852 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2853 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2854 APFloat::opStatus St = Result.convertFromAPInt(Value, Value.isSigned(), RM);
2855 return checkFloatingPointResult(Info, E, St);
2856}
2857
2858static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2859 APValue &Value, const FieldDecl *FD) {
2860 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2861
2862 if (!Value.isInt()) {
2863 // Trying to store a pointer-cast-to-integer into a bitfield.
2864 // FIXME: In this case, we should provide the diagnostic for casting
2865 // a pointer to an integer.
2866 assert(Value.isLValue() && "integral value neither int nor lvalue?");
2867 Info.FFDiag(E);
2868 return false;
2869 }
2870
2871 APSInt &Int = Value.getInt();
2872 unsigned OldBitWidth = Int.getBitWidth();
2873 unsigned NewBitWidth = FD->getBitWidthValue();
2874 if (NewBitWidth < OldBitWidth)
2875 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2876 return true;
2877}
2878
2879/// Perform the given integer operation, which is known to need at most BitWidth
2880/// bits, and check for overflow in the original type (if that type was not an
2881/// unsigned type).
2882template<typename Operation>
2883static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2884 const APSInt &LHS, const APSInt &RHS,
2885 unsigned BitWidth, Operation Op,
2886 APSInt &Result) {
2887 if (LHS.isUnsigned()) {
2888 Result = Op(LHS, RHS);
2889 return true;
2890 }
2891
2892 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2893 Result = Value.trunc(LHS.getBitWidth());
2894 if (Result.extend(BitWidth) != Value) {
2895 if (Info.checkingForUndefinedBehavior())
2896 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2897 diag::warn_integer_constant_overflow)
2898 << toString(Result, 10, Result.isSigned(), /*formatAsCLiteral=*/false,
2899 /*UpperCase=*/true, /*InsertSeparators=*/true)
2900 << E->getType() << E->getSourceRange();
2901 return HandleOverflow(Info, E, Value, E->getType());
2902 }
2903 return true;
2904}
2905
2906/// Perform the given binary integer operation.
2907static bool handleIntIntBinOp(EvalInfo &Info, const BinaryOperator *E,
2908 const APSInt &LHS, BinaryOperatorKind Opcode,
2909 APSInt RHS, APSInt &Result) {
2910 bool HandleOverflowResult = true;
2911 switch (Opcode) {
2912 default:
2913 Info.FFDiag(E);
2914 return false;
2915 case BO_Mul:
2916 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2917 std::multiplies<APSInt>(), Result);
2918 case BO_Add:
2919 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2920 std::plus<APSInt>(), Result);
2921 case BO_Sub:
2922 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2923 std::minus<APSInt>(), Result);
2924 case BO_And: Result = LHS & RHS; return true;
2925 case BO_Xor: Result = LHS ^ RHS; return true;
2926 case BO_Or: Result = LHS | RHS; return true;
2927 case BO_Div:
2928 case BO_Rem:
2929 if (RHS == 0) {
2930 Info.FFDiag(E, diag::note_expr_divide_by_zero)
2931 << E->getRHS()->getSourceRange();
2932 return false;
2933 }
2934 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2935 // this operation and gives the two's complement result.
2936 if (RHS.isNegative() && RHS.isAllOnes() && LHS.isSigned() &&
2937 LHS.isMinSignedValue())
2938 HandleOverflowResult = HandleOverflow(
2939 Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
2940 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2941 return HandleOverflowResult;
2942 case BO_Shl: {
2943 if (Info.getLangOpts().OpenCL)
2944 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2945 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2946 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2947 RHS.isUnsigned());
2948 else if (RHS.isSigned() && RHS.isNegative()) {
2949 // During constant-folding, a negative shift is an opposite shift. Such
2950 // a shift is not a constant expression.
2951 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2952 if (!Info.noteUndefinedBehavior())
2953 return false;
2954 RHS = -RHS;
2955 goto shift_right;
2956 }
2957 shift_left:
2958 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2959 // the shifted type.
2960 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2961 if (SA != RHS) {
2962 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2963 << RHS << E->getType() << LHS.getBitWidth();
2964 if (!Info.noteUndefinedBehavior())
2965 return false;
2966 } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) {
2967 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2968 // operand, and must not overflow the corresponding unsigned type.
2969 // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2970 // E1 x 2^E2 module 2^N.
2971 if (LHS.isNegative()) {
2972 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2973 if (!Info.noteUndefinedBehavior())
2974 return false;
2975 } else if (LHS.countl_zero() < SA) {
2976 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2977 if (!Info.noteUndefinedBehavior())
2978 return false;
2979 }
2980 }
2981 Result = LHS << SA;
2982 return true;
2983 }
2984 case BO_Shr: {
2985 if (Info.getLangOpts().OpenCL)
2986 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2987 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2988 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2989 RHS.isUnsigned());
2990 else if (RHS.isSigned() && RHS.isNegative()) {
2991 // During constant-folding, a negative shift is an opposite shift. Such a
2992 // shift is not a constant expression.
2993 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2994 if (!Info.noteUndefinedBehavior())
2995 return false;
2996 RHS = -RHS;
2997 goto shift_left;
2998 }
2999 shift_right:
3000 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
3001 // shifted type.
3002 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
3003 if (SA != RHS) {
3004 Info.CCEDiag(E, diag::note_constexpr_large_shift)
3005 << RHS << E->getType() << LHS.getBitWidth();
3006 if (!Info.noteUndefinedBehavior())
3007 return false;
3008 }
3009
3010 Result = LHS >> SA;
3011 return true;
3012 }
3013
3014 case BO_LT: Result = LHS < RHS; return true;
3015 case BO_GT: Result = LHS > RHS; return true;
3016 case BO_LE: Result = LHS <= RHS; return true;
3017 case BO_GE: Result = LHS >= RHS; return true;
3018 case BO_EQ: Result = LHS == RHS; return true;
3019 case BO_NE: Result = LHS != RHS; return true;
3020 case BO_Cmp:
3021 llvm_unreachable("BO_Cmp should be handled elsewhere");
3022 }
3023}
3024
3025/// Perform the given binary floating-point operation, in-place, on LHS.
3026static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E,
3027 APFloat &LHS, BinaryOperatorKind Opcode,
3028 const APFloat &RHS) {
3029 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
3030 APFloat::opStatus St;
3031 switch (Opcode) {
3032 default:
3033 Info.FFDiag(E);
3034 return false;
3035 case BO_Mul:
3036 St = LHS.multiply(RHS, RM);
3037 break;
3038 case BO_Add:
3039 St = LHS.add(RHS, RM);
3040 break;
3041 case BO_Sub:
3042 St = LHS.subtract(RHS, RM);
3043 break;
3044 case BO_Div:
3045 // [expr.mul]p4:
3046 // If the second operand of / or % is zero the behavior is undefined.
3047 if (RHS.isZero())
3048 Info.CCEDiag(E, diag::note_expr_divide_by_zero);
3049 St = LHS.divide(RHS, RM);
3050 break;
3051 }
3052
3053 // [expr.pre]p4:
3054 // If during the evaluation of an expression, the result is not
3055 // mathematically defined [...], the behavior is undefined.
3056 // FIXME: C++ rules require us to not conform to IEEE 754 here.
3057 if (LHS.isNaN()) {
3058 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
3059 return Info.noteUndefinedBehavior();
3060 }
3061
3062 return checkFloatingPointResult(Info, E, St);
3063}
3064
3065static bool handleLogicalOpForVector(const APInt &LHSValue,
3066 BinaryOperatorKind Opcode,
3067 const APInt &RHSValue, APInt &Result) {
3068 bool LHS = (LHSValue != 0);
3069 bool RHS = (RHSValue != 0);
3070
3071 if (Opcode == BO_LAnd)
3072 Result = LHS && RHS;
3073 else
3074 Result = LHS || RHS;
3075 return true;
3076}
3077static bool handleLogicalOpForVector(const APFloat &LHSValue,
3078 BinaryOperatorKind Opcode,
3079 const APFloat &RHSValue, APInt &Result) {
3080 bool LHS = !LHSValue.isZero();
3081 bool RHS = !RHSValue.isZero();
3082
3083 if (Opcode == BO_LAnd)
3084 Result = LHS && RHS;
3085 else
3086 Result = LHS || RHS;
3087 return true;
3088}
3089
3090static bool handleLogicalOpForVector(const APValue &LHSValue,
3091 BinaryOperatorKind Opcode,
3092 const APValue &RHSValue, APInt &Result) {
3093 // The result is always an int type, however operands match the first.
3094 if (LHSValue.getKind() == APValue::Int)
3095 return handleLogicalOpForVector(LHSValue.getInt(), Opcode,
3096 RHSValue.getInt(), Result);
3097 assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
3098 return handleLogicalOpForVector(LHSValue.getFloat(), Opcode,
3099 RHSValue.getFloat(), Result);
3100}
3101
3102template <typename APTy>
3103static bool
3105 const APTy &RHSValue, APInt &Result) {
3106 switch (Opcode) {
3107 default:
3108 llvm_unreachable("unsupported binary operator");
3109 case BO_EQ:
3110 Result = (LHSValue == RHSValue);
3111 break;
3112 case BO_NE:
3113 Result = (LHSValue != RHSValue);
3114 break;
3115 case BO_LT:
3116 Result = (LHSValue < RHSValue);
3117 break;
3118 case BO_GT:
3119 Result = (LHSValue > RHSValue);
3120 break;
3121 case BO_LE:
3122 Result = (LHSValue <= RHSValue);
3123 break;
3124 case BO_GE:
3125 Result = (LHSValue >= RHSValue);
3126 break;
3127 }
3128
3129 // The boolean operations on these vector types use an instruction that
3130 // results in a mask of '-1' for the 'truth' value. Ensure that we negate 1
3131 // to -1 to make sure that we produce the correct value.
3132 Result.negate();
3133
3134 return true;
3135}
3136
3137static bool handleCompareOpForVector(const APValue &LHSValue,
3138 BinaryOperatorKind Opcode,
3139 const APValue &RHSValue, APInt &Result) {
3140 // The result is always an int type, however operands match the first.
3141 if (LHSValue.getKind() == APValue::Int)
3142 return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode,
3143 RHSValue.getInt(), Result);
3144 assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
3145 return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode,
3146 RHSValue.getFloat(), Result);
3147}
3148
3149// Perform binary operations for vector types, in place on the LHS.
3150static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E,
3151 BinaryOperatorKind Opcode,
3152 APValue &LHSValue,
3153 const APValue &RHSValue) {
3154 assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI &&
3155 "Operation not supported on vector types");
3156
3157 const auto *VT = E->getType()->castAs<VectorType>();
3158 unsigned NumElements = VT->getNumElements();
3159 QualType EltTy = VT->getElementType();
3160
3161 // In the cases (typically C as I've observed) where we aren't evaluating
3162 // constexpr but are checking for cases where the LHS isn't yet evaluatable,
3163 // just give up.
3164 if (!LHSValue.isVector()) {
3165 assert(LHSValue.isLValue() &&
3166 "A vector result that isn't a vector OR uncalculated LValue");
3167 Info.FFDiag(E);
3168 return false;
3169 }
3170
3171 assert(LHSValue.getVectorLength() == NumElements &&
3172 RHSValue.getVectorLength() == NumElements && "Different vector sizes");
3173
3174 SmallVector<APValue, 4> ResultElements;
3175
3176 for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) {
3177 APValue LHSElt = LHSValue.getVectorElt(EltNum);
3178 APValue RHSElt = RHSValue.getVectorElt(EltNum);
3179
3180 if (EltTy->isIntegerType()) {
3181 APSInt EltResult{Info.Ctx.getIntWidth(EltTy),
3182 EltTy->isUnsignedIntegerType()};
3183 bool Success = true;
3184
3185 if (BinaryOperator::isLogicalOp(Opcode))
3186 Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3187 else if (BinaryOperator::isComparisonOp(Opcode))
3188 Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3189 else
3190 Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode,
3191 RHSElt.getInt(), EltResult);
3192
3193 if (!Success) {
3194 Info.FFDiag(E);
3195 return false;
3196 }
3197 ResultElements.emplace_back(EltResult);
3198
3199 } else if (EltTy->isFloatingType()) {
3200 assert(LHSElt.getKind() == APValue::Float &&
3201 RHSElt.getKind() == APValue::Float &&
3202 "Mismatched LHS/RHS/Result Type");
3203 APFloat LHSFloat = LHSElt.getFloat();
3204
3205 if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode,
3206 RHSElt.getFloat())) {
3207 Info.FFDiag(E);
3208 return false;
3209 }
3210
3211 ResultElements.emplace_back(LHSFloat);
3212 }
3213 }
3214
3215 LHSValue = APValue(ResultElements.data(), ResultElements.size());
3216 return true;
3217}
3218
3219/// Cast an lvalue referring to a base subobject to a derived class, by
3220/// truncating the lvalue's path to the given length.
3221static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
3222 const RecordDecl *TruncatedType,
3223 unsigned TruncatedElements) {
3224 SubobjectDesignator &D = Result.Designator;
3225
3226 // Check we actually point to a derived class object.
3227 if (TruncatedElements == D.Entries.size())
3228 return true;
3229 assert(TruncatedElements >= D.MostDerivedPathLength &&
3230 "not casting to a derived class");
3231 if (!Result.checkSubobject(Info, E, CSK_Derived))
3232 return false;
3233
3234 // Truncate the path to the subobject, and remove any derived-to-base offsets.
3235 const RecordDecl *RD = TruncatedType;
3236 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
3237 if (RD->isInvalidDecl()) return false;
3238 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3239 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
3240 if (isVirtualBaseClass(D.Entries[I]))
3241 Result.Offset -= Layout.getVBaseClassOffset(Base);
3242 else
3243 Result.Offset -= Layout.getBaseClassOffset(Base);
3244 RD = Base;
3245 }
3246 D.Entries.resize(TruncatedElements);
3247 return true;
3248}
3249
3250static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3251 const CXXRecordDecl *Derived,
3252 const CXXRecordDecl *Base,
3253 const ASTRecordLayout *RL = nullptr) {
3254 if (!RL) {
3255 if (Derived->isInvalidDecl()) return false;
3256 RL = &Info.Ctx.getASTRecordLayout(Derived);
3257 }
3258
3259 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
3260 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
3261 return true;
3262}
3263
3264static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3265 const CXXRecordDecl *DerivedDecl,
3266 const CXXBaseSpecifier *Base) {
3267 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
3268
3269 if (!Base->isVirtual())
3270 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
3271
3272 SubobjectDesignator &D = Obj.Designator;
3273 if (D.Invalid)
3274 return false;
3275
3276 // Extract most-derived object and corresponding type.
3277 // FIXME: After implementing P2280R4 it became possible to get references
3278 // here. We do MostDerivedType->getAsCXXRecordDecl() in several other
3279 // locations and if we see crashes in those locations in the future
3280 // it may make more sense to move this fix into Lvalue::set.
3281 DerivedDecl = D.MostDerivedType.getNonReferenceType()->getAsCXXRecordDecl();
3282 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
3283 return false;
3284
3285 // Find the virtual base class.
3286 if (DerivedDecl->isInvalidDecl()) return false;
3287 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
3288 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
3289 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
3290 return true;
3291}
3292
3293static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
3294 QualType Type, LValue &Result) {
3295 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3296 PathE = E->path_end();
3297 PathI != PathE; ++PathI) {
3298 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3299 *PathI))
3300 return false;
3301 Type = (*PathI)->getType();
3302 }
3303 return true;
3304}
3305
3306/// Cast an lvalue referring to a derived class to a known base subobject.
3307static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
3308 const CXXRecordDecl *DerivedRD,
3309 const CXXRecordDecl *BaseRD) {
3310 CXXBasePaths Paths(/*FindAmbiguities=*/false,
3311 /*RecordPaths=*/true, /*DetectVirtual=*/false);
3312 if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
3313 llvm_unreachable("Class must be derived from the passed in base class!");
3314
3315 for (CXXBasePathElement &Elem : Paths.front())
3316 if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
3317 return false;
3318 return true;
3319}
3320
3321/// Update LVal to refer to the given field, which must be a member of the type
3322/// currently described by LVal.
3323static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
3324 const FieldDecl *FD,
3325 const ASTRecordLayout *RL = nullptr) {
3326 if (!RL) {
3327 if (FD->getParent()->isInvalidDecl()) return false;
3328 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
3329 }
3330
3331 unsigned I = FD->getFieldIndex();
3332 LVal.addDecl(Info, E, FD);
3333 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
3334 return true;
3335}
3336
3337/// Update LVal to refer to the given indirect field.
3338static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
3339 LValue &LVal,
3340 const IndirectFieldDecl *IFD) {
3341 for (const auto *C : IFD->chain())
3342 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
3343 return false;
3344 return true;
3345}
3346
3351
3352/// Get the size of the given type in char units.
3353static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, QualType Type,
3355 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
3356 // extension.
3357 if (Type->isVoidType() || Type->isFunctionType()) {
3358 Size = CharUnits::One();
3359 return true;
3360 }
3361
3362 if (Type->isDependentType()) {
3363 Info.FFDiag(Loc);
3364 return false;
3365 }
3366
3367 if (!Type->isConstantSizeType()) {
3368 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
3369 // FIXME: Better diagnostic.
3370 Info.FFDiag(Loc);
3371 return false;
3372 }
3373
3374 if (SOT == SizeOfType::SizeOf)
3375 Size = Info.Ctx.getTypeSizeInChars(Type);
3376 else
3377 Size = Info.Ctx.getTypeInfoDataSizeInChars(Type).Width;
3378 return true;
3379}
3380
3381/// Update a pointer value to model pointer arithmetic.
3382/// \param Info - Information about the ongoing evaluation.
3383/// \param E - The expression being evaluated, for diagnostic purposes.
3384/// \param LVal - The pointer value to be updated.
3385/// \param EltTy - The pointee type represented by LVal.
3386/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
3387static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3388 LValue &LVal, QualType EltTy,
3389 APSInt Adjustment) {
3390 CharUnits SizeOfPointee;
3391 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
3392 return false;
3393
3394 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
3395 return true;
3396}
3397
3398static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3399 LValue &LVal, QualType EltTy,
3400 int64_t Adjustment) {
3401 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
3402 APSInt::get(Adjustment));
3403}
3404
3405/// Update an lvalue to refer to a component of a complex number.
3406/// \param Info - Information about the ongoing evaluation.
3407/// \param LVal - The lvalue to be updated.
3408/// \param EltTy - The complex number's component type.
3409/// \param Imag - False for the real component, true for the imaginary.
3410static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
3411 LValue &LVal, QualType EltTy,
3412 bool Imag) {
3413 if (Imag) {
3414 CharUnits SizeOfComponent;
3415 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
3416 return false;
3417 LVal.Offset += SizeOfComponent;
3418 }
3419 LVal.addComplex(Info, E, EltTy, Imag);
3420 return true;
3421}
3422
3423static bool HandleLValueVectorElement(EvalInfo &Info, const Expr *E,
3424 LValue &LVal, QualType EltTy,
3425 uint64_t Size, uint64_t Idx) {
3426 if (Idx) {
3427 CharUnits SizeOfElement;
3428 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfElement))
3429 return false;
3430 LVal.Offset += SizeOfElement * Idx;
3431 }
3432 LVal.addVectorElement(Info, E, EltTy, Size, Idx);
3433 return true;
3434}
3435
3436/// Try to evaluate the initializer for a variable declaration.
3437///
3438/// \param Info Information about the ongoing evaluation.
3439/// \param E An expression to be used when printing diagnostics.
3440/// \param VD The variable whose initializer should be obtained.
3441/// \param Version The version of the variable within the frame.
3442/// \param Frame The frame in which the variable was created. Must be null
3443/// if this variable is not local to the evaluation.
3444/// \param Result Filled in with a pointer to the value of the variable.
3445static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
3446 const VarDecl *VD, CallStackFrame *Frame,
3447 unsigned Version, APValue *&Result) {
3448 // C++23 [expr.const]p8 If we have a reference type allow unknown references
3449 // and pointers.
3450 bool AllowConstexprUnknown =
3451 Info.getLangOpts().CPlusPlus23 && VD->getType()->isReferenceType();
3452
3453 APValue::LValueBase Base(VD, Frame ? Frame->Index : 0, Version);
3454
3455 auto CheckUninitReference = [&](bool IsLocalVariable) {
3456 if (!Result || (!Result->hasValue() && VD->getType()->isReferenceType())) {
3457 // C++23 [expr.const]p8
3458 // ... For such an object that is not usable in constant expressions, the
3459 // dynamic type of the object is constexpr-unknown. For such a reference
3460 // that is not usable in constant expressions, the reference is treated
3461 // as binding to an unspecified object of the referenced type whose
3462 // lifetime and that of all subobjects includes the entire constant
3463 // evaluation and whose dynamic type is constexpr-unknown.
3464 //
3465 // Variables that are part of the current evaluation are not
3466 // constexpr-unknown.
3467 if (!AllowConstexprUnknown || IsLocalVariable) {
3468 if (!Info.checkingPotentialConstantExpression())
3469 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
3470 return false;
3471 }
3472 Result = nullptr;
3473 }
3474 return true;
3475 };
3476
3477 // If this is a local variable, dig out its value.
3478 if (Frame) {
3479 Result = Frame->getTemporary(VD, Version);
3480 if (Result)
3481 return CheckUninitReference(/*IsLocalVariable=*/true);
3482
3483 if (!isa<ParmVarDecl>(VD)) {
3484 // Assume variables referenced within a lambda's call operator that were
3485 // not declared within the call operator are captures and during checking
3486 // of a potential constant expression, assume they are unknown constant
3487 // expressions.
3488 assert(isLambdaCallOperator(Frame->Callee) &&
3489 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
3490 "missing value for local variable");
3491 if (Info.checkingPotentialConstantExpression())
3492 return false;
3493 // FIXME: This diagnostic is bogus; we do support captures. Is this code
3494 // still reachable at all?
3495 Info.FFDiag(E->getBeginLoc(),
3496 diag::note_unimplemented_constexpr_lambda_feature_ast)
3497 << "captures not currently allowed";
3498 return false;
3499 }
3500 }
3501
3502 // If we're currently evaluating the initializer of this declaration, use that
3503 // in-flight value.
3504 if (Info.EvaluatingDecl == Base) {
3505 Result = Info.EvaluatingDeclValue;
3506 return CheckUninitReference(/*IsLocalVariable=*/false);
3507 }
3508
3509 // P2280R4 struck the restriction that variable of reference type lifetime
3510 // should begin within the evaluation of E
3511 // Used to be C++20 [expr.const]p5.12.2:
3512 // ... its lifetime began within the evaluation of E;
3513 if (isa<ParmVarDecl>(VD)) {
3514 if (AllowConstexprUnknown) {
3515 Result = nullptr;
3516 return true;
3517 }
3518
3519 // Assume parameters of a potential constant expression are usable in
3520 // constant expressions.
3521 if (!Info.checkingPotentialConstantExpression() ||
3522 !Info.CurrentCall->Callee ||
3523 !Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
3524 if (Info.getLangOpts().CPlusPlus11) {
3525 Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown)
3526 << VD;
3527 NoteLValueLocation(Info, Base);
3528 } else {
3529 Info.FFDiag(E);
3530 }
3531 }
3532 return false;
3533 }
3534
3535 if (E->isValueDependent())
3536 return false;
3537
3538 // Dig out the initializer, and use the declaration which it's attached to.
3539 // FIXME: We should eventually check whether the variable has a reachable
3540 // initializing declaration.
3541 const Expr *Init = VD->getAnyInitializer(VD);
3542 // P2280R4 struck the restriction that variable of reference type should have
3543 // a preceding initialization.
3544 // Used to be C++20 [expr.const]p5.12:
3545 // ... reference has a preceding initialization and either ...
3546 if (!Init && !AllowConstexprUnknown) {
3547 // Don't diagnose during potential constant expression checking; an
3548 // initializer might be added later.
3549 if (!Info.checkingPotentialConstantExpression()) {
3550 Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1)
3551 << VD;
3552 NoteLValueLocation(Info, Base);
3553 }
3554 return false;
3555 }
3556
3557 // P2280R4 struck the initialization requirement for variables of reference
3558 // type so we can no longer assume we have an Init.
3559 // Used to be C++20 [expr.const]p5.12:
3560 // ... reference has a preceding initialization and either ...
3561 if (Init && Init->isValueDependent()) {
3562 // The DeclRefExpr is not value-dependent, but the variable it refers to
3563 // has a value-dependent initializer. This should only happen in
3564 // constant-folding cases, where the variable is not actually of a suitable
3565 // type for use in a constant expression (otherwise the DeclRefExpr would
3566 // have been value-dependent too), so diagnose that.
3567 assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx));
3568 if (!Info.checkingPotentialConstantExpression()) {
3569 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
3570 ? diag::note_constexpr_ltor_non_constexpr
3571 : diag::note_constexpr_ltor_non_integral, 1)
3572 << VD << VD->getType();
3573 NoteLValueLocation(Info, Base);
3574 }
3575 return false;
3576 }
3577
3578 // Check that we can fold the initializer. In C++, we will have already done
3579 // this in the cases where it matters for conformance.
3580 // P2280R4 struck the initialization requirement for variables of reference
3581 // type so we can no longer assume we have an Init.
3582 // Used to be C++20 [expr.const]p5.12:
3583 // ... reference has a preceding initialization and either ...
3584 if (Init && !VD->evaluateValue() && !AllowConstexprUnknown) {
3585 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3586 NoteLValueLocation(Info, Base);
3587 return false;
3588 }
3589
3590 // Check that the variable is actually usable in constant expressions. For a
3591 // const integral variable or a reference, we might have a non-constant
3592 // initializer that we can nonetheless evaluate the initializer for. Such
3593 // variables are not usable in constant expressions. In C++98, the
3594 // initializer also syntactically needs to be an ICE.
3595 //
3596 // FIXME: We don't diagnose cases that aren't potentially usable in constant
3597 // expressions here; doing so would regress diagnostics for things like
3598 // reading from a volatile constexpr variable.
3599 if ((Info.getLangOpts().CPlusPlus && !VD->hasConstantInitialization() &&
3600 VD->mightBeUsableInConstantExpressions(Info.Ctx) &&
3601 !AllowConstexprUnknown) ||
3602 ((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) &&
3603 !Info.getLangOpts().CPlusPlus11 && !VD->hasICEInitializer(Info.Ctx))) {
3604 if (Init) {
3605 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3606 NoteLValueLocation(Info, Base);
3607 } else {
3608 Info.CCEDiag(E);
3609 }
3610 }
3611
3612 // Never use the initializer of a weak variable, not even for constant
3613 // folding. We can't be sure that this is the definition that will be used.
3614 if (VD->isWeak()) {
3615 Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD;
3616 NoteLValueLocation(Info, Base);
3617 return false;
3618 }
3619
3620 Result = VD->getEvaluatedValue();
3621
3622 if (!Result && !AllowConstexprUnknown)
3623 return false;
3624
3625 return CheckUninitReference(/*IsLocalVariable=*/false);
3626}
3627
3628/// Get the base index of the given base class within an APValue representing
3629/// the given derived class.
3630static unsigned getBaseIndex(const CXXRecordDecl *Derived,
3631 const CXXRecordDecl *Base) {
3632 Base = Base->getCanonicalDecl();
3633 unsigned Index = 0;
3635 E = Derived->bases_end(); I != E; ++I, ++Index) {
3636 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
3637 return Index;
3638 }
3639
3640 llvm_unreachable("base class missing from derived class's bases list");
3641}
3642
3643/// Extract the value of a character from a string literal.
3644static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
3645 uint64_t Index) {
3646 assert(!isa<SourceLocExpr>(Lit) &&
3647 "SourceLocExpr should have already been converted to a StringLiteral");
3648
3649 // FIXME: Support MakeStringConstant
3650 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
3651 std::string Str;
3652 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
3653 assert(Index <= Str.size() && "Index too large");
3654 return APSInt::getUnsigned(Str.c_str()[Index]);
3655 }
3656
3657 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
3658 Lit = PE->getFunctionName();
3659 const StringLiteral *S = cast<StringLiteral>(Lit);
3660 const ConstantArrayType *CAT =
3661 Info.Ctx.getAsConstantArrayType(S->getType());
3662 assert(CAT && "string literal isn't an array");
3663 QualType CharType = CAT->getElementType();
3664 assert(CharType->isIntegerType() && "unexpected character type");
3665 APSInt Value(Info.Ctx.getTypeSize(CharType),
3666 CharType->isUnsignedIntegerType());
3667 if (Index < S->getLength())
3668 Value = S->getCodeUnit(Index);
3669 return Value;
3670}
3671
3672// Expand a string literal into an array of characters.
3673//
3674// FIXME: This is inefficient; we should probably introduce something similar
3675// to the LLVM ConstantDataArray to make this cheaper.
3676static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
3677 APValue &Result,
3678 QualType AllocType = QualType()) {
3679 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
3680 AllocType.isNull() ? S->getType() : AllocType);
3681 assert(CAT && "string literal isn't an array");
3682 QualType CharType = CAT->getElementType();
3683 assert(CharType->isIntegerType() && "unexpected character type");
3684
3685 unsigned Elts = CAT->getZExtSize();
3686 Result = APValue(APValue::UninitArray(),
3687 std::min(S->getLength(), Elts), Elts);
3688 APSInt Value(Info.Ctx.getTypeSize(CharType),
3689 CharType->isUnsignedIntegerType());
3690 if (Result.hasArrayFiller())
3691 Result.getArrayFiller() = APValue(Value);
3692 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
3693 Value = S->getCodeUnit(I);
3694 Result.getArrayInitializedElt(I) = APValue(Value);
3695 }
3696}
3697
3698// Expand an array so that it has more than Index filled elements.
3699static void expandArray(APValue &Array, unsigned Index) {
3700 unsigned Size = Array.getArraySize();
3701 assert(Index < Size);
3702
3703 // Always at least double the number of elements for which we store a value.
3704 unsigned OldElts = Array.getArrayInitializedElts();
3705 unsigned NewElts = std::max(Index+1, OldElts * 2);
3706 NewElts = std::min(Size, std::max(NewElts, 8u));
3707
3708 // Copy the data across.
3709 APValue NewValue(APValue::UninitArray(), NewElts, Size);
3710 for (unsigned I = 0; I != OldElts; ++I)
3711 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
3712 for (unsigned I = OldElts; I != NewElts; ++I)
3713 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
3714 if (NewValue.hasArrayFiller())
3715 NewValue.getArrayFiller() = Array.getArrayFiller();
3716 Array.swap(NewValue);
3717}
3718
3719/// Determine whether a type would actually be read by an lvalue-to-rvalue
3720/// conversion. If it's of class type, we may assume that the copy operation
3721/// is trivial. Note that this is never true for a union type with fields
3722/// (because the copy always "reads" the active member) and always true for
3723/// a non-class type.
3724static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD);
3726 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3727 return !RD || isReadByLvalueToRvalueConversion(RD);
3728}
3730 // FIXME: A trivial copy of a union copies the object representation, even if
3731 // the union is empty.
3732 if (RD->isUnion())
3733 return !RD->field_empty();
3734 if (RD->isEmpty())
3735 return false;
3736
3737 for (auto *Field : RD->fields())
3738 if (!Field->isUnnamedBitField() &&
3739 isReadByLvalueToRvalueConversion(Field->getType()))
3740 return true;
3741
3742 for (auto &BaseSpec : RD->bases())
3743 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
3744 return true;
3745
3746 return false;
3747}
3748
3749/// Diagnose an attempt to read from any unreadable field within the specified
3750/// type, which might be a class type.
3751static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK,
3752 QualType T) {
3753 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3754 if (!RD)
3755 return false;
3756
3757 if (!RD->hasMutableFields())
3758 return false;
3759
3760 for (auto *Field : RD->fields()) {
3761 // If we're actually going to read this field in some way, then it can't
3762 // be mutable. If we're in a union, then assigning to a mutable field
3763 // (even an empty one) can change the active member, so that's not OK.
3764 // FIXME: Add core issue number for the union case.
3765 if (Field->isMutable() &&
3766 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
3767 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field;
3768 Info.Note(Field->getLocation(), diag::note_declared_at);
3769 return true;
3770 }
3771
3772 if (diagnoseMutableFields(Info, E, AK, Field->getType()))
3773 return true;
3774 }
3775
3776 for (auto &BaseSpec : RD->bases())
3777 if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType()))
3778 return true;
3779
3780 // All mutable fields were empty, and thus not actually read.
3781 return false;
3782}
3783
3784static bool lifetimeStartedInEvaluation(EvalInfo &Info,
3786 bool MutableSubobject = false) {
3787 // A temporary or transient heap allocation we created.
3788 if (Base.getCallIndex() || Base.is<DynamicAllocLValue>())
3789 return true;
3790
3791 switch (Info.IsEvaluatingDecl) {
3792 case EvalInfo::EvaluatingDeclKind::None:
3793 return false;
3794
3795 case EvalInfo::EvaluatingDeclKind::Ctor:
3796 // The variable whose initializer we're evaluating.
3797 if (Info.EvaluatingDecl == Base)
3798 return true;
3799
3800 // A temporary lifetime-extended by the variable whose initializer we're
3801 // evaluating.
3802 if (auto *BaseE = Base.dyn_cast<const Expr *>())
3803 if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
3804 return Info.EvaluatingDecl == BaseMTE->getExtendingDecl();
3805 return false;
3806
3807 case EvalInfo::EvaluatingDeclKind::Dtor:
3808 // C++2a [expr.const]p6:
3809 // [during constant destruction] the lifetime of a and its non-mutable
3810 // subobjects (but not its mutable subobjects) [are] considered to start
3811 // within e.
3812 if (MutableSubobject || Base != Info.EvaluatingDecl)
3813 return false;
3814 // FIXME: We can meaningfully extend this to cover non-const objects, but
3815 // we will need special handling: we should be able to access only
3816 // subobjects of such objects that are themselves declared const.
3818 return T.isConstQualified() || T->isReferenceType();
3819 }
3820
3821 llvm_unreachable("unknown evaluating decl kind");
3822}
3823
3824static bool CheckArraySize(EvalInfo &Info, const ConstantArrayType *CAT,
3825 SourceLocation CallLoc = {}) {
3826 return Info.CheckArraySize(
3827 CAT->getSizeExpr() ? CAT->getSizeExpr()->getBeginLoc() : CallLoc,
3828 CAT->getNumAddressingBits(Info.Ctx), CAT->getZExtSize(),
3829 /*Diag=*/true);
3830}
3831
3832static bool handleScalarCast(EvalInfo &Info, const FPOptions FPO, const Expr *E,
3833 QualType SourceTy, QualType DestTy,
3834 APValue const &Original, APValue &Result) {
3835 // boolean must be checked before integer
3836 // since IsIntegerType() is true for bool
3837 if (SourceTy->isBooleanType()) {
3838 if (DestTy->isBooleanType()) {
3839 Result = Original;
3840 return true;
3841 }
3842 if (DestTy->isIntegerType() || DestTy->isRealFloatingType()) {
3843 bool BoolResult;
3844 if (!HandleConversionToBool(Original, BoolResult))
3845 return false;
3846 uint64_t IntResult = BoolResult;
3847 QualType IntType = DestTy->isIntegerType()
3848 ? DestTy
3849 : Info.Ctx.getIntTypeForBitwidth(64, false);
3850 Result = APValue(Info.Ctx.MakeIntValue(IntResult, IntType));
3851 }
3852 if (DestTy->isRealFloatingType()) {
3853 APValue Result2 = APValue(APFloat(0.0));
3854 if (!HandleIntToFloatCast(Info, E, FPO,
3855 Info.Ctx.getIntTypeForBitwidth(64, false),
3856 Result.getInt(), DestTy, Result2.getFloat()))
3857 return false;
3858 Result = Result2;
3859 }
3860 return true;
3861 }
3862 if (SourceTy->isIntegerType()) {
3863 if (DestTy->isRealFloatingType()) {
3864 Result = APValue(APFloat(0.0));
3865 return HandleIntToFloatCast(Info, E, FPO, SourceTy, Original.getInt(),
3866 DestTy, Result.getFloat());
3867 }
3868 if (DestTy->isBooleanType()) {
3869 bool BoolResult;
3870 if (!HandleConversionToBool(Original, BoolResult))
3871 return false;
3872 uint64_t IntResult = BoolResult;
3873 Result = APValue(Info.Ctx.MakeIntValue(IntResult, DestTy));
3874 return true;
3875 }
3876 if (DestTy->isIntegerType()) {
3877 Result = APValue(
3878 HandleIntToIntCast(Info, E, DestTy, SourceTy, Original.getInt()));
3879 return true;
3880 }
3881 } else if (SourceTy->isRealFloatingType()) {
3882 if (DestTy->isRealFloatingType()) {
3883 Result = Original;
3884 return HandleFloatToFloatCast(Info, E, SourceTy, DestTy,
3885 Result.getFloat());
3886 }
3887 if (DestTy->isBooleanType()) {
3888 bool BoolResult;
3889 if (!HandleConversionToBool(Original, BoolResult))
3890 return false;
3891 uint64_t IntResult = BoolResult;
3892 Result = APValue(Info.Ctx.MakeIntValue(IntResult, DestTy));
3893 return true;
3894 }
3895 if (DestTy->isIntegerType()) {
3896 Result = APValue(APSInt());
3897 return HandleFloatToIntCast(Info, E, SourceTy, Original.getFloat(),
3898 DestTy, Result.getInt());
3899 }
3900 }
3901
3902 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3903 return false;
3904}
3905
3906// do the heavy lifting for casting to aggregate types
3907// because we have to deal with bitfields specially
3908static bool constructAggregate(EvalInfo &Info, const FPOptions FPO,
3909 const Expr *E, APValue &Result,
3910 QualType ResultType,
3911 SmallVectorImpl<APValue> &Elements,
3912 SmallVectorImpl<QualType> &ElTypes) {
3913
3915 {&Result, ResultType, 0}};
3916
3917 unsigned ElI = 0;
3918 while (!WorkList.empty() && ElI < Elements.size()) {
3919 auto [Res, Type, BitWidth] = WorkList.pop_back_val();
3920
3921 if (Type->isRealFloatingType()) {
3922 if (!handleScalarCast(Info, FPO, E, ElTypes[ElI], Type, Elements[ElI],
3923 *Res))
3924 return false;
3925 ElI++;
3926 continue;
3927 }
3928 if (Type->isIntegerType()) {
3929 if (!handleScalarCast(Info, FPO, E, ElTypes[ElI], Type, Elements[ElI],
3930 *Res))
3931 return false;
3932 if (BitWidth > 0) {
3933 if (!Res->isInt())
3934 return false;
3935 APSInt &Int = Res->getInt();
3936 unsigned OldBitWidth = Int.getBitWidth();
3937 unsigned NewBitWidth = BitWidth;
3938 if (NewBitWidth < OldBitWidth)
3939 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
3940 }
3941 ElI++;
3942 continue;
3943 }
3944 if (Type->isVectorType()) {
3945 QualType ElTy = Type->castAs<VectorType>()->getElementType();
3946 unsigned NumEl = Type->castAs<VectorType>()->getNumElements();
3947 SmallVector<APValue> Vals(NumEl);
3948 for (unsigned I = 0; I < NumEl; ++I) {
3949 if (!handleScalarCast(Info, FPO, E, ElTypes[ElI], ElTy, Elements[ElI],
3950 Vals[I]))
3951 return false;
3952 ElI++;
3953 }
3954 *Res = APValue(Vals.data(), NumEl);
3955 continue;
3956 }
3957 if (Type->isConstantArrayType()) {
3959 ->getElementType();
3960 uint64_t Size =
3961 cast<ConstantArrayType>(Info.Ctx.getAsArrayType(Type))->getZExtSize();
3962 *Res = APValue(APValue::UninitArray(), Size, Size);
3963 for (int64_t I = Size - 1; I > -1; --I)
3964 WorkList.emplace_back(&Res->getArrayInitializedElt(I), ElTy, 0u);
3965 continue;
3966 }
3967 if (Type->isRecordType()) {
3968 const RecordDecl *RD = Type->getAsRecordDecl();
3969
3970 unsigned NumBases = 0;
3971 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
3972 NumBases = CXXRD->getNumBases();
3973
3974 *Res = APValue(APValue::UninitStruct(), NumBases,
3975 std::distance(RD->field_begin(), RD->field_end()));
3976
3978 // we need to traverse backwards
3979 // Visit the base classes.
3980 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3981 if (CXXRD->getNumBases() > 0) {
3982 assert(CXXRD->getNumBases() == 1);
3983 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[0];
3984 ReverseList.emplace_back(&Res->getStructBase(0), BS.getType(), 0u);
3985 }
3986 }
3987
3988 // Visit the fields.
3989 for (FieldDecl *FD : RD->fields()) {
3990 unsigned FDBW = 0;
3991 if (FD->isUnnamedBitField())
3992 continue;
3993 if (FD->isBitField()) {
3994 FDBW = FD->getBitWidthValue();
3995 }
3996
3997 ReverseList.emplace_back(&Res->getStructField(FD->getFieldIndex()),
3998 FD->getType(), FDBW);
3999 }
4000
4001 std::reverse(ReverseList.begin(), ReverseList.end());
4002 llvm::append_range(WorkList, ReverseList);
4003 continue;
4004 }
4005 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
4006 return false;
4007 }
4008 return true;
4009}
4010
4011static bool handleElementwiseCast(EvalInfo &Info, const Expr *E,
4012 const FPOptions FPO,
4013 SmallVectorImpl<APValue> &Elements,
4014 SmallVectorImpl<QualType> &SrcTypes,
4015 SmallVectorImpl<QualType> &DestTypes,
4016 SmallVectorImpl<APValue> &Results) {
4017
4018 assert((Elements.size() == SrcTypes.size()) &&
4019 (Elements.size() == DestTypes.size()));
4020
4021 for (unsigned I = 0, ESz = Elements.size(); I < ESz; ++I) {
4022 APValue Original = Elements[I];
4023 QualType SourceTy = SrcTypes[I];
4024 QualType DestTy = DestTypes[I];
4025
4026 if (!handleScalarCast(Info, FPO, E, SourceTy, DestTy, Original, Results[I]))
4027 return false;
4028 }
4029 return true;
4030}
4031
4032static unsigned elementwiseSize(EvalInfo &Info, QualType BaseTy) {
4033
4034 SmallVector<QualType> WorkList = {BaseTy};
4035
4036 unsigned Size = 0;
4037 while (!WorkList.empty()) {
4038 QualType Type = WorkList.pop_back_val();
4040 Type->isBooleanType()) {
4041 ++Size;
4042 continue;
4043 }
4044 if (Type->isVectorType()) {
4045 unsigned NumEl = Type->castAs<VectorType>()->getNumElements();
4046 Size += NumEl;
4047 continue;
4048 }
4049 if (Type->isConstantArrayType()) {
4051 ->getElementType();
4052 uint64_t ArrSize =
4053 cast<ConstantArrayType>(Info.Ctx.getAsArrayType(Type))->getZExtSize();
4054 for (uint64_t I = 0; I < ArrSize; ++I) {
4055 WorkList.push_back(ElTy);
4056 }
4057 continue;
4058 }
4059 if (Type->isRecordType()) {
4060 const RecordDecl *RD = Type->getAsRecordDecl();
4061
4062 // Visit the base classes.
4063 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
4064 if (CXXRD->getNumBases() > 0) {
4065 assert(CXXRD->getNumBases() == 1);
4066 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[0];
4067 WorkList.push_back(BS.getType());
4068 }
4069 }
4070
4071 // visit the fields.
4072 for (FieldDecl *FD : RD->fields()) {
4073 if (FD->isUnnamedBitField())
4074 continue;
4075 WorkList.push_back(FD->getType());
4076 }
4077 continue;
4078 }
4079 }
4080 return Size;
4081}
4082
4083static bool hlslAggSplatHelper(EvalInfo &Info, const Expr *E, APValue &SrcVal,
4084 QualType &SrcTy) {
4085 SrcTy = E->getType();
4086
4087 if (!Evaluate(SrcVal, Info, E))
4088 return false;
4089
4090 assert(SrcVal.isFloat() || SrcVal.isInt() ||
4091 (SrcVal.isVector() && SrcVal.getVectorLength() == 1) &&
4092 "Not a valid HLSLAggregateSplatCast.");
4093
4094 if (SrcVal.isVector()) {
4095 assert(SrcTy->isVectorType() && "Type mismatch.");
4096 SrcTy = SrcTy->castAs<VectorType>()->getElementType();
4097 SrcVal = SrcVal.getVectorElt(0);
4098 }
4099 return true;
4100}
4101
4102static bool flattenAPValue(EvalInfo &Info, const Expr *E, APValue Value,
4103 QualType BaseTy, SmallVectorImpl<APValue> &Elements,
4104 SmallVectorImpl<QualType> &Types, unsigned Size) {
4105
4106 SmallVector<std::pair<APValue, QualType>> WorkList = {{Value, BaseTy}};
4107 unsigned Populated = 0;
4108 while (!WorkList.empty() && Populated < Size) {
4109 auto [Work, Type] = WorkList.pop_back_val();
4110
4111 if (Work.isFloat() || Work.isInt()) {
4112 Elements.push_back(Work);
4113 Types.push_back(Type);
4114 Populated++;
4115 continue;
4116 }
4117 if (Work.isVector()) {
4118 assert(Type->isVectorType() && "Type mismatch.");
4119 QualType ElTy = Type->castAs<VectorType>()->getElementType();
4120 for (unsigned I = 0; I < Work.getVectorLength() && Populated < Size;
4121 I++) {
4122 Elements.push_back(Work.getVectorElt(I));
4123 Types.push_back(ElTy);
4124 Populated++;
4125 }
4126 continue;
4127 }
4128 if (Work.isArray()) {
4129 assert(Type->isConstantArrayType() && "Type mismatch.");
4131 ->getElementType();
4132 for (int64_t I = Work.getArraySize() - 1; I > -1; --I) {
4133 WorkList.emplace_back(Work.getArrayInitializedElt(I), ElTy);
4134 }
4135 continue;
4136 }
4137
4138 if (Work.isStruct()) {
4139 assert(Type->isRecordType() && "Type mismatch.");
4140
4141 const RecordDecl *RD = Type->getAsRecordDecl();
4142
4144 // Visit the fields.
4145 for (FieldDecl *FD : RD->fields()) {
4146 if (FD->isUnnamedBitField())
4147 continue;
4148 ReverseList.emplace_back(Work.getStructField(FD->getFieldIndex()),
4149 FD->getType());
4150 }
4151
4152 std::reverse(ReverseList.begin(), ReverseList.end());
4153 llvm::append_range(WorkList, ReverseList);
4154
4155 // Visit the base classes.
4156 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
4157 if (CXXRD->getNumBases() > 0) {
4158 assert(CXXRD->getNumBases() == 1);
4159 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[0];
4160 const APValue &Base = Work.getStructBase(0);
4161
4162 // Can happen in error cases.
4163 if (!Base.isStruct())
4164 return false;
4165
4166 WorkList.emplace_back(Base, BS.getType());
4167 }
4168 }
4169 continue;
4170 }
4171 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
4172 return false;
4173 }
4174 return true;
4175}
4176
4177namespace {
4178/// A handle to a complete object (an object that is not a subobject of
4179/// another object).
4180struct CompleteObject {
4181 /// The identity of the object.
4182 APValue::LValueBase Base;
4183 /// The value of the complete object.
4184 APValue *Value;
4185 /// The type of the complete object.
4186 QualType Type;
4187
4188 CompleteObject() : Value(nullptr) {}
4189 CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
4190 : Base(Base), Value(Value), Type(Type) {}
4191
4192 bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const {
4193 // If this isn't a "real" access (eg, if it's just accessing the type
4194 // info), allow it. We assume the type doesn't change dynamically for
4195 // subobjects of constexpr objects (even though we'd hit UB here if it
4196 // did). FIXME: Is this right?
4197 if (!isAnyAccess(AK))
4198 return true;
4199
4200 // In C++14 onwards, it is permitted to read a mutable member whose
4201 // lifetime began within the evaluation.
4202 // FIXME: Should we also allow this in C++11?
4203 if (!Info.getLangOpts().CPlusPlus14 &&
4204 AK != AccessKinds::AK_IsWithinLifetime)
4205 return false;
4206 return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);
4207 }
4208
4209 explicit operator bool() const { return !Type.isNull(); }
4210};
4211} // end anonymous namespace
4212
4213static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
4214 bool IsMutable = false) {
4215 // C++ [basic.type.qualifier]p1:
4216 // - A const object is an object of type const T or a non-mutable subobject
4217 // of a const object.
4218 if (ObjType.isConstQualified() && !IsMutable)
4219 SubobjType.addConst();
4220 // - A volatile object is an object of type const T or a subobject of a
4221 // volatile object.
4222 if (ObjType.isVolatileQualified())
4223 SubobjType.addVolatile();
4224 return SubobjType;
4225}
4226
4227/// Find the designated sub-object of an rvalue.
4228template <typename SubobjectHandler>
4229static typename SubobjectHandler::result_type
4230findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
4231 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
4232 if (Sub.Invalid)
4233 // A diagnostic will have already been produced.
4234 return handler.failed();
4235 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
4236 if (Info.getLangOpts().CPlusPlus11)
4237 Info.FFDiag(E, Sub.isOnePastTheEnd()
4238 ? diag::note_constexpr_access_past_end
4239 : diag::note_constexpr_access_unsized_array)
4240 << handler.AccessKind;
4241 else
4242 Info.FFDiag(E);
4243 return handler.failed();
4244 }
4245
4246 APValue *O = Obj.Value;
4247 QualType ObjType = Obj.Type;
4248 const FieldDecl *LastField = nullptr;
4249 const FieldDecl *VolatileField = nullptr;
4250
4251 // Walk the designator's path to find the subobject.
4252 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
4253 // Reading an indeterminate value is undefined, but assigning over one is OK.
4254 if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) ||
4255 (O->isIndeterminate() &&
4256 !isValidIndeterminateAccess(handler.AccessKind))) {
4257 // Object has ended lifetime.
4258 // If I is non-zero, some subobject (member or array element) of a
4259 // complete object has ended its lifetime, so this is valid for
4260 // IsWithinLifetime, resulting in false.
4261 if (I != 0 && handler.AccessKind == AK_IsWithinLifetime)
4262 return false;
4263 if (!Info.checkingPotentialConstantExpression())
4264 Info.FFDiag(E, diag::note_constexpr_access_uninit)
4265 << handler.AccessKind << O->isIndeterminate()
4266 << E->getSourceRange();
4267 return handler.failed();
4268 }
4269
4270 // C++ [class.ctor]p5, C++ [class.dtor]p5:
4271 // const and volatile semantics are not applied on an object under
4272 // {con,de}struction.
4273 if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
4274 ObjType->isRecordType() &&
4275 Info.isEvaluatingCtorDtor(
4276 Obj.Base, ArrayRef(Sub.Entries.begin(), Sub.Entries.begin() + I)) !=
4277 ConstructionPhase::None) {
4278 ObjType = Info.Ctx.getCanonicalType(ObjType);
4279 ObjType.removeLocalConst();
4280 ObjType.removeLocalVolatile();
4281 }
4282
4283 // If this is our last pass, check that the final object type is OK.
4284 if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
4285 // Accesses to volatile objects are prohibited.
4286 if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
4287 if (Info.getLangOpts().CPlusPlus) {
4288 int DiagKind;
4289 SourceLocation Loc;
4290 const NamedDecl *Decl = nullptr;
4291 if (VolatileField) {
4292 DiagKind = 2;
4293 Loc = VolatileField->getLocation();
4294 Decl = VolatileField;
4295 } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
4296 DiagKind = 1;
4297 Loc = VD->getLocation();
4298 Decl = VD;
4299 } else {
4300 DiagKind = 0;
4301 if (auto *E = Obj.Base.dyn_cast<const Expr *>())
4302 Loc = E->getExprLoc();
4303 }
4304 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
4305 << handler.AccessKind << DiagKind << Decl;
4306 Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
4307 } else {
4308 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
4309 }
4310 return handler.failed();
4311 }
4312
4313 // If we are reading an object of class type, there may still be more
4314 // things we need to check: if there are any mutable subobjects, we
4315 // cannot perform this read. (This only happens when performing a trivial
4316 // copy or assignment.)
4317 if (ObjType->isRecordType() &&
4318 !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
4319 diagnoseMutableFields(Info, E, handler.AccessKind, ObjType))
4320 return handler.failed();
4321 }
4322
4323 if (I == N) {
4324 if (!handler.found(*O, ObjType))
4325 return false;
4326
4327 // If we modified a bit-field, truncate it to the right width.
4328 if (isModification(handler.AccessKind) &&
4329 LastField && LastField->isBitField() &&
4330 !truncateBitfieldValue(Info, E, *O, LastField))
4331 return false;
4332
4333 return true;
4334 }
4335
4336 LastField = nullptr;
4337 if (ObjType->isArrayType()) {
4338 // Next subobject is an array element.
4339 const ArrayType *AT = Info.Ctx.getAsArrayType(ObjType);
4341 "vla in literal type?");
4342 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
4343 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT);
4344 CAT && CAT->getSize().ule(Index)) {
4345 // Note, it should not be possible to form a pointer with a valid
4346 // designator which points more than one past the end of the array.
4347 if (Info.getLangOpts().CPlusPlus11)
4348 Info.FFDiag(E, diag::note_constexpr_access_past_end)
4349 << handler.AccessKind;
4350 else
4351 Info.FFDiag(E);
4352 return handler.failed();
4353 }
4354
4355 ObjType = AT->getElementType();
4356
4357 if (O->getArrayInitializedElts() > Index)
4358 O = &O->getArrayInitializedElt(Index);
4359 else if (!isRead(handler.AccessKind)) {
4360 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT);
4361 CAT && !CheckArraySize(Info, CAT, E->getExprLoc()))
4362 return handler.failed();
4363
4364 expandArray(*O, Index);
4365 O = &O->getArrayInitializedElt(Index);
4366 } else
4367 O = &O->getArrayFiller();
4368 } else if (ObjType->isAnyComplexType()) {
4369 // Next subobject is a complex number.
4370 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
4371 if (Index > 1) {
4372 if (Info.getLangOpts().CPlusPlus11)
4373 Info.FFDiag(E, diag::note_constexpr_access_past_end)
4374 << handler.AccessKind;
4375 else
4376 Info.FFDiag(E);
4377 return handler.failed();
4378 }
4379
4380 ObjType = getSubobjectType(
4381 ObjType, ObjType->castAs<ComplexType>()->getElementType());
4382
4383 assert(I == N - 1 && "extracting subobject of scalar?");
4384 if (O->isComplexInt()) {
4385 return handler.found(Index ? O->getComplexIntImag()
4386 : O->getComplexIntReal(), ObjType);
4387 } else {
4388 assert(O->isComplexFloat());
4389 return handler.found(Index ? O->getComplexFloatImag()
4390 : O->getComplexFloatReal(), ObjType);
4391 }
4392 } else if (const auto *VT = ObjType->getAs<VectorType>()) {
4393 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
4394 unsigned NumElements = VT->getNumElements();
4395 if (Index == NumElements) {
4396 if (Info.getLangOpts().CPlusPlus11)
4397 Info.FFDiag(E, diag::note_constexpr_access_past_end)
4398 << handler.AccessKind;
4399 else
4400 Info.FFDiag(E);
4401 return handler.failed();
4402 }
4403
4404 if (Index > NumElements) {
4405 Info.CCEDiag(E, diag::note_constexpr_array_index)
4406 << Index << /*array*/ 0 << NumElements;
4407 return handler.failed();
4408 }
4409
4410 ObjType = VT->getElementType();
4411 assert(I == N - 1 && "extracting subobject of scalar?");
4412 return handler.found(O->getVectorElt(Index), ObjType);
4413 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
4414 if (Field->isMutable() &&
4415 !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) {
4416 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
4417 << handler.AccessKind << Field;
4418 Info.Note(Field->getLocation(), diag::note_declared_at);
4419 return handler.failed();
4420 }
4421
4422 // Next subobject is a class, struct or union field.
4423 RecordDecl *RD = ObjType->castAsCanonical<RecordType>()->getDecl();
4424 if (RD->isUnion()) {
4425 const FieldDecl *UnionField = O->getUnionField();
4426 if (!UnionField ||
4427 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
4428 if (I == N - 1 && handler.AccessKind == AK_Construct) {
4429 // Placement new onto an inactive union member makes it active.
4430 O->setUnion(Field, APValue());
4431 } else {
4432 // Pointer to/into inactive union member: Not within lifetime
4433 if (handler.AccessKind == AK_IsWithinLifetime)
4434 return false;
4435 // FIXME: If O->getUnionValue() is absent, report that there's no
4436 // active union member rather than reporting the prior active union
4437 // member. We'll need to fix nullptr_t to not use APValue() as its
4438 // representation first.
4439 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
4440 << handler.AccessKind << Field << !UnionField << UnionField;
4441 return handler.failed();
4442 }
4443 }
4444 O = &O->getUnionValue();
4445 } else
4446 O = &O->getStructField(Field->getFieldIndex());
4447
4448 ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
4449 LastField = Field;
4450 if (Field->getType().isVolatileQualified())
4451 VolatileField = Field;
4452 } else {
4453 // Next subobject is a base class.
4454 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
4455 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
4456 O = &O->getStructBase(getBaseIndex(Derived, Base));
4457
4458 ObjType = getSubobjectType(ObjType, Info.Ctx.getCanonicalTagType(Base));
4459 }
4460 }
4461}
4462
4463namespace {
4464struct ExtractSubobjectHandler {
4465 EvalInfo &Info;
4466 const Expr *E;
4467 APValue &Result;
4468 const AccessKinds AccessKind;
4469
4470 typedef bool result_type;
4471 bool failed() { return false; }
4472 bool found(APValue &Subobj, QualType SubobjType) {
4473 Result = Subobj;
4474 if (AccessKind == AK_ReadObjectRepresentation)
4475 return true;
4476 return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
4477 }
4478 bool found(APSInt &Value, QualType SubobjType) {
4479 Result = APValue(Value);
4480 return true;
4481 }
4482 bool found(APFloat &Value, QualType SubobjType) {
4483 Result = APValue(Value);
4484 return true;
4485 }
4486};
4487} // end anonymous namespace
4488
4489/// Extract the designated sub-object of an rvalue.
4490static bool extractSubobject(EvalInfo &Info, const Expr *E,
4491 const CompleteObject &Obj,
4492 const SubobjectDesignator &Sub, APValue &Result,
4493 AccessKinds AK = AK_Read) {
4494 assert(AK == AK_Read || AK == AK_ReadObjectRepresentation);
4495 ExtractSubobjectHandler Handler = {Info, E, Result, AK};
4496 return findSubobject(Info, E, Obj, Sub, Handler);
4497}
4498
4499namespace {
4500struct ModifySubobjectHandler {
4501 EvalInfo &Info;
4502 APValue &NewVal;
4503 const Expr *E;
4504
4505 typedef bool result_type;
4506 static const AccessKinds AccessKind = AK_Assign;
4507
4508 bool checkConst(QualType QT) {
4509 // Assigning to a const object has undefined behavior.
4510 if (QT.isConstQualified()) {
4511 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4512 return false;
4513 }
4514 return true;
4515 }
4516
4517 bool failed() { return false; }
4518 bool found(APValue &Subobj, QualType SubobjType) {
4519 if (!checkConst(SubobjType))
4520 return false;
4521 // We've been given ownership of NewVal, so just swap it in.
4522 Subobj.swap(NewVal);
4523 return true;
4524 }
4525 bool found(APSInt &Value, QualType SubobjType) {
4526 if (!checkConst(SubobjType))
4527 return false;
4528 if (!NewVal.isInt()) {
4529 // Maybe trying to write a cast pointer value into a complex?
4530 Info.FFDiag(E);
4531 return false;
4532 }
4533 Value = NewVal.getInt();
4534 return true;
4535 }
4536 bool found(APFloat &Value, QualType SubobjType) {
4537 if (!checkConst(SubobjType))
4538 return false;
4539 Value = NewVal.getFloat();
4540 return true;
4541 }
4542};
4543} // end anonymous namespace
4544
4545const AccessKinds ModifySubobjectHandler::AccessKind;
4546
4547/// Update the designated sub-object of an rvalue to the given value.
4548static bool modifySubobject(EvalInfo &Info, const Expr *E,
4549 const CompleteObject &Obj,
4550 const SubobjectDesignator &Sub,
4551 APValue &NewVal) {
4552 ModifySubobjectHandler Handler = { Info, NewVal, E };
4553 return findSubobject(Info, E, Obj, Sub, Handler);
4554}
4555
4556/// Find the position where two subobject designators diverge, or equivalently
4557/// the length of the common initial subsequence.
4558static unsigned FindDesignatorMismatch(QualType ObjType,
4559 const SubobjectDesignator &A,
4560 const SubobjectDesignator &B,
4561 bool &WasArrayIndex) {
4562 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
4563 for (/**/; I != N; ++I) {
4564 if (!ObjType.isNull() &&
4565 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
4566 // Next subobject is an array element.
4567 if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
4568 WasArrayIndex = true;
4569 return I;
4570 }
4571 if (ObjType->isAnyComplexType())
4572 ObjType = ObjType->castAs<ComplexType>()->getElementType();
4573 else
4574 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
4575 } else {
4576 if (A.Entries[I].getAsBaseOrMember() !=
4577 B.Entries[I].getAsBaseOrMember()) {
4578 WasArrayIndex = false;
4579 return I;
4580 }
4581 if (const FieldDecl *FD = getAsField(A.Entries[I]))
4582 // Next subobject is a field.
4583 ObjType = FD->getType();
4584 else
4585 // Next subobject is a base class.
4586 ObjType = QualType();
4587 }
4588 }
4589 WasArrayIndex = false;
4590 return I;
4591}
4592
4593/// Determine whether the given subobject designators refer to elements of the
4594/// same array object.
4596 const SubobjectDesignator &A,
4597 const SubobjectDesignator &B) {
4598 if (A.Entries.size() != B.Entries.size())
4599 return false;
4600
4601 bool IsArray = A.MostDerivedIsArrayElement;
4602 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
4603 // A is a subobject of the array element.
4604 return false;
4605
4606 // If A (and B) designates an array element, the last entry will be the array
4607 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
4608 // of length 1' case, and the entire path must match.
4609 bool WasArrayIndex;
4610 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
4611 return CommonLength >= A.Entries.size() - IsArray;
4612}
4613
4614/// Find the complete object to which an LValue refers.
4615static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
4616 AccessKinds AK, const LValue &LVal,
4617 QualType LValType) {
4618 if (LVal.InvalidBase) {
4619 Info.FFDiag(E);
4620 return CompleteObject();
4621 }
4622
4623 if (!LVal.Base) {
4625 Info.FFDiag(E, diag::note_constexpr_dereferencing_null);
4626 else
4627 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
4628 return CompleteObject();
4629 }
4630
4631 CallStackFrame *Frame = nullptr;
4632 unsigned Depth = 0;
4633 if (LVal.getLValueCallIndex()) {
4634 std::tie(Frame, Depth) =
4635 Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
4636 if (!Frame) {
4637 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
4638 << AK << LVal.Base.is<const ValueDecl*>();
4639 NoteLValueLocation(Info, LVal.Base);
4640 return CompleteObject();
4641 }
4642 }
4643
4644 bool IsAccess = isAnyAccess(AK);
4645
4646 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
4647 // is not a constant expression (even if the object is non-volatile). We also
4648 // apply this rule to C++98, in order to conform to the expected 'volatile'
4649 // semantics.
4650 if (isFormalAccess(AK) && LValType.isVolatileQualified()) {
4651 if (Info.getLangOpts().CPlusPlus)
4652 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
4653 << AK << LValType;
4654 else
4655 Info.FFDiag(E);
4656 return CompleteObject();
4657 }
4658
4659 // Compute value storage location and type of base object.
4660 APValue *BaseVal = nullptr;
4661 QualType BaseType = getType(LVal.Base);
4662
4663 if (Info.getLangOpts().CPlusPlus14 && LVal.Base == Info.EvaluatingDecl &&
4664 lifetimeStartedInEvaluation(Info, LVal.Base)) {
4665 // This is the object whose initializer we're evaluating, so its lifetime
4666 // started in the current evaluation.
4667 BaseVal = Info.EvaluatingDeclValue;
4668 } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) {
4669 // Allow reading from a GUID declaration.
4670 if (auto *GD = dyn_cast<MSGuidDecl>(D)) {
4671 if (isModification(AK)) {
4672 // All the remaining cases do not permit modification of the object.
4673 Info.FFDiag(E, diag::note_constexpr_modify_global);
4674 return CompleteObject();
4675 }
4676 APValue &V = GD->getAsAPValue();
4677 if (V.isAbsent()) {
4678 Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
4679 << GD->getType();
4680 return CompleteObject();
4681 }
4682 return CompleteObject(LVal.Base, &V, GD->getType());
4683 }
4684
4685 // Allow reading the APValue from an UnnamedGlobalConstantDecl.
4686 if (auto *GCD = dyn_cast<UnnamedGlobalConstantDecl>(D)) {
4687 if (isModification(AK)) {
4688 Info.FFDiag(E, diag::note_constexpr_modify_global);
4689 return CompleteObject();
4690 }
4691 return CompleteObject(LVal.Base, const_cast<APValue *>(&GCD->getValue()),
4692 GCD->getType());
4693 }
4694
4695 // Allow reading from template parameter objects.
4696 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) {
4697 if (isModification(AK)) {
4698 Info.FFDiag(E, diag::note_constexpr_modify_global);
4699 return CompleteObject();
4700 }
4701 return CompleteObject(LVal.Base, const_cast<APValue *>(&TPO->getValue()),
4702 TPO->getType());
4703 }
4704
4705 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
4706 // In C++11, constexpr, non-volatile variables initialized with constant
4707 // expressions are constant expressions too. Inside constexpr functions,
4708 // parameters are constant expressions even if they're non-const.
4709 // In C++1y, objects local to a constant expression (those with a Frame) are
4710 // both readable and writable inside constant expressions.
4711 // In C, such things can also be folded, although they are not ICEs.
4712 const VarDecl *VD = dyn_cast<VarDecl>(D);
4713 if (VD) {
4714 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
4715 VD = VDef;
4716 }
4717 if (!VD || VD->isInvalidDecl()) {
4718 Info.FFDiag(E);
4719 return CompleteObject();
4720 }
4721
4722 bool IsConstant = BaseType.isConstant(Info.Ctx);
4723 bool ConstexprVar = false;
4724 if (const auto *VD = dyn_cast_if_present<VarDecl>(
4725 Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()))
4726 ConstexprVar = VD->isConstexpr();
4727
4728 // Unless we're looking at a local variable or argument in a constexpr call,
4729 // the variable we're reading must be const (unless we are binding to a
4730 // reference).
4731 if (AK != clang::AK_Dereference && !Frame) {
4732 if (IsAccess && isa<ParmVarDecl>(VD)) {
4733 // Access of a parameter that's not associated with a frame isn't going
4734 // to work out, but we can leave it to evaluateVarDeclInit to provide a
4735 // suitable diagnostic.
4736 } else if (Info.getLangOpts().CPlusPlus14 &&
4737 lifetimeStartedInEvaluation(Info, LVal.Base)) {
4738 // OK, we can read and modify an object if we're in the process of
4739 // evaluating its initializer, because its lifetime began in this
4740 // evaluation.
4741 } else if (isModification(AK)) {
4742 // All the remaining cases do not permit modification of the object.
4743 Info.FFDiag(E, diag::note_constexpr_modify_global);
4744 return CompleteObject();
4745 } else if (VD->isConstexpr()) {
4746 // OK, we can read this variable.
4747 } else if (Info.getLangOpts().C23 && ConstexprVar) {
4748 Info.FFDiag(E);
4749 return CompleteObject();
4750 } else if (BaseType->isIntegralOrEnumerationType()) {
4751 if (!IsConstant) {
4752 if (!IsAccess)
4753 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4754 if (Info.getLangOpts().CPlusPlus) {
4755 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
4756 Info.Note(VD->getLocation(), diag::note_declared_at);
4757 } else {
4758 Info.FFDiag(E);
4759 }
4760 return CompleteObject();
4761 }
4762 } else if (!IsAccess) {
4763 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4764 } else if ((IsConstant || BaseType->isReferenceType()) &&
4765 Info.checkingPotentialConstantExpression() &&
4766 BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) {
4767 // This variable might end up being constexpr. Don't diagnose it yet.
4768 } else if (IsConstant) {
4769 // Keep evaluating to see what we can do. In particular, we support
4770 // folding of const floating-point types, in order to make static const
4771 // data members of such types (supported as an extension) more useful.
4772 if (Info.getLangOpts().CPlusPlus) {
4773 Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11
4774 ? diag::note_constexpr_ltor_non_constexpr
4775 : diag::note_constexpr_ltor_non_integral, 1)
4776 << VD << BaseType;
4777 Info.Note(VD->getLocation(), diag::note_declared_at);
4778 } else {
4779 Info.CCEDiag(E);
4780 }
4781 } else {
4782 // Never allow reading a non-const value.
4783 if (Info.getLangOpts().CPlusPlus) {
4784 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
4785 ? diag::note_constexpr_ltor_non_constexpr
4786 : diag::note_constexpr_ltor_non_integral, 1)
4787 << VD << BaseType;
4788 Info.Note(VD->getLocation(), diag::note_declared_at);
4789 } else {
4790 Info.FFDiag(E);
4791 }
4792 return CompleteObject();
4793 }
4794 }
4795
4796 // When binding to a reference, the variable does not need to be constexpr
4797 // or have constant initalization.
4798 if (AK != clang::AK_Dereference &&
4799 !evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(),
4800 BaseVal))
4801 return CompleteObject();
4802 // If evaluateVarDeclInit sees a constexpr-unknown variable, it returns
4803 // a null BaseVal. Any constexpr-unknown variable seen here is an error:
4804 // we can't access a constexpr-unknown object.
4805 if (AK != clang::AK_Dereference && !BaseVal) {
4806 if (!Info.checkingPotentialConstantExpression()) {
4807 Info.FFDiag(E, diag::note_constexpr_access_unknown_variable, 1)
4808 << AK << VD;
4809 Info.Note(VD->getLocation(), diag::note_declared_at);
4810 }
4811 return CompleteObject();
4812 }
4813 } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) {
4814 std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
4815 if (!Alloc) {
4816 Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK;
4817 return CompleteObject();
4818 }
4819 return CompleteObject(LVal.Base, &(*Alloc)->Value,
4820 LVal.Base.getDynamicAllocType());
4821 }
4822 // When binding to a reference, the variable does not need to be
4823 // within its lifetime.
4824 else if (AK != clang::AK_Dereference) {
4825 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4826
4827 if (!Frame) {
4828 if (const MaterializeTemporaryExpr *MTE =
4829 dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
4830 assert(MTE->getStorageDuration() == SD_Static &&
4831 "should have a frame for a non-global materialized temporary");
4832
4833 // C++20 [expr.const]p4: [DR2126]
4834 // An object or reference is usable in constant expressions if it is
4835 // - a temporary object of non-volatile const-qualified literal type
4836 // whose lifetime is extended to that of a variable that is usable
4837 // in constant expressions
4838 //
4839 // C++20 [expr.const]p5:
4840 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
4841 // - a non-volatile glvalue that refers to an object that is usable
4842 // in constant expressions, or
4843 // - a non-volatile glvalue of literal type that refers to a
4844 // non-volatile object whose lifetime began within the evaluation
4845 // of E;
4846 //
4847 // C++11 misses the 'began within the evaluation of e' check and
4848 // instead allows all temporaries, including things like:
4849 // int &&r = 1;
4850 // int x = ++r;
4851 // constexpr int k = r;
4852 // Therefore we use the C++14-onwards rules in C++11 too.
4853 //
4854 // Note that temporaries whose lifetimes began while evaluating a
4855 // variable's constructor are not usable while evaluating the
4856 // corresponding destructor, not even if they're of const-qualified
4857 // types.
4858 if (!MTE->isUsableInConstantExpressions(Info.Ctx) &&
4859 !lifetimeStartedInEvaluation(Info, LVal.Base)) {
4860 if (!IsAccess)
4861 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4862 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
4863 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
4864 return CompleteObject();
4865 }
4866
4867 BaseVal = MTE->getOrCreateValue(false);
4868 assert(BaseVal && "got reference to unevaluated temporary");
4869 } else if (const CompoundLiteralExpr *CLE =
4870 dyn_cast_or_null<CompoundLiteralExpr>(Base)) {
4871 // According to GCC info page:
4872 //
4873 // 6.28 Compound Literals
4874 //
4875 // As an optimization, G++ sometimes gives array compound literals
4876 // longer lifetimes: when the array either appears outside a function or
4877 // has a const-qualified type. If foo and its initializer had elements
4878 // of type char *const rather than char *, or if foo were a global
4879 // variable, the array would have static storage duration. But it is
4880 // probably safest just to avoid the use of array compound literals in
4881 // C++ code.
4882 //
4883 // Obey that rule by checking constness for converted array types.
4884 if (QualType CLETy = CLE->getType(); CLETy->isArrayType() &&
4885 !LValType->isArrayType() &&
4886 !CLETy.isConstant(Info.Ctx)) {
4887 Info.FFDiag(E);
4888 Info.Note(CLE->getExprLoc(), diag::note_declared_at);
4889 return CompleteObject();
4890 }
4891
4892 BaseVal = &CLE->getStaticValue();
4893 } else {
4894 if (!IsAccess)
4895 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4896 APValue Val;
4897 LVal.moveInto(Val);
4898 Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
4899 << AK
4900 << Val.getAsString(Info.Ctx,
4901 Info.Ctx.getLValueReferenceType(LValType));
4902 NoteLValueLocation(Info, LVal.Base);
4903 return CompleteObject();
4904 }
4905 } else if (AK != clang::AK_Dereference) {
4906 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
4907 assert(BaseVal && "missing value for temporary");
4908 }
4909 }
4910
4911 // In C++14, we can't safely access any mutable state when we might be
4912 // evaluating after an unmodeled side effect. Parameters are modeled as state
4913 // in the caller, but aren't visible once the call returns, so they can be
4914 // modified in a speculatively-evaluated call.
4915 //
4916 // FIXME: Not all local state is mutable. Allow local constant subobjects
4917 // to be read here (but take care with 'mutable' fields).
4918 unsigned VisibleDepth = Depth;
4919 if (llvm::isa_and_nonnull<ParmVarDecl>(
4920 LVal.Base.dyn_cast<const ValueDecl *>()))
4921 ++VisibleDepth;
4922 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
4923 Info.EvalStatus.HasSideEffects) ||
4924 (isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth))
4925 return CompleteObject();
4926
4927 return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
4928}
4929
4930/// Perform an lvalue-to-rvalue conversion on the given glvalue. This
4931/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
4932/// glvalue referred to by an entity of reference type.
4933///
4934/// \param Info - Information about the ongoing evaluation.
4935/// \param Conv - The expression for which we are performing the conversion.
4936/// Used for diagnostics.
4937/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
4938/// case of a non-class type).
4939/// \param LVal - The glvalue on which we are attempting to perform this action.
4940/// \param RVal - The produced value will be placed here.
4941/// \param WantObjectRepresentation - If true, we're looking for the object
4942/// representation rather than the value, and in particular,
4943/// there is no requirement that the result be fully initialized.
4944static bool
4946 const LValue &LVal, APValue &RVal,
4947 bool WantObjectRepresentation = false) {
4948 if (LVal.Designator.Invalid)
4949 return false;
4950
4951 // Check for special cases where there is no existing APValue to look at.
4952 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4953
4954 AccessKinds AK =
4955 WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;
4956
4957 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
4959 // Special-case character extraction so we don't have to construct an
4960 // APValue for the whole string.
4961 assert(LVal.Designator.Entries.size() <= 1 &&
4962 "Can only read characters from string literals");
4963 if (LVal.Designator.Entries.empty()) {
4964 // Fail for now for LValue to RValue conversion of an array.
4965 // (This shouldn't show up in C/C++, but it could be triggered by a
4966 // weird EvaluateAsRValue call from a tool.)
4967 Info.FFDiag(Conv);
4968 return false;
4969 }
4970 if (LVal.Designator.isOnePastTheEnd()) {
4971 if (Info.getLangOpts().CPlusPlus11)
4972 Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
4973 else
4974 Info.FFDiag(Conv);
4975 return false;
4976 }
4977 uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
4978 RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
4979 return true;
4980 }
4981 }
4982
4983 CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
4984 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
4985}
4986
4987static bool hlslElementwiseCastHelper(EvalInfo &Info, const Expr *E,
4988 QualType DestTy,
4989 SmallVectorImpl<APValue> &SrcVals,
4990 SmallVectorImpl<QualType> &SrcTypes) {
4991 APValue Val;
4992 if (!Evaluate(Val, Info, E))
4993 return false;
4994
4995 // must be dealing with a record
4996 if (Val.isLValue()) {
4997 LValue LVal;
4998 LVal.setFrom(Info.Ctx, Val);
4999 if (!handleLValueToRValueConversion(Info, E, E->getType(), LVal, Val))
5000 return false;
5001 }
5002
5003 unsigned NEls = elementwiseSize(Info, DestTy);
5004 // flatten the source
5005 if (!flattenAPValue(Info, E, Val, E->getType(), SrcVals, SrcTypes, NEls))
5006 return false;
5007
5008 return true;
5009}
5010
5011/// Perform an assignment of Val to LVal. Takes ownership of Val.
5012static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
5013 QualType LValType, APValue &Val) {
5014 if (LVal.Designator.Invalid)
5015 return false;
5016
5017 if (!Info.getLangOpts().CPlusPlus14) {
5018 Info.FFDiag(E);
5019 return false;
5020 }
5021
5022 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
5023 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
5024}
5025
5026namespace {
5027struct CompoundAssignSubobjectHandler {
5028 EvalInfo &Info;
5029 const CompoundAssignOperator *E;
5030 QualType PromotedLHSType;
5032 const APValue &RHS;
5033
5034 static const AccessKinds AccessKind = AK_Assign;
5035
5036 typedef bool result_type;
5037
5038 bool checkConst(QualType QT) {
5039 // Assigning to a const object has undefined behavior.
5040 if (QT.isConstQualified()) {
5041 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
5042 return false;
5043 }
5044 return true;
5045 }
5046
5047 bool failed() { return false; }
5048 bool found(APValue &Subobj, QualType SubobjType) {
5049 switch (Subobj.getKind()) {
5050 case APValue::Int:
5051 return found(Subobj.getInt(), SubobjType);
5052 case APValue::Float:
5053 return found(Subobj.getFloat(), SubobjType);
5056 // FIXME: Implement complex compound assignment.
5057 Info.FFDiag(E);
5058 return false;
5059 case APValue::LValue:
5060 return foundPointer(Subobj, SubobjType);
5061 case APValue::Vector:
5062 return foundVector(Subobj, SubobjType);
5064 Info.FFDiag(E, diag::note_constexpr_access_uninit)
5065 << /*read of=*/0 << /*uninitialized object=*/1
5066 << E->getLHS()->getSourceRange();
5067 return false;
5068 default:
5069 // FIXME: can this happen?
5070 Info.FFDiag(E);
5071 return false;
5072 }
5073 }
5074
5075 bool foundVector(APValue &Value, QualType SubobjType) {
5076 if (!checkConst(SubobjType))
5077 return false;
5078
5079 if (!SubobjType->isVectorType()) {
5080 Info.FFDiag(E);
5081 return false;
5082 }
5083 return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS);
5084 }
5085
5086 bool found(APSInt &Value, QualType SubobjType) {
5087 if (!checkConst(SubobjType))
5088 return false;
5089
5090 if (!SubobjType->isIntegerType()) {
5091 // We don't support compound assignment on integer-cast-to-pointer
5092 // values.
5093 Info.FFDiag(E);
5094 return false;
5095 }
5096
5097 if (RHS.isInt()) {
5098 APSInt LHS =
5099 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
5100 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
5101 return false;
5102 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
5103 return true;
5104 } else if (RHS.isFloat()) {
5105 const FPOptions FPO = E->getFPFeaturesInEffect(
5106 Info.Ctx.getLangOpts());
5107 APFloat FValue(0.0);
5108 return HandleIntToFloatCast(Info, E, FPO, SubobjType, Value,
5109 PromotedLHSType, FValue) &&
5110 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
5111 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
5112 Value);
5113 }
5114
5115 Info.FFDiag(E);
5116 return false;
5117 }
5118 bool found(APFloat &Value, QualType SubobjType) {
5119 return checkConst(SubobjType) &&
5120 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
5121 Value) &&
5122 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
5123 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
5124 }
5125 bool foundPointer(APValue &Subobj, QualType SubobjType) {
5126 if (!checkConst(SubobjType))
5127 return false;
5128
5129 QualType PointeeType;
5130 if (const PointerType *PT = SubobjType->getAs<PointerType>())
5131 PointeeType = PT->getPointeeType();
5132
5133 if (PointeeType.isNull() || !RHS.isInt() ||
5134 (Opcode != BO_Add && Opcode != BO_Sub)) {
5135 Info.FFDiag(E);
5136 return false;
5137 }
5138
5139 APSInt Offset = RHS.getInt();
5140 if (Opcode == BO_Sub)
5141 negateAsSigned(Offset);
5142
5143 LValue LVal;
5144 LVal.setFrom(Info.Ctx, Subobj);
5145 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
5146 return false;
5147 LVal.moveInto(Subobj);
5148 return true;
5149 }
5150};
5151} // end anonymous namespace
5152
5153const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
5154
5155/// Perform a compound assignment of LVal <op>= RVal.
5156static bool handleCompoundAssignment(EvalInfo &Info,
5157 const CompoundAssignOperator *E,
5158 const LValue &LVal, QualType LValType,
5159 QualType PromotedLValType,
5160 BinaryOperatorKind Opcode,
5161 const APValue &RVal) {
5162 if (LVal.Designator.Invalid)
5163 return false;
5164
5165 if (!Info.getLangOpts().CPlusPlus14) {
5166 Info.FFDiag(E);
5167 return false;
5168 }
5169
5170 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
5171 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
5172 RVal };
5173 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
5174}
5175
5176namespace {
5177struct IncDecSubobjectHandler {
5178 EvalInfo &Info;
5179 const UnaryOperator *E;
5181 APValue *Old;
5182
5183 typedef bool result_type;
5184
5185 bool checkConst(QualType QT) {
5186 // Assigning to a const object has undefined behavior.
5187 if (QT.isConstQualified()) {
5188 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
5189 return false;
5190 }
5191 return true;
5192 }
5193
5194 bool failed() { return false; }
5195 bool found(APValue &Subobj, QualType SubobjType) {
5196 // Stash the old value. Also clear Old, so we don't clobber it later
5197 // if we're post-incrementing a complex.
5198 if (Old) {
5199 *Old = Subobj;
5200 Old = nullptr;
5201 }
5202
5203 switch (Subobj.getKind()) {
5204 case APValue::Int:
5205 return found(Subobj.getInt(), SubobjType);
5206 case APValue::Float:
5207 return found(Subobj.getFloat(), SubobjType);
5209 return found(Subobj.getComplexIntReal(),
5210 SubobjType->castAs<ComplexType>()->getElementType()
5211 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
5213 return found(Subobj.getComplexFloatReal(),
5214 SubobjType->castAs<ComplexType>()->getElementType()
5215 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
5216 case APValue::LValue:
5217 return foundPointer(Subobj, SubobjType);
5218 default:
5219 // FIXME: can this happen?
5220 Info.FFDiag(E);
5221 return false;
5222 }
5223 }
5224 bool found(APSInt &Value, QualType SubobjType) {
5225 if (!checkConst(SubobjType))
5226 return false;
5227
5228 if (!SubobjType->isIntegerType()) {
5229 // We don't support increment / decrement on integer-cast-to-pointer
5230 // values.
5231 Info.FFDiag(E);
5232 return false;
5233 }
5234
5235 if (Old) *Old = APValue(Value);
5236
5237 // bool arithmetic promotes to int, and the conversion back to bool
5238 // doesn't reduce mod 2^n, so special-case it.
5239 if (SubobjType->isBooleanType()) {
5240 if (AccessKind == AK_Increment)
5241 Value = 1;
5242 else
5243 Value = !Value;
5244 return true;
5245 }
5246
5247 bool WasNegative = Value.isNegative();
5248 if (AccessKind == AK_Increment) {
5249 ++Value;
5250
5251 if (!WasNegative && Value.isNegative() && E->canOverflow()) {
5252 APSInt ActualValue(Value, /*IsUnsigned*/true);
5253 return HandleOverflow(Info, E, ActualValue, SubobjType);
5254 }
5255 } else {
5256 --Value;
5257
5258 if (WasNegative && !Value.isNegative() && E->canOverflow()) {
5259 unsigned BitWidth = Value.getBitWidth();
5260 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
5261 ActualValue.setBit(BitWidth);
5262 return HandleOverflow(Info, E, ActualValue, SubobjType);
5263 }
5264 }
5265 return true;
5266 }
5267 bool found(APFloat &Value, QualType SubobjType) {
5268 if (!checkConst(SubobjType))
5269 return false;
5270
5271 if (Old) *Old = APValue(Value);
5272
5273 APFloat One(Value.getSemantics(), 1);
5274 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
5275 APFloat::opStatus St;
5276 if (AccessKind == AK_Increment)
5277 St = Value.add(One, RM);
5278 else
5279 St = Value.subtract(One, RM);
5280 return checkFloatingPointResult(Info, E, St);
5281 }
5282 bool foundPointer(APValue &Subobj, QualType SubobjType) {
5283 if (!checkConst(SubobjType))
5284 return false;
5285
5286 QualType PointeeType;
5287 if (const PointerType *PT = SubobjType->getAs<PointerType>())
5288 PointeeType = PT->getPointeeType();
5289 else {
5290 Info.FFDiag(E);
5291 return false;
5292 }
5293
5294 LValue LVal;
5295 LVal.setFrom(Info.Ctx, Subobj);
5296 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
5297 AccessKind == AK_Increment ? 1 : -1))
5298 return false;
5299 LVal.moveInto(Subobj);
5300 return true;
5301 }
5302};
5303} // end anonymous namespace
5304
5305/// Perform an increment or decrement on LVal.
5306static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
5307 QualType LValType, bool IsIncrement, APValue *Old) {
5308 if (LVal.Designator.Invalid)
5309 return false;
5310
5311 if (!Info.getLangOpts().CPlusPlus14) {
5312 Info.FFDiag(E);
5313 return false;
5314 }
5315
5316 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
5317 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
5318 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
5319 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
5320}
5321
5322/// Build an lvalue for the object argument of a member function call.
5323static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
5324 LValue &This) {
5325 if (Object->getType()->isPointerType() && Object->isPRValue())
5326 return EvaluatePointer(Object, This, Info);
5327
5328 if (Object->isGLValue())
5329 return EvaluateLValue(Object, This, Info);
5330
5331 if (Object->getType()->isLiteralType(Info.Ctx))
5332 return EvaluateTemporary(Object, This, Info);
5333
5334 if (Object->getType()->isRecordType() && Object->isPRValue())
5335 return EvaluateTemporary(Object, This, Info);
5336
5337 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
5338 return false;
5339}
5340
5341/// HandleMemberPointerAccess - Evaluate a member access operation and build an
5342/// lvalue referring to the result.
5343///
5344/// \param Info - Information about the ongoing evaluation.
5345/// \param LV - An lvalue referring to the base of the member pointer.
5346/// \param RHS - The member pointer expression.
5347/// \param IncludeMember - Specifies whether the member itself is included in
5348/// the resulting LValue subobject designator. This is not possible when
5349/// creating a bound member function.
5350/// \return The field or method declaration to which the member pointer refers,
5351/// or 0 if evaluation fails.
5352static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
5353 QualType LVType,
5354 LValue &LV,
5355 const Expr *RHS,
5356 bool IncludeMember = true) {
5357 MemberPtr MemPtr;
5358 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
5359 return nullptr;
5360
5361 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
5362 // member value, the behavior is undefined.
5363 if (!MemPtr.getDecl()) {
5364 // FIXME: Specific diagnostic.
5365 Info.FFDiag(RHS);
5366 return nullptr;
5367 }
5368
5369 if (MemPtr.isDerivedMember()) {
5370 // This is a member of some derived class. Truncate LV appropriately.
5371 // The end of the derived-to-base path for the base object must match the
5372 // derived-to-base path for the member pointer.
5373 // C++23 [expr.mptr.oper]p4:
5374 // If the result of E1 is an object [...] whose most derived object does
5375 // not contain the member to which E2 refers, the behavior is undefined.
5376 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
5377 LV.Designator.Entries.size()) {
5378 Info.FFDiag(RHS);
5379 return nullptr;
5380 }
5381 unsigned PathLengthToMember =
5382 LV.Designator.Entries.size() - MemPtr.Path.size();
5383 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
5384 const CXXRecordDecl *LVDecl = getAsBaseClass(
5385 LV.Designator.Entries[PathLengthToMember + I]);
5386 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
5387 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
5388 Info.FFDiag(RHS);
5389 return nullptr;
5390 }
5391 }
5392 // MemPtr.Path only contains the base classes of the class directly
5393 // containing the member E2. It is still necessary to check that the class
5394 // directly containing the member E2 lies on the derived-to-base path of E1
5395 // to avoid incorrectly permitting member pointer access into a sibling
5396 // class of the class containing the member E2. If this class would
5397 // correspond to the most-derived class of E1, it either isn't contained in
5398 // LV.Designator.Entries or the corresponding entry refers to an array
5399 // element instead. Therefore get the most derived class directly in this
5400 // case. Otherwise the previous entry should correpond to this class.
5401 const CXXRecordDecl *LastLVDecl =
5402 (PathLengthToMember > LV.Designator.MostDerivedPathLength)
5403 ? getAsBaseClass(LV.Designator.Entries[PathLengthToMember - 1])
5404 : LV.Designator.MostDerivedType->getAsCXXRecordDecl();
5405 const CXXRecordDecl *LastMPDecl = MemPtr.getContainingRecord();
5406 if (LastLVDecl->getCanonicalDecl() != LastMPDecl->getCanonicalDecl()) {
5407 Info.FFDiag(RHS);
5408 return nullptr;
5409 }
5410
5411 // Truncate the lvalue to the appropriate derived class.
5412 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
5413 PathLengthToMember))
5414 return nullptr;
5415 } else if (!MemPtr.Path.empty()) {
5416 // Extend the LValue path with the member pointer's path.
5417 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
5418 MemPtr.Path.size() + IncludeMember);
5419
5420 // Walk down to the appropriate base class.
5421 if (const PointerType *PT = LVType->getAs<PointerType>())
5422 LVType = PT->getPointeeType();
5423 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
5424 assert(RD && "member pointer access on non-class-type expression");
5425 // The first class in the path is that of the lvalue.
5426 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
5427 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
5428 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
5429 return nullptr;
5430 RD = Base;
5431 }
5432 // Finally cast to the class containing the member.
5433 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
5434 MemPtr.getContainingRecord()))
5435 return nullptr;
5436 }
5437
5438 // Add the member. Note that we cannot build bound member functions here.
5439 if (IncludeMember) {
5440 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
5441 if (!HandleLValueMember(Info, RHS, LV, FD))
5442 return nullptr;
5443 } else if (const IndirectFieldDecl *IFD =
5444 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
5445 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
5446 return nullptr;
5447 } else {
5448 llvm_unreachable("can't construct reference to bound member function");
5449 }
5450 }
5451
5452 return MemPtr.getDecl();
5453}
5454
5455static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
5456 const BinaryOperator *BO,
5457 LValue &LV,
5458 bool IncludeMember = true) {
5459 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
5460
5461 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
5462 if (Info.noteFailure()) {
5463 MemberPtr MemPtr;
5464 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
5465 }
5466 return nullptr;
5467 }
5468
5469 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
5470 BO->getRHS(), IncludeMember);
5471}
5472
5473/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
5474/// the provided lvalue, which currently refers to the base object.
5475static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
5476 LValue &Result) {
5477 SubobjectDesignator &D = Result.Designator;
5478 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
5479 return false;
5480
5481 QualType TargetQT = E->getType();
5482 if (const PointerType *PT = TargetQT->getAs<PointerType>())
5483 TargetQT = PT->getPointeeType();
5484
5485 auto InvalidCast = [&]() {
5486 if (!Info.checkingPotentialConstantExpression() ||
5487 !Result.AllowConstexprUnknown) {
5488 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
5489 << D.MostDerivedType << TargetQT;
5490 }
5491 return false;
5492 };
5493
5494 // Check this cast lands within the final derived-to-base subobject path.
5495 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size())
5496 return InvalidCast();
5497
5498 // Check the type of the final cast. We don't need to check the path,
5499 // since a cast can only be formed if the path is unique.
5500 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
5501 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
5502 const CXXRecordDecl *FinalType;
5503 if (NewEntriesSize == D.MostDerivedPathLength)
5504 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
5505 else
5506 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
5507 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl())
5508 return InvalidCast();
5509
5510 // Truncate the lvalue to the appropriate derived class.
5511 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
5512}
5513
5514/// Get the value to use for a default-initialized object of type T.
5515/// Return false if it encounters something invalid.
5517 bool Success = true;
5518
5519 // If there is already a value present don't overwrite it.
5520 if (!Result.isAbsent())
5521 return true;
5522
5523 if (auto *RD = T->getAsCXXRecordDecl()) {
5524 if (RD->isInvalidDecl()) {
5525 Result = APValue();
5526 return false;
5527 }
5528 if (RD->isUnion()) {
5529 Result = APValue((const FieldDecl *)nullptr);
5530 return true;
5531 }
5532 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
5533 std::distance(RD->field_begin(), RD->field_end()));
5534
5535 unsigned Index = 0;
5536 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
5537 End = RD->bases_end();
5538 I != End; ++I, ++Index)
5539 Success &=
5540 handleDefaultInitValue(I->getType(), Result.getStructBase(Index));
5541
5542 for (const auto *I : RD->fields()) {
5543 if (I->isUnnamedBitField())
5544 continue;
5546 I->getType(), Result.getStructField(I->getFieldIndex()));
5547 }
5548 return Success;
5549 }
5550
5551 if (auto *AT =
5552 dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
5553 Result = APValue(APValue::UninitArray(), 0, AT->getZExtSize());
5554 if (Result.hasArrayFiller())
5555 Success &=
5556 handleDefaultInitValue(AT->getElementType(), Result.getArrayFiller());
5557
5558 return Success;
5559 }
5560
5561 Result = APValue::IndeterminateValue();
5562 return true;
5563}
5564
5565namespace {
5566enum EvalStmtResult {
5567 /// Evaluation failed.
5568 ESR_Failed,
5569 /// Hit a 'return' statement.
5570 ESR_Returned,
5571 /// Evaluation succeeded.
5572 ESR_Succeeded,
5573 /// Hit a 'continue' statement.
5574 ESR_Continue,
5575 /// Hit a 'break' statement.
5576 ESR_Break,
5577 /// Still scanning for 'case' or 'default' statement.
5578 ESR_CaseNotFound
5579};
5580}
5581/// Evaluates the initializer of a reference.
5582static bool EvaluateInitForDeclOfReferenceType(EvalInfo &Info,
5583 const ValueDecl *D,
5584 const Expr *Init, LValue &Result,
5585 APValue &Val) {
5586 assert(Init->isGLValue() && D->getType()->isReferenceType());
5587 // A reference is an lvalue.
5588 if (!EvaluateLValue(Init, Result, Info))
5589 return false;
5590 // [C++26][decl.ref]
5591 // The object designated by such a glvalue can be outside its lifetime
5592 // Because a null pointer value or a pointer past the end of an object
5593 // does not point to an object, a reference in a well-defined program cannot
5594 // refer to such things;
5595 if (!Result.Designator.Invalid && Result.Designator.isOnePastTheEnd()) {
5596 Info.FFDiag(Init, diag::note_constexpr_access_past_end) << AK_Dereference;
5597 return false;
5598 }
5599
5600 // Save the result.
5601 Result.moveInto(Val);
5602 return true;
5603}
5604
5605static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
5606 if (VD->isInvalidDecl())
5607 return false;
5608 // We don't need to evaluate the initializer for a static local.
5609 if (!VD->hasLocalStorage())
5610 return true;
5611
5612 LValue Result;
5613 APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(),
5614 ScopeKind::Block, Result);
5615
5616 const Expr *InitE = VD->getInit();
5617 if (!InitE) {
5618 if (VD->getType()->isDependentType())
5619 return Info.noteSideEffect();
5620 return handleDefaultInitValue(VD->getType(), Val);
5621 }
5622 if (InitE->isValueDependent())
5623 return false;
5624
5625 // For references to objects, check they do not designate a one-past-the-end
5626 // object.
5627 if (VD->getType()->isReferenceType()) {
5628 return EvaluateInitForDeclOfReferenceType(Info, VD, InitE, Result, Val);
5629 } else if (!EvaluateInPlace(Val, Info, Result, InitE)) {
5630 // Wipe out any partially-computed value, to allow tracking that this
5631 // evaluation failed.
5632 Val = APValue();
5633 return false;
5634 }
5635
5636 return true;
5637}
5638
5639static bool EvaluateDecompositionDeclInit(EvalInfo &Info,
5640 const DecompositionDecl *DD);
5641
5642static bool EvaluateDecl(EvalInfo &Info, const Decl *D,
5643 bool EvaluateConditionDecl = false) {
5644 bool OK = true;
5645 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
5646 OK &= EvaluateVarDecl(Info, VD);
5647
5648 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D);
5649 EvaluateConditionDecl && DD)
5650 OK &= EvaluateDecompositionDeclInit(Info, DD);
5651
5652 return OK;
5653}
5654
5655static bool EvaluateDecompositionDeclInit(EvalInfo &Info,
5656 const DecompositionDecl *DD) {
5657 bool OK = true;
5658 for (auto *BD : DD->flat_bindings())
5659 if (auto *VD = BD->getHoldingVar())
5660 OK &= EvaluateDecl(Info, VD, /*EvaluateConditionDecl=*/true);
5661
5662 return OK;
5663}
5664
5665static bool MaybeEvaluateDeferredVarDeclInit(EvalInfo &Info,
5666 const VarDecl *VD) {
5667 if (auto *DD = dyn_cast_if_present<DecompositionDecl>(VD)) {
5668 if (!EvaluateDecompositionDeclInit(Info, DD))
5669 return false;
5670 }
5671 return true;
5672}
5673
5674static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info) {
5675 assert(E->isValueDependent());
5676 if (Info.noteSideEffect())
5677 return true;
5678 assert(E->containsErrors() && "valid value-dependent expression should never "
5679 "reach invalid code path.");
5680 return false;
5681}
5682
5683/// Evaluate a condition (either a variable declaration or an expression).
5684static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
5685 const Expr *Cond, bool &Result) {
5686 if (Cond->isValueDependent())
5687 return false;
5688 FullExpressionRAII Scope(Info);
5689 if (CondDecl && !EvaluateDecl(Info, CondDecl))
5690 return false;
5691 if (!EvaluateAsBooleanCondition(Cond, Result, Info))
5692 return false;
5693 if (!MaybeEvaluateDeferredVarDeclInit(Info, CondDecl))
5694 return false;
5695 return Scope.destroy();
5696}
5697
5698namespace {
5699/// A location where the result (returned value) of evaluating a
5700/// statement should be stored.
5701struct StmtResult {
5702 /// The APValue that should be filled in with the returned value.
5703 APValue &Value;
5704 /// The location containing the result, if any (used to support RVO).
5705 const LValue *Slot;
5706};
5707
5708struct TempVersionRAII {
5709 CallStackFrame &Frame;
5710
5711 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
5712 Frame.pushTempVersion();
5713 }
5714
5715 ~TempVersionRAII() {
5716 Frame.popTempVersion();
5717 }
5718};
5719
5720}
5721
5722static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
5723 const Stmt *S,
5724 const SwitchCase *SC = nullptr);
5725
5726/// Helper to implement named break/continue. Returns 'true' if the evaluation
5727/// result should be propagated up. Otherwise, it sets the evaluation result
5728/// to either Continue to continue the current loop, or Succeeded to break it.
5729static bool ShouldPropagateBreakContinue(EvalInfo &Info,
5730 const Stmt *LoopOrSwitch,
5732 EvalStmtResult &ESR) {
5733 bool IsSwitch = isa<SwitchStmt>(LoopOrSwitch);
5734
5735 // For loops, map Succeeded to Continue so we don't have to check for both.
5736 if (!IsSwitch && ESR == ESR_Succeeded) {
5737 ESR = ESR_Continue;
5738 return false;
5739 }
5740
5741 if (ESR != ESR_Break && ESR != ESR_Continue)
5742 return false;
5743
5744 // Are we breaking out of or continuing this statement?
5745 bool CanBreakOrContinue = !IsSwitch || ESR == ESR_Break;
5746 const Stmt *StackTop = Info.BreakContinueStack.back();
5747 if (CanBreakOrContinue && (StackTop == nullptr || StackTop == LoopOrSwitch)) {
5748 Info.BreakContinueStack.pop_back();
5749 if (ESR == ESR_Break)
5750 ESR = ESR_Succeeded;
5751 return false;
5752 }
5753
5754 // We're not. Propagate the result up.
5755 for (BlockScopeRAII *S : Scopes) {
5756 if (!S->destroy()) {
5757 ESR = ESR_Failed;
5758 break;
5759 }
5760 }
5761 return true;
5762}
5763
5764/// Evaluate the body of a loop, and translate the result as appropriate.
5765static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
5766 const Stmt *Body,
5767 const SwitchCase *Case = nullptr) {
5768 BlockScopeRAII Scope(Info);
5769
5770 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case);
5771 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
5772 ESR = ESR_Failed;
5773
5774 return ESR;
5775}
5776
5777/// Evaluate a switch statement.
5778static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
5779 const SwitchStmt *SS) {
5780 BlockScopeRAII Scope(Info);
5781
5782 // Evaluate the switch condition.
5783 APSInt Value;
5784 {
5785 if (const Stmt *Init = SS->getInit()) {
5786 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
5787 if (ESR != ESR_Succeeded) {
5788 if (ESR != ESR_Failed && !Scope.destroy())
5789 ESR = ESR_Failed;
5790 return ESR;
5791 }
5792 }
5793
5794 FullExpressionRAII CondScope(Info);
5795 if (SS->getConditionVariable() &&
5796 !EvaluateDecl(Info, SS->getConditionVariable()))
5797 return ESR_Failed;
5798 if (SS->getCond()->isValueDependent()) {
5799 // We don't know what the value is, and which branch should jump to.
5800 EvaluateDependentExpr(SS->getCond(), Info);
5801 return ESR_Failed;
5802 }
5803 if (!EvaluateInteger(SS->getCond(), Value, Info))
5804 return ESR_Failed;
5805
5807 return ESR_Failed;
5808
5809 if (!CondScope.destroy())
5810 return ESR_Failed;
5811 }
5812
5813 // Find the switch case corresponding to the value of the condition.
5814 // FIXME: Cache this lookup.
5815 const SwitchCase *Found = nullptr;
5816 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
5817 SC = SC->getNextSwitchCase()) {
5818 if (isa<DefaultStmt>(SC)) {
5819 Found = SC;
5820 continue;
5821 }
5822
5823 const CaseStmt *CS = cast<CaseStmt>(SC);
5824 const Expr *LHS = CS->getLHS();
5825 const Expr *RHS = CS->getRHS();
5826 if (LHS->isValueDependent() || (RHS && RHS->isValueDependent()))
5827 return ESR_Failed;
5828 APSInt LHSValue = LHS->EvaluateKnownConstInt(Info.Ctx);
5829 APSInt RHSValue = RHS ? RHS->EvaluateKnownConstInt(Info.Ctx) : LHSValue;
5830 if (LHSValue <= Value && Value <= RHSValue) {
5831 Found = SC;
5832 break;
5833 }
5834 }
5835
5836 if (!Found)
5837 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5838
5839 // Search the switch body for the switch case and evaluate it from there.
5840 EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found);
5841 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
5842 return ESR_Failed;
5843 if (ShouldPropagateBreakContinue(Info, SS, /*Scopes=*/{}, ESR))
5844 return ESR;
5845
5846 switch (ESR) {
5847 case ESR_Break:
5848 llvm_unreachable("Should have been converted to Succeeded");
5849 case ESR_Succeeded:
5850 case ESR_Continue:
5851 case ESR_Failed:
5852 case ESR_Returned:
5853 return ESR;
5854 case ESR_CaseNotFound:
5855 // This can only happen if the switch case is nested within a statement
5856 // expression. We have no intention of supporting that.
5857 Info.FFDiag(Found->getBeginLoc(),
5858 diag::note_constexpr_stmt_expr_unsupported);
5859 return ESR_Failed;
5860 }
5861 llvm_unreachable("Invalid EvalStmtResult!");
5862}
5863
5864static bool CheckLocalVariableDeclaration(EvalInfo &Info, const VarDecl *VD) {
5865 // An expression E is a core constant expression unless the evaluation of E
5866 // would evaluate one of the following: [C++23] - a control flow that passes
5867 // through a declaration of a variable with static or thread storage duration
5868 // unless that variable is usable in constant expressions.
5869 if (VD->isLocalVarDecl() && VD->isStaticLocal() &&
5870 !VD->isUsableInConstantExpressions(Info.Ctx)) {
5871 Info.CCEDiag(VD->getLocation(), diag::note_constexpr_static_local)
5872 << (VD->getTSCSpec() == TSCS_unspecified ? 0 : 1) << VD;
5873 return false;
5874 }
5875 return true;
5876}
5877
5878// Evaluate a statement.
5879static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
5880 const Stmt *S, const SwitchCase *Case) {
5881 if (!Info.nextStep(S))
5882 return ESR_Failed;
5883
5884 // If we're hunting down a 'case' or 'default' label, recurse through
5885 // substatements until we hit the label.
5886 if (Case) {
5887 switch (S->getStmtClass()) {
5888 case Stmt::CompoundStmtClass:
5889 // FIXME: Precompute which substatement of a compound statement we
5890 // would jump to, and go straight there rather than performing a
5891 // linear scan each time.
5892 case Stmt::LabelStmtClass:
5893 case Stmt::AttributedStmtClass:
5894 case Stmt::DoStmtClass:
5895 break;
5896
5897 case Stmt::CaseStmtClass:
5898 case Stmt::DefaultStmtClass:
5899 if (Case == S)
5900 Case = nullptr;
5901 break;
5902
5903 case Stmt::IfStmtClass: {
5904 // FIXME: Precompute which side of an 'if' we would jump to, and go
5905 // straight there rather than scanning both sides.
5906 const IfStmt *IS = cast<IfStmt>(S);
5907
5908 // Wrap the evaluation in a block scope, in case it's a DeclStmt
5909 // preceded by our switch label.
5910 BlockScopeRAII Scope(Info);
5911
5912 // Step into the init statement in case it brings an (uninitialized)
5913 // variable into scope.
5914 if (const Stmt *Init = IS->getInit()) {
5915 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5916 if (ESR != ESR_CaseNotFound) {
5917 assert(ESR != ESR_Succeeded);
5918 return ESR;
5919 }
5920 }
5921
5922 // Condition variable must be initialized if it exists.
5923 // FIXME: We can skip evaluating the body if there's a condition
5924 // variable, as there can't be any case labels within it.
5925 // (The same is true for 'for' statements.)
5926
5927 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
5928 if (ESR == ESR_Failed)
5929 return ESR;
5930 if (ESR != ESR_CaseNotFound)
5931 return Scope.destroy() ? ESR : ESR_Failed;
5932 if (!IS->getElse())
5933 return ESR_CaseNotFound;
5934
5935 ESR = EvaluateStmt(Result, Info, IS->getElse(), Case);
5936 if (ESR == ESR_Failed)
5937 return ESR;
5938 if (ESR != ESR_CaseNotFound)
5939 return Scope.destroy() ? ESR : ESR_Failed;
5940 return ESR_CaseNotFound;
5941 }
5942
5943 case Stmt::WhileStmtClass: {
5944 EvalStmtResult ESR =
5945 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
5946 if (ShouldPropagateBreakContinue(Info, S, /*Scopes=*/{}, ESR))
5947 return ESR;
5948 if (ESR != ESR_Continue)
5949 return ESR;
5950 break;
5951 }
5952
5953 case Stmt::ForStmtClass: {
5954 const ForStmt *FS = cast<ForStmt>(S);
5955 BlockScopeRAII Scope(Info);
5956
5957 // Step into the init statement in case it brings an (uninitialized)
5958 // variable into scope.
5959 if (const Stmt *Init = FS->getInit()) {
5960 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5961 if (ESR != ESR_CaseNotFound) {
5962 assert(ESR != ESR_Succeeded);
5963 return ESR;
5964 }
5965 }
5966
5967 EvalStmtResult ESR =
5968 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
5969 if (ShouldPropagateBreakContinue(Info, FS, /*Scopes=*/{}, ESR))
5970 return ESR;
5971 if (ESR != ESR_Continue)
5972 return ESR;
5973 if (const auto *Inc = FS->getInc()) {
5974 if (Inc->isValueDependent()) {
5975 if (!EvaluateDependentExpr(Inc, Info))
5976 return ESR_Failed;
5977 } else {
5978 FullExpressionRAII IncScope(Info);
5979 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5980 return ESR_Failed;
5981 }
5982 }
5983 break;
5984 }
5985
5986 case Stmt::DeclStmtClass: {
5987 // Start the lifetime of any uninitialized variables we encounter. They
5988 // might be used by the selected branch of the switch.
5989 const DeclStmt *DS = cast<DeclStmt>(S);
5990 for (const auto *D : DS->decls()) {
5991 if (const auto *VD = dyn_cast<VarDecl>(D)) {
5992 if (!CheckLocalVariableDeclaration(Info, VD))
5993 return ESR_Failed;
5994 if (VD->hasLocalStorage() && !VD->getInit())
5995 if (!EvaluateVarDecl(Info, VD))
5996 return ESR_Failed;
5997 // FIXME: If the variable has initialization that can't be jumped
5998 // over, bail out of any immediately-surrounding compound-statement
5999 // too. There can't be any case labels here.
6000 }
6001 }
6002 return ESR_CaseNotFound;
6003 }
6004
6005 default:
6006 return ESR_CaseNotFound;
6007 }
6008 }
6009
6010 switch (S->getStmtClass()) {
6011 default:
6012 if (const Expr *E = dyn_cast<Expr>(S)) {
6013 if (E->isValueDependent()) {
6014 if (!EvaluateDependentExpr(E, Info))
6015 return ESR_Failed;
6016 } else {
6017 // Don't bother evaluating beyond an expression-statement which couldn't
6018 // be evaluated.
6019 // FIXME: Do we need the FullExpressionRAII object here?
6020 // VisitExprWithCleanups should create one when necessary.
6021 FullExpressionRAII Scope(Info);
6022 if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy())
6023 return ESR_Failed;
6024 }
6025 return ESR_Succeeded;
6026 }
6027
6028 Info.FFDiag(S->getBeginLoc()) << S->getSourceRange();
6029 return ESR_Failed;
6030
6031 case Stmt::NullStmtClass:
6032 return ESR_Succeeded;
6033
6034 case Stmt::DeclStmtClass: {
6035 const DeclStmt *DS = cast<DeclStmt>(S);
6036 for (const auto *D : DS->decls()) {
6037 const VarDecl *VD = dyn_cast_or_null<VarDecl>(D);
6038 if (VD && !CheckLocalVariableDeclaration(Info, VD))
6039 return ESR_Failed;
6040 // Each declaration initialization is its own full-expression.
6041 FullExpressionRAII Scope(Info);
6042 if (!EvaluateDecl(Info, D, /*EvaluateConditionDecl=*/true) &&
6043 !Info.noteFailure())
6044 return ESR_Failed;
6045 if (!Scope.destroy())
6046 return ESR_Failed;
6047 }
6048 return ESR_Succeeded;
6049 }
6050
6051 case Stmt::ReturnStmtClass: {
6052 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
6053 FullExpressionRAII Scope(Info);
6054 if (RetExpr && RetExpr->isValueDependent()) {
6055 EvaluateDependentExpr(RetExpr, Info);
6056 // We know we returned, but we don't know what the value is.
6057 return ESR_Failed;
6058 }
6059 if (RetExpr &&
6060 !(Result.Slot
6061 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
6062 : Evaluate(Result.Value, Info, RetExpr)))
6063 return ESR_Failed;
6064 return Scope.destroy() ? ESR_Returned : ESR_Failed;
6065 }
6066
6067 case Stmt::CompoundStmtClass: {
6068 BlockScopeRAII Scope(Info);
6069
6070 const CompoundStmt *CS = cast<CompoundStmt>(S);
6071 for (const auto *BI : CS->body()) {
6072 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
6073 if (ESR == ESR_Succeeded)
6074 Case = nullptr;
6075 else if (ESR != ESR_CaseNotFound) {
6076 if (ESR != ESR_Failed && !Scope.destroy())
6077 return ESR_Failed;
6078 return ESR;
6079 }
6080 }
6081 if (Case)
6082 return ESR_CaseNotFound;
6083 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
6084 }
6085
6086 case Stmt::IfStmtClass: {
6087 const IfStmt *IS = cast<IfStmt>(S);
6088
6089 // Evaluate the condition, as either a var decl or as an expression.
6090 BlockScopeRAII Scope(Info);
6091 if (const Stmt *Init = IS->getInit()) {
6092 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
6093 if (ESR != ESR_Succeeded) {
6094 if (ESR != ESR_Failed && !Scope.destroy())
6095 return ESR_Failed;
6096 return ESR;
6097 }
6098 }
6099 bool Cond;
6100 if (IS->isConsteval()) {
6102 // If we are not in a constant context, if consteval should not evaluate
6103 // to true.
6104 if (!Info.InConstantContext)
6105 Cond = !Cond;
6106 } else if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(),
6107 Cond))
6108 return ESR_Failed;
6109
6110 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
6111 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
6112 if (ESR != ESR_Succeeded) {
6113 if (ESR != ESR_Failed && !Scope.destroy())
6114 return ESR_Failed;
6115 return ESR;
6116 }
6117 }
6118 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
6119 }
6120
6121 case Stmt::WhileStmtClass: {
6122 const WhileStmt *WS = cast<WhileStmt>(S);
6123 while (true) {
6124 BlockScopeRAII Scope(Info);
6125 bool Continue;
6126 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
6127 Continue))
6128 return ESR_Failed;
6129 if (!Continue)
6130 break;
6131
6132 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
6133 if (ShouldPropagateBreakContinue(Info, WS, &Scope, ESR))
6134 return ESR;
6135
6136 if (ESR != ESR_Continue) {
6137 if (ESR != ESR_Failed && !Scope.destroy())
6138 return ESR_Failed;
6139 return ESR;
6140 }
6141 if (!Scope.destroy())
6142 return ESR_Failed;
6143 }
6144 return ESR_Succeeded;
6145 }
6146
6147 case Stmt::DoStmtClass: {
6148 const DoStmt *DS = cast<DoStmt>(S);
6149 bool Continue;
6150 do {
6151 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
6152 if (ShouldPropagateBreakContinue(Info, DS, /*Scopes=*/{}, ESR))
6153 return ESR;
6154 if (ESR != ESR_Continue)
6155 return ESR;
6156 Case = nullptr;
6157
6158 if (DS->getCond()->isValueDependent()) {
6159 EvaluateDependentExpr(DS->getCond(), Info);
6160 // Bailout as we don't know whether to keep going or terminate the loop.
6161 return ESR_Failed;
6162 }
6163 FullExpressionRAII CondScope(Info);
6164 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) ||
6165 !CondScope.destroy())
6166 return ESR_Failed;
6167 } while (Continue);
6168 return ESR_Succeeded;
6169 }
6170
6171 case Stmt::ForStmtClass: {
6172 const ForStmt *FS = cast<ForStmt>(S);
6173 BlockScopeRAII ForScope(Info);
6174 if (FS->getInit()) {
6175 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
6176 if (ESR != ESR_Succeeded) {
6177 if (ESR != ESR_Failed && !ForScope.destroy())
6178 return ESR_Failed;
6179 return ESR;
6180 }
6181 }
6182 while (true) {
6183 BlockScopeRAII IterScope(Info);
6184 bool Continue = true;
6185 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
6186 FS->getCond(), Continue))
6187 return ESR_Failed;
6188
6189 if (!Continue) {
6190 if (!IterScope.destroy())
6191 return ESR_Failed;
6192 break;
6193 }
6194
6195 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
6196 if (ShouldPropagateBreakContinue(Info, FS, {&IterScope, &ForScope}, ESR))
6197 return ESR;
6198 if (ESR != ESR_Continue) {
6199 if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))
6200 return ESR_Failed;
6201 return ESR;
6202 }
6203
6204 if (const auto *Inc = FS->getInc()) {
6205 if (Inc->isValueDependent()) {
6206 if (!EvaluateDependentExpr(Inc, Info))
6207 return ESR_Failed;
6208 } else {
6209 FullExpressionRAII IncScope(Info);
6210 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
6211 return ESR_Failed;
6212 }
6213 }
6214
6215 if (!IterScope.destroy())
6216 return ESR_Failed;
6217 }
6218 return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;
6219 }
6220
6221 case Stmt::CXXForRangeStmtClass: {
6223 BlockScopeRAII Scope(Info);
6224
6225 // Evaluate the init-statement if present.
6226 if (FS->getInit()) {
6227 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
6228 if (ESR != ESR_Succeeded) {
6229 if (ESR != ESR_Failed && !Scope.destroy())
6230 return ESR_Failed;
6231 return ESR;
6232 }
6233 }
6234
6235 // Initialize the __range variable.
6236 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
6237 if (ESR != ESR_Succeeded) {
6238 if (ESR != ESR_Failed && !Scope.destroy())
6239 return ESR_Failed;
6240 return ESR;
6241 }
6242
6243 // In error-recovery cases it's possible to get here even if we failed to
6244 // synthesize the __begin and __end variables.
6245 if (!FS->getBeginStmt() || !FS->getEndStmt() || !FS->getCond())
6246 return ESR_Failed;
6247
6248 // Create the __begin and __end iterators.
6249 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
6250 if (ESR != ESR_Succeeded) {
6251 if (ESR != ESR_Failed && !Scope.destroy())
6252 return ESR_Failed;
6253 return ESR;
6254 }
6255 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
6256 if (ESR != ESR_Succeeded) {
6257 if (ESR != ESR_Failed && !Scope.destroy())
6258 return ESR_Failed;
6259 return ESR;
6260 }
6261
6262 while (true) {
6263 // Condition: __begin != __end.
6264 {
6265 if (FS->getCond()->isValueDependent()) {
6266 EvaluateDependentExpr(FS->getCond(), Info);
6267 // We don't know whether to keep going or terminate the loop.
6268 return ESR_Failed;
6269 }
6270 bool Continue = true;
6271 FullExpressionRAII CondExpr(Info);
6272 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
6273 return ESR_Failed;
6274 if (!Continue)
6275 break;
6276 }
6277
6278 // User's variable declaration, initialized by *__begin.
6279 BlockScopeRAII InnerScope(Info);
6280 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
6281 if (ESR != ESR_Succeeded) {
6282 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
6283 return ESR_Failed;
6284 return ESR;
6285 }
6286
6287 // Loop body.
6288 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
6289 if (ShouldPropagateBreakContinue(Info, FS, {&InnerScope, &Scope}, ESR))
6290 return ESR;
6291 if (ESR != ESR_Continue) {
6292 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
6293 return ESR_Failed;
6294 return ESR;
6295 }
6296 if (FS->getInc()->isValueDependent()) {
6297 if (!EvaluateDependentExpr(FS->getInc(), Info))
6298 return ESR_Failed;
6299 } else {
6300 // Increment: ++__begin
6301 if (!EvaluateIgnoredValue(Info, FS->getInc()))
6302 return ESR_Failed;
6303 }
6304
6305 if (!InnerScope.destroy())
6306 return ESR_Failed;
6307 }
6308
6309 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
6310 }
6311
6312 case Stmt::SwitchStmtClass:
6313 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
6314
6315 case Stmt::ContinueStmtClass:
6316 case Stmt::BreakStmtClass: {
6317 auto *B = cast<LoopControlStmt>(S);
6318 Info.BreakContinueStack.push_back(B->getNamedLoopOrSwitch());
6319 return isa<ContinueStmt>(S) ? ESR_Continue : ESR_Break;
6320 }
6321
6322 case Stmt::LabelStmtClass:
6323 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
6324
6325 case Stmt::AttributedStmtClass: {
6326 const auto *AS = cast<AttributedStmt>(S);
6327 const auto *SS = AS->getSubStmt();
6328 MSConstexprContextRAII ConstexprContext(
6329 *Info.CurrentCall, hasSpecificAttr<MSConstexprAttr>(AS->getAttrs()) &&
6330 isa<ReturnStmt>(SS));
6331
6332 auto LO = Info.getASTContext().getLangOpts();
6333 if (LO.CXXAssumptions && !LO.MSVCCompat) {
6334 for (auto *Attr : AS->getAttrs()) {
6335 auto *AA = dyn_cast<CXXAssumeAttr>(Attr);
6336 if (!AA)
6337 continue;
6338
6339 auto *Assumption = AA->getAssumption();
6340 if (Assumption->isValueDependent())
6341 return ESR_Failed;
6342
6343 if (Assumption->HasSideEffects(Info.getASTContext()))
6344 continue;
6345
6346 bool Value;
6347 if (!EvaluateAsBooleanCondition(Assumption, Value, Info))
6348 return ESR_Failed;
6349 if (!Value) {
6350 Info.CCEDiag(Assumption->getExprLoc(),
6351 diag::note_constexpr_assumption_failed);
6352 return ESR_Failed;
6353 }
6354 }
6355 }
6356
6357 return EvaluateStmt(Result, Info, SS, Case);
6358 }
6359
6360 case Stmt::CaseStmtClass:
6361 case Stmt::DefaultStmtClass:
6362 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
6363 case Stmt::CXXTryStmtClass:
6364 // Evaluate try blocks by evaluating all sub statements.
6365 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
6366 }
6367}
6368
6369/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
6370/// default constructor. If so, we'll fold it whether or not it's marked as
6371/// constexpr. If it is marked as constexpr, we will never implicitly define it,
6372/// so we need special handling.
6373static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
6374 const CXXConstructorDecl *CD,
6375 bool IsValueInitialization) {
6376 if (!CD->isTrivial() || !CD->isDefaultConstructor())
6377 return false;
6378
6379 // Value-initialization does not call a trivial default constructor, so such a
6380 // call is a core constant expression whether or not the constructor is
6381 // constexpr.
6382 if (!CD->isConstexpr() && !IsValueInitialization) {
6383 if (Info.getLangOpts().CPlusPlus11) {
6384 // FIXME: If DiagDecl is an implicitly-declared special member function,
6385 // we should be much more explicit about why it's not constexpr.
6386 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
6387 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
6388 Info.Note(CD->getLocation(), diag::note_declared_at);
6389 } else {
6390 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
6391 }
6392 }
6393 return true;
6394}
6395
6396/// CheckConstexprFunction - Check that a function can be called in a constant
6397/// expression.
6398static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
6400 const FunctionDecl *Definition,
6401 const Stmt *Body) {
6402 // Potential constant expressions can contain calls to declared, but not yet
6403 // defined, constexpr functions.
6404 if (Info.checkingPotentialConstantExpression() && !Definition &&
6405 Declaration->isConstexpr())
6406 return false;
6407
6408 // Bail out if the function declaration itself is invalid. We will
6409 // have produced a relevant diagnostic while parsing it, so just
6410 // note the problematic sub-expression.
6411 if (Declaration->isInvalidDecl()) {
6412 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
6413 return false;
6414 }
6415
6416 // DR1872: An instantiated virtual constexpr function can't be called in a
6417 // constant expression (prior to C++20). We can still constant-fold such a
6418 // call.
6419 if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) &&
6420 cast<CXXMethodDecl>(Declaration)->isVirtual())
6421 Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
6422
6423 if (Definition && Definition->isInvalidDecl()) {
6424 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
6425 return false;
6426 }
6427
6428 // Can we evaluate this function call?
6429 if (Definition && Body &&
6430 (Definition->isConstexpr() || (Info.CurrentCall->CanEvalMSConstexpr &&
6431 Definition->hasAttr<MSConstexprAttr>())))
6432 return true;
6433
6434 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
6435 // Special note for the assert() macro, as the normal error message falsely
6436 // implies we cannot use an assertion during constant evaluation.
6437 if (CallLoc.isMacroID() && DiagDecl->getIdentifier()) {
6438 // FIXME: Instead of checking for an implementation-defined function,
6439 // check and evaluate the assert() macro.
6440 StringRef Name = DiagDecl->getName();
6441 bool AssertFailed =
6442 Name == "__assert_rtn" || Name == "__assert_fail" || Name == "_wassert";
6443 if (AssertFailed) {
6444 Info.FFDiag(CallLoc, diag::note_constexpr_assert_failed);
6445 return false;
6446 }
6447 }
6448
6449 if (Info.getLangOpts().CPlusPlus11) {
6450 // If this function is not constexpr because it is an inherited
6451 // non-constexpr constructor, diagnose that directly.
6452 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
6453 if (CD && CD->isInheritingConstructor()) {
6454 auto *Inherited = CD->getInheritedConstructor().getConstructor();
6455 if (!Inherited->isConstexpr())
6456 DiagDecl = CD = Inherited;
6457 }
6458
6459 // FIXME: If DiagDecl is an implicitly-declared special member function
6460 // or an inheriting constructor, we should be much more explicit about why
6461 // it's not constexpr.
6462 if (CD && CD->isInheritingConstructor())
6463 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
6464 << CD->getInheritedConstructor().getConstructor()->getParent();
6465 else
6466 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
6467 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
6468 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
6469 } else {
6470 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
6471 }
6472 return false;
6473}
6474
6475namespace {
6476struct CheckDynamicTypeHandler {
6478 typedef bool result_type;
6479 bool failed() { return false; }
6480 bool found(APValue &Subobj, QualType SubobjType) { return true; }
6481 bool found(APSInt &Value, QualType SubobjType) { return true; }
6482 bool found(APFloat &Value, QualType SubobjType) { return true; }
6483};
6484} // end anonymous namespace
6485
6486/// Check that we can access the notional vptr of an object / determine its
6487/// dynamic type.
6488static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
6489 AccessKinds AK, bool Polymorphic) {
6490 if (This.Designator.Invalid)
6491 return false;
6492
6493 CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
6494
6495 if (!Obj)
6496 return false;
6497
6498 if (!Obj.Value) {
6499 // The object is not usable in constant expressions, so we can't inspect
6500 // its value to see if it's in-lifetime or what the active union members
6501 // are. We can still check for a one-past-the-end lvalue.
6502 if (This.Designator.isOnePastTheEnd() ||
6503 This.Designator.isMostDerivedAnUnsizedArray()) {
6504 Info.FFDiag(E, This.Designator.isOnePastTheEnd()
6505 ? diag::note_constexpr_access_past_end
6506 : diag::note_constexpr_access_unsized_array)
6507 << AK;
6508 return false;
6509 } else if (Polymorphic) {
6510 // Conservatively refuse to perform a polymorphic operation if we would
6511 // not be able to read a notional 'vptr' value.
6512 if (!Info.checkingPotentialConstantExpression() ||
6513 !This.AllowConstexprUnknown) {
6514 APValue Val;
6515 This.moveInto(Val);
6516 QualType StarThisType =
6517 Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
6518 Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
6519 << AK << Val.getAsString(Info.Ctx, StarThisType);
6520 }
6521 return false;
6522 }
6523 return true;
6524 }
6525
6526 CheckDynamicTypeHandler Handler{AK};
6527 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
6528}
6529
6530/// Check that the pointee of the 'this' pointer in a member function call is
6531/// either within its lifetime or in its period of construction or destruction.
6532static bool
6534 const LValue &This,
6535 const CXXMethodDecl *NamedMember) {
6536 return checkDynamicType(
6537 Info, E, This,
6538 isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false);
6539}
6540
6542 /// The dynamic class type of the object.
6544 /// The corresponding path length in the lvalue.
6545 unsigned PathLength;
6546};
6547
6548static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
6549 unsigned PathLength) {
6550 assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
6551 Designator.Entries.size() && "invalid path length");
6552 return (PathLength == Designator.MostDerivedPathLength)
6553 ? Designator.MostDerivedType->getAsCXXRecordDecl()
6554 : getAsBaseClass(Designator.Entries[PathLength - 1]);
6555}
6556
6557/// Determine the dynamic type of an object.
6558static std::optional<DynamicType> ComputeDynamicType(EvalInfo &Info,
6559 const Expr *E,
6560 LValue &This,
6561 AccessKinds AK) {
6562 // If we don't have an lvalue denoting an object of class type, there is no
6563 // meaningful dynamic type. (We consider objects of non-class type to have no
6564 // dynamic type.)
6565 if (!checkDynamicType(Info, E, This, AK,
6566 AK != AK_TypeId || This.AllowConstexprUnknown))
6567 return std::nullopt;
6568
6569 if (This.Designator.Invalid)
6570 return std::nullopt;
6571
6572 // Refuse to compute a dynamic type in the presence of virtual bases. This
6573 // shouldn't happen other than in constant-folding situations, since literal
6574 // types can't have virtual bases.
6575 //
6576 // Note that consumers of DynamicType assume that the type has no virtual
6577 // bases, and will need modifications if this restriction is relaxed.
6578 const CXXRecordDecl *Class =
6579 This.Designator.MostDerivedType->getAsCXXRecordDecl();
6580 if (!Class || Class->getNumVBases()) {
6581 Info.FFDiag(E);
6582 return std::nullopt;
6583 }
6584
6585 // FIXME: For very deep class hierarchies, it might be beneficial to use a
6586 // binary search here instead. But the overwhelmingly common case is that
6587 // we're not in the middle of a constructor, so it probably doesn't matter
6588 // in practice.
6589 ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
6590 for (unsigned PathLength = This.Designator.MostDerivedPathLength;
6591 PathLength <= Path.size(); ++PathLength) {
6592 switch (Info.isEvaluatingCtorDtor(This.getLValueBase(),
6593 Path.slice(0, PathLength))) {
6594 case ConstructionPhase::Bases:
6595 case ConstructionPhase::DestroyingBases:
6596 // We're constructing or destroying a base class. This is not the dynamic
6597 // type.
6598 break;
6599
6600 case ConstructionPhase::None:
6601 case ConstructionPhase::AfterBases:
6602 case ConstructionPhase::AfterFields:
6603 case ConstructionPhase::Destroying:
6604 // We've finished constructing the base classes and not yet started
6605 // destroying them again, so this is the dynamic type.
6606 return DynamicType{getBaseClassType(This.Designator, PathLength),
6607 PathLength};
6608 }
6609 }
6610
6611 // CWG issue 1517: we're constructing a base class of the object described by
6612 // 'This', so that object has not yet begun its period of construction and
6613 // any polymorphic operation on it results in undefined behavior.
6614 Info.FFDiag(E);
6615 return std::nullopt;
6616}
6617
6618/// Perform virtual dispatch.
6620 EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
6621 llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
6622 std::optional<DynamicType> DynType = ComputeDynamicType(
6623 Info, E, This,
6625 if (!DynType)
6626 return nullptr;
6627
6628 // Find the final overrider. It must be declared in one of the classes on the
6629 // path from the dynamic type to the static type.
6630 // FIXME: If we ever allow literal types to have virtual base classes, that
6631 // won't be true.
6632 const CXXMethodDecl *Callee = Found;
6633 unsigned PathLength = DynType->PathLength;
6634 for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
6635 const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
6636 const CXXMethodDecl *Overrider =
6637 Found->getCorrespondingMethodDeclaredInClass(Class, false);
6638 if (Overrider) {
6639 Callee = Overrider;
6640 break;
6641 }
6642 }
6643
6644 // C++2a [class.abstract]p6:
6645 // the effect of making a virtual call to a pure virtual function [...] is
6646 // undefined
6647 if (Callee->isPureVirtual()) {
6648 Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
6649 Info.Note(Callee->getLocation(), diag::note_declared_at);
6650 return nullptr;
6651 }
6652
6653 // If necessary, walk the rest of the path to determine the sequence of
6654 // covariant adjustment steps to apply.
6655 if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
6656 Found->getReturnType())) {
6657 CovariantAdjustmentPath.push_back(Callee->getReturnType());
6658 for (unsigned CovariantPathLength = PathLength + 1;
6659 CovariantPathLength != This.Designator.Entries.size();
6660 ++CovariantPathLength) {
6661 const CXXRecordDecl *NextClass =
6662 getBaseClassType(This.Designator, CovariantPathLength);
6663 const CXXMethodDecl *Next =
6664 Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
6665 if (Next && !Info.Ctx.hasSameUnqualifiedType(
6666 Next->getReturnType(), CovariantAdjustmentPath.back()))
6667 CovariantAdjustmentPath.push_back(Next->getReturnType());
6668 }
6669 if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
6670 CovariantAdjustmentPath.back()))
6671 CovariantAdjustmentPath.push_back(Found->getReturnType());
6672 }
6673
6674 // Perform 'this' adjustment.
6675 if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
6676 return nullptr;
6677
6678 return Callee;
6679}
6680
6681/// Perform the adjustment from a value returned by a virtual function to
6682/// a value of the statically expected type, which may be a pointer or
6683/// reference to a base class of the returned type.
6684static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
6685 APValue &Result,
6686 ArrayRef<QualType> Path) {
6687 assert(Result.isLValue() &&
6688 "unexpected kind of APValue for covariant return");
6689 if (Result.isNullPointer())
6690 return true;
6691
6692 LValue LVal;
6693 LVal.setFrom(Info.Ctx, Result);
6694
6695 const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
6696 for (unsigned I = 1; I != Path.size(); ++I) {
6697 const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
6698 assert(OldClass && NewClass && "unexpected kind of covariant return");
6699 if (OldClass != NewClass &&
6700 !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
6701 return false;
6702 OldClass = NewClass;
6703 }
6704
6705 LVal.moveInto(Result);
6706 return true;
6707}
6708
6709/// Determine whether \p Base, which is known to be a direct base class of
6710/// \p Derived, is a public base class.
6711static bool isBaseClassPublic(const CXXRecordDecl *Derived,
6712 const CXXRecordDecl *Base) {
6713 for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
6714 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
6715 if (BaseClass && declaresSameEntity(BaseClass, Base))
6716 return BaseSpec.getAccessSpecifier() == AS_public;
6717 }
6718 llvm_unreachable("Base is not a direct base of Derived");
6719}
6720
6721/// Apply the given dynamic cast operation on the provided lvalue.
6722///
6723/// This implements the hard case of dynamic_cast, requiring a "runtime check"
6724/// to find a suitable target subobject.
6725static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
6726 LValue &Ptr) {
6727 // We can't do anything with a non-symbolic pointer value.
6728 SubobjectDesignator &D = Ptr.Designator;
6729 if (D.Invalid)
6730 return false;
6731
6732 // C++ [expr.dynamic.cast]p6:
6733 // If v is a null pointer value, the result is a null pointer value.
6734 if (Ptr.isNullPointer() && !E->isGLValue())
6735 return true;
6736
6737 // For all the other cases, we need the pointer to point to an object within
6738 // its lifetime / period of construction / destruction, and we need to know
6739 // its dynamic type.
6740 std::optional<DynamicType> DynType =
6741 ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
6742 if (!DynType)
6743 return false;
6744
6745 // C++ [expr.dynamic.cast]p7:
6746 // If T is "pointer to cv void", then the result is a pointer to the most
6747 // derived object
6748 if (E->getType()->isVoidPointerType())
6749 return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
6750
6752 assert(C && "dynamic_cast target is not void pointer nor class");
6753 CanQualType CQT = Info.Ctx.getCanonicalTagType(C);
6754
6755 auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
6756 // C++ [expr.dynamic.cast]p9:
6757 if (!E->isGLValue()) {
6758 // The value of a failed cast to pointer type is the null pointer value
6759 // of the required result type.
6760 Ptr.setNull(Info.Ctx, E->getType());
6761 return true;
6762 }
6763
6764 // A failed cast to reference type throws [...] std::bad_cast.
6765 unsigned DiagKind;
6766 if (!Paths && (declaresSameEntity(DynType->Type, C) ||
6767 DynType->Type->isDerivedFrom(C)))
6768 DiagKind = 0;
6769 else if (!Paths || Paths->begin() == Paths->end())
6770 DiagKind = 1;
6771 else if (Paths->isAmbiguous(CQT))
6772 DiagKind = 2;
6773 else {
6774 assert(Paths->front().Access != AS_public && "why did the cast fail?");
6775 DiagKind = 3;
6776 }
6777 Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
6778 << DiagKind << Ptr.Designator.getType(Info.Ctx)
6779 << Info.Ctx.getCanonicalTagType(DynType->Type)
6780 << E->getType().getUnqualifiedType();
6781 return false;
6782 };
6783
6784 // Runtime check, phase 1:
6785 // Walk from the base subobject towards the derived object looking for the
6786 // target type.
6787 for (int PathLength = Ptr.Designator.Entries.size();
6788 PathLength >= (int)DynType->PathLength; --PathLength) {
6789 const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
6790 if (declaresSameEntity(Class, C))
6791 return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
6792 // We can only walk across public inheritance edges.
6793 if (PathLength > (int)DynType->PathLength &&
6794 !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
6795 Class))
6796 return RuntimeCheckFailed(nullptr);
6797 }
6798
6799 // Runtime check, phase 2:
6800 // Search the dynamic type for an unambiguous public base of type C.
6801 CXXBasePaths Paths(/*FindAmbiguities=*/true,
6802 /*RecordPaths=*/true, /*DetectVirtual=*/false);
6803 if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
6804 Paths.front().Access == AS_public) {
6805 // Downcast to the dynamic type...
6806 if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
6807 return false;
6808 // ... then upcast to the chosen base class subobject.
6809 for (CXXBasePathElement &Elem : Paths.front())
6810 if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
6811 return false;
6812 return true;
6813 }
6814
6815 // Otherwise, the runtime check fails.
6816 return RuntimeCheckFailed(&Paths);
6817}
6818
6819namespace {
6820struct StartLifetimeOfUnionMemberHandler {
6821 EvalInfo &Info;
6822 const Expr *LHSExpr;
6823 const FieldDecl *Field;
6824 bool DuringInit;
6825 bool Failed = false;
6826 static const AccessKinds AccessKind = AK_Assign;
6827
6828 typedef bool result_type;
6829 bool failed() { return Failed; }
6830 bool found(APValue &Subobj, QualType SubobjType) {
6831 // We are supposed to perform no initialization but begin the lifetime of
6832 // the object. We interpret that as meaning to do what default
6833 // initialization of the object would do if all constructors involved were
6834 // trivial:
6835 // * All base, non-variant member, and array element subobjects' lifetimes
6836 // begin
6837 // * No variant members' lifetimes begin
6838 // * All scalar subobjects whose lifetimes begin have indeterminate values
6839 assert(SubobjType->isUnionType());
6840 if (declaresSameEntity(Subobj.getUnionField(), Field)) {
6841 // This union member is already active. If it's also in-lifetime, there's
6842 // nothing to do.
6843 if (Subobj.getUnionValue().hasValue())
6844 return true;
6845 } else if (DuringInit) {
6846 // We're currently in the process of initializing a different union
6847 // member. If we carried on, that initialization would attempt to
6848 // store to an inactive union member, resulting in undefined behavior.
6849 Info.FFDiag(LHSExpr,
6850 diag::note_constexpr_union_member_change_during_init);
6851 return false;
6852 }
6854 Failed = !handleDefaultInitValue(Field->getType(), Result);
6855 Subobj.setUnion(Field, Result);
6856 return true;
6857 }
6858 bool found(APSInt &Value, QualType SubobjType) {
6859 llvm_unreachable("wrong value kind for union object");
6860 }
6861 bool found(APFloat &Value, QualType SubobjType) {
6862 llvm_unreachable("wrong value kind for union object");
6863 }
6864};
6865} // end anonymous namespace
6866
6867const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
6868
6869/// Handle a builtin simple-assignment or a call to a trivial assignment
6870/// operator whose left-hand side might involve a union member access. If it
6871/// does, implicitly start the lifetime of any accessed union elements per
6872/// C++20 [class.union]5.
6873static bool MaybeHandleUnionActiveMemberChange(EvalInfo &Info,
6874 const Expr *LHSExpr,
6875 const LValue &LHS) {
6876 if (LHS.InvalidBase || LHS.Designator.Invalid)
6877 return false;
6878
6880 // C++ [class.union]p5:
6881 // define the set S(E) of subexpressions of E as follows:
6882 unsigned PathLength = LHS.Designator.Entries.size();
6883 for (const Expr *E = LHSExpr; E != nullptr;) {
6884 // -- If E is of the form A.B, S(E) contains the elements of S(A)...
6885 if (auto *ME = dyn_cast<MemberExpr>(E)) {
6886 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
6887 // Note that we can't implicitly start the lifetime of a reference,
6888 // so we don't need to proceed any further if we reach one.
6889 if (!FD || FD->getType()->isReferenceType())
6890 break;
6891
6892 // ... and also contains A.B if B names a union member ...
6893 if (FD->getParent()->isUnion()) {
6894 // ... of a non-class, non-array type, or of a class type with a
6895 // trivial default constructor that is not deleted, or an array of
6896 // such types.
6897 auto *RD =
6898 FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6899 if (!RD || RD->hasTrivialDefaultConstructor())
6900 UnionPathLengths.push_back({PathLength - 1, FD});
6901 }
6902
6903 E = ME->getBase();
6904 --PathLength;
6905 assert(declaresSameEntity(FD,
6906 LHS.Designator.Entries[PathLength]
6907 .getAsBaseOrMember().getPointer()));
6908
6909 // -- If E is of the form A[B] and is interpreted as a built-in array
6910 // subscripting operator, S(E) is [S(the array operand, if any)].
6911 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
6912 // Step over an ArrayToPointerDecay implicit cast.
6913 auto *Base = ASE->getBase()->IgnoreImplicit();
6914 if (!Base->getType()->isArrayType())
6915 break;
6916
6917 E = Base;
6918 --PathLength;
6919
6920 } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6921 // Step over a derived-to-base conversion.
6922 E = ICE->getSubExpr();
6923 if (ICE->getCastKind() == CK_NoOp)
6924 continue;
6925 if (ICE->getCastKind() != CK_DerivedToBase &&
6926 ICE->getCastKind() != CK_UncheckedDerivedToBase)
6927 break;
6928 // Walk path backwards as we walk up from the base to the derived class.
6929 for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
6930 if (Elt->isVirtual()) {
6931 // A class with virtual base classes never has a trivial default
6932 // constructor, so S(E) is empty in this case.
6933 E = nullptr;
6934 break;
6935 }
6936
6937 --PathLength;
6938 assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
6939 LHS.Designator.Entries[PathLength]
6940 .getAsBaseOrMember().getPointer()));
6941 }
6942
6943 // -- Otherwise, S(E) is empty.
6944 } else {
6945 break;
6946 }
6947 }
6948
6949 // Common case: no unions' lifetimes are started.
6950 if (UnionPathLengths.empty())
6951 return true;
6952
6953 // if modification of X [would access an inactive union member], an object
6954 // of the type of X is implicitly created
6955 CompleteObject Obj =
6956 findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
6957 if (!Obj)
6958 return false;
6959 for (std::pair<unsigned, const FieldDecl *> LengthAndField :
6960 llvm::reverse(UnionPathLengths)) {
6961 // Form a designator for the union object.
6962 SubobjectDesignator D = LHS.Designator;
6963 D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
6964
6965 bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) ==
6966 ConstructionPhase::AfterBases;
6967 StartLifetimeOfUnionMemberHandler StartLifetime{
6968 Info, LHSExpr, LengthAndField.second, DuringInit};
6969 if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
6970 return false;
6971 }
6972
6973 return true;
6974}
6975
6976static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg,
6977 CallRef Call, EvalInfo &Info, bool NonNull = false,
6978 APValue **EvaluatedArg = nullptr) {
6979 LValue LV;
6980 // Create the parameter slot and register its destruction. For a vararg
6981 // argument, create a temporary.
6982 // FIXME: For calling conventions that destroy parameters in the callee,
6983 // should we consider performing destruction when the function returns
6984 // instead?
6985 APValue &V = PVD ? Info.CurrentCall->createParam(Call, PVD, LV)
6986 : Info.CurrentCall->createTemporary(Arg, Arg->getType(),
6987 ScopeKind::Call, LV);
6988 if (!EvaluateInPlace(V, Info, LV, Arg))
6989 return false;
6990
6991 // Passing a null pointer to an __attribute__((nonnull)) parameter results in
6992 // undefined behavior, so is non-constant.
6993 if (NonNull && V.isLValue() && V.isNullPointer()) {
6994 Info.CCEDiag(Arg, diag::note_non_null_attribute_failed);
6995 return false;
6996 }
6997
6998 if (EvaluatedArg)
6999 *EvaluatedArg = &V;
7000
7001 return true;
7002}
7003
7004/// Evaluate the arguments to a function call.
7005static bool EvaluateArgs(ArrayRef<const Expr *> Args, CallRef Call,
7006 EvalInfo &Info, const FunctionDecl *Callee,
7007 bool RightToLeft = false,
7008 LValue *ObjectArg = nullptr) {
7009 bool Success = true;
7010 llvm::SmallBitVector ForbiddenNullArgs;
7011 if (Callee->hasAttr<NonNullAttr>()) {
7012 ForbiddenNullArgs.resize(Args.size());
7013 for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
7014 if (!Attr->args_size()) {
7015 ForbiddenNullArgs.set();
7016 break;
7017 } else
7018 for (auto Idx : Attr->args()) {
7019 unsigned ASTIdx = Idx.getASTIndex();
7020 if (ASTIdx >= Args.size())
7021 continue;
7022 ForbiddenNullArgs[ASTIdx] = true;
7023 }
7024 }
7025 }
7026 for (unsigned I = 0; I < Args.size(); I++) {
7027 unsigned Idx = RightToLeft ? Args.size() - I - 1 : I;
7028 const ParmVarDecl *PVD =
7029 Idx < Callee->getNumParams() ? Callee->getParamDecl(Idx) : nullptr;
7030 bool NonNull = !ForbiddenNullArgs.empty() && ForbiddenNullArgs[Idx];
7031 APValue *That = nullptr;
7032 if (!EvaluateCallArg(PVD, Args[Idx], Call, Info, NonNull, &That)) {
7033 // If we're checking for a potential constant expression, evaluate all
7034 // initializers even if some of them fail.
7035 if (!Info.noteFailure())
7036 return false;
7037 Success = false;
7038 }
7039 if (PVD && PVD->isExplicitObjectParameter() && That && That->isLValue())
7040 ObjectArg->setFrom(Info.Ctx, *That);
7041 }
7042 return Success;
7043}
7044
7045/// Perform a trivial copy from Param, which is the parameter of a copy or move
7046/// constructor or assignment operator.
7047static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param,
7048 const Expr *E, APValue &Result,
7049 bool CopyObjectRepresentation) {
7050 // Find the reference argument.
7051 CallStackFrame *Frame = Info.CurrentCall;
7052 APValue *RefValue = Info.getParamSlot(Frame->Arguments, Param);
7053 if (!RefValue) {
7054 Info.FFDiag(E);
7055 return false;
7056 }
7057
7058 // Copy out the contents of the RHS object.
7059 LValue RefLValue;
7060 RefLValue.setFrom(Info.Ctx, *RefValue);
7062 Info, E, Param->getType().getNonReferenceType(), RefLValue, Result,
7063 CopyObjectRepresentation);
7064}
7065
7066/// Evaluate a function call.
7068 const FunctionDecl *Callee,
7069 const LValue *ObjectArg, const Expr *E,
7070 ArrayRef<const Expr *> Args, CallRef Call,
7071 const Stmt *Body, EvalInfo &Info,
7072 APValue &Result, const LValue *ResultSlot) {
7073 if (!Info.CheckCallLimit(CallLoc))
7074 return false;
7075
7076 CallStackFrame Frame(Info, E->getSourceRange(), Callee, ObjectArg, E, Call);
7077
7078 // For a trivial copy or move assignment, perform an APValue copy. This is
7079 // essential for unions, where the operations performed by the assignment
7080 // operator cannot be represented as statements.
7081 //
7082 // Skip this for non-union classes with no fields; in that case, the defaulted
7083 // copy/move does not actually read the object.
7084 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
7085 if (MD && MD->isDefaulted() &&
7086 (MD->getParent()->isUnion() ||
7087 (MD->isTrivial() &&
7089 unsigned ExplicitOffset = MD->isExplicitObjectMemberFunction() ? 1 : 0;
7090 assert(ObjectArg &&
7092 APValue RHSValue;
7093 if (!handleTrivialCopy(Info, MD->getParamDecl(0), Args[0], RHSValue,
7094 MD->getParent()->isUnion()))
7095 return false;
7096
7097 LValue Obj;
7098 if (!handleAssignment(Info, Args[ExplicitOffset], *ObjectArg,
7100 RHSValue))
7101 return false;
7102 ObjectArg->moveInto(Result);
7103 return true;
7104 } else if (MD && isLambdaCallOperator(MD)) {
7105 // We're in a lambda; determine the lambda capture field maps unless we're
7106 // just constexpr checking a lambda's call operator. constexpr checking is
7107 // done before the captures have been added to the closure object (unless
7108 // we're inferring constexpr-ness), so we don't have access to them in this
7109 // case. But since we don't need the captures to constexpr check, we can
7110 // just ignore them.
7111 if (!Info.checkingPotentialConstantExpression())
7112 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
7113 Frame.LambdaThisCaptureField);
7114 }
7115
7116 StmtResult Ret = {Result, ResultSlot};
7117 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
7118 if (ESR == ESR_Succeeded) {
7119 if (Callee->getReturnType()->isVoidType())
7120 return true;
7121 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
7122 }
7123 return ESR == ESR_Returned;
7124}
7125
7126/// Evaluate a constructor call.
7127static bool HandleConstructorCall(const Expr *E, const LValue &This,
7128 CallRef Call,
7130 EvalInfo &Info, APValue &Result) {
7131 SourceLocation CallLoc = E->getExprLoc();
7132 if (!Info.CheckCallLimit(CallLoc))
7133 return false;
7134
7135 const CXXRecordDecl *RD = Definition->getParent();
7136 if (RD->getNumVBases()) {
7137 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
7138 return false;
7139 }
7140
7141 EvalInfo::EvaluatingConstructorRAII EvalObj(
7142 Info,
7143 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
7144 RD->getNumBases());
7145 CallStackFrame Frame(Info, E->getSourceRange(), Definition, &This, E, Call);
7146
7147 // FIXME: Creating an APValue just to hold a nonexistent return value is
7148 // wasteful.
7149 APValue RetVal;
7150 StmtResult Ret = {RetVal, nullptr};
7151
7152 // If it's a delegating constructor, delegate.
7153 if (Definition->isDelegatingConstructor()) {
7155 if ((*I)->getInit()->isValueDependent()) {
7156 if (!EvaluateDependentExpr((*I)->getInit(), Info))
7157 return false;
7158 } else {
7159 FullExpressionRAII InitScope(Info);
7160 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) ||
7161 !InitScope.destroy())
7162 return false;
7163 }
7164 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
7165 }
7166
7167 // For a trivial copy or move constructor, perform an APValue copy. This is
7168 // essential for unions (or classes with anonymous union members), where the
7169 // operations performed by the constructor cannot be represented by
7170 // ctor-initializers.
7171 //
7172 // Skip this for empty non-union classes; we should not perform an
7173 // lvalue-to-rvalue conversion on them because their copy constructor does not
7174 // actually read them.
7175 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
7176 (Definition->getParent()->isUnion() ||
7177 (Definition->isTrivial() &&
7179 return handleTrivialCopy(Info, Definition->getParamDecl(0), E, Result,
7180 Definition->getParent()->isUnion());
7181 }
7182
7183 // Reserve space for the struct members.
7184 if (!Result.hasValue()) {
7185 if (!RD->isUnion())
7186 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
7187 std::distance(RD->field_begin(), RD->field_end()));
7188 else
7189 // A union starts with no active member.
7190 Result = APValue((const FieldDecl*)nullptr);
7191 }
7192
7193 if (RD->isInvalidDecl()) return false;
7194 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7195
7196 // A scope for temporaries lifetime-extended by reference members.
7197 BlockScopeRAII LifetimeExtendedScope(Info);
7198
7199 bool Success = true;
7200 unsigned BasesSeen = 0;
7201#ifndef NDEBUG
7203#endif
7205 auto SkipToField = [&](FieldDecl *FD, bool Indirect) {
7206 // We might be initializing the same field again if this is an indirect
7207 // field initialization.
7208 if (FieldIt == RD->field_end() ||
7209 FieldIt->getFieldIndex() > FD->getFieldIndex()) {
7210 assert(Indirect && "fields out of order?");
7211 return;
7212 }
7213
7214 // Default-initialize any fields with no explicit initializer.
7215 for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
7216 assert(FieldIt != RD->field_end() && "missing field?");
7217 if (!FieldIt->isUnnamedBitField())
7219 FieldIt->getType(),
7220 Result.getStructField(FieldIt->getFieldIndex()));
7221 }
7222 ++FieldIt;
7223 };
7224 for (const auto *I : Definition->inits()) {
7225 LValue Subobject = This;
7226 LValue SubobjectParent = This;
7227 APValue *Value = &Result;
7228
7229 // Determine the subobject to initialize.
7230 FieldDecl *FD = nullptr;
7231 if (I->isBaseInitializer()) {
7232 QualType BaseType(I->getBaseClass(), 0);
7233#ifndef NDEBUG
7234 // Non-virtual base classes are initialized in the order in the class
7235 // definition. We have already checked for virtual base classes.
7236 assert(!BaseIt->isVirtual() && "virtual base for literal type");
7237 assert(Info.Ctx.hasSameUnqualifiedType(BaseIt->getType(), BaseType) &&
7238 "base class initializers not in expected order");
7239 ++BaseIt;
7240#endif
7241 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
7242 BaseType->getAsCXXRecordDecl(), &Layout))
7243 return false;
7244 Value = &Result.getStructBase(BasesSeen++);
7245 } else if ((FD = I->getMember())) {
7246 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
7247 return false;
7248 if (RD->isUnion()) {
7249 Result = APValue(FD);
7250 Value = &Result.getUnionValue();
7251 } else {
7252 SkipToField(FD, false);
7253 Value = &Result.getStructField(FD->getFieldIndex());
7254 }
7255 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
7256 // Walk the indirect field decl's chain to find the object to initialize,
7257 // and make sure we've initialized every step along it.
7258 auto IndirectFieldChain = IFD->chain();
7259 for (auto *C : IndirectFieldChain) {
7260 FD = cast<FieldDecl>(C);
7262 // Switch the union field if it differs. This happens if we had
7263 // preceding zero-initialization, and we're now initializing a union
7264 // subobject other than the first.
7265 // FIXME: In this case, the values of the other subobjects are
7266 // specified, since zero-initialization sets all padding bits to zero.
7267 if (!Value->hasValue() ||
7268 (Value->isUnion() &&
7269 !declaresSameEntity(Value->getUnionField(), FD))) {
7270 if (CD->isUnion())
7271 *Value = APValue(FD);
7272 else
7273 // FIXME: This immediately starts the lifetime of all members of
7274 // an anonymous struct. It would be preferable to strictly start
7275 // member lifetime in initialization order.
7277 *Value);
7278 }
7279 // Store Subobject as its parent before updating it for the last element
7280 // in the chain.
7281 if (C == IndirectFieldChain.back())
7282 SubobjectParent = Subobject;
7283 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
7284 return false;
7285 if (CD->isUnion())
7286 Value = &Value->getUnionValue();
7287 else {
7288 if (C == IndirectFieldChain.front() && !RD->isUnion())
7289 SkipToField(FD, true);
7290 Value = &Value->getStructField(FD->getFieldIndex());
7291 }
7292 }
7293 } else {
7294 llvm_unreachable("unknown base initializer kind");
7295 }
7296
7297 // Need to override This for implicit field initializers as in this case
7298 // This refers to innermost anonymous struct/union containing initializer,
7299 // not to currently constructed class.
7300 const Expr *Init = I->getInit();
7301 if (Init->isValueDependent()) {
7302 if (!EvaluateDependentExpr(Init, Info))
7303 return false;
7304 } else {
7305 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
7307 FullExpressionRAII InitScope(Info);
7308 if (FD && FD->getType()->isReferenceType() &&
7309 !FD->getType()->isFunctionReferenceType()) {
7310 LValue Result;
7311 if (!EvaluateInitForDeclOfReferenceType(Info, FD, Init, Result,
7312 *Value)) {
7313 if (!Info.noteFailure())
7314 return false;
7315 Success = false;
7316 }
7317 } else if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
7318 (FD && FD->isBitField() &&
7319 !truncateBitfieldValue(Info, Init, *Value, FD))) {
7320 // If we're checking for a potential constant expression, evaluate all
7321 // initializers even if some of them fail.
7322 if (!Info.noteFailure())
7323 return false;
7324 Success = false;
7325 }
7326 }
7327
7328 // This is the point at which the dynamic type of the object becomes this
7329 // class type.
7330 if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
7331 EvalObj.finishedConstructingBases();
7332 }
7333
7334 // Default-initialize any remaining fields.
7335 if (!RD->isUnion()) {
7336 for (; FieldIt != RD->field_end(); ++FieldIt) {
7337 if (!FieldIt->isUnnamedBitField())
7339 FieldIt->getType(),
7340 Result.getStructField(FieldIt->getFieldIndex()));
7341 }
7342 }
7343
7344 EvalObj.finishedConstructingFields();
7345
7346 return Success &&
7347 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed &&
7348 LifetimeExtendedScope.destroy();
7349}
7350
7351static bool HandleConstructorCall(const Expr *E, const LValue &This,
7354 EvalInfo &Info, APValue &Result) {
7355 CallScopeRAII CallScope(Info);
7356 CallRef Call = Info.CurrentCall->createCall(Definition);
7357 if (!EvaluateArgs(Args, Call, Info, Definition))
7358 return false;
7359
7360 return HandleConstructorCall(E, This, Call, Definition, Info, Result) &&
7361 CallScope.destroy();
7362}
7363
7364static bool HandleDestructionImpl(EvalInfo &Info, SourceRange CallRange,
7365 const LValue &This, APValue &Value,
7366 QualType T) {
7367 // Objects can only be destroyed while they're within their lifetimes.
7368 // FIXME: We have no representation for whether an object of type nullptr_t
7369 // is in its lifetime; it usually doesn't matter. Perhaps we should model it
7370 // as indeterminate instead?
7371 if (Value.isAbsent() && !T->isNullPtrType()) {
7372 APValue Printable;
7373 This.moveInto(Printable);
7374 Info.FFDiag(CallRange.getBegin(),
7375 diag::note_constexpr_destroy_out_of_lifetime)
7376 << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T));
7377 return false;
7378 }
7379
7380 // Invent an expression for location purposes.
7381 // FIXME: We shouldn't need to do this.
7382 OpaqueValueExpr LocE(CallRange.getBegin(), Info.Ctx.IntTy, VK_PRValue);
7383
7384 // For arrays, destroy elements right-to-left.
7385 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) {
7386 uint64_t Size = CAT->getZExtSize();
7387 QualType ElemT = CAT->getElementType();
7388
7389 if (!CheckArraySize(Info, CAT, CallRange.getBegin()))
7390 return false;
7391
7392 LValue ElemLV = This;
7393 ElemLV.addArray(Info, &LocE, CAT);
7394 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size))
7395 return false;
7396
7397 // Ensure that we have actual array elements available to destroy; the
7398 // destructors might mutate the value, so we can't run them on the array
7399 // filler.
7400 if (Size && Size > Value.getArrayInitializedElts())
7401 expandArray(Value, Value.getArraySize() - 1);
7402
7403 // The size of the array might have been reduced by
7404 // a placement new.
7405 for (Size = Value.getArraySize(); Size != 0; --Size) {
7406 APValue &Elem = Value.getArrayInitializedElt(Size - 1);
7407 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) ||
7408 !HandleDestructionImpl(Info, CallRange, ElemLV, Elem, ElemT))
7409 return false;
7410 }
7411
7412 // End the lifetime of this array now.
7413 Value = APValue();
7414 return true;
7415 }
7416
7417 const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
7418 if (!RD) {
7419 if (T.isDestructedType()) {
7420 Info.FFDiag(CallRange.getBegin(),
7421 diag::note_constexpr_unsupported_destruction)
7422 << T;
7423 return false;
7424 }
7425
7426 Value = APValue();
7427 return true;
7428 }
7429
7430 if (RD->getNumVBases()) {
7431 Info.FFDiag(CallRange.getBegin(), diag::note_constexpr_virtual_base) << RD;
7432 return false;
7433 }
7434
7435 const CXXDestructorDecl *DD = RD->getDestructor();
7436 if (!DD && !RD->hasTrivialDestructor()) {
7437 Info.FFDiag(CallRange.getBegin());
7438 return false;
7439 }
7440
7441 if (!DD || DD->isTrivial() ||
7442 (RD->isAnonymousStructOrUnion() && RD->isUnion())) {
7443 // A trivial destructor just ends the lifetime of the object. Check for
7444 // this case before checking for a body, because we might not bother
7445 // building a body for a trivial destructor. Note that it doesn't matter
7446 // whether the destructor is constexpr in this case; all trivial
7447 // destructors are constexpr.
7448 //
7449 // If an anonymous union would be destroyed, some enclosing destructor must
7450 // have been explicitly defined, and the anonymous union destruction should
7451 // have no effect.
7452 Value = APValue();
7453 return true;
7454 }
7455
7456 if (!Info.CheckCallLimit(CallRange.getBegin()))
7457 return false;
7458
7459 const FunctionDecl *Definition = nullptr;
7460 const Stmt *Body = DD->getBody(Definition);
7461
7462 if (!CheckConstexprFunction(Info, CallRange.getBegin(), DD, Definition, Body))
7463 return false;
7464
7465 CallStackFrame Frame(Info, CallRange, Definition, &This, /*CallExpr=*/nullptr,
7466 CallRef());
7467
7468 // We're now in the period of destruction of this object.
7469 unsigned BasesLeft = RD->getNumBases();
7470 EvalInfo::EvaluatingDestructorRAII EvalObj(
7471 Info,
7472 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries});
7473 if (!EvalObj.DidInsert) {
7474 // C++2a [class.dtor]p19:
7475 // the behavior is undefined if the destructor is invoked for an object
7476 // whose lifetime has ended
7477 // (Note that formally the lifetime ends when the period of destruction
7478 // begins, even though certain uses of the object remain valid until the
7479 // period of destruction ends.)
7480 Info.FFDiag(CallRange.getBegin(), diag::note_constexpr_double_destroy);
7481 return false;
7482 }
7483
7484 // FIXME: Creating an APValue just to hold a nonexistent return value is
7485 // wasteful.
7486 APValue RetVal;
7487 StmtResult Ret = {RetVal, nullptr};
7488 if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed)
7489 return false;
7490
7491 // A union destructor does not implicitly destroy its members.
7492 if (RD->isUnion())
7493 return true;
7494
7495 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7496
7497 // We don't have a good way to iterate fields in reverse, so collect all the
7498 // fields first and then walk them backwards.
7499 SmallVector<FieldDecl*, 16> Fields(RD->fields());
7500 for (const FieldDecl *FD : llvm::reverse(Fields)) {
7501 if (FD->isUnnamedBitField())
7502 continue;
7503
7504 LValue Subobject = This;
7505 if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout))
7506 return false;
7507
7508 APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex());
7509 if (!HandleDestructionImpl(Info, CallRange, Subobject, *SubobjectValue,
7510 FD->getType()))
7511 return false;
7512 }
7513
7514 if (BasesLeft != 0)
7515 EvalObj.startedDestroyingBases();
7516
7517 // Destroy base classes in reverse order.
7518 for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) {
7519 --BasesLeft;
7520
7521 QualType BaseType = Base.getType();
7522 LValue Subobject = This;
7523 if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD,
7524 BaseType->getAsCXXRecordDecl(), &Layout))
7525 return false;
7526
7527 APValue *SubobjectValue = &Value.getStructBase(BasesLeft);
7528 if (!HandleDestructionImpl(Info, CallRange, Subobject, *SubobjectValue,
7529 BaseType))
7530 return false;
7531 }
7532 assert(BasesLeft == 0 && "NumBases was wrong?");
7533
7534 // The period of destruction ends now. The object is gone.
7535 Value = APValue();
7536 return true;
7537}
7538
7539namespace {
7540struct DestroyObjectHandler {
7541 EvalInfo &Info;
7542 const Expr *E;
7543 const LValue &This;
7544 const AccessKinds AccessKind;
7545
7546 typedef bool result_type;
7547 bool failed() { return false; }
7548 bool found(APValue &Subobj, QualType SubobjType) {
7549 return HandleDestructionImpl(Info, E->getSourceRange(), This, Subobj,
7550 SubobjType);
7551 }
7552 bool found(APSInt &Value, QualType SubobjType) {
7553 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
7554 return false;
7555 }
7556 bool found(APFloat &Value, QualType SubobjType) {
7557 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
7558 return false;
7559 }
7560};
7561}
7562
7563/// Perform a destructor or pseudo-destructor call on the given object, which
7564/// might in general not be a complete object.
7565static bool HandleDestruction(EvalInfo &Info, const Expr *E,
7566 const LValue &This, QualType ThisType) {
7567 CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType);
7568 DestroyObjectHandler Handler = {Info, E, This, AK_Destroy};
7569 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
7570}
7571
7572/// Destroy and end the lifetime of the given complete object.
7573static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
7575 QualType T) {
7576 // If we've had an unmodeled side-effect, we can't rely on mutable state
7577 // (such as the object we're about to destroy) being correct.
7578 if (Info.EvalStatus.HasSideEffects)
7579 return false;
7580
7581 LValue LV;
7582 LV.set({LVBase});
7583 return HandleDestructionImpl(Info, Loc, LV, Value, T);
7584}
7585
7586/// Perform a call to 'operator new' or to `__builtin_operator_new'.
7587static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E,
7588 LValue &Result) {
7589 if (Info.checkingPotentialConstantExpression() ||
7590 Info.SpeculativeEvaluationDepth)
7591 return false;
7592
7593 // This is permitted only within a call to std::allocator<T>::allocate.
7594 auto Caller = Info.getStdAllocatorCaller("allocate");
7595 if (!Caller) {
7596 Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20
7597 ? diag::note_constexpr_new_untyped
7598 : diag::note_constexpr_new);
7599 return false;
7600 }
7601
7602 QualType ElemType = Caller.ElemType;
7603 if (ElemType->isIncompleteType() || ElemType->isFunctionType()) {
7604 Info.FFDiag(E->getExprLoc(),
7605 diag::note_constexpr_new_not_complete_object_type)
7606 << (ElemType->isIncompleteType() ? 0 : 1) << ElemType;
7607 return false;
7608 }
7609
7610 APSInt ByteSize;
7611 if (!EvaluateInteger(E->getArg(0), ByteSize, Info))
7612 return false;
7613 bool IsNothrow = false;
7614 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) {
7615 EvaluateIgnoredValue(Info, E->getArg(I));
7616 IsNothrow |= E->getType()->isNothrowT();
7617 }
7618
7619 CharUnits ElemSize;
7620 if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize))
7621 return false;
7622 APInt Size, Remainder;
7623 APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity());
7624 APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder);
7625 if (Remainder != 0) {
7626 // This likely indicates a bug in the implementation of 'std::allocator'.
7627 Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size)
7628 << ByteSize << APSInt(ElemSizeAP, true) << ElemType;
7629 return false;
7630 }
7631
7632 if (!Info.CheckArraySize(E->getBeginLoc(), ByteSize.getActiveBits(),
7633 Size.getZExtValue(), /*Diag=*/!IsNothrow)) {
7634 if (IsNothrow) {
7635 Result.setNull(Info.Ctx, E->getType());
7636 return true;
7637 }
7638 return false;
7639 }
7640
7641 QualType AllocType = Info.Ctx.getConstantArrayType(
7642 ElemType, Size, nullptr, ArraySizeModifier::Normal, 0);
7643 APValue *Val = Info.createHeapAlloc(Caller.Call, AllocType, Result);
7644 *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue());
7645 Result.addArray(Info, E, cast<ConstantArrayType>(AllocType));
7646 return true;
7647}
7648
7650 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
7651 if (CXXDestructorDecl *DD = RD->getDestructor())
7652 return DD->isVirtual();
7653 return false;
7654}
7655
7657 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
7658 if (CXXDestructorDecl *DD = RD->getDestructor())
7659 return DD->isVirtual() ? DD->getOperatorDelete() : nullptr;
7660 return nullptr;
7661}
7662
7663/// Check that the given object is a suitable pointer to a heap allocation that
7664/// still exists and is of the right kind for the purpose of a deletion.
7665///
7666/// On success, returns the heap allocation to deallocate. On failure, produces
7667/// a diagnostic and returns std::nullopt.
7668static std::optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E,
7669 const LValue &Pointer,
7670 DynAlloc::Kind DeallocKind) {
7671 auto PointerAsString = [&] {
7672 return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy);
7673 };
7674
7675 DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>();
7676 if (!DA) {
7677 Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc)
7678 << PointerAsString();
7679 if (Pointer.Base)
7680 NoteLValueLocation(Info, Pointer.Base);
7681 return std::nullopt;
7682 }
7683
7684 std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
7685 if (!Alloc) {
7686 Info.FFDiag(E, diag::note_constexpr_double_delete);
7687 return std::nullopt;
7688 }
7689
7690 if (DeallocKind != (*Alloc)->getKind()) {
7691 QualType AllocType = Pointer.Base.getDynamicAllocType();
7692 Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch)
7693 << DeallocKind << (*Alloc)->getKind() << AllocType;
7694 NoteLValueLocation(Info, Pointer.Base);
7695 return std::nullopt;
7696 }
7697
7698 bool Subobject = false;
7699 if (DeallocKind == DynAlloc::New) {
7700 Subobject = Pointer.Designator.MostDerivedPathLength != 0 ||
7701 Pointer.Designator.isOnePastTheEnd();
7702 } else {
7703 Subobject = Pointer.Designator.Entries.size() != 1 ||
7704 Pointer.Designator.Entries[0].getAsArrayIndex() != 0;
7705 }
7706 if (Subobject) {
7707 Info.FFDiag(E, diag::note_constexpr_delete_subobject)
7708 << PointerAsString() << Pointer.Designator.isOnePastTheEnd();
7709 return std::nullopt;
7710 }
7711
7712 return Alloc;
7713}
7714
7715// Perform a call to 'operator delete' or '__builtin_operator_delete'.
7716static bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) {
7717 if (Info.checkingPotentialConstantExpression() ||
7718 Info.SpeculativeEvaluationDepth)
7719 return false;
7720
7721 // This is permitted only within a call to std::allocator<T>::deallocate.
7722 if (!Info.getStdAllocatorCaller("deallocate")) {
7723 Info.FFDiag(E->getExprLoc());
7724 return true;
7725 }
7726
7727 LValue Pointer;
7728 if (!EvaluatePointer(E->getArg(0), Pointer, Info))
7729 return false;
7730 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
7731 EvaluateIgnoredValue(Info, E->getArg(I));
7732
7733 if (Pointer.Designator.Invalid)
7734 return false;
7735
7736 // Deleting a null pointer would have no effect, but it's not permitted by
7737 // std::allocator<T>::deallocate's contract.
7738 if (Pointer.isNullPointer()) {
7739 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_deallocate_null);
7740 return true;
7741 }
7742
7743 if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator))
7744 return false;
7745
7746 Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>());
7747 return true;
7748}
7749
7750//===----------------------------------------------------------------------===//
7751// Generic Evaluation
7752//===----------------------------------------------------------------------===//
7753namespace {
7754
7755class BitCastBuffer {
7756 // FIXME: We're going to need bit-level granularity when we support
7757 // bit-fields.
7758 // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
7759 // we don't support a host or target where that is the case. Still, we should
7760 // use a more generic type in case we ever do.
7761 SmallVector<std::optional<unsigned char>, 32> Bytes;
7762
7763 static_assert(std::numeric_limits<unsigned char>::digits >= 8,
7764 "Need at least 8 bit unsigned char");
7765
7766 bool TargetIsLittleEndian;
7767
7768public:
7769 BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
7770 : Bytes(Width.getQuantity()),
7771 TargetIsLittleEndian(TargetIsLittleEndian) {}
7772
7773 [[nodiscard]] bool readObject(CharUnits Offset, CharUnits Width,
7774 SmallVectorImpl<unsigned char> &Output) const {
7775 for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
7776 // If a byte of an integer is uninitialized, then the whole integer is
7777 // uninitialized.
7778 if (!Bytes[I.getQuantity()])
7779 return false;
7780 Output.push_back(*Bytes[I.getQuantity()]);
7781 }
7782 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
7783 std::reverse(Output.begin(), Output.end());
7784 return true;
7785 }
7786
7787 void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
7788 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
7789 std::reverse(Input.begin(), Input.end());
7790
7791 size_t Index = 0;
7792 for (unsigned char Byte : Input) {
7793 assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
7794 Bytes[Offset.getQuantity() + Index] = Byte;
7795 ++Index;
7796 }
7797 }
7798
7799 size_t size() { return Bytes.size(); }
7800};
7801
7802/// Traverse an APValue to produce an BitCastBuffer, emulating how the current
7803/// target would represent the value at runtime.
7804class APValueToBufferConverter {
7805 EvalInfo &Info;
7806 BitCastBuffer Buffer;
7807 const CastExpr *BCE;
7808
7809 APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
7810 const CastExpr *BCE)
7811 : Info(Info),
7812 Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
7813 BCE(BCE) {}
7814
7815 bool visit(const APValue &Val, QualType Ty) {
7816 return visit(Val, Ty, CharUnits::fromQuantity(0));
7817 }
7818
7819 // Write out Val with type Ty into Buffer starting at Offset.
7820 bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
7821 assert((size_t)Offset.getQuantity() <= Buffer.size());
7822
7823 // As a special case, nullptr_t has an indeterminate value.
7824 if (Ty->isNullPtrType())
7825 return true;
7826
7827 // Dig through Src to find the byte at SrcOffset.
7828 switch (Val.getKind()) {
7830 case APValue::None:
7831 return true;
7832
7833 case APValue::Int:
7834 return visitInt(Val.getInt(), Ty, Offset);
7835 case APValue::Float:
7836 return visitFloat(Val.getFloat(), Ty, Offset);
7837 case APValue::Array:
7838 return visitArray(Val, Ty, Offset);
7839 case APValue::Struct:
7840 return visitRecord(Val, Ty, Offset);
7841 case APValue::Vector:
7842 return visitVector(Val, Ty, Offset);
7843
7846 return visitComplex(Val, Ty, Offset);
7848 // FIXME: We should support these.
7849
7850 case APValue::Union:
7853 Info.FFDiag(BCE->getBeginLoc(),
7854 diag::note_constexpr_bit_cast_unsupported_type)
7855 << Ty;
7856 return false;
7857 }
7858
7859 case APValue::LValue:
7860 llvm_unreachable("LValue subobject in bit_cast?");
7861 }
7862 llvm_unreachable("Unhandled APValue::ValueKind");
7863 }
7864
7865 bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
7866 const RecordDecl *RD = Ty->getAsRecordDecl();
7867 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7868
7869 // Visit the base classes.
7870 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
7871 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
7872 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
7873 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
7874 const APValue &Base = Val.getStructBase(I);
7875
7876 // Can happen in error cases.
7877 if (!Base.isStruct())
7878 return false;
7879
7880 if (!visitRecord(Base, BS.getType(),
7881 Layout.getBaseClassOffset(BaseDecl) + Offset))
7882 return false;
7883 }
7884 }
7885
7886 // Visit the fields.
7887 unsigned FieldIdx = 0;
7888 for (FieldDecl *FD : RD->fields()) {
7889 if (FD->isBitField()) {
7890 Info.FFDiag(BCE->getBeginLoc(),
7891 diag::note_constexpr_bit_cast_unsupported_bitfield);
7892 return false;
7893 }
7894
7895 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
7896
7897 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
7898 "only bit-fields can have sub-char alignment");
7899 CharUnits FieldOffset =
7900 Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
7901 QualType FieldTy = FD->getType();
7902 if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
7903 return false;
7904 ++FieldIdx;
7905 }
7906
7907 return true;
7908 }
7909
7910 bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
7911 const auto *CAT =
7912 dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
7913 if (!CAT)
7914 return false;
7915
7916 CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
7917 unsigned NumInitializedElts = Val.getArrayInitializedElts();
7918 unsigned ArraySize = Val.getArraySize();
7919 // First, initialize the initialized elements.
7920 for (unsigned I = 0; I != NumInitializedElts; ++I) {
7921 const APValue &SubObj = Val.getArrayInitializedElt(I);
7922 if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
7923 return false;
7924 }
7925
7926 // Next, initialize the rest of the array using the filler.
7927 if (Val.hasArrayFiller()) {
7928 const APValue &Filler = Val.getArrayFiller();
7929 for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
7930 if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
7931 return false;
7932 }
7933 }
7934
7935 return true;
7936 }
7937
7938 bool visitComplex(const APValue &Val, QualType Ty, CharUnits Offset) {
7939 const ComplexType *ComplexTy = Ty->castAs<ComplexType>();
7940 QualType EltTy = ComplexTy->getElementType();
7941 CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
7942 bool IsInt = Val.isComplexInt();
7943
7944 if (IsInt) {
7945 if (!visitInt(Val.getComplexIntReal(), EltTy,
7946 Offset + (0 * EltSizeChars)))
7947 return false;
7948 if (!visitInt(Val.getComplexIntImag(), EltTy,
7949 Offset + (1 * EltSizeChars)))
7950 return false;
7951 } else {
7952 if (!visitFloat(Val.getComplexFloatReal(), EltTy,
7953 Offset + (0 * EltSizeChars)))
7954 return false;
7955 if (!visitFloat(Val.getComplexFloatImag(), EltTy,
7956 Offset + (1 * EltSizeChars)))
7957 return false;
7958 }
7959
7960 return true;
7961 }
7962
7963 bool visitVector(const APValue &Val, QualType Ty, CharUnits Offset) {
7964 const VectorType *VTy = Ty->castAs<VectorType>();
7965 QualType EltTy = VTy->getElementType();
7966 unsigned NElts = VTy->getNumElements();
7967
7968 if (VTy->isPackedVectorBoolType(Info.Ctx)) {
7969 // Special handling for OpenCL bool vectors:
7970 // Since these vectors are stored as packed bits, but we can't write
7971 // individual bits to the BitCastBuffer, we'll buffer all of the elements
7972 // together into an appropriately sized APInt and write them all out at
7973 // once. Because we don't accept vectors where NElts * EltSize isn't a
7974 // multiple of the char size, there will be no padding space, so we don't
7975 // have to worry about writing data which should have been left
7976 // uninitialized.
7977 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
7978
7979 llvm::APInt Res = llvm::APInt::getZero(NElts);
7980 for (unsigned I = 0; I < NElts; ++I) {
7981 const llvm::APSInt &EltAsInt = Val.getVectorElt(I).getInt();
7982 assert(EltAsInt.isUnsigned() && EltAsInt.getBitWidth() == 1 &&
7983 "bool vector element must be 1-bit unsigned integer!");
7984
7985 Res.insertBits(EltAsInt, BigEndian ? (NElts - I - 1) : I);
7986 }
7987
7988 SmallVector<uint8_t, 8> Bytes(NElts / 8);
7989 llvm::StoreIntToMemory(Res, &*Bytes.begin(), NElts / 8);
7990 Buffer.writeObject(Offset, Bytes);
7991 } else {
7992 // Iterate over each of the elements and write them out to the buffer at
7993 // the appropriate offset.
7994 CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
7995 for (unsigned I = 0; I < NElts; ++I) {
7996 if (!visit(Val.getVectorElt(I), EltTy, Offset + I * EltSizeChars))
7997 return false;
7998 }
7999 }
8000
8001 return true;
8002 }
8003
8004 bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
8005 APSInt AdjustedVal = Val;
8006 unsigned Width = AdjustedVal.getBitWidth();
8007 if (Ty->isBooleanType()) {
8008 Width = Info.Ctx.getTypeSize(Ty);
8009 AdjustedVal = AdjustedVal.extend(Width);
8010 }
8011
8012 SmallVector<uint8_t, 8> Bytes(Width / 8);
8013 llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8);
8014 Buffer.writeObject(Offset, Bytes);
8015 return true;
8016 }
8017
8018 bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
8019 APSInt AsInt(Val.bitcastToAPInt());
8020 return visitInt(AsInt, Ty, Offset);
8021 }
8022
8023public:
8024 static std::optional<BitCastBuffer>
8025 convert(EvalInfo &Info, const APValue &Src, const CastExpr *BCE) {
8026 CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
8027 APValueToBufferConverter Converter(Info, DstSize, BCE);
8028 if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
8029 return std::nullopt;
8030 return Converter.Buffer;
8031 }
8032};
8033
8034/// Write an BitCastBuffer into an APValue.
8035class BufferToAPValueConverter {
8036 EvalInfo &Info;
8037 const BitCastBuffer &Buffer;
8038 const CastExpr *BCE;
8039
8040 BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
8041 const CastExpr *BCE)
8042 : Info(Info), Buffer(Buffer), BCE(BCE) {}
8043
8044 // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
8045 // with an invalid type, so anything left is a deficiency on our part (FIXME).
8046 // Ideally this will be unreachable.
8047 std::nullopt_t unsupportedType(QualType Ty) {
8048 Info.FFDiag(BCE->getBeginLoc(),
8049 diag::note_constexpr_bit_cast_unsupported_type)
8050 << Ty;
8051 return std::nullopt;
8052 }
8053
8054 std::nullopt_t unrepresentableValue(QualType Ty, const APSInt &Val) {
8055 Info.FFDiag(BCE->getBeginLoc(),
8056 diag::note_constexpr_bit_cast_unrepresentable_value)
8057 << Ty << toString(Val, /*Radix=*/10);
8058 return std::nullopt;
8059 }
8060
8061 std::optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
8062 const EnumType *EnumSugar = nullptr) {
8063 if (T->isNullPtrType()) {
8064 uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
8065 return APValue((Expr *)nullptr,
8066 /*Offset=*/CharUnits::fromQuantity(NullValue),
8067 APValue::NoLValuePath{}, /*IsNullPtr=*/true);
8068 }
8069
8070 CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
8071
8072 // Work around floating point types that contain unused padding bytes. This
8073 // is really just `long double` on x86, which is the only fundamental type
8074 // with padding bytes.
8075 if (T->isRealFloatingType()) {
8076 const llvm::fltSemantics &Semantics =
8077 Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
8078 unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics);
8079 assert(NumBits % 8 == 0);
8080 CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8);
8081 if (NumBytes != SizeOf)
8082 SizeOf = NumBytes;
8083 }
8084
8085 SmallVector<uint8_t, 8> Bytes;
8086 if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
8087 // If this is std::byte or unsigned char, then its okay to store an
8088 // indeterminate value.
8089 bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
8090 bool IsUChar =
8091 !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
8092 T->isSpecificBuiltinType(BuiltinType::Char_U));
8093 if (!IsStdByte && !IsUChar) {
8094 QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
8095 Info.FFDiag(BCE->getExprLoc(),
8096 diag::note_constexpr_bit_cast_indet_dest)
8097 << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
8098 return std::nullopt;
8099 }
8100
8102 }
8103
8104 APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
8105 llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
8106
8108 Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
8109
8110 unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0));
8111 if (IntWidth != Val.getBitWidth()) {
8112 APSInt Truncated = Val.trunc(IntWidth);
8113 if (Truncated.extend(Val.getBitWidth()) != Val)
8114 return unrepresentableValue(QualType(T, 0), Val);
8115 Val = Truncated;
8116 }
8117
8118 return APValue(Val);
8119 }
8120
8121 if (T->isRealFloatingType()) {
8122 const llvm::fltSemantics &Semantics =
8123 Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
8124 return APValue(APFloat(Semantics, Val));
8125 }
8126
8127 return unsupportedType(QualType(T, 0));
8128 }
8129
8130 std::optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
8131 const RecordDecl *RD = RTy->getAsRecordDecl();
8132 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
8133
8134 unsigned NumBases = 0;
8135 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
8136 NumBases = CXXRD->getNumBases();
8137
8138 APValue ResultVal(APValue::UninitStruct(), NumBases,
8139 std::distance(RD->field_begin(), RD->field_end()));
8140
8141 // Visit the base classes.
8142 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
8143 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
8144 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
8145 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
8146
8147 std::optional<APValue> SubObj = visitType(
8148 BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
8149 if (!SubObj)
8150 return std::nullopt;
8151 ResultVal.getStructBase(I) = *SubObj;
8152 }
8153 }
8154
8155 // Visit the fields.
8156 unsigned FieldIdx = 0;
8157 for (FieldDecl *FD : RD->fields()) {
8158 // FIXME: We don't currently support bit-fields. A lot of the logic for
8159 // this is in CodeGen, so we need to factor it around.
8160 if (FD->isBitField()) {
8161 Info.FFDiag(BCE->getBeginLoc(),
8162 diag::note_constexpr_bit_cast_unsupported_bitfield);
8163 return std::nullopt;
8164 }
8165
8166 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
8167 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
8168
8169 CharUnits FieldOffset =
8170 CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
8171 Offset;
8172 QualType FieldTy = FD->getType();
8173 std::optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
8174 if (!SubObj)
8175 return std::nullopt;
8176 ResultVal.getStructField(FieldIdx) = *SubObj;
8177 ++FieldIdx;
8178 }
8179
8180 return ResultVal;
8181 }
8182
8183 std::optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
8184 QualType RepresentationType =
8185 Ty->getDecl()->getDefinitionOrSelf()->getIntegerType();
8186 assert(!RepresentationType.isNull() &&
8187 "enum forward decl should be caught by Sema");
8188 const auto *AsBuiltin =
8189 RepresentationType.getCanonicalType()->castAs<BuiltinType>();
8190 // Recurse into the underlying type. Treat std::byte transparently as
8191 // unsigned char.
8192 return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
8193 }
8194
8195 std::optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
8196 size_t Size = Ty->getLimitedSize();
8197 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
8198
8199 APValue ArrayValue(APValue::UninitArray(), Size, Size);
8200 for (size_t I = 0; I != Size; ++I) {
8201 std::optional<APValue> ElementValue =
8202 visitType(Ty->getElementType(), Offset + I * ElementWidth);
8203 if (!ElementValue)
8204 return std::nullopt;
8205 ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
8206 }
8207
8208 return ArrayValue;
8209 }
8210
8211 std::optional<APValue> visit(const ComplexType *Ty, CharUnits Offset) {
8212 QualType ElementType = Ty->getElementType();
8213 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(ElementType);
8214 bool IsInt = ElementType->isIntegerType();
8215
8216 std::optional<APValue> Values[2];
8217 for (unsigned I = 0; I != 2; ++I) {
8218 Values[I] = visitType(Ty->getElementType(), Offset + I * ElementWidth);
8219 if (!Values[I])
8220 return std::nullopt;
8221 }
8222
8223 if (IsInt)
8224 return APValue(Values[0]->getInt(), Values[1]->getInt());
8225 return APValue(Values[0]->getFloat(), Values[1]->getFloat());
8226 }
8227
8228 std::optional<APValue> visit(const VectorType *VTy, CharUnits Offset) {
8229 QualType EltTy = VTy->getElementType();
8230 unsigned NElts = VTy->getNumElements();
8231 unsigned EltSize =
8232 VTy->isPackedVectorBoolType(Info.Ctx) ? 1 : Info.Ctx.getTypeSize(EltTy);
8233
8234 SmallVector<APValue, 4> Elts;
8235 Elts.reserve(NElts);
8236 if (VTy->isPackedVectorBoolType(Info.Ctx)) {
8237 // Special handling for OpenCL bool vectors:
8238 // Since these vectors are stored as packed bits, but we can't read
8239 // individual bits from the BitCastBuffer, we'll buffer all of the
8240 // elements together into an appropriately sized APInt and write them all
8241 // out at once. Because we don't accept vectors where NElts * EltSize
8242 // isn't a multiple of the char size, there will be no padding space, so
8243 // we don't have to worry about reading any padding data which didn't
8244 // actually need to be accessed.
8245 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
8246
8247 SmallVector<uint8_t, 8> Bytes;
8248 Bytes.reserve(NElts / 8);
8249 if (!Buffer.readObject(Offset, CharUnits::fromQuantity(NElts / 8), Bytes))
8250 return std::nullopt;
8251
8252 APSInt SValInt(NElts, true);
8253 llvm::LoadIntFromMemory(SValInt, &*Bytes.begin(), Bytes.size());
8254
8255 for (unsigned I = 0; I < NElts; ++I) {
8256 llvm::APInt Elt =
8257 SValInt.extractBits(1, (BigEndian ? NElts - I - 1 : I) * EltSize);
8258 Elts.emplace_back(
8259 APSInt(std::move(Elt), !EltTy->isSignedIntegerType()));
8260 }
8261 } else {
8262 // Iterate over each of the elements and read them from the buffer at
8263 // the appropriate offset.
8264 CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
8265 for (unsigned I = 0; I < NElts; ++I) {
8266 std::optional<APValue> EltValue =
8267 visitType(EltTy, Offset + I * EltSizeChars);
8268 if (!EltValue)
8269 return std::nullopt;
8270 Elts.push_back(std::move(*EltValue));
8271 }
8272 }
8273
8274 return APValue(Elts.data(), Elts.size());
8275 }
8276
8277 std::optional<APValue> visit(const Type *Ty, CharUnits Offset) {
8278 return unsupportedType(QualType(Ty, 0));
8279 }
8280
8281 std::optional<APValue> visitType(QualType Ty, CharUnits Offset) {
8282 QualType Can = Ty.getCanonicalType();
8283
8284 switch (Can->getTypeClass()) {
8285#define TYPE(Class, Base) \
8286 case Type::Class: \
8287 return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
8288#define ABSTRACT_TYPE(Class, Base)
8289#define NON_CANONICAL_TYPE(Class, Base) \
8290 case Type::Class: \
8291 llvm_unreachable("non-canonical type should be impossible!");
8292#define DEPENDENT_TYPE(Class, Base) \
8293 case Type::Class: \
8294 llvm_unreachable( \
8295 "dependent types aren't supported in the constant evaluator!");
8296#define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base) \
8297 case Type::Class: \
8298 llvm_unreachable("either dependent or not canonical!");
8299#include "clang/AST/TypeNodes.inc"
8300 }
8301 llvm_unreachable("Unhandled Type::TypeClass");
8302 }
8303
8304public:
8305 // Pull out a full value of type DstType.
8306 static std::optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
8307 const CastExpr *BCE) {
8308 BufferToAPValueConverter Converter(Info, Buffer, BCE);
8309 return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
8310 }
8311};
8312
8313static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
8314 QualType Ty, EvalInfo *Info,
8315 const ASTContext &Ctx,
8316 bool CheckingDest) {
8317 Ty = Ty.getCanonicalType();
8318
8319 auto diag = [&](int Reason) {
8320 if (Info)
8321 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
8322 << CheckingDest << (Reason == 4) << Reason;
8323 return false;
8324 };
8325 auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
8326 if (Info)
8327 Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
8328 << NoteTy << Construct << Ty;
8329 return false;
8330 };
8331
8332 if (Ty->isUnionType())
8333 return diag(0);
8334 if (Ty->isPointerType())
8335 return diag(1);
8336 if (Ty->isMemberPointerType())
8337 return diag(2);
8338 if (Ty.isVolatileQualified())
8339 return diag(3);
8340
8341 if (RecordDecl *Record = Ty->getAsRecordDecl()) {
8342 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
8343 for (CXXBaseSpecifier &BS : CXXRD->bases())
8344 if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
8345 CheckingDest))
8346 return note(1, BS.getType(), BS.getBeginLoc());
8347 }
8348 for (FieldDecl *FD : Record->fields()) {
8349 if (FD->getType()->isReferenceType())
8350 return diag(4);
8351 if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
8352 CheckingDest))
8353 return note(0, FD->getType(), FD->getBeginLoc());
8354 }
8355 }
8356
8357 if (Ty->isArrayType() &&
8358 !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
8359 Info, Ctx, CheckingDest))
8360 return false;
8361
8362 if (const auto *VTy = Ty->getAs<VectorType>()) {
8363 QualType EltTy = VTy->getElementType();
8364 unsigned NElts = VTy->getNumElements();
8365 unsigned EltSize =
8366 VTy->isPackedVectorBoolType(Ctx) ? 1 : Ctx.getTypeSize(EltTy);
8367
8368 if ((NElts * EltSize) % Ctx.getCharWidth() != 0) {
8369 // The vector's size in bits is not a multiple of the target's byte size,
8370 // so its layout is unspecified. For now, we'll simply treat these cases
8371 // as unsupported (this should only be possible with OpenCL bool vectors
8372 // whose element count isn't a multiple of the byte size).
8373 if (Info)
8374 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_vector)
8375 << QualType(VTy, 0) << EltSize << NElts << Ctx.getCharWidth();
8376 return false;
8377 }
8378
8379 if (EltTy->isRealFloatingType() &&
8380 &Ctx.getFloatTypeSemantics(EltTy) == &APFloat::x87DoubleExtended()) {
8381 // The layout for x86_fp80 vectors seems to be handled very inconsistently
8382 // by both clang and LLVM, so for now we won't allow bit_casts involving
8383 // it in a constexpr context.
8384 if (Info)
8385 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_unsupported_type)
8386 << EltTy;
8387 return false;
8388 }
8389 }
8390
8391 return true;
8392}
8393
8394static bool checkBitCastConstexprEligibility(EvalInfo *Info,
8395 const ASTContext &Ctx,
8396 const CastExpr *BCE) {
8397 bool DestOK = checkBitCastConstexprEligibilityType(
8398 BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
8399 bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
8400 BCE->getBeginLoc(),
8401 BCE->getSubExpr()->getType(), Info, Ctx, false);
8402 return SourceOK;
8403}
8404
8405static bool handleRValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
8406 const APValue &SourceRValue,
8407 const CastExpr *BCE) {
8408 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
8409 "no host or target supports non 8-bit chars");
8410
8411 if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
8412 return false;
8413
8414 // Read out SourceValue into a char buffer.
8415 std::optional<BitCastBuffer> Buffer =
8416 APValueToBufferConverter::convert(Info, SourceRValue, BCE);
8417 if (!Buffer)
8418 return false;
8419
8420 // Write out the buffer into a new APValue.
8421 std::optional<APValue> MaybeDestValue =
8422 BufferToAPValueConverter::convert(Info, *Buffer, BCE);
8423 if (!MaybeDestValue)
8424 return false;
8425
8426 DestValue = std::move(*MaybeDestValue);
8427 return true;
8428}
8429
8430static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
8431 APValue &SourceValue,
8432 const CastExpr *BCE) {
8433 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
8434 "no host or target supports non 8-bit chars");
8435 assert(SourceValue.isLValue() &&
8436 "LValueToRValueBitcast requires an lvalue operand!");
8437
8438 LValue SourceLValue;
8439 APValue SourceRValue;
8440 SourceLValue.setFrom(Info.Ctx, SourceValue);
8442 Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,
8443 SourceRValue, /*WantObjectRepresentation=*/true))
8444 return false;
8445
8446 return handleRValueToRValueBitCast(Info, DestValue, SourceRValue, BCE);
8447}
8448
8449template <class Derived>
8450class ExprEvaluatorBase
8451 : public ConstStmtVisitor<Derived, bool> {
8452private:
8453 Derived &getDerived() { return static_cast<Derived&>(*this); }
8454 bool DerivedSuccess(const APValue &V, const Expr *E) {
8455 return getDerived().Success(V, E);
8456 }
8457 bool DerivedZeroInitialization(const Expr *E) {
8458 return getDerived().ZeroInitialization(E);
8459 }
8460
8461 // Check whether a conditional operator with a non-constant condition is a
8462 // potential constant expression. If neither arm is a potential constant
8463 // expression, then the conditional operator is not either.
8464 template<typename ConditionalOperator>
8465 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
8466 assert(Info.checkingPotentialConstantExpression());
8467
8468 // Speculatively evaluate both arms.
8469 SmallVector<PartialDiagnosticAt, 8> Diag;
8470 {
8471 SpeculativeEvaluationRAII Speculate(Info, &Diag);
8472 StmtVisitorTy::Visit(E->getFalseExpr());
8473 if (Diag.empty())
8474 return;
8475 }
8476
8477 {
8478 SpeculativeEvaluationRAII Speculate(Info, &Diag);
8479 Diag.clear();
8480 StmtVisitorTy::Visit(E->getTrueExpr());
8481 if (Diag.empty())
8482 return;
8483 }
8484
8485 Error(E, diag::note_constexpr_conditional_never_const);
8486 }
8487
8488
8489 template<typename ConditionalOperator>
8490 bool HandleConditionalOperator(const ConditionalOperator *E) {
8491 bool BoolResult;
8492 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
8493 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
8494 CheckPotentialConstantConditional(E);
8495 return false;
8496 }
8497 if (Info.noteFailure()) {
8498 StmtVisitorTy::Visit(E->getTrueExpr());
8499 StmtVisitorTy::Visit(E->getFalseExpr());
8500 }
8501 return false;
8502 }
8503
8504 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
8505 return StmtVisitorTy::Visit(EvalExpr);
8506 }
8507
8508protected:
8509 EvalInfo &Info;
8510 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
8511 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
8512
8513 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
8514 return Info.CCEDiag(E, D);
8515 }
8516
8517 bool ZeroInitialization(const Expr *E) { return Error(E); }
8518
8519 bool IsConstantEvaluatedBuiltinCall(const CallExpr *E) {
8520 unsigned BuiltinOp = E->getBuiltinCallee();
8521 return BuiltinOp != 0 &&
8522 Info.Ctx.BuiltinInfo.isConstantEvaluated(BuiltinOp);
8523 }
8524
8525public:
8526 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
8527
8528 EvalInfo &getEvalInfo() { return Info; }
8529
8530 /// Report an evaluation error. This should only be called when an error is
8531 /// first discovered. When propagating an error, just return false.
8532 bool Error(const Expr *E, diag::kind D) {
8533 Info.FFDiag(E, D) << E->getSourceRange();
8534 return false;
8535 }
8536 bool Error(const Expr *E) {
8537 return Error(E, diag::note_invalid_subexpr_in_const_expr);
8538 }
8539
8540 bool VisitStmt(const Stmt *) {
8541 llvm_unreachable("Expression evaluator should not be called on stmts");
8542 }
8543 bool VisitExpr(const Expr *E) {
8544 return Error(E);
8545 }
8546
8547 bool VisitEmbedExpr(const EmbedExpr *E) {
8548 const auto It = E->begin();
8549 return StmtVisitorTy::Visit(*It);
8550 }
8551
8552 bool VisitPredefinedExpr(const PredefinedExpr *E) {
8553 return StmtVisitorTy::Visit(E->getFunctionName());
8554 }
8555 bool VisitConstantExpr(const ConstantExpr *E) {
8556 if (E->hasAPValueResult())
8557 return DerivedSuccess(E->getAPValueResult(), E);
8558
8559 return StmtVisitorTy::Visit(E->getSubExpr());
8560 }
8561
8562 bool VisitParenExpr(const ParenExpr *E)
8563 { return StmtVisitorTy::Visit(E->getSubExpr()); }
8564 bool VisitUnaryExtension(const UnaryOperator *E)
8565 { return StmtVisitorTy::Visit(E->getSubExpr()); }
8566 bool VisitUnaryPlus(const UnaryOperator *E)
8567 { return StmtVisitorTy::Visit(E->getSubExpr()); }
8568 bool VisitChooseExpr(const ChooseExpr *E)
8569 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
8570 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
8571 { return StmtVisitorTy::Visit(E->getResultExpr()); }
8572 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
8573 { return StmtVisitorTy::Visit(E->getReplacement()); }
8574 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
8575 TempVersionRAII RAII(*Info.CurrentCall);
8576 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
8577 return StmtVisitorTy::Visit(E->getExpr());
8578 }
8579 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
8580 TempVersionRAII RAII(*Info.CurrentCall);
8581 // The initializer may not have been parsed yet, or might be erroneous.
8582 if (!E->getExpr())
8583 return Error(E);
8584 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
8585 return StmtVisitorTy::Visit(E->getExpr());
8586 }
8587
8588 bool VisitExprWithCleanups(const ExprWithCleanups *E) {
8589 FullExpressionRAII Scope(Info);
8590 return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy();
8591 }
8592
8593 // Temporaries are registered when created, so we don't care about
8594 // CXXBindTemporaryExpr.
8595 bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
8596 return StmtVisitorTy::Visit(E->getSubExpr());
8597 }
8598
8599 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
8600 CCEDiag(E, diag::note_constexpr_invalid_cast)
8601 << diag::ConstexprInvalidCastKind::Reinterpret;
8602 return static_cast<Derived*>(this)->VisitCastExpr(E);
8603 }
8604 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
8605 if (!Info.Ctx.getLangOpts().CPlusPlus20)
8606 CCEDiag(E, diag::note_constexpr_invalid_cast)
8607 << diag::ConstexprInvalidCastKind::Dynamic;
8608 return static_cast<Derived*>(this)->VisitCastExpr(E);
8609 }
8610 bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
8611 return static_cast<Derived*>(this)->VisitCastExpr(E);
8612 }
8613
8614 bool VisitBinaryOperator(const BinaryOperator *E) {
8615 switch (E->getOpcode()) {
8616 default:
8617 return Error(E);
8618
8619 case BO_Comma:
8620 VisitIgnoredValue(E->getLHS());
8621 return StmtVisitorTy::Visit(E->getRHS());
8622
8623 case BO_PtrMemD:
8624 case BO_PtrMemI: {
8625 LValue Obj;
8626 if (!HandleMemberPointerAccess(Info, E, Obj))
8627 return false;
8629 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
8630 return false;
8631 return DerivedSuccess(Result, E);
8632 }
8633 }
8634 }
8635
8636 bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) {
8637 return StmtVisitorTy::Visit(E->getSemanticForm());
8638 }
8639
8640 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
8641 // Evaluate and cache the common expression. We treat it as a temporary,
8642 // even though it's not quite the same thing.
8643 LValue CommonLV;
8644 if (!Evaluate(Info.CurrentCall->createTemporary(
8645 E->getOpaqueValue(),
8646 getStorageType(Info.Ctx, E->getOpaqueValue()),
8647 ScopeKind::FullExpression, CommonLV),
8648 Info, E->getCommon()))
8649 return false;
8650
8651 return HandleConditionalOperator(E);
8652 }
8653
8654 bool VisitConditionalOperator(const ConditionalOperator *E) {
8655 bool IsBcpCall = false;
8656 // If the condition (ignoring parens) is a __builtin_constant_p call,
8657 // the result is a constant expression if it can be folded without
8658 // side-effects. This is an important GNU extension. See GCC PR38377
8659 // for discussion.
8660 if (const CallExpr *CallCE =
8661 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
8662 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
8663 IsBcpCall = true;
8664
8665 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
8666 // constant expression; we can't check whether it's potentially foldable.
8667 // FIXME: We should instead treat __builtin_constant_p as non-constant if
8668 // it would return 'false' in this mode.
8669 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
8670 return false;
8671
8672 FoldConstant Fold(Info, IsBcpCall);
8673 if (!HandleConditionalOperator(E)) {
8674 Fold.keepDiagnostics();
8675 return false;
8676 }
8677
8678 return true;
8679 }
8680
8681 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
8682 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E);
8683 Value && !Value->isAbsent())
8684 return DerivedSuccess(*Value, E);
8685
8686 const Expr *Source = E->getSourceExpr();
8687 if (!Source)
8688 return Error(E);
8689 if (Source == E) {
8690 assert(0 && "OpaqueValueExpr recursively refers to itself");
8691 return Error(E);
8692 }
8693 return StmtVisitorTy::Visit(Source);
8694 }
8695
8696 bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
8697 for (const Expr *SemE : E->semantics()) {
8698 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
8699 // FIXME: We can't handle the case where an OpaqueValueExpr is also the
8700 // result expression: there could be two different LValues that would
8701 // refer to the same object in that case, and we can't model that.
8702 if (SemE == E->getResultExpr())
8703 return Error(E);
8704
8705 // Unique OVEs get evaluated if and when we encounter them when
8706 // emitting the rest of the semantic form, rather than eagerly.
8707 if (OVE->isUnique())
8708 continue;
8709
8710 LValue LV;
8711 if (!Evaluate(Info.CurrentCall->createTemporary(
8712 OVE, getStorageType(Info.Ctx, OVE),
8713 ScopeKind::FullExpression, LV),
8714 Info, OVE->getSourceExpr()))
8715 return false;
8716 } else if (SemE == E->getResultExpr()) {
8717 if (!StmtVisitorTy::Visit(SemE))
8718 return false;
8719 } else {
8720 if (!EvaluateIgnoredValue(Info, SemE))
8721 return false;
8722 }
8723 }
8724 return true;
8725 }
8726
8727 bool VisitCallExpr(const CallExpr *E) {
8729 if (!handleCallExpr(E, Result, nullptr))
8730 return false;
8731 return DerivedSuccess(Result, E);
8732 }
8733
8734 bool handleCallExpr(const CallExpr *E, APValue &Result,
8735 const LValue *ResultSlot) {
8736 CallScopeRAII CallScope(Info);
8737
8738 const Expr *Callee = E->getCallee()->IgnoreParens();
8739 QualType CalleeType = Callee->getType();
8740
8741 const FunctionDecl *FD = nullptr;
8742 LValue *This = nullptr, ObjectArg;
8743 auto Args = ArrayRef(E->getArgs(), E->getNumArgs());
8744 bool HasQualifier = false;
8745
8746 CallRef Call;
8747
8748 // Extract function decl and 'this' pointer from the callee.
8749 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
8750 const CXXMethodDecl *Member = nullptr;
8751 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
8752 // Explicit bound member calls, such as x.f() or p->g();
8753 if (!EvaluateObjectArgument(Info, ME->getBase(), ObjectArg))
8754 return false;
8755 Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
8756 if (!Member)
8757 return Error(Callee);
8758 This = &ObjectArg;
8759 HasQualifier = ME->hasQualifier();
8760 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
8761 // Indirect bound member calls ('.*' or '->*').
8762 const ValueDecl *D =
8763 HandleMemberPointerAccess(Info, BE, ObjectArg, false);
8764 if (!D)
8765 return false;
8766 Member = dyn_cast<CXXMethodDecl>(D);
8767 if (!Member)
8768 return Error(Callee);
8769 This = &ObjectArg;
8770 } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
8771 if (!Info.getLangOpts().CPlusPlus20)
8772 Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
8773 return EvaluateObjectArgument(Info, PDE->getBase(), ObjectArg) &&
8774 HandleDestruction(Info, PDE, ObjectArg, PDE->getDestroyedType());
8775 } else
8776 return Error(Callee);
8777 FD = Member;
8778 } else if (CalleeType->isFunctionPointerType()) {
8779 LValue CalleeLV;
8780 if (!EvaluatePointer(Callee, CalleeLV, Info))
8781 return false;
8782
8783 if (!CalleeLV.getLValueOffset().isZero())
8784 return Error(Callee);
8785 if (CalleeLV.isNullPointer()) {
8786 Info.FFDiag(Callee, diag::note_constexpr_null_callee)
8787 << const_cast<Expr *>(Callee);
8788 return false;
8789 }
8790 FD = dyn_cast_or_null<FunctionDecl>(
8791 CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>());
8792 if (!FD)
8793 return Error(Callee);
8794 // Don't call function pointers which have been cast to some other type.
8795 // Per DR (no number yet), the caller and callee can differ in noexcept.
8797 CalleeType->getPointeeType(), FD->getType())) {
8798 return Error(E);
8799 }
8800
8801 // For an (overloaded) assignment expression, evaluate the RHS before the
8802 // LHS.
8803 auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
8804 if (OCE && OCE->isAssignmentOp()) {
8805 assert(Args.size() == 2 && "wrong number of arguments in assignment");
8806 Call = Info.CurrentCall->createCall(FD);
8807 bool HasThis = false;
8808 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
8809 HasThis = MD->isImplicitObjectMemberFunction();
8810 if (!EvaluateArgs(HasThis ? Args.slice(1) : Args, Call, Info, FD,
8811 /*RightToLeft=*/true, &ObjectArg))
8812 return false;
8813 }
8814
8815 // Overloaded operator calls to member functions are represented as normal
8816 // calls with '*this' as the first argument.
8817 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8818 if (MD &&
8819 (MD->isImplicitObjectMemberFunction() || (OCE && MD->isStatic()))) {
8820 // FIXME: When selecting an implicit conversion for an overloaded
8821 // operator delete, we sometimes try to evaluate calls to conversion
8822 // operators without a 'this' parameter!
8823 if (Args.empty())
8824 return Error(E);
8825
8826 if (!EvaluateObjectArgument(Info, Args[0], ObjectArg))
8827 return false;
8828
8829 // If we are calling a static operator, the 'this' argument needs to be
8830 // ignored after being evaluated.
8831 if (MD->isInstance())
8832 This = &ObjectArg;
8833
8834 // If this is syntactically a simple assignment using a trivial
8835 // assignment operator, start the lifetimes of union members as needed,
8836 // per C++20 [class.union]5.
8837 if (Info.getLangOpts().CPlusPlus20 && OCE &&
8838 OCE->getOperator() == OO_Equal && MD->isTrivial() &&
8839 !MaybeHandleUnionActiveMemberChange(Info, Args[0], ObjectArg))
8840 return false;
8841
8842 Args = Args.slice(1);
8843 } else if (MD && MD->isLambdaStaticInvoker()) {
8844 // Map the static invoker for the lambda back to the call operator.
8845 // Conveniently, we don't have to slice out the 'this' argument (as is
8846 // being done for the non-static case), since a static member function
8847 // doesn't have an implicit argument passed in.
8848 const CXXRecordDecl *ClosureClass = MD->getParent();
8849 assert(
8850 ClosureClass->captures().empty() &&
8851 "Number of captures must be zero for conversion to function-ptr");
8852
8853 const CXXMethodDecl *LambdaCallOp =
8854 ClosureClass->getLambdaCallOperator();
8855
8856 // Set 'FD', the function that will be called below, to the call
8857 // operator. If the closure object represents a generic lambda, find
8858 // the corresponding specialization of the call operator.
8859
8860 if (ClosureClass->isGenericLambda()) {
8861 assert(MD->isFunctionTemplateSpecialization() &&
8862 "A generic lambda's static-invoker function must be a "
8863 "template specialization");
8864 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
8865 FunctionTemplateDecl *CallOpTemplate =
8866 LambdaCallOp->getDescribedFunctionTemplate();
8867 void *InsertPos = nullptr;
8868 FunctionDecl *CorrespondingCallOpSpecialization =
8869 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
8870 assert(CorrespondingCallOpSpecialization &&
8871 "We must always have a function call operator specialization "
8872 "that corresponds to our static invoker specialization");
8873 assert(isa<CXXMethodDecl>(CorrespondingCallOpSpecialization));
8874 FD = CorrespondingCallOpSpecialization;
8875 } else
8876 FD = LambdaCallOp;
8878 if (FD->getDeclName().isAnyOperatorNew()) {
8879 LValue Ptr;
8880 if (!HandleOperatorNewCall(Info, E, Ptr))
8881 return false;
8882 Ptr.moveInto(Result);
8883 return CallScope.destroy();
8884 } else {
8885 return HandleOperatorDeleteCall(Info, E) && CallScope.destroy();
8886 }
8887 }
8888 } else
8889 return Error(E);
8890
8891 // Evaluate the arguments now if we've not already done so.
8892 if (!Call) {
8893 Call = Info.CurrentCall->createCall(FD);
8894 if (!EvaluateArgs(Args, Call, Info, FD, /*RightToLeft*/ false,
8895 &ObjectArg))
8896 return false;
8897 }
8898
8899 SmallVector<QualType, 4> CovariantAdjustmentPath;
8900 if (This) {
8901 auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
8902 if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
8903 // Perform virtual dispatch, if necessary.
8904 FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
8905 CovariantAdjustmentPath);
8906 if (!FD)
8907 return false;
8908 } else if (NamedMember && NamedMember->isImplicitObjectMemberFunction()) {
8909 // Check that the 'this' pointer points to an object of the right type.
8910 // FIXME: If this is an assignment operator call, we may need to change
8911 // the active union member before we check this.
8912 if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
8913 return false;
8914 }
8915 }
8916
8917 // Destructor calls are different enough that they have their own codepath.
8918 if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
8919 assert(This && "no 'this' pointer for destructor call");
8920 return HandleDestruction(Info, E, *This,
8921 Info.Ctx.getCanonicalTagType(DD->getParent())) &&
8922 CallScope.destroy();
8923 }
8924
8925 const FunctionDecl *Definition = nullptr;
8926 Stmt *Body = FD->getBody(Definition);
8927 SourceLocation Loc = E->getExprLoc();
8928
8929 // Treat the object argument as `this` when evaluating defaulted
8930 // special menmber functions
8932 This = &ObjectArg;
8933
8934 if (!CheckConstexprFunction(Info, Loc, FD, Definition, Body) ||
8935 !HandleFunctionCall(Loc, Definition, This, E, Args, Call, Body, Info,
8936 Result, ResultSlot))
8937 return false;
8938
8939 if (!CovariantAdjustmentPath.empty() &&
8941 CovariantAdjustmentPath))
8942 return false;
8943
8944 return CallScope.destroy();
8945 }
8946
8947 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
8948 return StmtVisitorTy::Visit(E->getInitializer());
8949 }
8950 bool VisitInitListExpr(const InitListExpr *E) {
8951 if (E->getNumInits() == 0)
8952 return DerivedZeroInitialization(E);
8953 if (E->getNumInits() == 1)
8954 return StmtVisitorTy::Visit(E->getInit(0));
8955 return Error(E);
8956 }
8957 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
8958 return DerivedZeroInitialization(E);
8959 }
8960 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
8961 return DerivedZeroInitialization(E);
8962 }
8963 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
8964 return DerivedZeroInitialization(E);
8965 }
8966
8967 /// A member expression where the object is a prvalue is itself a prvalue.
8968 bool VisitMemberExpr(const MemberExpr *E) {
8969 assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
8970 "missing temporary materialization conversion");
8971 assert(!E->isArrow() && "missing call to bound member function?");
8972
8973 APValue Val;
8974 if (!Evaluate(Val, Info, E->getBase()))
8975 return false;
8976
8977 QualType BaseTy = E->getBase()->getType();
8978
8979 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
8980 if (!FD) return Error(E);
8981 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
8982 assert(BaseTy->castAsCanonical<RecordType>()->getDecl() ==
8983 FD->getParent()->getCanonicalDecl() &&
8984 "record / field mismatch");
8985
8986 // Note: there is no lvalue base here. But this case should only ever
8987 // happen in C or in C++98, where we cannot be evaluating a constexpr
8988 // constructor, which is the only case the base matters.
8989 CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
8990 SubobjectDesignator Designator(BaseTy);
8991 Designator.addDeclUnchecked(FD);
8992
8994 return extractSubobject(Info, E, Obj, Designator, Result) &&
8995 DerivedSuccess(Result, E);
8996 }
8997
8998 bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) {
8999 APValue Val;
9000 if (!Evaluate(Val, Info, E->getBase()))
9001 return false;
9002
9003 if (Val.isVector()) {
9004 SmallVector<uint32_t, 4> Indices;
9005 E->getEncodedElementAccess(Indices);
9006 if (Indices.size() == 1) {
9007 // Return scalar.
9008 return DerivedSuccess(Val.getVectorElt(Indices[0]), E);
9009 } else {
9010 // Construct new APValue vector.
9011 SmallVector<APValue, 4> Elts;
9012 for (unsigned I = 0; I < Indices.size(); ++I) {
9013 Elts.push_back(Val.getVectorElt(Indices[I]));
9014 }
9015 APValue VecResult(Elts.data(), Indices.size());
9016 return DerivedSuccess(VecResult, E);
9017 }
9018 }
9019
9020 return false;
9021 }
9022
9023 bool VisitCastExpr(const CastExpr *E) {
9024 switch (E->getCastKind()) {
9025 default:
9026 break;
9027
9028 case CK_AtomicToNonAtomic: {
9029 APValue AtomicVal;
9030 // This does not need to be done in place even for class/array types:
9031 // atomic-to-non-atomic conversion implies copying the object
9032 // representation.
9033 if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
9034 return false;
9035 return DerivedSuccess(AtomicVal, E);
9036 }
9037
9038 case CK_NoOp:
9039 case CK_UserDefinedConversion:
9040 return StmtVisitorTy::Visit(E->getSubExpr());
9041
9042 case CK_HLSLArrayRValue: {
9043 const Expr *SubExpr = E->getSubExpr();
9044 if (!SubExpr->isGLValue()) {
9045 APValue Val;
9046 if (!Evaluate(Val, Info, SubExpr))
9047 return false;
9048 return DerivedSuccess(Val, E);
9049 }
9050
9051 LValue LVal;
9052 if (!EvaluateLValue(SubExpr, LVal, Info))
9053 return false;
9054 APValue RVal;
9055 // Note, we use the subexpression's type in order to retain cv-qualifiers.
9056 if (!handleLValueToRValueConversion(Info, E, SubExpr->getType(), LVal,
9057 RVal))
9058 return false;
9059 return DerivedSuccess(RVal, E);
9060 }
9061 case CK_LValueToRValue: {
9062 LValue LVal;
9063 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
9064 return false;
9065 APValue RVal;
9066 // Note, we use the subexpression's type in order to retain cv-qualifiers.
9068 LVal, RVal))
9069 return false;
9070 return DerivedSuccess(RVal, E);
9071 }
9072 case CK_LValueToRValueBitCast: {
9073 APValue DestValue, SourceValue;
9074 if (!Evaluate(SourceValue, Info, E->getSubExpr()))
9075 return false;
9076 if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
9077 return false;
9078 return DerivedSuccess(DestValue, E);
9079 }
9080
9081 case CK_AddressSpaceConversion: {
9082 APValue Value;
9083 if (!Evaluate(Value, Info, E->getSubExpr()))
9084 return false;
9085 return DerivedSuccess(Value, E);
9086 }
9087 }
9088
9089 return Error(E);
9090 }
9091
9092 bool VisitUnaryPostInc(const UnaryOperator *UO) {
9093 return VisitUnaryPostIncDec(UO);
9094 }
9095 bool VisitUnaryPostDec(const UnaryOperator *UO) {
9096 return VisitUnaryPostIncDec(UO);
9097 }
9098 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
9099 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9100 return Error(UO);
9101
9102 LValue LVal;
9103 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
9104 return false;
9105 APValue RVal;
9106 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
9107 UO->isIncrementOp(), &RVal))
9108 return false;
9109 return DerivedSuccess(RVal, UO);
9110 }
9111
9112 bool VisitStmtExpr(const StmtExpr *E) {
9113 // We will have checked the full-expressions inside the statement expression
9114 // when they were completed, and don't need to check them again now.
9115 llvm::SaveAndRestore NotCheckingForUB(Info.CheckingForUndefinedBehavior,
9116 false);
9117
9118 const CompoundStmt *CS = E->getSubStmt();
9119 if (CS->body_empty())
9120 return true;
9121
9122 BlockScopeRAII Scope(Info);
9124 BE = CS->body_end();
9125 /**/; ++BI) {
9126 if (BI + 1 == BE) {
9127 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
9128 if (!FinalExpr) {
9129 Info.FFDiag((*BI)->getBeginLoc(),
9130 diag::note_constexpr_stmt_expr_unsupported);
9131 return false;
9132 }
9133 return this->Visit(FinalExpr) && Scope.destroy();
9134 }
9135
9137 StmtResult Result = { ReturnValue, nullptr };
9138 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
9139 if (ESR != ESR_Succeeded) {
9140 // FIXME: If the statement-expression terminated due to 'return',
9141 // 'break', or 'continue', it would be nice to propagate that to
9142 // the outer statement evaluation rather than bailing out.
9143 if (ESR != ESR_Failed)
9144 Info.FFDiag((*BI)->getBeginLoc(),
9145 diag::note_constexpr_stmt_expr_unsupported);
9146 return false;
9147 }
9148 }
9149
9150 llvm_unreachable("Return from function from the loop above.");
9151 }
9152
9153 bool VisitPackIndexingExpr(const PackIndexingExpr *E) {
9154 return StmtVisitorTy::Visit(E->getSelectedExpr());
9155 }
9156
9157 /// Visit a value which is evaluated, but whose value is ignored.
9158 void VisitIgnoredValue(const Expr *E) {
9159 EvaluateIgnoredValue(Info, E);
9160 }
9161
9162 /// Potentially visit a MemberExpr's base expression.
9163 void VisitIgnoredBaseExpression(const Expr *E) {
9164 // While MSVC doesn't evaluate the base expression, it does diagnose the
9165 // presence of side-effecting behavior.
9166 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
9167 return;
9168 VisitIgnoredValue(E);
9169 }
9170};
9171
9172} // namespace
9173
9174//===----------------------------------------------------------------------===//
9175// Common base class for lvalue and temporary evaluation.
9176//===----------------------------------------------------------------------===//
9177namespace {
9178template<class Derived>
9179class LValueExprEvaluatorBase
9180 : public ExprEvaluatorBase<Derived> {
9181protected:
9182 LValue &Result;
9183 bool InvalidBaseOK;
9184 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
9185 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
9186
9187 bool Success(APValue::LValueBase B) {
9188 Result.set(B);
9189 return true;
9190 }
9191
9192 bool evaluatePointer(const Expr *E, LValue &Result) {
9193 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
9194 }
9195
9196public:
9197 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
9198 : ExprEvaluatorBaseTy(Info), Result(Result),
9199 InvalidBaseOK(InvalidBaseOK) {}
9200
9201 bool Success(const APValue &V, const Expr *E) {
9202 Result.setFrom(this->Info.Ctx, V);
9203 return true;
9204 }
9205
9206 bool VisitMemberExpr(const MemberExpr *E) {
9207 // Handle non-static data members.
9208 QualType BaseTy;
9209 bool EvalOK;
9210 if (E->isArrow()) {
9211 EvalOK = evaluatePointer(E->getBase(), Result);
9212 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
9213 } else if (E->getBase()->isPRValue()) {
9214 assert(E->getBase()->getType()->isRecordType());
9215 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
9216 BaseTy = E->getBase()->getType();
9217 } else {
9218 EvalOK = this->Visit(E->getBase());
9219 BaseTy = E->getBase()->getType();
9220 }
9221 if (!EvalOK) {
9222 if (!InvalidBaseOK)
9223 return false;
9224 Result.setInvalid(E);
9225 return true;
9226 }
9227
9228 const ValueDecl *MD = E->getMemberDecl();
9229 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
9230 assert(BaseTy->castAsCanonical<RecordType>()->getDecl() ==
9231 FD->getParent()->getCanonicalDecl() &&
9232 "record / field mismatch");
9233 (void)BaseTy;
9234 if (!HandleLValueMember(this->Info, E, Result, FD))
9235 return false;
9236 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
9237 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
9238 return false;
9239 } else
9240 return this->Error(E);
9241
9242 if (MD->getType()->isReferenceType()) {
9243 APValue RefValue;
9244 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
9245 RefValue))
9246 return false;
9247 return Success(RefValue, E);
9248 }
9249 return true;
9250 }
9251
9252 bool VisitBinaryOperator(const BinaryOperator *E) {
9253 switch (E->getOpcode()) {
9254 default:
9255 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9256
9257 case BO_PtrMemD:
9258 case BO_PtrMemI:
9259 return HandleMemberPointerAccess(this->Info, E, Result);
9260 }
9261 }
9262
9263 bool VisitCastExpr(const CastExpr *E) {
9264 switch (E->getCastKind()) {
9265 default:
9266 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9267
9268 case CK_DerivedToBase:
9269 case CK_UncheckedDerivedToBase:
9270 if (!this->Visit(E->getSubExpr()))
9271 return false;
9272
9273 // Now figure out the necessary offset to add to the base LV to get from
9274 // the derived class to the base class.
9275 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
9276 Result);
9277 }
9278 }
9279};
9280}
9281
9282//===----------------------------------------------------------------------===//
9283// LValue Evaluation
9284//
9285// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
9286// function designators (in C), decl references to void objects (in C), and
9287// temporaries (if building with -Wno-address-of-temporary).
9288//
9289// LValue evaluation produces values comprising a base expression of one of the
9290// following types:
9291// - Declarations
9292// * VarDecl
9293// * FunctionDecl
9294// - Literals
9295// * CompoundLiteralExpr in C (and in global scope in C++)
9296// * StringLiteral
9297// * PredefinedExpr
9298// * ObjCStringLiteralExpr
9299// * ObjCEncodeExpr
9300// * AddrLabelExpr
9301// * BlockExpr
9302// * CallExpr for a MakeStringConstant builtin
9303// - typeid(T) expressions, as TypeInfoLValues
9304// - Locals and temporaries
9305// * MaterializeTemporaryExpr
9306// * Any Expr, with a CallIndex indicating the function in which the temporary
9307// was evaluated, for cases where the MaterializeTemporaryExpr is missing
9308// from the AST (FIXME).
9309// * A MaterializeTemporaryExpr that has static storage duration, with no
9310// CallIndex, for a lifetime-extended temporary.
9311// * The ConstantExpr that is currently being evaluated during evaluation of an
9312// immediate invocation.
9313// plus an offset in bytes.
9314//===----------------------------------------------------------------------===//
9315namespace {
9316class LValueExprEvaluator
9317 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
9318public:
9319 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
9320 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
9321
9322 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
9323 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
9324
9325 bool VisitCallExpr(const CallExpr *E);
9326 bool VisitDeclRefExpr(const DeclRefExpr *E);
9327 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
9328 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
9329 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
9330 bool VisitMemberExpr(const MemberExpr *E);
9331 bool VisitStringLiteral(const StringLiteral *E) {
9332 return Success(APValue::LValueBase(
9333 E, 0, Info.getASTContext().getNextStringLiteralVersion()));
9334 }
9335 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
9336 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
9337 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
9338 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
9339 bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E);
9340 bool VisitUnaryDeref(const UnaryOperator *E);
9341 bool VisitUnaryReal(const UnaryOperator *E);
9342 bool VisitUnaryImag(const UnaryOperator *E);
9343 bool VisitUnaryPreInc(const UnaryOperator *UO) {
9344 return VisitUnaryPreIncDec(UO);
9345 }
9346 bool VisitUnaryPreDec(const UnaryOperator *UO) {
9347 return VisitUnaryPreIncDec(UO);
9348 }
9349 bool VisitBinAssign(const BinaryOperator *BO);
9350 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
9351
9352 bool VisitCastExpr(const CastExpr *E) {
9353 switch (E->getCastKind()) {
9354 default:
9355 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
9356
9357 case CK_LValueBitCast:
9358 this->CCEDiag(E, diag::note_constexpr_invalid_cast)
9359 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
9360 << Info.Ctx.getLangOpts().CPlusPlus;
9361 if (!Visit(E->getSubExpr()))
9362 return false;
9363 Result.Designator.setInvalid();
9364 return true;
9365
9366 case CK_BaseToDerived:
9367 if (!Visit(E->getSubExpr()))
9368 return false;
9369 return HandleBaseToDerivedCast(Info, E, Result);
9370
9371 case CK_Dynamic:
9372 if (!Visit(E->getSubExpr()))
9373 return false;
9375 }
9376 }
9377};
9378} // end anonymous namespace
9379
9380/// Get an lvalue to a field of a lambda's closure type.
9381static bool HandleLambdaCapture(EvalInfo &Info, const Expr *E, LValue &Result,
9382 const CXXMethodDecl *MD, const FieldDecl *FD,
9383 bool LValueToRValueConversion) {
9384 // Static lambda function call operators can't have captures. We already
9385 // diagnosed this, so bail out here.
9386 if (MD->isStatic()) {
9387 assert(Info.CurrentCall->This == nullptr &&
9388 "This should not be set for a static call operator");
9389 return false;
9390 }
9391
9392 // Start with 'Result' referring to the complete closure object...
9394 // Self may be passed by reference or by value.
9395 const ParmVarDecl *Self = MD->getParamDecl(0);
9396 if (Self->getType()->isReferenceType()) {
9397 APValue *RefValue = Info.getParamSlot(Info.CurrentCall->Arguments, Self);
9398 if (!RefValue->allowConstexprUnknown() || RefValue->hasValue())
9399 Result.setFrom(Info.Ctx, *RefValue);
9400 } else {
9401 const ParmVarDecl *VD = Info.CurrentCall->Arguments.getOrigParam(Self);
9402 CallStackFrame *Frame =
9403 Info.getCallFrameAndDepth(Info.CurrentCall->Arguments.CallIndex)
9404 .first;
9405 unsigned Version = Info.CurrentCall->Arguments.Version;
9406 Result.set({VD, Frame->Index, Version});
9407 }
9408 } else
9409 Result = *Info.CurrentCall->This;
9410
9411 // ... then update it to refer to the field of the closure object
9412 // that represents the capture.
9413 if (!HandleLValueMember(Info, E, Result, FD))
9414 return false;
9415
9416 // And if the field is of reference type (or if we captured '*this' by
9417 // reference), update 'Result' to refer to what
9418 // the field refers to.
9419 if (LValueToRValueConversion) {
9420 APValue RVal;
9421 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result, RVal))
9422 return false;
9423 Result.setFrom(Info.Ctx, RVal);
9424 }
9425 return true;
9426}
9427
9428/// Evaluate an expression as an lvalue. This can be legitimately called on
9429/// expressions which are not glvalues, in three cases:
9430/// * function designators in C, and
9431/// * "extern void" objects
9432/// * @selector() expressions in Objective-C
9433static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
9434 bool InvalidBaseOK) {
9435 assert(!E->isValueDependent());
9436 assert(E->isGLValue() || E->getType()->isFunctionType() ||
9438 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
9439}
9440
9441bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
9442 const ValueDecl *D = E->getDecl();
9443
9444 // If we are within a lambda's call operator, check whether the 'VD' referred
9445 // to within 'E' actually represents a lambda-capture that maps to a
9446 // data-member/field within the closure object, and if so, evaluate to the
9447 // field or what the field refers to.
9448 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
9450 // We don't always have a complete capture-map when checking or inferring if
9451 // the function call operator meets the requirements of a constexpr function
9452 // - but we don't need to evaluate the captures to determine constexprness
9453 // (dcl.constexpr C++17).
9454 if (Info.checkingPotentialConstantExpression())
9455 return false;
9456
9457 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(D)) {
9458 const auto *MD = cast<CXXMethodDecl>(Info.CurrentCall->Callee);
9459 return HandleLambdaCapture(Info, E, Result, MD, FD,
9460 FD->getType()->isReferenceType());
9461 }
9462 }
9463
9464 if (isa<FunctionDecl, MSGuidDecl, TemplateParamObjectDecl,
9465 UnnamedGlobalConstantDecl>(D))
9466 return Success(cast<ValueDecl>(D));
9467 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
9468 return VisitVarDecl(E, VD);
9469 if (const BindingDecl *BD = dyn_cast<BindingDecl>(D))
9470 return Visit(BD->getBinding());
9471 return Error(E);
9472}
9473
9474bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
9475 CallStackFrame *Frame = nullptr;
9476 unsigned Version = 0;
9477 if (VD->hasLocalStorage()) {
9478 // Only if a local variable was declared in the function currently being
9479 // evaluated, do we expect to be able to find its value in the current
9480 // frame. (Otherwise it was likely declared in an enclosing context and
9481 // could either have a valid evaluatable value (for e.g. a constexpr
9482 // variable) or be ill-formed (and trigger an appropriate evaluation
9483 // diagnostic)).
9484 CallStackFrame *CurrFrame = Info.CurrentCall;
9485 if (CurrFrame->Callee && CurrFrame->Callee->Equals(VD->getDeclContext())) {
9486 // Function parameters are stored in some caller's frame. (Usually the
9487 // immediate caller, but for an inherited constructor they may be more
9488 // distant.)
9489 if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) {
9490 if (CurrFrame->Arguments) {
9491 VD = CurrFrame->Arguments.getOrigParam(PVD);
9492 Frame =
9493 Info.getCallFrameAndDepth(CurrFrame->Arguments.CallIndex).first;
9494 Version = CurrFrame->Arguments.Version;
9495 }
9496 } else {
9497 Frame = CurrFrame;
9498 Version = CurrFrame->getCurrentTemporaryVersion(VD);
9499 }
9500 }
9501 }
9502
9503 if (!VD->getType()->isReferenceType()) {
9504 if (Frame) {
9505 Result.set({VD, Frame->Index, Version});
9506 return true;
9507 }
9508 return Success(VD);
9509 }
9510
9511 if (!Info.getLangOpts().CPlusPlus11) {
9512 Info.CCEDiag(E, diag::note_constexpr_ltor_non_integral, 1)
9513 << VD << VD->getType();
9514 Info.Note(VD->getLocation(), diag::note_declared_at);
9515 }
9516
9517 APValue *V;
9518 if (!evaluateVarDeclInit(Info, E, VD, Frame, Version, V))
9519 return false;
9520
9521 if (!V) {
9522 Result.set(VD);
9523 Result.AllowConstexprUnknown = true;
9524 return true;
9525 }
9526
9527 return Success(*V, E);
9528}
9529
9530bool LValueExprEvaluator::VisitCallExpr(const CallExpr *E) {
9531 if (!IsConstantEvaluatedBuiltinCall(E))
9532 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9533
9534 switch (E->getBuiltinCallee()) {
9535 default:
9536 return false;
9537 case Builtin::BIas_const:
9538 case Builtin::BIforward:
9539 case Builtin::BIforward_like:
9540 case Builtin::BImove:
9541 case Builtin::BImove_if_noexcept:
9542 if (cast<FunctionDecl>(E->getCalleeDecl())->isConstexpr())
9543 return Visit(E->getArg(0));
9544 break;
9545 }
9546
9547 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9548}
9549
9550bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
9551 const MaterializeTemporaryExpr *E) {
9552 // Walk through the expression to find the materialized temporary itself.
9555 const Expr *Inner =
9556 E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
9557
9558 // If we passed any comma operators, evaluate their LHSs.
9559 for (const Expr *E : CommaLHSs)
9560 if (!EvaluateIgnoredValue(Info, E))
9561 return false;
9562
9563 // A materialized temporary with static storage duration can appear within the
9564 // result of a constant expression evaluation, so we need to preserve its
9565 // value for use outside this evaluation.
9566 APValue *Value;
9567 if (E->getStorageDuration() == SD_Static) {
9568 if (Info.EvalMode == EvaluationMode::ConstantFold)
9569 return false;
9570 // FIXME: What about SD_Thread?
9571 Value = E->getOrCreateValue(true);
9572 *Value = APValue();
9573 Result.set(E);
9574 } else {
9575 Value = &Info.CurrentCall->createTemporary(
9576 E, Inner->getType(),
9577 E->getStorageDuration() == SD_FullExpression ? ScopeKind::FullExpression
9578 : ScopeKind::Block,
9579 Result);
9580 }
9581
9582 QualType Type = Inner->getType();
9583
9584 // Materialize the temporary itself.
9585 if (!EvaluateInPlace(*Value, Info, Result, Inner)) {
9586 *Value = APValue();
9587 return false;
9588 }
9589
9590 // Adjust our lvalue to refer to the desired subobject.
9591 for (unsigned I = Adjustments.size(); I != 0; /**/) {
9592 --I;
9593 switch (Adjustments[I].Kind) {
9595 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
9596 Type, Result))
9597 return false;
9598 Type = Adjustments[I].DerivedToBase.BasePath->getType();
9599 break;
9600
9602 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
9603 return false;
9604 Type = Adjustments[I].Field->getType();
9605 break;
9606
9608 if (!HandleMemberPointerAccess(this->Info, Type, Result,
9609 Adjustments[I].Ptr.RHS))
9610 return false;
9611 Type = Adjustments[I].Ptr.MPT->getPointeeType();
9612 break;
9613 }
9614 }
9615
9616 return true;
9617}
9618
9619bool
9620LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
9621 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
9622 "lvalue compound literal in c++?");
9623 APValue *Lit;
9624 // If CompountLiteral has static storage, its value can be used outside
9625 // this expression. So evaluate it once and store it in ASTContext.
9626 if (E->hasStaticStorage()) {
9627 Lit = &E->getOrCreateStaticValue(Info.Ctx);
9628 Result.set(E);
9629 // Reset any previously evaluated state, otherwise evaluation below might
9630 // fail.
9631 // FIXME: Should we just re-use the previously evaluated value instead?
9632 *Lit = APValue();
9633 } else {
9634 assert(!Info.getLangOpts().CPlusPlus);
9635 Lit = &Info.CurrentCall->createTemporary(E, E->getInitializer()->getType(),
9636 ScopeKind::Block, Result);
9637 }
9638 // FIXME: Evaluating in place isn't always right. We should figure out how to
9639 // use appropriate evaluation context here, see
9640 // clang/test/AST/static-compound-literals-reeval.cpp for a failure.
9641 if (!EvaluateInPlace(*Lit, Info, Result, E->getInitializer())) {
9642 *Lit = APValue();
9643 return false;
9644 }
9645 return true;
9646}
9647
9648bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
9649 TypeInfoLValue TypeInfo;
9650
9651 if (!E->isPotentiallyEvaluated()) {
9652 if (E->isTypeOperand())
9653 TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
9654 else
9655 TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
9656 } else {
9657 if (!Info.Ctx.getLangOpts().CPlusPlus20) {
9658 Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
9659 << E->getExprOperand()->getType()
9660 << E->getExprOperand()->getSourceRange();
9661 }
9662
9663 if (!Visit(E->getExprOperand()))
9664 return false;
9665
9666 std::optional<DynamicType> DynType =
9668 if (!DynType)
9669 return false;
9670
9671 TypeInfo = TypeInfoLValue(
9672 Info.Ctx.getCanonicalTagType(DynType->Type).getTypePtr());
9673 }
9674
9675 return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
9676}
9677
9678bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
9679 return Success(E->getGuidDecl());
9680}
9681
9682bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
9683 // Handle static data members.
9684 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
9685 VisitIgnoredBaseExpression(E->getBase());
9686 return VisitVarDecl(E, VD);
9687 }
9688
9689 // Handle static member functions.
9690 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
9691 if (MD->isStatic()) {
9692 VisitIgnoredBaseExpression(E->getBase());
9693 return Success(MD);
9694 }
9695 }
9696
9697 // Handle non-static data members.
9698 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
9699}
9700
9701bool LValueExprEvaluator::VisitExtVectorElementExpr(
9702 const ExtVectorElementExpr *E) {
9703 bool Success = true;
9704
9705 APValue Val;
9706 if (!Evaluate(Val, Info, E->getBase())) {
9707 if (!Info.noteFailure())
9708 return false;
9709 Success = false;
9710 }
9711
9713 E->getEncodedElementAccess(Indices);
9714 // FIXME: support accessing more than one element
9715 if (Indices.size() > 1)
9716 return false;
9717
9718 if (Success) {
9719 Result.setFrom(Info.Ctx, Val);
9720 QualType BaseType = E->getBase()->getType();
9721 if (E->isArrow())
9722 BaseType = BaseType->getPointeeType();
9723 const auto *VT = BaseType->castAs<VectorType>();
9724 HandleLValueVectorElement(Info, E, Result, VT->getElementType(),
9725 VT->getNumElements(), Indices[0]);
9726 }
9727
9728 return Success;
9729}
9730
9731bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
9732 if (E->getBase()->getType()->isSveVLSBuiltinType())
9733 return Error(E);
9734
9735 APSInt Index;
9736 bool Success = true;
9737
9738 if (const auto *VT = E->getBase()->getType()->getAs<VectorType>()) {
9739 APValue Val;
9740 if (!Evaluate(Val, Info, E->getBase())) {
9741 if (!Info.noteFailure())
9742 return false;
9743 Success = false;
9744 }
9745
9746 if (!EvaluateInteger(E->getIdx(), Index, Info)) {
9747 if (!Info.noteFailure())
9748 return false;
9749 Success = false;
9750 }
9751
9752 if (Success) {
9753 Result.setFrom(Info.Ctx, Val);
9754 HandleLValueVectorElement(Info, E, Result, VT->getElementType(),
9755 VT->getNumElements(), Index.getExtValue());
9756 }
9757
9758 return Success;
9759 }
9760
9761 // C++17's rules require us to evaluate the LHS first, regardless of which
9762 // side is the base.
9763 for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) {
9764 if (SubExpr == E->getBase() ? !evaluatePointer(SubExpr, Result)
9765 : !EvaluateInteger(SubExpr, Index, Info)) {
9766 if (!Info.noteFailure())
9767 return false;
9768 Success = false;
9769 }
9770 }
9771
9772 return Success &&
9773 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
9774}
9775
9776bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
9777 bool Success = evaluatePointer(E->getSubExpr(), Result);
9778 // [C++26][expr.unary.op]
9779 // If the operand points to an object or function, the result
9780 // denotes that object or function; otherwise, the behavior is undefined.
9781 // Because &(*(type*)0) is a common pattern, we do not fail the evaluation
9782 // immediately.
9784 return Success;
9786 E->getType())) ||
9787 Info.noteUndefinedBehavior();
9788}
9789
9790bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
9791 if (!Visit(E->getSubExpr()))
9792 return false;
9793 // __real is a no-op on scalar lvalues.
9794 if (E->getSubExpr()->getType()->isAnyComplexType())
9795 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
9796 return true;
9797}
9798
9799bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
9800 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
9801 "lvalue __imag__ on scalar?");
9802 if (!Visit(E->getSubExpr()))
9803 return false;
9804 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
9805 return true;
9806}
9807
9808bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
9809 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9810 return Error(UO);
9811
9812 if (!this->Visit(UO->getSubExpr()))
9813 return false;
9814
9815 return handleIncDec(
9816 this->Info, UO, Result, UO->getSubExpr()->getType(),
9817 UO->isIncrementOp(), nullptr);
9818}
9819
9820bool LValueExprEvaluator::VisitCompoundAssignOperator(
9821 const CompoundAssignOperator *CAO) {
9822 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9823 return Error(CAO);
9824
9825 bool Success = true;
9826
9827 // C++17 onwards require that we evaluate the RHS first.
9828 APValue RHS;
9829 if (!Evaluate(RHS, this->Info, CAO->getRHS())) {
9830 if (!Info.noteFailure())
9831 return false;
9832 Success = false;
9833 }
9834
9835 // The overall lvalue result is the result of evaluating the LHS.
9836 if (!this->Visit(CAO->getLHS()) || !Success)
9837 return false;
9838
9840 this->Info, CAO,
9841 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
9842 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
9843}
9844
9845bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
9846 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9847 return Error(E);
9848
9849 bool Success = true;
9850
9851 // C++17 onwards require that we evaluate the RHS first.
9852 APValue NewVal;
9853 if (!Evaluate(NewVal, this->Info, E->getRHS())) {
9854 if (!Info.noteFailure())
9855 return false;
9856 Success = false;
9857 }
9858
9859 if (!this->Visit(E->getLHS()) || !Success)
9860 return false;
9861
9862 if (Info.getLangOpts().CPlusPlus20 &&
9864 return false;
9865
9866 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
9867 NewVal);
9868}
9869
9870//===----------------------------------------------------------------------===//
9871// Pointer Evaluation
9872//===----------------------------------------------------------------------===//
9873
9874/// Convenience function. LVal's base must be a call to an alloc_size
9875/// function.
9877 const LValue &LVal,
9878 llvm::APInt &Result) {
9879 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
9880 "Can't get the size of a non alloc_size function");
9881 const auto *Base = LVal.getLValueBase().get<const Expr *>();
9882 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
9883 std::optional<llvm::APInt> Size =
9884 CE->evaluateBytesReturnedByAllocSizeCall(Ctx);
9885 if (!Size)
9886 return false;
9887
9888 Result = std::move(*Size);
9889 return true;
9890}
9891
9892/// Attempts to evaluate the given LValueBase as the result of a call to
9893/// a function with the alloc_size attribute. If it was possible to do so, this
9894/// function will return true, make Result's Base point to said function call,
9895/// and mark Result's Base as invalid.
9897 LValue &Result) {
9898 if (Base.isNull())
9899 return false;
9900
9901 // Because we do no form of static analysis, we only support const variables.
9902 //
9903 // Additionally, we can't support parameters, nor can we support static
9904 // variables (in the latter case, use-before-assign isn't UB; in the former,
9905 // we have no clue what they'll be assigned to).
9906 const auto *VD =
9907 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
9908 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
9909 return false;
9910
9911 const Expr *Init = VD->getAnyInitializer();
9912 if (!Init || Init->getType().isNull())
9913 return false;
9914
9915 const Expr *E = Init->IgnoreParens();
9916 if (!tryUnwrapAllocSizeCall(E))
9917 return false;
9918
9919 // Store E instead of E unwrapped so that the type of the LValue's base is
9920 // what the user wanted.
9921 Result.setInvalid(E);
9922
9923 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
9924 Result.addUnsizedArray(Info, E, Pointee);
9925 return true;
9926}
9927
9928namespace {
9929class PointerExprEvaluator
9930 : public ExprEvaluatorBase<PointerExprEvaluator> {
9931 LValue &Result;
9932 bool InvalidBaseOK;
9933
9934 bool Success(const Expr *E) {
9935 Result.set(E);
9936 return true;
9937 }
9938
9939 bool evaluateLValue(const Expr *E, LValue &Result) {
9940 return EvaluateLValue(E, Result, Info, InvalidBaseOK);
9941 }
9942
9943 bool evaluatePointer(const Expr *E, LValue &Result) {
9944 return EvaluatePointer(E, Result, Info, InvalidBaseOK);
9945 }
9946
9947 bool visitNonBuiltinCallExpr(const CallExpr *E);
9948public:
9949
9950 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
9951 : ExprEvaluatorBaseTy(info), Result(Result),
9952 InvalidBaseOK(InvalidBaseOK) {}
9953
9954 bool Success(const APValue &V, const Expr *E) {
9955 Result.setFrom(Info.Ctx, V);
9956 return true;
9957 }
9958 bool ZeroInitialization(const Expr *E) {
9959 Result.setNull(Info.Ctx, E->getType());
9960 return true;
9961 }
9962
9963 bool VisitBinaryOperator(const BinaryOperator *E);
9964 bool VisitCastExpr(const CastExpr* E);
9965 bool VisitUnaryAddrOf(const UnaryOperator *E);
9966 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
9967 { return Success(E); }
9968 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
9970 return Success(E);
9971 if (Info.noteFailure())
9972 EvaluateIgnoredValue(Info, E->getSubExpr());
9973 return Error(E);
9974 }
9975 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
9976 { return Success(E); }
9977 bool VisitCallExpr(const CallExpr *E);
9978 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
9979 bool VisitBlockExpr(const BlockExpr *E) {
9980 if (!E->getBlockDecl()->hasCaptures())
9981 return Success(E);
9982 return Error(E);
9983 }
9984 bool VisitCXXThisExpr(const CXXThisExpr *E) {
9985 auto DiagnoseInvalidUseOfThis = [&] {
9986 if (Info.getLangOpts().CPlusPlus11)
9987 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
9988 else
9989 Info.FFDiag(E);
9990 };
9991
9992 // Can't look at 'this' when checking a potential constant expression.
9993 if (Info.checkingPotentialConstantExpression())
9994 return false;
9995
9996 bool IsExplicitLambda =
9997 isLambdaCallWithExplicitObjectParameter(Info.CurrentCall->Callee);
9998 if (!IsExplicitLambda) {
9999 if (!Info.CurrentCall->This) {
10000 DiagnoseInvalidUseOfThis();
10001 return false;
10002 }
10003
10004 Result = *Info.CurrentCall->This;
10005 }
10006
10007 if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
10008 // Ensure we actually have captured 'this'. If something was wrong with
10009 // 'this' capture, the error would have been previously reported.
10010 // Otherwise we can be inside of a default initialization of an object
10011 // declared by lambda's body, so no need to return false.
10012 if (!Info.CurrentCall->LambdaThisCaptureField) {
10013 if (IsExplicitLambda && !Info.CurrentCall->This) {
10014 DiagnoseInvalidUseOfThis();
10015 return false;
10016 }
10017
10018 return true;
10019 }
10020
10021 const auto *MD = cast<CXXMethodDecl>(Info.CurrentCall->Callee);
10022 return HandleLambdaCapture(
10023 Info, E, Result, MD, Info.CurrentCall->LambdaThisCaptureField,
10024 Info.CurrentCall->LambdaThisCaptureField->getType()->isPointerType());
10025 }
10026 return true;
10027 }
10028
10029 bool VisitCXXNewExpr(const CXXNewExpr *E);
10030
10031 bool VisitSourceLocExpr(const SourceLocExpr *E) {
10032 assert(!E->isIntType() && "SourceLocExpr isn't a pointer type?");
10033 APValue LValResult = E->EvaluateInContext(
10034 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
10035 Result.setFrom(Info.Ctx, LValResult);
10036 return true;
10037 }
10038
10039 bool VisitEmbedExpr(const EmbedExpr *E) {
10040 llvm::report_fatal_error("Not yet implemented for ExprConstant.cpp");
10041 return true;
10042 }
10043
10044 bool VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr *E) {
10045 std::string ResultStr = E->ComputeName(Info.Ctx);
10046
10047 QualType CharTy = Info.Ctx.CharTy.withConst();
10048 APInt Size(Info.Ctx.getTypeSize(Info.Ctx.getSizeType()),
10049 ResultStr.size() + 1);
10050 QualType ArrayTy = Info.Ctx.getConstantArrayType(
10051 CharTy, Size, nullptr, ArraySizeModifier::Normal, 0);
10052
10053 StringLiteral *SL =
10054 StringLiteral::Create(Info.Ctx, ResultStr, StringLiteralKind::Ordinary,
10055 /*Pascal*/ false, ArrayTy, E->getLocation());
10056
10057 evaluateLValue(SL, Result);
10058 Result.addArray(Info, E, cast<ConstantArrayType>(ArrayTy));
10059 return true;
10060 }
10061
10062 // FIXME: Missing: @protocol, @selector
10063};
10064} // end anonymous namespace
10065
10066static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
10067 bool InvalidBaseOK) {
10068 assert(!E->isValueDependent());
10069 assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
10070 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
10071}
10072
10073bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
10074 if (E->getOpcode() != BO_Add &&
10075 E->getOpcode() != BO_Sub)
10076 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10077
10078 const Expr *PExp = E->getLHS();
10079 const Expr *IExp = E->getRHS();
10080 if (IExp->getType()->isPointerType())
10081 std::swap(PExp, IExp);
10082
10083 bool EvalPtrOK = evaluatePointer(PExp, Result);
10084 if (!EvalPtrOK && !Info.noteFailure())
10085 return false;
10086
10087 llvm::APSInt Offset;
10088 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
10089 return false;
10090
10091 if (E->getOpcode() == BO_Sub)
10092 negateAsSigned(Offset);
10093
10094 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
10095 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
10096}
10097
10098bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
10099 return evaluateLValue(E->getSubExpr(), Result);
10100}
10101
10102// Is the provided decl 'std::source_location::current'?
10104 if (!FD)
10105 return false;
10106 const IdentifierInfo *FnII = FD->getIdentifier();
10107 if (!FnII || !FnII->isStr("current"))
10108 return false;
10109
10110 const auto *RD = dyn_cast<RecordDecl>(FD->getParent());
10111 if (!RD)
10112 return false;
10113
10114 const IdentifierInfo *ClassII = RD->getIdentifier();
10115 return RD->isInStdNamespace() && ClassII && ClassII->isStr("source_location");
10116}
10117
10118bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
10119 const Expr *SubExpr = E->getSubExpr();
10120
10121 switch (E->getCastKind()) {
10122 default:
10123 break;
10124 case CK_BitCast:
10125 case CK_CPointerToObjCPointerCast:
10126 case CK_BlockPointerToObjCPointerCast:
10127 case CK_AnyPointerToBlockPointerCast:
10128 case CK_AddressSpaceConversion:
10129 if (!Visit(SubExpr))
10130 return false;
10131 if (E->getType()->isFunctionPointerType() ||
10132 SubExpr->getType()->isFunctionPointerType()) {
10133 // Casting between two function pointer types, or between a function
10134 // pointer and an object pointer, is always a reinterpret_cast.
10135 CCEDiag(E, diag::note_constexpr_invalid_cast)
10136 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
10137 << Info.Ctx.getLangOpts().CPlusPlus;
10138 Result.Designator.setInvalid();
10139 } else if (!E->getType()->isVoidPointerType()) {
10140 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
10141 // permitted in constant expressions in C++11. Bitcasts from cv void* are
10142 // also static_casts, but we disallow them as a resolution to DR1312.
10143 //
10144 // In some circumstances, we permit casting from void* to cv1 T*, when the
10145 // actual pointee object is actually a cv2 T.
10146 bool HasValidResult = !Result.InvalidBase && !Result.Designator.Invalid &&
10147 !Result.IsNullPtr;
10148 bool VoidPtrCastMaybeOK =
10149 Result.IsNullPtr ||
10150 (HasValidResult &&
10151 Info.Ctx.hasSimilarType(Result.Designator.getType(Info.Ctx),
10152 E->getType()->getPointeeType()));
10153 // 1. We'll allow it in std::allocator::allocate, and anything which that
10154 // calls.
10155 // 2. HACK 2022-03-28: Work around an issue with libstdc++'s
10156 // <source_location> header. Fixed in GCC 12 and later (2022-04-??).
10157 // We'll allow it in the body of std::source_location::current. GCC's
10158 // implementation had a parameter of type `void*`, and casts from
10159 // that back to `const __impl*` in its body.
10160 if (VoidPtrCastMaybeOK &&
10161 (Info.getStdAllocatorCaller("allocate") ||
10162 IsDeclSourceLocationCurrent(Info.CurrentCall->Callee) ||
10163 Info.getLangOpts().CPlusPlus26)) {
10164 // Permitted.
10165 } else {
10166 if (SubExpr->getType()->isVoidPointerType() &&
10167 Info.getLangOpts().CPlusPlus) {
10168 if (HasValidResult)
10169 CCEDiag(E, diag::note_constexpr_invalid_void_star_cast)
10170 << SubExpr->getType() << Info.getLangOpts().CPlusPlus26
10171 << Result.Designator.getType(Info.Ctx).getCanonicalType()
10172 << E->getType()->getPointeeType();
10173 else
10174 CCEDiag(E, diag::note_constexpr_invalid_cast)
10175 << diag::ConstexprInvalidCastKind::CastFrom
10176 << SubExpr->getType();
10177 } else
10178 CCEDiag(E, diag::note_constexpr_invalid_cast)
10179 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
10180 << Info.Ctx.getLangOpts().CPlusPlus;
10181 Result.Designator.setInvalid();
10182 }
10183 }
10184 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
10185 ZeroInitialization(E);
10186 return true;
10187
10188 case CK_DerivedToBase:
10189 case CK_UncheckedDerivedToBase:
10190 if (!evaluatePointer(E->getSubExpr(), Result))
10191 return false;
10192 if (!Result.Base && Result.Offset.isZero())
10193 return true;
10194
10195 // Now figure out the necessary offset to add to the base LV to get from
10196 // the derived class to the base class.
10197 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
10198 castAs<PointerType>()->getPointeeType(),
10199 Result);
10200
10201 case CK_BaseToDerived:
10202 if (!Visit(E->getSubExpr()))
10203 return false;
10204 if (!Result.Base && Result.Offset.isZero())
10205 return true;
10206 return HandleBaseToDerivedCast(Info, E, Result);
10207
10208 case CK_Dynamic:
10209 if (!Visit(E->getSubExpr()))
10210 return false;
10212
10213 case CK_NullToPointer:
10214 VisitIgnoredValue(E->getSubExpr());
10215 return ZeroInitialization(E);
10216
10217 case CK_IntegralToPointer: {
10218 CCEDiag(E, diag::note_constexpr_invalid_cast)
10219 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
10220 << Info.Ctx.getLangOpts().CPlusPlus;
10221
10222 APValue Value;
10223 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
10224 break;
10225
10226 if (Value.isInt()) {
10227 unsigned Size = Info.Ctx.getTypeSize(E->getType());
10228 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
10229 if (N == Info.Ctx.getTargetNullPointerValue(E->getType())) {
10230 Result.setNull(Info.Ctx, E->getType());
10231 } else {
10232 Result.Base = (Expr *)nullptr;
10233 Result.InvalidBase = false;
10234 Result.Offset = CharUnits::fromQuantity(N);
10235 Result.Designator.setInvalid();
10236 Result.IsNullPtr = false;
10237 }
10238 return true;
10239 } else {
10240 // In rare instances, the value isn't an lvalue.
10241 // For example, when the value is the difference between the addresses of
10242 // two labels. We reject that as a constant expression because we can't
10243 // compute a valid offset to convert into a pointer.
10244 if (!Value.isLValue())
10245 return false;
10246
10247 // Cast is of an lvalue, no need to change value.
10248 Result.setFrom(Info.Ctx, Value);
10249 return true;
10250 }
10251 }
10252
10253 case CK_ArrayToPointerDecay: {
10254 if (SubExpr->isGLValue()) {
10255 if (!evaluateLValue(SubExpr, Result))
10256 return false;
10257 } else {
10258 APValue &Value = Info.CurrentCall->createTemporary(
10259 SubExpr, SubExpr->getType(), ScopeKind::FullExpression, Result);
10260 if (!EvaluateInPlace(Value, Info, Result, SubExpr))
10261 return false;
10262 }
10263 // The result is a pointer to the first element of the array.
10264 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
10265 if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
10266 Result.addArray(Info, E, CAT);
10267 else
10268 Result.addUnsizedArray(Info, E, AT->getElementType());
10269 return true;
10270 }
10271
10272 case CK_FunctionToPointerDecay:
10273 return evaluateLValue(SubExpr, Result);
10274
10275 case CK_LValueToRValue: {
10276 LValue LVal;
10277 if (!evaluateLValue(E->getSubExpr(), LVal))
10278 return false;
10279
10280 APValue RVal;
10281 // Note, we use the subexpression's type in order to retain cv-qualifiers.
10283 LVal, RVal))
10284 return InvalidBaseOK &&
10285 evaluateLValueAsAllocSize(Info, LVal.Base, Result);
10286 return Success(RVal, E);
10287 }
10288 }
10289
10290 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10291}
10292
10294 UnaryExprOrTypeTrait ExprKind) {
10295 // C++ [expr.alignof]p3:
10296 // When alignof is applied to a reference type, the result is the
10297 // alignment of the referenced type.
10298 T = T.getNonReferenceType();
10299
10300 if (T.getQualifiers().hasUnaligned())
10301 return CharUnits::One();
10302
10303 const bool AlignOfReturnsPreferred =
10304 Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
10305
10306 // __alignof is defined to return the preferred alignment.
10307 // Before 8, clang returned the preferred alignment for alignof and _Alignof
10308 // as well.
10309 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
10310 return Ctx.toCharUnitsFromBits(Ctx.getPreferredTypeAlign(T.getTypePtr()));
10311 // alignof and _Alignof are defined to return the ABI alignment.
10312 else if (ExprKind == UETT_AlignOf)
10313 return Ctx.getTypeAlignInChars(T.getTypePtr());
10314 else
10315 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
10316}
10317
10319 UnaryExprOrTypeTrait ExprKind) {
10320 E = E->IgnoreParens();
10321
10322 // The kinds of expressions that we have special-case logic here for
10323 // should be kept up to date with the special checks for those
10324 // expressions in Sema.
10325
10326 // alignof decl is always accepted, even if it doesn't make sense: we default
10327 // to 1 in those cases.
10328 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
10329 return Ctx.getDeclAlign(DRE->getDecl(),
10330 /*RefAsPointee*/ true);
10331
10332 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
10333 return Ctx.getDeclAlign(ME->getMemberDecl(),
10334 /*RefAsPointee*/ true);
10335
10336 return GetAlignOfType(Ctx, E->getType(), ExprKind);
10337}
10338
10339static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) {
10340 if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>())
10341 return Info.Ctx.getDeclAlign(VD);
10342 if (const auto *E = Value.Base.dyn_cast<const Expr *>())
10343 return GetAlignOfExpr(Info.Ctx, E, UETT_AlignOf);
10344 return GetAlignOfType(Info.Ctx, Value.Base.getTypeInfoType(), UETT_AlignOf);
10345}
10346
10347/// Evaluate the value of the alignment argument to __builtin_align_{up,down},
10348/// __builtin_is_aligned and __builtin_assume_aligned.
10349static bool getAlignmentArgument(const Expr *E, QualType ForType,
10350 EvalInfo &Info, APSInt &Alignment) {
10351 if (!EvaluateInteger(E, Alignment, Info))
10352 return false;
10353 if (Alignment < 0 || !Alignment.isPowerOf2()) {
10354 Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment;
10355 return false;
10356 }
10357 unsigned SrcWidth = Info.Ctx.getIntWidth(ForType);
10358 APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1));
10359 if (APSInt::compareValues(Alignment, MaxValue) > 0) {
10360 Info.FFDiag(E, diag::note_constexpr_alignment_too_big)
10361 << MaxValue << ForType << Alignment;
10362 return false;
10363 }
10364 // Ensure both alignment and source value have the same bit width so that we
10365 // don't assert when computing the resulting value.
10366 APSInt ExtAlignment =
10367 APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true);
10368 assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 &&
10369 "Alignment should not be changed by ext/trunc");
10370 Alignment = ExtAlignment;
10371 assert(Alignment.getBitWidth() == SrcWidth);
10372 return true;
10373}
10374
10375// To be clear: this happily visits unsupported builtins. Better name welcomed.
10376bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
10377 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
10378 return true;
10379
10380 if (!(InvalidBaseOK && E->getCalleeAllocSizeAttr()))
10381 return false;
10382
10383 Result.setInvalid(E);
10384 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
10385 Result.addUnsizedArray(Info, E, PointeeTy);
10386 return true;
10387}
10388
10389bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
10390 if (!IsConstantEvaluatedBuiltinCall(E))
10391 return visitNonBuiltinCallExpr(E);
10392 return VisitBuiltinCallExpr(E, E->getBuiltinCallee());
10393}
10394
10395// Determine if T is a character type for which we guarantee that
10396// sizeof(T) == 1.
10398 return T->isCharType() || T->isChar8Type();
10399}
10400
10401bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
10402 unsigned BuiltinOp) {
10403 if (IsOpaqueConstantCall(E))
10404 return Success(E);
10405
10406 switch (BuiltinOp) {
10407 case Builtin::BIaddressof:
10408 case Builtin::BI__addressof:
10409 case Builtin::BI__builtin_addressof:
10410 return evaluateLValue(E->getArg(0), Result);
10411 case Builtin::BI__builtin_assume_aligned: {
10412 // We need to be very careful here because: if the pointer does not have the
10413 // asserted alignment, then the behavior is undefined, and undefined
10414 // behavior is non-constant.
10415 if (!evaluatePointer(E->getArg(0), Result))
10416 return false;
10417
10418 LValue OffsetResult(Result);
10419 APSInt Alignment;
10420 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
10421 Alignment))
10422 return false;
10423 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
10424
10425 if (E->getNumArgs() > 2) {
10426 APSInt Offset;
10427 if (!EvaluateInteger(E->getArg(2), Offset, Info))
10428 return false;
10429
10430 int64_t AdditionalOffset = -Offset.getZExtValue();
10431 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
10432 }
10433
10434 // If there is a base object, then it must have the correct alignment.
10435 if (OffsetResult.Base) {
10436 CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult);
10437
10438 if (BaseAlignment < Align) {
10439 Result.Designator.setInvalid();
10440 CCEDiag(E->getArg(0), diag::note_constexpr_baa_insufficient_alignment)
10441 << 0 << BaseAlignment.getQuantity() << Align.getQuantity();
10442 return false;
10443 }
10444 }
10445
10446 // The offset must also have the correct alignment.
10447 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
10448 Result.Designator.setInvalid();
10449
10450 (OffsetResult.Base
10451 ? CCEDiag(E->getArg(0),
10452 diag::note_constexpr_baa_insufficient_alignment)
10453 << 1
10454 : CCEDiag(E->getArg(0),
10455 diag::note_constexpr_baa_value_insufficient_alignment))
10456 << OffsetResult.Offset.getQuantity() << Align.getQuantity();
10457 return false;
10458 }
10459
10460 return true;
10461 }
10462 case Builtin::BI__builtin_align_up:
10463 case Builtin::BI__builtin_align_down: {
10464 if (!evaluatePointer(E->getArg(0), Result))
10465 return false;
10466 APSInt Alignment;
10467 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
10468 Alignment))
10469 return false;
10470 CharUnits BaseAlignment = getBaseAlignment(Info, Result);
10471 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset);
10472 // For align_up/align_down, we can return the same value if the alignment
10473 // is known to be greater or equal to the requested value.
10474 if (PtrAlign.getQuantity() >= Alignment)
10475 return true;
10476
10477 // The alignment could be greater than the minimum at run-time, so we cannot
10478 // infer much about the resulting pointer value. One case is possible:
10479 // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we
10480 // can infer the correct index if the requested alignment is smaller than
10481 // the base alignment so we can perform the computation on the offset.
10482 if (BaseAlignment.getQuantity() >= Alignment) {
10483 assert(Alignment.getBitWidth() <= 64 &&
10484 "Cannot handle > 64-bit address-space");
10485 uint64_t Alignment64 = Alignment.getZExtValue();
10486 CharUnits NewOffset = CharUnits::fromQuantity(
10487 BuiltinOp == Builtin::BI__builtin_align_down
10488 ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64)
10489 : llvm::alignTo(Result.Offset.getQuantity(), Alignment64));
10490 Result.adjustOffset(NewOffset - Result.Offset);
10491 // TODO: diagnose out-of-bounds values/only allow for arrays?
10492 return true;
10493 }
10494 // Otherwise, we cannot constant-evaluate the result.
10495 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust)
10496 << Alignment;
10497 return false;
10498 }
10499 case Builtin::BI__builtin_operator_new:
10500 return HandleOperatorNewCall(Info, E, Result);
10501 case Builtin::BI__builtin_launder:
10502 return evaluatePointer(E->getArg(0), Result);
10503 case Builtin::BIstrchr:
10504 case Builtin::BIwcschr:
10505 case Builtin::BImemchr:
10506 case Builtin::BIwmemchr:
10507 if (Info.getLangOpts().CPlusPlus11)
10508 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
10509 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
10510 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
10511 else
10512 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
10513 [[fallthrough]];
10514 case Builtin::BI__builtin_strchr:
10515 case Builtin::BI__builtin_wcschr:
10516 case Builtin::BI__builtin_memchr:
10517 case Builtin::BI__builtin_char_memchr:
10518 case Builtin::BI__builtin_wmemchr: {
10519 if (!Visit(E->getArg(0)))
10520 return false;
10521 APSInt Desired;
10522 if (!EvaluateInteger(E->getArg(1), Desired, Info))
10523 return false;
10524 uint64_t MaxLength = uint64_t(-1);
10525 if (BuiltinOp != Builtin::BIstrchr &&
10526 BuiltinOp != Builtin::BIwcschr &&
10527 BuiltinOp != Builtin::BI__builtin_strchr &&
10528 BuiltinOp != Builtin::BI__builtin_wcschr) {
10529 APSInt N;
10530 if (!EvaluateInteger(E->getArg(2), N, Info))
10531 return false;
10532 MaxLength = N.getZExtValue();
10533 }
10534 // We cannot find the value if there are no candidates to match against.
10535 if (MaxLength == 0u)
10536 return ZeroInitialization(E);
10537 if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
10538 Result.Designator.Invalid)
10539 return false;
10540 QualType CharTy = Result.Designator.getType(Info.Ctx);
10541 bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
10542 BuiltinOp == Builtin::BI__builtin_memchr;
10543 assert(IsRawByte ||
10544 Info.Ctx.hasSameUnqualifiedType(
10545 CharTy, E->getArg(0)->getType()->getPointeeType()));
10546 // Pointers to const void may point to objects of incomplete type.
10547 if (IsRawByte && CharTy->isIncompleteType()) {
10548 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
10549 return false;
10550 }
10551 // Give up on byte-oriented matching against multibyte elements.
10552 // FIXME: We can compare the bytes in the correct order.
10553 if (IsRawByte && !isOneByteCharacterType(CharTy)) {
10554 Info.FFDiag(E, diag::note_constexpr_memchr_unsupported)
10555 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp) << CharTy;
10556 return false;
10557 }
10558 // Figure out what value we're actually looking for (after converting to
10559 // the corresponding unsigned type if necessary).
10560 uint64_t DesiredVal;
10561 bool StopAtNull = false;
10562 switch (BuiltinOp) {
10563 case Builtin::BIstrchr:
10564 case Builtin::BI__builtin_strchr:
10565 // strchr compares directly to the passed integer, and therefore
10566 // always fails if given an int that is not a char.
10567 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
10568 E->getArg(1)->getType(),
10569 Desired),
10570 Desired))
10571 return ZeroInitialization(E);
10572 StopAtNull = true;
10573 [[fallthrough]];
10574 case Builtin::BImemchr:
10575 case Builtin::BI__builtin_memchr:
10576 case Builtin::BI__builtin_char_memchr:
10577 // memchr compares by converting both sides to unsigned char. That's also
10578 // correct for strchr if we get this far (to cope with plain char being
10579 // unsigned in the strchr case).
10580 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
10581 break;
10582
10583 case Builtin::BIwcschr:
10584 case Builtin::BI__builtin_wcschr:
10585 StopAtNull = true;
10586 [[fallthrough]];
10587 case Builtin::BIwmemchr:
10588 case Builtin::BI__builtin_wmemchr:
10589 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
10590 DesiredVal = Desired.getZExtValue();
10591 break;
10592 }
10593
10594 for (; MaxLength; --MaxLength) {
10595 APValue Char;
10596 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
10597 !Char.isInt())
10598 return false;
10599 if (Char.getInt().getZExtValue() == DesiredVal)
10600 return true;
10601 if (StopAtNull && !Char.getInt())
10602 break;
10603 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
10604 return false;
10605 }
10606 // Not found: return nullptr.
10607 return ZeroInitialization(E);
10608 }
10609
10610 case Builtin::BImemcpy:
10611 case Builtin::BImemmove:
10612 case Builtin::BIwmemcpy:
10613 case Builtin::BIwmemmove:
10614 if (Info.getLangOpts().CPlusPlus11)
10615 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
10616 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
10617 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
10618 else
10619 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
10620 [[fallthrough]];
10621 case Builtin::BI__builtin_memcpy:
10622 case Builtin::BI__builtin_memmove:
10623 case Builtin::BI__builtin_wmemcpy:
10624 case Builtin::BI__builtin_wmemmove: {
10625 bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
10626 BuiltinOp == Builtin::BIwmemmove ||
10627 BuiltinOp == Builtin::BI__builtin_wmemcpy ||
10628 BuiltinOp == Builtin::BI__builtin_wmemmove;
10629 bool Move = BuiltinOp == Builtin::BImemmove ||
10630 BuiltinOp == Builtin::BIwmemmove ||
10631 BuiltinOp == Builtin::BI__builtin_memmove ||
10632 BuiltinOp == Builtin::BI__builtin_wmemmove;
10633
10634 // The result of mem* is the first argument.
10635 if (!Visit(E->getArg(0)))
10636 return false;
10637 LValue Dest = Result;
10638
10639 LValue Src;
10640 if (!EvaluatePointer(E->getArg(1), Src, Info))
10641 return false;
10642
10643 APSInt N;
10644 if (!EvaluateInteger(E->getArg(2), N, Info))
10645 return false;
10646 assert(!N.isSigned() && "memcpy and friends take an unsigned size");
10647
10648 // If the size is zero, we treat this as always being a valid no-op.
10649 // (Even if one of the src and dest pointers is null.)
10650 if (!N)
10651 return true;
10652
10653 // Otherwise, if either of the operands is null, we can't proceed. Don't
10654 // try to determine the type of the copied objects, because there aren't
10655 // any.
10656 if (!Src.Base || !Dest.Base) {
10657 APValue Val;
10658 (!Src.Base ? Src : Dest).moveInto(Val);
10659 Info.FFDiag(E, diag::note_constexpr_memcpy_null)
10660 << Move << WChar << !!Src.Base
10661 << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
10662 return false;
10663 }
10664 if (Src.Designator.Invalid || Dest.Designator.Invalid)
10665 return false;
10666
10667 // We require that Src and Dest are both pointers to arrays of
10668 // trivially-copyable type. (For the wide version, the designator will be
10669 // invalid if the designated object is not a wchar_t.)
10670 QualType T = Dest.Designator.getType(Info.Ctx);
10671 QualType SrcT = Src.Designator.getType(Info.Ctx);
10672 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
10673 // FIXME: Consider using our bit_cast implementation to support this.
10674 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
10675 return false;
10676 }
10677 if (T->isIncompleteType()) {
10678 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
10679 return false;
10680 }
10681 if (!T.isTriviallyCopyableType(Info.Ctx)) {
10682 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
10683 return false;
10684 }
10685
10686 // Figure out how many T's we're copying.
10687 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
10688 if (TSize == 0)
10689 return false;
10690 if (!WChar) {
10691 uint64_t Remainder;
10692 llvm::APInt OrigN = N;
10693 llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
10694 if (Remainder) {
10695 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
10696 << Move << WChar << 0 << T << toString(OrigN, 10, /*Signed*/false)
10697 << (unsigned)TSize;
10698 return false;
10699 }
10700 }
10701
10702 // Check that the copying will remain within the arrays, just so that we
10703 // can give a more meaningful diagnostic. This implicitly also checks that
10704 // N fits into 64 bits.
10705 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
10706 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
10707 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
10708 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
10709 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
10710 << toString(N, 10, /*Signed*/false);
10711 return false;
10712 }
10713 uint64_t NElems = N.getZExtValue();
10714 uint64_t NBytes = NElems * TSize;
10715
10716 // Check for overlap.
10717 int Direction = 1;
10718 if (HasSameBase(Src, Dest)) {
10719 uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
10720 uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
10721 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
10722 // Dest is inside the source region.
10723 if (!Move) {
10724 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
10725 return false;
10726 }
10727 // For memmove and friends, copy backwards.
10728 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
10729 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
10730 return false;
10731 Direction = -1;
10732 } else if (!Move && SrcOffset >= DestOffset &&
10733 SrcOffset - DestOffset < NBytes) {
10734 // Src is inside the destination region for memcpy: invalid.
10735 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
10736 return false;
10737 }
10738 }
10739
10740 while (true) {
10741 APValue Val;
10742 // FIXME: Set WantObjectRepresentation to true if we're copying a
10743 // char-like type?
10744 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
10745 !handleAssignment(Info, E, Dest, T, Val))
10746 return false;
10747 // Do not iterate past the last element; if we're copying backwards, that
10748 // might take us off the start of the array.
10749 if (--NElems == 0)
10750 return true;
10751 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
10752 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
10753 return false;
10754 }
10755 }
10756
10757 default:
10758 return false;
10759 }
10760}
10761
10762static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
10763 APValue &Result, const InitListExpr *ILE,
10764 QualType AllocType);
10765static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
10766 APValue &Result,
10767 const CXXConstructExpr *CCE,
10768 QualType AllocType);
10769
10770bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) {
10771 if (!Info.getLangOpts().CPlusPlus20)
10772 Info.CCEDiag(E, diag::note_constexpr_new);
10773
10774 // We cannot speculatively evaluate a delete expression.
10775 if (Info.SpeculativeEvaluationDepth)
10776 return false;
10777
10778 FunctionDecl *OperatorNew = E->getOperatorNew();
10779 QualType AllocType = E->getAllocatedType();
10780 QualType TargetType = AllocType;
10781
10782 bool IsNothrow = false;
10783 bool IsPlacement = false;
10784
10785 if (E->getNumPlacementArgs() == 1 &&
10786 E->getPlacementArg(0)->getType()->isNothrowT()) {
10787 // The only new-placement list we support is of the form (std::nothrow).
10788 //
10789 // FIXME: There is no restriction on this, but it's not clear that any
10790 // other form makes any sense. We get here for cases such as:
10791 //
10792 // new (std::align_val_t{N}) X(int)
10793 //
10794 // (which should presumably be valid only if N is a multiple of
10795 // alignof(int), and in any case can't be deallocated unless N is
10796 // alignof(X) and X has new-extended alignment).
10797 LValue Nothrow;
10798 if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info))
10799 return false;
10800 IsNothrow = true;
10801 } else if (OperatorNew->isReservedGlobalPlacementOperator()) {
10802 if (Info.CurrentCall->isStdFunction() || Info.getLangOpts().CPlusPlus26 ||
10803 (Info.CurrentCall->CanEvalMSConstexpr &&
10804 OperatorNew->hasAttr<MSConstexprAttr>())) {
10805 if (!EvaluatePointer(E->getPlacementArg(0), Result, Info))
10806 return false;
10807 if (Result.Designator.Invalid)
10808 return false;
10809 TargetType = E->getPlacementArg(0)->getType();
10810 IsPlacement = true;
10811 } else {
10812 Info.FFDiag(E, diag::note_constexpr_new_placement)
10813 << /*C++26 feature*/ 1 << E->getSourceRange();
10814 return false;
10815 }
10816 } else if (E->getNumPlacementArgs()) {
10817 Info.FFDiag(E, diag::note_constexpr_new_placement)
10818 << /*Unsupported*/ 0 << E->getSourceRange();
10819 return false;
10820 } else if (!OperatorNew
10821 ->isUsableAsGlobalAllocationFunctionInConstantEvaluation()) {
10822 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
10823 << isa<CXXMethodDecl>(OperatorNew) << OperatorNew;
10824 return false;
10825 }
10826
10827 const Expr *Init = E->getInitializer();
10828 const InitListExpr *ResizedArrayILE = nullptr;
10829 const CXXConstructExpr *ResizedArrayCCE = nullptr;
10830 bool ValueInit = false;
10831
10832 if (std::optional<const Expr *> ArraySize = E->getArraySize()) {
10833 const Expr *Stripped = *ArraySize;
10834 for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
10835 Stripped = ICE->getSubExpr())
10836 if (ICE->getCastKind() != CK_NoOp &&
10837 ICE->getCastKind() != CK_IntegralCast)
10838 break;
10839
10840 llvm::APSInt ArrayBound;
10841 if (!EvaluateInteger(Stripped, ArrayBound, Info))
10842 return false;
10843
10844 // C++ [expr.new]p9:
10845 // The expression is erroneous if:
10846 // -- [...] its value before converting to size_t [or] applying the
10847 // second standard conversion sequence is less than zero
10848 if (ArrayBound.isSigned() && ArrayBound.isNegative()) {
10849 if (IsNothrow)
10850 return ZeroInitialization(E);
10851
10852 Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative)
10853 << ArrayBound << (*ArraySize)->getSourceRange();
10854 return false;
10855 }
10856
10857 // -- its value is such that the size of the allocated object would
10858 // exceed the implementation-defined limit
10859 if (!Info.CheckArraySize(ArraySize.value()->getExprLoc(),
10861 Info.Ctx, AllocType, ArrayBound),
10862 ArrayBound.getZExtValue(), /*Diag=*/!IsNothrow)) {
10863 if (IsNothrow)
10864 return ZeroInitialization(E);
10865 return false;
10866 }
10867
10868 // -- the new-initializer is a braced-init-list and the number of
10869 // array elements for which initializers are provided [...]
10870 // exceeds the number of elements to initialize
10871 if (!Init) {
10872 // No initialization is performed.
10873 } else if (isa<CXXScalarValueInitExpr>(Init) ||
10875 ValueInit = true;
10876 } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) {
10877 ResizedArrayCCE = CCE;
10878 } else {
10879 auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType());
10880 assert(CAT && "unexpected type for array initializer");
10881
10882 unsigned Bits =
10883 std::max(CAT->getSizeBitWidth(), ArrayBound.getBitWidth());
10884 llvm::APInt InitBound = CAT->getSize().zext(Bits);
10885 llvm::APInt AllocBound = ArrayBound.zext(Bits);
10886 if (InitBound.ugt(AllocBound)) {
10887 if (IsNothrow)
10888 return ZeroInitialization(E);
10889
10890 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small)
10891 << toString(AllocBound, 10, /*Signed=*/false)
10892 << toString(InitBound, 10, /*Signed=*/false)
10893 << (*ArraySize)->getSourceRange();
10894 return false;
10895 }
10896
10897 // If the sizes differ, we must have an initializer list, and we need
10898 // special handling for this case when we initialize.
10899 if (InitBound != AllocBound)
10900 ResizedArrayILE = cast<InitListExpr>(Init);
10901 }
10902
10903 AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr,
10904 ArraySizeModifier::Normal, 0);
10905 } else {
10906 assert(!AllocType->isArrayType() &&
10907 "array allocation with non-array new");
10908 }
10909
10910 APValue *Val;
10911 if (IsPlacement) {
10913 struct FindObjectHandler {
10914 EvalInfo &Info;
10915 const Expr *E;
10916 QualType AllocType;
10917 const AccessKinds AccessKind;
10918 APValue *Value;
10919
10920 typedef bool result_type;
10921 bool failed() { return false; }
10922 bool checkConst(QualType QT) {
10923 if (QT.isConstQualified()) {
10924 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
10925 return false;
10926 }
10927 return true;
10928 }
10929 bool found(APValue &Subobj, QualType SubobjType) {
10930 if (!checkConst(SubobjType))
10931 return false;
10932 // FIXME: Reject the cases where [basic.life]p8 would not permit the
10933 // old name of the object to be used to name the new object.
10934 unsigned SubobjectSize = 1;
10935 unsigned AllocSize = 1;
10936 if (auto *CAT = dyn_cast<ConstantArrayType>(AllocType))
10937 AllocSize = CAT->getZExtSize();
10938 if (auto *CAT = dyn_cast<ConstantArrayType>(SubobjType))
10939 SubobjectSize = CAT->getZExtSize();
10940 if (SubobjectSize < AllocSize ||
10941 !Info.Ctx.hasSimilarType(Info.Ctx.getBaseElementType(SubobjType),
10942 Info.Ctx.getBaseElementType(AllocType))) {
10943 Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type)
10944 << SubobjType << AllocType;
10945 return false;
10946 }
10947 Value = &Subobj;
10948 return true;
10949 }
10950 bool found(APSInt &Value, QualType SubobjType) {
10951 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
10952 return false;
10953 }
10954 bool found(APFloat &Value, QualType SubobjType) {
10955 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
10956 return false;
10957 }
10958 } Handler = {Info, E, AllocType, AK, nullptr};
10959
10960 CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType);
10961 if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler))
10962 return false;
10963
10964 Val = Handler.Value;
10965
10966 // [basic.life]p1:
10967 // The lifetime of an object o of type T ends when [...] the storage
10968 // which the object occupies is [...] reused by an object that is not
10969 // nested within o (6.6.2).
10970 *Val = APValue();
10971 } else {
10972 // Perform the allocation and obtain a pointer to the resulting object.
10973 Val = Info.createHeapAlloc(E, AllocType, Result);
10974 if (!Val)
10975 return false;
10976 }
10977
10978 if (ValueInit) {
10979 ImplicitValueInitExpr VIE(AllocType);
10980 if (!EvaluateInPlace(*Val, Info, Result, &VIE))
10981 return false;
10982 } else if (ResizedArrayILE) {
10983 if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE,
10984 AllocType))
10985 return false;
10986 } else if (ResizedArrayCCE) {
10987 if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE,
10988 AllocType))
10989 return false;
10990 } else if (Init) {
10991 if (!EvaluateInPlace(*Val, Info, Result, Init))
10992 return false;
10993 } else if (!handleDefaultInitValue(AllocType, *Val)) {
10994 return false;
10995 }
10996
10997 // Array new returns a pointer to the first element, not a pointer to the
10998 // array.
10999 if (auto *AT = AllocType->getAsArrayTypeUnsafe())
11000 Result.addArray(Info, E, cast<ConstantArrayType>(AT));
11001
11002 return true;
11003}
11004//===----------------------------------------------------------------------===//
11005// Member Pointer Evaluation
11006//===----------------------------------------------------------------------===//
11007
11008namespace {
11009class MemberPointerExprEvaluator
11010 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
11011 MemberPtr &Result;
11012
11013 bool Success(const ValueDecl *D) {
11014 Result = MemberPtr(D);
11015 return true;
11016 }
11017public:
11018
11019 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
11020 : ExprEvaluatorBaseTy(Info), Result(Result) {}
11021
11022 bool Success(const APValue &V, const Expr *E) {
11023 Result.setFrom(V);
11024 return true;
11025 }
11026 bool ZeroInitialization(const Expr *E) {
11027 return Success((const ValueDecl*)nullptr);
11028 }
11029
11030 bool VisitCastExpr(const CastExpr *E);
11031 bool VisitUnaryAddrOf(const UnaryOperator *E);
11032};
11033} // end anonymous namespace
11034
11035static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
11036 EvalInfo &Info) {
11037 assert(!E->isValueDependent());
11038 assert(E->isPRValue() && E->getType()->isMemberPointerType());
11039 return MemberPointerExprEvaluator(Info, Result).Visit(E);
11040}
11041
11042bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
11043 switch (E->getCastKind()) {
11044 default:
11045 return ExprEvaluatorBaseTy::VisitCastExpr(E);
11046
11047 case CK_NullToMemberPointer:
11048 VisitIgnoredValue(E->getSubExpr());
11049 return ZeroInitialization(E);
11050
11051 case CK_BaseToDerivedMemberPointer: {
11052 if (!Visit(E->getSubExpr()))
11053 return false;
11054 if (E->path_empty())
11055 return true;
11056 // Base-to-derived member pointer casts store the path in derived-to-base
11057 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
11058 // the wrong end of the derived->base arc, so stagger the path by one class.
11059 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
11060 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
11061 PathI != PathE; ++PathI) {
11062 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
11063 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
11064 if (!Result.castToDerived(Derived))
11065 return Error(E);
11066 }
11067 if (!Result.castToDerived(E->getType()
11068 ->castAs<MemberPointerType>()
11069 ->getMostRecentCXXRecordDecl()))
11070 return Error(E);
11071 return true;
11072 }
11073
11074 case CK_DerivedToBaseMemberPointer:
11075 if (!Visit(E->getSubExpr()))
11076 return false;
11077 for (CastExpr::path_const_iterator PathI = E->path_begin(),
11078 PathE = E->path_end(); PathI != PathE; ++PathI) {
11079 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
11080 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
11081 if (!Result.castToBase(Base))
11082 return Error(E);
11083 }
11084 return true;
11085 }
11086}
11087
11088bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
11089 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
11090 // member can be formed.
11091 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
11092}
11093
11094//===----------------------------------------------------------------------===//
11095// Record Evaluation
11096//===----------------------------------------------------------------------===//
11097
11098namespace {
11099 class RecordExprEvaluator
11100 : public ExprEvaluatorBase<RecordExprEvaluator> {
11101 const LValue &This;
11102 APValue &Result;
11103 public:
11104
11105 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
11106 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
11107
11108 bool Success(const APValue &V, const Expr *E) {
11109 Result = V;
11110 return true;
11111 }
11112 bool ZeroInitialization(const Expr *E) {
11113 return ZeroInitialization(E, E->getType());
11114 }
11115 bool ZeroInitialization(const Expr *E, QualType T);
11116
11117 bool VisitCallExpr(const CallExpr *E) {
11118 return handleCallExpr(E, Result, &This);
11119 }
11120 bool VisitCastExpr(const CastExpr *E);
11121 bool VisitInitListExpr(const InitListExpr *E);
11122 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
11123 return VisitCXXConstructExpr(E, E->getType());
11124 }
11125 bool VisitLambdaExpr(const LambdaExpr *E);
11126 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
11127 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
11128 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
11129 bool VisitBinCmp(const BinaryOperator *E);
11130 bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E);
11131 bool VisitCXXParenListOrInitListExpr(const Expr *ExprToVisit,
11132 ArrayRef<Expr *> Args);
11133 };
11134}
11135
11136/// Perform zero-initialization on an object of non-union class type.
11137/// C++11 [dcl.init]p5:
11138/// To zero-initialize an object or reference of type T means:
11139/// [...]
11140/// -- if T is a (possibly cv-qualified) non-union class type,
11141/// each non-static data member and each base-class subobject is
11142/// zero-initialized
11143static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
11144 const RecordDecl *RD,
11145 const LValue &This, APValue &Result) {
11146 assert(!RD->isUnion() && "Expected non-union class type");
11147 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
11148 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
11149 std::distance(RD->field_begin(), RD->field_end()));
11150
11151 if (RD->isInvalidDecl()) return false;
11152 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
11153
11154 if (CD) {
11155 unsigned Index = 0;
11157 End = CD->bases_end(); I != End; ++I, ++Index) {
11158 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
11159 LValue Subobject = This;
11160 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
11161 return false;
11162 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
11163 Result.getStructBase(Index)))
11164 return false;
11165 }
11166 }
11167
11168 for (const auto *I : RD->fields()) {
11169 // -- if T is a reference type, no initialization is performed.
11170 if (I->isUnnamedBitField() || I->getType()->isReferenceType())
11171 continue;
11172
11173 LValue Subobject = This;
11174 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
11175 return false;
11176
11177 ImplicitValueInitExpr VIE(I->getType());
11178 if (!EvaluateInPlace(
11179 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
11180 return false;
11181 }
11182
11183 return true;
11184}
11185
11186bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
11187 const auto *RD = T->castAsRecordDecl();
11188 if (RD->isInvalidDecl()) return false;
11189 if (RD->isUnion()) {
11190 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
11191 // object's first non-static named data member is zero-initialized
11193 while (I != RD->field_end() && (*I)->isUnnamedBitField())
11194 ++I;
11195 if (I == RD->field_end()) {
11196 Result = APValue((const FieldDecl*)nullptr);
11197 return true;
11198 }
11199
11200 LValue Subobject = This;
11201 if (!HandleLValueMember(Info, E, Subobject, *I))
11202 return false;
11203 Result = APValue(*I);
11204 ImplicitValueInitExpr VIE(I->getType());
11205 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
11206 }
11207
11208 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
11209 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
11210 return false;
11211 }
11212
11213 return HandleClassZeroInitialization(Info, E, RD, This, Result);
11214}
11215
11216bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
11217 switch (E->getCastKind()) {
11218 default:
11219 return ExprEvaluatorBaseTy::VisitCastExpr(E);
11220
11221 case CK_ConstructorConversion:
11222 return Visit(E->getSubExpr());
11223
11224 case CK_DerivedToBase:
11225 case CK_UncheckedDerivedToBase: {
11226 APValue DerivedObject;
11227 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
11228 return false;
11229 if (!DerivedObject.isStruct())
11230 return Error(E->getSubExpr());
11231
11232 // Derived-to-base rvalue conversion: just slice off the derived part.
11233 APValue *Value = &DerivedObject;
11234 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
11235 for (CastExpr::path_const_iterator PathI = E->path_begin(),
11236 PathE = E->path_end(); PathI != PathE; ++PathI) {
11237 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
11238 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
11239 Value = &Value->getStructBase(getBaseIndex(RD, Base));
11240 RD = Base;
11241 }
11242 Result = *Value;
11243 return true;
11244 }
11245 case CK_HLSLAggregateSplatCast: {
11246 APValue Val;
11247 QualType ValTy;
11248
11249 if (!hlslAggSplatHelper(Info, E->getSubExpr(), Val, ValTy))
11250 return false;
11251
11252 unsigned NEls = elementwiseSize(Info, E->getType());
11253 // splat our Val
11254 SmallVector<APValue> SplatEls(NEls, Val);
11255 SmallVector<QualType> SplatType(NEls, ValTy);
11256
11257 // cast the elements and construct our struct result
11258 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
11259 if (!constructAggregate(Info, FPO, E, Result, E->getType(), SplatEls,
11260 SplatType))
11261 return false;
11262
11263 return true;
11264 }
11265 case CK_HLSLElementwiseCast: {
11266 SmallVector<APValue> SrcEls;
11267 SmallVector<QualType> SrcTypes;
11268
11269 if (!hlslElementwiseCastHelper(Info, E->getSubExpr(), E->getType(), SrcEls,
11270 SrcTypes))
11271 return false;
11272
11273 // cast the elements and construct our struct result
11274 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
11275 if (!constructAggregate(Info, FPO, E, Result, E->getType(), SrcEls,
11276 SrcTypes))
11277 return false;
11278
11279 return true;
11280 }
11281 }
11282}
11283
11284bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
11285 if (E->isTransparent())
11286 return Visit(E->getInit(0));
11287 return VisitCXXParenListOrInitListExpr(E, E->inits());
11288}
11289
11290bool RecordExprEvaluator::VisitCXXParenListOrInitListExpr(
11291 const Expr *ExprToVisit, ArrayRef<Expr *> Args) {
11292 const auto *RD = ExprToVisit->getType()->castAsRecordDecl();
11293 if (RD->isInvalidDecl()) return false;
11294 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
11295 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
11296
11297 EvalInfo::EvaluatingConstructorRAII EvalObj(
11298 Info,
11299 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
11300 CXXRD && CXXRD->getNumBases());
11301
11302 if (RD->isUnion()) {
11303 const FieldDecl *Field;
11304 if (auto *ILE = dyn_cast<InitListExpr>(ExprToVisit)) {
11305 Field = ILE->getInitializedFieldInUnion();
11306 } else if (auto *PLIE = dyn_cast<CXXParenListInitExpr>(ExprToVisit)) {
11307 Field = PLIE->getInitializedFieldInUnion();
11308 } else {
11309 llvm_unreachable(
11310 "Expression is neither an init list nor a C++ paren list");
11311 }
11312
11313 Result = APValue(Field);
11314 if (!Field)
11315 return true;
11316
11317 // If the initializer list for a union does not contain any elements, the
11318 // first element of the union is value-initialized.
11319 // FIXME: The element should be initialized from an initializer list.
11320 // Is this difference ever observable for initializer lists which
11321 // we don't build?
11322 ImplicitValueInitExpr VIE(Field->getType());
11323 const Expr *InitExpr = Args.empty() ? &VIE : Args[0];
11324
11325 LValue Subobject = This;
11326 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
11327 return false;
11328
11329 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
11330 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
11331 isa<CXXDefaultInitExpr>(InitExpr));
11332
11333 if (EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr)) {
11334 if (Field->isBitField())
11335 return truncateBitfieldValue(Info, InitExpr, Result.getUnionValue(),
11336 Field);
11337 return true;
11338 }
11339
11340 return false;
11341 }
11342
11343 if (!Result.hasValue())
11344 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
11345 std::distance(RD->field_begin(), RD->field_end()));
11346 unsigned ElementNo = 0;
11347 bool Success = true;
11348
11349 // Initialize base classes.
11350 if (CXXRD && CXXRD->getNumBases()) {
11351 for (const auto &Base : CXXRD->bases()) {
11352 assert(ElementNo < Args.size() && "missing init for base class");
11353 const Expr *Init = Args[ElementNo];
11354
11355 LValue Subobject = This;
11356 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
11357 return false;
11358
11359 APValue &FieldVal = Result.getStructBase(ElementNo);
11360 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
11361 if (!Info.noteFailure())
11362 return false;
11363 Success = false;
11364 }
11365 ++ElementNo;
11366 }
11367
11368 EvalObj.finishedConstructingBases();
11369 }
11370
11371 // Initialize members.
11372 for (const auto *Field : RD->fields()) {
11373 // Anonymous bit-fields are not considered members of the class for
11374 // purposes of aggregate initialization.
11375 if (Field->isUnnamedBitField())
11376 continue;
11377
11378 LValue Subobject = This;
11379
11380 bool HaveInit = ElementNo < Args.size();
11381
11382 // FIXME: Diagnostics here should point to the end of the initializer
11383 // list, not the start.
11384 if (!HandleLValueMember(Info, HaveInit ? Args[ElementNo] : ExprToVisit,
11385 Subobject, Field, &Layout))
11386 return false;
11387
11388 // Perform an implicit value-initialization for members beyond the end of
11389 // the initializer list.
11390 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
11391 const Expr *Init = HaveInit ? Args[ElementNo++] : &VIE;
11392
11393 if (Field->getType()->isIncompleteArrayType()) {
11394 if (auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType())) {
11395 if (!CAT->isZeroSize()) {
11396 // Bail out for now. This might sort of "work", but the rest of the
11397 // code isn't really prepared to handle it.
11398 Info.FFDiag(Init, diag::note_constexpr_unsupported_flexible_array);
11399 return false;
11400 }
11401 }
11402 }
11403
11404 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
11405 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
11407
11408 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
11409 if (Field->getType()->isReferenceType()) {
11410 LValue Result;
11412 FieldVal)) {
11413 if (!Info.noteFailure())
11414 return false;
11415 Success = false;
11416 }
11417 } else if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
11418 (Field->isBitField() &&
11419 !truncateBitfieldValue(Info, Init, FieldVal, Field))) {
11420 if (!Info.noteFailure())
11421 return false;
11422 Success = false;
11423 }
11424 }
11425
11426 EvalObj.finishedConstructingFields();
11427
11428 return Success;
11429}
11430
11431bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
11432 QualType T) {
11433 // Note that E's type is not necessarily the type of our class here; we might
11434 // be initializing an array element instead.
11435 const CXXConstructorDecl *FD = E->getConstructor();
11436 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
11437
11438 bool ZeroInit = E->requiresZeroInitialization();
11439 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
11440 if (ZeroInit)
11441 return ZeroInitialization(E, T);
11442
11444 }
11445
11446 const FunctionDecl *Definition = nullptr;
11447 auto Body = FD->getBody(Definition);
11448
11449 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
11450 return false;
11451
11452 // Avoid materializing a temporary for an elidable copy/move constructor.
11453 if (E->isElidable() && !ZeroInit) {
11454 // FIXME: This only handles the simplest case, where the source object
11455 // is passed directly as the first argument to the constructor.
11456 // This should also handle stepping though implicit casts and
11457 // and conversion sequences which involve two steps, with a
11458 // conversion operator followed by a converting constructor.
11459 const Expr *SrcObj = E->getArg(0);
11460 assert(SrcObj->isTemporaryObject(Info.Ctx, FD->getParent()));
11461 assert(Info.Ctx.hasSameUnqualifiedType(E->getType(), SrcObj->getType()));
11462 if (const MaterializeTemporaryExpr *ME =
11463 dyn_cast<MaterializeTemporaryExpr>(SrcObj))
11464 return Visit(ME->getSubExpr());
11465 }
11466
11467 if (ZeroInit && !ZeroInitialization(E, T))
11468 return false;
11469
11470 auto Args = ArrayRef(E->getArgs(), E->getNumArgs());
11471 return HandleConstructorCall(E, This, Args,
11473 Result);
11474}
11475
11476bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
11477 const CXXInheritedCtorInitExpr *E) {
11478 if (!Info.CurrentCall) {
11479 assert(Info.checkingPotentialConstantExpression());
11480 return false;
11481 }
11482
11483 const CXXConstructorDecl *FD = E->getConstructor();
11484 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
11485 return false;
11486
11487 const FunctionDecl *Definition = nullptr;
11488 auto Body = FD->getBody(Definition);
11489
11490 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
11491 return false;
11492
11493 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
11495 Result);
11496}
11497
11498bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
11499 const CXXStdInitializerListExpr *E) {
11500 const ConstantArrayType *ArrayType =
11501 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
11502
11503 LValue Array;
11504 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
11505 return false;
11506
11507 assert(ArrayType && "unexpected type for array initializer");
11508
11509 // Get a pointer to the first element of the array.
11510 Array.addArray(Info, E, ArrayType);
11511
11512 // FIXME: What if the initializer_list type has base classes, etc?
11513 Result = APValue(APValue::UninitStruct(), 0, 2);
11514 Array.moveInto(Result.getStructField(0));
11515
11516 auto *Record = E->getType()->castAsRecordDecl();
11517 RecordDecl::field_iterator Field = Record->field_begin();
11518 assert(Field != Record->field_end() &&
11519 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
11520 ArrayType->getElementType()) &&
11521 "Expected std::initializer_list first field to be const E *");
11522 ++Field;
11523 assert(Field != Record->field_end() &&
11524 "Expected std::initializer_list to have two fields");
11525
11526 if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType())) {
11527 // Length.
11528 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
11529 } else {
11530 // End pointer.
11531 assert(Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
11532 ArrayType->getElementType()) &&
11533 "Expected std::initializer_list second field to be const E *");
11534 if (!HandleLValueArrayAdjustment(Info, E, Array,
11535 ArrayType->getElementType(),
11536 ArrayType->getZExtSize()))
11537 return false;
11538 Array.moveInto(Result.getStructField(1));
11539 }
11540
11541 assert(++Field == Record->field_end() &&
11542 "Expected std::initializer_list to only have two fields");
11543
11544 return true;
11545}
11546
11547bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
11548 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
11549 if (ClosureClass->isInvalidDecl())
11550 return false;
11551
11552 const size_t NumFields =
11553 std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
11554
11555 assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
11556 E->capture_init_end()) &&
11557 "The number of lambda capture initializers should equal the number of "
11558 "fields within the closure type");
11559
11560 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
11561 // Iterate through all the lambda's closure object's fields and initialize
11562 // them.
11563 auto *CaptureInitIt = E->capture_init_begin();
11564 bool Success = true;
11565 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(ClosureClass);
11566 for (const auto *Field : ClosureClass->fields()) {
11567 assert(CaptureInitIt != E->capture_init_end());
11568 // Get the initializer for this field
11569 Expr *const CurFieldInit = *CaptureInitIt++;
11570
11571 // If there is no initializer, either this is a VLA or an error has
11572 // occurred.
11573 if (!CurFieldInit || CurFieldInit->containsErrors())
11574 return Error(E);
11575
11576 LValue Subobject = This;
11577
11578 if (!HandleLValueMember(Info, E, Subobject, Field, &Layout))
11579 return false;
11580
11581 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
11582 if (!EvaluateInPlace(FieldVal, Info, Subobject, CurFieldInit)) {
11583 if (!Info.keepEvaluatingAfterFailure())
11584 return false;
11585 Success = false;
11586 }
11587 }
11588 return Success;
11589}
11590
11591static bool EvaluateRecord(const Expr *E, const LValue &This,
11592 APValue &Result, EvalInfo &Info) {
11593 assert(!E->isValueDependent());
11594 assert(E->isPRValue() && E->getType()->isRecordType() &&
11595 "can't evaluate expression as a record rvalue");
11596 return RecordExprEvaluator(Info, This, Result).Visit(E);
11597}
11598
11599//===----------------------------------------------------------------------===//
11600// Temporary Evaluation
11601//
11602// Temporaries are represented in the AST as rvalues, but generally behave like
11603// lvalues. The full-object of which the temporary is a subobject is implicitly
11604// materialized so that a reference can bind to it.
11605//===----------------------------------------------------------------------===//
11606namespace {
11607class TemporaryExprEvaluator
11608 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
11609public:
11610 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
11611 LValueExprEvaluatorBaseTy(Info, Result, false) {}
11612
11613 /// Visit an expression which constructs the value of this temporary.
11614 bool VisitConstructExpr(const Expr *E) {
11615 APValue &Value = Info.CurrentCall->createTemporary(
11616 E, E->getType(), ScopeKind::FullExpression, Result);
11617 return EvaluateInPlace(Value, Info, Result, E);
11618 }
11619
11620 bool VisitCastExpr(const CastExpr *E) {
11621 switch (E->getCastKind()) {
11622 default:
11623 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
11624
11625 case CK_ConstructorConversion:
11626 return VisitConstructExpr(E->getSubExpr());
11627 }
11628 }
11629 bool VisitInitListExpr(const InitListExpr *E) {
11630 return VisitConstructExpr(E);
11631 }
11632 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
11633 return VisitConstructExpr(E);
11634 }
11635 bool VisitCallExpr(const CallExpr *E) {
11636 return VisitConstructExpr(E);
11637 }
11638 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
11639 return VisitConstructExpr(E);
11640 }
11641 bool VisitLambdaExpr(const LambdaExpr *E) {
11642 return VisitConstructExpr(E);
11643 }
11644};
11645} // end anonymous namespace
11646
11647/// Evaluate an expression of record type as a temporary.
11648static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
11649 assert(!E->isValueDependent());
11650 assert(E->isPRValue() && E->getType()->isRecordType());
11651 return TemporaryExprEvaluator(Info, Result).Visit(E);
11652}
11653
11654//===----------------------------------------------------------------------===//
11655// Vector Evaluation
11656//===----------------------------------------------------------------------===//
11657
11658namespace {
11659 class VectorExprEvaluator
11660 : public ExprEvaluatorBase<VectorExprEvaluator> {
11661 APValue &Result;
11662 public:
11663
11664 VectorExprEvaluator(EvalInfo &info, APValue &Result)
11665 : ExprEvaluatorBaseTy(info), Result(Result) {}
11666
11667 bool Success(ArrayRef<APValue> V, const Expr *E) {
11668 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
11669 // FIXME: remove this APValue copy.
11670 Result = APValue(V.data(), V.size());
11671 return true;
11672 }
11673 bool Success(const APValue &V, const Expr *E) {
11674 assert(V.isVector());
11675 Result = V;
11676 return true;
11677 }
11678 bool ZeroInitialization(const Expr *E);
11679
11680 bool VisitUnaryReal(const UnaryOperator *E)
11681 { return Visit(E->getSubExpr()); }
11682 bool VisitCastExpr(const CastExpr* E);
11683 bool VisitInitListExpr(const InitListExpr *E);
11684 bool VisitUnaryImag(const UnaryOperator *E);
11685 bool VisitBinaryOperator(const BinaryOperator *E);
11686 bool VisitUnaryOperator(const UnaryOperator *E);
11687 bool VisitCallExpr(const CallExpr *E);
11688 bool VisitConvertVectorExpr(const ConvertVectorExpr *E);
11689 bool VisitShuffleVectorExpr(const ShuffleVectorExpr *E);
11690
11691 // FIXME: Missing: conditional operator (for GNU
11692 // conditional select), ExtVectorElementExpr
11693 };
11694} // end anonymous namespace
11695
11696static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
11697 assert(E->isPRValue() && E->getType()->isVectorType() &&
11698 "not a vector prvalue");
11699 return VectorExprEvaluator(Info, Result).Visit(E);
11700}
11701
11702static llvm::APInt ConvertBoolVectorToInt(const APValue &Val) {
11703 assert(Val.isVector() && "expected vector APValue");
11704 unsigned NumElts = Val.getVectorLength();
11705
11706 // Each element is one bit, so create an integer with NumElts bits.
11707 llvm::APInt Result(NumElts, 0);
11708
11709 for (unsigned I = 0; I < NumElts; ++I) {
11710 const APValue &Elt = Val.getVectorElt(I);
11711 assert(Elt.isInt() && "expected integer element in bool vector");
11712
11713 if (Elt.getInt().getBoolValue())
11714 Result.setBit(I);
11715 }
11716
11717 return Result;
11718}
11719
11720bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
11721 const VectorType *VTy = E->getType()->castAs<VectorType>();
11722 unsigned NElts = VTy->getNumElements();
11723
11724 const Expr *SE = E->getSubExpr();
11725 QualType SETy = SE->getType();
11726
11727 switch (E->getCastKind()) {
11728 case CK_VectorSplat: {
11729 APValue Val = APValue();
11730 if (SETy->isIntegerType()) {
11731 APSInt IntResult;
11732 if (!EvaluateInteger(SE, IntResult, Info))
11733 return false;
11734 Val = APValue(std::move(IntResult));
11735 } else if (SETy->isRealFloatingType()) {
11736 APFloat FloatResult(0.0);
11737 if (!EvaluateFloat(SE, FloatResult, Info))
11738 return false;
11739 Val = APValue(std::move(FloatResult));
11740 } else {
11741 return Error(E);
11742 }
11743
11744 // Splat and create vector APValue.
11745 SmallVector<APValue, 4> Elts(NElts, Val);
11746 return Success(Elts, E);
11747 }
11748 case CK_BitCast: {
11749 APValue SVal;
11750 if (!Evaluate(SVal, Info, SE))
11751 return false;
11752
11753 if (!SVal.isInt() && !SVal.isFloat() && !SVal.isVector()) {
11754 // Give up if the input isn't an int, float, or vector. For example, we
11755 // reject "(v4i16)(intptr_t)&a".
11756 Info.FFDiag(E, diag::note_constexpr_invalid_cast)
11757 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
11758 << Info.Ctx.getLangOpts().CPlusPlus;
11759 return false;
11760 }
11761
11762 if (!handleRValueToRValueBitCast(Info, Result, SVal, E))
11763 return false;
11764
11765 return true;
11766 }
11767 case CK_HLSLVectorTruncation: {
11768 APValue Val;
11769 SmallVector<APValue, 4> Elements;
11770 if (!EvaluateVector(SE, Val, Info))
11771 return Error(E);
11772 for (unsigned I = 0; I < NElts; I++)
11773 Elements.push_back(Val.getVectorElt(I));
11774 return Success(Elements, E);
11775 }
11776 case CK_HLSLAggregateSplatCast: {
11777 APValue Val;
11778 QualType ValTy;
11779
11780 if (!hlslAggSplatHelper(Info, SE, Val, ValTy))
11781 return false;
11782
11783 // cast our Val once.
11785 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
11786 if (!handleScalarCast(Info, FPO, E, ValTy, VTy->getElementType(), Val,
11787 Result))
11788 return false;
11789
11790 SmallVector<APValue, 4> SplatEls(NElts, Result);
11791 return Success(SplatEls, E);
11792 }
11793 case CK_HLSLElementwiseCast: {
11794 SmallVector<APValue> SrcVals;
11795 SmallVector<QualType> SrcTypes;
11796
11797 if (!hlslElementwiseCastHelper(Info, SE, E->getType(), SrcVals, SrcTypes))
11798 return false;
11799
11800 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
11801 SmallVector<QualType, 4> DestTypes(NElts, VTy->getElementType());
11802 SmallVector<APValue, 4> ResultEls(NElts);
11803 if (!handleElementwiseCast(Info, E, FPO, SrcVals, SrcTypes, DestTypes,
11804 ResultEls))
11805 return false;
11806 return Success(ResultEls, E);
11807 }
11808 default:
11809 return ExprEvaluatorBaseTy::VisitCastExpr(E);
11810 }
11811}
11812
11813bool
11814VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
11815 const VectorType *VT = E->getType()->castAs<VectorType>();
11816 unsigned NumInits = E->getNumInits();
11817 unsigned NumElements = VT->getNumElements();
11818
11819 QualType EltTy = VT->getElementType();
11820 SmallVector<APValue, 4> Elements;
11821
11822 // MFloat8 type doesn't have constants and thus constant folding
11823 // is impossible.
11824 if (EltTy->isMFloat8Type())
11825 return false;
11826
11827 // The number of initializers can be less than the number of
11828 // vector elements. For OpenCL, this can be due to nested vector
11829 // initialization. For GCC compatibility, missing trailing elements
11830 // should be initialized with zeroes.
11831 unsigned CountInits = 0, CountElts = 0;
11832 while (CountElts < NumElements) {
11833 // Handle nested vector initialization.
11834 if (CountInits < NumInits
11835 && E->getInit(CountInits)->getType()->isVectorType()) {
11836 APValue v;
11837 if (!EvaluateVector(E->getInit(CountInits), v, Info))
11838 return Error(E);
11839 unsigned vlen = v.getVectorLength();
11840 for (unsigned j = 0; j < vlen; j++)
11841 Elements.push_back(v.getVectorElt(j));
11842 CountElts += vlen;
11843 } else if (EltTy->isIntegerType()) {
11844 llvm::APSInt sInt(32);
11845 if (CountInits < NumInits) {
11846 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
11847 return false;
11848 } else // trailing integer zero.
11849 sInt = Info.Ctx.MakeIntValue(0, EltTy);
11850 Elements.push_back(APValue(sInt));
11851 CountElts++;
11852 } else {
11853 llvm::APFloat f(0.0);
11854 if (CountInits < NumInits) {
11855 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
11856 return false;
11857 } else // trailing float zero.
11858 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
11859 Elements.push_back(APValue(f));
11860 CountElts++;
11861 }
11862 CountInits++;
11863 }
11864 return Success(Elements, E);
11865}
11866
11867bool
11868VectorExprEvaluator::ZeroInitialization(const Expr *E) {
11869 const auto *VT = E->getType()->castAs<VectorType>();
11870 QualType EltTy = VT->getElementType();
11871 APValue ZeroElement;
11872 if (EltTy->isIntegerType())
11873 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
11874 else
11875 ZeroElement =
11876 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
11877
11878 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
11879 return Success(Elements, E);
11880}
11881
11882bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
11883 VisitIgnoredValue(E->getSubExpr());
11884 return ZeroInitialization(E);
11885}
11886
11887bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
11888 BinaryOperatorKind Op = E->getOpcode();
11889 assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp &&
11890 "Operation not supported on vector types");
11891
11892 if (Op == BO_Comma)
11893 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
11894
11895 Expr *LHS = E->getLHS();
11896 Expr *RHS = E->getRHS();
11897
11898 assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() &&
11899 "Must both be vector types");
11900 // Checking JUST the types are the same would be fine, except shifts don't
11901 // need to have their types be the same (since you always shift by an int).
11902 assert(LHS->getType()->castAs<VectorType>()->getNumElements() ==
11903 E->getType()->castAs<VectorType>()->getNumElements() &&
11904 RHS->getType()->castAs<VectorType>()->getNumElements() ==
11905 E->getType()->castAs<VectorType>()->getNumElements() &&
11906 "All operands must be the same size.");
11907
11908 APValue LHSValue;
11909 APValue RHSValue;
11910 bool LHSOK = Evaluate(LHSValue, Info, LHS);
11911 if (!LHSOK && !Info.noteFailure())
11912 return false;
11913 if (!Evaluate(RHSValue, Info, RHS) || !LHSOK)
11914 return false;
11915
11916 if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue))
11917 return false;
11918
11919 return Success(LHSValue, E);
11920}
11921
11922static std::optional<APValue> handleVectorUnaryOperator(ASTContext &Ctx,
11923 QualType ResultTy,
11925 APValue Elt) {
11926 switch (Op) {
11927 case UO_Plus:
11928 // Nothing to do here.
11929 return Elt;
11930 case UO_Minus:
11931 if (Elt.getKind() == APValue::Int) {
11932 Elt.getInt().negate();
11933 } else {
11934 assert(Elt.getKind() == APValue::Float &&
11935 "Vector can only be int or float type");
11936 Elt.getFloat().changeSign();
11937 }
11938 return Elt;
11939 case UO_Not:
11940 // This is only valid for integral types anyway, so we don't have to handle
11941 // float here.
11942 assert(Elt.getKind() == APValue::Int &&
11943 "Vector operator ~ can only be int");
11944 Elt.getInt().flipAllBits();
11945 return Elt;
11946 case UO_LNot: {
11947 if (Elt.getKind() == APValue::Int) {
11948 Elt.getInt() = !Elt.getInt();
11949 // operator ! on vectors returns -1 for 'truth', so negate it.
11950 Elt.getInt().negate();
11951 return Elt;
11952 }
11953 assert(Elt.getKind() == APValue::Float &&
11954 "Vector can only be int or float type");
11955 // Float types result in an int of the same size, but -1 for true, or 0 for
11956 // false.
11957 APSInt EltResult{Ctx.getIntWidth(ResultTy),
11958 ResultTy->isUnsignedIntegerType()};
11959 if (Elt.getFloat().isZero())
11960 EltResult.setAllBits();
11961 else
11962 EltResult.clearAllBits();
11963
11964 return APValue{EltResult};
11965 }
11966 default:
11967 // FIXME: Implement the rest of the unary operators.
11968 return std::nullopt;
11969 }
11970}
11971
11972bool VectorExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
11973 Expr *SubExpr = E->getSubExpr();
11974 const auto *VD = SubExpr->getType()->castAs<VectorType>();
11975 // This result element type differs in the case of negating a floating point
11976 // vector, since the result type is the a vector of the equivilant sized
11977 // integer.
11978 const QualType ResultEltTy = VD->getElementType();
11979 UnaryOperatorKind Op = E->getOpcode();
11980
11981 APValue SubExprValue;
11982 if (!Evaluate(SubExprValue, Info, SubExpr))
11983 return false;
11984
11985 // FIXME: This vector evaluator someday needs to be changed to be LValue
11986 // aware/keep LValue information around, rather than dealing with just vector
11987 // types directly. Until then, we cannot handle cases where the operand to
11988 // these unary operators is an LValue. The only case I've been able to see
11989 // cause this is operator++ assigning to a member expression (only valid in
11990 // altivec compilations) in C mode, so this shouldn't limit us too much.
11991 if (SubExprValue.isLValue())
11992 return false;
11993
11994 assert(SubExprValue.getVectorLength() == VD->getNumElements() &&
11995 "Vector length doesn't match type?");
11996
11997 SmallVector<APValue, 4> ResultElements;
11998 for (unsigned EltNum = 0; EltNum < VD->getNumElements(); ++EltNum) {
11999 std::optional<APValue> Elt = handleVectorUnaryOperator(
12000 Info.Ctx, ResultEltTy, Op, SubExprValue.getVectorElt(EltNum));
12001 if (!Elt)
12002 return false;
12003 ResultElements.push_back(*Elt);
12004 }
12005 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12006}
12007
12008static bool handleVectorElementCast(EvalInfo &Info, const FPOptions FPO,
12009 const Expr *E, QualType SourceTy,
12010 QualType DestTy, APValue const &Original,
12011 APValue &Result) {
12012 if (SourceTy->isIntegerType()) {
12013 if (DestTy->isRealFloatingType()) {
12014 Result = APValue(APFloat(0.0));
12015 return HandleIntToFloatCast(Info, E, FPO, SourceTy, Original.getInt(),
12016 DestTy, Result.getFloat());
12017 }
12018 if (DestTy->isIntegerType()) {
12019 Result = APValue(
12020 HandleIntToIntCast(Info, E, DestTy, SourceTy, Original.getInt()));
12021 return true;
12022 }
12023 } else if (SourceTy->isRealFloatingType()) {
12024 if (DestTy->isRealFloatingType()) {
12025 Result = Original;
12026 return HandleFloatToFloatCast(Info, E, SourceTy, DestTy,
12027 Result.getFloat());
12028 }
12029 if (DestTy->isIntegerType()) {
12030 Result = APValue(APSInt());
12031 return HandleFloatToIntCast(Info, E, SourceTy, Original.getFloat(),
12032 DestTy, Result.getInt());
12033 }
12034 }
12035
12036 Info.FFDiag(E, diag::err_convertvector_constexpr_unsupported_vector_cast)
12037 << SourceTy << DestTy;
12038 return false;
12039}
12040
12041static bool evalPackBuiltin(const CallExpr *E, EvalInfo &Info, APValue &Result,
12042 llvm::function_ref<APInt(const APSInt &)> PackFn) {
12043 APValue LHS, RHS;
12044 if (!EvaluateAsRValue(Info, E->getArg(0), LHS) ||
12045 !EvaluateAsRValue(Info, E->getArg(1), RHS))
12046 return false;
12047
12048 unsigned LHSVecLen = LHS.getVectorLength();
12049 unsigned RHSVecLen = RHS.getVectorLength();
12050
12051 assert(LHSVecLen != 0 && LHSVecLen == RHSVecLen &&
12052 "pack builtin LHSVecLen must equal to RHSVecLen");
12053
12054 const VectorType *VT0 = E->getArg(0)->getType()->castAs<VectorType>();
12055 const unsigned SrcBits = Info.Ctx.getIntWidth(VT0->getElementType());
12056
12057 const VectorType *DstVT = E->getType()->castAs<VectorType>();
12058 QualType DstElemTy = DstVT->getElementType();
12059 const bool DstIsUnsigned = DstElemTy->isUnsignedIntegerType();
12060
12061 const unsigned SrcPerLane = 128 / SrcBits;
12062 const unsigned Lanes = LHSVecLen * SrcBits / 128;
12063
12065 Out.reserve(LHSVecLen + RHSVecLen);
12066
12067 for (unsigned Lane = 0; Lane != Lanes; ++Lane) {
12068 unsigned base = Lane * SrcPerLane;
12069 for (unsigned I = 0; I != SrcPerLane; ++I)
12070 Out.emplace_back(APValue(
12071 APSInt(PackFn(LHS.getVectorElt(base + I).getInt()), DstIsUnsigned)));
12072 for (unsigned I = 0; I != SrcPerLane; ++I)
12073 Out.emplace_back(APValue(
12074 APSInt(PackFn(RHS.getVectorElt(base + I).getInt()), DstIsUnsigned)));
12075 }
12076
12077 Result = APValue(Out.data(), Out.size());
12078 return true;
12079}
12080
12082 EvalInfo &Info, const CallExpr *Call, APValue &Out,
12083 llvm::function_ref<std::pair<unsigned, int>(unsigned, unsigned)>
12084 GetSourceIndex) {
12085
12086 const auto *VT = Call->getType()->getAs<VectorType>();
12087 if (!VT)
12088 return false;
12089
12090 unsigned ShuffleMask = 0;
12091 APValue A, MaskVector, B;
12092 bool IsVectorMask = false;
12093 bool IsSingleOperand = (Call->getNumArgs() == 2);
12094
12095 if (IsSingleOperand) {
12096 QualType MaskType = Call->getArg(1)->getType();
12097 if (MaskType->isVectorType()) {
12098 IsVectorMask = true;
12099 if (!EvaluateAsRValue(Info, Call->getArg(0), A) ||
12100 !EvaluateAsRValue(Info, Call->getArg(1), MaskVector))
12101 return false;
12102 B = A;
12103 } else if (MaskType->isIntegerType()) {
12104 APSInt MaskImm;
12105 if (!EvaluateInteger(Call->getArg(1), MaskImm, Info))
12106 return false;
12107 ShuffleMask = static_cast<unsigned>(MaskImm.getZExtValue());
12108 if (!EvaluateAsRValue(Info, Call->getArg(0), A))
12109 return false;
12110 B = A;
12111 } else {
12112 return false;
12113 }
12114 } else {
12115 QualType Arg2Type = Call->getArg(2)->getType();
12116 if (Arg2Type->isVectorType()) {
12117 IsVectorMask = true;
12118 if (!EvaluateAsRValue(Info, Call->getArg(0), A) ||
12119 !EvaluateAsRValue(Info, Call->getArg(1), MaskVector) ||
12120 !EvaluateAsRValue(Info, Call->getArg(2), B))
12121 return false;
12122 } else if (Arg2Type->isIntegerType()) {
12123 APSInt MaskImm;
12124 if (!EvaluateInteger(Call->getArg(2), MaskImm, Info))
12125 return false;
12126 ShuffleMask = static_cast<unsigned>(MaskImm.getZExtValue());
12127 if (!EvaluateAsRValue(Info, Call->getArg(0), A) ||
12128 !EvaluateAsRValue(Info, Call->getArg(1), B))
12129 return false;
12130 } else {
12131 return false;
12132 }
12133 }
12134
12135 unsigned NumElts = VT->getNumElements();
12136 SmallVector<APValue, 64> ResultElements;
12137 ResultElements.reserve(NumElts);
12138
12139 for (unsigned DstIdx = 0; DstIdx != NumElts; ++DstIdx) {
12140 if (IsVectorMask) {
12141 ShuffleMask = static_cast<unsigned>(
12142 MaskVector.getVectorElt(DstIdx).getInt().getZExtValue());
12143 }
12144 auto [SrcVecIdx, SrcIdx] = GetSourceIndex(DstIdx, ShuffleMask);
12145
12146 if (SrcIdx < 0) {
12147 // Zero out this element
12148 QualType ElemTy = VT->getElementType();
12149 if (ElemTy->isRealFloatingType()) {
12150 ResultElements.push_back(
12151 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy))));
12152 } else if (ElemTy->isIntegerType()) {
12153 APValue Zero(Info.Ctx.MakeIntValue(0, ElemTy));
12154 ResultElements.push_back(APValue(Zero));
12155 } else {
12156 // Other types of fallback logic
12157 ResultElements.push_back(APValue());
12158 }
12159 } else {
12160 const APValue &Src = (SrcVecIdx == 0) ? A : B;
12161 ResultElements.push_back(Src.getVectorElt(SrcIdx));
12162 }
12163 }
12164
12165 Out = APValue(ResultElements.data(), ResultElements.size());
12166 return true;
12167}
12168
12169bool VectorExprEvaluator::VisitCallExpr(const CallExpr *E) {
12170 if (!IsConstantEvaluatedBuiltinCall(E))
12171 return ExprEvaluatorBaseTy::VisitCallExpr(E);
12172
12173 auto EvaluateBinOpExpr =
12174 [&](llvm::function_ref<APInt(const APSInt &, const APSInt &)> Fn) {
12175 APValue SourceLHS, SourceRHS;
12176 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
12177 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
12178 return false;
12179
12180 auto *DestTy = E->getType()->castAs<VectorType>();
12181 QualType DestEltTy = DestTy->getElementType();
12182 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
12183 unsigned SourceLen = SourceLHS.getVectorLength();
12184 SmallVector<APValue, 4> ResultElements;
12185 ResultElements.reserve(SourceLen);
12186
12187 if (SourceRHS.isInt()) {
12188 const APSInt &RHS = SourceRHS.getInt();
12189 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12190 const APSInt &LHS = SourceLHS.getVectorElt(EltNum).getInt();
12191 ResultElements.push_back(
12192 APValue(APSInt(Fn(LHS, RHS), DestUnsigned)));
12193 }
12194 } else {
12195 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12196 const APSInt &LHS = SourceLHS.getVectorElt(EltNum).getInt();
12197 const APSInt &RHS = SourceRHS.getVectorElt(EltNum).getInt();
12198 ResultElements.push_back(
12199 APValue(APSInt(Fn(LHS, RHS), DestUnsigned)));
12200 }
12201 }
12202 return Success(APValue(ResultElements.data(), SourceLen), E);
12203 };
12204
12205 switch (E->getBuiltinCallee()) {
12206 default:
12207 return false;
12208 case Builtin::BI__builtin_elementwise_popcount:
12209 case Builtin::BI__builtin_elementwise_bitreverse: {
12210 APValue Source;
12211 if (!EvaluateAsRValue(Info, E->getArg(0), Source))
12212 return false;
12213
12214 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
12215 unsigned SourceLen = Source.getVectorLength();
12216 SmallVector<APValue, 4> ResultElements;
12217 ResultElements.reserve(SourceLen);
12218
12219 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12220 APSInt Elt = Source.getVectorElt(EltNum).getInt();
12221 switch (E->getBuiltinCallee()) {
12222 case Builtin::BI__builtin_elementwise_popcount:
12223 ResultElements.push_back(APValue(
12224 APSInt(APInt(Info.Ctx.getIntWidth(DestEltTy), Elt.popcount()),
12225 DestEltTy->isUnsignedIntegerOrEnumerationType())));
12226 break;
12227 case Builtin::BI__builtin_elementwise_bitreverse:
12228 ResultElements.push_back(
12229 APValue(APSInt(Elt.reverseBits(),
12230 DestEltTy->isUnsignedIntegerOrEnumerationType())));
12231 break;
12232 }
12233 }
12234
12235 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12236 }
12237 case Builtin::BI__builtin_elementwise_abs: {
12238 APValue Source;
12239 if (!EvaluateAsRValue(Info, E->getArg(0), Source))
12240 return false;
12241
12242 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
12243 unsigned SourceLen = Source.getVectorLength();
12244 SmallVector<APValue, 4> ResultElements;
12245 ResultElements.reserve(SourceLen);
12246
12247 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12248 APValue CurrentEle = Source.getVectorElt(EltNum);
12249 APValue Val = DestEltTy->isFloatingType()
12250 ? APValue(llvm::abs(CurrentEle.getFloat()))
12251 : APValue(APSInt(
12252 CurrentEle.getInt().abs(),
12253 DestEltTy->isUnsignedIntegerOrEnumerationType()));
12254 ResultElements.push_back(Val);
12255 }
12256
12257 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12258 }
12259
12260 case Builtin::BI__builtin_elementwise_add_sat:
12261 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
12262 return LHS.isSigned() ? LHS.sadd_sat(RHS) : LHS.uadd_sat(RHS);
12263 });
12264
12265 case Builtin::BI__builtin_elementwise_sub_sat:
12266 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
12267 return LHS.isSigned() ? LHS.ssub_sat(RHS) : LHS.usub_sat(RHS);
12268 });
12269
12270 case X86::BI__builtin_ia32_extract128i256:
12271 case X86::BI__builtin_ia32_vextractf128_pd256:
12272 case X86::BI__builtin_ia32_vextractf128_ps256:
12273 case X86::BI__builtin_ia32_vextractf128_si256: {
12274 APValue SourceVec, SourceImm;
12275 if (!EvaluateAsRValue(Info, E->getArg(0), SourceVec) ||
12276 !EvaluateAsRValue(Info, E->getArg(1), SourceImm))
12277 return false;
12278
12279 if (!SourceVec.isVector())
12280 return false;
12281
12282 const auto *RetVT = E->getType()->castAs<VectorType>();
12283 unsigned RetLen = RetVT->getNumElements();
12284 unsigned Idx = SourceImm.getInt().getZExtValue() & 1;
12285
12286 SmallVector<APValue, 32> ResultElements;
12287 ResultElements.reserve(RetLen);
12288
12289 for (unsigned I = 0; I < RetLen; I++)
12290 ResultElements.push_back(SourceVec.getVectorElt(Idx * RetLen + I));
12291
12292 return Success(APValue(ResultElements.data(), RetLen), E);
12293 }
12294
12295 case X86::BI__builtin_ia32_extracti32x4_256_mask:
12296 case X86::BI__builtin_ia32_extractf32x4_256_mask:
12297 case X86::BI__builtin_ia32_extracti32x4_mask:
12298 case X86::BI__builtin_ia32_extractf32x4_mask:
12299 case X86::BI__builtin_ia32_extracti32x8_mask:
12300 case X86::BI__builtin_ia32_extractf32x8_mask:
12301 case X86::BI__builtin_ia32_extracti64x2_256_mask:
12302 case X86::BI__builtin_ia32_extractf64x2_256_mask:
12303 case X86::BI__builtin_ia32_extracti64x2_512_mask:
12304 case X86::BI__builtin_ia32_extractf64x2_512_mask:
12305 case X86::BI__builtin_ia32_extracti64x4_mask:
12306 case X86::BI__builtin_ia32_extractf64x4_mask: {
12307 APValue SourceVec, MergeVec;
12308 APSInt Imm, MaskImm;
12309
12310 if (!EvaluateAsRValue(Info, E->getArg(0), SourceVec) ||
12311 !EvaluateInteger(E->getArg(1), Imm, Info) ||
12312 !EvaluateAsRValue(Info, E->getArg(2), MergeVec) ||
12313 !EvaluateInteger(E->getArg(3), MaskImm, Info))
12314 return false;
12315
12316 const auto *RetVT = E->getType()->castAs<VectorType>();
12317 unsigned RetLen = RetVT->getNumElements();
12318
12319 if (!SourceVec.isVector() || !MergeVec.isVector())
12320 return false;
12321 unsigned SrcLen = SourceVec.getVectorLength();
12322 unsigned Lanes = SrcLen / RetLen;
12323 unsigned Lane = static_cast<unsigned>(Imm.getZExtValue() % Lanes);
12324 unsigned Base = Lane * RetLen;
12325
12326 SmallVector<APValue, 32> ResultElements;
12327 ResultElements.reserve(RetLen);
12328 for (unsigned I = 0; I < RetLen; ++I) {
12329 if (MaskImm[I])
12330 ResultElements.push_back(SourceVec.getVectorElt(Base + I));
12331 else
12332 ResultElements.push_back(MergeVec.getVectorElt(I));
12333 }
12334 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12335 }
12336
12337 case clang::X86::BI__builtin_ia32_pavgb128:
12338 case clang::X86::BI__builtin_ia32_pavgw128:
12339 case clang::X86::BI__builtin_ia32_pavgb256:
12340 case clang::X86::BI__builtin_ia32_pavgw256:
12341 case clang::X86::BI__builtin_ia32_pavgb512:
12342 case clang::X86::BI__builtin_ia32_pavgw512:
12343 return EvaluateBinOpExpr(llvm::APIntOps::avgCeilU);
12344
12345 case clang::X86::BI__builtin_ia32_pmulhrsw128:
12346 case clang::X86::BI__builtin_ia32_pmulhrsw256:
12347 case clang::X86::BI__builtin_ia32_pmulhrsw512:
12348 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
12349 return (llvm::APIntOps::mulsExtended(LHS, RHS).ashr(14) + 1)
12350 .extractBits(16, 1);
12351 });
12352
12353 case clang::X86::BI__builtin_ia32_pmaddubsw128:
12354 case clang::X86::BI__builtin_ia32_pmaddubsw256:
12355 case clang::X86::BI__builtin_ia32_pmaddubsw512:
12356 case clang::X86::BI__builtin_ia32_pmaddwd128:
12357 case clang::X86::BI__builtin_ia32_pmaddwd256:
12358 case clang::X86::BI__builtin_ia32_pmaddwd512: {
12359 APValue SourceLHS, SourceRHS;
12360 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
12361 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
12362 return false;
12363
12364 auto *DestTy = E->getType()->castAs<VectorType>();
12365 QualType DestEltTy = DestTy->getElementType();
12366 unsigned SourceLen = SourceLHS.getVectorLength();
12367 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
12368 SmallVector<APValue, 4> ResultElements;
12369 ResultElements.reserve(SourceLen / 2);
12370
12371 for (unsigned EltNum = 0; EltNum < SourceLen; EltNum += 2) {
12372 const APSInt &LoLHS = SourceLHS.getVectorElt(EltNum).getInt();
12373 const APSInt &HiLHS = SourceLHS.getVectorElt(EltNum + 1).getInt();
12374 const APSInt &LoRHS = SourceRHS.getVectorElt(EltNum).getInt();
12375 const APSInt &HiRHS = SourceRHS.getVectorElt(EltNum + 1).getInt();
12376 unsigned BitWidth = 2 * LoLHS.getBitWidth();
12377
12378 switch (E->getBuiltinCallee()) {
12379 case clang::X86::BI__builtin_ia32_pmaddubsw128:
12380 case clang::X86::BI__builtin_ia32_pmaddubsw256:
12381 case clang::X86::BI__builtin_ia32_pmaddubsw512:
12382 ResultElements.push_back(APValue(
12383 APSInt((LoLHS.zext(BitWidth) * LoRHS.sext(BitWidth))
12384 .sadd_sat((HiLHS.zext(BitWidth) * HiRHS.sext(BitWidth))),
12385 DestUnsigned)));
12386 break;
12387 case clang::X86::BI__builtin_ia32_pmaddwd128:
12388 case clang::X86::BI__builtin_ia32_pmaddwd256:
12389 case clang::X86::BI__builtin_ia32_pmaddwd512:
12390 ResultElements.push_back(
12391 APValue(APSInt((LoLHS.sext(BitWidth) * LoRHS.sext(BitWidth)) +
12392 (HiLHS.sext(BitWidth) * HiRHS.sext(BitWidth)),
12393 DestUnsigned)));
12394 break;
12395 }
12396 }
12397
12398 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12399 }
12400
12401 case clang::X86::BI__builtin_ia32_pmulhuw128:
12402 case clang::X86::BI__builtin_ia32_pmulhuw256:
12403 case clang::X86::BI__builtin_ia32_pmulhuw512:
12404 return EvaluateBinOpExpr(llvm::APIntOps::mulhu);
12405
12406 case clang::X86::BI__builtin_ia32_pmulhw128:
12407 case clang::X86::BI__builtin_ia32_pmulhw256:
12408 case clang::X86::BI__builtin_ia32_pmulhw512:
12409 return EvaluateBinOpExpr(llvm::APIntOps::mulhs);
12410
12411 case clang::X86::BI__builtin_ia32_psllv2di:
12412 case clang::X86::BI__builtin_ia32_psllv4di:
12413 case clang::X86::BI__builtin_ia32_psllv4si:
12414 case clang::X86::BI__builtin_ia32_psllv8di:
12415 case clang::X86::BI__builtin_ia32_psllv8hi:
12416 case clang::X86::BI__builtin_ia32_psllv8si:
12417 case clang::X86::BI__builtin_ia32_psllv16hi:
12418 case clang::X86::BI__builtin_ia32_psllv16si:
12419 case clang::X86::BI__builtin_ia32_psllv32hi:
12420 case clang::X86::BI__builtin_ia32_psllwi128:
12421 case clang::X86::BI__builtin_ia32_pslldi128:
12422 case clang::X86::BI__builtin_ia32_psllqi128:
12423 case clang::X86::BI__builtin_ia32_psllwi256:
12424 case clang::X86::BI__builtin_ia32_pslldi256:
12425 case clang::X86::BI__builtin_ia32_psllqi256:
12426 case clang::X86::BI__builtin_ia32_psllwi512:
12427 case clang::X86::BI__builtin_ia32_pslldi512:
12428 case clang::X86::BI__builtin_ia32_psllqi512:
12429 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
12430 if (RHS.uge(LHS.getBitWidth())) {
12431 return APInt::getZero(LHS.getBitWidth());
12432 }
12433 return LHS.shl(RHS.getZExtValue());
12434 });
12435
12436 case clang::X86::BI__builtin_ia32_psrav4si:
12437 case clang::X86::BI__builtin_ia32_psrav8di:
12438 case clang::X86::BI__builtin_ia32_psrav8hi:
12439 case clang::X86::BI__builtin_ia32_psrav8si:
12440 case clang::X86::BI__builtin_ia32_psrav16hi:
12441 case clang::X86::BI__builtin_ia32_psrav16si:
12442 case clang::X86::BI__builtin_ia32_psrav32hi:
12443 case clang::X86::BI__builtin_ia32_psravq128:
12444 case clang::X86::BI__builtin_ia32_psravq256:
12445 case clang::X86::BI__builtin_ia32_psrawi128:
12446 case clang::X86::BI__builtin_ia32_psradi128:
12447 case clang::X86::BI__builtin_ia32_psraqi128:
12448 case clang::X86::BI__builtin_ia32_psrawi256:
12449 case clang::X86::BI__builtin_ia32_psradi256:
12450 case clang::X86::BI__builtin_ia32_psraqi256:
12451 case clang::X86::BI__builtin_ia32_psrawi512:
12452 case clang::X86::BI__builtin_ia32_psradi512:
12453 case clang::X86::BI__builtin_ia32_psraqi512:
12454 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
12455 if (RHS.uge(LHS.getBitWidth())) {
12456 return LHS.ashr(LHS.getBitWidth() - 1);
12457 }
12458 return LHS.ashr(RHS.getZExtValue());
12459 });
12460
12461 case clang::X86::BI__builtin_ia32_psrlv2di:
12462 case clang::X86::BI__builtin_ia32_psrlv4di:
12463 case clang::X86::BI__builtin_ia32_psrlv4si:
12464 case clang::X86::BI__builtin_ia32_psrlv8di:
12465 case clang::X86::BI__builtin_ia32_psrlv8hi:
12466 case clang::X86::BI__builtin_ia32_psrlv8si:
12467 case clang::X86::BI__builtin_ia32_psrlv16hi:
12468 case clang::X86::BI__builtin_ia32_psrlv16si:
12469 case clang::X86::BI__builtin_ia32_psrlv32hi:
12470 case clang::X86::BI__builtin_ia32_psrlwi128:
12471 case clang::X86::BI__builtin_ia32_psrldi128:
12472 case clang::X86::BI__builtin_ia32_psrlqi128:
12473 case clang::X86::BI__builtin_ia32_psrlwi256:
12474 case clang::X86::BI__builtin_ia32_psrldi256:
12475 case clang::X86::BI__builtin_ia32_psrlqi256:
12476 case clang::X86::BI__builtin_ia32_psrlwi512:
12477 case clang::X86::BI__builtin_ia32_psrldi512:
12478 case clang::X86::BI__builtin_ia32_psrlqi512:
12479 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
12480 if (RHS.uge(LHS.getBitWidth())) {
12481 return APInt::getZero(LHS.getBitWidth());
12482 }
12483 return LHS.lshr(RHS.getZExtValue());
12484 });
12485 case X86::BI__builtin_ia32_packsswb128:
12486 case X86::BI__builtin_ia32_packsswb256:
12487 case X86::BI__builtin_ia32_packsswb512:
12488 case X86::BI__builtin_ia32_packssdw128:
12489 case X86::BI__builtin_ia32_packssdw256:
12490 case X86::BI__builtin_ia32_packssdw512:
12491 return evalPackBuiltin(E, Info, Result, [](const APSInt &Src) {
12492 return APSInt(Src).truncSSat(Src.getBitWidth() / 2);
12493 });
12494 case X86::BI__builtin_ia32_packusdw128:
12495 case X86::BI__builtin_ia32_packusdw256:
12496 case X86::BI__builtin_ia32_packusdw512:
12497 case X86::BI__builtin_ia32_packuswb128:
12498 case X86::BI__builtin_ia32_packuswb256:
12499 case X86::BI__builtin_ia32_packuswb512:
12500 return evalPackBuiltin(E, Info, Result, [](const APSInt &Src) {
12501 unsigned DstBits = Src.getBitWidth() / 2;
12502 if (Src.isNegative())
12503 return APInt::getZero(DstBits);
12504 if (Src.isIntN(DstBits))
12505 return APInt((Src).trunc(DstBits));
12506 return APInt::getAllOnes(DstBits);
12507 });
12508 case clang::X86::BI__builtin_ia32_pmuldq128:
12509 case clang::X86::BI__builtin_ia32_pmuldq256:
12510 case clang::X86::BI__builtin_ia32_pmuldq512:
12511 case clang::X86::BI__builtin_ia32_pmuludq128:
12512 case clang::X86::BI__builtin_ia32_pmuludq256:
12513 case clang::X86::BI__builtin_ia32_pmuludq512: {
12514 APValue SourceLHS, SourceRHS;
12515 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
12516 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
12517 return false;
12518
12519 unsigned SourceLen = SourceLHS.getVectorLength();
12520 SmallVector<APValue, 4> ResultElements;
12521 ResultElements.reserve(SourceLen / 2);
12522
12523 for (unsigned EltNum = 0; EltNum < SourceLen; EltNum += 2) {
12524 APSInt LHS = SourceLHS.getVectorElt(EltNum).getInt();
12525 APSInt RHS = SourceRHS.getVectorElt(EltNum).getInt();
12526
12527 switch (E->getBuiltinCallee()) {
12528 case clang::X86::BI__builtin_ia32_pmuludq128:
12529 case clang::X86::BI__builtin_ia32_pmuludq256:
12530 case clang::X86::BI__builtin_ia32_pmuludq512:
12531 ResultElements.push_back(
12532 APValue(APSInt(llvm::APIntOps::muluExtended(LHS, RHS), true)));
12533 break;
12534 case clang::X86::BI__builtin_ia32_pmuldq128:
12535 case clang::X86::BI__builtin_ia32_pmuldq256:
12536 case clang::X86::BI__builtin_ia32_pmuldq512:
12537 ResultElements.push_back(
12538 APValue(APSInt(llvm::APIntOps::mulsExtended(LHS, RHS), false)));
12539 break;
12540 }
12541 }
12542
12543 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12544 }
12545
12546 case X86::BI__builtin_ia32_vpmadd52luq128:
12547 case X86::BI__builtin_ia32_vpmadd52luq256:
12548 case X86::BI__builtin_ia32_vpmadd52luq512: {
12549 APValue A, B, C;
12550 if (!EvaluateAsRValue(Info, E->getArg(0), A) ||
12551 !EvaluateAsRValue(Info, E->getArg(1), B) ||
12552 !EvaluateAsRValue(Info, E->getArg(2), C))
12553 return false;
12554
12555 unsigned ALen = A.getVectorLength();
12556 SmallVector<APValue, 4> ResultElements;
12557 ResultElements.reserve(ALen);
12558
12559 for (unsigned EltNum = 0; EltNum < ALen; EltNum += 1) {
12560 APInt AElt = A.getVectorElt(EltNum).getInt();
12561 APInt BElt = B.getVectorElt(EltNum).getInt().trunc(52);
12562 APInt CElt = C.getVectorElt(EltNum).getInt().trunc(52);
12563 APSInt ResElt(AElt + (BElt * CElt).zext(64), false);
12564 ResultElements.push_back(APValue(ResElt));
12565 }
12566
12567 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12568 }
12569 case X86::BI__builtin_ia32_vpmadd52huq128:
12570 case X86::BI__builtin_ia32_vpmadd52huq256:
12571 case X86::BI__builtin_ia32_vpmadd52huq512: {
12572 APValue A, B, C;
12573 if (!EvaluateAsRValue(Info, E->getArg(0), A) ||
12574 !EvaluateAsRValue(Info, E->getArg(1), B) ||
12575 !EvaluateAsRValue(Info, E->getArg(2), C))
12576 return false;
12577
12578 unsigned ALen = A.getVectorLength();
12579 SmallVector<APValue, 4> ResultElements;
12580 ResultElements.reserve(ALen);
12581
12582 for (unsigned EltNum = 0; EltNum < ALen; EltNum += 1) {
12583 APInt AElt = A.getVectorElt(EltNum).getInt();
12584 APInt BElt = B.getVectorElt(EltNum).getInt().trunc(52);
12585 APInt CElt = C.getVectorElt(EltNum).getInt().trunc(52);
12586 APSInt ResElt(AElt + llvm::APIntOps::mulhu(BElt, CElt).zext(64), false);
12587 ResultElements.push_back(APValue(ResElt));
12588 }
12589
12590 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12591 }
12592
12593 case clang::X86::BI__builtin_ia32_vprotbi:
12594 case clang::X86::BI__builtin_ia32_vprotdi:
12595 case clang::X86::BI__builtin_ia32_vprotqi:
12596 case clang::X86::BI__builtin_ia32_vprotwi:
12597 case clang::X86::BI__builtin_ia32_prold128:
12598 case clang::X86::BI__builtin_ia32_prold256:
12599 case clang::X86::BI__builtin_ia32_prold512:
12600 case clang::X86::BI__builtin_ia32_prolq128:
12601 case clang::X86::BI__builtin_ia32_prolq256:
12602 case clang::X86::BI__builtin_ia32_prolq512:
12603 return EvaluateBinOpExpr(
12604 [](const APSInt &LHS, const APSInt &RHS) { return LHS.rotl(RHS); });
12605
12606 case clang::X86::BI__builtin_ia32_prord128:
12607 case clang::X86::BI__builtin_ia32_prord256:
12608 case clang::X86::BI__builtin_ia32_prord512:
12609 case clang::X86::BI__builtin_ia32_prorq128:
12610 case clang::X86::BI__builtin_ia32_prorq256:
12611 case clang::X86::BI__builtin_ia32_prorq512:
12612 return EvaluateBinOpExpr(
12613 [](const APSInt &LHS, const APSInt &RHS) { return LHS.rotr(RHS); });
12614
12615 case Builtin::BI__builtin_elementwise_max:
12616 case Builtin::BI__builtin_elementwise_min: {
12617 APValue SourceLHS, SourceRHS;
12618 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
12619 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
12620 return false;
12621
12622 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
12623
12624 if (!DestEltTy->isIntegerType())
12625 return false;
12626
12627 unsigned SourceLen = SourceLHS.getVectorLength();
12628 SmallVector<APValue, 4> ResultElements;
12629 ResultElements.reserve(SourceLen);
12630
12631 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12632 APSInt LHS = SourceLHS.getVectorElt(EltNum).getInt();
12633 APSInt RHS = SourceRHS.getVectorElt(EltNum).getInt();
12634 switch (E->getBuiltinCallee()) {
12635 case Builtin::BI__builtin_elementwise_max:
12636 ResultElements.push_back(
12637 APValue(APSInt(std::max(LHS, RHS),
12638 DestEltTy->isUnsignedIntegerOrEnumerationType())));
12639 break;
12640 case Builtin::BI__builtin_elementwise_min:
12641 ResultElements.push_back(
12642 APValue(APSInt(std::min(LHS, RHS),
12643 DestEltTy->isUnsignedIntegerOrEnumerationType())));
12644 break;
12645 }
12646 }
12647
12648 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12649 }
12650 case X86::BI__builtin_ia32_vpshldd128:
12651 case X86::BI__builtin_ia32_vpshldd256:
12652 case X86::BI__builtin_ia32_vpshldd512:
12653 case X86::BI__builtin_ia32_vpshldq128:
12654 case X86::BI__builtin_ia32_vpshldq256:
12655 case X86::BI__builtin_ia32_vpshldq512:
12656 case X86::BI__builtin_ia32_vpshldw128:
12657 case X86::BI__builtin_ia32_vpshldw256:
12658 case X86::BI__builtin_ia32_vpshldw512: {
12659 APValue SourceHi, SourceLo, SourceAmt;
12660 if (!EvaluateAsRValue(Info, E->getArg(0), SourceHi) ||
12661 !EvaluateAsRValue(Info, E->getArg(1), SourceLo) ||
12662 !EvaluateAsRValue(Info, E->getArg(2), SourceAmt))
12663 return false;
12664
12665 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
12666 unsigned SourceLen = SourceHi.getVectorLength();
12667 SmallVector<APValue, 32> ResultElements;
12668 ResultElements.reserve(SourceLen);
12669
12670 APInt Amt = SourceAmt.getInt();
12671 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12672 APInt Hi = SourceHi.getVectorElt(EltNum).getInt();
12673 APInt Lo = SourceLo.getVectorElt(EltNum).getInt();
12674 APInt R = llvm::APIntOps::fshl(Hi, Lo, Amt);
12675 ResultElements.push_back(
12677 }
12678
12679 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12680 }
12681 case X86::BI__builtin_ia32_vpshrdd128:
12682 case X86::BI__builtin_ia32_vpshrdd256:
12683 case X86::BI__builtin_ia32_vpshrdd512:
12684 case X86::BI__builtin_ia32_vpshrdq128:
12685 case X86::BI__builtin_ia32_vpshrdq256:
12686 case X86::BI__builtin_ia32_vpshrdq512:
12687 case X86::BI__builtin_ia32_vpshrdw128:
12688 case X86::BI__builtin_ia32_vpshrdw256:
12689 case X86::BI__builtin_ia32_vpshrdw512: {
12690 // NOTE: Reversed Hi/Lo operands.
12691 APValue SourceHi, SourceLo, SourceAmt;
12692 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLo) ||
12693 !EvaluateAsRValue(Info, E->getArg(1), SourceHi) ||
12694 !EvaluateAsRValue(Info, E->getArg(2), SourceAmt))
12695 return false;
12696
12697 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
12698 unsigned SourceLen = SourceHi.getVectorLength();
12699 SmallVector<APValue, 32> ResultElements;
12700 ResultElements.reserve(SourceLen);
12701
12702 APInt Amt = SourceAmt.getInt();
12703 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12704 APInt Hi = SourceHi.getVectorElt(EltNum).getInt();
12705 APInt Lo = SourceLo.getVectorElt(EltNum).getInt();
12706 APInt R = llvm::APIntOps::fshr(Hi, Lo, Amt);
12707 ResultElements.push_back(
12709 }
12710
12711 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12712 }
12713 case X86::BI__builtin_ia32_vpconflictsi_128:
12714 case X86::BI__builtin_ia32_vpconflictsi_256:
12715 case X86::BI__builtin_ia32_vpconflictsi_512:
12716 case X86::BI__builtin_ia32_vpconflictdi_128:
12717 case X86::BI__builtin_ia32_vpconflictdi_256:
12718 case X86::BI__builtin_ia32_vpconflictdi_512: {
12719 APValue Source;
12720
12721 if (!EvaluateAsRValue(Info, E->getArg(0), Source))
12722 return false;
12723
12724 unsigned SourceLen = Source.getVectorLength();
12725 SmallVector<APValue, 32> ResultElements;
12726 ResultElements.reserve(SourceLen);
12727
12728 const auto *VecT = E->getType()->castAs<VectorType>();
12729 bool DestUnsigned =
12730 VecT->getElementType()->isUnsignedIntegerOrEnumerationType();
12731
12732 for (unsigned I = 0; I != SourceLen; ++I) {
12733 const APValue &EltI = Source.getVectorElt(I);
12734
12735 APInt ConflictMask(EltI.getInt().getBitWidth(), 0);
12736 for (unsigned J = 0; J != I; ++J) {
12737 const APValue &EltJ = Source.getVectorElt(J);
12738 ConflictMask.setBitVal(J, EltI.getInt() == EltJ.getInt());
12739 }
12740 ResultElements.push_back(APValue(APSInt(ConflictMask, DestUnsigned)));
12741 }
12742 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12743 }
12744 case X86::BI__builtin_ia32_blendpd:
12745 case X86::BI__builtin_ia32_blendpd256:
12746 case X86::BI__builtin_ia32_blendps:
12747 case X86::BI__builtin_ia32_blendps256:
12748 case X86::BI__builtin_ia32_pblendw128:
12749 case X86::BI__builtin_ia32_pblendw256:
12750 case X86::BI__builtin_ia32_pblendd128:
12751 case X86::BI__builtin_ia32_pblendd256: {
12752 APValue SourceF, SourceT, SourceC;
12753 if (!EvaluateAsRValue(Info, E->getArg(0), SourceF) ||
12754 !EvaluateAsRValue(Info, E->getArg(1), SourceT) ||
12755 !EvaluateAsRValue(Info, E->getArg(2), SourceC))
12756 return false;
12757
12758 const APInt &C = SourceC.getInt();
12759 unsigned SourceLen = SourceF.getVectorLength();
12760 SmallVector<APValue, 32> ResultElements;
12761 ResultElements.reserve(SourceLen);
12762 for (unsigned EltNum = 0; EltNum != SourceLen; ++EltNum) {
12763 const APValue &F = SourceF.getVectorElt(EltNum);
12764 const APValue &T = SourceT.getVectorElt(EltNum);
12765 ResultElements.push_back(C[EltNum % 8] ? T : F);
12766 }
12767
12768 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12769 }
12770
12771 case X86::BI__builtin_ia32_psignb128:
12772 case X86::BI__builtin_ia32_psignb256:
12773 case X86::BI__builtin_ia32_psignw128:
12774 case X86::BI__builtin_ia32_psignw256:
12775 case X86::BI__builtin_ia32_psignd128:
12776 case X86::BI__builtin_ia32_psignd256:
12777 return EvaluateBinOpExpr([](const APInt &AElem, const APInt &BElem) {
12778 if (BElem.isZero())
12779 return APInt::getZero(AElem.getBitWidth());
12780 if (BElem.isNegative())
12781 return -AElem;
12782 return AElem;
12783 });
12784
12785 case X86::BI__builtin_ia32_blendvpd:
12786 case X86::BI__builtin_ia32_blendvpd256:
12787 case X86::BI__builtin_ia32_blendvps:
12788 case X86::BI__builtin_ia32_blendvps256:
12789 case X86::BI__builtin_ia32_pblendvb128:
12790 case X86::BI__builtin_ia32_pblendvb256: {
12791 // SSE blendv by mask signbit: "Result = C[] < 0 ? T[] : F[]".
12792 APValue SourceF, SourceT, SourceC;
12793 if (!EvaluateAsRValue(Info, E->getArg(0), SourceF) ||
12794 !EvaluateAsRValue(Info, E->getArg(1), SourceT) ||
12795 !EvaluateAsRValue(Info, E->getArg(2), SourceC))
12796 return false;
12797
12798 unsigned SourceLen = SourceF.getVectorLength();
12799 SmallVector<APValue, 32> ResultElements;
12800 ResultElements.reserve(SourceLen);
12801
12802 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12803 const APValue &F = SourceF.getVectorElt(EltNum);
12804 const APValue &T = SourceT.getVectorElt(EltNum);
12805 const APValue &C = SourceC.getVectorElt(EltNum);
12806 APInt M = C.isInt() ? (APInt)C.getInt() : C.getFloat().bitcastToAPInt();
12807 ResultElements.push_back(M.isNegative() ? T : F);
12808 }
12809
12810 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12811 }
12812 case X86::BI__builtin_ia32_selectb_128:
12813 case X86::BI__builtin_ia32_selectb_256:
12814 case X86::BI__builtin_ia32_selectb_512:
12815 case X86::BI__builtin_ia32_selectw_128:
12816 case X86::BI__builtin_ia32_selectw_256:
12817 case X86::BI__builtin_ia32_selectw_512:
12818 case X86::BI__builtin_ia32_selectd_128:
12819 case X86::BI__builtin_ia32_selectd_256:
12820 case X86::BI__builtin_ia32_selectd_512:
12821 case X86::BI__builtin_ia32_selectq_128:
12822 case X86::BI__builtin_ia32_selectq_256:
12823 case X86::BI__builtin_ia32_selectq_512:
12824 case X86::BI__builtin_ia32_selectph_128:
12825 case X86::BI__builtin_ia32_selectph_256:
12826 case X86::BI__builtin_ia32_selectph_512:
12827 case X86::BI__builtin_ia32_selectpbf_128:
12828 case X86::BI__builtin_ia32_selectpbf_256:
12829 case X86::BI__builtin_ia32_selectpbf_512:
12830 case X86::BI__builtin_ia32_selectps_128:
12831 case X86::BI__builtin_ia32_selectps_256:
12832 case X86::BI__builtin_ia32_selectps_512:
12833 case X86::BI__builtin_ia32_selectpd_128:
12834 case X86::BI__builtin_ia32_selectpd_256:
12835 case X86::BI__builtin_ia32_selectpd_512: {
12836 // AVX512 predicated move: "Result = Mask[] ? LHS[] : RHS[]".
12837 APValue SourceMask, SourceLHS, SourceRHS;
12838 if (!EvaluateAsRValue(Info, E->getArg(0), SourceMask) ||
12839 !EvaluateAsRValue(Info, E->getArg(1), SourceLHS) ||
12840 !EvaluateAsRValue(Info, E->getArg(2), SourceRHS))
12841 return false;
12842
12843 APSInt Mask = SourceMask.getInt();
12844 unsigned SourceLen = SourceLHS.getVectorLength();
12845 SmallVector<APValue, 4> ResultElements;
12846 ResultElements.reserve(SourceLen);
12847
12848 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12849 const APValue &LHS = SourceLHS.getVectorElt(EltNum);
12850 const APValue &RHS = SourceRHS.getVectorElt(EltNum);
12851 ResultElements.push_back(Mask[EltNum] ? LHS : RHS);
12852 }
12853
12854 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12855 }
12856 case X86::BI__builtin_ia32_shufps:
12857 case X86::BI__builtin_ia32_shufps256:
12858 case X86::BI__builtin_ia32_shufps512: {
12859 APValue R;
12860 if (!evalShuffleGeneric(
12861 Info, E, R,
12862 [](unsigned DstIdx,
12863 unsigned ShuffleMask) -> std::pair<unsigned, int> {
12864 constexpr unsigned LaneBits = 128u;
12865 unsigned NumElemPerLane = LaneBits / 32;
12866 unsigned NumSelectableElems = NumElemPerLane / 2;
12867 unsigned BitsPerElem = 2;
12868 unsigned IndexMask = (1u << BitsPerElem) - 1;
12869 unsigned MaskBits = 8;
12870 unsigned Lane = DstIdx / NumElemPerLane;
12871 unsigned ElemInLane = DstIdx % NumElemPerLane;
12872 unsigned LaneOffset = Lane * NumElemPerLane;
12873 unsigned BitIndex = (DstIdx * BitsPerElem) % MaskBits;
12874 unsigned SrcIdx = (ElemInLane < NumSelectableElems) ? 0 : 1;
12875 unsigned Index = (ShuffleMask >> BitIndex) & IndexMask;
12876 return {SrcIdx, static_cast<int>(LaneOffset + Index)};
12877 }))
12878 return false;
12879 return Success(R, E);
12880 }
12881 case X86::BI__builtin_ia32_shufpd:
12882 case X86::BI__builtin_ia32_shufpd256:
12883 case X86::BI__builtin_ia32_shufpd512: {
12884 APValue R;
12885 if (!evalShuffleGeneric(
12886 Info, E, R,
12887 [](unsigned DstIdx,
12888 unsigned ShuffleMask) -> std::pair<unsigned, int> {
12889 constexpr unsigned LaneBits = 128u;
12890 unsigned NumElemPerLane = LaneBits / 64;
12891 unsigned NumSelectableElems = NumElemPerLane / 2;
12892 unsigned BitsPerElem = 1;
12893 unsigned IndexMask = (1u << BitsPerElem) - 1;
12894 unsigned MaskBits = 8;
12895 unsigned Lane = DstIdx / NumElemPerLane;
12896 unsigned ElemInLane = DstIdx % NumElemPerLane;
12897 unsigned LaneOffset = Lane * NumElemPerLane;
12898 unsigned BitIndex = (DstIdx * BitsPerElem) % MaskBits;
12899 unsigned SrcIdx = (ElemInLane < NumSelectableElems) ? 0 : 1;
12900 unsigned Index = (ShuffleMask >> BitIndex) & IndexMask;
12901 return {SrcIdx, static_cast<int>(LaneOffset + Index)};
12902 }))
12903 return false;
12904 return Success(R, E);
12905 }
12906 case X86::BI__builtin_ia32_insertps128: {
12907 APValue R;
12908 if (!evalShuffleGeneric(
12909 Info, E, R,
12910 [](unsigned DstIdx, unsigned Mask) -> std::pair<unsigned, int> {
12911 // Bits [3:0]: zero mask - if bit is set, zero this element
12912 if ((Mask & (1 << DstIdx)) != 0) {
12913 return {0, -1};
12914 }
12915 // Bits [7:6]: select element from source vector Y (0-3)
12916 // Bits [5:4]: select destination position (0-3)
12917 unsigned SrcElem = (Mask >> 6) & 0x3;
12918 unsigned DstElem = (Mask >> 4) & 0x3;
12919 if (DstIdx == DstElem) {
12920 // Insert element from source vector (B) at this position
12921 return {1, static_cast<int>(SrcElem)};
12922 } else {
12923 // Copy from destination vector (A)
12924 return {0, static_cast<int>(DstIdx)};
12925 }
12926 }))
12927 return false;
12928 return Success(R, E);
12929 }
12930 case X86::BI__builtin_ia32_pshufb128:
12931 case X86::BI__builtin_ia32_pshufb256:
12932 case X86::BI__builtin_ia32_pshufb512: {
12933 APValue R;
12934 if (!evalShuffleGeneric(
12935 Info, E, R,
12936 [](unsigned DstIdx,
12937 unsigned ShuffleMask) -> std::pair<unsigned, int> {
12938 uint8_t Ctlb = static_cast<uint8_t>(ShuffleMask);
12939 if (Ctlb & 0x80)
12940 return std::make_pair(0, -1);
12941
12942 unsigned LaneBase = (DstIdx / 16) * 16;
12943 unsigned SrcOffset = Ctlb & 0x0F;
12944 unsigned SrcIdx = LaneBase + SrcOffset;
12945 return std::make_pair(0, static_cast<int>(SrcIdx));
12946 }))
12947 return false;
12948 return Success(R, E);
12949 }
12950
12951 case X86::BI__builtin_ia32_pshuflw:
12952 case X86::BI__builtin_ia32_pshuflw256:
12953 case X86::BI__builtin_ia32_pshuflw512: {
12954 APValue R;
12955 if (!evalShuffleGeneric(
12956 Info, E, R,
12957 [](unsigned DstIdx, unsigned Mask) -> std::pair<unsigned, int> {
12958 constexpr unsigned LaneBits = 128u;
12959 constexpr unsigned ElemBits = 16u;
12960 constexpr unsigned LaneElts = LaneBits / ElemBits;
12961 constexpr unsigned HalfSize = 4;
12962 unsigned LaneBase = (DstIdx / LaneElts) * LaneElts;
12963 unsigned LaneIdx = DstIdx % LaneElts;
12964 if (LaneIdx < HalfSize) {
12965 unsigned Sel = (Mask >> (2 * LaneIdx)) & 0x3;
12966 return std::make_pair(0, static_cast<int>(LaneBase + Sel));
12967 }
12968 return std::make_pair(0, static_cast<int>(DstIdx));
12969 }))
12970 return false;
12971 return Success(R, E);
12972 }
12973
12974 case X86::BI__builtin_ia32_pshufhw:
12975 case X86::BI__builtin_ia32_pshufhw256:
12976 case X86::BI__builtin_ia32_pshufhw512: {
12977 APValue R;
12978 if (!evalShuffleGeneric(
12979 Info, E, R,
12980 [](unsigned DstIdx, unsigned Mask) -> std::pair<unsigned, int> {
12981 constexpr unsigned LaneBits = 128u;
12982 constexpr unsigned ElemBits = 16u;
12983 constexpr unsigned LaneElts = LaneBits / ElemBits;
12984 constexpr unsigned HalfSize = 4;
12985 unsigned LaneBase = (DstIdx / LaneElts) * LaneElts;
12986 unsigned LaneIdx = DstIdx % LaneElts;
12987 if (LaneIdx >= HalfSize) {
12988 unsigned Rel = LaneIdx - HalfSize;
12989 unsigned Sel = (Mask >> (2 * Rel)) & 0x3;
12990 return std::make_pair(
12991 0, static_cast<int>(LaneBase + HalfSize + Sel));
12992 }
12993 return std::make_pair(0, static_cast<int>(DstIdx));
12994 }))
12995 return false;
12996 return Success(R, E);
12997 }
12998
12999 case X86::BI__builtin_ia32_pshufd:
13000 case X86::BI__builtin_ia32_pshufd256:
13001 case X86::BI__builtin_ia32_pshufd512: {
13002 APValue R;
13003 if (!evalShuffleGeneric(
13004 Info, E, R,
13005 [](unsigned DstIdx, unsigned Mask) -> std::pair<unsigned, int> {
13006 constexpr unsigned LaneBits = 128u;
13007 constexpr unsigned ElemBits = 32u;
13008 constexpr unsigned LaneElts = LaneBits / ElemBits;
13009 unsigned LaneBase = (DstIdx / LaneElts) * LaneElts;
13010 unsigned LaneIdx = DstIdx % LaneElts;
13011 unsigned Sel = (Mask >> (2 * LaneIdx)) & 0x3;
13012 return std::make_pair(0, static_cast<int>(LaneBase + Sel));
13013 }))
13014 return false;
13015 return Success(R, E);
13016 }
13017
13018 case X86::BI__builtin_ia32_phminposuw128: {
13019 APValue Source;
13020 if (!Evaluate(Source, Info, E->getArg(0)))
13021 return false;
13022 unsigned SourceLen = Source.getVectorLength();
13023 const VectorType *VT = E->getArg(0)->getType()->castAs<VectorType>();
13024 QualType ElemQT = VT->getElementType();
13025 unsigned ElemBitWidth = Info.Ctx.getTypeSize(ElemQT);
13026
13027 APInt MinIndex(ElemBitWidth, 0);
13028 APInt MinVal = Source.getVectorElt(0).getInt();
13029 for (unsigned I = 1; I != SourceLen; ++I) {
13030 APInt Val = Source.getVectorElt(I).getInt();
13031 if (MinVal.ugt(Val)) {
13032 MinVal = Val;
13033 MinIndex = I;
13034 }
13035 }
13036
13037 bool ResultUnsigned = E->getCallReturnType(Info.Ctx)
13038 ->castAs<VectorType>()
13039 ->getElementType()
13040 ->isUnsignedIntegerOrEnumerationType();
13041
13043 Result.reserve(SourceLen);
13044 Result.emplace_back(APSInt(MinVal, ResultUnsigned));
13045 Result.emplace_back(APSInt(MinIndex, ResultUnsigned));
13046 for (unsigned I = 0; I != SourceLen - 2; ++I) {
13047 Result.emplace_back(APSInt(APInt(ElemBitWidth, 0), ResultUnsigned));
13048 }
13049 return Success(APValue(Result.data(), Result.size()), E);
13050 }
13051
13052 case X86::BI__builtin_ia32_pternlogd128_mask:
13053 case X86::BI__builtin_ia32_pternlogd256_mask:
13054 case X86::BI__builtin_ia32_pternlogd512_mask:
13055 case X86::BI__builtin_ia32_pternlogq128_mask:
13056 case X86::BI__builtin_ia32_pternlogq256_mask:
13057 case X86::BI__builtin_ia32_pternlogq512_mask: {
13058 APValue AValue, BValue, CValue, ImmValue, UValue;
13059 if (!EvaluateAsRValue(Info, E->getArg(0), AValue) ||
13060 !EvaluateAsRValue(Info, E->getArg(1), BValue) ||
13061 !EvaluateAsRValue(Info, E->getArg(2), CValue) ||
13062 !EvaluateAsRValue(Info, E->getArg(3), ImmValue) ||
13063 !EvaluateAsRValue(Info, E->getArg(4), UValue))
13064 return false;
13065
13066 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
13067 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
13068 APInt Imm = ImmValue.getInt();
13069 APInt U = UValue.getInt();
13070 unsigned ResultLen = AValue.getVectorLength();
13071 SmallVector<APValue, 16> ResultElements;
13072 ResultElements.reserve(ResultLen);
13073
13074 for (unsigned EltNum = 0; EltNum < ResultLen; ++EltNum) {
13075 APInt ALane = AValue.getVectorElt(EltNum).getInt();
13076 APInt BLane = BValue.getVectorElt(EltNum).getInt();
13077 APInt CLane = CValue.getVectorElt(EltNum).getInt();
13078
13079 if (U[EltNum]) {
13080 unsigned BitWidth = ALane.getBitWidth();
13081 APInt ResLane(BitWidth, 0);
13082
13083 for (unsigned Bit = 0; Bit < BitWidth; ++Bit) {
13084 unsigned ABit = ALane[Bit];
13085 unsigned BBit = BLane[Bit];
13086 unsigned CBit = CLane[Bit];
13087
13088 unsigned Idx = (ABit << 2) | (BBit << 1) | CBit;
13089 ResLane.setBitVal(Bit, Imm[Idx]);
13090 }
13091 ResultElements.push_back(APValue(APSInt(ResLane, DestUnsigned)));
13092 } else {
13093 ResultElements.push_back(APValue(APSInt(ALane, DestUnsigned)));
13094 }
13095 }
13096 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13097 }
13098 case X86::BI__builtin_ia32_pternlogd128_maskz:
13099 case X86::BI__builtin_ia32_pternlogd256_maskz:
13100 case X86::BI__builtin_ia32_pternlogd512_maskz:
13101 case X86::BI__builtin_ia32_pternlogq128_maskz:
13102 case X86::BI__builtin_ia32_pternlogq256_maskz:
13103 case X86::BI__builtin_ia32_pternlogq512_maskz: {
13104 APValue AValue, BValue, CValue, ImmValue, UValue;
13105 if (!EvaluateAsRValue(Info, E->getArg(0), AValue) ||
13106 !EvaluateAsRValue(Info, E->getArg(1), BValue) ||
13107 !EvaluateAsRValue(Info, E->getArg(2), CValue) ||
13108 !EvaluateAsRValue(Info, E->getArg(3), ImmValue) ||
13109 !EvaluateAsRValue(Info, E->getArg(4), UValue))
13110 return false;
13111
13112 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
13113 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
13114 APInt Imm = ImmValue.getInt();
13115 APInt U = UValue.getInt();
13116 unsigned ResultLen = AValue.getVectorLength();
13117 SmallVector<APValue, 16> ResultElements;
13118 ResultElements.reserve(ResultLen);
13119
13120 for (unsigned EltNum = 0; EltNum < ResultLen; ++EltNum) {
13121 APInt ALane = AValue.getVectorElt(EltNum).getInt();
13122 APInt BLane = BValue.getVectorElt(EltNum).getInt();
13123 APInt CLane = CValue.getVectorElt(EltNum).getInt();
13124
13125 unsigned BitWidth = ALane.getBitWidth();
13126 APInt ResLane(BitWidth, 0);
13127
13128 if (U[EltNum]) {
13129 for (unsigned Bit = 0; Bit < BitWidth; ++Bit) {
13130 unsigned ABit = ALane[Bit];
13131 unsigned BBit = BLane[Bit];
13132 unsigned CBit = CLane[Bit];
13133
13134 unsigned Idx = (ABit << 2) | (BBit << 1) | CBit;
13135 ResLane.setBitVal(Bit, Imm[Idx]);
13136 }
13137 }
13138 ResultElements.push_back(APValue(APSInt(ResLane, DestUnsigned)));
13139 }
13140 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13141 }
13142
13143 case Builtin::BI__builtin_elementwise_clzg:
13144 case Builtin::BI__builtin_elementwise_ctzg: {
13145 APValue SourceLHS;
13146 std::optional<APValue> Fallback;
13147 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS))
13148 return false;
13149 if (E->getNumArgs() > 1) {
13150 APValue FallbackTmp;
13151 if (!EvaluateAsRValue(Info, E->getArg(1), FallbackTmp))
13152 return false;
13153 Fallback = FallbackTmp;
13154 }
13155
13156 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
13157 unsigned SourceLen = SourceLHS.getVectorLength();
13158 SmallVector<APValue, 4> ResultElements;
13159 ResultElements.reserve(SourceLen);
13160
13161 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
13162 APSInt LHS = SourceLHS.getVectorElt(EltNum).getInt();
13163 if (!LHS) {
13164 // Without a fallback, a zero element is undefined
13165 if (!Fallback) {
13166 Info.FFDiag(E, diag::note_constexpr_countzeroes_zero)
13167 << /*IsTrailing=*/(E->getBuiltinCallee() ==
13168 Builtin::BI__builtin_elementwise_ctzg);
13169 return false;
13170 }
13171 ResultElements.push_back(Fallback->getVectorElt(EltNum));
13172 continue;
13173 }
13174 switch (E->getBuiltinCallee()) {
13175 case Builtin::BI__builtin_elementwise_clzg:
13176 ResultElements.push_back(APValue(
13177 APSInt(APInt(Info.Ctx.getIntWidth(DestEltTy), LHS.countl_zero()),
13178 DestEltTy->isUnsignedIntegerOrEnumerationType())));
13179 break;
13180 case Builtin::BI__builtin_elementwise_ctzg:
13181 ResultElements.push_back(APValue(
13182 APSInt(APInt(Info.Ctx.getIntWidth(DestEltTy), LHS.countr_zero()),
13183 DestEltTy->isUnsignedIntegerOrEnumerationType())));
13184 break;
13185 }
13186 }
13187
13188 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13189 }
13190
13191 case Builtin::BI__builtin_elementwise_fma: {
13192 APValue SourceX, SourceY, SourceZ;
13193 if (!EvaluateAsRValue(Info, E->getArg(0), SourceX) ||
13194 !EvaluateAsRValue(Info, E->getArg(1), SourceY) ||
13195 !EvaluateAsRValue(Info, E->getArg(2), SourceZ))
13196 return false;
13197
13198 unsigned SourceLen = SourceX.getVectorLength();
13199 SmallVector<APValue> ResultElements;
13200 ResultElements.reserve(SourceLen);
13201 llvm::RoundingMode RM = getActiveRoundingMode(getEvalInfo(), E);
13202 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
13203 const APFloat &X = SourceX.getVectorElt(EltNum).getFloat();
13204 const APFloat &Y = SourceY.getVectorElt(EltNum).getFloat();
13205 const APFloat &Z = SourceZ.getVectorElt(EltNum).getFloat();
13206 APFloat Result(X);
13207 (void)Result.fusedMultiplyAdd(Y, Z, RM);
13208 ResultElements.push_back(APValue(Result));
13209 }
13210 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13211 }
13212
13213 case clang::X86::BI__builtin_ia32_phaddw128:
13214 case clang::X86::BI__builtin_ia32_phaddw256:
13215 case clang::X86::BI__builtin_ia32_phaddd128:
13216 case clang::X86::BI__builtin_ia32_phaddd256:
13217 case clang::X86::BI__builtin_ia32_phaddsw128:
13218 case clang::X86::BI__builtin_ia32_phaddsw256:
13219
13220 case clang::X86::BI__builtin_ia32_phsubw128:
13221 case clang::X86::BI__builtin_ia32_phsubw256:
13222 case clang::X86::BI__builtin_ia32_phsubd128:
13223 case clang::X86::BI__builtin_ia32_phsubd256:
13224 case clang::X86::BI__builtin_ia32_phsubsw128:
13225 case clang::X86::BI__builtin_ia32_phsubsw256: {
13226 APValue SourceLHS, SourceRHS;
13227 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
13228 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
13229 return false;
13230 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
13231 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
13232
13233 unsigned NumElts = SourceLHS.getVectorLength();
13234 unsigned EltBits = Info.Ctx.getIntWidth(DestEltTy);
13235 unsigned EltsPerLane = 128 / EltBits;
13236 SmallVector<APValue, 4> ResultElements;
13237 ResultElements.reserve(NumElts);
13238
13239 for (unsigned LaneStart = 0; LaneStart != NumElts;
13240 LaneStart += EltsPerLane) {
13241 for (unsigned I = 0; I != EltsPerLane; I += 2) {
13242 APSInt LHSA = SourceLHS.getVectorElt(LaneStart + I).getInt();
13243 APSInt LHSB = SourceLHS.getVectorElt(LaneStart + I + 1).getInt();
13244 switch (E->getBuiltinCallee()) {
13245 case clang::X86::BI__builtin_ia32_phaddw128:
13246 case clang::X86::BI__builtin_ia32_phaddw256:
13247 case clang::X86::BI__builtin_ia32_phaddd128:
13248 case clang::X86::BI__builtin_ia32_phaddd256: {
13249 APSInt Res(LHSA + LHSB, DestUnsigned);
13250 ResultElements.push_back(APValue(Res));
13251 break;
13252 }
13253 case clang::X86::BI__builtin_ia32_phaddsw128:
13254 case clang::X86::BI__builtin_ia32_phaddsw256: {
13255 APSInt Res(LHSA.sadd_sat(LHSB));
13256 ResultElements.push_back(APValue(Res));
13257 break;
13258 }
13259 case clang::X86::BI__builtin_ia32_phsubw128:
13260 case clang::X86::BI__builtin_ia32_phsubw256:
13261 case clang::X86::BI__builtin_ia32_phsubd128:
13262 case clang::X86::BI__builtin_ia32_phsubd256: {
13263 APSInt Res(LHSA - LHSB, DestUnsigned);
13264 ResultElements.push_back(APValue(Res));
13265 break;
13266 }
13267 case clang::X86::BI__builtin_ia32_phsubsw128:
13268 case clang::X86::BI__builtin_ia32_phsubsw256: {
13269 APSInt Res(LHSA.ssub_sat(LHSB));
13270 ResultElements.push_back(APValue(Res));
13271 break;
13272 }
13273 }
13274 }
13275 for (unsigned I = 0; I != EltsPerLane; I += 2) {
13276 APSInt RHSA = SourceRHS.getVectorElt(LaneStart + I).getInt();
13277 APSInt RHSB = SourceRHS.getVectorElt(LaneStart + I + 1).getInt();
13278 switch (E->getBuiltinCallee()) {
13279 case clang::X86::BI__builtin_ia32_phaddw128:
13280 case clang::X86::BI__builtin_ia32_phaddw256:
13281 case clang::X86::BI__builtin_ia32_phaddd128:
13282 case clang::X86::BI__builtin_ia32_phaddd256: {
13283 APSInt Res(RHSA + RHSB, DestUnsigned);
13284 ResultElements.push_back(APValue(Res));
13285 break;
13286 }
13287 case clang::X86::BI__builtin_ia32_phaddsw128:
13288 case clang::X86::BI__builtin_ia32_phaddsw256: {
13289 APSInt Res(RHSA.sadd_sat(RHSB));
13290 ResultElements.push_back(APValue(Res));
13291 break;
13292 }
13293 case clang::X86::BI__builtin_ia32_phsubw128:
13294 case clang::X86::BI__builtin_ia32_phsubw256:
13295 case clang::X86::BI__builtin_ia32_phsubd128:
13296 case clang::X86::BI__builtin_ia32_phsubd256: {
13297 APSInt Res(RHSA - RHSB, DestUnsigned);
13298 ResultElements.push_back(APValue(Res));
13299 break;
13300 }
13301 case clang::X86::BI__builtin_ia32_phsubsw128:
13302 case clang::X86::BI__builtin_ia32_phsubsw256: {
13303 APSInt Res(RHSA.ssub_sat(RHSB));
13304 ResultElements.push_back(APValue(Res));
13305 break;
13306 }
13307 }
13308 }
13309 }
13310 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13311 }
13312 case clang::X86::BI__builtin_ia32_haddpd:
13313 case clang::X86::BI__builtin_ia32_haddps:
13314 case clang::X86::BI__builtin_ia32_haddps256:
13315 case clang::X86::BI__builtin_ia32_haddpd256:
13316 case clang::X86::BI__builtin_ia32_hsubpd:
13317 case clang::X86::BI__builtin_ia32_hsubps:
13318 case clang::X86::BI__builtin_ia32_hsubps256:
13319 case clang::X86::BI__builtin_ia32_hsubpd256: {
13320 APValue SourceLHS, SourceRHS;
13321 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
13322 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
13323 return false;
13324 unsigned NumElts = SourceLHS.getVectorLength();
13325 SmallVector<APValue, 4> ResultElements;
13326 ResultElements.reserve(NumElts);
13327 llvm::RoundingMode RM = getActiveRoundingMode(getEvalInfo(), E);
13328 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
13329 unsigned EltBits = Info.Ctx.getTypeSize(DestEltTy);
13330 unsigned NumLanes = NumElts * EltBits / 128;
13331 unsigned NumElemsPerLane = NumElts / NumLanes;
13332 unsigned HalfElemsPerLane = NumElemsPerLane / 2;
13333
13334 for (unsigned L = 0; L != NumElts; L += NumElemsPerLane) {
13335 for (unsigned I = 0; I != HalfElemsPerLane; ++I) {
13336 APFloat LHSA = SourceLHS.getVectorElt(L + (2 * I) + 0).getFloat();
13337 APFloat LHSB = SourceLHS.getVectorElt(L + (2 * I) + 1).getFloat();
13338 switch (E->getBuiltinCallee()) {
13339 case clang::X86::BI__builtin_ia32_haddpd:
13340 case clang::X86::BI__builtin_ia32_haddps:
13341 case clang::X86::BI__builtin_ia32_haddps256:
13342 case clang::X86::BI__builtin_ia32_haddpd256:
13343 LHSA.add(LHSB, RM);
13344 break;
13345 case clang::X86::BI__builtin_ia32_hsubpd:
13346 case clang::X86::BI__builtin_ia32_hsubps:
13347 case clang::X86::BI__builtin_ia32_hsubps256:
13348 case clang::X86::BI__builtin_ia32_hsubpd256:
13349 LHSA.subtract(LHSB, RM);
13350 break;
13351 }
13352 ResultElements.push_back(APValue(LHSA));
13353 }
13354 for (unsigned I = 0; I != HalfElemsPerLane; ++I) {
13355 APFloat RHSA = SourceRHS.getVectorElt(L + (2 * I) + 0).getFloat();
13356 APFloat RHSB = SourceRHS.getVectorElt(L + (2 * I) + 1).getFloat();
13357 switch (E->getBuiltinCallee()) {
13358 case clang::X86::BI__builtin_ia32_haddpd:
13359 case clang::X86::BI__builtin_ia32_haddps:
13360 case clang::X86::BI__builtin_ia32_haddps256:
13361 case clang::X86::BI__builtin_ia32_haddpd256:
13362 RHSA.add(RHSB, RM);
13363 break;
13364 case clang::X86::BI__builtin_ia32_hsubpd:
13365 case clang::X86::BI__builtin_ia32_hsubps:
13366 case clang::X86::BI__builtin_ia32_hsubps256:
13367 case clang::X86::BI__builtin_ia32_hsubpd256:
13368 RHSA.subtract(RHSB, RM);
13369 break;
13370 }
13371 ResultElements.push_back(APValue(RHSA));
13372 }
13373 }
13374 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13375 }
13376 case Builtin::BI__builtin_elementwise_fshl:
13377 case Builtin::BI__builtin_elementwise_fshr: {
13378 APValue SourceHi, SourceLo, SourceShift;
13379 if (!EvaluateAsRValue(Info, E->getArg(0), SourceHi) ||
13380 !EvaluateAsRValue(Info, E->getArg(1), SourceLo) ||
13381 !EvaluateAsRValue(Info, E->getArg(2), SourceShift))
13382 return false;
13383
13384 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
13385 if (!DestEltTy->isIntegerType())
13386 return false;
13387
13388 unsigned SourceLen = SourceHi.getVectorLength();
13389 SmallVector<APValue> ResultElements;
13390 ResultElements.reserve(SourceLen);
13391 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
13392 const APSInt &Hi = SourceHi.getVectorElt(EltNum).getInt();
13393 const APSInt &Lo = SourceLo.getVectorElt(EltNum).getInt();
13394 const APSInt &Shift = SourceShift.getVectorElt(EltNum).getInt();
13395 switch (E->getBuiltinCallee()) {
13396 case Builtin::BI__builtin_elementwise_fshl:
13397 ResultElements.push_back(APValue(
13398 APSInt(llvm::APIntOps::fshl(Hi, Lo, Shift), Hi.isUnsigned())));
13399 break;
13400 case Builtin::BI__builtin_elementwise_fshr:
13401 ResultElements.push_back(APValue(
13402 APSInt(llvm::APIntOps::fshr(Hi, Lo, Shift), Hi.isUnsigned())));
13403 break;
13404 }
13405 }
13406
13407 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13408 }
13409
13410 case X86::BI__builtin_ia32_insertf32x4_256:
13411 case X86::BI__builtin_ia32_inserti32x4_256:
13412 case X86::BI__builtin_ia32_insertf64x2_256:
13413 case X86::BI__builtin_ia32_inserti64x2_256:
13414 case X86::BI__builtin_ia32_insertf32x4:
13415 case X86::BI__builtin_ia32_inserti32x4:
13416 case X86::BI__builtin_ia32_insertf64x2_512:
13417 case X86::BI__builtin_ia32_inserti64x2_512:
13418 case X86::BI__builtin_ia32_insertf32x8:
13419 case X86::BI__builtin_ia32_inserti32x8:
13420 case X86::BI__builtin_ia32_insertf64x4:
13421 case X86::BI__builtin_ia32_inserti64x4:
13422 case X86::BI__builtin_ia32_vinsertf128_ps256:
13423 case X86::BI__builtin_ia32_vinsertf128_pd256:
13424 case X86::BI__builtin_ia32_vinsertf128_si256:
13425 case X86::BI__builtin_ia32_insert128i256: {
13426 APValue SourceDst, SourceSub;
13427 if (!EvaluateAsRValue(Info, E->getArg(0), SourceDst) ||
13428 !EvaluateAsRValue(Info, E->getArg(1), SourceSub))
13429 return false;
13430
13431 APSInt Imm;
13432 if (!EvaluateInteger(E->getArg(2), Imm, Info))
13433 return false;
13434
13435 assert(SourceDst.isVector() && SourceSub.isVector());
13436 unsigned DstLen = SourceDst.getVectorLength();
13437 unsigned SubLen = SourceSub.getVectorLength();
13438 assert(SubLen != 0 && DstLen != 0 && (DstLen % SubLen) == 0);
13439 unsigned NumLanes = DstLen / SubLen;
13440 unsigned LaneIdx = (Imm.getZExtValue() % NumLanes) * SubLen;
13441
13442 SmallVector<APValue, 16> ResultElements;
13443 ResultElements.reserve(DstLen);
13444
13445 for (unsigned EltNum = 0; EltNum < DstLen; ++EltNum) {
13446 if (EltNum >= LaneIdx && EltNum < LaneIdx + SubLen)
13447 ResultElements.push_back(SourceSub.getVectorElt(EltNum - LaneIdx));
13448 else
13449 ResultElements.push_back(SourceDst.getVectorElt(EltNum));
13450 }
13451
13452 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13453 }
13454
13455 case clang::X86::BI__builtin_ia32_vec_set_v4hi:
13456 case clang::X86::BI__builtin_ia32_vec_set_v16qi:
13457 case clang::X86::BI__builtin_ia32_vec_set_v8hi:
13458 case clang::X86::BI__builtin_ia32_vec_set_v4si:
13459 case clang::X86::BI__builtin_ia32_vec_set_v2di:
13460 case clang::X86::BI__builtin_ia32_vec_set_v32qi:
13461 case clang::X86::BI__builtin_ia32_vec_set_v16hi:
13462 case clang::X86::BI__builtin_ia32_vec_set_v8si:
13463 case clang::X86::BI__builtin_ia32_vec_set_v4di: {
13464 APValue VecVal;
13465 APSInt Scalar, IndexAPS;
13466 if (!EvaluateVector(E->getArg(0), VecVal, Info) ||
13467 !EvaluateInteger(E->getArg(1), Scalar, Info) ||
13468 !EvaluateInteger(E->getArg(2), IndexAPS, Info))
13469 return false;
13470
13471 QualType ElemTy = E->getType()->castAs<VectorType>()->getElementType();
13472 unsigned ElemWidth = Info.Ctx.getIntWidth(ElemTy);
13473 bool ElemUnsigned = ElemTy->isUnsignedIntegerOrEnumerationType();
13474 Scalar.setIsUnsigned(ElemUnsigned);
13475 APSInt ElemAPS = Scalar.extOrTrunc(ElemWidth);
13476 APValue ElemAV(ElemAPS);
13477
13478 unsigned NumElems = VecVal.getVectorLength();
13479 unsigned Index =
13480 static_cast<unsigned>(IndexAPS.getZExtValue() & (NumElems - 1));
13481
13483 Elems.reserve(NumElems);
13484 for (unsigned ElemNum = 0; ElemNum != NumElems; ++ElemNum)
13485 Elems.push_back(ElemNum == Index ? ElemAV : VecVal.getVectorElt(ElemNum));
13486
13487 return Success(APValue(Elems.data(), NumElems), E);
13488 }
13489
13490 case X86::BI__builtin_ia32_pslldqi128_byteshift:
13491 case X86::BI__builtin_ia32_pslldqi256_byteshift:
13492 case X86::BI__builtin_ia32_pslldqi512_byteshift: {
13493 APValue R;
13494 if (!evalShuffleGeneric(
13495 Info, E, R,
13496 [](unsigned DstIdx, unsigned Shift) -> std::pair<unsigned, int> {
13497 unsigned LaneBase = (DstIdx / 16) * 16;
13498 unsigned LaneIdx = DstIdx % 16;
13499 if (LaneIdx < Shift)
13500 return std::make_pair(0, -1);
13501
13502 return std::make_pair(
13503 0, static_cast<int>(LaneBase + LaneIdx - Shift));
13504 }))
13505 return false;
13506 return Success(R, E);
13507 }
13508
13509 case X86::BI__builtin_ia32_psrldqi128_byteshift:
13510 case X86::BI__builtin_ia32_psrldqi256_byteshift:
13511 case X86::BI__builtin_ia32_psrldqi512_byteshift: {
13512 APValue R;
13513 if (!evalShuffleGeneric(
13514 Info, E, R,
13515 [](unsigned DstIdx, unsigned Shift) -> std::pair<unsigned, int> {
13516 unsigned LaneBase = (DstIdx / 16) * 16;
13517 unsigned LaneIdx = DstIdx % 16;
13518 if (LaneIdx + Shift < 16)
13519 return std::make_pair(
13520 0, static_cast<int>(LaneBase + LaneIdx + Shift));
13521
13522 return std::make_pair(0, -1);
13523 }))
13524 return false;
13525 return Success(R, E);
13526 }
13527
13528 case X86::BI__builtin_ia32_palignr128:
13529 case X86::BI__builtin_ia32_palignr256:
13530 case X86::BI__builtin_ia32_palignr512: {
13531 APValue R;
13532 if (!evalShuffleGeneric(Info, E, R, [](unsigned DstIdx, unsigned Shift) {
13533 // Default to -1 → zero-fill this destination element
13534 unsigned VecIdx = 1;
13535 int ElemIdx = -1;
13536
13537 int Lane = DstIdx / 16;
13538 int Offset = DstIdx % 16;
13539
13540 // Elements come from VecB first, then VecA after the shift boundary
13541 unsigned ShiftedIdx = Offset + (Shift & 0xFF);
13542 if (ShiftedIdx < 16) { // from VecB
13543 ElemIdx = ShiftedIdx + (Lane * 16);
13544 } else if (ShiftedIdx < 32) { // from VecA
13545 VecIdx = 0;
13546 ElemIdx = (ShiftedIdx - 16) + (Lane * 16);
13547 }
13548
13549 return std::pair<unsigned, int>{VecIdx, ElemIdx};
13550 }))
13551 return false;
13552 return Success(R, E);
13553 }
13554 case X86::BI__builtin_ia32_vpermi2varq128:
13555 case X86::BI__builtin_ia32_vpermi2varpd128: {
13556 APValue R;
13557 if (!evalShuffleGeneric(Info, E, R,
13558 [](unsigned DstIdx, unsigned ShuffleMask) {
13559 int Offset = ShuffleMask & 0x1;
13560 unsigned SrcIdx = (ShuffleMask >> 1) & 0x1;
13561 return std::pair<unsigned, int>{SrcIdx, Offset};
13562 }))
13563 return false;
13564 return Success(R, E);
13565 }
13566 case X86::BI__builtin_ia32_vpermi2vard128:
13567 case X86::BI__builtin_ia32_vpermi2varps128:
13568 case X86::BI__builtin_ia32_vpermi2varq256:
13569 case X86::BI__builtin_ia32_vpermi2varpd256: {
13570 APValue R;
13571 if (!evalShuffleGeneric(Info, E, R,
13572 [](unsigned DstIdx, unsigned ShuffleMask) {
13573 int Offset = ShuffleMask & 0x3;
13574 unsigned SrcIdx = (ShuffleMask >> 2) & 0x1;
13575 return std::pair<unsigned, int>{SrcIdx, Offset};
13576 }))
13577 return false;
13578 return Success(R, E);
13579 }
13580 case X86::BI__builtin_ia32_vpermi2varhi128:
13581 case X86::BI__builtin_ia32_vpermi2vard256:
13582 case X86::BI__builtin_ia32_vpermi2varps256:
13583 case X86::BI__builtin_ia32_vpermi2varq512:
13584 case X86::BI__builtin_ia32_vpermi2varpd512: {
13585 APValue R;
13586 if (!evalShuffleGeneric(Info, E, R,
13587 [](unsigned DstIdx, unsigned ShuffleMask) {
13588 int Offset = ShuffleMask & 0x7;
13589 unsigned SrcIdx = (ShuffleMask >> 3) & 0x1;
13590 return std::pair<unsigned, int>{SrcIdx, Offset};
13591 }))
13592 return false;
13593 return Success(R, E);
13594 }
13595 case X86::BI__builtin_ia32_vpermi2varqi128:
13596 case X86::BI__builtin_ia32_vpermi2varhi256:
13597 case X86::BI__builtin_ia32_vpermi2vard512:
13598 case X86::BI__builtin_ia32_vpermi2varps512: {
13599 APValue R;
13600 if (!evalShuffleGeneric(Info, E, R,
13601 [](unsigned DstIdx, unsigned ShuffleMask) {
13602 int Offset = ShuffleMask & 0xF;
13603 unsigned SrcIdx = (ShuffleMask >> 4) & 0x1;
13604 return std::pair<unsigned, int>{SrcIdx, Offset};
13605 }))
13606 return false;
13607 return Success(R, E);
13608 }
13609 case X86::BI__builtin_ia32_vpermi2varqi256:
13610 case X86::BI__builtin_ia32_vpermi2varhi512: {
13611 APValue R;
13612 if (!evalShuffleGeneric(Info, E, R,
13613 [](unsigned DstIdx, unsigned ShuffleMask) {
13614 int Offset = ShuffleMask & 0x1F;
13615 unsigned SrcIdx = (ShuffleMask >> 5) & 0x1;
13616 return std::pair<unsigned, int>{SrcIdx, Offset};
13617 }))
13618 return false;
13619 return Success(R, E);
13620 }
13621 case X86::BI__builtin_ia32_vpermi2varqi512: {
13622 APValue R;
13623 if (!evalShuffleGeneric(Info, E, R,
13624 [](unsigned DstIdx, unsigned ShuffleMask) {
13625 int Offset = ShuffleMask & 0x3F;
13626 unsigned SrcIdx = (ShuffleMask >> 6) & 0x1;
13627 return std::pair<unsigned, int>{SrcIdx, Offset};
13628 }))
13629 return false;
13630 return Success(R, E);
13631 }
13632 }
13633}
13634
13635bool VectorExprEvaluator::VisitConvertVectorExpr(const ConvertVectorExpr *E) {
13636 APValue Source;
13637 QualType SourceVecType = E->getSrcExpr()->getType();
13638 if (!EvaluateAsRValue(Info, E->getSrcExpr(), Source))
13639 return false;
13640
13641 QualType DestTy = E->getType()->castAs<VectorType>()->getElementType();
13642 QualType SourceTy = SourceVecType->castAs<VectorType>()->getElementType();
13643
13644 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
13645
13646 auto SourceLen = Source.getVectorLength();
13647 SmallVector<APValue, 4> ResultElements;
13648 ResultElements.reserve(SourceLen);
13649 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
13650 APValue Elt;
13651 if (!handleVectorElementCast(Info, FPO, E, SourceTy, DestTy,
13652 Source.getVectorElt(EltNum), Elt))
13653 return false;
13654 ResultElements.push_back(std::move(Elt));
13655 }
13656
13657 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13658}
13659
13660static bool handleVectorShuffle(EvalInfo &Info, const ShuffleVectorExpr *E,
13661 QualType ElemType, APValue const &VecVal1,
13662 APValue const &VecVal2, unsigned EltNum,
13663 APValue &Result) {
13664 unsigned const TotalElementsInInputVector1 = VecVal1.getVectorLength();
13665 unsigned const TotalElementsInInputVector2 = VecVal2.getVectorLength();
13666
13667 APSInt IndexVal = E->getShuffleMaskIdx(EltNum);
13668 int64_t index = IndexVal.getExtValue();
13669 // The spec says that -1 should be treated as undef for optimizations,
13670 // but in constexpr we'd have to produce an APValue::Indeterminate,
13671 // which is prohibited from being a top-level constant value. Emit a
13672 // diagnostic instead.
13673 if (index == -1) {
13674 Info.FFDiag(
13675 E, diag::err_shufflevector_minus_one_is_undefined_behavior_constexpr)
13676 << EltNum;
13677 return false;
13678 }
13679
13680 if (index < 0 ||
13681 index >= TotalElementsInInputVector1 + TotalElementsInInputVector2)
13682 llvm_unreachable("Out of bounds shuffle index");
13683
13684 if (index >= TotalElementsInInputVector1)
13685 Result = VecVal2.getVectorElt(index - TotalElementsInInputVector1);
13686 else
13687 Result = VecVal1.getVectorElt(index);
13688 return true;
13689}
13690
13691bool VectorExprEvaluator::VisitShuffleVectorExpr(const ShuffleVectorExpr *E) {
13692 // FIXME: Unary shuffle with mask not currently supported.
13693 if (E->getNumSubExprs() == 2)
13694 return Error(E);
13695 APValue VecVal1;
13696 const Expr *Vec1 = E->getExpr(0);
13697 if (!EvaluateAsRValue(Info, Vec1, VecVal1))
13698 return false;
13699 APValue VecVal2;
13700 const Expr *Vec2 = E->getExpr(1);
13701 if (!EvaluateAsRValue(Info, Vec2, VecVal2))
13702 return false;
13703
13704 VectorType const *DestVecTy = E->getType()->castAs<VectorType>();
13705 QualType DestElTy = DestVecTy->getElementType();
13706
13707 auto TotalElementsInOutputVector = DestVecTy->getNumElements();
13708
13709 SmallVector<APValue, 4> ResultElements;
13710 ResultElements.reserve(TotalElementsInOutputVector);
13711 for (unsigned EltNum = 0; EltNum < TotalElementsInOutputVector; ++EltNum) {
13712 APValue Elt;
13713 if (!handleVectorShuffle(Info, E, DestElTy, VecVal1, VecVal2, EltNum, Elt))
13714 return false;
13715 ResultElements.push_back(std::move(Elt));
13716 }
13717
13718 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13719}
13720
13721//===----------------------------------------------------------------------===//
13722// Array Evaluation
13723//===----------------------------------------------------------------------===//
13724
13725namespace {
13726 class ArrayExprEvaluator
13727 : public ExprEvaluatorBase<ArrayExprEvaluator> {
13728 const LValue &This;
13729 APValue &Result;
13730 public:
13731
13732 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
13733 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
13734
13735 bool Success(const APValue &V, const Expr *E) {
13736 assert(V.isArray() && "expected array");
13737 Result = V;
13738 return true;
13739 }
13740
13741 bool ZeroInitialization(const Expr *E) {
13742 const ConstantArrayType *CAT =
13743 Info.Ctx.getAsConstantArrayType(E->getType());
13744 if (!CAT) {
13745 if (E->getType()->isIncompleteArrayType()) {
13746 // We can be asked to zero-initialize a flexible array member; this
13747 // is represented as an ImplicitValueInitExpr of incomplete array
13748 // type. In this case, the array has zero elements.
13749 Result = APValue(APValue::UninitArray(), 0, 0);
13750 return true;
13751 }
13752 // FIXME: We could handle VLAs here.
13753 return Error(E);
13754 }
13755
13756 Result = APValue(APValue::UninitArray(), 0, CAT->getZExtSize());
13757 if (!Result.hasArrayFiller())
13758 return true;
13759
13760 // Zero-initialize all elements.
13761 LValue Subobject = This;
13762 Subobject.addArray(Info, E, CAT);
13763 ImplicitValueInitExpr VIE(CAT->getElementType());
13764 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
13765 }
13766
13767 bool VisitCallExpr(const CallExpr *E) {
13768 return handleCallExpr(E, Result, &This);
13769 }
13770 bool VisitCastExpr(const CastExpr *E);
13771 bool VisitInitListExpr(const InitListExpr *E,
13772 QualType AllocType = QualType());
13773 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
13774 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
13775 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
13776 const LValue &Subobject,
13777 APValue *Value, QualType Type);
13778 bool VisitStringLiteral(const StringLiteral *E,
13779 QualType AllocType = QualType()) {
13780 expandStringLiteral(Info, E, Result, AllocType);
13781 return true;
13782 }
13783 bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E);
13784 bool VisitCXXParenListOrInitListExpr(const Expr *ExprToVisit,
13785 ArrayRef<Expr *> Args,
13786 const Expr *ArrayFiller,
13787 QualType AllocType = QualType());
13788 };
13789} // end anonymous namespace
13790
13791static bool EvaluateArray(const Expr *E, const LValue &This,
13792 APValue &Result, EvalInfo &Info) {
13793 assert(!E->isValueDependent());
13794 assert(E->isPRValue() && E->getType()->isArrayType() &&
13795 "not an array prvalue");
13796 return ArrayExprEvaluator(Info, This, Result).Visit(E);
13797}
13798
13799static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
13800 APValue &Result, const InitListExpr *ILE,
13801 QualType AllocType) {
13802 assert(!ILE->isValueDependent());
13803 assert(ILE->isPRValue() && ILE->getType()->isArrayType() &&
13804 "not an array prvalue");
13805 return ArrayExprEvaluator(Info, This, Result)
13806 .VisitInitListExpr(ILE, AllocType);
13807}
13808
13809static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
13810 APValue &Result,
13811 const CXXConstructExpr *CCE,
13812 QualType AllocType) {
13813 assert(!CCE->isValueDependent());
13814 assert(CCE->isPRValue() && CCE->getType()->isArrayType() &&
13815 "not an array prvalue");
13816 return ArrayExprEvaluator(Info, This, Result)
13817 .VisitCXXConstructExpr(CCE, This, &Result, AllocType);
13818}
13819
13820// Return true iff the given array filler may depend on the element index.
13821static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
13822 // For now, just allow non-class value-initialization and initialization
13823 // lists comprised of them.
13824 if (isa<ImplicitValueInitExpr>(FillerExpr))
13825 return false;
13826 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
13827 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
13828 if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
13829 return true;
13830 }
13831
13832 if (ILE->hasArrayFiller() &&
13833 MaybeElementDependentArrayFiller(ILE->getArrayFiller()))
13834 return true;
13835
13836 return false;
13837 }
13838 return true;
13839}
13840
13841bool ArrayExprEvaluator::VisitCastExpr(const CastExpr *E) {
13842 const Expr *SE = E->getSubExpr();
13843
13844 switch (E->getCastKind()) {
13845 default:
13846 return ExprEvaluatorBaseTy::VisitCastExpr(E);
13847 case CK_HLSLAggregateSplatCast: {
13848 APValue Val;
13849 QualType ValTy;
13850
13851 if (!hlslAggSplatHelper(Info, SE, Val, ValTy))
13852 return false;
13853
13854 unsigned NEls = elementwiseSize(Info, E->getType());
13855
13856 SmallVector<APValue> SplatEls(NEls, Val);
13857 SmallVector<QualType> SplatType(NEls, ValTy);
13858
13859 // cast the elements
13860 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
13861 if (!constructAggregate(Info, FPO, E, Result, E->getType(), SplatEls,
13862 SplatType))
13863 return false;
13864
13865 return true;
13866 }
13867 case CK_HLSLElementwiseCast: {
13868 SmallVector<APValue> SrcEls;
13869 SmallVector<QualType> SrcTypes;
13870
13871 if (!hlslElementwiseCastHelper(Info, SE, E->getType(), SrcEls, SrcTypes))
13872 return false;
13873
13874 // cast the elements
13875 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
13876 if (!constructAggregate(Info, FPO, E, Result, E->getType(), SrcEls,
13877 SrcTypes))
13878 return false;
13879 return true;
13880 }
13881 }
13882}
13883
13884bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E,
13885 QualType AllocType) {
13886 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
13887 AllocType.isNull() ? E->getType() : AllocType);
13888 if (!CAT)
13889 return Error(E);
13890
13891 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
13892 // an appropriately-typed string literal enclosed in braces.
13893 if (E->isStringLiteralInit()) {
13894 auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParenImpCasts());
13895 // FIXME: Support ObjCEncodeExpr here once we support it in
13896 // ArrayExprEvaluator generally.
13897 if (!SL)
13898 return Error(E);
13899 return VisitStringLiteral(SL, AllocType);
13900 }
13901 // Any other transparent list init will need proper handling of the
13902 // AllocType; we can't just recurse to the inner initializer.
13903 assert(!E->isTransparent() &&
13904 "transparent array list initialization is not string literal init?");
13905
13906 return VisitCXXParenListOrInitListExpr(E, E->inits(), E->getArrayFiller(),
13907 AllocType);
13908}
13909
13910bool ArrayExprEvaluator::VisitCXXParenListOrInitListExpr(
13911 const Expr *ExprToVisit, ArrayRef<Expr *> Args, const Expr *ArrayFiller,
13912 QualType AllocType) {
13913 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
13914 AllocType.isNull() ? ExprToVisit->getType() : AllocType);
13915
13916 bool Success = true;
13917
13918 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
13919 "zero-initialized array shouldn't have any initialized elts");
13920 APValue Filler;
13921 if (Result.isArray() && Result.hasArrayFiller())
13922 Filler = Result.getArrayFiller();
13923
13924 unsigned NumEltsToInit = Args.size();
13925 unsigned NumElts = CAT->getZExtSize();
13926
13927 // If the initializer might depend on the array index, run it for each
13928 // array element.
13929 if (NumEltsToInit != NumElts &&
13930 MaybeElementDependentArrayFiller(ArrayFiller)) {
13931 NumEltsToInit = NumElts;
13932 } else {
13933 for (auto *Init : Args) {
13934 if (auto *EmbedS = dyn_cast<EmbedExpr>(Init->IgnoreParenImpCasts()))
13935 NumEltsToInit += EmbedS->getDataElementCount() - 1;
13936 }
13937 if (NumEltsToInit > NumElts)
13938 NumEltsToInit = NumElts;
13939 }
13940
13941 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
13942 << NumEltsToInit << ".\n");
13943
13944 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
13945
13946 // If the array was previously zero-initialized, preserve the
13947 // zero-initialized values.
13948 if (Filler.hasValue()) {
13949 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
13950 Result.getArrayInitializedElt(I) = Filler;
13951 if (Result.hasArrayFiller())
13952 Result.getArrayFiller() = Filler;
13953 }
13954
13955 LValue Subobject = This;
13956 Subobject.addArray(Info, ExprToVisit, CAT);
13957 auto Eval = [&](const Expr *Init, unsigned ArrayIndex) {
13958 if (Init->isValueDependent())
13959 return EvaluateDependentExpr(Init, Info);
13960
13961 if (!EvaluateInPlace(Result.getArrayInitializedElt(ArrayIndex), Info,
13962 Subobject, Init) ||
13963 !HandleLValueArrayAdjustment(Info, Init, Subobject,
13964 CAT->getElementType(), 1)) {
13965 if (!Info.noteFailure())
13966 return false;
13967 Success = false;
13968 }
13969 return true;
13970 };
13971 unsigned ArrayIndex = 0;
13972 QualType DestTy = CAT->getElementType();
13973 APSInt Value(Info.Ctx.getTypeSize(DestTy), DestTy->isUnsignedIntegerType());
13974 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
13975 const Expr *Init = Index < Args.size() ? Args[Index] : ArrayFiller;
13976 if (ArrayIndex >= NumEltsToInit)
13977 break;
13978 if (auto *EmbedS = dyn_cast<EmbedExpr>(Init->IgnoreParenImpCasts())) {
13979 StringLiteral *SL = EmbedS->getDataStringLiteral();
13980 for (unsigned I = EmbedS->getStartingElementPos(),
13981 N = EmbedS->getDataElementCount();
13982 I != EmbedS->getStartingElementPos() + N; ++I) {
13983 Value = SL->getCodeUnit(I);
13984 if (DestTy->isIntegerType()) {
13985 Result.getArrayInitializedElt(ArrayIndex) = APValue(Value);
13986 } else {
13987 assert(DestTy->isFloatingType() && "unexpected type");
13988 const FPOptions FPO =
13989 Init->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
13990 APFloat FValue(0.0);
13991 if (!HandleIntToFloatCast(Info, Init, FPO, EmbedS->getType(), Value,
13992 DestTy, FValue))
13993 return false;
13994 Result.getArrayInitializedElt(ArrayIndex) = APValue(FValue);
13995 }
13996 ArrayIndex++;
13997 }
13998 } else {
13999 if (!Eval(Init, ArrayIndex))
14000 return false;
14001 ++ArrayIndex;
14002 }
14003 }
14004
14005 if (!Result.hasArrayFiller())
14006 return Success;
14007
14008 // If we get here, we have a trivial filler, which we can just evaluate
14009 // once and splat over the rest of the array elements.
14010 assert(ArrayFiller && "no array filler for incomplete init list");
14011 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
14012 ArrayFiller) &&
14013 Success;
14014}
14015
14016bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
14017 LValue CommonLV;
14018 if (E->getCommonExpr() &&
14019 !Evaluate(Info.CurrentCall->createTemporary(
14020 E->getCommonExpr(),
14021 getStorageType(Info.Ctx, E->getCommonExpr()),
14022 ScopeKind::FullExpression, CommonLV),
14023 Info, E->getCommonExpr()->getSourceExpr()))
14024 return false;
14025
14027
14028 uint64_t Elements = CAT->getZExtSize();
14029 Result = APValue(APValue::UninitArray(), Elements, Elements);
14030
14031 LValue Subobject = This;
14032 Subobject.addArray(Info, E, CAT);
14033
14034 bool Success = true;
14035 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
14036 // C++ [class.temporary]/5
14037 // There are four contexts in which temporaries are destroyed at a different
14038 // point than the end of the full-expression. [...] The second context is
14039 // when a copy constructor is called to copy an element of an array while
14040 // the entire array is copied [...]. In either case, if the constructor has
14041 // one or more default arguments, the destruction of every temporary created
14042 // in a default argument is sequenced before the construction of the next
14043 // array element, if any.
14044 FullExpressionRAII Scope(Info);
14045
14046 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
14047 Info, Subobject, E->getSubExpr()) ||
14048 !HandleLValueArrayAdjustment(Info, E, Subobject,
14049 CAT->getElementType(), 1)) {
14050 if (!Info.noteFailure())
14051 return false;
14052 Success = false;
14053 }
14054
14055 // Make sure we run the destructors too.
14056 Scope.destroy();
14057 }
14058
14059 return Success;
14060}
14061
14062bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
14063 return VisitCXXConstructExpr(E, This, &Result, E->getType());
14064}
14065
14066bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
14067 const LValue &Subobject,
14068 APValue *Value,
14069 QualType Type) {
14070 bool HadZeroInit = Value->hasValue();
14071
14072 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
14073 unsigned FinalSize = CAT->getZExtSize();
14074
14075 // Preserve the array filler if we had prior zero-initialization.
14076 APValue Filler =
14077 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
14078 : APValue();
14079
14080 *Value = APValue(APValue::UninitArray(), 0, FinalSize);
14081 if (FinalSize == 0)
14082 return true;
14083
14084 bool HasTrivialConstructor = CheckTrivialDefaultConstructor(
14085 Info, E->getExprLoc(), E->getConstructor(),
14087 LValue ArrayElt = Subobject;
14088 ArrayElt.addArray(Info, E, CAT);
14089 // We do the whole initialization in two passes, first for just one element,
14090 // then for the whole array. It's possible we may find out we can't do const
14091 // init in the first pass, in which case we avoid allocating a potentially
14092 // large array. We don't do more passes because expanding array requires
14093 // copying the data, which is wasteful.
14094 for (const unsigned N : {1u, FinalSize}) {
14095 unsigned OldElts = Value->getArrayInitializedElts();
14096 if (OldElts == N)
14097 break;
14098
14099 // Expand the array to appropriate size.
14100 APValue NewValue(APValue::UninitArray(), N, FinalSize);
14101 for (unsigned I = 0; I < OldElts; ++I)
14102 NewValue.getArrayInitializedElt(I).swap(
14103 Value->getArrayInitializedElt(I));
14104 Value->swap(NewValue);
14105
14106 if (HadZeroInit)
14107 for (unsigned I = OldElts; I < N; ++I)
14108 Value->getArrayInitializedElt(I) = Filler;
14109
14110 if (HasTrivialConstructor && N == FinalSize && FinalSize != 1) {
14111 // If we have a trivial constructor, only evaluate it once and copy
14112 // the result into all the array elements.
14113 APValue &FirstResult = Value->getArrayInitializedElt(0);
14114 for (unsigned I = OldElts; I < FinalSize; ++I)
14115 Value->getArrayInitializedElt(I) = FirstResult;
14116 } else {
14117 for (unsigned I = OldElts; I < N; ++I) {
14118 if (!VisitCXXConstructExpr(E, ArrayElt,
14119 &Value->getArrayInitializedElt(I),
14120 CAT->getElementType()) ||
14121 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
14122 CAT->getElementType(), 1))
14123 return false;
14124 // When checking for const initilization any diagnostic is considered
14125 // an error.
14126 if (Info.EvalStatus.Diag && !Info.EvalStatus.Diag->empty() &&
14127 !Info.keepEvaluatingAfterFailure())
14128 return false;
14129 }
14130 }
14131 }
14132
14133 return true;
14134 }
14135
14136 if (!Type->isRecordType())
14137 return Error(E);
14138
14139 return RecordExprEvaluator(Info, Subobject, *Value)
14140 .VisitCXXConstructExpr(E, Type);
14141}
14142
14143bool ArrayExprEvaluator::VisitCXXParenListInitExpr(
14144 const CXXParenListInitExpr *E) {
14145 assert(E->getType()->isConstantArrayType() &&
14146 "Expression result is not a constant array type");
14147
14148 return VisitCXXParenListOrInitListExpr(E, E->getInitExprs(),
14149 E->getArrayFiller());
14150}
14151
14152//===----------------------------------------------------------------------===//
14153// Integer Evaluation
14154//
14155// As a GNU extension, we support casting pointers to sufficiently-wide integer
14156// types and back in constant folding. Integer values are thus represented
14157// either as an integer-valued APValue, or as an lvalue-valued APValue.
14158//===----------------------------------------------------------------------===//
14159
14160namespace {
14161class IntExprEvaluator
14162 : public ExprEvaluatorBase<IntExprEvaluator> {
14163 APValue &Result;
14164public:
14165 IntExprEvaluator(EvalInfo &info, APValue &result)
14166 : ExprEvaluatorBaseTy(info), Result(result) {}
14167
14168 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
14169 assert(E->getType()->isIntegralOrEnumerationType() &&
14170 "Invalid evaluation result.");
14171 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
14172 "Invalid evaluation result.");
14173 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
14174 "Invalid evaluation result.");
14175 Result = APValue(SI);
14176 return true;
14177 }
14178 bool Success(const llvm::APSInt &SI, const Expr *E) {
14179 return Success(SI, E, Result);
14180 }
14181
14182 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
14183 assert(E->getType()->isIntegralOrEnumerationType() &&
14184 "Invalid evaluation result.");
14185 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
14186 "Invalid evaluation result.");
14187 Result = APValue(APSInt(I));
14188 Result.getInt().setIsUnsigned(
14190 return true;
14191 }
14192 bool Success(const llvm::APInt &I, const Expr *E) {
14193 return Success(I, E, Result);
14194 }
14195
14196 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
14197 assert(E->getType()->isIntegralOrEnumerationType() &&
14198 "Invalid evaluation result.");
14199 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
14200 return true;
14201 }
14202 bool Success(uint64_t Value, const Expr *E) {
14203 return Success(Value, E, Result);
14204 }
14205
14206 bool Success(CharUnits Size, const Expr *E) {
14207 return Success(Size.getQuantity(), E);
14208 }
14209
14210 bool Success(const APValue &V, const Expr *E) {
14211 // C++23 [expr.const]p8 If we have a variable that is unknown reference or
14212 // pointer allow further evaluation of the value.
14213 if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate() ||
14214 V.allowConstexprUnknown()) {
14215 Result = V;
14216 return true;
14217 }
14218 return Success(V.getInt(), E);
14219 }
14220
14221 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
14222
14223 friend std::optional<bool> EvaluateBuiltinIsWithinLifetime(IntExprEvaluator &,
14224 const CallExpr *);
14225
14226 //===--------------------------------------------------------------------===//
14227 // Visitor Methods
14228 //===--------------------------------------------------------------------===//
14229
14230 bool VisitIntegerLiteral(const IntegerLiteral *E) {
14231 return Success(E->getValue(), E);
14232 }
14233 bool VisitCharacterLiteral(const CharacterLiteral *E) {
14234 return Success(E->getValue(), E);
14235 }
14236
14237 bool CheckReferencedDecl(const Expr *E, const Decl *D);
14238 bool VisitDeclRefExpr(const DeclRefExpr *E) {
14239 if (CheckReferencedDecl(E, E->getDecl()))
14240 return true;
14241
14242 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
14243 }
14244 bool VisitMemberExpr(const MemberExpr *E) {
14245 if (CheckReferencedDecl(E, E->getMemberDecl())) {
14246 VisitIgnoredBaseExpression(E->getBase());
14247 return true;
14248 }
14249
14250 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
14251 }
14252
14253 bool VisitCallExpr(const CallExpr *E);
14254 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
14255 bool VisitBinaryOperator(const BinaryOperator *E);
14256 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
14257 bool VisitUnaryOperator(const UnaryOperator *E);
14258
14259 bool VisitCastExpr(const CastExpr* E);
14260 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
14261
14262 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
14263 return Success(E->getValue(), E);
14264 }
14265
14266 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
14267 return Success(E->getValue(), E);
14268 }
14269
14270 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
14271 if (Info.ArrayInitIndex == uint64_t(-1)) {
14272 // We were asked to evaluate this subexpression independent of the
14273 // enclosing ArrayInitLoopExpr. We can't do that.
14274 Info.FFDiag(E);
14275 return false;
14276 }
14277 return Success(Info.ArrayInitIndex, E);
14278 }
14279
14280 // Note, GNU defines __null as an integer, not a pointer.
14281 bool VisitGNUNullExpr(const GNUNullExpr *E) {
14282 return ZeroInitialization(E);
14283 }
14284
14285 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
14286 if (E->isStoredAsBoolean())
14287 return Success(E->getBoolValue(), E);
14288 if (E->getAPValue().isAbsent())
14289 return false;
14290 assert(E->getAPValue().isInt() && "APValue type not supported");
14291 return Success(E->getAPValue().getInt(), E);
14292 }
14293
14294 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
14295 return Success(E->getValue(), E);
14296 }
14297
14298 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
14299 return Success(E->getValue(), E);
14300 }
14301
14302 bool VisitOpenACCAsteriskSizeExpr(const OpenACCAsteriskSizeExpr *E) {
14303 // This should not be evaluated during constant expr evaluation, as it
14304 // should always be in an unevaluated context (the args list of a 'gang' or
14305 // 'tile' clause).
14306 return Error(E);
14307 }
14308
14309 bool VisitUnaryReal(const UnaryOperator *E);
14310 bool VisitUnaryImag(const UnaryOperator *E);
14311
14312 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
14313 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
14314 bool VisitSourceLocExpr(const SourceLocExpr *E);
14315 bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E);
14316 bool VisitRequiresExpr(const RequiresExpr *E);
14317 // FIXME: Missing: array subscript of vector, member of vector
14318};
14319
14320class FixedPointExprEvaluator
14321 : public ExprEvaluatorBase<FixedPointExprEvaluator> {
14322 APValue &Result;
14323
14324 public:
14325 FixedPointExprEvaluator(EvalInfo &info, APValue &result)
14326 : ExprEvaluatorBaseTy(info), Result(result) {}
14327
14328 bool Success(const llvm::APInt &I, const Expr *E) {
14329 return Success(
14330 APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
14331 }
14332
14333 bool Success(uint64_t Value, const Expr *E) {
14334 return Success(
14335 APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
14336 }
14337
14338 bool Success(const APValue &V, const Expr *E) {
14339 return Success(V.getFixedPoint(), E);
14340 }
14341
14342 bool Success(const APFixedPoint &V, const Expr *E) {
14343 assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
14344 assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
14345 "Invalid evaluation result.");
14346 Result = APValue(V);
14347 return true;
14348 }
14349
14350 bool ZeroInitialization(const Expr *E) {
14351 return Success(0, E);
14352 }
14353
14354 //===--------------------------------------------------------------------===//
14355 // Visitor Methods
14356 //===--------------------------------------------------------------------===//
14357
14358 bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
14359 return Success(E->getValue(), E);
14360 }
14361
14362 bool VisitCastExpr(const CastExpr *E);
14363 bool VisitUnaryOperator(const UnaryOperator *E);
14364 bool VisitBinaryOperator(const BinaryOperator *E);
14365};
14366} // end anonymous namespace
14367
14368/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
14369/// produce either the integer value or a pointer.
14370///
14371/// GCC has a heinous extension which folds casts between pointer types and
14372/// pointer-sized integral types. We support this by allowing the evaluation of
14373/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
14374/// Some simple arithmetic on such values is supported (they are treated much
14375/// like char*).
14376static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
14377 EvalInfo &Info) {
14378 assert(!E->isValueDependent());
14379 assert(E->isPRValue() && E->getType()->isIntegralOrEnumerationType());
14380 return IntExprEvaluator(Info, Result).Visit(E);
14381}
14382
14383static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
14384 assert(!E->isValueDependent());
14385 APValue Val;
14386 if (!EvaluateIntegerOrLValue(E, Val, Info))
14387 return false;
14388 if (!Val.isInt()) {
14389 // FIXME: It would be better to produce the diagnostic for casting
14390 // a pointer to an integer.
14391 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
14392 return false;
14393 }
14394 Result = Val.getInt();
14395 return true;
14396}
14397
14398bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
14400 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
14401 return Success(Evaluated, E);
14402}
14403
14404static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
14405 EvalInfo &Info) {
14406 assert(!E->isValueDependent());
14407 if (E->getType()->isFixedPointType()) {
14408 APValue Val;
14409 if (!FixedPointExprEvaluator(Info, Val).Visit(E))
14410 return false;
14411 if (!Val.isFixedPoint())
14412 return false;
14413
14414 Result = Val.getFixedPoint();
14415 return true;
14416 }
14417 return false;
14418}
14419
14420static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
14421 EvalInfo &Info) {
14422 assert(!E->isValueDependent());
14423 if (E->getType()->isIntegerType()) {
14424 auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
14425 APSInt Val;
14426 if (!EvaluateInteger(E, Val, Info))
14427 return false;
14428 Result = APFixedPoint(Val, FXSema);
14429 return true;
14430 } else if (E->getType()->isFixedPointType()) {
14431 return EvaluateFixedPoint(E, Result, Info);
14432 }
14433 return false;
14434}
14435
14436/// Check whether the given declaration can be directly converted to an integral
14437/// rvalue. If not, no diagnostic is produced; there are other things we can
14438/// try.
14439bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
14440 // Enums are integer constant exprs.
14441 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
14442 // Check for signedness/width mismatches between E type and ECD value.
14443 bool SameSign = (ECD->getInitVal().isSigned()
14445 bool SameWidth = (ECD->getInitVal().getBitWidth()
14446 == Info.Ctx.getIntWidth(E->getType()));
14447 if (SameSign && SameWidth)
14448 return Success(ECD->getInitVal(), E);
14449 else {
14450 // Get rid of mismatch (otherwise Success assertions will fail)
14451 // by computing a new value matching the type of E.
14452 llvm::APSInt Val = ECD->getInitVal();
14453 if (!SameSign)
14454 Val.setIsSigned(!ECD->getInitVal().isSigned());
14455 if (!SameWidth)
14456 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
14457 return Success(Val, E);
14458 }
14459 }
14460 return false;
14461}
14462
14463/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
14464/// as GCC.
14466 const LangOptions &LangOpts) {
14467 assert(!T->isDependentType() && "unexpected dependent type");
14468
14469 QualType CanTy = T.getCanonicalType();
14470
14471 switch (CanTy->getTypeClass()) {
14472#define TYPE(ID, BASE)
14473#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
14474#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
14475#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
14476#include "clang/AST/TypeNodes.inc"
14477 case Type::Auto:
14478 case Type::DeducedTemplateSpecialization:
14479 llvm_unreachable("unexpected non-canonical or dependent type");
14480
14481 case Type::Builtin:
14482 switch (cast<BuiltinType>(CanTy)->getKind()) {
14483#define BUILTIN_TYPE(ID, SINGLETON_ID)
14484#define SIGNED_TYPE(ID, SINGLETON_ID) \
14485 case BuiltinType::ID: return GCCTypeClass::Integer;
14486#define FLOATING_TYPE(ID, SINGLETON_ID) \
14487 case BuiltinType::ID: return GCCTypeClass::RealFloat;
14488#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
14489 case BuiltinType::ID: break;
14490#include "clang/AST/BuiltinTypes.def"
14491 case BuiltinType::Void:
14492 return GCCTypeClass::Void;
14493
14494 case BuiltinType::Bool:
14495 return GCCTypeClass::Bool;
14496
14497 case BuiltinType::Char_U:
14498 case BuiltinType::UChar:
14499 case BuiltinType::WChar_U:
14500 case BuiltinType::Char8:
14501 case BuiltinType::Char16:
14502 case BuiltinType::Char32:
14503 case BuiltinType::UShort:
14504 case BuiltinType::UInt:
14505 case BuiltinType::ULong:
14506 case BuiltinType::ULongLong:
14507 case BuiltinType::UInt128:
14508 return GCCTypeClass::Integer;
14509
14510 case BuiltinType::UShortAccum:
14511 case BuiltinType::UAccum:
14512 case BuiltinType::ULongAccum:
14513 case BuiltinType::UShortFract:
14514 case BuiltinType::UFract:
14515 case BuiltinType::ULongFract:
14516 case BuiltinType::SatUShortAccum:
14517 case BuiltinType::SatUAccum:
14518 case BuiltinType::SatULongAccum:
14519 case BuiltinType::SatUShortFract:
14520 case BuiltinType::SatUFract:
14521 case BuiltinType::SatULongFract:
14522 return GCCTypeClass::None;
14523
14524 case BuiltinType::NullPtr:
14525
14526 case BuiltinType::ObjCId:
14527 case BuiltinType::ObjCClass:
14528 case BuiltinType::ObjCSel:
14529#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
14530 case BuiltinType::Id:
14531#include "clang/Basic/OpenCLImageTypes.def"
14532#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
14533 case BuiltinType::Id:
14534#include "clang/Basic/OpenCLExtensionTypes.def"
14535 case BuiltinType::OCLSampler:
14536 case BuiltinType::OCLEvent:
14537 case BuiltinType::OCLClkEvent:
14538 case BuiltinType::OCLQueue:
14539 case BuiltinType::OCLReserveID:
14540#define SVE_TYPE(Name, Id, SingletonId) \
14541 case BuiltinType::Id:
14542#include "clang/Basic/AArch64ACLETypes.def"
14543#define PPC_VECTOR_TYPE(Name, Id, Size) \
14544 case BuiltinType::Id:
14545#include "clang/Basic/PPCTypes.def"
14546#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
14547#include "clang/Basic/RISCVVTypes.def"
14548#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
14549#include "clang/Basic/WebAssemblyReferenceTypes.def"
14550#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
14551#include "clang/Basic/AMDGPUTypes.def"
14552#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
14553#include "clang/Basic/HLSLIntangibleTypes.def"
14554 return GCCTypeClass::None;
14555
14556 case BuiltinType::Dependent:
14557 llvm_unreachable("unexpected dependent type");
14558 };
14559 llvm_unreachable("unexpected placeholder type");
14560
14561 case Type::Enum:
14562 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
14563
14564 case Type::Pointer:
14565 case Type::ConstantArray:
14566 case Type::VariableArray:
14567 case Type::IncompleteArray:
14568 case Type::FunctionNoProto:
14569 case Type::FunctionProto:
14570 case Type::ArrayParameter:
14571 return GCCTypeClass::Pointer;
14572
14573 case Type::MemberPointer:
14574 return CanTy->isMemberDataPointerType()
14577
14578 case Type::Complex:
14579 return GCCTypeClass::Complex;
14580
14581 case Type::Record:
14582 return CanTy->isUnionType() ? GCCTypeClass::Union
14584
14585 case Type::Atomic:
14586 // GCC classifies _Atomic T the same as T.
14588 CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
14589
14590 case Type::Vector:
14591 case Type::ExtVector:
14592 return GCCTypeClass::Vector;
14593
14594 case Type::BlockPointer:
14595 case Type::ConstantMatrix:
14596 case Type::ObjCObject:
14597 case Type::ObjCInterface:
14598 case Type::ObjCObjectPointer:
14599 case Type::Pipe:
14600 case Type::HLSLAttributedResource:
14601 case Type::HLSLInlineSpirv:
14602 // Classify all other types that don't fit into the regular
14603 // classification the same way.
14604 return GCCTypeClass::None;
14605
14606 case Type::BitInt:
14607 return GCCTypeClass::BitInt;
14608
14609 case Type::LValueReference:
14610 case Type::RValueReference:
14611 llvm_unreachable("invalid type for expression");
14612 }
14613
14614 llvm_unreachable("unexpected type class");
14615}
14616
14617/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
14618/// as GCC.
14619static GCCTypeClass
14621 // If no argument was supplied, default to None. This isn't
14622 // ideal, however it is what gcc does.
14623 if (E->getNumArgs() == 0)
14624 return GCCTypeClass::None;
14625
14626 // FIXME: Bizarrely, GCC treats a call with more than one argument as not
14627 // being an ICE, but still folds it to a constant using the type of the first
14628 // argument.
14629 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
14630}
14631
14632/// EvaluateBuiltinConstantPForLValue - Determine the result of
14633/// __builtin_constant_p when applied to the given pointer.
14634///
14635/// A pointer is only "constant" if it is null (or a pointer cast to integer)
14636/// or it points to the first character of a string literal.
14639 if (Base.isNull()) {
14640 // A null base is acceptable.
14641 return true;
14642 } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
14643 if (!isa<StringLiteral>(E))
14644 return false;
14645 return LV.getLValueOffset().isZero();
14646 } else if (Base.is<TypeInfoLValue>()) {
14647 // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
14648 // evaluate to true.
14649 return true;
14650 } else {
14651 // Any other base is not constant enough for GCC.
14652 return false;
14653 }
14654}
14655
14656/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
14657/// GCC as we can manage.
14658static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
14659 // This evaluation is not permitted to have side-effects, so evaluate it in
14660 // a speculative evaluation context.
14661 SpeculativeEvaluationRAII SpeculativeEval(Info);
14662
14663 // Constant-folding is always enabled for the operand of __builtin_constant_p
14664 // (even when the enclosing evaluation context otherwise requires a strict
14665 // language-specific constant expression).
14666 FoldConstant Fold(Info, true);
14667
14668 QualType ArgType = Arg->getType();
14669
14670 // __builtin_constant_p always has one operand. The rules which gcc follows
14671 // are not precisely documented, but are as follows:
14672 //
14673 // - If the operand is of integral, floating, complex or enumeration type,
14674 // and can be folded to a known value of that type, it returns 1.
14675 // - If the operand can be folded to a pointer to the first character
14676 // of a string literal (or such a pointer cast to an integral type)
14677 // or to a null pointer or an integer cast to a pointer, it returns 1.
14678 //
14679 // Otherwise, it returns 0.
14680 //
14681 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
14682 // its support for this did not work prior to GCC 9 and is not yet well
14683 // understood.
14684 if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
14685 ArgType->isAnyComplexType() || ArgType->isPointerType() ||
14686 ArgType->isNullPtrType()) {
14687 APValue V;
14688 if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) {
14689 Fold.keepDiagnostics();
14690 return false;
14691 }
14692
14693 // For a pointer (possibly cast to integer), there are special rules.
14694 if (V.getKind() == APValue::LValue)
14696
14697 // Otherwise, any constant value is good enough.
14698 return V.hasValue();
14699 }
14700
14701 // Anything else isn't considered to be sufficiently constant.
14702 return false;
14703}
14704
14705/// Retrieves the "underlying object type" of the given expression,
14706/// as used by __builtin_object_size.
14708 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
14709 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
14710 return VD->getType();
14711 } else if (const Expr *E = B.dyn_cast<const Expr*>()) {
14713 return E->getType();
14714 } else if (B.is<TypeInfoLValue>()) {
14715 return B.getTypeInfoType();
14716 } else if (B.is<DynamicAllocLValue>()) {
14717 return B.getDynamicAllocType();
14718 }
14719
14720 return QualType();
14721}
14722
14723/// A more selective version of E->IgnoreParenCasts for
14724/// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
14725/// to change the type of E.
14726/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
14727///
14728/// Always returns an RValue with a pointer representation.
14729static const Expr *ignorePointerCastsAndParens(const Expr *E) {
14730 assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
14731
14732 const Expr *NoParens = E->IgnoreParens();
14733 const auto *Cast = dyn_cast<CastExpr>(NoParens);
14734 if (Cast == nullptr)
14735 return NoParens;
14736
14737 // We only conservatively allow a few kinds of casts, because this code is
14738 // inherently a simple solution that seeks to support the common case.
14739 auto CastKind = Cast->getCastKind();
14740 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
14741 CastKind != CK_AddressSpaceConversion)
14742 return NoParens;
14743
14744 const auto *SubExpr = Cast->getSubExpr();
14745 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isPRValue())
14746 return NoParens;
14747 return ignorePointerCastsAndParens(SubExpr);
14748}
14749
14750/// Checks to see if the given LValue's Designator is at the end of the LValue's
14751/// record layout. e.g.
14752/// struct { struct { int a, b; } fst, snd; } obj;
14753/// obj.fst // no
14754/// obj.snd // yes
14755/// obj.fst.a // no
14756/// obj.fst.b // no
14757/// obj.snd.a // no
14758/// obj.snd.b // yes
14759///
14760/// Please note: this function is specialized for how __builtin_object_size
14761/// views "objects".
14762///
14763/// If this encounters an invalid RecordDecl or otherwise cannot determine the
14764/// correct result, it will always return true.
14765static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
14766 assert(!LVal.Designator.Invalid);
14767
14768 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD) {
14769 const RecordDecl *Parent = FD->getParent();
14770 if (Parent->isInvalidDecl() || Parent->isUnion())
14771 return true;
14772 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
14773 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
14774 };
14775
14776 auto &Base = LVal.getLValueBase();
14777 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
14778 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
14779 if (!IsLastOrInvalidFieldDecl(FD))
14780 return false;
14781 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
14782 for (auto *FD : IFD->chain()) {
14783 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD)))
14784 return false;
14785 }
14786 }
14787 }
14788
14789 unsigned I = 0;
14790 QualType BaseType = getType(Base);
14791 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
14792 // If we don't know the array bound, conservatively assume we're looking at
14793 // the final array element.
14794 ++I;
14795 if (BaseType->isIncompleteArrayType())
14796 BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
14797 else
14798 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
14799 }
14800
14801 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
14802 const auto &Entry = LVal.Designator.Entries[I];
14803 if (BaseType->isArrayType()) {
14804 // Because __builtin_object_size treats arrays as objects, we can ignore
14805 // the index iff this is the last array in the Designator.
14806 if (I + 1 == E)
14807 return true;
14808 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
14809 uint64_t Index = Entry.getAsArrayIndex();
14810 if (Index + 1 != CAT->getZExtSize())
14811 return false;
14812 BaseType = CAT->getElementType();
14813 } else if (BaseType->isAnyComplexType()) {
14814 const auto *CT = BaseType->castAs<ComplexType>();
14815 uint64_t Index = Entry.getAsArrayIndex();
14816 if (Index != 1)
14817 return false;
14818 BaseType = CT->getElementType();
14819 } else if (auto *FD = getAsField(Entry)) {
14820 if (!IsLastOrInvalidFieldDecl(FD))
14821 return false;
14822 BaseType = FD->getType();
14823 } else {
14824 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
14825 return false;
14826 }
14827 }
14828 return true;
14829}
14830
14831/// Tests to see if the LValue has a user-specified designator (that isn't
14832/// necessarily valid). Note that this always returns 'true' if the LValue has
14833/// an unsized array as its first designator entry, because there's currently no
14834/// way to tell if the user typed *foo or foo[0].
14835static bool refersToCompleteObject(const LValue &LVal) {
14836 if (LVal.Designator.Invalid)
14837 return false;
14838
14839 if (!LVal.Designator.Entries.empty())
14840 return LVal.Designator.isMostDerivedAnUnsizedArray();
14841
14842 if (!LVal.InvalidBase)
14843 return true;
14844
14845 // If `E` is a MemberExpr, then the first part of the designator is hiding in
14846 // the LValueBase.
14847 const auto *E = LVal.Base.dyn_cast<const Expr *>();
14848 return !E || !isa<MemberExpr>(E);
14849}
14850
14851/// Attempts to detect a user writing into a piece of memory that's impossible
14852/// to figure out the size of by just using types.
14853static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
14854 const SubobjectDesignator &Designator = LVal.Designator;
14855 // Notes:
14856 // - Users can only write off of the end when we have an invalid base. Invalid
14857 // bases imply we don't know where the memory came from.
14858 // - We used to be a bit more aggressive here; we'd only be conservative if
14859 // the array at the end was flexible, or if it had 0 or 1 elements. This
14860 // broke some common standard library extensions (PR30346), but was
14861 // otherwise seemingly fine. It may be useful to reintroduce this behavior
14862 // with some sort of list. OTOH, it seems that GCC is always
14863 // conservative with the last element in structs (if it's an array), so our
14864 // current behavior is more compatible than an explicit list approach would
14865 // be.
14866 auto isFlexibleArrayMember = [&] {
14868 FAMKind StrictFlexArraysLevel =
14869 Ctx.getLangOpts().getStrictFlexArraysLevel();
14870
14871 if (Designator.isMostDerivedAnUnsizedArray())
14872 return true;
14873
14874 if (StrictFlexArraysLevel == FAMKind::Default)
14875 return true;
14876
14877 if (Designator.getMostDerivedArraySize() == 0 &&
14878 StrictFlexArraysLevel != FAMKind::IncompleteOnly)
14879 return true;
14880
14881 if (Designator.getMostDerivedArraySize() == 1 &&
14882 StrictFlexArraysLevel == FAMKind::OneZeroOrIncomplete)
14883 return true;
14884
14885 return false;
14886 };
14887
14888 return LVal.InvalidBase &&
14889 Designator.Entries.size() == Designator.MostDerivedPathLength &&
14890 Designator.MostDerivedIsArrayElement && isFlexibleArrayMember() &&
14891 isDesignatorAtObjectEnd(Ctx, LVal);
14892}
14893
14894/// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
14895/// Fails if the conversion would cause loss of precision.
14896static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
14897 CharUnits &Result) {
14898 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
14899 if (Int.ugt(CharUnitsMax))
14900 return false;
14901 Result = CharUnits::fromQuantity(Int.getZExtValue());
14902 return true;
14903}
14904
14905/// If we're evaluating the object size of an instance of a struct that
14906/// contains a flexible array member, add the size of the initializer.
14907static void addFlexibleArrayMemberInitSize(EvalInfo &Info, const QualType &T,
14908 const LValue &LV, CharUnits &Size) {
14909 if (!T.isNull() && T->isStructureType() &&
14910 T->castAsRecordDecl()->hasFlexibleArrayMember())
14911 if (const auto *V = LV.getLValueBase().dyn_cast<const ValueDecl *>())
14912 if (const auto *VD = dyn_cast<VarDecl>(V))
14913 if (VD->hasInit())
14914 Size += VD->getFlexibleArrayInitChars(Info.Ctx);
14915}
14916
14917/// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
14918/// determine how many bytes exist from the beginning of the object to either
14919/// the end of the current subobject, or the end of the object itself, depending
14920/// on what the LValue looks like + the value of Type.
14921///
14922/// If this returns false, the value of Result is undefined.
14923static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
14924 unsigned Type, const LValue &LVal,
14925 CharUnits &EndOffset) {
14926 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
14927
14928 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
14929 if (Ty.isNull())
14930 return false;
14931
14932 Ty = Ty.getNonReferenceType();
14933
14934 if (Ty->isIncompleteType() || Ty->isFunctionType())
14935 return false;
14936
14937 return HandleSizeof(Info, ExprLoc, Ty, Result);
14938 };
14939
14940 // We want to evaluate the size of the entire object. This is a valid fallback
14941 // for when Type=1 and the designator is invalid, because we're asked for an
14942 // upper-bound.
14943 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
14944 // Type=3 wants a lower bound, so we can't fall back to this.
14945 if (Type == 3 && !DetermineForCompleteObject)
14946 return false;
14947
14948 llvm::APInt APEndOffset;
14949 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
14950 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
14951 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
14952
14953 if (LVal.InvalidBase)
14954 return false;
14955
14956 QualType BaseTy = getObjectType(LVal.getLValueBase());
14957 const bool Ret = CheckedHandleSizeof(BaseTy, EndOffset);
14958 addFlexibleArrayMemberInitSize(Info, BaseTy, LVal, EndOffset);
14959 return Ret;
14960 }
14961
14962 // We want to evaluate the size of a subobject.
14963 const SubobjectDesignator &Designator = LVal.Designator;
14964
14965 // The following is a moderately common idiom in C:
14966 //
14967 // struct Foo { int a; char c[1]; };
14968 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
14969 // strcpy(&F->c[0], Bar);
14970 //
14971 // In order to not break too much legacy code, we need to support it.
14972 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
14973 // If we can resolve this to an alloc_size call, we can hand that back,
14974 // because we know for certain how many bytes there are to write to.
14975 llvm::APInt APEndOffset;
14976 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
14977 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
14978 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
14979
14980 // If we cannot determine the size of the initial allocation, then we can't
14981 // given an accurate upper-bound. However, we are still able to give
14982 // conservative lower-bounds for Type=3.
14983 if (Type == 1)
14984 return false;
14985 }
14986
14987 CharUnits BytesPerElem;
14988 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
14989 return false;
14990
14991 // According to the GCC documentation, we want the size of the subobject
14992 // denoted by the pointer. But that's not quite right -- what we actually
14993 // want is the size of the immediately-enclosing array, if there is one.
14994 int64_t ElemsRemaining;
14995 if (Designator.MostDerivedIsArrayElement &&
14996 Designator.Entries.size() == Designator.MostDerivedPathLength) {
14997 uint64_t ArraySize = Designator.getMostDerivedArraySize();
14998 uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
14999 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
15000 } else {
15001 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
15002 }
15003
15004 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
15005 return true;
15006}
15007
15008/// Tries to evaluate the __builtin_object_size for @p E. If successful,
15009/// returns true and stores the result in @p Size.
15010///
15011/// If @p WasError is non-null, this will report whether the failure to evaluate
15012/// is to be treated as an Error in IntExprEvaluator.
15013static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
15014 EvalInfo &Info, uint64_t &Size) {
15015 // Determine the denoted object.
15016 LValue LVal;
15017 {
15018 // The operand of __builtin_object_size is never evaluated for side-effects.
15019 // If there are any, but we can determine the pointed-to object anyway, then
15020 // ignore the side-effects.
15021 SpeculativeEvaluationRAII SpeculativeEval(Info);
15022 IgnoreSideEffectsRAII Fold(Info);
15023
15024 if (E->isGLValue()) {
15025 // It's possible for us to be given GLValues if we're called via
15026 // Expr::tryEvaluateObjectSize.
15027 APValue RVal;
15028 if (!EvaluateAsRValue(Info, E, RVal))
15029 return false;
15030 LVal.setFrom(Info.Ctx, RVal);
15031 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
15032 /*InvalidBaseOK=*/true))
15033 return false;
15034 }
15035
15036 // If we point to before the start of the object, there are no accessible
15037 // bytes.
15038 if (LVal.getLValueOffset().isNegative()) {
15039 Size = 0;
15040 return true;
15041 }
15042
15043 CharUnits EndOffset;
15044 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
15045 return false;
15046
15047 // If we've fallen outside of the end offset, just pretend there's nothing to
15048 // write to/read from.
15049 if (EndOffset <= LVal.getLValueOffset())
15050 Size = 0;
15051 else
15052 Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
15053 return true;
15054}
15055
15056bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
15057 if (!IsConstantEvaluatedBuiltinCall(E))
15058 return ExprEvaluatorBaseTy::VisitCallExpr(E);
15059 return VisitBuiltinCallExpr(E, E->getBuiltinCallee());
15060}
15061
15062static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info,
15063 APValue &Val, APSInt &Alignment) {
15064 QualType SrcTy = E->getArg(0)->getType();
15065 if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment))
15066 return false;
15067 // Even though we are evaluating integer expressions we could get a pointer
15068 // argument for the __builtin_is_aligned() case.
15069 if (SrcTy->isPointerType()) {
15070 LValue Ptr;
15071 if (!EvaluatePointer(E->getArg(0), Ptr, Info))
15072 return false;
15073 Ptr.moveInto(Val);
15074 } else if (!SrcTy->isIntegralOrEnumerationType()) {
15075 Info.FFDiag(E->getArg(0));
15076 return false;
15077 } else {
15078 APSInt SrcInt;
15079 if (!EvaluateInteger(E->getArg(0), SrcInt, Info))
15080 return false;
15081 assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() &&
15082 "Bit widths must be the same");
15083 Val = APValue(SrcInt);
15084 }
15085 assert(Val.hasValue());
15086 return true;
15087}
15088
15089bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
15090 unsigned BuiltinOp) {
15091 auto EvalTestOp = [&](llvm::function_ref<bool(const APInt &, const APInt &)>
15092 Fn) {
15093 APValue SourceLHS, SourceRHS;
15094 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
15095 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
15096 return false;
15097
15098 unsigned SourceLen = SourceLHS.getVectorLength();
15099 const VectorType *VT = E->getArg(0)->getType()->castAs<VectorType>();
15100 QualType ElemQT = VT->getElementType();
15101 unsigned LaneWidth = Info.Ctx.getTypeSize(ElemQT);
15102
15103 APInt AWide(LaneWidth * SourceLen, 0);
15104 APInt BWide(LaneWidth * SourceLen, 0);
15105
15106 for (unsigned I = 0; I != SourceLen; ++I) {
15107 APInt ALane;
15108 APInt BLane;
15109 if (ElemQT->isIntegerType()) { // Get value.
15110 ALane = SourceLHS.getVectorElt(I).getInt();
15111 BLane = SourceRHS.getVectorElt(I).getInt();
15112 } else if (ElemQT->isFloatingType()) { // Get only sign bit.
15113 ALane =
15114 SourceLHS.getVectorElt(I).getFloat().bitcastToAPInt().isNegative();
15115 BLane =
15116 SourceRHS.getVectorElt(I).getFloat().bitcastToAPInt().isNegative();
15117 } else { // Must be integer or floating type.
15118 return false;
15119 }
15120 AWide.insertBits(ALane, I * LaneWidth);
15121 BWide.insertBits(BLane, I * LaneWidth);
15122 }
15123 return Success(Fn(AWide, BWide), E);
15124 };
15125
15126 auto HandleMaskBinOp =
15127 [&](llvm::function_ref<APSInt(const APSInt &, const APSInt &)> Fn)
15128 -> bool {
15129 APValue LHS, RHS;
15130 if (!Evaluate(LHS, Info, E->getArg(0)) ||
15131 !Evaluate(RHS, Info, E->getArg(1)))
15132 return false;
15133
15134 APSInt ResultInt = Fn(LHS.getInt(), RHS.getInt());
15135
15136 return Success(APValue(ResultInt), E);
15137 };
15138
15139 switch (BuiltinOp) {
15140 default:
15141 return false;
15142
15143 case Builtin::BI__builtin_dynamic_object_size:
15144 case Builtin::BI__builtin_object_size: {
15145 // The type was checked when we built the expression.
15146 unsigned Type =
15147 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
15148 assert(Type <= 3 && "unexpected type");
15149
15150 uint64_t Size;
15151 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
15152 return Success(Size, E);
15153
15154 if (E->getArg(0)->HasSideEffects(Info.Ctx))
15155 return Success((Type & 2) ? 0 : -1, E);
15156
15157 // Expression had no side effects, but we couldn't statically determine the
15158 // size of the referenced object.
15159 switch (Info.EvalMode) {
15160 case EvaluationMode::ConstantExpression:
15161 case EvaluationMode::ConstantFold:
15162 case EvaluationMode::IgnoreSideEffects:
15163 // Leave it to IR generation.
15164 return Error(E);
15165 case EvaluationMode::ConstantExpressionUnevaluated:
15166 // Reduce it to a constant now.
15167 return Success((Type & 2) ? 0 : -1, E);
15168 }
15169
15170 llvm_unreachable("unexpected EvalMode");
15171 }
15172
15173 case Builtin::BI__builtin_os_log_format_buffer_size: {
15174 analyze_os_log::OSLogBufferLayout Layout;
15175 analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
15176 return Success(Layout.size().getQuantity(), E);
15177 }
15178
15179 case Builtin::BI__builtin_is_aligned: {
15180 APValue Src;
15181 APSInt Alignment;
15182 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
15183 return false;
15184 if (Src.isLValue()) {
15185 // If we evaluated a pointer, check the minimum known alignment.
15186 LValue Ptr;
15187 Ptr.setFrom(Info.Ctx, Src);
15188 CharUnits BaseAlignment = getBaseAlignment(Info, Ptr);
15189 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset);
15190 // We can return true if the known alignment at the computed offset is
15191 // greater than the requested alignment.
15192 assert(PtrAlign.isPowerOfTwo());
15193 assert(Alignment.isPowerOf2());
15194 if (PtrAlign.getQuantity() >= Alignment)
15195 return Success(1, E);
15196 // If the alignment is not known to be sufficient, some cases could still
15197 // be aligned at run time. However, if the requested alignment is less or
15198 // equal to the base alignment and the offset is not aligned, we know that
15199 // the run-time value can never be aligned.
15200 if (BaseAlignment.getQuantity() >= Alignment &&
15201 PtrAlign.getQuantity() < Alignment)
15202 return Success(0, E);
15203 // Otherwise we can't infer whether the value is sufficiently aligned.
15204 // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N)
15205 // in cases where we can't fully evaluate the pointer.
15206 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute)
15207 << Alignment;
15208 return false;
15209 }
15210 assert(Src.isInt());
15211 return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E);
15212 }
15213 case Builtin::BI__builtin_align_up: {
15214 APValue Src;
15215 APSInt Alignment;
15216 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
15217 return false;
15218 if (!Src.isInt())
15219 return Error(E);
15220 APSInt AlignedVal =
15221 APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1),
15222 Src.getInt().isUnsigned());
15223 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
15224 return Success(AlignedVal, E);
15225 }
15226 case Builtin::BI__builtin_align_down: {
15227 APValue Src;
15228 APSInt Alignment;
15229 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
15230 return false;
15231 if (!Src.isInt())
15232 return Error(E);
15233 APSInt AlignedVal =
15234 APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned());
15235 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
15236 return Success(AlignedVal, E);
15237 }
15238
15239 case Builtin::BI__builtin_bitreverse8:
15240 case Builtin::BI__builtin_bitreverse16:
15241 case Builtin::BI__builtin_bitreverse32:
15242 case Builtin::BI__builtin_bitreverse64:
15243 case Builtin::BI__builtin_elementwise_bitreverse: {
15244 APSInt Val;
15245 if (!EvaluateInteger(E->getArg(0), Val, Info))
15246 return false;
15247
15248 return Success(Val.reverseBits(), E);
15249 }
15250
15251 case Builtin::BI__builtin_bswap16:
15252 case Builtin::BI__builtin_bswap32:
15253 case Builtin::BI__builtin_bswap64: {
15254 APSInt Val;
15255 if (!EvaluateInteger(E->getArg(0), Val, Info))
15256 return false;
15257
15258 return Success(Val.byteSwap(), E);
15259 }
15260
15261 case Builtin::BI__builtin_classify_type:
15262 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
15263
15264 case Builtin::BI__builtin_clrsb:
15265 case Builtin::BI__builtin_clrsbl:
15266 case Builtin::BI__builtin_clrsbll: {
15267 APSInt Val;
15268 if (!EvaluateInteger(E->getArg(0), Val, Info))
15269 return false;
15270
15271 return Success(Val.getBitWidth() - Val.getSignificantBits(), E);
15272 }
15273
15274 case Builtin::BI__builtin_clz:
15275 case Builtin::BI__builtin_clzl:
15276 case Builtin::BI__builtin_clzll:
15277 case Builtin::BI__builtin_clzs:
15278 case Builtin::BI__builtin_clzg:
15279 case Builtin::BI__builtin_elementwise_clzg:
15280 case Builtin::BI__lzcnt16: // Microsoft variants of count leading-zeroes
15281 case Builtin::BI__lzcnt:
15282 case Builtin::BI__lzcnt64: {
15283 APSInt Val;
15284 if (E->getArg(0)->getType()->isExtVectorBoolType()) {
15285 APValue Vec;
15286 if (!EvaluateVector(E->getArg(0), Vec, Info))
15287 return false;
15288 Val = ConvertBoolVectorToInt(Vec);
15289 } else if (!EvaluateInteger(E->getArg(0), Val, Info)) {
15290 return false;
15291 }
15292
15293 std::optional<APSInt> Fallback;
15294 if ((BuiltinOp == Builtin::BI__builtin_clzg ||
15295 BuiltinOp == Builtin::BI__builtin_elementwise_clzg) &&
15296 E->getNumArgs() > 1) {
15297 APSInt FallbackTemp;
15298 if (!EvaluateInteger(E->getArg(1), FallbackTemp, Info))
15299 return false;
15300 Fallback = FallbackTemp;
15301 }
15302
15303 if (!Val) {
15304 if (Fallback)
15305 return Success(*Fallback, E);
15306
15307 // When the argument is 0, the result of GCC builtins is undefined,
15308 // whereas for Microsoft intrinsics, the result is the bit-width of the
15309 // argument.
15310 bool ZeroIsUndefined = BuiltinOp != Builtin::BI__lzcnt16 &&
15311 BuiltinOp != Builtin::BI__lzcnt &&
15312 BuiltinOp != Builtin::BI__lzcnt64;
15313
15314 if (BuiltinOp == Builtin::BI__builtin_elementwise_clzg) {
15315 Info.FFDiag(E, diag::note_constexpr_countzeroes_zero)
15316 << /*IsTrailing=*/false;
15317 }
15318
15319 if (ZeroIsUndefined)
15320 return Error(E);
15321 }
15322
15323 return Success(Val.countl_zero(), E);
15324 }
15325
15326 case Builtin::BI__builtin_constant_p: {
15327 const Expr *Arg = E->getArg(0);
15328 if (EvaluateBuiltinConstantP(Info, Arg))
15329 return Success(true, E);
15330 if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
15331 // Outside a constant context, eagerly evaluate to false in the presence
15332 // of side-effects in order to avoid -Wunsequenced false-positives in
15333 // a branch on __builtin_constant_p(expr).
15334 return Success(false, E);
15335 }
15336 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
15337 return false;
15338 }
15339
15340 case Builtin::BI__noop:
15341 // __noop always evaluates successfully and returns 0.
15342 return Success(0, E);
15343
15344 case Builtin::BI__builtin_is_constant_evaluated: {
15345 const auto *Callee = Info.CurrentCall->getCallee();
15346 if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression &&
15347 (Info.CallStackDepth == 1 ||
15348 (Info.CallStackDepth == 2 && Callee->isInStdNamespace() &&
15349 Callee->getIdentifier() &&
15350 Callee->getIdentifier()->isStr("is_constant_evaluated")))) {
15351 // FIXME: Find a better way to avoid duplicated diagnostics.
15352 if (Info.EvalStatus.Diag)
15353 Info.report((Info.CallStackDepth == 1)
15354 ? E->getExprLoc()
15355 : Info.CurrentCall->getCallRange().getBegin(),
15356 diag::warn_is_constant_evaluated_always_true_constexpr)
15357 << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated"
15358 : "std::is_constant_evaluated");
15359 }
15360
15361 return Success(Info.InConstantContext, E);
15362 }
15363
15364 case Builtin::BI__builtin_is_within_lifetime:
15365 if (auto result = EvaluateBuiltinIsWithinLifetime(*this, E))
15366 return Success(*result, E);
15367 return false;
15368
15369 case Builtin::BI__builtin_ctz:
15370 case Builtin::BI__builtin_ctzl:
15371 case Builtin::BI__builtin_ctzll:
15372 case Builtin::BI__builtin_ctzs:
15373 case Builtin::BI__builtin_ctzg:
15374 case Builtin::BI__builtin_elementwise_ctzg: {
15375 APSInt Val;
15376 if (E->getArg(0)->getType()->isExtVectorBoolType()) {
15377 APValue Vec;
15378 if (!EvaluateVector(E->getArg(0), Vec, Info))
15379 return false;
15380 Val = ConvertBoolVectorToInt(Vec);
15381 } else if (!EvaluateInteger(E->getArg(0), Val, Info)) {
15382 return false;
15383 }
15384
15385 std::optional<APSInt> Fallback;
15386 if ((BuiltinOp == Builtin::BI__builtin_ctzg ||
15387 BuiltinOp == Builtin::BI__builtin_elementwise_ctzg) &&
15388 E->getNumArgs() > 1) {
15389 APSInt FallbackTemp;
15390 if (!EvaluateInteger(E->getArg(1), FallbackTemp, Info))
15391 return false;
15392 Fallback = FallbackTemp;
15393 }
15394
15395 if (!Val) {
15396 if (Fallback)
15397 return Success(*Fallback, E);
15398
15399 if (BuiltinOp == Builtin::BI__builtin_elementwise_ctzg) {
15400 Info.FFDiag(E, diag::note_constexpr_countzeroes_zero)
15401 << /*IsTrailing=*/true;
15402 }
15403 return Error(E);
15404 }
15405
15406 return Success(Val.countr_zero(), E);
15407 }
15408
15409 case Builtin::BI__builtin_eh_return_data_regno: {
15410 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
15411 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
15412 return Success(Operand, E);
15413 }
15414
15415 case Builtin::BI__builtin_elementwise_abs: {
15416 APSInt Val;
15417 if (!EvaluateInteger(E->getArg(0), Val, Info))
15418 return false;
15419
15420 return Success(Val.abs(), E);
15421 }
15422
15423 case Builtin::BI__builtin_expect:
15424 case Builtin::BI__builtin_expect_with_probability:
15425 return Visit(E->getArg(0));
15426
15427 case Builtin::BI__builtin_ptrauth_string_discriminator: {
15428 const auto *Literal =
15430 uint64_t Result = getPointerAuthStableSipHash(Literal->getString());
15431 return Success(Result, E);
15432 }
15433
15434 case Builtin::BI__builtin_infer_alloc_token: {
15435 // If we fail to infer a type, this fails to be a constant expression; this
15436 // can be checked with __builtin_constant_p(...).
15437 QualType AllocType = infer_alloc::inferPossibleType(E, Info.Ctx, nullptr);
15438 if (AllocType.isNull())
15439 return Error(
15440 E, diag::note_constexpr_infer_alloc_token_type_inference_failed);
15441 auto ATMD = infer_alloc::getAllocTokenMetadata(AllocType, Info.Ctx);
15442 if (!ATMD)
15443 return Error(E, diag::note_constexpr_infer_alloc_token_no_metadata);
15444 auto Mode =
15445 Info.getLangOpts().AllocTokenMode.value_or(llvm::DefaultAllocTokenMode);
15446 uint64_t BitWidth = Info.Ctx.getTypeSize(Info.Ctx.getSizeType());
15447 uint64_t MaxTokens =
15448 Info.getLangOpts().AllocTokenMax.value_or(~0ULL >> (64 - BitWidth));
15449 auto MaybeToken = llvm::getAllocToken(Mode, *ATMD, MaxTokens);
15450 if (!MaybeToken)
15451 return Error(E, diag::note_constexpr_infer_alloc_token_stateful_mode);
15452 return Success(llvm::APInt(BitWidth, *MaybeToken), E);
15453 }
15454
15455 case Builtin::BI__builtin_ffs:
15456 case Builtin::BI__builtin_ffsl:
15457 case Builtin::BI__builtin_ffsll: {
15458 APSInt Val;
15459 if (!EvaluateInteger(E->getArg(0), Val, Info))
15460 return false;
15461
15462 unsigned N = Val.countr_zero();
15463 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
15464 }
15465
15466 case Builtin::BI__builtin_fpclassify: {
15467 APFloat Val(0.0);
15468 if (!EvaluateFloat(E->getArg(5), Val, Info))
15469 return false;
15470 unsigned Arg;
15471 switch (Val.getCategory()) {
15472 case APFloat::fcNaN: Arg = 0; break;
15473 case APFloat::fcInfinity: Arg = 1; break;
15474 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
15475 case APFloat::fcZero: Arg = 4; break;
15476 }
15477 return Visit(E->getArg(Arg));
15478 }
15479
15480 case Builtin::BI__builtin_isinf_sign: {
15481 APFloat Val(0.0);
15482 return EvaluateFloat(E->getArg(0), Val, Info) &&
15483 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
15484 }
15485
15486 case Builtin::BI__builtin_isinf: {
15487 APFloat Val(0.0);
15488 return EvaluateFloat(E->getArg(0), Val, Info) &&
15489 Success(Val.isInfinity() ? 1 : 0, E);
15490 }
15491
15492 case Builtin::BI__builtin_isfinite: {
15493 APFloat Val(0.0);
15494 return EvaluateFloat(E->getArg(0), Val, Info) &&
15495 Success(Val.isFinite() ? 1 : 0, E);
15496 }
15497
15498 case Builtin::BI__builtin_isnan: {
15499 APFloat Val(0.0);
15500 return EvaluateFloat(E->getArg(0), Val, Info) &&
15501 Success(Val.isNaN() ? 1 : 0, E);
15502 }
15503
15504 case Builtin::BI__builtin_isnormal: {
15505 APFloat Val(0.0);
15506 return EvaluateFloat(E->getArg(0), Val, Info) &&
15507 Success(Val.isNormal() ? 1 : 0, E);
15508 }
15509
15510 case Builtin::BI__builtin_issubnormal: {
15511 APFloat Val(0.0);
15512 return EvaluateFloat(E->getArg(0), Val, Info) &&
15513 Success(Val.isDenormal() ? 1 : 0, E);
15514 }
15515
15516 case Builtin::BI__builtin_iszero: {
15517 APFloat Val(0.0);
15518 return EvaluateFloat(E->getArg(0), Val, Info) &&
15519 Success(Val.isZero() ? 1 : 0, E);
15520 }
15521
15522 case Builtin::BI__builtin_signbit:
15523 case Builtin::BI__builtin_signbitf:
15524 case Builtin::BI__builtin_signbitl: {
15525 APFloat Val(0.0);
15526 return EvaluateFloat(E->getArg(0), Val, Info) &&
15527 Success(Val.isNegative() ? 1 : 0, E);
15528 }
15529
15530 case Builtin::BI__builtin_isgreater:
15531 case Builtin::BI__builtin_isgreaterequal:
15532 case Builtin::BI__builtin_isless:
15533 case Builtin::BI__builtin_islessequal:
15534 case Builtin::BI__builtin_islessgreater:
15535 case Builtin::BI__builtin_isunordered: {
15536 APFloat LHS(0.0);
15537 APFloat RHS(0.0);
15538 if (!EvaluateFloat(E->getArg(0), LHS, Info) ||
15539 !EvaluateFloat(E->getArg(1), RHS, Info))
15540 return false;
15541
15542 return Success(
15543 [&] {
15544 switch (BuiltinOp) {
15545 case Builtin::BI__builtin_isgreater:
15546 return LHS > RHS;
15547 case Builtin::BI__builtin_isgreaterequal:
15548 return LHS >= RHS;
15549 case Builtin::BI__builtin_isless:
15550 return LHS < RHS;
15551 case Builtin::BI__builtin_islessequal:
15552 return LHS <= RHS;
15553 case Builtin::BI__builtin_islessgreater: {
15554 APFloat::cmpResult cmp = LHS.compare(RHS);
15555 return cmp == APFloat::cmpResult::cmpLessThan ||
15556 cmp == APFloat::cmpResult::cmpGreaterThan;
15557 }
15558 case Builtin::BI__builtin_isunordered:
15559 return LHS.compare(RHS) == APFloat::cmpResult::cmpUnordered;
15560 default:
15561 llvm_unreachable("Unexpected builtin ID: Should be a floating "
15562 "point comparison function");
15563 }
15564 }()
15565 ? 1
15566 : 0,
15567 E);
15568 }
15569
15570 case Builtin::BI__builtin_issignaling: {
15571 APFloat Val(0.0);
15572 return EvaluateFloat(E->getArg(0), Val, Info) &&
15573 Success(Val.isSignaling() ? 1 : 0, E);
15574 }
15575
15576 case Builtin::BI__builtin_isfpclass: {
15577 APSInt MaskVal;
15578 if (!EvaluateInteger(E->getArg(1), MaskVal, Info))
15579 return false;
15580 unsigned Test = static_cast<llvm::FPClassTest>(MaskVal.getZExtValue());
15581 APFloat Val(0.0);
15582 return EvaluateFloat(E->getArg(0), Val, Info) &&
15583 Success((Val.classify() & Test) ? 1 : 0, E);
15584 }
15585
15586 case Builtin::BI__builtin_parity:
15587 case Builtin::BI__builtin_parityl:
15588 case Builtin::BI__builtin_parityll: {
15589 APSInt Val;
15590 if (!EvaluateInteger(E->getArg(0), Val, Info))
15591 return false;
15592
15593 return Success(Val.popcount() % 2, E);
15594 }
15595
15596 case Builtin::BI__builtin_abs:
15597 case Builtin::BI__builtin_labs:
15598 case Builtin::BI__builtin_llabs: {
15599 APSInt Val;
15600 if (!EvaluateInteger(E->getArg(0), Val, Info))
15601 return false;
15602 if (Val == APSInt(APInt::getSignedMinValue(Val.getBitWidth()),
15603 /*IsUnsigned=*/false))
15604 return false;
15605 if (Val.isNegative())
15606 Val.negate();
15607 return Success(Val, E);
15608 }
15609
15610 case Builtin::BI__builtin_popcount:
15611 case Builtin::BI__builtin_popcountl:
15612 case Builtin::BI__builtin_popcountll:
15613 case Builtin::BI__builtin_popcountg:
15614 case Builtin::BI__builtin_elementwise_popcount:
15615 case Builtin::BI__popcnt16: // Microsoft variants of popcount
15616 case Builtin::BI__popcnt:
15617 case Builtin::BI__popcnt64: {
15618 APSInt Val;
15619 if (E->getArg(0)->getType()->isExtVectorBoolType()) {
15620 APValue Vec;
15621 if (!EvaluateVector(E->getArg(0), Vec, Info))
15622 return false;
15623 Val = ConvertBoolVectorToInt(Vec);
15624 } else if (!EvaluateInteger(E->getArg(0), Val, Info)) {
15625 return false;
15626 }
15627
15628 return Success(Val.popcount(), E);
15629 }
15630
15631 case Builtin::BI__builtin_rotateleft8:
15632 case Builtin::BI__builtin_rotateleft16:
15633 case Builtin::BI__builtin_rotateleft32:
15634 case Builtin::BI__builtin_rotateleft64:
15635 case Builtin::BI_rotl8: // Microsoft variants of rotate right
15636 case Builtin::BI_rotl16:
15637 case Builtin::BI_rotl:
15638 case Builtin::BI_lrotl:
15639 case Builtin::BI_rotl64: {
15640 APSInt Val, Amt;
15641 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
15642 !EvaluateInteger(E->getArg(1), Amt, Info))
15643 return false;
15644
15645 return Success(Val.rotl(Amt), E);
15646 }
15647
15648 case Builtin::BI__builtin_rotateright8:
15649 case Builtin::BI__builtin_rotateright16:
15650 case Builtin::BI__builtin_rotateright32:
15651 case Builtin::BI__builtin_rotateright64:
15652 case Builtin::BI_rotr8: // Microsoft variants of rotate right
15653 case Builtin::BI_rotr16:
15654 case Builtin::BI_rotr:
15655 case Builtin::BI_lrotr:
15656 case Builtin::BI_rotr64: {
15657 APSInt Val, Amt;
15658 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
15659 !EvaluateInteger(E->getArg(1), Amt, Info))
15660 return false;
15661
15662 return Success(Val.rotr(Amt), E);
15663 }
15664
15665 case Builtin::BI__builtin_elementwise_add_sat: {
15666 APSInt LHS, RHS;
15667 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
15668 !EvaluateInteger(E->getArg(1), RHS, Info))
15669 return false;
15670
15671 APInt Result = LHS.isSigned() ? LHS.sadd_sat(RHS) : LHS.uadd_sat(RHS);
15672 return Success(APSInt(Result, !LHS.isSigned()), E);
15673 }
15674 case Builtin::BI__builtin_elementwise_sub_sat: {
15675 APSInt LHS, RHS;
15676 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
15677 !EvaluateInteger(E->getArg(1), RHS, Info))
15678 return false;
15679
15680 APInt Result = LHS.isSigned() ? LHS.ssub_sat(RHS) : LHS.usub_sat(RHS);
15681 return Success(APSInt(Result, !LHS.isSigned()), E);
15682 }
15683 case Builtin::BI__builtin_elementwise_max: {
15684 APSInt LHS, RHS;
15685 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
15686 !EvaluateInteger(E->getArg(1), RHS, Info))
15687 return false;
15688
15689 APInt Result = std::max(LHS, RHS);
15690 return Success(APSInt(Result, !LHS.isSigned()), E);
15691 }
15692 case Builtin::BI__builtin_elementwise_min: {
15693 APSInt LHS, RHS;
15694 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
15695 !EvaluateInteger(E->getArg(1), RHS, Info))
15696 return false;
15697
15698 APInt Result = std::min(LHS, RHS);
15699 return Success(APSInt(Result, !LHS.isSigned()), E);
15700 }
15701 case Builtin::BI__builtin_elementwise_fshl:
15702 case Builtin::BI__builtin_elementwise_fshr: {
15703 APSInt Hi, Lo, Shift;
15704 if (!EvaluateInteger(E->getArg(0), Hi, Info) ||
15705 !EvaluateInteger(E->getArg(1), Lo, Info) ||
15706 !EvaluateInteger(E->getArg(2), Shift, Info))
15707 return false;
15708
15709 switch (BuiltinOp) {
15710 case Builtin::BI__builtin_elementwise_fshl: {
15711 APSInt Result(llvm::APIntOps::fshl(Hi, Lo, Shift), Hi.isUnsigned());
15712 return Success(Result, E);
15713 }
15714 case Builtin::BI__builtin_elementwise_fshr: {
15715 APSInt Result(llvm::APIntOps::fshr(Hi, Lo, Shift), Hi.isUnsigned());
15716 return Success(Result, E);
15717 }
15718 }
15719 llvm_unreachable("Fully covered switch above");
15720 }
15721 case Builtin::BIstrlen:
15722 case Builtin::BIwcslen:
15723 // A call to strlen is not a constant expression.
15724 if (Info.getLangOpts().CPlusPlus11)
15725 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
15726 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
15727 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
15728 else
15729 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
15730 [[fallthrough]];
15731 case Builtin::BI__builtin_strlen:
15732 case Builtin::BI__builtin_wcslen: {
15733 // As an extension, we support __builtin_strlen() as a constant expression,
15734 // and support folding strlen() to a constant.
15735 uint64_t StrLen;
15736 if (EvaluateBuiltinStrLen(E->getArg(0), StrLen, Info))
15737 return Success(StrLen, E);
15738 return false;
15739 }
15740
15741 case Builtin::BIstrcmp:
15742 case Builtin::BIwcscmp:
15743 case Builtin::BIstrncmp:
15744 case Builtin::BIwcsncmp:
15745 case Builtin::BImemcmp:
15746 case Builtin::BIbcmp:
15747 case Builtin::BIwmemcmp:
15748 // A call to strlen is not a constant expression.
15749 if (Info.getLangOpts().CPlusPlus11)
15750 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
15751 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
15752 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
15753 else
15754 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
15755 [[fallthrough]];
15756 case Builtin::BI__builtin_strcmp:
15757 case Builtin::BI__builtin_wcscmp:
15758 case Builtin::BI__builtin_strncmp:
15759 case Builtin::BI__builtin_wcsncmp:
15760 case Builtin::BI__builtin_memcmp:
15761 case Builtin::BI__builtin_bcmp:
15762 case Builtin::BI__builtin_wmemcmp: {
15763 LValue String1, String2;
15764 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
15765 !EvaluatePointer(E->getArg(1), String2, Info))
15766 return false;
15767
15768 uint64_t MaxLength = uint64_t(-1);
15769 if (BuiltinOp != Builtin::BIstrcmp &&
15770 BuiltinOp != Builtin::BIwcscmp &&
15771 BuiltinOp != Builtin::BI__builtin_strcmp &&
15772 BuiltinOp != Builtin::BI__builtin_wcscmp) {
15773 APSInt N;
15774 if (!EvaluateInteger(E->getArg(2), N, Info))
15775 return false;
15776 MaxLength = N.getZExtValue();
15777 }
15778
15779 // Empty substrings compare equal by definition.
15780 if (MaxLength == 0u)
15781 return Success(0, E);
15782
15783 if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
15784 !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
15785 String1.Designator.Invalid || String2.Designator.Invalid)
15786 return false;
15787
15788 QualType CharTy1 = String1.Designator.getType(Info.Ctx);
15789 QualType CharTy2 = String2.Designator.getType(Info.Ctx);
15790
15791 bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
15792 BuiltinOp == Builtin::BIbcmp ||
15793 BuiltinOp == Builtin::BI__builtin_memcmp ||
15794 BuiltinOp == Builtin::BI__builtin_bcmp;
15795
15796 assert(IsRawByte ||
15797 (Info.Ctx.hasSameUnqualifiedType(
15798 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
15799 Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
15800
15801 // For memcmp, allow comparing any arrays of '[[un]signed] char' or
15802 // 'char8_t', but no other types.
15803 if (IsRawByte &&
15804 !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) {
15805 // FIXME: Consider using our bit_cast implementation to support this.
15806 Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported)
15807 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp) << CharTy1
15808 << CharTy2;
15809 return false;
15810 }
15811
15812 const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
15813 return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
15814 handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
15815 Char1.isInt() && Char2.isInt();
15816 };
15817 const auto &AdvanceElems = [&] {
15818 return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
15819 HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
15820 };
15821
15822 bool StopAtNull =
15823 (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
15824 BuiltinOp != Builtin::BIwmemcmp &&
15825 BuiltinOp != Builtin::BI__builtin_memcmp &&
15826 BuiltinOp != Builtin::BI__builtin_bcmp &&
15827 BuiltinOp != Builtin::BI__builtin_wmemcmp);
15828 bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
15829 BuiltinOp == Builtin::BIwcsncmp ||
15830 BuiltinOp == Builtin::BIwmemcmp ||
15831 BuiltinOp == Builtin::BI__builtin_wcscmp ||
15832 BuiltinOp == Builtin::BI__builtin_wcsncmp ||
15833 BuiltinOp == Builtin::BI__builtin_wmemcmp;
15834
15835 for (; MaxLength; --MaxLength) {
15836 APValue Char1, Char2;
15837 if (!ReadCurElems(Char1, Char2))
15838 return false;
15839 if (Char1.getInt().ne(Char2.getInt())) {
15840 if (IsWide) // wmemcmp compares with wchar_t signedness.
15841 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
15842 // memcmp always compares unsigned chars.
15843 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
15844 }
15845 if (StopAtNull && !Char1.getInt())
15846 return Success(0, E);
15847 assert(!(StopAtNull && !Char2.getInt()));
15848 if (!AdvanceElems())
15849 return false;
15850 }
15851 // We hit the strncmp / memcmp limit.
15852 return Success(0, E);
15853 }
15854
15855 case Builtin::BI__atomic_always_lock_free:
15856 case Builtin::BI__atomic_is_lock_free:
15857 case Builtin::BI__c11_atomic_is_lock_free: {
15858 APSInt SizeVal;
15859 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
15860 return false;
15861
15862 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
15863 // of two less than or equal to the maximum inline atomic width, we know it
15864 // is lock-free. If the size isn't a power of two, or greater than the
15865 // maximum alignment where we promote atomics, we know it is not lock-free
15866 // (at least not in the sense of atomic_is_lock_free). Otherwise,
15867 // the answer can only be determined at runtime; for example, 16-byte
15868 // atomics have lock-free implementations on some, but not all,
15869 // x86-64 processors.
15870
15871 // Check power-of-two.
15872 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
15873 if (Size.isPowerOfTwo()) {
15874 // Check against inlining width.
15875 unsigned InlineWidthBits =
15877 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
15878 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
15879 Size == CharUnits::One())
15880 return Success(1, E);
15881
15882 // If the pointer argument can be evaluated to a compile-time constant
15883 // integer (or nullptr), check if that value is appropriately aligned.
15884 const Expr *PtrArg = E->getArg(1);
15885 Expr::EvalResult ExprResult;
15886 APSInt IntResult;
15887 if (PtrArg->EvaluateAsRValue(ExprResult, Info.Ctx) &&
15888 ExprResult.Val.toIntegralConstant(IntResult, PtrArg->getType(),
15889 Info.Ctx) &&
15890 IntResult.isAligned(Size.getAsAlign()))
15891 return Success(1, E);
15892
15893 // Otherwise, check if the type's alignment against Size.
15894 if (auto *ICE = dyn_cast<ImplicitCastExpr>(PtrArg)) {
15895 // Drop the potential implicit-cast to 'const volatile void*', getting
15896 // the underlying type.
15897 if (ICE->getCastKind() == CK_BitCast)
15898 PtrArg = ICE->getSubExpr();
15899 }
15900
15901 if (auto PtrTy = PtrArg->getType()->getAs<PointerType>()) {
15902 QualType PointeeType = PtrTy->getPointeeType();
15903 if (!PointeeType->isIncompleteType() &&
15904 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
15905 // OK, we will inline operations on this object.
15906 return Success(1, E);
15907 }
15908 }
15909 }
15910 }
15911
15912 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
15913 Success(0, E) : Error(E);
15914 }
15915 case Builtin::BI__builtin_addcb:
15916 case Builtin::BI__builtin_addcs:
15917 case Builtin::BI__builtin_addc:
15918 case Builtin::BI__builtin_addcl:
15919 case Builtin::BI__builtin_addcll:
15920 case Builtin::BI__builtin_subcb:
15921 case Builtin::BI__builtin_subcs:
15922 case Builtin::BI__builtin_subc:
15923 case Builtin::BI__builtin_subcl:
15924 case Builtin::BI__builtin_subcll: {
15925 LValue CarryOutLValue;
15926 APSInt LHS, RHS, CarryIn, CarryOut, Result;
15927 QualType ResultType = E->getArg(0)->getType();
15928 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
15929 !EvaluateInteger(E->getArg(1), RHS, Info) ||
15930 !EvaluateInteger(E->getArg(2), CarryIn, Info) ||
15931 !EvaluatePointer(E->getArg(3), CarryOutLValue, Info))
15932 return false;
15933 // Copy the number of bits and sign.
15934 Result = LHS;
15935 CarryOut = LHS;
15936
15937 bool FirstOverflowed = false;
15938 bool SecondOverflowed = false;
15939 switch (BuiltinOp) {
15940 default:
15941 llvm_unreachable("Invalid value for BuiltinOp");
15942 case Builtin::BI__builtin_addcb:
15943 case Builtin::BI__builtin_addcs:
15944 case Builtin::BI__builtin_addc:
15945 case Builtin::BI__builtin_addcl:
15946 case Builtin::BI__builtin_addcll:
15947 Result =
15948 LHS.uadd_ov(RHS, FirstOverflowed).uadd_ov(CarryIn, SecondOverflowed);
15949 break;
15950 case Builtin::BI__builtin_subcb:
15951 case Builtin::BI__builtin_subcs:
15952 case Builtin::BI__builtin_subc:
15953 case Builtin::BI__builtin_subcl:
15954 case Builtin::BI__builtin_subcll:
15955 Result =
15956 LHS.usub_ov(RHS, FirstOverflowed).usub_ov(CarryIn, SecondOverflowed);
15957 break;
15958 }
15959
15960 // It is possible for both overflows to happen but CGBuiltin uses an OR so
15961 // this is consistent.
15962 CarryOut = (uint64_t)(FirstOverflowed | SecondOverflowed);
15963 APValue APV{CarryOut};
15964 if (!handleAssignment(Info, E, CarryOutLValue, ResultType, APV))
15965 return false;
15966 return Success(Result, E);
15967 }
15968 case Builtin::BI__builtin_add_overflow:
15969 case Builtin::BI__builtin_sub_overflow:
15970 case Builtin::BI__builtin_mul_overflow:
15971 case Builtin::BI__builtin_sadd_overflow:
15972 case Builtin::BI__builtin_uadd_overflow:
15973 case Builtin::BI__builtin_uaddl_overflow:
15974 case Builtin::BI__builtin_uaddll_overflow:
15975 case Builtin::BI__builtin_usub_overflow:
15976 case Builtin::BI__builtin_usubl_overflow:
15977 case Builtin::BI__builtin_usubll_overflow:
15978 case Builtin::BI__builtin_umul_overflow:
15979 case Builtin::BI__builtin_umull_overflow:
15980 case Builtin::BI__builtin_umulll_overflow:
15981 case Builtin::BI__builtin_saddl_overflow:
15982 case Builtin::BI__builtin_saddll_overflow:
15983 case Builtin::BI__builtin_ssub_overflow:
15984 case Builtin::BI__builtin_ssubl_overflow:
15985 case Builtin::BI__builtin_ssubll_overflow:
15986 case Builtin::BI__builtin_smul_overflow:
15987 case Builtin::BI__builtin_smull_overflow:
15988 case Builtin::BI__builtin_smulll_overflow: {
15989 LValue ResultLValue;
15990 APSInt LHS, RHS;
15991
15992 QualType ResultType = E->getArg(2)->getType()->getPointeeType();
15993 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
15994 !EvaluateInteger(E->getArg(1), RHS, Info) ||
15995 !EvaluatePointer(E->getArg(2), ResultLValue, Info))
15996 return false;
15997
15998 APSInt Result;
15999 bool DidOverflow = false;
16000
16001 // If the types don't have to match, enlarge all 3 to the largest of them.
16002 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
16003 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
16004 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
16005 bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
16007 bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
16009 uint64_t LHSSize = LHS.getBitWidth();
16010 uint64_t RHSSize = RHS.getBitWidth();
16011 uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
16012 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
16013
16014 // Add an additional bit if the signedness isn't uniformly agreed to. We
16015 // could do this ONLY if there is a signed and an unsigned that both have
16016 // MaxBits, but the code to check that is pretty nasty. The issue will be
16017 // caught in the shrink-to-result later anyway.
16018 if (IsSigned && !AllSigned)
16019 ++MaxBits;
16020
16021 LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
16022 RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
16023 Result = APSInt(MaxBits, !IsSigned);
16024 }
16025
16026 // Find largest int.
16027 switch (BuiltinOp) {
16028 default:
16029 llvm_unreachable("Invalid value for BuiltinOp");
16030 case Builtin::BI__builtin_add_overflow:
16031 case Builtin::BI__builtin_sadd_overflow:
16032 case Builtin::BI__builtin_saddl_overflow:
16033 case Builtin::BI__builtin_saddll_overflow:
16034 case Builtin::BI__builtin_uadd_overflow:
16035 case Builtin::BI__builtin_uaddl_overflow:
16036 case Builtin::BI__builtin_uaddll_overflow:
16037 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
16038 : LHS.uadd_ov(RHS, DidOverflow);
16039 break;
16040 case Builtin::BI__builtin_sub_overflow:
16041 case Builtin::BI__builtin_ssub_overflow:
16042 case Builtin::BI__builtin_ssubl_overflow:
16043 case Builtin::BI__builtin_ssubll_overflow:
16044 case Builtin::BI__builtin_usub_overflow:
16045 case Builtin::BI__builtin_usubl_overflow:
16046 case Builtin::BI__builtin_usubll_overflow:
16047 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
16048 : LHS.usub_ov(RHS, DidOverflow);
16049 break;
16050 case Builtin::BI__builtin_mul_overflow:
16051 case Builtin::BI__builtin_smul_overflow:
16052 case Builtin::BI__builtin_smull_overflow:
16053 case Builtin::BI__builtin_smulll_overflow:
16054 case Builtin::BI__builtin_umul_overflow:
16055 case Builtin::BI__builtin_umull_overflow:
16056 case Builtin::BI__builtin_umulll_overflow:
16057 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
16058 : LHS.umul_ov(RHS, DidOverflow);
16059 break;
16060 }
16061
16062 // In the case where multiple sizes are allowed, truncate and see if
16063 // the values are the same.
16064 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
16065 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
16066 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
16067 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
16068 // since it will give us the behavior of a TruncOrSelf in the case where
16069 // its parameter <= its size. We previously set Result to be at least the
16070 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
16071 // will work exactly like TruncOrSelf.
16072 APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
16073 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
16074
16075 if (!APSInt::isSameValue(Temp, Result))
16076 DidOverflow = true;
16077 Result = Temp;
16078 }
16079
16080 APValue APV{Result};
16081 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
16082 return false;
16083 return Success(DidOverflow, E);
16084 }
16085
16086 case Builtin::BI__builtin_reduce_add:
16087 case Builtin::BI__builtin_reduce_mul:
16088 case Builtin::BI__builtin_reduce_and:
16089 case Builtin::BI__builtin_reduce_or:
16090 case Builtin::BI__builtin_reduce_xor:
16091 case Builtin::BI__builtin_reduce_min:
16092 case Builtin::BI__builtin_reduce_max: {
16093 APValue Source;
16094 if (!EvaluateAsRValue(Info, E->getArg(0), Source))
16095 return false;
16096
16097 unsigned SourceLen = Source.getVectorLength();
16098 APSInt Reduced = Source.getVectorElt(0).getInt();
16099 for (unsigned EltNum = 1; EltNum < SourceLen; ++EltNum) {
16100 switch (BuiltinOp) {
16101 default:
16102 return false;
16103 case Builtin::BI__builtin_reduce_add: {
16105 Info, E, Reduced, Source.getVectorElt(EltNum).getInt(),
16106 Reduced.getBitWidth() + 1, std::plus<APSInt>(), Reduced))
16107 return false;
16108 break;
16109 }
16110 case Builtin::BI__builtin_reduce_mul: {
16112 Info, E, Reduced, Source.getVectorElt(EltNum).getInt(),
16113 Reduced.getBitWidth() * 2, std::multiplies<APSInt>(), Reduced))
16114 return false;
16115 break;
16116 }
16117 case Builtin::BI__builtin_reduce_and: {
16118 Reduced &= Source.getVectorElt(EltNum).getInt();
16119 break;
16120 }
16121 case Builtin::BI__builtin_reduce_or: {
16122 Reduced |= Source.getVectorElt(EltNum).getInt();
16123 break;
16124 }
16125 case Builtin::BI__builtin_reduce_xor: {
16126 Reduced ^= Source.getVectorElt(EltNum).getInt();
16127 break;
16128 }
16129 case Builtin::BI__builtin_reduce_min: {
16130 Reduced = std::min(Reduced, Source.getVectorElt(EltNum).getInt());
16131 break;
16132 }
16133 case Builtin::BI__builtin_reduce_max: {
16134 Reduced = std::max(Reduced, Source.getVectorElt(EltNum).getInt());
16135 break;
16136 }
16137 }
16138 }
16139
16140 return Success(Reduced, E);
16141 }
16142
16143 case clang::X86::BI__builtin_ia32_addcarryx_u32:
16144 case clang::X86::BI__builtin_ia32_addcarryx_u64:
16145 case clang::X86::BI__builtin_ia32_subborrow_u32:
16146 case clang::X86::BI__builtin_ia32_subborrow_u64: {
16147 LValue ResultLValue;
16148 APSInt CarryIn, LHS, RHS;
16149 QualType ResultType = E->getArg(3)->getType()->getPointeeType();
16150 if (!EvaluateInteger(E->getArg(0), CarryIn, Info) ||
16151 !EvaluateInteger(E->getArg(1), LHS, Info) ||
16152 !EvaluateInteger(E->getArg(2), RHS, Info) ||
16153 !EvaluatePointer(E->getArg(3), ResultLValue, Info))
16154 return false;
16155
16156 bool IsAdd = BuiltinOp == clang::X86::BI__builtin_ia32_addcarryx_u32 ||
16157 BuiltinOp == clang::X86::BI__builtin_ia32_addcarryx_u64;
16158
16159 unsigned BitWidth = LHS.getBitWidth();
16160 unsigned CarryInBit = CarryIn.ugt(0) ? 1 : 0;
16161 APInt ExResult =
16162 IsAdd
16163 ? (LHS.zext(BitWidth + 1) + (RHS.zext(BitWidth + 1) + CarryInBit))
16164 : (LHS.zext(BitWidth + 1) - (RHS.zext(BitWidth + 1) + CarryInBit));
16165
16166 APInt Result = ExResult.extractBits(BitWidth, 0);
16167 uint64_t CarryOut = ExResult.extractBitsAsZExtValue(1, BitWidth);
16168
16169 APValue APV{APSInt(Result, /*isUnsigned=*/true)};
16170 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
16171 return false;
16172 return Success(CarryOut, E);
16173 }
16174
16175 case clang::X86::BI__builtin_ia32_movmskps:
16176 case clang::X86::BI__builtin_ia32_movmskpd:
16177 case clang::X86::BI__builtin_ia32_pmovmskb128:
16178 case clang::X86::BI__builtin_ia32_pmovmskb256:
16179 case clang::X86::BI__builtin_ia32_movmskps256:
16180 case clang::X86::BI__builtin_ia32_movmskpd256: {
16181 APValue Source;
16182 if (!Evaluate(Source, Info, E->getArg(0)))
16183 return false;
16184 unsigned SourceLen = Source.getVectorLength();
16185 const VectorType *VT = E->getArg(0)->getType()->castAs<VectorType>();
16186 QualType ElemQT = VT->getElementType();
16187 unsigned ResultLen = Info.Ctx.getTypeSize(
16188 E->getCallReturnType(Info.Ctx)); // Always 32-bit integer.
16189 APInt Result(ResultLen, 0);
16190
16191 for (unsigned I = 0; I != SourceLen; ++I) {
16192 APInt Elem;
16193 if (ElemQT->isIntegerType()) {
16194 Elem = Source.getVectorElt(I).getInt();
16195 } else if (ElemQT->isRealFloatingType()) {
16196 Elem = Source.getVectorElt(I).getFloat().bitcastToAPInt();
16197 } else {
16198 return false;
16199 }
16200 Result.setBitVal(I, Elem.isNegative());
16201 }
16202 return Success(Result, E);
16203 }
16204
16205 case clang::X86::BI__builtin_ia32_bextr_u32:
16206 case clang::X86::BI__builtin_ia32_bextr_u64:
16207 case clang::X86::BI__builtin_ia32_bextri_u32:
16208 case clang::X86::BI__builtin_ia32_bextri_u64: {
16209 APSInt Val, Idx;
16210 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
16211 !EvaluateInteger(E->getArg(1), Idx, Info))
16212 return false;
16213
16214 unsigned BitWidth = Val.getBitWidth();
16215 uint64_t Shift = Idx.extractBitsAsZExtValue(8, 0);
16216 uint64_t Length = Idx.extractBitsAsZExtValue(8, 8);
16217 Length = Length > BitWidth ? BitWidth : Length;
16218
16219 // Handle out of bounds cases.
16220 if (Length == 0 || Shift >= BitWidth)
16221 return Success(0, E);
16222
16223 uint64_t Result = Val.getZExtValue() >> Shift;
16224 Result &= llvm::maskTrailingOnes<uint64_t>(Length);
16225 return Success(Result, E);
16226 }
16227
16228 case clang::X86::BI__builtin_ia32_bzhi_si:
16229 case clang::X86::BI__builtin_ia32_bzhi_di: {
16230 APSInt Val, Idx;
16231 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
16232 !EvaluateInteger(E->getArg(1), Idx, Info))
16233 return false;
16234
16235 unsigned BitWidth = Val.getBitWidth();
16236 unsigned Index = Idx.extractBitsAsZExtValue(8, 0);
16237 if (Index < BitWidth)
16238 Val.clearHighBits(BitWidth - Index);
16239 return Success(Val, E);
16240 }
16241
16242 case clang::X86::BI__builtin_ia32_ktestcqi:
16243 case clang::X86::BI__builtin_ia32_ktestchi:
16244 case clang::X86::BI__builtin_ia32_ktestcsi:
16245 case clang::X86::BI__builtin_ia32_ktestcdi: {
16246 APSInt A, B;
16247 if (!EvaluateInteger(E->getArg(0), A, Info) ||
16248 !EvaluateInteger(E->getArg(1), B, Info))
16249 return false;
16250
16251 return Success((~A & B) == 0, E);
16252 }
16253
16254 case clang::X86::BI__builtin_ia32_ktestzqi:
16255 case clang::X86::BI__builtin_ia32_ktestzhi:
16256 case clang::X86::BI__builtin_ia32_ktestzsi:
16257 case clang::X86::BI__builtin_ia32_ktestzdi: {
16258 APSInt A, B;
16259 if (!EvaluateInteger(E->getArg(0), A, Info) ||
16260 !EvaluateInteger(E->getArg(1), B, Info))
16261 return false;
16262
16263 return Success((A & B) == 0, E);
16264 }
16265
16266 case clang::X86::BI__builtin_ia32_kortestcqi:
16267 case clang::X86::BI__builtin_ia32_kortestchi:
16268 case clang::X86::BI__builtin_ia32_kortestcsi:
16269 case clang::X86::BI__builtin_ia32_kortestcdi: {
16270 APSInt A, B;
16271 if (!EvaluateInteger(E->getArg(0), A, Info) ||
16272 !EvaluateInteger(E->getArg(1), B, Info))
16273 return false;
16274
16275 return Success(~(A | B) == 0, E);
16276 }
16277
16278 case clang::X86::BI__builtin_ia32_kortestzqi:
16279 case clang::X86::BI__builtin_ia32_kortestzhi:
16280 case clang::X86::BI__builtin_ia32_kortestzsi:
16281 case clang::X86::BI__builtin_ia32_kortestzdi: {
16282 APSInt A, B;
16283 if (!EvaluateInteger(E->getArg(0), A, Info) ||
16284 !EvaluateInteger(E->getArg(1), B, Info))
16285 return false;
16286
16287 return Success((A | B) == 0, E);
16288 }
16289
16290 case clang::X86::BI__builtin_ia32_lzcnt_u16:
16291 case clang::X86::BI__builtin_ia32_lzcnt_u32:
16292 case clang::X86::BI__builtin_ia32_lzcnt_u64: {
16293 APSInt Val;
16294 if (!EvaluateInteger(E->getArg(0), Val, Info))
16295 return false;
16296 return Success(Val.countLeadingZeros(), E);
16297 }
16298
16299 case clang::X86::BI__builtin_ia32_tzcnt_u16:
16300 case clang::X86::BI__builtin_ia32_tzcnt_u32:
16301 case clang::X86::BI__builtin_ia32_tzcnt_u64: {
16302 APSInt Val;
16303 if (!EvaluateInteger(E->getArg(0), Val, Info))
16304 return false;
16305 return Success(Val.countTrailingZeros(), E);
16306 }
16307
16308 case clang::X86::BI__builtin_ia32_pdep_si:
16309 case clang::X86::BI__builtin_ia32_pdep_di: {
16310 APSInt Val, Msk;
16311 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
16312 !EvaluateInteger(E->getArg(1), Msk, Info))
16313 return false;
16314
16315 unsigned BitWidth = Val.getBitWidth();
16316 APInt Result = APInt::getZero(BitWidth);
16317 for (unsigned I = 0, P = 0; I != BitWidth; ++I)
16318 if (Msk[I])
16319 Result.setBitVal(I, Val[P++]);
16320 return Success(Result, E);
16321 }
16322
16323 case clang::X86::BI__builtin_ia32_pext_si:
16324 case clang::X86::BI__builtin_ia32_pext_di: {
16325 APSInt Val, Msk;
16326 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
16327 !EvaluateInteger(E->getArg(1), Msk, Info))
16328 return false;
16329
16330 unsigned BitWidth = Val.getBitWidth();
16331 APInt Result = APInt::getZero(BitWidth);
16332 for (unsigned I = 0, P = 0; I != BitWidth; ++I)
16333 if (Msk[I])
16334 Result.setBitVal(P++, Val[I]);
16335 return Success(Result, E);
16336 }
16337 case X86::BI__builtin_ia32_ptestz128:
16338 case X86::BI__builtin_ia32_ptestz256:
16339 case X86::BI__builtin_ia32_vtestzps:
16340 case X86::BI__builtin_ia32_vtestzps256:
16341 case X86::BI__builtin_ia32_vtestzpd:
16342 case X86::BI__builtin_ia32_vtestzpd256: {
16343 return EvalTestOp(
16344 [](const APInt &A, const APInt &B) { return (A & B) == 0; });
16345 }
16346 case X86::BI__builtin_ia32_ptestc128:
16347 case X86::BI__builtin_ia32_ptestc256:
16348 case X86::BI__builtin_ia32_vtestcps:
16349 case X86::BI__builtin_ia32_vtestcps256:
16350 case X86::BI__builtin_ia32_vtestcpd:
16351 case X86::BI__builtin_ia32_vtestcpd256: {
16352 return EvalTestOp(
16353 [](const APInt &A, const APInt &B) { return (~A & B) == 0; });
16354 }
16355 case X86::BI__builtin_ia32_ptestnzc128:
16356 case X86::BI__builtin_ia32_ptestnzc256:
16357 case X86::BI__builtin_ia32_vtestnzcps:
16358 case X86::BI__builtin_ia32_vtestnzcps256:
16359 case X86::BI__builtin_ia32_vtestnzcpd:
16360 case X86::BI__builtin_ia32_vtestnzcpd256: {
16361 return EvalTestOp([](const APInt &A, const APInt &B) {
16362 return ((A & B) != 0) && ((~A & B) != 0);
16363 });
16364 }
16365 case X86::BI__builtin_ia32_kandqi:
16366 case X86::BI__builtin_ia32_kandhi:
16367 case X86::BI__builtin_ia32_kandsi:
16368 case X86::BI__builtin_ia32_kanddi: {
16369 return HandleMaskBinOp(
16370 [](const APSInt &LHS, const APSInt &RHS) { return LHS & RHS; });
16371 }
16372
16373 case X86::BI__builtin_ia32_kandnqi:
16374 case X86::BI__builtin_ia32_kandnhi:
16375 case X86::BI__builtin_ia32_kandnsi:
16376 case X86::BI__builtin_ia32_kandndi: {
16377 return HandleMaskBinOp(
16378 [](const APSInt &LHS, const APSInt &RHS) { return ~LHS & RHS; });
16379 }
16380
16381 case X86::BI__builtin_ia32_korqi:
16382 case X86::BI__builtin_ia32_korhi:
16383 case X86::BI__builtin_ia32_korsi:
16384 case X86::BI__builtin_ia32_kordi: {
16385 return HandleMaskBinOp(
16386 [](const APSInt &LHS, const APSInt &RHS) { return LHS | RHS; });
16387 }
16388
16389 case X86::BI__builtin_ia32_kxnorqi:
16390 case X86::BI__builtin_ia32_kxnorhi:
16391 case X86::BI__builtin_ia32_kxnorsi:
16392 case X86::BI__builtin_ia32_kxnordi: {
16393 return HandleMaskBinOp(
16394 [](const APSInt &LHS, const APSInt &RHS) { return ~(LHS ^ RHS); });
16395 }
16396
16397 case X86::BI__builtin_ia32_kxorqi:
16398 case X86::BI__builtin_ia32_kxorhi:
16399 case X86::BI__builtin_ia32_kxorsi:
16400 case X86::BI__builtin_ia32_kxordi: {
16401 return HandleMaskBinOp(
16402 [](const APSInt &LHS, const APSInt &RHS) { return LHS ^ RHS; });
16403 }
16404
16405 case X86::BI__builtin_ia32_knotqi:
16406 case X86::BI__builtin_ia32_knothi:
16407 case X86::BI__builtin_ia32_knotsi:
16408 case X86::BI__builtin_ia32_knotdi: {
16409 APSInt Val;
16410 if (!EvaluateInteger(E->getArg(0), Val, Info))
16411 return false;
16412 APSInt Result = ~Val;
16413 return Success(APValue(Result), E);
16414 }
16415
16416 case X86::BI__builtin_ia32_kaddqi:
16417 case X86::BI__builtin_ia32_kaddhi:
16418 case X86::BI__builtin_ia32_kaddsi:
16419 case X86::BI__builtin_ia32_kadddi: {
16420 return HandleMaskBinOp(
16421 [](const APSInt &LHS, const APSInt &RHS) { return LHS + RHS; });
16422 }
16423
16424 case clang::X86::BI__builtin_ia32_vec_ext_v4hi:
16425 case clang::X86::BI__builtin_ia32_vec_ext_v16qi:
16426 case clang::X86::BI__builtin_ia32_vec_ext_v8hi:
16427 case clang::X86::BI__builtin_ia32_vec_ext_v4si:
16428 case clang::X86::BI__builtin_ia32_vec_ext_v2di:
16429 case clang::X86::BI__builtin_ia32_vec_ext_v32qi:
16430 case clang::X86::BI__builtin_ia32_vec_ext_v16hi:
16431 case clang::X86::BI__builtin_ia32_vec_ext_v8si:
16432 case clang::X86::BI__builtin_ia32_vec_ext_v4di: {
16433 APValue Vec;
16434 APSInt IdxAPS;
16435 if (!EvaluateVector(E->getArg(0), Vec, Info) ||
16436 !EvaluateInteger(E->getArg(1), IdxAPS, Info))
16437 return false;
16438 unsigned N = Vec.getVectorLength();
16439 unsigned Idx = static_cast<unsigned>(IdxAPS.getZExtValue() & (N - 1));
16440 return Success(Vec.getVectorElt(Idx).getInt(), E);
16441 }
16442
16443 case clang::X86::BI__builtin_ia32_cmpb128_mask:
16444 case clang::X86::BI__builtin_ia32_cmpw128_mask:
16445 case clang::X86::BI__builtin_ia32_cmpd128_mask:
16446 case clang::X86::BI__builtin_ia32_cmpq128_mask:
16447 case clang::X86::BI__builtin_ia32_cmpb256_mask:
16448 case clang::X86::BI__builtin_ia32_cmpw256_mask:
16449 case clang::X86::BI__builtin_ia32_cmpd256_mask:
16450 case clang::X86::BI__builtin_ia32_cmpq256_mask:
16451 case clang::X86::BI__builtin_ia32_cmpb512_mask:
16452 case clang::X86::BI__builtin_ia32_cmpw512_mask:
16453 case clang::X86::BI__builtin_ia32_cmpd512_mask:
16454 case clang::X86::BI__builtin_ia32_cmpq512_mask:
16455 case clang::X86::BI__builtin_ia32_ucmpb128_mask:
16456 case clang::X86::BI__builtin_ia32_ucmpw128_mask:
16457 case clang::X86::BI__builtin_ia32_ucmpd128_mask:
16458 case clang::X86::BI__builtin_ia32_ucmpq128_mask:
16459 case clang::X86::BI__builtin_ia32_ucmpb256_mask:
16460 case clang::X86::BI__builtin_ia32_ucmpw256_mask:
16461 case clang::X86::BI__builtin_ia32_ucmpd256_mask:
16462 case clang::X86::BI__builtin_ia32_ucmpq256_mask:
16463 case clang::X86::BI__builtin_ia32_ucmpb512_mask:
16464 case clang::X86::BI__builtin_ia32_ucmpw512_mask:
16465 case clang::X86::BI__builtin_ia32_ucmpd512_mask:
16466 case clang::X86::BI__builtin_ia32_ucmpq512_mask: {
16467 assert(E->getNumArgs() == 4);
16468
16469 bool IsUnsigned =
16470 (BuiltinOp >= clang::X86::BI__builtin_ia32_ucmpb128_mask &&
16471 BuiltinOp <= clang::X86::BI__builtin_ia32_ucmpq512_mask);
16472
16473 APValue LHS, RHS;
16474 APSInt Mask, Opcode;
16475 if (!EvaluateVector(E->getArg(0), LHS, Info) ||
16476 !EvaluateVector(E->getArg(1), RHS, Info) ||
16477 !EvaluateInteger(E->getArg(2), Opcode, Info) ||
16478 !EvaluateInteger(E->getArg(3), Mask, Info))
16479 return false;
16480
16481 assert(LHS.getVectorLength() == RHS.getVectorLength());
16482
16483 unsigned VectorLen = LHS.getVectorLength();
16484 unsigned RetWidth = Mask.getBitWidth();
16485
16486 APSInt RetMask(llvm::APInt(RetWidth, 0), /*isUnsigned=*/true);
16487
16488 for (unsigned ElemNum = 0; ElemNum < VectorLen; ++ElemNum) {
16489 const APSInt &A = LHS.getVectorElt(ElemNum).getInt();
16490 const APSInt &B = RHS.getVectorElt(ElemNum).getInt();
16491 bool Result = false;
16492
16493 switch (Opcode.getExtValue() & 0x7) {
16494 case 0: // _MM_CMPINT_EQ
16495 Result = (A == B);
16496 break;
16497 case 1: // _MM_CMPINT_LT
16498 Result = IsUnsigned ? A.ult(B) : A.slt(B);
16499 break;
16500 case 2: // _MM_CMPINT_LE
16501 Result = IsUnsigned ? A.ule(B) : A.sle(B);
16502 break;
16503 case 3: // _MM_CMPINT_FALSE
16504 Result = false;
16505 break;
16506 case 4: // _MM_CMPINT_NE
16507 Result = (A != B);
16508 break;
16509 case 5: // _MM_CMPINT_NLT (>=)
16510 Result = IsUnsigned ? A.uge(B) : A.sge(B);
16511 break;
16512 case 6: // _MM_CMPINT_NLE (>)
16513 Result = IsUnsigned ? A.ugt(B) : A.sgt(B);
16514 break;
16515 case 7: // _MM_CMPINT_TRUE
16516 Result = true;
16517 break;
16518 }
16519
16520 RetMask.setBitVal(ElemNum, Mask[ElemNum] && Result);
16521 }
16522
16523 return Success(APValue(RetMask), E);
16524 }
16525 }
16526}
16527
16528/// Determine whether this is a pointer past the end of the complete
16529/// object referred to by the lvalue.
16531 const LValue &LV) {
16532 // A null pointer can be viewed as being "past the end" but we don't
16533 // choose to look at it that way here.
16534 if (!LV.getLValueBase())
16535 return false;
16536
16537 // If the designator is valid and refers to a subobject, we're not pointing
16538 // past the end.
16539 if (!LV.getLValueDesignator().Invalid &&
16540 !LV.getLValueDesignator().isOnePastTheEnd())
16541 return false;
16542
16543 // A pointer to an incomplete type might be past-the-end if the type's size is
16544 // zero. We cannot tell because the type is incomplete.
16545 QualType Ty = getType(LV.getLValueBase());
16546 if (Ty->isIncompleteType())
16547 return true;
16548
16549 // Can't be past the end of an invalid object.
16550 if (LV.getLValueDesignator().Invalid)
16551 return false;
16552
16553 // We're a past-the-end pointer if we point to the byte after the object,
16554 // no matter what our type or path is.
16555 auto Size = Ctx.getTypeSizeInChars(Ty);
16556 return LV.getLValueOffset() == Size;
16557}
16558
16559namespace {
16560
16561/// Data recursive integer evaluator of certain binary operators.
16562///
16563/// We use a data recursive algorithm for binary operators so that we are able
16564/// to handle extreme cases of chained binary operators without causing stack
16565/// overflow.
16566class DataRecursiveIntBinOpEvaluator {
16567 struct EvalResult {
16568 APValue Val;
16569 bool Failed = false;
16570
16571 EvalResult() = default;
16572
16573 void swap(EvalResult &RHS) {
16574 Val.swap(RHS.Val);
16575 Failed = RHS.Failed;
16576 RHS.Failed = false;
16577 }
16578 };
16579
16580 struct Job {
16581 const Expr *E;
16582 EvalResult LHSResult; // meaningful only for binary operator expression.
16583 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
16584
16585 Job() = default;
16586 Job(Job &&) = default;
16587
16588 void startSpeculativeEval(EvalInfo &Info) {
16589 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
16590 }
16591
16592 private:
16593 SpeculativeEvaluationRAII SpecEvalRAII;
16594 };
16595
16596 SmallVector<Job, 16> Queue;
16597
16598 IntExprEvaluator &IntEval;
16599 EvalInfo &Info;
16600 APValue &FinalResult;
16601
16602public:
16603 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
16604 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
16605
16606 /// True if \param E is a binary operator that we are going to handle
16607 /// data recursively.
16608 /// We handle binary operators that are comma, logical, or that have operands
16609 /// with integral or enumeration type.
16610 static bool shouldEnqueue(const BinaryOperator *E) {
16611 return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
16615 }
16616
16617 bool Traverse(const BinaryOperator *E) {
16618 enqueue(E);
16619 EvalResult PrevResult;
16620 while (!Queue.empty())
16621 process(PrevResult);
16622
16623 if (PrevResult.Failed) return false;
16624
16625 FinalResult.swap(PrevResult.Val);
16626 return true;
16627 }
16628
16629private:
16630 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
16631 return IntEval.Success(Value, E, Result);
16632 }
16633 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
16634 return IntEval.Success(Value, E, Result);
16635 }
16636 bool Error(const Expr *E) {
16637 return IntEval.Error(E);
16638 }
16639 bool Error(const Expr *E, diag::kind D) {
16640 return IntEval.Error(E, D);
16641 }
16642
16643 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
16644 return Info.CCEDiag(E, D);
16645 }
16646
16647 // Returns true if visiting the RHS is necessary, false otherwise.
16648 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
16649 bool &SuppressRHSDiags);
16650
16651 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
16652 const BinaryOperator *E, APValue &Result);
16653
16654 void EvaluateExpr(const Expr *E, EvalResult &Result) {
16655 Result.Failed = !Evaluate(Result.Val, Info, E);
16656 if (Result.Failed)
16657 Result.Val = APValue();
16658 }
16659
16660 void process(EvalResult &Result);
16661
16662 void enqueue(const Expr *E) {
16663 E = E->IgnoreParens();
16664 Queue.resize(Queue.size()+1);
16665 Queue.back().E = E;
16666 Queue.back().Kind = Job::AnyExprKind;
16667 }
16668};
16669
16670}
16671
16672bool DataRecursiveIntBinOpEvaluator::
16673 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
16674 bool &SuppressRHSDiags) {
16675 if (E->getOpcode() == BO_Comma) {
16676 // Ignore LHS but note if we could not evaluate it.
16677 if (LHSResult.Failed)
16678 return Info.noteSideEffect();
16679 return true;
16680 }
16681
16682 if (E->isLogicalOp()) {
16683 bool LHSAsBool;
16684 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
16685 // We were able to evaluate the LHS, see if we can get away with not
16686 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
16687 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
16688 Success(LHSAsBool, E, LHSResult.Val);
16689 return false; // Ignore RHS
16690 }
16691 } else {
16692 LHSResult.Failed = true;
16693
16694 // Since we weren't able to evaluate the left hand side, it
16695 // might have had side effects.
16696 if (!Info.noteSideEffect())
16697 return false;
16698
16699 // We can't evaluate the LHS; however, sometimes the result
16700 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
16701 // Don't ignore RHS and suppress diagnostics from this arm.
16702 SuppressRHSDiags = true;
16703 }
16704
16705 return true;
16706 }
16707
16708 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
16710
16711 if (LHSResult.Failed && !Info.noteFailure())
16712 return false; // Ignore RHS;
16713
16714 return true;
16715}
16716
16717static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
16718 bool IsSub) {
16719 // Compute the new offset in the appropriate width, wrapping at 64 bits.
16720 // FIXME: When compiling for a 32-bit target, we should use 32-bit
16721 // offsets.
16722 assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
16723 CharUnits &Offset = LVal.getLValueOffset();
16724 uint64_t Offset64 = Offset.getQuantity();
16725 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
16726 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
16727 : Offset64 + Index64);
16728}
16729
16730bool DataRecursiveIntBinOpEvaluator::
16731 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
16732 const BinaryOperator *E, APValue &Result) {
16733 if (E->getOpcode() == BO_Comma) {
16734 if (RHSResult.Failed)
16735 return false;
16736 Result = RHSResult.Val;
16737 return true;
16738 }
16739
16740 if (E->isLogicalOp()) {
16741 bool lhsResult, rhsResult;
16742 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
16743 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
16744
16745 if (LHSIsOK) {
16746 if (RHSIsOK) {
16747 if (E->getOpcode() == BO_LOr)
16748 return Success(lhsResult || rhsResult, E, Result);
16749 else
16750 return Success(lhsResult && rhsResult, E, Result);
16751 }
16752 } else {
16753 if (RHSIsOK) {
16754 // We can't evaluate the LHS; however, sometimes the result
16755 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
16756 if (rhsResult == (E->getOpcode() == BO_LOr))
16757 return Success(rhsResult, E, Result);
16758 }
16759 }
16760
16761 return false;
16762 }
16763
16764 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
16766
16767 if (LHSResult.Failed || RHSResult.Failed)
16768 return false;
16769
16770 const APValue &LHSVal = LHSResult.Val;
16771 const APValue &RHSVal = RHSResult.Val;
16772
16773 // Handle cases like (unsigned long)&a + 4.
16774 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
16775 Result = LHSVal;
16776 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
16777 return true;
16778 }
16779
16780 // Handle cases like 4 + (unsigned long)&a
16781 if (E->getOpcode() == BO_Add &&
16782 RHSVal.isLValue() && LHSVal.isInt()) {
16783 Result = RHSVal;
16784 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
16785 return true;
16786 }
16787
16788 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
16789 // Handle (intptr_t)&&A - (intptr_t)&&B.
16790 if (!LHSVal.getLValueOffset().isZero() ||
16791 !RHSVal.getLValueOffset().isZero())
16792 return false;
16793 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
16794 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
16795 if (!LHSExpr || !RHSExpr)
16796 return false;
16797 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
16798 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
16799 if (!LHSAddrExpr || !RHSAddrExpr)
16800 return false;
16801 // Make sure both labels come from the same function.
16802 if (LHSAddrExpr->getLabel()->getDeclContext() !=
16803 RHSAddrExpr->getLabel()->getDeclContext())
16804 return false;
16805 Result = APValue(LHSAddrExpr, RHSAddrExpr);
16806 return true;
16807 }
16808
16809 // All the remaining cases expect both operands to be an integer
16810 if (!LHSVal.isInt() || !RHSVal.isInt())
16811 return Error(E);
16812
16813 // Set up the width and signedness manually, in case it can't be deduced
16814 // from the operation we're performing.
16815 // FIXME: Don't do this in the cases where we can deduce it.
16816 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
16818 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
16819 RHSVal.getInt(), Value))
16820 return false;
16821 return Success(Value, E, Result);
16822}
16823
16824void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
16825 Job &job = Queue.back();
16826
16827 switch (job.Kind) {
16828 case Job::AnyExprKind: {
16829 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
16830 if (shouldEnqueue(Bop)) {
16831 job.Kind = Job::BinOpKind;
16832 enqueue(Bop->getLHS());
16833 return;
16834 }
16835 }
16836
16837 EvaluateExpr(job.E, Result);
16838 Queue.pop_back();
16839 return;
16840 }
16841
16842 case Job::BinOpKind: {
16843 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
16844 bool SuppressRHSDiags = false;
16845 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
16846 Queue.pop_back();
16847 return;
16848 }
16849 if (SuppressRHSDiags)
16850 job.startSpeculativeEval(Info);
16851 job.LHSResult.swap(Result);
16852 job.Kind = Job::BinOpVisitedLHSKind;
16853 enqueue(Bop->getRHS());
16854 return;
16855 }
16856
16857 case Job::BinOpVisitedLHSKind: {
16858 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
16859 EvalResult RHS;
16860 RHS.swap(Result);
16861 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
16862 Queue.pop_back();
16863 return;
16864 }
16865 }
16866
16867 llvm_unreachable("Invalid Job::Kind!");
16868}
16869
16870namespace {
16871enum class CmpResult {
16872 Unequal,
16873 Less,
16874 Equal,
16875 Greater,
16876 Unordered,
16877};
16878}
16879
16880template <class SuccessCB, class AfterCB>
16881static bool
16883 SuccessCB &&Success, AfterCB &&DoAfter) {
16884 assert(!E->isValueDependent());
16885 assert(E->isComparisonOp() && "expected comparison operator");
16886 assert((E->getOpcode() == BO_Cmp ||
16888 "unsupported binary expression evaluation");
16889 auto Error = [&](const Expr *E) {
16890 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
16891 return false;
16892 };
16893
16894 bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp;
16895 bool IsEquality = E->isEqualityOp();
16896
16897 QualType LHSTy = E->getLHS()->getType();
16898 QualType RHSTy = E->getRHS()->getType();
16899
16900 if (LHSTy->isIntegralOrEnumerationType() &&
16901 RHSTy->isIntegralOrEnumerationType()) {
16902 APSInt LHS, RHS;
16903 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
16904 if (!LHSOK && !Info.noteFailure())
16905 return false;
16906 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
16907 return false;
16908 if (LHS < RHS)
16909 return Success(CmpResult::Less, E);
16910 if (LHS > RHS)
16911 return Success(CmpResult::Greater, E);
16912 return Success(CmpResult::Equal, E);
16913 }
16914
16915 if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
16916 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
16917 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
16918
16919 bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
16920 if (!LHSOK && !Info.noteFailure())
16921 return false;
16922 if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
16923 return false;
16924 if (LHSFX < RHSFX)
16925 return Success(CmpResult::Less, E);
16926 if (LHSFX > RHSFX)
16927 return Success(CmpResult::Greater, E);
16928 return Success(CmpResult::Equal, E);
16929 }
16930
16931 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
16932 ComplexValue LHS, RHS;
16933 bool LHSOK;
16934 if (E->isAssignmentOp()) {
16935 LValue LV;
16936 EvaluateLValue(E->getLHS(), LV, Info);
16937 LHSOK = false;
16938 } else if (LHSTy->isRealFloatingType()) {
16939 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
16940 if (LHSOK) {
16941 LHS.makeComplexFloat();
16942 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
16943 }
16944 } else {
16945 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
16946 }
16947 if (!LHSOK && !Info.noteFailure())
16948 return false;
16949
16950 if (E->getRHS()->getType()->isRealFloatingType()) {
16951 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
16952 return false;
16953 RHS.makeComplexFloat();
16954 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
16955 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
16956 return false;
16957
16958 if (LHS.isComplexFloat()) {
16959 APFloat::cmpResult CR_r =
16960 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
16961 APFloat::cmpResult CR_i =
16962 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
16963 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
16964 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
16965 } else {
16966 assert(IsEquality && "invalid complex comparison");
16967 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
16968 LHS.getComplexIntImag() == RHS.getComplexIntImag();
16969 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
16970 }
16971 }
16972
16973 if (LHSTy->isRealFloatingType() &&
16974 RHSTy->isRealFloatingType()) {
16975 APFloat RHS(0.0), LHS(0.0);
16976
16977 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
16978 if (!LHSOK && !Info.noteFailure())
16979 return false;
16980
16981 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
16982 return false;
16983
16984 assert(E->isComparisonOp() && "Invalid binary operator!");
16985 llvm::APFloatBase::cmpResult APFloatCmpResult = LHS.compare(RHS);
16986 if (!Info.InConstantContext &&
16987 APFloatCmpResult == APFloat::cmpUnordered &&
16989 // Note: Compares may raise invalid in some cases involving NaN or sNaN.
16990 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
16991 return false;
16992 }
16993 auto GetCmpRes = [&]() {
16994 switch (APFloatCmpResult) {
16995 case APFloat::cmpEqual:
16996 return CmpResult::Equal;
16997 case APFloat::cmpLessThan:
16998 return CmpResult::Less;
16999 case APFloat::cmpGreaterThan:
17000 return CmpResult::Greater;
17001 case APFloat::cmpUnordered:
17002 return CmpResult::Unordered;
17003 }
17004 llvm_unreachable("Unrecognised APFloat::cmpResult enum");
17005 };
17006 return Success(GetCmpRes(), E);
17007 }
17008
17009 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
17010 LValue LHSValue, RHSValue;
17011
17012 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
17013 if (!LHSOK && !Info.noteFailure())
17014 return false;
17015
17016 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
17017 return false;
17018
17019 // Reject differing bases from the normal codepath; we special-case
17020 // comparisons to null.
17021 if (!HasSameBase(LHSValue, RHSValue)) {
17022 // Bail out early if we're checking potential constant expression.
17023 // Otherwise, prefer to diagnose other issues.
17024 if (Info.checkingPotentialConstantExpression() &&
17025 (LHSValue.AllowConstexprUnknown || RHSValue.AllowConstexprUnknown))
17026 return false;
17027 auto DiagComparison = [&] (unsigned DiagID, bool Reversed = false) {
17028 std::string LHS = LHSValue.toString(Info.Ctx, E->getLHS()->getType());
17029 std::string RHS = RHSValue.toString(Info.Ctx, E->getRHS()->getType());
17030 Info.FFDiag(E, DiagID)
17031 << (Reversed ? RHS : LHS) << (Reversed ? LHS : RHS);
17032 return false;
17033 };
17034 // Inequalities and subtractions between unrelated pointers have
17035 // unspecified or undefined behavior.
17036 if (!IsEquality)
17037 return DiagComparison(
17038 diag::note_constexpr_pointer_comparison_unspecified);
17039 // A constant address may compare equal to the address of a symbol.
17040 // The one exception is that address of an object cannot compare equal
17041 // to a null pointer constant.
17042 // TODO: Should we restrict this to actual null pointers, and exclude the
17043 // case of zero cast to pointer type?
17044 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
17045 (!RHSValue.Base && !RHSValue.Offset.isZero()))
17046 return DiagComparison(diag::note_constexpr_pointer_constant_comparison,
17047 !RHSValue.Base);
17048 // C++2c [intro.object]/10:
17049 // Two objects [...] may have the same address if [...] they are both
17050 // potentially non-unique objects.
17051 // C++2c [intro.object]/9:
17052 // An object is potentially non-unique if it is a string literal object,
17053 // the backing array of an initializer list, or a subobject thereof.
17054 //
17055 // This makes the comparison result unspecified, so it's not a constant
17056 // expression.
17057 //
17058 // TODO: Do we need to handle the initializer list case here?
17059 if (ArePotentiallyOverlappingStringLiterals(Info, LHSValue, RHSValue))
17060 return DiagComparison(diag::note_constexpr_literal_comparison);
17061 if (IsOpaqueConstantCall(LHSValue) || IsOpaqueConstantCall(RHSValue))
17062 return DiagComparison(diag::note_constexpr_opaque_call_comparison,
17063 !IsOpaqueConstantCall(LHSValue));
17064 // We can't tell whether weak symbols will end up pointing to the same
17065 // object.
17066 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
17067 return DiagComparison(diag::note_constexpr_pointer_weak_comparison,
17068 !IsWeakLValue(LHSValue));
17069 // We can't compare the address of the start of one object with the
17070 // past-the-end address of another object, per C++ DR1652.
17071 if (LHSValue.Base && LHSValue.Offset.isZero() &&
17072 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue))
17073 return DiagComparison(diag::note_constexpr_pointer_comparison_past_end,
17074 true);
17075 if (RHSValue.Base && RHSValue.Offset.isZero() &&
17076 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue))
17077 return DiagComparison(diag::note_constexpr_pointer_comparison_past_end,
17078 false);
17079 // We can't tell whether an object is at the same address as another
17080 // zero sized object.
17081 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
17082 (LHSValue.Base && isZeroSized(RHSValue)))
17083 return DiagComparison(
17084 diag::note_constexpr_pointer_comparison_zero_sized);
17085 if (LHSValue.AllowConstexprUnknown || RHSValue.AllowConstexprUnknown)
17086 return DiagComparison(
17087 diag::note_constexpr_pointer_comparison_unspecified);
17088 // FIXME: Verify both variables are live.
17089 return Success(CmpResult::Unequal, E);
17090 }
17091
17092 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
17093 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
17094
17095 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
17096 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
17097
17098 // C++11 [expr.rel]p2:
17099 // - If two pointers point to non-static data members of the same object,
17100 // or to subobjects or array elements fo such members, recursively, the
17101 // pointer to the later declared member compares greater provided the
17102 // two members have the same access control and provided their class is
17103 // not a union.
17104 // [...]
17105 // - Otherwise pointer comparisons are unspecified.
17106 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
17107 bool WasArrayIndex;
17108 unsigned Mismatch = FindDesignatorMismatch(
17109 LHSValue.Base.isNull() ? QualType()
17110 : getType(LHSValue.Base).getNonReferenceType(),
17111 LHSDesignator, RHSDesignator, WasArrayIndex);
17112 // At the point where the designators diverge, the comparison has a
17113 // specified value if:
17114 // - we are comparing array indices
17115 // - we are comparing fields of a union, or fields with the same access
17116 // Otherwise, the result is unspecified and thus the comparison is not a
17117 // constant expression.
17118 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
17119 Mismatch < RHSDesignator.Entries.size()) {
17120 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
17121 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
17122 if (!LF && !RF)
17123 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
17124 else if (!LF)
17125 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
17126 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
17127 << RF->getParent() << RF;
17128 else if (!RF)
17129 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
17130 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
17131 << LF->getParent() << LF;
17132 else if (!LF->getParent()->isUnion() &&
17133 LF->getAccess() != RF->getAccess())
17134 Info.CCEDiag(E,
17135 diag::note_constexpr_pointer_comparison_differing_access)
17136 << LF << LF->getAccess() << RF << RF->getAccess()
17137 << LF->getParent();
17138 }
17139 }
17140
17141 // The comparison here must be unsigned, and performed with the same
17142 // width as the pointer.
17143 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
17144 uint64_t CompareLHS = LHSOffset.getQuantity();
17145 uint64_t CompareRHS = RHSOffset.getQuantity();
17146 assert(PtrSize <= 64 && "Unexpected pointer width");
17147 uint64_t Mask = ~0ULL >> (64 - PtrSize);
17148 CompareLHS &= Mask;
17149 CompareRHS &= Mask;
17150
17151 // If there is a base and this is a relational operator, we can only
17152 // compare pointers within the object in question; otherwise, the result
17153 // depends on where the object is located in memory.
17154 if (!LHSValue.Base.isNull() && IsRelational) {
17155 QualType BaseTy = getType(LHSValue.Base).getNonReferenceType();
17156 if (BaseTy->isIncompleteType())
17157 return Error(E);
17158 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
17159 uint64_t OffsetLimit = Size.getQuantity();
17160 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
17161 return Error(E);
17162 }
17163
17164 if (CompareLHS < CompareRHS)
17165 return Success(CmpResult::Less, E);
17166 if (CompareLHS > CompareRHS)
17167 return Success(CmpResult::Greater, E);
17168 return Success(CmpResult::Equal, E);
17169 }
17170
17171 if (LHSTy->isMemberPointerType()) {
17172 assert(IsEquality && "unexpected member pointer operation");
17173 assert(RHSTy->isMemberPointerType() && "invalid comparison");
17174
17175 MemberPtr LHSValue, RHSValue;
17176
17177 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
17178 if (!LHSOK && !Info.noteFailure())
17179 return false;
17180
17181 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
17182 return false;
17183
17184 // If either operand is a pointer to a weak function, the comparison is not
17185 // constant.
17186 if (LHSValue.getDecl() && LHSValue.getDecl()->isWeak()) {
17187 Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison)
17188 << LHSValue.getDecl();
17189 return false;
17190 }
17191 if (RHSValue.getDecl() && RHSValue.getDecl()->isWeak()) {
17192 Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison)
17193 << RHSValue.getDecl();
17194 return false;
17195 }
17196
17197 // C++11 [expr.eq]p2:
17198 // If both operands are null, they compare equal. Otherwise if only one is
17199 // null, they compare unequal.
17200 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
17201 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
17202 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
17203 }
17204
17205 // Otherwise if either is a pointer to a virtual member function, the
17206 // result is unspecified.
17207 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
17208 if (MD->isVirtual())
17209 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
17210 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
17211 if (MD->isVirtual())
17212 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
17213
17214 // Otherwise they compare equal if and only if they would refer to the
17215 // same member of the same most derived object or the same subobject if
17216 // they were dereferenced with a hypothetical object of the associated
17217 // class type.
17218 bool Equal = LHSValue == RHSValue;
17219 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
17220 }
17221
17222 if (LHSTy->isNullPtrType()) {
17223 assert(E->isComparisonOp() && "unexpected nullptr operation");
17224 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
17225 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
17226 // are compared, the result is true of the operator is <=, >= or ==, and
17227 // false otherwise.
17228 LValue Res;
17229 if (!EvaluatePointer(E->getLHS(), Res, Info) ||
17230 !EvaluatePointer(E->getRHS(), Res, Info))
17231 return false;
17232 return Success(CmpResult::Equal, E);
17233 }
17234
17235 return DoAfter();
17236}
17237
17238bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
17239 if (!CheckLiteralType(Info, E))
17240 return false;
17241
17242 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
17244 switch (CR) {
17245 case CmpResult::Unequal:
17246 llvm_unreachable("should never produce Unequal for three-way comparison");
17247 case CmpResult::Less:
17248 CCR = ComparisonCategoryResult::Less;
17249 break;
17250 case CmpResult::Equal:
17251 CCR = ComparisonCategoryResult::Equal;
17252 break;
17253 case CmpResult::Greater:
17254 CCR = ComparisonCategoryResult::Greater;
17255 break;
17256 case CmpResult::Unordered:
17257 CCR = ComparisonCategoryResult::Unordered;
17258 break;
17259 }
17260 // Evaluation succeeded. Lookup the information for the comparison category
17261 // type and fetch the VarDecl for the result.
17262 const ComparisonCategoryInfo &CmpInfo =
17263 Info.Ctx.CompCategories.getInfoForType(E->getType());
17264 const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD;
17265 // Check and evaluate the result as a constant expression.
17266 LValue LV;
17267 LV.set(VD);
17268 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
17269 return false;
17270 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
17271 ConstantExprKind::Normal);
17272 };
17273 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
17274 return ExprEvaluatorBaseTy::VisitBinCmp(E);
17275 });
17276}
17277
17278bool RecordExprEvaluator::VisitCXXParenListInitExpr(
17279 const CXXParenListInitExpr *E) {
17280 return VisitCXXParenListOrInitListExpr(E, E->getInitExprs());
17281}
17282
17283bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
17284 // We don't support assignment in C. C++ assignments don't get here because
17285 // assignment is an lvalue in C++.
17286 if (E->isAssignmentOp()) {
17287 Error(E);
17288 if (!Info.noteFailure())
17289 return false;
17290 }
17291
17292 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
17293 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
17294
17295 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
17297 "DataRecursiveIntBinOpEvaluator should have handled integral types");
17298
17299 if (E->isComparisonOp()) {
17300 // Evaluate builtin binary comparisons by evaluating them as three-way
17301 // comparisons and then translating the result.
17302 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
17303 assert((CR != CmpResult::Unequal || E->isEqualityOp()) &&
17304 "should only produce Unequal for equality comparisons");
17305 bool IsEqual = CR == CmpResult::Equal,
17306 IsLess = CR == CmpResult::Less,
17307 IsGreater = CR == CmpResult::Greater;
17308 auto Op = E->getOpcode();
17309 switch (Op) {
17310 default:
17311 llvm_unreachable("unsupported binary operator");
17312 case BO_EQ:
17313 case BO_NE:
17314 return Success(IsEqual == (Op == BO_EQ), E);
17315 case BO_LT:
17316 return Success(IsLess, E);
17317 case BO_GT:
17318 return Success(IsGreater, E);
17319 case BO_LE:
17320 return Success(IsEqual || IsLess, E);
17321 case BO_GE:
17322 return Success(IsEqual || IsGreater, E);
17323 }
17324 };
17325 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
17326 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
17327 });
17328 }
17329
17330 QualType LHSTy = E->getLHS()->getType();
17331 QualType RHSTy = E->getRHS()->getType();
17332
17333 if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
17334 E->getOpcode() == BO_Sub) {
17335 LValue LHSValue, RHSValue;
17336
17337 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
17338 if (!LHSOK && !Info.noteFailure())
17339 return false;
17340
17341 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
17342 return false;
17343
17344 // Reject differing bases from the normal codepath; we special-case
17345 // comparisons to null.
17346 if (!HasSameBase(LHSValue, RHSValue)) {
17347 if (Info.checkingPotentialConstantExpression() &&
17348 (LHSValue.AllowConstexprUnknown || RHSValue.AllowConstexprUnknown))
17349 return false;
17350
17351 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
17352 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
17353
17354 auto DiagArith = [&](unsigned DiagID) {
17355 std::string LHS = LHSValue.toString(Info.Ctx, E->getLHS()->getType());
17356 std::string RHS = RHSValue.toString(Info.Ctx, E->getRHS()->getType());
17357 Info.FFDiag(E, DiagID) << LHS << RHS;
17358 if (LHSExpr && LHSExpr == RHSExpr)
17359 Info.Note(LHSExpr->getExprLoc(),
17360 diag::note_constexpr_repeated_literal_eval)
17361 << LHSExpr->getSourceRange();
17362 return false;
17363 };
17364
17365 if (!LHSExpr || !RHSExpr)
17366 return DiagArith(diag::note_constexpr_pointer_arith_unspecified);
17367
17368 if (ArePotentiallyOverlappingStringLiterals(Info, LHSValue, RHSValue))
17369 return DiagArith(diag::note_constexpr_literal_arith);
17370
17371 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
17372 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
17373 if (!LHSAddrExpr || !RHSAddrExpr)
17374 return Error(E);
17375 // Make sure both labels come from the same function.
17376 if (LHSAddrExpr->getLabel()->getDeclContext() !=
17377 RHSAddrExpr->getLabel()->getDeclContext())
17378 return Error(E);
17379 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
17380 }
17381 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
17382 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
17383
17384 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
17385 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
17386
17387 // C++11 [expr.add]p6:
17388 // Unless both pointers point to elements of the same array object, or
17389 // one past the last element of the array object, the behavior is
17390 // undefined.
17391 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
17392 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
17393 RHSDesignator))
17394 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
17395
17396 QualType Type = E->getLHS()->getType();
17397 QualType ElementType = Type->castAs<PointerType>()->getPointeeType();
17398
17399 CharUnits ElementSize;
17400 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
17401 return false;
17402
17403 // As an extension, a type may have zero size (empty struct or union in
17404 // C, array of zero length). Pointer subtraction in such cases has
17405 // undefined behavior, so is not constant.
17406 if (ElementSize.isZero()) {
17407 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
17408 << ElementType;
17409 return false;
17410 }
17411
17412 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
17413 // and produce incorrect results when it overflows. Such behavior
17414 // appears to be non-conforming, but is common, so perhaps we should
17415 // assume the standard intended for such cases to be undefined behavior
17416 // and check for them.
17417
17418 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
17419 // overflow in the final conversion to ptrdiff_t.
17420 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
17421 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
17422 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
17423 false);
17424 APSInt TrueResult = (LHS - RHS) / ElemSize;
17425 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
17426
17427 if (Result.extend(65) != TrueResult &&
17428 !HandleOverflow(Info, E, TrueResult, E->getType()))
17429 return false;
17430 return Success(Result, E);
17431 }
17432
17433 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
17434}
17435
17436/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
17437/// a result as the expression's type.
17438bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
17439 const UnaryExprOrTypeTraitExpr *E) {
17440 switch(E->getKind()) {
17441 case UETT_PreferredAlignOf:
17442 case UETT_AlignOf: {
17443 if (E->isArgumentType())
17444 return Success(
17445 GetAlignOfType(Info.Ctx, E->getArgumentType(), E->getKind()), E);
17446 else
17447 return Success(
17448 GetAlignOfExpr(Info.Ctx, E->getArgumentExpr(), E->getKind()), E);
17449 }
17450
17451 case UETT_PtrAuthTypeDiscriminator: {
17452 if (E->getArgumentType()->isDependentType())
17453 return false;
17454 return Success(
17456 }
17457 case UETT_VecStep: {
17458 QualType Ty = E->getTypeOfArgument();
17459
17460 if (Ty->isVectorType()) {
17461 unsigned n = Ty->castAs<VectorType>()->getNumElements();
17462
17463 // The vec_step built-in functions that take a 3-component
17464 // vector return 4. (OpenCL 1.1 spec 6.11.12)
17465 if (n == 3)
17466 n = 4;
17467
17468 return Success(n, E);
17469 } else
17470 return Success(1, E);
17471 }
17472
17473 case UETT_DataSizeOf:
17474 case UETT_SizeOf: {
17475 QualType SrcTy = E->getTypeOfArgument();
17476 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
17477 // the result is the size of the referenced type."
17478 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
17479 SrcTy = Ref->getPointeeType();
17480
17481 CharUnits Sizeof;
17482 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof,
17483 E->getKind() == UETT_DataSizeOf ? SizeOfType::DataSizeOf
17484 : SizeOfType::SizeOf)) {
17485 return false;
17486 }
17487 return Success(Sizeof, E);
17488 }
17489 case UETT_OpenMPRequiredSimdAlign:
17490 assert(E->isArgumentType());
17491 return Success(
17492 Info.Ctx.toCharUnitsFromBits(
17494 .getQuantity(),
17495 E);
17496 case UETT_VectorElements: {
17497 QualType Ty = E->getTypeOfArgument();
17498 // If the vector has a fixed size, we can determine the number of elements
17499 // at compile time.
17500 if (const auto *VT = Ty->getAs<VectorType>())
17501 return Success(VT->getNumElements(), E);
17502
17503 assert(Ty->isSizelessVectorType());
17504 if (Info.InConstantContext)
17505 Info.CCEDiag(E, diag::note_constexpr_non_const_vectorelements)
17506 << E->getSourceRange();
17507
17508 return false;
17509 }
17510 case UETT_CountOf: {
17511 QualType Ty = E->getTypeOfArgument();
17512 assert(Ty->isArrayType());
17513
17514 // We don't need to worry about array element qualifiers, so getting the
17515 // unsafe array type is fine.
17516 if (const auto *CAT =
17517 dyn_cast<ConstantArrayType>(Ty->getAsArrayTypeUnsafe())) {
17518 return Success(CAT->getSize(), E);
17519 }
17520
17521 assert(!Ty->isConstantSizeType());
17522
17523 // If it's a variable-length array type, we need to check whether it is a
17524 // multidimensional array. If so, we need to check the size expression of
17525 // the VLA to see if it's a constant size. If so, we can return that value.
17526 const auto *VAT = Info.Ctx.getAsVariableArrayType(Ty);
17527 assert(VAT);
17528 if (VAT->getElementType()->isArrayType()) {
17529 // Variable array size expression could be missing (e.g. int a[*][10]) In
17530 // that case, it can't be a constant expression.
17531 if (!VAT->getSizeExpr()) {
17532 Info.FFDiag(E->getBeginLoc());
17533 return false;
17534 }
17535
17536 std::optional<APSInt> Res =
17537 VAT->getSizeExpr()->getIntegerConstantExpr(Info.Ctx);
17538 if (Res) {
17539 // The resulting value always has type size_t, so we need to make the
17540 // returned APInt have the correct sign and bit-width.
17541 APInt Val{
17542 static_cast<unsigned>(Info.Ctx.getTypeSize(Info.Ctx.getSizeType())),
17543 Res->getZExtValue()};
17544 return Success(Val, E);
17545 }
17546 }
17547
17548 // Definitely a variable-length type, which is not an ICE.
17549 // FIXME: Better diagnostic.
17550 Info.FFDiag(E->getBeginLoc());
17551 return false;
17552 }
17553 }
17554
17555 llvm_unreachable("unknown expr/type trait");
17556}
17557
17558bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
17559 CharUnits Result;
17560 unsigned n = OOE->getNumComponents();
17561 if (n == 0)
17562 return Error(OOE);
17563 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
17564 for (unsigned i = 0; i != n; ++i) {
17565 OffsetOfNode ON = OOE->getComponent(i);
17566 switch (ON.getKind()) {
17567 case OffsetOfNode::Array: {
17568 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
17569 APSInt IdxResult;
17570 if (!EvaluateInteger(Idx, IdxResult, Info))
17571 return false;
17572 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
17573 if (!AT)
17574 return Error(OOE);
17575 CurrentType = AT->getElementType();
17576 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
17577 Result += IdxResult.getSExtValue() * ElementSize;
17578 break;
17579 }
17580
17581 case OffsetOfNode::Field: {
17582 FieldDecl *MemberDecl = ON.getField();
17583 const auto *RD = CurrentType->getAsRecordDecl();
17584 if (!RD)
17585 return Error(OOE);
17586 if (RD->isInvalidDecl()) return false;
17587 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
17588 unsigned i = MemberDecl->getFieldIndex();
17589 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
17590 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
17591 CurrentType = MemberDecl->getType().getNonReferenceType();
17592 break;
17593 }
17594
17596 llvm_unreachable("dependent __builtin_offsetof");
17597
17598 case OffsetOfNode::Base: {
17599 CXXBaseSpecifier *BaseSpec = ON.getBase();
17600 if (BaseSpec->isVirtual())
17601 return Error(OOE);
17602
17603 // Find the layout of the class whose base we are looking into.
17604 const auto *RD = CurrentType->getAsCXXRecordDecl();
17605 if (!RD)
17606 return Error(OOE);
17607 if (RD->isInvalidDecl()) return false;
17608 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
17609
17610 // Find the base class itself.
17611 CurrentType = BaseSpec->getType();
17612 const auto *BaseRD = CurrentType->getAsCXXRecordDecl();
17613 if (!BaseRD)
17614 return Error(OOE);
17615
17616 // Add the offset to the base.
17617 Result += RL.getBaseClassOffset(BaseRD);
17618 break;
17619 }
17620 }
17621 }
17622 return Success(Result, OOE);
17623}
17624
17625bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
17626 switch (E->getOpcode()) {
17627 default:
17628 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
17629 // See C99 6.6p3.
17630 return Error(E);
17631 case UO_Extension:
17632 // FIXME: Should extension allow i-c-e extension expressions in its scope?
17633 // If so, we could clear the diagnostic ID.
17634 return Visit(E->getSubExpr());
17635 case UO_Plus:
17636 // The result is just the value.
17637 return Visit(E->getSubExpr());
17638 case UO_Minus: {
17639 if (!Visit(E->getSubExpr()))
17640 return false;
17641 if (!Result.isInt()) return Error(E);
17642 const APSInt &Value = Result.getInt();
17643 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow()) {
17644 if (Info.checkingForUndefinedBehavior())
17645 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
17646 diag::warn_integer_constant_overflow)
17647 << toString(Value, 10, Value.isSigned(), /*formatAsCLiteral=*/false,
17648 /*UpperCase=*/true, /*InsertSeparators=*/true)
17649 << E->getType() << E->getSourceRange();
17650
17651 if (!HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
17652 E->getType()))
17653 return false;
17654 }
17655 return Success(-Value, E);
17656 }
17657 case UO_Not: {
17658 if (!Visit(E->getSubExpr()))
17659 return false;
17660 if (!Result.isInt()) return Error(E);
17661 return Success(~Result.getInt(), E);
17662 }
17663 case UO_LNot: {
17664 bool bres;
17665 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
17666 return false;
17667 return Success(!bres, E);
17668 }
17669 }
17670}
17671
17672/// HandleCast - This is used to evaluate implicit or explicit casts where the
17673/// result type is integer.
17674bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
17675 const Expr *SubExpr = E->getSubExpr();
17676 QualType DestType = E->getType();
17677 QualType SrcType = SubExpr->getType();
17678
17679 switch (E->getCastKind()) {
17680 case CK_BaseToDerived:
17681 case CK_DerivedToBase:
17682 case CK_UncheckedDerivedToBase:
17683 case CK_Dynamic:
17684 case CK_ToUnion:
17685 case CK_ArrayToPointerDecay:
17686 case CK_FunctionToPointerDecay:
17687 case CK_NullToPointer:
17688 case CK_NullToMemberPointer:
17689 case CK_BaseToDerivedMemberPointer:
17690 case CK_DerivedToBaseMemberPointer:
17691 case CK_ReinterpretMemberPointer:
17692 case CK_ConstructorConversion:
17693 case CK_IntegralToPointer:
17694 case CK_ToVoid:
17695 case CK_VectorSplat:
17696 case CK_IntegralToFloating:
17697 case CK_FloatingCast:
17698 case CK_CPointerToObjCPointerCast:
17699 case CK_BlockPointerToObjCPointerCast:
17700 case CK_AnyPointerToBlockPointerCast:
17701 case CK_ObjCObjectLValueCast:
17702 case CK_FloatingRealToComplex:
17703 case CK_FloatingComplexToReal:
17704 case CK_FloatingComplexCast:
17705 case CK_FloatingComplexToIntegralComplex:
17706 case CK_IntegralRealToComplex:
17707 case CK_IntegralComplexCast:
17708 case CK_IntegralComplexToFloatingComplex:
17709 case CK_BuiltinFnToFnPtr:
17710 case CK_ZeroToOCLOpaqueType:
17711 case CK_NonAtomicToAtomic:
17712 case CK_AddressSpaceConversion:
17713 case CK_IntToOCLSampler:
17714 case CK_FloatingToFixedPoint:
17715 case CK_FixedPointToFloating:
17716 case CK_FixedPointCast:
17717 case CK_IntegralToFixedPoint:
17718 case CK_MatrixCast:
17719 case CK_HLSLAggregateSplatCast:
17720 llvm_unreachable("invalid cast kind for integral value");
17721
17722 case CK_BitCast:
17723 case CK_Dependent:
17724 case CK_LValueBitCast:
17725 case CK_ARCProduceObject:
17726 case CK_ARCConsumeObject:
17727 case CK_ARCReclaimReturnedObject:
17728 case CK_ARCExtendBlockObject:
17729 case CK_CopyAndAutoreleaseBlockObject:
17730 return Error(E);
17731
17732 case CK_UserDefinedConversion:
17733 case CK_LValueToRValue:
17734 case CK_AtomicToNonAtomic:
17735 case CK_NoOp:
17736 case CK_LValueToRValueBitCast:
17737 case CK_HLSLArrayRValue:
17738 return ExprEvaluatorBaseTy::VisitCastExpr(E);
17739
17740 case CK_MemberPointerToBoolean:
17741 case CK_PointerToBoolean:
17742 case CK_IntegralToBoolean:
17743 case CK_FloatingToBoolean:
17744 case CK_BooleanToSignedIntegral:
17745 case CK_FloatingComplexToBoolean:
17746 case CK_IntegralComplexToBoolean: {
17747 bool BoolResult;
17748 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
17749 return false;
17750 uint64_t IntResult = BoolResult;
17751 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
17752 IntResult = (uint64_t)-1;
17753 return Success(IntResult, E);
17754 }
17755
17756 case CK_FixedPointToIntegral: {
17757 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
17758 if (!EvaluateFixedPoint(SubExpr, Src, Info))
17759 return false;
17760 bool Overflowed;
17761 llvm::APSInt Result = Src.convertToInt(
17762 Info.Ctx.getIntWidth(DestType),
17763 DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
17764 if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
17765 return false;
17766 return Success(Result, E);
17767 }
17768
17769 case CK_FixedPointToBoolean: {
17770 // Unsigned padding does not affect this.
17771 APValue Val;
17772 if (!Evaluate(Val, Info, SubExpr))
17773 return false;
17774 return Success(Val.getFixedPoint().getBoolValue(), E);
17775 }
17776
17777 case CK_IntegralCast: {
17778 if (!Visit(SubExpr))
17779 return false;
17780
17781 if (!Result.isInt()) {
17782 // Allow casts of address-of-label differences if they are no-ops
17783 // or narrowing. (The narrowing case isn't actually guaranteed to
17784 // be constant-evaluatable except in some narrow cases which are hard
17785 // to detect here. We let it through on the assumption the user knows
17786 // what they are doing.)
17787 if (Result.isAddrLabelDiff())
17788 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
17789 // Only allow casts of lvalues if they are lossless.
17790 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
17791 }
17792
17793 if (Info.Ctx.getLangOpts().CPlusPlus && DestType->isEnumeralType()) {
17794 const auto *ED = DestType->getAsEnumDecl();
17795 // Check that the value is within the range of the enumeration values.
17796 //
17797 // This corressponds to [expr.static.cast]p10 which says:
17798 // A value of integral or enumeration type can be explicitly converted
17799 // to a complete enumeration type ... If the enumeration type does not
17800 // have a fixed underlying type, the value is unchanged if the original
17801 // value is within the range of the enumeration values ([dcl.enum]), and
17802 // otherwise, the behavior is undefined.
17803 //
17804 // This was resolved as part of DR2338 which has CD5 status.
17805 if (!ED->isFixed()) {
17806 llvm::APInt Min;
17807 llvm::APInt Max;
17808
17809 ED->getValueRange(Max, Min);
17810 --Max;
17811
17812 if (ED->getNumNegativeBits() &&
17813 (Max.slt(Result.getInt().getSExtValue()) ||
17814 Min.sgt(Result.getInt().getSExtValue())))
17815 Info.CCEDiag(E, diag::note_constexpr_unscoped_enum_out_of_range)
17816 << llvm::toString(Result.getInt(), 10) << Min.getSExtValue()
17817 << Max.getSExtValue() << ED;
17818 else if (!ED->getNumNegativeBits() &&
17819 Max.ult(Result.getInt().getZExtValue()))
17820 Info.CCEDiag(E, diag::note_constexpr_unscoped_enum_out_of_range)
17821 << llvm::toString(Result.getInt(), 10) << Min.getZExtValue()
17822 << Max.getZExtValue() << ED;
17823 }
17824 }
17825
17826 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
17827 Result.getInt()), E);
17828 }
17829
17830 case CK_PointerToIntegral: {
17831 CCEDiag(E, diag::note_constexpr_invalid_cast)
17832 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
17833 << Info.Ctx.getLangOpts().CPlusPlus << E->getSourceRange();
17834
17835 LValue LV;
17836 if (!EvaluatePointer(SubExpr, LV, Info))
17837 return false;
17838
17839 if (LV.getLValueBase()) {
17840 // Only allow based lvalue casts if they are lossless.
17841 // FIXME: Allow a larger integer size than the pointer size, and allow
17842 // narrowing back down to pointer width in subsequent integral casts.
17843 // FIXME: Check integer type's active bits, not its type size.
17844 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
17845 return Error(E);
17846
17847 LV.Designator.setInvalid();
17848 LV.moveInto(Result);
17849 return true;
17850 }
17851
17852 APSInt AsInt;
17853 APValue V;
17854 LV.moveInto(V);
17855 if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
17856 llvm_unreachable("Can't cast this!");
17857
17858 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
17859 }
17860
17861 case CK_IntegralComplexToReal: {
17862 ComplexValue C;
17863 if (!EvaluateComplex(SubExpr, C, Info))
17864 return false;
17865 return Success(C.getComplexIntReal(), E);
17866 }
17867
17868 case CK_FloatingToIntegral: {
17869 APFloat F(0.0);
17870 if (!EvaluateFloat(SubExpr, F, Info))
17871 return false;
17872
17873 APSInt Value;
17874 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
17875 return false;
17876 return Success(Value, E);
17877 }
17878 case CK_HLSLVectorTruncation: {
17879 APValue Val;
17880 if (!EvaluateVector(SubExpr, Val, Info))
17881 return Error(E);
17882 return Success(Val.getVectorElt(0), E);
17883 }
17884 case CK_HLSLElementwiseCast: {
17885 SmallVector<APValue> SrcVals;
17886 SmallVector<QualType> SrcTypes;
17887
17888 if (!hlslElementwiseCastHelper(Info, SubExpr, DestType, SrcVals, SrcTypes))
17889 return false;
17890
17891 // cast our single element
17892 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
17893 APValue ResultVal;
17894 if (!handleScalarCast(Info, FPO, E, SrcTypes[0], DestType, SrcVals[0],
17895 ResultVal))
17896 return false;
17897 return Success(ResultVal, E);
17898 }
17899 }
17900
17901 llvm_unreachable("unknown cast resulting in integral value");
17902}
17903
17904bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
17905 if (E->getSubExpr()->getType()->isAnyComplexType()) {
17906 ComplexValue LV;
17907 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
17908 return false;
17909 if (!LV.isComplexInt())
17910 return Error(E);
17911 return Success(LV.getComplexIntReal(), E);
17912 }
17913
17914 return Visit(E->getSubExpr());
17915}
17916
17917bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
17918 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
17919 ComplexValue LV;
17920 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
17921 return false;
17922 if (!LV.isComplexInt())
17923 return Error(E);
17924 return Success(LV.getComplexIntImag(), E);
17925 }
17926
17927 VisitIgnoredValue(E->getSubExpr());
17928 return Success(0, E);
17929}
17930
17931bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
17932 return Success(E->getPackLength(), E);
17933}
17934
17935bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
17936 return Success(E->getValue(), E);
17937}
17938
17939bool IntExprEvaluator::VisitConceptSpecializationExpr(
17940 const ConceptSpecializationExpr *E) {
17941 return Success(E->isSatisfied(), E);
17942}
17943
17944bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) {
17945 return Success(E->isSatisfied(), E);
17946}
17947
17948bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
17949 switch (E->getOpcode()) {
17950 default:
17951 // Invalid unary operators
17952 return Error(E);
17953 case UO_Plus:
17954 // The result is just the value.
17955 return Visit(E->getSubExpr());
17956 case UO_Minus: {
17957 if (!Visit(E->getSubExpr())) return false;
17958 if (!Result.isFixedPoint())
17959 return Error(E);
17960 bool Overflowed;
17961 APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
17962 if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
17963 return false;
17964 return Success(Negated, E);
17965 }
17966 case UO_LNot: {
17967 bool bres;
17968 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
17969 return false;
17970 return Success(!bres, E);
17971 }
17972 }
17973}
17974
17975bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
17976 const Expr *SubExpr = E->getSubExpr();
17977 QualType DestType = E->getType();
17978 assert(DestType->isFixedPointType() &&
17979 "Expected destination type to be a fixed point type");
17980 auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
17981
17982 switch (E->getCastKind()) {
17983 case CK_FixedPointCast: {
17984 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
17985 if (!EvaluateFixedPoint(SubExpr, Src, Info))
17986 return false;
17987 bool Overflowed;
17988 APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
17989 if (Overflowed) {
17990 if (Info.checkingForUndefinedBehavior())
17991 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
17992 diag::warn_fixedpoint_constant_overflow)
17993 << Result.toString() << E->getType();
17994 if (!HandleOverflow(Info, E, Result, E->getType()))
17995 return false;
17996 }
17997 return Success(Result, E);
17998 }
17999 case CK_IntegralToFixedPoint: {
18000 APSInt Src;
18001 if (!EvaluateInteger(SubExpr, Src, Info))
18002 return false;
18003
18004 bool Overflowed;
18005 APFixedPoint IntResult = APFixedPoint::getFromIntValue(
18006 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
18007
18008 if (Overflowed) {
18009 if (Info.checkingForUndefinedBehavior())
18010 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
18011 diag::warn_fixedpoint_constant_overflow)
18012 << IntResult.toString() << E->getType();
18013 if (!HandleOverflow(Info, E, IntResult, E->getType()))
18014 return false;
18015 }
18016
18017 return Success(IntResult, E);
18018 }
18019 case CK_FloatingToFixedPoint: {
18020 APFloat Src(0.0);
18021 if (!EvaluateFloat(SubExpr, Src, Info))
18022 return false;
18023
18024 bool Overflowed;
18025 APFixedPoint Result = APFixedPoint::getFromFloatValue(
18026 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
18027
18028 if (Overflowed) {
18029 if (Info.checkingForUndefinedBehavior())
18030 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
18031 diag::warn_fixedpoint_constant_overflow)
18032 << Result.toString() << E->getType();
18033 if (!HandleOverflow(Info, E, Result, E->getType()))
18034 return false;
18035 }
18036
18037 return Success(Result, E);
18038 }
18039 case CK_NoOp:
18040 case CK_LValueToRValue:
18041 return ExprEvaluatorBaseTy::VisitCastExpr(E);
18042 default:
18043 return Error(E);
18044 }
18045}
18046
18047bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
18048 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
18049 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
18050
18051 const Expr *LHS = E->getLHS();
18052 const Expr *RHS = E->getRHS();
18053 FixedPointSemantics ResultFXSema =
18054 Info.Ctx.getFixedPointSemantics(E->getType());
18055
18056 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
18057 if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
18058 return false;
18059 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
18060 if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
18061 return false;
18062
18063 bool OpOverflow = false, ConversionOverflow = false;
18064 APFixedPoint Result(LHSFX.getSemantics());
18065 switch (E->getOpcode()) {
18066 case BO_Add: {
18067 Result = LHSFX.add(RHSFX, &OpOverflow)
18068 .convert(ResultFXSema, &ConversionOverflow);
18069 break;
18070 }
18071 case BO_Sub: {
18072 Result = LHSFX.sub(RHSFX, &OpOverflow)
18073 .convert(ResultFXSema, &ConversionOverflow);
18074 break;
18075 }
18076 case BO_Mul: {
18077 Result = LHSFX.mul(RHSFX, &OpOverflow)
18078 .convert(ResultFXSema, &ConversionOverflow);
18079 break;
18080 }
18081 case BO_Div: {
18082 if (RHSFX.getValue() == 0) {
18083 Info.FFDiag(E, diag::note_expr_divide_by_zero);
18084 return false;
18085 }
18086 Result = LHSFX.div(RHSFX, &OpOverflow)
18087 .convert(ResultFXSema, &ConversionOverflow);
18088 break;
18089 }
18090 case BO_Shl:
18091 case BO_Shr: {
18092 FixedPointSemantics LHSSema = LHSFX.getSemantics();
18093 llvm::APSInt RHSVal = RHSFX.getValue();
18094
18095 unsigned ShiftBW =
18096 LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding();
18097 unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1);
18098 // Embedded-C 4.1.6.2.2:
18099 // The right operand must be nonnegative and less than the total number
18100 // of (nonpadding) bits of the fixed-point operand ...
18101 if (RHSVal.isNegative())
18102 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal;
18103 else if (Amt != RHSVal)
18104 Info.CCEDiag(E, diag::note_constexpr_large_shift)
18105 << RHSVal << E->getType() << ShiftBW;
18106
18107 if (E->getOpcode() == BO_Shl)
18108 Result = LHSFX.shl(Amt, &OpOverflow);
18109 else
18110 Result = LHSFX.shr(Amt, &OpOverflow);
18111 break;
18112 }
18113 default:
18114 return false;
18115 }
18116 if (OpOverflow || ConversionOverflow) {
18117 if (Info.checkingForUndefinedBehavior())
18118 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
18119 diag::warn_fixedpoint_constant_overflow)
18120 << Result.toString() << E->getType();
18121 if (!HandleOverflow(Info, E, Result, E->getType()))
18122 return false;
18123 }
18124 return Success(Result, E);
18125}
18126
18127//===----------------------------------------------------------------------===//
18128// Float Evaluation
18129//===----------------------------------------------------------------------===//
18130
18131namespace {
18132class FloatExprEvaluator
18133 : public ExprEvaluatorBase<FloatExprEvaluator> {
18134 APFloat &Result;
18135public:
18136 FloatExprEvaluator(EvalInfo &info, APFloat &result)
18137 : ExprEvaluatorBaseTy(info), Result(result) {}
18138
18139 bool Success(const APValue &V, const Expr *e) {
18140 Result = V.getFloat();
18141 return true;
18142 }
18143
18144 bool ZeroInitialization(const Expr *E) {
18145 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
18146 return true;
18147 }
18148
18149 bool VisitCallExpr(const CallExpr *E);
18150
18151 bool VisitUnaryOperator(const UnaryOperator *E);
18152 bool VisitBinaryOperator(const BinaryOperator *E);
18153 bool VisitFloatingLiteral(const FloatingLiteral *E);
18154 bool VisitCastExpr(const CastExpr *E);
18155
18156 bool VisitUnaryReal(const UnaryOperator *E);
18157 bool VisitUnaryImag(const UnaryOperator *E);
18158
18159 // FIXME: Missing: array subscript of vector, member of vector
18160};
18161} // end anonymous namespace
18162
18163static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
18164 assert(!E->isValueDependent());
18165 assert(E->isPRValue() && E->getType()->isRealFloatingType());
18166 return FloatExprEvaluator(Info, Result).Visit(E);
18167}
18168
18169static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
18170 QualType ResultTy,
18171 const Expr *Arg,
18172 bool SNaN,
18173 llvm::APFloat &Result) {
18174 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
18175 if (!S) return false;
18176
18177 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
18178
18179 llvm::APInt fill;
18180
18181 // Treat empty strings as if they were zero.
18182 if (S->getString().empty())
18183 fill = llvm::APInt(32, 0);
18184 else if (S->getString().getAsInteger(0, fill))
18185 return false;
18186
18187 if (Context.getTargetInfo().isNan2008()) {
18188 if (SNaN)
18189 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
18190 else
18191 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
18192 } else {
18193 // Prior to IEEE 754-2008, architectures were allowed to choose whether
18194 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
18195 // a different encoding to what became a standard in 2008, and for pre-
18196 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
18197 // sNaN. This is now known as "legacy NaN" encoding.
18198 if (SNaN)
18199 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
18200 else
18201 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
18202 }
18203
18204 return true;
18205}
18206
18207bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
18208 if (!IsConstantEvaluatedBuiltinCall(E))
18209 return ExprEvaluatorBaseTy::VisitCallExpr(E);
18210
18211 switch (E->getBuiltinCallee()) {
18212 default:
18213 return false;
18214
18215 case Builtin::BI__builtin_huge_val:
18216 case Builtin::BI__builtin_huge_valf:
18217 case Builtin::BI__builtin_huge_vall:
18218 case Builtin::BI__builtin_huge_valf16:
18219 case Builtin::BI__builtin_huge_valf128:
18220 case Builtin::BI__builtin_inf:
18221 case Builtin::BI__builtin_inff:
18222 case Builtin::BI__builtin_infl:
18223 case Builtin::BI__builtin_inff16:
18224 case Builtin::BI__builtin_inff128: {
18225 const llvm::fltSemantics &Sem =
18226 Info.Ctx.getFloatTypeSemantics(E->getType());
18227 Result = llvm::APFloat::getInf(Sem);
18228 return true;
18229 }
18230
18231 case Builtin::BI__builtin_nans:
18232 case Builtin::BI__builtin_nansf:
18233 case Builtin::BI__builtin_nansl:
18234 case Builtin::BI__builtin_nansf16:
18235 case Builtin::BI__builtin_nansf128:
18236 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
18237 true, Result))
18238 return Error(E);
18239 return true;
18240
18241 case Builtin::BI__builtin_nan:
18242 case Builtin::BI__builtin_nanf:
18243 case Builtin::BI__builtin_nanl:
18244 case Builtin::BI__builtin_nanf16:
18245 case Builtin::BI__builtin_nanf128:
18246 // If this is __builtin_nan() turn this into a nan, otherwise we
18247 // can't constant fold it.
18248 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
18249 false, Result))
18250 return Error(E);
18251 return true;
18252
18253 case Builtin::BI__builtin_elementwise_abs:
18254 case Builtin::BI__builtin_fabs:
18255 case Builtin::BI__builtin_fabsf:
18256 case Builtin::BI__builtin_fabsl:
18257 case Builtin::BI__builtin_fabsf128:
18258 // The C standard says "fabs raises no floating-point exceptions,
18259 // even if x is a signaling NaN. The returned value is independent of
18260 // the current rounding direction mode." Therefore constant folding can
18261 // proceed without regard to the floating point settings.
18262 // Reference, WG14 N2478 F.10.4.3
18263 if (!EvaluateFloat(E->getArg(0), Result, Info))
18264 return false;
18265
18266 if (Result.isNegative())
18267 Result.changeSign();
18268 return true;
18269
18270 case Builtin::BI__arithmetic_fence:
18271 return EvaluateFloat(E->getArg(0), Result, Info);
18272
18273 // FIXME: Builtin::BI__builtin_powi
18274 // FIXME: Builtin::BI__builtin_powif
18275 // FIXME: Builtin::BI__builtin_powil
18276
18277 case Builtin::BI__builtin_copysign:
18278 case Builtin::BI__builtin_copysignf:
18279 case Builtin::BI__builtin_copysignl:
18280 case Builtin::BI__builtin_copysignf128: {
18281 APFloat RHS(0.);
18282 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
18283 !EvaluateFloat(E->getArg(1), RHS, Info))
18284 return false;
18285 Result.copySign(RHS);
18286 return true;
18287 }
18288
18289 case Builtin::BI__builtin_fmax:
18290 case Builtin::BI__builtin_fmaxf:
18291 case Builtin::BI__builtin_fmaxl:
18292 case Builtin::BI__builtin_fmaxf16:
18293 case Builtin::BI__builtin_fmaxf128: {
18294 APFloat RHS(0.);
18295 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
18296 !EvaluateFloat(E->getArg(1), RHS, Info))
18297 return false;
18298 Result = maxnum(Result, RHS);
18299 return true;
18300 }
18301
18302 case Builtin::BI__builtin_fmin:
18303 case Builtin::BI__builtin_fminf:
18304 case Builtin::BI__builtin_fminl:
18305 case Builtin::BI__builtin_fminf16:
18306 case Builtin::BI__builtin_fminf128: {
18307 APFloat RHS(0.);
18308 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
18309 !EvaluateFloat(E->getArg(1), RHS, Info))
18310 return false;
18311 Result = minnum(Result, RHS);
18312 return true;
18313 }
18314
18315 case Builtin::BI__builtin_fmaximum_num:
18316 case Builtin::BI__builtin_fmaximum_numf:
18317 case Builtin::BI__builtin_fmaximum_numl:
18318 case Builtin::BI__builtin_fmaximum_numf16:
18319 case Builtin::BI__builtin_fmaximum_numf128: {
18320 APFloat RHS(0.);
18321 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
18322 !EvaluateFloat(E->getArg(1), RHS, Info))
18323 return false;
18324 Result = maximumnum(Result, RHS);
18325 return true;
18326 }
18327
18328 case Builtin::BI__builtin_fminimum_num:
18329 case Builtin::BI__builtin_fminimum_numf:
18330 case Builtin::BI__builtin_fminimum_numl:
18331 case Builtin::BI__builtin_fminimum_numf16:
18332 case Builtin::BI__builtin_fminimum_numf128: {
18333 APFloat RHS(0.);
18334 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
18335 !EvaluateFloat(E->getArg(1), RHS, Info))
18336 return false;
18337 Result = minimumnum(Result, RHS);
18338 return true;
18339 }
18340
18341 case Builtin::BI__builtin_elementwise_fma: {
18342 if (!E->getArg(0)->isPRValue() || !E->getArg(1)->isPRValue() ||
18343 !E->getArg(2)->isPRValue()) {
18344 return false;
18345 }
18346 APFloat SourceY(0.), SourceZ(0.);
18347 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
18348 !EvaluateFloat(E->getArg(1), SourceY, Info) ||
18349 !EvaluateFloat(E->getArg(2), SourceZ, Info))
18350 return false;
18351 llvm::RoundingMode RM = getActiveRoundingMode(getEvalInfo(), E);
18352 (void)Result.fusedMultiplyAdd(SourceY, SourceZ, RM);
18353 return true;
18354 }
18355
18356 case clang::X86::BI__builtin_ia32_vec_ext_v4sf: {
18357 APValue Vec;
18358 APSInt IdxAPS;
18359 if (!EvaluateVector(E->getArg(0), Vec, Info) ||
18360 !EvaluateInteger(E->getArg(1), IdxAPS, Info))
18361 return false;
18362 unsigned N = Vec.getVectorLength();
18363 unsigned Idx = static_cast<unsigned>(IdxAPS.getZExtValue() & (N - 1));
18364 return Success(Vec.getVectorElt(Idx), E);
18365 }
18366 }
18367}
18368
18369bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
18370 if (E->getSubExpr()->getType()->isAnyComplexType()) {
18371 ComplexValue CV;
18372 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
18373 return false;
18374 Result = CV.FloatReal;
18375 return true;
18376 }
18377
18378 return Visit(E->getSubExpr());
18379}
18380
18381bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
18382 if (E->getSubExpr()->getType()->isAnyComplexType()) {
18383 ComplexValue CV;
18384 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
18385 return false;
18386 Result = CV.FloatImag;
18387 return true;
18388 }
18389
18390 VisitIgnoredValue(E->getSubExpr());
18391 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
18392 Result = llvm::APFloat::getZero(Sem);
18393 return true;
18394}
18395
18396bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
18397 switch (E->getOpcode()) {
18398 default: return Error(E);
18399 case UO_Plus:
18400 return EvaluateFloat(E->getSubExpr(), Result, Info);
18401 case UO_Minus:
18402 // In C standard, WG14 N2478 F.3 p4
18403 // "the unary - raises no floating point exceptions,
18404 // even if the operand is signalling."
18405 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
18406 return false;
18407 Result.changeSign();
18408 return true;
18409 }
18410}
18411
18412bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
18413 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
18414 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
18415
18416 APFloat RHS(0.0);
18417 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
18418 if (!LHSOK && !Info.noteFailure())
18419 return false;
18420 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
18421 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
18422}
18423
18424bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
18425 Result = E->getValue();
18426 return true;
18427}
18428
18429bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
18430 const Expr* SubExpr = E->getSubExpr();
18431
18432 switch (E->getCastKind()) {
18433 default:
18434 return ExprEvaluatorBaseTy::VisitCastExpr(E);
18435
18436 case CK_HLSLAggregateSplatCast:
18437 llvm_unreachable("invalid cast kind for floating value");
18438
18439 case CK_IntegralToFloating: {
18440 APSInt IntResult;
18441 const FPOptions FPO = E->getFPFeaturesInEffect(
18442 Info.Ctx.getLangOpts());
18443 return EvaluateInteger(SubExpr, IntResult, Info) &&
18444 HandleIntToFloatCast(Info, E, FPO, SubExpr->getType(),
18445 IntResult, E->getType(), Result);
18446 }
18447
18448 case CK_FixedPointToFloating: {
18449 APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
18450 if (!EvaluateFixedPoint(SubExpr, FixResult, Info))
18451 return false;
18452 Result =
18453 FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->getType()));
18454 return true;
18455 }
18456
18457 case CK_FloatingCast: {
18458 if (!Visit(SubExpr))
18459 return false;
18460 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
18461 Result);
18462 }
18463
18464 case CK_FloatingComplexToReal: {
18465 ComplexValue V;
18466 if (!EvaluateComplex(SubExpr, V, Info))
18467 return false;
18468 Result = V.getComplexFloatReal();
18469 return true;
18470 }
18471 case CK_HLSLVectorTruncation: {
18472 APValue Val;
18473 if (!EvaluateVector(SubExpr, Val, Info))
18474 return Error(E);
18475 return Success(Val.getVectorElt(0), E);
18476 }
18477 case CK_HLSLElementwiseCast: {
18478 SmallVector<APValue> SrcVals;
18479 SmallVector<QualType> SrcTypes;
18480
18481 if (!hlslElementwiseCastHelper(Info, SubExpr, E->getType(), SrcVals,
18482 SrcTypes))
18483 return false;
18484 APValue Val;
18485
18486 // cast our single element
18487 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
18488 APValue ResultVal;
18489 if (!handleScalarCast(Info, FPO, E, SrcTypes[0], E->getType(), SrcVals[0],
18490 ResultVal))
18491 return false;
18492 return Success(ResultVal, E);
18493 }
18494 }
18495}
18496
18497//===----------------------------------------------------------------------===//
18498// Complex Evaluation (for float and integer)
18499//===----------------------------------------------------------------------===//
18500
18501namespace {
18502class ComplexExprEvaluator
18503 : public ExprEvaluatorBase<ComplexExprEvaluator> {
18504 ComplexValue &Result;
18505
18506public:
18507 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
18508 : ExprEvaluatorBaseTy(info), Result(Result) {}
18509
18510 bool Success(const APValue &V, const Expr *e) {
18511 Result.setFrom(V);
18512 return true;
18513 }
18514
18515 bool ZeroInitialization(const Expr *E);
18516
18517 //===--------------------------------------------------------------------===//
18518 // Visitor Methods
18519 //===--------------------------------------------------------------------===//
18520
18521 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
18522 bool VisitCastExpr(const CastExpr *E);
18523 bool VisitBinaryOperator(const BinaryOperator *E);
18524 bool VisitUnaryOperator(const UnaryOperator *E);
18525 bool VisitInitListExpr(const InitListExpr *E);
18526 bool VisitCallExpr(const CallExpr *E);
18527};
18528} // end anonymous namespace
18529
18530static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
18531 EvalInfo &Info) {
18532 assert(!E->isValueDependent());
18533 assert(E->isPRValue() && E->getType()->isAnyComplexType());
18534 return ComplexExprEvaluator(Info, Result).Visit(E);
18535}
18536
18537bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
18538 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
18539 if (ElemTy->isRealFloatingType()) {
18540 Result.makeComplexFloat();
18541 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
18542 Result.FloatReal = Zero;
18543 Result.FloatImag = Zero;
18544 } else {
18545 Result.makeComplexInt();
18546 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
18547 Result.IntReal = Zero;
18548 Result.IntImag = Zero;
18549 }
18550 return true;
18551}
18552
18553bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
18554 const Expr* SubExpr = E->getSubExpr();
18555
18556 if (SubExpr->getType()->isRealFloatingType()) {
18557 Result.makeComplexFloat();
18558 APFloat &Imag = Result.FloatImag;
18559 if (!EvaluateFloat(SubExpr, Imag, Info))
18560 return false;
18561
18562 Result.FloatReal = APFloat(Imag.getSemantics());
18563 return true;
18564 } else {
18565 assert(SubExpr->getType()->isIntegerType() &&
18566 "Unexpected imaginary literal.");
18567
18568 Result.makeComplexInt();
18569 APSInt &Imag = Result.IntImag;
18570 if (!EvaluateInteger(SubExpr, Imag, Info))
18571 return false;
18572
18573 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
18574 return true;
18575 }
18576}
18577
18578bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
18579
18580 switch (E->getCastKind()) {
18581 case CK_BitCast:
18582 case CK_BaseToDerived:
18583 case CK_DerivedToBase:
18584 case CK_UncheckedDerivedToBase:
18585 case CK_Dynamic:
18586 case CK_ToUnion:
18587 case CK_ArrayToPointerDecay:
18588 case CK_FunctionToPointerDecay:
18589 case CK_NullToPointer:
18590 case CK_NullToMemberPointer:
18591 case CK_BaseToDerivedMemberPointer:
18592 case CK_DerivedToBaseMemberPointer:
18593 case CK_MemberPointerToBoolean:
18594 case CK_ReinterpretMemberPointer:
18595 case CK_ConstructorConversion:
18596 case CK_IntegralToPointer:
18597 case CK_PointerToIntegral:
18598 case CK_PointerToBoolean:
18599 case CK_ToVoid:
18600 case CK_VectorSplat:
18601 case CK_IntegralCast:
18602 case CK_BooleanToSignedIntegral:
18603 case CK_IntegralToBoolean:
18604 case CK_IntegralToFloating:
18605 case CK_FloatingToIntegral:
18606 case CK_FloatingToBoolean:
18607 case CK_FloatingCast:
18608 case CK_CPointerToObjCPointerCast:
18609 case CK_BlockPointerToObjCPointerCast:
18610 case CK_AnyPointerToBlockPointerCast:
18611 case CK_ObjCObjectLValueCast:
18612 case CK_FloatingComplexToReal:
18613 case CK_FloatingComplexToBoolean:
18614 case CK_IntegralComplexToReal:
18615 case CK_IntegralComplexToBoolean:
18616 case CK_ARCProduceObject:
18617 case CK_ARCConsumeObject:
18618 case CK_ARCReclaimReturnedObject:
18619 case CK_ARCExtendBlockObject:
18620 case CK_CopyAndAutoreleaseBlockObject:
18621 case CK_BuiltinFnToFnPtr:
18622 case CK_ZeroToOCLOpaqueType:
18623 case CK_NonAtomicToAtomic:
18624 case CK_AddressSpaceConversion:
18625 case CK_IntToOCLSampler:
18626 case CK_FloatingToFixedPoint:
18627 case CK_FixedPointToFloating:
18628 case CK_FixedPointCast:
18629 case CK_FixedPointToBoolean:
18630 case CK_FixedPointToIntegral:
18631 case CK_IntegralToFixedPoint:
18632 case CK_MatrixCast:
18633 case CK_HLSLVectorTruncation:
18634 case CK_HLSLElementwiseCast:
18635 case CK_HLSLAggregateSplatCast:
18636 llvm_unreachable("invalid cast kind for complex value");
18637
18638 case CK_LValueToRValue:
18639 case CK_AtomicToNonAtomic:
18640 case CK_NoOp:
18641 case CK_LValueToRValueBitCast:
18642 case CK_HLSLArrayRValue:
18643 return ExprEvaluatorBaseTy::VisitCastExpr(E);
18644
18645 case CK_Dependent:
18646 case CK_LValueBitCast:
18647 case CK_UserDefinedConversion:
18648 return Error(E);
18649
18650 case CK_FloatingRealToComplex: {
18651 APFloat &Real = Result.FloatReal;
18652 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
18653 return false;
18654
18655 Result.makeComplexFloat();
18656 Result.FloatImag = APFloat(Real.getSemantics());
18657 return true;
18658 }
18659
18660 case CK_FloatingComplexCast: {
18661 if (!Visit(E->getSubExpr()))
18662 return false;
18663
18664 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
18665 QualType From
18666 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
18667
18668 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
18669 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
18670 }
18671
18672 case CK_FloatingComplexToIntegralComplex: {
18673 if (!Visit(E->getSubExpr()))
18674 return false;
18675
18676 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
18677 QualType From
18678 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
18679 Result.makeComplexInt();
18680 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
18681 To, Result.IntReal) &&
18682 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
18683 To, Result.IntImag);
18684 }
18685
18686 case CK_IntegralRealToComplex: {
18687 APSInt &Real = Result.IntReal;
18688 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
18689 return false;
18690
18691 Result.makeComplexInt();
18692 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
18693 return true;
18694 }
18695
18696 case CK_IntegralComplexCast: {
18697 if (!Visit(E->getSubExpr()))
18698 return false;
18699
18700 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
18701 QualType From
18702 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
18703
18704 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
18705 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
18706 return true;
18707 }
18708
18709 case CK_IntegralComplexToFloatingComplex: {
18710 if (!Visit(E->getSubExpr()))
18711 return false;
18712
18713 const FPOptions FPO = E->getFPFeaturesInEffect(
18714 Info.Ctx.getLangOpts());
18715 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
18716 QualType From
18717 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
18718 Result.makeComplexFloat();
18719 return HandleIntToFloatCast(Info, E, FPO, From, Result.IntReal,
18720 To, Result.FloatReal) &&
18721 HandleIntToFloatCast(Info, E, FPO, From, Result.IntImag,
18722 To, Result.FloatImag);
18723 }
18724 }
18725
18726 llvm_unreachable("unknown cast resulting in complex value");
18727}
18728
18729void HandleComplexComplexMul(APFloat A, APFloat B, APFloat C, APFloat D,
18730 APFloat &ResR, APFloat &ResI) {
18731 // This is an implementation of complex multiplication according to the
18732 // constraints laid out in C11 Annex G. The implementation uses the
18733 // following naming scheme:
18734 // (a + ib) * (c + id)
18735
18736 APFloat AC = A * C;
18737 APFloat BD = B * D;
18738 APFloat AD = A * D;
18739 APFloat BC = B * C;
18740 ResR = AC - BD;
18741 ResI = AD + BC;
18742 if (ResR.isNaN() && ResI.isNaN()) {
18743 bool Recalc = false;
18744 if (A.isInfinity() || B.isInfinity()) {
18745 A = APFloat::copySign(APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0),
18746 A);
18747 B = APFloat::copySign(APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0),
18748 B);
18749 if (C.isNaN())
18750 C = APFloat::copySign(APFloat(C.getSemantics()), C);
18751 if (D.isNaN())
18752 D = APFloat::copySign(APFloat(D.getSemantics()), D);
18753 Recalc = true;
18754 }
18755 if (C.isInfinity() || D.isInfinity()) {
18756 C = APFloat::copySign(APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0),
18757 C);
18758 D = APFloat::copySign(APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0),
18759 D);
18760 if (A.isNaN())
18761 A = APFloat::copySign(APFloat(A.getSemantics()), A);
18762 if (B.isNaN())
18763 B = APFloat::copySign(APFloat(B.getSemantics()), B);
18764 Recalc = true;
18765 }
18766 if (!Recalc && (AC.isInfinity() || BD.isInfinity() || AD.isInfinity() ||
18767 BC.isInfinity())) {
18768 if (A.isNaN())
18769 A = APFloat::copySign(APFloat(A.getSemantics()), A);
18770 if (B.isNaN())
18771 B = APFloat::copySign(APFloat(B.getSemantics()), B);
18772 if (C.isNaN())
18773 C = APFloat::copySign(APFloat(C.getSemantics()), C);
18774 if (D.isNaN())
18775 D = APFloat::copySign(APFloat(D.getSemantics()), D);
18776 Recalc = true;
18777 }
18778 if (Recalc) {
18779 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
18780 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
18781 }
18782 }
18783}
18784
18785void HandleComplexComplexDiv(APFloat A, APFloat B, APFloat C, APFloat D,
18786 APFloat &ResR, APFloat &ResI) {
18787 // This is an implementation of complex division according to the
18788 // constraints laid out in C11 Annex G. The implementation uses the
18789 // following naming scheme:
18790 // (a + ib) / (c + id)
18791
18792 int DenomLogB = 0;
18793 APFloat MaxCD = maxnum(abs(C), abs(D));
18794 if (MaxCD.isFinite()) {
18795 DenomLogB = ilogb(MaxCD);
18796 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
18797 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
18798 }
18799 APFloat Denom = C * C + D * D;
18800 ResR =
18801 scalbn((A * C + B * D) / Denom, -DenomLogB, APFloat::rmNearestTiesToEven);
18802 ResI =
18803 scalbn((B * C - A * D) / Denom, -DenomLogB, APFloat::rmNearestTiesToEven);
18804 if (ResR.isNaN() && ResI.isNaN()) {
18805 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
18806 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
18807 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
18808 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
18809 D.isFinite()) {
18810 A = APFloat::copySign(APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0),
18811 A);
18812 B = APFloat::copySign(APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0),
18813 B);
18814 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
18815 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
18816 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
18817 C = APFloat::copySign(APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0),
18818 C);
18819 D = APFloat::copySign(APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0),
18820 D);
18821 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
18822 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
18823 }
18824 }
18825}
18826
18827bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
18828 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
18829 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
18830
18831 // Track whether the LHS or RHS is real at the type system level. When this is
18832 // the case we can simplify our evaluation strategy.
18833 bool LHSReal = false, RHSReal = false;
18834
18835 bool LHSOK;
18836 if (E->getLHS()->getType()->isRealFloatingType()) {
18837 LHSReal = true;
18838 APFloat &Real = Result.FloatReal;
18839 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
18840 if (LHSOK) {
18841 Result.makeComplexFloat();
18842 Result.FloatImag = APFloat(Real.getSemantics());
18843 }
18844 } else {
18845 LHSOK = Visit(E->getLHS());
18846 }
18847 if (!LHSOK && !Info.noteFailure())
18848 return false;
18849
18850 ComplexValue RHS;
18851 if (E->getRHS()->getType()->isRealFloatingType()) {
18852 RHSReal = true;
18853 APFloat &Real = RHS.FloatReal;
18854 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
18855 return false;
18856 RHS.makeComplexFloat();
18857 RHS.FloatImag = APFloat(Real.getSemantics());
18858 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
18859 return false;
18860
18861 assert(!(LHSReal && RHSReal) &&
18862 "Cannot have both operands of a complex operation be real.");
18863 switch (E->getOpcode()) {
18864 default: return Error(E);
18865 case BO_Add:
18866 if (Result.isComplexFloat()) {
18867 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
18868 APFloat::rmNearestTiesToEven);
18869 if (LHSReal)
18870 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
18871 else if (!RHSReal)
18872 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
18873 APFloat::rmNearestTiesToEven);
18874 } else {
18875 Result.getComplexIntReal() += RHS.getComplexIntReal();
18876 Result.getComplexIntImag() += RHS.getComplexIntImag();
18877 }
18878 break;
18879 case BO_Sub:
18880 if (Result.isComplexFloat()) {
18881 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
18882 APFloat::rmNearestTiesToEven);
18883 if (LHSReal) {
18884 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
18885 Result.getComplexFloatImag().changeSign();
18886 } else if (!RHSReal) {
18887 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
18888 APFloat::rmNearestTiesToEven);
18889 }
18890 } else {
18891 Result.getComplexIntReal() -= RHS.getComplexIntReal();
18892 Result.getComplexIntImag() -= RHS.getComplexIntImag();
18893 }
18894 break;
18895 case BO_Mul:
18896 if (Result.isComplexFloat()) {
18897 // This is an implementation of complex multiplication according to the
18898 // constraints laid out in C11 Annex G. The implementation uses the
18899 // following naming scheme:
18900 // (a + ib) * (c + id)
18901 ComplexValue LHS = Result;
18902 APFloat &A = LHS.getComplexFloatReal();
18903 APFloat &B = LHS.getComplexFloatImag();
18904 APFloat &C = RHS.getComplexFloatReal();
18905 APFloat &D = RHS.getComplexFloatImag();
18906 APFloat &ResR = Result.getComplexFloatReal();
18907 APFloat &ResI = Result.getComplexFloatImag();
18908 if (LHSReal) {
18909 assert(!RHSReal && "Cannot have two real operands for a complex op!");
18910 ResR = A;
18911 ResI = A;
18912 // ResR = A * C;
18913 // ResI = A * D;
18914 if (!handleFloatFloatBinOp(Info, E, ResR, BO_Mul, C) ||
18915 !handleFloatFloatBinOp(Info, E, ResI, BO_Mul, D))
18916 return false;
18917 } else if (RHSReal) {
18918 // ResR = C * A;
18919 // ResI = C * B;
18920 ResR = C;
18921 ResI = C;
18922 if (!handleFloatFloatBinOp(Info, E, ResR, BO_Mul, A) ||
18923 !handleFloatFloatBinOp(Info, E, ResI, BO_Mul, B))
18924 return false;
18925 } else {
18926 HandleComplexComplexMul(A, B, C, D, ResR, ResI);
18927 }
18928 } else {
18929 ComplexValue LHS = Result;
18930 Result.getComplexIntReal() =
18931 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
18932 LHS.getComplexIntImag() * RHS.getComplexIntImag());
18933 Result.getComplexIntImag() =
18934 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
18935 LHS.getComplexIntImag() * RHS.getComplexIntReal());
18936 }
18937 break;
18938 case BO_Div:
18939 if (Result.isComplexFloat()) {
18940 // This is an implementation of complex division according to the
18941 // constraints laid out in C11 Annex G. The implementation uses the
18942 // following naming scheme:
18943 // (a + ib) / (c + id)
18944 ComplexValue LHS = Result;
18945 APFloat &A = LHS.getComplexFloatReal();
18946 APFloat &B = LHS.getComplexFloatImag();
18947 APFloat &C = RHS.getComplexFloatReal();
18948 APFloat &D = RHS.getComplexFloatImag();
18949 APFloat &ResR = Result.getComplexFloatReal();
18950 APFloat &ResI = Result.getComplexFloatImag();
18951 if (RHSReal) {
18952 ResR = A;
18953 ResI = B;
18954 // ResR = A / C;
18955 // ResI = B / C;
18956 if (!handleFloatFloatBinOp(Info, E, ResR, BO_Div, C) ||
18957 !handleFloatFloatBinOp(Info, E, ResI, BO_Div, C))
18958 return false;
18959 } else {
18960 if (LHSReal) {
18961 // No real optimizations we can do here, stub out with zero.
18962 B = APFloat::getZero(A.getSemantics());
18963 }
18964 HandleComplexComplexDiv(A, B, C, D, ResR, ResI);
18965 }
18966 } else {
18967 ComplexValue LHS = Result;
18968 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
18969 RHS.getComplexIntImag() * RHS.getComplexIntImag();
18970 if (Den.isZero())
18971 return Error(E, diag::note_expr_divide_by_zero);
18972
18973 Result.getComplexIntReal() =
18974 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
18975 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
18976 Result.getComplexIntImag() =
18977 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
18978 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
18979 }
18980 break;
18981 }
18982
18983 return true;
18984}
18985
18986bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
18987 // Get the operand value into 'Result'.
18988 if (!Visit(E->getSubExpr()))
18989 return false;
18990
18991 switch (E->getOpcode()) {
18992 default:
18993 return Error(E);
18994 case UO_Extension:
18995 return true;
18996 case UO_Plus:
18997 // The result is always just the subexpr.
18998 return true;
18999 case UO_Minus:
19000 if (Result.isComplexFloat()) {
19001 Result.getComplexFloatReal().changeSign();
19002 Result.getComplexFloatImag().changeSign();
19003 }
19004 else {
19005 Result.getComplexIntReal() = -Result.getComplexIntReal();
19006 Result.getComplexIntImag() = -Result.getComplexIntImag();
19007 }
19008 return true;
19009 case UO_Not:
19010 if (Result.isComplexFloat())
19011 Result.getComplexFloatImag().changeSign();
19012 else
19013 Result.getComplexIntImag() = -Result.getComplexIntImag();
19014 return true;
19015 }
19016}
19017
19018bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
19019 if (E->getNumInits() == 2) {
19020 if (E->getType()->isComplexType()) {
19021 Result.makeComplexFloat();
19022 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
19023 return false;
19024 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
19025 return false;
19026 } else {
19027 Result.makeComplexInt();
19028 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
19029 return false;
19030 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
19031 return false;
19032 }
19033 return true;
19034 }
19035 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
19036}
19037
19038bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) {
19039 if (!IsConstantEvaluatedBuiltinCall(E))
19040 return ExprEvaluatorBaseTy::VisitCallExpr(E);
19041
19042 switch (E->getBuiltinCallee()) {
19043 case Builtin::BI__builtin_complex:
19044 Result.makeComplexFloat();
19045 if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info))
19046 return false;
19047 if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info))
19048 return false;
19049 return true;
19050
19051 default:
19052 return false;
19053 }
19054}
19055
19056//===----------------------------------------------------------------------===//
19057// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
19058// implicit conversion.
19059//===----------------------------------------------------------------------===//
19060
19061namespace {
19062class AtomicExprEvaluator :
19063 public ExprEvaluatorBase<AtomicExprEvaluator> {
19064 const LValue *This;
19065 APValue &Result;
19066public:
19067 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
19068 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
19069
19070 bool Success(const APValue &V, const Expr *E) {
19071 Result = V;
19072 return true;
19073 }
19074
19075 bool ZeroInitialization(const Expr *E) {
19076 ImplicitValueInitExpr VIE(
19077 E->getType()->castAs<AtomicType>()->getValueType());
19078 // For atomic-qualified class (and array) types in C++, initialize the
19079 // _Atomic-wrapped subobject directly, in-place.
19080 return This ? EvaluateInPlace(Result, Info, *This, &VIE)
19081 : Evaluate(Result, Info, &VIE);
19082 }
19083
19084 bool VisitCastExpr(const CastExpr *E) {
19085 switch (E->getCastKind()) {
19086 default:
19087 return ExprEvaluatorBaseTy::VisitCastExpr(E);
19088 case CK_NullToPointer:
19089 VisitIgnoredValue(E->getSubExpr());
19090 return ZeroInitialization(E);
19091 case CK_NonAtomicToAtomic:
19092 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
19093 : Evaluate(Result, Info, E->getSubExpr());
19094 }
19095 }
19096};
19097} // end anonymous namespace
19098
19099static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
19100 EvalInfo &Info) {
19101 assert(!E->isValueDependent());
19102 assert(E->isPRValue() && E->getType()->isAtomicType());
19103 return AtomicExprEvaluator(Info, This, Result).Visit(E);
19104}
19105
19106//===----------------------------------------------------------------------===//
19107// Void expression evaluation, primarily for a cast to void on the LHS of a
19108// comma operator
19109//===----------------------------------------------------------------------===//
19110
19111namespace {
19112class VoidExprEvaluator
19113 : public ExprEvaluatorBase<VoidExprEvaluator> {
19114public:
19115 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
19116
19117 bool Success(const APValue &V, const Expr *e) { return true; }
19118
19119 bool ZeroInitialization(const Expr *E) { return true; }
19120
19121 bool VisitCastExpr(const CastExpr *E) {
19122 switch (E->getCastKind()) {
19123 default:
19124 return ExprEvaluatorBaseTy::VisitCastExpr(E);
19125 case CK_ToVoid:
19126 VisitIgnoredValue(E->getSubExpr());
19127 return true;
19128 }
19129 }
19130
19131 bool VisitCallExpr(const CallExpr *E) {
19132 if (!IsConstantEvaluatedBuiltinCall(E))
19133 return ExprEvaluatorBaseTy::VisitCallExpr(E);
19134
19135 switch (E->getBuiltinCallee()) {
19136 case Builtin::BI__assume:
19137 case Builtin::BI__builtin_assume:
19138 // The argument is not evaluated!
19139 return true;
19140
19141 case Builtin::BI__builtin_operator_delete:
19142 return HandleOperatorDeleteCall(Info, E);
19143
19144 default:
19145 return false;
19146 }
19147 }
19148
19149 bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
19150};
19151} // end anonymous namespace
19152
19153bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
19154 // We cannot speculatively evaluate a delete expression.
19155 if (Info.SpeculativeEvaluationDepth)
19156 return false;
19157
19158 FunctionDecl *OperatorDelete = E->getOperatorDelete();
19159 if (!OperatorDelete
19160 ->isUsableAsGlobalAllocationFunctionInConstantEvaluation()) {
19161 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
19162 << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;
19163 return false;
19164 }
19165
19166 const Expr *Arg = E->getArgument();
19167
19168 LValue Pointer;
19169 if (!EvaluatePointer(Arg, Pointer, Info))
19170 return false;
19171 if (Pointer.Designator.Invalid)
19172 return false;
19173
19174 // Deleting a null pointer has no effect.
19175 if (Pointer.isNullPointer()) {
19176 // This is the only case where we need to produce an extension warning:
19177 // the only other way we can succeed is if we find a dynamic allocation,
19178 // and we will have warned when we allocated it in that case.
19179 if (!Info.getLangOpts().CPlusPlus20)
19180 Info.CCEDiag(E, diag::note_constexpr_new);
19181 return true;
19182 }
19183
19184 std::optional<DynAlloc *> Alloc = CheckDeleteKind(
19185 Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New);
19186 if (!Alloc)
19187 return false;
19188 QualType AllocType = Pointer.Base.getDynamicAllocType();
19189
19190 // For the non-array case, the designator must be empty if the static type
19191 // does not have a virtual destructor.
19192 if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 &&
19194 Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor)
19195 << Arg->getType()->getPointeeType() << AllocType;
19196 return false;
19197 }
19198
19199 // For a class type with a virtual destructor, the selected operator delete
19200 // is the one looked up when building the destructor.
19201 if (!E->isArrayForm() && !E->isGlobalDelete()) {
19202 const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType);
19203 if (VirtualDelete &&
19204 !VirtualDelete
19205 ->isUsableAsGlobalAllocationFunctionInConstantEvaluation()) {
19206 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
19207 << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete;
19208 return false;
19209 }
19210 }
19211
19212 if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(),
19213 (*Alloc)->Value, AllocType))
19214 return false;
19215
19216 if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) {
19217 // The element was already erased. This means the destructor call also
19218 // deleted the object.
19219 // FIXME: This probably results in undefined behavior before we get this
19220 // far, and should be diagnosed elsewhere first.
19221 Info.FFDiag(E, diag::note_constexpr_double_delete);
19222 return false;
19223 }
19224
19225 return true;
19226}
19227
19228static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
19229 assert(!E->isValueDependent());
19230 assert(E->isPRValue() && E->getType()->isVoidType());
19231 return VoidExprEvaluator(Info).Visit(E);
19232}
19233
19234//===----------------------------------------------------------------------===//
19235// Top level Expr::EvaluateAsRValue method.
19236//===----------------------------------------------------------------------===//
19237
19238static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
19239 assert(!E->isValueDependent());
19240 // In C, function designators are not lvalues, but we evaluate them as if they
19241 // are.
19242 QualType T = E->getType();
19243 if (E->isGLValue() || T->isFunctionType()) {
19244 LValue LV;
19245 if (!EvaluateLValue(E, LV, Info))
19246 return false;
19247 LV.moveInto(Result);
19248 } else if (T->isVectorType()) {
19249 if (!EvaluateVector(E, Result, Info))
19250 return false;
19251 } else if (T->isIntegralOrEnumerationType()) {
19252 if (!IntExprEvaluator(Info, Result).Visit(E))
19253 return false;
19254 } else if (T->hasPointerRepresentation()) {
19255 LValue LV;
19256 if (!EvaluatePointer(E, LV, Info))
19257 return false;
19258 LV.moveInto(Result);
19259 } else if (T->isRealFloatingType()) {
19260 llvm::APFloat F(0.0);
19261 if (!EvaluateFloat(E, F, Info))
19262 return false;
19263 Result = APValue(F);
19264 } else if (T->isAnyComplexType()) {
19265 ComplexValue C;
19266 if (!EvaluateComplex(E, C, Info))
19267 return false;
19268 C.moveInto(Result);
19269 } else if (T->isFixedPointType()) {
19270 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
19271 } else if (T->isMemberPointerType()) {
19272 MemberPtr P;
19273 if (!EvaluateMemberPointer(E, P, Info))
19274 return false;
19275 P.moveInto(Result);
19276 return true;
19277 } else if (T->isArrayType()) {
19278 LValue LV;
19279 APValue &Value =
19280 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
19281 if (!EvaluateArray(E, LV, Value, Info))
19282 return false;
19283 Result = Value;
19284 } else if (T->isRecordType()) {
19285 LValue LV;
19286 APValue &Value =
19287 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
19288 if (!EvaluateRecord(E, LV, Value, Info))
19289 return false;
19290 Result = Value;
19291 } else if (T->isVoidType()) {
19292 if (!Info.getLangOpts().CPlusPlus11)
19293 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
19294 << E->getType();
19295 if (!EvaluateVoid(E, Info))
19296 return false;
19297 } else if (T->isAtomicType()) {
19298 QualType Unqual = T.getAtomicUnqualifiedType();
19299 if (Unqual->isArrayType() || Unqual->isRecordType()) {
19300 LValue LV;
19301 APValue &Value = Info.CurrentCall->createTemporary(
19302 E, Unqual, ScopeKind::FullExpression, LV);
19303 if (!EvaluateAtomic(E, &LV, Value, Info))
19304 return false;
19305 Result = Value;
19306 } else {
19307 if (!EvaluateAtomic(E, nullptr, Result, Info))
19308 return false;
19309 }
19310 } else if (Info.getLangOpts().CPlusPlus11) {
19311 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
19312 return false;
19313 } else {
19314 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
19315 return false;
19316 }
19317
19318 return true;
19319}
19320
19321/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
19322/// cases, the in-place evaluation is essential, since later initializers for
19323/// an object can indirectly refer to subobjects which were initialized earlier.
19324static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
19325 const Expr *E, bool AllowNonLiteralTypes) {
19326 assert(!E->isValueDependent());
19327
19328 // Normally expressions passed to EvaluateInPlace have a type, but not when
19329 // a VarDecl initializer is evaluated before the untyped ParenListExpr is
19330 // replaced with a CXXConstructExpr. This can happen in LLDB.
19331 if (E->getType().isNull())
19332 return false;
19333
19334 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
19335 return false;
19336
19337 if (E->isPRValue()) {
19338 // Evaluate arrays and record types in-place, so that later initializers can
19339 // refer to earlier-initialized members of the object.
19340 QualType T = E->getType();
19341 if (T->isArrayType())
19342 return EvaluateArray(E, This, Result, Info);
19343 else if (T->isRecordType())
19344 return EvaluateRecord(E, This, Result, Info);
19345 else if (T->isAtomicType()) {
19346 QualType Unqual = T.getAtomicUnqualifiedType();
19347 if (Unqual->isArrayType() || Unqual->isRecordType())
19348 return EvaluateAtomic(E, &This, Result, Info);
19349 }
19350 }
19351
19352 // For any other type, in-place evaluation is unimportant.
19353 return Evaluate(Result, Info, E);
19354}
19355
19356/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
19357/// lvalue-to-rvalue cast if it is an lvalue.
19358static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
19359 assert(!E->isValueDependent());
19360
19361 if (E->getType().isNull())
19362 return false;
19363
19364 if (!CheckLiteralType(Info, E))
19365 return false;
19366
19367 if (Info.EnableNewConstInterp) {
19368 if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result))
19369 return false;
19370 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
19371 ConstantExprKind::Normal);
19372 }
19373
19374 if (!::Evaluate(Result, Info, E))
19375 return false;
19376
19377 // Implicit lvalue-to-rvalue cast.
19378 if (E->isGLValue()) {
19379 LValue LV;
19380 LV.setFrom(Info.Ctx, Result);
19381 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
19382 return false;
19383 }
19384
19385 // Check this core constant expression is a constant expression.
19386 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
19387 ConstantExprKind::Normal) &&
19388 CheckMemoryLeaks(Info);
19389}
19390
19391static bool FastEvaluateAsRValue(const Expr *Exp, APValue &Result,
19392 const ASTContext &Ctx, bool &IsConst) {
19393 // Fast-path evaluations of integer literals, since we sometimes see files
19394 // containing vast quantities of these.
19395 if (const auto *L = dyn_cast<IntegerLiteral>(Exp)) {
19396 Result =
19397 APValue(APSInt(L->getValue(), L->getType()->isUnsignedIntegerType()));
19398 IsConst = true;
19399 return true;
19400 }
19401
19402 if (const auto *L = dyn_cast<CXXBoolLiteralExpr>(Exp)) {
19403 Result = APValue(APSInt(APInt(1, L->getValue())));
19404 IsConst = true;
19405 return true;
19406 }
19407
19408 if (const auto *FL = dyn_cast<FloatingLiteral>(Exp)) {
19409 Result = APValue(FL->getValue());
19410 IsConst = true;
19411 return true;
19412 }
19413
19414 if (const auto *L = dyn_cast<CharacterLiteral>(Exp)) {
19415 Result = APValue(Ctx.MakeIntValue(L->getValue(), L->getType()));
19416 IsConst = true;
19417 return true;
19418 }
19419
19420 if (const auto *CE = dyn_cast<ConstantExpr>(Exp)) {
19421 if (CE->hasAPValueResult()) {
19422 APValue APV = CE->getAPValueResult();
19423 if (!APV.isLValue()) {
19424 Result = std::move(APV);
19425 IsConst = true;
19426 return true;
19427 }
19428 }
19429
19430 // The SubExpr is usually just an IntegerLiteral.
19431 return FastEvaluateAsRValue(CE->getSubExpr(), Result, Ctx, IsConst);
19432 }
19433
19434 // This case should be rare, but we need to check it before we check on
19435 // the type below.
19436 if (Exp->getType().isNull()) {
19437 IsConst = false;
19438 return true;
19439 }
19440
19441 return false;
19442}
19443
19446 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
19447 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
19448}
19449
19450static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
19451 const ASTContext &Ctx, EvalInfo &Info) {
19452 assert(!E->isValueDependent());
19453 bool IsConst;
19454 if (FastEvaluateAsRValue(E, Result.Val, Ctx, IsConst))
19455 return IsConst;
19456
19457 return EvaluateAsRValue(Info, E, Result.Val);
19458}
19459
19461 const ASTContext &Ctx,
19462 Expr::SideEffectsKind AllowSideEffects,
19463 EvalInfo &Info) {
19464 assert(!E->isValueDependent());
19466 return false;
19467
19468 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
19469 !ExprResult.Val.isInt() ||
19470 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
19471 return false;
19472
19473 return true;
19474}
19475
19477 const ASTContext &Ctx,
19478 Expr::SideEffectsKind AllowSideEffects,
19479 EvalInfo &Info) {
19480 assert(!E->isValueDependent());
19481 if (!E->getType()->isFixedPointType())
19482 return false;
19483
19484 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
19485 return false;
19486
19487 if (!ExprResult.Val.isFixedPoint() ||
19488 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
19489 return false;
19490
19491 return true;
19492}
19493
19494/// EvaluateAsRValue - Return true if this is a constant which we can fold using
19495/// any crazy technique (that has nothing to do with language standards) that
19496/// we want to. If this function returns true, it returns the folded constant
19497/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
19498/// will be applied to the result.
19500 bool InConstantContext) const {
19501 assert(!isValueDependent() &&
19502 "Expression evaluator can't be called on a dependent expression.");
19503 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsRValue");
19504 EvalInfo Info(Ctx, Result, EvaluationMode::IgnoreSideEffects);
19505 Info.InConstantContext = InConstantContext;
19506 return ::EvaluateAsRValue(this, Result, Ctx, Info);
19507}
19508
19510 bool InConstantContext) const {
19511 assert(!isValueDependent() &&
19512 "Expression evaluator can't be called on a dependent expression.");
19513 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsBooleanCondition");
19514 EvalResult Scratch;
19515 return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
19516 HandleConversionToBool(Scratch.Val, Result);
19517}
19518
19520 SideEffectsKind AllowSideEffects,
19521 bool InConstantContext) const {
19522 assert(!isValueDependent() &&
19523 "Expression evaluator can't be called on a dependent expression.");
19524 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsInt");
19525 EvalInfo Info(Ctx, Result, EvaluationMode::IgnoreSideEffects);
19526 Info.InConstantContext = InConstantContext;
19527 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
19528}
19529
19531 SideEffectsKind AllowSideEffects,
19532 bool InConstantContext) const {
19533 assert(!isValueDependent() &&
19534 "Expression evaluator can't be called on a dependent expression.");
19535 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFixedPoint");
19536 EvalInfo Info(Ctx, Result, EvaluationMode::IgnoreSideEffects);
19537 Info.InConstantContext = InConstantContext;
19538 return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
19539}
19540
19541bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
19542 SideEffectsKind AllowSideEffects,
19543 bool InConstantContext) const {
19544 assert(!isValueDependent() &&
19545 "Expression evaluator can't be called on a dependent expression.");
19546
19547 if (!getType()->isRealFloatingType())
19548 return false;
19549
19550 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFloat");
19552 if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
19553 !ExprResult.Val.isFloat() ||
19554 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
19555 return false;
19556
19557 Result = ExprResult.Val.getFloat();
19558 return true;
19559}
19560
19562 bool InConstantContext) const {
19563 assert(!isValueDependent() &&
19564 "Expression evaluator can't be called on a dependent expression.");
19565
19566 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsLValue");
19567 EvalInfo Info(Ctx, Result, EvaluationMode::ConstantFold);
19568 Info.InConstantContext = InConstantContext;
19569 LValue LV;
19570 CheckedTemporaries CheckedTemps;
19571
19572 if (Info.EnableNewConstInterp) {
19573 if (!Info.Ctx.getInterpContext().evaluate(Info, this, Result.Val,
19574 ConstantExprKind::Normal))
19575 return false;
19576
19577 LV.setFrom(Ctx, Result.Val);
19579 Info, getExprLoc(), Ctx.getLValueReferenceType(getType()), LV,
19580 ConstantExprKind::Normal, CheckedTemps);
19581 }
19582
19583 if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() ||
19584 Result.HasSideEffects ||
19587 ConstantExprKind::Normal, CheckedTemps))
19588 return false;
19589
19590 LV.moveInto(Result.Val);
19591 return true;
19592}
19593
19595 APValue DestroyedValue, QualType Type,
19596 SourceLocation Loc, Expr::EvalStatus &EStatus,
19597 bool IsConstantDestruction) {
19598 EvalInfo Info(Ctx, EStatus,
19599 IsConstantDestruction ? EvaluationMode::ConstantExpression
19601 Info.setEvaluatingDecl(Base, DestroyedValue,
19602 EvalInfo::EvaluatingDeclKind::Dtor);
19603 Info.InConstantContext = IsConstantDestruction;
19604
19605 LValue LVal;
19606 LVal.set(Base);
19607
19608 if (!HandleDestruction(Info, Loc, Base, DestroyedValue, Type) ||
19609 EStatus.HasSideEffects)
19610 return false;
19611
19612 if (!Info.discardCleanups())
19613 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
19614
19615 return true;
19616}
19617
19619 ConstantExprKind Kind) const {
19620 assert(!isValueDependent() &&
19621 "Expression evaluator can't be called on a dependent expression.");
19622 bool IsConst;
19623 if (FastEvaluateAsRValue(this, Result.Val, Ctx, IsConst) &&
19624 Result.Val.hasValue())
19625 return true;
19626
19627 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsConstantExpr");
19629 EvalInfo Info(Ctx, Result, EM);
19630 Info.InConstantContext = true;
19631
19632 if (Info.EnableNewConstInterp) {
19633 if (!Info.Ctx.getInterpContext().evaluate(Info, this, Result.Val, Kind))
19634 return false;
19635 return CheckConstantExpression(Info, getExprLoc(),
19636 getStorageType(Ctx, this), Result.Val, Kind);
19637 }
19638
19639 // The type of the object we're initializing is 'const T' for a class NTTP.
19640 QualType T = getType();
19641 if (Kind == ConstantExprKind::ClassTemplateArgument)
19642 T.addConst();
19643
19644 // If we're evaluating a prvalue, fake up a MaterializeTemporaryExpr to
19645 // represent the result of the evaluation. CheckConstantExpression ensures
19646 // this doesn't escape.
19647 MaterializeTemporaryExpr BaseMTE(T, const_cast<Expr*>(this), true);
19648 APValue::LValueBase Base(&BaseMTE);
19649 Info.setEvaluatingDecl(Base, Result.Val);
19650
19651 LValue LVal;
19652 LVal.set(Base);
19653 // C++23 [intro.execution]/p5
19654 // A full-expression is [...] a constant-expression
19655 // So we need to make sure temporary objects are destroyed after having
19656 // evaluating the expression (per C++23 [class.temporary]/p4).
19657 FullExpressionRAII Scope(Info);
19658 if (!::EvaluateInPlace(Result.Val, Info, LVal, this) ||
19659 Result.HasSideEffects || !Scope.destroy())
19660 return false;
19661
19662 if (!Info.discardCleanups())
19663 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
19664
19665 if (!CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this),
19666 Result.Val, Kind))
19667 return false;
19668 if (!CheckMemoryLeaks(Info))
19669 return false;
19670
19671 // If this is a class template argument, it's required to have constant
19672 // destruction too.
19673 if (Kind == ConstantExprKind::ClassTemplateArgument &&
19675 true) ||
19676 Result.HasSideEffects)) {
19677 // FIXME: Prefix a note to indicate that the problem is lack of constant
19678 // destruction.
19679 return false;
19680 }
19681
19682 return true;
19683}
19684
19686 const VarDecl *VD,
19688 bool IsConstantInitialization) const {
19689 assert(!isValueDependent() &&
19690 "Expression evaluator can't be called on a dependent expression.");
19691 assert(VD && "Need a valid VarDecl");
19692
19693 llvm::TimeTraceScope TimeScope("EvaluateAsInitializer", [&] {
19694 std::string Name;
19695 llvm::raw_string_ostream OS(Name);
19696 VD->printQualifiedName(OS);
19697 return Name;
19698 });
19699
19700 Expr::EvalStatus EStatus;
19701 EStatus.Diag = &Notes;
19702
19703 EvalInfo Info(Ctx, EStatus,
19704 (IsConstantInitialization &&
19705 (Ctx.getLangOpts().CPlusPlus || Ctx.getLangOpts().C23))
19708 Info.setEvaluatingDecl(VD, Value);
19709 Info.InConstantContext = IsConstantInitialization;
19710
19711 SourceLocation DeclLoc = VD->getLocation();
19712 QualType DeclTy = VD->getType();
19713
19714 if (Info.EnableNewConstInterp) {
19715 auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext();
19716 if (!InterpCtx.evaluateAsInitializer(Info, VD, this, Value))
19717 return false;
19718
19719 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value,
19720 ConstantExprKind::Normal);
19721 } else {
19722 LValue LVal;
19723 LVal.set(VD);
19724
19725 {
19726 // C++23 [intro.execution]/p5
19727 // A full-expression is ... an init-declarator ([dcl.decl]) or a
19728 // mem-initializer.
19729 // So we need to make sure temporary objects are destroyed after having
19730 // evaluated the expression (per C++23 [class.temporary]/p4).
19731 //
19732 // FIXME: Otherwise this may break test/Modules/pr68702.cpp because the
19733 // serialization code calls ParmVarDecl::getDefaultArg() which strips the
19734 // outermost FullExpr, such as ExprWithCleanups.
19735 FullExpressionRAII Scope(Info);
19736 if (!EvaluateInPlace(Value, Info, LVal, this,
19737 /*AllowNonLiteralTypes=*/true) ||
19738 EStatus.HasSideEffects)
19739 return false;
19740 }
19741
19742 // At this point, any lifetime-extended temporaries are completely
19743 // initialized.
19744 Info.performLifetimeExtension();
19745
19746 if (!Info.discardCleanups())
19747 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
19748 }
19749
19750 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value,
19751 ConstantExprKind::Normal) &&
19752 CheckMemoryLeaks(Info);
19753}
19754
19757 Expr::EvalStatus EStatus;
19758 EStatus.Diag = &Notes;
19759
19760 // Only treat the destruction as constant destruction if we formally have
19761 // constant initialization (or are usable in a constant expression).
19762 bool IsConstantDestruction = hasConstantInitialization();
19763
19764 // Make a copy of the value for the destructor to mutate, if we know it.
19765 // Otherwise, treat the value as default-initialized; if the destructor works
19766 // anyway, then the destruction is constant (and must be essentially empty).
19767 APValue DestroyedValue;
19768 if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent())
19769 DestroyedValue = *getEvaluatedValue();
19770 else if (!handleDefaultInitValue(getType(), DestroyedValue))
19771 return false;
19772
19773 if (!EvaluateDestruction(getASTContext(), this, std::move(DestroyedValue),
19774 getType(), getLocation(), EStatus,
19775 IsConstantDestruction) ||
19776 EStatus.HasSideEffects)
19777 return false;
19778
19779 ensureEvaluatedStmt()->HasConstantDestruction = true;
19780 return true;
19781}
19782
19783/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
19784/// constant folded, but discard the result.
19786 assert(!isValueDependent() &&
19787 "Expression evaluator can't be called on a dependent expression.");
19788
19790 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
19792}
19793
19794APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
19795 assert(!isValueDependent() &&
19796 "Expression evaluator can't be called on a dependent expression.");
19797
19798 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstInt");
19799 EvalResult EVResult;
19800 EvalInfo Info(Ctx, EVResult, EvaluationMode::IgnoreSideEffects);
19801 Info.InConstantContext = true;
19802
19803 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
19804 (void)Result;
19805 assert(Result && "Could not evaluate expression");
19806 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
19807
19808 return EVResult.Val.getInt();
19809}
19810
19813 assert(!isValueDependent() &&
19814 "Expression evaluator can't be called on a dependent expression.");
19815
19816 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstIntCheckOverflow");
19817 EvalResult EVResult;
19818 EVResult.Diag = Diag;
19819 EvalInfo Info(Ctx, EVResult, EvaluationMode::IgnoreSideEffects);
19820 Info.InConstantContext = true;
19821 Info.CheckingForUndefinedBehavior = true;
19822
19823 bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
19824 (void)Result;
19825 assert(Result && "Could not evaluate expression");
19826 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
19827
19828 return EVResult.Val.getInt();
19829}
19830
19832 assert(!isValueDependent() &&
19833 "Expression evaluator can't be called on a dependent expression.");
19834
19835 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateForOverflow");
19836 bool IsConst;
19837 EvalResult EVResult;
19838 if (!FastEvaluateAsRValue(this, EVResult.Val, Ctx, IsConst)) {
19839 EvalInfo Info(Ctx, EVResult, EvaluationMode::IgnoreSideEffects);
19840 Info.CheckingForUndefinedBehavior = true;
19841 (void)::EvaluateAsRValue(Info, this, EVResult.Val);
19842 }
19843}
19844
19846 assert(Val.isLValue());
19847 return IsGlobalLValue(Val.getLValueBase());
19848}
19849
19850/// isIntegerConstantExpr - this recursive routine will test if an expression is
19851/// an integer constant expression.
19852
19853/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
19854/// comma, etc
19855
19856// CheckICE - This function does the fundamental ICE checking: the returned
19857// ICEDiag contains an ICEKind indicating whether the expression is an ICE.
19858//
19859// Note that to reduce code duplication, this helper does no evaluation
19860// itself; the caller checks whether the expression is evaluatable, and
19861// in the rare cases where CheckICE actually cares about the evaluated
19862// value, it calls into Evaluate.
19863
19864namespace {
19865
19866enum ICEKind {
19867 /// This expression is an ICE.
19868 IK_ICE,
19869 /// This expression is not an ICE, but if it isn't evaluated, it's
19870 /// a legal subexpression for an ICE. This return value is used to handle
19871 /// the comma operator in C99 mode, and non-constant subexpressions.
19872 IK_ICEIfUnevaluated,
19873 /// This expression is not an ICE, and is not a legal subexpression for one.
19874 IK_NotICE
19875};
19876
19877struct ICEDiag {
19878 ICEKind Kind;
19879 SourceLocation Loc;
19880
19881 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
19882};
19883
19884}
19885
19886static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
19887
19888static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
19889
19890static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
19891 Expr::EvalResult EVResult;
19892 Expr::EvalStatus Status;
19893 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantExpression);
19894
19895 Info.InConstantContext = true;
19896 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
19897 !EVResult.Val.isInt())
19898 return ICEDiag(IK_NotICE, E->getBeginLoc());
19899
19900 return NoDiag();
19901}
19902
19903static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
19904 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
19906 return ICEDiag(IK_NotICE, E->getBeginLoc());
19907
19908 switch (E->getStmtClass()) {
19909#define ABSTRACT_STMT(Node)
19910#define STMT(Node, Base) case Expr::Node##Class:
19911#define EXPR(Node, Base)
19912#include "clang/AST/StmtNodes.inc"
19913 case Expr::PredefinedExprClass:
19914 case Expr::FloatingLiteralClass:
19915 case Expr::ImaginaryLiteralClass:
19916 case Expr::StringLiteralClass:
19917 case Expr::ArraySubscriptExprClass:
19918 case Expr::MatrixSubscriptExprClass:
19919 case Expr::ArraySectionExprClass:
19920 case Expr::OMPArrayShapingExprClass:
19921 case Expr::OMPIteratorExprClass:
19922 case Expr::MemberExprClass:
19923 case Expr::CompoundAssignOperatorClass:
19924 case Expr::CompoundLiteralExprClass:
19925 case Expr::ExtVectorElementExprClass:
19926 case Expr::DesignatedInitExprClass:
19927 case Expr::ArrayInitLoopExprClass:
19928 case Expr::ArrayInitIndexExprClass:
19929 case Expr::NoInitExprClass:
19930 case Expr::DesignatedInitUpdateExprClass:
19931 case Expr::ImplicitValueInitExprClass:
19932 case Expr::ParenListExprClass:
19933 case Expr::VAArgExprClass:
19934 case Expr::AddrLabelExprClass:
19935 case Expr::StmtExprClass:
19936 case Expr::CXXMemberCallExprClass:
19937 case Expr::CUDAKernelCallExprClass:
19938 case Expr::CXXAddrspaceCastExprClass:
19939 case Expr::CXXDynamicCastExprClass:
19940 case Expr::CXXTypeidExprClass:
19941 case Expr::CXXUuidofExprClass:
19942 case Expr::MSPropertyRefExprClass:
19943 case Expr::MSPropertySubscriptExprClass:
19944 case Expr::CXXNullPtrLiteralExprClass:
19945 case Expr::UserDefinedLiteralClass:
19946 case Expr::CXXThisExprClass:
19947 case Expr::CXXThrowExprClass:
19948 case Expr::CXXNewExprClass:
19949 case Expr::CXXDeleteExprClass:
19950 case Expr::CXXPseudoDestructorExprClass:
19951 case Expr::UnresolvedLookupExprClass:
19952 case Expr::RecoveryExprClass:
19953 case Expr::DependentScopeDeclRefExprClass:
19954 case Expr::CXXConstructExprClass:
19955 case Expr::CXXInheritedCtorInitExprClass:
19956 case Expr::CXXStdInitializerListExprClass:
19957 case Expr::CXXBindTemporaryExprClass:
19958 case Expr::ExprWithCleanupsClass:
19959 case Expr::CXXTemporaryObjectExprClass:
19960 case Expr::CXXUnresolvedConstructExprClass:
19961 case Expr::CXXDependentScopeMemberExprClass:
19962 case Expr::UnresolvedMemberExprClass:
19963 case Expr::ObjCStringLiteralClass:
19964 case Expr::ObjCBoxedExprClass:
19965 case Expr::ObjCArrayLiteralClass:
19966 case Expr::ObjCDictionaryLiteralClass:
19967 case Expr::ObjCEncodeExprClass:
19968 case Expr::ObjCMessageExprClass:
19969 case Expr::ObjCSelectorExprClass:
19970 case Expr::ObjCProtocolExprClass:
19971 case Expr::ObjCIvarRefExprClass:
19972 case Expr::ObjCPropertyRefExprClass:
19973 case Expr::ObjCSubscriptRefExprClass:
19974 case Expr::ObjCIsaExprClass:
19975 case Expr::ObjCAvailabilityCheckExprClass:
19976 case Expr::ShuffleVectorExprClass:
19977 case Expr::ConvertVectorExprClass:
19978 case Expr::BlockExprClass:
19979 case Expr::NoStmtClass:
19980 case Expr::OpaqueValueExprClass:
19981 case Expr::PackExpansionExprClass:
19982 case Expr::SubstNonTypeTemplateParmPackExprClass:
19983 case Expr::FunctionParmPackExprClass:
19984 case Expr::AsTypeExprClass:
19985 case Expr::ObjCIndirectCopyRestoreExprClass:
19986 case Expr::MaterializeTemporaryExprClass:
19987 case Expr::PseudoObjectExprClass:
19988 case Expr::AtomicExprClass:
19989 case Expr::LambdaExprClass:
19990 case Expr::CXXFoldExprClass:
19991 case Expr::CoawaitExprClass:
19992 case Expr::DependentCoawaitExprClass:
19993 case Expr::CoyieldExprClass:
19994 case Expr::SYCLUniqueStableNameExprClass:
19995 case Expr::CXXParenListInitExprClass:
19996 case Expr::HLSLOutArgExprClass:
19997 return ICEDiag(IK_NotICE, E->getBeginLoc());
19998
19999 case Expr::InitListExprClass: {
20000 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
20001 // form "T x = { a };" is equivalent to "T x = a;".
20002 // Unless we're initializing a reference, T is a scalar as it is known to be
20003 // of integral or enumeration type.
20004 if (E->isPRValue())
20005 if (cast<InitListExpr>(E)->getNumInits() == 1)
20006 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
20007 return ICEDiag(IK_NotICE, E->getBeginLoc());
20008 }
20009
20010 case Expr::SizeOfPackExprClass:
20011 case Expr::GNUNullExprClass:
20012 case Expr::SourceLocExprClass:
20013 case Expr::EmbedExprClass:
20014 case Expr::OpenACCAsteriskSizeExprClass:
20015 return NoDiag();
20016
20017 case Expr::PackIndexingExprClass:
20018 return CheckICE(cast<PackIndexingExpr>(E)->getSelectedExpr(), Ctx);
20019
20020 case Expr::SubstNonTypeTemplateParmExprClass:
20021 return
20022 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
20023
20024 case Expr::ConstantExprClass:
20025 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
20026
20027 case Expr::ParenExprClass:
20028 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
20029 case Expr::GenericSelectionExprClass:
20030 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
20031 case Expr::IntegerLiteralClass:
20032 case Expr::FixedPointLiteralClass:
20033 case Expr::CharacterLiteralClass:
20034 case Expr::ObjCBoolLiteralExprClass:
20035 case Expr::CXXBoolLiteralExprClass:
20036 case Expr::CXXScalarValueInitExprClass:
20037 case Expr::TypeTraitExprClass:
20038 case Expr::ConceptSpecializationExprClass:
20039 case Expr::RequiresExprClass:
20040 case Expr::ArrayTypeTraitExprClass:
20041 case Expr::ExpressionTraitExprClass:
20042 case Expr::CXXNoexceptExprClass:
20043 return NoDiag();
20044 case Expr::CallExprClass:
20045 case Expr::CXXOperatorCallExprClass: {
20046 // C99 6.6/3 allows function calls within unevaluated subexpressions of
20047 // constant expressions, but they can never be ICEs because an ICE cannot
20048 // contain an operand of (pointer to) function type.
20049 const CallExpr *CE = cast<CallExpr>(E);
20050 if (CE->getBuiltinCallee())
20051 return CheckEvalInICE(E, Ctx);
20052 return ICEDiag(IK_NotICE, E->getBeginLoc());
20053 }
20054 case Expr::CXXRewrittenBinaryOperatorClass:
20055 return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(),
20056 Ctx);
20057 case Expr::DeclRefExprClass: {
20058 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
20059 if (isa<EnumConstantDecl>(D))
20060 return NoDiag();
20061
20062 // C++ and OpenCL (FIXME: spec reference?) allow reading const-qualified
20063 // integer variables in constant expressions:
20064 //
20065 // C++ 7.1.5.1p2
20066 // A variable of non-volatile const-qualified integral or enumeration
20067 // type initialized by an ICE can be used in ICEs.
20068 //
20069 // We sometimes use CheckICE to check the C++98 rules in C++11 mode. In
20070 // that mode, use of reference variables should not be allowed.
20071 const VarDecl *VD = dyn_cast<VarDecl>(D);
20072 if (VD && VD->isUsableInConstantExpressions(Ctx) &&
20073 !VD->getType()->isReferenceType())
20074 return NoDiag();
20075
20076 return ICEDiag(IK_NotICE, E->getBeginLoc());
20077 }
20078 case Expr::UnaryOperatorClass: {
20079 const UnaryOperator *Exp = cast<UnaryOperator>(E);
20080 switch (Exp->getOpcode()) {
20081 case UO_PostInc:
20082 case UO_PostDec:
20083 case UO_PreInc:
20084 case UO_PreDec:
20085 case UO_AddrOf:
20086 case UO_Deref:
20087 case UO_Coawait:
20088 // C99 6.6/3 allows increment and decrement within unevaluated
20089 // subexpressions of constant expressions, but they can never be ICEs
20090 // because an ICE cannot contain an lvalue operand.
20091 return ICEDiag(IK_NotICE, E->getBeginLoc());
20092 case UO_Extension:
20093 case UO_LNot:
20094 case UO_Plus:
20095 case UO_Minus:
20096 case UO_Not:
20097 case UO_Real:
20098 case UO_Imag:
20099 return CheckICE(Exp->getSubExpr(), Ctx);
20100 }
20101 llvm_unreachable("invalid unary operator class");
20102 }
20103 case Expr::OffsetOfExprClass: {
20104 // Note that per C99, offsetof must be an ICE. And AFAIK, using
20105 // EvaluateAsRValue matches the proposed gcc behavior for cases like
20106 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
20107 // compliance: we should warn earlier for offsetof expressions with
20108 // array subscripts that aren't ICEs, and if the array subscripts
20109 // are ICEs, the value of the offsetof must be an integer constant.
20110 return CheckEvalInICE(E, Ctx);
20111 }
20112 case Expr::UnaryExprOrTypeTraitExprClass: {
20114 if ((Exp->getKind() == UETT_SizeOf) &&
20116 return ICEDiag(IK_NotICE, E->getBeginLoc());
20117 if (Exp->getKind() == UETT_CountOf) {
20118 QualType ArgTy = Exp->getTypeOfArgument();
20119 if (ArgTy->isVariableArrayType()) {
20120 // We need to look whether the array is multidimensional. If it is,
20121 // then we want to check the size expression manually to see whether
20122 // it is an ICE or not.
20123 const auto *VAT = Ctx.getAsVariableArrayType(ArgTy);
20124 if (VAT->getElementType()->isArrayType())
20125 // Variable array size expression could be missing (e.g. int a[*][10])
20126 // In that case, it can't be a constant expression.
20127 return VAT->getSizeExpr() ? CheckICE(VAT->getSizeExpr(), Ctx)
20128 : ICEDiag(IK_NotICE, E->getBeginLoc());
20129
20130 // Otherwise, this is a regular VLA, which is definitely not an ICE.
20131 return ICEDiag(IK_NotICE, E->getBeginLoc());
20132 }
20133 }
20134 return NoDiag();
20135 }
20136 case Expr::BinaryOperatorClass: {
20137 const BinaryOperator *Exp = cast<BinaryOperator>(E);
20138 switch (Exp->getOpcode()) {
20139 case BO_PtrMemD:
20140 case BO_PtrMemI:
20141 case BO_Assign:
20142 case BO_MulAssign:
20143 case BO_DivAssign:
20144 case BO_RemAssign:
20145 case BO_AddAssign:
20146 case BO_SubAssign:
20147 case BO_ShlAssign:
20148 case BO_ShrAssign:
20149 case BO_AndAssign:
20150 case BO_XorAssign:
20151 case BO_OrAssign:
20152 // C99 6.6/3 allows assignments within unevaluated subexpressions of
20153 // constant expressions, but they can never be ICEs because an ICE cannot
20154 // contain an lvalue operand.
20155 return ICEDiag(IK_NotICE, E->getBeginLoc());
20156
20157 case BO_Mul:
20158 case BO_Div:
20159 case BO_Rem:
20160 case BO_Add:
20161 case BO_Sub:
20162 case BO_Shl:
20163 case BO_Shr:
20164 case BO_LT:
20165 case BO_GT:
20166 case BO_LE:
20167 case BO_GE:
20168 case BO_EQ:
20169 case BO_NE:
20170 case BO_And:
20171 case BO_Xor:
20172 case BO_Or:
20173 case BO_Comma:
20174 case BO_Cmp: {
20175 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
20176 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
20177 if (Exp->getOpcode() == BO_Div ||
20178 Exp->getOpcode() == BO_Rem) {
20179 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
20180 // we don't evaluate one.
20181 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
20182 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
20183 if (REval == 0)
20184 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
20185 if (REval.isSigned() && REval.isAllOnes()) {
20186 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
20187 if (LEval.isMinSignedValue())
20188 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
20189 }
20190 }
20191 }
20192 if (Exp->getOpcode() == BO_Comma) {
20193 if (Ctx.getLangOpts().C99) {
20194 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
20195 // if it isn't evaluated.
20196 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
20197 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
20198 } else {
20199 // In both C89 and C++, commas in ICEs are illegal.
20200 return ICEDiag(IK_NotICE, E->getBeginLoc());
20201 }
20202 }
20203 return Worst(LHSResult, RHSResult);
20204 }
20205 case BO_LAnd:
20206 case BO_LOr: {
20207 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
20208 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
20209 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
20210 // Rare case where the RHS has a comma "side-effect"; we need
20211 // to actually check the condition to see whether the side
20212 // with the comma is evaluated.
20213 if ((Exp->getOpcode() == BO_LAnd) !=
20214 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
20215 return RHSResult;
20216 return NoDiag();
20217 }
20218
20219 return Worst(LHSResult, RHSResult);
20220 }
20221 }
20222 llvm_unreachable("invalid binary operator kind");
20223 }
20224 case Expr::ImplicitCastExprClass:
20225 case Expr::CStyleCastExprClass:
20226 case Expr::CXXFunctionalCastExprClass:
20227 case Expr::CXXStaticCastExprClass:
20228 case Expr::CXXReinterpretCastExprClass:
20229 case Expr::CXXConstCastExprClass:
20230 case Expr::ObjCBridgedCastExprClass: {
20231 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
20232 if (isa<ExplicitCastExpr>(E)) {
20233 if (const FloatingLiteral *FL
20234 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
20235 unsigned DestWidth = Ctx.getIntWidth(E->getType());
20236 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
20237 APSInt IgnoredVal(DestWidth, !DestSigned);
20238 bool Ignored;
20239 // If the value does not fit in the destination type, the behavior is
20240 // undefined, so we are not required to treat it as a constant
20241 // expression.
20242 if (FL->getValue().convertToInteger(IgnoredVal,
20243 llvm::APFloat::rmTowardZero,
20244 &Ignored) & APFloat::opInvalidOp)
20245 return ICEDiag(IK_NotICE, E->getBeginLoc());
20246 return NoDiag();
20247 }
20248 }
20249 switch (cast<CastExpr>(E)->getCastKind()) {
20250 case CK_LValueToRValue:
20251 case CK_AtomicToNonAtomic:
20252 case CK_NonAtomicToAtomic:
20253 case CK_NoOp:
20254 case CK_IntegralToBoolean:
20255 case CK_IntegralCast:
20256 return CheckICE(SubExpr, Ctx);
20257 default:
20258 return ICEDiag(IK_NotICE, E->getBeginLoc());
20259 }
20260 }
20261 case Expr::BinaryConditionalOperatorClass: {
20263 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
20264 if (CommonResult.Kind == IK_NotICE) return CommonResult;
20265 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
20266 if (FalseResult.Kind == IK_NotICE) return FalseResult;
20267 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
20268 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
20269 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
20270 return FalseResult;
20271 }
20272 case Expr::ConditionalOperatorClass: {
20274 // If the condition (ignoring parens) is a __builtin_constant_p call,
20275 // then only the true side is actually considered in an integer constant
20276 // expression, and it is fully evaluated. This is an important GNU
20277 // extension. See GCC PR38377 for discussion.
20278 if (const CallExpr *CallCE
20279 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
20280 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
20281 return CheckEvalInICE(E, Ctx);
20282 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
20283 if (CondResult.Kind == IK_NotICE)
20284 return CondResult;
20285
20286 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
20287 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
20288
20289 if (TrueResult.Kind == IK_NotICE)
20290 return TrueResult;
20291 if (FalseResult.Kind == IK_NotICE)
20292 return FalseResult;
20293 if (CondResult.Kind == IK_ICEIfUnevaluated)
20294 return CondResult;
20295 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
20296 return NoDiag();
20297 // Rare case where the diagnostics depend on which side is evaluated
20298 // Note that if we get here, CondResult is 0, and at least one of
20299 // TrueResult and FalseResult is non-zero.
20300 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
20301 return FalseResult;
20302 return TrueResult;
20303 }
20304 case Expr::CXXDefaultArgExprClass:
20305 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
20306 case Expr::CXXDefaultInitExprClass:
20307 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
20308 case Expr::ChooseExprClass: {
20309 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
20310 }
20311 case Expr::BuiltinBitCastExprClass: {
20312 if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
20313 return ICEDiag(IK_NotICE, E->getBeginLoc());
20314 return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
20315 }
20316 }
20317
20318 llvm_unreachable("Invalid StmtClass!");
20319}
20320
20321/// Evaluate an expression as a C++11 integral constant expression.
20323 const Expr *E,
20324 llvm::APSInt *Value) {
20326 return false;
20327
20328 APValue Result;
20329 if (!E->isCXX11ConstantExpr(Ctx, &Result))
20330 return false;
20331
20332 if (!Result.isInt())
20333 return false;
20334
20335 if (Value) *Value = Result.getInt();
20336 return true;
20337}
20338
20340 assert(!isValueDependent() &&
20341 "Expression evaluator can't be called on a dependent expression.");
20342
20343 ExprTimeTraceScope TimeScope(this, Ctx, "isIntegerConstantExpr");
20344
20345 if (Ctx.getLangOpts().CPlusPlus11)
20346 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr);
20347
20348 ICEDiag D = CheckICE(this, Ctx);
20349 if (D.Kind != IK_ICE)
20350 return false;
20351 return true;
20352}
20353
20354std::optional<llvm::APSInt>
20356 if (isValueDependent()) {
20357 // Expression evaluator can't succeed on a dependent expression.
20358 return std::nullopt;
20359 }
20360
20361 if (Ctx.getLangOpts().CPlusPlus11) {
20362 APSInt Value;
20364 return Value;
20365 return std::nullopt;
20366 }
20367
20368 if (!isIntegerConstantExpr(Ctx))
20369 return std::nullopt;
20370
20371 // The only possible side-effects here are due to UB discovered in the
20372 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
20373 // required to treat the expression as an ICE, so we produce the folded
20374 // value.
20376 Expr::EvalStatus Status;
20377 EvalInfo Info(Ctx, Status, EvaluationMode::IgnoreSideEffects);
20378 Info.InConstantContext = true;
20379
20380 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
20381 llvm_unreachable("ICE cannot be evaluated!");
20382
20383 return ExprResult.Val.getInt();
20384}
20385
20387 assert(!isValueDependent() &&
20388 "Expression evaluator can't be called on a dependent expression.");
20389
20390 return CheckICE(this, Ctx).Kind == IK_ICE;
20391}
20392
20394 assert(!isValueDependent() &&
20395 "Expression evaluator can't be called on a dependent expression.");
20396
20397 // We support this checking in C++98 mode in order to diagnose compatibility
20398 // issues.
20399 assert(Ctx.getLangOpts().CPlusPlus);
20400
20401 bool IsConst;
20402 APValue Scratch;
20403 if (FastEvaluateAsRValue(this, Scratch, Ctx, IsConst) && Scratch.hasValue()) {
20404 if (Result)
20405 *Result = Scratch;
20406 return true;
20407 }
20408
20409 // Build evaluation settings.
20410 Expr::EvalStatus Status;
20412 Status.Diag = &Diags;
20413 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantExpression);
20414
20415 bool IsConstExpr =
20416 ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) &&
20417 // FIXME: We don't produce a diagnostic for this, but the callers that
20418 // call us on arbitrary full-expressions should generally not care.
20419 Info.discardCleanups() && !Status.HasSideEffects;
20420
20421 return IsConstExpr && Diags.empty();
20422}
20423
20425 const FunctionDecl *Callee,
20427 const Expr *This) const {
20428 assert(!isValueDependent() &&
20429 "Expression evaluator can't be called on a dependent expression.");
20430
20431 llvm::TimeTraceScope TimeScope("EvaluateWithSubstitution", [&] {
20432 std::string Name;
20433 llvm::raw_string_ostream OS(Name);
20434 Callee->getNameForDiagnostic(OS, Ctx.getPrintingPolicy(),
20435 /*Qualified=*/true);
20436 return Name;
20437 });
20438
20439 Expr::EvalStatus Status;
20440 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantExpressionUnevaluated);
20441 Info.InConstantContext = true;
20442
20443 LValue ThisVal;
20444 const LValue *ThisPtr = nullptr;
20445 if (This) {
20446#ifndef NDEBUG
20447 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
20448 assert(MD && "Don't provide `this` for non-methods.");
20449 assert(MD->isImplicitObjectMemberFunction() &&
20450 "Don't provide `this` for methods without an implicit object.");
20451#endif
20452 if (!This->isValueDependent() &&
20453 EvaluateObjectArgument(Info, This, ThisVal) &&
20454 !Info.EvalStatus.HasSideEffects)
20455 ThisPtr = &ThisVal;
20456
20457 // Ignore any side-effects from a failed evaluation. This is safe because
20458 // they can't interfere with any other argument evaluation.
20459 Info.EvalStatus.HasSideEffects = false;
20460 }
20461
20462 CallRef Call = Info.CurrentCall->createCall(Callee);
20463 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
20464 I != E; ++I) {
20465 unsigned Idx = I - Args.begin();
20466 if (Idx >= Callee->getNumParams())
20467 break;
20468 const ParmVarDecl *PVD = Callee->getParamDecl(Idx);
20469 if ((*I)->isValueDependent() ||
20470 !EvaluateCallArg(PVD, *I, Call, Info) ||
20471 Info.EvalStatus.HasSideEffects) {
20472 // If evaluation fails, throw away the argument entirely.
20473 if (APValue *Slot = Info.getParamSlot(Call, PVD))
20474 *Slot = APValue();
20475 }
20476
20477 // Ignore any side-effects from a failed evaluation. This is safe because
20478 // they can't interfere with any other argument evaluation.
20479 Info.EvalStatus.HasSideEffects = false;
20480 }
20481
20482 // Parameter cleanups happen in the caller and are not part of this
20483 // evaluation.
20484 Info.discardCleanups();
20485 Info.EvalStatus.HasSideEffects = false;
20486
20487 // Build fake call to Callee.
20488 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, This,
20489 Call);
20490 // FIXME: Missing ExprWithCleanups in enable_if conditions?
20491 FullExpressionRAII Scope(Info);
20492 return Evaluate(Value, Info, this) && Scope.destroy() &&
20493 !Info.EvalStatus.HasSideEffects;
20494}
20495
20498 PartialDiagnosticAt> &Diags) {
20499 // FIXME: It would be useful to check constexpr function templates, but at the
20500 // moment the constant expression evaluator cannot cope with the non-rigorous
20501 // ASTs which we build for dependent expressions.
20502 if (FD->isDependentContext())
20503 return true;
20504
20505 llvm::TimeTraceScope TimeScope("isPotentialConstantExpr", [&] {
20506 std::string Name;
20507 llvm::raw_string_ostream OS(Name);
20509 /*Qualified=*/true);
20510 return Name;
20511 });
20512
20513 Expr::EvalStatus Status;
20514 Status.Diag = &Diags;
20515
20516 EvalInfo Info(FD->getASTContext(), Status,
20518 Info.InConstantContext = true;
20519 Info.CheckingPotentialConstantExpression = true;
20520
20521 // The constexpr VM attempts to compile all methods to bytecode here.
20522 if (Info.EnableNewConstInterp) {
20523 Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD);
20524 return Diags.empty();
20525 }
20526
20527 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
20528 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
20529
20530 // Fabricate an arbitrary expression on the stack and pretend that it
20531 // is a temporary being used as the 'this' pointer.
20532 LValue This;
20533 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getCanonicalTagType(RD)
20534 : Info.Ctx.IntTy);
20535 This.set({&VIE, Info.CurrentCall->Index});
20536
20538
20539 APValue Scratch;
20540 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
20541 // Evaluate the call as a constant initializer, to allow the construction
20542 // of objects of non-literal types.
20543 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
20544 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
20545 } else {
20546 SourceLocation Loc = FD->getLocation();
20548 Loc, FD, (MD && MD->isImplicitObjectMemberFunction()) ? &This : nullptr,
20549 &VIE, Args, CallRef(), FD->getBody(), Info, Scratch,
20550 /*ResultSlot=*/nullptr);
20551 }
20552
20553 return Diags.empty();
20554}
20555
20557 const FunctionDecl *FD,
20559 PartialDiagnosticAt> &Diags) {
20560 assert(!E->isValueDependent() &&
20561 "Expression evaluator can't be called on a dependent expression.");
20562
20563 Expr::EvalStatus Status;
20564 Status.Diag = &Diags;
20565
20566 EvalInfo Info(FD->getASTContext(), Status,
20568 Info.InConstantContext = true;
20569 Info.CheckingPotentialConstantExpression = true;
20570
20571 if (Info.EnableNewConstInterp) {
20573 return Diags.empty();
20574 }
20575
20576 // Fabricate a call stack frame to give the arguments a plausible cover story.
20577 CallStackFrame Frame(Info, SourceLocation(), FD, /*This=*/nullptr,
20578 /*CallExpr=*/nullptr, CallRef());
20579
20580 APValue ResultScratch;
20581 Evaluate(ResultScratch, Info, E);
20582 return Diags.empty();
20583}
20584
20586 unsigned Type) const {
20587 if (!getType()->isPointerType())
20588 return false;
20589
20590 Expr::EvalStatus Status;
20591 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantFold);
20592 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
20593}
20594
20595static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,
20596 EvalInfo &Info, std::string *StringResult) {
20597 if (!E->getType()->hasPointerRepresentation() || !E->isPRValue())
20598 return false;
20599
20600 LValue String;
20601
20602 if (!EvaluatePointer(E, String, Info))
20603 return false;
20604
20605 QualType CharTy = E->getType()->getPointeeType();
20606
20607 // Fast path: if it's a string literal, search the string value.
20608 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
20609 String.getLValueBase().dyn_cast<const Expr *>())) {
20610 StringRef Str = S->getBytes();
20611 int64_t Off = String.Offset.getQuantity();
20612 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
20613 S->getCharByteWidth() == 1 &&
20614 // FIXME: Add fast-path for wchar_t too.
20615 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
20616 Str = Str.substr(Off);
20617
20618 StringRef::size_type Pos = Str.find(0);
20619 if (Pos != StringRef::npos)
20620 Str = Str.substr(0, Pos);
20621
20622 Result = Str.size();
20623 if (StringResult)
20624 *StringResult = Str;
20625 return true;
20626 }
20627
20628 // Fall through to slow path.
20629 }
20630
20631 // Slow path: scan the bytes of the string looking for the terminating 0.
20632 for (uint64_t Strlen = 0; /**/; ++Strlen) {
20633 APValue Char;
20634 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
20635 !Char.isInt())
20636 return false;
20637 if (!Char.getInt()) {
20638 Result = Strlen;
20639 return true;
20640 } else if (StringResult)
20641 StringResult->push_back(Char.getInt().getExtValue());
20642 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
20643 return false;
20644 }
20645}
20646
20647std::optional<std::string> Expr::tryEvaluateString(ASTContext &Ctx) const {
20648 Expr::EvalStatus Status;
20649 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantFold);
20650 uint64_t Result;
20651 std::string StringResult;
20652
20653 if (Info.EnableNewConstInterp) {
20654 if (!Info.Ctx.getInterpContext().evaluateString(Info, this, StringResult))
20655 return std::nullopt;
20656 return StringResult;
20657 }
20658
20659 if (EvaluateBuiltinStrLen(this, Result, Info, &StringResult))
20660 return StringResult;
20661 return std::nullopt;
20662}
20663
20664template <typename T>
20665static bool EvaluateCharRangeAsStringImpl(const Expr *, T &Result,
20666 const Expr *SizeExpression,
20667 const Expr *PtrExpression,
20668 ASTContext &Ctx,
20669 Expr::EvalResult &Status) {
20670 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantExpression);
20671 Info.InConstantContext = true;
20672
20673 if (Info.EnableNewConstInterp)
20674 return Info.Ctx.getInterpContext().evaluateCharRange(Info, SizeExpression,
20675 PtrExpression, Result);
20676
20677 LValue String;
20678 FullExpressionRAII Scope(Info);
20679 APSInt SizeValue;
20680 if (!::EvaluateInteger(SizeExpression, SizeValue, Info))
20681 return false;
20682
20683 uint64_t Size = SizeValue.getZExtValue();
20684
20685 // FIXME: better protect against invalid or excessive sizes
20686 if constexpr (std::is_same_v<APValue, T>)
20687 Result = APValue(APValue::UninitArray{}, Size, Size);
20688 else {
20689 if (Size < Result.max_size())
20690 Result.reserve(Size);
20691 }
20692 if (!::EvaluatePointer(PtrExpression, String, Info))
20693 return false;
20694
20695 QualType CharTy = PtrExpression->getType()->getPointeeType();
20696 for (uint64_t I = 0; I < Size; ++I) {
20697 APValue Char;
20698 if (!handleLValueToRValueConversion(Info, PtrExpression, CharTy, String,
20699 Char))
20700 return false;
20701
20702 if constexpr (std::is_same_v<APValue, T>) {
20703 Result.getArrayInitializedElt(I) = std::move(Char);
20704 } else {
20705 APSInt C = Char.getInt();
20706
20707 assert(C.getBitWidth() <= 8 &&
20708 "string element not representable in char");
20709
20710 Result.push_back(static_cast<char>(C.getExtValue()));
20711 }
20712
20713 if (!HandleLValueArrayAdjustment(Info, PtrExpression, String, CharTy, 1))
20714 return false;
20715 }
20716
20717 return Scope.destroy() && CheckMemoryLeaks(Info);
20718}
20719
20721 const Expr *SizeExpression,
20722 const Expr *PtrExpression, ASTContext &Ctx,
20723 EvalResult &Status) const {
20724 return EvaluateCharRangeAsStringImpl(this, Result, SizeExpression,
20725 PtrExpression, Ctx, Status);
20726}
20727
20729 const Expr *SizeExpression,
20730 const Expr *PtrExpression, ASTContext &Ctx,
20731 EvalResult &Status) const {
20732 return EvaluateCharRangeAsStringImpl(this, Result, SizeExpression,
20733 PtrExpression, Ctx, Status);
20734}
20735
20736bool Expr::tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const {
20737 Expr::EvalStatus Status;
20738 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantFold);
20739
20740 if (Info.EnableNewConstInterp)
20741 return Info.Ctx.getInterpContext().evaluateStrlen(Info, this, Result);
20742
20743 return EvaluateBuiltinStrLen(this, Result, Info);
20744}
20745
20746namespace {
20747struct IsWithinLifetimeHandler {
20748 EvalInfo &Info;
20749 static constexpr AccessKinds AccessKind = AccessKinds::AK_IsWithinLifetime;
20750 using result_type = std::optional<bool>;
20751 std::optional<bool> failed() { return std::nullopt; }
20752 template <typename T>
20753 std::optional<bool> found(T &Subobj, QualType SubobjType) {
20754 return true;
20755 }
20756};
20757
20758std::optional<bool> EvaluateBuiltinIsWithinLifetime(IntExprEvaluator &IEE,
20759 const CallExpr *E) {
20760 EvalInfo &Info = IEE.Info;
20761 // Sometimes this is called during some sorts of constant folding / early
20762 // evaluation. These are meant for non-constant expressions and are not
20763 // necessary since this consteval builtin will never be evaluated at runtime.
20764 // Just fail to evaluate when not in a constant context.
20765 if (!Info.InConstantContext)
20766 return std::nullopt;
20767 assert(E->getBuiltinCallee() == Builtin::BI__builtin_is_within_lifetime);
20768 const Expr *Arg = E->getArg(0);
20769 if (Arg->isValueDependent())
20770 return std::nullopt;
20771 LValue Val;
20772 if (!EvaluatePointer(Arg, Val, Info))
20773 return std::nullopt;
20774
20775 if (Val.allowConstexprUnknown())
20776 return true;
20777
20778 auto Error = [&](int Diag) {
20779 bool CalledFromStd = false;
20780 const auto *Callee = Info.CurrentCall->getCallee();
20781 if (Callee && Callee->isInStdNamespace()) {
20782 const IdentifierInfo *Identifier = Callee->getIdentifier();
20783 CalledFromStd = Identifier && Identifier->isStr("is_within_lifetime");
20784 }
20785 Info.CCEDiag(CalledFromStd ? Info.CurrentCall->getCallRange().getBegin()
20786 : E->getExprLoc(),
20787 diag::err_invalid_is_within_lifetime)
20788 << (CalledFromStd ? "std::is_within_lifetime"
20789 : "__builtin_is_within_lifetime")
20790 << Diag;
20791 return std::nullopt;
20792 };
20793 // C++2c [meta.const.eval]p4:
20794 // During the evaluation of an expression E as a core constant expression, a
20795 // call to this function is ill-formed unless p points to an object that is
20796 // usable in constant expressions or whose complete object's lifetime began
20797 // within E.
20798
20799 // Make sure it points to an object
20800 // nullptr does not point to an object
20801 if (Val.isNullPointer() || Val.getLValueBase().isNull())
20802 return Error(0);
20803 QualType T = Val.getLValueBase().getType();
20804 assert(!T->isFunctionType() &&
20805 "Pointers to functions should have been typed as function pointers "
20806 "which would have been rejected earlier");
20807 assert(T->isObjectType());
20808 // Hypothetical array element is not an object
20809 if (Val.getLValueDesignator().isOnePastTheEnd())
20810 return Error(1);
20811 assert(Val.getLValueDesignator().isValidSubobject() &&
20812 "Unchecked case for valid subobject");
20813 // All other ill-formed values should have failed EvaluatePointer, so the
20814 // object should be a pointer to an object that is usable in a constant
20815 // expression or whose complete lifetime began within the expression
20816 CompleteObject CO =
20817 findCompleteObject(Info, E, AccessKinds::AK_IsWithinLifetime, Val, T);
20818 // The lifetime hasn't begun yet if we are still evaluating the
20819 // initializer ([basic.life]p(1.2))
20820 if (Info.EvaluatingDeclValue && CO.Value == Info.EvaluatingDeclValue)
20821 return Error(2);
20822
20823 if (!CO)
20824 return false;
20825 IsWithinLifetimeHandler handler{Info};
20826 return findSubobject(Info, E, CO, Val.getLValueDesignator(), handler);
20827}
20828} // 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:23
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 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 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...
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)
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:833
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:774
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:926
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:825
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:891
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.
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:4507
OpaqueValueExpr * getCommonExpr() const
Get the common subexpression shared by all initializations (the source array).
Definition Expr.h:5917
Expr * getSubExpr() const
Get the initializer to use for each array element.
Definition Expr.h:5922
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:3046
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3722
QualType getElementType() const
Definition TypeBase.h:3734
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition TypeBase.h:8077
Attr - This represents one attribute.
Definition Attr.h:45
BinaryConditionalOperator - The GNU extension to the conditional operator which allows the middle ope...
Definition Expr.h:4387
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression which will be evaluated if the condition evaluates to false; ...
Definition Expr.h:4441
OpaqueValueExpr * getOpaqueValue() const
getOpaqueValue - Return the opaque value placeholder.
Definition Expr.h:4425
Expr * getCommon() const
getCommon - Return the common expression, written to the left of the condition.
Definition Expr.h:4422
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:3972
static bool isLogicalOp(Opcode Opc)
Definition Expr.h:4105
Expr * getLHS() const
Definition Expr.h:4022
static bool isRelationalOp(Opcode Opc)
Definition Expr.h:4066
static bool isComparisonOp(Opcode Opc)
Definition Expr.h:4072
static Opcode getOpForCompoundAssignment(Opcode Opc)
Definition Expr.h:4119
SourceLocation getExprLoc() const
Definition Expr.h:4013
Expr * getRHS() const
Definition Expr.h:4024
static bool isAdditiveOp(Opcode Opc)
Definition Expr.h:4058
static bool isPtrMemOp(Opcode Opc)
predicates to categorize the respective opcodes.
Definition Expr.h:4049
static bool isAssignmentOp(Opcode Opc)
Definition Expr.h:4108
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operator.
Definition Expr.h:4185
Opcode getOpcode() const
Definition Expr.h:4017
static bool isEqualityOp(Opcode Opc)
Definition Expr.h:4069
bool hasCaptures() const
True if this block (or its nested blocks) captures anything of local storage from its enclosing scope...
Definition Decl.h:4773
const BlockDecl * getBlockDecl() const
Definition Expr.h:6570
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:431
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)
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:1516
bool getValue() const
Definition ExprCXX.h:740
Represents a call to a C++ constructor.
Definition ExprCXX.h:1549
bool isElidable() const
Whether this construction is elidable.
Definition ExprCXX.h:1618
Expr * getArg(unsigned Arg)
Return the specified argument.
Definition ExprCXX.h:1692
bool requiresZeroInitialization() const
Whether this construction first requires zero-initialization before the initializer is called.
Definition ExprCXX.h:1651
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition ExprCXX.h:1612
unsigned getNumArgs() const
Return the number of arguments to the constructor call.
Definition ExprCXX.h:1689
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:2667
bool isArrayForm() const
Definition ExprCXX.h:2654
bool isGlobalDelete() const
Definition ExprCXX.h:2653
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:1790
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:2436
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:2471
Expr * getPlacementArg(unsigned I)
Definition ExprCXX.h:2505
unsigned getNumPlacementArgs() const
Definition ExprCXX.h:2496
SourceRange getSourceRange() const
Definition ExprCXX.h:2612
FunctionDecl * getOperatorNew() const
Definition ExprCXX.h:2461
Expr * getInitializer()
The initializer of this new-expression.
Definition ExprCXX.h:2535
bool getValue() const
Definition ExprCXX.h:4334
MutableArrayRef< Expr * > getInitExprs()
Definition ExprCXX.h:5183
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:1178
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:1115
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2877
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3081
SourceLocation getBeginLoc() const
Definition Expr.h:3211
const AllocSizeAttr * getCalleeAllocSizeAttr() const
Try to get the alloc_size attribute of the callee. May return null.
Definition Expr.cpp:3569
unsigned getBuiltinCallee() const
getBuiltinCallee - If this is a call to a builtin, return the builtin ID of the callee.
Definition Expr.cpp:1588
Expr * getCallee()
Definition Expr.h:3024
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition Expr.h:3068
Expr ** getArgs()
Retrieve the call arguments.
Definition Expr.h:3071
Decl * getCalleeDecl()
Definition Expr.h:3054
QualType getCallReturnType(const ASTContext &Ctx) const
getCallReturnType - Get the return type of the call expr.
Definition Expr.cpp:1599
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:1900
Expr * getLHS()
Definition Stmt.h:1983
Expr * getRHS()
Definition Stmt.h:1995
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition Expr.h:3610
path_iterator path_begin()
Definition Expr.h:3680
unsigned path_size() const
Definition Expr.h:3679
CastKind getCastKind() const
Definition Expr.h:3654
path_iterator path_end()
Definition Expr.h:3681
const CXXBaseSpecifier *const * path_const_iterator
Definition Expr.h:3677
bool path_empty() const
Definition Expr.h:3678
Expr * getSubExpr()
Definition Expr.h:3660
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operation.
Definition Expr.h:3724
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:4818
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:3275
QualType getElementType() const
Definition TypeBase.h:3285
CompoundAssignOperator - For compound assignments (e.g.
Definition Expr.h:4234
QualType getComputationLHSType() const
Definition Expr.h:4268
CompoundLiteralExpr - [C99 6.5.2.5].
Definition Expr.h:3539
bool hasStaticStorage() const
Definition Expr.h:3584
APValue & getOrCreateStaticValue(ASTContext &Ctx) const
Definition Expr.cpp:5563
bool isFileScope() const
Definition Expr.h:3571
const Expr * getInitializer() const
Definition Expr.h:3567
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition Stmt.h:1720
bool body_empty() const
Definition Stmt.h:1764
Stmt *const * const_body_iterator
Definition Stmt.h:1792
body_iterator body_end()
Definition Stmt.h:1785
body_range body()
Definition Stmt.h:1783
body_iterator body_begin()
Definition Stmt.h:1784
bool isSatisfied() const
Whether or not the concept with the given arguments was satisfied when the expression was created.
ConditionalOperator - The ?
Definition Expr.h:4325
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression representing the value of the expression if the condition eva...
Definition Expr.h:4357
Expr * getCond() const
getCond - Return the expression representing the condition for the ?
Definition Expr.h:4348
Expr * getTrueExpr() const
getTrueExpr - Return the subexpression representing the value of the expression if the condition eval...
Definition Expr.h:4352
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3760
unsigned getSizeBitWidth() const
Return the bit width of the size type.
Definition TypeBase.h:3823
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:214
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:254
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:3849
bool isZeroSize() const
Return true if the size is zero.
Definition TypeBase.h:3830
const Expr * getSizeExpr() const
Return a pointer to the size expression.
Definition TypeBase.h:3856
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3816
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition TypeBase.h:3836
APValue getAPValueResult() const
Definition Expr.cpp:409
bool hasAPValueResult() const
Definition Expr.h:1157
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operator.
Definition Expr.h:4730
Expr * getSrcExpr() const
getSrcExpr - Return the Expr to be converted.
Definition Expr.h:4743
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:1611
decl_range decls()
Definition Stmt.h:1659
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:4249
auto flat_bindings() const
Definition DeclCXX.h:4292
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:2812
Stmt * getBody()
Definition Stmt.h:2837
Expr * getCond()
Definition Stmt.h:2830
Symbolic representation of a dynamic allocation.
Definition APValue.h:65
static unsigned getMaxIndex()
Definition APValue.h:85
ChildElementIter< false > begin()
Definition Expr.h:5166
ExplicitCastExpr - An explicit cast written in the source code.
Definition Expr.h:3862
QualType getTypeAsWritten() const
getTypeAsWritten - Returns the type that this expression is casting to, as written in the source code...
Definition Expr.h:3889
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:80
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:3090
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:3963
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3085
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:3081
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:3665
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:3248
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:273
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:4410
void getEncodedElementAccess(SmallVectorImpl< uint32_t > &Elts) const
getEncodedElementAccess - Encode the elements accessed into an llvm aggregate Constant of ConstantInt...
Definition Expr.cpp:4442
const Expr * getBase() const
Definition Expr.h:6515
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:4741
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:2868
Stmt * getInit()
Definition Stmt.h:2883
VarDecl * getConditionVariable() const
Retrieve the variable declared in this "for" statement, if any.
Definition Stmt.cpp:1082
Stmt * getBody()
Definition Stmt.h:2912
Expr * getInc()
Definition Stmt.h:2911
Expr * getCond()
Definition Stmt.h:2910
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:3268
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition Decl.cpp:4194
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition Decl.cpp:4182
bool hasCXXExplicitFunctionObjectParameter() const
Definition Decl.cpp:3854
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:4318
ArrayRef< ParmVarDecl * >::const_iterator param_const_iterator
Definition Decl.h:2783
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:3415
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:3114
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:6396
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:2239
Stmt * getThen()
Definition Stmt.h:2328
Stmt * getInit()
Definition Stmt.h:2389
bool isNonNegatedConsteval() const
Definition Stmt.h:2424
Expr * getCond()
Definition Stmt.h:2316
Stmt * getElse()
Definition Stmt.h:2337
bool isConsteval() const
Definition Stmt.h:2419
VarDecl * getConditionVariable()
Retrieve the variable declared in this "if" statement, if any.
Definition Stmt.cpp:1030
const Expr * getSubExpr() const
Definition Expr.h:1743
Represents an implicitly-generated value initialization of an object of a given type.
Definition Expr.h:5991
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:5233
bool isTransparent() const
Is this a transparent initializer list (that is, an InitListExpr that is purely syntactic,...
Definition Expr.cpp:2457
bool isStringLiteralInit() const
Is this an initializer for an array of characters, initialized by a string literal or an @encode?
Definition Expr.cpp:2443
unsigned getNumInits() const
Definition Expr.h:5263
Expr * getArrayFiller()
If this initializer list initializes an array with more elements than there are initializers in the l...
Definition Expr.h:5335
const Expr * getInit(unsigned Init) const
Definition Expr.h:5287
ArrayRef< Expr * > inits()
Definition Expr.h:5283
capture_init_iterator capture_init_end()
Retrieve the iterator pointing one past the last initialization argument for this lambda expression.
Definition ExprCXX.h:2108
capture_init_iterator capture_init_begin()
Retrieve the first initialization argument for this lambda expression (which initializes the first ca...
Definition ExprCXX.h:2096
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:4922
StorageDuration getStorageDuration() const
Retrieve the storage duration for the materialized temporary.
Definition ExprCXX.h:4947
Expr * getSubExpr() const
Retrieve the temporary-generating subexpression whose value will be materialized into a glvalue.
Definition ExprCXX.h:4939
APValue * getOrCreateValue(bool MayCreate) const
Get the storage for the constant value of a materialized temporary of static storage duration.
Definition ExprCXX.h:4955
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3298
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3381
Expr * getBase() const
Definition Expr.h:3375
bool isArrow() const
Definition Expr.h:3482
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:4641
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:3328
StringLiteral * getFunctionName()
Definition Expr.h:2049
Expr * getResultExpr()
Return the result-bearing expression, or null if there is none.
Definition Expr.h:6738
ArrayRef< Expr * > semantics()
Definition Expr.h:6762
A (possibly-)qualified type.
Definition TypeBase.h:937
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8362
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:8278
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:8463
QualType getCanonicalType() const
Definition TypeBase.h:8330
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8372
void removeLocalVolatile()
Definition TypeBase.h:8394
void addVolatile()
Add the volatile type qualifier to this QualType.
Definition TypeBase.h:1164
void removeLocalConst()
Definition TypeBase.h:8386
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8351
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:8324
Represents a struct/union/class.
Definition Decl.h:4312
field_iterator field_end() const
Definition Decl.h:4518
field_range fields() const
Definition Decl.h:4515
specific_decl_iterator< FieldDecl > field_iterator
Definition Decl.h:4512
bool isAnonymousStructOrUnion() const
Whether this is an anonymous struct or union.
Definition Decl.h:4364
bool field_empty() const
Definition Decl.h:4523
field_iterator field_begin() const
Definition Decl.cpp:5202
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:583
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:4577
llvm::APSInt getShuffleMaskIdx(unsigned N) const
Definition Expr.h:4629
unsigned getNumSubExprs() const
getNumSubExprs - Return the size of the SubExprs array.
Definition Expr.h:4610
Expr * getExpr(unsigned Index)
getExpr - Return the Expr at the specified index.
Definition Expr.h:4616
unsigned getPackLength() const
Retrieve the length of the parameter pack.
Definition ExprCXX.h:4517
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:2277
bool isIntType() const
Definition Expr.h:4975
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:4546
Stmt - This represents one statement.
Definition Stmt.h:85
@ NoStmtClass
Definition Stmt.h:88
StmtClass getStmtClass() const
Definition Stmt.h:1472
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:1873
SwitchStmt - This represents a 'switch' stmt.
Definition Stmt.h:2489
Expr * getCond()
Definition Stmt.h:2552
Stmt * getBody()
Definition Stmt.h:2564
VarDecl * getConditionVariable()
Retrieve the variable declared in this "switch" statement, if any.
Definition Stmt.cpp:1148
Stmt * getInit()
Definition Stmt.h:2569
SwitchCase * getSwitchCaseList()
Definition Stmt.h:2620
TagDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:4888
bool isUnion() const
Definition Decl.h:3922
unsigned getMaxAtomicInlineWidth() const
Return the maximum width lock-free atomic operation which can be inlined given the supported features...
Definition TargetInfo.h:856
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:518
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:8260
bool getBoolValue() const
Definition ExprCXX.h:2949
const APValue & getAPValue() const
Definition ExprCXX.h:2954
bool isStoredAsBoolean() const
Definition ExprCXX.h:2945
The base class of the type hierarchy.
Definition TypeBase.h:1833
bool isVoidType() const
Definition TypeBase.h:8871
bool isBooleanType() const
Definition TypeBase.h:9001
bool isFunctionReferenceType() const
Definition TypeBase.h:8589
bool isMFloat8Type() const
Definition TypeBase.h:8896
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2225
bool isPackedVectorBoolType(const ASTContext &ctx) const
Definition Type.cpp:418
bool isLiteralType(const ASTContext &Ctx) const
Return true if this is a literal type (C++11 [basic.types]p10)
Definition Type.cpp:2993
bool isIncompleteArrayType() const
Definition TypeBase.h:8622
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2205
bool isComplexType() const
isComplexType() does not include complex integers (a GCC extension).
Definition Type.cpp:724
const ArrayType * castAsArrayTypeUnsafe() const
A variant of castAs<> for array type which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9167
bool isUnsignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is unsigned or an enumeration types whose underlying ...
Definition Type.cpp:2273
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition Type.cpp:2115
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:8618
bool isNothrowT() const
Definition Type.cpp:3170
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition Type.h:41
bool isVoidPointerType() const
Definition Type.cpp:712
bool isConstantSizeType() const
Return true if this is not a variable sized type, according to the rules of C99 6....
Definition Type.cpp:2425
bool isArrayType() const
Definition TypeBase.h:8614
bool isFunctionPointerType() const
Definition TypeBase.h:8582
bool isPointerType() const
Definition TypeBase.h:8515
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:8915
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9158
bool isReferenceType() const
Definition TypeBase.h:8539
bool isEnumeralType() const
Definition TypeBase.h:8646
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:1909
bool isVariableArrayType() const
Definition TypeBase.h:8626
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition Type.cpp:2607
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:752
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:8989
bool isExtVectorBoolType() const
Definition TypeBase.h:8662
bool isMemberDataPointerType() const
Definition TypeBase.h:8607
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition TypeBase.h:8840
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2782
RecordDecl * castAsRecordDecl() const
Definition Type.h:48
bool isAnyComplexType() const
Definition TypeBase.h:8650
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:8927
bool isMemberPointerType() const
Definition TypeBase.h:8596
bool isAtomicType() const
Definition TypeBase.h:8697
bool isComplexIntegerType() const
Definition Type.cpp:730
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9144
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:2435
bool isFunctionType() const
Definition TypeBase.h:8511
bool isVectorType() const
Definition TypeBase.h:8654
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2320
bool isFloatingType() const
Definition Type.cpp:2304
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:2253
const T * castAsCanonical() const
Return this type's canonical type cast to the specified type.
Definition TypeBase.h:2928
bool isAnyPointerType() const
Definition TypeBase.h:8523
TypeClass getTypeClass() const
Definition TypeBase.h:2385
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9091
bool isNullPtrType() const
Definition TypeBase.h:8908
bool isRecordType() const
Definition TypeBase.h:8642
bool isUnionType() const
Definition Type.cpp:718
bool isSizelessVectorType() const
Returns true for all scalable vector types.
Definition Type.cpp:2569
bool hasPointerRepresentation() const
Whether this type is represented natively as a pointer.
Definition TypeBase.h:9035
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:5501
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:2398
bool hasICEInitializer(const ASTContext &Context) const
Determine whether the initializer of this variable is an integer constant expression.
Definition Decl.cpp:2636
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:2575
CharUnits getFlexibleArrayInitChars(const ASTContext &Ctx) const
If hasFlexibleArrayInit is true, compute the number of additional bytes necessary to store those elem...
Definition Decl.cpp:2877
bool hasConstantInitialization() const
Determine whether this variable has constant initialization.
Definition Decl.cpp:2648
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
Definition Decl.cpp:2366
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:2486
EvaluatedStmt * ensureEvaluatedStmt() const
Convert the initializer for this declaration to the elaborated EvaluatedStmt form,...
Definition Decl.cpp:2557
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:2628
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:2375
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:2528
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:3980
Represents a GCC generic vector type.
Definition TypeBase.h:4175
unsigned getNumElements() const
Definition TypeBase.h:4190
QualType getElementType() const
Definition TypeBase.h:4189
WhileStmt - This represents a 'while' stmt.
Definition Stmt.h:2677
Expr * getCond()
Definition Stmt.h:2729
VarDecl * getConditionVariable()
Retrieve the variable declared in this "while" statement, if any.
Definition Stmt.cpp:1209
Stmt * getBody()
Definition Stmt.h:2741
bool evaluateCharRange(State &Parent, const Expr *SizeExpr, const Expr *PtrExpr, APValue &Result)
Definition Context.cpp:227
bool evaluateString(State &Parent, const Expr *E, std::string &Result)
Evaluate.
Definition Context.cpp:243
bool evaluateStrlen(State &Parent, const Expr *E, uint64_t &Result)
Evalute.
Definition Context.cpp:289
void isPotentialConstantExprUnevaluated(State &Parent, const Expr *E, const FunctionDecl *FD)
Definition Context.cpp:60
bool isPotentialConstantExpr(State &Parent, const FunctionDecl *FD)
Checks if a function is a potential constant expression.
Definition Context.cpp:40
bool evaluateAsRValue(State &Parent, const Expr *E, APValue &Result)
Evaluates a toplevel expression as an rvalue.
Definition Context.cpp:73
bool evaluate(State &Parent, const Expr *E, APValue &Result, ConstantExprKind Kind)
Like evaluateAsRvalue(), but does no implicit lvalue-to-rvalue conversion.
Definition Context.cpp:103
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:79
#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:1235
llvm::FixedPointSemantics FixedPointSemantics
Definition Interp.h:42
bool This(InterpState &S, CodePtr OpPC)
Definition Interp.h:2799
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:3518
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:204
@ 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:42
@ CSK_ArrayToPointer
Definition State.h:46
@ CSK_Derived
Definition State.h:44
@ CSK_Base
Definition State.h:43
@ CSK_Real
Definition State.h:48
@ CSK_ArrayIndex
Definition State.h:47
@ CSK_Imag
Definition State.h:49
@ CSK_VectorElement
Definition State.h:50
@ CSK_Field
Definition State.h:45
@ 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:26
@ AK_TypeId
Definition State.h:34
@ AK_Construct
Definition State.h:35
@ AK_Increment
Definition State.h:30
@ AK_DynamicCast
Definition State.h:33
@ AK_Read
Definition State.h:27
@ AK_Assign
Definition State.h:29
@ AK_IsWithinLifetime
Definition State.h:37
@ AK_MemberCall
Definition State.h:32
@ AK_ReadObjectRepresentation
Definition State.h:28
@ AK_Dereference
Definition State.h:38
@ AK_Destroy
Definition State.h:36
@ AK_Decrement
Definition State.h:31
const FunctionProtoType * T
@ Type
The name was classified as a type.
Definition Sema.h:562
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:53
@ ConstantFold
Fold the expression to a constant.
Definition State.h:67
@ ConstantExpressionUnevaluated
Evaluate as a constant expression.
Definition State.h:63
@ ConstantExpression
Evaluate as a constant expression.
Definition State.h:56
@ IgnoreSideEffects
Evaluate in any way we know how.
Definition State.h:71
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:830
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5864
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
Diagnostic wrappers for TextAPI types for error reporting.
Definition Dominators.h:30
hash_code hash_value(const clang::tooling::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 trunc(__x)
Definition tgmath.h:1216
#define scalbn(__x, __y)
Definition tgmath.h:1165