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
3832namespace {
3833/// A handle to a complete object (an object that is not a subobject of
3834/// another object).
3835struct CompleteObject {
3836 /// The identity of the object.
3837 APValue::LValueBase Base;
3838 /// The value of the complete object.
3839 APValue *Value;
3840 /// The type of the complete object.
3841 QualType Type;
3842
3843 CompleteObject() : Value(nullptr) {}
3844 CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
3845 : Base(Base), Value(Value), Type(Type) {}
3846
3847 bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const {
3848 // If this isn't a "real" access (eg, if it's just accessing the type
3849 // info), allow it. We assume the type doesn't change dynamically for
3850 // subobjects of constexpr objects (even though we'd hit UB here if it
3851 // did). FIXME: Is this right?
3852 if (!isAnyAccess(AK))
3853 return true;
3854
3855 // In C++14 onwards, it is permitted to read a mutable member whose
3856 // lifetime began within the evaluation.
3857 // FIXME: Should we also allow this in C++11?
3858 if (!Info.getLangOpts().CPlusPlus14 &&
3859 AK != AccessKinds::AK_IsWithinLifetime)
3860 return false;
3861 return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);
3862 }
3863
3864 explicit operator bool() const { return !Type.isNull(); }
3865};
3866} // end anonymous namespace
3867
3868static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
3869 bool IsMutable = false) {
3870 // C++ [basic.type.qualifier]p1:
3871 // - A const object is an object of type const T or a non-mutable subobject
3872 // of a const object.
3873 if (ObjType.isConstQualified() && !IsMutable)
3874 SubobjType.addConst();
3875 // - A volatile object is an object of type const T or a subobject of a
3876 // volatile object.
3877 if (ObjType.isVolatileQualified())
3878 SubobjType.addVolatile();
3879 return SubobjType;
3880}
3881
3882/// Find the designated sub-object of an rvalue.
3883template <typename SubobjectHandler>
3884static typename SubobjectHandler::result_type
3885findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
3886 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
3887 if (Sub.Invalid)
3888 // A diagnostic will have already been produced.
3889 return handler.failed();
3890 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
3891 if (Info.getLangOpts().CPlusPlus11)
3892 Info.FFDiag(E, Sub.isOnePastTheEnd()
3893 ? diag::note_constexpr_access_past_end
3894 : diag::note_constexpr_access_unsized_array)
3895 << handler.AccessKind;
3896 else
3897 Info.FFDiag(E);
3898 return handler.failed();
3899 }
3900
3901 APValue *O = Obj.Value;
3902 QualType ObjType = Obj.Type;
3903 const FieldDecl *LastField = nullptr;
3904 const FieldDecl *VolatileField = nullptr;
3905
3906 // Walk the designator's path to find the subobject.
3907 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
3908 // Reading an indeterminate value is undefined, but assigning over one is OK.
3909 if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) ||
3910 (O->isIndeterminate() &&
3911 !isValidIndeterminateAccess(handler.AccessKind))) {
3912 // Object has ended lifetime.
3913 // If I is non-zero, some subobject (member or array element) of a
3914 // complete object has ended its lifetime, so this is valid for
3915 // IsWithinLifetime, resulting in false.
3916 if (I != 0 && handler.AccessKind == AK_IsWithinLifetime)
3917 return false;
3918 if (!Info.checkingPotentialConstantExpression())
3919 Info.FFDiag(E, diag::note_constexpr_access_uninit)
3920 << handler.AccessKind << O->isIndeterminate()
3921 << E->getSourceRange();
3922 return handler.failed();
3923 }
3924
3925 // C++ [class.ctor]p5, C++ [class.dtor]p5:
3926 // const and volatile semantics are not applied on an object under
3927 // {con,de}struction.
3928 if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
3929 ObjType->isRecordType() &&
3930 Info.isEvaluatingCtorDtor(
3931 Obj.Base, ArrayRef(Sub.Entries.begin(), Sub.Entries.begin() + I)) !=
3932 ConstructionPhase::None) {
3933 ObjType = Info.Ctx.getCanonicalType(ObjType);
3934 ObjType.removeLocalConst();
3935 ObjType.removeLocalVolatile();
3936 }
3937
3938 // If this is our last pass, check that the final object type is OK.
3939 if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
3940 // Accesses to volatile objects are prohibited.
3941 if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
3942 if (Info.getLangOpts().CPlusPlus) {
3943 int DiagKind;
3944 SourceLocation Loc;
3945 const NamedDecl *Decl = nullptr;
3946 if (VolatileField) {
3947 DiagKind = 2;
3948 Loc = VolatileField->getLocation();
3949 Decl = VolatileField;
3950 } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3951 DiagKind = 1;
3952 Loc = VD->getLocation();
3953 Decl = VD;
3954 } else {
3955 DiagKind = 0;
3956 if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3957 Loc = E->getExprLoc();
3958 }
3959 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3960 << handler.AccessKind << DiagKind << Decl;
3961 Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3962 } else {
3963 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3964 }
3965 return handler.failed();
3966 }
3967
3968 // If we are reading an object of class type, there may still be more
3969 // things we need to check: if there are any mutable subobjects, we
3970 // cannot perform this read. (This only happens when performing a trivial
3971 // copy or assignment.)
3972 if (ObjType->isRecordType() &&
3973 !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
3974 diagnoseMutableFields(Info, E, handler.AccessKind, ObjType))
3975 return handler.failed();
3976 }
3977
3978 if (I == N) {
3979 if (!handler.found(*O, ObjType))
3980 return false;
3981
3982 // If we modified a bit-field, truncate it to the right width.
3983 if (isModification(handler.AccessKind) &&
3984 LastField && LastField->isBitField() &&
3985 !truncateBitfieldValue(Info, E, *O, LastField))
3986 return false;
3987
3988 return true;
3989 }
3990
3991 LastField = nullptr;
3992 if (ObjType->isArrayType()) {
3993 // Next subobject is an array element.
3994 const ArrayType *AT = Info.Ctx.getAsArrayType(ObjType);
3996 "vla in literal type?");
3997 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3998 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT);
3999 CAT && CAT->getSize().ule(Index)) {
4000 // Note, it should not be possible to form a pointer with a valid
4001 // designator which points more than one past the end of the array.
4002 if (Info.getLangOpts().CPlusPlus11)
4003 Info.FFDiag(E, diag::note_constexpr_access_past_end)
4004 << handler.AccessKind;
4005 else
4006 Info.FFDiag(E);
4007 return handler.failed();
4008 }
4009
4010 ObjType = AT->getElementType();
4011
4012 if (O->getArrayInitializedElts() > Index)
4013 O = &O->getArrayInitializedElt(Index);
4014 else if (!isRead(handler.AccessKind)) {
4015 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT);
4016 CAT && !CheckArraySize(Info, CAT, E->getExprLoc()))
4017 return handler.failed();
4018
4019 expandArray(*O, Index);
4020 O = &O->getArrayInitializedElt(Index);
4021 } else
4022 O = &O->getArrayFiller();
4023 } else if (ObjType->isAnyComplexType()) {
4024 // Next subobject is a complex number.
4025 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
4026 if (Index > 1) {
4027 if (Info.getLangOpts().CPlusPlus11)
4028 Info.FFDiag(E, diag::note_constexpr_access_past_end)
4029 << handler.AccessKind;
4030 else
4031 Info.FFDiag(E);
4032 return handler.failed();
4033 }
4034
4035 ObjType = getSubobjectType(
4036 ObjType, ObjType->castAs<ComplexType>()->getElementType());
4037
4038 assert(I == N - 1 && "extracting subobject of scalar?");
4039 if (O->isComplexInt()) {
4040 return handler.found(Index ? O->getComplexIntImag()
4041 : O->getComplexIntReal(), ObjType);
4042 } else {
4043 assert(O->isComplexFloat());
4044 return handler.found(Index ? O->getComplexFloatImag()
4045 : O->getComplexFloatReal(), ObjType);
4046 }
4047 } else if (const auto *VT = ObjType->getAs<VectorType>()) {
4048 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
4049 unsigned NumElements = VT->getNumElements();
4050 if (Index == NumElements) {
4051 if (Info.getLangOpts().CPlusPlus11)
4052 Info.FFDiag(E, diag::note_constexpr_access_past_end)
4053 << handler.AccessKind;
4054 else
4055 Info.FFDiag(E);
4056 return handler.failed();
4057 }
4058
4059 if (Index > NumElements) {
4060 Info.CCEDiag(E, diag::note_constexpr_array_index)
4061 << Index << /*array*/ 0 << NumElements;
4062 return handler.failed();
4063 }
4064
4065 ObjType = VT->getElementType();
4066 assert(I == N - 1 && "extracting subobject of scalar?");
4067 return handler.found(O->getVectorElt(Index), ObjType);
4068 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
4069 if (Field->isMutable() &&
4070 !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) {
4071 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
4072 << handler.AccessKind << Field;
4073 Info.Note(Field->getLocation(), diag::note_declared_at);
4074 return handler.failed();
4075 }
4076
4077 // Next subobject is a class, struct or union field.
4078 RecordDecl *RD = ObjType->castAsCanonical<RecordType>()->getDecl();
4079 if (RD->isUnion()) {
4080 const FieldDecl *UnionField = O->getUnionField();
4081 if (!UnionField ||
4082 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
4083 if (I == N - 1 && handler.AccessKind == AK_Construct) {
4084 // Placement new onto an inactive union member makes it active.
4085 O->setUnion(Field, APValue());
4086 } else {
4087 // Pointer to/into inactive union member: Not within lifetime
4088 if (handler.AccessKind == AK_IsWithinLifetime)
4089 return false;
4090 // FIXME: If O->getUnionValue() is absent, report that there's no
4091 // active union member rather than reporting the prior active union
4092 // member. We'll need to fix nullptr_t to not use APValue() as its
4093 // representation first.
4094 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
4095 << handler.AccessKind << Field << !UnionField << UnionField;
4096 return handler.failed();
4097 }
4098 }
4099 O = &O->getUnionValue();
4100 } else
4101 O = &O->getStructField(Field->getFieldIndex());
4102
4103 ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
4104 LastField = Field;
4105 if (Field->getType().isVolatileQualified())
4106 VolatileField = Field;
4107 } else {
4108 // Next subobject is a base class.
4109 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
4110 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
4111 O = &O->getStructBase(getBaseIndex(Derived, Base));
4112
4113 ObjType = getSubobjectType(ObjType, Info.Ctx.getCanonicalTagType(Base));
4114 }
4115 }
4116}
4117
4118namespace {
4119struct ExtractSubobjectHandler {
4120 EvalInfo &Info;
4121 const Expr *E;
4122 APValue &Result;
4123 const AccessKinds AccessKind;
4124
4125 typedef bool result_type;
4126 bool failed() { return false; }
4127 bool found(APValue &Subobj, QualType SubobjType) {
4128 Result = Subobj;
4129 if (AccessKind == AK_ReadObjectRepresentation)
4130 return true;
4131 return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
4132 }
4133 bool found(APSInt &Value, QualType SubobjType) {
4134 Result = APValue(Value);
4135 return true;
4136 }
4137 bool found(APFloat &Value, QualType SubobjType) {
4138 Result = APValue(Value);
4139 return true;
4140 }
4141};
4142} // end anonymous namespace
4143
4144/// Extract the designated sub-object of an rvalue.
4145static bool extractSubobject(EvalInfo &Info, const Expr *E,
4146 const CompleteObject &Obj,
4147 const SubobjectDesignator &Sub, APValue &Result,
4148 AccessKinds AK = AK_Read) {
4149 assert(AK == AK_Read || AK == AK_ReadObjectRepresentation);
4150 ExtractSubobjectHandler Handler = {Info, E, Result, AK};
4151 return findSubobject(Info, E, Obj, Sub, Handler);
4152}
4153
4154namespace {
4155struct ModifySubobjectHandler {
4156 EvalInfo &Info;
4157 APValue &NewVal;
4158 const Expr *E;
4159
4160 typedef bool result_type;
4161 static const AccessKinds AccessKind = AK_Assign;
4162
4163 bool checkConst(QualType QT) {
4164 // Assigning to a const object has undefined behavior.
4165 if (QT.isConstQualified()) {
4166 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4167 return false;
4168 }
4169 return true;
4170 }
4171
4172 bool failed() { return false; }
4173 bool found(APValue &Subobj, QualType SubobjType) {
4174 if (!checkConst(SubobjType))
4175 return false;
4176 // We've been given ownership of NewVal, so just swap it in.
4177 Subobj.swap(NewVal);
4178 return true;
4179 }
4180 bool found(APSInt &Value, QualType SubobjType) {
4181 if (!checkConst(SubobjType))
4182 return false;
4183 if (!NewVal.isInt()) {
4184 // Maybe trying to write a cast pointer value into a complex?
4185 Info.FFDiag(E);
4186 return false;
4187 }
4188 Value = NewVal.getInt();
4189 return true;
4190 }
4191 bool found(APFloat &Value, QualType SubobjType) {
4192 if (!checkConst(SubobjType))
4193 return false;
4194 Value = NewVal.getFloat();
4195 return true;
4196 }
4197};
4198} // end anonymous namespace
4199
4200const AccessKinds ModifySubobjectHandler::AccessKind;
4201
4202/// Update the designated sub-object of an rvalue to the given value.
4203static bool modifySubobject(EvalInfo &Info, const Expr *E,
4204 const CompleteObject &Obj,
4205 const SubobjectDesignator &Sub,
4206 APValue &NewVal) {
4207 ModifySubobjectHandler Handler = { Info, NewVal, E };
4208 return findSubobject(Info, E, Obj, Sub, Handler);
4209}
4210
4211/// Find the position where two subobject designators diverge, or equivalently
4212/// the length of the common initial subsequence.
4213static unsigned FindDesignatorMismatch(QualType ObjType,
4214 const SubobjectDesignator &A,
4215 const SubobjectDesignator &B,
4216 bool &WasArrayIndex) {
4217 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
4218 for (/**/; I != N; ++I) {
4219 if (!ObjType.isNull() &&
4220 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
4221 // Next subobject is an array element.
4222 if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
4223 WasArrayIndex = true;
4224 return I;
4225 }
4226 if (ObjType->isAnyComplexType())
4227 ObjType = ObjType->castAs<ComplexType>()->getElementType();
4228 else
4229 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
4230 } else {
4231 if (A.Entries[I].getAsBaseOrMember() !=
4232 B.Entries[I].getAsBaseOrMember()) {
4233 WasArrayIndex = false;
4234 return I;
4235 }
4236 if (const FieldDecl *FD = getAsField(A.Entries[I]))
4237 // Next subobject is a field.
4238 ObjType = FD->getType();
4239 else
4240 // Next subobject is a base class.
4241 ObjType = QualType();
4242 }
4243 }
4244 WasArrayIndex = false;
4245 return I;
4246}
4247
4248/// Determine whether the given subobject designators refer to elements of the
4249/// same array object.
4251 const SubobjectDesignator &A,
4252 const SubobjectDesignator &B) {
4253 if (A.Entries.size() != B.Entries.size())
4254 return false;
4255
4256 bool IsArray = A.MostDerivedIsArrayElement;
4257 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
4258 // A is a subobject of the array element.
4259 return false;
4260
4261 // If A (and B) designates an array element, the last entry will be the array
4262 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
4263 // of length 1' case, and the entire path must match.
4264 bool WasArrayIndex;
4265 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
4266 return CommonLength >= A.Entries.size() - IsArray;
4267}
4268
4269/// Find the complete object to which an LValue refers.
4270static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
4271 AccessKinds AK, const LValue &LVal,
4272 QualType LValType) {
4273 if (LVal.InvalidBase) {
4274 Info.FFDiag(E);
4275 return CompleteObject();
4276 }
4277
4278 if (!LVal.Base) {
4280 Info.FFDiag(E, diag::note_constexpr_dereferencing_null);
4281 else
4282 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
4283 return CompleteObject();
4284 }
4285
4286 CallStackFrame *Frame = nullptr;
4287 unsigned Depth = 0;
4288 if (LVal.getLValueCallIndex()) {
4289 std::tie(Frame, Depth) =
4290 Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
4291 if (!Frame) {
4292 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
4293 << AK << LVal.Base.is<const ValueDecl*>();
4294 NoteLValueLocation(Info, LVal.Base);
4295 return CompleteObject();
4296 }
4297 }
4298
4299 bool IsAccess = isAnyAccess(AK);
4300
4301 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
4302 // is not a constant expression (even if the object is non-volatile). We also
4303 // apply this rule to C++98, in order to conform to the expected 'volatile'
4304 // semantics.
4305 if (isFormalAccess(AK) && LValType.isVolatileQualified()) {
4306 if (Info.getLangOpts().CPlusPlus)
4307 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
4308 << AK << LValType;
4309 else
4310 Info.FFDiag(E);
4311 return CompleteObject();
4312 }
4313
4314 // Compute value storage location and type of base object.
4315 APValue *BaseVal = nullptr;
4316 QualType BaseType = getType(LVal.Base);
4317
4318 if (Info.getLangOpts().CPlusPlus14 && LVal.Base == Info.EvaluatingDecl &&
4319 lifetimeStartedInEvaluation(Info, LVal.Base)) {
4320 // This is the object whose initializer we're evaluating, so its lifetime
4321 // started in the current evaluation.
4322 BaseVal = Info.EvaluatingDeclValue;
4323 } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) {
4324 // Allow reading from a GUID declaration.
4325 if (auto *GD = dyn_cast<MSGuidDecl>(D)) {
4326 if (isModification(AK)) {
4327 // All the remaining cases do not permit modification of the object.
4328 Info.FFDiag(E, diag::note_constexpr_modify_global);
4329 return CompleteObject();
4330 }
4331 APValue &V = GD->getAsAPValue();
4332 if (V.isAbsent()) {
4333 Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
4334 << GD->getType();
4335 return CompleteObject();
4336 }
4337 return CompleteObject(LVal.Base, &V, GD->getType());
4338 }
4339
4340 // Allow reading the APValue from an UnnamedGlobalConstantDecl.
4341 if (auto *GCD = dyn_cast<UnnamedGlobalConstantDecl>(D)) {
4342 if (isModification(AK)) {
4343 Info.FFDiag(E, diag::note_constexpr_modify_global);
4344 return CompleteObject();
4345 }
4346 return CompleteObject(LVal.Base, const_cast<APValue *>(&GCD->getValue()),
4347 GCD->getType());
4348 }
4349
4350 // Allow reading from template parameter objects.
4351 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) {
4352 if (isModification(AK)) {
4353 Info.FFDiag(E, diag::note_constexpr_modify_global);
4354 return CompleteObject();
4355 }
4356 return CompleteObject(LVal.Base, const_cast<APValue *>(&TPO->getValue()),
4357 TPO->getType());
4358 }
4359
4360 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
4361 // In C++11, constexpr, non-volatile variables initialized with constant
4362 // expressions are constant expressions too. Inside constexpr functions,
4363 // parameters are constant expressions even if they're non-const.
4364 // In C++1y, objects local to a constant expression (those with a Frame) are
4365 // both readable and writable inside constant expressions.
4366 // In C, such things can also be folded, although they are not ICEs.
4367 const VarDecl *VD = dyn_cast<VarDecl>(D);
4368 if (VD) {
4369 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
4370 VD = VDef;
4371 }
4372 if (!VD || VD->isInvalidDecl()) {
4373 Info.FFDiag(E);
4374 return CompleteObject();
4375 }
4376
4377 bool IsConstant = BaseType.isConstant(Info.Ctx);
4378 bool ConstexprVar = false;
4379 if (const auto *VD = dyn_cast_if_present<VarDecl>(
4380 Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()))
4381 ConstexprVar = VD->isConstexpr();
4382
4383 // Unless we're looking at a local variable or argument in a constexpr call,
4384 // the variable we're reading must be const (unless we are binding to a
4385 // reference).
4386 if (AK != clang::AK_Dereference && !Frame) {
4387 if (IsAccess && isa<ParmVarDecl>(VD)) {
4388 // Access of a parameter that's not associated with a frame isn't going
4389 // to work out, but we can leave it to evaluateVarDeclInit to provide a
4390 // suitable diagnostic.
4391 } else if (Info.getLangOpts().CPlusPlus14 &&
4392 lifetimeStartedInEvaluation(Info, LVal.Base)) {
4393 // OK, we can read and modify an object if we're in the process of
4394 // evaluating its initializer, because its lifetime began in this
4395 // evaluation.
4396 } else if (isModification(AK)) {
4397 // All the remaining cases do not permit modification of the object.
4398 Info.FFDiag(E, diag::note_constexpr_modify_global);
4399 return CompleteObject();
4400 } else if (VD->isConstexpr()) {
4401 // OK, we can read this variable.
4402 } else if (Info.getLangOpts().C23 && ConstexprVar) {
4403 Info.FFDiag(E);
4404 return CompleteObject();
4405 } else if (BaseType->isIntegralOrEnumerationType()) {
4406 if (!IsConstant) {
4407 if (!IsAccess)
4408 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4409 if (Info.getLangOpts().CPlusPlus) {
4410 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
4411 Info.Note(VD->getLocation(), diag::note_declared_at);
4412 } else {
4413 Info.FFDiag(E);
4414 }
4415 return CompleteObject();
4416 }
4417 } else if (!IsAccess) {
4418 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4419 } else if ((IsConstant || BaseType->isReferenceType()) &&
4420 Info.checkingPotentialConstantExpression() &&
4421 BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) {
4422 // This variable might end up being constexpr. Don't diagnose it yet.
4423 } else if (IsConstant) {
4424 // Keep evaluating to see what we can do. In particular, we support
4425 // folding of const floating-point types, in order to make static const
4426 // data members of such types (supported as an extension) more useful.
4427 if (Info.getLangOpts().CPlusPlus) {
4428 Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11
4429 ? diag::note_constexpr_ltor_non_constexpr
4430 : diag::note_constexpr_ltor_non_integral, 1)
4431 << VD << BaseType;
4432 Info.Note(VD->getLocation(), diag::note_declared_at);
4433 } else {
4434 Info.CCEDiag(E);
4435 }
4436 } else {
4437 // Never allow reading a non-const value.
4438 if (Info.getLangOpts().CPlusPlus) {
4439 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
4440 ? diag::note_constexpr_ltor_non_constexpr
4441 : diag::note_constexpr_ltor_non_integral, 1)
4442 << VD << BaseType;
4443 Info.Note(VD->getLocation(), diag::note_declared_at);
4444 } else {
4445 Info.FFDiag(E);
4446 }
4447 return CompleteObject();
4448 }
4449 }
4450
4451 // When binding to a reference, the variable does not need to be constexpr
4452 // or have constant initalization.
4453 if (AK != clang::AK_Dereference &&
4454 !evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(),
4455 BaseVal))
4456 return CompleteObject();
4457 // If evaluateVarDeclInit sees a constexpr-unknown variable, it returns
4458 // a null BaseVal. Any constexpr-unknown variable seen here is an error:
4459 // we can't access a constexpr-unknown object.
4460 if (AK != clang::AK_Dereference && !BaseVal) {
4461 if (!Info.checkingPotentialConstantExpression()) {
4462 Info.FFDiag(E, diag::note_constexpr_access_unknown_variable, 1)
4463 << AK << VD;
4464 Info.Note(VD->getLocation(), diag::note_declared_at);
4465 }
4466 return CompleteObject();
4467 }
4468 } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) {
4469 std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
4470 if (!Alloc) {
4471 Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK;
4472 return CompleteObject();
4473 }
4474 return CompleteObject(LVal.Base, &(*Alloc)->Value,
4475 LVal.Base.getDynamicAllocType());
4476 }
4477 // When binding to a reference, the variable does not need to be
4478 // within its lifetime.
4479 else if (AK != clang::AK_Dereference) {
4480 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4481
4482 if (!Frame) {
4483 if (const MaterializeTemporaryExpr *MTE =
4484 dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
4485 assert(MTE->getStorageDuration() == SD_Static &&
4486 "should have a frame for a non-global materialized temporary");
4487
4488 // C++20 [expr.const]p4: [DR2126]
4489 // An object or reference is usable in constant expressions if it is
4490 // - a temporary object of non-volatile const-qualified literal type
4491 // whose lifetime is extended to that of a variable that is usable
4492 // in constant expressions
4493 //
4494 // C++20 [expr.const]p5:
4495 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
4496 // - a non-volatile glvalue that refers to an object that is usable
4497 // in constant expressions, or
4498 // - a non-volatile glvalue of literal type that refers to a
4499 // non-volatile object whose lifetime began within the evaluation
4500 // of E;
4501 //
4502 // C++11 misses the 'began within the evaluation of e' check and
4503 // instead allows all temporaries, including things like:
4504 // int &&r = 1;
4505 // int x = ++r;
4506 // constexpr int k = r;
4507 // Therefore we use the C++14-onwards rules in C++11 too.
4508 //
4509 // Note that temporaries whose lifetimes began while evaluating a
4510 // variable's constructor are not usable while evaluating the
4511 // corresponding destructor, not even if they're of const-qualified
4512 // types.
4513 if (!MTE->isUsableInConstantExpressions(Info.Ctx) &&
4514 !lifetimeStartedInEvaluation(Info, LVal.Base)) {
4515 if (!IsAccess)
4516 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4517 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
4518 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
4519 return CompleteObject();
4520 }
4521
4522 BaseVal = MTE->getOrCreateValue(false);
4523 assert(BaseVal && "got reference to unevaluated temporary");
4524 } else if (const CompoundLiteralExpr *CLE =
4525 dyn_cast_or_null<CompoundLiteralExpr>(Base)) {
4526 // According to GCC info page:
4527 //
4528 // 6.28 Compound Literals
4529 //
4530 // As an optimization, G++ sometimes gives array compound literals
4531 // longer lifetimes: when the array either appears outside a function or
4532 // has a const-qualified type. If foo and its initializer had elements
4533 // of type char *const rather than char *, or if foo were a global
4534 // variable, the array would have static storage duration. But it is
4535 // probably safest just to avoid the use of array compound literals in
4536 // C++ code.
4537 //
4538 // Obey that rule by checking constness for converted array types.
4539 if (QualType CLETy = CLE->getType(); CLETy->isArrayType() &&
4540 !LValType->isArrayType() &&
4541 !CLETy.isConstant(Info.Ctx)) {
4542 Info.FFDiag(E);
4543 Info.Note(CLE->getExprLoc(), diag::note_declared_at);
4544 return CompleteObject();
4545 }
4546
4547 BaseVal = &CLE->getStaticValue();
4548 } else {
4549 if (!IsAccess)
4550 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4551 APValue Val;
4552 LVal.moveInto(Val);
4553 Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
4554 << AK
4555 << Val.getAsString(Info.Ctx,
4556 Info.Ctx.getLValueReferenceType(LValType));
4557 NoteLValueLocation(Info, LVal.Base);
4558 return CompleteObject();
4559 }
4560 } else if (AK != clang::AK_Dereference) {
4561 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
4562 assert(BaseVal && "missing value for temporary");
4563 }
4564 }
4565
4566 // In C++14, we can't safely access any mutable state when we might be
4567 // evaluating after an unmodeled side effect. Parameters are modeled as state
4568 // in the caller, but aren't visible once the call returns, so they can be
4569 // modified in a speculatively-evaluated call.
4570 //
4571 // FIXME: Not all local state is mutable. Allow local constant subobjects
4572 // to be read here (but take care with 'mutable' fields).
4573 unsigned VisibleDepth = Depth;
4574 if (llvm::isa_and_nonnull<ParmVarDecl>(
4575 LVal.Base.dyn_cast<const ValueDecl *>()))
4576 ++VisibleDepth;
4577 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
4578 Info.EvalStatus.HasSideEffects) ||
4579 (isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth))
4580 return CompleteObject();
4581
4582 return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
4583}
4584
4585/// Perform an lvalue-to-rvalue conversion on the given glvalue. This
4586/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
4587/// glvalue referred to by an entity of reference type.
4588///
4589/// \param Info - Information about the ongoing evaluation.
4590/// \param Conv - The expression for which we are performing the conversion.
4591/// Used for diagnostics.
4592/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
4593/// case of a non-class type).
4594/// \param LVal - The glvalue on which we are attempting to perform this action.
4595/// \param RVal - The produced value will be placed here.
4596/// \param WantObjectRepresentation - If true, we're looking for the object
4597/// representation rather than the value, and in particular,
4598/// there is no requirement that the result be fully initialized.
4599static bool
4601 const LValue &LVal, APValue &RVal,
4602 bool WantObjectRepresentation = false) {
4603 if (LVal.Designator.Invalid)
4604 return false;
4605
4606 // Check for special cases where there is no existing APValue to look at.
4607 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4608
4609 AccessKinds AK =
4610 WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;
4611
4612 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
4614 // Special-case character extraction so we don't have to construct an
4615 // APValue for the whole string.
4616 assert(LVal.Designator.Entries.size() <= 1 &&
4617 "Can only read characters from string literals");
4618 if (LVal.Designator.Entries.empty()) {
4619 // Fail for now for LValue to RValue conversion of an array.
4620 // (This shouldn't show up in C/C++, but it could be triggered by a
4621 // weird EvaluateAsRValue call from a tool.)
4622 Info.FFDiag(Conv);
4623 return false;
4624 }
4625 if (LVal.Designator.isOnePastTheEnd()) {
4626 if (Info.getLangOpts().CPlusPlus11)
4627 Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
4628 else
4629 Info.FFDiag(Conv);
4630 return false;
4631 }
4632 uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
4633 RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
4634 return true;
4635 }
4636 }
4637
4638 CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
4639 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
4640}
4641
4642/// Perform an assignment of Val to LVal. Takes ownership of Val.
4643static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
4644 QualType LValType, APValue &Val) {
4645 if (LVal.Designator.Invalid)
4646 return false;
4647
4648 if (!Info.getLangOpts().CPlusPlus14) {
4649 Info.FFDiag(E);
4650 return false;
4651 }
4652
4653 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4654 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
4655}
4656
4657namespace {
4658struct CompoundAssignSubobjectHandler {
4659 EvalInfo &Info;
4660 const CompoundAssignOperator *E;
4661 QualType PromotedLHSType;
4663 const APValue &RHS;
4664
4665 static const AccessKinds AccessKind = AK_Assign;
4666
4667 typedef bool result_type;
4668
4669 bool checkConst(QualType QT) {
4670 // Assigning to a const object has undefined behavior.
4671 if (QT.isConstQualified()) {
4672 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4673 return false;
4674 }
4675 return true;
4676 }
4677
4678 bool failed() { return false; }
4679 bool found(APValue &Subobj, QualType SubobjType) {
4680 switch (Subobj.getKind()) {
4681 case APValue::Int:
4682 return found(Subobj.getInt(), SubobjType);
4683 case APValue::Float:
4684 return found(Subobj.getFloat(), SubobjType);
4687 // FIXME: Implement complex compound assignment.
4688 Info.FFDiag(E);
4689 return false;
4690 case APValue::LValue:
4691 return foundPointer(Subobj, SubobjType);
4692 case APValue::Vector:
4693 return foundVector(Subobj, SubobjType);
4695 Info.FFDiag(E, diag::note_constexpr_access_uninit)
4696 << /*read of=*/0 << /*uninitialized object=*/1
4697 << E->getLHS()->getSourceRange();
4698 return false;
4699 default:
4700 // FIXME: can this happen?
4701 Info.FFDiag(E);
4702 return false;
4703 }
4704 }
4705
4706 bool foundVector(APValue &Value, QualType SubobjType) {
4707 if (!checkConst(SubobjType))
4708 return false;
4709
4710 if (!SubobjType->isVectorType()) {
4711 Info.FFDiag(E);
4712 return false;
4713 }
4714 return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS);
4715 }
4716
4717 bool found(APSInt &Value, QualType SubobjType) {
4718 if (!checkConst(SubobjType))
4719 return false;
4720
4721 if (!SubobjType->isIntegerType()) {
4722 // We don't support compound assignment on integer-cast-to-pointer
4723 // values.
4724 Info.FFDiag(E);
4725 return false;
4726 }
4727
4728 if (RHS.isInt()) {
4729 APSInt LHS =
4730 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
4731 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
4732 return false;
4733 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
4734 return true;
4735 } else if (RHS.isFloat()) {
4736 const FPOptions FPO = E->getFPFeaturesInEffect(
4737 Info.Ctx.getLangOpts());
4738 APFloat FValue(0.0);
4739 return HandleIntToFloatCast(Info, E, FPO, SubobjType, Value,
4740 PromotedLHSType, FValue) &&
4741 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
4742 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
4743 Value);
4744 }
4745
4746 Info.FFDiag(E);
4747 return false;
4748 }
4749 bool found(APFloat &Value, QualType SubobjType) {
4750 return checkConst(SubobjType) &&
4751 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
4752 Value) &&
4753 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
4754 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
4755 }
4756 bool foundPointer(APValue &Subobj, QualType SubobjType) {
4757 if (!checkConst(SubobjType))
4758 return false;
4759
4760 QualType PointeeType;
4761 if (const PointerType *PT = SubobjType->getAs<PointerType>())
4762 PointeeType = PT->getPointeeType();
4763
4764 if (PointeeType.isNull() || !RHS.isInt() ||
4765 (Opcode != BO_Add && Opcode != BO_Sub)) {
4766 Info.FFDiag(E);
4767 return false;
4768 }
4769
4770 APSInt Offset = RHS.getInt();
4771 if (Opcode == BO_Sub)
4772 negateAsSigned(Offset);
4773
4774 LValue LVal;
4775 LVal.setFrom(Info.Ctx, Subobj);
4776 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
4777 return false;
4778 LVal.moveInto(Subobj);
4779 return true;
4780 }
4781};
4782} // end anonymous namespace
4783
4784const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
4785
4786/// Perform a compound assignment of LVal <op>= RVal.
4787static bool handleCompoundAssignment(EvalInfo &Info,
4788 const CompoundAssignOperator *E,
4789 const LValue &LVal, QualType LValType,
4790 QualType PromotedLValType,
4791 BinaryOperatorKind Opcode,
4792 const APValue &RVal) {
4793 if (LVal.Designator.Invalid)
4794 return false;
4795
4796 if (!Info.getLangOpts().CPlusPlus14) {
4797 Info.FFDiag(E);
4798 return false;
4799 }
4800
4801 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4802 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
4803 RVal };
4804 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4805}
4806
4807namespace {
4808struct IncDecSubobjectHandler {
4809 EvalInfo &Info;
4810 const UnaryOperator *E;
4812 APValue *Old;
4813
4814 typedef bool result_type;
4815
4816 bool checkConst(QualType QT) {
4817 // Assigning to a const object has undefined behavior.
4818 if (QT.isConstQualified()) {
4819 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4820 return false;
4821 }
4822 return true;
4823 }
4824
4825 bool failed() { return false; }
4826 bool found(APValue &Subobj, QualType SubobjType) {
4827 // Stash the old value. Also clear Old, so we don't clobber it later
4828 // if we're post-incrementing a complex.
4829 if (Old) {
4830 *Old = Subobj;
4831 Old = nullptr;
4832 }
4833
4834 switch (Subobj.getKind()) {
4835 case APValue::Int:
4836 return found(Subobj.getInt(), SubobjType);
4837 case APValue::Float:
4838 return found(Subobj.getFloat(), SubobjType);
4840 return found(Subobj.getComplexIntReal(),
4841 SubobjType->castAs<ComplexType>()->getElementType()
4842 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4844 return found(Subobj.getComplexFloatReal(),
4845 SubobjType->castAs<ComplexType>()->getElementType()
4846 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4847 case APValue::LValue:
4848 return foundPointer(Subobj, SubobjType);
4849 default:
4850 // FIXME: can this happen?
4851 Info.FFDiag(E);
4852 return false;
4853 }
4854 }
4855 bool found(APSInt &Value, QualType SubobjType) {
4856 if (!checkConst(SubobjType))
4857 return false;
4858
4859 if (!SubobjType->isIntegerType()) {
4860 // We don't support increment / decrement on integer-cast-to-pointer
4861 // values.
4862 Info.FFDiag(E);
4863 return false;
4864 }
4865
4866 if (Old) *Old = APValue(Value);
4867
4868 // bool arithmetic promotes to int, and the conversion back to bool
4869 // doesn't reduce mod 2^n, so special-case it.
4870 if (SubobjType->isBooleanType()) {
4871 if (AccessKind == AK_Increment)
4872 Value = 1;
4873 else
4874 Value = !Value;
4875 return true;
4876 }
4877
4878 bool WasNegative = Value.isNegative();
4879 if (AccessKind == AK_Increment) {
4880 ++Value;
4881
4882 if (!WasNegative && Value.isNegative() && E->canOverflow()) {
4883 APSInt ActualValue(Value, /*IsUnsigned*/true);
4884 return HandleOverflow(Info, E, ActualValue, SubobjType);
4885 }
4886 } else {
4887 --Value;
4888
4889 if (WasNegative && !Value.isNegative() && E->canOverflow()) {
4890 unsigned BitWidth = Value.getBitWidth();
4891 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
4892 ActualValue.setBit(BitWidth);
4893 return HandleOverflow(Info, E, ActualValue, SubobjType);
4894 }
4895 }
4896 return true;
4897 }
4898 bool found(APFloat &Value, QualType SubobjType) {
4899 if (!checkConst(SubobjType))
4900 return false;
4901
4902 if (Old) *Old = APValue(Value);
4903
4904 APFloat One(Value.getSemantics(), 1);
4905 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
4906 APFloat::opStatus St;
4907 if (AccessKind == AK_Increment)
4908 St = Value.add(One, RM);
4909 else
4910 St = Value.subtract(One, RM);
4911 return checkFloatingPointResult(Info, E, St);
4912 }
4913 bool foundPointer(APValue &Subobj, QualType SubobjType) {
4914 if (!checkConst(SubobjType))
4915 return false;
4916
4917 QualType PointeeType;
4918 if (const PointerType *PT = SubobjType->getAs<PointerType>())
4919 PointeeType = PT->getPointeeType();
4920 else {
4921 Info.FFDiag(E);
4922 return false;
4923 }
4924
4925 LValue LVal;
4926 LVal.setFrom(Info.Ctx, Subobj);
4927 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
4928 AccessKind == AK_Increment ? 1 : -1))
4929 return false;
4930 LVal.moveInto(Subobj);
4931 return true;
4932 }
4933};
4934} // end anonymous namespace
4935
4936/// Perform an increment or decrement on LVal.
4937static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
4938 QualType LValType, bool IsIncrement, APValue *Old) {
4939 if (LVal.Designator.Invalid)
4940 return false;
4941
4942 if (!Info.getLangOpts().CPlusPlus14) {
4943 Info.FFDiag(E);
4944 return false;
4945 }
4946
4947 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
4948 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
4949 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
4950 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4951}
4952
4953/// Build an lvalue for the object argument of a member function call.
4954static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
4955 LValue &This) {
4956 if (Object->getType()->isPointerType() && Object->isPRValue())
4957 return EvaluatePointer(Object, This, Info);
4958
4959 if (Object->isGLValue())
4960 return EvaluateLValue(Object, This, Info);
4961
4962 if (Object->getType()->isLiteralType(Info.Ctx))
4963 return EvaluateTemporary(Object, This, Info);
4964
4965 if (Object->getType()->isRecordType() && Object->isPRValue())
4966 return EvaluateTemporary(Object, This, Info);
4967
4968 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
4969 return false;
4970}
4971
4972/// HandleMemberPointerAccess - Evaluate a member access operation and build an
4973/// lvalue referring to the result.
4974///
4975/// \param Info - Information about the ongoing evaluation.
4976/// \param LV - An lvalue referring to the base of the member pointer.
4977/// \param RHS - The member pointer expression.
4978/// \param IncludeMember - Specifies whether the member itself is included in
4979/// the resulting LValue subobject designator. This is not possible when
4980/// creating a bound member function.
4981/// \return The field or method declaration to which the member pointer refers,
4982/// or 0 if evaluation fails.
4983static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4984 QualType LVType,
4985 LValue &LV,
4986 const Expr *RHS,
4987 bool IncludeMember = true) {
4988 MemberPtr MemPtr;
4989 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
4990 return nullptr;
4991
4992 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
4993 // member value, the behavior is undefined.
4994 if (!MemPtr.getDecl()) {
4995 // FIXME: Specific diagnostic.
4996 Info.FFDiag(RHS);
4997 return nullptr;
4998 }
4999
5000 if (MemPtr.isDerivedMember()) {
5001 // This is a member of some derived class. Truncate LV appropriately.
5002 // The end of the derived-to-base path for the base object must match the
5003 // derived-to-base path for the member pointer.
5004 // C++23 [expr.mptr.oper]p4:
5005 // If the result of E1 is an object [...] whose most derived object does
5006 // not contain the member to which E2 refers, the behavior is undefined.
5007 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
5008 LV.Designator.Entries.size()) {
5009 Info.FFDiag(RHS);
5010 return nullptr;
5011 }
5012 unsigned PathLengthToMember =
5013 LV.Designator.Entries.size() - MemPtr.Path.size();
5014 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
5015 const CXXRecordDecl *LVDecl = getAsBaseClass(
5016 LV.Designator.Entries[PathLengthToMember + I]);
5017 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
5018 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
5019 Info.FFDiag(RHS);
5020 return nullptr;
5021 }
5022 }
5023 // MemPtr.Path only contains the base classes of the class directly
5024 // containing the member E2. It is still necessary to check that the class
5025 // directly containing the member E2 lies on the derived-to-base path of E1
5026 // to avoid incorrectly permitting member pointer access into a sibling
5027 // class of the class containing the member E2. If this class would
5028 // correspond to the most-derived class of E1, it either isn't contained in
5029 // LV.Designator.Entries or the corresponding entry refers to an array
5030 // element instead. Therefore get the most derived class directly in this
5031 // case. Otherwise the previous entry should correpond to this class.
5032 const CXXRecordDecl *LastLVDecl =
5033 (PathLengthToMember > LV.Designator.MostDerivedPathLength)
5034 ? getAsBaseClass(LV.Designator.Entries[PathLengthToMember - 1])
5035 : LV.Designator.MostDerivedType->getAsCXXRecordDecl();
5036 const CXXRecordDecl *LastMPDecl = MemPtr.getContainingRecord();
5037 if (LastLVDecl->getCanonicalDecl() != LastMPDecl->getCanonicalDecl()) {
5038 Info.FFDiag(RHS);
5039 return nullptr;
5040 }
5041
5042 // Truncate the lvalue to the appropriate derived class.
5043 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
5044 PathLengthToMember))
5045 return nullptr;
5046 } else if (!MemPtr.Path.empty()) {
5047 // Extend the LValue path with the member pointer's path.
5048 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
5049 MemPtr.Path.size() + IncludeMember);
5050
5051 // Walk down to the appropriate base class.
5052 if (const PointerType *PT = LVType->getAs<PointerType>())
5053 LVType = PT->getPointeeType();
5054 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
5055 assert(RD && "member pointer access on non-class-type expression");
5056 // The first class in the path is that of the lvalue.
5057 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
5058 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
5059 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
5060 return nullptr;
5061 RD = Base;
5062 }
5063 // Finally cast to the class containing the member.
5064 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
5065 MemPtr.getContainingRecord()))
5066 return nullptr;
5067 }
5068
5069 // Add the member. Note that we cannot build bound member functions here.
5070 if (IncludeMember) {
5071 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
5072 if (!HandleLValueMember(Info, RHS, LV, FD))
5073 return nullptr;
5074 } else if (const IndirectFieldDecl *IFD =
5075 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
5076 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
5077 return nullptr;
5078 } else {
5079 llvm_unreachable("can't construct reference to bound member function");
5080 }
5081 }
5082
5083 return MemPtr.getDecl();
5084}
5085
5086static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
5087 const BinaryOperator *BO,
5088 LValue &LV,
5089 bool IncludeMember = true) {
5090 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
5091
5092 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
5093 if (Info.noteFailure()) {
5094 MemberPtr MemPtr;
5095 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
5096 }
5097 return nullptr;
5098 }
5099
5100 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
5101 BO->getRHS(), IncludeMember);
5102}
5103
5104/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
5105/// the provided lvalue, which currently refers to the base object.
5106static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
5107 LValue &Result) {
5108 SubobjectDesignator &D = Result.Designator;
5109 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
5110 return false;
5111
5112 QualType TargetQT = E->getType();
5113 if (const PointerType *PT = TargetQT->getAs<PointerType>())
5114 TargetQT = PT->getPointeeType();
5115
5116 auto InvalidCast = [&]() {
5117 if (!Info.checkingPotentialConstantExpression() ||
5118 !Result.AllowConstexprUnknown) {
5119 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
5120 << D.MostDerivedType << TargetQT;
5121 }
5122 return false;
5123 };
5124
5125 // Check this cast lands within the final derived-to-base subobject path.
5126 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size())
5127 return InvalidCast();
5128
5129 // Check the type of the final cast. We don't need to check the path,
5130 // since a cast can only be formed if the path is unique.
5131 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
5132 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
5133 const CXXRecordDecl *FinalType;
5134 if (NewEntriesSize == D.MostDerivedPathLength)
5135 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
5136 else
5137 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
5138 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl())
5139 return InvalidCast();
5140
5141 // Truncate the lvalue to the appropriate derived class.
5142 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
5143}
5144
5145/// Get the value to use for a default-initialized object of type T.
5146/// Return false if it encounters something invalid.
5148 bool Success = true;
5149
5150 // If there is already a value present don't overwrite it.
5151 if (!Result.isAbsent())
5152 return true;
5153
5154 if (auto *RD = T->getAsCXXRecordDecl()) {
5155 if (RD->isInvalidDecl()) {
5156 Result = APValue();
5157 return false;
5158 }
5159 if (RD->isUnion()) {
5160 Result = APValue((const FieldDecl *)nullptr);
5161 return true;
5162 }
5163 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
5164 std::distance(RD->field_begin(), RD->field_end()));
5165
5166 unsigned Index = 0;
5167 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
5168 End = RD->bases_end();
5169 I != End; ++I, ++Index)
5170 Success &=
5171 handleDefaultInitValue(I->getType(), Result.getStructBase(Index));
5172
5173 for (const auto *I : RD->fields()) {
5174 if (I->isUnnamedBitField())
5175 continue;
5177 I->getType(), Result.getStructField(I->getFieldIndex()));
5178 }
5179 return Success;
5180 }
5181
5182 if (auto *AT =
5183 dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
5184 Result = APValue(APValue::UninitArray(), 0, AT->getZExtSize());
5185 if (Result.hasArrayFiller())
5186 Success &=
5187 handleDefaultInitValue(AT->getElementType(), Result.getArrayFiller());
5188
5189 return Success;
5190 }
5191
5192 Result = APValue::IndeterminateValue();
5193 return true;
5194}
5195
5196namespace {
5197enum EvalStmtResult {
5198 /// Evaluation failed.
5199 ESR_Failed,
5200 /// Hit a 'return' statement.
5201 ESR_Returned,
5202 /// Evaluation succeeded.
5203 ESR_Succeeded,
5204 /// Hit a 'continue' statement.
5205 ESR_Continue,
5206 /// Hit a 'break' statement.
5207 ESR_Break,
5208 /// Still scanning for 'case' or 'default' statement.
5209 ESR_CaseNotFound
5210};
5211}
5212/// Evaluates the initializer of a reference.
5213static bool EvaluateInitForDeclOfReferenceType(EvalInfo &Info,
5214 const ValueDecl *D,
5215 const Expr *Init, LValue &Result,
5216 APValue &Val) {
5217 assert(Init->isGLValue() && D->getType()->isReferenceType());
5218 // A reference is an lvalue.
5219 if (!EvaluateLValue(Init, Result, Info))
5220 return false;
5221 // [C++26][decl.ref]
5222 // The object designated by such a glvalue can be outside its lifetime
5223 // Because a null pointer value or a pointer past the end of an object
5224 // does not point to an object, a reference in a well-defined program cannot
5225 // refer to such things;
5226 if (!Result.Designator.Invalid && Result.Designator.isOnePastTheEnd()) {
5227 Info.FFDiag(Init, diag::note_constexpr_access_past_end) << AK_Dereference;
5228 return false;
5229 }
5230
5231 // Save the result.
5232 Result.moveInto(Val);
5233 return true;
5234}
5235
5236static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
5237 if (VD->isInvalidDecl())
5238 return false;
5239 // We don't need to evaluate the initializer for a static local.
5240 if (!VD->hasLocalStorage())
5241 return true;
5242
5243 LValue Result;
5244 APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(),
5245 ScopeKind::Block, Result);
5246
5247 const Expr *InitE = VD->getInit();
5248 if (!InitE) {
5249 if (VD->getType()->isDependentType())
5250 return Info.noteSideEffect();
5251 return handleDefaultInitValue(VD->getType(), Val);
5252 }
5253 if (InitE->isValueDependent())
5254 return false;
5255
5256 // For references to objects, check they do not designate a one-past-the-end
5257 // object.
5258 if (VD->getType()->isReferenceType()) {
5259 return EvaluateInitForDeclOfReferenceType(Info, VD, InitE, Result, Val);
5260 } else if (!EvaluateInPlace(Val, Info, Result, InitE)) {
5261 // Wipe out any partially-computed value, to allow tracking that this
5262 // evaluation failed.
5263 Val = APValue();
5264 return false;
5265 }
5266
5267 return true;
5268}
5269
5270static bool EvaluateDecompositionDeclInit(EvalInfo &Info,
5271 const DecompositionDecl *DD);
5272
5273static bool EvaluateDecl(EvalInfo &Info, const Decl *D,
5274 bool EvaluateConditionDecl = false) {
5275 bool OK = true;
5276 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
5277 OK &= EvaluateVarDecl(Info, VD);
5278
5279 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D);
5280 EvaluateConditionDecl && DD)
5281 OK &= EvaluateDecompositionDeclInit(Info, DD);
5282
5283 return OK;
5284}
5285
5286static bool EvaluateDecompositionDeclInit(EvalInfo &Info,
5287 const DecompositionDecl *DD) {
5288 bool OK = true;
5289 for (auto *BD : DD->flat_bindings())
5290 if (auto *VD = BD->getHoldingVar())
5291 OK &= EvaluateDecl(Info, VD, /*EvaluateConditionDecl=*/true);
5292
5293 return OK;
5294}
5295
5296static bool MaybeEvaluateDeferredVarDeclInit(EvalInfo &Info,
5297 const VarDecl *VD) {
5298 if (auto *DD = dyn_cast_if_present<DecompositionDecl>(VD)) {
5299 if (!EvaluateDecompositionDeclInit(Info, DD))
5300 return false;
5301 }
5302 return true;
5303}
5304
5305static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info) {
5306 assert(E->isValueDependent());
5307 if (Info.noteSideEffect())
5308 return true;
5309 assert(E->containsErrors() && "valid value-dependent expression should never "
5310 "reach invalid code path.");
5311 return false;
5312}
5313
5314/// Evaluate a condition (either a variable declaration or an expression).
5315static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
5316 const Expr *Cond, bool &Result) {
5317 if (Cond->isValueDependent())
5318 return false;
5319 FullExpressionRAII Scope(Info);
5320 if (CondDecl && !EvaluateDecl(Info, CondDecl))
5321 return false;
5322 if (!EvaluateAsBooleanCondition(Cond, Result, Info))
5323 return false;
5324 if (!MaybeEvaluateDeferredVarDeclInit(Info, CondDecl))
5325 return false;
5326 return Scope.destroy();
5327}
5328
5329namespace {
5330/// A location where the result (returned value) of evaluating a
5331/// statement should be stored.
5332struct StmtResult {
5333 /// The APValue that should be filled in with the returned value.
5334 APValue &Value;
5335 /// The location containing the result, if any (used to support RVO).
5336 const LValue *Slot;
5337};
5338
5339struct TempVersionRAII {
5340 CallStackFrame &Frame;
5341
5342 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
5343 Frame.pushTempVersion();
5344 }
5345
5346 ~TempVersionRAII() {
5347 Frame.popTempVersion();
5348 }
5349};
5350
5351}
5352
5353static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
5354 const Stmt *S,
5355 const SwitchCase *SC = nullptr);
5356
5357/// Helper to implement named break/continue. Returns 'true' if the evaluation
5358/// result should be propagated up. Otherwise, it sets the evaluation result
5359/// to either Continue to continue the current loop, or Succeeded to break it.
5360static bool ShouldPropagateBreakContinue(EvalInfo &Info,
5361 const Stmt *LoopOrSwitch,
5363 EvalStmtResult &ESR) {
5364 bool IsSwitch = isa<SwitchStmt>(LoopOrSwitch);
5365
5366 // For loops, map Succeeded to Continue so we don't have to check for both.
5367 if (!IsSwitch && ESR == ESR_Succeeded) {
5368 ESR = ESR_Continue;
5369 return false;
5370 }
5371
5372 if (ESR != ESR_Break && ESR != ESR_Continue)
5373 return false;
5374
5375 // Are we breaking out of or continuing this statement?
5376 bool CanBreakOrContinue = !IsSwitch || ESR == ESR_Break;
5377 const Stmt *StackTop = Info.BreakContinueStack.back();
5378 if (CanBreakOrContinue && (StackTop == nullptr || StackTop == LoopOrSwitch)) {
5379 Info.BreakContinueStack.pop_back();
5380 if (ESR == ESR_Break)
5381 ESR = ESR_Succeeded;
5382 return false;
5383 }
5384
5385 // We're not. Propagate the result up.
5386 for (BlockScopeRAII *S : Scopes) {
5387 if (!S->destroy()) {
5388 ESR = ESR_Failed;
5389 break;
5390 }
5391 }
5392 return true;
5393}
5394
5395/// Evaluate the body of a loop, and translate the result as appropriate.
5396static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
5397 const Stmt *Body,
5398 const SwitchCase *Case = nullptr) {
5399 BlockScopeRAII Scope(Info);
5400
5401 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case);
5402 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
5403 ESR = ESR_Failed;
5404
5405 return ESR;
5406}
5407
5408/// Evaluate a switch statement.
5409static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
5410 const SwitchStmt *SS) {
5411 BlockScopeRAII Scope(Info);
5412
5413 // Evaluate the switch condition.
5414 APSInt Value;
5415 {
5416 if (const Stmt *Init = SS->getInit()) {
5417 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
5418 if (ESR != ESR_Succeeded) {
5419 if (ESR != ESR_Failed && !Scope.destroy())
5420 ESR = ESR_Failed;
5421 return ESR;
5422 }
5423 }
5424
5425 FullExpressionRAII CondScope(Info);
5426 if (SS->getConditionVariable() &&
5427 !EvaluateDecl(Info, SS->getConditionVariable()))
5428 return ESR_Failed;
5429 if (SS->getCond()->isValueDependent()) {
5430 // We don't know what the value is, and which branch should jump to.
5431 EvaluateDependentExpr(SS->getCond(), Info);
5432 return ESR_Failed;
5433 }
5434 if (!EvaluateInteger(SS->getCond(), Value, Info))
5435 return ESR_Failed;
5436
5438 return ESR_Failed;
5439
5440 if (!CondScope.destroy())
5441 return ESR_Failed;
5442 }
5443
5444 // Find the switch case corresponding to the value of the condition.
5445 // FIXME: Cache this lookup.
5446 const SwitchCase *Found = nullptr;
5447 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
5448 SC = SC->getNextSwitchCase()) {
5449 if (isa<DefaultStmt>(SC)) {
5450 Found = SC;
5451 continue;
5452 }
5453
5454 const CaseStmt *CS = cast<CaseStmt>(SC);
5455 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
5456 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
5457 : LHS;
5458 if (LHS <= Value && Value <= RHS) {
5459 Found = SC;
5460 break;
5461 }
5462 }
5463
5464 if (!Found)
5465 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5466
5467 // Search the switch body for the switch case and evaluate it from there.
5468 EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found);
5469 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
5470 return ESR_Failed;
5471 if (ShouldPropagateBreakContinue(Info, SS, /*Scopes=*/{}, ESR))
5472 return ESR;
5473
5474 switch (ESR) {
5475 case ESR_Break:
5476 llvm_unreachable("Should have been converted to Succeeded");
5477 case ESR_Succeeded:
5478 case ESR_Continue:
5479 case ESR_Failed:
5480 case ESR_Returned:
5481 return ESR;
5482 case ESR_CaseNotFound:
5483 // This can only happen if the switch case is nested within a statement
5484 // expression. We have no intention of supporting that.
5485 Info.FFDiag(Found->getBeginLoc(),
5486 diag::note_constexpr_stmt_expr_unsupported);
5487 return ESR_Failed;
5488 }
5489 llvm_unreachable("Invalid EvalStmtResult!");
5490}
5491
5492static bool CheckLocalVariableDeclaration(EvalInfo &Info, const VarDecl *VD) {
5493 // An expression E is a core constant expression unless the evaluation of E
5494 // would evaluate one of the following: [C++23] - a control flow that passes
5495 // through a declaration of a variable with static or thread storage duration
5496 // unless that variable is usable in constant expressions.
5497 if (VD->isLocalVarDecl() && VD->isStaticLocal() &&
5498 !VD->isUsableInConstantExpressions(Info.Ctx)) {
5499 Info.CCEDiag(VD->getLocation(), diag::note_constexpr_static_local)
5500 << (VD->getTSCSpec() == TSCS_unspecified ? 0 : 1) << VD;
5501 return false;
5502 }
5503 return true;
5504}
5505
5506// Evaluate a statement.
5507static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
5508 const Stmt *S, const SwitchCase *Case) {
5509 if (!Info.nextStep(S))
5510 return ESR_Failed;
5511
5512 // If we're hunting down a 'case' or 'default' label, recurse through
5513 // substatements until we hit the label.
5514 if (Case) {
5515 switch (S->getStmtClass()) {
5516 case Stmt::CompoundStmtClass:
5517 // FIXME: Precompute which substatement of a compound statement we
5518 // would jump to, and go straight there rather than performing a
5519 // linear scan each time.
5520 case Stmt::LabelStmtClass:
5521 case Stmt::AttributedStmtClass:
5522 case Stmt::DoStmtClass:
5523 break;
5524
5525 case Stmt::CaseStmtClass:
5526 case Stmt::DefaultStmtClass:
5527 if (Case == S)
5528 Case = nullptr;
5529 break;
5530
5531 case Stmt::IfStmtClass: {
5532 // FIXME: Precompute which side of an 'if' we would jump to, and go
5533 // straight there rather than scanning both sides.
5534 const IfStmt *IS = cast<IfStmt>(S);
5535
5536 // Wrap the evaluation in a block scope, in case it's a DeclStmt
5537 // preceded by our switch label.
5538 BlockScopeRAII Scope(Info);
5539
5540 // Step into the init statement in case it brings an (uninitialized)
5541 // variable into scope.
5542 if (const Stmt *Init = IS->getInit()) {
5543 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5544 if (ESR != ESR_CaseNotFound) {
5545 assert(ESR != ESR_Succeeded);
5546 return ESR;
5547 }
5548 }
5549
5550 // Condition variable must be initialized if it exists.
5551 // FIXME: We can skip evaluating the body if there's a condition
5552 // variable, as there can't be any case labels within it.
5553 // (The same is true for 'for' statements.)
5554
5555 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
5556 if (ESR == ESR_Failed)
5557 return ESR;
5558 if (ESR != ESR_CaseNotFound)
5559 return Scope.destroy() ? ESR : ESR_Failed;
5560 if (!IS->getElse())
5561 return ESR_CaseNotFound;
5562
5563 ESR = EvaluateStmt(Result, Info, IS->getElse(), Case);
5564 if (ESR == ESR_Failed)
5565 return ESR;
5566 if (ESR != ESR_CaseNotFound)
5567 return Scope.destroy() ? ESR : ESR_Failed;
5568 return ESR_CaseNotFound;
5569 }
5570
5571 case Stmt::WhileStmtClass: {
5572 EvalStmtResult ESR =
5573 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
5574 if (ShouldPropagateBreakContinue(Info, S, /*Scopes=*/{}, ESR))
5575 return ESR;
5576 if (ESR != ESR_Continue)
5577 return ESR;
5578 break;
5579 }
5580
5581 case Stmt::ForStmtClass: {
5582 const ForStmt *FS = cast<ForStmt>(S);
5583 BlockScopeRAII Scope(Info);
5584
5585 // Step into the init statement in case it brings an (uninitialized)
5586 // variable into scope.
5587 if (const Stmt *Init = FS->getInit()) {
5588 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5589 if (ESR != ESR_CaseNotFound) {
5590 assert(ESR != ESR_Succeeded);
5591 return ESR;
5592 }
5593 }
5594
5595 EvalStmtResult ESR =
5596 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
5597 if (ShouldPropagateBreakContinue(Info, FS, /*Scopes=*/{}, ESR))
5598 return ESR;
5599 if (ESR != ESR_Continue)
5600 return ESR;
5601 if (const auto *Inc = FS->getInc()) {
5602 if (Inc->isValueDependent()) {
5603 if (!EvaluateDependentExpr(Inc, Info))
5604 return ESR_Failed;
5605 } else {
5606 FullExpressionRAII IncScope(Info);
5607 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5608 return ESR_Failed;
5609 }
5610 }
5611 break;
5612 }
5613
5614 case Stmt::DeclStmtClass: {
5615 // Start the lifetime of any uninitialized variables we encounter. They
5616 // might be used by the selected branch of the switch.
5617 const DeclStmt *DS = cast<DeclStmt>(S);
5618 for (const auto *D : DS->decls()) {
5619 if (const auto *VD = dyn_cast<VarDecl>(D)) {
5620 if (!CheckLocalVariableDeclaration(Info, VD))
5621 return ESR_Failed;
5622 if (VD->hasLocalStorage() && !VD->getInit())
5623 if (!EvaluateVarDecl(Info, VD))
5624 return ESR_Failed;
5625 // FIXME: If the variable has initialization that can't be jumped
5626 // over, bail out of any immediately-surrounding compound-statement
5627 // too. There can't be any case labels here.
5628 }
5629 }
5630 return ESR_CaseNotFound;
5631 }
5632
5633 default:
5634 return ESR_CaseNotFound;
5635 }
5636 }
5637
5638 switch (S->getStmtClass()) {
5639 default:
5640 if (const Expr *E = dyn_cast<Expr>(S)) {
5641 if (E->isValueDependent()) {
5642 if (!EvaluateDependentExpr(E, Info))
5643 return ESR_Failed;
5644 } else {
5645 // Don't bother evaluating beyond an expression-statement which couldn't
5646 // be evaluated.
5647 // FIXME: Do we need the FullExpressionRAII object here?
5648 // VisitExprWithCleanups should create one when necessary.
5649 FullExpressionRAII Scope(Info);
5650 if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy())
5651 return ESR_Failed;
5652 }
5653 return ESR_Succeeded;
5654 }
5655
5656 Info.FFDiag(S->getBeginLoc()) << S->getSourceRange();
5657 return ESR_Failed;
5658
5659 case Stmt::NullStmtClass:
5660 return ESR_Succeeded;
5661
5662 case Stmt::DeclStmtClass: {
5663 const DeclStmt *DS = cast<DeclStmt>(S);
5664 for (const auto *D : DS->decls()) {
5665 const VarDecl *VD = dyn_cast_or_null<VarDecl>(D);
5666 if (VD && !CheckLocalVariableDeclaration(Info, VD))
5667 return ESR_Failed;
5668 // Each declaration initialization is its own full-expression.
5669 FullExpressionRAII Scope(Info);
5670 if (!EvaluateDecl(Info, D, /*EvaluateConditionDecl=*/true) &&
5671 !Info.noteFailure())
5672 return ESR_Failed;
5673 if (!Scope.destroy())
5674 return ESR_Failed;
5675 }
5676 return ESR_Succeeded;
5677 }
5678
5679 case Stmt::ReturnStmtClass: {
5680 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
5681 FullExpressionRAII Scope(Info);
5682 if (RetExpr && RetExpr->isValueDependent()) {
5683 EvaluateDependentExpr(RetExpr, Info);
5684 // We know we returned, but we don't know what the value is.
5685 return ESR_Failed;
5686 }
5687 if (RetExpr &&
5688 !(Result.Slot
5689 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
5690 : Evaluate(Result.Value, Info, RetExpr)))
5691 return ESR_Failed;
5692 return Scope.destroy() ? ESR_Returned : ESR_Failed;
5693 }
5694
5695 case Stmt::CompoundStmtClass: {
5696 BlockScopeRAII Scope(Info);
5697
5698 const CompoundStmt *CS = cast<CompoundStmt>(S);
5699 for (const auto *BI : CS->body()) {
5700 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
5701 if (ESR == ESR_Succeeded)
5702 Case = nullptr;
5703 else if (ESR != ESR_CaseNotFound) {
5704 if (ESR != ESR_Failed && !Scope.destroy())
5705 return ESR_Failed;
5706 return ESR;
5707 }
5708 }
5709 if (Case)
5710 return ESR_CaseNotFound;
5711 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5712 }
5713
5714 case Stmt::IfStmtClass: {
5715 const IfStmt *IS = cast<IfStmt>(S);
5716
5717 // Evaluate the condition, as either a var decl or as an expression.
5718 BlockScopeRAII Scope(Info);
5719 if (const Stmt *Init = IS->getInit()) {
5720 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
5721 if (ESR != ESR_Succeeded) {
5722 if (ESR != ESR_Failed && !Scope.destroy())
5723 return ESR_Failed;
5724 return ESR;
5725 }
5726 }
5727 bool Cond;
5728 if (IS->isConsteval()) {
5730 // If we are not in a constant context, if consteval should not evaluate
5731 // to true.
5732 if (!Info.InConstantContext)
5733 Cond = !Cond;
5734 } else if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(),
5735 Cond))
5736 return ESR_Failed;
5737
5738 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
5739 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
5740 if (ESR != ESR_Succeeded) {
5741 if (ESR != ESR_Failed && !Scope.destroy())
5742 return ESR_Failed;
5743 return ESR;
5744 }
5745 }
5746 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5747 }
5748
5749 case Stmt::WhileStmtClass: {
5750 const WhileStmt *WS = cast<WhileStmt>(S);
5751 while (true) {
5752 BlockScopeRAII Scope(Info);
5753 bool Continue;
5754 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
5755 Continue))
5756 return ESR_Failed;
5757 if (!Continue)
5758 break;
5759
5760 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
5761 if (ShouldPropagateBreakContinue(Info, WS, &Scope, ESR))
5762 return ESR;
5763
5764 if (ESR != ESR_Continue) {
5765 if (ESR != ESR_Failed && !Scope.destroy())
5766 return ESR_Failed;
5767 return ESR;
5768 }
5769 if (!Scope.destroy())
5770 return ESR_Failed;
5771 }
5772 return ESR_Succeeded;
5773 }
5774
5775 case Stmt::DoStmtClass: {
5776 const DoStmt *DS = cast<DoStmt>(S);
5777 bool Continue;
5778 do {
5779 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
5780 if (ShouldPropagateBreakContinue(Info, DS, /*Scopes=*/{}, ESR))
5781 return ESR;
5782 if (ESR != ESR_Continue)
5783 return ESR;
5784 Case = nullptr;
5785
5786 if (DS->getCond()->isValueDependent()) {
5787 EvaluateDependentExpr(DS->getCond(), Info);
5788 // Bailout as we don't know whether to keep going or terminate the loop.
5789 return ESR_Failed;
5790 }
5791 FullExpressionRAII CondScope(Info);
5792 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) ||
5793 !CondScope.destroy())
5794 return ESR_Failed;
5795 } while (Continue);
5796 return ESR_Succeeded;
5797 }
5798
5799 case Stmt::ForStmtClass: {
5800 const ForStmt *FS = cast<ForStmt>(S);
5801 BlockScopeRAII ForScope(Info);
5802 if (FS->getInit()) {
5803 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5804 if (ESR != ESR_Succeeded) {
5805 if (ESR != ESR_Failed && !ForScope.destroy())
5806 return ESR_Failed;
5807 return ESR;
5808 }
5809 }
5810 while (true) {
5811 BlockScopeRAII IterScope(Info);
5812 bool Continue = true;
5813 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
5814 FS->getCond(), Continue))
5815 return ESR_Failed;
5816
5817 if (!Continue) {
5818 if (!IterScope.destroy())
5819 return ESR_Failed;
5820 break;
5821 }
5822
5823 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5824 if (ShouldPropagateBreakContinue(Info, FS, {&IterScope, &ForScope}, ESR))
5825 return ESR;
5826 if (ESR != ESR_Continue) {
5827 if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))
5828 return ESR_Failed;
5829 return ESR;
5830 }
5831
5832 if (const auto *Inc = FS->getInc()) {
5833 if (Inc->isValueDependent()) {
5834 if (!EvaluateDependentExpr(Inc, Info))
5835 return ESR_Failed;
5836 } else {
5837 FullExpressionRAII IncScope(Info);
5838 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5839 return ESR_Failed;
5840 }
5841 }
5842
5843 if (!IterScope.destroy())
5844 return ESR_Failed;
5845 }
5846 return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;
5847 }
5848
5849 case Stmt::CXXForRangeStmtClass: {
5851 BlockScopeRAII Scope(Info);
5852
5853 // Evaluate the init-statement if present.
5854 if (FS->getInit()) {
5855 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5856 if (ESR != ESR_Succeeded) {
5857 if (ESR != ESR_Failed && !Scope.destroy())
5858 return ESR_Failed;
5859 return ESR;
5860 }
5861 }
5862
5863 // Initialize the __range variable.
5864 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
5865 if (ESR != ESR_Succeeded) {
5866 if (ESR != ESR_Failed && !Scope.destroy())
5867 return ESR_Failed;
5868 return ESR;
5869 }
5870
5871 // In error-recovery cases it's possible to get here even if we failed to
5872 // synthesize the __begin and __end variables.
5873 if (!FS->getBeginStmt() || !FS->getEndStmt() || !FS->getCond())
5874 return ESR_Failed;
5875
5876 // Create the __begin and __end iterators.
5877 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
5878 if (ESR != ESR_Succeeded) {
5879 if (ESR != ESR_Failed && !Scope.destroy())
5880 return ESR_Failed;
5881 return ESR;
5882 }
5883 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
5884 if (ESR != ESR_Succeeded) {
5885 if (ESR != ESR_Failed && !Scope.destroy())
5886 return ESR_Failed;
5887 return ESR;
5888 }
5889
5890 while (true) {
5891 // Condition: __begin != __end.
5892 {
5893 if (FS->getCond()->isValueDependent()) {
5894 EvaluateDependentExpr(FS->getCond(), Info);
5895 // We don't know whether to keep going or terminate the loop.
5896 return ESR_Failed;
5897 }
5898 bool Continue = true;
5899 FullExpressionRAII CondExpr(Info);
5900 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
5901 return ESR_Failed;
5902 if (!Continue)
5903 break;
5904 }
5905
5906 // User's variable declaration, initialized by *__begin.
5907 BlockScopeRAII InnerScope(Info);
5908 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
5909 if (ESR != ESR_Succeeded) {
5910 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5911 return ESR_Failed;
5912 return ESR;
5913 }
5914
5915 // Loop body.
5916 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5917 if (ShouldPropagateBreakContinue(Info, FS, {&InnerScope, &Scope}, ESR))
5918 return ESR;
5919 if (ESR != ESR_Continue) {
5920 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5921 return ESR_Failed;
5922 return ESR;
5923 }
5924 if (FS->getInc()->isValueDependent()) {
5925 if (!EvaluateDependentExpr(FS->getInc(), Info))
5926 return ESR_Failed;
5927 } else {
5928 // Increment: ++__begin
5929 if (!EvaluateIgnoredValue(Info, FS->getInc()))
5930 return ESR_Failed;
5931 }
5932
5933 if (!InnerScope.destroy())
5934 return ESR_Failed;
5935 }
5936
5937 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5938 }
5939
5940 case Stmt::SwitchStmtClass:
5941 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
5942
5943 case Stmt::ContinueStmtClass:
5944 case Stmt::BreakStmtClass: {
5945 auto *B = cast<LoopControlStmt>(S);
5946 Info.BreakContinueStack.push_back(B->getNamedLoopOrSwitch());
5947 return isa<ContinueStmt>(S) ? ESR_Continue : ESR_Break;
5948 }
5949
5950 case Stmt::LabelStmtClass:
5951 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
5952
5953 case Stmt::AttributedStmtClass: {
5954 const auto *AS = cast<AttributedStmt>(S);
5955 const auto *SS = AS->getSubStmt();
5956 MSConstexprContextRAII ConstexprContext(
5957 *Info.CurrentCall, hasSpecificAttr<MSConstexprAttr>(AS->getAttrs()) &&
5958 isa<ReturnStmt>(SS));
5959
5960 auto LO = Info.getASTContext().getLangOpts();
5961 if (LO.CXXAssumptions && !LO.MSVCCompat) {
5962 for (auto *Attr : AS->getAttrs()) {
5963 auto *AA = dyn_cast<CXXAssumeAttr>(Attr);
5964 if (!AA)
5965 continue;
5966
5967 auto *Assumption = AA->getAssumption();
5968 if (Assumption->isValueDependent())
5969 return ESR_Failed;
5970
5971 if (Assumption->HasSideEffects(Info.getASTContext()))
5972 continue;
5973
5974 bool Value;
5975 if (!EvaluateAsBooleanCondition(Assumption, Value, Info))
5976 return ESR_Failed;
5977 if (!Value) {
5978 Info.CCEDiag(Assumption->getExprLoc(),
5979 diag::note_constexpr_assumption_failed);
5980 return ESR_Failed;
5981 }
5982 }
5983 }
5984
5985 return EvaluateStmt(Result, Info, SS, Case);
5986 }
5987
5988 case Stmt::CaseStmtClass:
5989 case Stmt::DefaultStmtClass:
5990 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
5991 case Stmt::CXXTryStmtClass:
5992 // Evaluate try blocks by evaluating all sub statements.
5993 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
5994 }
5995}
5996
5997/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
5998/// default constructor. If so, we'll fold it whether or not it's marked as
5999/// constexpr. If it is marked as constexpr, we will never implicitly define it,
6000/// so we need special handling.
6001static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
6002 const CXXConstructorDecl *CD,
6003 bool IsValueInitialization) {
6004 if (!CD->isTrivial() || !CD->isDefaultConstructor())
6005 return false;
6006
6007 // Value-initialization does not call a trivial default constructor, so such a
6008 // call is a core constant expression whether or not the constructor is
6009 // constexpr.
6010 if (!CD->isConstexpr() && !IsValueInitialization) {
6011 if (Info.getLangOpts().CPlusPlus11) {
6012 // FIXME: If DiagDecl is an implicitly-declared special member function,
6013 // we should be much more explicit about why it's not constexpr.
6014 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
6015 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
6016 Info.Note(CD->getLocation(), diag::note_declared_at);
6017 } else {
6018 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
6019 }
6020 }
6021 return true;
6022}
6023
6024/// CheckConstexprFunction - Check that a function can be called in a constant
6025/// expression.
6026static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
6028 const FunctionDecl *Definition,
6029 const Stmt *Body) {
6030 // Potential constant expressions can contain calls to declared, but not yet
6031 // defined, constexpr functions.
6032 if (Info.checkingPotentialConstantExpression() && !Definition &&
6033 Declaration->isConstexpr())
6034 return false;
6035
6036 // Bail out if the function declaration itself is invalid. We will
6037 // have produced a relevant diagnostic while parsing it, so just
6038 // note the problematic sub-expression.
6039 if (Declaration->isInvalidDecl()) {
6040 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
6041 return false;
6042 }
6043
6044 // DR1872: An instantiated virtual constexpr function can't be called in a
6045 // constant expression (prior to C++20). We can still constant-fold such a
6046 // call.
6047 if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) &&
6048 cast<CXXMethodDecl>(Declaration)->isVirtual())
6049 Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
6050
6051 if (Definition && Definition->isInvalidDecl()) {
6052 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
6053 return false;
6054 }
6055
6056 // Can we evaluate this function call?
6057 if (Definition && Body &&
6058 (Definition->isConstexpr() || (Info.CurrentCall->CanEvalMSConstexpr &&
6059 Definition->hasAttr<MSConstexprAttr>())))
6060 return true;
6061
6062 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
6063 // Special note for the assert() macro, as the normal error message falsely
6064 // implies we cannot use an assertion during constant evaluation.
6065 if (CallLoc.isMacroID() && DiagDecl->getIdentifier()) {
6066 // FIXME: Instead of checking for an implementation-defined function,
6067 // check and evaluate the assert() macro.
6068 StringRef Name = DiagDecl->getName();
6069 bool AssertFailed =
6070 Name == "__assert_rtn" || Name == "__assert_fail" || Name == "_wassert";
6071 if (AssertFailed) {
6072 Info.FFDiag(CallLoc, diag::note_constexpr_assert_failed);
6073 return false;
6074 }
6075 }
6076
6077 if (Info.getLangOpts().CPlusPlus11) {
6078 // If this function is not constexpr because it is an inherited
6079 // non-constexpr constructor, diagnose that directly.
6080 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
6081 if (CD && CD->isInheritingConstructor()) {
6082 auto *Inherited = CD->getInheritedConstructor().getConstructor();
6083 if (!Inherited->isConstexpr())
6084 DiagDecl = CD = Inherited;
6085 }
6086
6087 // FIXME: If DiagDecl is an implicitly-declared special member function
6088 // or an inheriting constructor, we should be much more explicit about why
6089 // it's not constexpr.
6090 if (CD && CD->isInheritingConstructor())
6091 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
6092 << CD->getInheritedConstructor().getConstructor()->getParent();
6093 else
6094 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
6095 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
6096 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
6097 } else {
6098 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
6099 }
6100 return false;
6101}
6102
6103namespace {
6104struct CheckDynamicTypeHandler {
6106 typedef bool result_type;
6107 bool failed() { return false; }
6108 bool found(APValue &Subobj, QualType SubobjType) { return true; }
6109 bool found(APSInt &Value, QualType SubobjType) { return true; }
6110 bool found(APFloat &Value, QualType SubobjType) { return true; }
6111};
6112} // end anonymous namespace
6113
6114/// Check that we can access the notional vptr of an object / determine its
6115/// dynamic type.
6116static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
6117 AccessKinds AK, bool Polymorphic) {
6118 if (This.Designator.Invalid)
6119 return false;
6120
6121 CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
6122
6123 if (!Obj)
6124 return false;
6125
6126 if (!Obj.Value) {
6127 // The object is not usable in constant expressions, so we can't inspect
6128 // its value to see if it's in-lifetime or what the active union members
6129 // are. We can still check for a one-past-the-end lvalue.
6130 if (This.Designator.isOnePastTheEnd() ||
6131 This.Designator.isMostDerivedAnUnsizedArray()) {
6132 Info.FFDiag(E, This.Designator.isOnePastTheEnd()
6133 ? diag::note_constexpr_access_past_end
6134 : diag::note_constexpr_access_unsized_array)
6135 << AK;
6136 return false;
6137 } else if (Polymorphic) {
6138 // Conservatively refuse to perform a polymorphic operation if we would
6139 // not be able to read a notional 'vptr' value.
6140 if (!Info.checkingPotentialConstantExpression() ||
6141 !This.AllowConstexprUnknown) {
6142 APValue Val;
6143 This.moveInto(Val);
6144 QualType StarThisType =
6145 Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
6146 Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
6147 << AK << Val.getAsString(Info.Ctx, StarThisType);
6148 }
6149 return false;
6150 }
6151 return true;
6152 }
6153
6154 CheckDynamicTypeHandler Handler{AK};
6155 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
6156}
6157
6158/// Check that the pointee of the 'this' pointer in a member function call is
6159/// either within its lifetime or in its period of construction or destruction.
6160static bool
6162 const LValue &This,
6163 const CXXMethodDecl *NamedMember) {
6164 return checkDynamicType(
6165 Info, E, This,
6166 isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false);
6167}
6168
6170 /// The dynamic class type of the object.
6172 /// The corresponding path length in the lvalue.
6173 unsigned PathLength;
6174};
6175
6176static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
6177 unsigned PathLength) {
6178 assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
6179 Designator.Entries.size() && "invalid path length");
6180 return (PathLength == Designator.MostDerivedPathLength)
6181 ? Designator.MostDerivedType->getAsCXXRecordDecl()
6182 : getAsBaseClass(Designator.Entries[PathLength - 1]);
6183}
6184
6185/// Determine the dynamic type of an object.
6186static std::optional<DynamicType> ComputeDynamicType(EvalInfo &Info,
6187 const Expr *E,
6188 LValue &This,
6189 AccessKinds AK) {
6190 // If we don't have an lvalue denoting an object of class type, there is no
6191 // meaningful dynamic type. (We consider objects of non-class type to have no
6192 // dynamic type.)
6193 if (!checkDynamicType(Info, E, This, AK,
6194 AK != AK_TypeId || This.AllowConstexprUnknown))
6195 return std::nullopt;
6196
6197 if (This.Designator.Invalid)
6198 return std::nullopt;
6199
6200 // Refuse to compute a dynamic type in the presence of virtual bases. This
6201 // shouldn't happen other than in constant-folding situations, since literal
6202 // types can't have virtual bases.
6203 //
6204 // Note that consumers of DynamicType assume that the type has no virtual
6205 // bases, and will need modifications if this restriction is relaxed.
6206 const CXXRecordDecl *Class =
6207 This.Designator.MostDerivedType->getAsCXXRecordDecl();
6208 if (!Class || Class->getNumVBases()) {
6209 Info.FFDiag(E);
6210 return std::nullopt;
6211 }
6212
6213 // FIXME: For very deep class hierarchies, it might be beneficial to use a
6214 // binary search here instead. But the overwhelmingly common case is that
6215 // we're not in the middle of a constructor, so it probably doesn't matter
6216 // in practice.
6217 ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
6218 for (unsigned PathLength = This.Designator.MostDerivedPathLength;
6219 PathLength <= Path.size(); ++PathLength) {
6220 switch (Info.isEvaluatingCtorDtor(This.getLValueBase(),
6221 Path.slice(0, PathLength))) {
6222 case ConstructionPhase::Bases:
6223 case ConstructionPhase::DestroyingBases:
6224 // We're constructing or destroying a base class. This is not the dynamic
6225 // type.
6226 break;
6227
6228 case ConstructionPhase::None:
6229 case ConstructionPhase::AfterBases:
6230 case ConstructionPhase::AfterFields:
6231 case ConstructionPhase::Destroying:
6232 // We've finished constructing the base classes and not yet started
6233 // destroying them again, so this is the dynamic type.
6234 return DynamicType{getBaseClassType(This.Designator, PathLength),
6235 PathLength};
6236 }
6237 }
6238
6239 // CWG issue 1517: we're constructing a base class of the object described by
6240 // 'This', so that object has not yet begun its period of construction and
6241 // any polymorphic operation on it results in undefined behavior.
6242 Info.FFDiag(E);
6243 return std::nullopt;
6244}
6245
6246/// Perform virtual dispatch.
6248 EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
6249 llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
6250 std::optional<DynamicType> DynType = ComputeDynamicType(
6251 Info, E, This,
6253 if (!DynType)
6254 return nullptr;
6255
6256 // Find the final overrider. It must be declared in one of the classes on the
6257 // path from the dynamic type to the static type.
6258 // FIXME: If we ever allow literal types to have virtual base classes, that
6259 // won't be true.
6260 const CXXMethodDecl *Callee = Found;
6261 unsigned PathLength = DynType->PathLength;
6262 for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
6263 const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
6264 const CXXMethodDecl *Overrider =
6265 Found->getCorrespondingMethodDeclaredInClass(Class, false);
6266 if (Overrider) {
6267 Callee = Overrider;
6268 break;
6269 }
6270 }
6271
6272 // C++2a [class.abstract]p6:
6273 // the effect of making a virtual call to a pure virtual function [...] is
6274 // undefined
6275 if (Callee->isPureVirtual()) {
6276 Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
6277 Info.Note(Callee->getLocation(), diag::note_declared_at);
6278 return nullptr;
6279 }
6280
6281 // If necessary, walk the rest of the path to determine the sequence of
6282 // covariant adjustment steps to apply.
6283 if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
6284 Found->getReturnType())) {
6285 CovariantAdjustmentPath.push_back(Callee->getReturnType());
6286 for (unsigned CovariantPathLength = PathLength + 1;
6287 CovariantPathLength != This.Designator.Entries.size();
6288 ++CovariantPathLength) {
6289 const CXXRecordDecl *NextClass =
6290 getBaseClassType(This.Designator, CovariantPathLength);
6291 const CXXMethodDecl *Next =
6292 Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
6293 if (Next && !Info.Ctx.hasSameUnqualifiedType(
6294 Next->getReturnType(), CovariantAdjustmentPath.back()))
6295 CovariantAdjustmentPath.push_back(Next->getReturnType());
6296 }
6297 if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
6298 CovariantAdjustmentPath.back()))
6299 CovariantAdjustmentPath.push_back(Found->getReturnType());
6300 }
6301
6302 // Perform 'this' adjustment.
6303 if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
6304 return nullptr;
6305
6306 return Callee;
6307}
6308
6309/// Perform the adjustment from a value returned by a virtual function to
6310/// a value of the statically expected type, which may be a pointer or
6311/// reference to a base class of the returned type.
6312static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
6313 APValue &Result,
6314 ArrayRef<QualType> Path) {
6315 assert(Result.isLValue() &&
6316 "unexpected kind of APValue for covariant return");
6317 if (Result.isNullPointer())
6318 return true;
6319
6320 LValue LVal;
6321 LVal.setFrom(Info.Ctx, Result);
6322
6323 const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
6324 for (unsigned I = 1; I != Path.size(); ++I) {
6325 const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
6326 assert(OldClass && NewClass && "unexpected kind of covariant return");
6327 if (OldClass != NewClass &&
6328 !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
6329 return false;
6330 OldClass = NewClass;
6331 }
6332
6333 LVal.moveInto(Result);
6334 return true;
6335}
6336
6337/// Determine whether \p Base, which is known to be a direct base class of
6338/// \p Derived, is a public base class.
6339static bool isBaseClassPublic(const CXXRecordDecl *Derived,
6340 const CXXRecordDecl *Base) {
6341 for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
6342 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
6343 if (BaseClass && declaresSameEntity(BaseClass, Base))
6344 return BaseSpec.getAccessSpecifier() == AS_public;
6345 }
6346 llvm_unreachable("Base is not a direct base of Derived");
6347}
6348
6349/// Apply the given dynamic cast operation on the provided lvalue.
6350///
6351/// This implements the hard case of dynamic_cast, requiring a "runtime check"
6352/// to find a suitable target subobject.
6353static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
6354 LValue &Ptr) {
6355 // We can't do anything with a non-symbolic pointer value.
6356 SubobjectDesignator &D = Ptr.Designator;
6357 if (D.Invalid)
6358 return false;
6359
6360 // C++ [expr.dynamic.cast]p6:
6361 // If v is a null pointer value, the result is a null pointer value.
6362 if (Ptr.isNullPointer() && !E->isGLValue())
6363 return true;
6364
6365 // For all the other cases, we need the pointer to point to an object within
6366 // its lifetime / period of construction / destruction, and we need to know
6367 // its dynamic type.
6368 std::optional<DynamicType> DynType =
6369 ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
6370 if (!DynType)
6371 return false;
6372
6373 // C++ [expr.dynamic.cast]p7:
6374 // If T is "pointer to cv void", then the result is a pointer to the most
6375 // derived object
6376 if (E->getType()->isVoidPointerType())
6377 return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
6378
6380 assert(C && "dynamic_cast target is not void pointer nor class");
6381 CanQualType CQT = Info.Ctx.getCanonicalTagType(C);
6382
6383 auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
6384 // C++ [expr.dynamic.cast]p9:
6385 if (!E->isGLValue()) {
6386 // The value of a failed cast to pointer type is the null pointer value
6387 // of the required result type.
6388 Ptr.setNull(Info.Ctx, E->getType());
6389 return true;
6390 }
6391
6392 // A failed cast to reference type throws [...] std::bad_cast.
6393 unsigned DiagKind;
6394 if (!Paths && (declaresSameEntity(DynType->Type, C) ||
6395 DynType->Type->isDerivedFrom(C)))
6396 DiagKind = 0;
6397 else if (!Paths || Paths->begin() == Paths->end())
6398 DiagKind = 1;
6399 else if (Paths->isAmbiguous(CQT))
6400 DiagKind = 2;
6401 else {
6402 assert(Paths->front().Access != AS_public && "why did the cast fail?");
6403 DiagKind = 3;
6404 }
6405 Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
6406 << DiagKind << Ptr.Designator.getType(Info.Ctx)
6407 << Info.Ctx.getCanonicalTagType(DynType->Type)
6408 << E->getType().getUnqualifiedType();
6409 return false;
6410 };
6411
6412 // Runtime check, phase 1:
6413 // Walk from the base subobject towards the derived object looking for the
6414 // target type.
6415 for (int PathLength = Ptr.Designator.Entries.size();
6416 PathLength >= (int)DynType->PathLength; --PathLength) {
6417 const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
6418 if (declaresSameEntity(Class, C))
6419 return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
6420 // We can only walk across public inheritance edges.
6421 if (PathLength > (int)DynType->PathLength &&
6422 !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
6423 Class))
6424 return RuntimeCheckFailed(nullptr);
6425 }
6426
6427 // Runtime check, phase 2:
6428 // Search the dynamic type for an unambiguous public base of type C.
6429 CXXBasePaths Paths(/*FindAmbiguities=*/true,
6430 /*RecordPaths=*/true, /*DetectVirtual=*/false);
6431 if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
6432 Paths.front().Access == AS_public) {
6433 // Downcast to the dynamic type...
6434 if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
6435 return false;
6436 // ... then upcast to the chosen base class subobject.
6437 for (CXXBasePathElement &Elem : Paths.front())
6438 if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
6439 return false;
6440 return true;
6441 }
6442
6443 // Otherwise, the runtime check fails.
6444 return RuntimeCheckFailed(&Paths);
6445}
6446
6447namespace {
6448struct StartLifetimeOfUnionMemberHandler {
6449 EvalInfo &Info;
6450 const Expr *LHSExpr;
6451 const FieldDecl *Field;
6452 bool DuringInit;
6453 bool Failed = false;
6454 static const AccessKinds AccessKind = AK_Assign;
6455
6456 typedef bool result_type;
6457 bool failed() { return Failed; }
6458 bool found(APValue &Subobj, QualType SubobjType) {
6459 // We are supposed to perform no initialization but begin the lifetime of
6460 // the object. We interpret that as meaning to do what default
6461 // initialization of the object would do if all constructors involved were
6462 // trivial:
6463 // * All base, non-variant member, and array element subobjects' lifetimes
6464 // begin
6465 // * No variant members' lifetimes begin
6466 // * All scalar subobjects whose lifetimes begin have indeterminate values
6467 assert(SubobjType->isUnionType());
6468 if (declaresSameEntity(Subobj.getUnionField(), Field)) {
6469 // This union member is already active. If it's also in-lifetime, there's
6470 // nothing to do.
6471 if (Subobj.getUnionValue().hasValue())
6472 return true;
6473 } else if (DuringInit) {
6474 // We're currently in the process of initializing a different union
6475 // member. If we carried on, that initialization would attempt to
6476 // store to an inactive union member, resulting in undefined behavior.
6477 Info.FFDiag(LHSExpr,
6478 diag::note_constexpr_union_member_change_during_init);
6479 return false;
6480 }
6482 Failed = !handleDefaultInitValue(Field->getType(), Result);
6483 Subobj.setUnion(Field, Result);
6484 return true;
6485 }
6486 bool found(APSInt &Value, QualType SubobjType) {
6487 llvm_unreachable("wrong value kind for union object");
6488 }
6489 bool found(APFloat &Value, QualType SubobjType) {
6490 llvm_unreachable("wrong value kind for union object");
6491 }
6492};
6493} // end anonymous namespace
6494
6495const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
6496
6497/// Handle a builtin simple-assignment or a call to a trivial assignment
6498/// operator whose left-hand side might involve a union member access. If it
6499/// does, implicitly start the lifetime of any accessed union elements per
6500/// C++20 [class.union]5.
6501static bool MaybeHandleUnionActiveMemberChange(EvalInfo &Info,
6502 const Expr *LHSExpr,
6503 const LValue &LHS) {
6504 if (LHS.InvalidBase || LHS.Designator.Invalid)
6505 return false;
6506
6508 // C++ [class.union]p5:
6509 // define the set S(E) of subexpressions of E as follows:
6510 unsigned PathLength = LHS.Designator.Entries.size();
6511 for (const Expr *E = LHSExpr; E != nullptr;) {
6512 // -- If E is of the form A.B, S(E) contains the elements of S(A)...
6513 if (auto *ME = dyn_cast<MemberExpr>(E)) {
6514 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
6515 // Note that we can't implicitly start the lifetime of a reference,
6516 // so we don't need to proceed any further if we reach one.
6517 if (!FD || FD->getType()->isReferenceType())
6518 break;
6519
6520 // ... and also contains A.B if B names a union member ...
6521 if (FD->getParent()->isUnion()) {
6522 // ... of a non-class, non-array type, or of a class type with a
6523 // trivial default constructor that is not deleted, or an array of
6524 // such types.
6525 auto *RD =
6526 FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6527 if (!RD || RD->hasTrivialDefaultConstructor())
6528 UnionPathLengths.push_back({PathLength - 1, FD});
6529 }
6530
6531 E = ME->getBase();
6532 --PathLength;
6533 assert(declaresSameEntity(FD,
6534 LHS.Designator.Entries[PathLength]
6535 .getAsBaseOrMember().getPointer()));
6536
6537 // -- If E is of the form A[B] and is interpreted as a built-in array
6538 // subscripting operator, S(E) is [S(the array operand, if any)].
6539 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
6540 // Step over an ArrayToPointerDecay implicit cast.
6541 auto *Base = ASE->getBase()->IgnoreImplicit();
6542 if (!Base->getType()->isArrayType())
6543 break;
6544
6545 E = Base;
6546 --PathLength;
6547
6548 } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6549 // Step over a derived-to-base conversion.
6550 E = ICE->getSubExpr();
6551 if (ICE->getCastKind() == CK_NoOp)
6552 continue;
6553 if (ICE->getCastKind() != CK_DerivedToBase &&
6554 ICE->getCastKind() != CK_UncheckedDerivedToBase)
6555 break;
6556 // Walk path backwards as we walk up from the base to the derived class.
6557 for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
6558 if (Elt->isVirtual()) {
6559 // A class with virtual base classes never has a trivial default
6560 // constructor, so S(E) is empty in this case.
6561 E = nullptr;
6562 break;
6563 }
6564
6565 --PathLength;
6566 assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
6567 LHS.Designator.Entries[PathLength]
6568 .getAsBaseOrMember().getPointer()));
6569 }
6570
6571 // -- Otherwise, S(E) is empty.
6572 } else {
6573 break;
6574 }
6575 }
6576
6577 // Common case: no unions' lifetimes are started.
6578 if (UnionPathLengths.empty())
6579 return true;
6580
6581 // if modification of X [would access an inactive union member], an object
6582 // of the type of X is implicitly created
6583 CompleteObject Obj =
6584 findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
6585 if (!Obj)
6586 return false;
6587 for (std::pair<unsigned, const FieldDecl *> LengthAndField :
6588 llvm::reverse(UnionPathLengths)) {
6589 // Form a designator for the union object.
6590 SubobjectDesignator D = LHS.Designator;
6591 D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
6592
6593 bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) ==
6594 ConstructionPhase::AfterBases;
6595 StartLifetimeOfUnionMemberHandler StartLifetime{
6596 Info, LHSExpr, LengthAndField.second, DuringInit};
6597 if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
6598 return false;
6599 }
6600
6601 return true;
6602}
6603
6604static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg,
6605 CallRef Call, EvalInfo &Info, bool NonNull = false,
6606 APValue **EvaluatedArg = nullptr) {
6607 LValue LV;
6608 // Create the parameter slot and register its destruction. For a vararg
6609 // argument, create a temporary.
6610 // FIXME: For calling conventions that destroy parameters in the callee,
6611 // should we consider performing destruction when the function returns
6612 // instead?
6613 APValue &V = PVD ? Info.CurrentCall->createParam(Call, PVD, LV)
6614 : Info.CurrentCall->createTemporary(Arg, Arg->getType(),
6615 ScopeKind::Call, LV);
6616 if (!EvaluateInPlace(V, Info, LV, Arg))
6617 return false;
6618
6619 // Passing a null pointer to an __attribute__((nonnull)) parameter results in
6620 // undefined behavior, so is non-constant.
6621 if (NonNull && V.isLValue() && V.isNullPointer()) {
6622 Info.CCEDiag(Arg, diag::note_non_null_attribute_failed);
6623 return false;
6624 }
6625
6626 if (EvaluatedArg)
6627 *EvaluatedArg = &V;
6628
6629 return true;
6630}
6631
6632/// Evaluate the arguments to a function call.
6633static bool EvaluateArgs(ArrayRef<const Expr *> Args, CallRef Call,
6634 EvalInfo &Info, const FunctionDecl *Callee,
6635 bool RightToLeft = false,
6636 LValue *ObjectArg = nullptr) {
6637 bool Success = true;
6638 llvm::SmallBitVector ForbiddenNullArgs;
6639 if (Callee->hasAttr<NonNullAttr>()) {
6640 ForbiddenNullArgs.resize(Args.size());
6641 for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
6642 if (!Attr->args_size()) {
6643 ForbiddenNullArgs.set();
6644 break;
6645 } else
6646 for (auto Idx : Attr->args()) {
6647 unsigned ASTIdx = Idx.getASTIndex();
6648 if (ASTIdx >= Args.size())
6649 continue;
6650 ForbiddenNullArgs[ASTIdx] = true;
6651 }
6652 }
6653 }
6654 for (unsigned I = 0; I < Args.size(); I++) {
6655 unsigned Idx = RightToLeft ? Args.size() - I - 1 : I;
6656 const ParmVarDecl *PVD =
6657 Idx < Callee->getNumParams() ? Callee->getParamDecl(Idx) : nullptr;
6658 bool NonNull = !ForbiddenNullArgs.empty() && ForbiddenNullArgs[Idx];
6659 APValue *That = nullptr;
6660 if (!EvaluateCallArg(PVD, Args[Idx], Call, Info, NonNull, &That)) {
6661 // If we're checking for a potential constant expression, evaluate all
6662 // initializers even if some of them fail.
6663 if (!Info.noteFailure())
6664 return false;
6665 Success = false;
6666 }
6667 if (PVD && PVD->isExplicitObjectParameter() && That && That->isLValue())
6668 ObjectArg->setFrom(Info.Ctx, *That);
6669 }
6670 return Success;
6671}
6672
6673/// Perform a trivial copy from Param, which is the parameter of a copy or move
6674/// constructor or assignment operator.
6675static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param,
6676 const Expr *E, APValue &Result,
6677 bool CopyObjectRepresentation) {
6678 // Find the reference argument.
6679 CallStackFrame *Frame = Info.CurrentCall;
6680 APValue *RefValue = Info.getParamSlot(Frame->Arguments, Param);
6681 if (!RefValue) {
6682 Info.FFDiag(E);
6683 return false;
6684 }
6685
6686 // Copy out the contents of the RHS object.
6687 LValue RefLValue;
6688 RefLValue.setFrom(Info.Ctx, *RefValue);
6690 Info, E, Param->getType().getNonReferenceType(), RefLValue, Result,
6691 CopyObjectRepresentation);
6692}
6693
6694/// Evaluate a function call.
6696 const FunctionDecl *Callee,
6697 const LValue *ObjectArg, const Expr *E,
6698 ArrayRef<const Expr *> Args, CallRef Call,
6699 const Stmt *Body, EvalInfo &Info,
6700 APValue &Result, const LValue *ResultSlot) {
6701 if (!Info.CheckCallLimit(CallLoc))
6702 return false;
6703
6704 CallStackFrame Frame(Info, E->getSourceRange(), Callee, ObjectArg, E, Call);
6705
6706 // For a trivial copy or move assignment, perform an APValue copy. This is
6707 // essential for unions, where the operations performed by the assignment
6708 // operator cannot be represented as statements.
6709 //
6710 // Skip this for non-union classes with no fields; in that case, the defaulted
6711 // copy/move does not actually read the object.
6712 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
6713 if (MD && MD->isDefaulted() &&
6714 (MD->getParent()->isUnion() ||
6715 (MD->isTrivial() &&
6717 unsigned ExplicitOffset = MD->isExplicitObjectMemberFunction() ? 1 : 0;
6718 assert(ObjectArg &&
6720 APValue RHSValue;
6721 if (!handleTrivialCopy(Info, MD->getParamDecl(0), Args[0], RHSValue,
6722 MD->getParent()->isUnion()))
6723 return false;
6724
6725 LValue Obj;
6726 if (!handleAssignment(Info, Args[ExplicitOffset], *ObjectArg,
6728 RHSValue))
6729 return false;
6730 ObjectArg->moveInto(Result);
6731 return true;
6732 } else if (MD && isLambdaCallOperator(MD)) {
6733 // We're in a lambda; determine the lambda capture field maps unless we're
6734 // just constexpr checking a lambda's call operator. constexpr checking is
6735 // done before the captures have been added to the closure object (unless
6736 // we're inferring constexpr-ness), so we don't have access to them in this
6737 // case. But since we don't need the captures to constexpr check, we can
6738 // just ignore them.
6739 if (!Info.checkingPotentialConstantExpression())
6740 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
6741 Frame.LambdaThisCaptureField);
6742 }
6743
6744 StmtResult Ret = {Result, ResultSlot};
6745 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
6746 if (ESR == ESR_Succeeded) {
6747 if (Callee->getReturnType()->isVoidType())
6748 return true;
6749 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
6750 }
6751 return ESR == ESR_Returned;
6752}
6753
6754/// Evaluate a constructor call.
6755static bool HandleConstructorCall(const Expr *E, const LValue &This,
6756 CallRef Call,
6758 EvalInfo &Info, APValue &Result) {
6759 SourceLocation CallLoc = E->getExprLoc();
6760 if (!Info.CheckCallLimit(CallLoc))
6761 return false;
6762
6763 const CXXRecordDecl *RD = Definition->getParent();
6764 if (RD->getNumVBases()) {
6765 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
6766 return false;
6767 }
6768
6769 EvalInfo::EvaluatingConstructorRAII EvalObj(
6770 Info,
6771 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
6772 RD->getNumBases());
6773 CallStackFrame Frame(Info, E->getSourceRange(), Definition, &This, E, Call);
6774
6775 // FIXME: Creating an APValue just to hold a nonexistent return value is
6776 // wasteful.
6777 APValue RetVal;
6778 StmtResult Ret = {RetVal, nullptr};
6779
6780 // If it's a delegating constructor, delegate.
6781 if (Definition->isDelegatingConstructor()) {
6783 if ((*I)->getInit()->isValueDependent()) {
6784 if (!EvaluateDependentExpr((*I)->getInit(), Info))
6785 return false;
6786 } else {
6787 FullExpressionRAII InitScope(Info);
6788 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) ||
6789 !InitScope.destroy())
6790 return false;
6791 }
6792 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
6793 }
6794
6795 // For a trivial copy or move constructor, perform an APValue copy. This is
6796 // essential for unions (or classes with anonymous union members), where the
6797 // operations performed by the constructor cannot be represented by
6798 // ctor-initializers.
6799 //
6800 // Skip this for empty non-union classes; we should not perform an
6801 // lvalue-to-rvalue conversion on them because their copy constructor does not
6802 // actually read them.
6803 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
6804 (Definition->getParent()->isUnion() ||
6805 (Definition->isTrivial() &&
6807 return handleTrivialCopy(Info, Definition->getParamDecl(0), E, Result,
6808 Definition->getParent()->isUnion());
6809 }
6810
6811 // Reserve space for the struct members.
6812 if (!Result.hasValue()) {
6813 if (!RD->isUnion())
6814 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
6815 std::distance(RD->field_begin(), RD->field_end()));
6816 else
6817 // A union starts with no active member.
6818 Result = APValue((const FieldDecl*)nullptr);
6819 }
6820
6821 if (RD->isInvalidDecl()) return false;
6822 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6823
6824 // A scope for temporaries lifetime-extended by reference members.
6825 BlockScopeRAII LifetimeExtendedScope(Info);
6826
6827 bool Success = true;
6828 unsigned BasesSeen = 0;
6829#ifndef NDEBUG
6831#endif
6833 auto SkipToField = [&](FieldDecl *FD, bool Indirect) {
6834 // We might be initializing the same field again if this is an indirect
6835 // field initialization.
6836 if (FieldIt == RD->field_end() ||
6837 FieldIt->getFieldIndex() > FD->getFieldIndex()) {
6838 assert(Indirect && "fields out of order?");
6839 return;
6840 }
6841
6842 // Default-initialize any fields with no explicit initializer.
6843 for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
6844 assert(FieldIt != RD->field_end() && "missing field?");
6845 if (!FieldIt->isUnnamedBitField())
6847 FieldIt->getType(),
6848 Result.getStructField(FieldIt->getFieldIndex()));
6849 }
6850 ++FieldIt;
6851 };
6852 for (const auto *I : Definition->inits()) {
6853 LValue Subobject = This;
6854 LValue SubobjectParent = This;
6855 APValue *Value = &Result;
6856
6857 // Determine the subobject to initialize.
6858 FieldDecl *FD = nullptr;
6859 if (I->isBaseInitializer()) {
6860 QualType BaseType(I->getBaseClass(), 0);
6861#ifndef NDEBUG
6862 // Non-virtual base classes are initialized in the order in the class
6863 // definition. We have already checked for virtual base classes.
6864 assert(!BaseIt->isVirtual() && "virtual base for literal type");
6865 assert(Info.Ctx.hasSameUnqualifiedType(BaseIt->getType(), BaseType) &&
6866 "base class initializers not in expected order");
6867 ++BaseIt;
6868#endif
6869 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
6870 BaseType->getAsCXXRecordDecl(), &Layout))
6871 return false;
6872 Value = &Result.getStructBase(BasesSeen++);
6873 } else if ((FD = I->getMember())) {
6874 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
6875 return false;
6876 if (RD->isUnion()) {
6877 Result = APValue(FD);
6878 Value = &Result.getUnionValue();
6879 } else {
6880 SkipToField(FD, false);
6881 Value = &Result.getStructField(FD->getFieldIndex());
6882 }
6883 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
6884 // Walk the indirect field decl's chain to find the object to initialize,
6885 // and make sure we've initialized every step along it.
6886 auto IndirectFieldChain = IFD->chain();
6887 for (auto *C : IndirectFieldChain) {
6888 FD = cast<FieldDecl>(C);
6890 // Switch the union field if it differs. This happens if we had
6891 // preceding zero-initialization, and we're now initializing a union
6892 // subobject other than the first.
6893 // FIXME: In this case, the values of the other subobjects are
6894 // specified, since zero-initialization sets all padding bits to zero.
6895 if (!Value->hasValue() ||
6896 (Value->isUnion() &&
6897 !declaresSameEntity(Value->getUnionField(), FD))) {
6898 if (CD->isUnion())
6899 *Value = APValue(FD);
6900 else
6901 // FIXME: This immediately starts the lifetime of all members of
6902 // an anonymous struct. It would be preferable to strictly start
6903 // member lifetime in initialization order.
6905 *Value);
6906 }
6907 // Store Subobject as its parent before updating it for the last element
6908 // in the chain.
6909 if (C == IndirectFieldChain.back())
6910 SubobjectParent = Subobject;
6911 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
6912 return false;
6913 if (CD->isUnion())
6914 Value = &Value->getUnionValue();
6915 else {
6916 if (C == IndirectFieldChain.front() && !RD->isUnion())
6917 SkipToField(FD, true);
6918 Value = &Value->getStructField(FD->getFieldIndex());
6919 }
6920 }
6921 } else {
6922 llvm_unreachable("unknown base initializer kind");
6923 }
6924
6925 // Need to override This for implicit field initializers as in this case
6926 // This refers to innermost anonymous struct/union containing initializer,
6927 // not to currently constructed class.
6928 const Expr *Init = I->getInit();
6929 if (Init->isValueDependent()) {
6930 if (!EvaluateDependentExpr(Init, Info))
6931 return false;
6932 } else {
6933 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
6935 FullExpressionRAII InitScope(Info);
6936 if (FD && FD->getType()->isReferenceType() &&
6937 !FD->getType()->isFunctionReferenceType()) {
6938 LValue Result;
6939 if (!EvaluateInitForDeclOfReferenceType(Info, FD, Init, Result,
6940 *Value)) {
6941 if (!Info.noteFailure())
6942 return false;
6943 Success = false;
6944 }
6945 } else if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
6946 (FD && FD->isBitField() &&
6947 !truncateBitfieldValue(Info, Init, *Value, FD))) {
6948 // If we're checking for a potential constant expression, evaluate all
6949 // initializers even if some of them fail.
6950 if (!Info.noteFailure())
6951 return false;
6952 Success = false;
6953 }
6954 }
6955
6956 // This is the point at which the dynamic type of the object becomes this
6957 // class type.
6958 if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
6959 EvalObj.finishedConstructingBases();
6960 }
6961
6962 // Default-initialize any remaining fields.
6963 if (!RD->isUnion()) {
6964 for (; FieldIt != RD->field_end(); ++FieldIt) {
6965 if (!FieldIt->isUnnamedBitField())
6967 FieldIt->getType(),
6968 Result.getStructField(FieldIt->getFieldIndex()));
6969 }
6970 }
6971
6972 EvalObj.finishedConstructingFields();
6973
6974 return Success &&
6975 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed &&
6976 LifetimeExtendedScope.destroy();
6977}
6978
6979static bool HandleConstructorCall(const Expr *E, const LValue &This,
6982 EvalInfo &Info, APValue &Result) {
6983 CallScopeRAII CallScope(Info);
6984 CallRef Call = Info.CurrentCall->createCall(Definition);
6985 if (!EvaluateArgs(Args, Call, Info, Definition))
6986 return false;
6987
6988 return HandleConstructorCall(E, This, Call, Definition, Info, Result) &&
6989 CallScope.destroy();
6990}
6991
6992static bool HandleDestructionImpl(EvalInfo &Info, SourceRange CallRange,
6993 const LValue &This, APValue &Value,
6994 QualType T) {
6995 // Objects can only be destroyed while they're within their lifetimes.
6996 // FIXME: We have no representation for whether an object of type nullptr_t
6997 // is in its lifetime; it usually doesn't matter. Perhaps we should model it
6998 // as indeterminate instead?
6999 if (Value.isAbsent() && !T->isNullPtrType()) {
7000 APValue Printable;
7001 This.moveInto(Printable);
7002 Info.FFDiag(CallRange.getBegin(),
7003 diag::note_constexpr_destroy_out_of_lifetime)
7004 << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T));
7005 return false;
7006 }
7007
7008 // Invent an expression for location purposes.
7009 // FIXME: We shouldn't need to do this.
7010 OpaqueValueExpr LocE(CallRange.getBegin(), Info.Ctx.IntTy, VK_PRValue);
7011
7012 // For arrays, destroy elements right-to-left.
7013 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) {
7014 uint64_t Size = CAT->getZExtSize();
7015 QualType ElemT = CAT->getElementType();
7016
7017 if (!CheckArraySize(Info, CAT, CallRange.getBegin()))
7018 return false;
7019
7020 LValue ElemLV = This;
7021 ElemLV.addArray(Info, &LocE, CAT);
7022 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size))
7023 return false;
7024
7025 // Ensure that we have actual array elements available to destroy; the
7026 // destructors might mutate the value, so we can't run them on the array
7027 // filler.
7028 if (Size && Size > Value.getArrayInitializedElts())
7029 expandArray(Value, Value.getArraySize() - 1);
7030
7031 // The size of the array might have been reduced by
7032 // a placement new.
7033 for (Size = Value.getArraySize(); Size != 0; --Size) {
7034 APValue &Elem = Value.getArrayInitializedElt(Size - 1);
7035 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) ||
7036 !HandleDestructionImpl(Info, CallRange, ElemLV, Elem, ElemT))
7037 return false;
7038 }
7039
7040 // End the lifetime of this array now.
7041 Value = APValue();
7042 return true;
7043 }
7044
7045 const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
7046 if (!RD) {
7047 if (T.isDestructedType()) {
7048 Info.FFDiag(CallRange.getBegin(),
7049 diag::note_constexpr_unsupported_destruction)
7050 << T;
7051 return false;
7052 }
7053
7054 Value = APValue();
7055 return true;
7056 }
7057
7058 if (RD->getNumVBases()) {
7059 Info.FFDiag(CallRange.getBegin(), diag::note_constexpr_virtual_base) << RD;
7060 return false;
7061 }
7062
7063 const CXXDestructorDecl *DD = RD->getDestructor();
7064 if (!DD && !RD->hasTrivialDestructor()) {
7065 Info.FFDiag(CallRange.getBegin());
7066 return false;
7067 }
7068
7069 if (!DD || DD->isTrivial() ||
7070 (RD->isAnonymousStructOrUnion() && RD->isUnion())) {
7071 // A trivial destructor just ends the lifetime of the object. Check for
7072 // this case before checking for a body, because we might not bother
7073 // building a body for a trivial destructor. Note that it doesn't matter
7074 // whether the destructor is constexpr in this case; all trivial
7075 // destructors are constexpr.
7076 //
7077 // If an anonymous union would be destroyed, some enclosing destructor must
7078 // have been explicitly defined, and the anonymous union destruction should
7079 // have no effect.
7080 Value = APValue();
7081 return true;
7082 }
7083
7084 if (!Info.CheckCallLimit(CallRange.getBegin()))
7085 return false;
7086
7087 const FunctionDecl *Definition = nullptr;
7088 const Stmt *Body = DD->getBody(Definition);
7089
7090 if (!CheckConstexprFunction(Info, CallRange.getBegin(), DD, Definition, Body))
7091 return false;
7092
7093 CallStackFrame Frame(Info, CallRange, Definition, &This, /*CallExpr=*/nullptr,
7094 CallRef());
7095
7096 // We're now in the period of destruction of this object.
7097 unsigned BasesLeft = RD->getNumBases();
7098 EvalInfo::EvaluatingDestructorRAII EvalObj(
7099 Info,
7100 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries});
7101 if (!EvalObj.DidInsert) {
7102 // C++2a [class.dtor]p19:
7103 // the behavior is undefined if the destructor is invoked for an object
7104 // whose lifetime has ended
7105 // (Note that formally the lifetime ends when the period of destruction
7106 // begins, even though certain uses of the object remain valid until the
7107 // period of destruction ends.)
7108 Info.FFDiag(CallRange.getBegin(), diag::note_constexpr_double_destroy);
7109 return false;
7110 }
7111
7112 // FIXME: Creating an APValue just to hold a nonexistent return value is
7113 // wasteful.
7114 APValue RetVal;
7115 StmtResult Ret = {RetVal, nullptr};
7116 if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed)
7117 return false;
7118
7119 // A union destructor does not implicitly destroy its members.
7120 if (RD->isUnion())
7121 return true;
7122
7123 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7124
7125 // We don't have a good way to iterate fields in reverse, so collect all the
7126 // fields first and then walk them backwards.
7127 SmallVector<FieldDecl*, 16> Fields(RD->fields());
7128 for (const FieldDecl *FD : llvm::reverse(Fields)) {
7129 if (FD->isUnnamedBitField())
7130 continue;
7131
7132 LValue Subobject = This;
7133 if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout))
7134 return false;
7135
7136 APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex());
7137 if (!HandleDestructionImpl(Info, CallRange, Subobject, *SubobjectValue,
7138 FD->getType()))
7139 return false;
7140 }
7141
7142 if (BasesLeft != 0)
7143 EvalObj.startedDestroyingBases();
7144
7145 // Destroy base classes in reverse order.
7146 for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) {
7147 --BasesLeft;
7148
7149 QualType BaseType = Base.getType();
7150 LValue Subobject = This;
7151 if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD,
7152 BaseType->getAsCXXRecordDecl(), &Layout))
7153 return false;
7154
7155 APValue *SubobjectValue = &Value.getStructBase(BasesLeft);
7156 if (!HandleDestructionImpl(Info, CallRange, Subobject, *SubobjectValue,
7157 BaseType))
7158 return false;
7159 }
7160 assert(BasesLeft == 0 && "NumBases was wrong?");
7161
7162 // The period of destruction ends now. The object is gone.
7163 Value = APValue();
7164 return true;
7165}
7166
7167namespace {
7168struct DestroyObjectHandler {
7169 EvalInfo &Info;
7170 const Expr *E;
7171 const LValue &This;
7172 const AccessKinds AccessKind;
7173
7174 typedef bool result_type;
7175 bool failed() { return false; }
7176 bool found(APValue &Subobj, QualType SubobjType) {
7177 return HandleDestructionImpl(Info, E->getSourceRange(), This, Subobj,
7178 SubobjType);
7179 }
7180 bool found(APSInt &Value, QualType SubobjType) {
7181 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
7182 return false;
7183 }
7184 bool found(APFloat &Value, QualType SubobjType) {
7185 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
7186 return false;
7187 }
7188};
7189}
7190
7191/// Perform a destructor or pseudo-destructor call on the given object, which
7192/// might in general not be a complete object.
7193static bool HandleDestruction(EvalInfo &Info, const Expr *E,
7194 const LValue &This, QualType ThisType) {
7195 CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType);
7196 DestroyObjectHandler Handler = {Info, E, This, AK_Destroy};
7197 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
7198}
7199
7200/// Destroy and end the lifetime of the given complete object.
7201static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
7203 QualType T) {
7204 // If we've had an unmodeled side-effect, we can't rely on mutable state
7205 // (such as the object we're about to destroy) being correct.
7206 if (Info.EvalStatus.HasSideEffects)
7207 return false;
7208
7209 LValue LV;
7210 LV.set({LVBase});
7211 return HandleDestructionImpl(Info, Loc, LV, Value, T);
7212}
7213
7214/// Perform a call to 'operator new' or to `__builtin_operator_new'.
7215static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E,
7216 LValue &Result) {
7217 if (Info.checkingPotentialConstantExpression() ||
7218 Info.SpeculativeEvaluationDepth)
7219 return false;
7220
7221 // This is permitted only within a call to std::allocator<T>::allocate.
7222 auto Caller = Info.getStdAllocatorCaller("allocate");
7223 if (!Caller) {
7224 Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20
7225 ? diag::note_constexpr_new_untyped
7226 : diag::note_constexpr_new);
7227 return false;
7228 }
7229
7230 QualType ElemType = Caller.ElemType;
7231 if (ElemType->isIncompleteType() || ElemType->isFunctionType()) {
7232 Info.FFDiag(E->getExprLoc(),
7233 diag::note_constexpr_new_not_complete_object_type)
7234 << (ElemType->isIncompleteType() ? 0 : 1) << ElemType;
7235 return false;
7236 }
7237
7238 APSInt ByteSize;
7239 if (!EvaluateInteger(E->getArg(0), ByteSize, Info))
7240 return false;
7241 bool IsNothrow = false;
7242 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) {
7243 EvaluateIgnoredValue(Info, E->getArg(I));
7244 IsNothrow |= E->getType()->isNothrowT();
7245 }
7246
7247 CharUnits ElemSize;
7248 if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize))
7249 return false;
7250 APInt Size, Remainder;
7251 APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity());
7252 APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder);
7253 if (Remainder != 0) {
7254 // This likely indicates a bug in the implementation of 'std::allocator'.
7255 Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size)
7256 << ByteSize << APSInt(ElemSizeAP, true) << ElemType;
7257 return false;
7258 }
7259
7260 if (!Info.CheckArraySize(E->getBeginLoc(), ByteSize.getActiveBits(),
7261 Size.getZExtValue(), /*Diag=*/!IsNothrow)) {
7262 if (IsNothrow) {
7263 Result.setNull(Info.Ctx, E->getType());
7264 return true;
7265 }
7266 return false;
7267 }
7268
7269 QualType AllocType = Info.Ctx.getConstantArrayType(
7270 ElemType, Size, nullptr, ArraySizeModifier::Normal, 0);
7271 APValue *Val = Info.createHeapAlloc(Caller.Call, AllocType, Result);
7272 *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue());
7273 Result.addArray(Info, E, cast<ConstantArrayType>(AllocType));
7274 return true;
7275}
7276
7278 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
7279 if (CXXDestructorDecl *DD = RD->getDestructor())
7280 return DD->isVirtual();
7281 return false;
7282}
7283
7285 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
7286 if (CXXDestructorDecl *DD = RD->getDestructor())
7287 return DD->isVirtual() ? DD->getOperatorDelete() : nullptr;
7288 return nullptr;
7289}
7290
7291/// Check that the given object is a suitable pointer to a heap allocation that
7292/// still exists and is of the right kind for the purpose of a deletion.
7293///
7294/// On success, returns the heap allocation to deallocate. On failure, produces
7295/// a diagnostic and returns std::nullopt.
7296static std::optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E,
7297 const LValue &Pointer,
7298 DynAlloc::Kind DeallocKind) {
7299 auto PointerAsString = [&] {
7300 return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy);
7301 };
7302
7303 DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>();
7304 if (!DA) {
7305 Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc)
7306 << PointerAsString();
7307 if (Pointer.Base)
7308 NoteLValueLocation(Info, Pointer.Base);
7309 return std::nullopt;
7310 }
7311
7312 std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
7313 if (!Alloc) {
7314 Info.FFDiag(E, diag::note_constexpr_double_delete);
7315 return std::nullopt;
7316 }
7317
7318 if (DeallocKind != (*Alloc)->getKind()) {
7319 QualType AllocType = Pointer.Base.getDynamicAllocType();
7320 Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch)
7321 << DeallocKind << (*Alloc)->getKind() << AllocType;
7322 NoteLValueLocation(Info, Pointer.Base);
7323 return std::nullopt;
7324 }
7325
7326 bool Subobject = false;
7327 if (DeallocKind == DynAlloc::New) {
7328 Subobject = Pointer.Designator.MostDerivedPathLength != 0 ||
7329 Pointer.Designator.isOnePastTheEnd();
7330 } else {
7331 Subobject = Pointer.Designator.Entries.size() != 1 ||
7332 Pointer.Designator.Entries[0].getAsArrayIndex() != 0;
7333 }
7334 if (Subobject) {
7335 Info.FFDiag(E, diag::note_constexpr_delete_subobject)
7336 << PointerAsString() << Pointer.Designator.isOnePastTheEnd();
7337 return std::nullopt;
7338 }
7339
7340 return Alloc;
7341}
7342
7343// Perform a call to 'operator delete' or '__builtin_operator_delete'.
7344static bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) {
7345 if (Info.checkingPotentialConstantExpression() ||
7346 Info.SpeculativeEvaluationDepth)
7347 return false;
7348
7349 // This is permitted only within a call to std::allocator<T>::deallocate.
7350 if (!Info.getStdAllocatorCaller("deallocate")) {
7351 Info.FFDiag(E->getExprLoc());
7352 return true;
7353 }
7354
7355 LValue Pointer;
7356 if (!EvaluatePointer(E->getArg(0), Pointer, Info))
7357 return false;
7358 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
7359 EvaluateIgnoredValue(Info, E->getArg(I));
7360
7361 if (Pointer.Designator.Invalid)
7362 return false;
7363
7364 // Deleting a null pointer would have no effect, but it's not permitted by
7365 // std::allocator<T>::deallocate's contract.
7366 if (Pointer.isNullPointer()) {
7367 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_deallocate_null);
7368 return true;
7369 }
7370
7371 if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator))
7372 return false;
7373
7374 Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>());
7375 return true;
7376}
7377
7378//===----------------------------------------------------------------------===//
7379// Generic Evaluation
7380//===----------------------------------------------------------------------===//
7381namespace {
7382
7383class BitCastBuffer {
7384 // FIXME: We're going to need bit-level granularity when we support
7385 // bit-fields.
7386 // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
7387 // we don't support a host or target where that is the case. Still, we should
7388 // use a more generic type in case we ever do.
7389 SmallVector<std::optional<unsigned char>, 32> Bytes;
7390
7391 static_assert(std::numeric_limits<unsigned char>::digits >= 8,
7392 "Need at least 8 bit unsigned char");
7393
7394 bool TargetIsLittleEndian;
7395
7396public:
7397 BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
7398 : Bytes(Width.getQuantity()),
7399 TargetIsLittleEndian(TargetIsLittleEndian) {}
7400
7401 [[nodiscard]] bool readObject(CharUnits Offset, CharUnits Width,
7402 SmallVectorImpl<unsigned char> &Output) const {
7403 for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
7404 // If a byte of an integer is uninitialized, then the whole integer is
7405 // uninitialized.
7406 if (!Bytes[I.getQuantity()])
7407 return false;
7408 Output.push_back(*Bytes[I.getQuantity()]);
7409 }
7410 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
7411 std::reverse(Output.begin(), Output.end());
7412 return true;
7413 }
7414
7415 void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
7416 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
7417 std::reverse(Input.begin(), Input.end());
7418
7419 size_t Index = 0;
7420 for (unsigned char Byte : Input) {
7421 assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
7422 Bytes[Offset.getQuantity() + Index] = Byte;
7423 ++Index;
7424 }
7425 }
7426
7427 size_t size() { return Bytes.size(); }
7428};
7429
7430/// Traverse an APValue to produce an BitCastBuffer, emulating how the current
7431/// target would represent the value at runtime.
7432class APValueToBufferConverter {
7433 EvalInfo &Info;
7434 BitCastBuffer Buffer;
7435 const CastExpr *BCE;
7436
7437 APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
7438 const CastExpr *BCE)
7439 : Info(Info),
7440 Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
7441 BCE(BCE) {}
7442
7443 bool visit(const APValue &Val, QualType Ty) {
7444 return visit(Val, Ty, CharUnits::fromQuantity(0));
7445 }
7446
7447 // Write out Val with type Ty into Buffer starting at Offset.
7448 bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
7449 assert((size_t)Offset.getQuantity() <= Buffer.size());
7450
7451 // As a special case, nullptr_t has an indeterminate value.
7452 if (Ty->isNullPtrType())
7453 return true;
7454
7455 // Dig through Src to find the byte at SrcOffset.
7456 switch (Val.getKind()) {
7458 case APValue::None:
7459 return true;
7460
7461 case APValue::Int:
7462 return visitInt(Val.getInt(), Ty, Offset);
7463 case APValue::Float:
7464 return visitFloat(Val.getFloat(), Ty, Offset);
7465 case APValue::Array:
7466 return visitArray(Val, Ty, Offset);
7467 case APValue::Struct:
7468 return visitRecord(Val, Ty, Offset);
7469 case APValue::Vector:
7470 return visitVector(Val, Ty, Offset);
7471
7474 return visitComplex(Val, Ty, Offset);
7476 // FIXME: We should support these.
7477
7478 case APValue::Union:
7481 Info.FFDiag(BCE->getBeginLoc(),
7482 diag::note_constexpr_bit_cast_unsupported_type)
7483 << Ty;
7484 return false;
7485 }
7486
7487 case APValue::LValue:
7488 llvm_unreachable("LValue subobject in bit_cast?");
7489 }
7490 llvm_unreachable("Unhandled APValue::ValueKind");
7491 }
7492
7493 bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
7494 const RecordDecl *RD = Ty->getAsRecordDecl();
7495 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7496
7497 // Visit the base classes.
7498 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
7499 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
7500 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
7501 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
7502 const APValue &Base = Val.getStructBase(I);
7503
7504 // Can happen in error cases.
7505 if (!Base.isStruct())
7506 return false;
7507
7508 if (!visitRecord(Base, BS.getType(),
7509 Layout.getBaseClassOffset(BaseDecl) + Offset))
7510 return false;
7511 }
7512 }
7513
7514 // Visit the fields.
7515 unsigned FieldIdx = 0;
7516 for (FieldDecl *FD : RD->fields()) {
7517 if (FD->isBitField()) {
7518 Info.FFDiag(BCE->getBeginLoc(),
7519 diag::note_constexpr_bit_cast_unsupported_bitfield);
7520 return false;
7521 }
7522
7523 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
7524
7525 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
7526 "only bit-fields can have sub-char alignment");
7527 CharUnits FieldOffset =
7528 Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
7529 QualType FieldTy = FD->getType();
7530 if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
7531 return false;
7532 ++FieldIdx;
7533 }
7534
7535 return true;
7536 }
7537
7538 bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
7539 const auto *CAT =
7540 dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
7541 if (!CAT)
7542 return false;
7543
7544 CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
7545 unsigned NumInitializedElts = Val.getArrayInitializedElts();
7546 unsigned ArraySize = Val.getArraySize();
7547 // First, initialize the initialized elements.
7548 for (unsigned I = 0; I != NumInitializedElts; ++I) {
7549 const APValue &SubObj = Val.getArrayInitializedElt(I);
7550 if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
7551 return false;
7552 }
7553
7554 // Next, initialize the rest of the array using the filler.
7555 if (Val.hasArrayFiller()) {
7556 const APValue &Filler = Val.getArrayFiller();
7557 for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
7558 if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
7559 return false;
7560 }
7561 }
7562
7563 return true;
7564 }
7565
7566 bool visitComplex(const APValue &Val, QualType Ty, CharUnits Offset) {
7567 const ComplexType *ComplexTy = Ty->castAs<ComplexType>();
7568 QualType EltTy = ComplexTy->getElementType();
7569 CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
7570 bool IsInt = Val.isComplexInt();
7571
7572 if (IsInt) {
7573 if (!visitInt(Val.getComplexIntReal(), EltTy,
7574 Offset + (0 * EltSizeChars)))
7575 return false;
7576 if (!visitInt(Val.getComplexIntImag(), EltTy,
7577 Offset + (1 * EltSizeChars)))
7578 return false;
7579 } else {
7580 if (!visitFloat(Val.getComplexFloatReal(), EltTy,
7581 Offset + (0 * EltSizeChars)))
7582 return false;
7583 if (!visitFloat(Val.getComplexFloatImag(), EltTy,
7584 Offset + (1 * EltSizeChars)))
7585 return false;
7586 }
7587
7588 return true;
7589 }
7590
7591 bool visitVector(const APValue &Val, QualType Ty, CharUnits Offset) {
7592 const VectorType *VTy = Ty->castAs<VectorType>();
7593 QualType EltTy = VTy->getElementType();
7594 unsigned NElts = VTy->getNumElements();
7595
7596 if (VTy->isPackedVectorBoolType(Info.Ctx)) {
7597 // Special handling for OpenCL bool vectors:
7598 // Since these vectors are stored as packed bits, but we can't write
7599 // individual bits to the BitCastBuffer, we'll buffer all of the elements
7600 // together into an appropriately sized APInt and write them all out at
7601 // once. Because we don't accept vectors where NElts * EltSize isn't a
7602 // multiple of the char size, there will be no padding space, so we don't
7603 // have to worry about writing data which should have been left
7604 // uninitialized.
7605 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
7606
7607 llvm::APInt Res = llvm::APInt::getZero(NElts);
7608 for (unsigned I = 0; I < NElts; ++I) {
7609 const llvm::APSInt &EltAsInt = Val.getVectorElt(I).getInt();
7610 assert(EltAsInt.isUnsigned() && EltAsInt.getBitWidth() == 1 &&
7611 "bool vector element must be 1-bit unsigned integer!");
7612
7613 Res.insertBits(EltAsInt, BigEndian ? (NElts - I - 1) : I);
7614 }
7615
7616 SmallVector<uint8_t, 8> Bytes(NElts / 8);
7617 llvm::StoreIntToMemory(Res, &*Bytes.begin(), NElts / 8);
7618 Buffer.writeObject(Offset, Bytes);
7619 } else {
7620 // Iterate over each of the elements and write them out to the buffer at
7621 // the appropriate offset.
7622 CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
7623 for (unsigned I = 0; I < NElts; ++I) {
7624 if (!visit(Val.getVectorElt(I), EltTy, Offset + I * EltSizeChars))
7625 return false;
7626 }
7627 }
7628
7629 return true;
7630 }
7631
7632 bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
7633 APSInt AdjustedVal = Val;
7634 unsigned Width = AdjustedVal.getBitWidth();
7635 if (Ty->isBooleanType()) {
7636 Width = Info.Ctx.getTypeSize(Ty);
7637 AdjustedVal = AdjustedVal.extend(Width);
7638 }
7639
7640 SmallVector<uint8_t, 8> Bytes(Width / 8);
7641 llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8);
7642 Buffer.writeObject(Offset, Bytes);
7643 return true;
7644 }
7645
7646 bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
7647 APSInt AsInt(Val.bitcastToAPInt());
7648 return visitInt(AsInt, Ty, Offset);
7649 }
7650
7651public:
7652 static std::optional<BitCastBuffer>
7653 convert(EvalInfo &Info, const APValue &Src, const CastExpr *BCE) {
7654 CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
7655 APValueToBufferConverter Converter(Info, DstSize, BCE);
7656 if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
7657 return std::nullopt;
7658 return Converter.Buffer;
7659 }
7660};
7661
7662/// Write an BitCastBuffer into an APValue.
7663class BufferToAPValueConverter {
7664 EvalInfo &Info;
7665 const BitCastBuffer &Buffer;
7666 const CastExpr *BCE;
7667
7668 BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
7669 const CastExpr *BCE)
7670 : Info(Info), Buffer(Buffer), BCE(BCE) {}
7671
7672 // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
7673 // with an invalid type, so anything left is a deficiency on our part (FIXME).
7674 // Ideally this will be unreachable.
7675 std::nullopt_t unsupportedType(QualType Ty) {
7676 Info.FFDiag(BCE->getBeginLoc(),
7677 diag::note_constexpr_bit_cast_unsupported_type)
7678 << Ty;
7679 return std::nullopt;
7680 }
7681
7682 std::nullopt_t unrepresentableValue(QualType Ty, const APSInt &Val) {
7683 Info.FFDiag(BCE->getBeginLoc(),
7684 diag::note_constexpr_bit_cast_unrepresentable_value)
7685 << Ty << toString(Val, /*Radix=*/10);
7686 return std::nullopt;
7687 }
7688
7689 std::optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
7690 const EnumType *EnumSugar = nullptr) {
7691 if (T->isNullPtrType()) {
7692 uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
7693 return APValue((Expr *)nullptr,
7694 /*Offset=*/CharUnits::fromQuantity(NullValue),
7695 APValue::NoLValuePath{}, /*IsNullPtr=*/true);
7696 }
7697
7698 CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
7699
7700 // Work around floating point types that contain unused padding bytes. This
7701 // is really just `long double` on x86, which is the only fundamental type
7702 // with padding bytes.
7703 if (T->isRealFloatingType()) {
7704 const llvm::fltSemantics &Semantics =
7705 Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
7706 unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics);
7707 assert(NumBits % 8 == 0);
7708 CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8);
7709 if (NumBytes != SizeOf)
7710 SizeOf = NumBytes;
7711 }
7712
7713 SmallVector<uint8_t, 8> Bytes;
7714 if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
7715 // If this is std::byte or unsigned char, then its okay to store an
7716 // indeterminate value.
7717 bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
7718 bool IsUChar =
7719 !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
7720 T->isSpecificBuiltinType(BuiltinType::Char_U));
7721 if (!IsStdByte && !IsUChar) {
7722 QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
7723 Info.FFDiag(BCE->getExprLoc(),
7724 diag::note_constexpr_bit_cast_indet_dest)
7725 << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
7726 return std::nullopt;
7727 }
7728
7730 }
7731
7732 APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
7733 llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
7734
7736 Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
7737
7738 unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0));
7739 if (IntWidth != Val.getBitWidth()) {
7740 APSInt Truncated = Val.trunc(IntWidth);
7741 if (Truncated.extend(Val.getBitWidth()) != Val)
7742 return unrepresentableValue(QualType(T, 0), Val);
7743 Val = Truncated;
7744 }
7745
7746 return APValue(Val);
7747 }
7748
7749 if (T->isRealFloatingType()) {
7750 const llvm::fltSemantics &Semantics =
7751 Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
7752 return APValue(APFloat(Semantics, Val));
7753 }
7754
7755 return unsupportedType(QualType(T, 0));
7756 }
7757
7758 std::optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
7759 const RecordDecl *RD = RTy->getAsRecordDecl();
7760 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7761
7762 unsigned NumBases = 0;
7763 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
7764 NumBases = CXXRD->getNumBases();
7765
7766 APValue ResultVal(APValue::UninitStruct(), NumBases,
7767 std::distance(RD->field_begin(), RD->field_end()));
7768
7769 // Visit the base classes.
7770 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
7771 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
7772 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
7773 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
7774
7775 std::optional<APValue> SubObj = visitType(
7776 BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
7777 if (!SubObj)
7778 return std::nullopt;
7779 ResultVal.getStructBase(I) = *SubObj;
7780 }
7781 }
7782
7783 // Visit the fields.
7784 unsigned FieldIdx = 0;
7785 for (FieldDecl *FD : RD->fields()) {
7786 // FIXME: We don't currently support bit-fields. A lot of the logic for
7787 // this is in CodeGen, so we need to factor it around.
7788 if (FD->isBitField()) {
7789 Info.FFDiag(BCE->getBeginLoc(),
7790 diag::note_constexpr_bit_cast_unsupported_bitfield);
7791 return std::nullopt;
7792 }
7793
7794 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
7795 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
7796
7797 CharUnits FieldOffset =
7798 CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
7799 Offset;
7800 QualType FieldTy = FD->getType();
7801 std::optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
7802 if (!SubObj)
7803 return std::nullopt;
7804 ResultVal.getStructField(FieldIdx) = *SubObj;
7805 ++FieldIdx;
7806 }
7807
7808 return ResultVal;
7809 }
7810
7811 std::optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
7812 QualType RepresentationType =
7813 Ty->getDecl()->getDefinitionOrSelf()->getIntegerType();
7814 assert(!RepresentationType.isNull() &&
7815 "enum forward decl should be caught by Sema");
7816 const auto *AsBuiltin =
7817 RepresentationType.getCanonicalType()->castAs<BuiltinType>();
7818 // Recurse into the underlying type. Treat std::byte transparently as
7819 // unsigned char.
7820 return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
7821 }
7822
7823 std::optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
7824 size_t Size = Ty->getLimitedSize();
7825 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
7826
7827 APValue ArrayValue(APValue::UninitArray(), Size, Size);
7828 for (size_t I = 0; I != Size; ++I) {
7829 std::optional<APValue> ElementValue =
7830 visitType(Ty->getElementType(), Offset + I * ElementWidth);
7831 if (!ElementValue)
7832 return std::nullopt;
7833 ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
7834 }
7835
7836 return ArrayValue;
7837 }
7838
7839 std::optional<APValue> visit(const ComplexType *Ty, CharUnits Offset) {
7840 QualType ElementType = Ty->getElementType();
7841 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(ElementType);
7842 bool IsInt = ElementType->isIntegerType();
7843
7844 std::optional<APValue> Values[2];
7845 for (unsigned I = 0; I != 2; ++I) {
7846 Values[I] = visitType(Ty->getElementType(), Offset + I * ElementWidth);
7847 if (!Values[I])
7848 return std::nullopt;
7849 }
7850
7851 if (IsInt)
7852 return APValue(Values[0]->getInt(), Values[1]->getInt());
7853 return APValue(Values[0]->getFloat(), Values[1]->getFloat());
7854 }
7855
7856 std::optional<APValue> visit(const VectorType *VTy, CharUnits Offset) {
7857 QualType EltTy = VTy->getElementType();
7858 unsigned NElts = VTy->getNumElements();
7859 unsigned EltSize =
7860 VTy->isPackedVectorBoolType(Info.Ctx) ? 1 : Info.Ctx.getTypeSize(EltTy);
7861
7862 SmallVector<APValue, 4> Elts;
7863 Elts.reserve(NElts);
7864 if (VTy->isPackedVectorBoolType(Info.Ctx)) {
7865 // Special handling for OpenCL bool vectors:
7866 // Since these vectors are stored as packed bits, but we can't read
7867 // individual bits from the BitCastBuffer, we'll buffer all of the
7868 // elements together into an appropriately sized APInt and write them all
7869 // out at once. Because we don't accept vectors where NElts * EltSize
7870 // isn't a multiple of the char size, there will be no padding space, so
7871 // we don't have to worry about reading any padding data which didn't
7872 // actually need to be accessed.
7873 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
7874
7875 SmallVector<uint8_t, 8> Bytes;
7876 Bytes.reserve(NElts / 8);
7877 if (!Buffer.readObject(Offset, CharUnits::fromQuantity(NElts / 8), Bytes))
7878 return std::nullopt;
7879
7880 APSInt SValInt(NElts, true);
7881 llvm::LoadIntFromMemory(SValInt, &*Bytes.begin(), Bytes.size());
7882
7883 for (unsigned I = 0; I < NElts; ++I) {
7884 llvm::APInt Elt =
7885 SValInt.extractBits(1, (BigEndian ? NElts - I - 1 : I) * EltSize);
7886 Elts.emplace_back(
7887 APSInt(std::move(Elt), !EltTy->isSignedIntegerType()));
7888 }
7889 } else {
7890 // Iterate over each of the elements and read them from the buffer at
7891 // the appropriate offset.
7892 CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
7893 for (unsigned I = 0; I < NElts; ++I) {
7894 std::optional<APValue> EltValue =
7895 visitType(EltTy, Offset + I * EltSizeChars);
7896 if (!EltValue)
7897 return std::nullopt;
7898 Elts.push_back(std::move(*EltValue));
7899 }
7900 }
7901
7902 return APValue(Elts.data(), Elts.size());
7903 }
7904
7905 std::optional<APValue> visit(const Type *Ty, CharUnits Offset) {
7906 return unsupportedType(QualType(Ty, 0));
7907 }
7908
7909 std::optional<APValue> visitType(QualType Ty, CharUnits Offset) {
7910 QualType Can = Ty.getCanonicalType();
7911
7912 switch (Can->getTypeClass()) {
7913#define TYPE(Class, Base) \
7914 case Type::Class: \
7915 return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
7916#define ABSTRACT_TYPE(Class, Base)
7917#define NON_CANONICAL_TYPE(Class, Base) \
7918 case Type::Class: \
7919 llvm_unreachable("non-canonical type should be impossible!");
7920#define DEPENDENT_TYPE(Class, Base) \
7921 case Type::Class: \
7922 llvm_unreachable( \
7923 "dependent types aren't supported in the constant evaluator!");
7924#define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base) \
7925 case Type::Class: \
7926 llvm_unreachable("either dependent or not canonical!");
7927#include "clang/AST/TypeNodes.inc"
7928 }
7929 llvm_unreachable("Unhandled Type::TypeClass");
7930 }
7931
7932public:
7933 // Pull out a full value of type DstType.
7934 static std::optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
7935 const CastExpr *BCE) {
7936 BufferToAPValueConverter Converter(Info, Buffer, BCE);
7937 return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
7938 }
7939};
7940
7941static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
7942 QualType Ty, EvalInfo *Info,
7943 const ASTContext &Ctx,
7944 bool CheckingDest) {
7945 Ty = Ty.getCanonicalType();
7946
7947 auto diag = [&](int Reason) {
7948 if (Info)
7949 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
7950 << CheckingDest << (Reason == 4) << Reason;
7951 return false;
7952 };
7953 auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
7954 if (Info)
7955 Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
7956 << NoteTy << Construct << Ty;
7957 return false;
7958 };
7959
7960 if (Ty->isUnionType())
7961 return diag(0);
7962 if (Ty->isPointerType())
7963 return diag(1);
7964 if (Ty->isMemberPointerType())
7965 return diag(2);
7966 if (Ty.isVolatileQualified())
7967 return diag(3);
7968
7969 if (RecordDecl *Record = Ty->getAsRecordDecl()) {
7970 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
7971 for (CXXBaseSpecifier &BS : CXXRD->bases())
7972 if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
7973 CheckingDest))
7974 return note(1, BS.getType(), BS.getBeginLoc());
7975 }
7976 for (FieldDecl *FD : Record->fields()) {
7977 if (FD->getType()->isReferenceType())
7978 return diag(4);
7979 if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
7980 CheckingDest))
7981 return note(0, FD->getType(), FD->getBeginLoc());
7982 }
7983 }
7984
7985 if (Ty->isArrayType() &&
7986 !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
7987 Info, Ctx, CheckingDest))
7988 return false;
7989
7990 if (const auto *VTy = Ty->getAs<VectorType>()) {
7991 QualType EltTy = VTy->getElementType();
7992 unsigned NElts = VTy->getNumElements();
7993 unsigned EltSize =
7994 VTy->isPackedVectorBoolType(Ctx) ? 1 : Ctx.getTypeSize(EltTy);
7995
7996 if ((NElts * EltSize) % Ctx.getCharWidth() != 0) {
7997 // The vector's size in bits is not a multiple of the target's byte size,
7998 // so its layout is unspecified. For now, we'll simply treat these cases
7999 // as unsupported (this should only be possible with OpenCL bool vectors
8000 // whose element count isn't a multiple of the byte size).
8001 if (Info)
8002 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_vector)
8003 << QualType(VTy, 0) << EltSize << NElts << Ctx.getCharWidth();
8004 return false;
8005 }
8006
8007 if (EltTy->isRealFloatingType() &&
8008 &Ctx.getFloatTypeSemantics(EltTy) == &APFloat::x87DoubleExtended()) {
8009 // The layout for x86_fp80 vectors seems to be handled very inconsistently
8010 // by both clang and LLVM, so for now we won't allow bit_casts involving
8011 // it in a constexpr context.
8012 if (Info)
8013 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_unsupported_type)
8014 << EltTy;
8015 return false;
8016 }
8017 }
8018
8019 return true;
8020}
8021
8022static bool checkBitCastConstexprEligibility(EvalInfo *Info,
8023 const ASTContext &Ctx,
8024 const CastExpr *BCE) {
8025 bool DestOK = checkBitCastConstexprEligibilityType(
8026 BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
8027 bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
8028 BCE->getBeginLoc(),
8029 BCE->getSubExpr()->getType(), Info, Ctx, false);
8030 return SourceOK;
8031}
8032
8033static bool handleRValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
8034 const APValue &SourceRValue,
8035 const CastExpr *BCE) {
8036 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
8037 "no host or target supports non 8-bit chars");
8038
8039 if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
8040 return false;
8041
8042 // Read out SourceValue into a char buffer.
8043 std::optional<BitCastBuffer> Buffer =
8044 APValueToBufferConverter::convert(Info, SourceRValue, BCE);
8045 if (!Buffer)
8046 return false;
8047
8048 // Write out the buffer into a new APValue.
8049 std::optional<APValue> MaybeDestValue =
8050 BufferToAPValueConverter::convert(Info, *Buffer, BCE);
8051 if (!MaybeDestValue)
8052 return false;
8053
8054 DestValue = std::move(*MaybeDestValue);
8055 return true;
8056}
8057
8058static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
8059 APValue &SourceValue,
8060 const CastExpr *BCE) {
8061 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
8062 "no host or target supports non 8-bit chars");
8063 assert(SourceValue.isLValue() &&
8064 "LValueToRValueBitcast requires an lvalue operand!");
8065
8066 LValue SourceLValue;
8067 APValue SourceRValue;
8068 SourceLValue.setFrom(Info.Ctx, SourceValue);
8070 Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,
8071 SourceRValue, /*WantObjectRepresentation=*/true))
8072 return false;
8073
8074 return handleRValueToRValueBitCast(Info, DestValue, SourceRValue, BCE);
8075}
8076
8077template <class Derived>
8078class ExprEvaluatorBase
8079 : public ConstStmtVisitor<Derived, bool> {
8080private:
8081 Derived &getDerived() { return static_cast<Derived&>(*this); }
8082 bool DerivedSuccess(const APValue &V, const Expr *E) {
8083 return getDerived().Success(V, E);
8084 }
8085 bool DerivedZeroInitialization(const Expr *E) {
8086 return getDerived().ZeroInitialization(E);
8087 }
8088
8089 // Check whether a conditional operator with a non-constant condition is a
8090 // potential constant expression. If neither arm is a potential constant
8091 // expression, then the conditional operator is not either.
8092 template<typename ConditionalOperator>
8093 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
8094 assert(Info.checkingPotentialConstantExpression());
8095
8096 // Speculatively evaluate both arms.
8097 SmallVector<PartialDiagnosticAt, 8> Diag;
8098 {
8099 SpeculativeEvaluationRAII Speculate(Info, &Diag);
8100 StmtVisitorTy::Visit(E->getFalseExpr());
8101 if (Diag.empty())
8102 return;
8103 }
8104
8105 {
8106 SpeculativeEvaluationRAII Speculate(Info, &Diag);
8107 Diag.clear();
8108 StmtVisitorTy::Visit(E->getTrueExpr());
8109 if (Diag.empty())
8110 return;
8111 }
8112
8113 Error(E, diag::note_constexpr_conditional_never_const);
8114 }
8115
8116
8117 template<typename ConditionalOperator>
8118 bool HandleConditionalOperator(const ConditionalOperator *E) {
8119 bool BoolResult;
8120 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
8121 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
8122 CheckPotentialConstantConditional(E);
8123 return false;
8124 }
8125 if (Info.noteFailure()) {
8126 StmtVisitorTy::Visit(E->getTrueExpr());
8127 StmtVisitorTy::Visit(E->getFalseExpr());
8128 }
8129 return false;
8130 }
8131
8132 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
8133 return StmtVisitorTy::Visit(EvalExpr);
8134 }
8135
8136protected:
8137 EvalInfo &Info;
8138 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
8139 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
8140
8141 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
8142 return Info.CCEDiag(E, D);
8143 }
8144
8145 bool ZeroInitialization(const Expr *E) { return Error(E); }
8146
8147 bool IsConstantEvaluatedBuiltinCall(const CallExpr *E) {
8148 unsigned BuiltinOp = E->getBuiltinCallee();
8149 return BuiltinOp != 0 &&
8150 Info.Ctx.BuiltinInfo.isConstantEvaluated(BuiltinOp);
8151 }
8152
8153public:
8154 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
8155
8156 EvalInfo &getEvalInfo() { return Info; }
8157
8158 /// Report an evaluation error. This should only be called when an error is
8159 /// first discovered. When propagating an error, just return false.
8160 bool Error(const Expr *E, diag::kind D) {
8161 Info.FFDiag(E, D) << E->getSourceRange();
8162 return false;
8163 }
8164 bool Error(const Expr *E) {
8165 return Error(E, diag::note_invalid_subexpr_in_const_expr);
8166 }
8167
8168 bool VisitStmt(const Stmt *) {
8169 llvm_unreachable("Expression evaluator should not be called on stmts");
8170 }
8171 bool VisitExpr(const Expr *E) {
8172 return Error(E);
8173 }
8174
8175 bool VisitEmbedExpr(const EmbedExpr *E) {
8176 const auto It = E->begin();
8177 return StmtVisitorTy::Visit(*It);
8178 }
8179
8180 bool VisitPredefinedExpr(const PredefinedExpr *E) {
8181 return StmtVisitorTy::Visit(E->getFunctionName());
8182 }
8183 bool VisitConstantExpr(const ConstantExpr *E) {
8184 if (E->hasAPValueResult())
8185 return DerivedSuccess(E->getAPValueResult(), E);
8186
8187 return StmtVisitorTy::Visit(E->getSubExpr());
8188 }
8189
8190 bool VisitParenExpr(const ParenExpr *E)
8191 { return StmtVisitorTy::Visit(E->getSubExpr()); }
8192 bool VisitUnaryExtension(const UnaryOperator *E)
8193 { return StmtVisitorTy::Visit(E->getSubExpr()); }
8194 bool VisitUnaryPlus(const UnaryOperator *E)
8195 { return StmtVisitorTy::Visit(E->getSubExpr()); }
8196 bool VisitChooseExpr(const ChooseExpr *E)
8197 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
8198 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
8199 { return StmtVisitorTy::Visit(E->getResultExpr()); }
8200 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
8201 { return StmtVisitorTy::Visit(E->getReplacement()); }
8202 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
8203 TempVersionRAII RAII(*Info.CurrentCall);
8204 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
8205 return StmtVisitorTy::Visit(E->getExpr());
8206 }
8207 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
8208 TempVersionRAII RAII(*Info.CurrentCall);
8209 // The initializer may not have been parsed yet, or might be erroneous.
8210 if (!E->getExpr())
8211 return Error(E);
8212 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
8213 return StmtVisitorTy::Visit(E->getExpr());
8214 }
8215
8216 bool VisitExprWithCleanups(const ExprWithCleanups *E) {
8217 FullExpressionRAII Scope(Info);
8218 return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy();
8219 }
8220
8221 // Temporaries are registered when created, so we don't care about
8222 // CXXBindTemporaryExpr.
8223 bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
8224 return StmtVisitorTy::Visit(E->getSubExpr());
8225 }
8226
8227 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
8228 CCEDiag(E, diag::note_constexpr_invalid_cast)
8229 << diag::ConstexprInvalidCastKind::Reinterpret;
8230 return static_cast<Derived*>(this)->VisitCastExpr(E);
8231 }
8232 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
8233 if (!Info.Ctx.getLangOpts().CPlusPlus20)
8234 CCEDiag(E, diag::note_constexpr_invalid_cast)
8235 << diag::ConstexprInvalidCastKind::Dynamic;
8236 return static_cast<Derived*>(this)->VisitCastExpr(E);
8237 }
8238 bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
8239 return static_cast<Derived*>(this)->VisitCastExpr(E);
8240 }
8241
8242 bool VisitBinaryOperator(const BinaryOperator *E) {
8243 switch (E->getOpcode()) {
8244 default:
8245 return Error(E);
8246
8247 case BO_Comma:
8248 VisitIgnoredValue(E->getLHS());
8249 return StmtVisitorTy::Visit(E->getRHS());
8250
8251 case BO_PtrMemD:
8252 case BO_PtrMemI: {
8253 LValue Obj;
8254 if (!HandleMemberPointerAccess(Info, E, Obj))
8255 return false;
8257 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
8258 return false;
8259 return DerivedSuccess(Result, E);
8260 }
8261 }
8262 }
8263
8264 bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) {
8265 return StmtVisitorTy::Visit(E->getSemanticForm());
8266 }
8267
8268 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
8269 // Evaluate and cache the common expression. We treat it as a temporary,
8270 // even though it's not quite the same thing.
8271 LValue CommonLV;
8272 if (!Evaluate(Info.CurrentCall->createTemporary(
8273 E->getOpaqueValue(),
8274 getStorageType(Info.Ctx, E->getOpaqueValue()),
8275 ScopeKind::FullExpression, CommonLV),
8276 Info, E->getCommon()))
8277 return false;
8278
8279 return HandleConditionalOperator(E);
8280 }
8281
8282 bool VisitConditionalOperator(const ConditionalOperator *E) {
8283 bool IsBcpCall = false;
8284 // If the condition (ignoring parens) is a __builtin_constant_p call,
8285 // the result is a constant expression if it can be folded without
8286 // side-effects. This is an important GNU extension. See GCC PR38377
8287 // for discussion.
8288 if (const CallExpr *CallCE =
8289 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
8290 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
8291 IsBcpCall = true;
8292
8293 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
8294 // constant expression; we can't check whether it's potentially foldable.
8295 // FIXME: We should instead treat __builtin_constant_p as non-constant if
8296 // it would return 'false' in this mode.
8297 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
8298 return false;
8299
8300 FoldConstant Fold(Info, IsBcpCall);
8301 if (!HandleConditionalOperator(E)) {
8302 Fold.keepDiagnostics();
8303 return false;
8304 }
8305
8306 return true;
8307 }
8308
8309 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
8310 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E);
8311 Value && !Value->isAbsent())
8312 return DerivedSuccess(*Value, E);
8313
8314 const Expr *Source = E->getSourceExpr();
8315 if (!Source)
8316 return Error(E);
8317 if (Source == E) {
8318 assert(0 && "OpaqueValueExpr recursively refers to itself");
8319 return Error(E);
8320 }
8321 return StmtVisitorTy::Visit(Source);
8322 }
8323
8324 bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
8325 for (const Expr *SemE : E->semantics()) {
8326 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
8327 // FIXME: We can't handle the case where an OpaqueValueExpr is also the
8328 // result expression: there could be two different LValues that would
8329 // refer to the same object in that case, and we can't model that.
8330 if (SemE == E->getResultExpr())
8331 return Error(E);
8332
8333 // Unique OVEs get evaluated if and when we encounter them when
8334 // emitting the rest of the semantic form, rather than eagerly.
8335 if (OVE->isUnique())
8336 continue;
8337
8338 LValue LV;
8339 if (!Evaluate(Info.CurrentCall->createTemporary(
8340 OVE, getStorageType(Info.Ctx, OVE),
8341 ScopeKind::FullExpression, LV),
8342 Info, OVE->getSourceExpr()))
8343 return false;
8344 } else if (SemE == E->getResultExpr()) {
8345 if (!StmtVisitorTy::Visit(SemE))
8346 return false;
8347 } else {
8348 if (!EvaluateIgnoredValue(Info, SemE))
8349 return false;
8350 }
8351 }
8352 return true;
8353 }
8354
8355 bool VisitCallExpr(const CallExpr *E) {
8357 if (!handleCallExpr(E, Result, nullptr))
8358 return false;
8359 return DerivedSuccess(Result, E);
8360 }
8361
8362 bool handleCallExpr(const CallExpr *E, APValue &Result,
8363 const LValue *ResultSlot) {
8364 CallScopeRAII CallScope(Info);
8365
8366 const Expr *Callee = E->getCallee()->IgnoreParens();
8367 QualType CalleeType = Callee->getType();
8368
8369 const FunctionDecl *FD = nullptr;
8370 LValue *This = nullptr, ObjectArg;
8371 auto Args = ArrayRef(E->getArgs(), E->getNumArgs());
8372 bool HasQualifier = false;
8373
8374 CallRef Call;
8375
8376 // Extract function decl and 'this' pointer from the callee.
8377 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
8378 const CXXMethodDecl *Member = nullptr;
8379 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
8380 // Explicit bound member calls, such as x.f() or p->g();
8381 if (!EvaluateObjectArgument(Info, ME->getBase(), ObjectArg))
8382 return false;
8383 Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
8384 if (!Member)
8385 return Error(Callee);
8386 This = &ObjectArg;
8387 HasQualifier = ME->hasQualifier();
8388 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
8389 // Indirect bound member calls ('.*' or '->*').
8390 const ValueDecl *D =
8391 HandleMemberPointerAccess(Info, BE, ObjectArg, false);
8392 if (!D)
8393 return false;
8394 Member = dyn_cast<CXXMethodDecl>(D);
8395 if (!Member)
8396 return Error(Callee);
8397 This = &ObjectArg;
8398 } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
8399 if (!Info.getLangOpts().CPlusPlus20)
8400 Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
8401 return EvaluateObjectArgument(Info, PDE->getBase(), ObjectArg) &&
8402 HandleDestruction(Info, PDE, ObjectArg, PDE->getDestroyedType());
8403 } else
8404 return Error(Callee);
8405 FD = Member;
8406 } else if (CalleeType->isFunctionPointerType()) {
8407 LValue CalleeLV;
8408 if (!EvaluatePointer(Callee, CalleeLV, Info))
8409 return false;
8410
8411 if (!CalleeLV.getLValueOffset().isZero())
8412 return Error(Callee);
8413 if (CalleeLV.isNullPointer()) {
8414 Info.FFDiag(Callee, diag::note_constexpr_null_callee)
8415 << const_cast<Expr *>(Callee);
8416 return false;
8417 }
8418 FD = dyn_cast_or_null<FunctionDecl>(
8419 CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>());
8420 if (!FD)
8421 return Error(Callee);
8422 // Don't call function pointers which have been cast to some other type.
8423 // Per DR (no number yet), the caller and callee can differ in noexcept.
8425 CalleeType->getPointeeType(), FD->getType())) {
8426 return Error(E);
8427 }
8428
8429 // For an (overloaded) assignment expression, evaluate the RHS before the
8430 // LHS.
8431 auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
8432 if (OCE && OCE->isAssignmentOp()) {
8433 assert(Args.size() == 2 && "wrong number of arguments in assignment");
8434 Call = Info.CurrentCall->createCall(FD);
8435 bool HasThis = false;
8436 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
8437 HasThis = MD->isImplicitObjectMemberFunction();
8438 if (!EvaluateArgs(HasThis ? Args.slice(1) : Args, Call, Info, FD,
8439 /*RightToLeft=*/true, &ObjectArg))
8440 return false;
8441 }
8442
8443 // Overloaded operator calls to member functions are represented as normal
8444 // calls with '*this' as the first argument.
8445 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8446 if (MD &&
8447 (MD->isImplicitObjectMemberFunction() || (OCE && MD->isStatic()))) {
8448 // FIXME: When selecting an implicit conversion for an overloaded
8449 // operator delete, we sometimes try to evaluate calls to conversion
8450 // operators without a 'this' parameter!
8451 if (Args.empty())
8452 return Error(E);
8453
8454 if (!EvaluateObjectArgument(Info, Args[0], ObjectArg))
8455 return false;
8456
8457 // If we are calling a static operator, the 'this' argument needs to be
8458 // ignored after being evaluated.
8459 if (MD->isInstance())
8460 This = &ObjectArg;
8461
8462 // If this is syntactically a simple assignment using a trivial
8463 // assignment operator, start the lifetimes of union members as needed,
8464 // per C++20 [class.union]5.
8465 if (Info.getLangOpts().CPlusPlus20 && OCE &&
8466 OCE->getOperator() == OO_Equal && MD->isTrivial() &&
8467 !MaybeHandleUnionActiveMemberChange(Info, Args[0], ObjectArg))
8468 return false;
8469
8470 Args = Args.slice(1);
8471 } else if (MD && MD->isLambdaStaticInvoker()) {
8472 // Map the static invoker for the lambda back to the call operator.
8473 // Conveniently, we don't have to slice out the 'this' argument (as is
8474 // being done for the non-static case), since a static member function
8475 // doesn't have an implicit argument passed in.
8476 const CXXRecordDecl *ClosureClass = MD->getParent();
8477 assert(
8478 ClosureClass->captures().empty() &&
8479 "Number of captures must be zero for conversion to function-ptr");
8480
8481 const CXXMethodDecl *LambdaCallOp =
8482 ClosureClass->getLambdaCallOperator();
8483
8484 // Set 'FD', the function that will be called below, to the call
8485 // operator. If the closure object represents a generic lambda, find
8486 // the corresponding specialization of the call operator.
8487
8488 if (ClosureClass->isGenericLambda()) {
8489 assert(MD->isFunctionTemplateSpecialization() &&
8490 "A generic lambda's static-invoker function must be a "
8491 "template specialization");
8492 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
8493 FunctionTemplateDecl *CallOpTemplate =
8494 LambdaCallOp->getDescribedFunctionTemplate();
8495 void *InsertPos = nullptr;
8496 FunctionDecl *CorrespondingCallOpSpecialization =
8497 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
8498 assert(CorrespondingCallOpSpecialization &&
8499 "We must always have a function call operator specialization "
8500 "that corresponds to our static invoker specialization");
8501 assert(isa<CXXMethodDecl>(CorrespondingCallOpSpecialization));
8502 FD = CorrespondingCallOpSpecialization;
8503 } else
8504 FD = LambdaCallOp;
8506 if (FD->getDeclName().isAnyOperatorNew()) {
8507 LValue Ptr;
8508 if (!HandleOperatorNewCall(Info, E, Ptr))
8509 return false;
8510 Ptr.moveInto(Result);
8511 return CallScope.destroy();
8512 } else {
8513 return HandleOperatorDeleteCall(Info, E) && CallScope.destroy();
8514 }
8515 }
8516 } else
8517 return Error(E);
8518
8519 // Evaluate the arguments now if we've not already done so.
8520 if (!Call) {
8521 Call = Info.CurrentCall->createCall(FD);
8522 if (!EvaluateArgs(Args, Call, Info, FD, /*RightToLeft*/ false,
8523 &ObjectArg))
8524 return false;
8525 }
8526
8527 SmallVector<QualType, 4> CovariantAdjustmentPath;
8528 if (This) {
8529 auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
8530 if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
8531 // Perform virtual dispatch, if necessary.
8532 FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
8533 CovariantAdjustmentPath);
8534 if (!FD)
8535 return false;
8536 } else if (NamedMember && NamedMember->isImplicitObjectMemberFunction()) {
8537 // Check that the 'this' pointer points to an object of the right type.
8538 // FIXME: If this is an assignment operator call, we may need to change
8539 // the active union member before we check this.
8540 if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
8541 return false;
8542 }
8543 }
8544
8545 // Destructor calls are different enough that they have their own codepath.
8546 if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
8547 assert(This && "no 'this' pointer for destructor call");
8548 return HandleDestruction(Info, E, *This,
8549 Info.Ctx.getCanonicalTagType(DD->getParent())) &&
8550 CallScope.destroy();
8551 }
8552
8553 const FunctionDecl *Definition = nullptr;
8554 Stmt *Body = FD->getBody(Definition);
8555 SourceLocation Loc = E->getExprLoc();
8556
8557 // Treat the object argument as `this` when evaluating defaulted
8558 // special menmber functions
8560 This = &ObjectArg;
8561
8562 if (!CheckConstexprFunction(Info, Loc, FD, Definition, Body) ||
8563 !HandleFunctionCall(Loc, Definition, This, E, Args, Call, Body, Info,
8564 Result, ResultSlot))
8565 return false;
8566
8567 if (!CovariantAdjustmentPath.empty() &&
8569 CovariantAdjustmentPath))
8570 return false;
8571
8572 return CallScope.destroy();
8573 }
8574
8575 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
8576 return StmtVisitorTy::Visit(E->getInitializer());
8577 }
8578 bool VisitInitListExpr(const InitListExpr *E) {
8579 if (E->getNumInits() == 0)
8580 return DerivedZeroInitialization(E);
8581 if (E->getNumInits() == 1)
8582 return StmtVisitorTy::Visit(E->getInit(0));
8583 return Error(E);
8584 }
8585 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
8586 return DerivedZeroInitialization(E);
8587 }
8588 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
8589 return DerivedZeroInitialization(E);
8590 }
8591 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
8592 return DerivedZeroInitialization(E);
8593 }
8594
8595 /// A member expression where the object is a prvalue is itself a prvalue.
8596 bool VisitMemberExpr(const MemberExpr *E) {
8597 assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
8598 "missing temporary materialization conversion");
8599 assert(!E->isArrow() && "missing call to bound member function?");
8600
8601 APValue Val;
8602 if (!Evaluate(Val, Info, E->getBase()))
8603 return false;
8604
8605 QualType BaseTy = E->getBase()->getType();
8606
8607 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
8608 if (!FD) return Error(E);
8609 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
8610 assert(BaseTy->castAsCanonical<RecordType>()->getDecl() ==
8611 FD->getParent()->getCanonicalDecl() &&
8612 "record / field mismatch");
8613
8614 // Note: there is no lvalue base here. But this case should only ever
8615 // happen in C or in C++98, where we cannot be evaluating a constexpr
8616 // constructor, which is the only case the base matters.
8617 CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
8618 SubobjectDesignator Designator(BaseTy);
8619 Designator.addDeclUnchecked(FD);
8620
8622 return extractSubobject(Info, E, Obj, Designator, Result) &&
8623 DerivedSuccess(Result, E);
8624 }
8625
8626 bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) {
8627 APValue Val;
8628 if (!Evaluate(Val, Info, E->getBase()))
8629 return false;
8630
8631 if (Val.isVector()) {
8632 SmallVector<uint32_t, 4> Indices;
8633 E->getEncodedElementAccess(Indices);
8634 if (Indices.size() == 1) {
8635 // Return scalar.
8636 return DerivedSuccess(Val.getVectorElt(Indices[0]), E);
8637 } else {
8638 // Construct new APValue vector.
8639 SmallVector<APValue, 4> Elts;
8640 for (unsigned I = 0; I < Indices.size(); ++I) {
8641 Elts.push_back(Val.getVectorElt(Indices[I]));
8642 }
8643 APValue VecResult(Elts.data(), Indices.size());
8644 return DerivedSuccess(VecResult, E);
8645 }
8646 }
8647
8648 return false;
8649 }
8650
8651 bool VisitCastExpr(const CastExpr *E) {
8652 switch (E->getCastKind()) {
8653 default:
8654 break;
8655
8656 case CK_AtomicToNonAtomic: {
8657 APValue AtomicVal;
8658 // This does not need to be done in place even for class/array types:
8659 // atomic-to-non-atomic conversion implies copying the object
8660 // representation.
8661 if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
8662 return false;
8663 return DerivedSuccess(AtomicVal, E);
8664 }
8665
8666 case CK_NoOp:
8667 case CK_UserDefinedConversion:
8668 return StmtVisitorTy::Visit(E->getSubExpr());
8669
8670 case CK_LValueToRValue: {
8671 LValue LVal;
8672 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
8673 return false;
8674 APValue RVal;
8675 // Note, we use the subexpression's type in order to retain cv-qualifiers.
8677 LVal, RVal))
8678 return false;
8679 return DerivedSuccess(RVal, E);
8680 }
8681 case CK_LValueToRValueBitCast: {
8682 APValue DestValue, SourceValue;
8683 if (!Evaluate(SourceValue, Info, E->getSubExpr()))
8684 return false;
8685 if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
8686 return false;
8687 return DerivedSuccess(DestValue, E);
8688 }
8689
8690 case CK_AddressSpaceConversion: {
8691 APValue Value;
8692 if (!Evaluate(Value, Info, E->getSubExpr()))
8693 return false;
8694 return DerivedSuccess(Value, E);
8695 }
8696 }
8697
8698 return Error(E);
8699 }
8700
8701 bool VisitUnaryPostInc(const UnaryOperator *UO) {
8702 return VisitUnaryPostIncDec(UO);
8703 }
8704 bool VisitUnaryPostDec(const UnaryOperator *UO) {
8705 return VisitUnaryPostIncDec(UO);
8706 }
8707 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
8708 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8709 return Error(UO);
8710
8711 LValue LVal;
8712 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
8713 return false;
8714 APValue RVal;
8715 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
8716 UO->isIncrementOp(), &RVal))
8717 return false;
8718 return DerivedSuccess(RVal, UO);
8719 }
8720
8721 bool VisitStmtExpr(const StmtExpr *E) {
8722 // We will have checked the full-expressions inside the statement expression
8723 // when they were completed, and don't need to check them again now.
8724 llvm::SaveAndRestore NotCheckingForUB(Info.CheckingForUndefinedBehavior,
8725 false);
8726
8727 const CompoundStmt *CS = E->getSubStmt();
8728 if (CS->body_empty())
8729 return true;
8730
8731 BlockScopeRAII Scope(Info);
8733 BE = CS->body_end();
8734 /**/; ++BI) {
8735 if (BI + 1 == BE) {
8736 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
8737 if (!FinalExpr) {
8738 Info.FFDiag((*BI)->getBeginLoc(),
8739 diag::note_constexpr_stmt_expr_unsupported);
8740 return false;
8741 }
8742 return this->Visit(FinalExpr) && Scope.destroy();
8743 }
8744
8746 StmtResult Result = { ReturnValue, nullptr };
8747 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
8748 if (ESR != ESR_Succeeded) {
8749 // FIXME: If the statement-expression terminated due to 'return',
8750 // 'break', or 'continue', it would be nice to propagate that to
8751 // the outer statement evaluation rather than bailing out.
8752 if (ESR != ESR_Failed)
8753 Info.FFDiag((*BI)->getBeginLoc(),
8754 diag::note_constexpr_stmt_expr_unsupported);
8755 return false;
8756 }
8757 }
8758
8759 llvm_unreachable("Return from function from the loop above.");
8760 }
8761
8762 bool VisitPackIndexingExpr(const PackIndexingExpr *E) {
8763 return StmtVisitorTy::Visit(E->getSelectedExpr());
8764 }
8765
8766 /// Visit a value which is evaluated, but whose value is ignored.
8767 void VisitIgnoredValue(const Expr *E) {
8768 EvaluateIgnoredValue(Info, E);
8769 }
8770
8771 /// Potentially visit a MemberExpr's base expression.
8772 void VisitIgnoredBaseExpression(const Expr *E) {
8773 // While MSVC doesn't evaluate the base expression, it does diagnose the
8774 // presence of side-effecting behavior.
8775 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
8776 return;
8777 VisitIgnoredValue(E);
8778 }
8779};
8780
8781} // namespace
8782
8783//===----------------------------------------------------------------------===//
8784// Common base class for lvalue and temporary evaluation.
8785//===----------------------------------------------------------------------===//
8786namespace {
8787template<class Derived>
8788class LValueExprEvaluatorBase
8789 : public ExprEvaluatorBase<Derived> {
8790protected:
8791 LValue &Result;
8792 bool InvalidBaseOK;
8793 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
8794 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
8795
8796 bool Success(APValue::LValueBase B) {
8797 Result.set(B);
8798 return true;
8799 }
8800
8801 bool evaluatePointer(const Expr *E, LValue &Result) {
8802 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
8803 }
8804
8805public:
8806 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
8807 : ExprEvaluatorBaseTy(Info), Result(Result),
8808 InvalidBaseOK(InvalidBaseOK) {}
8809
8810 bool Success(const APValue &V, const Expr *E) {
8811 Result.setFrom(this->Info.Ctx, V);
8812 return true;
8813 }
8814
8815 bool VisitMemberExpr(const MemberExpr *E) {
8816 // Handle non-static data members.
8817 QualType BaseTy;
8818 bool EvalOK;
8819 if (E->isArrow()) {
8820 EvalOK = evaluatePointer(E->getBase(), Result);
8821 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
8822 } else if (E->getBase()->isPRValue()) {
8823 assert(E->getBase()->getType()->isRecordType());
8824 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
8825 BaseTy = E->getBase()->getType();
8826 } else {
8827 EvalOK = this->Visit(E->getBase());
8828 BaseTy = E->getBase()->getType();
8829 }
8830 if (!EvalOK) {
8831 if (!InvalidBaseOK)
8832 return false;
8833 Result.setInvalid(E);
8834 return true;
8835 }
8836
8837 const ValueDecl *MD = E->getMemberDecl();
8838 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
8839 assert(BaseTy->castAsCanonical<RecordType>()->getDecl() ==
8840 FD->getParent()->getCanonicalDecl() &&
8841 "record / field mismatch");
8842 (void)BaseTy;
8843 if (!HandleLValueMember(this->Info, E, Result, FD))
8844 return false;
8845 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
8846 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
8847 return false;
8848 } else
8849 return this->Error(E);
8850
8851 if (MD->getType()->isReferenceType()) {
8852 APValue RefValue;
8853 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
8854 RefValue))
8855 return false;
8856 return Success(RefValue, E);
8857 }
8858 return true;
8859 }
8860
8861 bool VisitBinaryOperator(const BinaryOperator *E) {
8862 switch (E->getOpcode()) {
8863 default:
8864 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8865
8866 case BO_PtrMemD:
8867 case BO_PtrMemI:
8868 return HandleMemberPointerAccess(this->Info, E, Result);
8869 }
8870 }
8871
8872 bool VisitCastExpr(const CastExpr *E) {
8873 switch (E->getCastKind()) {
8874 default:
8875 return ExprEvaluatorBaseTy::VisitCastExpr(E);
8876
8877 case CK_DerivedToBase:
8878 case CK_UncheckedDerivedToBase:
8879 if (!this->Visit(E->getSubExpr()))
8880 return false;
8881
8882 // Now figure out the necessary offset to add to the base LV to get from
8883 // the derived class to the base class.
8884 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
8885 Result);
8886 }
8887 }
8888};
8889}
8890
8891//===----------------------------------------------------------------------===//
8892// LValue Evaluation
8893//
8894// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
8895// function designators (in C), decl references to void objects (in C), and
8896// temporaries (if building with -Wno-address-of-temporary).
8897//
8898// LValue evaluation produces values comprising a base expression of one of the
8899// following types:
8900// - Declarations
8901// * VarDecl
8902// * FunctionDecl
8903// - Literals
8904// * CompoundLiteralExpr in C (and in global scope in C++)
8905// * StringLiteral
8906// * PredefinedExpr
8907// * ObjCStringLiteralExpr
8908// * ObjCEncodeExpr
8909// * AddrLabelExpr
8910// * BlockExpr
8911// * CallExpr for a MakeStringConstant builtin
8912// - typeid(T) expressions, as TypeInfoLValues
8913// - Locals and temporaries
8914// * MaterializeTemporaryExpr
8915// * Any Expr, with a CallIndex indicating the function in which the temporary
8916// was evaluated, for cases where the MaterializeTemporaryExpr is missing
8917// from the AST (FIXME).
8918// * A MaterializeTemporaryExpr that has static storage duration, with no
8919// CallIndex, for a lifetime-extended temporary.
8920// * The ConstantExpr that is currently being evaluated during evaluation of an
8921// immediate invocation.
8922// plus an offset in bytes.
8923//===----------------------------------------------------------------------===//
8924namespace {
8925class LValueExprEvaluator
8926 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
8927public:
8928 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
8929 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
8930
8931 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
8932 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
8933
8934 bool VisitCallExpr(const CallExpr *E);
8935 bool VisitDeclRefExpr(const DeclRefExpr *E);
8936 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
8937 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
8938 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
8939 bool VisitMemberExpr(const MemberExpr *E);
8940 bool VisitStringLiteral(const StringLiteral *E) {
8941 return Success(APValue::LValueBase(
8942 E, 0, Info.getASTContext().getNextStringLiteralVersion()));
8943 }
8944 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
8945 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
8946 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
8947 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
8948 bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E);
8949 bool VisitUnaryDeref(const UnaryOperator *E);
8950 bool VisitUnaryReal(const UnaryOperator *E);
8951 bool VisitUnaryImag(const UnaryOperator *E);
8952 bool VisitUnaryPreInc(const UnaryOperator *UO) {
8953 return VisitUnaryPreIncDec(UO);
8954 }
8955 bool VisitUnaryPreDec(const UnaryOperator *UO) {
8956 return VisitUnaryPreIncDec(UO);
8957 }
8958 bool VisitBinAssign(const BinaryOperator *BO);
8959 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
8960
8961 bool VisitCastExpr(const CastExpr *E) {
8962 switch (E->getCastKind()) {
8963 default:
8964 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
8965
8966 case CK_LValueBitCast:
8967 this->CCEDiag(E, diag::note_constexpr_invalid_cast)
8968 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
8969 << Info.Ctx.getLangOpts().CPlusPlus;
8970 if (!Visit(E->getSubExpr()))
8971 return false;
8972 Result.Designator.setInvalid();
8973 return true;
8974
8975 case CK_BaseToDerived:
8976 if (!Visit(E->getSubExpr()))
8977 return false;
8978 return HandleBaseToDerivedCast(Info, E, Result);
8979
8980 case CK_Dynamic:
8981 if (!Visit(E->getSubExpr()))
8982 return false;
8984 }
8985 }
8986};
8987} // end anonymous namespace
8988
8989/// Get an lvalue to a field of a lambda's closure type.
8990static bool HandleLambdaCapture(EvalInfo &Info, const Expr *E, LValue &Result,
8991 const CXXMethodDecl *MD, const FieldDecl *FD,
8992 bool LValueToRValueConversion) {
8993 // Static lambda function call operators can't have captures. We already
8994 // diagnosed this, so bail out here.
8995 if (MD->isStatic()) {
8996 assert(Info.CurrentCall->This == nullptr &&
8997 "This should not be set for a static call operator");
8998 return false;
8999 }
9000
9001 // Start with 'Result' referring to the complete closure object...
9003 // Self may be passed by reference or by value.
9004 const ParmVarDecl *Self = MD->getParamDecl(0);
9005 if (Self->getType()->isReferenceType()) {
9006 APValue *RefValue = Info.getParamSlot(Info.CurrentCall->Arguments, Self);
9007 if (!RefValue->allowConstexprUnknown() || RefValue->hasValue())
9008 Result.setFrom(Info.Ctx, *RefValue);
9009 } else {
9010 const ParmVarDecl *VD = Info.CurrentCall->Arguments.getOrigParam(Self);
9011 CallStackFrame *Frame =
9012 Info.getCallFrameAndDepth(Info.CurrentCall->Arguments.CallIndex)
9013 .first;
9014 unsigned Version = Info.CurrentCall->Arguments.Version;
9015 Result.set({VD, Frame->Index, Version});
9016 }
9017 } else
9018 Result = *Info.CurrentCall->This;
9019
9020 // ... then update it to refer to the field of the closure object
9021 // that represents the capture.
9022 if (!HandleLValueMember(Info, E, Result, FD))
9023 return false;
9024
9025 // And if the field is of reference type (or if we captured '*this' by
9026 // reference), update 'Result' to refer to what
9027 // the field refers to.
9028 if (LValueToRValueConversion) {
9029 APValue RVal;
9030 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result, RVal))
9031 return false;
9032 Result.setFrom(Info.Ctx, RVal);
9033 }
9034 return true;
9035}
9036
9037/// Evaluate an expression as an lvalue. This can be legitimately called on
9038/// expressions which are not glvalues, in three cases:
9039/// * function designators in C, and
9040/// * "extern void" objects
9041/// * @selector() expressions in Objective-C
9042static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
9043 bool InvalidBaseOK) {
9044 assert(!E->isValueDependent());
9045 assert(E->isGLValue() || E->getType()->isFunctionType() ||
9047 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
9048}
9049
9050bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
9051 const ValueDecl *D = E->getDecl();
9052
9053 // If we are within a lambda's call operator, check whether the 'VD' referred
9054 // to within 'E' actually represents a lambda-capture that maps to a
9055 // data-member/field within the closure object, and if so, evaluate to the
9056 // field or what the field refers to.
9057 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
9059 // We don't always have a complete capture-map when checking or inferring if
9060 // the function call operator meets the requirements of a constexpr function
9061 // - but we don't need to evaluate the captures to determine constexprness
9062 // (dcl.constexpr C++17).
9063 if (Info.checkingPotentialConstantExpression())
9064 return false;
9065
9066 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(D)) {
9067 const auto *MD = cast<CXXMethodDecl>(Info.CurrentCall->Callee);
9068 return HandleLambdaCapture(Info, E, Result, MD, FD,
9069 FD->getType()->isReferenceType());
9070 }
9071 }
9072
9073 if (isa<FunctionDecl, MSGuidDecl, TemplateParamObjectDecl,
9074 UnnamedGlobalConstantDecl>(D))
9075 return Success(cast<ValueDecl>(D));
9076 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
9077 return VisitVarDecl(E, VD);
9078 if (const BindingDecl *BD = dyn_cast<BindingDecl>(D))
9079 return Visit(BD->getBinding());
9080 return Error(E);
9081}
9082
9083bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
9084 CallStackFrame *Frame = nullptr;
9085 unsigned Version = 0;
9086 if (VD->hasLocalStorage()) {
9087 // Only if a local variable was declared in the function currently being
9088 // evaluated, do we expect to be able to find its value in the current
9089 // frame. (Otherwise it was likely declared in an enclosing context and
9090 // could either have a valid evaluatable value (for e.g. a constexpr
9091 // variable) or be ill-formed (and trigger an appropriate evaluation
9092 // diagnostic)).
9093 CallStackFrame *CurrFrame = Info.CurrentCall;
9094 if (CurrFrame->Callee && CurrFrame->Callee->Equals(VD->getDeclContext())) {
9095 // Function parameters are stored in some caller's frame. (Usually the
9096 // immediate caller, but for an inherited constructor they may be more
9097 // distant.)
9098 if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) {
9099 if (CurrFrame->Arguments) {
9100 VD = CurrFrame->Arguments.getOrigParam(PVD);
9101 Frame =
9102 Info.getCallFrameAndDepth(CurrFrame->Arguments.CallIndex).first;
9103 Version = CurrFrame->Arguments.Version;
9104 }
9105 } else {
9106 Frame = CurrFrame;
9107 Version = CurrFrame->getCurrentTemporaryVersion(VD);
9108 }
9109 }
9110 }
9111
9112 if (!VD->getType()->isReferenceType()) {
9113 if (Frame) {
9114 Result.set({VD, Frame->Index, Version});
9115 return true;
9116 }
9117 return Success(VD);
9118 }
9119
9120 if (!Info.getLangOpts().CPlusPlus11) {
9121 Info.CCEDiag(E, diag::note_constexpr_ltor_non_integral, 1)
9122 << VD << VD->getType();
9123 Info.Note(VD->getLocation(), diag::note_declared_at);
9124 }
9125
9126 APValue *V;
9127 if (!evaluateVarDeclInit(Info, E, VD, Frame, Version, V))
9128 return false;
9129
9130 if (!V) {
9131 Result.set(VD);
9132 Result.AllowConstexprUnknown = true;
9133 return true;
9134 }
9135
9136 return Success(*V, E);
9137}
9138
9139bool LValueExprEvaluator::VisitCallExpr(const CallExpr *E) {
9140 if (!IsConstantEvaluatedBuiltinCall(E))
9141 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9142
9143 switch (E->getBuiltinCallee()) {
9144 default:
9145 return false;
9146 case Builtin::BIas_const:
9147 case Builtin::BIforward:
9148 case Builtin::BIforward_like:
9149 case Builtin::BImove:
9150 case Builtin::BImove_if_noexcept:
9151 if (cast<FunctionDecl>(E->getCalleeDecl())->isConstexpr())
9152 return Visit(E->getArg(0));
9153 break;
9154 }
9155
9156 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9157}
9158
9159bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
9160 const MaterializeTemporaryExpr *E) {
9161 // Walk through the expression to find the materialized temporary itself.
9164 const Expr *Inner =
9165 E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
9166
9167 // If we passed any comma operators, evaluate their LHSs.
9168 for (const Expr *E : CommaLHSs)
9169 if (!EvaluateIgnoredValue(Info, E))
9170 return false;
9171
9172 // A materialized temporary with static storage duration can appear within the
9173 // result of a constant expression evaluation, so we need to preserve its
9174 // value for use outside this evaluation.
9175 APValue *Value;
9176 if (E->getStorageDuration() == SD_Static) {
9177 if (Info.EvalMode == EvaluationMode::ConstantFold)
9178 return false;
9179 // FIXME: What about SD_Thread?
9180 Value = E->getOrCreateValue(true);
9181 *Value = APValue();
9182 Result.set(E);
9183 } else {
9184 Value = &Info.CurrentCall->createTemporary(
9185 E, Inner->getType(),
9186 E->getStorageDuration() == SD_FullExpression ? ScopeKind::FullExpression
9187 : ScopeKind::Block,
9188 Result);
9189 }
9190
9191 QualType Type = Inner->getType();
9192
9193 // Materialize the temporary itself.
9194 if (!EvaluateInPlace(*Value, Info, Result, Inner)) {
9195 *Value = APValue();
9196 return false;
9197 }
9198
9199 // Adjust our lvalue to refer to the desired subobject.
9200 for (unsigned I = Adjustments.size(); I != 0; /**/) {
9201 --I;
9202 switch (Adjustments[I].Kind) {
9204 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
9205 Type, Result))
9206 return false;
9207 Type = Adjustments[I].DerivedToBase.BasePath->getType();
9208 break;
9209
9211 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
9212 return false;
9213 Type = Adjustments[I].Field->getType();
9214 break;
9215
9217 if (!HandleMemberPointerAccess(this->Info, Type, Result,
9218 Adjustments[I].Ptr.RHS))
9219 return false;
9220 Type = Adjustments[I].Ptr.MPT->getPointeeType();
9221 break;
9222 }
9223 }
9224
9225 return true;
9226}
9227
9228bool
9229LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
9230 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
9231 "lvalue compound literal in c++?");
9232 APValue *Lit;
9233 // If CompountLiteral has static storage, its value can be used outside
9234 // this expression. So evaluate it once and store it in ASTContext.
9235 if (E->hasStaticStorage()) {
9236 Lit = &E->getOrCreateStaticValue(Info.Ctx);
9237 Result.set(E);
9238 // Reset any previously evaluated state, otherwise evaluation below might
9239 // fail.
9240 // FIXME: Should we just re-use the previously evaluated value instead?
9241 *Lit = APValue();
9242 } else {
9243 assert(!Info.getLangOpts().CPlusPlus);
9244 Lit = &Info.CurrentCall->createTemporary(E, E->getInitializer()->getType(),
9245 ScopeKind::Block, Result);
9246 }
9247 // FIXME: Evaluating in place isn't always right. We should figure out how to
9248 // use appropriate evaluation context here, see
9249 // clang/test/AST/static-compound-literals-reeval.cpp for a failure.
9250 if (!EvaluateInPlace(*Lit, Info, Result, E->getInitializer())) {
9251 *Lit = APValue();
9252 return false;
9253 }
9254 return true;
9255}
9256
9257bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
9258 TypeInfoLValue TypeInfo;
9259
9260 if (!E->isPotentiallyEvaluated()) {
9261 if (E->isTypeOperand())
9262 TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
9263 else
9264 TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
9265 } else {
9266 if (!Info.Ctx.getLangOpts().CPlusPlus20) {
9267 Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
9268 << E->getExprOperand()->getType()
9269 << E->getExprOperand()->getSourceRange();
9270 }
9271
9272 if (!Visit(E->getExprOperand()))
9273 return false;
9274
9275 std::optional<DynamicType> DynType =
9277 if (!DynType)
9278 return false;
9279
9280 TypeInfo = TypeInfoLValue(
9281 Info.Ctx.getCanonicalTagType(DynType->Type).getTypePtr());
9282 }
9283
9284 return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
9285}
9286
9287bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
9288 return Success(E->getGuidDecl());
9289}
9290
9291bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
9292 // Handle static data members.
9293 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
9294 VisitIgnoredBaseExpression(E->getBase());
9295 return VisitVarDecl(E, VD);
9296 }
9297
9298 // Handle static member functions.
9299 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
9300 if (MD->isStatic()) {
9301 VisitIgnoredBaseExpression(E->getBase());
9302 return Success(MD);
9303 }
9304 }
9305
9306 // Handle non-static data members.
9307 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
9308}
9309
9310bool LValueExprEvaluator::VisitExtVectorElementExpr(
9311 const ExtVectorElementExpr *E) {
9312 bool Success = true;
9313
9314 APValue Val;
9315 if (!Evaluate(Val, Info, E->getBase())) {
9316 if (!Info.noteFailure())
9317 return false;
9318 Success = false;
9319 }
9320
9322 E->getEncodedElementAccess(Indices);
9323 // FIXME: support accessing more than one element
9324 if (Indices.size() > 1)
9325 return false;
9326
9327 if (Success) {
9328 Result.setFrom(Info.Ctx, Val);
9329 QualType BaseType = E->getBase()->getType();
9330 if (E->isArrow())
9331 BaseType = BaseType->getPointeeType();
9332 const auto *VT = BaseType->castAs<VectorType>();
9333 HandleLValueVectorElement(Info, E, Result, VT->getElementType(),
9334 VT->getNumElements(), Indices[0]);
9335 }
9336
9337 return Success;
9338}
9339
9340bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
9341 if (E->getBase()->getType()->isSveVLSBuiltinType())
9342 return Error(E);
9343
9344 APSInt Index;
9345 bool Success = true;
9346
9347 if (const auto *VT = E->getBase()->getType()->getAs<VectorType>()) {
9348 APValue Val;
9349 if (!Evaluate(Val, Info, E->getBase())) {
9350 if (!Info.noteFailure())
9351 return false;
9352 Success = false;
9353 }
9354
9355 if (!EvaluateInteger(E->getIdx(), Index, Info)) {
9356 if (!Info.noteFailure())
9357 return false;
9358 Success = false;
9359 }
9360
9361 if (Success) {
9362 Result.setFrom(Info.Ctx, Val);
9363 HandleLValueVectorElement(Info, E, Result, VT->getElementType(),
9364 VT->getNumElements(), Index.getExtValue());
9365 }
9366
9367 return Success;
9368 }
9369
9370 // C++17's rules require us to evaluate the LHS first, regardless of which
9371 // side is the base.
9372 for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) {
9373 if (SubExpr == E->getBase() ? !evaluatePointer(SubExpr, Result)
9374 : !EvaluateInteger(SubExpr, Index, Info)) {
9375 if (!Info.noteFailure())
9376 return false;
9377 Success = false;
9378 }
9379 }
9380
9381 return Success &&
9382 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
9383}
9384
9385bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
9386 bool Success = evaluatePointer(E->getSubExpr(), Result);
9387 // [C++26][expr.unary.op]
9388 // If the operand points to an object or function, the result
9389 // denotes that object or function; otherwise, the behavior is undefined.
9390 // Because &(*(type*)0) is a common pattern, we do not fail the evaluation
9391 // immediately.
9393 return Success;
9395 E->getType())) ||
9396 Info.noteUndefinedBehavior();
9397}
9398
9399bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
9400 if (!Visit(E->getSubExpr()))
9401 return false;
9402 // __real is a no-op on scalar lvalues.
9403 if (E->getSubExpr()->getType()->isAnyComplexType())
9404 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
9405 return true;
9406}
9407
9408bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
9409 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
9410 "lvalue __imag__ on scalar?");
9411 if (!Visit(E->getSubExpr()))
9412 return false;
9413 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
9414 return true;
9415}
9416
9417bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
9418 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9419 return Error(UO);
9420
9421 if (!this->Visit(UO->getSubExpr()))
9422 return false;
9423
9424 return handleIncDec(
9425 this->Info, UO, Result, UO->getSubExpr()->getType(),
9426 UO->isIncrementOp(), nullptr);
9427}
9428
9429bool LValueExprEvaluator::VisitCompoundAssignOperator(
9430 const CompoundAssignOperator *CAO) {
9431 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9432 return Error(CAO);
9433
9434 bool Success = true;
9435
9436 // C++17 onwards require that we evaluate the RHS first.
9437 APValue RHS;
9438 if (!Evaluate(RHS, this->Info, CAO->getRHS())) {
9439 if (!Info.noteFailure())
9440 return false;
9441 Success = false;
9442 }
9443
9444 // The overall lvalue result is the result of evaluating the LHS.
9445 if (!this->Visit(CAO->getLHS()) || !Success)
9446 return false;
9447
9449 this->Info, CAO,
9450 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
9451 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
9452}
9453
9454bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
9455 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9456 return Error(E);
9457
9458 bool Success = true;
9459
9460 // C++17 onwards require that we evaluate the RHS first.
9461 APValue NewVal;
9462 if (!Evaluate(NewVal, this->Info, E->getRHS())) {
9463 if (!Info.noteFailure())
9464 return false;
9465 Success = false;
9466 }
9467
9468 if (!this->Visit(E->getLHS()) || !Success)
9469 return false;
9470
9471 if (Info.getLangOpts().CPlusPlus20 &&
9473 return false;
9474
9475 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
9476 NewVal);
9477}
9478
9479//===----------------------------------------------------------------------===//
9480// Pointer Evaluation
9481//===----------------------------------------------------------------------===//
9482
9483/// Convenience function. LVal's base must be a call to an alloc_size
9484/// function.
9486 const LValue &LVal,
9487 llvm::APInt &Result) {
9488 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
9489 "Can't get the size of a non alloc_size function");
9490 const auto *Base = LVal.getLValueBase().get<const Expr *>();
9491 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
9492 std::optional<llvm::APInt> Size =
9493 CE->evaluateBytesReturnedByAllocSizeCall(Ctx);
9494 if (!Size)
9495 return false;
9496
9497 Result = std::move(*Size);
9498 return true;
9499}
9500
9501/// Attempts to evaluate the given LValueBase as the result of a call to
9502/// a function with the alloc_size attribute. If it was possible to do so, this
9503/// function will return true, make Result's Base point to said function call,
9504/// and mark Result's Base as invalid.
9506 LValue &Result) {
9507 if (Base.isNull())
9508 return false;
9509
9510 // Because we do no form of static analysis, we only support const variables.
9511 //
9512 // Additionally, we can't support parameters, nor can we support static
9513 // variables (in the latter case, use-before-assign isn't UB; in the former,
9514 // we have no clue what they'll be assigned to).
9515 const auto *VD =
9516 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
9517 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
9518 return false;
9519
9520 const Expr *Init = VD->getAnyInitializer();
9521 if (!Init || Init->getType().isNull())
9522 return false;
9523
9524 const Expr *E = Init->IgnoreParens();
9525 if (!tryUnwrapAllocSizeCall(E))
9526 return false;
9527
9528 // Store E instead of E unwrapped so that the type of the LValue's base is
9529 // what the user wanted.
9530 Result.setInvalid(E);
9531
9532 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
9533 Result.addUnsizedArray(Info, E, Pointee);
9534 return true;
9535}
9536
9537namespace {
9538class PointerExprEvaluator
9539 : public ExprEvaluatorBase<PointerExprEvaluator> {
9540 LValue &Result;
9541 bool InvalidBaseOK;
9542
9543 bool Success(const Expr *E) {
9544 Result.set(E);
9545 return true;
9546 }
9547
9548 bool evaluateLValue(const Expr *E, LValue &Result) {
9549 return EvaluateLValue(E, Result, Info, InvalidBaseOK);
9550 }
9551
9552 bool evaluatePointer(const Expr *E, LValue &Result) {
9553 return EvaluatePointer(E, Result, Info, InvalidBaseOK);
9554 }
9555
9556 bool visitNonBuiltinCallExpr(const CallExpr *E);
9557public:
9558
9559 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
9560 : ExprEvaluatorBaseTy(info), Result(Result),
9561 InvalidBaseOK(InvalidBaseOK) {}
9562
9563 bool Success(const APValue &V, const Expr *E) {
9564 Result.setFrom(Info.Ctx, V);
9565 return true;
9566 }
9567 bool ZeroInitialization(const Expr *E) {
9568 Result.setNull(Info.Ctx, E->getType());
9569 return true;
9570 }
9571
9572 bool VisitBinaryOperator(const BinaryOperator *E);
9573 bool VisitCastExpr(const CastExpr* E);
9574 bool VisitUnaryAddrOf(const UnaryOperator *E);
9575 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
9576 { return Success(E); }
9577 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
9579 return Success(E);
9580 if (Info.noteFailure())
9581 EvaluateIgnoredValue(Info, E->getSubExpr());
9582 return Error(E);
9583 }
9584 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
9585 { return Success(E); }
9586 bool VisitCallExpr(const CallExpr *E);
9587 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
9588 bool VisitBlockExpr(const BlockExpr *E) {
9589 if (!E->getBlockDecl()->hasCaptures())
9590 return Success(E);
9591 return Error(E);
9592 }
9593 bool VisitCXXThisExpr(const CXXThisExpr *E) {
9594 auto DiagnoseInvalidUseOfThis = [&] {
9595 if (Info.getLangOpts().CPlusPlus11)
9596 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
9597 else
9598 Info.FFDiag(E);
9599 };
9600
9601 // Can't look at 'this' when checking a potential constant expression.
9602 if (Info.checkingPotentialConstantExpression())
9603 return false;
9604
9605 bool IsExplicitLambda =
9606 isLambdaCallWithExplicitObjectParameter(Info.CurrentCall->Callee);
9607 if (!IsExplicitLambda) {
9608 if (!Info.CurrentCall->This) {
9609 DiagnoseInvalidUseOfThis();
9610 return false;
9611 }
9612
9613 Result = *Info.CurrentCall->This;
9614 }
9615
9616 if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
9617 // Ensure we actually have captured 'this'. If something was wrong with
9618 // 'this' capture, the error would have been previously reported.
9619 // Otherwise we can be inside of a default initialization of an object
9620 // declared by lambda's body, so no need to return false.
9621 if (!Info.CurrentCall->LambdaThisCaptureField) {
9622 if (IsExplicitLambda && !Info.CurrentCall->This) {
9623 DiagnoseInvalidUseOfThis();
9624 return false;
9625 }
9626
9627 return true;
9628 }
9629
9630 const auto *MD = cast<CXXMethodDecl>(Info.CurrentCall->Callee);
9631 return HandleLambdaCapture(
9632 Info, E, Result, MD, Info.CurrentCall->LambdaThisCaptureField,
9633 Info.CurrentCall->LambdaThisCaptureField->getType()->isPointerType());
9634 }
9635 return true;
9636 }
9637
9638 bool VisitCXXNewExpr(const CXXNewExpr *E);
9639
9640 bool VisitSourceLocExpr(const SourceLocExpr *E) {
9641 assert(!E->isIntType() && "SourceLocExpr isn't a pointer type?");
9642 APValue LValResult = E->EvaluateInContext(
9643 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
9644 Result.setFrom(Info.Ctx, LValResult);
9645 return true;
9646 }
9647
9648 bool VisitEmbedExpr(const EmbedExpr *E) {
9649 llvm::report_fatal_error("Not yet implemented for ExprConstant.cpp");
9650 return true;
9651 }
9652
9653 bool VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr *E) {
9654 std::string ResultStr = E->ComputeName(Info.Ctx);
9655
9656 QualType CharTy = Info.Ctx.CharTy.withConst();
9657 APInt Size(Info.Ctx.getTypeSize(Info.Ctx.getSizeType()),
9658 ResultStr.size() + 1);
9659 QualType ArrayTy = Info.Ctx.getConstantArrayType(
9660 CharTy, Size, nullptr, ArraySizeModifier::Normal, 0);
9661
9662 StringLiteral *SL =
9663 StringLiteral::Create(Info.Ctx, ResultStr, StringLiteralKind::Ordinary,
9664 /*Pascal*/ false, ArrayTy, E->getLocation());
9665
9666 evaluateLValue(SL, Result);
9667 Result.addArray(Info, E, cast<ConstantArrayType>(ArrayTy));
9668 return true;
9669 }
9670
9671 // FIXME: Missing: @protocol, @selector
9672};
9673} // end anonymous namespace
9674
9675static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
9676 bool InvalidBaseOK) {
9677 assert(!E->isValueDependent());
9678 assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
9679 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
9680}
9681
9682bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
9683 if (E->getOpcode() != BO_Add &&
9684 E->getOpcode() != BO_Sub)
9685 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9686
9687 const Expr *PExp = E->getLHS();
9688 const Expr *IExp = E->getRHS();
9689 if (IExp->getType()->isPointerType())
9690 std::swap(PExp, IExp);
9691
9692 bool EvalPtrOK = evaluatePointer(PExp, Result);
9693 if (!EvalPtrOK && !Info.noteFailure())
9694 return false;
9695
9696 llvm::APSInt Offset;
9697 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
9698 return false;
9699
9700 if (E->getOpcode() == BO_Sub)
9701 negateAsSigned(Offset);
9702
9703 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
9704 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
9705}
9706
9707bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
9708 return evaluateLValue(E->getSubExpr(), Result);
9709}
9710
9711// Is the provided decl 'std::source_location::current'?
9713 if (!FD)
9714 return false;
9715 const IdentifierInfo *FnII = FD->getIdentifier();
9716 if (!FnII || !FnII->isStr("current"))
9717 return false;
9718
9719 const auto *RD = dyn_cast<RecordDecl>(FD->getParent());
9720 if (!RD)
9721 return false;
9722
9723 const IdentifierInfo *ClassII = RD->getIdentifier();
9724 return RD->isInStdNamespace() && ClassII && ClassII->isStr("source_location");
9725}
9726
9727bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
9728 const Expr *SubExpr = E->getSubExpr();
9729
9730 switch (E->getCastKind()) {
9731 default:
9732 break;
9733 case CK_BitCast:
9734 case CK_CPointerToObjCPointerCast:
9735 case CK_BlockPointerToObjCPointerCast:
9736 case CK_AnyPointerToBlockPointerCast:
9737 case CK_AddressSpaceConversion:
9738 if (!Visit(SubExpr))
9739 return false;
9740 if (E->getType()->isFunctionPointerType() ||
9741 SubExpr->getType()->isFunctionPointerType()) {
9742 // Casting between two function pointer types, or between a function
9743 // pointer and an object pointer, is always a reinterpret_cast.
9744 CCEDiag(E, diag::note_constexpr_invalid_cast)
9745 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
9746 << Info.Ctx.getLangOpts().CPlusPlus;
9747 Result.Designator.setInvalid();
9748 } else if (!E->getType()->isVoidPointerType()) {
9749 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
9750 // permitted in constant expressions in C++11. Bitcasts from cv void* are
9751 // also static_casts, but we disallow them as a resolution to DR1312.
9752 //
9753 // In some circumstances, we permit casting from void* to cv1 T*, when the
9754 // actual pointee object is actually a cv2 T.
9755 bool HasValidResult = !Result.InvalidBase && !Result.Designator.Invalid &&
9756 !Result.IsNullPtr;
9757 bool VoidPtrCastMaybeOK =
9758 Result.IsNullPtr ||
9759 (HasValidResult &&
9760 Info.Ctx.hasSimilarType(Result.Designator.getType(Info.Ctx),
9761 E->getType()->getPointeeType()));
9762 // 1. We'll allow it in std::allocator::allocate, and anything which that
9763 // calls.
9764 // 2. HACK 2022-03-28: Work around an issue with libstdc++'s
9765 // <source_location> header. Fixed in GCC 12 and later (2022-04-??).
9766 // We'll allow it in the body of std::source_location::current. GCC's
9767 // implementation had a parameter of type `void*`, and casts from
9768 // that back to `const __impl*` in its body.
9769 if (VoidPtrCastMaybeOK &&
9770 (Info.getStdAllocatorCaller("allocate") ||
9771 IsDeclSourceLocationCurrent(Info.CurrentCall->Callee) ||
9772 Info.getLangOpts().CPlusPlus26)) {
9773 // Permitted.
9774 } else {
9775 if (SubExpr->getType()->isVoidPointerType() &&
9776 Info.getLangOpts().CPlusPlus) {
9777 if (HasValidResult)
9778 CCEDiag(E, diag::note_constexpr_invalid_void_star_cast)
9779 << SubExpr->getType() << Info.getLangOpts().CPlusPlus26
9780 << Result.Designator.getType(Info.Ctx).getCanonicalType()
9781 << E->getType()->getPointeeType();
9782 else
9783 CCEDiag(E, diag::note_constexpr_invalid_cast)
9784 << diag::ConstexprInvalidCastKind::CastFrom
9785 << SubExpr->getType();
9786 } else
9787 CCEDiag(E, diag::note_constexpr_invalid_cast)
9788 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
9789 << Info.Ctx.getLangOpts().CPlusPlus;
9790 Result.Designator.setInvalid();
9791 }
9792 }
9793 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
9794 ZeroInitialization(E);
9795 return true;
9796
9797 case CK_DerivedToBase:
9798 case CK_UncheckedDerivedToBase:
9799 if (!evaluatePointer(E->getSubExpr(), Result))
9800 return false;
9801 if (!Result.Base && Result.Offset.isZero())
9802 return true;
9803
9804 // Now figure out the necessary offset to add to the base LV to get from
9805 // the derived class to the base class.
9806 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
9807 castAs<PointerType>()->getPointeeType(),
9808 Result);
9809
9810 case CK_BaseToDerived:
9811 if (!Visit(E->getSubExpr()))
9812 return false;
9813 if (!Result.Base && Result.Offset.isZero())
9814 return true;
9815 return HandleBaseToDerivedCast(Info, E, Result);
9816
9817 case CK_Dynamic:
9818 if (!Visit(E->getSubExpr()))
9819 return false;
9821
9822 case CK_NullToPointer:
9823 VisitIgnoredValue(E->getSubExpr());
9824 return ZeroInitialization(E);
9825
9826 case CK_IntegralToPointer: {
9827 CCEDiag(E, diag::note_constexpr_invalid_cast)
9828 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
9829 << Info.Ctx.getLangOpts().CPlusPlus;
9830
9831 APValue Value;
9832 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
9833 break;
9834
9835 if (Value.isInt()) {
9836 unsigned Size = Info.Ctx.getTypeSize(E->getType());
9837 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
9838 if (N == Info.Ctx.getTargetNullPointerValue(E->getType())) {
9839 Result.setNull(Info.Ctx, E->getType());
9840 } else {
9841 Result.Base = (Expr *)nullptr;
9842 Result.InvalidBase = false;
9843 Result.Offset = CharUnits::fromQuantity(N);
9844 Result.Designator.setInvalid();
9845 Result.IsNullPtr = false;
9846 }
9847 return true;
9848 } else {
9849 // In rare instances, the value isn't an lvalue.
9850 // For example, when the value is the difference between the addresses of
9851 // two labels. We reject that as a constant expression because we can't
9852 // compute a valid offset to convert into a pointer.
9853 if (!Value.isLValue())
9854 return false;
9855
9856 // Cast is of an lvalue, no need to change value.
9857 Result.setFrom(Info.Ctx, Value);
9858 return true;
9859 }
9860 }
9861
9862 case CK_ArrayToPointerDecay: {
9863 if (SubExpr->isGLValue()) {
9864 if (!evaluateLValue(SubExpr, Result))
9865 return false;
9866 } else {
9867 APValue &Value = Info.CurrentCall->createTemporary(
9868 SubExpr, SubExpr->getType(), ScopeKind::FullExpression, Result);
9869 if (!EvaluateInPlace(Value, Info, Result, SubExpr))
9870 return false;
9871 }
9872 // The result is a pointer to the first element of the array.
9873 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
9874 if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
9875 Result.addArray(Info, E, CAT);
9876 else
9877 Result.addUnsizedArray(Info, E, AT->getElementType());
9878 return true;
9879 }
9880
9881 case CK_FunctionToPointerDecay:
9882 return evaluateLValue(SubExpr, Result);
9883
9884 case CK_LValueToRValue: {
9885 LValue LVal;
9886 if (!evaluateLValue(E->getSubExpr(), LVal))
9887 return false;
9888
9889 APValue RVal;
9890 // Note, we use the subexpression's type in order to retain cv-qualifiers.
9892 LVal, RVal))
9893 return InvalidBaseOK &&
9894 evaluateLValueAsAllocSize(Info, LVal.Base, Result);
9895 return Success(RVal, E);
9896 }
9897 }
9898
9899 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9900}
9901
9903 UnaryExprOrTypeTrait ExprKind) {
9904 // C++ [expr.alignof]p3:
9905 // When alignof is applied to a reference type, the result is the
9906 // alignment of the referenced type.
9907 T = T.getNonReferenceType();
9908
9909 if (T.getQualifiers().hasUnaligned())
9910 return CharUnits::One();
9911
9912 const bool AlignOfReturnsPreferred =
9913 Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
9914
9915 // __alignof is defined to return the preferred alignment.
9916 // Before 8, clang returned the preferred alignment for alignof and _Alignof
9917 // as well.
9918 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
9919 return Ctx.toCharUnitsFromBits(Ctx.getPreferredTypeAlign(T.getTypePtr()));
9920 // alignof and _Alignof are defined to return the ABI alignment.
9921 else if (ExprKind == UETT_AlignOf)
9922 return Ctx.getTypeAlignInChars(T.getTypePtr());
9923 else
9924 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
9925}
9926
9928 UnaryExprOrTypeTrait ExprKind) {
9929 E = E->IgnoreParens();
9930
9931 // The kinds of expressions that we have special-case logic here for
9932 // should be kept up to date with the special checks for those
9933 // expressions in Sema.
9934
9935 // alignof decl is always accepted, even if it doesn't make sense: we default
9936 // to 1 in those cases.
9937 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9938 return Ctx.getDeclAlign(DRE->getDecl(),
9939 /*RefAsPointee*/ true);
9940
9941 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
9942 return Ctx.getDeclAlign(ME->getMemberDecl(),
9943 /*RefAsPointee*/ true);
9944
9945 return GetAlignOfType(Ctx, E->getType(), ExprKind);
9946}
9947
9948static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) {
9949 if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>())
9950 return Info.Ctx.getDeclAlign(VD);
9951 if (const auto *E = Value.Base.dyn_cast<const Expr *>())
9952 return GetAlignOfExpr(Info.Ctx, E, UETT_AlignOf);
9953 return GetAlignOfType(Info.Ctx, Value.Base.getTypeInfoType(), UETT_AlignOf);
9954}
9955
9956/// Evaluate the value of the alignment argument to __builtin_align_{up,down},
9957/// __builtin_is_aligned and __builtin_assume_aligned.
9958static bool getAlignmentArgument(const Expr *E, QualType ForType,
9959 EvalInfo &Info, APSInt &Alignment) {
9960 if (!EvaluateInteger(E, Alignment, Info))
9961 return false;
9962 if (Alignment < 0 || !Alignment.isPowerOf2()) {
9963 Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment;
9964 return false;
9965 }
9966 unsigned SrcWidth = Info.Ctx.getIntWidth(ForType);
9967 APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1));
9968 if (APSInt::compareValues(Alignment, MaxValue) > 0) {
9969 Info.FFDiag(E, diag::note_constexpr_alignment_too_big)
9970 << MaxValue << ForType << Alignment;
9971 return false;
9972 }
9973 // Ensure both alignment and source value have the same bit width so that we
9974 // don't assert when computing the resulting value.
9975 APSInt ExtAlignment =
9976 APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true);
9977 assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 &&
9978 "Alignment should not be changed by ext/trunc");
9979 Alignment = ExtAlignment;
9980 assert(Alignment.getBitWidth() == SrcWidth);
9981 return true;
9982}
9983
9984// To be clear: this happily visits unsupported builtins. Better name welcomed.
9985bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
9986 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
9987 return true;
9988
9989 if (!(InvalidBaseOK && E->getCalleeAllocSizeAttr()))
9990 return false;
9991
9992 Result.setInvalid(E);
9993 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
9994 Result.addUnsizedArray(Info, E, PointeeTy);
9995 return true;
9996}
9997
9998bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
9999 if (!IsConstantEvaluatedBuiltinCall(E))
10000 return visitNonBuiltinCallExpr(E);
10001 return VisitBuiltinCallExpr(E, E->getBuiltinCallee());
10002}
10003
10004// Determine if T is a character type for which we guarantee that
10005// sizeof(T) == 1.
10007 return T->isCharType() || T->isChar8Type();
10008}
10009
10010bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
10011 unsigned BuiltinOp) {
10012 if (IsOpaqueConstantCall(E))
10013 return Success(E);
10014
10015 switch (BuiltinOp) {
10016 case Builtin::BIaddressof:
10017 case Builtin::BI__addressof:
10018 case Builtin::BI__builtin_addressof:
10019 return evaluateLValue(E->getArg(0), Result);
10020 case Builtin::BI__builtin_assume_aligned: {
10021 // We need to be very careful here because: if the pointer does not have the
10022 // asserted alignment, then the behavior is undefined, and undefined
10023 // behavior is non-constant.
10024 if (!evaluatePointer(E->getArg(0), Result))
10025 return false;
10026
10027 LValue OffsetResult(Result);
10028 APSInt Alignment;
10029 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
10030 Alignment))
10031 return false;
10032 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
10033
10034 if (E->getNumArgs() > 2) {
10035 APSInt Offset;
10036 if (!EvaluateInteger(E->getArg(2), Offset, Info))
10037 return false;
10038
10039 int64_t AdditionalOffset = -Offset.getZExtValue();
10040 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
10041 }
10042
10043 // If there is a base object, then it must have the correct alignment.
10044 if (OffsetResult.Base) {
10045 CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult);
10046
10047 if (BaseAlignment < Align) {
10048 Result.Designator.setInvalid();
10049 CCEDiag(E->getArg(0), diag::note_constexpr_baa_insufficient_alignment)
10050 << 0 << BaseAlignment.getQuantity() << Align.getQuantity();
10051 return false;
10052 }
10053 }
10054
10055 // The offset must also have the correct alignment.
10056 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
10057 Result.Designator.setInvalid();
10058
10059 (OffsetResult.Base
10060 ? CCEDiag(E->getArg(0),
10061 diag::note_constexpr_baa_insufficient_alignment)
10062 << 1
10063 : CCEDiag(E->getArg(0),
10064 diag::note_constexpr_baa_value_insufficient_alignment))
10065 << OffsetResult.Offset.getQuantity() << Align.getQuantity();
10066 return false;
10067 }
10068
10069 return true;
10070 }
10071 case Builtin::BI__builtin_align_up:
10072 case Builtin::BI__builtin_align_down: {
10073 if (!evaluatePointer(E->getArg(0), Result))
10074 return false;
10075 APSInt Alignment;
10076 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
10077 Alignment))
10078 return false;
10079 CharUnits BaseAlignment = getBaseAlignment(Info, Result);
10080 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset);
10081 // For align_up/align_down, we can return the same value if the alignment
10082 // is known to be greater or equal to the requested value.
10083 if (PtrAlign.getQuantity() >= Alignment)
10084 return true;
10085
10086 // The alignment could be greater than the minimum at run-time, so we cannot
10087 // infer much about the resulting pointer value. One case is possible:
10088 // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we
10089 // can infer the correct index if the requested alignment is smaller than
10090 // the base alignment so we can perform the computation on the offset.
10091 if (BaseAlignment.getQuantity() >= Alignment) {
10092 assert(Alignment.getBitWidth() <= 64 &&
10093 "Cannot handle > 64-bit address-space");
10094 uint64_t Alignment64 = Alignment.getZExtValue();
10095 CharUnits NewOffset = CharUnits::fromQuantity(
10096 BuiltinOp == Builtin::BI__builtin_align_down
10097 ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64)
10098 : llvm::alignTo(Result.Offset.getQuantity(), Alignment64));
10099 Result.adjustOffset(NewOffset - Result.Offset);
10100 // TODO: diagnose out-of-bounds values/only allow for arrays?
10101 return true;
10102 }
10103 // Otherwise, we cannot constant-evaluate the result.
10104 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust)
10105 << Alignment;
10106 return false;
10107 }
10108 case Builtin::BI__builtin_operator_new:
10109 return HandleOperatorNewCall(Info, E, Result);
10110 case Builtin::BI__builtin_launder:
10111 return evaluatePointer(E->getArg(0), Result);
10112 case Builtin::BIstrchr:
10113 case Builtin::BIwcschr:
10114 case Builtin::BImemchr:
10115 case Builtin::BIwmemchr:
10116 if (Info.getLangOpts().CPlusPlus11)
10117 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
10118 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
10119 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
10120 else
10121 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
10122 [[fallthrough]];
10123 case Builtin::BI__builtin_strchr:
10124 case Builtin::BI__builtin_wcschr:
10125 case Builtin::BI__builtin_memchr:
10126 case Builtin::BI__builtin_char_memchr:
10127 case Builtin::BI__builtin_wmemchr: {
10128 if (!Visit(E->getArg(0)))
10129 return false;
10130 APSInt Desired;
10131 if (!EvaluateInteger(E->getArg(1), Desired, Info))
10132 return false;
10133 uint64_t MaxLength = uint64_t(-1);
10134 if (BuiltinOp != Builtin::BIstrchr &&
10135 BuiltinOp != Builtin::BIwcschr &&
10136 BuiltinOp != Builtin::BI__builtin_strchr &&
10137 BuiltinOp != Builtin::BI__builtin_wcschr) {
10138 APSInt N;
10139 if (!EvaluateInteger(E->getArg(2), N, Info))
10140 return false;
10141 MaxLength = N.getZExtValue();
10142 }
10143 // We cannot find the value if there are no candidates to match against.
10144 if (MaxLength == 0u)
10145 return ZeroInitialization(E);
10146 if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
10147 Result.Designator.Invalid)
10148 return false;
10149 QualType CharTy = Result.Designator.getType(Info.Ctx);
10150 bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
10151 BuiltinOp == Builtin::BI__builtin_memchr;
10152 assert(IsRawByte ||
10153 Info.Ctx.hasSameUnqualifiedType(
10154 CharTy, E->getArg(0)->getType()->getPointeeType()));
10155 // Pointers to const void may point to objects of incomplete type.
10156 if (IsRawByte && CharTy->isIncompleteType()) {
10157 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
10158 return false;
10159 }
10160 // Give up on byte-oriented matching against multibyte elements.
10161 // FIXME: We can compare the bytes in the correct order.
10162 if (IsRawByte && !isOneByteCharacterType(CharTy)) {
10163 Info.FFDiag(E, diag::note_constexpr_memchr_unsupported)
10164 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp) << CharTy;
10165 return false;
10166 }
10167 // Figure out what value we're actually looking for (after converting to
10168 // the corresponding unsigned type if necessary).
10169 uint64_t DesiredVal;
10170 bool StopAtNull = false;
10171 switch (BuiltinOp) {
10172 case Builtin::BIstrchr:
10173 case Builtin::BI__builtin_strchr:
10174 // strchr compares directly to the passed integer, and therefore
10175 // always fails if given an int that is not a char.
10176 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
10177 E->getArg(1)->getType(),
10178 Desired),
10179 Desired))
10180 return ZeroInitialization(E);
10181 StopAtNull = true;
10182 [[fallthrough]];
10183 case Builtin::BImemchr:
10184 case Builtin::BI__builtin_memchr:
10185 case Builtin::BI__builtin_char_memchr:
10186 // memchr compares by converting both sides to unsigned char. That's also
10187 // correct for strchr if we get this far (to cope with plain char being
10188 // unsigned in the strchr case).
10189 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
10190 break;
10191
10192 case Builtin::BIwcschr:
10193 case Builtin::BI__builtin_wcschr:
10194 StopAtNull = true;
10195 [[fallthrough]];
10196 case Builtin::BIwmemchr:
10197 case Builtin::BI__builtin_wmemchr:
10198 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
10199 DesiredVal = Desired.getZExtValue();
10200 break;
10201 }
10202
10203 for (; MaxLength; --MaxLength) {
10204 APValue Char;
10205 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
10206 !Char.isInt())
10207 return false;
10208 if (Char.getInt().getZExtValue() == DesiredVal)
10209 return true;
10210 if (StopAtNull && !Char.getInt())
10211 break;
10212 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
10213 return false;
10214 }
10215 // Not found: return nullptr.
10216 return ZeroInitialization(E);
10217 }
10218
10219 case Builtin::BImemcpy:
10220 case Builtin::BImemmove:
10221 case Builtin::BIwmemcpy:
10222 case Builtin::BIwmemmove:
10223 if (Info.getLangOpts().CPlusPlus11)
10224 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
10225 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
10226 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
10227 else
10228 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
10229 [[fallthrough]];
10230 case Builtin::BI__builtin_memcpy:
10231 case Builtin::BI__builtin_memmove:
10232 case Builtin::BI__builtin_wmemcpy:
10233 case Builtin::BI__builtin_wmemmove: {
10234 bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
10235 BuiltinOp == Builtin::BIwmemmove ||
10236 BuiltinOp == Builtin::BI__builtin_wmemcpy ||
10237 BuiltinOp == Builtin::BI__builtin_wmemmove;
10238 bool Move = BuiltinOp == Builtin::BImemmove ||
10239 BuiltinOp == Builtin::BIwmemmove ||
10240 BuiltinOp == Builtin::BI__builtin_memmove ||
10241 BuiltinOp == Builtin::BI__builtin_wmemmove;
10242
10243 // The result of mem* is the first argument.
10244 if (!Visit(E->getArg(0)))
10245 return false;
10246 LValue Dest = Result;
10247
10248 LValue Src;
10249 if (!EvaluatePointer(E->getArg(1), Src, Info))
10250 return false;
10251
10252 APSInt N;
10253 if (!EvaluateInteger(E->getArg(2), N, Info))
10254 return false;
10255 assert(!N.isSigned() && "memcpy and friends take an unsigned size");
10256
10257 // If the size is zero, we treat this as always being a valid no-op.
10258 // (Even if one of the src and dest pointers is null.)
10259 if (!N)
10260 return true;
10261
10262 // Otherwise, if either of the operands is null, we can't proceed. Don't
10263 // try to determine the type of the copied objects, because there aren't
10264 // any.
10265 if (!Src.Base || !Dest.Base) {
10266 APValue Val;
10267 (!Src.Base ? Src : Dest).moveInto(Val);
10268 Info.FFDiag(E, diag::note_constexpr_memcpy_null)
10269 << Move << WChar << !!Src.Base
10270 << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
10271 return false;
10272 }
10273 if (Src.Designator.Invalid || Dest.Designator.Invalid)
10274 return false;
10275
10276 // We require that Src and Dest are both pointers to arrays of
10277 // trivially-copyable type. (For the wide version, the designator will be
10278 // invalid if the designated object is not a wchar_t.)
10279 QualType T = Dest.Designator.getType(Info.Ctx);
10280 QualType SrcT = Src.Designator.getType(Info.Ctx);
10281 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
10282 // FIXME: Consider using our bit_cast implementation to support this.
10283 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
10284 return false;
10285 }
10286 if (T->isIncompleteType()) {
10287 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
10288 return false;
10289 }
10290 if (!T.isTriviallyCopyableType(Info.Ctx)) {
10291 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
10292 return false;
10293 }
10294
10295 // Figure out how many T's we're copying.
10296 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
10297 if (TSize == 0)
10298 return false;
10299 if (!WChar) {
10300 uint64_t Remainder;
10301 llvm::APInt OrigN = N;
10302 llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
10303 if (Remainder) {
10304 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
10305 << Move << WChar << 0 << T << toString(OrigN, 10, /*Signed*/false)
10306 << (unsigned)TSize;
10307 return false;
10308 }
10309 }
10310
10311 // Check that the copying will remain within the arrays, just so that we
10312 // can give a more meaningful diagnostic. This implicitly also checks that
10313 // N fits into 64 bits.
10314 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
10315 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
10316 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
10317 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
10318 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
10319 << toString(N, 10, /*Signed*/false);
10320 return false;
10321 }
10322 uint64_t NElems = N.getZExtValue();
10323 uint64_t NBytes = NElems * TSize;
10324
10325 // Check for overlap.
10326 int Direction = 1;
10327 if (HasSameBase(Src, Dest)) {
10328 uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
10329 uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
10330 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
10331 // Dest is inside the source region.
10332 if (!Move) {
10333 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
10334 return false;
10335 }
10336 // For memmove and friends, copy backwards.
10337 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
10338 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
10339 return false;
10340 Direction = -1;
10341 } else if (!Move && SrcOffset >= DestOffset &&
10342 SrcOffset - DestOffset < NBytes) {
10343 // Src is inside the destination region for memcpy: invalid.
10344 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
10345 return false;
10346 }
10347 }
10348
10349 while (true) {
10350 APValue Val;
10351 // FIXME: Set WantObjectRepresentation to true if we're copying a
10352 // char-like type?
10353 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
10354 !handleAssignment(Info, E, Dest, T, Val))
10355 return false;
10356 // Do not iterate past the last element; if we're copying backwards, that
10357 // might take us off the start of the array.
10358 if (--NElems == 0)
10359 return true;
10360 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
10361 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
10362 return false;
10363 }
10364 }
10365
10366 default:
10367 return false;
10368 }
10369}
10370
10371static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
10372 APValue &Result, const InitListExpr *ILE,
10373 QualType AllocType);
10374static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
10375 APValue &Result,
10376 const CXXConstructExpr *CCE,
10377 QualType AllocType);
10378
10379bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) {
10380 if (!Info.getLangOpts().CPlusPlus20)
10381 Info.CCEDiag(E, diag::note_constexpr_new);
10382
10383 // We cannot speculatively evaluate a delete expression.
10384 if (Info.SpeculativeEvaluationDepth)
10385 return false;
10386
10387 FunctionDecl *OperatorNew = E->getOperatorNew();
10388 QualType AllocType = E->getAllocatedType();
10389 QualType TargetType = AllocType;
10390
10391 bool IsNothrow = false;
10392 bool IsPlacement = false;
10393
10394 if (E->getNumPlacementArgs() == 1 &&
10395 E->getPlacementArg(0)->getType()->isNothrowT()) {
10396 // The only new-placement list we support is of the form (std::nothrow).
10397 //
10398 // FIXME: There is no restriction on this, but it's not clear that any
10399 // other form makes any sense. We get here for cases such as:
10400 //
10401 // new (std::align_val_t{N}) X(int)
10402 //
10403 // (which should presumably be valid only if N is a multiple of
10404 // alignof(int), and in any case can't be deallocated unless N is
10405 // alignof(X) and X has new-extended alignment).
10406 LValue Nothrow;
10407 if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info))
10408 return false;
10409 IsNothrow = true;
10410 } else if (OperatorNew->isReservedGlobalPlacementOperator()) {
10411 if (Info.CurrentCall->isStdFunction() || Info.getLangOpts().CPlusPlus26 ||
10412 (Info.CurrentCall->CanEvalMSConstexpr &&
10413 OperatorNew->hasAttr<MSConstexprAttr>())) {
10414 if (!EvaluatePointer(E->getPlacementArg(0), Result, Info))
10415 return false;
10416 if (Result.Designator.Invalid)
10417 return false;
10418 TargetType = E->getPlacementArg(0)->getType();
10419 IsPlacement = true;
10420 } else {
10421 Info.FFDiag(E, diag::note_constexpr_new_placement)
10422 << /*C++26 feature*/ 1 << E->getSourceRange();
10423 return false;
10424 }
10425 } else if (E->getNumPlacementArgs()) {
10426 Info.FFDiag(E, diag::note_constexpr_new_placement)
10427 << /*Unsupported*/ 0 << E->getSourceRange();
10428 return false;
10429 } else if (!OperatorNew
10430 ->isUsableAsGlobalAllocationFunctionInConstantEvaluation()) {
10431 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
10432 << isa<CXXMethodDecl>(OperatorNew) << OperatorNew;
10433 return false;
10434 }
10435
10436 const Expr *Init = E->getInitializer();
10437 const InitListExpr *ResizedArrayILE = nullptr;
10438 const CXXConstructExpr *ResizedArrayCCE = nullptr;
10439 bool ValueInit = false;
10440
10441 if (std::optional<const Expr *> ArraySize = E->getArraySize()) {
10442 const Expr *Stripped = *ArraySize;
10443 for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
10444 Stripped = ICE->getSubExpr())
10445 if (ICE->getCastKind() != CK_NoOp &&
10446 ICE->getCastKind() != CK_IntegralCast)
10447 break;
10448
10449 llvm::APSInt ArrayBound;
10450 if (!EvaluateInteger(Stripped, ArrayBound, Info))
10451 return false;
10452
10453 // C++ [expr.new]p9:
10454 // The expression is erroneous if:
10455 // -- [...] its value before converting to size_t [or] applying the
10456 // second standard conversion sequence is less than zero
10457 if (ArrayBound.isSigned() && ArrayBound.isNegative()) {
10458 if (IsNothrow)
10459 return ZeroInitialization(E);
10460
10461 Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative)
10462 << ArrayBound << (*ArraySize)->getSourceRange();
10463 return false;
10464 }
10465
10466 // -- its value is such that the size of the allocated object would
10467 // exceed the implementation-defined limit
10468 if (!Info.CheckArraySize(ArraySize.value()->getExprLoc(),
10470 Info.Ctx, AllocType, ArrayBound),
10471 ArrayBound.getZExtValue(), /*Diag=*/!IsNothrow)) {
10472 if (IsNothrow)
10473 return ZeroInitialization(E);
10474 return false;
10475 }
10476
10477 // -- the new-initializer is a braced-init-list and the number of
10478 // array elements for which initializers are provided [...]
10479 // exceeds the number of elements to initialize
10480 if (!Init) {
10481 // No initialization is performed.
10482 } else if (isa<CXXScalarValueInitExpr>(Init) ||
10484 ValueInit = true;
10485 } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) {
10486 ResizedArrayCCE = CCE;
10487 } else {
10488 auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType());
10489 assert(CAT && "unexpected type for array initializer");
10490
10491 unsigned Bits =
10492 std::max(CAT->getSizeBitWidth(), ArrayBound.getBitWidth());
10493 llvm::APInt InitBound = CAT->getSize().zext(Bits);
10494 llvm::APInt AllocBound = ArrayBound.zext(Bits);
10495 if (InitBound.ugt(AllocBound)) {
10496 if (IsNothrow)
10497 return ZeroInitialization(E);
10498
10499 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small)
10500 << toString(AllocBound, 10, /*Signed=*/false)
10501 << toString(InitBound, 10, /*Signed=*/false)
10502 << (*ArraySize)->getSourceRange();
10503 return false;
10504 }
10505
10506 // If the sizes differ, we must have an initializer list, and we need
10507 // special handling for this case when we initialize.
10508 if (InitBound != AllocBound)
10509 ResizedArrayILE = cast<InitListExpr>(Init);
10510 }
10511
10512 AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr,
10513 ArraySizeModifier::Normal, 0);
10514 } else {
10515 assert(!AllocType->isArrayType() &&
10516 "array allocation with non-array new");
10517 }
10518
10519 APValue *Val;
10520 if (IsPlacement) {
10522 struct FindObjectHandler {
10523 EvalInfo &Info;
10524 const Expr *E;
10525 QualType AllocType;
10526 const AccessKinds AccessKind;
10527 APValue *Value;
10528
10529 typedef bool result_type;
10530 bool failed() { return false; }
10531 bool checkConst(QualType QT) {
10532 if (QT.isConstQualified()) {
10533 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
10534 return false;
10535 }
10536 return true;
10537 }
10538 bool found(APValue &Subobj, QualType SubobjType) {
10539 if (!checkConst(SubobjType))
10540 return false;
10541 // FIXME: Reject the cases where [basic.life]p8 would not permit the
10542 // old name of the object to be used to name the new object.
10543 unsigned SubobjectSize = 1;
10544 unsigned AllocSize = 1;
10545 if (auto *CAT = dyn_cast<ConstantArrayType>(AllocType))
10546 AllocSize = CAT->getZExtSize();
10547 if (auto *CAT = dyn_cast<ConstantArrayType>(SubobjType))
10548 SubobjectSize = CAT->getZExtSize();
10549 if (SubobjectSize < AllocSize ||
10550 !Info.Ctx.hasSimilarType(Info.Ctx.getBaseElementType(SubobjType),
10551 Info.Ctx.getBaseElementType(AllocType))) {
10552 Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type)
10553 << SubobjType << AllocType;
10554 return false;
10555 }
10556 Value = &Subobj;
10557 return true;
10558 }
10559 bool found(APSInt &Value, QualType SubobjType) {
10560 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
10561 return false;
10562 }
10563 bool found(APFloat &Value, QualType SubobjType) {
10564 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
10565 return false;
10566 }
10567 } Handler = {Info, E, AllocType, AK, nullptr};
10568
10569 CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType);
10570 if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler))
10571 return false;
10572
10573 Val = Handler.Value;
10574
10575 // [basic.life]p1:
10576 // The lifetime of an object o of type T ends when [...] the storage
10577 // which the object occupies is [...] reused by an object that is not
10578 // nested within o (6.6.2).
10579 *Val = APValue();
10580 } else {
10581 // Perform the allocation and obtain a pointer to the resulting object.
10582 Val = Info.createHeapAlloc(E, AllocType, Result);
10583 if (!Val)
10584 return false;
10585 }
10586
10587 if (ValueInit) {
10588 ImplicitValueInitExpr VIE(AllocType);
10589 if (!EvaluateInPlace(*Val, Info, Result, &VIE))
10590 return false;
10591 } else if (ResizedArrayILE) {
10592 if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE,
10593 AllocType))
10594 return false;
10595 } else if (ResizedArrayCCE) {
10596 if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE,
10597 AllocType))
10598 return false;
10599 } else if (Init) {
10600 if (!EvaluateInPlace(*Val, Info, Result, Init))
10601 return false;
10602 } else if (!handleDefaultInitValue(AllocType, *Val)) {
10603 return false;
10604 }
10605
10606 // Array new returns a pointer to the first element, not a pointer to the
10607 // array.
10608 if (auto *AT = AllocType->getAsArrayTypeUnsafe())
10609 Result.addArray(Info, E, cast<ConstantArrayType>(AT));
10610
10611 return true;
10612}
10613//===----------------------------------------------------------------------===//
10614// Member Pointer Evaluation
10615//===----------------------------------------------------------------------===//
10616
10617namespace {
10618class MemberPointerExprEvaluator
10619 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
10620 MemberPtr &Result;
10621
10622 bool Success(const ValueDecl *D) {
10623 Result = MemberPtr(D);
10624 return true;
10625 }
10626public:
10627
10628 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
10629 : ExprEvaluatorBaseTy(Info), Result(Result) {}
10630
10631 bool Success(const APValue &V, const Expr *E) {
10632 Result.setFrom(V);
10633 return true;
10634 }
10635 bool ZeroInitialization(const Expr *E) {
10636 return Success((const ValueDecl*)nullptr);
10637 }
10638
10639 bool VisitCastExpr(const CastExpr *E);
10640 bool VisitUnaryAddrOf(const UnaryOperator *E);
10641};
10642} // end anonymous namespace
10643
10644static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
10645 EvalInfo &Info) {
10646 assert(!E->isValueDependent());
10647 assert(E->isPRValue() && E->getType()->isMemberPointerType());
10648 return MemberPointerExprEvaluator(Info, Result).Visit(E);
10649}
10650
10651bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
10652 switch (E->getCastKind()) {
10653 default:
10654 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10655
10656 case CK_NullToMemberPointer:
10657 VisitIgnoredValue(E->getSubExpr());
10658 return ZeroInitialization(E);
10659
10660 case CK_BaseToDerivedMemberPointer: {
10661 if (!Visit(E->getSubExpr()))
10662 return false;
10663 if (E->path_empty())
10664 return true;
10665 // Base-to-derived member pointer casts store the path in derived-to-base
10666 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
10667 // the wrong end of the derived->base arc, so stagger the path by one class.
10668 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
10669 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
10670 PathI != PathE; ++PathI) {
10671 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
10672 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
10673 if (!Result.castToDerived(Derived))
10674 return Error(E);
10675 }
10676 if (!Result.castToDerived(E->getType()
10677 ->castAs<MemberPointerType>()
10678 ->getMostRecentCXXRecordDecl()))
10679 return Error(E);
10680 return true;
10681 }
10682
10683 case CK_DerivedToBaseMemberPointer:
10684 if (!Visit(E->getSubExpr()))
10685 return false;
10686 for (CastExpr::path_const_iterator PathI = E->path_begin(),
10687 PathE = E->path_end(); PathI != PathE; ++PathI) {
10688 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
10689 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
10690 if (!Result.castToBase(Base))
10691 return Error(E);
10692 }
10693 return true;
10694 }
10695}
10696
10697bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
10698 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
10699 // member can be formed.
10700 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
10701}
10702
10703//===----------------------------------------------------------------------===//
10704// Record Evaluation
10705//===----------------------------------------------------------------------===//
10706
10707namespace {
10708 class RecordExprEvaluator
10709 : public ExprEvaluatorBase<RecordExprEvaluator> {
10710 const LValue &This;
10711 APValue &Result;
10712 public:
10713
10714 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
10715 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
10716
10717 bool Success(const APValue &V, const Expr *E) {
10718 Result = V;
10719 return true;
10720 }
10721 bool ZeroInitialization(const Expr *E) {
10722 return ZeroInitialization(E, E->getType());
10723 }
10724 bool ZeroInitialization(const Expr *E, QualType T);
10725
10726 bool VisitCallExpr(const CallExpr *E) {
10727 return handleCallExpr(E, Result, &This);
10728 }
10729 bool VisitCastExpr(const CastExpr *E);
10730 bool VisitInitListExpr(const InitListExpr *E);
10731 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
10732 return VisitCXXConstructExpr(E, E->getType());
10733 }
10734 bool VisitLambdaExpr(const LambdaExpr *E);
10735 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
10736 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
10737 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
10738 bool VisitBinCmp(const BinaryOperator *E);
10739 bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E);
10740 bool VisitCXXParenListOrInitListExpr(const Expr *ExprToVisit,
10741 ArrayRef<Expr *> Args);
10742 };
10743}
10744
10745/// Perform zero-initialization on an object of non-union class type.
10746/// C++11 [dcl.init]p5:
10747/// To zero-initialize an object or reference of type T means:
10748/// [...]
10749/// -- if T is a (possibly cv-qualified) non-union class type,
10750/// each non-static data member and each base-class subobject is
10751/// zero-initialized
10752static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
10753 const RecordDecl *RD,
10754 const LValue &This, APValue &Result) {
10755 assert(!RD->isUnion() && "Expected non-union class type");
10756 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
10757 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
10758 std::distance(RD->field_begin(), RD->field_end()));
10759
10760 if (RD->isInvalidDecl()) return false;
10761 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
10762
10763 if (CD) {
10764 unsigned Index = 0;
10766 End = CD->bases_end(); I != End; ++I, ++Index) {
10767 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
10768 LValue Subobject = This;
10769 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
10770 return false;
10771 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
10772 Result.getStructBase(Index)))
10773 return false;
10774 }
10775 }
10776
10777 for (const auto *I : RD->fields()) {
10778 // -- if T is a reference type, no initialization is performed.
10779 if (I->isUnnamedBitField() || I->getType()->isReferenceType())
10780 continue;
10781
10782 LValue Subobject = This;
10783 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
10784 return false;
10785
10786 ImplicitValueInitExpr VIE(I->getType());
10787 if (!EvaluateInPlace(
10788 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
10789 return false;
10790 }
10791
10792 return true;
10793}
10794
10795bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
10796 const auto *RD = T->castAsRecordDecl();
10797 if (RD->isInvalidDecl()) return false;
10798 if (RD->isUnion()) {
10799 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
10800 // object's first non-static named data member is zero-initialized
10802 while (I != RD->field_end() && (*I)->isUnnamedBitField())
10803 ++I;
10804 if (I == RD->field_end()) {
10805 Result = APValue((const FieldDecl*)nullptr);
10806 return true;
10807 }
10808
10809 LValue Subobject = This;
10810 if (!HandleLValueMember(Info, E, Subobject, *I))
10811 return false;
10812 Result = APValue(*I);
10813 ImplicitValueInitExpr VIE(I->getType());
10814 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
10815 }
10816
10817 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
10818 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
10819 return false;
10820 }
10821
10822 return HandleClassZeroInitialization(Info, E, RD, This, Result);
10823}
10824
10825bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
10826 switch (E->getCastKind()) {
10827 default:
10828 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10829
10830 case CK_ConstructorConversion:
10831 return Visit(E->getSubExpr());
10832
10833 case CK_DerivedToBase:
10834 case CK_UncheckedDerivedToBase: {
10835 APValue DerivedObject;
10836 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
10837 return false;
10838 if (!DerivedObject.isStruct())
10839 return Error(E->getSubExpr());
10840
10841 // Derived-to-base rvalue conversion: just slice off the derived part.
10842 APValue *Value = &DerivedObject;
10843 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
10844 for (CastExpr::path_const_iterator PathI = E->path_begin(),
10845 PathE = E->path_end(); PathI != PathE; ++PathI) {
10846 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
10847 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
10848 Value = &Value->getStructBase(getBaseIndex(RD, Base));
10849 RD = Base;
10850 }
10851 Result = *Value;
10852 return true;
10853 }
10854 }
10855}
10856
10857bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
10858 if (E->isTransparent())
10859 return Visit(E->getInit(0));
10860 return VisitCXXParenListOrInitListExpr(E, E->inits());
10861}
10862
10863bool RecordExprEvaluator::VisitCXXParenListOrInitListExpr(
10864 const Expr *ExprToVisit, ArrayRef<Expr *> Args) {
10865 const auto *RD = ExprToVisit->getType()->castAsRecordDecl();
10866 if (RD->isInvalidDecl()) return false;
10867 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
10868 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
10869
10870 EvalInfo::EvaluatingConstructorRAII EvalObj(
10871 Info,
10872 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
10873 CXXRD && CXXRD->getNumBases());
10874
10875 if (RD->isUnion()) {
10876 const FieldDecl *Field;
10877 if (auto *ILE = dyn_cast<InitListExpr>(ExprToVisit)) {
10878 Field = ILE->getInitializedFieldInUnion();
10879 } else if (auto *PLIE = dyn_cast<CXXParenListInitExpr>(ExprToVisit)) {
10880 Field = PLIE->getInitializedFieldInUnion();
10881 } else {
10882 llvm_unreachable(
10883 "Expression is neither an init list nor a C++ paren list");
10884 }
10885
10886 Result = APValue(Field);
10887 if (!Field)
10888 return true;
10889
10890 // If the initializer list for a union does not contain any elements, the
10891 // first element of the union is value-initialized.
10892 // FIXME: The element should be initialized from an initializer list.
10893 // Is this difference ever observable for initializer lists which
10894 // we don't build?
10895 ImplicitValueInitExpr VIE(Field->getType());
10896 const Expr *InitExpr = Args.empty() ? &VIE : Args[0];
10897
10898 LValue Subobject = This;
10899 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
10900 return false;
10901
10902 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
10903 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
10904 isa<CXXDefaultInitExpr>(InitExpr));
10905
10906 if (EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr)) {
10907 if (Field->isBitField())
10908 return truncateBitfieldValue(Info, InitExpr, Result.getUnionValue(),
10909 Field);
10910 return true;
10911 }
10912
10913 return false;
10914 }
10915
10916 if (!Result.hasValue())
10917 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
10918 std::distance(RD->field_begin(), RD->field_end()));
10919 unsigned ElementNo = 0;
10920 bool Success = true;
10921
10922 // Initialize base classes.
10923 if (CXXRD && CXXRD->getNumBases()) {
10924 for (const auto &Base : CXXRD->bases()) {
10925 assert(ElementNo < Args.size() && "missing init for base class");
10926 const Expr *Init = Args[ElementNo];
10927
10928 LValue Subobject = This;
10929 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
10930 return false;
10931
10932 APValue &FieldVal = Result.getStructBase(ElementNo);
10933 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
10934 if (!Info.noteFailure())
10935 return false;
10936 Success = false;
10937 }
10938 ++ElementNo;
10939 }
10940
10941 EvalObj.finishedConstructingBases();
10942 }
10943
10944 // Initialize members.
10945 for (const auto *Field : RD->fields()) {
10946 // Anonymous bit-fields are not considered members of the class for
10947 // purposes of aggregate initialization.
10948 if (Field->isUnnamedBitField())
10949 continue;
10950
10951 LValue Subobject = This;
10952
10953 bool HaveInit = ElementNo < Args.size();
10954
10955 // FIXME: Diagnostics here should point to the end of the initializer
10956 // list, not the start.
10957 if (!HandleLValueMember(Info, HaveInit ? Args[ElementNo] : ExprToVisit,
10958 Subobject, Field, &Layout))
10959 return false;
10960
10961 // Perform an implicit value-initialization for members beyond the end of
10962 // the initializer list.
10963 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
10964 const Expr *Init = HaveInit ? Args[ElementNo++] : &VIE;
10965
10966 if (Field->getType()->isIncompleteArrayType()) {
10967 if (auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType())) {
10968 if (!CAT->isZeroSize()) {
10969 // Bail out for now. This might sort of "work", but the rest of the
10970 // code isn't really prepared to handle it.
10971 Info.FFDiag(Init, diag::note_constexpr_unsupported_flexible_array);
10972 return false;
10973 }
10974 }
10975 }
10976
10977 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
10978 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
10980
10981 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
10982 if (Field->getType()->isReferenceType()) {
10983 LValue Result;
10985 FieldVal)) {
10986 if (!Info.noteFailure())
10987 return false;
10988 Success = false;
10989 }
10990 } else if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
10991 (Field->isBitField() &&
10992 !truncateBitfieldValue(Info, Init, FieldVal, Field))) {
10993 if (!Info.noteFailure())
10994 return false;
10995 Success = false;
10996 }
10997 }
10998
10999 EvalObj.finishedConstructingFields();
11000
11001 return Success;
11002}
11003
11004bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
11005 QualType T) {
11006 // Note that E's type is not necessarily the type of our class here; we might
11007 // be initializing an array element instead.
11008 const CXXConstructorDecl *FD = E->getConstructor();
11009 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
11010
11011 bool ZeroInit = E->requiresZeroInitialization();
11012 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
11013 if (ZeroInit)
11014 return ZeroInitialization(E, T);
11015
11017 }
11018
11019 const FunctionDecl *Definition = nullptr;
11020 auto Body = FD->getBody(Definition);
11021
11022 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
11023 return false;
11024
11025 // Avoid materializing a temporary for an elidable copy/move constructor.
11026 if (E->isElidable() && !ZeroInit) {
11027 // FIXME: This only handles the simplest case, where the source object
11028 // is passed directly as the first argument to the constructor.
11029 // This should also handle stepping though implicit casts and
11030 // and conversion sequences which involve two steps, with a
11031 // conversion operator followed by a converting constructor.
11032 const Expr *SrcObj = E->getArg(0);
11033 assert(SrcObj->isTemporaryObject(Info.Ctx, FD->getParent()));
11034 assert(Info.Ctx.hasSameUnqualifiedType(E->getType(), SrcObj->getType()));
11035 if (const MaterializeTemporaryExpr *ME =
11036 dyn_cast<MaterializeTemporaryExpr>(SrcObj))
11037 return Visit(ME->getSubExpr());
11038 }
11039
11040 if (ZeroInit && !ZeroInitialization(E, T))
11041 return false;
11042
11043 auto Args = ArrayRef(E->getArgs(), E->getNumArgs());
11044 return HandleConstructorCall(E, This, Args,
11046 Result);
11047}
11048
11049bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
11050 const CXXInheritedCtorInitExpr *E) {
11051 if (!Info.CurrentCall) {
11052 assert(Info.checkingPotentialConstantExpression());
11053 return false;
11054 }
11055
11056 const CXXConstructorDecl *FD = E->getConstructor();
11057 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
11058 return false;
11059
11060 const FunctionDecl *Definition = nullptr;
11061 auto Body = FD->getBody(Definition);
11062
11063 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
11064 return false;
11065
11066 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
11068 Result);
11069}
11070
11071bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
11072 const CXXStdInitializerListExpr *E) {
11073 const ConstantArrayType *ArrayType =
11074 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
11075
11076 LValue Array;
11077 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
11078 return false;
11079
11080 assert(ArrayType && "unexpected type for array initializer");
11081
11082 // Get a pointer to the first element of the array.
11083 Array.addArray(Info, E, ArrayType);
11084
11085 // FIXME: What if the initializer_list type has base classes, etc?
11086 Result = APValue(APValue::UninitStruct(), 0, 2);
11087 Array.moveInto(Result.getStructField(0));
11088
11089 auto *Record = E->getType()->castAsRecordDecl();
11090 RecordDecl::field_iterator Field = Record->field_begin();
11091 assert(Field != Record->field_end() &&
11092 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
11093 ArrayType->getElementType()) &&
11094 "Expected std::initializer_list first field to be const E *");
11095 ++Field;
11096 assert(Field != Record->field_end() &&
11097 "Expected std::initializer_list to have two fields");
11098
11099 if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType())) {
11100 // Length.
11101 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
11102 } else {
11103 // End pointer.
11104 assert(Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
11105 ArrayType->getElementType()) &&
11106 "Expected std::initializer_list second field to be const E *");
11107 if (!HandleLValueArrayAdjustment(Info, E, Array,
11108 ArrayType->getElementType(),
11109 ArrayType->getZExtSize()))
11110 return false;
11111 Array.moveInto(Result.getStructField(1));
11112 }
11113
11114 assert(++Field == Record->field_end() &&
11115 "Expected std::initializer_list to only have two fields");
11116
11117 return true;
11118}
11119
11120bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
11121 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
11122 if (ClosureClass->isInvalidDecl())
11123 return false;
11124
11125 const size_t NumFields =
11126 std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
11127
11128 assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
11129 E->capture_init_end()) &&
11130 "The number of lambda capture initializers should equal the number of "
11131 "fields within the closure type");
11132
11133 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
11134 // Iterate through all the lambda's closure object's fields and initialize
11135 // them.
11136 auto *CaptureInitIt = E->capture_init_begin();
11137 bool Success = true;
11138 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(ClosureClass);
11139 for (const auto *Field : ClosureClass->fields()) {
11140 assert(CaptureInitIt != E->capture_init_end());
11141 // Get the initializer for this field
11142 Expr *const CurFieldInit = *CaptureInitIt++;
11143
11144 // If there is no initializer, either this is a VLA or an error has
11145 // occurred.
11146 if (!CurFieldInit || CurFieldInit->containsErrors())
11147 return Error(E);
11148
11149 LValue Subobject = This;
11150
11151 if (!HandleLValueMember(Info, E, Subobject, Field, &Layout))
11152 return false;
11153
11154 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
11155 if (!EvaluateInPlace(FieldVal, Info, Subobject, CurFieldInit)) {
11156 if (!Info.keepEvaluatingAfterFailure())
11157 return false;
11158 Success = false;
11159 }
11160 }
11161 return Success;
11162}
11163
11164static bool EvaluateRecord(const Expr *E, const LValue &This,
11165 APValue &Result, EvalInfo &Info) {
11166 assert(!E->isValueDependent());
11167 assert(E->isPRValue() && E->getType()->isRecordType() &&
11168 "can't evaluate expression as a record rvalue");
11169 return RecordExprEvaluator(Info, This, Result).Visit(E);
11170}
11171
11172//===----------------------------------------------------------------------===//
11173// Temporary Evaluation
11174//
11175// Temporaries are represented in the AST as rvalues, but generally behave like
11176// lvalues. The full-object of which the temporary is a subobject is implicitly
11177// materialized so that a reference can bind to it.
11178//===----------------------------------------------------------------------===//
11179namespace {
11180class TemporaryExprEvaluator
11181 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
11182public:
11183 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
11184 LValueExprEvaluatorBaseTy(Info, Result, false) {}
11185
11186 /// Visit an expression which constructs the value of this temporary.
11187 bool VisitConstructExpr(const Expr *E) {
11188 APValue &Value = Info.CurrentCall->createTemporary(
11189 E, E->getType(), ScopeKind::FullExpression, Result);
11190 return EvaluateInPlace(Value, Info, Result, E);
11191 }
11192
11193 bool VisitCastExpr(const CastExpr *E) {
11194 switch (E->getCastKind()) {
11195 default:
11196 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
11197
11198 case CK_ConstructorConversion:
11199 return VisitConstructExpr(E->getSubExpr());
11200 }
11201 }
11202 bool VisitInitListExpr(const InitListExpr *E) {
11203 return VisitConstructExpr(E);
11204 }
11205 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
11206 return VisitConstructExpr(E);
11207 }
11208 bool VisitCallExpr(const CallExpr *E) {
11209 return VisitConstructExpr(E);
11210 }
11211 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
11212 return VisitConstructExpr(E);
11213 }
11214 bool VisitLambdaExpr(const LambdaExpr *E) {
11215 return VisitConstructExpr(E);
11216 }
11217};
11218} // end anonymous namespace
11219
11220/// Evaluate an expression of record type as a temporary.
11221static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
11222 assert(!E->isValueDependent());
11223 assert(E->isPRValue() && E->getType()->isRecordType());
11224 return TemporaryExprEvaluator(Info, Result).Visit(E);
11225}
11226
11227//===----------------------------------------------------------------------===//
11228// Vector Evaluation
11229//===----------------------------------------------------------------------===//
11230
11231namespace {
11232 class VectorExprEvaluator
11233 : public ExprEvaluatorBase<VectorExprEvaluator> {
11234 APValue &Result;
11235 public:
11236
11237 VectorExprEvaluator(EvalInfo &info, APValue &Result)
11238 : ExprEvaluatorBaseTy(info), Result(Result) {}
11239
11240 bool Success(ArrayRef<APValue> V, const Expr *E) {
11241 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
11242 // FIXME: remove this APValue copy.
11243 Result = APValue(V.data(), V.size());
11244 return true;
11245 }
11246 bool Success(const APValue &V, const Expr *E) {
11247 assert(V.isVector());
11248 Result = V;
11249 return true;
11250 }
11251 bool ZeroInitialization(const Expr *E);
11252
11253 bool VisitUnaryReal(const UnaryOperator *E)
11254 { return Visit(E->getSubExpr()); }
11255 bool VisitCastExpr(const CastExpr* E);
11256 bool VisitInitListExpr(const InitListExpr *E);
11257 bool VisitUnaryImag(const UnaryOperator *E);
11258 bool VisitBinaryOperator(const BinaryOperator *E);
11259 bool VisitUnaryOperator(const UnaryOperator *E);
11260 bool VisitCallExpr(const CallExpr *E);
11261 bool VisitConvertVectorExpr(const ConvertVectorExpr *E);
11262 bool VisitShuffleVectorExpr(const ShuffleVectorExpr *E);
11263
11264 // FIXME: Missing: conditional operator (for GNU
11265 // conditional select), ExtVectorElementExpr
11266 };
11267} // end anonymous namespace
11268
11269static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
11270 assert(E->isPRValue() && E->getType()->isVectorType() &&
11271 "not a vector prvalue");
11272 return VectorExprEvaluator(Info, Result).Visit(E);
11273}
11274
11275static llvm::APInt ConvertBoolVectorToInt(const APValue &Val) {
11276 assert(Val.isVector() && "expected vector APValue");
11277 unsigned NumElts = Val.getVectorLength();
11278
11279 // Each element is one bit, so create an integer with NumElts bits.
11280 llvm::APInt Result(NumElts, 0);
11281
11282 for (unsigned I = 0; I < NumElts; ++I) {
11283 const APValue &Elt = Val.getVectorElt(I);
11284 assert(Elt.isInt() && "expected integer element in bool vector");
11285
11286 if (Elt.getInt().getBoolValue())
11287 Result.setBit(I);
11288 }
11289
11290 return Result;
11291}
11292
11293bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
11294 const VectorType *VTy = E->getType()->castAs<VectorType>();
11295 unsigned NElts = VTy->getNumElements();
11296
11297 const Expr *SE = E->getSubExpr();
11298 QualType SETy = SE->getType();
11299
11300 switch (E->getCastKind()) {
11301 case CK_VectorSplat: {
11302 APValue Val = APValue();
11303 if (SETy->isIntegerType()) {
11304 APSInt IntResult;
11305 if (!EvaluateInteger(SE, IntResult, Info))
11306 return false;
11307 Val = APValue(std::move(IntResult));
11308 } else if (SETy->isRealFloatingType()) {
11309 APFloat FloatResult(0.0);
11310 if (!EvaluateFloat(SE, FloatResult, Info))
11311 return false;
11312 Val = APValue(std::move(FloatResult));
11313 } else {
11314 return Error(E);
11315 }
11316
11317 // Splat and create vector APValue.
11318 SmallVector<APValue, 4> Elts(NElts, Val);
11319 return Success(Elts, E);
11320 }
11321 case CK_BitCast: {
11322 APValue SVal;
11323 if (!Evaluate(SVal, Info, SE))
11324 return false;
11325
11326 if (!SVal.isInt() && !SVal.isFloat() && !SVal.isVector()) {
11327 // Give up if the input isn't an int, float, or vector. For example, we
11328 // reject "(v4i16)(intptr_t)&a".
11329 Info.FFDiag(E, diag::note_constexpr_invalid_cast)
11330 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
11331 << Info.Ctx.getLangOpts().CPlusPlus;
11332 return false;
11333 }
11334
11335 if (!handleRValueToRValueBitCast(Info, Result, SVal, E))
11336 return false;
11337
11338 return true;
11339 }
11340 case CK_HLSLVectorTruncation: {
11341 APValue Val;
11342 SmallVector<APValue, 4> Elements;
11343 if (!EvaluateVector(SE, Val, Info))
11344 return Error(E);
11345 for (unsigned I = 0; I < NElts; I++)
11346 Elements.push_back(Val.getVectorElt(I));
11347 return Success(Elements, E);
11348 }
11349 default:
11350 return ExprEvaluatorBaseTy::VisitCastExpr(E);
11351 }
11352}
11353
11354bool
11355VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
11356 const VectorType *VT = E->getType()->castAs<VectorType>();
11357 unsigned NumInits = E->getNumInits();
11358 unsigned NumElements = VT->getNumElements();
11359
11360 QualType EltTy = VT->getElementType();
11361 SmallVector<APValue, 4> Elements;
11362
11363 // MFloat8 type doesn't have constants and thus constant folding
11364 // is impossible.
11365 if (EltTy->isMFloat8Type())
11366 return false;
11367
11368 // The number of initializers can be less than the number of
11369 // vector elements. For OpenCL, this can be due to nested vector
11370 // initialization. For GCC compatibility, missing trailing elements
11371 // should be initialized with zeroes.
11372 unsigned CountInits = 0, CountElts = 0;
11373 while (CountElts < NumElements) {
11374 // Handle nested vector initialization.
11375 if (CountInits < NumInits
11376 && E->getInit(CountInits)->getType()->isVectorType()) {
11377 APValue v;
11378 if (!EvaluateVector(E->getInit(CountInits), v, Info))
11379 return Error(E);
11380 unsigned vlen = v.getVectorLength();
11381 for (unsigned j = 0; j < vlen; j++)
11382 Elements.push_back(v.getVectorElt(j));
11383 CountElts += vlen;
11384 } else if (EltTy->isIntegerType()) {
11385 llvm::APSInt sInt(32);
11386 if (CountInits < NumInits) {
11387 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
11388 return false;
11389 } else // trailing integer zero.
11390 sInt = Info.Ctx.MakeIntValue(0, EltTy);
11391 Elements.push_back(APValue(sInt));
11392 CountElts++;
11393 } else {
11394 llvm::APFloat f(0.0);
11395 if (CountInits < NumInits) {
11396 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
11397 return false;
11398 } else // trailing float zero.
11399 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
11400 Elements.push_back(APValue(f));
11401 CountElts++;
11402 }
11403 CountInits++;
11404 }
11405 return Success(Elements, E);
11406}
11407
11408bool
11409VectorExprEvaluator::ZeroInitialization(const Expr *E) {
11410 const auto *VT = E->getType()->castAs<VectorType>();
11411 QualType EltTy = VT->getElementType();
11412 APValue ZeroElement;
11413 if (EltTy->isIntegerType())
11414 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
11415 else
11416 ZeroElement =
11417 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
11418
11419 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
11420 return Success(Elements, E);
11421}
11422
11423bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
11424 VisitIgnoredValue(E->getSubExpr());
11425 return ZeroInitialization(E);
11426}
11427
11428bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
11429 BinaryOperatorKind Op = E->getOpcode();
11430 assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp &&
11431 "Operation not supported on vector types");
11432
11433 if (Op == BO_Comma)
11434 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
11435
11436 Expr *LHS = E->getLHS();
11437 Expr *RHS = E->getRHS();
11438
11439 assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() &&
11440 "Must both be vector types");
11441 // Checking JUST the types are the same would be fine, except shifts don't
11442 // need to have their types be the same (since you always shift by an int).
11443 assert(LHS->getType()->castAs<VectorType>()->getNumElements() ==
11444 E->getType()->castAs<VectorType>()->getNumElements() &&
11445 RHS->getType()->castAs<VectorType>()->getNumElements() ==
11446 E->getType()->castAs<VectorType>()->getNumElements() &&
11447 "All operands must be the same size.");
11448
11449 APValue LHSValue;
11450 APValue RHSValue;
11451 bool LHSOK = Evaluate(LHSValue, Info, LHS);
11452 if (!LHSOK && !Info.noteFailure())
11453 return false;
11454 if (!Evaluate(RHSValue, Info, RHS) || !LHSOK)
11455 return false;
11456
11457 if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue))
11458 return false;
11459
11460 return Success(LHSValue, E);
11461}
11462
11463static std::optional<APValue> handleVectorUnaryOperator(ASTContext &Ctx,
11464 QualType ResultTy,
11466 APValue Elt) {
11467 switch (Op) {
11468 case UO_Plus:
11469 // Nothing to do here.
11470 return Elt;
11471 case UO_Minus:
11472 if (Elt.getKind() == APValue::Int) {
11473 Elt.getInt().negate();
11474 } else {
11475 assert(Elt.getKind() == APValue::Float &&
11476 "Vector can only be int or float type");
11477 Elt.getFloat().changeSign();
11478 }
11479 return Elt;
11480 case UO_Not:
11481 // This is only valid for integral types anyway, so we don't have to handle
11482 // float here.
11483 assert(Elt.getKind() == APValue::Int &&
11484 "Vector operator ~ can only be int");
11485 Elt.getInt().flipAllBits();
11486 return Elt;
11487 case UO_LNot: {
11488 if (Elt.getKind() == APValue::Int) {
11489 Elt.getInt() = !Elt.getInt();
11490 // operator ! on vectors returns -1 for 'truth', so negate it.
11491 Elt.getInt().negate();
11492 return Elt;
11493 }
11494 assert(Elt.getKind() == APValue::Float &&
11495 "Vector can only be int or float type");
11496 // Float types result in an int of the same size, but -1 for true, or 0 for
11497 // false.
11498 APSInt EltResult{Ctx.getIntWidth(ResultTy),
11499 ResultTy->isUnsignedIntegerType()};
11500 if (Elt.getFloat().isZero())
11501 EltResult.setAllBits();
11502 else
11503 EltResult.clearAllBits();
11504
11505 return APValue{EltResult};
11506 }
11507 default:
11508 // FIXME: Implement the rest of the unary operators.
11509 return std::nullopt;
11510 }
11511}
11512
11513bool VectorExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
11514 Expr *SubExpr = E->getSubExpr();
11515 const auto *VD = SubExpr->getType()->castAs<VectorType>();
11516 // This result element type differs in the case of negating a floating point
11517 // vector, since the result type is the a vector of the equivilant sized
11518 // integer.
11519 const QualType ResultEltTy = VD->getElementType();
11520 UnaryOperatorKind Op = E->getOpcode();
11521
11522 APValue SubExprValue;
11523 if (!Evaluate(SubExprValue, Info, SubExpr))
11524 return false;
11525
11526 // FIXME: This vector evaluator someday needs to be changed to be LValue
11527 // aware/keep LValue information around, rather than dealing with just vector
11528 // types directly. Until then, we cannot handle cases where the operand to
11529 // these unary operators is an LValue. The only case I've been able to see
11530 // cause this is operator++ assigning to a member expression (only valid in
11531 // altivec compilations) in C mode, so this shouldn't limit us too much.
11532 if (SubExprValue.isLValue())
11533 return false;
11534
11535 assert(SubExprValue.getVectorLength() == VD->getNumElements() &&
11536 "Vector length doesn't match type?");
11537
11538 SmallVector<APValue, 4> ResultElements;
11539 for (unsigned EltNum = 0; EltNum < VD->getNumElements(); ++EltNum) {
11540 std::optional<APValue> Elt = handleVectorUnaryOperator(
11541 Info.Ctx, ResultEltTy, Op, SubExprValue.getVectorElt(EltNum));
11542 if (!Elt)
11543 return false;
11544 ResultElements.push_back(*Elt);
11545 }
11546 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
11547}
11548
11549static bool handleVectorElementCast(EvalInfo &Info, const FPOptions FPO,
11550 const Expr *E, QualType SourceTy,
11551 QualType DestTy, APValue const &Original,
11552 APValue &Result) {
11553 if (SourceTy->isIntegerType()) {
11554 if (DestTy->isRealFloatingType()) {
11555 Result = APValue(APFloat(0.0));
11556 return HandleIntToFloatCast(Info, E, FPO, SourceTy, Original.getInt(),
11557 DestTy, Result.getFloat());
11558 }
11559 if (DestTy->isIntegerType()) {
11560 Result = APValue(
11561 HandleIntToIntCast(Info, E, DestTy, SourceTy, Original.getInt()));
11562 return true;
11563 }
11564 } else if (SourceTy->isRealFloatingType()) {
11565 if (DestTy->isRealFloatingType()) {
11566 Result = Original;
11567 return HandleFloatToFloatCast(Info, E, SourceTy, DestTy,
11568 Result.getFloat());
11569 }
11570 if (DestTy->isIntegerType()) {
11571 Result = APValue(APSInt());
11572 return HandleFloatToIntCast(Info, E, SourceTy, Original.getFloat(),
11573 DestTy, Result.getInt());
11574 }
11575 }
11576
11577 Info.FFDiag(E, diag::err_convertvector_constexpr_unsupported_vector_cast)
11578 << SourceTy << DestTy;
11579 return false;
11580}
11581
11582static bool evalPackBuiltin(const CallExpr *E, EvalInfo &Info, APValue &Result,
11583 llvm::function_ref<APInt(const APSInt &)> PackFn) {
11584 APValue LHS, RHS;
11585 if (!EvaluateAsRValue(Info, E->getArg(0), LHS) ||
11586 !EvaluateAsRValue(Info, E->getArg(1), RHS))
11587 return false;
11588
11589 unsigned LHSVecLen = LHS.getVectorLength();
11590 unsigned RHSVecLen = RHS.getVectorLength();
11591
11592 assert(LHSVecLen != 0 && LHSVecLen == RHSVecLen &&
11593 "pack builtin LHSVecLen must equal to RHSVecLen");
11594
11595 const VectorType *VT0 = E->getArg(0)->getType()->castAs<VectorType>();
11596 const unsigned SrcBits = Info.Ctx.getIntWidth(VT0->getElementType());
11597
11598 const VectorType *DstVT = E->getType()->castAs<VectorType>();
11599 QualType DstElemTy = DstVT->getElementType();
11600 const bool DstIsUnsigned = DstElemTy->isUnsignedIntegerType();
11601
11602 const unsigned SrcPerLane = 128 / SrcBits;
11603 const unsigned Lanes = LHSVecLen * SrcBits / 128;
11604
11606 Out.reserve(LHSVecLen + RHSVecLen);
11607
11608 for (unsigned Lane = 0; Lane != Lanes; ++Lane) {
11609 unsigned base = Lane * SrcPerLane;
11610 for (unsigned I = 0; I != SrcPerLane; ++I)
11611 Out.emplace_back(APValue(
11612 APSInt(PackFn(LHS.getVectorElt(base + I).getInt()), DstIsUnsigned)));
11613 for (unsigned I = 0; I != SrcPerLane; ++I)
11614 Out.emplace_back(APValue(
11615 APSInt(PackFn(RHS.getVectorElt(base + I).getInt()), DstIsUnsigned)));
11616 }
11617
11618 Result = APValue(Out.data(), Out.size());
11619 return true;
11620}
11621
11623 EvalInfo &Info, const CallExpr *Call, APValue &Out,
11624 llvm::function_ref<std::pair<unsigned, unsigned>(unsigned, unsigned)>
11625 GetSourceIndex) {
11626
11627 const auto *VT = Call->getType()->getAs<VectorType>();
11628 if (!VT)
11629 return false;
11630
11631 APSInt MaskImm;
11632 if (!EvaluateInteger(Call->getArg(2), MaskImm, Info))
11633 return false;
11634 unsigned ShuffleMask = static_cast<unsigned>(MaskImm.getZExtValue());
11635
11636 APValue A, B;
11637 if (!EvaluateAsRValue(Info, Call->getArg(0), A) ||
11638 !EvaluateAsRValue(Info, Call->getArg(1), B))
11639 return false;
11640
11641 unsigned NumElts = VT->getNumElements();
11642 SmallVector<APValue, 16> ResultElements;
11643 ResultElements.reserve(NumElts);
11644
11645 for (unsigned DstIdx = 0; DstIdx != NumElts; ++DstIdx) {
11646 auto [SrcVecIdx, SrcIdx] = GetSourceIndex(DstIdx, ShuffleMask);
11647 const APValue &Src = (SrcVecIdx == 0) ? A : B;
11648 ResultElements.push_back(Src.getVectorElt(SrcIdx));
11649 }
11650
11651 Out = APValue(ResultElements.data(), ResultElements.size());
11652 return true;
11653}
11654
11655static bool evalPshufbBuiltin(EvalInfo &Info, const CallExpr *Call,
11656 APValue &Out) {
11657 APValue SrcVec, ControlVec;
11658 if (!EvaluateAsRValue(Info, Call->getArg(0), SrcVec))
11659 return false;
11660 if (!EvaluateAsRValue(Info, Call->getArg(1), ControlVec))
11661 return false;
11662
11663 const auto *VT = Call->getType()->getAs<VectorType>();
11664 if (!VT)
11665 return false;
11666
11667 QualType ElemT = VT->getElementType();
11668 unsigned NumElts = VT->getNumElements();
11669
11670 SmallVector<APValue, 64> ResultElements;
11671 ResultElements.reserve(NumElts);
11672
11673 for (unsigned Idx = 0; Idx != NumElts; ++Idx) {
11674 APValue CtlVal = ControlVec.getVectorElt(Idx);
11675 APSInt CtlByte = CtlVal.getInt();
11676 uint8_t Ctl = static_cast<uint8_t>(CtlByte.getZExtValue());
11677
11678 if (Ctl & 0x80) {
11679 APValue Zero(Info.Ctx.MakeIntValue(0, ElemT));
11680 ResultElements.push_back(Zero);
11681 } else {
11682 unsigned LaneBase = (Idx / 16) * 16;
11683 unsigned SrcOffset = Ctl & 0x0F;
11684 unsigned SrcIdx = LaneBase + SrcOffset;
11685
11686 ResultElements.push_back(SrcVec.getVectorElt(SrcIdx));
11687 }
11688 }
11689 Out = APValue(ResultElements.data(), ResultElements.size());
11690 return true;
11691}
11692
11693static bool evalPshufBuiltin(EvalInfo &Info, const CallExpr *Call,
11694 bool IsShufHW, APValue &Out) {
11695 APValue Vec;
11696 APSInt Imm;
11697 if (!EvaluateAsRValue(Info, Call->getArg(0), Vec))
11698 return false;
11699 if (!EvaluateInteger(Call->getArg(1), Imm, Info))
11700 return false;
11701
11702 const auto *VT = Call->getType()->getAs<VectorType>();
11703 if (!VT)
11704 return false;
11705
11706 QualType ElemT = VT->getElementType();
11707 unsigned ElemBits = Info.Ctx.getTypeSize(ElemT);
11708 unsigned NumElts = VT->getNumElements();
11709
11710 unsigned LaneBits = 128u;
11711 unsigned LaneElts = LaneBits / ElemBits;
11712 if (!LaneElts || (NumElts % LaneElts) != 0)
11713 return false;
11714
11715 uint8_t Ctl = static_cast<uint8_t>(Imm.getZExtValue());
11716
11717 SmallVector<APValue, 32> ResultElements;
11718 ResultElements.reserve(NumElts);
11719
11720 for (unsigned Idx = 0; Idx != NumElts; Idx++) {
11721 unsigned LaneBase = (Idx / LaneElts) * LaneElts;
11722 unsigned LaneIdx = Idx % LaneElts;
11723 unsigned SrcIdx = Idx;
11724 unsigned Sel = (Ctl >> (2 * LaneIdx)) & 0x3;
11725
11726 if (ElemBits == 32) {
11727 SrcIdx = LaneBase + Sel;
11728 } else {
11729 constexpr unsigned HalfSize = 4;
11730 bool InHigh = LaneIdx >= HalfSize;
11731 if (!IsShufHW && !InHigh) {
11732 SrcIdx = LaneBase + Sel;
11733 } else if (IsShufHW && InHigh) {
11734 unsigned Rel = LaneIdx - HalfSize;
11735 Sel = (Ctl >> (2 * Rel)) & 0x3;
11736 SrcIdx = LaneBase + HalfSize + Sel;
11737 }
11738 }
11739
11740 ResultElements.push_back(Vec.getVectorElt(SrcIdx));
11741 }
11742
11743 Out = APValue(ResultElements.data(), ResultElements.size());
11744 return true;
11745}
11746
11747bool VectorExprEvaluator::VisitCallExpr(const CallExpr *E) {
11748 if (!IsConstantEvaluatedBuiltinCall(E))
11749 return ExprEvaluatorBaseTy::VisitCallExpr(E);
11750
11751 auto EvaluateBinOpExpr =
11752 [&](llvm::function_ref<APInt(const APSInt &, const APSInt &)> Fn) {
11753 APValue SourceLHS, SourceRHS;
11754 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
11755 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
11756 return false;
11757
11758 auto *DestTy = E->getType()->castAs<VectorType>();
11759 QualType DestEltTy = DestTy->getElementType();
11760 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
11761 unsigned SourceLen = SourceLHS.getVectorLength();
11762 SmallVector<APValue, 4> ResultElements;
11763 ResultElements.reserve(SourceLen);
11764
11765 if (SourceRHS.isInt()) {
11766 const APSInt &RHS = SourceRHS.getInt();
11767 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
11768 const APSInt &LHS = SourceLHS.getVectorElt(EltNum).getInt();
11769 ResultElements.push_back(
11770 APValue(APSInt(Fn(LHS, RHS), DestUnsigned)));
11771 }
11772 } else {
11773 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
11774 const APSInt &LHS = SourceLHS.getVectorElt(EltNum).getInt();
11775 const APSInt &RHS = SourceRHS.getVectorElt(EltNum).getInt();
11776 ResultElements.push_back(
11777 APValue(APSInt(Fn(LHS, RHS), DestUnsigned)));
11778 }
11779 }
11780 return Success(APValue(ResultElements.data(), SourceLen), E);
11781 };
11782
11783 switch (E->getBuiltinCallee()) {
11784 default:
11785 return false;
11786 case Builtin::BI__builtin_elementwise_popcount:
11787 case Builtin::BI__builtin_elementwise_bitreverse: {
11788 APValue Source;
11789 if (!EvaluateAsRValue(Info, E->getArg(0), Source))
11790 return false;
11791
11792 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
11793 unsigned SourceLen = Source.getVectorLength();
11794 SmallVector<APValue, 4> ResultElements;
11795 ResultElements.reserve(SourceLen);
11796
11797 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
11798 APSInt Elt = Source.getVectorElt(EltNum).getInt();
11799 switch (E->getBuiltinCallee()) {
11800 case Builtin::BI__builtin_elementwise_popcount:
11801 ResultElements.push_back(APValue(
11802 APSInt(APInt(Info.Ctx.getIntWidth(DestEltTy), Elt.popcount()),
11803 DestEltTy->isUnsignedIntegerOrEnumerationType())));
11804 break;
11805 case Builtin::BI__builtin_elementwise_bitreverse:
11806 ResultElements.push_back(
11807 APValue(APSInt(Elt.reverseBits(),
11808 DestEltTy->isUnsignedIntegerOrEnumerationType())));
11809 break;
11810 }
11811 }
11812
11813 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
11814 }
11815 case Builtin::BI__builtin_elementwise_abs: {
11816 APValue Source;
11817 if (!EvaluateAsRValue(Info, E->getArg(0), Source))
11818 return false;
11819
11820 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
11821 unsigned SourceLen = Source.getVectorLength();
11822 SmallVector<APValue, 4> ResultElements;
11823 ResultElements.reserve(SourceLen);
11824
11825 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
11826 APValue CurrentEle = Source.getVectorElt(EltNum);
11827 APValue Val = DestEltTy->isFloatingType()
11828 ? APValue(llvm::abs(CurrentEle.getFloat()))
11829 : APValue(APSInt(
11830 CurrentEle.getInt().abs(),
11831 DestEltTy->isUnsignedIntegerOrEnumerationType()));
11832 ResultElements.push_back(Val);
11833 }
11834
11835 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
11836 }
11837
11838 case Builtin::BI__builtin_elementwise_add_sat:
11839 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
11840 return LHS.isSigned() ? LHS.sadd_sat(RHS) : LHS.uadd_sat(RHS);
11841 });
11842
11843 case Builtin::BI__builtin_elementwise_sub_sat:
11844 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
11845 return LHS.isSigned() ? LHS.ssub_sat(RHS) : LHS.usub_sat(RHS);
11846 });
11847
11848 case X86::BI__builtin_ia32_extract128i256:
11849 case X86::BI__builtin_ia32_vextractf128_pd256:
11850 case X86::BI__builtin_ia32_vextractf128_ps256:
11851 case X86::BI__builtin_ia32_vextractf128_si256: {
11852 APValue SourceVec, SourceImm;
11853 if (!EvaluateAsRValue(Info, E->getArg(0), SourceVec) ||
11854 !EvaluateAsRValue(Info, E->getArg(1), SourceImm))
11855 return false;
11856
11857 if (!SourceVec.isVector())
11858 return false;
11859
11860 const auto *RetVT = E->getType()->castAs<VectorType>();
11861 unsigned RetLen = RetVT->getNumElements();
11862 unsigned Idx = SourceImm.getInt().getZExtValue() & 1;
11863
11864 SmallVector<APValue, 32> ResultElements;
11865 ResultElements.reserve(RetLen);
11866
11867 for (unsigned I = 0; I < RetLen; I++)
11868 ResultElements.push_back(SourceVec.getVectorElt(Idx * RetLen + I));
11869
11870 return Success(APValue(ResultElements.data(), RetLen), E);
11871 }
11872
11873 case X86::BI__builtin_ia32_extracti32x4_256_mask:
11874 case X86::BI__builtin_ia32_extractf32x4_256_mask:
11875 case X86::BI__builtin_ia32_extracti32x4_mask:
11876 case X86::BI__builtin_ia32_extractf32x4_mask:
11877 case X86::BI__builtin_ia32_extracti32x8_mask:
11878 case X86::BI__builtin_ia32_extractf32x8_mask:
11879 case X86::BI__builtin_ia32_extracti64x2_256_mask:
11880 case X86::BI__builtin_ia32_extractf64x2_256_mask:
11881 case X86::BI__builtin_ia32_extracti64x2_512_mask:
11882 case X86::BI__builtin_ia32_extractf64x2_512_mask:
11883 case X86::BI__builtin_ia32_extracti64x4_mask:
11884 case X86::BI__builtin_ia32_extractf64x4_mask: {
11885 APValue SourceVec, MergeVec;
11886 APSInt Imm, MaskImm;
11887
11888 if (!EvaluateAsRValue(Info, E->getArg(0), SourceVec) ||
11889 !EvaluateInteger(E->getArg(1), Imm, Info) ||
11890 !EvaluateAsRValue(Info, E->getArg(2), MergeVec) ||
11891 !EvaluateInteger(E->getArg(3), MaskImm, Info))
11892 return false;
11893
11894 const auto *RetVT = E->getType()->castAs<VectorType>();
11895 unsigned RetLen = RetVT->getNumElements();
11896
11897 if (!SourceVec.isVector() || !MergeVec.isVector())
11898 return false;
11899 unsigned SrcLen = SourceVec.getVectorLength();
11900 unsigned Lanes = SrcLen / RetLen;
11901 unsigned Lane = static_cast<unsigned>(Imm.getZExtValue() % Lanes);
11902 unsigned Base = Lane * RetLen;
11903
11904 SmallVector<APValue, 32> ResultElements;
11905 ResultElements.reserve(RetLen);
11906 for (unsigned I = 0; I < RetLen; ++I) {
11907 if (MaskImm[I])
11908 ResultElements.push_back(SourceVec.getVectorElt(Base + I));
11909 else
11910 ResultElements.push_back(MergeVec.getVectorElt(I));
11911 }
11912 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
11913 }
11914
11915 case clang::X86::BI__builtin_ia32_pavgb128:
11916 case clang::X86::BI__builtin_ia32_pavgw128:
11917 case clang::X86::BI__builtin_ia32_pavgb256:
11918 case clang::X86::BI__builtin_ia32_pavgw256:
11919 case clang::X86::BI__builtin_ia32_pavgb512:
11920 case clang::X86::BI__builtin_ia32_pavgw512:
11921 return EvaluateBinOpExpr(llvm::APIntOps::avgCeilU);
11922
11923 case clang::X86::BI__builtin_ia32_pmulhrsw128:
11924 case clang::X86::BI__builtin_ia32_pmulhrsw256:
11925 case clang::X86::BI__builtin_ia32_pmulhrsw512:
11926 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
11927 return (llvm::APIntOps::mulsExtended(LHS, RHS).ashr(14) + 1)
11928 .extractBits(16, 1);
11929 });
11930
11931 case clang::X86::BI__builtin_ia32_pmaddubsw128:
11932 case clang::X86::BI__builtin_ia32_pmaddubsw256:
11933 case clang::X86::BI__builtin_ia32_pmaddubsw512:
11934 case clang::X86::BI__builtin_ia32_pmaddwd128:
11935 case clang::X86::BI__builtin_ia32_pmaddwd256:
11936 case clang::X86::BI__builtin_ia32_pmaddwd512: {
11937 APValue SourceLHS, SourceRHS;
11938 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
11939 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
11940 return false;
11941
11942 auto *DestTy = E->getType()->castAs<VectorType>();
11943 QualType DestEltTy = DestTy->getElementType();
11944 unsigned SourceLen = SourceLHS.getVectorLength();
11945 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
11946 SmallVector<APValue, 4> ResultElements;
11947 ResultElements.reserve(SourceLen / 2);
11948
11949 for (unsigned EltNum = 0; EltNum < SourceLen; EltNum += 2) {
11950 const APSInt &LoLHS = SourceLHS.getVectorElt(EltNum).getInt();
11951 const APSInt &HiLHS = SourceLHS.getVectorElt(EltNum + 1).getInt();
11952 const APSInt &LoRHS = SourceRHS.getVectorElt(EltNum).getInt();
11953 const APSInt &HiRHS = SourceRHS.getVectorElt(EltNum + 1).getInt();
11954 unsigned BitWidth = 2 * LoLHS.getBitWidth();
11955
11956 switch (E->getBuiltinCallee()) {
11957 case clang::X86::BI__builtin_ia32_pmaddubsw128:
11958 case clang::X86::BI__builtin_ia32_pmaddubsw256:
11959 case clang::X86::BI__builtin_ia32_pmaddubsw512:
11960 ResultElements.push_back(APValue(
11961 APSInt((LoLHS.zext(BitWidth) * LoRHS.sext(BitWidth))
11962 .sadd_sat((HiLHS.zext(BitWidth) * HiRHS.sext(BitWidth))),
11963 DestUnsigned)));
11964 break;
11965 case clang::X86::BI__builtin_ia32_pmaddwd128:
11966 case clang::X86::BI__builtin_ia32_pmaddwd256:
11967 case clang::X86::BI__builtin_ia32_pmaddwd512:
11968 ResultElements.push_back(
11969 APValue(APSInt((LoLHS.sext(BitWidth) * LoRHS.sext(BitWidth)) +
11970 (HiLHS.sext(BitWidth) * HiRHS.sext(BitWidth)),
11971 DestUnsigned)));
11972 break;
11973 }
11974 }
11975
11976 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
11977 }
11978
11979 case clang::X86::BI__builtin_ia32_pmulhuw128:
11980 case clang::X86::BI__builtin_ia32_pmulhuw256:
11981 case clang::X86::BI__builtin_ia32_pmulhuw512:
11982 return EvaluateBinOpExpr(llvm::APIntOps::mulhu);
11983
11984 case clang::X86::BI__builtin_ia32_pmulhw128:
11985 case clang::X86::BI__builtin_ia32_pmulhw256:
11986 case clang::X86::BI__builtin_ia32_pmulhw512:
11987 return EvaluateBinOpExpr(llvm::APIntOps::mulhs);
11988
11989 case clang::X86::BI__builtin_ia32_psllv2di:
11990 case clang::X86::BI__builtin_ia32_psllv4di:
11991 case clang::X86::BI__builtin_ia32_psllv4si:
11992 case clang::X86::BI__builtin_ia32_psllv8di:
11993 case clang::X86::BI__builtin_ia32_psllv8hi:
11994 case clang::X86::BI__builtin_ia32_psllv8si:
11995 case clang::X86::BI__builtin_ia32_psllv16hi:
11996 case clang::X86::BI__builtin_ia32_psllv16si:
11997 case clang::X86::BI__builtin_ia32_psllv32hi:
11998 case clang::X86::BI__builtin_ia32_psllwi128:
11999 case clang::X86::BI__builtin_ia32_pslldi128:
12000 case clang::X86::BI__builtin_ia32_psllqi128:
12001 case clang::X86::BI__builtin_ia32_psllwi256:
12002 case clang::X86::BI__builtin_ia32_pslldi256:
12003 case clang::X86::BI__builtin_ia32_psllqi256:
12004 case clang::X86::BI__builtin_ia32_psllwi512:
12005 case clang::X86::BI__builtin_ia32_pslldi512:
12006 case clang::X86::BI__builtin_ia32_psllqi512:
12007 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
12008 if (RHS.uge(LHS.getBitWidth())) {
12009 return APInt::getZero(LHS.getBitWidth());
12010 }
12011 return LHS.shl(RHS.getZExtValue());
12012 });
12013
12014 case clang::X86::BI__builtin_ia32_psrav4si:
12015 case clang::X86::BI__builtin_ia32_psrav8di:
12016 case clang::X86::BI__builtin_ia32_psrav8hi:
12017 case clang::X86::BI__builtin_ia32_psrav8si:
12018 case clang::X86::BI__builtin_ia32_psrav16hi:
12019 case clang::X86::BI__builtin_ia32_psrav16si:
12020 case clang::X86::BI__builtin_ia32_psrav32hi:
12021 case clang::X86::BI__builtin_ia32_psravq128:
12022 case clang::X86::BI__builtin_ia32_psravq256:
12023 case clang::X86::BI__builtin_ia32_psrawi128:
12024 case clang::X86::BI__builtin_ia32_psradi128:
12025 case clang::X86::BI__builtin_ia32_psraqi128:
12026 case clang::X86::BI__builtin_ia32_psrawi256:
12027 case clang::X86::BI__builtin_ia32_psradi256:
12028 case clang::X86::BI__builtin_ia32_psraqi256:
12029 case clang::X86::BI__builtin_ia32_psrawi512:
12030 case clang::X86::BI__builtin_ia32_psradi512:
12031 case clang::X86::BI__builtin_ia32_psraqi512:
12032 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
12033 if (RHS.uge(LHS.getBitWidth())) {
12034 return LHS.ashr(LHS.getBitWidth() - 1);
12035 }
12036 return LHS.ashr(RHS.getZExtValue());
12037 });
12038
12039 case clang::X86::BI__builtin_ia32_psrlv2di:
12040 case clang::X86::BI__builtin_ia32_psrlv4di:
12041 case clang::X86::BI__builtin_ia32_psrlv4si:
12042 case clang::X86::BI__builtin_ia32_psrlv8di:
12043 case clang::X86::BI__builtin_ia32_psrlv8hi:
12044 case clang::X86::BI__builtin_ia32_psrlv8si:
12045 case clang::X86::BI__builtin_ia32_psrlv16hi:
12046 case clang::X86::BI__builtin_ia32_psrlv16si:
12047 case clang::X86::BI__builtin_ia32_psrlv32hi:
12048 case clang::X86::BI__builtin_ia32_psrlwi128:
12049 case clang::X86::BI__builtin_ia32_psrldi128:
12050 case clang::X86::BI__builtin_ia32_psrlqi128:
12051 case clang::X86::BI__builtin_ia32_psrlwi256:
12052 case clang::X86::BI__builtin_ia32_psrldi256:
12053 case clang::X86::BI__builtin_ia32_psrlqi256:
12054 case clang::X86::BI__builtin_ia32_psrlwi512:
12055 case clang::X86::BI__builtin_ia32_psrldi512:
12056 case clang::X86::BI__builtin_ia32_psrlqi512:
12057 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
12058 if (RHS.uge(LHS.getBitWidth())) {
12059 return APInt::getZero(LHS.getBitWidth());
12060 }
12061 return LHS.lshr(RHS.getZExtValue());
12062 });
12063 case X86::BI__builtin_ia32_packsswb128:
12064 case X86::BI__builtin_ia32_packsswb256:
12065 case X86::BI__builtin_ia32_packsswb512:
12066 case X86::BI__builtin_ia32_packssdw128:
12067 case X86::BI__builtin_ia32_packssdw256:
12068 case X86::BI__builtin_ia32_packssdw512:
12069 return evalPackBuiltin(E, Info, Result, [](const APSInt &Src) {
12070 return APSInt(Src).truncSSat(Src.getBitWidth() / 2);
12071 });
12072 case X86::BI__builtin_ia32_packusdw128:
12073 case X86::BI__builtin_ia32_packusdw256:
12074 case X86::BI__builtin_ia32_packusdw512:
12075 case X86::BI__builtin_ia32_packuswb128:
12076 case X86::BI__builtin_ia32_packuswb256:
12077 case X86::BI__builtin_ia32_packuswb512:
12078 return evalPackBuiltin(E, Info, Result, [](const APSInt &Src) {
12079 unsigned DstBits = Src.getBitWidth() / 2;
12080 if (Src.isNegative())
12081 return APInt::getZero(DstBits);
12082 if (Src.isIntN(DstBits))
12083 return APInt((Src).trunc(DstBits));
12084 return APInt::getAllOnes(DstBits);
12085 });
12086 case clang::X86::BI__builtin_ia32_pmuldq128:
12087 case clang::X86::BI__builtin_ia32_pmuldq256:
12088 case clang::X86::BI__builtin_ia32_pmuldq512:
12089 case clang::X86::BI__builtin_ia32_pmuludq128:
12090 case clang::X86::BI__builtin_ia32_pmuludq256:
12091 case clang::X86::BI__builtin_ia32_pmuludq512: {
12092 APValue SourceLHS, SourceRHS;
12093 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
12094 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
12095 return false;
12096
12097 unsigned SourceLen = SourceLHS.getVectorLength();
12098 SmallVector<APValue, 4> ResultElements;
12099 ResultElements.reserve(SourceLen / 2);
12100
12101 for (unsigned EltNum = 0; EltNum < SourceLen; EltNum += 2) {
12102 APSInt LHS = SourceLHS.getVectorElt(EltNum).getInt();
12103 APSInt RHS = SourceRHS.getVectorElt(EltNum).getInt();
12104
12105 switch (E->getBuiltinCallee()) {
12106 case clang::X86::BI__builtin_ia32_pmuludq128:
12107 case clang::X86::BI__builtin_ia32_pmuludq256:
12108 case clang::X86::BI__builtin_ia32_pmuludq512:
12109 ResultElements.push_back(
12110 APValue(APSInt(llvm::APIntOps::muluExtended(LHS, RHS), true)));
12111 break;
12112 case clang::X86::BI__builtin_ia32_pmuldq128:
12113 case clang::X86::BI__builtin_ia32_pmuldq256:
12114 case clang::X86::BI__builtin_ia32_pmuldq512:
12115 ResultElements.push_back(
12116 APValue(APSInt(llvm::APIntOps::mulsExtended(LHS, RHS), false)));
12117 break;
12118 }
12119 }
12120
12121 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12122 }
12123
12124 case X86::BI__builtin_ia32_vpmadd52luq128:
12125 case X86::BI__builtin_ia32_vpmadd52luq256:
12126 case X86::BI__builtin_ia32_vpmadd52luq512: {
12127 APValue A, B, C;
12128 if (!EvaluateAsRValue(Info, E->getArg(0), A) ||
12129 !EvaluateAsRValue(Info, E->getArg(1), B) ||
12130 !EvaluateAsRValue(Info, E->getArg(2), C))
12131 return false;
12132
12133 unsigned ALen = A.getVectorLength();
12134 SmallVector<APValue, 4> ResultElements;
12135 ResultElements.reserve(ALen);
12136
12137 for (unsigned EltNum = 0; EltNum < ALen; EltNum += 1) {
12138 APInt AElt = A.getVectorElt(EltNum).getInt();
12139 APInt BElt = B.getVectorElt(EltNum).getInt().trunc(52);
12140 APInt CElt = C.getVectorElt(EltNum).getInt().trunc(52);
12141 APSInt ResElt(AElt + (BElt * CElt).zext(64), false);
12142 ResultElements.push_back(APValue(ResElt));
12143 }
12144
12145 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12146 }
12147 case X86::BI__builtin_ia32_vpmadd52huq128:
12148 case X86::BI__builtin_ia32_vpmadd52huq256:
12149 case X86::BI__builtin_ia32_vpmadd52huq512: {
12150 APValue A, B, C;
12151 if (!EvaluateAsRValue(Info, E->getArg(0), A) ||
12152 !EvaluateAsRValue(Info, E->getArg(1), B) ||
12153 !EvaluateAsRValue(Info, E->getArg(2), C))
12154 return false;
12155
12156 unsigned ALen = A.getVectorLength();
12157 SmallVector<APValue, 4> ResultElements;
12158 ResultElements.reserve(ALen);
12159
12160 for (unsigned EltNum = 0; EltNum < ALen; EltNum += 1) {
12161 APInt AElt = A.getVectorElt(EltNum).getInt();
12162 APInt BElt = B.getVectorElt(EltNum).getInt().trunc(52);
12163 APInt CElt = C.getVectorElt(EltNum).getInt().trunc(52);
12164 APSInt ResElt(AElt + llvm::APIntOps::mulhu(BElt, CElt).zext(64), false);
12165 ResultElements.push_back(APValue(ResElt));
12166 }
12167
12168 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12169 }
12170
12171 case clang::X86::BI__builtin_ia32_vprotbi:
12172 case clang::X86::BI__builtin_ia32_vprotdi:
12173 case clang::X86::BI__builtin_ia32_vprotqi:
12174 case clang::X86::BI__builtin_ia32_vprotwi:
12175 case clang::X86::BI__builtin_ia32_prold128:
12176 case clang::X86::BI__builtin_ia32_prold256:
12177 case clang::X86::BI__builtin_ia32_prold512:
12178 case clang::X86::BI__builtin_ia32_prolq128:
12179 case clang::X86::BI__builtin_ia32_prolq256:
12180 case clang::X86::BI__builtin_ia32_prolq512:
12181 return EvaluateBinOpExpr(
12182 [](const APSInt &LHS, const APSInt &RHS) { return LHS.rotl(RHS); });
12183
12184 case clang::X86::BI__builtin_ia32_prord128:
12185 case clang::X86::BI__builtin_ia32_prord256:
12186 case clang::X86::BI__builtin_ia32_prord512:
12187 case clang::X86::BI__builtin_ia32_prorq128:
12188 case clang::X86::BI__builtin_ia32_prorq256:
12189 case clang::X86::BI__builtin_ia32_prorq512:
12190 return EvaluateBinOpExpr(
12191 [](const APSInt &LHS, const APSInt &RHS) { return LHS.rotr(RHS); });
12192
12193 case Builtin::BI__builtin_elementwise_max:
12194 case Builtin::BI__builtin_elementwise_min: {
12195 APValue SourceLHS, SourceRHS;
12196 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
12197 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
12198 return false;
12199
12200 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
12201
12202 if (!DestEltTy->isIntegerType())
12203 return false;
12204
12205 unsigned SourceLen = SourceLHS.getVectorLength();
12206 SmallVector<APValue, 4> ResultElements;
12207 ResultElements.reserve(SourceLen);
12208
12209 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12210 APSInt LHS = SourceLHS.getVectorElt(EltNum).getInt();
12211 APSInt RHS = SourceRHS.getVectorElt(EltNum).getInt();
12212 switch (E->getBuiltinCallee()) {
12213 case Builtin::BI__builtin_elementwise_max:
12214 ResultElements.push_back(
12215 APValue(APSInt(std::max(LHS, RHS),
12216 DestEltTy->isUnsignedIntegerOrEnumerationType())));
12217 break;
12218 case Builtin::BI__builtin_elementwise_min:
12219 ResultElements.push_back(
12220 APValue(APSInt(std::min(LHS, RHS),
12221 DestEltTy->isUnsignedIntegerOrEnumerationType())));
12222 break;
12223 }
12224 }
12225
12226 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12227 }
12228 case X86::BI__builtin_ia32_vpshldd128:
12229 case X86::BI__builtin_ia32_vpshldd256:
12230 case X86::BI__builtin_ia32_vpshldd512:
12231 case X86::BI__builtin_ia32_vpshldq128:
12232 case X86::BI__builtin_ia32_vpshldq256:
12233 case X86::BI__builtin_ia32_vpshldq512:
12234 case X86::BI__builtin_ia32_vpshldw128:
12235 case X86::BI__builtin_ia32_vpshldw256:
12236 case X86::BI__builtin_ia32_vpshldw512: {
12237 APValue SourceHi, SourceLo, SourceAmt;
12238 if (!EvaluateAsRValue(Info, E->getArg(0), SourceHi) ||
12239 !EvaluateAsRValue(Info, E->getArg(1), SourceLo) ||
12240 !EvaluateAsRValue(Info, E->getArg(2), SourceAmt))
12241 return false;
12242
12243 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
12244 unsigned SourceLen = SourceHi.getVectorLength();
12245 SmallVector<APValue, 32> ResultElements;
12246 ResultElements.reserve(SourceLen);
12247
12248 APInt Amt = SourceAmt.getInt();
12249 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12250 APInt Hi = SourceHi.getVectorElt(EltNum).getInt();
12251 APInt Lo = SourceLo.getVectorElt(EltNum).getInt();
12252 APInt R = llvm::APIntOps::fshl(Hi, Lo, Amt);
12253 ResultElements.push_back(
12255 }
12256
12257 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12258 }
12259 case X86::BI__builtin_ia32_vpshrdd128:
12260 case X86::BI__builtin_ia32_vpshrdd256:
12261 case X86::BI__builtin_ia32_vpshrdd512:
12262 case X86::BI__builtin_ia32_vpshrdq128:
12263 case X86::BI__builtin_ia32_vpshrdq256:
12264 case X86::BI__builtin_ia32_vpshrdq512:
12265 case X86::BI__builtin_ia32_vpshrdw128:
12266 case X86::BI__builtin_ia32_vpshrdw256:
12267 case X86::BI__builtin_ia32_vpshrdw512: {
12268 // NOTE: Reversed Hi/Lo operands.
12269 APValue SourceHi, SourceLo, SourceAmt;
12270 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLo) ||
12271 !EvaluateAsRValue(Info, E->getArg(1), SourceHi) ||
12272 !EvaluateAsRValue(Info, E->getArg(2), SourceAmt))
12273 return false;
12274
12275 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
12276 unsigned SourceLen = SourceHi.getVectorLength();
12277 SmallVector<APValue, 32> ResultElements;
12278 ResultElements.reserve(SourceLen);
12279
12280 APInt Amt = SourceAmt.getInt();
12281 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12282 APInt Hi = SourceHi.getVectorElt(EltNum).getInt();
12283 APInt Lo = SourceLo.getVectorElt(EltNum).getInt();
12284 APInt R = llvm::APIntOps::fshr(Hi, Lo, Amt);
12285 ResultElements.push_back(
12287 }
12288
12289 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12290 }
12291 case X86::BI__builtin_ia32_vpconflictsi_128:
12292 case X86::BI__builtin_ia32_vpconflictsi_256:
12293 case X86::BI__builtin_ia32_vpconflictsi_512:
12294 case X86::BI__builtin_ia32_vpconflictdi_128:
12295 case X86::BI__builtin_ia32_vpconflictdi_256:
12296 case X86::BI__builtin_ia32_vpconflictdi_512: {
12297 APValue Source;
12298
12299 if (!EvaluateAsRValue(Info, E->getArg(0), Source))
12300 return false;
12301
12302 unsigned SourceLen = Source.getVectorLength();
12303 SmallVector<APValue, 32> ResultElements;
12304 ResultElements.reserve(SourceLen);
12305
12306 const auto *VecT = E->getType()->castAs<VectorType>();
12307 bool DestUnsigned =
12308 VecT->getElementType()->isUnsignedIntegerOrEnumerationType();
12309
12310 for (unsigned I = 0; I != SourceLen; ++I) {
12311 const APValue &EltI = Source.getVectorElt(I);
12312
12313 APInt ConflictMask(EltI.getInt().getBitWidth(), 0);
12314 for (unsigned J = 0; J != I; ++J) {
12315 const APValue &EltJ = Source.getVectorElt(J);
12316 ConflictMask.setBitVal(J, EltI.getInt() == EltJ.getInt());
12317 }
12318 ResultElements.push_back(APValue(APSInt(ConflictMask, DestUnsigned)));
12319 }
12320 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12321 }
12322 case X86::BI__builtin_ia32_blendpd:
12323 case X86::BI__builtin_ia32_blendpd256:
12324 case X86::BI__builtin_ia32_blendps:
12325 case X86::BI__builtin_ia32_blendps256:
12326 case X86::BI__builtin_ia32_pblendw128:
12327 case X86::BI__builtin_ia32_pblendw256:
12328 case X86::BI__builtin_ia32_pblendd128:
12329 case X86::BI__builtin_ia32_pblendd256: {
12330 APValue SourceF, SourceT, SourceC;
12331 if (!EvaluateAsRValue(Info, E->getArg(0), SourceF) ||
12332 !EvaluateAsRValue(Info, E->getArg(1), SourceT) ||
12333 !EvaluateAsRValue(Info, E->getArg(2), SourceC))
12334 return false;
12335
12336 const APInt &C = SourceC.getInt();
12337 unsigned SourceLen = SourceF.getVectorLength();
12338 SmallVector<APValue, 32> ResultElements;
12339 ResultElements.reserve(SourceLen);
12340 for (unsigned EltNum = 0; EltNum != SourceLen; ++EltNum) {
12341 const APValue &F = SourceF.getVectorElt(EltNum);
12342 const APValue &T = SourceT.getVectorElt(EltNum);
12343 ResultElements.push_back(C[EltNum % 8] ? T : F);
12344 }
12345
12346 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12347 }
12348
12349 case X86::BI__builtin_ia32_psignb128:
12350 case X86::BI__builtin_ia32_psignb256:
12351 case X86::BI__builtin_ia32_psignw128:
12352 case X86::BI__builtin_ia32_psignw256:
12353 case X86::BI__builtin_ia32_psignd128:
12354 case X86::BI__builtin_ia32_psignd256:
12355 return EvaluateBinOpExpr([](const APInt &AElem, const APInt &BElem) {
12356 if (BElem.isZero())
12357 return APInt::getZero(AElem.getBitWidth());
12358 if (BElem.isNegative())
12359 return -AElem;
12360 return AElem;
12361 });
12362
12363 case X86::BI__builtin_ia32_blendvpd:
12364 case X86::BI__builtin_ia32_blendvpd256:
12365 case X86::BI__builtin_ia32_blendvps:
12366 case X86::BI__builtin_ia32_blendvps256:
12367 case X86::BI__builtin_ia32_pblendvb128:
12368 case X86::BI__builtin_ia32_pblendvb256: {
12369 // SSE blendv by mask signbit: "Result = C[] < 0 ? T[] : F[]".
12370 APValue SourceF, SourceT, SourceC;
12371 if (!EvaluateAsRValue(Info, E->getArg(0), SourceF) ||
12372 !EvaluateAsRValue(Info, E->getArg(1), SourceT) ||
12373 !EvaluateAsRValue(Info, E->getArg(2), SourceC))
12374 return false;
12375
12376 unsigned SourceLen = SourceF.getVectorLength();
12377 SmallVector<APValue, 32> ResultElements;
12378 ResultElements.reserve(SourceLen);
12379
12380 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12381 const APValue &F = SourceF.getVectorElt(EltNum);
12382 const APValue &T = SourceT.getVectorElt(EltNum);
12383 const APValue &C = SourceC.getVectorElt(EltNum);
12384 APInt M = C.isInt() ? (APInt)C.getInt() : C.getFloat().bitcastToAPInt();
12385 ResultElements.push_back(M.isNegative() ? T : F);
12386 }
12387
12388 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12389 }
12390 case X86::BI__builtin_ia32_selectb_128:
12391 case X86::BI__builtin_ia32_selectb_256:
12392 case X86::BI__builtin_ia32_selectb_512:
12393 case X86::BI__builtin_ia32_selectw_128:
12394 case X86::BI__builtin_ia32_selectw_256:
12395 case X86::BI__builtin_ia32_selectw_512:
12396 case X86::BI__builtin_ia32_selectd_128:
12397 case X86::BI__builtin_ia32_selectd_256:
12398 case X86::BI__builtin_ia32_selectd_512:
12399 case X86::BI__builtin_ia32_selectq_128:
12400 case X86::BI__builtin_ia32_selectq_256:
12401 case X86::BI__builtin_ia32_selectq_512:
12402 case X86::BI__builtin_ia32_selectph_128:
12403 case X86::BI__builtin_ia32_selectph_256:
12404 case X86::BI__builtin_ia32_selectph_512:
12405 case X86::BI__builtin_ia32_selectpbf_128:
12406 case X86::BI__builtin_ia32_selectpbf_256:
12407 case X86::BI__builtin_ia32_selectpbf_512:
12408 case X86::BI__builtin_ia32_selectps_128:
12409 case X86::BI__builtin_ia32_selectps_256:
12410 case X86::BI__builtin_ia32_selectps_512:
12411 case X86::BI__builtin_ia32_selectpd_128:
12412 case X86::BI__builtin_ia32_selectpd_256:
12413 case X86::BI__builtin_ia32_selectpd_512: {
12414 // AVX512 predicated move: "Result = Mask[] ? LHS[] : RHS[]".
12415 APValue SourceMask, SourceLHS, SourceRHS;
12416 if (!EvaluateAsRValue(Info, E->getArg(0), SourceMask) ||
12417 !EvaluateAsRValue(Info, E->getArg(1), SourceLHS) ||
12418 !EvaluateAsRValue(Info, E->getArg(2), SourceRHS))
12419 return false;
12420
12421 APSInt Mask = SourceMask.getInt();
12422 unsigned SourceLen = SourceLHS.getVectorLength();
12423 SmallVector<APValue, 4> ResultElements;
12424 ResultElements.reserve(SourceLen);
12425
12426 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12427 const APValue &LHS = SourceLHS.getVectorElt(EltNum);
12428 const APValue &RHS = SourceRHS.getVectorElt(EltNum);
12429 ResultElements.push_back(Mask[EltNum] ? LHS : RHS);
12430 }
12431
12432 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12433 }
12434 case X86::BI__builtin_ia32_shufps:
12435 case X86::BI__builtin_ia32_shufps256:
12436 case X86::BI__builtin_ia32_shufps512: {
12437 APValue R;
12438 if (!evalShuffleGeneric(
12439 Info, E, R,
12440 [](unsigned DstIdx,
12441 unsigned ShuffleMask) -> std::pair<unsigned, unsigned> {
12442 constexpr unsigned LaneBits = 128u;
12443 unsigned NumElemPerLane = LaneBits / 32;
12444 unsigned NumSelectableElems = NumElemPerLane / 2;
12445 unsigned BitsPerElem = 2;
12446 unsigned IndexMask = (1u << BitsPerElem) - 1;
12447 unsigned MaskBits = 8;
12448 unsigned Lane = DstIdx / NumElemPerLane;
12449 unsigned ElemInLane = DstIdx % NumElemPerLane;
12450 unsigned LaneOffset = Lane * NumElemPerLane;
12451 unsigned BitIndex = (DstIdx * BitsPerElem) % MaskBits;
12452 unsigned SrcIdx = (ElemInLane < NumSelectableElems) ? 0 : 1;
12453 unsigned Index = (ShuffleMask >> BitIndex) & IndexMask;
12454 return {SrcIdx, LaneOffset + Index};
12455 }))
12456 return false;
12457 return Success(R, E);
12458 }
12459 case X86::BI__builtin_ia32_shufpd:
12460 case X86::BI__builtin_ia32_shufpd256:
12461 case X86::BI__builtin_ia32_shufpd512: {
12462 APValue R;
12463 if (!evalShuffleGeneric(
12464 Info, E, R,
12465 [](unsigned DstIdx,
12466 unsigned ShuffleMask) -> std::pair<unsigned, unsigned> {
12467 constexpr unsigned LaneBits = 128u;
12468 unsigned NumElemPerLane = LaneBits / 64;
12469 unsigned NumSelectableElems = NumElemPerLane / 2;
12470 unsigned BitsPerElem = 1;
12471 unsigned IndexMask = (1u << BitsPerElem) - 1;
12472 unsigned MaskBits = 8;
12473 unsigned Lane = DstIdx / NumElemPerLane;
12474 unsigned ElemInLane = DstIdx % NumElemPerLane;
12475 unsigned LaneOffset = Lane * NumElemPerLane;
12476 unsigned BitIndex = (DstIdx * BitsPerElem) % MaskBits;
12477 unsigned SrcIdx = (ElemInLane < NumSelectableElems) ? 0 : 1;
12478 unsigned Index = (ShuffleMask >> BitIndex) & IndexMask;
12479 return {SrcIdx, LaneOffset + Index};
12480 }))
12481 return false;
12482 return Success(R, E);
12483 }
12484 case X86::BI__builtin_ia32_pshufb128:
12485 case X86::BI__builtin_ia32_pshufb256:
12486 case X86::BI__builtin_ia32_pshufb512: {
12487 APValue R;
12488 if (!evalPshufbBuiltin(Info, E, R))
12489 return false;
12490 return Success(R, E);
12491 }
12492
12493 case X86::BI__builtin_ia32_pshuflw:
12494 case X86::BI__builtin_ia32_pshuflw256:
12495 case X86::BI__builtin_ia32_pshuflw512: {
12496 APValue R;
12497 if (!evalPshufBuiltin(Info, E, false, R))
12498 return false;
12499 return Success(R, E);
12500 }
12501
12502 case X86::BI__builtin_ia32_pshufhw:
12503 case X86::BI__builtin_ia32_pshufhw256:
12504 case X86::BI__builtin_ia32_pshufhw512: {
12505 APValue R;
12506 if (!evalPshufBuiltin(Info, E, true, R))
12507 return false;
12508 return Success(R, E);
12509 }
12510
12511 case X86::BI__builtin_ia32_pshufd:
12512 case X86::BI__builtin_ia32_pshufd256:
12513 case X86::BI__builtin_ia32_pshufd512: {
12514 APValue R;
12515 if (!evalPshufBuiltin(Info, E, false, R))
12516 return false;
12517 return Success(R, E);
12518 }
12519
12520 case X86::BI__builtin_ia32_phminposuw128: {
12521 APValue Source;
12522 if (!Evaluate(Source, Info, E->getArg(0)))
12523 return false;
12524 unsigned SourceLen = Source.getVectorLength();
12525 const VectorType *VT = E->getArg(0)->getType()->castAs<VectorType>();
12526 QualType ElemQT = VT->getElementType();
12527 unsigned ElemBitWidth = Info.Ctx.getTypeSize(ElemQT);
12528
12529 APInt MinIndex(ElemBitWidth, 0);
12530 APInt MinVal = Source.getVectorElt(0).getInt();
12531 for (unsigned I = 1; I != SourceLen; ++I) {
12532 APInt Val = Source.getVectorElt(I).getInt();
12533 if (MinVal.ugt(Val)) {
12534 MinVal = Val;
12535 MinIndex = I;
12536 }
12537 }
12538
12539 bool ResultUnsigned = E->getCallReturnType(Info.Ctx)
12540 ->castAs<VectorType>()
12541 ->getElementType()
12542 ->isUnsignedIntegerOrEnumerationType();
12543
12545 Result.reserve(SourceLen);
12546 Result.emplace_back(APSInt(MinVal, ResultUnsigned));
12547 Result.emplace_back(APSInt(MinIndex, ResultUnsigned));
12548 for (unsigned I = 0; I != SourceLen - 2; ++I) {
12549 Result.emplace_back(APSInt(APInt(ElemBitWidth, 0), ResultUnsigned));
12550 }
12551 return Success(APValue(Result.data(), Result.size()), E);
12552 }
12553
12554 case X86::BI__builtin_ia32_pternlogd128_mask:
12555 case X86::BI__builtin_ia32_pternlogd256_mask:
12556 case X86::BI__builtin_ia32_pternlogd512_mask:
12557 case X86::BI__builtin_ia32_pternlogq128_mask:
12558 case X86::BI__builtin_ia32_pternlogq256_mask:
12559 case X86::BI__builtin_ia32_pternlogq512_mask: {
12560 APValue AValue, BValue, CValue, ImmValue, UValue;
12561 if (!EvaluateAsRValue(Info, E->getArg(0), AValue) ||
12562 !EvaluateAsRValue(Info, E->getArg(1), BValue) ||
12563 !EvaluateAsRValue(Info, E->getArg(2), CValue) ||
12564 !EvaluateAsRValue(Info, E->getArg(3), ImmValue) ||
12565 !EvaluateAsRValue(Info, E->getArg(4), UValue))
12566 return false;
12567
12568 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
12569 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
12570 APInt Imm = ImmValue.getInt();
12571 APInt U = UValue.getInt();
12572 unsigned ResultLen = AValue.getVectorLength();
12573 SmallVector<APValue, 16> ResultElements;
12574 ResultElements.reserve(ResultLen);
12575
12576 for (unsigned EltNum = 0; EltNum < ResultLen; ++EltNum) {
12577 APInt ALane = AValue.getVectorElt(EltNum).getInt();
12578 APInt BLane = BValue.getVectorElt(EltNum).getInt();
12579 APInt CLane = CValue.getVectorElt(EltNum).getInt();
12580
12581 if (U[EltNum]) {
12582 unsigned BitWidth = ALane.getBitWidth();
12583 APInt ResLane(BitWidth, 0);
12584
12585 for (unsigned Bit = 0; Bit < BitWidth; ++Bit) {
12586 unsigned ABit = ALane[Bit];
12587 unsigned BBit = BLane[Bit];
12588 unsigned CBit = CLane[Bit];
12589
12590 unsigned Idx = (ABit << 2) | (BBit << 1) | CBit;
12591 ResLane.setBitVal(Bit, Imm[Idx]);
12592 }
12593 ResultElements.push_back(APValue(APSInt(ResLane, DestUnsigned)));
12594 } else {
12595 ResultElements.push_back(APValue(APSInt(ALane, DestUnsigned)));
12596 }
12597 }
12598 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12599 }
12600 case X86::BI__builtin_ia32_pternlogd128_maskz:
12601 case X86::BI__builtin_ia32_pternlogd256_maskz:
12602 case X86::BI__builtin_ia32_pternlogd512_maskz:
12603 case X86::BI__builtin_ia32_pternlogq128_maskz:
12604 case X86::BI__builtin_ia32_pternlogq256_maskz:
12605 case X86::BI__builtin_ia32_pternlogq512_maskz: {
12606 APValue AValue, BValue, CValue, ImmValue, UValue;
12607 if (!EvaluateAsRValue(Info, E->getArg(0), AValue) ||
12608 !EvaluateAsRValue(Info, E->getArg(1), BValue) ||
12609 !EvaluateAsRValue(Info, E->getArg(2), CValue) ||
12610 !EvaluateAsRValue(Info, E->getArg(3), ImmValue) ||
12611 !EvaluateAsRValue(Info, E->getArg(4), UValue))
12612 return false;
12613
12614 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
12615 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
12616 APInt Imm = ImmValue.getInt();
12617 APInt U = UValue.getInt();
12618 unsigned ResultLen = AValue.getVectorLength();
12619 SmallVector<APValue, 16> ResultElements;
12620 ResultElements.reserve(ResultLen);
12621
12622 for (unsigned EltNum = 0; EltNum < ResultLen; ++EltNum) {
12623 APInt ALane = AValue.getVectorElt(EltNum).getInt();
12624 APInt BLane = BValue.getVectorElt(EltNum).getInt();
12625 APInt CLane = CValue.getVectorElt(EltNum).getInt();
12626
12627 unsigned BitWidth = ALane.getBitWidth();
12628 APInt ResLane(BitWidth, 0);
12629
12630 if (U[EltNum]) {
12631 for (unsigned Bit = 0; Bit < BitWidth; ++Bit) {
12632 unsigned ABit = ALane[Bit];
12633 unsigned BBit = BLane[Bit];
12634 unsigned CBit = CLane[Bit];
12635
12636 unsigned Idx = (ABit << 2) | (BBit << 1) | CBit;
12637 ResLane.setBitVal(Bit, Imm[Idx]);
12638 }
12639 }
12640 ResultElements.push_back(APValue(APSInt(ResLane, DestUnsigned)));
12641 }
12642 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12643 }
12644
12645 case Builtin::BI__builtin_elementwise_clzg:
12646 case Builtin::BI__builtin_elementwise_ctzg: {
12647 APValue SourceLHS;
12648 std::optional<APValue> Fallback;
12649 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS))
12650 return false;
12651 if (E->getNumArgs() > 1) {
12652 APValue FallbackTmp;
12653 if (!EvaluateAsRValue(Info, E->getArg(1), FallbackTmp))
12654 return false;
12655 Fallback = FallbackTmp;
12656 }
12657
12658 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
12659 unsigned SourceLen = SourceLHS.getVectorLength();
12660 SmallVector<APValue, 4> ResultElements;
12661 ResultElements.reserve(SourceLen);
12662
12663 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12664 APSInt LHS = SourceLHS.getVectorElt(EltNum).getInt();
12665 if (!LHS) {
12666 // Without a fallback, a zero element is undefined
12667 if (!Fallback) {
12668 Info.FFDiag(E, diag::note_constexpr_countzeroes_zero)
12669 << /*IsTrailing=*/(E->getBuiltinCallee() ==
12670 Builtin::BI__builtin_elementwise_ctzg);
12671 return false;
12672 }
12673 ResultElements.push_back(Fallback->getVectorElt(EltNum));
12674 continue;
12675 }
12676 switch (E->getBuiltinCallee()) {
12677 case Builtin::BI__builtin_elementwise_clzg:
12678 ResultElements.push_back(APValue(
12679 APSInt(APInt(Info.Ctx.getIntWidth(DestEltTy), LHS.countl_zero()),
12680 DestEltTy->isUnsignedIntegerOrEnumerationType())));
12681 break;
12682 case Builtin::BI__builtin_elementwise_ctzg:
12683 ResultElements.push_back(APValue(
12684 APSInt(APInt(Info.Ctx.getIntWidth(DestEltTy), LHS.countr_zero()),
12685 DestEltTy->isUnsignedIntegerOrEnumerationType())));
12686 break;
12687 }
12688 }
12689
12690 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12691 }
12692
12693 case Builtin::BI__builtin_elementwise_fma: {
12694 APValue SourceX, SourceY, SourceZ;
12695 if (!EvaluateAsRValue(Info, E->getArg(0), SourceX) ||
12696 !EvaluateAsRValue(Info, E->getArg(1), SourceY) ||
12697 !EvaluateAsRValue(Info, E->getArg(2), SourceZ))
12698 return false;
12699
12700 unsigned SourceLen = SourceX.getVectorLength();
12701 SmallVector<APValue> ResultElements;
12702 ResultElements.reserve(SourceLen);
12703 llvm::RoundingMode RM = getActiveRoundingMode(getEvalInfo(), E);
12704 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12705 const APFloat &X = SourceX.getVectorElt(EltNum).getFloat();
12706 const APFloat &Y = SourceY.getVectorElt(EltNum).getFloat();
12707 const APFloat &Z = SourceZ.getVectorElt(EltNum).getFloat();
12708 APFloat Result(X);
12709 (void)Result.fusedMultiplyAdd(Y, Z, RM);
12710 ResultElements.push_back(APValue(Result));
12711 }
12712 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12713 }
12714
12715 case clang::X86::BI__builtin_ia32_phaddw128:
12716 case clang::X86::BI__builtin_ia32_phaddw256:
12717 case clang::X86::BI__builtin_ia32_phaddd128:
12718 case clang::X86::BI__builtin_ia32_phaddd256:
12719 case clang::X86::BI__builtin_ia32_phaddsw128:
12720 case clang::X86::BI__builtin_ia32_phaddsw256:
12721
12722 case clang::X86::BI__builtin_ia32_phsubw128:
12723 case clang::X86::BI__builtin_ia32_phsubw256:
12724 case clang::X86::BI__builtin_ia32_phsubd128:
12725 case clang::X86::BI__builtin_ia32_phsubd256:
12726 case clang::X86::BI__builtin_ia32_phsubsw128:
12727 case clang::X86::BI__builtin_ia32_phsubsw256: {
12728 APValue SourceLHS, SourceRHS;
12729 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
12730 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
12731 return false;
12732 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
12733 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
12734
12735 unsigned NumElts = SourceLHS.getVectorLength();
12736 unsigned EltBits = Info.Ctx.getIntWidth(DestEltTy);
12737 unsigned EltsPerLane = 128 / EltBits;
12738 SmallVector<APValue, 4> ResultElements;
12739 ResultElements.reserve(NumElts);
12740
12741 for (unsigned LaneStart = 0; LaneStart != NumElts;
12742 LaneStart += EltsPerLane) {
12743 for (unsigned I = 0; I != EltsPerLane; I += 2) {
12744 APSInt LHSA = SourceLHS.getVectorElt(LaneStart + I).getInt();
12745 APSInt LHSB = SourceLHS.getVectorElt(LaneStart + I + 1).getInt();
12746 switch (E->getBuiltinCallee()) {
12747 case clang::X86::BI__builtin_ia32_phaddw128:
12748 case clang::X86::BI__builtin_ia32_phaddw256:
12749 case clang::X86::BI__builtin_ia32_phaddd128:
12750 case clang::X86::BI__builtin_ia32_phaddd256: {
12751 APSInt Res(LHSA + LHSB, DestUnsigned);
12752 ResultElements.push_back(APValue(Res));
12753 break;
12754 }
12755 case clang::X86::BI__builtin_ia32_phaddsw128:
12756 case clang::X86::BI__builtin_ia32_phaddsw256: {
12757 APSInt Res(LHSA.sadd_sat(LHSB));
12758 ResultElements.push_back(APValue(Res));
12759 break;
12760 }
12761 case clang::X86::BI__builtin_ia32_phsubw128:
12762 case clang::X86::BI__builtin_ia32_phsubw256:
12763 case clang::X86::BI__builtin_ia32_phsubd128:
12764 case clang::X86::BI__builtin_ia32_phsubd256: {
12765 APSInt Res(LHSA - LHSB, DestUnsigned);
12766 ResultElements.push_back(APValue(Res));
12767 break;
12768 }
12769 case clang::X86::BI__builtin_ia32_phsubsw128:
12770 case clang::X86::BI__builtin_ia32_phsubsw256: {
12771 APSInt Res(LHSA.ssub_sat(LHSB));
12772 ResultElements.push_back(APValue(Res));
12773 break;
12774 }
12775 }
12776 }
12777 for (unsigned I = 0; I != EltsPerLane; I += 2) {
12778 APSInt RHSA = SourceRHS.getVectorElt(LaneStart + I).getInt();
12779 APSInt RHSB = SourceRHS.getVectorElt(LaneStart + I + 1).getInt();
12780 switch (E->getBuiltinCallee()) {
12781 case clang::X86::BI__builtin_ia32_phaddw128:
12782 case clang::X86::BI__builtin_ia32_phaddw256:
12783 case clang::X86::BI__builtin_ia32_phaddd128:
12784 case clang::X86::BI__builtin_ia32_phaddd256: {
12785 APSInt Res(RHSA + RHSB, DestUnsigned);
12786 ResultElements.push_back(APValue(Res));
12787 break;
12788 }
12789 case clang::X86::BI__builtin_ia32_phaddsw128:
12790 case clang::X86::BI__builtin_ia32_phaddsw256: {
12791 APSInt Res(RHSA.sadd_sat(RHSB));
12792 ResultElements.push_back(APValue(Res));
12793 break;
12794 }
12795 case clang::X86::BI__builtin_ia32_phsubw128:
12796 case clang::X86::BI__builtin_ia32_phsubw256:
12797 case clang::X86::BI__builtin_ia32_phsubd128:
12798 case clang::X86::BI__builtin_ia32_phsubd256: {
12799 APSInt Res(RHSA - RHSB, DestUnsigned);
12800 ResultElements.push_back(APValue(Res));
12801 break;
12802 }
12803 case clang::X86::BI__builtin_ia32_phsubsw128:
12804 case clang::X86::BI__builtin_ia32_phsubsw256: {
12805 APSInt Res(RHSA.ssub_sat(RHSB));
12806 ResultElements.push_back(APValue(Res));
12807 break;
12808 }
12809 }
12810 }
12811 }
12812 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12813 }
12814 case clang::X86::BI__builtin_ia32_haddpd:
12815 case clang::X86::BI__builtin_ia32_haddps:
12816 case clang::X86::BI__builtin_ia32_haddps256:
12817 case clang::X86::BI__builtin_ia32_haddpd256:
12818 case clang::X86::BI__builtin_ia32_hsubpd:
12819 case clang::X86::BI__builtin_ia32_hsubps:
12820 case clang::X86::BI__builtin_ia32_hsubps256:
12821 case clang::X86::BI__builtin_ia32_hsubpd256: {
12822 APValue SourceLHS, SourceRHS;
12823 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
12824 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
12825 return false;
12826 unsigned NumElts = SourceLHS.getVectorLength();
12827 SmallVector<APValue, 4> ResultElements;
12828 ResultElements.reserve(NumElts);
12829 llvm::RoundingMode RM = getActiveRoundingMode(getEvalInfo(), E);
12830 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
12831 unsigned EltBits = Info.Ctx.getTypeSize(DestEltTy);
12832 unsigned NumLanes = NumElts * EltBits / 128;
12833 unsigned NumElemsPerLane = NumElts / NumLanes;
12834 unsigned HalfElemsPerLane = NumElemsPerLane / 2;
12835
12836 for (unsigned L = 0; L != NumElts; L += NumElemsPerLane) {
12837 for (unsigned I = 0; I != HalfElemsPerLane; ++I) {
12838 APFloat LHSA = SourceLHS.getVectorElt(L + (2 * I) + 0).getFloat();
12839 APFloat LHSB = SourceLHS.getVectorElt(L + (2 * I) + 1).getFloat();
12840 switch (E->getBuiltinCallee()) {
12841 case clang::X86::BI__builtin_ia32_haddpd:
12842 case clang::X86::BI__builtin_ia32_haddps:
12843 case clang::X86::BI__builtin_ia32_haddps256:
12844 case clang::X86::BI__builtin_ia32_haddpd256:
12845 LHSA.add(LHSB, RM);
12846 break;
12847 case clang::X86::BI__builtin_ia32_hsubpd:
12848 case clang::X86::BI__builtin_ia32_hsubps:
12849 case clang::X86::BI__builtin_ia32_hsubps256:
12850 case clang::X86::BI__builtin_ia32_hsubpd256:
12851 LHSA.subtract(LHSB, RM);
12852 break;
12853 }
12854 ResultElements.push_back(APValue(LHSA));
12855 }
12856 for (unsigned I = 0; I != HalfElemsPerLane; ++I) {
12857 APFloat RHSA = SourceRHS.getVectorElt(L + (2 * I) + 0).getFloat();
12858 APFloat RHSB = SourceRHS.getVectorElt(L + (2 * I) + 1).getFloat();
12859 switch (E->getBuiltinCallee()) {
12860 case clang::X86::BI__builtin_ia32_haddpd:
12861 case clang::X86::BI__builtin_ia32_haddps:
12862 case clang::X86::BI__builtin_ia32_haddps256:
12863 case clang::X86::BI__builtin_ia32_haddpd256:
12864 RHSA.add(RHSB, RM);
12865 break;
12866 case clang::X86::BI__builtin_ia32_hsubpd:
12867 case clang::X86::BI__builtin_ia32_hsubps:
12868 case clang::X86::BI__builtin_ia32_hsubps256:
12869 case clang::X86::BI__builtin_ia32_hsubpd256:
12870 RHSA.subtract(RHSB, RM);
12871 break;
12872 }
12873 ResultElements.push_back(APValue(RHSA));
12874 }
12875 }
12876 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12877 }
12878 case Builtin::BI__builtin_elementwise_fshl:
12879 case Builtin::BI__builtin_elementwise_fshr: {
12880 APValue SourceHi, SourceLo, SourceShift;
12881 if (!EvaluateAsRValue(Info, E->getArg(0), SourceHi) ||
12882 !EvaluateAsRValue(Info, E->getArg(1), SourceLo) ||
12883 !EvaluateAsRValue(Info, E->getArg(2), SourceShift))
12884 return false;
12885
12886 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
12887 if (!DestEltTy->isIntegerType())
12888 return false;
12889
12890 unsigned SourceLen = SourceHi.getVectorLength();
12891 SmallVector<APValue> ResultElements;
12892 ResultElements.reserve(SourceLen);
12893 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12894 const APSInt &Hi = SourceHi.getVectorElt(EltNum).getInt();
12895 const APSInt &Lo = SourceLo.getVectorElt(EltNum).getInt();
12896 const APSInt &Shift = SourceShift.getVectorElt(EltNum).getInt();
12897 switch (E->getBuiltinCallee()) {
12898 case Builtin::BI__builtin_elementwise_fshl:
12899 ResultElements.push_back(APValue(
12900 APSInt(llvm::APIntOps::fshl(Hi, Lo, Shift), Hi.isUnsigned())));
12901 break;
12902 case Builtin::BI__builtin_elementwise_fshr:
12903 ResultElements.push_back(APValue(
12904 APSInt(llvm::APIntOps::fshr(Hi, Lo, Shift), Hi.isUnsigned())));
12905 break;
12906 }
12907 }
12908
12909 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12910 }
12911
12912 case X86::BI__builtin_ia32_insertf32x4_256:
12913 case X86::BI__builtin_ia32_inserti32x4_256:
12914 case X86::BI__builtin_ia32_insertf64x2_256:
12915 case X86::BI__builtin_ia32_inserti64x2_256:
12916 case X86::BI__builtin_ia32_insertf32x4:
12917 case X86::BI__builtin_ia32_inserti32x4:
12918 case X86::BI__builtin_ia32_insertf64x2_512:
12919 case X86::BI__builtin_ia32_inserti64x2_512:
12920 case X86::BI__builtin_ia32_insertf32x8:
12921 case X86::BI__builtin_ia32_inserti32x8:
12922 case X86::BI__builtin_ia32_insertf64x4:
12923 case X86::BI__builtin_ia32_inserti64x4:
12924 case X86::BI__builtin_ia32_vinsertf128_ps256:
12925 case X86::BI__builtin_ia32_vinsertf128_pd256:
12926 case X86::BI__builtin_ia32_vinsertf128_si256:
12927 case X86::BI__builtin_ia32_insert128i256: {
12928 APValue SourceDst, SourceSub;
12929 if (!EvaluateAsRValue(Info, E->getArg(0), SourceDst) ||
12930 !EvaluateAsRValue(Info, E->getArg(1), SourceSub))
12931 return false;
12932
12933 APSInt Imm;
12934 if (!EvaluateInteger(E->getArg(2), Imm, Info))
12935 return false;
12936
12937 assert(SourceDst.isVector() && SourceSub.isVector());
12938 unsigned DstLen = SourceDst.getVectorLength();
12939 unsigned SubLen = SourceSub.getVectorLength();
12940 assert(SubLen != 0 && DstLen != 0 && (DstLen % SubLen) == 0);
12941 unsigned NumLanes = DstLen / SubLen;
12942 unsigned LaneIdx = (Imm.getZExtValue() % NumLanes) * SubLen;
12943
12944 SmallVector<APValue, 16> ResultElements;
12945 ResultElements.reserve(DstLen);
12946
12947 for (unsigned EltNum = 0; EltNum < DstLen; ++EltNum) {
12948 if (EltNum >= LaneIdx && EltNum < LaneIdx + SubLen)
12949 ResultElements.push_back(SourceSub.getVectorElt(EltNum - LaneIdx));
12950 else
12951 ResultElements.push_back(SourceDst.getVectorElt(EltNum));
12952 }
12953
12954 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12955 }
12956
12957 case clang::X86::BI__builtin_ia32_vec_set_v4hi:
12958 case clang::X86::BI__builtin_ia32_vec_set_v16qi:
12959 case clang::X86::BI__builtin_ia32_vec_set_v8hi:
12960 case clang::X86::BI__builtin_ia32_vec_set_v4si:
12961 case clang::X86::BI__builtin_ia32_vec_set_v2di:
12962 case clang::X86::BI__builtin_ia32_vec_set_v32qi:
12963 case clang::X86::BI__builtin_ia32_vec_set_v16hi:
12964 case clang::X86::BI__builtin_ia32_vec_set_v8si:
12965 case clang::X86::BI__builtin_ia32_vec_set_v4di: {
12966 APValue VecVal;
12967 APSInt Scalar, IndexAPS;
12968 if (!EvaluateVector(E->getArg(0), VecVal, Info) ||
12969 !EvaluateInteger(E->getArg(1), Scalar, Info) ||
12970 !EvaluateInteger(E->getArg(2), IndexAPS, Info))
12971 return false;
12972
12973 QualType ElemTy = E->getType()->castAs<VectorType>()->getElementType();
12974 unsigned ElemWidth = Info.Ctx.getIntWidth(ElemTy);
12975 bool ElemUnsigned = ElemTy->isUnsignedIntegerOrEnumerationType();
12976 Scalar.setIsUnsigned(ElemUnsigned);
12977 APSInt ElemAPS = Scalar.extOrTrunc(ElemWidth);
12978 APValue ElemAV(ElemAPS);
12979
12980 unsigned NumElems = VecVal.getVectorLength();
12981 unsigned Index =
12982 static_cast<unsigned>(IndexAPS.getZExtValue() & (NumElems - 1));
12983
12985 Elems.reserve(NumElems);
12986 for (unsigned ElemNum = 0; ElemNum != NumElems; ++ElemNum)
12987 Elems.push_back(ElemNum == Index ? ElemAV : VecVal.getVectorElt(ElemNum));
12988
12989 return Success(APValue(Elems.data(), NumElems), E);
12990 }
12991
12992 case X86::BI__builtin_ia32_pslldqi128_byteshift:
12993 case X86::BI__builtin_ia32_pslldqi256_byteshift:
12994 case X86::BI__builtin_ia32_pslldqi512_byteshift: {
12995 assert(E->getNumArgs() == 2);
12996
12997 APValue Src;
12998 APSInt Imm;
12999 if (!EvaluateAsRValue(Info, E->getArg(0), Src) ||
13000 !EvaluateInteger(E->getArg(1), Imm, Info))
13001 return false;
13002
13003 unsigned VecLen = Src.getVectorLength();
13004 unsigned Shift = Imm.getZExtValue() & 0xff;
13005
13006 SmallVector<APValue> ResultElements;
13007 for (unsigned Lane = 0; Lane != VecLen; Lane += 16) {
13008 for (unsigned I = 0; I != 16; ++I) {
13009 if (I < Shift) {
13010 APSInt Zero(8, /*isUnsigned=*/true);
13011 Zero = 0;
13012 ResultElements.push_back(APValue(Zero));
13013 } else {
13014 ResultElements.push_back(Src.getVectorElt(Lane + I - Shift));
13015 }
13016 }
13017 }
13018
13019 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13020 }
13021
13022 case X86::BI__builtin_ia32_psrldqi128_byteshift:
13023 case X86::BI__builtin_ia32_psrldqi256_byteshift:
13024 case X86::BI__builtin_ia32_psrldqi512_byteshift: {
13025 assert(E->getNumArgs() == 2);
13026
13027 APValue Src;
13028 APSInt Imm;
13029 if (!EvaluateAsRValue(Info, E->getArg(0), Src) ||
13030 !EvaluateInteger(E->getArg(1), Imm, Info))
13031 return false;
13032
13033 unsigned VecLen = Src.getVectorLength();
13034 unsigned Shift = Imm.getZExtValue() & 0xff;
13035
13036 SmallVector<APValue> ResultElements;
13037 for (unsigned Lane = 0; Lane != VecLen; Lane += 16) {
13038 for (unsigned I = 0; I != 16; ++I) {
13039 if (I + Shift < 16) {
13040 ResultElements.push_back(Src.getVectorElt(Lane + I + Shift));
13041 } else {
13042 APSInt Zero(8, /*isUnsigned=*/true);
13043 Zero = 0;
13044 ResultElements.push_back(APValue(Zero));
13045 }
13046 }
13047 }
13048
13049 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13050 }
13051 }
13052}
13053
13054bool VectorExprEvaluator::VisitConvertVectorExpr(const ConvertVectorExpr *E) {
13055 APValue Source;
13056 QualType SourceVecType = E->getSrcExpr()->getType();
13057 if (!EvaluateAsRValue(Info, E->getSrcExpr(), Source))
13058 return false;
13059
13060 QualType DestTy = E->getType()->castAs<VectorType>()->getElementType();
13061 QualType SourceTy = SourceVecType->castAs<VectorType>()->getElementType();
13062
13063 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
13064
13065 auto SourceLen = Source.getVectorLength();
13066 SmallVector<APValue, 4> ResultElements;
13067 ResultElements.reserve(SourceLen);
13068 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
13069 APValue Elt;
13070 if (!handleVectorElementCast(Info, FPO, E, SourceTy, DestTy,
13071 Source.getVectorElt(EltNum), Elt))
13072 return false;
13073 ResultElements.push_back(std::move(Elt));
13074 }
13075
13076 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13077}
13078
13079static bool handleVectorShuffle(EvalInfo &Info, const ShuffleVectorExpr *E,
13080 QualType ElemType, APValue const &VecVal1,
13081 APValue const &VecVal2, unsigned EltNum,
13082 APValue &Result) {
13083 unsigned const TotalElementsInInputVector1 = VecVal1.getVectorLength();
13084 unsigned const TotalElementsInInputVector2 = VecVal2.getVectorLength();
13085
13086 APSInt IndexVal = E->getShuffleMaskIdx(EltNum);
13087 int64_t index = IndexVal.getExtValue();
13088 // The spec says that -1 should be treated as undef for optimizations,
13089 // but in constexpr we'd have to produce an APValue::Indeterminate,
13090 // which is prohibited from being a top-level constant value. Emit a
13091 // diagnostic instead.
13092 if (index == -1) {
13093 Info.FFDiag(
13094 E, diag::err_shufflevector_minus_one_is_undefined_behavior_constexpr)
13095 << EltNum;
13096 return false;
13097 }
13098
13099 if (index < 0 ||
13100 index >= TotalElementsInInputVector1 + TotalElementsInInputVector2)
13101 llvm_unreachable("Out of bounds shuffle index");
13102
13103 if (index >= TotalElementsInInputVector1)
13104 Result = VecVal2.getVectorElt(index - TotalElementsInInputVector1);
13105 else
13106 Result = VecVal1.getVectorElt(index);
13107 return true;
13108}
13109
13110bool VectorExprEvaluator::VisitShuffleVectorExpr(const ShuffleVectorExpr *E) {
13111 // FIXME: Unary shuffle with mask not currently supported.
13112 if (E->getNumSubExprs() == 2)
13113 return Error(E);
13114 APValue VecVal1;
13115 const Expr *Vec1 = E->getExpr(0);
13116 if (!EvaluateAsRValue(Info, Vec1, VecVal1))
13117 return false;
13118 APValue VecVal2;
13119 const Expr *Vec2 = E->getExpr(1);
13120 if (!EvaluateAsRValue(Info, Vec2, VecVal2))
13121 return false;
13122
13123 VectorType const *DestVecTy = E->getType()->castAs<VectorType>();
13124 QualType DestElTy = DestVecTy->getElementType();
13125
13126 auto TotalElementsInOutputVector = DestVecTy->getNumElements();
13127
13128 SmallVector<APValue, 4> ResultElements;
13129 ResultElements.reserve(TotalElementsInOutputVector);
13130 for (unsigned EltNum = 0; EltNum < TotalElementsInOutputVector; ++EltNum) {
13131 APValue Elt;
13132 if (!handleVectorShuffle(Info, E, DestElTy, VecVal1, VecVal2, EltNum, Elt))
13133 return false;
13134 ResultElements.push_back(std::move(Elt));
13135 }
13136
13137 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13138}
13139
13140//===----------------------------------------------------------------------===//
13141// Array Evaluation
13142//===----------------------------------------------------------------------===//
13143
13144namespace {
13145 class ArrayExprEvaluator
13146 : public ExprEvaluatorBase<ArrayExprEvaluator> {
13147 const LValue &This;
13148 APValue &Result;
13149 public:
13150
13151 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
13152 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
13153
13154 bool Success(const APValue &V, const Expr *E) {
13155 assert(V.isArray() && "expected array");
13156 Result = V;
13157 return true;
13158 }
13159
13160 bool ZeroInitialization(const Expr *E) {
13161 const ConstantArrayType *CAT =
13162 Info.Ctx.getAsConstantArrayType(E->getType());
13163 if (!CAT) {
13164 if (E->getType()->isIncompleteArrayType()) {
13165 // We can be asked to zero-initialize a flexible array member; this
13166 // is represented as an ImplicitValueInitExpr of incomplete array
13167 // type. In this case, the array has zero elements.
13168 Result = APValue(APValue::UninitArray(), 0, 0);
13169 return true;
13170 }
13171 // FIXME: We could handle VLAs here.
13172 return Error(E);
13173 }
13174
13175 Result = APValue(APValue::UninitArray(), 0, CAT->getZExtSize());
13176 if (!Result.hasArrayFiller())
13177 return true;
13178
13179 // Zero-initialize all elements.
13180 LValue Subobject = This;
13181 Subobject.addArray(Info, E, CAT);
13182 ImplicitValueInitExpr VIE(CAT->getElementType());
13183 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
13184 }
13185
13186 bool VisitCallExpr(const CallExpr *E) {
13187 return handleCallExpr(E, Result, &This);
13188 }
13189 bool VisitInitListExpr(const InitListExpr *E,
13190 QualType AllocType = QualType());
13191 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
13192 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
13193 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
13194 const LValue &Subobject,
13195 APValue *Value, QualType Type);
13196 bool VisitStringLiteral(const StringLiteral *E,
13197 QualType AllocType = QualType()) {
13198 expandStringLiteral(Info, E, Result, AllocType);
13199 return true;
13200 }
13201 bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E);
13202 bool VisitCXXParenListOrInitListExpr(const Expr *ExprToVisit,
13203 ArrayRef<Expr *> Args,
13204 const Expr *ArrayFiller,
13205 QualType AllocType = QualType());
13206 };
13207} // end anonymous namespace
13208
13209static bool EvaluateArray(const Expr *E, const LValue &This,
13210 APValue &Result, EvalInfo &Info) {
13211 assert(!E->isValueDependent());
13212 assert(E->isPRValue() && E->getType()->isArrayType() &&
13213 "not an array prvalue");
13214 return ArrayExprEvaluator(Info, This, Result).Visit(E);
13215}
13216
13217static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
13218 APValue &Result, const InitListExpr *ILE,
13219 QualType AllocType) {
13220 assert(!ILE->isValueDependent());
13221 assert(ILE->isPRValue() && ILE->getType()->isArrayType() &&
13222 "not an array prvalue");
13223 return ArrayExprEvaluator(Info, This, Result)
13224 .VisitInitListExpr(ILE, AllocType);
13225}
13226
13227static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
13228 APValue &Result,
13229 const CXXConstructExpr *CCE,
13230 QualType AllocType) {
13231 assert(!CCE->isValueDependent());
13232 assert(CCE->isPRValue() && CCE->getType()->isArrayType() &&
13233 "not an array prvalue");
13234 return ArrayExprEvaluator(Info, This, Result)
13235 .VisitCXXConstructExpr(CCE, This, &Result, AllocType);
13236}
13237
13238// Return true iff the given array filler may depend on the element index.
13239static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
13240 // For now, just allow non-class value-initialization and initialization
13241 // lists comprised of them.
13242 if (isa<ImplicitValueInitExpr>(FillerExpr))
13243 return false;
13244 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
13245 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
13246 if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
13247 return true;
13248 }
13249
13250 if (ILE->hasArrayFiller() &&
13251 MaybeElementDependentArrayFiller(ILE->getArrayFiller()))
13252 return true;
13253
13254 return false;
13255 }
13256 return true;
13257}
13258
13259bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E,
13260 QualType AllocType) {
13261 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
13262 AllocType.isNull() ? E->getType() : AllocType);
13263 if (!CAT)
13264 return Error(E);
13265
13266 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
13267 // an appropriately-typed string literal enclosed in braces.
13268 if (E->isStringLiteralInit()) {
13269 auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParenImpCasts());
13270 // FIXME: Support ObjCEncodeExpr here once we support it in
13271 // ArrayExprEvaluator generally.
13272 if (!SL)
13273 return Error(E);
13274 return VisitStringLiteral(SL, AllocType);
13275 }
13276 // Any other transparent list init will need proper handling of the
13277 // AllocType; we can't just recurse to the inner initializer.
13278 assert(!E->isTransparent() &&
13279 "transparent array list initialization is not string literal init?");
13280
13281 return VisitCXXParenListOrInitListExpr(E, E->inits(), E->getArrayFiller(),
13282 AllocType);
13283}
13284
13285bool ArrayExprEvaluator::VisitCXXParenListOrInitListExpr(
13286 const Expr *ExprToVisit, ArrayRef<Expr *> Args, const Expr *ArrayFiller,
13287 QualType AllocType) {
13288 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
13289 AllocType.isNull() ? ExprToVisit->getType() : AllocType);
13290
13291 bool Success = true;
13292
13293 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
13294 "zero-initialized array shouldn't have any initialized elts");
13295 APValue Filler;
13296 if (Result.isArray() && Result.hasArrayFiller())
13297 Filler = Result.getArrayFiller();
13298
13299 unsigned NumEltsToInit = Args.size();
13300 unsigned NumElts = CAT->getZExtSize();
13301
13302 // If the initializer might depend on the array index, run it for each
13303 // array element.
13304 if (NumEltsToInit != NumElts &&
13305 MaybeElementDependentArrayFiller(ArrayFiller)) {
13306 NumEltsToInit = NumElts;
13307 } else {
13308 for (auto *Init : Args) {
13309 if (auto *EmbedS = dyn_cast<EmbedExpr>(Init->IgnoreParenImpCasts()))
13310 NumEltsToInit += EmbedS->getDataElementCount() - 1;
13311 }
13312 if (NumEltsToInit > NumElts)
13313 NumEltsToInit = NumElts;
13314 }
13315
13316 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
13317 << NumEltsToInit << ".\n");
13318
13319 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
13320
13321 // If the array was previously zero-initialized, preserve the
13322 // zero-initialized values.
13323 if (Filler.hasValue()) {
13324 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
13325 Result.getArrayInitializedElt(I) = Filler;
13326 if (Result.hasArrayFiller())
13327 Result.getArrayFiller() = Filler;
13328 }
13329
13330 LValue Subobject = This;
13331 Subobject.addArray(Info, ExprToVisit, CAT);
13332 auto Eval = [&](const Expr *Init, unsigned ArrayIndex) {
13333 if (Init->isValueDependent())
13334 return EvaluateDependentExpr(Init, Info);
13335
13336 if (!EvaluateInPlace(Result.getArrayInitializedElt(ArrayIndex), Info,
13337 Subobject, Init) ||
13338 !HandleLValueArrayAdjustment(Info, Init, Subobject,
13339 CAT->getElementType(), 1)) {
13340 if (!Info.noteFailure())
13341 return false;
13342 Success = false;
13343 }
13344 return true;
13345 };
13346 unsigned ArrayIndex = 0;
13347 QualType DestTy = CAT->getElementType();
13348 APSInt Value(Info.Ctx.getTypeSize(DestTy), DestTy->isUnsignedIntegerType());
13349 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
13350 const Expr *Init = Index < Args.size() ? Args[Index] : ArrayFiller;
13351 if (ArrayIndex >= NumEltsToInit)
13352 break;
13353 if (auto *EmbedS = dyn_cast<EmbedExpr>(Init->IgnoreParenImpCasts())) {
13354 StringLiteral *SL = EmbedS->getDataStringLiteral();
13355 for (unsigned I = EmbedS->getStartingElementPos(),
13356 N = EmbedS->getDataElementCount();
13357 I != EmbedS->getStartingElementPos() + N; ++I) {
13358 Value = SL->getCodeUnit(I);
13359 if (DestTy->isIntegerType()) {
13360 Result.getArrayInitializedElt(ArrayIndex) = APValue(Value);
13361 } else {
13362 assert(DestTy->isFloatingType() && "unexpected type");
13363 const FPOptions FPO =
13364 Init->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
13365 APFloat FValue(0.0);
13366 if (!HandleIntToFloatCast(Info, Init, FPO, EmbedS->getType(), Value,
13367 DestTy, FValue))
13368 return false;
13369 Result.getArrayInitializedElt(ArrayIndex) = APValue(FValue);
13370 }
13371 ArrayIndex++;
13372 }
13373 } else {
13374 if (!Eval(Init, ArrayIndex))
13375 return false;
13376 ++ArrayIndex;
13377 }
13378 }
13379
13380 if (!Result.hasArrayFiller())
13381 return Success;
13382
13383 // If we get here, we have a trivial filler, which we can just evaluate
13384 // once and splat over the rest of the array elements.
13385 assert(ArrayFiller && "no array filler for incomplete init list");
13386 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
13387 ArrayFiller) &&
13388 Success;
13389}
13390
13391bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
13392 LValue CommonLV;
13393 if (E->getCommonExpr() &&
13394 !Evaluate(Info.CurrentCall->createTemporary(
13395 E->getCommonExpr(),
13396 getStorageType(Info.Ctx, E->getCommonExpr()),
13397 ScopeKind::FullExpression, CommonLV),
13398 Info, E->getCommonExpr()->getSourceExpr()))
13399 return false;
13400
13402
13403 uint64_t Elements = CAT->getZExtSize();
13404 Result = APValue(APValue::UninitArray(), Elements, Elements);
13405
13406 LValue Subobject = This;
13407 Subobject.addArray(Info, E, CAT);
13408
13409 bool Success = true;
13410 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
13411 // C++ [class.temporary]/5
13412 // There are four contexts in which temporaries are destroyed at a different
13413 // point than the end of the full-expression. [...] The second context is
13414 // when a copy constructor is called to copy an element of an array while
13415 // the entire array is copied [...]. In either case, if the constructor has
13416 // one or more default arguments, the destruction of every temporary created
13417 // in a default argument is sequenced before the construction of the next
13418 // array element, if any.
13419 FullExpressionRAII Scope(Info);
13420
13421 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
13422 Info, Subobject, E->getSubExpr()) ||
13423 !HandleLValueArrayAdjustment(Info, E, Subobject,
13424 CAT->getElementType(), 1)) {
13425 if (!Info.noteFailure())
13426 return false;
13427 Success = false;
13428 }
13429
13430 // Make sure we run the destructors too.
13431 Scope.destroy();
13432 }
13433
13434 return Success;
13435}
13436
13437bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
13438 return VisitCXXConstructExpr(E, This, &Result, E->getType());
13439}
13440
13441bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
13442 const LValue &Subobject,
13443 APValue *Value,
13444 QualType Type) {
13445 bool HadZeroInit = Value->hasValue();
13446
13447 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
13448 unsigned FinalSize = CAT->getZExtSize();
13449
13450 // Preserve the array filler if we had prior zero-initialization.
13451 APValue Filler =
13452 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
13453 : APValue();
13454
13455 *Value = APValue(APValue::UninitArray(), 0, FinalSize);
13456 if (FinalSize == 0)
13457 return true;
13458
13459 bool HasTrivialConstructor = CheckTrivialDefaultConstructor(
13460 Info, E->getExprLoc(), E->getConstructor(),
13462 LValue ArrayElt = Subobject;
13463 ArrayElt.addArray(Info, E, CAT);
13464 // We do the whole initialization in two passes, first for just one element,
13465 // then for the whole array. It's possible we may find out we can't do const
13466 // init in the first pass, in which case we avoid allocating a potentially
13467 // large array. We don't do more passes because expanding array requires
13468 // copying the data, which is wasteful.
13469 for (const unsigned N : {1u, FinalSize}) {
13470 unsigned OldElts = Value->getArrayInitializedElts();
13471 if (OldElts == N)
13472 break;
13473
13474 // Expand the array to appropriate size.
13475 APValue NewValue(APValue::UninitArray(), N, FinalSize);
13476 for (unsigned I = 0; I < OldElts; ++I)
13477 NewValue.getArrayInitializedElt(I).swap(
13478 Value->getArrayInitializedElt(I));
13479 Value->swap(NewValue);
13480
13481 if (HadZeroInit)
13482 for (unsigned I = OldElts; I < N; ++I)
13483 Value->getArrayInitializedElt(I) = Filler;
13484
13485 if (HasTrivialConstructor && N == FinalSize && FinalSize != 1) {
13486 // If we have a trivial constructor, only evaluate it once and copy
13487 // the result into all the array elements.
13488 APValue &FirstResult = Value->getArrayInitializedElt(0);
13489 for (unsigned I = OldElts; I < FinalSize; ++I)
13490 Value->getArrayInitializedElt(I) = FirstResult;
13491 } else {
13492 for (unsigned I = OldElts; I < N; ++I) {
13493 if (!VisitCXXConstructExpr(E, ArrayElt,
13494 &Value->getArrayInitializedElt(I),
13495 CAT->getElementType()) ||
13496 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
13497 CAT->getElementType(), 1))
13498 return false;
13499 // When checking for const initilization any diagnostic is considered
13500 // an error.
13501 if (Info.EvalStatus.Diag && !Info.EvalStatus.Diag->empty() &&
13502 !Info.keepEvaluatingAfterFailure())
13503 return false;
13504 }
13505 }
13506 }
13507
13508 return true;
13509 }
13510
13511 if (!Type->isRecordType())
13512 return Error(E);
13513
13514 return RecordExprEvaluator(Info, Subobject, *Value)
13515 .VisitCXXConstructExpr(E, Type);
13516}
13517
13518bool ArrayExprEvaluator::VisitCXXParenListInitExpr(
13519 const CXXParenListInitExpr *E) {
13520 assert(E->getType()->isConstantArrayType() &&
13521 "Expression result is not a constant array type");
13522
13523 return VisitCXXParenListOrInitListExpr(E, E->getInitExprs(),
13524 E->getArrayFiller());
13525}
13526
13527//===----------------------------------------------------------------------===//
13528// Integer Evaluation
13529//
13530// As a GNU extension, we support casting pointers to sufficiently-wide integer
13531// types and back in constant folding. Integer values are thus represented
13532// either as an integer-valued APValue, or as an lvalue-valued APValue.
13533//===----------------------------------------------------------------------===//
13534
13535namespace {
13536class IntExprEvaluator
13537 : public ExprEvaluatorBase<IntExprEvaluator> {
13538 APValue &Result;
13539public:
13540 IntExprEvaluator(EvalInfo &info, APValue &result)
13541 : ExprEvaluatorBaseTy(info), Result(result) {}
13542
13543 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
13544 assert(E->getType()->isIntegralOrEnumerationType() &&
13545 "Invalid evaluation result.");
13546 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
13547 "Invalid evaluation result.");
13548 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
13549 "Invalid evaluation result.");
13550 Result = APValue(SI);
13551 return true;
13552 }
13553 bool Success(const llvm::APSInt &SI, const Expr *E) {
13554 return Success(SI, E, Result);
13555 }
13556
13557 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
13558 assert(E->getType()->isIntegralOrEnumerationType() &&
13559 "Invalid evaluation result.");
13560 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
13561 "Invalid evaluation result.");
13562 Result = APValue(APSInt(I));
13563 Result.getInt().setIsUnsigned(
13565 return true;
13566 }
13567 bool Success(const llvm::APInt &I, const Expr *E) {
13568 return Success(I, E, Result);
13569 }
13570
13571 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
13572 assert(E->getType()->isIntegralOrEnumerationType() &&
13573 "Invalid evaluation result.");
13574 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
13575 return true;
13576 }
13577 bool Success(uint64_t Value, const Expr *E) {
13578 return Success(Value, E, Result);
13579 }
13580
13581 bool Success(CharUnits Size, const Expr *E) {
13582 return Success(Size.getQuantity(), E);
13583 }
13584
13585 bool Success(const APValue &V, const Expr *E) {
13586 // C++23 [expr.const]p8 If we have a variable that is unknown reference or
13587 // pointer allow further evaluation of the value.
13588 if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate() ||
13589 V.allowConstexprUnknown()) {
13590 Result = V;
13591 return true;
13592 }
13593 return Success(V.getInt(), E);
13594 }
13595
13596 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
13597
13598 friend std::optional<bool> EvaluateBuiltinIsWithinLifetime(IntExprEvaluator &,
13599 const CallExpr *);
13600
13601 //===--------------------------------------------------------------------===//
13602 // Visitor Methods
13603 //===--------------------------------------------------------------------===//
13604
13605 bool VisitIntegerLiteral(const IntegerLiteral *E) {
13606 return Success(E->getValue(), E);
13607 }
13608 bool VisitCharacterLiteral(const CharacterLiteral *E) {
13609 return Success(E->getValue(), E);
13610 }
13611
13612 bool CheckReferencedDecl(const Expr *E, const Decl *D);
13613 bool VisitDeclRefExpr(const DeclRefExpr *E) {
13614 if (CheckReferencedDecl(E, E->getDecl()))
13615 return true;
13616
13617 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
13618 }
13619 bool VisitMemberExpr(const MemberExpr *E) {
13620 if (CheckReferencedDecl(E, E->getMemberDecl())) {
13621 VisitIgnoredBaseExpression(E->getBase());
13622 return true;
13623 }
13624
13625 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
13626 }
13627
13628 bool VisitCallExpr(const CallExpr *E);
13629 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
13630 bool VisitBinaryOperator(const BinaryOperator *E);
13631 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
13632 bool VisitUnaryOperator(const UnaryOperator *E);
13633
13634 bool VisitCastExpr(const CastExpr* E);
13635 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
13636
13637 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
13638 return Success(E->getValue(), E);
13639 }
13640
13641 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
13642 return Success(E->getValue(), E);
13643 }
13644
13645 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
13646 if (Info.ArrayInitIndex == uint64_t(-1)) {
13647 // We were asked to evaluate this subexpression independent of the
13648 // enclosing ArrayInitLoopExpr. We can't do that.
13649 Info.FFDiag(E);
13650 return false;
13651 }
13652 return Success(Info.ArrayInitIndex, E);
13653 }
13654
13655 // Note, GNU defines __null as an integer, not a pointer.
13656 bool VisitGNUNullExpr(const GNUNullExpr *E) {
13657 return ZeroInitialization(E);
13658 }
13659
13660 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
13661 if (E->isStoredAsBoolean())
13662 return Success(E->getBoolValue(), E);
13663 if (E->getAPValue().isAbsent())
13664 return false;
13665 assert(E->getAPValue().isInt() && "APValue type not supported");
13666 return Success(E->getAPValue().getInt(), E);
13667 }
13668
13669 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
13670 return Success(E->getValue(), E);
13671 }
13672
13673 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
13674 return Success(E->getValue(), E);
13675 }
13676
13677 bool VisitOpenACCAsteriskSizeExpr(const OpenACCAsteriskSizeExpr *E) {
13678 // This should not be evaluated during constant expr evaluation, as it
13679 // should always be in an unevaluated context (the args list of a 'gang' or
13680 // 'tile' clause).
13681 return Error(E);
13682 }
13683
13684 bool VisitUnaryReal(const UnaryOperator *E);
13685 bool VisitUnaryImag(const UnaryOperator *E);
13686
13687 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
13688 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
13689 bool VisitSourceLocExpr(const SourceLocExpr *E);
13690 bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E);
13691 bool VisitRequiresExpr(const RequiresExpr *E);
13692 // FIXME: Missing: array subscript of vector, member of vector
13693};
13694
13695class FixedPointExprEvaluator
13696 : public ExprEvaluatorBase<FixedPointExprEvaluator> {
13697 APValue &Result;
13698
13699 public:
13700 FixedPointExprEvaluator(EvalInfo &info, APValue &result)
13701 : ExprEvaluatorBaseTy(info), Result(result) {}
13702
13703 bool Success(const llvm::APInt &I, const Expr *E) {
13704 return Success(
13705 APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
13706 }
13707
13708 bool Success(uint64_t Value, const Expr *E) {
13709 return Success(
13710 APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
13711 }
13712
13713 bool Success(const APValue &V, const Expr *E) {
13714 return Success(V.getFixedPoint(), E);
13715 }
13716
13717 bool Success(const APFixedPoint &V, const Expr *E) {
13718 assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
13719 assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
13720 "Invalid evaluation result.");
13721 Result = APValue(V);
13722 return true;
13723 }
13724
13725 bool ZeroInitialization(const Expr *E) {
13726 return Success(0, E);
13727 }
13728
13729 //===--------------------------------------------------------------------===//
13730 // Visitor Methods
13731 //===--------------------------------------------------------------------===//
13732
13733 bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
13734 return Success(E->getValue(), E);
13735 }
13736
13737 bool VisitCastExpr(const CastExpr *E);
13738 bool VisitUnaryOperator(const UnaryOperator *E);
13739 bool VisitBinaryOperator(const BinaryOperator *E);
13740};
13741} // end anonymous namespace
13742
13743/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
13744/// produce either the integer value or a pointer.
13745///
13746/// GCC has a heinous extension which folds casts between pointer types and
13747/// pointer-sized integral types. We support this by allowing the evaluation of
13748/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
13749/// Some simple arithmetic on such values is supported (they are treated much
13750/// like char*).
13751static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
13752 EvalInfo &Info) {
13753 assert(!E->isValueDependent());
13754 assert(E->isPRValue() && E->getType()->isIntegralOrEnumerationType());
13755 return IntExprEvaluator(Info, Result).Visit(E);
13756}
13757
13758static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
13759 assert(!E->isValueDependent());
13760 APValue Val;
13761 if (!EvaluateIntegerOrLValue(E, Val, Info))
13762 return false;
13763 if (!Val.isInt()) {
13764 // FIXME: It would be better to produce the diagnostic for casting
13765 // a pointer to an integer.
13766 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
13767 return false;
13768 }
13769 Result = Val.getInt();
13770 return true;
13771}
13772
13773bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
13775 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
13776 return Success(Evaluated, E);
13777}
13778
13779static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
13780 EvalInfo &Info) {
13781 assert(!E->isValueDependent());
13782 if (E->getType()->isFixedPointType()) {
13783 APValue Val;
13784 if (!FixedPointExprEvaluator(Info, Val).Visit(E))
13785 return false;
13786 if (!Val.isFixedPoint())
13787 return false;
13788
13789 Result = Val.getFixedPoint();
13790 return true;
13791 }
13792 return false;
13793}
13794
13795static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
13796 EvalInfo &Info) {
13797 assert(!E->isValueDependent());
13798 if (E->getType()->isIntegerType()) {
13799 auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
13800 APSInt Val;
13801 if (!EvaluateInteger(E, Val, Info))
13802 return false;
13803 Result = APFixedPoint(Val, FXSema);
13804 return true;
13805 } else if (E->getType()->isFixedPointType()) {
13806 return EvaluateFixedPoint(E, Result, Info);
13807 }
13808 return false;
13809}
13810
13811/// Check whether the given declaration can be directly converted to an integral
13812/// rvalue. If not, no diagnostic is produced; there are other things we can
13813/// try.
13814bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
13815 // Enums are integer constant exprs.
13816 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
13817 // Check for signedness/width mismatches between E type and ECD value.
13818 bool SameSign = (ECD->getInitVal().isSigned()
13820 bool SameWidth = (ECD->getInitVal().getBitWidth()
13821 == Info.Ctx.getIntWidth(E->getType()));
13822 if (SameSign && SameWidth)
13823 return Success(ECD->getInitVal(), E);
13824 else {
13825 // Get rid of mismatch (otherwise Success assertions will fail)
13826 // by computing a new value matching the type of E.
13827 llvm::APSInt Val = ECD->getInitVal();
13828 if (!SameSign)
13829 Val.setIsSigned(!ECD->getInitVal().isSigned());
13830 if (!SameWidth)
13831 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
13832 return Success(Val, E);
13833 }
13834 }
13835 return false;
13836}
13837
13838/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
13839/// as GCC.
13841 const LangOptions &LangOpts) {
13842 assert(!T->isDependentType() && "unexpected dependent type");
13843
13844 QualType CanTy = T.getCanonicalType();
13845
13846 switch (CanTy->getTypeClass()) {
13847#define TYPE(ID, BASE)
13848#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
13849#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
13850#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
13851#include "clang/AST/TypeNodes.inc"
13852 case Type::Auto:
13853 case Type::DeducedTemplateSpecialization:
13854 llvm_unreachable("unexpected non-canonical or dependent type");
13855
13856 case Type::Builtin:
13857 switch (cast<BuiltinType>(CanTy)->getKind()) {
13858#define BUILTIN_TYPE(ID, SINGLETON_ID)
13859#define SIGNED_TYPE(ID, SINGLETON_ID) \
13860 case BuiltinType::ID: return GCCTypeClass::Integer;
13861#define FLOATING_TYPE(ID, SINGLETON_ID) \
13862 case BuiltinType::ID: return GCCTypeClass::RealFloat;
13863#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
13864 case BuiltinType::ID: break;
13865#include "clang/AST/BuiltinTypes.def"
13866 case BuiltinType::Void:
13867 return GCCTypeClass::Void;
13868
13869 case BuiltinType::Bool:
13870 return GCCTypeClass::Bool;
13871
13872 case BuiltinType::Char_U:
13873 case BuiltinType::UChar:
13874 case BuiltinType::WChar_U:
13875 case BuiltinType::Char8:
13876 case BuiltinType::Char16:
13877 case BuiltinType::Char32:
13878 case BuiltinType::UShort:
13879 case BuiltinType::UInt:
13880 case BuiltinType::ULong:
13881 case BuiltinType::ULongLong:
13882 case BuiltinType::UInt128:
13883 return GCCTypeClass::Integer;
13884
13885 case BuiltinType::UShortAccum:
13886 case BuiltinType::UAccum:
13887 case BuiltinType::ULongAccum:
13888 case BuiltinType::UShortFract:
13889 case BuiltinType::UFract:
13890 case BuiltinType::ULongFract:
13891 case BuiltinType::SatUShortAccum:
13892 case BuiltinType::SatUAccum:
13893 case BuiltinType::SatULongAccum:
13894 case BuiltinType::SatUShortFract:
13895 case BuiltinType::SatUFract:
13896 case BuiltinType::SatULongFract:
13897 return GCCTypeClass::None;
13898
13899 case BuiltinType::NullPtr:
13900
13901 case BuiltinType::ObjCId:
13902 case BuiltinType::ObjCClass:
13903 case BuiltinType::ObjCSel:
13904#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
13905 case BuiltinType::Id:
13906#include "clang/Basic/OpenCLImageTypes.def"
13907#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
13908 case BuiltinType::Id:
13909#include "clang/Basic/OpenCLExtensionTypes.def"
13910 case BuiltinType::OCLSampler:
13911 case BuiltinType::OCLEvent:
13912 case BuiltinType::OCLClkEvent:
13913 case BuiltinType::OCLQueue:
13914 case BuiltinType::OCLReserveID:
13915#define SVE_TYPE(Name, Id, SingletonId) \
13916 case BuiltinType::Id:
13917#include "clang/Basic/AArch64ACLETypes.def"
13918#define PPC_VECTOR_TYPE(Name, Id, Size) \
13919 case BuiltinType::Id:
13920#include "clang/Basic/PPCTypes.def"
13921#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
13922#include "clang/Basic/RISCVVTypes.def"
13923#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
13924#include "clang/Basic/WebAssemblyReferenceTypes.def"
13925#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
13926#include "clang/Basic/AMDGPUTypes.def"
13927#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
13928#include "clang/Basic/HLSLIntangibleTypes.def"
13929 return GCCTypeClass::None;
13930
13931 case BuiltinType::Dependent:
13932 llvm_unreachable("unexpected dependent type");
13933 };
13934 llvm_unreachable("unexpected placeholder type");
13935
13936 case Type::Enum:
13937 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
13938
13939 case Type::Pointer:
13940 case Type::ConstantArray:
13941 case Type::VariableArray:
13942 case Type::IncompleteArray:
13943 case Type::FunctionNoProto:
13944 case Type::FunctionProto:
13945 case Type::ArrayParameter:
13946 return GCCTypeClass::Pointer;
13947
13948 case Type::MemberPointer:
13949 return CanTy->isMemberDataPointerType()
13952
13953 case Type::Complex:
13954 return GCCTypeClass::Complex;
13955
13956 case Type::Record:
13957 return CanTy->isUnionType() ? GCCTypeClass::Union
13959
13960 case Type::Atomic:
13961 // GCC classifies _Atomic T the same as T.
13963 CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
13964
13965 case Type::Vector:
13966 case Type::ExtVector:
13967 return GCCTypeClass::Vector;
13968
13969 case Type::BlockPointer:
13970 case Type::ConstantMatrix:
13971 case Type::ObjCObject:
13972 case Type::ObjCInterface:
13973 case Type::ObjCObjectPointer:
13974 case Type::Pipe:
13975 case Type::HLSLAttributedResource:
13976 case Type::HLSLInlineSpirv:
13977 // Classify all other types that don't fit into the regular
13978 // classification the same way.
13979 return GCCTypeClass::None;
13980
13981 case Type::BitInt:
13982 return GCCTypeClass::BitInt;
13983
13984 case Type::LValueReference:
13985 case Type::RValueReference:
13986 llvm_unreachable("invalid type for expression");
13987 }
13988
13989 llvm_unreachable("unexpected type class");
13990}
13991
13992/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
13993/// as GCC.
13994static GCCTypeClass
13996 // If no argument was supplied, default to None. This isn't
13997 // ideal, however it is what gcc does.
13998 if (E->getNumArgs() == 0)
13999 return GCCTypeClass::None;
14000
14001 // FIXME: Bizarrely, GCC treats a call with more than one argument as not
14002 // being an ICE, but still folds it to a constant using the type of the first
14003 // argument.
14004 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
14005}
14006
14007/// EvaluateBuiltinConstantPForLValue - Determine the result of
14008/// __builtin_constant_p when applied to the given pointer.
14009///
14010/// A pointer is only "constant" if it is null (or a pointer cast to integer)
14011/// or it points to the first character of a string literal.
14014 if (Base.isNull()) {
14015 // A null base is acceptable.
14016 return true;
14017 } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
14018 if (!isa<StringLiteral>(E))
14019 return false;
14020 return LV.getLValueOffset().isZero();
14021 } else if (Base.is<TypeInfoLValue>()) {
14022 // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
14023 // evaluate to true.
14024 return true;
14025 } else {
14026 // Any other base is not constant enough for GCC.
14027 return false;
14028 }
14029}
14030
14031/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
14032/// GCC as we can manage.
14033static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
14034 // This evaluation is not permitted to have side-effects, so evaluate it in
14035 // a speculative evaluation context.
14036 SpeculativeEvaluationRAII SpeculativeEval(Info);
14037
14038 // Constant-folding is always enabled for the operand of __builtin_constant_p
14039 // (even when the enclosing evaluation context otherwise requires a strict
14040 // language-specific constant expression).
14041 FoldConstant Fold(Info, true);
14042
14043 QualType ArgType = Arg->getType();
14044
14045 // __builtin_constant_p always has one operand. The rules which gcc follows
14046 // are not precisely documented, but are as follows:
14047 //
14048 // - If the operand is of integral, floating, complex or enumeration type,
14049 // and can be folded to a known value of that type, it returns 1.
14050 // - If the operand can be folded to a pointer to the first character
14051 // of a string literal (or such a pointer cast to an integral type)
14052 // or to a null pointer or an integer cast to a pointer, it returns 1.
14053 //
14054 // Otherwise, it returns 0.
14055 //
14056 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
14057 // its support for this did not work prior to GCC 9 and is not yet well
14058 // understood.
14059 if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
14060 ArgType->isAnyComplexType() || ArgType->isPointerType() ||
14061 ArgType->isNullPtrType()) {
14062 APValue V;
14063 if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) {
14064 Fold.keepDiagnostics();
14065 return false;
14066 }
14067
14068 // For a pointer (possibly cast to integer), there are special rules.
14069 if (V.getKind() == APValue::LValue)
14071
14072 // Otherwise, any constant value is good enough.
14073 return V.hasValue();
14074 }
14075
14076 // Anything else isn't considered to be sufficiently constant.
14077 return false;
14078}
14079
14080/// Retrieves the "underlying object type" of the given expression,
14081/// as used by __builtin_object_size.
14083 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
14084 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
14085 return VD->getType();
14086 } else if (const Expr *E = B.dyn_cast<const Expr*>()) {
14088 return E->getType();
14089 } else if (B.is<TypeInfoLValue>()) {
14090 return B.getTypeInfoType();
14091 } else if (B.is<DynamicAllocLValue>()) {
14092 return B.getDynamicAllocType();
14093 }
14094
14095 return QualType();
14096}
14097
14098/// A more selective version of E->IgnoreParenCasts for
14099/// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
14100/// to change the type of E.
14101/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
14102///
14103/// Always returns an RValue with a pointer representation.
14104static const Expr *ignorePointerCastsAndParens(const Expr *E) {
14105 assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
14106
14107 const Expr *NoParens = E->IgnoreParens();
14108 const auto *Cast = dyn_cast<CastExpr>(NoParens);
14109 if (Cast == nullptr)
14110 return NoParens;
14111
14112 // We only conservatively allow a few kinds of casts, because this code is
14113 // inherently a simple solution that seeks to support the common case.
14114 auto CastKind = Cast->getCastKind();
14115 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
14116 CastKind != CK_AddressSpaceConversion)
14117 return NoParens;
14118
14119 const auto *SubExpr = Cast->getSubExpr();
14120 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isPRValue())
14121 return NoParens;
14122 return ignorePointerCastsAndParens(SubExpr);
14123}
14124
14125/// Checks to see if the given LValue's Designator is at the end of the LValue's
14126/// record layout. e.g.
14127/// struct { struct { int a, b; } fst, snd; } obj;
14128/// obj.fst // no
14129/// obj.snd // yes
14130/// obj.fst.a // no
14131/// obj.fst.b // no
14132/// obj.snd.a // no
14133/// obj.snd.b // yes
14134///
14135/// Please note: this function is specialized for how __builtin_object_size
14136/// views "objects".
14137///
14138/// If this encounters an invalid RecordDecl or otherwise cannot determine the
14139/// correct result, it will always return true.
14140static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
14141 assert(!LVal.Designator.Invalid);
14142
14143 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD) {
14144 const RecordDecl *Parent = FD->getParent();
14145 if (Parent->isInvalidDecl() || Parent->isUnion())
14146 return true;
14147 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
14148 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
14149 };
14150
14151 auto &Base = LVal.getLValueBase();
14152 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
14153 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
14154 if (!IsLastOrInvalidFieldDecl(FD))
14155 return false;
14156 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
14157 for (auto *FD : IFD->chain()) {
14158 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD)))
14159 return false;
14160 }
14161 }
14162 }
14163
14164 unsigned I = 0;
14165 QualType BaseType = getType(Base);
14166 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
14167 // If we don't know the array bound, conservatively assume we're looking at
14168 // the final array element.
14169 ++I;
14170 if (BaseType->isIncompleteArrayType())
14171 BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
14172 else
14173 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
14174 }
14175
14176 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
14177 const auto &Entry = LVal.Designator.Entries[I];
14178 if (BaseType->isArrayType()) {
14179 // Because __builtin_object_size treats arrays as objects, we can ignore
14180 // the index iff this is the last array in the Designator.
14181 if (I + 1 == E)
14182 return true;
14183 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
14184 uint64_t Index = Entry.getAsArrayIndex();
14185 if (Index + 1 != CAT->getZExtSize())
14186 return false;
14187 BaseType = CAT->getElementType();
14188 } else if (BaseType->isAnyComplexType()) {
14189 const auto *CT = BaseType->castAs<ComplexType>();
14190 uint64_t Index = Entry.getAsArrayIndex();
14191 if (Index != 1)
14192 return false;
14193 BaseType = CT->getElementType();
14194 } else if (auto *FD = getAsField(Entry)) {
14195 if (!IsLastOrInvalidFieldDecl(FD))
14196 return false;
14197 BaseType = FD->getType();
14198 } else {
14199 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
14200 return false;
14201 }
14202 }
14203 return true;
14204}
14205
14206/// Tests to see if the LValue has a user-specified designator (that isn't
14207/// necessarily valid). Note that this always returns 'true' if the LValue has
14208/// an unsized array as its first designator entry, because there's currently no
14209/// way to tell if the user typed *foo or foo[0].
14210static bool refersToCompleteObject(const LValue &LVal) {
14211 if (LVal.Designator.Invalid)
14212 return false;
14213
14214 if (!LVal.Designator.Entries.empty())
14215 return LVal.Designator.isMostDerivedAnUnsizedArray();
14216
14217 if (!LVal.InvalidBase)
14218 return true;
14219
14220 // If `E` is a MemberExpr, then the first part of the designator is hiding in
14221 // the LValueBase.
14222 const auto *E = LVal.Base.dyn_cast<const Expr *>();
14223 return !E || !isa<MemberExpr>(E);
14224}
14225
14226/// Attempts to detect a user writing into a piece of memory that's impossible
14227/// to figure out the size of by just using types.
14228static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
14229 const SubobjectDesignator &Designator = LVal.Designator;
14230 // Notes:
14231 // - Users can only write off of the end when we have an invalid base. Invalid
14232 // bases imply we don't know where the memory came from.
14233 // - We used to be a bit more aggressive here; we'd only be conservative if
14234 // the array at the end was flexible, or if it had 0 or 1 elements. This
14235 // broke some common standard library extensions (PR30346), but was
14236 // otherwise seemingly fine. It may be useful to reintroduce this behavior
14237 // with some sort of list. OTOH, it seems that GCC is always
14238 // conservative with the last element in structs (if it's an array), so our
14239 // current behavior is more compatible than an explicit list approach would
14240 // be.
14241 auto isFlexibleArrayMember = [&] {
14243 FAMKind StrictFlexArraysLevel =
14244 Ctx.getLangOpts().getStrictFlexArraysLevel();
14245
14246 if (Designator.isMostDerivedAnUnsizedArray())
14247 return true;
14248
14249 if (StrictFlexArraysLevel == FAMKind::Default)
14250 return true;
14251
14252 if (Designator.getMostDerivedArraySize() == 0 &&
14253 StrictFlexArraysLevel != FAMKind::IncompleteOnly)
14254 return true;
14255
14256 if (Designator.getMostDerivedArraySize() == 1 &&
14257 StrictFlexArraysLevel == FAMKind::OneZeroOrIncomplete)
14258 return true;
14259
14260 return false;
14261 };
14262
14263 return LVal.InvalidBase &&
14264 Designator.Entries.size() == Designator.MostDerivedPathLength &&
14265 Designator.MostDerivedIsArrayElement && isFlexibleArrayMember() &&
14266 isDesignatorAtObjectEnd(Ctx, LVal);
14267}
14268
14269/// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
14270/// Fails if the conversion would cause loss of precision.
14271static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
14272 CharUnits &Result) {
14273 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
14274 if (Int.ugt(CharUnitsMax))
14275 return false;
14276 Result = CharUnits::fromQuantity(Int.getZExtValue());
14277 return true;
14278}
14279
14280/// If we're evaluating the object size of an instance of a struct that
14281/// contains a flexible array member, add the size of the initializer.
14282static void addFlexibleArrayMemberInitSize(EvalInfo &Info, const QualType &T,
14283 const LValue &LV, CharUnits &Size) {
14284 if (!T.isNull() && T->isStructureType() &&
14285 T->castAsRecordDecl()->hasFlexibleArrayMember())
14286 if (const auto *V = LV.getLValueBase().dyn_cast<const ValueDecl *>())
14287 if (const auto *VD = dyn_cast<VarDecl>(V))
14288 if (VD->hasInit())
14289 Size += VD->getFlexibleArrayInitChars(Info.Ctx);
14290}
14291
14292/// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
14293/// determine how many bytes exist from the beginning of the object to either
14294/// the end of the current subobject, or the end of the object itself, depending
14295/// on what the LValue looks like + the value of Type.
14296///
14297/// If this returns false, the value of Result is undefined.
14298static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
14299 unsigned Type, const LValue &LVal,
14300 CharUnits &EndOffset) {
14301 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
14302
14303 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
14304 if (Ty.isNull())
14305 return false;
14306
14307 Ty = Ty.getNonReferenceType();
14308
14309 if (Ty->isIncompleteType() || Ty->isFunctionType())
14310 return false;
14311
14312 return HandleSizeof(Info, ExprLoc, Ty, Result);
14313 };
14314
14315 // We want to evaluate the size of the entire object. This is a valid fallback
14316 // for when Type=1 and the designator is invalid, because we're asked for an
14317 // upper-bound.
14318 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
14319 // Type=3 wants a lower bound, so we can't fall back to this.
14320 if (Type == 3 && !DetermineForCompleteObject)
14321 return false;
14322
14323 llvm::APInt APEndOffset;
14324 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
14325 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
14326 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
14327
14328 if (LVal.InvalidBase)
14329 return false;
14330
14331 QualType BaseTy = getObjectType(LVal.getLValueBase());
14332 const bool Ret = CheckedHandleSizeof(BaseTy, EndOffset);
14333 addFlexibleArrayMemberInitSize(Info, BaseTy, LVal, EndOffset);
14334 return Ret;
14335 }
14336
14337 // We want to evaluate the size of a subobject.
14338 const SubobjectDesignator &Designator = LVal.Designator;
14339
14340 // The following is a moderately common idiom in C:
14341 //
14342 // struct Foo { int a; char c[1]; };
14343 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
14344 // strcpy(&F->c[0], Bar);
14345 //
14346 // In order to not break too much legacy code, we need to support it.
14347 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
14348 // If we can resolve this to an alloc_size call, we can hand that back,
14349 // because we know for certain how many bytes there are to write to.
14350 llvm::APInt APEndOffset;
14351 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
14352 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
14353 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
14354
14355 // If we cannot determine the size of the initial allocation, then we can't
14356 // given an accurate upper-bound. However, we are still able to give
14357 // conservative lower-bounds for Type=3.
14358 if (Type == 1)
14359 return false;
14360 }
14361
14362 CharUnits BytesPerElem;
14363 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
14364 return false;
14365
14366 // According to the GCC documentation, we want the size of the subobject
14367 // denoted by the pointer. But that's not quite right -- what we actually
14368 // want is the size of the immediately-enclosing array, if there is one.
14369 int64_t ElemsRemaining;
14370 if (Designator.MostDerivedIsArrayElement &&
14371 Designator.Entries.size() == Designator.MostDerivedPathLength) {
14372 uint64_t ArraySize = Designator.getMostDerivedArraySize();
14373 uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
14374 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
14375 } else {
14376 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
14377 }
14378
14379 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
14380 return true;
14381}
14382
14383/// Tries to evaluate the __builtin_object_size for @p E. If successful,
14384/// returns true and stores the result in @p Size.
14385///
14386/// If @p WasError is non-null, this will report whether the failure to evaluate
14387/// is to be treated as an Error in IntExprEvaluator.
14388static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
14389 EvalInfo &Info, uint64_t &Size) {
14390 // Determine the denoted object.
14391 LValue LVal;
14392 {
14393 // The operand of __builtin_object_size is never evaluated for side-effects.
14394 // If there are any, but we can determine the pointed-to object anyway, then
14395 // ignore the side-effects.
14396 SpeculativeEvaluationRAII SpeculativeEval(Info);
14397 IgnoreSideEffectsRAII Fold(Info);
14398
14399 if (E->isGLValue()) {
14400 // It's possible for us to be given GLValues if we're called via
14401 // Expr::tryEvaluateObjectSize.
14402 APValue RVal;
14403 if (!EvaluateAsRValue(Info, E, RVal))
14404 return false;
14405 LVal.setFrom(Info.Ctx, RVal);
14406 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
14407 /*InvalidBaseOK=*/true))
14408 return false;
14409 }
14410
14411 // If we point to before the start of the object, there are no accessible
14412 // bytes.
14413 if (LVal.getLValueOffset().isNegative()) {
14414 Size = 0;
14415 return true;
14416 }
14417
14418 CharUnits EndOffset;
14419 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
14420 return false;
14421
14422 // If we've fallen outside of the end offset, just pretend there's nothing to
14423 // write to/read from.
14424 if (EndOffset <= LVal.getLValueOffset())
14425 Size = 0;
14426 else
14427 Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
14428 return true;
14429}
14430
14431bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
14432 if (!IsConstantEvaluatedBuiltinCall(E))
14433 return ExprEvaluatorBaseTy::VisitCallExpr(E);
14434 return VisitBuiltinCallExpr(E, E->getBuiltinCallee());
14435}
14436
14437static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info,
14438 APValue &Val, APSInt &Alignment) {
14439 QualType SrcTy = E->getArg(0)->getType();
14440 if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment))
14441 return false;
14442 // Even though we are evaluating integer expressions we could get a pointer
14443 // argument for the __builtin_is_aligned() case.
14444 if (SrcTy->isPointerType()) {
14445 LValue Ptr;
14446 if (!EvaluatePointer(E->getArg(0), Ptr, Info))
14447 return false;
14448 Ptr.moveInto(Val);
14449 } else if (!SrcTy->isIntegralOrEnumerationType()) {
14450 Info.FFDiag(E->getArg(0));
14451 return false;
14452 } else {
14453 APSInt SrcInt;
14454 if (!EvaluateInteger(E->getArg(0), SrcInt, Info))
14455 return false;
14456 assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() &&
14457 "Bit widths must be the same");
14458 Val = APValue(SrcInt);
14459 }
14460 assert(Val.hasValue());
14461 return true;
14462}
14463
14464bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
14465 unsigned BuiltinOp) {
14466 auto EvalTestOp = [&](llvm::function_ref<bool(const APInt &, const APInt &)>
14467 Fn) {
14468 APValue SourceLHS, SourceRHS;
14469 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
14470 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
14471 return false;
14472
14473 unsigned SourceLen = SourceLHS.getVectorLength();
14474 const VectorType *VT = E->getArg(0)->getType()->castAs<VectorType>();
14475 QualType ElemQT = VT->getElementType();
14476 unsigned LaneWidth = Info.Ctx.getTypeSize(ElemQT);
14477
14478 APInt AWide(LaneWidth * SourceLen, 0);
14479 APInt BWide(LaneWidth * SourceLen, 0);
14480
14481 for (unsigned I = 0; I != SourceLen; ++I) {
14482 APInt ALane;
14483 APInt BLane;
14484 if (ElemQT->isIntegerType()) { // Get value.
14485 ALane = SourceLHS.getVectorElt(I).getInt();
14486 BLane = SourceRHS.getVectorElt(I).getInt();
14487 } else if (ElemQT->isFloatingType()) { // Get only sign bit.
14488 ALane =
14489 SourceLHS.getVectorElt(I).getFloat().bitcastToAPInt().isNegative();
14490 BLane =
14491 SourceRHS.getVectorElt(I).getFloat().bitcastToAPInt().isNegative();
14492 } else { // Must be integer or floating type.
14493 return false;
14494 }
14495 AWide.insertBits(ALane, I * LaneWidth);
14496 BWide.insertBits(BLane, I * LaneWidth);
14497 }
14498 return Success(Fn(AWide, BWide), E);
14499 };
14500
14501 auto HandleMaskBinOp =
14502 [&](llvm::function_ref<APSInt(const APSInt &, const APSInt &)> Fn)
14503 -> bool {
14504 APValue LHS, RHS;
14505 if (!Evaluate(LHS, Info, E->getArg(0)) ||
14506 !Evaluate(RHS, Info, E->getArg(1)))
14507 return false;
14508
14509 APSInt ResultInt = Fn(LHS.getInt(), RHS.getInt());
14510
14511 return Success(APValue(ResultInt), E);
14512 };
14513
14514 switch (BuiltinOp) {
14515 default:
14516 return false;
14517
14518 case Builtin::BI__builtin_dynamic_object_size:
14519 case Builtin::BI__builtin_object_size: {
14520 // The type was checked when we built the expression.
14521 unsigned Type =
14522 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
14523 assert(Type <= 3 && "unexpected type");
14524
14525 uint64_t Size;
14526 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
14527 return Success(Size, E);
14528
14529 if (E->getArg(0)->HasSideEffects(Info.Ctx))
14530 return Success((Type & 2) ? 0 : -1, E);
14531
14532 // Expression had no side effects, but we couldn't statically determine the
14533 // size of the referenced object.
14534 switch (Info.EvalMode) {
14535 case EvaluationMode::ConstantExpression:
14536 case EvaluationMode::ConstantFold:
14537 case EvaluationMode::IgnoreSideEffects:
14538 // Leave it to IR generation.
14539 return Error(E);
14540 case EvaluationMode::ConstantExpressionUnevaluated:
14541 // Reduce it to a constant now.
14542 return Success((Type & 2) ? 0 : -1, E);
14543 }
14544
14545 llvm_unreachable("unexpected EvalMode");
14546 }
14547
14548 case Builtin::BI__builtin_os_log_format_buffer_size: {
14549 analyze_os_log::OSLogBufferLayout Layout;
14550 analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
14551 return Success(Layout.size().getQuantity(), E);
14552 }
14553
14554 case Builtin::BI__builtin_is_aligned: {
14555 APValue Src;
14556 APSInt Alignment;
14557 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
14558 return false;
14559 if (Src.isLValue()) {
14560 // If we evaluated a pointer, check the minimum known alignment.
14561 LValue Ptr;
14562 Ptr.setFrom(Info.Ctx, Src);
14563 CharUnits BaseAlignment = getBaseAlignment(Info, Ptr);
14564 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset);
14565 // We can return true if the known alignment at the computed offset is
14566 // greater than the requested alignment.
14567 assert(PtrAlign.isPowerOfTwo());
14568 assert(Alignment.isPowerOf2());
14569 if (PtrAlign.getQuantity() >= Alignment)
14570 return Success(1, E);
14571 // If the alignment is not known to be sufficient, some cases could still
14572 // be aligned at run time. However, if the requested alignment is less or
14573 // equal to the base alignment and the offset is not aligned, we know that
14574 // the run-time value can never be aligned.
14575 if (BaseAlignment.getQuantity() >= Alignment &&
14576 PtrAlign.getQuantity() < Alignment)
14577 return Success(0, E);
14578 // Otherwise we can't infer whether the value is sufficiently aligned.
14579 // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N)
14580 // in cases where we can't fully evaluate the pointer.
14581 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute)
14582 << Alignment;
14583 return false;
14584 }
14585 assert(Src.isInt());
14586 return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E);
14587 }
14588 case Builtin::BI__builtin_align_up: {
14589 APValue Src;
14590 APSInt Alignment;
14591 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
14592 return false;
14593 if (!Src.isInt())
14594 return Error(E);
14595 APSInt AlignedVal =
14596 APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1),
14597 Src.getInt().isUnsigned());
14598 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
14599 return Success(AlignedVal, E);
14600 }
14601 case Builtin::BI__builtin_align_down: {
14602 APValue Src;
14603 APSInt Alignment;
14604 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
14605 return false;
14606 if (!Src.isInt())
14607 return Error(E);
14608 APSInt AlignedVal =
14609 APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned());
14610 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
14611 return Success(AlignedVal, E);
14612 }
14613
14614 case Builtin::BI__builtin_bitreverse8:
14615 case Builtin::BI__builtin_bitreverse16:
14616 case Builtin::BI__builtin_bitreverse32:
14617 case Builtin::BI__builtin_bitreverse64:
14618 case Builtin::BI__builtin_elementwise_bitreverse: {
14619 APSInt Val;
14620 if (!EvaluateInteger(E->getArg(0), Val, Info))
14621 return false;
14622
14623 return Success(Val.reverseBits(), E);
14624 }
14625
14626 case Builtin::BI__builtin_bswap16:
14627 case Builtin::BI__builtin_bswap32:
14628 case Builtin::BI__builtin_bswap64: {
14629 APSInt Val;
14630 if (!EvaluateInteger(E->getArg(0), Val, Info))
14631 return false;
14632
14633 return Success(Val.byteSwap(), E);
14634 }
14635
14636 case Builtin::BI__builtin_classify_type:
14637 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
14638
14639 case Builtin::BI__builtin_clrsb:
14640 case Builtin::BI__builtin_clrsbl:
14641 case Builtin::BI__builtin_clrsbll: {
14642 APSInt Val;
14643 if (!EvaluateInteger(E->getArg(0), Val, Info))
14644 return false;
14645
14646 return Success(Val.getBitWidth() - Val.getSignificantBits(), E);
14647 }
14648
14649 case Builtin::BI__builtin_clz:
14650 case Builtin::BI__builtin_clzl:
14651 case Builtin::BI__builtin_clzll:
14652 case Builtin::BI__builtin_clzs:
14653 case Builtin::BI__builtin_clzg:
14654 case Builtin::BI__builtin_elementwise_clzg:
14655 case Builtin::BI__lzcnt16: // Microsoft variants of count leading-zeroes
14656 case Builtin::BI__lzcnt:
14657 case Builtin::BI__lzcnt64: {
14658 APSInt Val;
14659 if (E->getArg(0)->getType()->isExtVectorBoolType()) {
14660 APValue Vec;
14661 if (!EvaluateVector(E->getArg(0), Vec, Info))
14662 return false;
14663 Val = ConvertBoolVectorToInt(Vec);
14664 } else if (!EvaluateInteger(E->getArg(0), Val, Info)) {
14665 return false;
14666 }
14667
14668 std::optional<APSInt> Fallback;
14669 if ((BuiltinOp == Builtin::BI__builtin_clzg ||
14670 BuiltinOp == Builtin::BI__builtin_elementwise_clzg) &&
14671 E->getNumArgs() > 1) {
14672 APSInt FallbackTemp;
14673 if (!EvaluateInteger(E->getArg(1), FallbackTemp, Info))
14674 return false;
14675 Fallback = FallbackTemp;
14676 }
14677
14678 if (!Val) {
14679 if (Fallback)
14680 return Success(*Fallback, E);
14681
14682 // When the argument is 0, the result of GCC builtins is undefined,
14683 // whereas for Microsoft intrinsics, the result is the bit-width of the
14684 // argument.
14685 bool ZeroIsUndefined = BuiltinOp != Builtin::BI__lzcnt16 &&
14686 BuiltinOp != Builtin::BI__lzcnt &&
14687 BuiltinOp != Builtin::BI__lzcnt64;
14688
14689 if (BuiltinOp == Builtin::BI__builtin_elementwise_clzg) {
14690 Info.FFDiag(E, diag::note_constexpr_countzeroes_zero)
14691 << /*IsTrailing=*/false;
14692 }
14693
14694 if (ZeroIsUndefined)
14695 return Error(E);
14696 }
14697
14698 return Success(Val.countl_zero(), E);
14699 }
14700
14701 case Builtin::BI__builtin_constant_p: {
14702 const Expr *Arg = E->getArg(0);
14703 if (EvaluateBuiltinConstantP(Info, Arg))
14704 return Success(true, E);
14705 if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
14706 // Outside a constant context, eagerly evaluate to false in the presence
14707 // of side-effects in order to avoid -Wunsequenced false-positives in
14708 // a branch on __builtin_constant_p(expr).
14709 return Success(false, E);
14710 }
14711 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
14712 return false;
14713 }
14714
14715 case Builtin::BI__noop:
14716 // __noop always evaluates successfully and returns 0.
14717 return Success(0, E);
14718
14719 case Builtin::BI__builtin_is_constant_evaluated: {
14720 const auto *Callee = Info.CurrentCall->getCallee();
14721 if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression &&
14722 (Info.CallStackDepth == 1 ||
14723 (Info.CallStackDepth == 2 && Callee->isInStdNamespace() &&
14724 Callee->getIdentifier() &&
14725 Callee->getIdentifier()->isStr("is_constant_evaluated")))) {
14726 // FIXME: Find a better way to avoid duplicated diagnostics.
14727 if (Info.EvalStatus.Diag)
14728 Info.report((Info.CallStackDepth == 1)
14729 ? E->getExprLoc()
14730 : Info.CurrentCall->getCallRange().getBegin(),
14731 diag::warn_is_constant_evaluated_always_true_constexpr)
14732 << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated"
14733 : "std::is_constant_evaluated");
14734 }
14735
14736 return Success(Info.InConstantContext, E);
14737 }
14738
14739 case Builtin::BI__builtin_is_within_lifetime:
14740 if (auto result = EvaluateBuiltinIsWithinLifetime(*this, E))
14741 return Success(*result, E);
14742 return false;
14743
14744 case Builtin::BI__builtin_ctz:
14745 case Builtin::BI__builtin_ctzl:
14746 case Builtin::BI__builtin_ctzll:
14747 case Builtin::BI__builtin_ctzs:
14748 case Builtin::BI__builtin_ctzg:
14749 case Builtin::BI__builtin_elementwise_ctzg: {
14750 APSInt Val;
14751 if (E->getArg(0)->getType()->isExtVectorBoolType()) {
14752 APValue Vec;
14753 if (!EvaluateVector(E->getArg(0), Vec, Info))
14754 return false;
14755 Val = ConvertBoolVectorToInt(Vec);
14756 } else if (!EvaluateInteger(E->getArg(0), Val, Info)) {
14757 return false;
14758 }
14759
14760 std::optional<APSInt> Fallback;
14761 if ((BuiltinOp == Builtin::BI__builtin_ctzg ||
14762 BuiltinOp == Builtin::BI__builtin_elementwise_ctzg) &&
14763 E->getNumArgs() > 1) {
14764 APSInt FallbackTemp;
14765 if (!EvaluateInteger(E->getArg(1), FallbackTemp, Info))
14766 return false;
14767 Fallback = FallbackTemp;
14768 }
14769
14770 if (!Val) {
14771 if (Fallback)
14772 return Success(*Fallback, E);
14773
14774 if (BuiltinOp == Builtin::BI__builtin_elementwise_ctzg) {
14775 Info.FFDiag(E, diag::note_constexpr_countzeroes_zero)
14776 << /*IsTrailing=*/true;
14777 }
14778 return Error(E);
14779 }
14780
14781 return Success(Val.countr_zero(), E);
14782 }
14783
14784 case Builtin::BI__builtin_eh_return_data_regno: {
14785 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
14786 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
14787 return Success(Operand, E);
14788 }
14789
14790 case Builtin::BI__builtin_elementwise_abs: {
14791 APSInt Val;
14792 if (!EvaluateInteger(E->getArg(0), Val, Info))
14793 return false;
14794
14795 return Success(Val.abs(), E);
14796 }
14797
14798 case Builtin::BI__builtin_expect:
14799 case Builtin::BI__builtin_expect_with_probability:
14800 return Visit(E->getArg(0));
14801
14802 case Builtin::BI__builtin_ptrauth_string_discriminator: {
14803 const auto *Literal =
14805 uint64_t Result = getPointerAuthStableSipHash(Literal->getString());
14806 return Success(Result, E);
14807 }
14808
14809 case Builtin::BI__builtin_infer_alloc_token: {
14810 // If we fail to infer a type, this fails to be a constant expression; this
14811 // can be checked with __builtin_constant_p(...).
14812 QualType AllocType = infer_alloc::inferPossibleType(E, Info.Ctx, nullptr);
14813 if (AllocType.isNull())
14814 return Error(
14815 E, diag::note_constexpr_infer_alloc_token_type_inference_failed);
14816 auto ATMD = infer_alloc::getAllocTokenMetadata(AllocType, Info.Ctx);
14817 if (!ATMD)
14818 return Error(E, diag::note_constexpr_infer_alloc_token_no_metadata);
14819 auto Mode =
14820 Info.getLangOpts().AllocTokenMode.value_or(llvm::DefaultAllocTokenMode);
14821 uint64_t BitWidth = Info.Ctx.getTypeSize(Info.Ctx.getSizeType());
14822 uint64_t MaxTokens =
14823 Info.getLangOpts().AllocTokenMax.value_or(~0ULL >> (64 - BitWidth));
14824 auto MaybeToken = llvm::getAllocToken(Mode, *ATMD, MaxTokens);
14825 if (!MaybeToken)
14826 return Error(E, diag::note_constexpr_infer_alloc_token_stateful_mode);
14827 return Success(llvm::APInt(BitWidth, *MaybeToken), E);
14828 }
14829
14830 case Builtin::BI__builtin_ffs:
14831 case Builtin::BI__builtin_ffsl:
14832 case Builtin::BI__builtin_ffsll: {
14833 APSInt Val;
14834 if (!EvaluateInteger(E->getArg(0), Val, Info))
14835 return false;
14836
14837 unsigned N = Val.countr_zero();
14838 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
14839 }
14840
14841 case Builtin::BI__builtin_fpclassify: {
14842 APFloat Val(0.0);
14843 if (!EvaluateFloat(E->getArg(5), Val, Info))
14844 return false;
14845 unsigned Arg;
14846 switch (Val.getCategory()) {
14847 case APFloat::fcNaN: Arg = 0; break;
14848 case APFloat::fcInfinity: Arg = 1; break;
14849 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
14850 case APFloat::fcZero: Arg = 4; break;
14851 }
14852 return Visit(E->getArg(Arg));
14853 }
14854
14855 case Builtin::BI__builtin_isinf_sign: {
14856 APFloat Val(0.0);
14857 return EvaluateFloat(E->getArg(0), Val, Info) &&
14858 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
14859 }
14860
14861 case Builtin::BI__builtin_isinf: {
14862 APFloat Val(0.0);
14863 return EvaluateFloat(E->getArg(0), Val, Info) &&
14864 Success(Val.isInfinity() ? 1 : 0, E);
14865 }
14866
14867 case Builtin::BI__builtin_isfinite: {
14868 APFloat Val(0.0);
14869 return EvaluateFloat(E->getArg(0), Val, Info) &&
14870 Success(Val.isFinite() ? 1 : 0, E);
14871 }
14872
14873 case Builtin::BI__builtin_isnan: {
14874 APFloat Val(0.0);
14875 return EvaluateFloat(E->getArg(0), Val, Info) &&
14876 Success(Val.isNaN() ? 1 : 0, E);
14877 }
14878
14879 case Builtin::BI__builtin_isnormal: {
14880 APFloat Val(0.0);
14881 return EvaluateFloat(E->getArg(0), Val, Info) &&
14882 Success(Val.isNormal() ? 1 : 0, E);
14883 }
14884
14885 case Builtin::BI__builtin_issubnormal: {
14886 APFloat Val(0.0);
14887 return EvaluateFloat(E->getArg(0), Val, Info) &&
14888 Success(Val.isDenormal() ? 1 : 0, E);
14889 }
14890
14891 case Builtin::BI__builtin_iszero: {
14892 APFloat Val(0.0);
14893 return EvaluateFloat(E->getArg(0), Val, Info) &&
14894 Success(Val.isZero() ? 1 : 0, E);
14895 }
14896
14897 case Builtin::BI__builtin_signbit:
14898 case Builtin::BI__builtin_signbitf:
14899 case Builtin::BI__builtin_signbitl: {
14900 APFloat Val(0.0);
14901 return EvaluateFloat(E->getArg(0), Val, Info) &&
14902 Success(Val.isNegative() ? 1 : 0, E);
14903 }
14904
14905 case Builtin::BI__builtin_isgreater:
14906 case Builtin::BI__builtin_isgreaterequal:
14907 case Builtin::BI__builtin_isless:
14908 case Builtin::BI__builtin_islessequal:
14909 case Builtin::BI__builtin_islessgreater:
14910 case Builtin::BI__builtin_isunordered: {
14911 APFloat LHS(0.0);
14912 APFloat RHS(0.0);
14913 if (!EvaluateFloat(E->getArg(0), LHS, Info) ||
14914 !EvaluateFloat(E->getArg(1), RHS, Info))
14915 return false;
14916
14917 return Success(
14918 [&] {
14919 switch (BuiltinOp) {
14920 case Builtin::BI__builtin_isgreater:
14921 return LHS > RHS;
14922 case Builtin::BI__builtin_isgreaterequal:
14923 return LHS >= RHS;
14924 case Builtin::BI__builtin_isless:
14925 return LHS < RHS;
14926 case Builtin::BI__builtin_islessequal:
14927 return LHS <= RHS;
14928 case Builtin::BI__builtin_islessgreater: {
14929 APFloat::cmpResult cmp = LHS.compare(RHS);
14930 return cmp == APFloat::cmpResult::cmpLessThan ||
14931 cmp == APFloat::cmpResult::cmpGreaterThan;
14932 }
14933 case Builtin::BI__builtin_isunordered:
14934 return LHS.compare(RHS) == APFloat::cmpResult::cmpUnordered;
14935 default:
14936 llvm_unreachable("Unexpected builtin ID: Should be a floating "
14937 "point comparison function");
14938 }
14939 }()
14940 ? 1
14941 : 0,
14942 E);
14943 }
14944
14945 case Builtin::BI__builtin_issignaling: {
14946 APFloat Val(0.0);
14947 return EvaluateFloat(E->getArg(0), Val, Info) &&
14948 Success(Val.isSignaling() ? 1 : 0, E);
14949 }
14950
14951 case Builtin::BI__builtin_isfpclass: {
14952 APSInt MaskVal;
14953 if (!EvaluateInteger(E->getArg(1), MaskVal, Info))
14954 return false;
14955 unsigned Test = static_cast<llvm::FPClassTest>(MaskVal.getZExtValue());
14956 APFloat Val(0.0);
14957 return EvaluateFloat(E->getArg(0), Val, Info) &&
14958 Success((Val.classify() & Test) ? 1 : 0, E);
14959 }
14960
14961 case Builtin::BI__builtin_parity:
14962 case Builtin::BI__builtin_parityl:
14963 case Builtin::BI__builtin_parityll: {
14964 APSInt Val;
14965 if (!EvaluateInteger(E->getArg(0), Val, Info))
14966 return false;
14967
14968 return Success(Val.popcount() % 2, E);
14969 }
14970
14971 case Builtin::BI__builtin_abs:
14972 case Builtin::BI__builtin_labs:
14973 case Builtin::BI__builtin_llabs: {
14974 APSInt Val;
14975 if (!EvaluateInteger(E->getArg(0), Val, Info))
14976 return false;
14977 if (Val == APSInt(APInt::getSignedMinValue(Val.getBitWidth()),
14978 /*IsUnsigned=*/false))
14979 return false;
14980 if (Val.isNegative())
14981 Val.negate();
14982 return Success(Val, E);
14983 }
14984
14985 case Builtin::BI__builtin_popcount:
14986 case Builtin::BI__builtin_popcountl:
14987 case Builtin::BI__builtin_popcountll:
14988 case Builtin::BI__builtin_popcountg:
14989 case Builtin::BI__builtin_elementwise_popcount:
14990 case Builtin::BI__popcnt16: // Microsoft variants of popcount
14991 case Builtin::BI__popcnt:
14992 case Builtin::BI__popcnt64: {
14993 APSInt Val;
14994 if (E->getArg(0)->getType()->isExtVectorBoolType()) {
14995 APValue Vec;
14996 if (!EvaluateVector(E->getArg(0), Vec, Info))
14997 return false;
14998 Val = ConvertBoolVectorToInt(Vec);
14999 } else if (!EvaluateInteger(E->getArg(0), Val, Info)) {
15000 return false;
15001 }
15002
15003 return Success(Val.popcount(), E);
15004 }
15005
15006 case Builtin::BI__builtin_rotateleft8:
15007 case Builtin::BI__builtin_rotateleft16:
15008 case Builtin::BI__builtin_rotateleft32:
15009 case Builtin::BI__builtin_rotateleft64:
15010 case Builtin::BI_rotl8: // Microsoft variants of rotate right
15011 case Builtin::BI_rotl16:
15012 case Builtin::BI_rotl:
15013 case Builtin::BI_lrotl:
15014 case Builtin::BI_rotl64: {
15015 APSInt Val, Amt;
15016 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
15017 !EvaluateInteger(E->getArg(1), Amt, Info))
15018 return false;
15019
15020 return Success(Val.rotl(Amt), E);
15021 }
15022
15023 case Builtin::BI__builtin_rotateright8:
15024 case Builtin::BI__builtin_rotateright16:
15025 case Builtin::BI__builtin_rotateright32:
15026 case Builtin::BI__builtin_rotateright64:
15027 case Builtin::BI_rotr8: // Microsoft variants of rotate right
15028 case Builtin::BI_rotr16:
15029 case Builtin::BI_rotr:
15030 case Builtin::BI_lrotr:
15031 case Builtin::BI_rotr64: {
15032 APSInt Val, Amt;
15033 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
15034 !EvaluateInteger(E->getArg(1), Amt, Info))
15035 return false;
15036
15037 return Success(Val.rotr(Amt), E);
15038 }
15039
15040 case Builtin::BI__builtin_elementwise_add_sat: {
15041 APSInt LHS, RHS;
15042 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
15043 !EvaluateInteger(E->getArg(1), RHS, Info))
15044 return false;
15045
15046 APInt Result = LHS.isSigned() ? LHS.sadd_sat(RHS) : LHS.uadd_sat(RHS);
15047 return Success(APSInt(Result, !LHS.isSigned()), E);
15048 }
15049 case Builtin::BI__builtin_elementwise_sub_sat: {
15050 APSInt LHS, RHS;
15051 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
15052 !EvaluateInteger(E->getArg(1), RHS, Info))
15053 return false;
15054
15055 APInt Result = LHS.isSigned() ? LHS.ssub_sat(RHS) : LHS.usub_sat(RHS);
15056 return Success(APSInt(Result, !LHS.isSigned()), E);
15057 }
15058 case Builtin::BI__builtin_elementwise_max: {
15059 APSInt LHS, RHS;
15060 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
15061 !EvaluateInteger(E->getArg(1), RHS, Info))
15062 return false;
15063
15064 APInt Result = std::max(LHS, RHS);
15065 return Success(APSInt(Result, !LHS.isSigned()), E);
15066 }
15067 case Builtin::BI__builtin_elementwise_min: {
15068 APSInt LHS, RHS;
15069 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
15070 !EvaluateInteger(E->getArg(1), RHS, Info))
15071 return false;
15072
15073 APInt Result = std::min(LHS, RHS);
15074 return Success(APSInt(Result, !LHS.isSigned()), E);
15075 }
15076 case Builtin::BI__builtin_elementwise_fshl:
15077 case Builtin::BI__builtin_elementwise_fshr: {
15078 APSInt Hi, Lo, Shift;
15079 if (!EvaluateInteger(E->getArg(0), Hi, Info) ||
15080 !EvaluateInteger(E->getArg(1), Lo, Info) ||
15081 !EvaluateInteger(E->getArg(2), Shift, Info))
15082 return false;
15083
15084 switch (BuiltinOp) {
15085 case Builtin::BI__builtin_elementwise_fshl: {
15086 APSInt Result(llvm::APIntOps::fshl(Hi, Lo, Shift), Hi.isUnsigned());
15087 return Success(Result, E);
15088 }
15089 case Builtin::BI__builtin_elementwise_fshr: {
15090 APSInt Result(llvm::APIntOps::fshr(Hi, Lo, Shift), Hi.isUnsigned());
15091 return Success(Result, E);
15092 }
15093 }
15094 llvm_unreachable("Fully covered switch above");
15095 }
15096 case Builtin::BIstrlen:
15097 case Builtin::BIwcslen:
15098 // A call to strlen is not a constant expression.
15099 if (Info.getLangOpts().CPlusPlus11)
15100 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
15101 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
15102 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
15103 else
15104 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
15105 [[fallthrough]];
15106 case Builtin::BI__builtin_strlen:
15107 case Builtin::BI__builtin_wcslen: {
15108 // As an extension, we support __builtin_strlen() as a constant expression,
15109 // and support folding strlen() to a constant.
15110 uint64_t StrLen;
15111 if (EvaluateBuiltinStrLen(E->getArg(0), StrLen, Info))
15112 return Success(StrLen, E);
15113 return false;
15114 }
15115
15116 case Builtin::BIstrcmp:
15117 case Builtin::BIwcscmp:
15118 case Builtin::BIstrncmp:
15119 case Builtin::BIwcsncmp:
15120 case Builtin::BImemcmp:
15121 case Builtin::BIbcmp:
15122 case Builtin::BIwmemcmp:
15123 // A call to strlen is not a constant expression.
15124 if (Info.getLangOpts().CPlusPlus11)
15125 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
15126 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
15127 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
15128 else
15129 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
15130 [[fallthrough]];
15131 case Builtin::BI__builtin_strcmp:
15132 case Builtin::BI__builtin_wcscmp:
15133 case Builtin::BI__builtin_strncmp:
15134 case Builtin::BI__builtin_wcsncmp:
15135 case Builtin::BI__builtin_memcmp:
15136 case Builtin::BI__builtin_bcmp:
15137 case Builtin::BI__builtin_wmemcmp: {
15138 LValue String1, String2;
15139 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
15140 !EvaluatePointer(E->getArg(1), String2, Info))
15141 return false;
15142
15143 uint64_t MaxLength = uint64_t(-1);
15144 if (BuiltinOp != Builtin::BIstrcmp &&
15145 BuiltinOp != Builtin::BIwcscmp &&
15146 BuiltinOp != Builtin::BI__builtin_strcmp &&
15147 BuiltinOp != Builtin::BI__builtin_wcscmp) {
15148 APSInt N;
15149 if (!EvaluateInteger(E->getArg(2), N, Info))
15150 return false;
15151 MaxLength = N.getZExtValue();
15152 }
15153
15154 // Empty substrings compare equal by definition.
15155 if (MaxLength == 0u)
15156 return Success(0, E);
15157
15158 if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
15159 !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
15160 String1.Designator.Invalid || String2.Designator.Invalid)
15161 return false;
15162
15163 QualType CharTy1 = String1.Designator.getType(Info.Ctx);
15164 QualType CharTy2 = String2.Designator.getType(Info.Ctx);
15165
15166 bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
15167 BuiltinOp == Builtin::BIbcmp ||
15168 BuiltinOp == Builtin::BI__builtin_memcmp ||
15169 BuiltinOp == Builtin::BI__builtin_bcmp;
15170
15171 assert(IsRawByte ||
15172 (Info.Ctx.hasSameUnqualifiedType(
15173 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
15174 Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
15175
15176 // For memcmp, allow comparing any arrays of '[[un]signed] char' or
15177 // 'char8_t', but no other types.
15178 if (IsRawByte &&
15179 !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) {
15180 // FIXME: Consider using our bit_cast implementation to support this.
15181 Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported)
15182 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp) << CharTy1
15183 << CharTy2;
15184 return false;
15185 }
15186
15187 const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
15188 return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
15189 handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
15190 Char1.isInt() && Char2.isInt();
15191 };
15192 const auto &AdvanceElems = [&] {
15193 return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
15194 HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
15195 };
15196
15197 bool StopAtNull =
15198 (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
15199 BuiltinOp != Builtin::BIwmemcmp &&
15200 BuiltinOp != Builtin::BI__builtin_memcmp &&
15201 BuiltinOp != Builtin::BI__builtin_bcmp &&
15202 BuiltinOp != Builtin::BI__builtin_wmemcmp);
15203 bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
15204 BuiltinOp == Builtin::BIwcsncmp ||
15205 BuiltinOp == Builtin::BIwmemcmp ||
15206 BuiltinOp == Builtin::BI__builtin_wcscmp ||
15207 BuiltinOp == Builtin::BI__builtin_wcsncmp ||
15208 BuiltinOp == Builtin::BI__builtin_wmemcmp;
15209
15210 for (; MaxLength; --MaxLength) {
15211 APValue Char1, Char2;
15212 if (!ReadCurElems(Char1, Char2))
15213 return false;
15214 if (Char1.getInt().ne(Char2.getInt())) {
15215 if (IsWide) // wmemcmp compares with wchar_t signedness.
15216 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
15217 // memcmp always compares unsigned chars.
15218 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
15219 }
15220 if (StopAtNull && !Char1.getInt())
15221 return Success(0, E);
15222 assert(!(StopAtNull && !Char2.getInt()));
15223 if (!AdvanceElems())
15224 return false;
15225 }
15226 // We hit the strncmp / memcmp limit.
15227 return Success(0, E);
15228 }
15229
15230 case Builtin::BI__atomic_always_lock_free:
15231 case Builtin::BI__atomic_is_lock_free:
15232 case Builtin::BI__c11_atomic_is_lock_free: {
15233 APSInt SizeVal;
15234 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
15235 return false;
15236
15237 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
15238 // of two less than or equal to the maximum inline atomic width, we know it
15239 // is lock-free. If the size isn't a power of two, or greater than the
15240 // maximum alignment where we promote atomics, we know it is not lock-free
15241 // (at least not in the sense of atomic_is_lock_free). Otherwise,
15242 // the answer can only be determined at runtime; for example, 16-byte
15243 // atomics have lock-free implementations on some, but not all,
15244 // x86-64 processors.
15245
15246 // Check power-of-two.
15247 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
15248 if (Size.isPowerOfTwo()) {
15249 // Check against inlining width.
15250 unsigned InlineWidthBits =
15252 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
15253 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
15254 Size == CharUnits::One())
15255 return Success(1, E);
15256
15257 // If the pointer argument can be evaluated to a compile-time constant
15258 // integer (or nullptr), check if that value is appropriately aligned.
15259 const Expr *PtrArg = E->getArg(1);
15260 Expr::EvalResult ExprResult;
15261 APSInt IntResult;
15262 if (PtrArg->EvaluateAsRValue(ExprResult, Info.Ctx) &&
15263 ExprResult.Val.toIntegralConstant(IntResult, PtrArg->getType(),
15264 Info.Ctx) &&
15265 IntResult.isAligned(Size.getAsAlign()))
15266 return Success(1, E);
15267
15268 // Otherwise, check if the type's alignment against Size.
15269 if (auto *ICE = dyn_cast<ImplicitCastExpr>(PtrArg)) {
15270 // Drop the potential implicit-cast to 'const volatile void*', getting
15271 // the underlying type.
15272 if (ICE->getCastKind() == CK_BitCast)
15273 PtrArg = ICE->getSubExpr();
15274 }
15275
15276 if (auto PtrTy = PtrArg->getType()->getAs<PointerType>()) {
15277 QualType PointeeType = PtrTy->getPointeeType();
15278 if (!PointeeType->isIncompleteType() &&
15279 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
15280 // OK, we will inline operations on this object.
15281 return Success(1, E);
15282 }
15283 }
15284 }
15285 }
15286
15287 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
15288 Success(0, E) : Error(E);
15289 }
15290 case Builtin::BI__builtin_addcb:
15291 case Builtin::BI__builtin_addcs:
15292 case Builtin::BI__builtin_addc:
15293 case Builtin::BI__builtin_addcl:
15294 case Builtin::BI__builtin_addcll:
15295 case Builtin::BI__builtin_subcb:
15296 case Builtin::BI__builtin_subcs:
15297 case Builtin::BI__builtin_subc:
15298 case Builtin::BI__builtin_subcl:
15299 case Builtin::BI__builtin_subcll: {
15300 LValue CarryOutLValue;
15301 APSInt LHS, RHS, CarryIn, CarryOut, Result;
15302 QualType ResultType = E->getArg(0)->getType();
15303 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
15304 !EvaluateInteger(E->getArg(1), RHS, Info) ||
15305 !EvaluateInteger(E->getArg(2), CarryIn, Info) ||
15306 !EvaluatePointer(E->getArg(3), CarryOutLValue, Info))
15307 return false;
15308 // Copy the number of bits and sign.
15309 Result = LHS;
15310 CarryOut = LHS;
15311
15312 bool FirstOverflowed = false;
15313 bool SecondOverflowed = false;
15314 switch (BuiltinOp) {
15315 default:
15316 llvm_unreachable("Invalid value for BuiltinOp");
15317 case Builtin::BI__builtin_addcb:
15318 case Builtin::BI__builtin_addcs:
15319 case Builtin::BI__builtin_addc:
15320 case Builtin::BI__builtin_addcl:
15321 case Builtin::BI__builtin_addcll:
15322 Result =
15323 LHS.uadd_ov(RHS, FirstOverflowed).uadd_ov(CarryIn, SecondOverflowed);
15324 break;
15325 case Builtin::BI__builtin_subcb:
15326 case Builtin::BI__builtin_subcs:
15327 case Builtin::BI__builtin_subc:
15328 case Builtin::BI__builtin_subcl:
15329 case Builtin::BI__builtin_subcll:
15330 Result =
15331 LHS.usub_ov(RHS, FirstOverflowed).usub_ov(CarryIn, SecondOverflowed);
15332 break;
15333 }
15334
15335 // It is possible for both overflows to happen but CGBuiltin uses an OR so
15336 // this is consistent.
15337 CarryOut = (uint64_t)(FirstOverflowed | SecondOverflowed);
15338 APValue APV{CarryOut};
15339 if (!handleAssignment(Info, E, CarryOutLValue, ResultType, APV))
15340 return false;
15341 return Success(Result, E);
15342 }
15343 case Builtin::BI__builtin_add_overflow:
15344 case Builtin::BI__builtin_sub_overflow:
15345 case Builtin::BI__builtin_mul_overflow:
15346 case Builtin::BI__builtin_sadd_overflow:
15347 case Builtin::BI__builtin_uadd_overflow:
15348 case Builtin::BI__builtin_uaddl_overflow:
15349 case Builtin::BI__builtin_uaddll_overflow:
15350 case Builtin::BI__builtin_usub_overflow:
15351 case Builtin::BI__builtin_usubl_overflow:
15352 case Builtin::BI__builtin_usubll_overflow:
15353 case Builtin::BI__builtin_umul_overflow:
15354 case Builtin::BI__builtin_umull_overflow:
15355 case Builtin::BI__builtin_umulll_overflow:
15356 case Builtin::BI__builtin_saddl_overflow:
15357 case Builtin::BI__builtin_saddll_overflow:
15358 case Builtin::BI__builtin_ssub_overflow:
15359 case Builtin::BI__builtin_ssubl_overflow:
15360 case Builtin::BI__builtin_ssubll_overflow:
15361 case Builtin::BI__builtin_smul_overflow:
15362 case Builtin::BI__builtin_smull_overflow:
15363 case Builtin::BI__builtin_smulll_overflow: {
15364 LValue ResultLValue;
15365 APSInt LHS, RHS;
15366
15367 QualType ResultType = E->getArg(2)->getType()->getPointeeType();
15368 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
15369 !EvaluateInteger(E->getArg(1), RHS, Info) ||
15370 !EvaluatePointer(E->getArg(2), ResultLValue, Info))
15371 return false;
15372
15373 APSInt Result;
15374 bool DidOverflow = false;
15375
15376 // If the types don't have to match, enlarge all 3 to the largest of them.
15377 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
15378 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
15379 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
15380 bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
15382 bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
15384 uint64_t LHSSize = LHS.getBitWidth();
15385 uint64_t RHSSize = RHS.getBitWidth();
15386 uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
15387 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
15388
15389 // Add an additional bit if the signedness isn't uniformly agreed to. We
15390 // could do this ONLY if there is a signed and an unsigned that both have
15391 // MaxBits, but the code to check that is pretty nasty. The issue will be
15392 // caught in the shrink-to-result later anyway.
15393 if (IsSigned && !AllSigned)
15394 ++MaxBits;
15395
15396 LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
15397 RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
15398 Result = APSInt(MaxBits, !IsSigned);
15399 }
15400
15401 // Find largest int.
15402 switch (BuiltinOp) {
15403 default:
15404 llvm_unreachable("Invalid value for BuiltinOp");
15405 case Builtin::BI__builtin_add_overflow:
15406 case Builtin::BI__builtin_sadd_overflow:
15407 case Builtin::BI__builtin_saddl_overflow:
15408 case Builtin::BI__builtin_saddll_overflow:
15409 case Builtin::BI__builtin_uadd_overflow:
15410 case Builtin::BI__builtin_uaddl_overflow:
15411 case Builtin::BI__builtin_uaddll_overflow:
15412 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
15413 : LHS.uadd_ov(RHS, DidOverflow);
15414 break;
15415 case Builtin::BI__builtin_sub_overflow:
15416 case Builtin::BI__builtin_ssub_overflow:
15417 case Builtin::BI__builtin_ssubl_overflow:
15418 case Builtin::BI__builtin_ssubll_overflow:
15419 case Builtin::BI__builtin_usub_overflow:
15420 case Builtin::BI__builtin_usubl_overflow:
15421 case Builtin::BI__builtin_usubll_overflow:
15422 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
15423 : LHS.usub_ov(RHS, DidOverflow);
15424 break;
15425 case Builtin::BI__builtin_mul_overflow:
15426 case Builtin::BI__builtin_smul_overflow:
15427 case Builtin::BI__builtin_smull_overflow:
15428 case Builtin::BI__builtin_smulll_overflow:
15429 case Builtin::BI__builtin_umul_overflow:
15430 case Builtin::BI__builtin_umull_overflow:
15431 case Builtin::BI__builtin_umulll_overflow:
15432 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
15433 : LHS.umul_ov(RHS, DidOverflow);
15434 break;
15435 }
15436
15437 // In the case where multiple sizes are allowed, truncate and see if
15438 // the values are the same.
15439 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
15440 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
15441 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
15442 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
15443 // since it will give us the behavior of a TruncOrSelf in the case where
15444 // its parameter <= its size. We previously set Result to be at least the
15445 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
15446 // will work exactly like TruncOrSelf.
15447 APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
15448 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
15449
15450 if (!APSInt::isSameValue(Temp, Result))
15451 DidOverflow = true;
15452 Result = Temp;
15453 }
15454
15455 APValue APV{Result};
15456 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
15457 return false;
15458 return Success(DidOverflow, E);
15459 }
15460
15461 case Builtin::BI__builtin_reduce_add:
15462 case Builtin::BI__builtin_reduce_mul:
15463 case Builtin::BI__builtin_reduce_and:
15464 case Builtin::BI__builtin_reduce_or:
15465 case Builtin::BI__builtin_reduce_xor:
15466 case Builtin::BI__builtin_reduce_min:
15467 case Builtin::BI__builtin_reduce_max: {
15468 APValue Source;
15469 if (!EvaluateAsRValue(Info, E->getArg(0), Source))
15470 return false;
15471
15472 unsigned SourceLen = Source.getVectorLength();
15473 APSInt Reduced = Source.getVectorElt(0).getInt();
15474 for (unsigned EltNum = 1; EltNum < SourceLen; ++EltNum) {
15475 switch (BuiltinOp) {
15476 default:
15477 return false;
15478 case Builtin::BI__builtin_reduce_add: {
15480 Info, E, Reduced, Source.getVectorElt(EltNum).getInt(),
15481 Reduced.getBitWidth() + 1, std::plus<APSInt>(), Reduced))
15482 return false;
15483 break;
15484 }
15485 case Builtin::BI__builtin_reduce_mul: {
15487 Info, E, Reduced, Source.getVectorElt(EltNum).getInt(),
15488 Reduced.getBitWidth() * 2, std::multiplies<APSInt>(), Reduced))
15489 return false;
15490 break;
15491 }
15492 case Builtin::BI__builtin_reduce_and: {
15493 Reduced &= Source.getVectorElt(EltNum).getInt();
15494 break;
15495 }
15496 case Builtin::BI__builtin_reduce_or: {
15497 Reduced |= Source.getVectorElt(EltNum).getInt();
15498 break;
15499 }
15500 case Builtin::BI__builtin_reduce_xor: {
15501 Reduced ^= Source.getVectorElt(EltNum).getInt();
15502 break;
15503 }
15504 case Builtin::BI__builtin_reduce_min: {
15505 Reduced = std::min(Reduced, Source.getVectorElt(EltNum).getInt());
15506 break;
15507 }
15508 case Builtin::BI__builtin_reduce_max: {
15509 Reduced = std::max(Reduced, Source.getVectorElt(EltNum).getInt());
15510 break;
15511 }
15512 }
15513 }
15514
15515 return Success(Reduced, E);
15516 }
15517
15518 case clang::X86::BI__builtin_ia32_addcarryx_u32:
15519 case clang::X86::BI__builtin_ia32_addcarryx_u64:
15520 case clang::X86::BI__builtin_ia32_subborrow_u32:
15521 case clang::X86::BI__builtin_ia32_subborrow_u64: {
15522 LValue ResultLValue;
15523 APSInt CarryIn, LHS, RHS;
15524 QualType ResultType = E->getArg(3)->getType()->getPointeeType();
15525 if (!EvaluateInteger(E->getArg(0), CarryIn, Info) ||
15526 !EvaluateInteger(E->getArg(1), LHS, Info) ||
15527 !EvaluateInteger(E->getArg(2), RHS, Info) ||
15528 !EvaluatePointer(E->getArg(3), ResultLValue, Info))
15529 return false;
15530
15531 bool IsAdd = BuiltinOp == clang::X86::BI__builtin_ia32_addcarryx_u32 ||
15532 BuiltinOp == clang::X86::BI__builtin_ia32_addcarryx_u64;
15533
15534 unsigned BitWidth = LHS.getBitWidth();
15535 unsigned CarryInBit = CarryIn.ugt(0) ? 1 : 0;
15536 APInt ExResult =
15537 IsAdd
15538 ? (LHS.zext(BitWidth + 1) + (RHS.zext(BitWidth + 1) + CarryInBit))
15539 : (LHS.zext(BitWidth + 1) - (RHS.zext(BitWidth + 1) + CarryInBit));
15540
15541 APInt Result = ExResult.extractBits(BitWidth, 0);
15542 uint64_t CarryOut = ExResult.extractBitsAsZExtValue(1, BitWidth);
15543
15544 APValue APV{APSInt(Result, /*isUnsigned=*/true)};
15545 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
15546 return false;
15547 return Success(CarryOut, E);
15548 }
15549
15550 case clang::X86::BI__builtin_ia32_movmskps:
15551 case clang::X86::BI__builtin_ia32_movmskpd:
15552 case clang::X86::BI__builtin_ia32_pmovmskb128:
15553 case clang::X86::BI__builtin_ia32_pmovmskb256:
15554 case clang::X86::BI__builtin_ia32_movmskps256:
15555 case clang::X86::BI__builtin_ia32_movmskpd256: {
15556 APValue Source;
15557 if (!Evaluate(Source, Info, E->getArg(0)))
15558 return false;
15559 unsigned SourceLen = Source.getVectorLength();
15560 const VectorType *VT = E->getArg(0)->getType()->castAs<VectorType>();
15561 QualType ElemQT = VT->getElementType();
15562 unsigned ResultLen = Info.Ctx.getTypeSize(
15563 E->getCallReturnType(Info.Ctx)); // Always 32-bit integer.
15564 APInt Result(ResultLen, 0);
15565
15566 for (unsigned I = 0; I != SourceLen; ++I) {
15567 APInt Elem;
15568 if (ElemQT->isIntegerType()) {
15569 Elem = Source.getVectorElt(I).getInt();
15570 } else if (ElemQT->isRealFloatingType()) {
15571 Elem = Source.getVectorElt(I).getFloat().bitcastToAPInt();
15572 } else {
15573 return false;
15574 }
15575 Result.setBitVal(I, Elem.isNegative());
15576 }
15577 return Success(Result, E);
15578 }
15579
15580 case clang::X86::BI__builtin_ia32_bextr_u32:
15581 case clang::X86::BI__builtin_ia32_bextr_u64:
15582 case clang::X86::BI__builtin_ia32_bextri_u32:
15583 case clang::X86::BI__builtin_ia32_bextri_u64: {
15584 APSInt Val, Idx;
15585 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
15586 !EvaluateInteger(E->getArg(1), Idx, Info))
15587 return false;
15588
15589 unsigned BitWidth = Val.getBitWidth();
15590 uint64_t Shift = Idx.extractBitsAsZExtValue(8, 0);
15591 uint64_t Length = Idx.extractBitsAsZExtValue(8, 8);
15592 Length = Length > BitWidth ? BitWidth : Length;
15593
15594 // Handle out of bounds cases.
15595 if (Length == 0 || Shift >= BitWidth)
15596 return Success(0, E);
15597
15598 uint64_t Result = Val.getZExtValue() >> Shift;
15599 Result &= llvm::maskTrailingOnes<uint64_t>(Length);
15600 return Success(Result, E);
15601 }
15602
15603 case clang::X86::BI__builtin_ia32_bzhi_si:
15604 case clang::X86::BI__builtin_ia32_bzhi_di: {
15605 APSInt Val, Idx;
15606 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
15607 !EvaluateInteger(E->getArg(1), Idx, Info))
15608 return false;
15609
15610 unsigned BitWidth = Val.getBitWidth();
15611 unsigned Index = Idx.extractBitsAsZExtValue(8, 0);
15612 if (Index < BitWidth)
15613 Val.clearHighBits(BitWidth - Index);
15614 return Success(Val, E);
15615 }
15616
15617 case clang::X86::BI__builtin_ia32_lzcnt_u16:
15618 case clang::X86::BI__builtin_ia32_lzcnt_u32:
15619 case clang::X86::BI__builtin_ia32_lzcnt_u64: {
15620 APSInt Val;
15621 if (!EvaluateInteger(E->getArg(0), Val, Info))
15622 return false;
15623 return Success(Val.countLeadingZeros(), E);
15624 }
15625
15626 case clang::X86::BI__builtin_ia32_tzcnt_u16:
15627 case clang::X86::BI__builtin_ia32_tzcnt_u32:
15628 case clang::X86::BI__builtin_ia32_tzcnt_u64: {
15629 APSInt Val;
15630 if (!EvaluateInteger(E->getArg(0), Val, Info))
15631 return false;
15632 return Success(Val.countTrailingZeros(), E);
15633 }
15634
15635 case clang::X86::BI__builtin_ia32_pdep_si:
15636 case clang::X86::BI__builtin_ia32_pdep_di: {
15637 APSInt Val, Msk;
15638 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
15639 !EvaluateInteger(E->getArg(1), Msk, Info))
15640 return false;
15641
15642 unsigned BitWidth = Val.getBitWidth();
15643 APInt Result = APInt::getZero(BitWidth);
15644 for (unsigned I = 0, P = 0; I != BitWidth; ++I)
15645 if (Msk[I])
15646 Result.setBitVal(I, Val[P++]);
15647 return Success(Result, E);
15648 }
15649
15650 case clang::X86::BI__builtin_ia32_pext_si:
15651 case clang::X86::BI__builtin_ia32_pext_di: {
15652 APSInt Val, Msk;
15653 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
15654 !EvaluateInteger(E->getArg(1), Msk, Info))
15655 return false;
15656
15657 unsigned BitWidth = Val.getBitWidth();
15658 APInt Result = APInt::getZero(BitWidth);
15659 for (unsigned I = 0, P = 0; I != BitWidth; ++I)
15660 if (Msk[I])
15661 Result.setBitVal(P++, Val[I]);
15662 return Success(Result, E);
15663 }
15664 case X86::BI__builtin_ia32_ptestz128:
15665 case X86::BI__builtin_ia32_ptestz256:
15666 case X86::BI__builtin_ia32_vtestzps:
15667 case X86::BI__builtin_ia32_vtestzps256:
15668 case X86::BI__builtin_ia32_vtestzpd:
15669 case X86::BI__builtin_ia32_vtestzpd256: {
15670 return EvalTestOp(
15671 [](const APInt &A, const APInt &B) { return (A & B) == 0; });
15672 }
15673 case X86::BI__builtin_ia32_ptestc128:
15674 case X86::BI__builtin_ia32_ptestc256:
15675 case X86::BI__builtin_ia32_vtestcps:
15676 case X86::BI__builtin_ia32_vtestcps256:
15677 case X86::BI__builtin_ia32_vtestcpd:
15678 case X86::BI__builtin_ia32_vtestcpd256: {
15679 return EvalTestOp(
15680 [](const APInt &A, const APInt &B) { return (~A & B) == 0; });
15681 }
15682 case X86::BI__builtin_ia32_ptestnzc128:
15683 case X86::BI__builtin_ia32_ptestnzc256:
15684 case X86::BI__builtin_ia32_vtestnzcps:
15685 case X86::BI__builtin_ia32_vtestnzcps256:
15686 case X86::BI__builtin_ia32_vtestnzcpd:
15687 case X86::BI__builtin_ia32_vtestnzcpd256: {
15688 return EvalTestOp([](const APInt &A, const APInt &B) {
15689 return ((A & B) != 0) && ((~A & B) != 0);
15690 });
15691 }
15692 case X86::BI__builtin_ia32_kandqi:
15693 case X86::BI__builtin_ia32_kandhi:
15694 case X86::BI__builtin_ia32_kandsi:
15695 case X86::BI__builtin_ia32_kanddi: {
15696 return HandleMaskBinOp(
15697 [](const APSInt &LHS, const APSInt &RHS) { return LHS & RHS; });
15698 }
15699
15700 case X86::BI__builtin_ia32_kandnqi:
15701 case X86::BI__builtin_ia32_kandnhi:
15702 case X86::BI__builtin_ia32_kandnsi:
15703 case X86::BI__builtin_ia32_kandndi: {
15704 return HandleMaskBinOp(
15705 [](const APSInt &LHS, const APSInt &RHS) { return ~LHS & RHS; });
15706 }
15707
15708 case X86::BI__builtin_ia32_korqi:
15709 case X86::BI__builtin_ia32_korhi:
15710 case X86::BI__builtin_ia32_korsi:
15711 case X86::BI__builtin_ia32_kordi: {
15712 return HandleMaskBinOp(
15713 [](const APSInt &LHS, const APSInt &RHS) { return LHS | RHS; });
15714 }
15715
15716 case X86::BI__builtin_ia32_kxnorqi:
15717 case X86::BI__builtin_ia32_kxnorhi:
15718 case X86::BI__builtin_ia32_kxnorsi:
15719 case X86::BI__builtin_ia32_kxnordi: {
15720 return HandleMaskBinOp(
15721 [](const APSInt &LHS, const APSInt &RHS) { return ~(LHS ^ RHS); });
15722 }
15723
15724 case X86::BI__builtin_ia32_kxorqi:
15725 case X86::BI__builtin_ia32_kxorhi:
15726 case X86::BI__builtin_ia32_kxorsi:
15727 case X86::BI__builtin_ia32_kxordi: {
15728 return HandleMaskBinOp(
15729 [](const APSInt &LHS, const APSInt &RHS) { return LHS ^ RHS; });
15730 }
15731
15732 case X86::BI__builtin_ia32_knotqi:
15733 case X86::BI__builtin_ia32_knothi:
15734 case X86::BI__builtin_ia32_knotsi:
15735 case X86::BI__builtin_ia32_knotdi: {
15736 APSInt Val;
15737 if (!EvaluateInteger(E->getArg(0), Val, Info))
15738 return false;
15739 APSInt Result = ~Val;
15740 return Success(APValue(Result), E);
15741 }
15742
15743 case X86::BI__builtin_ia32_kaddqi:
15744 case X86::BI__builtin_ia32_kaddhi:
15745 case X86::BI__builtin_ia32_kaddsi:
15746 case X86::BI__builtin_ia32_kadddi: {
15747 return HandleMaskBinOp(
15748 [](const APSInt &LHS, const APSInt &RHS) { return LHS + RHS; });
15749 }
15750
15751 case clang::X86::BI__builtin_ia32_vec_ext_v4hi:
15752 case clang::X86::BI__builtin_ia32_vec_ext_v16qi:
15753 case clang::X86::BI__builtin_ia32_vec_ext_v8hi:
15754 case clang::X86::BI__builtin_ia32_vec_ext_v4si:
15755 case clang::X86::BI__builtin_ia32_vec_ext_v2di:
15756 case clang::X86::BI__builtin_ia32_vec_ext_v32qi:
15757 case clang::X86::BI__builtin_ia32_vec_ext_v16hi:
15758 case clang::X86::BI__builtin_ia32_vec_ext_v8si:
15759 case clang::X86::BI__builtin_ia32_vec_ext_v4di: {
15760 APValue Vec;
15761 APSInt IdxAPS;
15762 if (!EvaluateVector(E->getArg(0), Vec, Info) ||
15763 !EvaluateInteger(E->getArg(1), IdxAPS, Info))
15764 return false;
15765 unsigned N = Vec.getVectorLength();
15766 unsigned Idx = static_cast<unsigned>(IdxAPS.getZExtValue() & (N - 1));
15767 return Success(Vec.getVectorElt(Idx).getInt(), E);
15768 }
15769
15770 case clang::X86::BI__builtin_ia32_cmpb128_mask:
15771 case clang::X86::BI__builtin_ia32_cmpw128_mask:
15772 case clang::X86::BI__builtin_ia32_cmpd128_mask:
15773 case clang::X86::BI__builtin_ia32_cmpq128_mask:
15774 case clang::X86::BI__builtin_ia32_cmpb256_mask:
15775 case clang::X86::BI__builtin_ia32_cmpw256_mask:
15776 case clang::X86::BI__builtin_ia32_cmpd256_mask:
15777 case clang::X86::BI__builtin_ia32_cmpq256_mask:
15778 case clang::X86::BI__builtin_ia32_cmpb512_mask:
15779 case clang::X86::BI__builtin_ia32_cmpw512_mask:
15780 case clang::X86::BI__builtin_ia32_cmpd512_mask:
15781 case clang::X86::BI__builtin_ia32_cmpq512_mask:
15782 case clang::X86::BI__builtin_ia32_ucmpb128_mask:
15783 case clang::X86::BI__builtin_ia32_ucmpw128_mask:
15784 case clang::X86::BI__builtin_ia32_ucmpd128_mask:
15785 case clang::X86::BI__builtin_ia32_ucmpq128_mask:
15786 case clang::X86::BI__builtin_ia32_ucmpb256_mask:
15787 case clang::X86::BI__builtin_ia32_ucmpw256_mask:
15788 case clang::X86::BI__builtin_ia32_ucmpd256_mask:
15789 case clang::X86::BI__builtin_ia32_ucmpq256_mask:
15790 case clang::X86::BI__builtin_ia32_ucmpb512_mask:
15791 case clang::X86::BI__builtin_ia32_ucmpw512_mask:
15792 case clang::X86::BI__builtin_ia32_ucmpd512_mask:
15793 case clang::X86::BI__builtin_ia32_ucmpq512_mask: {
15794 assert(E->getNumArgs() == 4);
15795
15796 bool IsUnsigned =
15797 (BuiltinOp >= clang::X86::BI__builtin_ia32_ucmpb128_mask &&
15798 BuiltinOp <= clang::X86::BI__builtin_ia32_ucmpq512_mask);
15799
15800 APValue LHS, RHS;
15801 APSInt Mask, Opcode;
15802 if (!EvaluateVector(E->getArg(0), LHS, Info) ||
15803 !EvaluateVector(E->getArg(1), RHS, Info) ||
15804 !EvaluateInteger(E->getArg(2), Opcode, Info) ||
15805 !EvaluateInteger(E->getArg(3), Mask, Info))
15806 return false;
15807
15808 assert(LHS.getVectorLength() == RHS.getVectorLength());
15809
15810 unsigned VectorLen = LHS.getVectorLength();
15811 unsigned RetWidth = Mask.getBitWidth();
15812
15813 APSInt RetMask(llvm::APInt(RetWidth, 0), /*isUnsigned=*/true);
15814
15815 for (unsigned ElemNum = 0; ElemNum < VectorLen; ++ElemNum) {
15816 const APSInt &A = LHS.getVectorElt(ElemNum).getInt();
15817 const APSInt &B = RHS.getVectorElt(ElemNum).getInt();
15818 bool Result = false;
15819
15820 switch (Opcode.getExtValue() & 0x7) {
15821 case 0: // _MM_CMPINT_EQ
15822 Result = (A == B);
15823 break;
15824 case 1: // _MM_CMPINT_LT
15825 Result = IsUnsigned ? A.ult(B) : A.slt(B);
15826 break;
15827 case 2: // _MM_CMPINT_LE
15828 Result = IsUnsigned ? A.ule(B) : A.sle(B);
15829 break;
15830 case 3: // _MM_CMPINT_FALSE
15831 Result = false;
15832 break;
15833 case 4: // _MM_CMPINT_NE
15834 Result = (A != B);
15835 break;
15836 case 5: // _MM_CMPINT_NLT (>=)
15837 Result = IsUnsigned ? A.uge(B) : A.sge(B);
15838 break;
15839 case 6: // _MM_CMPINT_NLE (>)
15840 Result = IsUnsigned ? A.ugt(B) : A.sgt(B);
15841 break;
15842 case 7: // _MM_CMPINT_TRUE
15843 Result = true;
15844 break;
15845 }
15846
15847 RetMask.setBitVal(ElemNum, Mask[ElemNum] && Result);
15848 }
15849
15850 return Success(APValue(RetMask), E);
15851 }
15852 }
15853}
15854
15855/// Determine whether this is a pointer past the end of the complete
15856/// object referred to by the lvalue.
15858 const LValue &LV) {
15859 // A null pointer can be viewed as being "past the end" but we don't
15860 // choose to look at it that way here.
15861 if (!LV.getLValueBase())
15862 return false;
15863
15864 // If the designator is valid and refers to a subobject, we're not pointing
15865 // past the end.
15866 if (!LV.getLValueDesignator().Invalid &&
15867 !LV.getLValueDesignator().isOnePastTheEnd())
15868 return false;
15869
15870 // A pointer to an incomplete type might be past-the-end if the type's size is
15871 // zero. We cannot tell because the type is incomplete.
15872 QualType Ty = getType(LV.getLValueBase());
15873 if (Ty->isIncompleteType())
15874 return true;
15875
15876 // Can't be past the end of an invalid object.
15877 if (LV.getLValueDesignator().Invalid)
15878 return false;
15879
15880 // We're a past-the-end pointer if we point to the byte after the object,
15881 // no matter what our type or path is.
15882 auto Size = Ctx.getTypeSizeInChars(Ty);
15883 return LV.getLValueOffset() == Size;
15884}
15885
15886namespace {
15887
15888/// Data recursive integer evaluator of certain binary operators.
15889///
15890/// We use a data recursive algorithm for binary operators so that we are able
15891/// to handle extreme cases of chained binary operators without causing stack
15892/// overflow.
15893class DataRecursiveIntBinOpEvaluator {
15894 struct EvalResult {
15895 APValue Val;
15896 bool Failed = false;
15897
15898 EvalResult() = default;
15899
15900 void swap(EvalResult &RHS) {
15901 Val.swap(RHS.Val);
15902 Failed = RHS.Failed;
15903 RHS.Failed = false;
15904 }
15905 };
15906
15907 struct Job {
15908 const Expr *E;
15909 EvalResult LHSResult; // meaningful only for binary operator expression.
15910 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
15911
15912 Job() = default;
15913 Job(Job &&) = default;
15914
15915 void startSpeculativeEval(EvalInfo &Info) {
15916 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
15917 }
15918
15919 private:
15920 SpeculativeEvaluationRAII SpecEvalRAII;
15921 };
15922
15923 SmallVector<Job, 16> Queue;
15924
15925 IntExprEvaluator &IntEval;
15926 EvalInfo &Info;
15927 APValue &FinalResult;
15928
15929public:
15930 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
15931 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
15932
15933 /// True if \param E is a binary operator that we are going to handle
15934 /// data recursively.
15935 /// We handle binary operators that are comma, logical, or that have operands
15936 /// with integral or enumeration type.
15937 static bool shouldEnqueue(const BinaryOperator *E) {
15938 return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
15942 }
15943
15944 bool Traverse(const BinaryOperator *E) {
15945 enqueue(E);
15946 EvalResult PrevResult;
15947 while (!Queue.empty())
15948 process(PrevResult);
15949
15950 if (PrevResult.Failed) return false;
15951
15952 FinalResult.swap(PrevResult.Val);
15953 return true;
15954 }
15955
15956private:
15957 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
15958 return IntEval.Success(Value, E, Result);
15959 }
15960 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
15961 return IntEval.Success(Value, E, Result);
15962 }
15963 bool Error(const Expr *E) {
15964 return IntEval.Error(E);
15965 }
15966 bool Error(const Expr *E, diag::kind D) {
15967 return IntEval.Error(E, D);
15968 }
15969
15970 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
15971 return Info.CCEDiag(E, D);
15972 }
15973
15974 // Returns true if visiting the RHS is necessary, false otherwise.
15975 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
15976 bool &SuppressRHSDiags);
15977
15978 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
15979 const BinaryOperator *E, APValue &Result);
15980
15981 void EvaluateExpr(const Expr *E, EvalResult &Result) {
15982 Result.Failed = !Evaluate(Result.Val, Info, E);
15983 if (Result.Failed)
15984 Result.Val = APValue();
15985 }
15986
15987 void process(EvalResult &Result);
15988
15989 void enqueue(const Expr *E) {
15990 E = E->IgnoreParens();
15991 Queue.resize(Queue.size()+1);
15992 Queue.back().E = E;
15993 Queue.back().Kind = Job::AnyExprKind;
15994 }
15995};
15996
15997}
15998
15999bool DataRecursiveIntBinOpEvaluator::
16000 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
16001 bool &SuppressRHSDiags) {
16002 if (E->getOpcode() == BO_Comma) {
16003 // Ignore LHS but note if we could not evaluate it.
16004 if (LHSResult.Failed)
16005 return Info.noteSideEffect();
16006 return true;
16007 }
16008
16009 if (E->isLogicalOp()) {
16010 bool LHSAsBool;
16011 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
16012 // We were able to evaluate the LHS, see if we can get away with not
16013 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
16014 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
16015 Success(LHSAsBool, E, LHSResult.Val);
16016 return false; // Ignore RHS
16017 }
16018 } else {
16019 LHSResult.Failed = true;
16020
16021 // Since we weren't able to evaluate the left hand side, it
16022 // might have had side effects.
16023 if (!Info.noteSideEffect())
16024 return false;
16025
16026 // We can't evaluate the LHS; however, sometimes the result
16027 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
16028 // Don't ignore RHS and suppress diagnostics from this arm.
16029 SuppressRHSDiags = true;
16030 }
16031
16032 return true;
16033 }
16034
16035 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
16037
16038 if (LHSResult.Failed && !Info.noteFailure())
16039 return false; // Ignore RHS;
16040
16041 return true;
16042}
16043
16044static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
16045 bool IsSub) {
16046 // Compute the new offset in the appropriate width, wrapping at 64 bits.
16047 // FIXME: When compiling for a 32-bit target, we should use 32-bit
16048 // offsets.
16049 assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
16050 CharUnits &Offset = LVal.getLValueOffset();
16051 uint64_t Offset64 = Offset.getQuantity();
16052 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
16053 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
16054 : Offset64 + Index64);
16055}
16056
16057bool DataRecursiveIntBinOpEvaluator::
16058 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
16059 const BinaryOperator *E, APValue &Result) {
16060 if (E->getOpcode() == BO_Comma) {
16061 if (RHSResult.Failed)
16062 return false;
16063 Result = RHSResult.Val;
16064 return true;
16065 }
16066
16067 if (E->isLogicalOp()) {
16068 bool lhsResult, rhsResult;
16069 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
16070 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
16071
16072 if (LHSIsOK) {
16073 if (RHSIsOK) {
16074 if (E->getOpcode() == BO_LOr)
16075 return Success(lhsResult || rhsResult, E, Result);
16076 else
16077 return Success(lhsResult && rhsResult, E, Result);
16078 }
16079 } else {
16080 if (RHSIsOK) {
16081 // We can't evaluate the LHS; however, sometimes the result
16082 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
16083 if (rhsResult == (E->getOpcode() == BO_LOr))
16084 return Success(rhsResult, E, Result);
16085 }
16086 }
16087
16088 return false;
16089 }
16090
16091 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
16093
16094 if (LHSResult.Failed || RHSResult.Failed)
16095 return false;
16096
16097 const APValue &LHSVal = LHSResult.Val;
16098 const APValue &RHSVal = RHSResult.Val;
16099
16100 // Handle cases like (unsigned long)&a + 4.
16101 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
16102 Result = LHSVal;
16103 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
16104 return true;
16105 }
16106
16107 // Handle cases like 4 + (unsigned long)&a
16108 if (E->getOpcode() == BO_Add &&
16109 RHSVal.isLValue() && LHSVal.isInt()) {
16110 Result = RHSVal;
16111 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
16112 return true;
16113 }
16114
16115 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
16116 // Handle (intptr_t)&&A - (intptr_t)&&B.
16117 if (!LHSVal.getLValueOffset().isZero() ||
16118 !RHSVal.getLValueOffset().isZero())
16119 return false;
16120 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
16121 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
16122 if (!LHSExpr || !RHSExpr)
16123 return false;
16124 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
16125 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
16126 if (!LHSAddrExpr || !RHSAddrExpr)
16127 return false;
16128 // Make sure both labels come from the same function.
16129 if (LHSAddrExpr->getLabel()->getDeclContext() !=
16130 RHSAddrExpr->getLabel()->getDeclContext())
16131 return false;
16132 Result = APValue(LHSAddrExpr, RHSAddrExpr);
16133 return true;
16134 }
16135
16136 // All the remaining cases expect both operands to be an integer
16137 if (!LHSVal.isInt() || !RHSVal.isInt())
16138 return Error(E);
16139
16140 // Set up the width and signedness manually, in case it can't be deduced
16141 // from the operation we're performing.
16142 // FIXME: Don't do this in the cases where we can deduce it.
16143 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
16145 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
16146 RHSVal.getInt(), Value))
16147 return false;
16148 return Success(Value, E, Result);
16149}
16150
16151void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
16152 Job &job = Queue.back();
16153
16154 switch (job.Kind) {
16155 case Job::AnyExprKind: {
16156 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
16157 if (shouldEnqueue(Bop)) {
16158 job.Kind = Job::BinOpKind;
16159 enqueue(Bop->getLHS());
16160 return;
16161 }
16162 }
16163
16164 EvaluateExpr(job.E, Result);
16165 Queue.pop_back();
16166 return;
16167 }
16168
16169 case Job::BinOpKind: {
16170 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
16171 bool SuppressRHSDiags = false;
16172 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
16173 Queue.pop_back();
16174 return;
16175 }
16176 if (SuppressRHSDiags)
16177 job.startSpeculativeEval(Info);
16178 job.LHSResult.swap(Result);
16179 job.Kind = Job::BinOpVisitedLHSKind;
16180 enqueue(Bop->getRHS());
16181 return;
16182 }
16183
16184 case Job::BinOpVisitedLHSKind: {
16185 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
16186 EvalResult RHS;
16187 RHS.swap(Result);
16188 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
16189 Queue.pop_back();
16190 return;
16191 }
16192 }
16193
16194 llvm_unreachable("Invalid Job::Kind!");
16195}
16196
16197namespace {
16198enum class CmpResult {
16199 Unequal,
16200 Less,
16201 Equal,
16202 Greater,
16203 Unordered,
16204};
16205}
16206
16207template <class SuccessCB, class AfterCB>
16208static bool
16210 SuccessCB &&Success, AfterCB &&DoAfter) {
16211 assert(!E->isValueDependent());
16212 assert(E->isComparisonOp() && "expected comparison operator");
16213 assert((E->getOpcode() == BO_Cmp ||
16215 "unsupported binary expression evaluation");
16216 auto Error = [&](const Expr *E) {
16217 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
16218 return false;
16219 };
16220
16221 bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp;
16222 bool IsEquality = E->isEqualityOp();
16223
16224 QualType LHSTy = E->getLHS()->getType();
16225 QualType RHSTy = E->getRHS()->getType();
16226
16227 if (LHSTy->isIntegralOrEnumerationType() &&
16228 RHSTy->isIntegralOrEnumerationType()) {
16229 APSInt LHS, RHS;
16230 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
16231 if (!LHSOK && !Info.noteFailure())
16232 return false;
16233 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
16234 return false;
16235 if (LHS < RHS)
16236 return Success(CmpResult::Less, E);
16237 if (LHS > RHS)
16238 return Success(CmpResult::Greater, E);
16239 return Success(CmpResult::Equal, E);
16240 }
16241
16242 if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
16243 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
16244 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
16245
16246 bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
16247 if (!LHSOK && !Info.noteFailure())
16248 return false;
16249 if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
16250 return false;
16251 if (LHSFX < RHSFX)
16252 return Success(CmpResult::Less, E);
16253 if (LHSFX > RHSFX)
16254 return Success(CmpResult::Greater, E);
16255 return Success(CmpResult::Equal, E);
16256 }
16257
16258 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
16259 ComplexValue LHS, RHS;
16260 bool LHSOK;
16261 if (E->isAssignmentOp()) {
16262 LValue LV;
16263 EvaluateLValue(E->getLHS(), LV, Info);
16264 LHSOK = false;
16265 } else if (LHSTy->isRealFloatingType()) {
16266 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
16267 if (LHSOK) {
16268 LHS.makeComplexFloat();
16269 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
16270 }
16271 } else {
16272 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
16273 }
16274 if (!LHSOK && !Info.noteFailure())
16275 return false;
16276
16277 if (E->getRHS()->getType()->isRealFloatingType()) {
16278 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
16279 return false;
16280 RHS.makeComplexFloat();
16281 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
16282 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
16283 return false;
16284
16285 if (LHS.isComplexFloat()) {
16286 APFloat::cmpResult CR_r =
16287 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
16288 APFloat::cmpResult CR_i =
16289 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
16290 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
16291 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
16292 } else {
16293 assert(IsEquality && "invalid complex comparison");
16294 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
16295 LHS.getComplexIntImag() == RHS.getComplexIntImag();
16296 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
16297 }
16298 }
16299
16300 if (LHSTy->isRealFloatingType() &&
16301 RHSTy->isRealFloatingType()) {
16302 APFloat RHS(0.0), LHS(0.0);
16303
16304 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
16305 if (!LHSOK && !Info.noteFailure())
16306 return false;
16307
16308 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
16309 return false;
16310
16311 assert(E->isComparisonOp() && "Invalid binary operator!");
16312 llvm::APFloatBase::cmpResult APFloatCmpResult = LHS.compare(RHS);
16313 if (!Info.InConstantContext &&
16314 APFloatCmpResult == APFloat::cmpUnordered &&
16316 // Note: Compares may raise invalid in some cases involving NaN or sNaN.
16317 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
16318 return false;
16319 }
16320 auto GetCmpRes = [&]() {
16321 switch (APFloatCmpResult) {
16322 case APFloat::cmpEqual:
16323 return CmpResult::Equal;
16324 case APFloat::cmpLessThan:
16325 return CmpResult::Less;
16326 case APFloat::cmpGreaterThan:
16327 return CmpResult::Greater;
16328 case APFloat::cmpUnordered:
16329 return CmpResult::Unordered;
16330 }
16331 llvm_unreachable("Unrecognised APFloat::cmpResult enum");
16332 };
16333 return Success(GetCmpRes(), E);
16334 }
16335
16336 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
16337 LValue LHSValue, RHSValue;
16338
16339 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
16340 if (!LHSOK && !Info.noteFailure())
16341 return false;
16342
16343 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
16344 return false;
16345
16346 // Reject differing bases from the normal codepath; we special-case
16347 // comparisons to null.
16348 if (!HasSameBase(LHSValue, RHSValue)) {
16349 // Bail out early if we're checking potential constant expression.
16350 // Otherwise, prefer to diagnose other issues.
16351 if (Info.checkingPotentialConstantExpression() &&
16352 (LHSValue.AllowConstexprUnknown || RHSValue.AllowConstexprUnknown))
16353 return false;
16354 auto DiagComparison = [&] (unsigned DiagID, bool Reversed = false) {
16355 std::string LHS = LHSValue.toString(Info.Ctx, E->getLHS()->getType());
16356 std::string RHS = RHSValue.toString(Info.Ctx, E->getRHS()->getType());
16357 Info.FFDiag(E, DiagID)
16358 << (Reversed ? RHS : LHS) << (Reversed ? LHS : RHS);
16359 return false;
16360 };
16361 // Inequalities and subtractions between unrelated pointers have
16362 // unspecified or undefined behavior.
16363 if (!IsEquality)
16364 return DiagComparison(
16365 diag::note_constexpr_pointer_comparison_unspecified);
16366 // A constant address may compare equal to the address of a symbol.
16367 // The one exception is that address of an object cannot compare equal
16368 // to a null pointer constant.
16369 // TODO: Should we restrict this to actual null pointers, and exclude the
16370 // case of zero cast to pointer type?
16371 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
16372 (!RHSValue.Base && !RHSValue.Offset.isZero()))
16373 return DiagComparison(diag::note_constexpr_pointer_constant_comparison,
16374 !RHSValue.Base);
16375 // C++2c [intro.object]/10:
16376 // Two objects [...] may have the same address if [...] they are both
16377 // potentially non-unique objects.
16378 // C++2c [intro.object]/9:
16379 // An object is potentially non-unique if it is a string literal object,
16380 // the backing array of an initializer list, or a subobject thereof.
16381 //
16382 // This makes the comparison result unspecified, so it's not a constant
16383 // expression.
16384 //
16385 // TODO: Do we need to handle the initializer list case here?
16386 if (ArePotentiallyOverlappingStringLiterals(Info, LHSValue, RHSValue))
16387 return DiagComparison(diag::note_constexpr_literal_comparison);
16388 if (IsOpaqueConstantCall(LHSValue) || IsOpaqueConstantCall(RHSValue))
16389 return DiagComparison(diag::note_constexpr_opaque_call_comparison,
16390 !IsOpaqueConstantCall(LHSValue));
16391 // We can't tell whether weak symbols will end up pointing to the same
16392 // object.
16393 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
16394 return DiagComparison(diag::note_constexpr_pointer_weak_comparison,
16395 !IsWeakLValue(LHSValue));
16396 // We can't compare the address of the start of one object with the
16397 // past-the-end address of another object, per C++ DR1652.
16398 if (LHSValue.Base && LHSValue.Offset.isZero() &&
16399 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue))
16400 return DiagComparison(diag::note_constexpr_pointer_comparison_past_end,
16401 true);
16402 if (RHSValue.Base && RHSValue.Offset.isZero() &&
16403 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue))
16404 return DiagComparison(diag::note_constexpr_pointer_comparison_past_end,
16405 false);
16406 // We can't tell whether an object is at the same address as another
16407 // zero sized object.
16408 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
16409 (LHSValue.Base && isZeroSized(RHSValue)))
16410 return DiagComparison(
16411 diag::note_constexpr_pointer_comparison_zero_sized);
16412 if (LHSValue.AllowConstexprUnknown || RHSValue.AllowConstexprUnknown)
16413 return DiagComparison(
16414 diag::note_constexpr_pointer_comparison_unspecified);
16415 // FIXME: Verify both variables are live.
16416 return Success(CmpResult::Unequal, E);
16417 }
16418
16419 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
16420 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
16421
16422 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
16423 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
16424
16425 // C++11 [expr.rel]p2:
16426 // - If two pointers point to non-static data members of the same object,
16427 // or to subobjects or array elements fo such members, recursively, the
16428 // pointer to the later declared member compares greater provided the
16429 // two members have the same access control and provided their class is
16430 // not a union.
16431 // [...]
16432 // - Otherwise pointer comparisons are unspecified.
16433 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
16434 bool WasArrayIndex;
16435 unsigned Mismatch = FindDesignatorMismatch(
16436 LHSValue.Base.isNull() ? QualType()
16437 : getType(LHSValue.Base).getNonReferenceType(),
16438 LHSDesignator, RHSDesignator, WasArrayIndex);
16439 // At the point where the designators diverge, the comparison has a
16440 // specified value if:
16441 // - we are comparing array indices
16442 // - we are comparing fields of a union, or fields with the same access
16443 // Otherwise, the result is unspecified and thus the comparison is not a
16444 // constant expression.
16445 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
16446 Mismatch < RHSDesignator.Entries.size()) {
16447 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
16448 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
16449 if (!LF && !RF)
16450 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
16451 else if (!LF)
16452 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
16453 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
16454 << RF->getParent() << RF;
16455 else if (!RF)
16456 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
16457 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
16458 << LF->getParent() << LF;
16459 else if (!LF->getParent()->isUnion() &&
16460 LF->getAccess() != RF->getAccess())
16461 Info.CCEDiag(E,
16462 diag::note_constexpr_pointer_comparison_differing_access)
16463 << LF << LF->getAccess() << RF << RF->getAccess()
16464 << LF->getParent();
16465 }
16466 }
16467
16468 // The comparison here must be unsigned, and performed with the same
16469 // width as the pointer.
16470 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
16471 uint64_t CompareLHS = LHSOffset.getQuantity();
16472 uint64_t CompareRHS = RHSOffset.getQuantity();
16473 assert(PtrSize <= 64 && "Unexpected pointer width");
16474 uint64_t Mask = ~0ULL >> (64 - PtrSize);
16475 CompareLHS &= Mask;
16476 CompareRHS &= Mask;
16477
16478 // If there is a base and this is a relational operator, we can only
16479 // compare pointers within the object in question; otherwise, the result
16480 // depends on where the object is located in memory.
16481 if (!LHSValue.Base.isNull() && IsRelational) {
16482 QualType BaseTy = getType(LHSValue.Base).getNonReferenceType();
16483 if (BaseTy->isIncompleteType())
16484 return Error(E);
16485 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
16486 uint64_t OffsetLimit = Size.getQuantity();
16487 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
16488 return Error(E);
16489 }
16490
16491 if (CompareLHS < CompareRHS)
16492 return Success(CmpResult::Less, E);
16493 if (CompareLHS > CompareRHS)
16494 return Success(CmpResult::Greater, E);
16495 return Success(CmpResult::Equal, E);
16496 }
16497
16498 if (LHSTy->isMemberPointerType()) {
16499 assert(IsEquality && "unexpected member pointer operation");
16500 assert(RHSTy->isMemberPointerType() && "invalid comparison");
16501
16502 MemberPtr LHSValue, RHSValue;
16503
16504 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
16505 if (!LHSOK && !Info.noteFailure())
16506 return false;
16507
16508 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
16509 return false;
16510
16511 // If either operand is a pointer to a weak function, the comparison is not
16512 // constant.
16513 if (LHSValue.getDecl() && LHSValue.getDecl()->isWeak()) {
16514 Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison)
16515 << LHSValue.getDecl();
16516 return false;
16517 }
16518 if (RHSValue.getDecl() && RHSValue.getDecl()->isWeak()) {
16519 Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison)
16520 << RHSValue.getDecl();
16521 return false;
16522 }
16523
16524 // C++11 [expr.eq]p2:
16525 // If both operands are null, they compare equal. Otherwise if only one is
16526 // null, they compare unequal.
16527 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
16528 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
16529 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
16530 }
16531
16532 // Otherwise if either is a pointer to a virtual member function, the
16533 // result is unspecified.
16534 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
16535 if (MD->isVirtual())
16536 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
16537 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
16538 if (MD->isVirtual())
16539 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
16540
16541 // Otherwise they compare equal if and only if they would refer to the
16542 // same member of the same most derived object or the same subobject if
16543 // they were dereferenced with a hypothetical object of the associated
16544 // class type.
16545 bool Equal = LHSValue == RHSValue;
16546 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
16547 }
16548
16549 if (LHSTy->isNullPtrType()) {
16550 assert(E->isComparisonOp() && "unexpected nullptr operation");
16551 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
16552 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
16553 // are compared, the result is true of the operator is <=, >= or ==, and
16554 // false otherwise.
16555 LValue Res;
16556 if (!EvaluatePointer(E->getLHS(), Res, Info) ||
16557 !EvaluatePointer(E->getRHS(), Res, Info))
16558 return false;
16559 return Success(CmpResult::Equal, E);
16560 }
16561
16562 return DoAfter();
16563}
16564
16565bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
16566 if (!CheckLiteralType(Info, E))
16567 return false;
16568
16569 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
16571 switch (CR) {
16572 case CmpResult::Unequal:
16573 llvm_unreachable("should never produce Unequal for three-way comparison");
16574 case CmpResult::Less:
16575 CCR = ComparisonCategoryResult::Less;
16576 break;
16577 case CmpResult::Equal:
16578 CCR = ComparisonCategoryResult::Equal;
16579 break;
16580 case CmpResult::Greater:
16581 CCR = ComparisonCategoryResult::Greater;
16582 break;
16583 case CmpResult::Unordered:
16584 CCR = ComparisonCategoryResult::Unordered;
16585 break;
16586 }
16587 // Evaluation succeeded. Lookup the information for the comparison category
16588 // type and fetch the VarDecl for the result.
16589 const ComparisonCategoryInfo &CmpInfo =
16590 Info.Ctx.CompCategories.getInfoForType(E->getType());
16591 const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD;
16592 // Check and evaluate the result as a constant expression.
16593 LValue LV;
16594 LV.set(VD);
16595 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
16596 return false;
16597 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
16598 ConstantExprKind::Normal);
16599 };
16600 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
16601 return ExprEvaluatorBaseTy::VisitBinCmp(E);
16602 });
16603}
16604
16605bool RecordExprEvaluator::VisitCXXParenListInitExpr(
16606 const CXXParenListInitExpr *E) {
16607 return VisitCXXParenListOrInitListExpr(E, E->getInitExprs());
16608}
16609
16610bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
16611 // We don't support assignment in C. C++ assignments don't get here because
16612 // assignment is an lvalue in C++.
16613 if (E->isAssignmentOp()) {
16614 Error(E);
16615 if (!Info.noteFailure())
16616 return false;
16617 }
16618
16619 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
16620 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
16621
16622 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
16624 "DataRecursiveIntBinOpEvaluator should have handled integral types");
16625
16626 if (E->isComparisonOp()) {
16627 // Evaluate builtin binary comparisons by evaluating them as three-way
16628 // comparisons and then translating the result.
16629 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
16630 assert((CR != CmpResult::Unequal || E->isEqualityOp()) &&
16631 "should only produce Unequal for equality comparisons");
16632 bool IsEqual = CR == CmpResult::Equal,
16633 IsLess = CR == CmpResult::Less,
16634 IsGreater = CR == CmpResult::Greater;
16635 auto Op = E->getOpcode();
16636 switch (Op) {
16637 default:
16638 llvm_unreachable("unsupported binary operator");
16639 case BO_EQ:
16640 case BO_NE:
16641 return Success(IsEqual == (Op == BO_EQ), E);
16642 case BO_LT:
16643 return Success(IsLess, E);
16644 case BO_GT:
16645 return Success(IsGreater, E);
16646 case BO_LE:
16647 return Success(IsEqual || IsLess, E);
16648 case BO_GE:
16649 return Success(IsEqual || IsGreater, E);
16650 }
16651 };
16652 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
16653 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
16654 });
16655 }
16656
16657 QualType LHSTy = E->getLHS()->getType();
16658 QualType RHSTy = E->getRHS()->getType();
16659
16660 if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
16661 E->getOpcode() == BO_Sub) {
16662 LValue LHSValue, RHSValue;
16663
16664 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
16665 if (!LHSOK && !Info.noteFailure())
16666 return false;
16667
16668 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
16669 return false;
16670
16671 // Reject differing bases from the normal codepath; we special-case
16672 // comparisons to null.
16673 if (!HasSameBase(LHSValue, RHSValue)) {
16674 if (Info.checkingPotentialConstantExpression() &&
16675 (LHSValue.AllowConstexprUnknown || RHSValue.AllowConstexprUnknown))
16676 return false;
16677
16678 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
16679 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
16680
16681 auto DiagArith = [&](unsigned DiagID) {
16682 std::string LHS = LHSValue.toString(Info.Ctx, E->getLHS()->getType());
16683 std::string RHS = RHSValue.toString(Info.Ctx, E->getRHS()->getType());
16684 Info.FFDiag(E, DiagID) << LHS << RHS;
16685 if (LHSExpr && LHSExpr == RHSExpr)
16686 Info.Note(LHSExpr->getExprLoc(),
16687 diag::note_constexpr_repeated_literal_eval)
16688 << LHSExpr->getSourceRange();
16689 return false;
16690 };
16691
16692 if (!LHSExpr || !RHSExpr)
16693 return DiagArith(diag::note_constexpr_pointer_arith_unspecified);
16694
16695 if (ArePotentiallyOverlappingStringLiterals(Info, LHSValue, RHSValue))
16696 return DiagArith(diag::note_constexpr_literal_arith);
16697
16698 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
16699 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
16700 if (!LHSAddrExpr || !RHSAddrExpr)
16701 return Error(E);
16702 // Make sure both labels come from the same function.
16703 if (LHSAddrExpr->getLabel()->getDeclContext() !=
16704 RHSAddrExpr->getLabel()->getDeclContext())
16705 return Error(E);
16706 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
16707 }
16708 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
16709 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
16710
16711 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
16712 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
16713
16714 // C++11 [expr.add]p6:
16715 // Unless both pointers point to elements of the same array object, or
16716 // one past the last element of the array object, the behavior is
16717 // undefined.
16718 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
16719 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
16720 RHSDesignator))
16721 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
16722
16723 QualType Type = E->getLHS()->getType();
16724 QualType ElementType = Type->castAs<PointerType>()->getPointeeType();
16725
16726 CharUnits ElementSize;
16727 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
16728 return false;
16729
16730 // As an extension, a type may have zero size (empty struct or union in
16731 // C, array of zero length). Pointer subtraction in such cases has
16732 // undefined behavior, so is not constant.
16733 if (ElementSize.isZero()) {
16734 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
16735 << ElementType;
16736 return false;
16737 }
16738
16739 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
16740 // and produce incorrect results when it overflows. Such behavior
16741 // appears to be non-conforming, but is common, so perhaps we should
16742 // assume the standard intended for such cases to be undefined behavior
16743 // and check for them.
16744
16745 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
16746 // overflow in the final conversion to ptrdiff_t.
16747 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
16748 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
16749 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
16750 false);
16751 APSInt TrueResult = (LHS - RHS) / ElemSize;
16752 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
16753
16754 if (Result.extend(65) != TrueResult &&
16755 !HandleOverflow(Info, E, TrueResult, E->getType()))
16756 return false;
16757 return Success(Result, E);
16758 }
16759
16760 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
16761}
16762
16763/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
16764/// a result as the expression's type.
16765bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
16766 const UnaryExprOrTypeTraitExpr *E) {
16767 switch(E->getKind()) {
16768 case UETT_PreferredAlignOf:
16769 case UETT_AlignOf: {
16770 if (E->isArgumentType())
16771 return Success(
16772 GetAlignOfType(Info.Ctx, E->getArgumentType(), E->getKind()), E);
16773 else
16774 return Success(
16775 GetAlignOfExpr(Info.Ctx, E->getArgumentExpr(), E->getKind()), E);
16776 }
16777
16778 case UETT_PtrAuthTypeDiscriminator: {
16779 if (E->getArgumentType()->isDependentType())
16780 return false;
16781 return Success(
16783 }
16784 case UETT_VecStep: {
16785 QualType Ty = E->getTypeOfArgument();
16786
16787 if (Ty->isVectorType()) {
16788 unsigned n = Ty->castAs<VectorType>()->getNumElements();
16789
16790 // The vec_step built-in functions that take a 3-component
16791 // vector return 4. (OpenCL 1.1 spec 6.11.12)
16792 if (n == 3)
16793 n = 4;
16794
16795 return Success(n, E);
16796 } else
16797 return Success(1, E);
16798 }
16799
16800 case UETT_DataSizeOf:
16801 case UETT_SizeOf: {
16802 QualType SrcTy = E->getTypeOfArgument();
16803 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
16804 // the result is the size of the referenced type."
16805 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
16806 SrcTy = Ref->getPointeeType();
16807
16808 CharUnits Sizeof;
16809 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof,
16810 E->getKind() == UETT_DataSizeOf ? SizeOfType::DataSizeOf
16811 : SizeOfType::SizeOf)) {
16812 return false;
16813 }
16814 return Success(Sizeof, E);
16815 }
16816 case UETT_OpenMPRequiredSimdAlign:
16817 assert(E->isArgumentType());
16818 return Success(
16819 Info.Ctx.toCharUnitsFromBits(
16821 .getQuantity(),
16822 E);
16823 case UETT_VectorElements: {
16824 QualType Ty = E->getTypeOfArgument();
16825 // If the vector has a fixed size, we can determine the number of elements
16826 // at compile time.
16827 if (const auto *VT = Ty->getAs<VectorType>())
16828 return Success(VT->getNumElements(), E);
16829
16830 assert(Ty->isSizelessVectorType());
16831 if (Info.InConstantContext)
16832 Info.CCEDiag(E, diag::note_constexpr_non_const_vectorelements)
16833 << E->getSourceRange();
16834
16835 return false;
16836 }
16837 case UETT_CountOf: {
16838 QualType Ty = E->getTypeOfArgument();
16839 assert(Ty->isArrayType());
16840
16841 // We don't need to worry about array element qualifiers, so getting the
16842 // unsafe array type is fine.
16843 if (const auto *CAT =
16844 dyn_cast<ConstantArrayType>(Ty->getAsArrayTypeUnsafe())) {
16845 return Success(CAT->getSize(), E);
16846 }
16847
16848 assert(!Ty->isConstantSizeType());
16849
16850 // If it's a variable-length array type, we need to check whether it is a
16851 // multidimensional array. If so, we need to check the size expression of
16852 // the VLA to see if it's a constant size. If so, we can return that value.
16853 const auto *VAT = Info.Ctx.getAsVariableArrayType(Ty);
16854 assert(VAT);
16855 if (VAT->getElementType()->isArrayType()) {
16856 // Variable array size expression could be missing (e.g. int a[*][10]) In
16857 // that case, it can't be a constant expression.
16858 if (!VAT->getSizeExpr()) {
16859 Info.FFDiag(E->getBeginLoc());
16860 return false;
16861 }
16862
16863 std::optional<APSInt> Res =
16864 VAT->getSizeExpr()->getIntegerConstantExpr(Info.Ctx);
16865 if (Res) {
16866 // The resulting value always has type size_t, so we need to make the
16867 // returned APInt have the correct sign and bit-width.
16868 APInt Val{
16869 static_cast<unsigned>(Info.Ctx.getTypeSize(Info.Ctx.getSizeType())),
16870 Res->getZExtValue()};
16871 return Success(Val, E);
16872 }
16873 }
16874
16875 // Definitely a variable-length type, which is not an ICE.
16876 // FIXME: Better diagnostic.
16877 Info.FFDiag(E->getBeginLoc());
16878 return false;
16879 }
16880 }
16881
16882 llvm_unreachable("unknown expr/type trait");
16883}
16884
16885bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
16886 CharUnits Result;
16887 unsigned n = OOE->getNumComponents();
16888 if (n == 0)
16889 return Error(OOE);
16890 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
16891 for (unsigned i = 0; i != n; ++i) {
16892 OffsetOfNode ON = OOE->getComponent(i);
16893 switch (ON.getKind()) {
16894 case OffsetOfNode::Array: {
16895 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
16896 APSInt IdxResult;
16897 if (!EvaluateInteger(Idx, IdxResult, Info))
16898 return false;
16899 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
16900 if (!AT)
16901 return Error(OOE);
16902 CurrentType = AT->getElementType();
16903 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
16904 Result += IdxResult.getSExtValue() * ElementSize;
16905 break;
16906 }
16907
16908 case OffsetOfNode::Field: {
16909 FieldDecl *MemberDecl = ON.getField();
16910 const auto *RD = CurrentType->getAsRecordDecl();
16911 if (!RD)
16912 return Error(OOE);
16913 if (RD->isInvalidDecl()) return false;
16914 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
16915 unsigned i = MemberDecl->getFieldIndex();
16916 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
16917 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
16918 CurrentType = MemberDecl->getType().getNonReferenceType();
16919 break;
16920 }
16921
16923 llvm_unreachable("dependent __builtin_offsetof");
16924
16925 case OffsetOfNode::Base: {
16926 CXXBaseSpecifier *BaseSpec = ON.getBase();
16927 if (BaseSpec->isVirtual())
16928 return Error(OOE);
16929
16930 // Find the layout of the class whose base we are looking into.
16931 const auto *RD = CurrentType->getAsCXXRecordDecl();
16932 if (!RD)
16933 return Error(OOE);
16934 if (RD->isInvalidDecl()) return false;
16935 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
16936
16937 // Find the base class itself.
16938 CurrentType = BaseSpec->getType();
16939 const auto *BaseRD = CurrentType->getAsCXXRecordDecl();
16940 if (!BaseRD)
16941 return Error(OOE);
16942
16943 // Add the offset to the base.
16944 Result += RL.getBaseClassOffset(BaseRD);
16945 break;
16946 }
16947 }
16948 }
16949 return Success(Result, OOE);
16950}
16951
16952bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
16953 switch (E->getOpcode()) {
16954 default:
16955 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
16956 // See C99 6.6p3.
16957 return Error(E);
16958 case UO_Extension:
16959 // FIXME: Should extension allow i-c-e extension expressions in its scope?
16960 // If so, we could clear the diagnostic ID.
16961 return Visit(E->getSubExpr());
16962 case UO_Plus:
16963 // The result is just the value.
16964 return Visit(E->getSubExpr());
16965 case UO_Minus: {
16966 if (!Visit(E->getSubExpr()))
16967 return false;
16968 if (!Result.isInt()) return Error(E);
16969 const APSInt &Value = Result.getInt();
16970 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow()) {
16971 if (Info.checkingForUndefinedBehavior())
16972 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
16973 diag::warn_integer_constant_overflow)
16974 << toString(Value, 10, Value.isSigned(), /*formatAsCLiteral=*/false,
16975 /*UpperCase=*/true, /*InsertSeparators=*/true)
16976 << E->getType() << E->getSourceRange();
16977
16978 if (!HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
16979 E->getType()))
16980 return false;
16981 }
16982 return Success(-Value, E);
16983 }
16984 case UO_Not: {
16985 if (!Visit(E->getSubExpr()))
16986 return false;
16987 if (!Result.isInt()) return Error(E);
16988 return Success(~Result.getInt(), E);
16989 }
16990 case UO_LNot: {
16991 bool bres;
16992 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
16993 return false;
16994 return Success(!bres, E);
16995 }
16996 }
16997}
16998
16999/// HandleCast - This is used to evaluate implicit or explicit casts where the
17000/// result type is integer.
17001bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
17002 const Expr *SubExpr = E->getSubExpr();
17003 QualType DestType = E->getType();
17004 QualType SrcType = SubExpr->getType();
17005
17006 switch (E->getCastKind()) {
17007 case CK_BaseToDerived:
17008 case CK_DerivedToBase:
17009 case CK_UncheckedDerivedToBase:
17010 case CK_Dynamic:
17011 case CK_ToUnion:
17012 case CK_ArrayToPointerDecay:
17013 case CK_FunctionToPointerDecay:
17014 case CK_NullToPointer:
17015 case CK_NullToMemberPointer:
17016 case CK_BaseToDerivedMemberPointer:
17017 case CK_DerivedToBaseMemberPointer:
17018 case CK_ReinterpretMemberPointer:
17019 case CK_ConstructorConversion:
17020 case CK_IntegralToPointer:
17021 case CK_ToVoid:
17022 case CK_VectorSplat:
17023 case CK_IntegralToFloating:
17024 case CK_FloatingCast:
17025 case CK_CPointerToObjCPointerCast:
17026 case CK_BlockPointerToObjCPointerCast:
17027 case CK_AnyPointerToBlockPointerCast:
17028 case CK_ObjCObjectLValueCast:
17029 case CK_FloatingRealToComplex:
17030 case CK_FloatingComplexToReal:
17031 case CK_FloatingComplexCast:
17032 case CK_FloatingComplexToIntegralComplex:
17033 case CK_IntegralRealToComplex:
17034 case CK_IntegralComplexCast:
17035 case CK_IntegralComplexToFloatingComplex:
17036 case CK_BuiltinFnToFnPtr:
17037 case CK_ZeroToOCLOpaqueType:
17038 case CK_NonAtomicToAtomic:
17039 case CK_AddressSpaceConversion:
17040 case CK_IntToOCLSampler:
17041 case CK_FloatingToFixedPoint:
17042 case CK_FixedPointToFloating:
17043 case CK_FixedPointCast:
17044 case CK_IntegralToFixedPoint:
17045 case CK_MatrixCast:
17046 case CK_HLSLAggregateSplatCast:
17047 llvm_unreachable("invalid cast kind for integral value");
17048
17049 case CK_BitCast:
17050 case CK_Dependent:
17051 case CK_LValueBitCast:
17052 case CK_ARCProduceObject:
17053 case CK_ARCConsumeObject:
17054 case CK_ARCReclaimReturnedObject:
17055 case CK_ARCExtendBlockObject:
17056 case CK_CopyAndAutoreleaseBlockObject:
17057 return Error(E);
17058
17059 case CK_UserDefinedConversion:
17060 case CK_LValueToRValue:
17061 case CK_AtomicToNonAtomic:
17062 case CK_NoOp:
17063 case CK_LValueToRValueBitCast:
17064 case CK_HLSLArrayRValue:
17065 case CK_HLSLElementwiseCast:
17066 return ExprEvaluatorBaseTy::VisitCastExpr(E);
17067
17068 case CK_MemberPointerToBoolean:
17069 case CK_PointerToBoolean:
17070 case CK_IntegralToBoolean:
17071 case CK_FloatingToBoolean:
17072 case CK_BooleanToSignedIntegral:
17073 case CK_FloatingComplexToBoolean:
17074 case CK_IntegralComplexToBoolean: {
17075 bool BoolResult;
17076 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
17077 return false;
17078 uint64_t IntResult = BoolResult;
17079 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
17080 IntResult = (uint64_t)-1;
17081 return Success(IntResult, E);
17082 }
17083
17084 case CK_FixedPointToIntegral: {
17085 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
17086 if (!EvaluateFixedPoint(SubExpr, Src, Info))
17087 return false;
17088 bool Overflowed;
17089 llvm::APSInt Result = Src.convertToInt(
17090 Info.Ctx.getIntWidth(DestType),
17091 DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
17092 if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
17093 return false;
17094 return Success(Result, E);
17095 }
17096
17097 case CK_FixedPointToBoolean: {
17098 // Unsigned padding does not affect this.
17099 APValue Val;
17100 if (!Evaluate(Val, Info, SubExpr))
17101 return false;
17102 return Success(Val.getFixedPoint().getBoolValue(), E);
17103 }
17104
17105 case CK_IntegralCast: {
17106 if (!Visit(SubExpr))
17107 return false;
17108
17109 if (!Result.isInt()) {
17110 // Allow casts of address-of-label differences if they are no-ops
17111 // or narrowing. (The narrowing case isn't actually guaranteed to
17112 // be constant-evaluatable except in some narrow cases which are hard
17113 // to detect here. We let it through on the assumption the user knows
17114 // what they are doing.)
17115 if (Result.isAddrLabelDiff())
17116 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
17117 // Only allow casts of lvalues if they are lossless.
17118 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
17119 }
17120
17121 if (Info.Ctx.getLangOpts().CPlusPlus && DestType->isEnumeralType()) {
17122 const auto *ED = DestType->getAsEnumDecl();
17123 // Check that the value is within the range of the enumeration values.
17124 //
17125 // This corressponds to [expr.static.cast]p10 which says:
17126 // A value of integral or enumeration type can be explicitly converted
17127 // to a complete enumeration type ... If the enumeration type does not
17128 // have a fixed underlying type, the value is unchanged if the original
17129 // value is within the range of the enumeration values ([dcl.enum]), and
17130 // otherwise, the behavior is undefined.
17131 //
17132 // This was resolved as part of DR2338 which has CD5 status.
17133 if (!ED->isFixed()) {
17134 llvm::APInt Min;
17135 llvm::APInt Max;
17136
17137 ED->getValueRange(Max, Min);
17138 --Max;
17139
17140 if (ED->getNumNegativeBits() &&
17141 (Max.slt(Result.getInt().getSExtValue()) ||
17142 Min.sgt(Result.getInt().getSExtValue())))
17143 Info.CCEDiag(E, diag::note_constexpr_unscoped_enum_out_of_range)
17144 << llvm::toString(Result.getInt(), 10) << Min.getSExtValue()
17145 << Max.getSExtValue() << ED;
17146 else if (!ED->getNumNegativeBits() &&
17147 Max.ult(Result.getInt().getZExtValue()))
17148 Info.CCEDiag(E, diag::note_constexpr_unscoped_enum_out_of_range)
17149 << llvm::toString(Result.getInt(), 10) << Min.getZExtValue()
17150 << Max.getZExtValue() << ED;
17151 }
17152 }
17153
17154 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
17155 Result.getInt()), E);
17156 }
17157
17158 case CK_PointerToIntegral: {
17159 CCEDiag(E, diag::note_constexpr_invalid_cast)
17160 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
17161 << Info.Ctx.getLangOpts().CPlusPlus << E->getSourceRange();
17162
17163 LValue LV;
17164 if (!EvaluatePointer(SubExpr, LV, Info))
17165 return false;
17166
17167 if (LV.getLValueBase()) {
17168 // Only allow based lvalue casts if they are lossless.
17169 // FIXME: Allow a larger integer size than the pointer size, and allow
17170 // narrowing back down to pointer width in subsequent integral casts.
17171 // FIXME: Check integer type's active bits, not its type size.
17172 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
17173 return Error(E);
17174
17175 LV.Designator.setInvalid();
17176 LV.moveInto(Result);
17177 return true;
17178 }
17179
17180 APSInt AsInt;
17181 APValue V;
17182 LV.moveInto(V);
17183 if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
17184 llvm_unreachable("Can't cast this!");
17185
17186 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
17187 }
17188
17189 case CK_IntegralComplexToReal: {
17190 ComplexValue C;
17191 if (!EvaluateComplex(SubExpr, C, Info))
17192 return false;
17193 return Success(C.getComplexIntReal(), E);
17194 }
17195
17196 case CK_FloatingToIntegral: {
17197 APFloat F(0.0);
17198 if (!EvaluateFloat(SubExpr, F, Info))
17199 return false;
17200
17201 APSInt Value;
17202 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
17203 return false;
17204 return Success(Value, E);
17205 }
17206 case CK_HLSLVectorTruncation: {
17207 APValue Val;
17208 if (!EvaluateVector(SubExpr, Val, Info))
17209 return Error(E);
17210 return Success(Val.getVectorElt(0), E);
17211 }
17212 }
17213
17214 llvm_unreachable("unknown cast resulting in integral value");
17215}
17216
17217bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
17218 if (E->getSubExpr()->getType()->isAnyComplexType()) {
17219 ComplexValue LV;
17220 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
17221 return false;
17222 if (!LV.isComplexInt())
17223 return Error(E);
17224 return Success(LV.getComplexIntReal(), E);
17225 }
17226
17227 return Visit(E->getSubExpr());
17228}
17229
17230bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
17231 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
17232 ComplexValue LV;
17233 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
17234 return false;
17235 if (!LV.isComplexInt())
17236 return Error(E);
17237 return Success(LV.getComplexIntImag(), E);
17238 }
17239
17240 VisitIgnoredValue(E->getSubExpr());
17241 return Success(0, E);
17242}
17243
17244bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
17245 return Success(E->getPackLength(), E);
17246}
17247
17248bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
17249 return Success(E->getValue(), E);
17250}
17251
17252bool IntExprEvaluator::VisitConceptSpecializationExpr(
17253 const ConceptSpecializationExpr *E) {
17254 return Success(E->isSatisfied(), E);
17255}
17256
17257bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) {
17258 return Success(E->isSatisfied(), E);
17259}
17260
17261bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
17262 switch (E->getOpcode()) {
17263 default:
17264 // Invalid unary operators
17265 return Error(E);
17266 case UO_Plus:
17267 // The result is just the value.
17268 return Visit(E->getSubExpr());
17269 case UO_Minus: {
17270 if (!Visit(E->getSubExpr())) return false;
17271 if (!Result.isFixedPoint())
17272 return Error(E);
17273 bool Overflowed;
17274 APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
17275 if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
17276 return false;
17277 return Success(Negated, E);
17278 }
17279 case UO_LNot: {
17280 bool bres;
17281 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
17282 return false;
17283 return Success(!bres, E);
17284 }
17285 }
17286}
17287
17288bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
17289 const Expr *SubExpr = E->getSubExpr();
17290 QualType DestType = E->getType();
17291 assert(DestType->isFixedPointType() &&
17292 "Expected destination type to be a fixed point type");
17293 auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
17294
17295 switch (E->getCastKind()) {
17296 case CK_FixedPointCast: {
17297 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
17298 if (!EvaluateFixedPoint(SubExpr, Src, Info))
17299 return false;
17300 bool Overflowed;
17301 APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
17302 if (Overflowed) {
17303 if (Info.checkingForUndefinedBehavior())
17304 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
17305 diag::warn_fixedpoint_constant_overflow)
17306 << Result.toString() << E->getType();
17307 if (!HandleOverflow(Info, E, Result, E->getType()))
17308 return false;
17309 }
17310 return Success(Result, E);
17311 }
17312 case CK_IntegralToFixedPoint: {
17313 APSInt Src;
17314 if (!EvaluateInteger(SubExpr, Src, Info))
17315 return false;
17316
17317 bool Overflowed;
17318 APFixedPoint IntResult = APFixedPoint::getFromIntValue(
17319 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
17320
17321 if (Overflowed) {
17322 if (Info.checkingForUndefinedBehavior())
17323 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
17324 diag::warn_fixedpoint_constant_overflow)
17325 << IntResult.toString() << E->getType();
17326 if (!HandleOverflow(Info, E, IntResult, E->getType()))
17327 return false;
17328 }
17329
17330 return Success(IntResult, E);
17331 }
17332 case CK_FloatingToFixedPoint: {
17333 APFloat Src(0.0);
17334 if (!EvaluateFloat(SubExpr, Src, Info))
17335 return false;
17336
17337 bool Overflowed;
17338 APFixedPoint Result = APFixedPoint::getFromFloatValue(
17339 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
17340
17341 if (Overflowed) {
17342 if (Info.checkingForUndefinedBehavior())
17343 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
17344 diag::warn_fixedpoint_constant_overflow)
17345 << Result.toString() << E->getType();
17346 if (!HandleOverflow(Info, E, Result, E->getType()))
17347 return false;
17348 }
17349
17350 return Success(Result, E);
17351 }
17352 case CK_NoOp:
17353 case CK_LValueToRValue:
17354 return ExprEvaluatorBaseTy::VisitCastExpr(E);
17355 default:
17356 return Error(E);
17357 }
17358}
17359
17360bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
17361 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
17362 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
17363
17364 const Expr *LHS = E->getLHS();
17365 const Expr *RHS = E->getRHS();
17366 FixedPointSemantics ResultFXSema =
17367 Info.Ctx.getFixedPointSemantics(E->getType());
17368
17369 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
17370 if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
17371 return false;
17372 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
17373 if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
17374 return false;
17375
17376 bool OpOverflow = false, ConversionOverflow = false;
17377 APFixedPoint Result(LHSFX.getSemantics());
17378 switch (E->getOpcode()) {
17379 case BO_Add: {
17380 Result = LHSFX.add(RHSFX, &OpOverflow)
17381 .convert(ResultFXSema, &ConversionOverflow);
17382 break;
17383 }
17384 case BO_Sub: {
17385 Result = LHSFX.sub(RHSFX, &OpOverflow)
17386 .convert(ResultFXSema, &ConversionOverflow);
17387 break;
17388 }
17389 case BO_Mul: {
17390 Result = LHSFX.mul(RHSFX, &OpOverflow)
17391 .convert(ResultFXSema, &ConversionOverflow);
17392 break;
17393 }
17394 case BO_Div: {
17395 if (RHSFX.getValue() == 0) {
17396 Info.FFDiag(E, diag::note_expr_divide_by_zero);
17397 return false;
17398 }
17399 Result = LHSFX.div(RHSFX, &OpOverflow)
17400 .convert(ResultFXSema, &ConversionOverflow);
17401 break;
17402 }
17403 case BO_Shl:
17404 case BO_Shr: {
17405 FixedPointSemantics LHSSema = LHSFX.getSemantics();
17406 llvm::APSInt RHSVal = RHSFX.getValue();
17407
17408 unsigned ShiftBW =
17409 LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding();
17410 unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1);
17411 // Embedded-C 4.1.6.2.2:
17412 // The right operand must be nonnegative and less than the total number
17413 // of (nonpadding) bits of the fixed-point operand ...
17414 if (RHSVal.isNegative())
17415 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal;
17416 else if (Amt != RHSVal)
17417 Info.CCEDiag(E, diag::note_constexpr_large_shift)
17418 << RHSVal << E->getType() << ShiftBW;
17419
17420 if (E->getOpcode() == BO_Shl)
17421 Result = LHSFX.shl(Amt, &OpOverflow);
17422 else
17423 Result = LHSFX.shr(Amt, &OpOverflow);
17424 break;
17425 }
17426 default:
17427 return false;
17428 }
17429 if (OpOverflow || ConversionOverflow) {
17430 if (Info.checkingForUndefinedBehavior())
17431 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
17432 diag::warn_fixedpoint_constant_overflow)
17433 << Result.toString() << E->getType();
17434 if (!HandleOverflow(Info, E, Result, E->getType()))
17435 return false;
17436 }
17437 return Success(Result, E);
17438}
17439
17440//===----------------------------------------------------------------------===//
17441// Float Evaluation
17442//===----------------------------------------------------------------------===//
17443
17444namespace {
17445class FloatExprEvaluator
17446 : public ExprEvaluatorBase<FloatExprEvaluator> {
17447 APFloat &Result;
17448public:
17449 FloatExprEvaluator(EvalInfo &info, APFloat &result)
17450 : ExprEvaluatorBaseTy(info), Result(result) {}
17451
17452 bool Success(const APValue &V, const Expr *e) {
17453 Result = V.getFloat();
17454 return true;
17455 }
17456
17457 bool ZeroInitialization(const Expr *E) {
17458 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
17459 return true;
17460 }
17461
17462 bool VisitCallExpr(const CallExpr *E);
17463
17464 bool VisitUnaryOperator(const UnaryOperator *E);
17465 bool VisitBinaryOperator(const BinaryOperator *E);
17466 bool VisitFloatingLiteral(const FloatingLiteral *E);
17467 bool VisitCastExpr(const CastExpr *E);
17468
17469 bool VisitUnaryReal(const UnaryOperator *E);
17470 bool VisitUnaryImag(const UnaryOperator *E);
17471
17472 // FIXME: Missing: array subscript of vector, member of vector
17473};
17474} // end anonymous namespace
17475
17476static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
17477 assert(!E->isValueDependent());
17478 assert(E->isPRValue() && E->getType()->isRealFloatingType());
17479 return FloatExprEvaluator(Info, Result).Visit(E);
17480}
17481
17482static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
17483 QualType ResultTy,
17484 const Expr *Arg,
17485 bool SNaN,
17486 llvm::APFloat &Result) {
17487 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
17488 if (!S) return false;
17489
17490 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
17491
17492 llvm::APInt fill;
17493
17494 // Treat empty strings as if they were zero.
17495 if (S->getString().empty())
17496 fill = llvm::APInt(32, 0);
17497 else if (S->getString().getAsInteger(0, fill))
17498 return false;
17499
17500 if (Context.getTargetInfo().isNan2008()) {
17501 if (SNaN)
17502 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
17503 else
17504 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
17505 } else {
17506 // Prior to IEEE 754-2008, architectures were allowed to choose whether
17507 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
17508 // a different encoding to what became a standard in 2008, and for pre-
17509 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
17510 // sNaN. This is now known as "legacy NaN" encoding.
17511 if (SNaN)
17512 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
17513 else
17514 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
17515 }
17516
17517 return true;
17518}
17519
17520bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
17521 if (!IsConstantEvaluatedBuiltinCall(E))
17522 return ExprEvaluatorBaseTy::VisitCallExpr(E);
17523
17524 switch (E->getBuiltinCallee()) {
17525 default:
17526 return false;
17527
17528 case Builtin::BI__builtin_huge_val:
17529 case Builtin::BI__builtin_huge_valf:
17530 case Builtin::BI__builtin_huge_vall:
17531 case Builtin::BI__builtin_huge_valf16:
17532 case Builtin::BI__builtin_huge_valf128:
17533 case Builtin::BI__builtin_inf:
17534 case Builtin::BI__builtin_inff:
17535 case Builtin::BI__builtin_infl:
17536 case Builtin::BI__builtin_inff16:
17537 case Builtin::BI__builtin_inff128: {
17538 const llvm::fltSemantics &Sem =
17539 Info.Ctx.getFloatTypeSemantics(E->getType());
17540 Result = llvm::APFloat::getInf(Sem);
17541 return true;
17542 }
17543
17544 case Builtin::BI__builtin_nans:
17545 case Builtin::BI__builtin_nansf:
17546 case Builtin::BI__builtin_nansl:
17547 case Builtin::BI__builtin_nansf16:
17548 case Builtin::BI__builtin_nansf128:
17549 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
17550 true, Result))
17551 return Error(E);
17552 return true;
17553
17554 case Builtin::BI__builtin_nan:
17555 case Builtin::BI__builtin_nanf:
17556 case Builtin::BI__builtin_nanl:
17557 case Builtin::BI__builtin_nanf16:
17558 case Builtin::BI__builtin_nanf128:
17559 // If this is __builtin_nan() turn this into a nan, otherwise we
17560 // can't constant fold it.
17561 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
17562 false, Result))
17563 return Error(E);
17564 return true;
17565
17566 case Builtin::BI__builtin_elementwise_abs:
17567 case Builtin::BI__builtin_fabs:
17568 case Builtin::BI__builtin_fabsf:
17569 case Builtin::BI__builtin_fabsl:
17570 case Builtin::BI__builtin_fabsf128:
17571 // The C standard says "fabs raises no floating-point exceptions,
17572 // even if x is a signaling NaN. The returned value is independent of
17573 // the current rounding direction mode." Therefore constant folding can
17574 // proceed without regard to the floating point settings.
17575 // Reference, WG14 N2478 F.10.4.3
17576 if (!EvaluateFloat(E->getArg(0), Result, Info))
17577 return false;
17578
17579 if (Result.isNegative())
17580 Result.changeSign();
17581 return true;
17582
17583 case Builtin::BI__arithmetic_fence:
17584 return EvaluateFloat(E->getArg(0), Result, Info);
17585
17586 // FIXME: Builtin::BI__builtin_powi
17587 // FIXME: Builtin::BI__builtin_powif
17588 // FIXME: Builtin::BI__builtin_powil
17589
17590 case Builtin::BI__builtin_copysign:
17591 case Builtin::BI__builtin_copysignf:
17592 case Builtin::BI__builtin_copysignl:
17593 case Builtin::BI__builtin_copysignf128: {
17594 APFloat RHS(0.);
17595 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
17596 !EvaluateFloat(E->getArg(1), RHS, Info))
17597 return false;
17598 Result.copySign(RHS);
17599 return true;
17600 }
17601
17602 case Builtin::BI__builtin_fmax:
17603 case Builtin::BI__builtin_fmaxf:
17604 case Builtin::BI__builtin_fmaxl:
17605 case Builtin::BI__builtin_fmaxf16:
17606 case Builtin::BI__builtin_fmaxf128: {
17607 APFloat RHS(0.);
17608 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
17609 !EvaluateFloat(E->getArg(1), RHS, Info))
17610 return false;
17611 Result = maxnum(Result, RHS);
17612 return true;
17613 }
17614
17615 case Builtin::BI__builtin_fmin:
17616 case Builtin::BI__builtin_fminf:
17617 case Builtin::BI__builtin_fminl:
17618 case Builtin::BI__builtin_fminf16:
17619 case Builtin::BI__builtin_fminf128: {
17620 APFloat RHS(0.);
17621 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
17622 !EvaluateFloat(E->getArg(1), RHS, Info))
17623 return false;
17624 Result = minnum(Result, RHS);
17625 return true;
17626 }
17627
17628 case Builtin::BI__builtin_fmaximum_num:
17629 case Builtin::BI__builtin_fmaximum_numf:
17630 case Builtin::BI__builtin_fmaximum_numl:
17631 case Builtin::BI__builtin_fmaximum_numf16:
17632 case Builtin::BI__builtin_fmaximum_numf128: {
17633 APFloat RHS(0.);
17634 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
17635 !EvaluateFloat(E->getArg(1), RHS, Info))
17636 return false;
17637 Result = maximumnum(Result, RHS);
17638 return true;
17639 }
17640
17641 case Builtin::BI__builtin_fminimum_num:
17642 case Builtin::BI__builtin_fminimum_numf:
17643 case Builtin::BI__builtin_fminimum_numl:
17644 case Builtin::BI__builtin_fminimum_numf16:
17645 case Builtin::BI__builtin_fminimum_numf128: {
17646 APFloat RHS(0.);
17647 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
17648 !EvaluateFloat(E->getArg(1), RHS, Info))
17649 return false;
17650 Result = minimumnum(Result, RHS);
17651 return true;
17652 }
17653
17654 case Builtin::BI__builtin_elementwise_fma: {
17655 if (!E->getArg(0)->isPRValue() || !E->getArg(1)->isPRValue() ||
17656 !E->getArg(2)->isPRValue()) {
17657 return false;
17658 }
17659 APFloat SourceY(0.), SourceZ(0.);
17660 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
17661 !EvaluateFloat(E->getArg(1), SourceY, Info) ||
17662 !EvaluateFloat(E->getArg(2), SourceZ, Info))
17663 return false;
17664 llvm::RoundingMode RM = getActiveRoundingMode(getEvalInfo(), E);
17665 (void)Result.fusedMultiplyAdd(SourceY, SourceZ, RM);
17666 return true;
17667 }
17668
17669 case clang::X86::BI__builtin_ia32_vec_ext_v4sf: {
17670 APValue Vec;
17671 APSInt IdxAPS;
17672 if (!EvaluateVector(E->getArg(0), Vec, Info) ||
17673 !EvaluateInteger(E->getArg(1), IdxAPS, Info))
17674 return false;
17675 unsigned N = Vec.getVectorLength();
17676 unsigned Idx = static_cast<unsigned>(IdxAPS.getZExtValue() & (N - 1));
17677 return Success(Vec.getVectorElt(Idx), E);
17678 }
17679 }
17680}
17681
17682bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
17683 if (E->getSubExpr()->getType()->isAnyComplexType()) {
17684 ComplexValue CV;
17685 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
17686 return false;
17687 Result = CV.FloatReal;
17688 return true;
17689 }
17690
17691 return Visit(E->getSubExpr());
17692}
17693
17694bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
17695 if (E->getSubExpr()->getType()->isAnyComplexType()) {
17696 ComplexValue CV;
17697 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
17698 return false;
17699 Result = CV.FloatImag;
17700 return true;
17701 }
17702
17703 VisitIgnoredValue(E->getSubExpr());
17704 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
17705 Result = llvm::APFloat::getZero(Sem);
17706 return true;
17707}
17708
17709bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
17710 switch (E->getOpcode()) {
17711 default: return Error(E);
17712 case UO_Plus:
17713 return EvaluateFloat(E->getSubExpr(), Result, Info);
17714 case UO_Minus:
17715 // In C standard, WG14 N2478 F.3 p4
17716 // "the unary - raises no floating point exceptions,
17717 // even if the operand is signalling."
17718 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
17719 return false;
17720 Result.changeSign();
17721 return true;
17722 }
17723}
17724
17725bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
17726 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
17727 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
17728
17729 APFloat RHS(0.0);
17730 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
17731 if (!LHSOK && !Info.noteFailure())
17732 return false;
17733 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
17734 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
17735}
17736
17737bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
17738 Result = E->getValue();
17739 return true;
17740}
17741
17742bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
17743 const Expr* SubExpr = E->getSubExpr();
17744
17745 switch (E->getCastKind()) {
17746 default:
17747 return ExprEvaluatorBaseTy::VisitCastExpr(E);
17748
17749 case CK_IntegralToFloating: {
17750 APSInt IntResult;
17751 const FPOptions FPO = E->getFPFeaturesInEffect(
17752 Info.Ctx.getLangOpts());
17753 return EvaluateInteger(SubExpr, IntResult, Info) &&
17754 HandleIntToFloatCast(Info, E, FPO, SubExpr->getType(),
17755 IntResult, E->getType(), Result);
17756 }
17757
17758 case CK_FixedPointToFloating: {
17759 APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
17760 if (!EvaluateFixedPoint(SubExpr, FixResult, Info))
17761 return false;
17762 Result =
17763 FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->getType()));
17764 return true;
17765 }
17766
17767 case CK_FloatingCast: {
17768 if (!Visit(SubExpr))
17769 return false;
17770 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
17771 Result);
17772 }
17773
17774 case CK_FloatingComplexToReal: {
17775 ComplexValue V;
17776 if (!EvaluateComplex(SubExpr, V, Info))
17777 return false;
17778 Result = V.getComplexFloatReal();
17779 return true;
17780 }
17781 case CK_HLSLVectorTruncation: {
17782 APValue Val;
17783 if (!EvaluateVector(SubExpr, Val, Info))
17784 return Error(E);
17785 return Success(Val.getVectorElt(0), E);
17786 }
17787 }
17788}
17789
17790//===----------------------------------------------------------------------===//
17791// Complex Evaluation (for float and integer)
17792//===----------------------------------------------------------------------===//
17793
17794namespace {
17795class ComplexExprEvaluator
17796 : public ExprEvaluatorBase<ComplexExprEvaluator> {
17797 ComplexValue &Result;
17798
17799public:
17800 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
17801 : ExprEvaluatorBaseTy(info), Result(Result) {}
17802
17803 bool Success(const APValue &V, const Expr *e) {
17804 Result.setFrom(V);
17805 return true;
17806 }
17807
17808 bool ZeroInitialization(const Expr *E);
17809
17810 //===--------------------------------------------------------------------===//
17811 // Visitor Methods
17812 //===--------------------------------------------------------------------===//
17813
17814 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
17815 bool VisitCastExpr(const CastExpr *E);
17816 bool VisitBinaryOperator(const BinaryOperator *E);
17817 bool VisitUnaryOperator(const UnaryOperator *E);
17818 bool VisitInitListExpr(const InitListExpr *E);
17819 bool VisitCallExpr(const CallExpr *E);
17820};
17821} // end anonymous namespace
17822
17823static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
17824 EvalInfo &Info) {
17825 assert(!E->isValueDependent());
17826 assert(E->isPRValue() && E->getType()->isAnyComplexType());
17827 return ComplexExprEvaluator(Info, Result).Visit(E);
17828}
17829
17830bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
17831 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
17832 if (ElemTy->isRealFloatingType()) {
17833 Result.makeComplexFloat();
17834 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
17835 Result.FloatReal = Zero;
17836 Result.FloatImag = Zero;
17837 } else {
17838 Result.makeComplexInt();
17839 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
17840 Result.IntReal = Zero;
17841 Result.IntImag = Zero;
17842 }
17843 return true;
17844}
17845
17846bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
17847 const Expr* SubExpr = E->getSubExpr();
17848
17849 if (SubExpr->getType()->isRealFloatingType()) {
17850 Result.makeComplexFloat();
17851 APFloat &Imag = Result.FloatImag;
17852 if (!EvaluateFloat(SubExpr, Imag, Info))
17853 return false;
17854
17855 Result.FloatReal = APFloat(Imag.getSemantics());
17856 return true;
17857 } else {
17858 assert(SubExpr->getType()->isIntegerType() &&
17859 "Unexpected imaginary literal.");
17860
17861 Result.makeComplexInt();
17862 APSInt &Imag = Result.IntImag;
17863 if (!EvaluateInteger(SubExpr, Imag, Info))
17864 return false;
17865
17866 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
17867 return true;
17868 }
17869}
17870
17871bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
17872
17873 switch (E->getCastKind()) {
17874 case CK_BitCast:
17875 case CK_BaseToDerived:
17876 case CK_DerivedToBase:
17877 case CK_UncheckedDerivedToBase:
17878 case CK_Dynamic:
17879 case CK_ToUnion:
17880 case CK_ArrayToPointerDecay:
17881 case CK_FunctionToPointerDecay:
17882 case CK_NullToPointer:
17883 case CK_NullToMemberPointer:
17884 case CK_BaseToDerivedMemberPointer:
17885 case CK_DerivedToBaseMemberPointer:
17886 case CK_MemberPointerToBoolean:
17887 case CK_ReinterpretMemberPointer:
17888 case CK_ConstructorConversion:
17889 case CK_IntegralToPointer:
17890 case CK_PointerToIntegral:
17891 case CK_PointerToBoolean:
17892 case CK_ToVoid:
17893 case CK_VectorSplat:
17894 case CK_IntegralCast:
17895 case CK_BooleanToSignedIntegral:
17896 case CK_IntegralToBoolean:
17897 case CK_IntegralToFloating:
17898 case CK_FloatingToIntegral:
17899 case CK_FloatingToBoolean:
17900 case CK_FloatingCast:
17901 case CK_CPointerToObjCPointerCast:
17902 case CK_BlockPointerToObjCPointerCast:
17903 case CK_AnyPointerToBlockPointerCast:
17904 case CK_ObjCObjectLValueCast:
17905 case CK_FloatingComplexToReal:
17906 case CK_FloatingComplexToBoolean:
17907 case CK_IntegralComplexToReal:
17908 case CK_IntegralComplexToBoolean:
17909 case CK_ARCProduceObject:
17910 case CK_ARCConsumeObject:
17911 case CK_ARCReclaimReturnedObject:
17912 case CK_ARCExtendBlockObject:
17913 case CK_CopyAndAutoreleaseBlockObject:
17914 case CK_BuiltinFnToFnPtr:
17915 case CK_ZeroToOCLOpaqueType:
17916 case CK_NonAtomicToAtomic:
17917 case CK_AddressSpaceConversion:
17918 case CK_IntToOCLSampler:
17919 case CK_FloatingToFixedPoint:
17920 case CK_FixedPointToFloating:
17921 case CK_FixedPointCast:
17922 case CK_FixedPointToBoolean:
17923 case CK_FixedPointToIntegral:
17924 case CK_IntegralToFixedPoint:
17925 case CK_MatrixCast:
17926 case CK_HLSLVectorTruncation:
17927 case CK_HLSLElementwiseCast:
17928 case CK_HLSLAggregateSplatCast:
17929 llvm_unreachable("invalid cast kind for complex value");
17930
17931 case CK_LValueToRValue:
17932 case CK_AtomicToNonAtomic:
17933 case CK_NoOp:
17934 case CK_LValueToRValueBitCast:
17935 case CK_HLSLArrayRValue:
17936 return ExprEvaluatorBaseTy::VisitCastExpr(E);
17937
17938 case CK_Dependent:
17939 case CK_LValueBitCast:
17940 case CK_UserDefinedConversion:
17941 return Error(E);
17942
17943 case CK_FloatingRealToComplex: {
17944 APFloat &Real = Result.FloatReal;
17945 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
17946 return false;
17947
17948 Result.makeComplexFloat();
17949 Result.FloatImag = APFloat(Real.getSemantics());
17950 return true;
17951 }
17952
17953 case CK_FloatingComplexCast: {
17954 if (!Visit(E->getSubExpr()))
17955 return false;
17956
17957 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
17958 QualType From
17959 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
17960
17961 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
17962 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
17963 }
17964
17965 case CK_FloatingComplexToIntegralComplex: {
17966 if (!Visit(E->getSubExpr()))
17967 return false;
17968
17969 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
17970 QualType From
17971 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
17972 Result.makeComplexInt();
17973 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
17974 To, Result.IntReal) &&
17975 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
17976 To, Result.IntImag);
17977 }
17978
17979 case CK_IntegralRealToComplex: {
17980 APSInt &Real = Result.IntReal;
17981 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
17982 return false;
17983
17984 Result.makeComplexInt();
17985 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
17986 return true;
17987 }
17988
17989 case CK_IntegralComplexCast: {
17990 if (!Visit(E->getSubExpr()))
17991 return false;
17992
17993 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
17994 QualType From
17995 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
17996
17997 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
17998 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
17999 return true;
18000 }
18001
18002 case CK_IntegralComplexToFloatingComplex: {
18003 if (!Visit(E->getSubExpr()))
18004 return false;
18005
18006 const FPOptions FPO = E->getFPFeaturesInEffect(
18007 Info.Ctx.getLangOpts());
18008 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
18009 QualType From
18010 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
18011 Result.makeComplexFloat();
18012 return HandleIntToFloatCast(Info, E, FPO, From, Result.IntReal,
18013 To, Result.FloatReal) &&
18014 HandleIntToFloatCast(Info, E, FPO, From, Result.IntImag,
18015 To, Result.FloatImag);
18016 }
18017 }
18018
18019 llvm_unreachable("unknown cast resulting in complex value");
18020}
18021
18022void HandleComplexComplexMul(APFloat A, APFloat B, APFloat C, APFloat D,
18023 APFloat &ResR, APFloat &ResI) {
18024 // This is an implementation of complex multiplication according to the
18025 // constraints laid out in C11 Annex G. The implementation uses the
18026 // following naming scheme:
18027 // (a + ib) * (c + id)
18028
18029 APFloat AC = A * C;
18030 APFloat BD = B * D;
18031 APFloat AD = A * D;
18032 APFloat BC = B * C;
18033 ResR = AC - BD;
18034 ResI = AD + BC;
18035 if (ResR.isNaN() && ResI.isNaN()) {
18036 bool Recalc = false;
18037 if (A.isInfinity() || B.isInfinity()) {
18038 A = APFloat::copySign(APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0),
18039 A);
18040 B = APFloat::copySign(APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0),
18041 B);
18042 if (C.isNaN())
18043 C = APFloat::copySign(APFloat(C.getSemantics()), C);
18044 if (D.isNaN())
18045 D = APFloat::copySign(APFloat(D.getSemantics()), D);
18046 Recalc = true;
18047 }
18048 if (C.isInfinity() || D.isInfinity()) {
18049 C = APFloat::copySign(APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0),
18050 C);
18051 D = APFloat::copySign(APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0),
18052 D);
18053 if (A.isNaN())
18054 A = APFloat::copySign(APFloat(A.getSemantics()), A);
18055 if (B.isNaN())
18056 B = APFloat::copySign(APFloat(B.getSemantics()), B);
18057 Recalc = true;
18058 }
18059 if (!Recalc && (AC.isInfinity() || BD.isInfinity() || AD.isInfinity() ||
18060 BC.isInfinity())) {
18061 if (A.isNaN())
18062 A = APFloat::copySign(APFloat(A.getSemantics()), A);
18063 if (B.isNaN())
18064 B = APFloat::copySign(APFloat(B.getSemantics()), B);
18065 if (C.isNaN())
18066 C = APFloat::copySign(APFloat(C.getSemantics()), C);
18067 if (D.isNaN())
18068 D = APFloat::copySign(APFloat(D.getSemantics()), D);
18069 Recalc = true;
18070 }
18071 if (Recalc) {
18072 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
18073 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
18074 }
18075 }
18076}
18077
18078void HandleComplexComplexDiv(APFloat A, APFloat B, APFloat C, APFloat D,
18079 APFloat &ResR, APFloat &ResI) {
18080 // This is an implementation of complex division according to the
18081 // constraints laid out in C11 Annex G. The implementation uses the
18082 // following naming scheme:
18083 // (a + ib) / (c + id)
18084
18085 int DenomLogB = 0;
18086 APFloat MaxCD = maxnum(abs(C), abs(D));
18087 if (MaxCD.isFinite()) {
18088 DenomLogB = ilogb(MaxCD);
18089 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
18090 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
18091 }
18092 APFloat Denom = C * C + D * D;
18093 ResR =
18094 scalbn((A * C + B * D) / Denom, -DenomLogB, APFloat::rmNearestTiesToEven);
18095 ResI =
18096 scalbn((B * C - A * D) / Denom, -DenomLogB, APFloat::rmNearestTiesToEven);
18097 if (ResR.isNaN() && ResI.isNaN()) {
18098 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
18099 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
18100 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
18101 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
18102 D.isFinite()) {
18103 A = APFloat::copySign(APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0),
18104 A);
18105 B = APFloat::copySign(APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0),
18106 B);
18107 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
18108 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
18109 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
18110 C = APFloat::copySign(APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0),
18111 C);
18112 D = APFloat::copySign(APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0),
18113 D);
18114 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
18115 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
18116 }
18117 }
18118}
18119
18120bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
18121 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
18122 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
18123
18124 // Track whether the LHS or RHS is real at the type system level. When this is
18125 // the case we can simplify our evaluation strategy.
18126 bool LHSReal = false, RHSReal = false;
18127
18128 bool LHSOK;
18129 if (E->getLHS()->getType()->isRealFloatingType()) {
18130 LHSReal = true;
18131 APFloat &Real = Result.FloatReal;
18132 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
18133 if (LHSOK) {
18134 Result.makeComplexFloat();
18135 Result.FloatImag = APFloat(Real.getSemantics());
18136 }
18137 } else {
18138 LHSOK = Visit(E->getLHS());
18139 }
18140 if (!LHSOK && !Info.noteFailure())
18141 return false;
18142
18143 ComplexValue RHS;
18144 if (E->getRHS()->getType()->isRealFloatingType()) {
18145 RHSReal = true;
18146 APFloat &Real = RHS.FloatReal;
18147 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
18148 return false;
18149 RHS.makeComplexFloat();
18150 RHS.FloatImag = APFloat(Real.getSemantics());
18151 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
18152 return false;
18153
18154 assert(!(LHSReal && RHSReal) &&
18155 "Cannot have both operands of a complex operation be real.");
18156 switch (E->getOpcode()) {
18157 default: return Error(E);
18158 case BO_Add:
18159 if (Result.isComplexFloat()) {
18160 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
18161 APFloat::rmNearestTiesToEven);
18162 if (LHSReal)
18163 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
18164 else if (!RHSReal)
18165 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
18166 APFloat::rmNearestTiesToEven);
18167 } else {
18168 Result.getComplexIntReal() += RHS.getComplexIntReal();
18169 Result.getComplexIntImag() += RHS.getComplexIntImag();
18170 }
18171 break;
18172 case BO_Sub:
18173 if (Result.isComplexFloat()) {
18174 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
18175 APFloat::rmNearestTiesToEven);
18176 if (LHSReal) {
18177 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
18178 Result.getComplexFloatImag().changeSign();
18179 } else if (!RHSReal) {
18180 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
18181 APFloat::rmNearestTiesToEven);
18182 }
18183 } else {
18184 Result.getComplexIntReal() -= RHS.getComplexIntReal();
18185 Result.getComplexIntImag() -= RHS.getComplexIntImag();
18186 }
18187 break;
18188 case BO_Mul:
18189 if (Result.isComplexFloat()) {
18190 // This is an implementation of complex multiplication according to the
18191 // constraints laid out in C11 Annex G. The implementation uses the
18192 // following naming scheme:
18193 // (a + ib) * (c + id)
18194 ComplexValue LHS = Result;
18195 APFloat &A = LHS.getComplexFloatReal();
18196 APFloat &B = LHS.getComplexFloatImag();
18197 APFloat &C = RHS.getComplexFloatReal();
18198 APFloat &D = RHS.getComplexFloatImag();
18199 APFloat &ResR = Result.getComplexFloatReal();
18200 APFloat &ResI = Result.getComplexFloatImag();
18201 if (LHSReal) {
18202 assert(!RHSReal && "Cannot have two real operands for a complex op!");
18203 ResR = A;
18204 ResI = A;
18205 // ResR = A * C;
18206 // ResI = A * D;
18207 if (!handleFloatFloatBinOp(Info, E, ResR, BO_Mul, C) ||
18208 !handleFloatFloatBinOp(Info, E, ResI, BO_Mul, D))
18209 return false;
18210 } else if (RHSReal) {
18211 // ResR = C * A;
18212 // ResI = C * B;
18213 ResR = C;
18214 ResI = C;
18215 if (!handleFloatFloatBinOp(Info, E, ResR, BO_Mul, A) ||
18216 !handleFloatFloatBinOp(Info, E, ResI, BO_Mul, B))
18217 return false;
18218 } else {
18219 HandleComplexComplexMul(A, B, C, D, ResR, ResI);
18220 }
18221 } else {
18222 ComplexValue LHS = Result;
18223 Result.getComplexIntReal() =
18224 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
18225 LHS.getComplexIntImag() * RHS.getComplexIntImag());
18226 Result.getComplexIntImag() =
18227 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
18228 LHS.getComplexIntImag() * RHS.getComplexIntReal());
18229 }
18230 break;
18231 case BO_Div:
18232 if (Result.isComplexFloat()) {
18233 // This is an implementation of complex division according to the
18234 // constraints laid out in C11 Annex G. The implementation uses the
18235 // following naming scheme:
18236 // (a + ib) / (c + id)
18237 ComplexValue LHS = Result;
18238 APFloat &A = LHS.getComplexFloatReal();
18239 APFloat &B = LHS.getComplexFloatImag();
18240 APFloat &C = RHS.getComplexFloatReal();
18241 APFloat &D = RHS.getComplexFloatImag();
18242 APFloat &ResR = Result.getComplexFloatReal();
18243 APFloat &ResI = Result.getComplexFloatImag();
18244 if (RHSReal) {
18245 ResR = A;
18246 ResI = B;
18247 // ResR = A / C;
18248 // ResI = B / C;
18249 if (!handleFloatFloatBinOp(Info, E, ResR, BO_Div, C) ||
18250 !handleFloatFloatBinOp(Info, E, ResI, BO_Div, C))
18251 return false;
18252 } else {
18253 if (LHSReal) {
18254 // No real optimizations we can do here, stub out with zero.
18255 B = APFloat::getZero(A.getSemantics());
18256 }
18257 HandleComplexComplexDiv(A, B, C, D, ResR, ResI);
18258 }
18259 } else {
18260 ComplexValue LHS = Result;
18261 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
18262 RHS.getComplexIntImag() * RHS.getComplexIntImag();
18263 if (Den.isZero())
18264 return Error(E, diag::note_expr_divide_by_zero);
18265
18266 Result.getComplexIntReal() =
18267 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
18268 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
18269 Result.getComplexIntImag() =
18270 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
18271 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
18272 }
18273 break;
18274 }
18275
18276 return true;
18277}
18278
18279bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
18280 // Get the operand value into 'Result'.
18281 if (!Visit(E->getSubExpr()))
18282 return false;
18283
18284 switch (E->getOpcode()) {
18285 default:
18286 return Error(E);
18287 case UO_Extension:
18288 return true;
18289 case UO_Plus:
18290 // The result is always just the subexpr.
18291 return true;
18292 case UO_Minus:
18293 if (Result.isComplexFloat()) {
18294 Result.getComplexFloatReal().changeSign();
18295 Result.getComplexFloatImag().changeSign();
18296 }
18297 else {
18298 Result.getComplexIntReal() = -Result.getComplexIntReal();
18299 Result.getComplexIntImag() = -Result.getComplexIntImag();
18300 }
18301 return true;
18302 case UO_Not:
18303 if (Result.isComplexFloat())
18304 Result.getComplexFloatImag().changeSign();
18305 else
18306 Result.getComplexIntImag() = -Result.getComplexIntImag();
18307 return true;
18308 }
18309}
18310
18311bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
18312 if (E->getNumInits() == 2) {
18313 if (E->getType()->isComplexType()) {
18314 Result.makeComplexFloat();
18315 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
18316 return false;
18317 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
18318 return false;
18319 } else {
18320 Result.makeComplexInt();
18321 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
18322 return false;
18323 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
18324 return false;
18325 }
18326 return true;
18327 }
18328 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
18329}
18330
18331bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) {
18332 if (!IsConstantEvaluatedBuiltinCall(E))
18333 return ExprEvaluatorBaseTy::VisitCallExpr(E);
18334
18335 switch (E->getBuiltinCallee()) {
18336 case Builtin::BI__builtin_complex:
18337 Result.makeComplexFloat();
18338 if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info))
18339 return false;
18340 if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info))
18341 return false;
18342 return true;
18343
18344 default:
18345 return false;
18346 }
18347}
18348
18349//===----------------------------------------------------------------------===//
18350// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
18351// implicit conversion.
18352//===----------------------------------------------------------------------===//
18353
18354namespace {
18355class AtomicExprEvaluator :
18356 public ExprEvaluatorBase<AtomicExprEvaluator> {
18357 const LValue *This;
18358 APValue &Result;
18359public:
18360 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
18361 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
18362
18363 bool Success(const APValue &V, const Expr *E) {
18364 Result = V;
18365 return true;
18366 }
18367
18368 bool ZeroInitialization(const Expr *E) {
18369 ImplicitValueInitExpr VIE(
18370 E->getType()->castAs<AtomicType>()->getValueType());
18371 // For atomic-qualified class (and array) types in C++, initialize the
18372 // _Atomic-wrapped subobject directly, in-place.
18373 return This ? EvaluateInPlace(Result, Info, *This, &VIE)
18374 : Evaluate(Result, Info, &VIE);
18375 }
18376
18377 bool VisitCastExpr(const CastExpr *E) {
18378 switch (E->getCastKind()) {
18379 default:
18380 return ExprEvaluatorBaseTy::VisitCastExpr(E);
18381 case CK_NullToPointer:
18382 VisitIgnoredValue(E->getSubExpr());
18383 return ZeroInitialization(E);
18384 case CK_NonAtomicToAtomic:
18385 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
18386 : Evaluate(Result, Info, E->getSubExpr());
18387 }
18388 }
18389};
18390} // end anonymous namespace
18391
18392static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
18393 EvalInfo &Info) {
18394 assert(!E->isValueDependent());
18395 assert(E->isPRValue() && E->getType()->isAtomicType());
18396 return AtomicExprEvaluator(Info, This, Result).Visit(E);
18397}
18398
18399//===----------------------------------------------------------------------===//
18400// Void expression evaluation, primarily for a cast to void on the LHS of a
18401// comma operator
18402//===----------------------------------------------------------------------===//
18403
18404namespace {
18405class VoidExprEvaluator
18406 : public ExprEvaluatorBase<VoidExprEvaluator> {
18407public:
18408 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
18409
18410 bool Success(const APValue &V, const Expr *e) { return true; }
18411
18412 bool ZeroInitialization(const Expr *E) { return true; }
18413
18414 bool VisitCastExpr(const CastExpr *E) {
18415 switch (E->getCastKind()) {
18416 default:
18417 return ExprEvaluatorBaseTy::VisitCastExpr(E);
18418 case CK_ToVoid:
18419 VisitIgnoredValue(E->getSubExpr());
18420 return true;
18421 }
18422 }
18423
18424 bool VisitCallExpr(const CallExpr *E) {
18425 if (!IsConstantEvaluatedBuiltinCall(E))
18426 return ExprEvaluatorBaseTy::VisitCallExpr(E);
18427
18428 switch (E->getBuiltinCallee()) {
18429 case Builtin::BI__assume:
18430 case Builtin::BI__builtin_assume:
18431 // The argument is not evaluated!
18432 return true;
18433
18434 case Builtin::BI__builtin_operator_delete:
18435 return HandleOperatorDeleteCall(Info, E);
18436
18437 default:
18438 return false;
18439 }
18440 }
18441
18442 bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
18443};
18444} // end anonymous namespace
18445
18446bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
18447 // We cannot speculatively evaluate a delete expression.
18448 if (Info.SpeculativeEvaluationDepth)
18449 return false;
18450
18451 FunctionDecl *OperatorDelete = E->getOperatorDelete();
18452 if (!OperatorDelete
18453 ->isUsableAsGlobalAllocationFunctionInConstantEvaluation()) {
18454 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
18455 << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;
18456 return false;
18457 }
18458
18459 const Expr *Arg = E->getArgument();
18460
18461 LValue Pointer;
18462 if (!EvaluatePointer(Arg, Pointer, Info))
18463 return false;
18464 if (Pointer.Designator.Invalid)
18465 return false;
18466
18467 // Deleting a null pointer has no effect.
18468 if (Pointer.isNullPointer()) {
18469 // This is the only case where we need to produce an extension warning:
18470 // the only other way we can succeed is if we find a dynamic allocation,
18471 // and we will have warned when we allocated it in that case.
18472 if (!Info.getLangOpts().CPlusPlus20)
18473 Info.CCEDiag(E, diag::note_constexpr_new);
18474 return true;
18475 }
18476
18477 std::optional<DynAlloc *> Alloc = CheckDeleteKind(
18478 Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New);
18479 if (!Alloc)
18480 return false;
18481 QualType AllocType = Pointer.Base.getDynamicAllocType();
18482
18483 // For the non-array case, the designator must be empty if the static type
18484 // does not have a virtual destructor.
18485 if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 &&
18487 Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor)
18488 << Arg->getType()->getPointeeType() << AllocType;
18489 return false;
18490 }
18491
18492 // For a class type with a virtual destructor, the selected operator delete
18493 // is the one looked up when building the destructor.
18494 if (!E->isArrayForm() && !E->isGlobalDelete()) {
18495 const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType);
18496 if (VirtualDelete &&
18497 !VirtualDelete
18498 ->isUsableAsGlobalAllocationFunctionInConstantEvaluation()) {
18499 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
18500 << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete;
18501 return false;
18502 }
18503 }
18504
18505 if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(),
18506 (*Alloc)->Value, AllocType))
18507 return false;
18508
18509 if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) {
18510 // The element was already erased. This means the destructor call also
18511 // deleted the object.
18512 // FIXME: This probably results in undefined behavior before we get this
18513 // far, and should be diagnosed elsewhere first.
18514 Info.FFDiag(E, diag::note_constexpr_double_delete);
18515 return false;
18516 }
18517
18518 return true;
18519}
18520
18521static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
18522 assert(!E->isValueDependent());
18523 assert(E->isPRValue() && E->getType()->isVoidType());
18524 return VoidExprEvaluator(Info).Visit(E);
18525}
18526
18527//===----------------------------------------------------------------------===//
18528// Top level Expr::EvaluateAsRValue method.
18529//===----------------------------------------------------------------------===//
18530
18531static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
18532 assert(!E->isValueDependent());
18533 // In C, function designators are not lvalues, but we evaluate them as if they
18534 // are.
18535 QualType T = E->getType();
18536 if (E->isGLValue() || T->isFunctionType()) {
18537 LValue LV;
18538 if (!EvaluateLValue(E, LV, Info))
18539 return false;
18540 LV.moveInto(Result);
18541 } else if (T->isVectorType()) {
18542 if (!EvaluateVector(E, Result, Info))
18543 return false;
18544 } else if (T->isIntegralOrEnumerationType()) {
18545 if (!IntExprEvaluator(Info, Result).Visit(E))
18546 return false;
18547 } else if (T->hasPointerRepresentation()) {
18548 LValue LV;
18549 if (!EvaluatePointer(E, LV, Info))
18550 return false;
18551 LV.moveInto(Result);
18552 } else if (T->isRealFloatingType()) {
18553 llvm::APFloat F(0.0);
18554 if (!EvaluateFloat(E, F, Info))
18555 return false;
18556 Result = APValue(F);
18557 } else if (T->isAnyComplexType()) {
18558 ComplexValue C;
18559 if (!EvaluateComplex(E, C, Info))
18560 return false;
18561 C.moveInto(Result);
18562 } else if (T->isFixedPointType()) {
18563 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
18564 } else if (T->isMemberPointerType()) {
18565 MemberPtr P;
18566 if (!EvaluateMemberPointer(E, P, Info))
18567 return false;
18568 P.moveInto(Result);
18569 return true;
18570 } else if (T->isArrayType()) {
18571 LValue LV;
18572 APValue &Value =
18573 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
18574 if (!EvaluateArray(E, LV, Value, Info))
18575 return false;
18576 Result = Value;
18577 } else if (T->isRecordType()) {
18578 LValue LV;
18579 APValue &Value =
18580 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
18581 if (!EvaluateRecord(E, LV, Value, Info))
18582 return false;
18583 Result = Value;
18584 } else if (T->isVoidType()) {
18585 if (!Info.getLangOpts().CPlusPlus11)
18586 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
18587 << E->getType();
18588 if (!EvaluateVoid(E, Info))
18589 return false;
18590 } else if (T->isAtomicType()) {
18591 QualType Unqual = T.getAtomicUnqualifiedType();
18592 if (Unqual->isArrayType() || Unqual->isRecordType()) {
18593 LValue LV;
18594 APValue &Value = Info.CurrentCall->createTemporary(
18595 E, Unqual, ScopeKind::FullExpression, LV);
18596 if (!EvaluateAtomic(E, &LV, Value, Info))
18597 return false;
18598 Result = Value;
18599 } else {
18600 if (!EvaluateAtomic(E, nullptr, Result, Info))
18601 return false;
18602 }
18603 } else if (Info.getLangOpts().CPlusPlus11) {
18604 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
18605 return false;
18606 } else {
18607 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
18608 return false;
18609 }
18610
18611 return true;
18612}
18613
18614/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
18615/// cases, the in-place evaluation is essential, since later initializers for
18616/// an object can indirectly refer to subobjects which were initialized earlier.
18617static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
18618 const Expr *E, bool AllowNonLiteralTypes) {
18619 assert(!E->isValueDependent());
18620
18621 // Normally expressions passed to EvaluateInPlace have a type, but not when
18622 // a VarDecl initializer is evaluated before the untyped ParenListExpr is
18623 // replaced with a CXXConstructExpr. This can happen in LLDB.
18624 if (E->getType().isNull())
18625 return false;
18626
18627 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
18628 return false;
18629
18630 if (E->isPRValue()) {
18631 // Evaluate arrays and record types in-place, so that later initializers can
18632 // refer to earlier-initialized members of the object.
18633 QualType T = E->getType();
18634 if (T->isArrayType())
18635 return EvaluateArray(E, This, Result, Info);
18636 else if (T->isRecordType())
18637 return EvaluateRecord(E, This, Result, Info);
18638 else if (T->isAtomicType()) {
18639 QualType Unqual = T.getAtomicUnqualifiedType();
18640 if (Unqual->isArrayType() || Unqual->isRecordType())
18641 return EvaluateAtomic(E, &This, Result, Info);
18642 }
18643 }
18644
18645 // For any other type, in-place evaluation is unimportant.
18646 return Evaluate(Result, Info, E);
18647}
18648
18649/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
18650/// lvalue-to-rvalue cast if it is an lvalue.
18651static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
18652 assert(!E->isValueDependent());
18653
18654 if (E->getType().isNull())
18655 return false;
18656
18657 if (!CheckLiteralType(Info, E))
18658 return false;
18659
18660 if (Info.EnableNewConstInterp) {
18661 if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result))
18662 return false;
18663 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
18664 ConstantExprKind::Normal);
18665 }
18666
18667 if (!::Evaluate(Result, Info, E))
18668 return false;
18669
18670 // Implicit lvalue-to-rvalue cast.
18671 if (E->isGLValue()) {
18672 LValue LV;
18673 LV.setFrom(Info.Ctx, Result);
18674 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
18675 return false;
18676 }
18677
18678 // Check this core constant expression is a constant expression.
18679 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
18680 ConstantExprKind::Normal) &&
18681 CheckMemoryLeaks(Info);
18682}
18683
18684static bool FastEvaluateAsRValue(const Expr *Exp, APValue &Result,
18685 const ASTContext &Ctx, bool &IsConst) {
18686 // Fast-path evaluations of integer literals, since we sometimes see files
18687 // containing vast quantities of these.
18688 if (const auto *L = dyn_cast<IntegerLiteral>(Exp)) {
18689 Result =
18690 APValue(APSInt(L->getValue(), L->getType()->isUnsignedIntegerType()));
18691 IsConst = true;
18692 return true;
18693 }
18694
18695 if (const auto *L = dyn_cast<CXXBoolLiteralExpr>(Exp)) {
18696 Result = APValue(APSInt(APInt(1, L->getValue())));
18697 IsConst = true;
18698 return true;
18699 }
18700
18701 if (const auto *FL = dyn_cast<FloatingLiteral>(Exp)) {
18702 Result = APValue(FL->getValue());
18703 IsConst = true;
18704 return true;
18705 }
18706
18707 if (const auto *L = dyn_cast<CharacterLiteral>(Exp)) {
18708 Result = APValue(Ctx.MakeIntValue(L->getValue(), L->getType()));
18709 IsConst = true;
18710 return true;
18711 }
18712
18713 if (const auto *CE = dyn_cast<ConstantExpr>(Exp)) {
18714 if (CE->hasAPValueResult()) {
18715 APValue APV = CE->getAPValueResult();
18716 if (!APV.isLValue()) {
18717 Result = std::move(APV);
18718 IsConst = true;
18719 return true;
18720 }
18721 }
18722
18723 // The SubExpr is usually just an IntegerLiteral.
18724 return FastEvaluateAsRValue(CE->getSubExpr(), Result, Ctx, IsConst);
18725 }
18726
18727 // This case should be rare, but we need to check it before we check on
18728 // the type below.
18729 if (Exp->getType().isNull()) {
18730 IsConst = false;
18731 return true;
18732 }
18733
18734 return false;
18735}
18736
18739 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
18740 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
18741}
18742
18743static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
18744 const ASTContext &Ctx, EvalInfo &Info) {
18745 assert(!E->isValueDependent());
18746 bool IsConst;
18747 if (FastEvaluateAsRValue(E, Result.Val, Ctx, IsConst))
18748 return IsConst;
18749
18750 return EvaluateAsRValue(Info, E, Result.Val);
18751}
18752
18754 const ASTContext &Ctx,
18755 Expr::SideEffectsKind AllowSideEffects,
18756 EvalInfo &Info) {
18757 assert(!E->isValueDependent());
18759 return false;
18760
18761 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
18762 !ExprResult.Val.isInt() ||
18763 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
18764 return false;
18765
18766 return true;
18767}
18768
18770 const ASTContext &Ctx,
18771 Expr::SideEffectsKind AllowSideEffects,
18772 EvalInfo &Info) {
18773 assert(!E->isValueDependent());
18774 if (!E->getType()->isFixedPointType())
18775 return false;
18776
18777 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
18778 return false;
18779
18780 if (!ExprResult.Val.isFixedPoint() ||
18781 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
18782 return false;
18783
18784 return true;
18785}
18786
18787/// EvaluateAsRValue - Return true if this is a constant which we can fold using
18788/// any crazy technique (that has nothing to do with language standards) that
18789/// we want to. If this function returns true, it returns the folded constant
18790/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
18791/// will be applied to the result.
18793 bool InConstantContext) const {
18794 assert(!isValueDependent() &&
18795 "Expression evaluator can't be called on a dependent expression.");
18796 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsRValue");
18797 EvalInfo Info(Ctx, Result, EvaluationMode::IgnoreSideEffects);
18798 Info.InConstantContext = InConstantContext;
18799 return ::EvaluateAsRValue(this, Result, Ctx, Info);
18800}
18801
18803 bool InConstantContext) const {
18804 assert(!isValueDependent() &&
18805 "Expression evaluator can't be called on a dependent expression.");
18806 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsBooleanCondition");
18807 EvalResult Scratch;
18808 return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
18809 HandleConversionToBool(Scratch.Val, Result);
18810}
18811
18813 SideEffectsKind AllowSideEffects,
18814 bool InConstantContext) const {
18815 assert(!isValueDependent() &&
18816 "Expression evaluator can't be called on a dependent expression.");
18817 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsInt");
18818 EvalInfo Info(Ctx, Result, EvaluationMode::IgnoreSideEffects);
18819 Info.InConstantContext = InConstantContext;
18820 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
18821}
18822
18824 SideEffectsKind AllowSideEffects,
18825 bool InConstantContext) const {
18826 assert(!isValueDependent() &&
18827 "Expression evaluator can't be called on a dependent expression.");
18828 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFixedPoint");
18829 EvalInfo Info(Ctx, Result, EvaluationMode::IgnoreSideEffects);
18830 Info.InConstantContext = InConstantContext;
18831 return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
18832}
18833
18834bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
18835 SideEffectsKind AllowSideEffects,
18836 bool InConstantContext) const {
18837 assert(!isValueDependent() &&
18838 "Expression evaluator can't be called on a dependent expression.");
18839
18840 if (!getType()->isRealFloatingType())
18841 return false;
18842
18843 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFloat");
18845 if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
18846 !ExprResult.Val.isFloat() ||
18847 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
18848 return false;
18849
18850 Result = ExprResult.Val.getFloat();
18851 return true;
18852}
18853
18855 bool InConstantContext) const {
18856 assert(!isValueDependent() &&
18857 "Expression evaluator can't be called on a dependent expression.");
18858
18859 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsLValue");
18860 EvalInfo Info(Ctx, Result, EvaluationMode::ConstantFold);
18861 Info.InConstantContext = InConstantContext;
18862 LValue LV;
18863 CheckedTemporaries CheckedTemps;
18864
18865 if (Info.EnableNewConstInterp) {
18866 if (!Info.Ctx.getInterpContext().evaluate(Info, this, Result.Val,
18867 ConstantExprKind::Normal))
18868 return false;
18869
18870 LV.setFrom(Ctx, Result.Val);
18872 Info, getExprLoc(), Ctx.getLValueReferenceType(getType()), LV,
18873 ConstantExprKind::Normal, CheckedTemps);
18874 }
18875
18876 if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() ||
18877 Result.HasSideEffects ||
18880 ConstantExprKind::Normal, CheckedTemps))
18881 return false;
18882
18883 LV.moveInto(Result.Val);
18884 return true;
18885}
18886
18888 APValue DestroyedValue, QualType Type,
18889 SourceLocation Loc, Expr::EvalStatus &EStatus,
18890 bool IsConstantDestruction) {
18891 EvalInfo Info(Ctx, EStatus,
18892 IsConstantDestruction ? EvaluationMode::ConstantExpression
18894 Info.setEvaluatingDecl(Base, DestroyedValue,
18895 EvalInfo::EvaluatingDeclKind::Dtor);
18896 Info.InConstantContext = IsConstantDestruction;
18897
18898 LValue LVal;
18899 LVal.set(Base);
18900
18901 if (!HandleDestruction(Info, Loc, Base, DestroyedValue, Type) ||
18902 EStatus.HasSideEffects)
18903 return false;
18904
18905 if (!Info.discardCleanups())
18906 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
18907
18908 return true;
18909}
18910
18912 ConstantExprKind Kind) const {
18913 assert(!isValueDependent() &&
18914 "Expression evaluator can't be called on a dependent expression.");
18915 bool IsConst;
18916 if (FastEvaluateAsRValue(this, Result.Val, Ctx, IsConst) &&
18917 Result.Val.hasValue())
18918 return true;
18919
18920 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsConstantExpr");
18922 EvalInfo Info(Ctx, Result, EM);
18923 Info.InConstantContext = true;
18924
18925 if (Info.EnableNewConstInterp) {
18926 if (!Info.Ctx.getInterpContext().evaluate(Info, this, Result.Val, Kind))
18927 return false;
18928 return CheckConstantExpression(Info, getExprLoc(),
18929 getStorageType(Ctx, this), Result.Val, Kind);
18930 }
18931
18932 // The type of the object we're initializing is 'const T' for a class NTTP.
18933 QualType T = getType();
18934 if (Kind == ConstantExprKind::ClassTemplateArgument)
18935 T.addConst();
18936
18937 // If we're evaluating a prvalue, fake up a MaterializeTemporaryExpr to
18938 // represent the result of the evaluation. CheckConstantExpression ensures
18939 // this doesn't escape.
18940 MaterializeTemporaryExpr BaseMTE(T, const_cast<Expr*>(this), true);
18941 APValue::LValueBase Base(&BaseMTE);
18942 Info.setEvaluatingDecl(Base, Result.Val);
18943
18944 LValue LVal;
18945 LVal.set(Base);
18946 // C++23 [intro.execution]/p5
18947 // A full-expression is [...] a constant-expression
18948 // So we need to make sure temporary objects are destroyed after having
18949 // evaluating the expression (per C++23 [class.temporary]/p4).
18950 FullExpressionRAII Scope(Info);
18951 if (!::EvaluateInPlace(Result.Val, Info, LVal, this) ||
18952 Result.HasSideEffects || !Scope.destroy())
18953 return false;
18954
18955 if (!Info.discardCleanups())
18956 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
18957
18958 if (!CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this),
18959 Result.Val, Kind))
18960 return false;
18961 if (!CheckMemoryLeaks(Info))
18962 return false;
18963
18964 // If this is a class template argument, it's required to have constant
18965 // destruction too.
18966 if (Kind == ConstantExprKind::ClassTemplateArgument &&
18968 true) ||
18969 Result.HasSideEffects)) {
18970 // FIXME: Prefix a note to indicate that the problem is lack of constant
18971 // destruction.
18972 return false;
18973 }
18974
18975 return true;
18976}
18977
18979 const VarDecl *VD,
18981 bool IsConstantInitialization) const {
18982 assert(!isValueDependent() &&
18983 "Expression evaluator can't be called on a dependent expression.");
18984 assert(VD && "Need a valid VarDecl");
18985
18986 llvm::TimeTraceScope TimeScope("EvaluateAsInitializer", [&] {
18987 std::string Name;
18988 llvm::raw_string_ostream OS(Name);
18989 VD->printQualifiedName(OS);
18990 return Name;
18991 });
18992
18993 Expr::EvalStatus EStatus;
18994 EStatus.Diag = &Notes;
18995
18996 EvalInfo Info(Ctx, EStatus,
18997 (IsConstantInitialization &&
18998 (Ctx.getLangOpts().CPlusPlus || Ctx.getLangOpts().C23))
19001 Info.setEvaluatingDecl(VD, Value);
19002 Info.InConstantContext = IsConstantInitialization;
19003
19004 SourceLocation DeclLoc = VD->getLocation();
19005 QualType DeclTy = VD->getType();
19006
19007 if (Info.EnableNewConstInterp) {
19008 auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext();
19009 if (!InterpCtx.evaluateAsInitializer(Info, VD, this, Value))
19010 return false;
19011
19012 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value,
19013 ConstantExprKind::Normal);
19014 } else {
19015 LValue LVal;
19016 LVal.set(VD);
19017
19018 {
19019 // C++23 [intro.execution]/p5
19020 // A full-expression is ... an init-declarator ([dcl.decl]) or a
19021 // mem-initializer.
19022 // So we need to make sure temporary objects are destroyed after having
19023 // evaluated the expression (per C++23 [class.temporary]/p4).
19024 //
19025 // FIXME: Otherwise this may break test/Modules/pr68702.cpp because the
19026 // serialization code calls ParmVarDecl::getDefaultArg() which strips the
19027 // outermost FullExpr, such as ExprWithCleanups.
19028 FullExpressionRAII Scope(Info);
19029 if (!EvaluateInPlace(Value, Info, LVal, this,
19030 /*AllowNonLiteralTypes=*/true) ||
19031 EStatus.HasSideEffects)
19032 return false;
19033 }
19034
19035 // At this point, any lifetime-extended temporaries are completely
19036 // initialized.
19037 Info.performLifetimeExtension();
19038
19039 if (!Info.discardCleanups())
19040 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
19041 }
19042
19043 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value,
19044 ConstantExprKind::Normal) &&
19045 CheckMemoryLeaks(Info);
19046}
19047
19050 Expr::EvalStatus EStatus;
19051 EStatus.Diag = &Notes;
19052
19053 // Only treat the destruction as constant destruction if we formally have
19054 // constant initialization (or are usable in a constant expression).
19055 bool IsConstantDestruction = hasConstantInitialization();
19056
19057 // Make a copy of the value for the destructor to mutate, if we know it.
19058 // Otherwise, treat the value as default-initialized; if the destructor works
19059 // anyway, then the destruction is constant (and must be essentially empty).
19060 APValue DestroyedValue;
19061 if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent())
19062 DestroyedValue = *getEvaluatedValue();
19063 else if (!handleDefaultInitValue(getType(), DestroyedValue))
19064 return false;
19065
19066 if (!EvaluateDestruction(getASTContext(), this, std::move(DestroyedValue),
19067 getType(), getLocation(), EStatus,
19068 IsConstantDestruction) ||
19069 EStatus.HasSideEffects)
19070 return false;
19071
19072 ensureEvaluatedStmt()->HasConstantDestruction = true;
19073 return true;
19074}
19075
19076/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
19077/// constant folded, but discard the result.
19079 assert(!isValueDependent() &&
19080 "Expression evaluator can't be called on a dependent expression.");
19081
19083 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
19085}
19086
19087APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
19088 assert(!isValueDependent() &&
19089 "Expression evaluator can't be called on a dependent expression.");
19090
19091 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstInt");
19092 EvalResult EVResult;
19093 EvalInfo Info(Ctx, EVResult, EvaluationMode::IgnoreSideEffects);
19094 Info.InConstantContext = true;
19095
19096 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
19097 (void)Result;
19098 assert(Result && "Could not evaluate expression");
19099 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
19100
19101 return EVResult.Val.getInt();
19102}
19103
19106 assert(!isValueDependent() &&
19107 "Expression evaluator can't be called on a dependent expression.");
19108
19109 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstIntCheckOverflow");
19110 EvalResult EVResult;
19111 EVResult.Diag = Diag;
19112 EvalInfo Info(Ctx, EVResult, EvaluationMode::IgnoreSideEffects);
19113 Info.InConstantContext = true;
19114 Info.CheckingForUndefinedBehavior = true;
19115
19116 bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
19117 (void)Result;
19118 assert(Result && "Could not evaluate expression");
19119 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
19120
19121 return EVResult.Val.getInt();
19122}
19123
19125 assert(!isValueDependent() &&
19126 "Expression evaluator can't be called on a dependent expression.");
19127
19128 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateForOverflow");
19129 bool IsConst;
19130 EvalResult EVResult;
19131 if (!FastEvaluateAsRValue(this, EVResult.Val, Ctx, IsConst)) {
19132 EvalInfo Info(Ctx, EVResult, EvaluationMode::IgnoreSideEffects);
19133 Info.CheckingForUndefinedBehavior = true;
19134 (void)::EvaluateAsRValue(Info, this, EVResult.Val);
19135 }
19136}
19137
19139 assert(Val.isLValue());
19140 return IsGlobalLValue(Val.getLValueBase());
19141}
19142
19143/// isIntegerConstantExpr - this recursive routine will test if an expression is
19144/// an integer constant expression.
19145
19146/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
19147/// comma, etc
19148
19149// CheckICE - This function does the fundamental ICE checking: the returned
19150// ICEDiag contains an ICEKind indicating whether the expression is an ICE.
19151//
19152// Note that to reduce code duplication, this helper does no evaluation
19153// itself; the caller checks whether the expression is evaluatable, and
19154// in the rare cases where CheckICE actually cares about the evaluated
19155// value, it calls into Evaluate.
19156
19157namespace {
19158
19159enum ICEKind {
19160 /// This expression is an ICE.
19161 IK_ICE,
19162 /// This expression is not an ICE, but if it isn't evaluated, it's
19163 /// a legal subexpression for an ICE. This return value is used to handle
19164 /// the comma operator in C99 mode, and non-constant subexpressions.
19165 IK_ICEIfUnevaluated,
19166 /// This expression is not an ICE, and is not a legal subexpression for one.
19167 IK_NotICE
19168};
19169
19170struct ICEDiag {
19171 ICEKind Kind;
19172 SourceLocation Loc;
19173
19174 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
19175};
19176
19177}
19178
19179static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
19180
19181static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
19182
19183static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
19184 Expr::EvalResult EVResult;
19185 Expr::EvalStatus Status;
19186 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantExpression);
19187
19188 Info.InConstantContext = true;
19189 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
19190 !EVResult.Val.isInt())
19191 return ICEDiag(IK_NotICE, E->getBeginLoc());
19192
19193 return NoDiag();
19194}
19195
19196static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
19197 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
19199 return ICEDiag(IK_NotICE, E->getBeginLoc());
19200
19201 switch (E->getStmtClass()) {
19202#define ABSTRACT_STMT(Node)
19203#define STMT(Node, Base) case Expr::Node##Class:
19204#define EXPR(Node, Base)
19205#include "clang/AST/StmtNodes.inc"
19206 case Expr::PredefinedExprClass:
19207 case Expr::FloatingLiteralClass:
19208 case Expr::ImaginaryLiteralClass:
19209 case Expr::StringLiteralClass:
19210 case Expr::ArraySubscriptExprClass:
19211 case Expr::MatrixSubscriptExprClass:
19212 case Expr::ArraySectionExprClass:
19213 case Expr::OMPArrayShapingExprClass:
19214 case Expr::OMPIteratorExprClass:
19215 case Expr::MemberExprClass:
19216 case Expr::CompoundAssignOperatorClass:
19217 case Expr::CompoundLiteralExprClass:
19218 case Expr::ExtVectorElementExprClass:
19219 case Expr::DesignatedInitExprClass:
19220 case Expr::ArrayInitLoopExprClass:
19221 case Expr::ArrayInitIndexExprClass:
19222 case Expr::NoInitExprClass:
19223 case Expr::DesignatedInitUpdateExprClass:
19224 case Expr::ImplicitValueInitExprClass:
19225 case Expr::ParenListExprClass:
19226 case Expr::VAArgExprClass:
19227 case Expr::AddrLabelExprClass:
19228 case Expr::StmtExprClass:
19229 case Expr::CXXMemberCallExprClass:
19230 case Expr::CUDAKernelCallExprClass:
19231 case Expr::CXXAddrspaceCastExprClass:
19232 case Expr::CXXDynamicCastExprClass:
19233 case Expr::CXXTypeidExprClass:
19234 case Expr::CXXUuidofExprClass:
19235 case Expr::MSPropertyRefExprClass:
19236 case Expr::MSPropertySubscriptExprClass:
19237 case Expr::CXXNullPtrLiteralExprClass:
19238 case Expr::UserDefinedLiteralClass:
19239 case Expr::CXXThisExprClass:
19240 case Expr::CXXThrowExprClass:
19241 case Expr::CXXNewExprClass:
19242 case Expr::CXXDeleteExprClass:
19243 case Expr::CXXPseudoDestructorExprClass:
19244 case Expr::UnresolvedLookupExprClass:
19245 case Expr::RecoveryExprClass:
19246 case Expr::DependentScopeDeclRefExprClass:
19247 case Expr::CXXConstructExprClass:
19248 case Expr::CXXInheritedCtorInitExprClass:
19249 case Expr::CXXStdInitializerListExprClass:
19250 case Expr::CXXBindTemporaryExprClass:
19251 case Expr::ExprWithCleanupsClass:
19252 case Expr::CXXTemporaryObjectExprClass:
19253 case Expr::CXXUnresolvedConstructExprClass:
19254 case Expr::CXXDependentScopeMemberExprClass:
19255 case Expr::UnresolvedMemberExprClass:
19256 case Expr::ObjCStringLiteralClass:
19257 case Expr::ObjCBoxedExprClass:
19258 case Expr::ObjCArrayLiteralClass:
19259 case Expr::ObjCDictionaryLiteralClass:
19260 case Expr::ObjCEncodeExprClass:
19261 case Expr::ObjCMessageExprClass:
19262 case Expr::ObjCSelectorExprClass:
19263 case Expr::ObjCProtocolExprClass:
19264 case Expr::ObjCIvarRefExprClass:
19265 case Expr::ObjCPropertyRefExprClass:
19266 case Expr::ObjCSubscriptRefExprClass:
19267 case Expr::ObjCIsaExprClass:
19268 case Expr::ObjCAvailabilityCheckExprClass:
19269 case Expr::ShuffleVectorExprClass:
19270 case Expr::ConvertVectorExprClass:
19271 case Expr::BlockExprClass:
19272 case Expr::NoStmtClass:
19273 case Expr::OpaqueValueExprClass:
19274 case Expr::PackExpansionExprClass:
19275 case Expr::SubstNonTypeTemplateParmPackExprClass:
19276 case Expr::FunctionParmPackExprClass:
19277 case Expr::AsTypeExprClass:
19278 case Expr::ObjCIndirectCopyRestoreExprClass:
19279 case Expr::MaterializeTemporaryExprClass:
19280 case Expr::PseudoObjectExprClass:
19281 case Expr::AtomicExprClass:
19282 case Expr::LambdaExprClass:
19283 case Expr::CXXFoldExprClass:
19284 case Expr::CoawaitExprClass:
19285 case Expr::DependentCoawaitExprClass:
19286 case Expr::CoyieldExprClass:
19287 case Expr::SYCLUniqueStableNameExprClass:
19288 case Expr::CXXParenListInitExprClass:
19289 case Expr::HLSLOutArgExprClass:
19290 return ICEDiag(IK_NotICE, E->getBeginLoc());
19291
19292 case Expr::InitListExprClass: {
19293 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
19294 // form "T x = { a };" is equivalent to "T x = a;".
19295 // Unless we're initializing a reference, T is a scalar as it is known to be
19296 // of integral or enumeration type.
19297 if (E->isPRValue())
19298 if (cast<InitListExpr>(E)->getNumInits() == 1)
19299 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
19300 return ICEDiag(IK_NotICE, E->getBeginLoc());
19301 }
19302
19303 case Expr::SizeOfPackExprClass:
19304 case Expr::GNUNullExprClass:
19305 case Expr::SourceLocExprClass:
19306 case Expr::EmbedExprClass:
19307 case Expr::OpenACCAsteriskSizeExprClass:
19308 return NoDiag();
19309
19310 case Expr::PackIndexingExprClass:
19311 return CheckICE(cast<PackIndexingExpr>(E)->getSelectedExpr(), Ctx);
19312
19313 case Expr::SubstNonTypeTemplateParmExprClass:
19314 return
19315 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
19316
19317 case Expr::ConstantExprClass:
19318 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
19319
19320 case Expr::ParenExprClass:
19321 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
19322 case Expr::GenericSelectionExprClass:
19323 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
19324 case Expr::IntegerLiteralClass:
19325 case Expr::FixedPointLiteralClass:
19326 case Expr::CharacterLiteralClass:
19327 case Expr::ObjCBoolLiteralExprClass:
19328 case Expr::CXXBoolLiteralExprClass:
19329 case Expr::CXXScalarValueInitExprClass:
19330 case Expr::TypeTraitExprClass:
19331 case Expr::ConceptSpecializationExprClass:
19332 case Expr::RequiresExprClass:
19333 case Expr::ArrayTypeTraitExprClass:
19334 case Expr::ExpressionTraitExprClass:
19335 case Expr::CXXNoexceptExprClass:
19336 return NoDiag();
19337 case Expr::CallExprClass:
19338 case Expr::CXXOperatorCallExprClass: {
19339 // C99 6.6/3 allows function calls within unevaluated subexpressions of
19340 // constant expressions, but they can never be ICEs because an ICE cannot
19341 // contain an operand of (pointer to) function type.
19342 const CallExpr *CE = cast<CallExpr>(E);
19343 if (CE->getBuiltinCallee())
19344 return CheckEvalInICE(E, Ctx);
19345 return ICEDiag(IK_NotICE, E->getBeginLoc());
19346 }
19347 case Expr::CXXRewrittenBinaryOperatorClass:
19348 return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(),
19349 Ctx);
19350 case Expr::DeclRefExprClass: {
19351 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
19352 if (isa<EnumConstantDecl>(D))
19353 return NoDiag();
19354
19355 // C++ and OpenCL (FIXME: spec reference?) allow reading const-qualified
19356 // integer variables in constant expressions:
19357 //
19358 // C++ 7.1.5.1p2
19359 // A variable of non-volatile const-qualified integral or enumeration
19360 // type initialized by an ICE can be used in ICEs.
19361 //
19362 // We sometimes use CheckICE to check the C++98 rules in C++11 mode. In
19363 // that mode, use of reference variables should not be allowed.
19364 const VarDecl *VD = dyn_cast<VarDecl>(D);
19365 if (VD && VD->isUsableInConstantExpressions(Ctx) &&
19366 !VD->getType()->isReferenceType())
19367 return NoDiag();
19368
19369 return ICEDiag(IK_NotICE, E->getBeginLoc());
19370 }
19371 case Expr::UnaryOperatorClass: {
19372 const UnaryOperator *Exp = cast<UnaryOperator>(E);
19373 switch (Exp->getOpcode()) {
19374 case UO_PostInc:
19375 case UO_PostDec:
19376 case UO_PreInc:
19377 case UO_PreDec:
19378 case UO_AddrOf:
19379 case UO_Deref:
19380 case UO_Coawait:
19381 // C99 6.6/3 allows increment and decrement within unevaluated
19382 // subexpressions of constant expressions, but they can never be ICEs
19383 // because an ICE cannot contain an lvalue operand.
19384 return ICEDiag(IK_NotICE, E->getBeginLoc());
19385 case UO_Extension:
19386 case UO_LNot:
19387 case UO_Plus:
19388 case UO_Minus:
19389 case UO_Not:
19390 case UO_Real:
19391 case UO_Imag:
19392 return CheckICE(Exp->getSubExpr(), Ctx);
19393 }
19394 llvm_unreachable("invalid unary operator class");
19395 }
19396 case Expr::OffsetOfExprClass: {
19397 // Note that per C99, offsetof must be an ICE. And AFAIK, using
19398 // EvaluateAsRValue matches the proposed gcc behavior for cases like
19399 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
19400 // compliance: we should warn earlier for offsetof expressions with
19401 // array subscripts that aren't ICEs, and if the array subscripts
19402 // are ICEs, the value of the offsetof must be an integer constant.
19403 return CheckEvalInICE(E, Ctx);
19404 }
19405 case Expr::UnaryExprOrTypeTraitExprClass: {
19407 if ((Exp->getKind() == UETT_SizeOf) &&
19409 return ICEDiag(IK_NotICE, E->getBeginLoc());
19410 if (Exp->getKind() == UETT_CountOf) {
19411 QualType ArgTy = Exp->getTypeOfArgument();
19412 if (ArgTy->isVariableArrayType()) {
19413 // We need to look whether the array is multidimensional. If it is,
19414 // then we want to check the size expression manually to see whether
19415 // it is an ICE or not.
19416 const auto *VAT = Ctx.getAsVariableArrayType(ArgTy);
19417 if (VAT->getElementType()->isArrayType())
19418 // Variable array size expression could be missing (e.g. int a[*][10])
19419 // In that case, it can't be a constant expression.
19420 return VAT->getSizeExpr() ? CheckICE(VAT->getSizeExpr(), Ctx)
19421 : ICEDiag(IK_NotICE, E->getBeginLoc());
19422
19423 // Otherwise, this is a regular VLA, which is definitely not an ICE.
19424 return ICEDiag(IK_NotICE, E->getBeginLoc());
19425 }
19426 }
19427 return NoDiag();
19428 }
19429 case Expr::BinaryOperatorClass: {
19430 const BinaryOperator *Exp = cast<BinaryOperator>(E);
19431 switch (Exp->getOpcode()) {
19432 case BO_PtrMemD:
19433 case BO_PtrMemI:
19434 case BO_Assign:
19435 case BO_MulAssign:
19436 case BO_DivAssign:
19437 case BO_RemAssign:
19438 case BO_AddAssign:
19439 case BO_SubAssign:
19440 case BO_ShlAssign:
19441 case BO_ShrAssign:
19442 case BO_AndAssign:
19443 case BO_XorAssign:
19444 case BO_OrAssign:
19445 // C99 6.6/3 allows assignments within unevaluated subexpressions of
19446 // constant expressions, but they can never be ICEs because an ICE cannot
19447 // contain an lvalue operand.
19448 return ICEDiag(IK_NotICE, E->getBeginLoc());
19449
19450 case BO_Mul:
19451 case BO_Div:
19452 case BO_Rem:
19453 case BO_Add:
19454 case BO_Sub:
19455 case BO_Shl:
19456 case BO_Shr:
19457 case BO_LT:
19458 case BO_GT:
19459 case BO_LE:
19460 case BO_GE:
19461 case BO_EQ:
19462 case BO_NE:
19463 case BO_And:
19464 case BO_Xor:
19465 case BO_Or:
19466 case BO_Comma:
19467 case BO_Cmp: {
19468 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
19469 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
19470 if (Exp->getOpcode() == BO_Div ||
19471 Exp->getOpcode() == BO_Rem) {
19472 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
19473 // we don't evaluate one.
19474 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
19475 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
19476 if (REval == 0)
19477 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
19478 if (REval.isSigned() && REval.isAllOnes()) {
19479 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
19480 if (LEval.isMinSignedValue())
19481 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
19482 }
19483 }
19484 }
19485 if (Exp->getOpcode() == BO_Comma) {
19486 if (Ctx.getLangOpts().C99) {
19487 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
19488 // if it isn't evaluated.
19489 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
19490 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
19491 } else {
19492 // In both C89 and C++, commas in ICEs are illegal.
19493 return ICEDiag(IK_NotICE, E->getBeginLoc());
19494 }
19495 }
19496 return Worst(LHSResult, RHSResult);
19497 }
19498 case BO_LAnd:
19499 case BO_LOr: {
19500 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
19501 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
19502 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
19503 // Rare case where the RHS has a comma "side-effect"; we need
19504 // to actually check the condition to see whether the side
19505 // with the comma is evaluated.
19506 if ((Exp->getOpcode() == BO_LAnd) !=
19507 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
19508 return RHSResult;
19509 return NoDiag();
19510 }
19511
19512 return Worst(LHSResult, RHSResult);
19513 }
19514 }
19515 llvm_unreachable("invalid binary operator kind");
19516 }
19517 case Expr::ImplicitCastExprClass:
19518 case Expr::CStyleCastExprClass:
19519 case Expr::CXXFunctionalCastExprClass:
19520 case Expr::CXXStaticCastExprClass:
19521 case Expr::CXXReinterpretCastExprClass:
19522 case Expr::CXXConstCastExprClass:
19523 case Expr::ObjCBridgedCastExprClass: {
19524 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
19525 if (isa<ExplicitCastExpr>(E)) {
19526 if (const FloatingLiteral *FL
19527 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
19528 unsigned DestWidth = Ctx.getIntWidth(E->getType());
19529 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
19530 APSInt IgnoredVal(DestWidth, !DestSigned);
19531 bool Ignored;
19532 // If the value does not fit in the destination type, the behavior is
19533 // undefined, so we are not required to treat it as a constant
19534 // expression.
19535 if (FL->getValue().convertToInteger(IgnoredVal,
19536 llvm::APFloat::rmTowardZero,
19537 &Ignored) & APFloat::opInvalidOp)
19538 return ICEDiag(IK_NotICE, E->getBeginLoc());
19539 return NoDiag();
19540 }
19541 }
19542 switch (cast<CastExpr>(E)->getCastKind()) {
19543 case CK_LValueToRValue:
19544 case CK_AtomicToNonAtomic:
19545 case CK_NonAtomicToAtomic:
19546 case CK_NoOp:
19547 case CK_IntegralToBoolean:
19548 case CK_IntegralCast:
19549 return CheckICE(SubExpr, Ctx);
19550 default:
19551 return ICEDiag(IK_NotICE, E->getBeginLoc());
19552 }
19553 }
19554 case Expr::BinaryConditionalOperatorClass: {
19556 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
19557 if (CommonResult.Kind == IK_NotICE) return CommonResult;
19558 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
19559 if (FalseResult.Kind == IK_NotICE) return FalseResult;
19560 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
19561 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
19562 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
19563 return FalseResult;
19564 }
19565 case Expr::ConditionalOperatorClass: {
19567 // If the condition (ignoring parens) is a __builtin_constant_p call,
19568 // then only the true side is actually considered in an integer constant
19569 // expression, and it is fully evaluated. This is an important GNU
19570 // extension. See GCC PR38377 for discussion.
19571 if (const CallExpr *CallCE
19572 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
19573 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
19574 return CheckEvalInICE(E, Ctx);
19575 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
19576 if (CondResult.Kind == IK_NotICE)
19577 return CondResult;
19578
19579 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
19580 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
19581
19582 if (TrueResult.Kind == IK_NotICE)
19583 return TrueResult;
19584 if (FalseResult.Kind == IK_NotICE)
19585 return FalseResult;
19586 if (CondResult.Kind == IK_ICEIfUnevaluated)
19587 return CondResult;
19588 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
19589 return NoDiag();
19590 // Rare case where the diagnostics depend on which side is evaluated
19591 // Note that if we get here, CondResult is 0, and at least one of
19592 // TrueResult and FalseResult is non-zero.
19593 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
19594 return FalseResult;
19595 return TrueResult;
19596 }
19597 case Expr::CXXDefaultArgExprClass:
19598 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
19599 case Expr::CXXDefaultInitExprClass:
19600 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
19601 case Expr::ChooseExprClass: {
19602 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
19603 }
19604 case Expr::BuiltinBitCastExprClass: {
19605 if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
19606 return ICEDiag(IK_NotICE, E->getBeginLoc());
19607 return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
19608 }
19609 }
19610
19611 llvm_unreachable("Invalid StmtClass!");
19612}
19613
19614/// Evaluate an expression as a C++11 integral constant expression.
19616 const Expr *E,
19617 llvm::APSInt *Value) {
19619 return false;
19620
19621 APValue Result;
19622 if (!E->isCXX11ConstantExpr(Ctx, &Result))
19623 return false;
19624
19625 if (!Result.isInt())
19626 return false;
19627
19628 if (Value) *Value = Result.getInt();
19629 return true;
19630}
19631
19633 assert(!isValueDependent() &&
19634 "Expression evaluator can't be called on a dependent expression.");
19635
19636 ExprTimeTraceScope TimeScope(this, Ctx, "isIntegerConstantExpr");
19637
19638 if (Ctx.getLangOpts().CPlusPlus11)
19639 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr);
19640
19641 ICEDiag D = CheckICE(this, Ctx);
19642 if (D.Kind != IK_ICE)
19643 return false;
19644 return true;
19645}
19646
19647std::optional<llvm::APSInt>
19649 if (isValueDependent()) {
19650 // Expression evaluator can't succeed on a dependent expression.
19651 return std::nullopt;
19652 }
19653
19654 if (Ctx.getLangOpts().CPlusPlus11) {
19655 APSInt Value;
19657 return Value;
19658 return std::nullopt;
19659 }
19660
19661 if (!isIntegerConstantExpr(Ctx))
19662 return std::nullopt;
19663
19664 // The only possible side-effects here are due to UB discovered in the
19665 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
19666 // required to treat the expression as an ICE, so we produce the folded
19667 // value.
19669 Expr::EvalStatus Status;
19670 EvalInfo Info(Ctx, Status, EvaluationMode::IgnoreSideEffects);
19671 Info.InConstantContext = true;
19672
19673 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
19674 llvm_unreachable("ICE cannot be evaluated!");
19675
19676 return ExprResult.Val.getInt();
19677}
19678
19680 assert(!isValueDependent() &&
19681 "Expression evaluator can't be called on a dependent expression.");
19682
19683 return CheckICE(this, Ctx).Kind == IK_ICE;
19684}
19685
19687 assert(!isValueDependent() &&
19688 "Expression evaluator can't be called on a dependent expression.");
19689
19690 // We support this checking in C++98 mode in order to diagnose compatibility
19691 // issues.
19692 assert(Ctx.getLangOpts().CPlusPlus);
19693
19694 bool IsConst;
19695 APValue Scratch;
19696 if (FastEvaluateAsRValue(this, Scratch, Ctx, IsConst) && Scratch.hasValue()) {
19697 if (Result)
19698 *Result = Scratch;
19699 return true;
19700 }
19701
19702 // Build evaluation settings.
19703 Expr::EvalStatus Status;
19705 Status.Diag = &Diags;
19706 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantExpression);
19707
19708 bool IsConstExpr =
19709 ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) &&
19710 // FIXME: We don't produce a diagnostic for this, but the callers that
19711 // call us on arbitrary full-expressions should generally not care.
19712 Info.discardCleanups() && !Status.HasSideEffects;
19713
19714 return IsConstExpr && Diags.empty();
19715}
19716
19718 const FunctionDecl *Callee,
19720 const Expr *This) const {
19721 assert(!isValueDependent() &&
19722 "Expression evaluator can't be called on a dependent expression.");
19723
19724 llvm::TimeTraceScope TimeScope("EvaluateWithSubstitution", [&] {
19725 std::string Name;
19726 llvm::raw_string_ostream OS(Name);
19727 Callee->getNameForDiagnostic(OS, Ctx.getPrintingPolicy(),
19728 /*Qualified=*/true);
19729 return Name;
19730 });
19731
19732 Expr::EvalStatus Status;
19733 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantExpressionUnevaluated);
19734 Info.InConstantContext = true;
19735
19736 LValue ThisVal;
19737 const LValue *ThisPtr = nullptr;
19738 if (This) {
19739#ifndef NDEBUG
19740 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
19741 assert(MD && "Don't provide `this` for non-methods.");
19742 assert(MD->isImplicitObjectMemberFunction() &&
19743 "Don't provide `this` for methods without an implicit object.");
19744#endif
19745 if (!This->isValueDependent() &&
19746 EvaluateObjectArgument(Info, This, ThisVal) &&
19747 !Info.EvalStatus.HasSideEffects)
19748 ThisPtr = &ThisVal;
19749
19750 // Ignore any side-effects from a failed evaluation. This is safe because
19751 // they can't interfere with any other argument evaluation.
19752 Info.EvalStatus.HasSideEffects = false;
19753 }
19754
19755 CallRef Call = Info.CurrentCall->createCall(Callee);
19756 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
19757 I != E; ++I) {
19758 unsigned Idx = I - Args.begin();
19759 if (Idx >= Callee->getNumParams())
19760 break;
19761 const ParmVarDecl *PVD = Callee->getParamDecl(Idx);
19762 if ((*I)->isValueDependent() ||
19763 !EvaluateCallArg(PVD, *I, Call, Info) ||
19764 Info.EvalStatus.HasSideEffects) {
19765 // If evaluation fails, throw away the argument entirely.
19766 if (APValue *Slot = Info.getParamSlot(Call, PVD))
19767 *Slot = APValue();
19768 }
19769
19770 // Ignore any side-effects from a failed evaluation. This is safe because
19771 // they can't interfere with any other argument evaluation.
19772 Info.EvalStatus.HasSideEffects = false;
19773 }
19774
19775 // Parameter cleanups happen in the caller and are not part of this
19776 // evaluation.
19777 Info.discardCleanups();
19778 Info.EvalStatus.HasSideEffects = false;
19779
19780 // Build fake call to Callee.
19781 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, This,
19782 Call);
19783 // FIXME: Missing ExprWithCleanups in enable_if conditions?
19784 FullExpressionRAII Scope(Info);
19785 return Evaluate(Value, Info, this) && Scope.destroy() &&
19786 !Info.EvalStatus.HasSideEffects;
19787}
19788
19791 PartialDiagnosticAt> &Diags) {
19792 // FIXME: It would be useful to check constexpr function templates, but at the
19793 // moment the constant expression evaluator cannot cope with the non-rigorous
19794 // ASTs which we build for dependent expressions.
19795 if (FD->isDependentContext())
19796 return true;
19797
19798 llvm::TimeTraceScope TimeScope("isPotentialConstantExpr", [&] {
19799 std::string Name;
19800 llvm::raw_string_ostream OS(Name);
19802 /*Qualified=*/true);
19803 return Name;
19804 });
19805
19806 Expr::EvalStatus Status;
19807 Status.Diag = &Diags;
19808
19809 EvalInfo Info(FD->getASTContext(), Status,
19811 Info.InConstantContext = true;
19812 Info.CheckingPotentialConstantExpression = true;
19813
19814 // The constexpr VM attempts to compile all methods to bytecode here.
19815 if (Info.EnableNewConstInterp) {
19816 Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD);
19817 return Diags.empty();
19818 }
19819
19820 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
19821 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
19822
19823 // Fabricate an arbitrary expression on the stack and pretend that it
19824 // is a temporary being used as the 'this' pointer.
19825 LValue This;
19826 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getCanonicalTagType(RD)
19827 : Info.Ctx.IntTy);
19828 This.set({&VIE, Info.CurrentCall->Index});
19829
19831
19832 APValue Scratch;
19833 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
19834 // Evaluate the call as a constant initializer, to allow the construction
19835 // of objects of non-literal types.
19836 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
19837 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
19838 } else {
19839 SourceLocation Loc = FD->getLocation();
19841 Loc, FD, (MD && MD->isImplicitObjectMemberFunction()) ? &This : nullptr,
19842 &VIE, Args, CallRef(), FD->getBody(), Info, Scratch,
19843 /*ResultSlot=*/nullptr);
19844 }
19845
19846 return Diags.empty();
19847}
19848
19850 const FunctionDecl *FD,
19852 PartialDiagnosticAt> &Diags) {
19853 assert(!E->isValueDependent() &&
19854 "Expression evaluator can't be called on a dependent expression.");
19855
19856 Expr::EvalStatus Status;
19857 Status.Diag = &Diags;
19858
19859 EvalInfo Info(FD->getASTContext(), Status,
19861 Info.InConstantContext = true;
19862 Info.CheckingPotentialConstantExpression = true;
19863
19864 if (Info.EnableNewConstInterp) {
19866 return Diags.empty();
19867 }
19868
19869 // Fabricate a call stack frame to give the arguments a plausible cover story.
19870 CallStackFrame Frame(Info, SourceLocation(), FD, /*This=*/nullptr,
19871 /*CallExpr=*/nullptr, CallRef());
19872
19873 APValue ResultScratch;
19874 Evaluate(ResultScratch, Info, E);
19875 return Diags.empty();
19876}
19877
19879 unsigned Type) const {
19880 if (!getType()->isPointerType())
19881 return false;
19882
19883 Expr::EvalStatus Status;
19884 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantFold);
19885 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
19886}
19887
19888static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,
19889 EvalInfo &Info, std::string *StringResult) {
19890 if (!E->getType()->hasPointerRepresentation() || !E->isPRValue())
19891 return false;
19892
19893 LValue String;
19894
19895 if (!EvaluatePointer(E, String, Info))
19896 return false;
19897
19898 QualType CharTy = E->getType()->getPointeeType();
19899
19900 // Fast path: if it's a string literal, search the string value.
19901 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
19902 String.getLValueBase().dyn_cast<const Expr *>())) {
19903 StringRef Str = S->getBytes();
19904 int64_t Off = String.Offset.getQuantity();
19905 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
19906 S->getCharByteWidth() == 1 &&
19907 // FIXME: Add fast-path for wchar_t too.
19908 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
19909 Str = Str.substr(Off);
19910
19911 StringRef::size_type Pos = Str.find(0);
19912 if (Pos != StringRef::npos)
19913 Str = Str.substr(0, Pos);
19914
19915 Result = Str.size();
19916 if (StringResult)
19917 *StringResult = Str;
19918 return true;
19919 }
19920
19921 // Fall through to slow path.
19922 }
19923
19924 // Slow path: scan the bytes of the string looking for the terminating 0.
19925 for (uint64_t Strlen = 0; /**/; ++Strlen) {
19926 APValue Char;
19927 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
19928 !Char.isInt())
19929 return false;
19930 if (!Char.getInt()) {
19931 Result = Strlen;
19932 return true;
19933 } else if (StringResult)
19934 StringResult->push_back(Char.getInt().getExtValue());
19935 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
19936 return false;
19937 }
19938}
19939
19940std::optional<std::string> Expr::tryEvaluateString(ASTContext &Ctx) const {
19941 Expr::EvalStatus Status;
19942 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantFold);
19943 uint64_t Result;
19944 std::string StringResult;
19945
19946 if (Info.EnableNewConstInterp) {
19947 if (!Info.Ctx.getInterpContext().evaluateString(Info, this, StringResult))
19948 return std::nullopt;
19949 return StringResult;
19950 }
19951
19952 if (EvaluateBuiltinStrLen(this, Result, Info, &StringResult))
19953 return StringResult;
19954 return std::nullopt;
19955}
19956
19957template <typename T>
19958static bool EvaluateCharRangeAsStringImpl(const Expr *, T &Result,
19959 const Expr *SizeExpression,
19960 const Expr *PtrExpression,
19961 ASTContext &Ctx,
19962 Expr::EvalResult &Status) {
19963 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantExpression);
19964 Info.InConstantContext = true;
19965
19966 if (Info.EnableNewConstInterp)
19967 return Info.Ctx.getInterpContext().evaluateCharRange(Info, SizeExpression,
19968 PtrExpression, Result);
19969
19970 LValue String;
19971 FullExpressionRAII Scope(Info);
19972 APSInt SizeValue;
19973 if (!::EvaluateInteger(SizeExpression, SizeValue, Info))
19974 return false;
19975
19976 uint64_t Size = SizeValue.getZExtValue();
19977
19978 // FIXME: better protect against invalid or excessive sizes
19979 if constexpr (std::is_same_v<APValue, T>)
19980 Result = APValue(APValue::UninitArray{}, Size, Size);
19981 else {
19982 if (Size < Result.max_size())
19983 Result.reserve(Size);
19984 }
19985 if (!::EvaluatePointer(PtrExpression, String, Info))
19986 return false;
19987
19988 QualType CharTy = PtrExpression->getType()->getPointeeType();
19989 for (uint64_t I = 0; I < Size; ++I) {
19990 APValue Char;
19991 if (!handleLValueToRValueConversion(Info, PtrExpression, CharTy, String,
19992 Char))
19993 return false;
19994
19995 if constexpr (std::is_same_v<APValue, T>) {
19996 Result.getArrayInitializedElt(I) = std::move(Char);
19997 } else {
19998 APSInt C = Char.getInt();
19999
20000 assert(C.getBitWidth() <= 8 &&
20001 "string element not representable in char");
20002
20003 Result.push_back(static_cast<char>(C.getExtValue()));
20004 }
20005
20006 if (!HandleLValueArrayAdjustment(Info, PtrExpression, String, CharTy, 1))
20007 return false;
20008 }
20009
20010 return Scope.destroy() && CheckMemoryLeaks(Info);
20011}
20012
20014 const Expr *SizeExpression,
20015 const Expr *PtrExpression, ASTContext &Ctx,
20016 EvalResult &Status) const {
20017 return EvaluateCharRangeAsStringImpl(this, Result, SizeExpression,
20018 PtrExpression, Ctx, Status);
20019}
20020
20022 const Expr *SizeExpression,
20023 const Expr *PtrExpression, ASTContext &Ctx,
20024 EvalResult &Status) const {
20025 return EvaluateCharRangeAsStringImpl(this, Result, SizeExpression,
20026 PtrExpression, Ctx, Status);
20027}
20028
20029bool Expr::tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const {
20030 Expr::EvalStatus Status;
20031 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantFold);
20032
20033 if (Info.EnableNewConstInterp)
20034 return Info.Ctx.getInterpContext().evaluateStrlen(Info, this, Result);
20035
20036 return EvaluateBuiltinStrLen(this, Result, Info);
20037}
20038
20039namespace {
20040struct IsWithinLifetimeHandler {
20041 EvalInfo &Info;
20042 static constexpr AccessKinds AccessKind = AccessKinds::AK_IsWithinLifetime;
20043 using result_type = std::optional<bool>;
20044 std::optional<bool> failed() { return std::nullopt; }
20045 template <typename T>
20046 std::optional<bool> found(T &Subobj, QualType SubobjType) {
20047 return true;
20048 }
20049};
20050
20051std::optional<bool> EvaluateBuiltinIsWithinLifetime(IntExprEvaluator &IEE,
20052 const CallExpr *E) {
20053 EvalInfo &Info = IEE.Info;
20054 // Sometimes this is called during some sorts of constant folding / early
20055 // evaluation. These are meant for non-constant expressions and are not
20056 // necessary since this consteval builtin will never be evaluated at runtime.
20057 // Just fail to evaluate when not in a constant context.
20058 if (!Info.InConstantContext)
20059 return std::nullopt;
20060 assert(E->getBuiltinCallee() == Builtin::BI__builtin_is_within_lifetime);
20061 const Expr *Arg = E->getArg(0);
20062 if (Arg->isValueDependent())
20063 return std::nullopt;
20064 LValue Val;
20065 if (!EvaluatePointer(Arg, Val, Info))
20066 return std::nullopt;
20067
20068 if (Val.allowConstexprUnknown())
20069 return true;
20070
20071 auto Error = [&](int Diag) {
20072 bool CalledFromStd = false;
20073 const auto *Callee = Info.CurrentCall->getCallee();
20074 if (Callee && Callee->isInStdNamespace()) {
20075 const IdentifierInfo *Identifier = Callee->getIdentifier();
20076 CalledFromStd = Identifier && Identifier->isStr("is_within_lifetime");
20077 }
20078 Info.CCEDiag(CalledFromStd ? Info.CurrentCall->getCallRange().getBegin()
20079 : E->getExprLoc(),
20080 diag::err_invalid_is_within_lifetime)
20081 << (CalledFromStd ? "std::is_within_lifetime"
20082 : "__builtin_is_within_lifetime")
20083 << Diag;
20084 return std::nullopt;
20085 };
20086 // C++2c [meta.const.eval]p4:
20087 // During the evaluation of an expression E as a core constant expression, a
20088 // call to this function is ill-formed unless p points to an object that is
20089 // usable in constant expressions or whose complete object's lifetime began
20090 // within E.
20091
20092 // Make sure it points to an object
20093 // nullptr does not point to an object
20094 if (Val.isNullPointer() || Val.getLValueBase().isNull())
20095 return Error(0);
20096 QualType T = Val.getLValueBase().getType();
20097 assert(!T->isFunctionType() &&
20098 "Pointers to functions should have been typed as function pointers "
20099 "which would have been rejected earlier");
20100 assert(T->isObjectType());
20101 // Hypothetical array element is not an object
20102 if (Val.getLValueDesignator().isOnePastTheEnd())
20103 return Error(1);
20104 assert(Val.getLValueDesignator().isValidSubobject() &&
20105 "Unchecked case for valid subobject");
20106 // All other ill-formed values should have failed EvaluatePointer, so the
20107 // object should be a pointer to an object that is usable in a constant
20108 // expression or whose complete lifetime began within the expression
20109 CompleteObject CO =
20110 findCompleteObject(Info, E, AccessKinds::AK_IsWithinLifetime, Val, T);
20111 // The lifetime hasn't begun yet if we are still evaluating the
20112 // initializer ([basic.life]p(1.2))
20113 if (Info.EvaluatingDeclValue && CO.Value == Info.EvaluatingDeclValue)
20114 return Error(2);
20115
20116 if (!CO)
20117 return false;
20118 IsWithinLifetimeHandler handler{Info};
20119 return findSubobject(Info, E, CO, Val.getLValueDesignator(), handler);
20120}
20121} // 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 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 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 evalPshufbBuiltin(EvalInfo &Info, const CallExpr *Call, APValue &Out)
static ICEDiag CheckEvalInICE(const Expr *E, const ASTContext &Ctx)
static llvm::APInt ConvertBoolVectorToInt(const APValue &Val)
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 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 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 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 evalPshufBuiltin(EvalInfo &Info, const CallExpr *Call, bool IsShufHW, APValue &Out)
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 evalShuffleGeneric(EvalInfo &Info, const CallExpr *Call, APValue &Out, llvm::function_ref< std::pair< unsigned, unsigned >(unsigned, unsigned)> GetSourceIndex)
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<=>,...
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:44
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:1920
Expr * getLHS()
Definition Stmt.h:2003
Expr * getRHS()
Definition Stmt.h:2015
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:2832
Stmt * getBody()
Definition Stmt.h:2857
Expr * getCond()
Definition Stmt.h:2850
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:2888
Stmt * getInit()
Definition Stmt.h:2903
VarDecl * getConditionVariable() const
Retrieve the variable declared in this "for" statement, if any.
Definition Stmt.cpp:1082
Stmt * getBody()
Definition Stmt.h:2932
Expr * getInc()
Definition Stmt.h:2931
Expr * getCond()
Definition Stmt.h:2930
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:2259
Stmt * getThen()
Definition Stmt.h:2348
Stmt * getInit()
Definition Stmt.h:2409
bool isNonNegatedConsteval() const
Definition Stmt.h:2444
Expr * getCond()
Definition Stmt.h:2336
Stmt * getElse()
Definition Stmt.h:2357
bool isConsteval() const
Definition Stmt.h:2439
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:1893
SwitchStmt - This represents a 'switch' stmt.
Definition Stmt.h:2509
Expr * getCond()
Definition Stmt.h:2572
Stmt * getBody()
Definition Stmt.h:2584
VarDecl * getConditionVariable()
Retrieve the variable declared in this "switch" statement, if any.
Definition Stmt.cpp:1148
Stmt * getInit()
Definition Stmt.h:2589
SwitchCase * getSwitchCaseList()
Definition Stmt.h:2640
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:853
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:517
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:2697
Expr * getCond()
Definition Stmt.h:2749
VarDecl * getConditionVariable()
Retrieve the variable declared in this "while" statement, if any.
Definition Stmt.cpp:1209
Stmt * getBody()
Definition Stmt.h:2761
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:1234
llvm::FixedPointSemantics FixedPointSemantics
Definition Interp.h:42
bool This(InterpState &S, CodePtr OpPC)
Definition Interp.h:2792
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:3460
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