Thanks to visit codestin.com
Credit goes to clang.llvm.org

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"
47#include "clang/AST/OSLog.h"
51#include "clang/AST/Type.h"
52#include "clang/AST/TypeLoc.h"
57#include "llvm/ADT/APFixedPoint.h"
58#include "llvm/ADT/Sequence.h"
59#include "llvm/ADT/SmallBitVector.h"
60#include "llvm/ADT/StringExtras.h"
61#include "llvm/Support/Casting.h"
62#include "llvm/Support/Debug.h"
63#include "llvm/Support/SaveAndRestore.h"
64#include "llvm/Support/SipHash.h"
65#include "llvm/Support/TimeProfiler.h"
66#include "llvm/Support/raw_ostream.h"
67#include <cstring>
68#include <functional>
69#include <limits>
70#include <optional>
71
72#define DEBUG_TYPE "exprconstant"
73
74using namespace clang;
75using llvm::APFixedPoint;
76using llvm::APInt;
77using llvm::APSInt;
78using llvm::APFloat;
79using llvm::FixedPointSemantics;
80
81namespace {
82 struct LValue;
83 class CallStackFrame;
84 class EvalInfo;
85
86 using SourceLocExprScopeGuard =
88
90 return B.getType();
91 }
92
93 /// Get an LValue path entry, which is known to not be an array index, as a
94 /// field declaration.
95 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
96 return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer());
97 }
98 /// Get an LValue path entry, which is known to not be an array index, as a
99 /// base class declaration.
100 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
101 return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer());
102 }
103 /// Determine whether this LValue path entry for a base class names a virtual
104 /// base class.
105 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
106 return E.getAsBaseOrMember().getInt();
107 }
108
109 /// Given an expression, determine the type used to store the result of
110 /// evaluating that expression.
111 static QualType getStorageType(const ASTContext &Ctx, const Expr *E) {
112 if (E->isPRValue())
113 return E->getType();
114 return Ctx.getLValueReferenceType(E->getType());
115 }
116
117 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
118 /// This will look through a single cast.
119 ///
120 /// Returns null if we couldn't unwrap a function with alloc_size.
121 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
122 if (!E->getType()->isPointerType())
123 return nullptr;
124
125 E = E->IgnoreParens();
126 // If we're doing a variable assignment from e.g. malloc(N), there will
127 // probably be a cast of some kind. In exotic cases, we might also see a
128 // top-level ExprWithCleanups. Ignore them either way.
129 if (const auto *FE = dyn_cast<FullExpr>(E))
130 E = FE->getSubExpr()->IgnoreParens();
131
132 if (const auto *Cast = dyn_cast<CastExpr>(E))
133 E = Cast->getSubExpr()->IgnoreParens();
134
135 if (const auto *CE = dyn_cast<CallExpr>(E))
136 return CE->getCalleeAllocSizeAttr() ? CE : nullptr;
137 return nullptr;
138 }
139
140 /// Determines whether or not the given Base contains a call to a function
141 /// with the alloc_size attribute.
142 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
143 const auto *E = Base.dyn_cast<const Expr *>();
144 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
145 }
146
147 /// Determines whether the given kind of constant expression is only ever
148 /// used for name mangling. If so, it's permitted to reference things that we
149 /// can't generate code for (in particular, dllimported functions).
150 static bool isForManglingOnly(ConstantExprKind Kind) {
151 switch (Kind) {
152 case ConstantExprKind::Normal:
153 case ConstantExprKind::ClassTemplateArgument:
154 case ConstantExprKind::ImmediateInvocation:
155 // Note that non-type template arguments of class type are emitted as
156 // template parameter objects.
157 return false;
158
159 case ConstantExprKind::NonClassTemplateArgument:
160 return true;
161 }
162 llvm_unreachable("unknown ConstantExprKind");
163 }
164
165 static bool isTemplateArgument(ConstantExprKind Kind) {
166 switch (Kind) {
167 case ConstantExprKind::Normal:
168 case ConstantExprKind::ImmediateInvocation:
169 return false;
170
171 case ConstantExprKind::ClassTemplateArgument:
172 case ConstantExprKind::NonClassTemplateArgument:
173 return true;
174 }
175 llvm_unreachable("unknown ConstantExprKind");
176 }
177
178 /// The bound to claim that an array of unknown bound has.
179 /// The value in MostDerivedArraySize is undefined in this case. So, set it
180 /// to an arbitrary value that's likely to loudly break things if it's used.
181 static const uint64_t AssumedSizeForUnsizedArray =
182 std::numeric_limits<uint64_t>::max() / 2;
183
184 /// Determines if an LValue with the given LValueBase will have an unsized
185 /// array in its designator.
186 /// Find the path length and type of the most-derived subobject in the given
187 /// path, and find the size of the containing array, if any.
188 static unsigned
189 findMostDerivedSubobject(const ASTContext &Ctx, APValue::LValueBase Base,
191 uint64_t &ArraySize, QualType &Type, bool &IsArray,
192 bool &FirstEntryIsUnsizedArray) {
193 // This only accepts LValueBases from APValues, and APValues don't support
194 // arrays that lack size info.
195 assert(!isBaseAnAllocSizeCall(Base) &&
196 "Unsized arrays shouldn't appear here");
197 unsigned MostDerivedLength = 0;
198 // The type of Base is a reference type if the base is a constexpr-unknown
199 // variable. In that case, look through the reference type.
200 Type = getType(Base).getNonReferenceType();
201
202 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
203 if (Type->isArrayType()) {
204 const ArrayType *AT = Ctx.getAsArrayType(Type);
205 Type = AT->getElementType();
206 MostDerivedLength = I + 1;
207 IsArray = true;
208
209 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
210 ArraySize = CAT->getZExtSize();
211 } else {
212 assert(I == 0 && "unexpected unsized array designator");
213 FirstEntryIsUnsizedArray = true;
214 ArraySize = AssumedSizeForUnsizedArray;
215 }
216 } else if (Type->isAnyComplexType()) {
217 const ComplexType *CT = Type->castAs<ComplexType>();
218 Type = CT->getElementType();
219 ArraySize = 2;
220 MostDerivedLength = I + 1;
221 IsArray = true;
222 } else if (const auto *VT = Type->getAs<VectorType>()) {
223 Type = VT->getElementType();
224 ArraySize = VT->getNumElements();
225 MostDerivedLength = I + 1;
226 IsArray = true;
227 } else if (const FieldDecl *FD = getAsField(Path[I])) {
228 Type = FD->getType();
229 ArraySize = 0;
230 MostDerivedLength = I + 1;
231 IsArray = false;
232 } else {
233 // Path[I] describes a base class.
234 ArraySize = 0;
235 IsArray = false;
236 }
237 }
238 return MostDerivedLength;
239 }
240
241 /// A path from a glvalue to a subobject of that glvalue.
242 struct SubobjectDesignator {
243 /// True if the subobject was named in a manner not supported by C++11. Such
244 /// lvalues can still be folded, but they are not core constant expressions
245 /// and we cannot perform lvalue-to-rvalue conversions on them.
246 LLVM_PREFERRED_TYPE(bool)
247 unsigned Invalid : 1;
248
249 /// Is this a pointer one past the end of an object?
250 LLVM_PREFERRED_TYPE(bool)
251 unsigned IsOnePastTheEnd : 1;
252
253 /// Indicator of whether the first entry is an unsized array.
254 LLVM_PREFERRED_TYPE(bool)
255 unsigned FirstEntryIsAnUnsizedArray : 1;
256
257 /// Indicator of whether the most-derived object is an array element.
258 LLVM_PREFERRED_TYPE(bool)
259 unsigned MostDerivedIsArrayElement : 1;
260
261 /// The length of the path to the most-derived object of which this is a
262 /// subobject.
263 unsigned MostDerivedPathLength : 28;
264
265 /// The size of the array of which the most-derived object is an element.
266 /// This will always be 0 if the most-derived object is not an array
267 /// element. 0 is not an indicator of whether or not the most-derived object
268 /// is an array, however, because 0-length arrays are allowed.
269 ///
270 /// If the current array is an unsized array, the value of this is
271 /// undefined.
272 uint64_t MostDerivedArraySize;
273 /// The type of the most derived object referred to by this address.
274 QualType MostDerivedType;
275
276 typedef APValue::LValuePathEntry PathEntry;
277
278 /// The entries on the path from the glvalue to the designated subobject.
280
281 SubobjectDesignator() : Invalid(true) {}
282
283 explicit SubobjectDesignator(QualType T)
284 : Invalid(false), IsOnePastTheEnd(false),
285 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
286 MostDerivedPathLength(0), MostDerivedArraySize(0),
287 MostDerivedType(T.isNull() ? QualType() : T.getNonReferenceType()) {}
288
289 SubobjectDesignator(const ASTContext &Ctx, const APValue &V)
290 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
291 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
292 MostDerivedPathLength(0), MostDerivedArraySize(0) {
293 assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
294 if (!Invalid) {
295 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
296 llvm::append_range(Entries, V.getLValuePath());
297 if (V.getLValueBase()) {
298 bool IsArray = false;
299 bool FirstIsUnsizedArray = false;
300 MostDerivedPathLength = findMostDerivedSubobject(
301 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
302 MostDerivedType, IsArray, FirstIsUnsizedArray);
303 MostDerivedIsArrayElement = IsArray;
304 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
305 }
306 }
307 }
308
309 void truncate(ASTContext &Ctx, APValue::LValueBase Base,
310 unsigned NewLength) {
311 if (Invalid)
312 return;
313
314 assert(Base && "cannot truncate path for null pointer");
315 assert(NewLength <= Entries.size() && "not a truncation");
316
317 if (NewLength == Entries.size())
318 return;
319 Entries.resize(NewLength);
320
321 bool IsArray = false;
322 bool FirstIsUnsizedArray = false;
323 MostDerivedPathLength = findMostDerivedSubobject(
324 Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray,
325 FirstIsUnsizedArray);
326 MostDerivedIsArrayElement = IsArray;
327 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
328 }
329
330 void setInvalid() {
331 Invalid = true;
332 Entries.clear();
333 }
334
335 /// Determine whether the most derived subobject is an array without a
336 /// known bound.
337 bool isMostDerivedAnUnsizedArray() const {
338 assert(!Invalid && "Calling this makes no sense on invalid designators");
339 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
340 }
341
342 /// Determine what the most derived array's size is. Results in an assertion
343 /// failure if the most derived array lacks a size.
344 uint64_t getMostDerivedArraySize() const {
345 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
346 return MostDerivedArraySize;
347 }
348
349 /// Determine whether this is a one-past-the-end pointer.
350 bool isOnePastTheEnd() const {
351 assert(!Invalid);
352 if (IsOnePastTheEnd)
353 return true;
354 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
355 Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==
356 MostDerivedArraySize)
357 return true;
358 return false;
359 }
360
361 /// Get the range of valid index adjustments in the form
362 /// {maximum value that can be subtracted from this pointer,
363 /// maximum value that can be added to this pointer}
364 std::pair<uint64_t, uint64_t> validIndexAdjustments() {
365 if (Invalid || isMostDerivedAnUnsizedArray())
366 return {0, 0};
367
368 // [expr.add]p4: For the purposes of these operators, a pointer to a
369 // nonarray object behaves the same as a pointer to the first element of
370 // an array of length one with the type of the object as its element type.
371 bool IsArray = MostDerivedPathLength == Entries.size() &&
372 MostDerivedIsArrayElement;
373 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
374 : (uint64_t)IsOnePastTheEnd;
375 uint64_t ArraySize =
376 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
377 return {ArrayIndex, ArraySize - ArrayIndex};
378 }
379
380 /// Check that this refers to a valid subobject.
381 bool isValidSubobject() const {
382 if (Invalid)
383 return false;
384 return !isOnePastTheEnd();
385 }
386 /// Check that this refers to a valid subobject, and if not, produce a
387 /// relevant diagnostic and set the designator as invalid.
388 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
389
390 /// Get the type of the designated object.
391 QualType getType(ASTContext &Ctx) const {
392 assert(!Invalid && "invalid designator has no subobject type");
393 return MostDerivedPathLength == Entries.size()
394 ? MostDerivedType
395 : Ctx.getCanonicalTagType(getAsBaseClass(Entries.back()));
396 }
397
398 /// Update this designator to refer to the first element within this array.
399 void addArrayUnchecked(const ConstantArrayType *CAT) {
400 Entries.push_back(PathEntry::ArrayIndex(0));
401
402 // This is a most-derived object.
403 MostDerivedType = CAT->getElementType();
404 MostDerivedIsArrayElement = true;
405 MostDerivedArraySize = CAT->getZExtSize();
406 MostDerivedPathLength = Entries.size();
407 }
408 /// Update this designator to refer to the first element within the array of
409 /// elements of type T. This is an array of unknown size.
410 void addUnsizedArrayUnchecked(QualType ElemTy) {
411 Entries.push_back(PathEntry::ArrayIndex(0));
412
413 MostDerivedType = ElemTy;
414 MostDerivedIsArrayElement = true;
415 // The value in MostDerivedArraySize is undefined in this case. So, set it
416 // to an arbitrary value that's likely to loudly break things if it's
417 // used.
418 MostDerivedArraySize = AssumedSizeForUnsizedArray;
419 MostDerivedPathLength = Entries.size();
420 }
421 /// Update this designator to refer to the given base or member of this
422 /// object.
423 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
424 Entries.push_back(APValue::BaseOrMemberType(D, Virtual));
425
426 // If this isn't a base class, it's a new most-derived object.
427 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
428 MostDerivedType = FD->getType();
429 MostDerivedIsArrayElement = false;
430 MostDerivedArraySize = 0;
431 MostDerivedPathLength = Entries.size();
432 }
433 }
434 /// Update this designator to refer to the given complex component.
435 void addComplexUnchecked(QualType EltTy, bool Imag) {
436 Entries.push_back(PathEntry::ArrayIndex(Imag));
437
438 // This is technically a most-derived object, though in practice this
439 // is unlikely to matter.
440 MostDerivedType = EltTy;
441 MostDerivedIsArrayElement = true;
442 MostDerivedArraySize = 2;
443 MostDerivedPathLength = Entries.size();
444 }
445
446 void addVectorElementUnchecked(QualType EltTy, uint64_t Size,
447 uint64_t Idx) {
448 Entries.push_back(PathEntry::ArrayIndex(Idx));
449 MostDerivedType = EltTy;
450 MostDerivedPathLength = Entries.size();
451 MostDerivedArraySize = 0;
452 MostDerivedIsArrayElement = false;
453 }
454
455 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
456 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
457 const APSInt &N);
458 /// Add N to the address of this subobject.
459 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N, const LValue &LV);
460 };
461
462 /// A scope at the end of which an object can need to be destroyed.
463 enum class ScopeKind {
464 Block,
465 FullExpression,
466 Call
467 };
468
469 /// A reference to a particular call and its arguments.
470 struct CallRef {
471 CallRef() : OrigCallee(), CallIndex(0), Version() {}
472 CallRef(const FunctionDecl *Callee, unsigned CallIndex, unsigned Version)
473 : OrigCallee(Callee), CallIndex(CallIndex), Version(Version) {}
474
475 explicit operator bool() const { return OrigCallee; }
476
477 /// Get the parameter that the caller initialized, corresponding to the
478 /// given parameter in the callee.
479 const ParmVarDecl *getOrigParam(const ParmVarDecl *PVD) const {
480 return OrigCallee ? OrigCallee->getParamDecl(PVD->getFunctionScopeIndex())
481 : PVD;
482 }
483
484 /// The callee at the point where the arguments were evaluated. This might
485 /// be different from the actual callee (a different redeclaration, or a
486 /// virtual override), but this function's parameters are the ones that
487 /// appear in the parameter map.
488 const FunctionDecl *OrigCallee;
489 /// The call index of the frame that holds the argument values.
490 unsigned CallIndex;
491 /// The version of the parameters corresponding to this call.
492 unsigned Version;
493 };
494
495 /// A stack frame in the constexpr call stack.
496 class CallStackFrame : public interp::Frame {
497 public:
498 EvalInfo &Info;
499
500 /// Parent - The caller of this stack frame.
501 CallStackFrame *Caller;
502
503 /// Callee - The function which was called.
504 const FunctionDecl *Callee;
505
506 /// This - The binding for the this pointer in this call, if any.
507 const LValue *This;
508
509 /// CallExpr - The syntactical structure of member function calls
510 const Expr *CallExpr;
511
512 /// Information on how to find the arguments to this call. Our arguments
513 /// are stored in our parent's CallStackFrame, using the ParmVarDecl* as a
514 /// key and this value as the version.
515 CallRef Arguments;
516
517 /// Source location information about the default argument or default
518 /// initializer expression we're evaluating, if any.
519 CurrentSourceLocExprScope CurSourceLocExprScope;
520
521 // Note that we intentionally use std::map here so that references to
522 // values are stable.
523 typedef std::pair<const void *, unsigned> MapKeyTy;
524 typedef std::map<MapKeyTy, APValue> MapTy;
525 /// Temporaries - Temporary lvalues materialized within this stack frame.
526 MapTy Temporaries;
527
528 /// CallRange - The source range of the call expression for this call.
529 SourceRange CallRange;
530
531 /// Index - The call index of this call.
532 unsigned Index;
533
534 /// The stack of integers for tracking version numbers for temporaries.
535 SmallVector<unsigned, 2> TempVersionStack = {1};
536 unsigned CurTempVersion = TempVersionStack.back();
537
538 unsigned getTempVersion() const { return TempVersionStack.back(); }
539
540 void pushTempVersion() {
541 TempVersionStack.push_back(++CurTempVersion);
542 }
543
544 void popTempVersion() {
545 TempVersionStack.pop_back();
546 }
547
548 CallRef createCall(const FunctionDecl *Callee) {
549 return {Callee, Index, ++CurTempVersion};
550 }
551
552 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
553 // on the overall stack usage of deeply-recursing constexpr evaluations.
554 // (We should cache this map rather than recomputing it repeatedly.)
555 // But let's try this and see how it goes; we can look into caching the map
556 // as a later change.
557
558 /// LambdaCaptureFields - Mapping from captured variables/this to
559 /// corresponding data members in the closure class.
560 llvm::DenseMap<const ValueDecl *, FieldDecl *> LambdaCaptureFields;
561 FieldDecl *LambdaThisCaptureField = nullptr;
562
563 CallStackFrame(EvalInfo &Info, SourceRange CallRange,
564 const FunctionDecl *Callee, const LValue *This,
565 const Expr *CallExpr, CallRef Arguments);
566 ~CallStackFrame();
567
568 // Return the temporary for Key whose version number is Version.
569 APValue *getTemporary(const void *Key, unsigned Version) {
570 MapKeyTy KV(Key, Version);
571 auto LB = Temporaries.lower_bound(KV);
572 if (LB != Temporaries.end() && LB->first == KV)
573 return &LB->second;
574 return nullptr;
575 }
576
577 // Return the current temporary for Key in the map.
578 APValue *getCurrentTemporary(const void *Key) {
579 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
580 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
581 return &std::prev(UB)->second;
582 return nullptr;
583 }
584
585 // Return the version number of the current temporary for Key.
586 unsigned getCurrentTemporaryVersion(const void *Key) const {
587 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
588 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
589 return std::prev(UB)->first.second;
590 return 0;
591 }
592
593 /// Allocate storage for an object of type T in this stack frame.
594 /// Populates LV with a handle to the created object. Key identifies
595 /// the temporary within the stack frame, and must not be reused without
596 /// bumping the temporary version number.
597 template<typename KeyT>
598 APValue &createTemporary(const KeyT *Key, QualType T,
599 ScopeKind Scope, LValue &LV);
600
601 /// Allocate storage for a parameter of a function call made in this frame.
602 APValue &createParam(CallRef Args, const ParmVarDecl *PVD, LValue &LV);
603
604 void describe(llvm::raw_ostream &OS) const override;
605
606 Frame *getCaller() const override { return Caller; }
607 SourceRange getCallRange() const override { return CallRange; }
608 const FunctionDecl *getCallee() const override { return Callee; }
609
610 bool isStdFunction() const {
611 for (const DeclContext *DC = Callee; DC; DC = DC->getParent())
612 if (DC->isStdNamespace())
613 return true;
614 return false;
615 }
616
617 /// Whether we're in a context where [[msvc::constexpr]] evaluation is
618 /// permitted. See MSConstexprDocs for description of permitted contexts.
619 bool CanEvalMSConstexpr = false;
620
621 private:
622 APValue &createLocal(APValue::LValueBase Base, const void *Key, QualType T,
623 ScopeKind Scope);
624 };
625
626 /// Temporarily override 'this'.
627 class ThisOverrideRAII {
628 public:
629 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
630 : Frame(Frame), OldThis(Frame.This) {
631 if (Enable)
632 Frame.This = NewThis;
633 }
634 ~ThisOverrideRAII() {
635 Frame.This = OldThis;
636 }
637 private:
638 CallStackFrame &Frame;
639 const LValue *OldThis;
640 };
641
642 // A shorthand time trace scope struct, prints source range, for example
643 // {"name":"EvaluateAsRValue","args":{"detail":"<test.cc:8:21, col:25>"}}}
644 class ExprTimeTraceScope {
645 public:
646 ExprTimeTraceScope(const Expr *E, const ASTContext &Ctx, StringRef Name)
647 : TimeScope(Name, [E, &Ctx] {
649 }) {}
650
651 private:
652 llvm::TimeTraceScope TimeScope;
653 };
654
655 /// RAII object used to change the current ability of
656 /// [[msvc::constexpr]] evaulation.
657 struct MSConstexprContextRAII {
658 CallStackFrame &Frame;
659 bool OldValue;
660 explicit MSConstexprContextRAII(CallStackFrame &Frame, bool Value)
661 : Frame(Frame), OldValue(Frame.CanEvalMSConstexpr) {
662 Frame.CanEvalMSConstexpr = Value;
663 }
664
665 ~MSConstexprContextRAII() { Frame.CanEvalMSConstexpr = OldValue; }
666 };
667}
668
669static bool HandleDestruction(EvalInfo &Info, const Expr *E,
670 const LValue &This, QualType ThisType);
671static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
673 QualType T);
674
675namespace {
676 /// A cleanup, and a flag indicating whether it is lifetime-extended.
677 class Cleanup {
678 llvm::PointerIntPair<APValue*, 2, ScopeKind> Value;
679 APValue::LValueBase Base;
680 QualType T;
681
682 public:
683 Cleanup(APValue *Val, APValue::LValueBase Base, QualType T,
684 ScopeKind Scope)
685 : Value(Val, Scope), Base(Base), T(T) {}
686
687 /// Determine whether this cleanup should be performed at the end of the
688 /// given kind of scope.
689 bool isDestroyedAtEndOf(ScopeKind K) const {
690 return (int)Value.getInt() >= (int)K;
691 }
692 bool endLifetime(EvalInfo &Info, bool RunDestructors) {
693 if (RunDestructors) {
694 SourceLocation Loc;
695 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>())
696 Loc = VD->getLocation();
697 else if (const Expr *E = Base.dyn_cast<const Expr*>())
698 Loc = E->getExprLoc();
699 return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T);
700 }
701 *Value.getPointer() = APValue();
702 return true;
703 }
704
705 bool hasSideEffect() {
706 return T.isDestructedType();
707 }
708 };
709
710 /// A reference to an object whose construction we are currently evaluating.
711 struct ObjectUnderConstruction {
712 APValue::LValueBase Base;
713 ArrayRef<APValue::LValuePathEntry> Path;
714 friend bool operator==(const ObjectUnderConstruction &LHS,
715 const ObjectUnderConstruction &RHS) {
716 return LHS.Base == RHS.Base && LHS.Path == RHS.Path;
717 }
718 friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {
719 return llvm::hash_combine(Obj.Base, Obj.Path);
720 }
721 };
722 enum class ConstructionPhase {
723 None,
724 Bases,
725 AfterBases,
726 AfterFields,
727 Destroying,
728 DestroyingBases
729 };
730}
731
732namespace llvm {
733template<> struct DenseMapInfo<ObjectUnderConstruction> {
734 using Base = DenseMapInfo<APValue::LValueBase>;
735 static ObjectUnderConstruction getEmptyKey() {
736 return {Base::getEmptyKey(), {}}; }
737 static ObjectUnderConstruction getTombstoneKey() {
738 return {Base::getTombstoneKey(), {}};
739 }
740 static unsigned getHashValue(const ObjectUnderConstruction &Object) {
741 return hash_value(Object);
742 }
743 static bool isEqual(const ObjectUnderConstruction &LHS,
744 const ObjectUnderConstruction &RHS) {
745 return LHS == RHS;
746 }
747};
748}
749
750namespace {
751 /// A dynamically-allocated heap object.
752 struct DynAlloc {
753 /// The value of this heap-allocated object.
754 APValue Value;
755 /// The allocating expression; used for diagnostics. Either a CXXNewExpr
756 /// or a CallExpr (the latter is for direct calls to operator new inside
757 /// std::allocator<T>::allocate).
758 const Expr *AllocExpr = nullptr;
759
760 enum Kind {
761 New,
762 ArrayNew,
763 StdAllocator
764 };
765
766 /// Get the kind of the allocation. This must match between allocation
767 /// and deallocation.
768 Kind getKind() const {
769 if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr))
770 return NE->isArray() ? ArrayNew : New;
771 assert(isa<CallExpr>(AllocExpr));
772 return StdAllocator;
773 }
774 };
775
776 struct DynAllocOrder {
777 bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const {
778 return L.getIndex() < R.getIndex();
779 }
780 };
781
782 /// EvalInfo - This is a private struct used by the evaluator to capture
783 /// information about a subexpression as it is folded. It retains information
784 /// about the AST context, but also maintains information about the folded
785 /// expression.
786 ///
787 /// If an expression could be evaluated, it is still possible it is not a C
788 /// "integer constant expression" or constant expression. If not, this struct
789 /// captures information about how and why not.
790 ///
791 /// One bit of information passed *into* the request for constant folding
792 /// indicates whether the subexpression is "evaluated" or not according to C
793 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
794 /// evaluate the expression regardless of what the RHS is, but C only allows
795 /// certain things in certain situations.
796 class EvalInfo : public interp::State {
797 public:
798 ASTContext &Ctx;
799
800 /// EvalStatus - Contains information about the evaluation.
801 Expr::EvalStatus &EvalStatus;
802
803 /// CurrentCall - The top of the constexpr call stack.
804 CallStackFrame *CurrentCall;
805
806 /// CallStackDepth - The number of calls in the call stack right now.
807 unsigned CallStackDepth;
808
809 /// NextCallIndex - The next call index to assign.
810 unsigned NextCallIndex;
811
812 /// StepsLeft - The remaining number of evaluation steps we're permitted
813 /// to perform. This is essentially a limit for the number of statements
814 /// we will evaluate.
815 unsigned StepsLeft;
816
817 /// Enable the experimental new constant interpreter. If an expression is
818 /// not supported by the interpreter, an error is triggered.
819 bool EnableNewConstInterp;
820
821 /// BottomFrame - The frame in which evaluation started. This must be
822 /// initialized after CurrentCall and CallStackDepth.
823 CallStackFrame BottomFrame;
824
825 /// A stack of values whose lifetimes end at the end of some surrounding
826 /// evaluation frame.
827 llvm::SmallVector<Cleanup, 16> CleanupStack;
828
829 /// EvaluatingDecl - This is the declaration whose initializer is being
830 /// evaluated, if any.
831 APValue::LValueBase EvaluatingDecl;
832
833 enum class EvaluatingDeclKind {
834 None,
835 /// We're evaluating the construction of EvaluatingDecl.
836 Ctor,
837 /// We're evaluating the destruction of EvaluatingDecl.
838 Dtor,
839 };
840 EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None;
841
842 /// EvaluatingDeclValue - This is the value being constructed for the
843 /// declaration whose initializer is being evaluated, if any.
844 APValue *EvaluatingDeclValue;
845
846 /// Stack of loops and 'switch' statements which we're currently
847 /// breaking/continuing; null entries are used to mark unlabeled
848 /// break/continue.
849 SmallVector<const Stmt *> BreakContinueStack;
850
851 /// Set of objects that are currently being constructed.
852 llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
853 ObjectsUnderConstruction;
854
855 /// Current heap allocations, along with the location where each was
856 /// allocated. We use std::map here because we need stable addresses
857 /// for the stored APValues.
858 std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs;
859
860 /// The number of heap allocations performed so far in this evaluation.
861 unsigned NumHeapAllocs = 0;
862
863 struct EvaluatingConstructorRAII {
864 EvalInfo &EI;
865 ObjectUnderConstruction Object;
866 bool DidInsert;
867 EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
868 bool HasBases)
869 : EI(EI), Object(Object) {
870 DidInsert =
871 EI.ObjectsUnderConstruction
872 .insert({Object, HasBases ? ConstructionPhase::Bases
873 : ConstructionPhase::AfterBases})
874 .second;
875 }
876 void finishedConstructingBases() {
877 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
878 }
879 void finishedConstructingFields() {
880 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields;
881 }
882 ~EvaluatingConstructorRAII() {
883 if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
884 }
885 };
886
887 struct EvaluatingDestructorRAII {
888 EvalInfo &EI;
889 ObjectUnderConstruction Object;
890 bool DidInsert;
891 EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object)
892 : EI(EI), Object(Object) {
893 DidInsert = EI.ObjectsUnderConstruction
894 .insert({Object, ConstructionPhase::Destroying})
895 .second;
896 }
897 void startedDestroyingBases() {
898 EI.ObjectsUnderConstruction[Object] =
899 ConstructionPhase::DestroyingBases;
900 }
901 ~EvaluatingDestructorRAII() {
902 if (DidInsert)
903 EI.ObjectsUnderConstruction.erase(Object);
904 }
905 };
906
907 ConstructionPhase
908 isEvaluatingCtorDtor(APValue::LValueBase Base,
909 ArrayRef<APValue::LValuePathEntry> Path) {
910 return ObjectsUnderConstruction.lookup({Base, Path});
911 }
912
913 /// If we're currently speculatively evaluating, the outermost call stack
914 /// depth at which we can mutate state, otherwise 0.
915 unsigned SpeculativeEvaluationDepth = 0;
916
917 /// The current array initialization index, if we're performing array
918 /// initialization.
919 uint64_t ArrayInitIndex = -1;
920
921 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
922 /// notes attached to it will also be stored, otherwise they will not be.
923 bool HasActiveDiagnostic;
924
925 /// Have we emitted a diagnostic explaining why we couldn't constant
926 /// fold (not just why it's not strictly a constant expression)?
927 bool HasFoldFailureDiagnostic;
928
929 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
930 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
931 CallStackDepth(0), NextCallIndex(1),
932 StepsLeft(C.getLangOpts().ConstexprStepLimit),
933 EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp),
934 BottomFrame(*this, SourceLocation(), /*Callee=*/nullptr,
935 /*This=*/nullptr,
936 /*CallExpr=*/nullptr, CallRef()),
937 EvaluatingDecl((const ValueDecl *)nullptr),
938 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
939 HasFoldFailureDiagnostic(false) {
940 EvalMode = Mode;
941 }
942
943 ~EvalInfo() {
944 discardCleanups();
945 }
946
947 ASTContext &getASTContext() const override { return Ctx; }
948 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
949
950 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value,
951 EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) {
952 EvaluatingDecl = Base;
953 IsEvaluatingDecl = EDK;
954 EvaluatingDeclValue = &Value;
955 }
956
957 bool CheckCallLimit(SourceLocation Loc) {
958 // Don't perform any constexpr calls (other than the call we're checking)
959 // when checking a potential constant expression.
960 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
961 return false;
962 if (NextCallIndex == 0) {
963 // NextCallIndex has wrapped around.
964 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
965 return false;
966 }
967 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
968 return true;
969 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
970 << getLangOpts().ConstexprCallDepth;
971 return false;
972 }
973
974 bool CheckArraySize(SourceLocation Loc, unsigned BitWidth,
975 uint64_t ElemCount, bool Diag) {
976 // FIXME: GH63562
977 // APValue stores array extents as unsigned,
978 // so anything that is greater that unsigned would overflow when
979 // constructing the array, we catch this here.
980 if (BitWidth > ConstantArrayType::getMaxSizeBits(Ctx) ||
981 ElemCount > uint64_t(std::numeric_limits<unsigned>::max())) {
982 if (Diag)
983 FFDiag(Loc, diag::note_constexpr_new_too_large) << ElemCount;
984 return false;
985 }
986
987 // FIXME: GH63562
988 // Arrays allocate an APValue per element.
989 // We use the number of constexpr steps as a proxy for the maximum size
990 // of arrays to avoid exhausting the system resources, as initialization
991 // of each element is likely to take some number of steps anyway.
992 uint64_t Limit = Ctx.getLangOpts().ConstexprStepLimit;
993 if (ElemCount > Limit) {
994 if (Diag)
995 FFDiag(Loc, diag::note_constexpr_new_exceeds_limits)
996 << ElemCount << Limit;
997 return false;
998 }
999 return true;
1000 }
1001
1002 std::pair<CallStackFrame *, unsigned>
1003 getCallFrameAndDepth(unsigned CallIndex) {
1004 assert(CallIndex && "no call index in getCallFrameAndDepth");
1005 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
1006 // be null in this loop.
1007 unsigned Depth = CallStackDepth;
1008 CallStackFrame *Frame = CurrentCall;
1009 while (Frame->Index > CallIndex) {
1010 Frame = Frame->Caller;
1011 --Depth;
1012 }
1013 if (Frame->Index == CallIndex)
1014 return {Frame, Depth};
1015 return {nullptr, 0};
1016 }
1017
1018 bool nextStep(const Stmt *S) {
1019 if (!StepsLeft) {
1020 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
1021 return false;
1022 }
1023 --StepsLeft;
1024 return true;
1025 }
1026
1027 APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV);
1028
1029 std::optional<DynAlloc *> lookupDynamicAlloc(DynamicAllocLValue DA) {
1030 std::optional<DynAlloc *> Result;
1031 auto It = HeapAllocs.find(DA);
1032 if (It != HeapAllocs.end())
1033 Result = &It->second;
1034 return Result;
1035 }
1036
1037 /// Get the allocated storage for the given parameter of the given call.
1038 APValue *getParamSlot(CallRef Call, const ParmVarDecl *PVD) {
1039 CallStackFrame *Frame = getCallFrameAndDepth(Call.CallIndex).first;
1040 return Frame ? Frame->getTemporary(Call.getOrigParam(PVD), Call.Version)
1041 : nullptr;
1042 }
1043
1044 /// Information about a stack frame for std::allocator<T>::[de]allocate.
1045 struct StdAllocatorCaller {
1046 unsigned FrameIndex;
1047 QualType ElemType;
1048 const Expr *Call;
1049 explicit operator bool() const { return FrameIndex != 0; };
1050 };
1051
1052 StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const {
1053 for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame;
1054 Call = Call->Caller) {
1055 const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee);
1056 if (!MD)
1057 continue;
1058 const IdentifierInfo *FnII = MD->getIdentifier();
1059 if (!FnII || !FnII->isStr(FnName))
1060 continue;
1061
1062 const auto *CTSD =
1063 dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent());
1064 if (!CTSD)
1065 continue;
1066
1067 const IdentifierInfo *ClassII = CTSD->getIdentifier();
1068 const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
1069 if (CTSD->isInStdNamespace() && ClassII &&
1070 ClassII->isStr("allocator") && TAL.size() >= 1 &&
1071 TAL[0].getKind() == TemplateArgument::Type)
1072 return {Call->Index, TAL[0].getAsType(), Call->CallExpr};
1073 }
1074
1075 return {};
1076 }
1077
1078 void performLifetimeExtension() {
1079 // Disable the cleanups for lifetime-extended temporaries.
1080 llvm::erase_if(CleanupStack, [](Cleanup &C) {
1081 return !C.isDestroyedAtEndOf(ScopeKind::FullExpression);
1082 });
1083 }
1084
1085 /// Throw away any remaining cleanups at the end of evaluation. If any
1086 /// cleanups would have had a side-effect, note that as an unmodeled
1087 /// side-effect and return false. Otherwise, return true.
1088 bool discardCleanups() {
1089 for (Cleanup &C : CleanupStack) {
1090 if (C.hasSideEffect() && !noteSideEffect()) {
1091 CleanupStack.clear();
1092 return false;
1093 }
1094 }
1095 CleanupStack.clear();
1096 return true;
1097 }
1098
1099 private:
1100 interp::Frame *getCurrentFrame() override { return CurrentCall; }
1101 const interp::Frame *getBottomFrame() const override { return &BottomFrame; }
1102
1103 bool hasActiveDiagnostic() override { return HasActiveDiagnostic; }
1104 void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; }
1105
1106 void setFoldFailureDiagnostic(bool Flag) override {
1107 HasFoldFailureDiagnostic = Flag;
1108 }
1109
1110 Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; }
1111
1112 // If we have a prior diagnostic, it will be noting that the expression
1113 // isn't a constant expression. This diagnostic is more important,
1114 // unless we require this evaluation to produce a constant expression.
1115 //
1116 // FIXME: We might want to show both diagnostics to the user in
1117 // EvaluationMode::ConstantFold mode.
1118 bool hasPriorDiagnostic() override {
1119 if (!EvalStatus.Diag->empty()) {
1120 switch (EvalMode) {
1121 case EvaluationMode::ConstantFold:
1122 case EvaluationMode::IgnoreSideEffects:
1123 if (!HasFoldFailureDiagnostic)
1124 break;
1125 // We've already failed to fold something. Keep that diagnostic.
1126 [[fallthrough]];
1127 case EvaluationMode::ConstantExpression:
1128 case EvaluationMode::ConstantExpressionUnevaluated:
1129 setActiveDiagnostic(false);
1130 return true;
1131 }
1132 }
1133 return false;
1134 }
1135
1136 unsigned getCallStackDepth() override { return CallStackDepth; }
1137
1138 public:
1139 /// Should we continue evaluation after encountering a side-effect that we
1140 /// couldn't model?
1141 bool keepEvaluatingAfterSideEffect() const override {
1142 switch (EvalMode) {
1143 case EvaluationMode::IgnoreSideEffects:
1144 return true;
1145
1146 case EvaluationMode::ConstantExpression:
1147 case EvaluationMode::ConstantExpressionUnevaluated:
1148 case EvaluationMode::ConstantFold:
1149 // By default, assume any side effect might be valid in some other
1150 // evaluation of this expression from a different context.
1151 return checkingPotentialConstantExpression() ||
1152 checkingForUndefinedBehavior();
1153 }
1154 llvm_unreachable("Missed EvalMode case");
1155 }
1156
1157 /// Note that we have had a side-effect, and determine whether we should
1158 /// keep evaluating.
1159 bool noteSideEffect() override {
1160 EvalStatus.HasSideEffects = true;
1161 return keepEvaluatingAfterSideEffect();
1162 }
1163
1164 /// Should we continue evaluation after encountering undefined behavior?
1165 bool keepEvaluatingAfterUndefinedBehavior() {
1166 switch (EvalMode) {
1167 case EvaluationMode::IgnoreSideEffects:
1168 case EvaluationMode::ConstantFold:
1169 return true;
1170
1171 case EvaluationMode::ConstantExpression:
1172 case EvaluationMode::ConstantExpressionUnevaluated:
1173 return checkingForUndefinedBehavior();
1174 }
1175 llvm_unreachable("Missed EvalMode case");
1176 }
1177
1178 /// Note that we hit something that was technically undefined behavior, but
1179 /// that we can evaluate past it (such as signed overflow or floating-point
1180 /// division by zero.)
1181 bool noteUndefinedBehavior() override {
1182 EvalStatus.HasUndefinedBehavior = true;
1183 return keepEvaluatingAfterUndefinedBehavior();
1184 }
1185
1186 /// Should we continue evaluation as much as possible after encountering a
1187 /// construct which can't be reduced to a value?
1188 bool keepEvaluatingAfterFailure() const override {
1189 if (!StepsLeft)
1190 return false;
1191
1192 switch (EvalMode) {
1193 case EvaluationMode::ConstantExpression:
1194 case EvaluationMode::ConstantExpressionUnevaluated:
1195 case EvaluationMode::ConstantFold:
1196 case EvaluationMode::IgnoreSideEffects:
1197 return checkingPotentialConstantExpression() ||
1198 checkingForUndefinedBehavior();
1199 }
1200 llvm_unreachable("Missed EvalMode case");
1201 }
1202
1203 /// Notes that we failed to evaluate an expression that other expressions
1204 /// directly depend on, and determine if we should keep evaluating. This
1205 /// should only be called if we actually intend to keep evaluating.
1206 ///
1207 /// Call noteSideEffect() instead if we may be able to ignore the value that
1208 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1209 ///
1210 /// (Foo(), 1) // use noteSideEffect
1211 /// (Foo() || true) // use noteSideEffect
1212 /// Foo() + 1 // use noteFailure
1213 [[nodiscard]] bool noteFailure() {
1214 // Failure when evaluating some expression often means there is some
1215 // subexpression whose evaluation was skipped. Therefore, (because we
1216 // don't track whether we skipped an expression when unwinding after an
1217 // evaluation failure) every evaluation failure that bubbles up from a
1218 // subexpression implies that a side-effect has potentially happened. We
1219 // skip setting the HasSideEffects flag to true until we decide to
1220 // continue evaluating after that point, which happens here.
1221 bool KeepGoing = keepEvaluatingAfterFailure();
1222 EvalStatus.HasSideEffects |= KeepGoing;
1223 return KeepGoing;
1224 }
1225
1226 class ArrayInitLoopIndex {
1227 EvalInfo &Info;
1228 uint64_t OuterIndex;
1229
1230 public:
1231 ArrayInitLoopIndex(EvalInfo &Info)
1232 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1233 Info.ArrayInitIndex = 0;
1234 }
1235 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1236
1237 operator uint64_t&() { return Info.ArrayInitIndex; }
1238 };
1239 };
1240
1241 /// Object used to treat all foldable expressions as constant expressions.
1242 struct FoldConstant {
1243 EvalInfo &Info;
1244 bool Enabled;
1245 bool HadNoPriorDiags;
1246 EvaluationMode OldMode;
1247
1248 explicit FoldConstant(EvalInfo &Info, bool Enabled)
1249 : Info(Info),
1250 Enabled(Enabled),
1251 HadNoPriorDiags(Info.EvalStatus.Diag &&
1252 Info.EvalStatus.Diag->empty() &&
1253 !Info.EvalStatus.HasSideEffects),
1254 OldMode(Info.EvalMode) {
1255 if (Enabled)
1256 Info.EvalMode = EvaluationMode::ConstantFold;
1257 }
1258 void keepDiagnostics() { Enabled = false; }
1259 ~FoldConstant() {
1260 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
1261 !Info.EvalStatus.HasSideEffects)
1262 Info.EvalStatus.Diag->clear();
1263 Info.EvalMode = OldMode;
1264 }
1265 };
1266
1267 /// RAII object used to set the current evaluation mode to ignore
1268 /// side-effects.
1269 struct IgnoreSideEffectsRAII {
1270 EvalInfo &Info;
1271 EvaluationMode OldMode;
1272 explicit IgnoreSideEffectsRAII(EvalInfo &Info)
1273 : Info(Info), OldMode(Info.EvalMode) {
1274 Info.EvalMode = EvaluationMode::IgnoreSideEffects;
1275 }
1276
1277 ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
1278 };
1279
1280 /// RAII object used to optionally suppress diagnostics and side-effects from
1281 /// a speculative evaluation.
1282 class SpeculativeEvaluationRAII {
1283 EvalInfo *Info = nullptr;
1284 Expr::EvalStatus OldStatus;
1285 unsigned OldSpeculativeEvaluationDepth = 0;
1286
1287 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1288 Info = Other.Info;
1289 OldStatus = Other.OldStatus;
1290 OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
1291 Other.Info = nullptr;
1292 }
1293
1294 void maybeRestoreState() {
1295 if (!Info)
1296 return;
1297
1298 Info->EvalStatus = OldStatus;
1299 Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
1300 }
1301
1302 public:
1303 SpeculativeEvaluationRAII() = default;
1304
1305 SpeculativeEvaluationRAII(
1306 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1307 : Info(&Info), OldStatus(Info.EvalStatus),
1308 OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
1309 Info.EvalStatus.Diag = NewDiag;
1310 Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
1311 }
1312
1313 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1314 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1315 moveFromAndCancel(std::move(Other));
1316 }
1317
1318 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1319 maybeRestoreState();
1320 moveFromAndCancel(std::move(Other));
1321 return *this;
1322 }
1323
1324 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1325 };
1326
1327 /// RAII object wrapping a full-expression or block scope, and handling
1328 /// the ending of the lifetime of temporaries created within it.
1329 template<ScopeKind Kind>
1330 class ScopeRAII {
1331 EvalInfo &Info;
1332 unsigned OldStackSize;
1333 public:
1334 ScopeRAII(EvalInfo &Info)
1335 : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1336 // Push a new temporary version. This is needed to distinguish between
1337 // temporaries created in different iterations of a loop.
1338 Info.CurrentCall->pushTempVersion();
1339 }
1340 bool destroy(bool RunDestructors = true) {
1341 bool OK = cleanup(Info, RunDestructors, OldStackSize);
1342 OldStackSize = std::numeric_limits<unsigned>::max();
1343 return OK;
1344 }
1345 ~ScopeRAII() {
1346 if (OldStackSize != std::numeric_limits<unsigned>::max())
1347 destroy(false);
1348 // Body moved to a static method to encourage the compiler to inline away
1349 // instances of this class.
1350 Info.CurrentCall->popTempVersion();
1351 }
1352 private:
1353 static bool cleanup(EvalInfo &Info, bool RunDestructors,
1354 unsigned OldStackSize) {
1355 assert(OldStackSize <= Info.CleanupStack.size() &&
1356 "running cleanups out of order?");
1357
1358 // Run all cleanups for a block scope, and non-lifetime-extended cleanups
1359 // for a full-expression scope.
1360 bool Success = true;
1361 for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) {
1362 if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) {
1363 if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) {
1364 Success = false;
1365 break;
1366 }
1367 }
1368 }
1369
1370 // Compact any retained cleanups.
1371 auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
1372 if (Kind != ScopeKind::Block)
1373 NewEnd =
1374 std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) {
1375 return C.isDestroyedAtEndOf(Kind);
1376 });
1377 Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
1378 return Success;
1379 }
1380 };
1381 typedef ScopeRAII<ScopeKind::Block> BlockScopeRAII;
1382 typedef ScopeRAII<ScopeKind::FullExpression> FullExpressionRAII;
1383 typedef ScopeRAII<ScopeKind::Call> CallScopeRAII;
1384}
1385
1386bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1387 CheckSubobjectKind CSK) {
1388 if (Invalid)
1389 return false;
1390 if (isOnePastTheEnd()) {
1391 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1392 << CSK;
1393 setInvalid();
1394 return false;
1395 }
1396 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1397 // must actually be at least one array element; even a VLA cannot have a
1398 // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1399 return true;
1400}
1401
1402void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1403 const Expr *E) {
1404 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1405 // Do not set the designator as invalid: we can represent this situation,
1406 // and correct handling of __builtin_object_size requires us to do so.
1407}
1408
1409void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1410 const Expr *E,
1411 const APSInt &N) {
1412 // If we're complaining, we must be able to statically determine the size of
1413 // the most derived array.
1414 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1415 Info.CCEDiag(E, diag::note_constexpr_array_index)
1416 << N << /*array*/ 0
1417 << static_cast<unsigned>(getMostDerivedArraySize());
1418 else
1419 Info.CCEDiag(E, diag::note_constexpr_array_index)
1420 << N << /*non-array*/ 1;
1421 setInvalid();
1422}
1423
1424CallStackFrame::CallStackFrame(EvalInfo &Info, SourceRange CallRange,
1425 const FunctionDecl *Callee, const LValue *This,
1426 const Expr *CallExpr, CallRef Call)
1427 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1428 CallExpr(CallExpr), Arguments(Call), CallRange(CallRange),
1429 Index(Info.NextCallIndex++) {
1430 Info.CurrentCall = this;
1431 ++Info.CallStackDepth;
1432}
1433
1434CallStackFrame::~CallStackFrame() {
1435 assert(Info.CurrentCall == this && "calls retired out of order");
1436 --Info.CallStackDepth;
1437 Info.CurrentCall = Caller;
1438}
1439
1440static bool isRead(AccessKinds AK) {
1441 return AK == AK_Read || AK == AK_ReadObjectRepresentation ||
1442 AK == AK_IsWithinLifetime || AK == AK_Dereference;
1443}
1444
1446 switch (AK) {
1447 case AK_Read:
1449 case AK_MemberCall:
1450 case AK_DynamicCast:
1451 case AK_TypeId:
1453 case AK_Dereference:
1454 return false;
1455 case AK_Assign:
1456 case AK_Increment:
1457 case AK_Decrement:
1458 case AK_Construct:
1459 case AK_Destroy:
1460 return true;
1461 }
1462 llvm_unreachable("unknown access kind");
1463}
1464
1465static bool isAnyAccess(AccessKinds AK) {
1466 return isRead(AK) || isModification(AK);
1467}
1468
1469/// Is this an access per the C++ definition?
1471 return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy &&
1472 AK != AK_IsWithinLifetime && AK != AK_Dereference;
1473}
1474
1475/// Is this kind of access valid on an indeterminate object value?
1477 switch (AK) {
1478 case AK_Read:
1479 case AK_Increment:
1480 case AK_Decrement:
1481 case AK_Dereference:
1482 // These need the object's value.
1483 return false;
1484
1487 case AK_Assign:
1488 case AK_Construct:
1489 case AK_Destroy:
1490 // Construction and destruction don't need the value.
1491 return true;
1492
1493 case AK_MemberCall:
1494 case AK_DynamicCast:
1495 case AK_TypeId:
1496 // These aren't really meaningful on scalars.
1497 return true;
1498 }
1499 llvm_unreachable("unknown access kind");
1500}
1501
1502namespace {
1503 struct ComplexValue {
1504 private:
1505 bool IsInt;
1506
1507 public:
1508 APSInt IntReal, IntImag;
1509 APFloat FloatReal, FloatImag;
1510
1511 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1512
1513 void makeComplexFloat() { IsInt = false; }
1514 bool isComplexFloat() const { return !IsInt; }
1515 APFloat &getComplexFloatReal() { return FloatReal; }
1516 APFloat &getComplexFloatImag() { return FloatImag; }
1517
1518 void makeComplexInt() { IsInt = true; }
1519 bool isComplexInt() const { return IsInt; }
1520 APSInt &getComplexIntReal() { return IntReal; }
1521 APSInt &getComplexIntImag() { return IntImag; }
1522
1523 void moveInto(APValue &v) const {
1524 if (isComplexFloat())
1525 v = APValue(FloatReal, FloatImag);
1526 else
1527 v = APValue(IntReal, IntImag);
1528 }
1529 void setFrom(const APValue &v) {
1530 assert(v.isComplexFloat() || v.isComplexInt());
1531 if (v.isComplexFloat()) {
1532 makeComplexFloat();
1533 FloatReal = v.getComplexFloatReal();
1534 FloatImag = v.getComplexFloatImag();
1535 } else {
1536 makeComplexInt();
1537 IntReal = v.getComplexIntReal();
1538 IntImag = v.getComplexIntImag();
1539 }
1540 }
1541 };
1542
1543 struct LValue {
1544 APValue::LValueBase Base;
1545 CharUnits Offset;
1546 SubobjectDesignator Designator;
1547 bool IsNullPtr : 1;
1548 bool InvalidBase : 1;
1549 // P2280R4 track if we have an unknown reference or pointer.
1550 bool AllowConstexprUnknown = false;
1551
1552 const APValue::LValueBase getLValueBase() const { return Base; }
1553 bool allowConstexprUnknown() const { return AllowConstexprUnknown; }
1554 CharUnits &getLValueOffset() { return Offset; }
1555 const CharUnits &getLValueOffset() const { return Offset; }
1556 SubobjectDesignator &getLValueDesignator() { return Designator; }
1557 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1558 bool isNullPointer() const { return IsNullPtr;}
1559
1560 unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1561 unsigned getLValueVersion() const { return Base.getVersion(); }
1562
1563 void moveInto(APValue &V) const {
1564 if (Designator.Invalid)
1565 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
1566 else {
1567 assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1568 V = APValue(Base, Offset, Designator.Entries,
1569 Designator.IsOnePastTheEnd, IsNullPtr);
1570 }
1571 if (AllowConstexprUnknown)
1572 V.setConstexprUnknown();
1573 }
1574 void setFrom(const ASTContext &Ctx, const APValue &V) {
1575 assert(V.isLValue() && "Setting LValue from a non-LValue?");
1576 Base = V.getLValueBase();
1577 Offset = V.getLValueOffset();
1578 InvalidBase = false;
1579 Designator = SubobjectDesignator(Ctx, V);
1580 IsNullPtr = V.isNullPointer();
1581 AllowConstexprUnknown = V.allowConstexprUnknown();
1582 }
1583
1584 void set(APValue::LValueBase B, bool BInvalid = false) {
1585#ifndef NDEBUG
1586 // We only allow a few types of invalid bases. Enforce that here.
1587 if (BInvalid) {
1588 const auto *E = B.get<const Expr *>();
1589 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1590 "Unexpected type of invalid base");
1591 }
1592#endif
1593
1594 Base = B;
1595 Offset = CharUnits::fromQuantity(0);
1596 InvalidBase = BInvalid;
1597 Designator = SubobjectDesignator(getType(B));
1598 IsNullPtr = false;
1599 AllowConstexprUnknown = false;
1600 }
1601
1602 void setNull(ASTContext &Ctx, QualType PointerTy) {
1603 Base = (const ValueDecl *)nullptr;
1604 Offset =
1606 InvalidBase = false;
1607 Designator = SubobjectDesignator(PointerTy->getPointeeType());
1608 IsNullPtr = true;
1609 AllowConstexprUnknown = false;
1610 }
1611
1612 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1613 set(B, true);
1614 }
1615
1616 std::string toString(ASTContext &Ctx, QualType T) const {
1617 APValue Printable;
1618 moveInto(Printable);
1619 return Printable.getAsString(Ctx, T);
1620 }
1621
1622 private:
1623 // Check that this LValue is not based on a null pointer. If it is, produce
1624 // a diagnostic and mark the designator as invalid.
1625 template <typename GenDiagType>
1626 bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
1627 if (Designator.Invalid)
1628 return false;
1629 if (IsNullPtr) {
1630 GenDiag();
1631 Designator.setInvalid();
1632 return false;
1633 }
1634 return true;
1635 }
1636
1637 public:
1638 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1639 CheckSubobjectKind CSK) {
1640 return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1641 Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1642 });
1643 }
1644
1645 bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1646 AccessKinds AK) {
1647 return checkNullPointerDiagnosingWith([&Info, E, AK] {
1648 if (AK == AccessKinds::AK_Dereference)
1649 Info.FFDiag(E, diag::note_constexpr_dereferencing_null);
1650 else
1651 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1652 });
1653 }
1654
1655 // Check this LValue refers to an object. If not, set the designator to be
1656 // invalid and emit a diagnostic.
1657 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1658 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1659 Designator.checkSubobject(Info, E, CSK);
1660 }
1661
1662 void addDecl(EvalInfo &Info, const Expr *E,
1663 const Decl *D, bool Virtual = false) {
1664 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1665 Designator.addDeclUnchecked(D, Virtual);
1666 }
1667 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1668 if (!Designator.Entries.empty()) {
1669 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1670 Designator.setInvalid();
1671 return;
1672 }
1673 if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1674 assert(getType(Base).getNonReferenceType()->isPointerType() ||
1675 getType(Base).getNonReferenceType()->isArrayType());
1676 Designator.FirstEntryIsAnUnsizedArray = true;
1677 Designator.addUnsizedArrayUnchecked(ElemTy);
1678 }
1679 }
1680 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1681 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1682 Designator.addArrayUnchecked(CAT);
1683 }
1684 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1685 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1686 Designator.addComplexUnchecked(EltTy, Imag);
1687 }
1688 void addVectorElement(EvalInfo &Info, const Expr *E, QualType EltTy,
1689 uint64_t Size, uint64_t Idx) {
1690 if (checkSubobject(Info, E, CSK_VectorElement))
1691 Designator.addVectorElementUnchecked(EltTy, Size, Idx);
1692 }
1693 void clearIsNullPointer() {
1694 IsNullPtr = false;
1695 }
1696 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1697 const APSInt &Index, CharUnits ElementSize) {
1698 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1699 // but we're not required to diagnose it and it's valid in C++.)
1700 if (!Index)
1701 return;
1702
1703 // Compute the new offset in the appropriate width, wrapping at 64 bits.
1704 // FIXME: When compiling for a 32-bit target, we should use 32-bit
1705 // offsets.
1706 uint64_t Offset64 = Offset.getQuantity();
1707 uint64_t ElemSize64 = ElementSize.getQuantity();
1708 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1709 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1710
1711 if (checkNullPointer(Info, E, CSK_ArrayIndex))
1712 Designator.adjustIndex(Info, E, Index, *this);
1713 clearIsNullPointer();
1714 }
1715 void adjustOffset(CharUnits N) {
1716 Offset += N;
1717 if (N.getQuantity())
1718 clearIsNullPointer();
1719 }
1720 };
1721
1722 struct MemberPtr {
1723 MemberPtr() {}
1724 explicit MemberPtr(const ValueDecl *Decl)
1725 : DeclAndIsDerivedMember(Decl, false) {}
1726
1727 /// The member or (direct or indirect) field referred to by this member
1728 /// pointer, or 0 if this is a null member pointer.
1729 const ValueDecl *getDecl() const {
1730 return DeclAndIsDerivedMember.getPointer();
1731 }
1732 /// Is this actually a member of some type derived from the relevant class?
1733 bool isDerivedMember() const {
1734 return DeclAndIsDerivedMember.getInt();
1735 }
1736 /// Get the class which the declaration actually lives in.
1737 const CXXRecordDecl *getContainingRecord() const {
1738 return cast<CXXRecordDecl>(
1739 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1740 }
1741
1742 void moveInto(APValue &V) const {
1743 V = APValue(getDecl(), isDerivedMember(), Path);
1744 }
1745 void setFrom(const APValue &V) {
1746 assert(V.isMemberPointer());
1747 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1748 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1749 Path.clear();
1750 llvm::append_range(Path, V.getMemberPointerPath());
1751 }
1752
1753 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1754 /// whether the member is a member of some class derived from the class type
1755 /// of the member pointer.
1756 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1757 /// Path - The path of base/derived classes from the member declaration's
1758 /// class (exclusive) to the class type of the member pointer (inclusive).
1759 SmallVector<const CXXRecordDecl*, 4> Path;
1760
1761 /// Perform a cast towards the class of the Decl (either up or down the
1762 /// hierarchy).
1763 bool castBack(const CXXRecordDecl *Class) {
1764 assert(!Path.empty());
1765 const CXXRecordDecl *Expected;
1766 if (Path.size() >= 2)
1767 Expected = Path[Path.size() - 2];
1768 else
1769 Expected = getContainingRecord();
1770 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1771 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1772 // if B does not contain the original member and is not a base or
1773 // derived class of the class containing the original member, the result
1774 // of the cast is undefined.
1775 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1776 // (D::*). We consider that to be a language defect.
1777 return false;
1778 }
1779 Path.pop_back();
1780 return true;
1781 }
1782 /// Perform a base-to-derived member pointer cast.
1783 bool castToDerived(const CXXRecordDecl *Derived) {
1784 if (!getDecl())
1785 return true;
1786 if (!isDerivedMember()) {
1787 Path.push_back(Derived);
1788 return true;
1789 }
1790 if (!castBack(Derived))
1791 return false;
1792 if (Path.empty())
1793 DeclAndIsDerivedMember.setInt(false);
1794 return true;
1795 }
1796 /// Perform a derived-to-base member pointer cast.
1797 bool castToBase(const CXXRecordDecl *Base) {
1798 if (!getDecl())
1799 return true;
1800 if (Path.empty())
1801 DeclAndIsDerivedMember.setInt(true);
1802 if (isDerivedMember()) {
1803 Path.push_back(Base);
1804 return true;
1805 }
1806 return castBack(Base);
1807 }
1808 };
1809
1810 /// Compare two member pointers, which are assumed to be of the same type.
1811 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1812 if (!LHS.getDecl() || !RHS.getDecl())
1813 return !LHS.getDecl() && !RHS.getDecl();
1814 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1815 return false;
1816 return LHS.Path == RHS.Path;
1817 }
1818}
1819
1820void SubobjectDesignator::adjustIndex(EvalInfo &Info, const Expr *E, APSInt N,
1821 const LValue &LV) {
1822 if (Invalid || !N)
1823 return;
1824 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
1825 if (isMostDerivedAnUnsizedArray()) {
1826 diagnoseUnsizedArrayPointerArithmetic(Info, E);
1827 // Can't verify -- trust that the user is doing the right thing (or if
1828 // not, trust that the caller will catch the bad behavior).
1829 // FIXME: Should we reject if this overflows, at least?
1830 Entries.back() =
1831 PathEntry::ArrayIndex(Entries.back().getAsArrayIndex() + TruncatedN);
1832 return;
1833 }
1834
1835 // [expr.add]p4: For the purposes of these operators, a pointer to a
1836 // nonarray object behaves the same as a pointer to the first element of
1837 // an array of length one with the type of the object as its element type.
1838 bool IsArray =
1839 MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement;
1840 uint64_t ArrayIndex =
1841 IsArray ? Entries.back().getAsArrayIndex() : (uint64_t)IsOnePastTheEnd;
1842 uint64_t ArraySize = IsArray ? getMostDerivedArraySize() : (uint64_t)1;
1843
1844 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
1845 if (!Info.checkingPotentialConstantExpression() ||
1846 !LV.AllowConstexprUnknown) {
1847 // Calculate the actual index in a wide enough type, so we can include
1848 // it in the note.
1849 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
1850 (llvm::APInt &)N += ArrayIndex;
1851 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
1852 diagnosePointerArithmetic(Info, E, N);
1853 }
1854 setInvalid();
1855 return;
1856 }
1857
1858 ArrayIndex += TruncatedN;
1859 assert(ArrayIndex <= ArraySize &&
1860 "bounds check succeeded for out-of-bounds index");
1861
1862 if (IsArray)
1863 Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
1864 else
1865 IsOnePastTheEnd = (ArrayIndex != 0);
1866}
1867
1868static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1869static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1870 const LValue &This, const Expr *E,
1871 bool AllowNonLiteralTypes = false);
1872static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1873 bool InvalidBaseOK = false);
1874static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1875 bool InvalidBaseOK = false);
1876static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1877 EvalInfo &Info);
1878static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1879static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1880static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1881 EvalInfo &Info);
1882static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1883static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1884static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1885 EvalInfo &Info);
1886static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1887static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,
1888 EvalInfo &Info,
1889 std::string *StringResult = nullptr);
1890
1891/// Evaluate an integer or fixed point expression into an APResult.
1892static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1893 EvalInfo &Info);
1894
1895/// Evaluate only a fixed point expression into an APResult.
1896static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1897 EvalInfo &Info);
1898
1899//===----------------------------------------------------------------------===//
1900// Misc utilities
1901//===----------------------------------------------------------------------===//
1902
1903/// Negate an APSInt in place, converting it to a signed form if necessary, and
1904/// preserving its value (by extending by up to one bit as needed).
1905static void negateAsSigned(APSInt &Int) {
1906 if (Int.isUnsigned() || Int.isMinSignedValue()) {
1907 Int = Int.extend(Int.getBitWidth() + 1);
1908 Int.setIsSigned(true);
1909 }
1910 Int = -Int;
1911}
1912
1913template<typename KeyT>
1914APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T,
1915 ScopeKind Scope, LValue &LV) {
1916 unsigned Version = getTempVersion();
1917 APValue::LValueBase Base(Key, Index, Version);
1918 LV.set(Base);
1919 return createLocal(Base, Key, T, Scope);
1920}
1921
1922/// Allocate storage for a parameter of a function call made in this frame.
1923APValue &CallStackFrame::createParam(CallRef Args, const ParmVarDecl *PVD,
1924 LValue &LV) {
1925 assert(Args.CallIndex == Index && "creating parameter in wrong frame");
1926 APValue::LValueBase Base(PVD, Index, Args.Version);
1927 LV.set(Base);
1928 // We always destroy parameters at the end of the call, even if we'd allow
1929 // them to live to the end of the full-expression at runtime, in order to
1930 // give portable results and match other compilers.
1931 return createLocal(Base, PVD, PVD->getType(), ScopeKind::Call);
1932}
1933
1934APValue &CallStackFrame::createLocal(APValue::LValueBase Base, const void *Key,
1935 QualType T, ScopeKind Scope) {
1936 assert(Base.getCallIndex() == Index && "lvalue for wrong frame");
1937 unsigned Version = Base.getVersion();
1938 APValue &Result = Temporaries[MapKeyTy(Key, Version)];
1939 assert(Result.isAbsent() && "local created multiple times");
1940
1941 // If we're creating a local immediately in the operand of a speculative
1942 // evaluation, don't register a cleanup to be run outside the speculative
1943 // evaluation context, since we won't actually be able to initialize this
1944 // object.
1945 if (Index <= Info.SpeculativeEvaluationDepth) {
1946 if (T.isDestructedType())
1947 Info.noteSideEffect();
1948 } else {
1949 Info.CleanupStack.push_back(Cleanup(&Result, Base, T, Scope));
1950 }
1951 return Result;
1952}
1953
1954APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) {
1955 if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) {
1956 FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded);
1957 return nullptr;
1958 }
1959
1960 DynamicAllocLValue DA(NumHeapAllocs++);
1962 auto Result = HeapAllocs.emplace(std::piecewise_construct,
1963 std::forward_as_tuple(DA), std::tuple<>());
1964 assert(Result.second && "reused a heap alloc index?");
1965 Result.first->second.AllocExpr = E;
1966 return &Result.first->second.Value;
1967}
1968
1969/// Produce a string describing the given constexpr call.
1970void CallStackFrame::describe(raw_ostream &Out) const {
1971 unsigned ArgIndex = 0;
1972 bool IsMemberCall =
1973 isa<CXXMethodDecl>(Callee) && !isa<CXXConstructorDecl>(Callee) &&
1974 cast<CXXMethodDecl>(Callee)->isImplicitObjectMemberFunction();
1975
1976 if (!IsMemberCall)
1977 Callee->getNameForDiagnostic(Out, Info.Ctx.getPrintingPolicy(),
1978 /*Qualified=*/false);
1979
1980 if (This && IsMemberCall) {
1981 if (const auto *MCE = dyn_cast_if_present<CXXMemberCallExpr>(CallExpr)) {
1982 const Expr *Object = MCE->getImplicitObjectArgument();
1983 Object->printPretty(Out, /*Helper=*/nullptr, Info.Ctx.getPrintingPolicy(),
1984 /*Indentation=*/0);
1985 if (Object->getType()->isPointerType())
1986 Out << "->";
1987 else
1988 Out << ".";
1989 } else if (const auto *OCE =
1990 dyn_cast_if_present<CXXOperatorCallExpr>(CallExpr)) {
1991 OCE->getArg(0)->printPretty(Out, /*Helper=*/nullptr,
1992 Info.Ctx.getPrintingPolicy(),
1993 /*Indentation=*/0);
1994 Out << ".";
1995 } else {
1996 APValue Val;
1997 This->moveInto(Val);
1998 Val.printPretty(
1999 Out, Info.Ctx,
2000 Info.Ctx.getLValueReferenceType(This->Designator.MostDerivedType));
2001 Out << ".";
2002 }
2003 Callee->getNameForDiagnostic(Out, Info.Ctx.getPrintingPolicy(),
2004 /*Qualified=*/false);
2005 IsMemberCall = false;
2006 }
2007
2008 Out << '(';
2009
2010 for (FunctionDecl::param_const_iterator I = Callee->param_begin(),
2011 E = Callee->param_end(); I != E; ++I, ++ArgIndex) {
2012 if (ArgIndex > (unsigned)IsMemberCall)
2013 Out << ", ";
2014
2015 const ParmVarDecl *Param = *I;
2016 APValue *V = Info.getParamSlot(Arguments, Param);
2017 if (V)
2018 V->printPretty(Out, Info.Ctx, Param->getType());
2019 else
2020 Out << "<...>";
2021
2022 if (ArgIndex == 0 && IsMemberCall)
2023 Out << "->" << *Callee << '(';
2024 }
2025
2026 Out << ')';
2027}
2028
2029/// Evaluate an expression to see if it had side-effects, and discard its
2030/// result.
2031/// \return \c true if the caller should keep evaluating.
2032static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
2033 assert(!E->isValueDependent());
2034 APValue Scratch;
2035 if (!Evaluate(Scratch, Info, E))
2036 // We don't need the value, but we might have skipped a side effect here.
2037 return Info.noteSideEffect();
2038 return true;
2039}
2040
2041/// Should this call expression be treated as forming an opaque constant?
2042static bool IsOpaqueConstantCall(const CallExpr *E) {
2043 unsigned Builtin = E->getBuiltinCallee();
2044 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
2045 Builtin == Builtin::BI__builtin___NSStringMakeConstantString ||
2046 Builtin == Builtin::BI__builtin_ptrauth_sign_constant ||
2047 Builtin == Builtin::BI__builtin_function_start);
2048}
2049
2050static bool IsOpaqueConstantCall(const LValue &LVal) {
2051 const auto *BaseExpr =
2052 llvm::dyn_cast_if_present<CallExpr>(LVal.Base.dyn_cast<const Expr *>());
2053 return BaseExpr && IsOpaqueConstantCall(BaseExpr);
2054}
2055
2057 // C++11 [expr.const]p3 An address constant expression is a prvalue core
2058 // constant expression of pointer type that evaluates to...
2059
2060 // ... a null pointer value, or a prvalue core constant expression of type
2061 // std::nullptr_t.
2062 if (!B)
2063 return true;
2064
2065 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
2066 // ... the address of an object with static storage duration,
2067 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
2068 return VD->hasGlobalStorage();
2070 return true;
2071 // ... the address of a function,
2072 // ... the address of a GUID [MS extension],
2073 // ... the address of an unnamed global constant
2075 }
2076
2077 if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>())
2078 return true;
2079
2080 const Expr *E = B.get<const Expr*>();
2081 switch (E->getStmtClass()) {
2082 default:
2083 return false;
2084 case Expr::CompoundLiteralExprClass: {
2086 return CLE->isFileScope() && CLE->isLValue();
2087 }
2088 case Expr::MaterializeTemporaryExprClass:
2089 // A materialized temporary might have been lifetime-extended to static
2090 // storage duration.
2091 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
2092 // A string literal has static storage duration.
2093 case Expr::StringLiteralClass:
2094 case Expr::PredefinedExprClass:
2095 case Expr::ObjCStringLiteralClass:
2096 case Expr::ObjCEncodeExprClass:
2097 return true;
2098 case Expr::ObjCBoxedExprClass:
2099 return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
2100 case Expr::CallExprClass:
2102 // For GCC compatibility, &&label has static storage duration.
2103 case Expr::AddrLabelExprClass:
2104 return true;
2105 // A Block literal expression may be used as the initialization value for
2106 // Block variables at global or local static scope.
2107 case Expr::BlockExprClass:
2108 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
2109 // The APValue generated from a __builtin_source_location will be emitted as a
2110 // literal.
2111 case Expr::SourceLocExprClass:
2112 return true;
2113 case Expr::ImplicitValueInitExprClass:
2114 // FIXME:
2115 // We can never form an lvalue with an implicit value initialization as its
2116 // base through expression evaluation, so these only appear in one case: the
2117 // implicit variable declaration we invent when checking whether a constexpr
2118 // constructor can produce a constant expression. We must assume that such
2119 // an expression might be a global lvalue.
2120 return true;
2121 }
2122}
2123
2124static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
2125 return LVal.Base.dyn_cast<const ValueDecl*>();
2126}
2127
2128// Information about an LValueBase that is some kind of string.
2131 StringRef Bytes;
2133};
2134
2135// Gets the lvalue base of LVal as a string.
2136static bool GetLValueBaseAsString(const EvalInfo &Info, const LValue &LVal,
2137 LValueBaseString &AsString) {
2138 const auto *BaseExpr = LVal.Base.dyn_cast<const Expr *>();
2139 if (!BaseExpr)
2140 return false;
2141
2142 // For ObjCEncodeExpr, we need to compute and store the string.
2143 if (const auto *EE = dyn_cast<ObjCEncodeExpr>(BaseExpr)) {
2144 Info.Ctx.getObjCEncodingForType(EE->getEncodedType(),
2145 AsString.ObjCEncodeStorage);
2146 AsString.Bytes = AsString.ObjCEncodeStorage;
2147 AsString.CharWidth = 1;
2148 return true;
2149 }
2150
2151 // Otherwise, we have a StringLiteral.
2152 const auto *Lit = dyn_cast<StringLiteral>(BaseExpr);
2153 if (const auto *PE = dyn_cast<PredefinedExpr>(BaseExpr))
2154 Lit = PE->getFunctionName();
2155
2156 if (!Lit)
2157 return false;
2158
2159 AsString.Bytes = Lit->getBytes();
2160 AsString.CharWidth = Lit->getCharByteWidth();
2161 return true;
2162}
2163
2164// Determine whether two string literals potentially overlap. This will be the
2165// case if they agree on the values of all the bytes on the overlapping region
2166// between them.
2167//
2168// The overlapping region is the portion of the two string literals that must
2169// overlap in memory if the pointers actually point to the same address at
2170// runtime. For example, if LHS is "abcdef" + 3 and RHS is "cdef\0gh" + 1 then
2171// the overlapping region is "cdef\0", which in this case does agree, so the
2172// strings are potentially overlapping. Conversely, for "foobar" + 3 versus
2173// "bazbar" + 3, the overlapping region contains all of both strings, so they
2174// are not potentially overlapping, even though they agree from the given
2175// addresses onwards.
2176//
2177// See open core issue CWG2765 which is discussing the desired rule here.
2178static bool ArePotentiallyOverlappingStringLiterals(const EvalInfo &Info,
2179 const LValue &LHS,
2180 const LValue &RHS) {
2181 LValueBaseString LHSString, RHSString;
2182 if (!GetLValueBaseAsString(Info, LHS, LHSString) ||
2183 !GetLValueBaseAsString(Info, RHS, RHSString))
2184 return false;
2185
2186 // This is the byte offset to the location of the first character of LHS
2187 // within RHS. We don't need to look at the characters of one string that
2188 // would appear before the start of the other string if they were merged.
2189 CharUnits Offset = RHS.Offset - LHS.Offset;
2190 if (Offset.isNegative()) {
2191 if (LHSString.Bytes.size() < (size_t)-Offset.getQuantity())
2192 return false;
2193 LHSString.Bytes = LHSString.Bytes.drop_front(-Offset.getQuantity());
2194 } else {
2195 if (RHSString.Bytes.size() < (size_t)Offset.getQuantity())
2196 return false;
2197 RHSString.Bytes = RHSString.Bytes.drop_front(Offset.getQuantity());
2198 }
2199
2200 bool LHSIsLonger = LHSString.Bytes.size() > RHSString.Bytes.size();
2201 StringRef Longer = LHSIsLonger ? LHSString.Bytes : RHSString.Bytes;
2202 StringRef Shorter = LHSIsLonger ? RHSString.Bytes : LHSString.Bytes;
2203 int ShorterCharWidth = (LHSIsLonger ? RHSString : LHSString).CharWidth;
2204
2205 // The null terminator isn't included in the string data, so check for it
2206 // manually. If the longer string doesn't have a null terminator where the
2207 // shorter string ends, they aren't potentially overlapping.
2208 for (int NullByte : llvm::seq(ShorterCharWidth)) {
2209 if (Shorter.size() + NullByte >= Longer.size())
2210 break;
2211 if (Longer[Shorter.size() + NullByte])
2212 return false;
2213 }
2214
2215 // Otherwise, they're potentially overlapping if and only if the overlapping
2216 // region is the same.
2217 return Shorter == Longer.take_front(Shorter.size());
2218}
2219
2220static bool IsWeakLValue(const LValue &Value) {
2222 return Decl && Decl->isWeak();
2223}
2224
2225static bool isZeroSized(const LValue &Value) {
2227 if (isa_and_nonnull<VarDecl>(Decl)) {
2228 QualType Ty = Decl->getType();
2229 if (Ty->isArrayType())
2230 return Ty->isIncompleteType() ||
2231 Decl->getASTContext().getTypeSize(Ty) == 0;
2232 }
2233 return false;
2234}
2235
2236static bool HasSameBase(const LValue &A, const LValue &B) {
2237 if (!A.getLValueBase())
2238 return !B.getLValueBase();
2239 if (!B.getLValueBase())
2240 return false;
2241
2242 if (A.getLValueBase().getOpaqueValue() !=
2243 B.getLValueBase().getOpaqueValue())
2244 return false;
2245
2246 return A.getLValueCallIndex() == B.getLValueCallIndex() &&
2247 A.getLValueVersion() == B.getLValueVersion();
2248}
2249
2250static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
2251 assert(Base && "no location for a null lvalue");
2252 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2253
2254 // For a parameter, find the corresponding call stack frame (if it still
2255 // exists), and point at the parameter of the function definition we actually
2256 // invoked.
2257 if (auto *PVD = dyn_cast_or_null<ParmVarDecl>(VD)) {
2258 unsigned Idx = PVD->getFunctionScopeIndex();
2259 for (CallStackFrame *F = Info.CurrentCall; F; F = F->Caller) {
2260 if (F->Arguments.CallIndex == Base.getCallIndex() &&
2261 F->Arguments.Version == Base.getVersion() && F->Callee &&
2262 Idx < F->Callee->getNumParams()) {
2263 VD = F->Callee->getParamDecl(Idx);
2264 break;
2265 }
2266 }
2267 }
2268
2269 if (VD)
2270 Info.Note(VD->getLocation(), diag::note_declared_at);
2271 else if (const Expr *E = Base.dyn_cast<const Expr*>())
2272 Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
2273 else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
2274 // FIXME: Produce a note for dangling pointers too.
2275 if (std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA))
2276 Info.Note((*Alloc)->AllocExpr->getExprLoc(),
2277 diag::note_constexpr_dynamic_alloc_here);
2278 }
2279
2280 // We have no information to show for a typeid(T) object.
2281}
2282
2287
2288/// Materialized temporaries that we've already checked to determine if they're
2289/// initializsed by a constant expression.
2292
2294 EvalInfo &Info, SourceLocation DiagLoc,
2295 QualType Type, const APValue &Value,
2296 ConstantExprKind Kind,
2297 const FieldDecl *SubobjectDecl,
2298 CheckedTemporaries &CheckedTemps);
2299
2300/// Check that this reference or pointer core constant expression is a valid
2301/// value for an address or reference constant expression. Return true if we
2302/// can fold this expression, whether or not it's a constant expression.
2303static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
2304 QualType Type, const LValue &LVal,
2305 ConstantExprKind Kind,
2306 CheckedTemporaries &CheckedTemps) {
2307 bool IsReferenceType = Type->isReferenceType();
2308
2309 APValue::LValueBase Base = LVal.getLValueBase();
2310 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
2311
2312 const Expr *BaseE = Base.dyn_cast<const Expr *>();
2313 const ValueDecl *BaseVD = Base.dyn_cast<const ValueDecl*>();
2314
2315 // Additional restrictions apply in a template argument. We only enforce the
2316 // C++20 restrictions here; additional syntactic and semantic restrictions
2317 // are applied elsewhere.
2318 if (isTemplateArgument(Kind)) {
2319 int InvalidBaseKind = -1;
2320 StringRef Ident;
2321 if (Base.is<TypeInfoLValue>())
2322 InvalidBaseKind = 0;
2323 else if (isa_and_nonnull<StringLiteral>(BaseE))
2324 InvalidBaseKind = 1;
2325 else if (isa_and_nonnull<MaterializeTemporaryExpr>(BaseE) ||
2326 isa_and_nonnull<LifetimeExtendedTemporaryDecl>(BaseVD))
2327 InvalidBaseKind = 2;
2328 else if (auto *PE = dyn_cast_or_null<PredefinedExpr>(BaseE)) {
2329 InvalidBaseKind = 3;
2330 Ident = PE->getIdentKindName();
2331 }
2332
2333 if (InvalidBaseKind != -1) {
2334 Info.FFDiag(Loc, diag::note_constexpr_invalid_template_arg)
2335 << IsReferenceType << !Designator.Entries.empty() << InvalidBaseKind
2336 << Ident;
2337 return false;
2338 }
2339 }
2340
2341 if (auto *FD = dyn_cast_or_null<FunctionDecl>(BaseVD);
2342 FD && FD->isImmediateFunction()) {
2343 Info.FFDiag(Loc, diag::note_consteval_address_accessible)
2344 << !Type->isAnyPointerType();
2345 Info.Note(FD->getLocation(), diag::note_declared_at);
2346 return false;
2347 }
2348
2349 // Check that the object is a global. Note that the fake 'this' object we
2350 // manufacture when checking potential constant expressions is conservatively
2351 // assumed to be global here.
2352 if (!IsGlobalLValue(Base)) {
2353 if (Info.getLangOpts().CPlusPlus11) {
2354 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
2355 << IsReferenceType << !Designator.Entries.empty() << !!BaseVD
2356 << BaseVD;
2357 auto *VarD = dyn_cast_or_null<VarDecl>(BaseVD);
2358 if (VarD && VarD->isConstexpr()) {
2359 // Non-static local constexpr variables have unintuitive semantics:
2360 // constexpr int a = 1;
2361 // constexpr const int *p = &a;
2362 // ... is invalid because the address of 'a' is not constant. Suggest
2363 // adding a 'static' in this case.
2364 Info.Note(VarD->getLocation(), diag::note_constexpr_not_static)
2365 << VarD
2366 << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static ");
2367 } else {
2368 NoteLValueLocation(Info, Base);
2369 }
2370 } else {
2371 Info.FFDiag(Loc);
2372 }
2373 // Don't allow references to temporaries to escape.
2374 return false;
2375 }
2376 assert((Info.checkingPotentialConstantExpression() ||
2377 LVal.getLValueCallIndex() == 0) &&
2378 "have call index for global lvalue");
2379
2380 if (LVal.allowConstexprUnknown()) {
2381 if (BaseVD) {
2382 Info.FFDiag(Loc, diag::note_constexpr_var_init_non_constant, 1) << BaseVD;
2383 NoteLValueLocation(Info, Base);
2384 } else {
2385 Info.FFDiag(Loc);
2386 }
2387 return false;
2388 }
2389
2390 if (Base.is<DynamicAllocLValue>()) {
2391 Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc)
2392 << IsReferenceType << !Designator.Entries.empty();
2393 NoteLValueLocation(Info, Base);
2394 return false;
2395 }
2396
2397 if (BaseVD) {
2398 if (const VarDecl *Var = dyn_cast<const VarDecl>(BaseVD)) {
2399 // Check if this is a thread-local variable.
2400 if (Var->getTLSKind())
2401 // FIXME: Diagnostic!
2402 return false;
2403
2404 // A dllimport variable never acts like a constant, unless we're
2405 // evaluating a value for use only in name mangling.
2406 if (!isForManglingOnly(Kind) && Var->hasAttr<DLLImportAttr>())
2407 // FIXME: Diagnostic!
2408 return false;
2409
2410 // In CUDA/HIP device compilation, only device side variables have
2411 // constant addresses.
2412 if (Info.getASTContext().getLangOpts().CUDA &&
2413 Info.getASTContext().getLangOpts().CUDAIsDevice &&
2414 Info.getASTContext().CUDAConstantEvalCtx.NoWrongSidedVars) {
2415 if ((!Var->hasAttr<CUDADeviceAttr>() &&
2416 !Var->hasAttr<CUDAConstantAttr>() &&
2417 !Var->getType()->isCUDADeviceBuiltinSurfaceType() &&
2418 !Var->getType()->isCUDADeviceBuiltinTextureType()) ||
2419 Var->hasAttr<HIPManagedAttr>())
2420 return false;
2421 }
2422 }
2423 if (const auto *FD = dyn_cast<const FunctionDecl>(BaseVD)) {
2424 // __declspec(dllimport) must be handled very carefully:
2425 // We must never initialize an expression with the thunk in C++.
2426 // Doing otherwise would allow the same id-expression to yield
2427 // different addresses for the same function in different translation
2428 // units. However, this means that we must dynamically initialize the
2429 // expression with the contents of the import address table at runtime.
2430 //
2431 // The C language has no notion of ODR; furthermore, it has no notion of
2432 // dynamic initialization. This means that we are permitted to
2433 // perform initialization with the address of the thunk.
2434 if (Info.getLangOpts().CPlusPlus && !isForManglingOnly(Kind) &&
2435 FD->hasAttr<DLLImportAttr>())
2436 // FIXME: Diagnostic!
2437 return false;
2438 }
2439 } else if (const auto *MTE =
2440 dyn_cast_or_null<MaterializeTemporaryExpr>(BaseE)) {
2441 if (CheckedTemps.insert(MTE).second) {
2442 QualType TempType = getType(Base);
2443 if (TempType.isDestructedType()) {
2444 Info.FFDiag(MTE->getExprLoc(),
2445 diag::note_constexpr_unsupported_temporary_nontrivial_dtor)
2446 << TempType;
2447 return false;
2448 }
2449
2450 APValue *V = MTE->getOrCreateValue(false);
2451 assert(V && "evasluation result refers to uninitialised temporary");
2453 Info, MTE->getExprLoc(), TempType, *V, Kind,
2454 /*SubobjectDecl=*/nullptr, CheckedTemps))
2455 return false;
2456 }
2457 }
2458
2459 // Allow address constant expressions to be past-the-end pointers. This is
2460 // an extension: the standard requires them to point to an object.
2461 if (!IsReferenceType)
2462 return true;
2463
2464 // A reference constant expression must refer to an object.
2465 if (!Base) {
2466 // FIXME: diagnostic
2467 Info.CCEDiag(Loc);
2468 return true;
2469 }
2470
2471 // Does this refer one past the end of some object?
2472 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
2473 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
2474 << !Designator.Entries.empty() << !!BaseVD << BaseVD;
2475 NoteLValueLocation(Info, Base);
2476 }
2477
2478 return true;
2479}
2480
2481/// Member pointers are constant expressions unless they point to a
2482/// non-virtual dllimport member function.
2483static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
2484 SourceLocation Loc,
2485 QualType Type,
2486 const APValue &Value,
2487 ConstantExprKind Kind) {
2488 const ValueDecl *Member = Value.getMemberPointerDecl();
2489 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
2490 if (!FD)
2491 return true;
2492 if (FD->isImmediateFunction()) {
2493 Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0;
2494 Info.Note(FD->getLocation(), diag::note_declared_at);
2495 return false;
2496 }
2497 return isForManglingOnly(Kind) || FD->isVirtual() ||
2498 !FD->hasAttr<DLLImportAttr>();
2499}
2500
2501/// Check that this core constant expression is of literal type, and if not,
2502/// produce an appropriate diagnostic.
2503static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
2504 const LValue *This = nullptr) {
2505 // The restriction to literal types does not exist in C++23 anymore.
2506 if (Info.getLangOpts().CPlusPlus23)
2507 return true;
2508
2509 if (!E->isPRValue() || E->getType()->isLiteralType(Info.Ctx))
2510 return true;
2511
2512 // C++1y: A constant initializer for an object o [...] may also invoke
2513 // constexpr constructors for o and its subobjects even if those objects
2514 // are of non-literal class types.
2515 //
2516 // C++11 missed this detail for aggregates, so classes like this:
2517 // struct foo_t { union { int i; volatile int j; } u; };
2518 // are not (obviously) initializable like so:
2519 // __attribute__((__require_constant_initialization__))
2520 // static const foo_t x = {{0}};
2521 // because "i" is a subobject with non-literal initialization (due to the
2522 // volatile member of the union). See:
2523 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2524 // Therefore, we use the C++1y behavior.
2525 if (This && Info.EvaluatingDecl == This->getLValueBase())
2526 return true;
2527
2528 // Prvalue constant expressions must be of literal types.
2529 if (Info.getLangOpts().CPlusPlus11)
2530 Info.FFDiag(E, diag::note_constexpr_nonliteral)
2531 << E->getType();
2532 else
2533 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2534 return false;
2535}
2536
2538 EvalInfo &Info, SourceLocation DiagLoc,
2539 QualType Type, const APValue &Value,
2540 ConstantExprKind Kind,
2541 const FieldDecl *SubobjectDecl,
2542 CheckedTemporaries &CheckedTemps) {
2543 if (!Value.hasValue()) {
2544 if (SubobjectDecl) {
2545 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2546 << /*(name)*/ 1 << SubobjectDecl;
2547 Info.Note(SubobjectDecl->getLocation(),
2548 diag::note_constexpr_subobject_declared_here);
2549 } else {
2550 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2551 << /*of type*/ 0 << Type;
2552 }
2553 return false;
2554 }
2555
2556 // We allow _Atomic(T) to be initialized from anything that T can be
2557 // initialized from.
2558 if (const AtomicType *AT = Type->getAs<AtomicType>())
2559 Type = AT->getValueType();
2560
2561 // Core issue 1454: For a literal constant expression of array or class type,
2562 // each subobject of its value shall have been initialized by a constant
2563 // expression.
2564 if (Value.isArray()) {
2566 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
2567 if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2568 Value.getArrayInitializedElt(I), Kind,
2569 SubobjectDecl, CheckedTemps))
2570 return false;
2571 }
2572 if (!Value.hasArrayFiller())
2573 return true;
2574 return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2575 Value.getArrayFiller(), Kind, SubobjectDecl,
2576 CheckedTemps);
2577 }
2578 if (Value.isUnion() && Value.getUnionField()) {
2579 return CheckEvaluationResult(
2580 CERK, Info, DiagLoc, Value.getUnionField()->getType(),
2581 Value.getUnionValue(), Kind, Value.getUnionField(), CheckedTemps);
2582 }
2583 if (Value.isStruct()) {
2584 auto *RD = Type->castAsRecordDecl();
2585 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2586 unsigned BaseIndex = 0;
2587 for (const CXXBaseSpecifier &BS : CD->bases()) {
2588 const APValue &BaseValue = Value.getStructBase(BaseIndex);
2589 if (!BaseValue.hasValue()) {
2590 SourceLocation TypeBeginLoc = BS.getBaseTypeLoc();
2591 Info.FFDiag(TypeBeginLoc, diag::note_constexpr_uninitialized_base)
2592 << BS.getType() << SourceRange(TypeBeginLoc, BS.getEndLoc());
2593 return false;
2594 }
2595 if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(), BaseValue,
2596 Kind, /*SubobjectDecl=*/nullptr,
2597 CheckedTemps))
2598 return false;
2599 ++BaseIndex;
2600 }
2601 }
2602 for (const auto *I : RD->fields()) {
2603 if (I->isUnnamedBitField())
2604 continue;
2605
2606 if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),
2607 Value.getStructField(I->getFieldIndex()), Kind,
2608 I, CheckedTemps))
2609 return false;
2610 }
2611 }
2612
2613 if (Value.isLValue() &&
2615 LValue LVal;
2616 LVal.setFrom(Info.Ctx, Value);
2617 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Kind,
2618 CheckedTemps);
2619 }
2620
2621 if (Value.isMemberPointer() &&
2623 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Kind);
2624
2625 // Everything else is fine.
2626 return true;
2627}
2628
2629/// Check that this core constant expression value is a valid value for a
2630/// constant expression. If not, report an appropriate diagnostic. Does not
2631/// check that the expression is of literal type.
2632static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
2633 QualType Type, const APValue &Value,
2634 ConstantExprKind Kind) {
2635 // Nothing to check for a constant expression of type 'cv void'.
2636 if (Type->isVoidType())
2637 return true;
2638
2639 CheckedTemporaries CheckedTemps;
2641 Info, DiagLoc, Type, Value, Kind,
2642 /*SubobjectDecl=*/nullptr, CheckedTemps);
2643}
2644
2645/// Check that this evaluated value is fully-initialized and can be loaded by
2646/// an lvalue-to-rvalue conversion.
2647static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,
2648 QualType Type, const APValue &Value) {
2649 CheckedTemporaries CheckedTemps;
2650 return CheckEvaluationResult(
2652 ConstantExprKind::Normal, /*SubobjectDecl=*/nullptr, CheckedTemps);
2653}
2654
2655/// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless
2656/// "the allocated storage is deallocated within the evaluation".
2657static bool CheckMemoryLeaks(EvalInfo &Info) {
2658 if (!Info.HeapAllocs.empty()) {
2659 // We can still fold to a constant despite a compile-time memory leak,
2660 // so long as the heap allocation isn't referenced in the result (we check
2661 // that in CheckConstantExpression).
2662 Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr,
2663 diag::note_constexpr_memory_leak)
2664 << unsigned(Info.HeapAllocs.size() - 1);
2665 }
2666 return true;
2667}
2668
2669static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
2670 // A null base expression indicates a null pointer. These are always
2671 // evaluatable, and they are false unless the offset is zero.
2672 if (!Value.getLValueBase()) {
2673 // TODO: Should a non-null pointer with an offset of zero evaluate to true?
2674 Result = !Value.getLValueOffset().isZero();
2675 return true;
2676 }
2677
2678 // We have a non-null base. These are generally known to be true, but if it's
2679 // a weak declaration it can be null at runtime.
2680 Result = true;
2681 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
2682 return !Decl || !Decl->isWeak();
2683}
2684
2685static bool HandleConversionToBool(const APValue &Val, bool &Result) {
2686 // TODO: This function should produce notes if it fails.
2687 switch (Val.getKind()) {
2688 case APValue::None:
2690 return false;
2691 case APValue::Int:
2692 Result = Val.getInt().getBoolValue();
2693 return true;
2695 Result = Val.getFixedPoint().getBoolValue();
2696 return true;
2697 case APValue::Float:
2698 Result = !Val.getFloat().isZero();
2699 return true;
2701 Result = Val.getComplexIntReal().getBoolValue() ||
2702 Val.getComplexIntImag().getBoolValue();
2703 return true;
2705 Result = !Val.getComplexFloatReal().isZero() ||
2706 !Val.getComplexFloatImag().isZero();
2707 return true;
2708 case APValue::LValue:
2709 return EvalPointerValueAsBool(Val, Result);
2711 if (Val.getMemberPointerDecl() && Val.getMemberPointerDecl()->isWeak()) {
2712 return false;
2713 }
2714 Result = Val.getMemberPointerDecl();
2715 return true;
2716 case APValue::Vector:
2717 case APValue::Array:
2718 case APValue::Struct:
2719 case APValue::Union:
2721 return false;
2722 }
2723
2724 llvm_unreachable("unknown APValue kind");
2725}
2726
2727static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2728 EvalInfo &Info) {
2729 assert(!E->isValueDependent());
2730 assert(E->isPRValue() && "missing lvalue-to-rvalue conv in bool condition");
2731 APValue Val;
2732 if (!Evaluate(Val, Info, E))
2733 return false;
2734 return HandleConversionToBool(Val, Result);
2735}
2736
2737template<typename T>
2738static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2739 const T &SrcValue, QualType DestType) {
2740 Info.CCEDiag(E, diag::note_constexpr_overflow)
2741 << SrcValue << DestType;
2742 return Info.noteUndefinedBehavior();
2743}
2744
2745static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2746 QualType SrcType, const APFloat &Value,
2747 QualType DestType, APSInt &Result) {
2748 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2749 // Determine whether we are converting to unsigned or signed.
2750 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2751
2752 Result = APSInt(DestWidth, !DestSigned);
2753 bool ignored;
2754 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2755 & APFloat::opInvalidOp)
2756 return HandleOverflow(Info, E, Value, DestType);
2757 return true;
2758}
2759
2760/// Get rounding mode to use in evaluation of the specified expression.
2761///
2762/// If rounding mode is unknown at compile time, still try to evaluate the
2763/// expression. If the result is exact, it does not depend on rounding mode.
2764/// So return "tonearest" mode instead of "dynamic".
2765static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E) {
2766 llvm::RoundingMode RM =
2768 if (RM == llvm::RoundingMode::Dynamic)
2769 RM = llvm::RoundingMode::NearestTiesToEven;
2770 return RM;
2771}
2772
2773/// Check if the given evaluation result is allowed for constant evaluation.
2774static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E,
2775 APFloat::opStatus St) {
2776 // In a constant context, assume that any dynamic rounding mode or FP
2777 // exception state matches the default floating-point environment.
2778 if (Info.InConstantContext)
2779 return true;
2780
2781 FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
2782 if ((St & APFloat::opInexact) &&
2783 FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) {
2784 // Inexact result means that it depends on rounding mode. If the requested
2785 // mode is dynamic, the evaluation cannot be made in compile time.
2786 Info.FFDiag(E, diag::note_constexpr_dynamic_rounding);
2787 return false;
2788 }
2789
2790 if ((St != APFloat::opOK) &&
2791 (FPO.getRoundingMode() == llvm::RoundingMode::Dynamic ||
2793 FPO.getAllowFEnvAccess())) {
2794 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
2795 return false;
2796 }
2797
2798 if ((St & APFloat::opStatus::opInvalidOp) &&
2800 // There is no usefully definable result.
2801 Info.FFDiag(E);
2802 return false;
2803 }
2804
2805 // FIXME: if:
2806 // - evaluation triggered other FP exception, and
2807 // - exception mode is not "ignore", and
2808 // - the expression being evaluated is not a part of global variable
2809 // initializer,
2810 // the evaluation probably need to be rejected.
2811 return true;
2812}
2813
2814static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2815 QualType SrcType, QualType DestType,
2816 APFloat &Result) {
2817 assert((isa<CastExpr>(E) || isa<CompoundAssignOperator>(E) ||
2819 "HandleFloatToFloatCast has been checked with only CastExpr, "
2820 "CompoundAssignOperator and ConvertVectorExpr. Please either validate "
2821 "the new expression or address the root cause of this usage.");
2822 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2823 APFloat::opStatus St;
2824 APFloat Value = Result;
2825 bool ignored;
2826 St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored);
2827 return checkFloatingPointResult(Info, E, St);
2828}
2829
2830static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2831 QualType DestType, QualType SrcType,
2832 const APSInt &Value) {
2833 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2834 // Figure out if this is a truncate, extend or noop cast.
2835 // If the input is signed, do a sign extend, noop, or truncate.
2836 APSInt Result = Value.extOrTrunc(DestWidth);
2837 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2838 if (DestType->isBooleanType())
2839 Result = Value.getBoolValue();
2840 return Result;
2841}
2842
2843static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2844 const FPOptions FPO,
2845 QualType SrcType, const APSInt &Value,
2846 QualType DestType, APFloat &Result) {
2847 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2848 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2849 APFloat::opStatus St = Result.convertFromAPInt(Value, Value.isSigned(), RM);
2850 return checkFloatingPointResult(Info, E, St);
2851}
2852
2853static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2854 APValue &Value, const FieldDecl *FD) {
2855 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2856
2857 if (!Value.isInt()) {
2858 // Trying to store a pointer-cast-to-integer into a bitfield.
2859 // FIXME: In this case, we should provide the diagnostic for casting
2860 // a pointer to an integer.
2861 assert(Value.isLValue() && "integral value neither int nor lvalue?");
2862 Info.FFDiag(E);
2863 return false;
2864 }
2865
2866 APSInt &Int = Value.getInt();
2867 unsigned OldBitWidth = Int.getBitWidth();
2868 unsigned NewBitWidth = FD->getBitWidthValue();
2869 if (NewBitWidth < OldBitWidth)
2870 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2871 return true;
2872}
2873
2874/// Perform the given integer operation, which is known to need at most BitWidth
2875/// bits, and check for overflow in the original type (if that type was not an
2876/// unsigned type).
2877template<typename Operation>
2878static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2879 const APSInt &LHS, const APSInt &RHS,
2880 unsigned BitWidth, Operation Op,
2881 APSInt &Result) {
2882 if (LHS.isUnsigned()) {
2883 Result = Op(LHS, RHS);
2884 return true;
2885 }
2886
2887 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2888 Result = Value.trunc(LHS.getBitWidth());
2889 if (Result.extend(BitWidth) != Value) {
2890 if (Info.checkingForUndefinedBehavior())
2891 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2892 diag::warn_integer_constant_overflow)
2893 << toString(Result, 10, Result.isSigned(), /*formatAsCLiteral=*/false,
2894 /*UpperCase=*/true, /*InsertSeparators=*/true)
2895 << E->getType() << E->getSourceRange();
2896 return HandleOverflow(Info, E, Value, E->getType());
2897 }
2898 return true;
2899}
2900
2901/// Perform the given binary integer operation.
2902static bool handleIntIntBinOp(EvalInfo &Info, const BinaryOperator *E,
2903 const APSInt &LHS, BinaryOperatorKind Opcode,
2904 APSInt RHS, APSInt &Result) {
2905 bool HandleOverflowResult = true;
2906 switch (Opcode) {
2907 default:
2908 Info.FFDiag(E);
2909 return false;
2910 case BO_Mul:
2911 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2912 std::multiplies<APSInt>(), Result);
2913 case BO_Add:
2914 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2915 std::plus<APSInt>(), Result);
2916 case BO_Sub:
2917 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2918 std::minus<APSInt>(), Result);
2919 case BO_And: Result = LHS & RHS; return true;
2920 case BO_Xor: Result = LHS ^ RHS; return true;
2921 case BO_Or: Result = LHS | RHS; return true;
2922 case BO_Div:
2923 case BO_Rem:
2924 if (RHS == 0) {
2925 Info.FFDiag(E, diag::note_expr_divide_by_zero)
2926 << E->getRHS()->getSourceRange();
2927 return false;
2928 }
2929 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2930 // this operation and gives the two's complement result.
2931 if (RHS.isNegative() && RHS.isAllOnes() && LHS.isSigned() &&
2932 LHS.isMinSignedValue())
2933 HandleOverflowResult = HandleOverflow(
2934 Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
2935 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2936 return HandleOverflowResult;
2937 case BO_Shl: {
2938 if (Info.getLangOpts().OpenCL)
2939 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2940 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2941 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2942 RHS.isUnsigned());
2943 else if (RHS.isSigned() && RHS.isNegative()) {
2944 // During constant-folding, a negative shift is an opposite shift. Such
2945 // a shift is not a constant expression.
2946 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2947 if (!Info.noteUndefinedBehavior())
2948 return false;
2949 RHS = -RHS;
2950 goto shift_right;
2951 }
2952 shift_left:
2953 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2954 // the shifted type.
2955 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2956 if (SA != RHS) {
2957 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2958 << RHS << E->getType() << LHS.getBitWidth();
2959 if (!Info.noteUndefinedBehavior())
2960 return false;
2961 } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) {
2962 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2963 // operand, and must not overflow the corresponding unsigned type.
2964 // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2965 // E1 x 2^E2 module 2^N.
2966 if (LHS.isNegative()) {
2967 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2968 if (!Info.noteUndefinedBehavior())
2969 return false;
2970 } else if (LHS.countl_zero() < SA) {
2971 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2972 if (!Info.noteUndefinedBehavior())
2973 return false;
2974 }
2975 }
2976 Result = LHS << SA;
2977 return true;
2978 }
2979 case BO_Shr: {
2980 if (Info.getLangOpts().OpenCL)
2981 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2982 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2983 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2984 RHS.isUnsigned());
2985 else if (RHS.isSigned() && RHS.isNegative()) {
2986 // During constant-folding, a negative shift is an opposite shift. Such a
2987 // shift is not a constant expression.
2988 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2989 if (!Info.noteUndefinedBehavior())
2990 return false;
2991 RHS = -RHS;
2992 goto shift_left;
2993 }
2994 shift_right:
2995 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2996 // shifted type.
2997 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2998 if (SA != RHS) {
2999 Info.CCEDiag(E, diag::note_constexpr_large_shift)
3000 << RHS << E->getType() << LHS.getBitWidth();
3001 if (!Info.noteUndefinedBehavior())
3002 return false;
3003 }
3004
3005 Result = LHS >> SA;
3006 return true;
3007 }
3008
3009 case BO_LT: Result = LHS < RHS; return true;
3010 case BO_GT: Result = LHS > RHS; return true;
3011 case BO_LE: Result = LHS <= RHS; return true;
3012 case BO_GE: Result = LHS >= RHS; return true;
3013 case BO_EQ: Result = LHS == RHS; return true;
3014 case BO_NE: Result = LHS != RHS; return true;
3015 case BO_Cmp:
3016 llvm_unreachable("BO_Cmp should be handled elsewhere");
3017 }
3018}
3019
3020/// Perform the given binary floating-point operation, in-place, on LHS.
3021static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E,
3022 APFloat &LHS, BinaryOperatorKind Opcode,
3023 const APFloat &RHS) {
3024 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
3025 APFloat::opStatus St;
3026 switch (Opcode) {
3027 default:
3028 Info.FFDiag(E);
3029 return false;
3030 case BO_Mul:
3031 St = LHS.multiply(RHS, RM);
3032 break;
3033 case BO_Add:
3034 St = LHS.add(RHS, RM);
3035 break;
3036 case BO_Sub:
3037 St = LHS.subtract(RHS, RM);
3038 break;
3039 case BO_Div:
3040 // [expr.mul]p4:
3041 // If the second operand of / or % is zero the behavior is undefined.
3042 if (RHS.isZero())
3043 Info.CCEDiag(E, diag::note_expr_divide_by_zero);
3044 St = LHS.divide(RHS, RM);
3045 break;
3046 }
3047
3048 // [expr.pre]p4:
3049 // If during the evaluation of an expression, the result is not
3050 // mathematically defined [...], the behavior is undefined.
3051 // FIXME: C++ rules require us to not conform to IEEE 754 here.
3052 if (LHS.isNaN()) {
3053 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
3054 return Info.noteUndefinedBehavior();
3055 }
3056
3057 return checkFloatingPointResult(Info, E, St);
3058}
3059
3060static bool handleLogicalOpForVector(const APInt &LHSValue,
3061 BinaryOperatorKind Opcode,
3062 const APInt &RHSValue, APInt &Result) {
3063 bool LHS = (LHSValue != 0);
3064 bool RHS = (RHSValue != 0);
3065
3066 if (Opcode == BO_LAnd)
3067 Result = LHS && RHS;
3068 else
3069 Result = LHS || RHS;
3070 return true;
3071}
3072static bool handleLogicalOpForVector(const APFloat &LHSValue,
3073 BinaryOperatorKind Opcode,
3074 const APFloat &RHSValue, APInt &Result) {
3075 bool LHS = !LHSValue.isZero();
3076 bool RHS = !RHSValue.isZero();
3077
3078 if (Opcode == BO_LAnd)
3079 Result = LHS && RHS;
3080 else
3081 Result = LHS || RHS;
3082 return true;
3083}
3084
3085static bool handleLogicalOpForVector(const APValue &LHSValue,
3086 BinaryOperatorKind Opcode,
3087 const APValue &RHSValue, APInt &Result) {
3088 // The result is always an int type, however operands match the first.
3089 if (LHSValue.getKind() == APValue::Int)
3090 return handleLogicalOpForVector(LHSValue.getInt(), Opcode,
3091 RHSValue.getInt(), Result);
3092 assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
3093 return handleLogicalOpForVector(LHSValue.getFloat(), Opcode,
3094 RHSValue.getFloat(), Result);
3095}
3096
3097template <typename APTy>
3098static bool
3100 const APTy &RHSValue, APInt &Result) {
3101 switch (Opcode) {
3102 default:
3103 llvm_unreachable("unsupported binary operator");
3104 case BO_EQ:
3105 Result = (LHSValue == RHSValue);
3106 break;
3107 case BO_NE:
3108 Result = (LHSValue != RHSValue);
3109 break;
3110 case BO_LT:
3111 Result = (LHSValue < RHSValue);
3112 break;
3113 case BO_GT:
3114 Result = (LHSValue > RHSValue);
3115 break;
3116 case BO_LE:
3117 Result = (LHSValue <= RHSValue);
3118 break;
3119 case BO_GE:
3120 Result = (LHSValue >= RHSValue);
3121 break;
3122 }
3123
3124 // The boolean operations on these vector types use an instruction that
3125 // results in a mask of '-1' for the 'truth' value. Ensure that we negate 1
3126 // to -1 to make sure that we produce the correct value.
3127 Result.negate();
3128
3129 return true;
3130}
3131
3132static bool handleCompareOpForVector(const APValue &LHSValue,
3133 BinaryOperatorKind Opcode,
3134 const APValue &RHSValue, APInt &Result) {
3135 // The result is always an int type, however operands match the first.
3136 if (LHSValue.getKind() == APValue::Int)
3137 return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode,
3138 RHSValue.getInt(), Result);
3139 assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
3140 return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode,
3141 RHSValue.getFloat(), Result);
3142}
3143
3144// Perform binary operations for vector types, in place on the LHS.
3145static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E,
3146 BinaryOperatorKind Opcode,
3147 APValue &LHSValue,
3148 const APValue &RHSValue) {
3149 assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI &&
3150 "Operation not supported on vector types");
3151
3152 const auto *VT = E->getType()->castAs<VectorType>();
3153 unsigned NumElements = VT->getNumElements();
3154 QualType EltTy = VT->getElementType();
3155
3156 // In the cases (typically C as I've observed) where we aren't evaluating
3157 // constexpr but are checking for cases where the LHS isn't yet evaluatable,
3158 // just give up.
3159 if (!LHSValue.isVector()) {
3160 assert(LHSValue.isLValue() &&
3161 "A vector result that isn't a vector OR uncalculated LValue");
3162 Info.FFDiag(E);
3163 return false;
3164 }
3165
3166 assert(LHSValue.getVectorLength() == NumElements &&
3167 RHSValue.getVectorLength() == NumElements && "Different vector sizes");
3168
3169 SmallVector<APValue, 4> ResultElements;
3170
3171 for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) {
3172 APValue LHSElt = LHSValue.getVectorElt(EltNum);
3173 APValue RHSElt = RHSValue.getVectorElt(EltNum);
3174
3175 if (EltTy->isIntegerType()) {
3176 APSInt EltResult{Info.Ctx.getIntWidth(EltTy),
3177 EltTy->isUnsignedIntegerType()};
3178 bool Success = true;
3179
3180 if (BinaryOperator::isLogicalOp(Opcode))
3181 Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3182 else if (BinaryOperator::isComparisonOp(Opcode))
3183 Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3184 else
3185 Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode,
3186 RHSElt.getInt(), EltResult);
3187
3188 if (!Success) {
3189 Info.FFDiag(E);
3190 return false;
3191 }
3192 ResultElements.emplace_back(EltResult);
3193
3194 } else if (EltTy->isFloatingType()) {
3195 assert(LHSElt.getKind() == APValue::Float &&
3196 RHSElt.getKind() == APValue::Float &&
3197 "Mismatched LHS/RHS/Result Type");
3198 APFloat LHSFloat = LHSElt.getFloat();
3199
3200 if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode,
3201 RHSElt.getFloat())) {
3202 Info.FFDiag(E);
3203 return false;
3204 }
3205
3206 ResultElements.emplace_back(LHSFloat);
3207 }
3208 }
3209
3210 LHSValue = APValue(ResultElements.data(), ResultElements.size());
3211 return true;
3212}
3213
3214/// Cast an lvalue referring to a base subobject to a derived class, by
3215/// truncating the lvalue's path to the given length.
3216static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
3217 const RecordDecl *TruncatedType,
3218 unsigned TruncatedElements) {
3219 SubobjectDesignator &D = Result.Designator;
3220
3221 // Check we actually point to a derived class object.
3222 if (TruncatedElements == D.Entries.size())
3223 return true;
3224 assert(TruncatedElements >= D.MostDerivedPathLength &&
3225 "not casting to a derived class");
3226 if (!Result.checkSubobject(Info, E, CSK_Derived))
3227 return false;
3228
3229 // Truncate the path to the subobject, and remove any derived-to-base offsets.
3230 const RecordDecl *RD = TruncatedType;
3231 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
3232 if (RD->isInvalidDecl()) return false;
3233 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3234 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
3235 if (isVirtualBaseClass(D.Entries[I]))
3236 Result.Offset -= Layout.getVBaseClassOffset(Base);
3237 else
3238 Result.Offset -= Layout.getBaseClassOffset(Base);
3239 RD = Base;
3240 }
3241 D.Entries.resize(TruncatedElements);
3242 return true;
3243}
3244
3245static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3246 const CXXRecordDecl *Derived,
3247 const CXXRecordDecl *Base,
3248 const ASTRecordLayout *RL = nullptr) {
3249 if (!RL) {
3250 if (Derived->isInvalidDecl()) return false;
3251 RL = &Info.Ctx.getASTRecordLayout(Derived);
3252 }
3253
3254 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
3255 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
3256 return true;
3257}
3258
3259static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3260 const CXXRecordDecl *DerivedDecl,
3261 const CXXBaseSpecifier *Base) {
3262 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
3263
3264 if (!Base->isVirtual())
3265 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
3266
3267 SubobjectDesignator &D = Obj.Designator;
3268 if (D.Invalid)
3269 return false;
3270
3271 // Extract most-derived object and corresponding type.
3272 // FIXME: After implementing P2280R4 it became possible to get references
3273 // here. We do MostDerivedType->getAsCXXRecordDecl() in several other
3274 // locations and if we see crashes in those locations in the future
3275 // it may make more sense to move this fix into Lvalue::set.
3276 DerivedDecl = D.MostDerivedType.getNonReferenceType()->getAsCXXRecordDecl();
3277 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
3278 return false;
3279
3280 // Find the virtual base class.
3281 if (DerivedDecl->isInvalidDecl()) return false;
3282 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
3283 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
3284 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
3285 return true;
3286}
3287
3288static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
3289 QualType Type, LValue &Result) {
3290 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3291 PathE = E->path_end();
3292 PathI != PathE; ++PathI) {
3293 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3294 *PathI))
3295 return false;
3296 Type = (*PathI)->getType();
3297 }
3298 return true;
3299}
3300
3301/// Cast an lvalue referring to a derived class to a known base subobject.
3302static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
3303 const CXXRecordDecl *DerivedRD,
3304 const CXXRecordDecl *BaseRD) {
3305 CXXBasePaths Paths(/*FindAmbiguities=*/false,
3306 /*RecordPaths=*/true, /*DetectVirtual=*/false);
3307 if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
3308 llvm_unreachable("Class must be derived from the passed in base class!");
3309
3310 for (CXXBasePathElement &Elem : Paths.front())
3311 if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
3312 return false;
3313 return true;
3314}
3315
3316/// Update LVal to refer to the given field, which must be a member of the type
3317/// currently described by LVal.
3318static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
3319 const FieldDecl *FD,
3320 const ASTRecordLayout *RL = nullptr) {
3321 if (!RL) {
3322 if (FD->getParent()->isInvalidDecl()) return false;
3323 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
3324 }
3325
3326 unsigned I = FD->getFieldIndex();
3327 LVal.addDecl(Info, E, FD);
3328 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
3329 return true;
3330}
3331
3332/// Update LVal to refer to the given indirect field.
3333static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
3334 LValue &LVal,
3335 const IndirectFieldDecl *IFD) {
3336 for (const auto *C : IFD->chain())
3337 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
3338 return false;
3339 return true;
3340}
3341
3346
3347/// Get the size of the given type in char units.
3348static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, QualType Type,
3350 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
3351 // extension.
3352 if (Type->isVoidType() || Type->isFunctionType()) {
3353 Size = CharUnits::One();
3354 return true;
3355 }
3356
3357 if (Type->isDependentType()) {
3358 Info.FFDiag(Loc);
3359 return false;
3360 }
3361
3362 if (!Type->isConstantSizeType()) {
3363 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
3364 // FIXME: Better diagnostic.
3365 Info.FFDiag(Loc);
3366 return false;
3367 }
3368
3369 if (SOT == SizeOfType::SizeOf)
3370 Size = Info.Ctx.getTypeSizeInChars(Type);
3371 else
3372 Size = Info.Ctx.getTypeInfoDataSizeInChars(Type).Width;
3373 return true;
3374}
3375
3376/// Update a pointer value to model pointer arithmetic.
3377/// \param Info - Information about the ongoing evaluation.
3378/// \param E - The expression being evaluated, for diagnostic purposes.
3379/// \param LVal - The pointer value to be updated.
3380/// \param EltTy - The pointee type represented by LVal.
3381/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
3382static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3383 LValue &LVal, QualType EltTy,
3384 APSInt Adjustment) {
3385 CharUnits SizeOfPointee;
3386 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
3387 return false;
3388
3389 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
3390 return true;
3391}
3392
3393static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3394 LValue &LVal, QualType EltTy,
3395 int64_t Adjustment) {
3396 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
3397 APSInt::get(Adjustment));
3398}
3399
3400/// Update an lvalue to refer to a component of a complex number.
3401/// \param Info - Information about the ongoing evaluation.
3402/// \param LVal - The lvalue to be updated.
3403/// \param EltTy - The complex number's component type.
3404/// \param Imag - False for the real component, true for the imaginary.
3405static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
3406 LValue &LVal, QualType EltTy,
3407 bool Imag) {
3408 if (Imag) {
3409 CharUnits SizeOfComponent;
3410 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
3411 return false;
3412 LVal.Offset += SizeOfComponent;
3413 }
3414 LVal.addComplex(Info, E, EltTy, Imag);
3415 return true;
3416}
3417
3418static bool HandleLValueVectorElement(EvalInfo &Info, const Expr *E,
3419 LValue &LVal, QualType EltTy,
3420 uint64_t Size, uint64_t Idx) {
3421 if (Idx) {
3422 CharUnits SizeOfElement;
3423 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfElement))
3424 return false;
3425 LVal.Offset += SizeOfElement * Idx;
3426 }
3427 LVal.addVectorElement(Info, E, EltTy, Size, Idx);
3428 return true;
3429}
3430
3431/// Try to evaluate the initializer for a variable declaration.
3432///
3433/// \param Info Information about the ongoing evaluation.
3434/// \param E An expression to be used when printing diagnostics.
3435/// \param VD The variable whose initializer should be obtained.
3436/// \param Version The version of the variable within the frame.
3437/// \param Frame The frame in which the variable was created. Must be null
3438/// if this variable is not local to the evaluation.
3439/// \param Result Filled in with a pointer to the value of the variable.
3440static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
3441 const VarDecl *VD, CallStackFrame *Frame,
3442 unsigned Version, APValue *&Result) {
3443 // C++23 [expr.const]p8 If we have a reference type allow unknown references
3444 // and pointers.
3445 bool AllowConstexprUnknown =
3446 Info.getLangOpts().CPlusPlus23 && VD->getType()->isReferenceType();
3447
3448 APValue::LValueBase Base(VD, Frame ? Frame->Index : 0, Version);
3449
3450 auto CheckUninitReference = [&](bool IsLocalVariable) {
3451 if (!Result || (!Result->hasValue() && VD->getType()->isReferenceType())) {
3452 // C++23 [expr.const]p8
3453 // ... For such an object that is not usable in constant expressions, the
3454 // dynamic type of the object is constexpr-unknown. For such a reference
3455 // that is not usable in constant expressions, the reference is treated
3456 // as binding to an unspecified object of the referenced type whose
3457 // lifetime and that of all subobjects includes the entire constant
3458 // evaluation and whose dynamic type is constexpr-unknown.
3459 //
3460 // Variables that are part of the current evaluation are not
3461 // constexpr-unknown.
3462 if (!AllowConstexprUnknown || IsLocalVariable) {
3463 if (!Info.checkingPotentialConstantExpression())
3464 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
3465 return false;
3466 }
3467 Result = nullptr;
3468 }
3469 return true;
3470 };
3471
3472 // If this is a local variable, dig out its value.
3473 if (Frame) {
3474 Result = Frame->getTemporary(VD, Version);
3475 if (Result)
3476 return CheckUninitReference(/*IsLocalVariable=*/true);
3477
3478 if (!isa<ParmVarDecl>(VD)) {
3479 // Assume variables referenced within a lambda's call operator that were
3480 // not declared within the call operator are captures and during checking
3481 // of a potential constant expression, assume they are unknown constant
3482 // expressions.
3483 assert(isLambdaCallOperator(Frame->Callee) &&
3484 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
3485 "missing value for local variable");
3486 if (Info.checkingPotentialConstantExpression())
3487 return false;
3488 // FIXME: This diagnostic is bogus; we do support captures. Is this code
3489 // still reachable at all?
3490 Info.FFDiag(E->getBeginLoc(),
3491 diag::note_unimplemented_constexpr_lambda_feature_ast)
3492 << "captures not currently allowed";
3493 return false;
3494 }
3495 }
3496
3497 // If we're currently evaluating the initializer of this declaration, use that
3498 // in-flight value.
3499 if (Info.EvaluatingDecl == Base) {
3500 Result = Info.EvaluatingDeclValue;
3501 return CheckUninitReference(/*IsLocalVariable=*/false);
3502 }
3503
3504 // P2280R4 struck the restriction that variable of reference type lifetime
3505 // should begin within the evaluation of E
3506 // Used to be C++20 [expr.const]p5.12.2:
3507 // ... its lifetime began within the evaluation of E;
3508 if (isa<ParmVarDecl>(VD)) {
3509 if (AllowConstexprUnknown) {
3510 Result = nullptr;
3511 return true;
3512 }
3513
3514 // Assume parameters of a potential constant expression are usable in
3515 // constant expressions.
3516 if (!Info.checkingPotentialConstantExpression() ||
3517 !Info.CurrentCall->Callee ||
3518 !Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
3519 if (Info.getLangOpts().CPlusPlus11) {
3520 Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown)
3521 << VD;
3522 NoteLValueLocation(Info, Base);
3523 } else {
3524 Info.FFDiag(E);
3525 }
3526 }
3527 return false;
3528 }
3529
3530 if (E->isValueDependent())
3531 return false;
3532
3533 // Dig out the initializer, and use the declaration which it's attached to.
3534 // FIXME: We should eventually check whether the variable has a reachable
3535 // initializing declaration.
3536 const Expr *Init = VD->getAnyInitializer(VD);
3537 // P2280R4 struck the restriction that variable of reference type should have
3538 // a preceding initialization.
3539 // Used to be C++20 [expr.const]p5.12:
3540 // ... reference has a preceding initialization and either ...
3541 if (!Init && !AllowConstexprUnknown) {
3542 // Don't diagnose during potential constant expression checking; an
3543 // initializer might be added later.
3544 if (!Info.checkingPotentialConstantExpression()) {
3545 Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1)
3546 << VD;
3547 NoteLValueLocation(Info, Base);
3548 }
3549 return false;
3550 }
3551
3552 // P2280R4 struck the initialization requirement for variables of reference
3553 // type so we can no longer assume we have an Init.
3554 // Used to be C++20 [expr.const]p5.12:
3555 // ... reference has a preceding initialization and either ...
3556 if (Init && Init->isValueDependent()) {
3557 // The DeclRefExpr is not value-dependent, but the variable it refers to
3558 // has a value-dependent initializer. This should only happen in
3559 // constant-folding cases, where the variable is not actually of a suitable
3560 // type for use in a constant expression (otherwise the DeclRefExpr would
3561 // have been value-dependent too), so diagnose that.
3562 assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx));
3563 if (!Info.checkingPotentialConstantExpression()) {
3564 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
3565 ? diag::note_constexpr_ltor_non_constexpr
3566 : diag::note_constexpr_ltor_non_integral, 1)
3567 << VD << VD->getType();
3568 NoteLValueLocation(Info, Base);
3569 }
3570 return false;
3571 }
3572
3573 // Check that we can fold the initializer. In C++, we will have already done
3574 // this in the cases where it matters for conformance.
3575 // P2280R4 struck the initialization requirement for variables of reference
3576 // type so we can no longer assume we have an Init.
3577 // Used to be C++20 [expr.const]p5.12:
3578 // ... reference has a preceding initialization and either ...
3579 if (Init && !VD->evaluateValue() && !AllowConstexprUnknown) {
3580 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3581 NoteLValueLocation(Info, Base);
3582 return false;
3583 }
3584
3585 // Check that the variable is actually usable in constant expressions. For a
3586 // const integral variable or a reference, we might have a non-constant
3587 // initializer that we can nonetheless evaluate the initializer for. Such
3588 // variables are not usable in constant expressions. In C++98, the
3589 // initializer also syntactically needs to be an ICE.
3590 //
3591 // FIXME: We don't diagnose cases that aren't potentially usable in constant
3592 // expressions here; doing so would regress diagnostics for things like
3593 // reading from a volatile constexpr variable.
3594 if ((Info.getLangOpts().CPlusPlus && !VD->hasConstantInitialization() &&
3595 VD->mightBeUsableInConstantExpressions(Info.Ctx) &&
3596 !AllowConstexprUnknown) ||
3597 ((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) &&
3598 !Info.getLangOpts().CPlusPlus11 && !VD->hasICEInitializer(Info.Ctx))) {
3599 if (Init) {
3600 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3601 NoteLValueLocation(Info, Base);
3602 } else {
3603 Info.CCEDiag(E);
3604 }
3605 }
3606
3607 // Never use the initializer of a weak variable, not even for constant
3608 // folding. We can't be sure that this is the definition that will be used.
3609 if (VD->isWeak()) {
3610 Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD;
3611 NoteLValueLocation(Info, Base);
3612 return false;
3613 }
3614
3615 Result = VD->getEvaluatedValue();
3616
3617 if (!Result && !AllowConstexprUnknown)
3618 return false;
3619
3620 return CheckUninitReference(/*IsLocalVariable=*/false);
3621}
3622
3623/// Get the base index of the given base class within an APValue representing
3624/// the given derived class.
3625static unsigned getBaseIndex(const CXXRecordDecl *Derived,
3626 const CXXRecordDecl *Base) {
3627 Base = Base->getCanonicalDecl();
3628 unsigned Index = 0;
3630 E = Derived->bases_end(); I != E; ++I, ++Index) {
3631 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
3632 return Index;
3633 }
3634
3635 llvm_unreachable("base class missing from derived class's bases list");
3636}
3637
3638/// Extract the value of a character from a string literal.
3639static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
3640 uint64_t Index) {
3641 assert(!isa<SourceLocExpr>(Lit) &&
3642 "SourceLocExpr should have already been converted to a StringLiteral");
3643
3644 // FIXME: Support MakeStringConstant
3645 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
3646 std::string Str;
3647 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
3648 assert(Index <= Str.size() && "Index too large");
3649 return APSInt::getUnsigned(Str.c_str()[Index]);
3650 }
3651
3652 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
3653 Lit = PE->getFunctionName();
3654 const StringLiteral *S = cast<StringLiteral>(Lit);
3655 const ConstantArrayType *CAT =
3656 Info.Ctx.getAsConstantArrayType(S->getType());
3657 assert(CAT && "string literal isn't an array");
3658 QualType CharType = CAT->getElementType();
3659 assert(CharType->isIntegerType() && "unexpected character type");
3660 APSInt Value(Info.Ctx.getTypeSize(CharType),
3661 CharType->isUnsignedIntegerType());
3662 if (Index < S->getLength())
3663 Value = S->getCodeUnit(Index);
3664 return Value;
3665}
3666
3667// Expand a string literal into an array of characters.
3668//
3669// FIXME: This is inefficient; we should probably introduce something similar
3670// to the LLVM ConstantDataArray to make this cheaper.
3671static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
3672 APValue &Result,
3673 QualType AllocType = QualType()) {
3674 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
3675 AllocType.isNull() ? S->getType() : AllocType);
3676 assert(CAT && "string literal isn't an array");
3677 QualType CharType = CAT->getElementType();
3678 assert(CharType->isIntegerType() && "unexpected character type");
3679
3680 unsigned Elts = CAT->getZExtSize();
3681 Result = APValue(APValue::UninitArray(),
3682 std::min(S->getLength(), Elts), Elts);
3683 APSInt Value(Info.Ctx.getTypeSize(CharType),
3684 CharType->isUnsignedIntegerType());
3685 if (Result.hasArrayFiller())
3686 Result.getArrayFiller() = APValue(Value);
3687 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
3688 Value = S->getCodeUnit(I);
3689 Result.getArrayInitializedElt(I) = APValue(Value);
3690 }
3691}
3692
3693// Expand an array so that it has more than Index filled elements.
3694static void expandArray(APValue &Array, unsigned Index) {
3695 unsigned Size = Array.getArraySize();
3696 assert(Index < Size);
3697
3698 // Always at least double the number of elements for which we store a value.
3699 unsigned OldElts = Array.getArrayInitializedElts();
3700 unsigned NewElts = std::max(Index+1, OldElts * 2);
3701 NewElts = std::min(Size, std::max(NewElts, 8u));
3702
3703 // Copy the data across.
3704 APValue NewValue(APValue::UninitArray(), NewElts, Size);
3705 for (unsigned I = 0; I != OldElts; ++I)
3706 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
3707 for (unsigned I = OldElts; I != NewElts; ++I)
3708 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
3709 if (NewValue.hasArrayFiller())
3710 NewValue.getArrayFiller() = Array.getArrayFiller();
3711 Array.swap(NewValue);
3712}
3713
3714/// Determine whether a type would actually be read by an lvalue-to-rvalue
3715/// conversion. If it's of class type, we may assume that the copy operation
3716/// is trivial. Note that this is never true for a union type with fields
3717/// (because the copy always "reads" the active member) and always true for
3718/// a non-class type.
3719static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD);
3721 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3722 return !RD || isReadByLvalueToRvalueConversion(RD);
3723}
3725 // FIXME: A trivial copy of a union copies the object representation, even if
3726 // the union is empty.
3727 if (RD->isUnion())
3728 return !RD->field_empty();
3729 if (RD->isEmpty())
3730 return false;
3731
3732 for (auto *Field : RD->fields())
3733 if (!Field->isUnnamedBitField() &&
3734 isReadByLvalueToRvalueConversion(Field->getType()))
3735 return true;
3736
3737 for (auto &BaseSpec : RD->bases())
3738 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
3739 return true;
3740
3741 return false;
3742}
3743
3744/// Diagnose an attempt to read from any unreadable field within the specified
3745/// type, which might be a class type.
3746static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK,
3747 QualType T) {
3748 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3749 if (!RD)
3750 return false;
3751
3752 if (!RD->hasMutableFields())
3753 return false;
3754
3755 for (auto *Field : RD->fields()) {
3756 // If we're actually going to read this field in some way, then it can't
3757 // be mutable. If we're in a union, then assigning to a mutable field
3758 // (even an empty one) can change the active member, so that's not OK.
3759 // FIXME: Add core issue number for the union case.
3760 if (Field->isMutable() &&
3761 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
3762 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field;
3763 Info.Note(Field->getLocation(), diag::note_declared_at);
3764 return true;
3765 }
3766
3767 if (diagnoseMutableFields(Info, E, AK, Field->getType()))
3768 return true;
3769 }
3770
3771 for (auto &BaseSpec : RD->bases())
3772 if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType()))
3773 return true;
3774
3775 // All mutable fields were empty, and thus not actually read.
3776 return false;
3777}
3778
3779static bool lifetimeStartedInEvaluation(EvalInfo &Info,
3781 bool MutableSubobject = false) {
3782 // A temporary or transient heap allocation we created.
3783 if (Base.getCallIndex() || Base.is<DynamicAllocLValue>())
3784 return true;
3785
3786 switch (Info.IsEvaluatingDecl) {
3787 case EvalInfo::EvaluatingDeclKind::None:
3788 return false;
3789
3790 case EvalInfo::EvaluatingDeclKind::Ctor:
3791 // The variable whose initializer we're evaluating.
3792 if (Info.EvaluatingDecl == Base)
3793 return true;
3794
3795 // A temporary lifetime-extended by the variable whose initializer we're
3796 // evaluating.
3797 if (auto *BaseE = Base.dyn_cast<const Expr *>())
3798 if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
3799 return Info.EvaluatingDecl == BaseMTE->getExtendingDecl();
3800 return false;
3801
3802 case EvalInfo::EvaluatingDeclKind::Dtor:
3803 // C++2a [expr.const]p6:
3804 // [during constant destruction] the lifetime of a and its non-mutable
3805 // subobjects (but not its mutable subobjects) [are] considered to start
3806 // within e.
3807 if (MutableSubobject || Base != Info.EvaluatingDecl)
3808 return false;
3809 // FIXME: We can meaningfully extend this to cover non-const objects, but
3810 // we will need special handling: we should be able to access only
3811 // subobjects of such objects that are themselves declared const.
3813 return T.isConstQualified() || T->isReferenceType();
3814 }
3815
3816 llvm_unreachable("unknown evaluating decl kind");
3817}
3818
3819static bool CheckArraySize(EvalInfo &Info, const ConstantArrayType *CAT,
3820 SourceLocation CallLoc = {}) {
3821 return Info.CheckArraySize(
3822 CAT->getSizeExpr() ? CAT->getSizeExpr()->getBeginLoc() : CallLoc,
3823 CAT->getNumAddressingBits(Info.Ctx), CAT->getZExtSize(),
3824 /*Diag=*/true);
3825}
3826
3827namespace {
3828/// A handle to a complete object (an object that is not a subobject of
3829/// another object).
3830struct CompleteObject {
3831 /// The identity of the object.
3832 APValue::LValueBase Base;
3833 /// The value of the complete object.
3834 APValue *Value;
3835 /// The type of the complete object.
3836 QualType Type;
3837
3838 CompleteObject() : Value(nullptr) {}
3839 CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
3840 : Base(Base), Value(Value), Type(Type) {}
3841
3842 bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const {
3843 // If this isn't a "real" access (eg, if it's just accessing the type
3844 // info), allow it. We assume the type doesn't change dynamically for
3845 // subobjects of constexpr objects (even though we'd hit UB here if it
3846 // did). FIXME: Is this right?
3847 if (!isAnyAccess(AK))
3848 return true;
3849
3850 // In C++14 onwards, it is permitted to read a mutable member whose
3851 // lifetime began within the evaluation.
3852 // FIXME: Should we also allow this in C++11?
3853 if (!Info.getLangOpts().CPlusPlus14 &&
3854 AK != AccessKinds::AK_IsWithinLifetime)
3855 return false;
3856 return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);
3857 }
3858
3859 explicit operator bool() const { return !Type.isNull(); }
3860};
3861} // end anonymous namespace
3862
3863static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
3864 bool IsMutable = false) {
3865 // C++ [basic.type.qualifier]p1:
3866 // - A const object is an object of type const T or a non-mutable subobject
3867 // of a const object.
3868 if (ObjType.isConstQualified() && !IsMutable)
3869 SubobjType.addConst();
3870 // - A volatile object is an object of type const T or a subobject of a
3871 // volatile object.
3872 if (ObjType.isVolatileQualified())
3873 SubobjType.addVolatile();
3874 return SubobjType;
3875}
3876
3877/// Find the designated sub-object of an rvalue.
3878template <typename SubobjectHandler>
3879static typename SubobjectHandler::result_type
3880findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
3881 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
3882 if (Sub.Invalid)
3883 // A diagnostic will have already been produced.
3884 return handler.failed();
3885 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
3886 if (Info.getLangOpts().CPlusPlus11)
3887 Info.FFDiag(E, Sub.isOnePastTheEnd()
3888 ? diag::note_constexpr_access_past_end
3889 : diag::note_constexpr_access_unsized_array)
3890 << handler.AccessKind;
3891 else
3892 Info.FFDiag(E);
3893 return handler.failed();
3894 }
3895
3896 APValue *O = Obj.Value;
3897 QualType ObjType = Obj.Type;
3898 const FieldDecl *LastField = nullptr;
3899 const FieldDecl *VolatileField = nullptr;
3900
3901 // Walk the designator's path to find the subobject.
3902 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
3903 // Reading an indeterminate value is undefined, but assigning over one is OK.
3904 if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) ||
3905 (O->isIndeterminate() &&
3906 !isValidIndeterminateAccess(handler.AccessKind))) {
3907 // Object has ended lifetime.
3908 // If I is non-zero, some subobject (member or array element) of a
3909 // complete object has ended its lifetime, so this is valid for
3910 // IsWithinLifetime, resulting in false.
3911 if (I != 0 && handler.AccessKind == AK_IsWithinLifetime)
3912 return false;
3913 if (!Info.checkingPotentialConstantExpression())
3914 Info.FFDiag(E, diag::note_constexpr_access_uninit)
3915 << handler.AccessKind << O->isIndeterminate()
3916 << E->getSourceRange();
3917 return handler.failed();
3918 }
3919
3920 // C++ [class.ctor]p5, C++ [class.dtor]p5:
3921 // const and volatile semantics are not applied on an object under
3922 // {con,de}struction.
3923 if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
3924 ObjType->isRecordType() &&
3925 Info.isEvaluatingCtorDtor(
3926 Obj.Base, ArrayRef(Sub.Entries.begin(), Sub.Entries.begin() + I)) !=
3927 ConstructionPhase::None) {
3928 ObjType = Info.Ctx.getCanonicalType(ObjType);
3929 ObjType.removeLocalConst();
3930 ObjType.removeLocalVolatile();
3931 }
3932
3933 // If this is our last pass, check that the final object type is OK.
3934 if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
3935 // Accesses to volatile objects are prohibited.
3936 if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
3937 if (Info.getLangOpts().CPlusPlus) {
3938 int DiagKind;
3939 SourceLocation Loc;
3940 const NamedDecl *Decl = nullptr;
3941 if (VolatileField) {
3942 DiagKind = 2;
3943 Loc = VolatileField->getLocation();
3944 Decl = VolatileField;
3945 } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3946 DiagKind = 1;
3947 Loc = VD->getLocation();
3948 Decl = VD;
3949 } else {
3950 DiagKind = 0;
3951 if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3952 Loc = E->getExprLoc();
3953 }
3954 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3955 << handler.AccessKind << DiagKind << Decl;
3956 Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3957 } else {
3958 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3959 }
3960 return handler.failed();
3961 }
3962
3963 // If we are reading an object of class type, there may still be more
3964 // things we need to check: if there are any mutable subobjects, we
3965 // cannot perform this read. (This only happens when performing a trivial
3966 // copy or assignment.)
3967 if (ObjType->isRecordType() &&
3968 !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
3969 diagnoseMutableFields(Info, E, handler.AccessKind, ObjType))
3970 return handler.failed();
3971 }
3972
3973 if (I == N) {
3974 if (!handler.found(*O, ObjType))
3975 return false;
3976
3977 // If we modified a bit-field, truncate it to the right width.
3978 if (isModification(handler.AccessKind) &&
3979 LastField && LastField->isBitField() &&
3980 !truncateBitfieldValue(Info, E, *O, LastField))
3981 return false;
3982
3983 return true;
3984 }
3985
3986 LastField = nullptr;
3987 if (ObjType->isArrayType()) {
3988 // Next subobject is an array element.
3989 const ArrayType *AT = Info.Ctx.getAsArrayType(ObjType);
3991 "vla in literal type?");
3992 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3993 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT);
3994 CAT && CAT->getSize().ule(Index)) {
3995 // Note, it should not be possible to form a pointer with a valid
3996 // designator which points more than one past the end of the array.
3997 if (Info.getLangOpts().CPlusPlus11)
3998 Info.FFDiag(E, diag::note_constexpr_access_past_end)
3999 << handler.AccessKind;
4000 else
4001 Info.FFDiag(E);
4002 return handler.failed();
4003 }
4004
4005 ObjType = AT->getElementType();
4006
4007 if (O->getArrayInitializedElts() > Index)
4008 O = &O->getArrayInitializedElt(Index);
4009 else if (!isRead(handler.AccessKind)) {
4010 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT);
4011 CAT && !CheckArraySize(Info, CAT, E->getExprLoc()))
4012 return handler.failed();
4013
4014 expandArray(*O, Index);
4015 O = &O->getArrayInitializedElt(Index);
4016 } else
4017 O = &O->getArrayFiller();
4018 } else if (ObjType->isAnyComplexType()) {
4019 // Next subobject is a complex number.
4020 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
4021 if (Index > 1) {
4022 if (Info.getLangOpts().CPlusPlus11)
4023 Info.FFDiag(E, diag::note_constexpr_access_past_end)
4024 << handler.AccessKind;
4025 else
4026 Info.FFDiag(E);
4027 return handler.failed();
4028 }
4029
4030 ObjType = getSubobjectType(
4031 ObjType, ObjType->castAs<ComplexType>()->getElementType());
4032
4033 assert(I == N - 1 && "extracting subobject of scalar?");
4034 if (O->isComplexInt()) {
4035 return handler.found(Index ? O->getComplexIntImag()
4036 : O->getComplexIntReal(), ObjType);
4037 } else {
4038 assert(O->isComplexFloat());
4039 return handler.found(Index ? O->getComplexFloatImag()
4040 : O->getComplexFloatReal(), ObjType);
4041 }
4042 } else if (const auto *VT = ObjType->getAs<VectorType>()) {
4043 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
4044 unsigned NumElements = VT->getNumElements();
4045 if (Index == NumElements) {
4046 if (Info.getLangOpts().CPlusPlus11)
4047 Info.FFDiag(E, diag::note_constexpr_access_past_end)
4048 << handler.AccessKind;
4049 else
4050 Info.FFDiag(E);
4051 return handler.failed();
4052 }
4053
4054 if (Index > NumElements) {
4055 Info.CCEDiag(E, diag::note_constexpr_array_index)
4056 << Index << /*array*/ 0 << NumElements;
4057 return handler.failed();
4058 }
4059
4060 ObjType = VT->getElementType();
4061 assert(I == N - 1 && "extracting subobject of scalar?");
4062 return handler.found(O->getVectorElt(Index), ObjType);
4063 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
4064 if (Field->isMutable() &&
4065 !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) {
4066 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
4067 << handler.AccessKind << Field;
4068 Info.Note(Field->getLocation(), diag::note_declared_at);
4069 return handler.failed();
4070 }
4071
4072 // Next subobject is a class, struct or union field.
4073 RecordDecl *RD =
4074 ObjType->castAsCanonical<RecordType>()->getOriginalDecl();
4075 if (RD->isUnion()) {
4076 const FieldDecl *UnionField = O->getUnionField();
4077 if (!UnionField ||
4078 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
4079 if (I == N - 1 && handler.AccessKind == AK_Construct) {
4080 // Placement new onto an inactive union member makes it active.
4081 O->setUnion(Field, APValue());
4082 } else {
4083 // Pointer to/into inactive union member: Not within lifetime
4084 if (handler.AccessKind == AK_IsWithinLifetime)
4085 return false;
4086 // FIXME: If O->getUnionValue() is absent, report that there's no
4087 // active union member rather than reporting the prior active union
4088 // member. We'll need to fix nullptr_t to not use APValue() as its
4089 // representation first.
4090 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
4091 << handler.AccessKind << Field << !UnionField << UnionField;
4092 return handler.failed();
4093 }
4094 }
4095 O = &O->getUnionValue();
4096 } else
4097 O = &O->getStructField(Field->getFieldIndex());
4098
4099 ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
4100 LastField = Field;
4101 if (Field->getType().isVolatileQualified())
4102 VolatileField = Field;
4103 } else {
4104 // Next subobject is a base class.
4105 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
4106 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
4107 O = &O->getStructBase(getBaseIndex(Derived, Base));
4108
4109 ObjType = getSubobjectType(ObjType, Info.Ctx.getCanonicalTagType(Base));
4110 }
4111 }
4112}
4113
4114namespace {
4115struct ExtractSubobjectHandler {
4116 EvalInfo &Info;
4117 const Expr *E;
4118 APValue &Result;
4119 const AccessKinds AccessKind;
4120
4121 typedef bool result_type;
4122 bool failed() { return false; }
4123 bool found(APValue &Subobj, QualType SubobjType) {
4124 Result = Subobj;
4125 if (AccessKind == AK_ReadObjectRepresentation)
4126 return true;
4127 return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
4128 }
4129 bool found(APSInt &Value, QualType SubobjType) {
4130 Result = APValue(Value);
4131 return true;
4132 }
4133 bool found(APFloat &Value, QualType SubobjType) {
4134 Result = APValue(Value);
4135 return true;
4136 }
4137};
4138} // end anonymous namespace
4139
4140/// Extract the designated sub-object of an rvalue.
4141static bool extractSubobject(EvalInfo &Info, const Expr *E,
4142 const CompleteObject &Obj,
4143 const SubobjectDesignator &Sub, APValue &Result,
4144 AccessKinds AK = AK_Read) {
4145 assert(AK == AK_Read || AK == AK_ReadObjectRepresentation);
4146 ExtractSubobjectHandler Handler = {Info, E, Result, AK};
4147 return findSubobject(Info, E, Obj, Sub, Handler);
4148}
4149
4150namespace {
4151struct ModifySubobjectHandler {
4152 EvalInfo &Info;
4153 APValue &NewVal;
4154 const Expr *E;
4155
4156 typedef bool result_type;
4157 static const AccessKinds AccessKind = AK_Assign;
4158
4159 bool checkConst(QualType QT) {
4160 // Assigning to a const object has undefined behavior.
4161 if (QT.isConstQualified()) {
4162 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4163 return false;
4164 }
4165 return true;
4166 }
4167
4168 bool failed() { return false; }
4169 bool found(APValue &Subobj, QualType SubobjType) {
4170 if (!checkConst(SubobjType))
4171 return false;
4172 // We've been given ownership of NewVal, so just swap it in.
4173 Subobj.swap(NewVal);
4174 return true;
4175 }
4176 bool found(APSInt &Value, QualType SubobjType) {
4177 if (!checkConst(SubobjType))
4178 return false;
4179 if (!NewVal.isInt()) {
4180 // Maybe trying to write a cast pointer value into a complex?
4181 Info.FFDiag(E);
4182 return false;
4183 }
4184 Value = NewVal.getInt();
4185 return true;
4186 }
4187 bool found(APFloat &Value, QualType SubobjType) {
4188 if (!checkConst(SubobjType))
4189 return false;
4190 Value = NewVal.getFloat();
4191 return true;
4192 }
4193};
4194} // end anonymous namespace
4195
4196const AccessKinds ModifySubobjectHandler::AccessKind;
4197
4198/// Update the designated sub-object of an rvalue to the given value.
4199static bool modifySubobject(EvalInfo &Info, const Expr *E,
4200 const CompleteObject &Obj,
4201 const SubobjectDesignator &Sub,
4202 APValue &NewVal) {
4203 ModifySubobjectHandler Handler = { Info, NewVal, E };
4204 return findSubobject(Info, E, Obj, Sub, Handler);
4205}
4206
4207/// Find the position where two subobject designators diverge, or equivalently
4208/// the length of the common initial subsequence.
4209static unsigned FindDesignatorMismatch(QualType ObjType,
4210 const SubobjectDesignator &A,
4211 const SubobjectDesignator &B,
4212 bool &WasArrayIndex) {
4213 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
4214 for (/**/; I != N; ++I) {
4215 if (!ObjType.isNull() &&
4216 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
4217 // Next subobject is an array element.
4218 if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
4219 WasArrayIndex = true;
4220 return I;
4221 }
4222 if (ObjType->isAnyComplexType())
4223 ObjType = ObjType->castAs<ComplexType>()->getElementType();
4224 else
4225 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
4226 } else {
4227 if (A.Entries[I].getAsBaseOrMember() !=
4228 B.Entries[I].getAsBaseOrMember()) {
4229 WasArrayIndex = false;
4230 return I;
4231 }
4232 if (const FieldDecl *FD = getAsField(A.Entries[I]))
4233 // Next subobject is a field.
4234 ObjType = FD->getType();
4235 else
4236 // Next subobject is a base class.
4237 ObjType = QualType();
4238 }
4239 }
4240 WasArrayIndex = false;
4241 return I;
4242}
4243
4244/// Determine whether the given subobject designators refer to elements of the
4245/// same array object.
4247 const SubobjectDesignator &A,
4248 const SubobjectDesignator &B) {
4249 if (A.Entries.size() != B.Entries.size())
4250 return false;
4251
4252 bool IsArray = A.MostDerivedIsArrayElement;
4253 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
4254 // A is a subobject of the array element.
4255 return false;
4256
4257 // If A (and B) designates an array element, the last entry will be the array
4258 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
4259 // of length 1' case, and the entire path must match.
4260 bool WasArrayIndex;
4261 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
4262 return CommonLength >= A.Entries.size() - IsArray;
4263}
4264
4265/// Find the complete object to which an LValue refers.
4266static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
4267 AccessKinds AK, const LValue &LVal,
4268 QualType LValType) {
4269 if (LVal.InvalidBase) {
4270 Info.FFDiag(E);
4271 return CompleteObject();
4272 }
4273
4274 if (!LVal.Base) {
4276 Info.FFDiag(E, diag::note_constexpr_dereferencing_null);
4277 else
4278 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
4279 return CompleteObject();
4280 }
4281
4282 CallStackFrame *Frame = nullptr;
4283 unsigned Depth = 0;
4284 if (LVal.getLValueCallIndex()) {
4285 std::tie(Frame, Depth) =
4286 Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
4287 if (!Frame) {
4288 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
4289 << AK << LVal.Base.is<const ValueDecl*>();
4290 NoteLValueLocation(Info, LVal.Base);
4291 return CompleteObject();
4292 }
4293 }
4294
4295 bool IsAccess = isAnyAccess(AK);
4296
4297 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
4298 // is not a constant expression (even if the object is non-volatile). We also
4299 // apply this rule to C++98, in order to conform to the expected 'volatile'
4300 // semantics.
4301 if (isFormalAccess(AK) && LValType.isVolatileQualified()) {
4302 if (Info.getLangOpts().CPlusPlus)
4303 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
4304 << AK << LValType;
4305 else
4306 Info.FFDiag(E);
4307 return CompleteObject();
4308 }
4309
4310 // Compute value storage location and type of base object.
4311 APValue *BaseVal = nullptr;
4312 QualType BaseType = getType(LVal.Base);
4313
4314 if (Info.getLangOpts().CPlusPlus14 && LVal.Base == Info.EvaluatingDecl &&
4315 lifetimeStartedInEvaluation(Info, LVal.Base)) {
4316 // This is the object whose initializer we're evaluating, so its lifetime
4317 // started in the current evaluation.
4318 BaseVal = Info.EvaluatingDeclValue;
4319 } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) {
4320 // Allow reading from a GUID declaration.
4321 if (auto *GD = dyn_cast<MSGuidDecl>(D)) {
4322 if (isModification(AK)) {
4323 // All the remaining cases do not permit modification of the object.
4324 Info.FFDiag(E, diag::note_constexpr_modify_global);
4325 return CompleteObject();
4326 }
4327 APValue &V = GD->getAsAPValue();
4328 if (V.isAbsent()) {
4329 Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
4330 << GD->getType();
4331 return CompleteObject();
4332 }
4333 return CompleteObject(LVal.Base, &V, GD->getType());
4334 }
4335
4336 // Allow reading the APValue from an UnnamedGlobalConstantDecl.
4337 if (auto *GCD = dyn_cast<UnnamedGlobalConstantDecl>(D)) {
4338 if (isModification(AK)) {
4339 Info.FFDiag(E, diag::note_constexpr_modify_global);
4340 return CompleteObject();
4341 }
4342 return CompleteObject(LVal.Base, const_cast<APValue *>(&GCD->getValue()),
4343 GCD->getType());
4344 }
4345
4346 // Allow reading from template parameter objects.
4347 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) {
4348 if (isModification(AK)) {
4349 Info.FFDiag(E, diag::note_constexpr_modify_global);
4350 return CompleteObject();
4351 }
4352 return CompleteObject(LVal.Base, const_cast<APValue *>(&TPO->getValue()),
4353 TPO->getType());
4354 }
4355
4356 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
4357 // In C++11, constexpr, non-volatile variables initialized with constant
4358 // expressions are constant expressions too. Inside constexpr functions,
4359 // parameters are constant expressions even if they're non-const.
4360 // In C++1y, objects local to a constant expression (those with a Frame) are
4361 // both readable and writable inside constant expressions.
4362 // In C, such things can also be folded, although they are not ICEs.
4363 const VarDecl *VD = dyn_cast<VarDecl>(D);
4364 if (VD) {
4365 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
4366 VD = VDef;
4367 }
4368 if (!VD || VD->isInvalidDecl()) {
4369 Info.FFDiag(E);
4370 return CompleteObject();
4371 }
4372
4373 bool IsConstant = BaseType.isConstant(Info.Ctx);
4374 bool ConstexprVar = false;
4375 if (const auto *VD = dyn_cast_if_present<VarDecl>(
4376 Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()))
4377 ConstexprVar = VD->isConstexpr();
4378
4379 // Unless we're looking at a local variable or argument in a constexpr call,
4380 // the variable we're reading must be const (unless we are binding to a
4381 // reference).
4382 if (AK != clang::AK_Dereference && !Frame) {
4383 if (IsAccess && isa<ParmVarDecl>(VD)) {
4384 // Access of a parameter that's not associated with a frame isn't going
4385 // to work out, but we can leave it to evaluateVarDeclInit to provide a
4386 // suitable diagnostic.
4387 } else if (Info.getLangOpts().CPlusPlus14 &&
4388 lifetimeStartedInEvaluation(Info, LVal.Base)) {
4389 // OK, we can read and modify an object if we're in the process of
4390 // evaluating its initializer, because its lifetime began in this
4391 // evaluation.
4392 } else if (isModification(AK)) {
4393 // All the remaining cases do not permit modification of the object.
4394 Info.FFDiag(E, diag::note_constexpr_modify_global);
4395 return CompleteObject();
4396 } else if (VD->isConstexpr()) {
4397 // OK, we can read this variable.
4398 } else if (Info.getLangOpts().C23 && ConstexprVar) {
4399 Info.FFDiag(E);
4400 return CompleteObject();
4401 } else if (BaseType->isIntegralOrEnumerationType()) {
4402 if (!IsConstant) {
4403 if (!IsAccess)
4404 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4405 if (Info.getLangOpts().CPlusPlus) {
4406 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
4407 Info.Note(VD->getLocation(), diag::note_declared_at);
4408 } else {
4409 Info.FFDiag(E);
4410 }
4411 return CompleteObject();
4412 }
4413 } else if (!IsAccess) {
4414 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4415 } else if ((IsConstant || BaseType->isReferenceType()) &&
4416 Info.checkingPotentialConstantExpression() &&
4417 BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) {
4418 // This variable might end up being constexpr. Don't diagnose it yet.
4419 } else if (IsConstant) {
4420 // Keep evaluating to see what we can do. In particular, we support
4421 // folding of const floating-point types, in order to make static const
4422 // data members of such types (supported as an extension) more useful.
4423 if (Info.getLangOpts().CPlusPlus) {
4424 Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11
4425 ? diag::note_constexpr_ltor_non_constexpr
4426 : diag::note_constexpr_ltor_non_integral, 1)
4427 << VD << BaseType;
4428 Info.Note(VD->getLocation(), diag::note_declared_at);
4429 } else {
4430 Info.CCEDiag(E);
4431 }
4432 } else {
4433 // Never allow reading a non-const value.
4434 if (Info.getLangOpts().CPlusPlus) {
4435 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
4436 ? diag::note_constexpr_ltor_non_constexpr
4437 : diag::note_constexpr_ltor_non_integral, 1)
4438 << VD << BaseType;
4439 Info.Note(VD->getLocation(), diag::note_declared_at);
4440 } else {
4441 Info.FFDiag(E);
4442 }
4443 return CompleteObject();
4444 }
4445 }
4446
4447 // When binding to a reference, the variable does not need to be constexpr
4448 // or have constant initalization.
4449 if (AK != clang::AK_Dereference &&
4450 !evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(),
4451 BaseVal))
4452 return CompleteObject();
4453 // If evaluateVarDeclInit sees a constexpr-unknown variable, it returns
4454 // a null BaseVal. Any constexpr-unknown variable seen here is an error:
4455 // we can't access a constexpr-unknown object.
4456 if (AK != clang::AK_Dereference && !BaseVal) {
4457 if (!Info.checkingPotentialConstantExpression()) {
4458 Info.FFDiag(E, diag::note_constexpr_access_unknown_variable, 1)
4459 << AK << VD;
4460 Info.Note(VD->getLocation(), diag::note_declared_at);
4461 }
4462 return CompleteObject();
4463 }
4464 } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) {
4465 std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
4466 if (!Alloc) {
4467 Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK;
4468 return CompleteObject();
4469 }
4470 return CompleteObject(LVal.Base, &(*Alloc)->Value,
4471 LVal.Base.getDynamicAllocType());
4472 }
4473 // When binding to a reference, the variable does not need to be
4474 // within its lifetime.
4475 else if (AK != clang::AK_Dereference) {
4476 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4477
4478 if (!Frame) {
4479 if (const MaterializeTemporaryExpr *MTE =
4480 dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
4481 assert(MTE->getStorageDuration() == SD_Static &&
4482 "should have a frame for a non-global materialized temporary");
4483
4484 // C++20 [expr.const]p4: [DR2126]
4485 // An object or reference is usable in constant expressions if it is
4486 // - a temporary object of non-volatile const-qualified literal type
4487 // whose lifetime is extended to that of a variable that is usable
4488 // in constant expressions
4489 //
4490 // C++20 [expr.const]p5:
4491 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
4492 // - a non-volatile glvalue that refers to an object that is usable
4493 // in constant expressions, or
4494 // - a non-volatile glvalue of literal type that refers to a
4495 // non-volatile object whose lifetime began within the evaluation
4496 // of E;
4497 //
4498 // C++11 misses the 'began within the evaluation of e' check and
4499 // instead allows all temporaries, including things like:
4500 // int &&r = 1;
4501 // int x = ++r;
4502 // constexpr int k = r;
4503 // Therefore we use the C++14-onwards rules in C++11 too.
4504 //
4505 // Note that temporaries whose lifetimes began while evaluating a
4506 // variable's constructor are not usable while evaluating the
4507 // corresponding destructor, not even if they're of const-qualified
4508 // types.
4509 if (!MTE->isUsableInConstantExpressions(Info.Ctx) &&
4510 !lifetimeStartedInEvaluation(Info, LVal.Base)) {
4511 if (!IsAccess)
4512 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4513 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
4514 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
4515 return CompleteObject();
4516 }
4517
4518 BaseVal = MTE->getOrCreateValue(false);
4519 assert(BaseVal && "got reference to unevaluated temporary");
4520 } else if (const CompoundLiteralExpr *CLE =
4521 dyn_cast_or_null<CompoundLiteralExpr>(Base)) {
4522 // According to GCC info page:
4523 //
4524 // 6.28 Compound Literals
4525 //
4526 // As an optimization, G++ sometimes gives array compound literals
4527 // longer lifetimes: when the array either appears outside a function or
4528 // has a const-qualified type. If foo and its initializer had elements
4529 // of type char *const rather than char *, or if foo were a global
4530 // variable, the array would have static storage duration. But it is
4531 // probably safest just to avoid the use of array compound literals in
4532 // C++ code.
4533 //
4534 // Obey that rule by checking constness for converted array types.
4535 if (QualType CLETy = CLE->getType(); CLETy->isArrayType() &&
4536 !LValType->isArrayType() &&
4537 !CLETy.isConstant(Info.Ctx)) {
4538 Info.FFDiag(E);
4539 Info.Note(CLE->getExprLoc(), diag::note_declared_at);
4540 return CompleteObject();
4541 }
4542
4543 BaseVal = &CLE->getStaticValue();
4544 } else {
4545 if (!IsAccess)
4546 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4547 APValue Val;
4548 LVal.moveInto(Val);
4549 Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
4550 << AK
4551 << Val.getAsString(Info.Ctx,
4552 Info.Ctx.getLValueReferenceType(LValType));
4553 NoteLValueLocation(Info, LVal.Base);
4554 return CompleteObject();
4555 }
4556 } else if (AK != clang::AK_Dereference) {
4557 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
4558 assert(BaseVal && "missing value for temporary");
4559 }
4560 }
4561
4562 // In C++14, we can't safely access any mutable state when we might be
4563 // evaluating after an unmodeled side effect. Parameters are modeled as state
4564 // in the caller, but aren't visible once the call returns, so they can be
4565 // modified in a speculatively-evaluated call.
4566 //
4567 // FIXME: Not all local state is mutable. Allow local constant subobjects
4568 // to be read here (but take care with 'mutable' fields).
4569 unsigned VisibleDepth = Depth;
4570 if (llvm::isa_and_nonnull<ParmVarDecl>(
4571 LVal.Base.dyn_cast<const ValueDecl *>()))
4572 ++VisibleDepth;
4573 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
4574 Info.EvalStatus.HasSideEffects) ||
4575 (isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth))
4576 return CompleteObject();
4577
4578 return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
4579}
4580
4581/// Perform an lvalue-to-rvalue conversion on the given glvalue. This
4582/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
4583/// glvalue referred to by an entity of reference type.
4584///
4585/// \param Info - Information about the ongoing evaluation.
4586/// \param Conv - The expression for which we are performing the conversion.
4587/// Used for diagnostics.
4588/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
4589/// case of a non-class type).
4590/// \param LVal - The glvalue on which we are attempting to perform this action.
4591/// \param RVal - The produced value will be placed here.
4592/// \param WantObjectRepresentation - If true, we're looking for the object
4593/// representation rather than the value, and in particular,
4594/// there is no requirement that the result be fully initialized.
4595static bool
4597 const LValue &LVal, APValue &RVal,
4598 bool WantObjectRepresentation = false) {
4599 if (LVal.Designator.Invalid)
4600 return false;
4601
4602 // Check for special cases where there is no existing APValue to look at.
4603 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4604
4605 AccessKinds AK =
4606 WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;
4607
4608 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
4610 // Special-case character extraction so we don't have to construct an
4611 // APValue for the whole string.
4612 assert(LVal.Designator.Entries.size() <= 1 &&
4613 "Can only read characters from string literals");
4614 if (LVal.Designator.Entries.empty()) {
4615 // Fail for now for LValue to RValue conversion of an array.
4616 // (This shouldn't show up in C/C++, but it could be triggered by a
4617 // weird EvaluateAsRValue call from a tool.)
4618 Info.FFDiag(Conv);
4619 return false;
4620 }
4621 if (LVal.Designator.isOnePastTheEnd()) {
4622 if (Info.getLangOpts().CPlusPlus11)
4623 Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
4624 else
4625 Info.FFDiag(Conv);
4626 return false;
4627 }
4628 uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
4629 RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
4630 return true;
4631 }
4632 }
4633
4634 CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
4635 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
4636}
4637
4638/// Perform an assignment of Val to LVal. Takes ownership of Val.
4639static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
4640 QualType LValType, APValue &Val) {
4641 if (LVal.Designator.Invalid)
4642 return false;
4643
4644 if (!Info.getLangOpts().CPlusPlus14) {
4645 Info.FFDiag(E);
4646 return false;
4647 }
4648
4649 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4650 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
4651}
4652
4653namespace {
4654struct CompoundAssignSubobjectHandler {
4655 EvalInfo &Info;
4656 const CompoundAssignOperator *E;
4657 QualType PromotedLHSType;
4659 const APValue &RHS;
4660
4661 static const AccessKinds AccessKind = AK_Assign;
4662
4663 typedef bool result_type;
4664
4665 bool checkConst(QualType QT) {
4666 // Assigning to a const object has undefined behavior.
4667 if (QT.isConstQualified()) {
4668 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4669 return false;
4670 }
4671 return true;
4672 }
4673
4674 bool failed() { return false; }
4675 bool found(APValue &Subobj, QualType SubobjType) {
4676 switch (Subobj.getKind()) {
4677 case APValue::Int:
4678 return found(Subobj.getInt(), SubobjType);
4679 case APValue::Float:
4680 return found(Subobj.getFloat(), SubobjType);
4683 // FIXME: Implement complex compound assignment.
4684 Info.FFDiag(E);
4685 return false;
4686 case APValue::LValue:
4687 return foundPointer(Subobj, SubobjType);
4688 case APValue::Vector:
4689 return foundVector(Subobj, SubobjType);
4691 Info.FFDiag(E, diag::note_constexpr_access_uninit)
4692 << /*read of=*/0 << /*uninitialized object=*/1
4693 << E->getLHS()->getSourceRange();
4694 return false;
4695 default:
4696 // FIXME: can this happen?
4697 Info.FFDiag(E);
4698 return false;
4699 }
4700 }
4701
4702 bool foundVector(APValue &Value, QualType SubobjType) {
4703 if (!checkConst(SubobjType))
4704 return false;
4705
4706 if (!SubobjType->isVectorType()) {
4707 Info.FFDiag(E);
4708 return false;
4709 }
4710 return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS);
4711 }
4712
4713 bool found(APSInt &Value, QualType SubobjType) {
4714 if (!checkConst(SubobjType))
4715 return false;
4716
4717 if (!SubobjType->isIntegerType()) {
4718 // We don't support compound assignment on integer-cast-to-pointer
4719 // values.
4720 Info.FFDiag(E);
4721 return false;
4722 }
4723
4724 if (RHS.isInt()) {
4725 APSInt LHS =
4726 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
4727 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
4728 return false;
4729 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
4730 return true;
4731 } else if (RHS.isFloat()) {
4732 const FPOptions FPO = E->getFPFeaturesInEffect(
4733 Info.Ctx.getLangOpts());
4734 APFloat FValue(0.0);
4735 return HandleIntToFloatCast(Info, E, FPO, SubobjType, Value,
4736 PromotedLHSType, FValue) &&
4737 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
4738 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
4739 Value);
4740 }
4741
4742 Info.FFDiag(E);
4743 return false;
4744 }
4745 bool found(APFloat &Value, QualType SubobjType) {
4746 return checkConst(SubobjType) &&
4747 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
4748 Value) &&
4749 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
4750 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
4751 }
4752 bool foundPointer(APValue &Subobj, QualType SubobjType) {
4753 if (!checkConst(SubobjType))
4754 return false;
4755
4756 QualType PointeeType;
4757 if (const PointerType *PT = SubobjType->getAs<PointerType>())
4758 PointeeType = PT->getPointeeType();
4759
4760 if (PointeeType.isNull() || !RHS.isInt() ||
4761 (Opcode != BO_Add && Opcode != BO_Sub)) {
4762 Info.FFDiag(E);
4763 return false;
4764 }
4765
4766 APSInt Offset = RHS.getInt();
4767 if (Opcode == BO_Sub)
4768 negateAsSigned(Offset);
4769
4770 LValue LVal;
4771 LVal.setFrom(Info.Ctx, Subobj);
4772 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
4773 return false;
4774 LVal.moveInto(Subobj);
4775 return true;
4776 }
4777};
4778} // end anonymous namespace
4779
4780const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
4781
4782/// Perform a compound assignment of LVal <op>= RVal.
4783static bool handleCompoundAssignment(EvalInfo &Info,
4784 const CompoundAssignOperator *E,
4785 const LValue &LVal, QualType LValType,
4786 QualType PromotedLValType,
4787 BinaryOperatorKind Opcode,
4788 const APValue &RVal) {
4789 if (LVal.Designator.Invalid)
4790 return false;
4791
4792 if (!Info.getLangOpts().CPlusPlus14) {
4793 Info.FFDiag(E);
4794 return false;
4795 }
4796
4797 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4798 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
4799 RVal };
4800 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4801}
4802
4803namespace {
4804struct IncDecSubobjectHandler {
4805 EvalInfo &Info;
4806 const UnaryOperator *E;
4808 APValue *Old;
4809
4810 typedef bool result_type;
4811
4812 bool checkConst(QualType QT) {
4813 // Assigning to a const object has undefined behavior.
4814 if (QT.isConstQualified()) {
4815 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4816 return false;
4817 }
4818 return true;
4819 }
4820
4821 bool failed() { return false; }
4822 bool found(APValue &Subobj, QualType SubobjType) {
4823 // Stash the old value. Also clear Old, so we don't clobber it later
4824 // if we're post-incrementing a complex.
4825 if (Old) {
4826 *Old = Subobj;
4827 Old = nullptr;
4828 }
4829
4830 switch (Subobj.getKind()) {
4831 case APValue::Int:
4832 return found(Subobj.getInt(), SubobjType);
4833 case APValue::Float:
4834 return found(Subobj.getFloat(), SubobjType);
4836 return found(Subobj.getComplexIntReal(),
4837 SubobjType->castAs<ComplexType>()->getElementType()
4838 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4840 return found(Subobj.getComplexFloatReal(),
4841 SubobjType->castAs<ComplexType>()->getElementType()
4842 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4843 case APValue::LValue:
4844 return foundPointer(Subobj, SubobjType);
4845 default:
4846 // FIXME: can this happen?
4847 Info.FFDiag(E);
4848 return false;
4849 }
4850 }
4851 bool found(APSInt &Value, QualType SubobjType) {
4852 if (!checkConst(SubobjType))
4853 return false;
4854
4855 if (!SubobjType->isIntegerType()) {
4856 // We don't support increment / decrement on integer-cast-to-pointer
4857 // values.
4858 Info.FFDiag(E);
4859 return false;
4860 }
4861
4862 if (Old) *Old = APValue(Value);
4863
4864 // bool arithmetic promotes to int, and the conversion back to bool
4865 // doesn't reduce mod 2^n, so special-case it.
4866 if (SubobjType->isBooleanType()) {
4867 if (AccessKind == AK_Increment)
4868 Value = 1;
4869 else
4870 Value = !Value;
4871 return true;
4872 }
4873
4874 bool WasNegative = Value.isNegative();
4875 if (AccessKind == AK_Increment) {
4876 ++Value;
4877
4878 if (!WasNegative && Value.isNegative() && E->canOverflow()) {
4879 APSInt ActualValue(Value, /*IsUnsigned*/true);
4880 return HandleOverflow(Info, E, ActualValue, SubobjType);
4881 }
4882 } else {
4883 --Value;
4884
4885 if (WasNegative && !Value.isNegative() && E->canOverflow()) {
4886 unsigned BitWidth = Value.getBitWidth();
4887 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
4888 ActualValue.setBit(BitWidth);
4889 return HandleOverflow(Info, E, ActualValue, SubobjType);
4890 }
4891 }
4892 return true;
4893 }
4894 bool found(APFloat &Value, QualType SubobjType) {
4895 if (!checkConst(SubobjType))
4896 return false;
4897
4898 if (Old) *Old = APValue(Value);
4899
4900 APFloat One(Value.getSemantics(), 1);
4901 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
4902 APFloat::opStatus St;
4903 if (AccessKind == AK_Increment)
4904 St = Value.add(One, RM);
4905 else
4906 St = Value.subtract(One, RM);
4907 return checkFloatingPointResult(Info, E, St);
4908 }
4909 bool foundPointer(APValue &Subobj, QualType SubobjType) {
4910 if (!checkConst(SubobjType))
4911 return false;
4912
4913 QualType PointeeType;
4914 if (const PointerType *PT = SubobjType->getAs<PointerType>())
4915 PointeeType = PT->getPointeeType();
4916 else {
4917 Info.FFDiag(E);
4918 return false;
4919 }
4920
4921 LValue LVal;
4922 LVal.setFrom(Info.Ctx, Subobj);
4923 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
4924 AccessKind == AK_Increment ? 1 : -1))
4925 return false;
4926 LVal.moveInto(Subobj);
4927 return true;
4928 }
4929};
4930} // end anonymous namespace
4931
4932/// Perform an increment or decrement on LVal.
4933static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
4934 QualType LValType, bool IsIncrement, APValue *Old) {
4935 if (LVal.Designator.Invalid)
4936 return false;
4937
4938 if (!Info.getLangOpts().CPlusPlus14) {
4939 Info.FFDiag(E);
4940 return false;
4941 }
4942
4943 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
4944 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
4945 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
4946 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4947}
4948
4949/// Build an lvalue for the object argument of a member function call.
4950static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
4951 LValue &This) {
4952 if (Object->getType()->isPointerType() && Object->isPRValue())
4953 return EvaluatePointer(Object, This, Info);
4954
4955 if (Object->isGLValue())
4956 return EvaluateLValue(Object, This, Info);
4957
4958 if (Object->getType()->isLiteralType(Info.Ctx))
4959 return EvaluateTemporary(Object, This, Info);
4960
4961 if (Object->getType()->isRecordType() && Object->isPRValue())
4962 return EvaluateTemporary(Object, This, Info);
4963
4964 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
4965 return false;
4966}
4967
4968/// HandleMemberPointerAccess - Evaluate a member access operation and build an
4969/// lvalue referring to the result.
4970///
4971/// \param Info - Information about the ongoing evaluation.
4972/// \param LV - An lvalue referring to the base of the member pointer.
4973/// \param RHS - The member pointer expression.
4974/// \param IncludeMember - Specifies whether the member itself is included in
4975/// the resulting LValue subobject designator. This is not possible when
4976/// creating a bound member function.
4977/// \return The field or method declaration to which the member pointer refers,
4978/// or 0 if evaluation fails.
4979static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4980 QualType LVType,
4981 LValue &LV,
4982 const Expr *RHS,
4983 bool IncludeMember = true) {
4984 MemberPtr MemPtr;
4985 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
4986 return nullptr;
4987
4988 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
4989 // member value, the behavior is undefined.
4990 if (!MemPtr.getDecl()) {
4991 // FIXME: Specific diagnostic.
4992 Info.FFDiag(RHS);
4993 return nullptr;
4994 }
4995
4996 if (MemPtr.isDerivedMember()) {
4997 // This is a member of some derived class. Truncate LV appropriately.
4998 // The end of the derived-to-base path for the base object must match the
4999 // derived-to-base path for the member pointer.
5000 // C++23 [expr.mptr.oper]p4:
5001 // If the result of E1 is an object [...] whose most derived object does
5002 // not contain the member to which E2 refers, the behavior is undefined.
5003 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
5004 LV.Designator.Entries.size()) {
5005 Info.FFDiag(RHS);
5006 return nullptr;
5007 }
5008 unsigned PathLengthToMember =
5009 LV.Designator.Entries.size() - MemPtr.Path.size();
5010 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
5011 const CXXRecordDecl *LVDecl = getAsBaseClass(
5012 LV.Designator.Entries[PathLengthToMember + I]);
5013 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
5014 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
5015 Info.FFDiag(RHS);
5016 return nullptr;
5017 }
5018 }
5019 // MemPtr.Path only contains the base classes of the class directly
5020 // containing the member E2. It is still necessary to check that the class
5021 // directly containing the member E2 lies on the derived-to-base path of E1
5022 // to avoid incorrectly permitting member pointer access into a sibling
5023 // class of the class containing the member E2. If this class would
5024 // correspond to the most-derived class of E1, it either isn't contained in
5025 // LV.Designator.Entries or the corresponding entry refers to an array
5026 // element instead. Therefore get the most derived class directly in this
5027 // case. Otherwise the previous entry should correpond to this class.
5028 const CXXRecordDecl *LastLVDecl =
5029 (PathLengthToMember > LV.Designator.MostDerivedPathLength)
5030 ? getAsBaseClass(LV.Designator.Entries[PathLengthToMember - 1])
5031 : LV.Designator.MostDerivedType->getAsCXXRecordDecl();
5032 const CXXRecordDecl *LastMPDecl = MemPtr.getContainingRecord();
5033 if (LastLVDecl->getCanonicalDecl() != LastMPDecl->getCanonicalDecl()) {
5034 Info.FFDiag(RHS);
5035 return nullptr;
5036 }
5037
5038 // Truncate the lvalue to the appropriate derived class.
5039 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
5040 PathLengthToMember))
5041 return nullptr;
5042 } else if (!MemPtr.Path.empty()) {
5043 // Extend the LValue path with the member pointer's path.
5044 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
5045 MemPtr.Path.size() + IncludeMember);
5046
5047 // Walk down to the appropriate base class.
5048 if (const PointerType *PT = LVType->getAs<PointerType>())
5049 LVType = PT->getPointeeType();
5050 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
5051 assert(RD && "member pointer access on non-class-type expression");
5052 // The first class in the path is that of the lvalue.
5053 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
5054 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
5055 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
5056 return nullptr;
5057 RD = Base;
5058 }
5059 // Finally cast to the class containing the member.
5060 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
5061 MemPtr.getContainingRecord()))
5062 return nullptr;
5063 }
5064
5065 // Add the member. Note that we cannot build bound member functions here.
5066 if (IncludeMember) {
5067 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
5068 if (!HandleLValueMember(Info, RHS, LV, FD))
5069 return nullptr;
5070 } else if (const IndirectFieldDecl *IFD =
5071 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
5072 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
5073 return nullptr;
5074 } else {
5075 llvm_unreachable("can't construct reference to bound member function");
5076 }
5077 }
5078
5079 return MemPtr.getDecl();
5080}
5081
5082static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
5083 const BinaryOperator *BO,
5084 LValue &LV,
5085 bool IncludeMember = true) {
5086 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
5087
5088 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
5089 if (Info.noteFailure()) {
5090 MemberPtr MemPtr;
5091 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
5092 }
5093 return nullptr;
5094 }
5095
5096 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
5097 BO->getRHS(), IncludeMember);
5098}
5099
5100/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
5101/// the provided lvalue, which currently refers to the base object.
5102static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
5103 LValue &Result) {
5104 SubobjectDesignator &D = Result.Designator;
5105 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
5106 return false;
5107
5108 QualType TargetQT = E->getType();
5109 if (const PointerType *PT = TargetQT->getAs<PointerType>())
5110 TargetQT = PT->getPointeeType();
5111
5112 auto InvalidCast = [&]() {
5113 if (!Info.checkingPotentialConstantExpression() ||
5114 !Result.AllowConstexprUnknown) {
5115 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
5116 << D.MostDerivedType << TargetQT;
5117 }
5118 return false;
5119 };
5120
5121 // Check this cast lands within the final derived-to-base subobject path.
5122 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size())
5123 return InvalidCast();
5124
5125 // Check the type of the final cast. We don't need to check the path,
5126 // since a cast can only be formed if the path is unique.
5127 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
5128 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
5129 const CXXRecordDecl *FinalType;
5130 if (NewEntriesSize == D.MostDerivedPathLength)
5131 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
5132 else
5133 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
5134 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl())
5135 return InvalidCast();
5136
5137 // Truncate the lvalue to the appropriate derived class.
5138 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
5139}
5140
5141/// Get the value to use for a default-initialized object of type T.
5142/// Return false if it encounters something invalid.
5144 bool Success = true;
5145
5146 // If there is already a value present don't overwrite it.
5147 if (!Result.isAbsent())
5148 return true;
5149
5150 if (auto *RD = T->getAsCXXRecordDecl()) {
5151 if (RD->isInvalidDecl()) {
5152 Result = APValue();
5153 return false;
5154 }
5155 if (RD->isUnion()) {
5156 Result = APValue((const FieldDecl *)nullptr);
5157 return true;
5158 }
5159 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
5160 std::distance(RD->field_begin(), RD->field_end()));
5161
5162 unsigned Index = 0;
5163 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
5164 End = RD->bases_end();
5165 I != End; ++I, ++Index)
5166 Success &=
5167 handleDefaultInitValue(I->getType(), Result.getStructBase(Index));
5168
5169 for (const auto *I : RD->fields()) {
5170 if (I->isUnnamedBitField())
5171 continue;
5173 I->getType(), Result.getStructField(I->getFieldIndex()));
5174 }
5175 return Success;
5176 }
5177
5178 if (auto *AT =
5179 dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
5180 Result = APValue(APValue::UninitArray(), 0, AT->getZExtSize());
5181 if (Result.hasArrayFiller())
5182 Success &=
5183 handleDefaultInitValue(AT->getElementType(), Result.getArrayFiller());
5184
5185 return Success;
5186 }
5187
5188 Result = APValue::IndeterminateValue();
5189 return true;
5190}
5191
5192namespace {
5193enum EvalStmtResult {
5194 /// Evaluation failed.
5195 ESR_Failed,
5196 /// Hit a 'return' statement.
5197 ESR_Returned,
5198 /// Evaluation succeeded.
5199 ESR_Succeeded,
5200 /// Hit a 'continue' statement.
5201 ESR_Continue,
5202 /// Hit a 'break' statement.
5203 ESR_Break,
5204 /// Still scanning for 'case' or 'default' statement.
5205 ESR_CaseNotFound
5206};
5207}
5208/// Evaluates the initializer of a reference.
5209static bool EvaluateInitForDeclOfReferenceType(EvalInfo &Info,
5210 const ValueDecl *D,
5211 const Expr *Init, LValue &Result,
5212 APValue &Val) {
5213 assert(Init->isGLValue() && D->getType()->isReferenceType());
5214 // A reference is an lvalue.
5215 if (!EvaluateLValue(Init, Result, Info))
5216 return false;
5217 // [C++26][decl.ref]
5218 // The object designated by such a glvalue can be outside its lifetime
5219 // Because a null pointer value or a pointer past the end of an object
5220 // does not point to an object, a reference in a well-defined program cannot
5221 // refer to such things;
5222 if (!Result.Designator.Invalid && Result.Designator.isOnePastTheEnd()) {
5223 Info.FFDiag(Init, diag::note_constexpr_access_past_end) << AK_Dereference;
5224 return false;
5225 }
5226
5227 // Save the result.
5228 Result.moveInto(Val);
5229 return true;
5230}
5231
5232static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
5233 if (VD->isInvalidDecl())
5234 return false;
5235 // We don't need to evaluate the initializer for a static local.
5236 if (!VD->hasLocalStorage())
5237 return true;
5238
5239 LValue Result;
5240 APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(),
5241 ScopeKind::Block, Result);
5242
5243 const Expr *InitE = VD->getInit();
5244 if (!InitE) {
5245 if (VD->getType()->isDependentType())
5246 return Info.noteSideEffect();
5247 return handleDefaultInitValue(VD->getType(), Val);
5248 }
5249 if (InitE->isValueDependent())
5250 return false;
5251
5252 // For references to objects, check they do not designate a one-past-the-end
5253 // object.
5254 if (VD->getType()->isReferenceType()) {
5255 return EvaluateInitForDeclOfReferenceType(Info, VD, InitE, Result, Val);
5256 } else if (!EvaluateInPlace(Val, Info, Result, InitE)) {
5257 // Wipe out any partially-computed value, to allow tracking that this
5258 // evaluation failed.
5259 Val = APValue();
5260 return false;
5261 }
5262
5263 return true;
5264}
5265
5266static bool EvaluateDecompositionDeclInit(EvalInfo &Info,
5267 const DecompositionDecl *DD);
5268
5269static bool EvaluateDecl(EvalInfo &Info, const Decl *D,
5270 bool EvaluateConditionDecl = false) {
5271 bool OK = true;
5272 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
5273 OK &= EvaluateVarDecl(Info, VD);
5274
5275 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D);
5276 EvaluateConditionDecl && DD)
5277 OK &= EvaluateDecompositionDeclInit(Info, DD);
5278
5279 return OK;
5280}
5281
5282static bool EvaluateDecompositionDeclInit(EvalInfo &Info,
5283 const DecompositionDecl *DD) {
5284 bool OK = true;
5285 for (auto *BD : DD->flat_bindings())
5286 if (auto *VD = BD->getHoldingVar())
5287 OK &= EvaluateDecl(Info, VD, /*EvaluateConditionDecl=*/true);
5288
5289 return OK;
5290}
5291
5292static bool MaybeEvaluateDeferredVarDeclInit(EvalInfo &Info,
5293 const VarDecl *VD) {
5294 if (auto *DD = dyn_cast_if_present<DecompositionDecl>(VD)) {
5295 if (!EvaluateDecompositionDeclInit(Info, DD))
5296 return false;
5297 }
5298 return true;
5299}
5300
5301static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info) {
5302 assert(E->isValueDependent());
5303 if (Info.noteSideEffect())
5304 return true;
5305 assert(E->containsErrors() && "valid value-dependent expression should never "
5306 "reach invalid code path.");
5307 return false;
5308}
5309
5310/// Evaluate a condition (either a variable declaration or an expression).
5311static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
5312 const Expr *Cond, bool &Result) {
5313 if (Cond->isValueDependent())
5314 return false;
5315 FullExpressionRAII Scope(Info);
5316 if (CondDecl && !EvaluateDecl(Info, CondDecl))
5317 return false;
5318 if (!EvaluateAsBooleanCondition(Cond, Result, Info))
5319 return false;
5320 if (!MaybeEvaluateDeferredVarDeclInit(Info, CondDecl))
5321 return false;
5322 return Scope.destroy();
5323}
5324
5325namespace {
5326/// A location where the result (returned value) of evaluating a
5327/// statement should be stored.
5328struct StmtResult {
5329 /// The APValue that should be filled in with the returned value.
5330 APValue &Value;
5331 /// The location containing the result, if any (used to support RVO).
5332 const LValue *Slot;
5333};
5334
5335struct TempVersionRAII {
5336 CallStackFrame &Frame;
5337
5338 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
5339 Frame.pushTempVersion();
5340 }
5341
5342 ~TempVersionRAII() {
5343 Frame.popTempVersion();
5344 }
5345};
5346
5347}
5348
5349static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
5350 const Stmt *S,
5351 const SwitchCase *SC = nullptr);
5352
5353/// Helper to implement named break/continue. Returns 'true' if the evaluation
5354/// result should be propagated up. Otherwise, it sets the evaluation result
5355/// to either Continue to continue the current loop, or Succeeded to break it.
5356static bool ShouldPropagateBreakContinue(EvalInfo &Info,
5357 const Stmt *LoopOrSwitch,
5359 EvalStmtResult &ESR) {
5360 bool IsSwitch = isa<SwitchStmt>(LoopOrSwitch);
5361
5362 // For loops, map Succeeded to Continue so we don't have to check for both.
5363 if (!IsSwitch && ESR == ESR_Succeeded) {
5364 ESR = ESR_Continue;
5365 return false;
5366 }
5367
5368 if (ESR != ESR_Break && ESR != ESR_Continue)
5369 return false;
5370
5371 // Are we breaking out of or continuing this statement?
5372 bool CanBreakOrContinue = !IsSwitch || ESR == ESR_Break;
5373 const Stmt *StackTop = Info.BreakContinueStack.back();
5374 if (CanBreakOrContinue && (StackTop == nullptr || StackTop == LoopOrSwitch)) {
5375 Info.BreakContinueStack.pop_back();
5376 if (ESR == ESR_Break)
5377 ESR = ESR_Succeeded;
5378 return false;
5379 }
5380
5381 // We're not. Propagate the result up.
5382 for (BlockScopeRAII *S : Scopes) {
5383 if (!S->destroy()) {
5384 ESR = ESR_Failed;
5385 break;
5386 }
5387 }
5388 return true;
5389}
5390
5391/// Evaluate the body of a loop, and translate the result as appropriate.
5392static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
5393 const Stmt *Body,
5394 const SwitchCase *Case = nullptr) {
5395 BlockScopeRAII Scope(Info);
5396
5397 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case);
5398 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
5399 ESR = ESR_Failed;
5400
5401 return ESR;
5402}
5403
5404/// Evaluate a switch statement.
5405static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
5406 const SwitchStmt *SS) {
5407 BlockScopeRAII Scope(Info);
5408
5409 // Evaluate the switch condition.
5410 APSInt Value;
5411 {
5412 if (const Stmt *Init = SS->getInit()) {
5413 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
5414 if (ESR != ESR_Succeeded) {
5415 if (ESR != ESR_Failed && !Scope.destroy())
5416 ESR = ESR_Failed;
5417 return ESR;
5418 }
5419 }
5420
5421 FullExpressionRAII CondScope(Info);
5422 if (SS->getConditionVariable() &&
5423 !EvaluateDecl(Info, SS->getConditionVariable()))
5424 return ESR_Failed;
5425 if (SS->getCond()->isValueDependent()) {
5426 // We don't know what the value is, and which branch should jump to.
5427 EvaluateDependentExpr(SS->getCond(), Info);
5428 return ESR_Failed;
5429 }
5430 if (!EvaluateInteger(SS->getCond(), Value, Info))
5431 return ESR_Failed;
5432
5434 return ESR_Failed;
5435
5436 if (!CondScope.destroy())
5437 return ESR_Failed;
5438 }
5439
5440 // Find the switch case corresponding to the value of the condition.
5441 // FIXME: Cache this lookup.
5442 const SwitchCase *Found = nullptr;
5443 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
5444 SC = SC->getNextSwitchCase()) {
5445 if (isa<DefaultStmt>(SC)) {
5446 Found = SC;
5447 continue;
5448 }
5449
5450 const CaseStmt *CS = cast<CaseStmt>(SC);
5451 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
5452 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
5453 : LHS;
5454 if (LHS <= Value && Value <= RHS) {
5455 Found = SC;
5456 break;
5457 }
5458 }
5459
5460 if (!Found)
5461 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5462
5463 // Search the switch body for the switch case and evaluate it from there.
5464 EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found);
5465 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
5466 return ESR_Failed;
5467 if (ShouldPropagateBreakContinue(Info, SS, /*Scopes=*/{}, ESR))
5468 return ESR;
5469
5470 switch (ESR) {
5471 case ESR_Break:
5472 llvm_unreachable("Should have been converted to Succeeded");
5473 case ESR_Succeeded:
5474 case ESR_Continue:
5475 case ESR_Failed:
5476 case ESR_Returned:
5477 return ESR;
5478 case ESR_CaseNotFound:
5479 // This can only happen if the switch case is nested within a statement
5480 // expression. We have no intention of supporting that.
5481 Info.FFDiag(Found->getBeginLoc(),
5482 diag::note_constexpr_stmt_expr_unsupported);
5483 return ESR_Failed;
5484 }
5485 llvm_unreachable("Invalid EvalStmtResult!");
5486}
5487
5488static bool CheckLocalVariableDeclaration(EvalInfo &Info, const VarDecl *VD) {
5489 // An expression E is a core constant expression unless the evaluation of E
5490 // would evaluate one of the following: [C++23] - a control flow that passes
5491 // through a declaration of a variable with static or thread storage duration
5492 // unless that variable is usable in constant expressions.
5493 if (VD->isLocalVarDecl() && VD->isStaticLocal() &&
5494 !VD->isUsableInConstantExpressions(Info.Ctx)) {
5495 Info.CCEDiag(VD->getLocation(), diag::note_constexpr_static_local)
5496 << (VD->getTSCSpec() == TSCS_unspecified ? 0 : 1) << VD;
5497 return false;
5498 }
5499 return true;
5500}
5501
5502// Evaluate a statement.
5503static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
5504 const Stmt *S, const SwitchCase *Case) {
5505 if (!Info.nextStep(S))
5506 return ESR_Failed;
5507
5508 // If we're hunting down a 'case' or 'default' label, recurse through
5509 // substatements until we hit the label.
5510 if (Case) {
5511 switch (S->getStmtClass()) {
5512 case Stmt::CompoundStmtClass:
5513 // FIXME: Precompute which substatement of a compound statement we
5514 // would jump to, and go straight there rather than performing a
5515 // linear scan each time.
5516 case Stmt::LabelStmtClass:
5517 case Stmt::AttributedStmtClass:
5518 case Stmt::DoStmtClass:
5519 break;
5520
5521 case Stmt::CaseStmtClass:
5522 case Stmt::DefaultStmtClass:
5523 if (Case == S)
5524 Case = nullptr;
5525 break;
5526
5527 case Stmt::IfStmtClass: {
5528 // FIXME: Precompute which side of an 'if' we would jump to, and go
5529 // straight there rather than scanning both sides.
5530 const IfStmt *IS = cast<IfStmt>(S);
5531
5532 // Wrap the evaluation in a block scope, in case it's a DeclStmt
5533 // preceded by our switch label.
5534 BlockScopeRAII Scope(Info);
5535
5536 // Step into the init statement in case it brings an (uninitialized)
5537 // variable into scope.
5538 if (const Stmt *Init = IS->getInit()) {
5539 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5540 if (ESR != ESR_CaseNotFound) {
5541 assert(ESR != ESR_Succeeded);
5542 return ESR;
5543 }
5544 }
5545
5546 // Condition variable must be initialized if it exists.
5547 // FIXME: We can skip evaluating the body if there's a condition
5548 // variable, as there can't be any case labels within it.
5549 // (The same is true for 'for' statements.)
5550
5551 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
5552 if (ESR == ESR_Failed)
5553 return ESR;
5554 if (ESR != ESR_CaseNotFound)
5555 return Scope.destroy() ? ESR : ESR_Failed;
5556 if (!IS->getElse())
5557 return ESR_CaseNotFound;
5558
5559 ESR = EvaluateStmt(Result, Info, IS->getElse(), Case);
5560 if (ESR == ESR_Failed)
5561 return ESR;
5562 if (ESR != ESR_CaseNotFound)
5563 return Scope.destroy() ? ESR : ESR_Failed;
5564 return ESR_CaseNotFound;
5565 }
5566
5567 case Stmt::WhileStmtClass: {
5568 EvalStmtResult ESR =
5569 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
5570 if (ShouldPropagateBreakContinue(Info, S, /*Scopes=*/{}, ESR))
5571 return ESR;
5572 if (ESR != ESR_Continue)
5573 return ESR;
5574 break;
5575 }
5576
5577 case Stmt::ForStmtClass: {
5578 const ForStmt *FS = cast<ForStmt>(S);
5579 BlockScopeRAII Scope(Info);
5580
5581 // Step into the init statement in case it brings an (uninitialized)
5582 // variable into scope.
5583 if (const Stmt *Init = FS->getInit()) {
5584 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5585 if (ESR != ESR_CaseNotFound) {
5586 assert(ESR != ESR_Succeeded);
5587 return ESR;
5588 }
5589 }
5590
5591 EvalStmtResult ESR =
5592 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
5593 if (ShouldPropagateBreakContinue(Info, FS, /*Scopes=*/{}, ESR))
5594 return ESR;
5595 if (ESR != ESR_Continue)
5596 return ESR;
5597 if (const auto *Inc = FS->getInc()) {
5598 if (Inc->isValueDependent()) {
5599 if (!EvaluateDependentExpr(Inc, Info))
5600 return ESR_Failed;
5601 } else {
5602 FullExpressionRAII IncScope(Info);
5603 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5604 return ESR_Failed;
5605 }
5606 }
5607 break;
5608 }
5609
5610 case Stmt::DeclStmtClass: {
5611 // Start the lifetime of any uninitialized variables we encounter. They
5612 // might be used by the selected branch of the switch.
5613 const DeclStmt *DS = cast<DeclStmt>(S);
5614 for (const auto *D : DS->decls()) {
5615 if (const auto *VD = dyn_cast<VarDecl>(D)) {
5616 if (!CheckLocalVariableDeclaration(Info, VD))
5617 return ESR_Failed;
5618 if (VD->hasLocalStorage() && !VD->getInit())
5619 if (!EvaluateVarDecl(Info, VD))
5620 return ESR_Failed;
5621 // FIXME: If the variable has initialization that can't be jumped
5622 // over, bail out of any immediately-surrounding compound-statement
5623 // too. There can't be any case labels here.
5624 }
5625 }
5626 return ESR_CaseNotFound;
5627 }
5628
5629 default:
5630 return ESR_CaseNotFound;
5631 }
5632 }
5633
5634 switch (S->getStmtClass()) {
5635 default:
5636 if (const Expr *E = dyn_cast<Expr>(S)) {
5637 if (E->isValueDependent()) {
5638 if (!EvaluateDependentExpr(E, Info))
5639 return ESR_Failed;
5640 } else {
5641 // Don't bother evaluating beyond an expression-statement which couldn't
5642 // be evaluated.
5643 // FIXME: Do we need the FullExpressionRAII object here?
5644 // VisitExprWithCleanups should create one when necessary.
5645 FullExpressionRAII Scope(Info);
5646 if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy())
5647 return ESR_Failed;
5648 }
5649 return ESR_Succeeded;
5650 }
5651
5652 Info.FFDiag(S->getBeginLoc()) << S->getSourceRange();
5653 return ESR_Failed;
5654
5655 case Stmt::NullStmtClass:
5656 return ESR_Succeeded;
5657
5658 case Stmt::DeclStmtClass: {
5659 const DeclStmt *DS = cast<DeclStmt>(S);
5660 for (const auto *D : DS->decls()) {
5661 const VarDecl *VD = dyn_cast_or_null<VarDecl>(D);
5662 if (VD && !CheckLocalVariableDeclaration(Info, VD))
5663 return ESR_Failed;
5664 // Each declaration initialization is its own full-expression.
5665 FullExpressionRAII Scope(Info);
5666 if (!EvaluateDecl(Info, D, /*EvaluateConditionDecl=*/true) &&
5667 !Info.noteFailure())
5668 return ESR_Failed;
5669 if (!Scope.destroy())
5670 return ESR_Failed;
5671 }
5672 return ESR_Succeeded;
5673 }
5674
5675 case Stmt::ReturnStmtClass: {
5676 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
5677 FullExpressionRAII Scope(Info);
5678 if (RetExpr && RetExpr->isValueDependent()) {
5679 EvaluateDependentExpr(RetExpr, Info);
5680 // We know we returned, but we don't know what the value is.
5681 return ESR_Failed;
5682 }
5683 if (RetExpr &&
5684 !(Result.Slot
5685 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
5686 : Evaluate(Result.Value, Info, RetExpr)))
5687 return ESR_Failed;
5688 return Scope.destroy() ? ESR_Returned : ESR_Failed;
5689 }
5690
5691 case Stmt::CompoundStmtClass: {
5692 BlockScopeRAII Scope(Info);
5693
5694 const CompoundStmt *CS = cast<CompoundStmt>(S);
5695 for (const auto *BI : CS->body()) {
5696 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
5697 if (ESR == ESR_Succeeded)
5698 Case = nullptr;
5699 else if (ESR != ESR_CaseNotFound) {
5700 if (ESR != ESR_Failed && !Scope.destroy())
5701 return ESR_Failed;
5702 return ESR;
5703 }
5704 }
5705 if (Case)
5706 return ESR_CaseNotFound;
5707 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5708 }
5709
5710 case Stmt::IfStmtClass: {
5711 const IfStmt *IS = cast<IfStmt>(S);
5712
5713 // Evaluate the condition, as either a var decl or as an expression.
5714 BlockScopeRAII Scope(Info);
5715 if (const Stmt *Init = IS->getInit()) {
5716 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
5717 if (ESR != ESR_Succeeded) {
5718 if (ESR != ESR_Failed && !Scope.destroy())
5719 return ESR_Failed;
5720 return ESR;
5721 }
5722 }
5723 bool Cond;
5724 if (IS->isConsteval()) {
5726 // If we are not in a constant context, if consteval should not evaluate
5727 // to true.
5728 if (!Info.InConstantContext)
5729 Cond = !Cond;
5730 } else if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(),
5731 Cond))
5732 return ESR_Failed;
5733
5734 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
5735 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
5736 if (ESR != ESR_Succeeded) {
5737 if (ESR != ESR_Failed && !Scope.destroy())
5738 return ESR_Failed;
5739 return ESR;
5740 }
5741 }
5742 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5743 }
5744
5745 case Stmt::WhileStmtClass: {
5746 const WhileStmt *WS = cast<WhileStmt>(S);
5747 while (true) {
5748 BlockScopeRAII Scope(Info);
5749 bool Continue;
5750 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
5751 Continue))
5752 return ESR_Failed;
5753 if (!Continue)
5754 break;
5755
5756 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
5757 if (ShouldPropagateBreakContinue(Info, WS, &Scope, ESR))
5758 return ESR;
5759
5760 if (ESR != ESR_Continue) {
5761 if (ESR != ESR_Failed && !Scope.destroy())
5762 return ESR_Failed;
5763 return ESR;
5764 }
5765 if (!Scope.destroy())
5766 return ESR_Failed;
5767 }
5768 return ESR_Succeeded;
5769 }
5770
5771 case Stmt::DoStmtClass: {
5772 const DoStmt *DS = cast<DoStmt>(S);
5773 bool Continue;
5774 do {
5775 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
5776 if (ShouldPropagateBreakContinue(Info, DS, /*Scopes=*/{}, ESR))
5777 return ESR;
5778 if (ESR != ESR_Continue)
5779 return ESR;
5780 Case = nullptr;
5781
5782 if (DS->getCond()->isValueDependent()) {
5783 EvaluateDependentExpr(DS->getCond(), Info);
5784 // Bailout as we don't know whether to keep going or terminate the loop.
5785 return ESR_Failed;
5786 }
5787 FullExpressionRAII CondScope(Info);
5788 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) ||
5789 !CondScope.destroy())
5790 return ESR_Failed;
5791 } while (Continue);
5792 return ESR_Succeeded;
5793 }
5794
5795 case Stmt::ForStmtClass: {
5796 const ForStmt *FS = cast<ForStmt>(S);
5797 BlockScopeRAII ForScope(Info);
5798 if (FS->getInit()) {
5799 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5800 if (ESR != ESR_Succeeded) {
5801 if (ESR != ESR_Failed && !ForScope.destroy())
5802 return ESR_Failed;
5803 return ESR;
5804 }
5805 }
5806 while (true) {
5807 BlockScopeRAII IterScope(Info);
5808 bool Continue = true;
5809 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
5810 FS->getCond(), Continue))
5811 return ESR_Failed;
5812
5813 if (!Continue) {
5814 if (!IterScope.destroy())
5815 return ESR_Failed;
5816 break;
5817 }
5818
5819 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5820 if (ShouldPropagateBreakContinue(Info, FS, {&IterScope, &ForScope}, ESR))
5821 return ESR;
5822 if (ESR != ESR_Continue) {
5823 if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))
5824 return ESR_Failed;
5825 return ESR;
5826 }
5827
5828 if (const auto *Inc = FS->getInc()) {
5829 if (Inc->isValueDependent()) {
5830 if (!EvaluateDependentExpr(Inc, Info))
5831 return ESR_Failed;
5832 } else {
5833 FullExpressionRAII IncScope(Info);
5834 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5835 return ESR_Failed;
5836 }
5837 }
5838
5839 if (!IterScope.destroy())
5840 return ESR_Failed;
5841 }
5842 return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;
5843 }
5844
5845 case Stmt::CXXForRangeStmtClass: {
5847 BlockScopeRAII Scope(Info);
5848
5849 // Evaluate the init-statement if present.
5850 if (FS->getInit()) {
5851 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5852 if (ESR != ESR_Succeeded) {
5853 if (ESR != ESR_Failed && !Scope.destroy())
5854 return ESR_Failed;
5855 return ESR;
5856 }
5857 }
5858
5859 // Initialize the __range variable.
5860 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
5861 if (ESR != ESR_Succeeded) {
5862 if (ESR != ESR_Failed && !Scope.destroy())
5863 return ESR_Failed;
5864 return ESR;
5865 }
5866
5867 // In error-recovery cases it's possible to get here even if we failed to
5868 // synthesize the __begin and __end variables.
5869 if (!FS->getBeginStmt() || !FS->getEndStmt() || !FS->getCond())
5870 return ESR_Failed;
5871
5872 // Create the __begin and __end iterators.
5873 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
5874 if (ESR != ESR_Succeeded) {
5875 if (ESR != ESR_Failed && !Scope.destroy())
5876 return ESR_Failed;
5877 return ESR;
5878 }
5879 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
5880 if (ESR != ESR_Succeeded) {
5881 if (ESR != ESR_Failed && !Scope.destroy())
5882 return ESR_Failed;
5883 return ESR;
5884 }
5885
5886 while (true) {
5887 // Condition: __begin != __end.
5888 {
5889 if (FS->getCond()->isValueDependent()) {
5890 EvaluateDependentExpr(FS->getCond(), Info);
5891 // We don't know whether to keep going or terminate the loop.
5892 return ESR_Failed;
5893 }
5894 bool Continue = true;
5895 FullExpressionRAII CondExpr(Info);
5896 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
5897 return ESR_Failed;
5898 if (!Continue)
5899 break;
5900 }
5901
5902 // User's variable declaration, initialized by *__begin.
5903 BlockScopeRAII InnerScope(Info);
5904 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
5905 if (ESR != ESR_Succeeded) {
5906 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5907 return ESR_Failed;
5908 return ESR;
5909 }
5910
5911 // Loop body.
5912 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5913 if (ShouldPropagateBreakContinue(Info, FS, {&InnerScope, &Scope}, ESR))
5914 return ESR;
5915 if (ESR != ESR_Continue) {
5916 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5917 return ESR_Failed;
5918 return ESR;
5919 }
5920 if (FS->getInc()->isValueDependent()) {
5921 if (!EvaluateDependentExpr(FS->getInc(), Info))
5922 return ESR_Failed;
5923 } else {
5924 // Increment: ++__begin
5925 if (!EvaluateIgnoredValue(Info, FS->getInc()))
5926 return ESR_Failed;
5927 }
5928
5929 if (!InnerScope.destroy())
5930 return ESR_Failed;
5931 }
5932
5933 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5934 }
5935
5936 case Stmt::SwitchStmtClass:
5937 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
5938
5939 case Stmt::ContinueStmtClass:
5940 case Stmt::BreakStmtClass: {
5941 auto *B = cast<LoopControlStmt>(S);
5942 Info.BreakContinueStack.push_back(B->getNamedLoopOrSwitch());
5943 return isa<ContinueStmt>(S) ? ESR_Continue : ESR_Break;
5944 }
5945
5946 case Stmt::LabelStmtClass:
5947 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
5948
5949 case Stmt::AttributedStmtClass: {
5950 const auto *AS = cast<AttributedStmt>(S);
5951 const auto *SS = AS->getSubStmt();
5952 MSConstexprContextRAII ConstexprContext(
5953 *Info.CurrentCall, hasSpecificAttr<MSConstexprAttr>(AS->getAttrs()) &&
5954 isa<ReturnStmt>(SS));
5955
5956 auto LO = Info.getASTContext().getLangOpts();
5957 if (LO.CXXAssumptions && !LO.MSVCCompat) {
5958 for (auto *Attr : AS->getAttrs()) {
5959 auto *AA = dyn_cast<CXXAssumeAttr>(Attr);
5960 if (!AA)
5961 continue;
5962
5963 auto *Assumption = AA->getAssumption();
5964 if (Assumption->isValueDependent())
5965 return ESR_Failed;
5966
5967 if (Assumption->HasSideEffects(Info.getASTContext()))
5968 continue;
5969
5970 bool Value;
5971 if (!EvaluateAsBooleanCondition(Assumption, Value, Info))
5972 return ESR_Failed;
5973 if (!Value) {
5974 Info.CCEDiag(Assumption->getExprLoc(),
5975 diag::note_constexpr_assumption_failed);
5976 return ESR_Failed;
5977 }
5978 }
5979 }
5980
5981 return EvaluateStmt(Result, Info, SS, Case);
5982 }
5983
5984 case Stmt::CaseStmtClass:
5985 case Stmt::DefaultStmtClass:
5986 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
5987 case Stmt::CXXTryStmtClass:
5988 // Evaluate try blocks by evaluating all sub statements.
5989 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
5990 }
5991}
5992
5993/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
5994/// default constructor. If so, we'll fold it whether or not it's marked as
5995/// constexpr. If it is marked as constexpr, we will never implicitly define it,
5996/// so we need special handling.
5997static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
5998 const CXXConstructorDecl *CD,
5999 bool IsValueInitialization) {
6000 if (!CD->isTrivial() || !CD->isDefaultConstructor())
6001 return false;
6002
6003 // Value-initialization does not call a trivial default constructor, so such a
6004 // call is a core constant expression whether or not the constructor is
6005 // constexpr.
6006 if (!CD->isConstexpr() && !IsValueInitialization) {
6007 if (Info.getLangOpts().CPlusPlus11) {
6008 // FIXME: If DiagDecl is an implicitly-declared special member function,
6009 // we should be much more explicit about why it's not constexpr.
6010 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
6011 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
6012 Info.Note(CD->getLocation(), diag::note_declared_at);
6013 } else {
6014 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
6015 }
6016 }
6017 return true;
6018}
6019
6020/// CheckConstexprFunction - Check that a function can be called in a constant
6021/// expression.
6022static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
6024 const FunctionDecl *Definition,
6025 const Stmt *Body) {
6026 // Potential constant expressions can contain calls to declared, but not yet
6027 // defined, constexpr functions.
6028 if (Info.checkingPotentialConstantExpression() && !Definition &&
6029 Declaration->isConstexpr())
6030 return false;
6031
6032 // Bail out if the function declaration itself is invalid. We will
6033 // have produced a relevant diagnostic while parsing it, so just
6034 // note the problematic sub-expression.
6035 if (Declaration->isInvalidDecl()) {
6036 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
6037 return false;
6038 }
6039
6040 // DR1872: An instantiated virtual constexpr function can't be called in a
6041 // constant expression (prior to C++20). We can still constant-fold such a
6042 // call.
6043 if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) &&
6044 cast<CXXMethodDecl>(Declaration)->isVirtual())
6045 Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
6046
6047 if (Definition && Definition->isInvalidDecl()) {
6048 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
6049 return false;
6050 }
6051
6052 // Can we evaluate this function call?
6053 if (Definition && Body &&
6054 (Definition->isConstexpr() || (Info.CurrentCall->CanEvalMSConstexpr &&
6055 Definition->hasAttr<MSConstexprAttr>())))
6056 return true;
6057
6058 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
6059 // Special note for the assert() macro, as the normal error message falsely
6060 // implies we cannot use an assertion during constant evaluation.
6061 if (CallLoc.isMacroID() && DiagDecl->getIdentifier()) {
6062 // FIXME: Instead of checking for an implementation-defined function,
6063 // check and evaluate the assert() macro.
6064 StringRef Name = DiagDecl->getName();
6065 bool AssertFailed =
6066 Name == "__assert_rtn" || Name == "__assert_fail" || Name == "_wassert";
6067 if (AssertFailed) {
6068 Info.FFDiag(CallLoc, diag::note_constexpr_assert_failed);
6069 return false;
6070 }
6071 }
6072
6073 if (Info.getLangOpts().CPlusPlus11) {
6074 // If this function is not constexpr because it is an inherited
6075 // non-constexpr constructor, diagnose that directly.
6076 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
6077 if (CD && CD->isInheritingConstructor()) {
6078 auto *Inherited = CD->getInheritedConstructor().getConstructor();
6079 if (!Inherited->isConstexpr())
6080 DiagDecl = CD = Inherited;
6081 }
6082
6083 // FIXME: If DiagDecl is an implicitly-declared special member function
6084 // or an inheriting constructor, we should be much more explicit about why
6085 // it's not constexpr.
6086 if (CD && CD->isInheritingConstructor())
6087 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
6088 << CD->getInheritedConstructor().getConstructor()->getParent();
6089 else
6090 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
6091 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
6092 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
6093 } else {
6094 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
6095 }
6096 return false;
6097}
6098
6099namespace {
6100struct CheckDynamicTypeHandler {
6102 typedef bool result_type;
6103 bool failed() { return false; }
6104 bool found(APValue &Subobj, QualType SubobjType) { return true; }
6105 bool found(APSInt &Value, QualType SubobjType) { return true; }
6106 bool found(APFloat &Value, QualType SubobjType) { return true; }
6107};
6108} // end anonymous namespace
6109
6110/// Check that we can access the notional vptr of an object / determine its
6111/// dynamic type.
6112static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
6113 AccessKinds AK, bool Polymorphic) {
6114 if (This.Designator.Invalid)
6115 return false;
6116
6117 CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
6118
6119 if (!Obj)
6120 return false;
6121
6122 if (!Obj.Value) {
6123 // The object is not usable in constant expressions, so we can't inspect
6124 // its value to see if it's in-lifetime or what the active union members
6125 // are. We can still check for a one-past-the-end lvalue.
6126 if (This.Designator.isOnePastTheEnd() ||
6127 This.Designator.isMostDerivedAnUnsizedArray()) {
6128 Info.FFDiag(E, This.Designator.isOnePastTheEnd()
6129 ? diag::note_constexpr_access_past_end
6130 : diag::note_constexpr_access_unsized_array)
6131 << AK;
6132 return false;
6133 } else if (Polymorphic) {
6134 // Conservatively refuse to perform a polymorphic operation if we would
6135 // not be able to read a notional 'vptr' value.
6136 if (!Info.checkingPotentialConstantExpression() ||
6137 !This.AllowConstexprUnknown) {
6138 APValue Val;
6139 This.moveInto(Val);
6140 QualType StarThisType =
6141 Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
6142 Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
6143 << AK << Val.getAsString(Info.Ctx, StarThisType);
6144 }
6145 return false;
6146 }
6147 return true;
6148 }
6149
6150 CheckDynamicTypeHandler Handler{AK};
6151 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
6152}
6153
6154/// Check that the pointee of the 'this' pointer in a member function call is
6155/// either within its lifetime or in its period of construction or destruction.
6156static bool
6158 const LValue &This,
6159 const CXXMethodDecl *NamedMember) {
6160 return checkDynamicType(
6161 Info, E, This,
6162 isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false);
6163}
6164
6166 /// The dynamic class type of the object.
6168 /// The corresponding path length in the lvalue.
6169 unsigned PathLength;
6170};
6171
6172static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
6173 unsigned PathLength) {
6174 assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
6175 Designator.Entries.size() && "invalid path length");
6176 return (PathLength == Designator.MostDerivedPathLength)
6177 ? Designator.MostDerivedType->getAsCXXRecordDecl()
6178 : getAsBaseClass(Designator.Entries[PathLength - 1]);
6179}
6180
6181/// Determine the dynamic type of an object.
6182static std::optional<DynamicType> ComputeDynamicType(EvalInfo &Info,
6183 const Expr *E,
6184 LValue &This,
6185 AccessKinds AK) {
6186 // If we don't have an lvalue denoting an object of class type, there is no
6187 // meaningful dynamic type. (We consider objects of non-class type to have no
6188 // dynamic type.)
6189 if (!checkDynamicType(Info, E, This, AK,
6190 AK != AK_TypeId || This.AllowConstexprUnknown))
6191 return std::nullopt;
6192
6193 if (This.Designator.Invalid)
6194 return std::nullopt;
6195
6196 // Refuse to compute a dynamic type in the presence of virtual bases. This
6197 // shouldn't happen other than in constant-folding situations, since literal
6198 // types can't have virtual bases.
6199 //
6200 // Note that consumers of DynamicType assume that the type has no virtual
6201 // bases, and will need modifications if this restriction is relaxed.
6202 const CXXRecordDecl *Class =
6203 This.Designator.MostDerivedType->getAsCXXRecordDecl();
6204 if (!Class || Class->getNumVBases()) {
6205 Info.FFDiag(E);
6206 return std::nullopt;
6207 }
6208
6209 // FIXME: For very deep class hierarchies, it might be beneficial to use a
6210 // binary search here instead. But the overwhelmingly common case is that
6211 // we're not in the middle of a constructor, so it probably doesn't matter
6212 // in practice.
6213 ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
6214 for (unsigned PathLength = This.Designator.MostDerivedPathLength;
6215 PathLength <= Path.size(); ++PathLength) {
6216 switch (Info.isEvaluatingCtorDtor(This.getLValueBase(),
6217 Path.slice(0, PathLength))) {
6218 case ConstructionPhase::Bases:
6219 case ConstructionPhase::DestroyingBases:
6220 // We're constructing or destroying a base class. This is not the dynamic
6221 // type.
6222 break;
6223
6224 case ConstructionPhase::None:
6225 case ConstructionPhase::AfterBases:
6226 case ConstructionPhase::AfterFields:
6227 case ConstructionPhase::Destroying:
6228 // We've finished constructing the base classes and not yet started
6229 // destroying them again, so this is the dynamic type.
6230 return DynamicType{getBaseClassType(This.Designator, PathLength),
6231 PathLength};
6232 }
6233 }
6234
6235 // CWG issue 1517: we're constructing a base class of the object described by
6236 // 'This', so that object has not yet begun its period of construction and
6237 // any polymorphic operation on it results in undefined behavior.
6238 Info.FFDiag(E);
6239 return std::nullopt;
6240}
6241
6242/// Perform virtual dispatch.
6244 EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
6245 llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
6246 std::optional<DynamicType> DynType = ComputeDynamicType(
6247 Info, E, This,
6249 if (!DynType)
6250 return nullptr;
6251
6252 // Find the final overrider. It must be declared in one of the classes on the
6253 // path from the dynamic type to the static type.
6254 // FIXME: If we ever allow literal types to have virtual base classes, that
6255 // won't be true.
6256 const CXXMethodDecl *Callee = Found;
6257 unsigned PathLength = DynType->PathLength;
6258 for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
6259 const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
6260 const CXXMethodDecl *Overrider =
6261 Found->getCorrespondingMethodDeclaredInClass(Class, false);
6262 if (Overrider) {
6263 Callee = Overrider;
6264 break;
6265 }
6266 }
6267
6268 // C++2a [class.abstract]p6:
6269 // the effect of making a virtual call to a pure virtual function [...] is
6270 // undefined
6271 if (Callee->isPureVirtual()) {
6272 Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
6273 Info.Note(Callee->getLocation(), diag::note_declared_at);
6274 return nullptr;
6275 }
6276
6277 // If necessary, walk the rest of the path to determine the sequence of
6278 // covariant adjustment steps to apply.
6279 if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
6280 Found->getReturnType())) {
6281 CovariantAdjustmentPath.push_back(Callee->getReturnType());
6282 for (unsigned CovariantPathLength = PathLength + 1;
6283 CovariantPathLength != This.Designator.Entries.size();
6284 ++CovariantPathLength) {
6285 const CXXRecordDecl *NextClass =
6286 getBaseClassType(This.Designator, CovariantPathLength);
6287 const CXXMethodDecl *Next =
6288 Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
6289 if (Next && !Info.Ctx.hasSameUnqualifiedType(
6290 Next->getReturnType(), CovariantAdjustmentPath.back()))
6291 CovariantAdjustmentPath.push_back(Next->getReturnType());
6292 }
6293 if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
6294 CovariantAdjustmentPath.back()))
6295 CovariantAdjustmentPath.push_back(Found->getReturnType());
6296 }
6297
6298 // Perform 'this' adjustment.
6299 if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
6300 return nullptr;
6301
6302 return Callee;
6303}
6304
6305/// Perform the adjustment from a value returned by a virtual function to
6306/// a value of the statically expected type, which may be a pointer or
6307/// reference to a base class of the returned type.
6308static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
6309 APValue &Result,
6310 ArrayRef<QualType> Path) {
6311 assert(Result.isLValue() &&
6312 "unexpected kind of APValue for covariant return");
6313 if (Result.isNullPointer())
6314 return true;
6315
6316 LValue LVal;
6317 LVal.setFrom(Info.Ctx, Result);
6318
6319 const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
6320 for (unsigned I = 1; I != Path.size(); ++I) {
6321 const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
6322 assert(OldClass && NewClass && "unexpected kind of covariant return");
6323 if (OldClass != NewClass &&
6324 !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
6325 return false;
6326 OldClass = NewClass;
6327 }
6328
6329 LVal.moveInto(Result);
6330 return true;
6331}
6332
6333/// Determine whether \p Base, which is known to be a direct base class of
6334/// \p Derived, is a public base class.
6335static bool isBaseClassPublic(const CXXRecordDecl *Derived,
6336 const CXXRecordDecl *Base) {
6337 for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
6338 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
6339 if (BaseClass && declaresSameEntity(BaseClass, Base))
6340 return BaseSpec.getAccessSpecifier() == AS_public;
6341 }
6342 llvm_unreachable("Base is not a direct base of Derived");
6343}
6344
6345/// Apply the given dynamic cast operation on the provided lvalue.
6346///
6347/// This implements the hard case of dynamic_cast, requiring a "runtime check"
6348/// to find a suitable target subobject.
6349static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
6350 LValue &Ptr) {
6351 // We can't do anything with a non-symbolic pointer value.
6352 SubobjectDesignator &D = Ptr.Designator;
6353 if (D.Invalid)
6354 return false;
6355
6356 // C++ [expr.dynamic.cast]p6:
6357 // If v is a null pointer value, the result is a null pointer value.
6358 if (Ptr.isNullPointer() && !E->isGLValue())
6359 return true;
6360
6361 // For all the other cases, we need the pointer to point to an object within
6362 // its lifetime / period of construction / destruction, and we need to know
6363 // its dynamic type.
6364 std::optional<DynamicType> DynType =
6365 ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
6366 if (!DynType)
6367 return false;
6368
6369 // C++ [expr.dynamic.cast]p7:
6370 // If T is "pointer to cv void", then the result is a pointer to the most
6371 // derived object
6372 if (E->getType()->isVoidPointerType())
6373 return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
6374
6376 assert(C && "dynamic_cast target is not void pointer nor class");
6377 CanQualType CQT = Info.Ctx.getCanonicalTagType(C);
6378
6379 auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
6380 // C++ [expr.dynamic.cast]p9:
6381 if (!E->isGLValue()) {
6382 // The value of a failed cast to pointer type is the null pointer value
6383 // of the required result type.
6384 Ptr.setNull(Info.Ctx, E->getType());
6385 return true;
6386 }
6387
6388 // A failed cast to reference type throws [...] std::bad_cast.
6389 unsigned DiagKind;
6390 if (!Paths && (declaresSameEntity(DynType->Type, C) ||
6391 DynType->Type->isDerivedFrom(C)))
6392 DiagKind = 0;
6393 else if (!Paths || Paths->begin() == Paths->end())
6394 DiagKind = 1;
6395 else if (Paths->isAmbiguous(CQT))
6396 DiagKind = 2;
6397 else {
6398 assert(Paths->front().Access != AS_public && "why did the cast fail?");
6399 DiagKind = 3;
6400 }
6401 Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
6402 << DiagKind << Ptr.Designator.getType(Info.Ctx)
6403 << Info.Ctx.getCanonicalTagType(DynType->Type)
6404 << E->getType().getUnqualifiedType();
6405 return false;
6406 };
6407
6408 // Runtime check, phase 1:
6409 // Walk from the base subobject towards the derived object looking for the
6410 // target type.
6411 for (int PathLength = Ptr.Designator.Entries.size();
6412 PathLength >= (int)DynType->PathLength; --PathLength) {
6413 const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
6414 if (declaresSameEntity(Class, C))
6415 return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
6416 // We can only walk across public inheritance edges.
6417 if (PathLength > (int)DynType->PathLength &&
6418 !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
6419 Class))
6420 return RuntimeCheckFailed(nullptr);
6421 }
6422
6423 // Runtime check, phase 2:
6424 // Search the dynamic type for an unambiguous public base of type C.
6425 CXXBasePaths Paths(/*FindAmbiguities=*/true,
6426 /*RecordPaths=*/true, /*DetectVirtual=*/false);
6427 if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
6428 Paths.front().Access == AS_public) {
6429 // Downcast to the dynamic type...
6430 if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
6431 return false;
6432 // ... then upcast to the chosen base class subobject.
6433 for (CXXBasePathElement &Elem : Paths.front())
6434 if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
6435 return false;
6436 return true;
6437 }
6438
6439 // Otherwise, the runtime check fails.
6440 return RuntimeCheckFailed(&Paths);
6441}
6442
6443namespace {
6444struct StartLifetimeOfUnionMemberHandler {
6445 EvalInfo &Info;
6446 const Expr *LHSExpr;
6447 const FieldDecl *Field;
6448 bool DuringInit;
6449 bool Failed = false;
6450 static const AccessKinds AccessKind = AK_Assign;
6451
6452 typedef bool result_type;
6453 bool failed() { return Failed; }
6454 bool found(APValue &Subobj, QualType SubobjType) {
6455 // We are supposed to perform no initialization but begin the lifetime of
6456 // the object. We interpret that as meaning to do what default
6457 // initialization of the object would do if all constructors involved were
6458 // trivial:
6459 // * All base, non-variant member, and array element subobjects' lifetimes
6460 // begin
6461 // * No variant members' lifetimes begin
6462 // * All scalar subobjects whose lifetimes begin have indeterminate values
6463 assert(SubobjType->isUnionType());
6464 if (declaresSameEntity(Subobj.getUnionField(), Field)) {
6465 // This union member is already active. If it's also in-lifetime, there's
6466 // nothing to do.
6467 if (Subobj.getUnionValue().hasValue())
6468 return true;
6469 } else if (DuringInit) {
6470 // We're currently in the process of initializing a different union
6471 // member. If we carried on, that initialization would attempt to
6472 // store to an inactive union member, resulting in undefined behavior.
6473 Info.FFDiag(LHSExpr,
6474 diag::note_constexpr_union_member_change_during_init);
6475 return false;
6476 }
6478 Failed = !handleDefaultInitValue(Field->getType(), Result);
6479 Subobj.setUnion(Field, Result);
6480 return true;
6481 }
6482 bool found(APSInt &Value, QualType SubobjType) {
6483 llvm_unreachable("wrong value kind for union object");
6484 }
6485 bool found(APFloat &Value, QualType SubobjType) {
6486 llvm_unreachable("wrong value kind for union object");
6487 }
6488};
6489} // end anonymous namespace
6490
6491const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
6492
6493/// Handle a builtin simple-assignment or a call to a trivial assignment
6494/// operator whose left-hand side might involve a union member access. If it
6495/// does, implicitly start the lifetime of any accessed union elements per
6496/// C++20 [class.union]5.
6497static bool MaybeHandleUnionActiveMemberChange(EvalInfo &Info,
6498 const Expr *LHSExpr,
6499 const LValue &LHS) {
6500 if (LHS.InvalidBase || LHS.Designator.Invalid)
6501 return false;
6502
6504 // C++ [class.union]p5:
6505 // define the set S(E) of subexpressions of E as follows:
6506 unsigned PathLength = LHS.Designator.Entries.size();
6507 for (const Expr *E = LHSExpr; E != nullptr;) {
6508 // -- If E is of the form A.B, S(E) contains the elements of S(A)...
6509 if (auto *ME = dyn_cast<MemberExpr>(E)) {
6510 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
6511 // Note that we can't implicitly start the lifetime of a reference,
6512 // so we don't need to proceed any further if we reach one.
6513 if (!FD || FD->getType()->isReferenceType())
6514 break;
6515
6516 // ... and also contains A.B if B names a union member ...
6517 if (FD->getParent()->isUnion()) {
6518 // ... of a non-class, non-array type, or of a class type with a
6519 // trivial default constructor that is not deleted, or an array of
6520 // such types.
6521 auto *RD =
6522 FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6523 if (!RD || RD->hasTrivialDefaultConstructor())
6524 UnionPathLengths.push_back({PathLength - 1, FD});
6525 }
6526
6527 E = ME->getBase();
6528 --PathLength;
6529 assert(declaresSameEntity(FD,
6530 LHS.Designator.Entries[PathLength]
6531 .getAsBaseOrMember().getPointer()));
6532
6533 // -- If E is of the form A[B] and is interpreted as a built-in array
6534 // subscripting operator, S(E) is [S(the array operand, if any)].
6535 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
6536 // Step over an ArrayToPointerDecay implicit cast.
6537 auto *Base = ASE->getBase()->IgnoreImplicit();
6538 if (!Base->getType()->isArrayType())
6539 break;
6540
6541 E = Base;
6542 --PathLength;
6543
6544 } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6545 // Step over a derived-to-base conversion.
6546 E = ICE->getSubExpr();
6547 if (ICE->getCastKind() == CK_NoOp)
6548 continue;
6549 if (ICE->getCastKind() != CK_DerivedToBase &&
6550 ICE->getCastKind() != CK_UncheckedDerivedToBase)
6551 break;
6552 // Walk path backwards as we walk up from the base to the derived class.
6553 for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
6554 if (Elt->isVirtual()) {
6555 // A class with virtual base classes never has a trivial default
6556 // constructor, so S(E) is empty in this case.
6557 E = nullptr;
6558 break;
6559 }
6560
6561 --PathLength;
6562 assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
6563 LHS.Designator.Entries[PathLength]
6564 .getAsBaseOrMember().getPointer()));
6565 }
6566
6567 // -- Otherwise, S(E) is empty.
6568 } else {
6569 break;
6570 }
6571 }
6572
6573 // Common case: no unions' lifetimes are started.
6574 if (UnionPathLengths.empty())
6575 return true;
6576
6577 // if modification of X [would access an inactive union member], an object
6578 // of the type of X is implicitly created
6579 CompleteObject Obj =
6580 findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
6581 if (!Obj)
6582 return false;
6583 for (std::pair<unsigned, const FieldDecl *> LengthAndField :
6584 llvm::reverse(UnionPathLengths)) {
6585 // Form a designator for the union object.
6586 SubobjectDesignator D = LHS.Designator;
6587 D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
6588
6589 bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) ==
6590 ConstructionPhase::AfterBases;
6591 StartLifetimeOfUnionMemberHandler StartLifetime{
6592 Info, LHSExpr, LengthAndField.second, DuringInit};
6593 if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
6594 return false;
6595 }
6596
6597 return true;
6598}
6599
6600static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg,
6601 CallRef Call, EvalInfo &Info, bool NonNull = false,
6602 APValue **EvaluatedArg = nullptr) {
6603 LValue LV;
6604 // Create the parameter slot and register its destruction. For a vararg
6605 // argument, create a temporary.
6606 // FIXME: For calling conventions that destroy parameters in the callee,
6607 // should we consider performing destruction when the function returns
6608 // instead?
6609 APValue &V = PVD ? Info.CurrentCall->createParam(Call, PVD, LV)
6610 : Info.CurrentCall->createTemporary(Arg, Arg->getType(),
6611 ScopeKind::Call, LV);
6612 if (!EvaluateInPlace(V, Info, LV, Arg))
6613 return false;
6614
6615 // Passing a null pointer to an __attribute__((nonnull)) parameter results in
6616 // undefined behavior, so is non-constant.
6617 if (NonNull && V.isLValue() && V.isNullPointer()) {
6618 Info.CCEDiag(Arg, diag::note_non_null_attribute_failed);
6619 return false;
6620 }
6621
6622 if (EvaluatedArg)
6623 *EvaluatedArg = &V;
6624
6625 return true;
6626}
6627
6628/// Evaluate the arguments to a function call.
6629static bool EvaluateArgs(ArrayRef<const Expr *> Args, CallRef Call,
6630 EvalInfo &Info, const FunctionDecl *Callee,
6631 bool RightToLeft = false,
6632 LValue *ObjectArg = nullptr) {
6633 bool Success = true;
6634 llvm::SmallBitVector ForbiddenNullArgs;
6635 if (Callee->hasAttr<NonNullAttr>()) {
6636 ForbiddenNullArgs.resize(Args.size());
6637 for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
6638 if (!Attr->args_size()) {
6639 ForbiddenNullArgs.set();
6640 break;
6641 } else
6642 for (auto Idx : Attr->args()) {
6643 unsigned ASTIdx = Idx.getASTIndex();
6644 if (ASTIdx >= Args.size())
6645 continue;
6646 ForbiddenNullArgs[ASTIdx] = true;
6647 }
6648 }
6649 }
6650 for (unsigned I = 0; I < Args.size(); I++) {
6651 unsigned Idx = RightToLeft ? Args.size() - I - 1 : I;
6652 const ParmVarDecl *PVD =
6653 Idx < Callee->getNumParams() ? Callee->getParamDecl(Idx) : nullptr;
6654 bool NonNull = !ForbiddenNullArgs.empty() && ForbiddenNullArgs[Idx];
6655 APValue *That = nullptr;
6656 if (!EvaluateCallArg(PVD, Args[Idx], Call, Info, NonNull, &That)) {
6657 // If we're checking for a potential constant expression, evaluate all
6658 // initializers even if some of them fail.
6659 if (!Info.noteFailure())
6660 return false;
6661 Success = false;
6662 }
6663 if (PVD && PVD->isExplicitObjectParameter() && That && That->isLValue())
6664 ObjectArg->setFrom(Info.Ctx, *That);
6665 }
6666 return Success;
6667}
6668
6669/// Perform a trivial copy from Param, which is the parameter of a copy or move
6670/// constructor or assignment operator.
6671static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param,
6672 const Expr *E, APValue &Result,
6673 bool CopyObjectRepresentation) {
6674 // Find the reference argument.
6675 CallStackFrame *Frame = Info.CurrentCall;
6676 APValue *RefValue = Info.getParamSlot(Frame->Arguments, Param);
6677 if (!RefValue) {
6678 Info.FFDiag(E);
6679 return false;
6680 }
6681
6682 // Copy out the contents of the RHS object.
6683 LValue RefLValue;
6684 RefLValue.setFrom(Info.Ctx, *RefValue);
6686 Info, E, Param->getType().getNonReferenceType(), RefLValue, Result,
6687 CopyObjectRepresentation);
6688}
6689
6690/// Evaluate a function call.
6692 const FunctionDecl *Callee,
6693 const LValue *ObjectArg, const Expr *E,
6694 ArrayRef<const Expr *> Args, CallRef Call,
6695 const Stmt *Body, EvalInfo &Info,
6696 APValue &Result, const LValue *ResultSlot) {
6697 if (!Info.CheckCallLimit(CallLoc))
6698 return false;
6699
6700 CallStackFrame Frame(Info, E->getSourceRange(), Callee, ObjectArg, E, Call);
6701
6702 // For a trivial copy or move assignment, perform an APValue copy. This is
6703 // essential for unions, where the operations performed by the assignment
6704 // operator cannot be represented as statements.
6705 //
6706 // Skip this for non-union classes with no fields; in that case, the defaulted
6707 // copy/move does not actually read the object.
6708 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
6709 if (MD && MD->isDefaulted() &&
6710 (MD->getParent()->isUnion() ||
6711 (MD->isTrivial() &&
6713 unsigned ExplicitOffset = MD->isExplicitObjectMemberFunction() ? 1 : 0;
6714 assert(ObjectArg &&
6716 APValue RHSValue;
6717 if (!handleTrivialCopy(Info, MD->getParamDecl(0), Args[0], RHSValue,
6718 MD->getParent()->isUnion()))
6719 return false;
6720
6721 LValue Obj;
6722 if (!handleAssignment(Info, Args[ExplicitOffset], *ObjectArg,
6724 RHSValue))
6725 return false;
6726 ObjectArg->moveInto(Result);
6727 return true;
6728 } else if (MD && isLambdaCallOperator(MD)) {
6729 // We're in a lambda; determine the lambda capture field maps unless we're
6730 // just constexpr checking a lambda's call operator. constexpr checking is
6731 // done before the captures have been added to the closure object (unless
6732 // we're inferring constexpr-ness), so we don't have access to them in this
6733 // case. But since we don't need the captures to constexpr check, we can
6734 // just ignore them.
6735 if (!Info.checkingPotentialConstantExpression())
6736 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
6737 Frame.LambdaThisCaptureField);
6738 }
6739
6740 StmtResult Ret = {Result, ResultSlot};
6741 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
6742 if (ESR == ESR_Succeeded) {
6743 if (Callee->getReturnType()->isVoidType())
6744 return true;
6745 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
6746 }
6747 return ESR == ESR_Returned;
6748}
6749
6750/// Evaluate a constructor call.
6751static bool HandleConstructorCall(const Expr *E, const LValue &This,
6752 CallRef Call,
6754 EvalInfo &Info, APValue &Result) {
6755 SourceLocation CallLoc = E->getExprLoc();
6756 if (!Info.CheckCallLimit(CallLoc))
6757 return false;
6758
6759 const CXXRecordDecl *RD = Definition->getParent();
6760 if (RD->getNumVBases()) {
6761 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
6762 return false;
6763 }
6764
6765 EvalInfo::EvaluatingConstructorRAII EvalObj(
6766 Info,
6767 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
6768 RD->getNumBases());
6769 CallStackFrame Frame(Info, E->getSourceRange(), Definition, &This, E, Call);
6770
6771 // FIXME: Creating an APValue just to hold a nonexistent return value is
6772 // wasteful.
6773 APValue RetVal;
6774 StmtResult Ret = {RetVal, nullptr};
6775
6776 // If it's a delegating constructor, delegate.
6777 if (Definition->isDelegatingConstructor()) {
6779 if ((*I)->getInit()->isValueDependent()) {
6780 if (!EvaluateDependentExpr((*I)->getInit(), Info))
6781 return false;
6782 } else {
6783 FullExpressionRAII InitScope(Info);
6784 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) ||
6785 !InitScope.destroy())
6786 return false;
6787 }
6788 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
6789 }
6790
6791 // For a trivial copy or move constructor, perform an APValue copy. This is
6792 // essential for unions (or classes with anonymous union members), where the
6793 // operations performed by the constructor cannot be represented by
6794 // ctor-initializers.
6795 //
6796 // Skip this for empty non-union classes; we should not perform an
6797 // lvalue-to-rvalue conversion on them because their copy constructor does not
6798 // actually read them.
6799 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
6800 (Definition->getParent()->isUnion() ||
6801 (Definition->isTrivial() &&
6803 return handleTrivialCopy(Info, Definition->getParamDecl(0), E, Result,
6804 Definition->getParent()->isUnion());
6805 }
6806
6807 // Reserve space for the struct members.
6808 if (!Result.hasValue()) {
6809 if (!RD->isUnion())
6810 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
6811 std::distance(RD->field_begin(), RD->field_end()));
6812 else
6813 // A union starts with no active member.
6814 Result = APValue((const FieldDecl*)nullptr);
6815 }
6816
6817 if (RD->isInvalidDecl()) return false;
6818 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6819
6820 // A scope for temporaries lifetime-extended by reference members.
6821 BlockScopeRAII LifetimeExtendedScope(Info);
6822
6823 bool Success = true;
6824 unsigned BasesSeen = 0;
6825#ifndef NDEBUG
6827#endif
6829 auto SkipToField = [&](FieldDecl *FD, bool Indirect) {
6830 // We might be initializing the same field again if this is an indirect
6831 // field initialization.
6832 if (FieldIt == RD->field_end() ||
6833 FieldIt->getFieldIndex() > FD->getFieldIndex()) {
6834 assert(Indirect && "fields out of order?");
6835 return;
6836 }
6837
6838 // Default-initialize any fields with no explicit initializer.
6839 for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
6840 assert(FieldIt != RD->field_end() && "missing field?");
6841 if (!FieldIt->isUnnamedBitField())
6843 FieldIt->getType(),
6844 Result.getStructField(FieldIt->getFieldIndex()));
6845 }
6846 ++FieldIt;
6847 };
6848 for (const auto *I : Definition->inits()) {
6849 LValue Subobject = This;
6850 LValue SubobjectParent = This;
6851 APValue *Value = &Result;
6852
6853 // Determine the subobject to initialize.
6854 FieldDecl *FD = nullptr;
6855 if (I->isBaseInitializer()) {
6856 QualType BaseType(I->getBaseClass(), 0);
6857#ifndef NDEBUG
6858 // Non-virtual base classes are initialized in the order in the class
6859 // definition. We have already checked for virtual base classes.
6860 assert(!BaseIt->isVirtual() && "virtual base for literal type");
6861 assert(Info.Ctx.hasSameUnqualifiedType(BaseIt->getType(), BaseType) &&
6862 "base class initializers not in expected order");
6863 ++BaseIt;
6864#endif
6865 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
6866 BaseType->getAsCXXRecordDecl(), &Layout))
6867 return false;
6868 Value = &Result.getStructBase(BasesSeen++);
6869 } else if ((FD = I->getMember())) {
6870 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
6871 return false;
6872 if (RD->isUnion()) {
6873 Result = APValue(FD);
6874 Value = &Result.getUnionValue();
6875 } else {
6876 SkipToField(FD, false);
6877 Value = &Result.getStructField(FD->getFieldIndex());
6878 }
6879 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
6880 // Walk the indirect field decl's chain to find the object to initialize,
6881 // and make sure we've initialized every step along it.
6882 auto IndirectFieldChain = IFD->chain();
6883 for (auto *C : IndirectFieldChain) {
6884 FD = cast<FieldDecl>(C);
6886 // Switch the union field if it differs. This happens if we had
6887 // preceding zero-initialization, and we're now initializing a union
6888 // subobject other than the first.
6889 // FIXME: In this case, the values of the other subobjects are
6890 // specified, since zero-initialization sets all padding bits to zero.
6891 if (!Value->hasValue() ||
6892 (Value->isUnion() &&
6893 !declaresSameEntity(Value->getUnionField(), FD))) {
6894 if (CD->isUnion())
6895 *Value = APValue(FD);
6896 else
6897 // FIXME: This immediately starts the lifetime of all members of
6898 // an anonymous struct. It would be preferable to strictly start
6899 // member lifetime in initialization order.
6901 *Value);
6902 }
6903 // Store Subobject as its parent before updating it for the last element
6904 // in the chain.
6905 if (C == IndirectFieldChain.back())
6906 SubobjectParent = Subobject;
6907 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
6908 return false;
6909 if (CD->isUnion())
6910 Value = &Value->getUnionValue();
6911 else {
6912 if (C == IndirectFieldChain.front() && !RD->isUnion())
6913 SkipToField(FD, true);
6914 Value = &Value->getStructField(FD->getFieldIndex());
6915 }
6916 }
6917 } else {
6918 llvm_unreachable("unknown base initializer kind");
6919 }
6920
6921 // Need to override This for implicit field initializers as in this case
6922 // This refers to innermost anonymous struct/union containing initializer,
6923 // not to currently constructed class.
6924 const Expr *Init = I->getInit();
6925 if (Init->isValueDependent()) {
6926 if (!EvaluateDependentExpr(Init, Info))
6927 return false;
6928 } else {
6929 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
6931 FullExpressionRAII InitScope(Info);
6932 if (FD && FD->getType()->isReferenceType() &&
6933 !FD->getType()->isFunctionReferenceType()) {
6934 LValue Result;
6935 if (!EvaluateInitForDeclOfReferenceType(Info, FD, Init, Result,
6936 *Value)) {
6937 if (!Info.noteFailure())
6938 return false;
6939 Success = false;
6940 }
6941 } else if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
6942 (FD && FD->isBitField() &&
6943 !truncateBitfieldValue(Info, Init, *Value, FD))) {
6944 // If we're checking for a potential constant expression, evaluate all
6945 // initializers even if some of them fail.
6946 if (!Info.noteFailure())
6947 return false;
6948 Success = false;
6949 }
6950 }
6951
6952 // This is the point at which the dynamic type of the object becomes this
6953 // class type.
6954 if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
6955 EvalObj.finishedConstructingBases();
6956 }
6957
6958 // Default-initialize any remaining fields.
6959 if (!RD->isUnion()) {
6960 for (; FieldIt != RD->field_end(); ++FieldIt) {
6961 if (!FieldIt->isUnnamedBitField())
6963 FieldIt->getType(),
6964 Result.getStructField(FieldIt->getFieldIndex()));
6965 }
6966 }
6967
6968 EvalObj.finishedConstructingFields();
6969
6970 return Success &&
6971 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed &&
6972 LifetimeExtendedScope.destroy();
6973}
6974
6975static bool HandleConstructorCall(const Expr *E, const LValue &This,
6978 EvalInfo &Info, APValue &Result) {
6979 CallScopeRAII CallScope(Info);
6980 CallRef Call = Info.CurrentCall->createCall(Definition);
6981 if (!EvaluateArgs(Args, Call, Info, Definition))
6982 return false;
6983
6984 return HandleConstructorCall(E, This, Call, Definition, Info, Result) &&
6985 CallScope.destroy();
6986}
6987
6988static bool HandleDestructionImpl(EvalInfo &Info, SourceRange CallRange,
6989 const LValue &This, APValue &Value,
6990 QualType T) {
6991 // Objects can only be destroyed while they're within their lifetimes.
6992 // FIXME: We have no representation for whether an object of type nullptr_t
6993 // is in its lifetime; it usually doesn't matter. Perhaps we should model it
6994 // as indeterminate instead?
6995 if (Value.isAbsent() && !T->isNullPtrType()) {
6996 APValue Printable;
6997 This.moveInto(Printable);
6998 Info.FFDiag(CallRange.getBegin(),
6999 diag::note_constexpr_destroy_out_of_lifetime)
7000 << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T));
7001 return false;
7002 }
7003
7004 // Invent an expression for location purposes.
7005 // FIXME: We shouldn't need to do this.
7006 OpaqueValueExpr LocE(CallRange.getBegin(), Info.Ctx.IntTy, VK_PRValue);
7007
7008 // For arrays, destroy elements right-to-left.
7009 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) {
7010 uint64_t Size = CAT->getZExtSize();
7011 QualType ElemT = CAT->getElementType();
7012
7013 if (!CheckArraySize(Info, CAT, CallRange.getBegin()))
7014 return false;
7015
7016 LValue ElemLV = This;
7017 ElemLV.addArray(Info, &LocE, CAT);
7018 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size))
7019 return false;
7020
7021 // Ensure that we have actual array elements available to destroy; the
7022 // destructors might mutate the value, so we can't run them on the array
7023 // filler.
7024 if (Size && Size > Value.getArrayInitializedElts())
7025 expandArray(Value, Value.getArraySize() - 1);
7026
7027 // The size of the array might have been reduced by
7028 // a placement new.
7029 for (Size = Value.getArraySize(); Size != 0; --Size) {
7030 APValue &Elem = Value.getArrayInitializedElt(Size - 1);
7031 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) ||
7032 !HandleDestructionImpl(Info, CallRange, ElemLV, Elem, ElemT))
7033 return false;
7034 }
7035
7036 // End the lifetime of this array now.
7037 Value = APValue();
7038 return true;
7039 }
7040
7041 const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
7042 if (!RD) {
7043 if (T.isDestructedType()) {
7044 Info.FFDiag(CallRange.getBegin(),
7045 diag::note_constexpr_unsupported_destruction)
7046 << T;
7047 return false;
7048 }
7049
7050 Value = APValue();
7051 return true;
7052 }
7053
7054 if (RD->getNumVBases()) {
7055 Info.FFDiag(CallRange.getBegin(), diag::note_constexpr_virtual_base) << RD;
7056 return false;
7057 }
7058
7059 const CXXDestructorDecl *DD = RD->getDestructor();
7060 if (!DD && !RD->hasTrivialDestructor()) {
7061 Info.FFDiag(CallRange.getBegin());
7062 return false;
7063 }
7064
7065 if (!DD || DD->isTrivial() ||
7066 (RD->isAnonymousStructOrUnion() && RD->isUnion())) {
7067 // A trivial destructor just ends the lifetime of the object. Check for
7068 // this case before checking for a body, because we might not bother
7069 // building a body for a trivial destructor. Note that it doesn't matter
7070 // whether the destructor is constexpr in this case; all trivial
7071 // destructors are constexpr.
7072 //
7073 // If an anonymous union would be destroyed, some enclosing destructor must
7074 // have been explicitly defined, and the anonymous union destruction should
7075 // have no effect.
7076 Value = APValue();
7077 return true;
7078 }
7079
7080 if (!Info.CheckCallLimit(CallRange.getBegin()))
7081 return false;
7082
7083 const FunctionDecl *Definition = nullptr;
7084 const Stmt *Body = DD->getBody(Definition);
7085
7086 if (!CheckConstexprFunction(Info, CallRange.getBegin(), DD, Definition, Body))
7087 return false;
7088
7089 CallStackFrame Frame(Info, CallRange, Definition, &This, /*CallExpr=*/nullptr,
7090 CallRef());
7091
7092 // We're now in the period of destruction of this object.
7093 unsigned BasesLeft = RD->getNumBases();
7094 EvalInfo::EvaluatingDestructorRAII EvalObj(
7095 Info,
7096 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries});
7097 if (!EvalObj.DidInsert) {
7098 // C++2a [class.dtor]p19:
7099 // the behavior is undefined if the destructor is invoked for an object
7100 // whose lifetime has ended
7101 // (Note that formally the lifetime ends when the period of destruction
7102 // begins, even though certain uses of the object remain valid until the
7103 // period of destruction ends.)
7104 Info.FFDiag(CallRange.getBegin(), diag::note_constexpr_double_destroy);
7105 return false;
7106 }
7107
7108 // FIXME: Creating an APValue just to hold a nonexistent return value is
7109 // wasteful.
7110 APValue RetVal;
7111 StmtResult Ret = {RetVal, nullptr};
7112 if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed)
7113 return false;
7114
7115 // A union destructor does not implicitly destroy its members.
7116 if (RD->isUnion())
7117 return true;
7118
7119 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7120
7121 // We don't have a good way to iterate fields in reverse, so collect all the
7122 // fields first and then walk them backwards.
7123 SmallVector<FieldDecl*, 16> Fields(RD->fields());
7124 for (const FieldDecl *FD : llvm::reverse(Fields)) {
7125 if (FD->isUnnamedBitField())
7126 continue;
7127
7128 LValue Subobject = This;
7129 if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout))
7130 return false;
7131
7132 APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex());
7133 if (!HandleDestructionImpl(Info, CallRange, Subobject, *SubobjectValue,
7134 FD->getType()))
7135 return false;
7136 }
7137
7138 if (BasesLeft != 0)
7139 EvalObj.startedDestroyingBases();
7140
7141 // Destroy base classes in reverse order.
7142 for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) {
7143 --BasesLeft;
7144
7145 QualType BaseType = Base.getType();
7146 LValue Subobject = This;
7147 if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD,
7148 BaseType->getAsCXXRecordDecl(), &Layout))
7149 return false;
7150
7151 APValue *SubobjectValue = &Value.getStructBase(BasesLeft);
7152 if (!HandleDestructionImpl(Info, CallRange, Subobject, *SubobjectValue,
7153 BaseType))
7154 return false;
7155 }
7156 assert(BasesLeft == 0 && "NumBases was wrong?");
7157
7158 // The period of destruction ends now. The object is gone.
7159 Value = APValue();
7160 return true;
7161}
7162
7163namespace {
7164struct DestroyObjectHandler {
7165 EvalInfo &Info;
7166 const Expr *E;
7167 const LValue &This;
7168 const AccessKinds AccessKind;
7169
7170 typedef bool result_type;
7171 bool failed() { return false; }
7172 bool found(APValue &Subobj, QualType SubobjType) {
7173 return HandleDestructionImpl(Info, E->getSourceRange(), This, Subobj,
7174 SubobjType);
7175 }
7176 bool found(APSInt &Value, QualType SubobjType) {
7177 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
7178 return false;
7179 }
7180 bool found(APFloat &Value, QualType SubobjType) {
7181 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
7182 return false;
7183 }
7184};
7185}
7186
7187/// Perform a destructor or pseudo-destructor call on the given object, which
7188/// might in general not be a complete object.
7189static bool HandleDestruction(EvalInfo &Info, const Expr *E,
7190 const LValue &This, QualType ThisType) {
7191 CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType);
7192 DestroyObjectHandler Handler = {Info, E, This, AK_Destroy};
7193 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
7194}
7195
7196/// Destroy and end the lifetime of the given complete object.
7197static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
7199 QualType T) {
7200 // If we've had an unmodeled side-effect, we can't rely on mutable state
7201 // (such as the object we're about to destroy) being correct.
7202 if (Info.EvalStatus.HasSideEffects)
7203 return false;
7204
7205 LValue LV;
7206 LV.set({LVBase});
7207 return HandleDestructionImpl(Info, Loc, LV, Value, T);
7208}
7209
7210/// Perform a call to 'operator new' or to `__builtin_operator_new'.
7211static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E,
7212 LValue &Result) {
7213 if (Info.checkingPotentialConstantExpression() ||
7214 Info.SpeculativeEvaluationDepth)
7215 return false;
7216
7217 // This is permitted only within a call to std::allocator<T>::allocate.
7218 auto Caller = Info.getStdAllocatorCaller("allocate");
7219 if (!Caller) {
7220 Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20
7221 ? diag::note_constexpr_new_untyped
7222 : diag::note_constexpr_new);
7223 return false;
7224 }
7225
7226 QualType ElemType = Caller.ElemType;
7227 if (ElemType->isIncompleteType() || ElemType->isFunctionType()) {
7228 Info.FFDiag(E->getExprLoc(),
7229 diag::note_constexpr_new_not_complete_object_type)
7230 << (ElemType->isIncompleteType() ? 0 : 1) << ElemType;
7231 return false;
7232 }
7233
7234 APSInt ByteSize;
7235 if (!EvaluateInteger(E->getArg(0), ByteSize, Info))
7236 return false;
7237 bool IsNothrow = false;
7238 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) {
7239 EvaluateIgnoredValue(Info, E->getArg(I));
7240 IsNothrow |= E->getType()->isNothrowT();
7241 }
7242
7243 CharUnits ElemSize;
7244 if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize))
7245 return false;
7246 APInt Size, Remainder;
7247 APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity());
7248 APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder);
7249 if (Remainder != 0) {
7250 // This likely indicates a bug in the implementation of 'std::allocator'.
7251 Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size)
7252 << ByteSize << APSInt(ElemSizeAP, true) << ElemType;
7253 return false;
7254 }
7255
7256 if (!Info.CheckArraySize(E->getBeginLoc(), ByteSize.getActiveBits(),
7257 Size.getZExtValue(), /*Diag=*/!IsNothrow)) {
7258 if (IsNothrow) {
7259 Result.setNull(Info.Ctx, E->getType());
7260 return true;
7261 }
7262 return false;
7263 }
7264
7265 QualType AllocType = Info.Ctx.getConstantArrayType(
7266 ElemType, Size, nullptr, ArraySizeModifier::Normal, 0);
7267 APValue *Val = Info.createHeapAlloc(Caller.Call, AllocType, Result);
7268 *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue());
7269 Result.addArray(Info, E, cast<ConstantArrayType>(AllocType));
7270 return true;
7271}
7272
7274 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
7275 if (CXXDestructorDecl *DD = RD->getDestructor())
7276 return DD->isVirtual();
7277 return false;
7278}
7279
7281 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
7282 if (CXXDestructorDecl *DD = RD->getDestructor())
7283 return DD->isVirtual() ? DD->getOperatorDelete() : nullptr;
7284 return nullptr;
7285}
7286
7287/// Check that the given object is a suitable pointer to a heap allocation that
7288/// still exists and is of the right kind for the purpose of a deletion.
7289///
7290/// On success, returns the heap allocation to deallocate. On failure, produces
7291/// a diagnostic and returns std::nullopt.
7292static std::optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E,
7293 const LValue &Pointer,
7294 DynAlloc::Kind DeallocKind) {
7295 auto PointerAsString = [&] {
7296 return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy);
7297 };
7298
7299 DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>();
7300 if (!DA) {
7301 Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc)
7302 << PointerAsString();
7303 if (Pointer.Base)
7304 NoteLValueLocation(Info, Pointer.Base);
7305 return std::nullopt;
7306 }
7307
7308 std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
7309 if (!Alloc) {
7310 Info.FFDiag(E, diag::note_constexpr_double_delete);
7311 return std::nullopt;
7312 }
7313
7314 if (DeallocKind != (*Alloc)->getKind()) {
7315 QualType AllocType = Pointer.Base.getDynamicAllocType();
7316 Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch)
7317 << DeallocKind << (*Alloc)->getKind() << AllocType;
7318 NoteLValueLocation(Info, Pointer.Base);
7319 return std::nullopt;
7320 }
7321
7322 bool Subobject = false;
7323 if (DeallocKind == DynAlloc::New) {
7324 Subobject = Pointer.Designator.MostDerivedPathLength != 0 ||
7325 Pointer.Designator.isOnePastTheEnd();
7326 } else {
7327 Subobject = Pointer.Designator.Entries.size() != 1 ||
7328 Pointer.Designator.Entries[0].getAsArrayIndex() != 0;
7329 }
7330 if (Subobject) {
7331 Info.FFDiag(E, diag::note_constexpr_delete_subobject)
7332 << PointerAsString() << Pointer.Designator.isOnePastTheEnd();
7333 return std::nullopt;
7334 }
7335
7336 return Alloc;
7337}
7338
7339// Perform a call to 'operator delete' or '__builtin_operator_delete'.
7340static bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) {
7341 if (Info.checkingPotentialConstantExpression() ||
7342 Info.SpeculativeEvaluationDepth)
7343 return false;
7344
7345 // This is permitted only within a call to std::allocator<T>::deallocate.
7346 if (!Info.getStdAllocatorCaller("deallocate")) {
7347 Info.FFDiag(E->getExprLoc());
7348 return true;
7349 }
7350
7351 LValue Pointer;
7352 if (!EvaluatePointer(E->getArg(0), Pointer, Info))
7353 return false;
7354 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
7355 EvaluateIgnoredValue(Info, E->getArg(I));
7356
7357 if (Pointer.Designator.Invalid)
7358 return false;
7359
7360 // Deleting a null pointer would have no effect, but it's not permitted by
7361 // std::allocator<T>::deallocate's contract.
7362 if (Pointer.isNullPointer()) {
7363 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_deallocate_null);
7364 return true;
7365 }
7366
7367 if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator))
7368 return false;
7369
7370 Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>());
7371 return true;
7372}
7373
7374//===----------------------------------------------------------------------===//
7375// Generic Evaluation
7376//===----------------------------------------------------------------------===//
7377namespace {
7378
7379class BitCastBuffer {
7380 // FIXME: We're going to need bit-level granularity when we support
7381 // bit-fields.
7382 // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
7383 // we don't support a host or target where that is the case. Still, we should
7384 // use a more generic type in case we ever do.
7385 SmallVector<std::optional<unsigned char>, 32> Bytes;
7386
7387 static_assert(std::numeric_limits<unsigned char>::digits >= 8,
7388 "Need at least 8 bit unsigned char");
7389
7390 bool TargetIsLittleEndian;
7391
7392public:
7393 BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
7394 : Bytes(Width.getQuantity()),
7395 TargetIsLittleEndian(TargetIsLittleEndian) {}
7396
7397 [[nodiscard]] bool readObject(CharUnits Offset, CharUnits Width,
7398 SmallVectorImpl<unsigned char> &Output) const {
7399 for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
7400 // If a byte of an integer is uninitialized, then the whole integer is
7401 // uninitialized.
7402 if (!Bytes[I.getQuantity()])
7403 return false;
7404 Output.push_back(*Bytes[I.getQuantity()]);
7405 }
7406 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
7407 std::reverse(Output.begin(), Output.end());
7408 return true;
7409 }
7410
7411 void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
7412 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
7413 std::reverse(Input.begin(), Input.end());
7414
7415 size_t Index = 0;
7416 for (unsigned char Byte : Input) {
7417 assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
7418 Bytes[Offset.getQuantity() + Index] = Byte;
7419 ++Index;
7420 }
7421 }
7422
7423 size_t size() { return Bytes.size(); }
7424};
7425
7426/// Traverse an APValue to produce an BitCastBuffer, emulating how the current
7427/// target would represent the value at runtime.
7428class APValueToBufferConverter {
7429 EvalInfo &Info;
7430 BitCastBuffer Buffer;
7431 const CastExpr *BCE;
7432
7433 APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
7434 const CastExpr *BCE)
7435 : Info(Info),
7436 Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
7437 BCE(BCE) {}
7438
7439 bool visit(const APValue &Val, QualType Ty) {
7440 return visit(Val, Ty, CharUnits::fromQuantity(0));
7441 }
7442
7443 // Write out Val with type Ty into Buffer starting at Offset.
7444 bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
7445 assert((size_t)Offset.getQuantity() <= Buffer.size());
7446
7447 // As a special case, nullptr_t has an indeterminate value.
7448 if (Ty->isNullPtrType())
7449 return true;
7450
7451 // Dig through Src to find the byte at SrcOffset.
7452 switch (Val.getKind()) {
7454 case APValue::None:
7455 return true;
7456
7457 case APValue::Int:
7458 return visitInt(Val.getInt(), Ty, Offset);
7459 case APValue::Float:
7460 return visitFloat(Val.getFloat(), Ty, Offset);
7461 case APValue::Array:
7462 return visitArray(Val, Ty, Offset);
7463 case APValue::Struct:
7464 return visitRecord(Val, Ty, Offset);
7465 case APValue::Vector:
7466 return visitVector(Val, Ty, Offset);
7467
7470 return visitComplex(Val, Ty, Offset);
7472 // FIXME: We should support these.
7473
7474 case APValue::Union:
7477 Info.FFDiag(BCE->getBeginLoc(),
7478 diag::note_constexpr_bit_cast_unsupported_type)
7479 << Ty;
7480 return false;
7481 }
7482
7483 case APValue::LValue:
7484 llvm_unreachable("LValue subobject in bit_cast?");
7485 }
7486 llvm_unreachable("Unhandled APValue::ValueKind");
7487 }
7488
7489 bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
7490 const RecordDecl *RD = Ty->getAsRecordDecl();
7491 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7492
7493 // Visit the base classes.
7494 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
7495 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
7496 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
7497 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
7498 const APValue &Base = Val.getStructBase(I);
7499
7500 // Can happen in error cases.
7501 if (!Base.isStruct())
7502 return false;
7503
7504 if (!visitRecord(Base, BS.getType(),
7505 Layout.getBaseClassOffset(BaseDecl) + Offset))
7506 return false;
7507 }
7508 }
7509
7510 // Visit the fields.
7511 unsigned FieldIdx = 0;
7512 for (FieldDecl *FD : RD->fields()) {
7513 if (FD->isBitField()) {
7514 Info.FFDiag(BCE->getBeginLoc(),
7515 diag::note_constexpr_bit_cast_unsupported_bitfield);
7516 return false;
7517 }
7518
7519 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
7520
7521 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
7522 "only bit-fields can have sub-char alignment");
7523 CharUnits FieldOffset =
7524 Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
7525 QualType FieldTy = FD->getType();
7526 if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
7527 return false;
7528 ++FieldIdx;
7529 }
7530
7531 return true;
7532 }
7533
7534 bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
7535 const auto *CAT =
7536 dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
7537 if (!CAT)
7538 return false;
7539
7540 CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
7541 unsigned NumInitializedElts = Val.getArrayInitializedElts();
7542 unsigned ArraySize = Val.getArraySize();
7543 // First, initialize the initialized elements.
7544 for (unsigned I = 0; I != NumInitializedElts; ++I) {
7545 const APValue &SubObj = Val.getArrayInitializedElt(I);
7546 if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
7547 return false;
7548 }
7549
7550 // Next, initialize the rest of the array using the filler.
7551 if (Val.hasArrayFiller()) {
7552 const APValue &Filler = Val.getArrayFiller();
7553 for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
7554 if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
7555 return false;
7556 }
7557 }
7558
7559 return true;
7560 }
7561
7562 bool visitComplex(const APValue &Val, QualType Ty, CharUnits Offset) {
7563 const ComplexType *ComplexTy = Ty->castAs<ComplexType>();
7564 QualType EltTy = ComplexTy->getElementType();
7565 CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
7566 bool IsInt = Val.isComplexInt();
7567
7568 if (IsInt) {
7569 if (!visitInt(Val.getComplexIntReal(), EltTy,
7570 Offset + (0 * EltSizeChars)))
7571 return false;
7572 if (!visitInt(Val.getComplexIntImag(), EltTy,
7573 Offset + (1 * EltSizeChars)))
7574 return false;
7575 } else {
7576 if (!visitFloat(Val.getComplexFloatReal(), EltTy,
7577 Offset + (0 * EltSizeChars)))
7578 return false;
7579 if (!visitFloat(Val.getComplexFloatImag(), EltTy,
7580 Offset + (1 * EltSizeChars)))
7581 return false;
7582 }
7583
7584 return true;
7585 }
7586
7587 bool visitVector(const APValue &Val, QualType Ty, CharUnits Offset) {
7588 const VectorType *VTy = Ty->castAs<VectorType>();
7589 QualType EltTy = VTy->getElementType();
7590 unsigned NElts = VTy->getNumElements();
7591
7592 if (VTy->isPackedVectorBoolType(Info.Ctx)) {
7593 // Special handling for OpenCL bool vectors:
7594 // Since these vectors are stored as packed bits, but we can't write
7595 // individual bits to the BitCastBuffer, we'll buffer all of the elements
7596 // together into an appropriately sized APInt and write them all out at
7597 // once. Because we don't accept vectors where NElts * EltSize isn't a
7598 // multiple of the char size, there will be no padding space, so we don't
7599 // have to worry about writing data which should have been left
7600 // uninitialized.
7601 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
7602
7603 llvm::APInt Res = llvm::APInt::getZero(NElts);
7604 for (unsigned I = 0; I < NElts; ++I) {
7605 const llvm::APSInt &EltAsInt = Val.getVectorElt(I).getInt();
7606 assert(EltAsInt.isUnsigned() && EltAsInt.getBitWidth() == 1 &&
7607 "bool vector element must be 1-bit unsigned integer!");
7608
7609 Res.insertBits(EltAsInt, BigEndian ? (NElts - I - 1) : I);
7610 }
7611
7612 SmallVector<uint8_t, 8> Bytes(NElts / 8);
7613 llvm::StoreIntToMemory(Res, &*Bytes.begin(), NElts / 8);
7614 Buffer.writeObject(Offset, Bytes);
7615 } else {
7616 // Iterate over each of the elements and write them out to the buffer at
7617 // the appropriate offset.
7618 CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
7619 for (unsigned I = 0; I < NElts; ++I) {
7620 if (!visit(Val.getVectorElt(I), EltTy, Offset + I * EltSizeChars))
7621 return false;
7622 }
7623 }
7624
7625 return true;
7626 }
7627
7628 bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
7629 APSInt AdjustedVal = Val;
7630 unsigned Width = AdjustedVal.getBitWidth();
7631 if (Ty->isBooleanType()) {
7632 Width = Info.Ctx.getTypeSize(Ty);
7633 AdjustedVal = AdjustedVal.extend(Width);
7634 }
7635
7636 SmallVector<uint8_t, 8> Bytes(Width / 8);
7637 llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8);
7638 Buffer.writeObject(Offset, Bytes);
7639 return true;
7640 }
7641
7642 bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
7643 APSInt AsInt(Val.bitcastToAPInt());
7644 return visitInt(AsInt, Ty, Offset);
7645 }
7646
7647public:
7648 static std::optional<BitCastBuffer>
7649 convert(EvalInfo &Info, const APValue &Src, const CastExpr *BCE) {
7650 CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
7651 APValueToBufferConverter Converter(Info, DstSize, BCE);
7652 if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
7653 return std::nullopt;
7654 return Converter.Buffer;
7655 }
7656};
7657
7658/// Write an BitCastBuffer into an APValue.
7659class BufferToAPValueConverter {
7660 EvalInfo &Info;
7661 const BitCastBuffer &Buffer;
7662 const CastExpr *BCE;
7663
7664 BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
7665 const CastExpr *BCE)
7666 : Info(Info), Buffer(Buffer), BCE(BCE) {}
7667
7668 // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
7669 // with an invalid type, so anything left is a deficiency on our part (FIXME).
7670 // Ideally this will be unreachable.
7671 std::nullopt_t unsupportedType(QualType Ty) {
7672 Info.FFDiag(BCE->getBeginLoc(),
7673 diag::note_constexpr_bit_cast_unsupported_type)
7674 << Ty;
7675 return std::nullopt;
7676 }
7677
7678 std::nullopt_t unrepresentableValue(QualType Ty, const APSInt &Val) {
7679 Info.FFDiag(BCE->getBeginLoc(),
7680 diag::note_constexpr_bit_cast_unrepresentable_value)
7681 << Ty << toString(Val, /*Radix=*/10);
7682 return std::nullopt;
7683 }
7684
7685 std::optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
7686 const EnumType *EnumSugar = nullptr) {
7687 if (T->isNullPtrType()) {
7688 uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
7689 return APValue((Expr *)nullptr,
7690 /*Offset=*/CharUnits::fromQuantity(NullValue),
7691 APValue::NoLValuePath{}, /*IsNullPtr=*/true);
7692 }
7693
7694 CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
7695
7696 // Work around floating point types that contain unused padding bytes. This
7697 // is really just `long double` on x86, which is the only fundamental type
7698 // with padding bytes.
7699 if (T->isRealFloatingType()) {
7700 const llvm::fltSemantics &Semantics =
7701 Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
7702 unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics);
7703 assert(NumBits % 8 == 0);
7704 CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8);
7705 if (NumBytes != SizeOf)
7706 SizeOf = NumBytes;
7707 }
7708
7709 SmallVector<uint8_t, 8> Bytes;
7710 if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
7711 // If this is std::byte or unsigned char, then its okay to store an
7712 // indeterminate value.
7713 bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
7714 bool IsUChar =
7715 !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
7716 T->isSpecificBuiltinType(BuiltinType::Char_U));
7717 if (!IsStdByte && !IsUChar) {
7718 QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
7719 Info.FFDiag(BCE->getExprLoc(),
7720 diag::note_constexpr_bit_cast_indet_dest)
7721 << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
7722 return std::nullopt;
7723 }
7724
7726 }
7727
7728 APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
7729 llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
7730
7732 Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
7733
7734 unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0));
7735 if (IntWidth != Val.getBitWidth()) {
7736 APSInt Truncated = Val.trunc(IntWidth);
7737 if (Truncated.extend(Val.getBitWidth()) != Val)
7738 return unrepresentableValue(QualType(T, 0), Val);
7739 Val = Truncated;
7740 }
7741
7742 return APValue(Val);
7743 }
7744
7745 if (T->isRealFloatingType()) {
7746 const llvm::fltSemantics &Semantics =
7747 Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
7748 return APValue(APFloat(Semantics, Val));
7749 }
7750
7751 return unsupportedType(QualType(T, 0));
7752 }
7753
7754 std::optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
7755 const RecordDecl *RD = RTy->getAsRecordDecl();
7756 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7757
7758 unsigned NumBases = 0;
7759 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
7760 NumBases = CXXRD->getNumBases();
7761
7762 APValue ResultVal(APValue::UninitStruct(), NumBases,
7763 std::distance(RD->field_begin(), RD->field_end()));
7764
7765 // Visit the base classes.
7766 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
7767 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
7768 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
7769 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
7770
7771 std::optional<APValue> SubObj = visitType(
7772 BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
7773 if (!SubObj)
7774 return std::nullopt;
7775 ResultVal.getStructBase(I) = *SubObj;
7776 }
7777 }
7778
7779 // Visit the fields.
7780 unsigned FieldIdx = 0;
7781 for (FieldDecl *FD : RD->fields()) {
7782 // FIXME: We don't currently support bit-fields. A lot of the logic for
7783 // this is in CodeGen, so we need to factor it around.
7784 if (FD->isBitField()) {
7785 Info.FFDiag(BCE->getBeginLoc(),
7786 diag::note_constexpr_bit_cast_unsupported_bitfield);
7787 return std::nullopt;
7788 }
7789
7790 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
7791 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
7792
7793 CharUnits FieldOffset =
7794 CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
7795 Offset;
7796 QualType FieldTy = FD->getType();
7797 std::optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
7798 if (!SubObj)
7799 return std::nullopt;
7800 ResultVal.getStructField(FieldIdx) = *SubObj;
7801 ++FieldIdx;
7802 }
7803
7804 return ResultVal;
7805 }
7806
7807 std::optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
7808 QualType RepresentationType =
7809 Ty->getOriginalDecl()->getDefinitionOrSelf()->getIntegerType();
7810 assert(!RepresentationType.isNull() &&
7811 "enum forward decl should be caught by Sema");
7812 const auto *AsBuiltin =
7813 RepresentationType.getCanonicalType()->castAs<BuiltinType>();
7814 // Recurse into the underlying type. Treat std::byte transparently as
7815 // unsigned char.
7816 return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
7817 }
7818
7819 std::optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
7820 size_t Size = Ty->getLimitedSize();
7821 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
7822
7823 APValue ArrayValue(APValue::UninitArray(), Size, Size);
7824 for (size_t I = 0; I != Size; ++I) {
7825 std::optional<APValue> ElementValue =
7826 visitType(Ty->getElementType(), Offset + I * ElementWidth);
7827 if (!ElementValue)
7828 return std::nullopt;
7829 ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
7830 }
7831
7832 return ArrayValue;
7833 }
7834
7835 std::optional<APValue> visit(const ComplexType *Ty, CharUnits Offset) {
7836 QualType ElementType = Ty->getElementType();
7837 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(ElementType);
7838 bool IsInt = ElementType->isIntegerType();
7839
7840 std::optional<APValue> Values[2];
7841 for (unsigned I = 0; I != 2; ++I) {
7842 Values[I] = visitType(Ty->getElementType(), Offset + I * ElementWidth);
7843 if (!Values[I])
7844 return std::nullopt;
7845 }
7846
7847 if (IsInt)
7848 return APValue(Values[0]->getInt(), Values[1]->getInt());
7849 return APValue(Values[0]->getFloat(), Values[1]->getFloat());
7850 }
7851
7852 std::optional<APValue> visit(const VectorType *VTy, CharUnits Offset) {
7853 QualType EltTy = VTy->getElementType();
7854 unsigned NElts = VTy->getNumElements();
7855 unsigned EltSize =
7856 VTy->isPackedVectorBoolType(Info.Ctx) ? 1 : Info.Ctx.getTypeSize(EltTy);
7857
7858 SmallVector<APValue, 4> Elts;
7859 Elts.reserve(NElts);
7860 if (VTy->isPackedVectorBoolType(Info.Ctx)) {
7861 // Special handling for OpenCL bool vectors:
7862 // Since these vectors are stored as packed bits, but we can't read
7863 // individual bits from the BitCastBuffer, we'll buffer all of the
7864 // elements together into an appropriately sized APInt and write them all
7865 // out at once. Because we don't accept vectors where NElts * EltSize
7866 // isn't a multiple of the char size, there will be no padding space, so
7867 // we don't have to worry about reading any padding data which didn't
7868 // actually need to be accessed.
7869 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
7870
7871 SmallVector<uint8_t, 8> Bytes;
7872 Bytes.reserve(NElts / 8);
7873 if (!Buffer.readObject(Offset, CharUnits::fromQuantity(NElts / 8), Bytes))
7874 return std::nullopt;
7875
7876 APSInt SValInt(NElts, true);
7877 llvm::LoadIntFromMemory(SValInt, &*Bytes.begin(), Bytes.size());
7878
7879 for (unsigned I = 0; I < NElts; ++I) {
7880 llvm::APInt Elt =
7881 SValInt.extractBits(1, (BigEndian ? NElts - I - 1 : I) * EltSize);
7882 Elts.emplace_back(
7883 APSInt(std::move(Elt), !EltTy->isSignedIntegerType()));
7884 }
7885 } else {
7886 // Iterate over each of the elements and read them from the buffer at
7887 // the appropriate offset.
7888 CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
7889 for (unsigned I = 0; I < NElts; ++I) {
7890 std::optional<APValue> EltValue =
7891 visitType(EltTy, Offset + I * EltSizeChars);
7892 if (!EltValue)
7893 return std::nullopt;
7894 Elts.push_back(std::move(*EltValue));
7895 }
7896 }
7897
7898 return APValue(Elts.data(), Elts.size());
7899 }
7900
7901 std::optional<APValue> visit(const Type *Ty, CharUnits Offset) {
7902 return unsupportedType(QualType(Ty, 0));
7903 }
7904
7905 std::optional<APValue> visitType(QualType Ty, CharUnits Offset) {
7906 QualType Can = Ty.getCanonicalType();
7907
7908 switch (Can->getTypeClass()) {
7909#define TYPE(Class, Base) \
7910 case Type::Class: \
7911 return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
7912#define ABSTRACT_TYPE(Class, Base)
7913#define NON_CANONICAL_TYPE(Class, Base) \
7914 case Type::Class: \
7915 llvm_unreachable("non-canonical type should be impossible!");
7916#define DEPENDENT_TYPE(Class, Base) \
7917 case Type::Class: \
7918 llvm_unreachable( \
7919 "dependent types aren't supported in the constant evaluator!");
7920#define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base) \
7921 case Type::Class: \
7922 llvm_unreachable("either dependent or not canonical!");
7923#include "clang/AST/TypeNodes.inc"
7924 }
7925 llvm_unreachable("Unhandled Type::TypeClass");
7926 }
7927
7928public:
7929 // Pull out a full value of type DstType.
7930 static std::optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
7931 const CastExpr *BCE) {
7932 BufferToAPValueConverter Converter(Info, Buffer, BCE);
7933 return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
7934 }
7935};
7936
7937static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
7938 QualType Ty, EvalInfo *Info,
7939 const ASTContext &Ctx,
7940 bool CheckingDest) {
7941 Ty = Ty.getCanonicalType();
7942
7943 auto diag = [&](int Reason) {
7944 if (Info)
7945 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
7946 << CheckingDest << (Reason == 4) << Reason;
7947 return false;
7948 };
7949 auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
7950 if (Info)
7951 Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
7952 << NoteTy << Construct << Ty;
7953 return false;
7954 };
7955
7956 if (Ty->isUnionType())
7957 return diag(0);
7958 if (Ty->isPointerType())
7959 return diag(1);
7960 if (Ty->isMemberPointerType())
7961 return diag(2);
7962 if (Ty.isVolatileQualified())
7963 return diag(3);
7964
7965 if (RecordDecl *Record = Ty->getAsRecordDecl()) {
7966 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
7967 for (CXXBaseSpecifier &BS : CXXRD->bases())
7968 if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
7969 CheckingDest))
7970 return note(1, BS.getType(), BS.getBeginLoc());
7971 }
7972 for (FieldDecl *FD : Record->fields()) {
7973 if (FD->getType()->isReferenceType())
7974 return diag(4);
7975 if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
7976 CheckingDest))
7977 return note(0, FD->getType(), FD->getBeginLoc());
7978 }
7979 }
7980
7981 if (Ty->isArrayType() &&
7982 !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
7983 Info, Ctx, CheckingDest))
7984 return false;
7985
7986 if (const auto *VTy = Ty->getAs<VectorType>()) {
7987 QualType EltTy = VTy->getElementType();
7988 unsigned NElts = VTy->getNumElements();
7989 unsigned EltSize =
7990 VTy->isPackedVectorBoolType(Ctx) ? 1 : Ctx.getTypeSize(EltTy);
7991
7992 if ((NElts * EltSize) % Ctx.getCharWidth() != 0) {
7993 // The vector's size in bits is not a multiple of the target's byte size,
7994 // so its layout is unspecified. For now, we'll simply treat these cases
7995 // as unsupported (this should only be possible with OpenCL bool vectors
7996 // whose element count isn't a multiple of the byte size).
7997 if (Info)
7998 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_vector)
7999 << QualType(VTy, 0) << EltSize << NElts << Ctx.getCharWidth();
8000 return false;
8001 }
8002
8003 if (EltTy->isRealFloatingType() &&
8004 &Ctx.getFloatTypeSemantics(EltTy) == &APFloat::x87DoubleExtended()) {
8005 // The layout for x86_fp80 vectors seems to be handled very inconsistently
8006 // by both clang and LLVM, so for now we won't allow bit_casts involving
8007 // it in a constexpr context.
8008 if (Info)
8009 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_unsupported_type)
8010 << EltTy;
8011 return false;
8012 }
8013 }
8014
8015 return true;
8016}
8017
8018static bool checkBitCastConstexprEligibility(EvalInfo *Info,
8019 const ASTContext &Ctx,
8020 const CastExpr *BCE) {
8021 bool DestOK = checkBitCastConstexprEligibilityType(
8022 BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
8023 bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
8024 BCE->getBeginLoc(),
8025 BCE->getSubExpr()->getType(), Info, Ctx, false);
8026 return SourceOK;
8027}
8028
8029static bool handleRValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
8030 const APValue &SourceRValue,
8031 const CastExpr *BCE) {
8032 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
8033 "no host or target supports non 8-bit chars");
8034
8035 if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
8036 return false;
8037
8038 // Read out SourceValue into a char buffer.
8039 std::optional<BitCastBuffer> Buffer =
8040 APValueToBufferConverter::convert(Info, SourceRValue, BCE);
8041 if (!Buffer)
8042 return false;
8043
8044 // Write out the buffer into a new APValue.
8045 std::optional<APValue> MaybeDestValue =
8046 BufferToAPValueConverter::convert(Info, *Buffer, BCE);
8047 if (!MaybeDestValue)
8048 return false;
8049
8050 DestValue = std::move(*MaybeDestValue);
8051 return true;
8052}
8053
8054static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
8055 APValue &SourceValue,
8056 const CastExpr *BCE) {
8057 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
8058 "no host or target supports non 8-bit chars");
8059 assert(SourceValue.isLValue() &&
8060 "LValueToRValueBitcast requires an lvalue operand!");
8061
8062 LValue SourceLValue;
8063 APValue SourceRValue;
8064 SourceLValue.setFrom(Info.Ctx, SourceValue);
8066 Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,
8067 SourceRValue, /*WantObjectRepresentation=*/true))
8068 return false;
8069
8070 return handleRValueToRValueBitCast(Info, DestValue, SourceRValue, BCE);
8071}
8072
8073template <class Derived>
8074class ExprEvaluatorBase
8075 : public ConstStmtVisitor<Derived, bool> {
8076private:
8077 Derived &getDerived() { return static_cast<Derived&>(*this); }
8078 bool DerivedSuccess(const APValue &V, const Expr *E) {
8079 return getDerived().Success(V, E);
8080 }
8081 bool DerivedZeroInitialization(const Expr *E) {
8082 return getDerived().ZeroInitialization(E);
8083 }
8084
8085 // Check whether a conditional operator with a non-constant condition is a
8086 // potential constant expression. If neither arm is a potential constant
8087 // expression, then the conditional operator is not either.
8088 template<typename ConditionalOperator>
8089 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
8090 assert(Info.checkingPotentialConstantExpression());
8091
8092 // Speculatively evaluate both arms.
8093 SmallVector<PartialDiagnosticAt, 8> Diag;
8094 {
8095 SpeculativeEvaluationRAII Speculate(Info, &Diag);
8096 StmtVisitorTy::Visit(E->getFalseExpr());
8097 if (Diag.empty())
8098 return;
8099 }
8100
8101 {
8102 SpeculativeEvaluationRAII Speculate(Info, &Diag);
8103 Diag.clear();
8104 StmtVisitorTy::Visit(E->getTrueExpr());
8105 if (Diag.empty())
8106 return;
8107 }
8108
8109 Error(E, diag::note_constexpr_conditional_never_const);
8110 }
8111
8112
8113 template<typename ConditionalOperator>
8114 bool HandleConditionalOperator(const ConditionalOperator *E) {
8115 bool BoolResult;
8116 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
8117 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
8118 CheckPotentialConstantConditional(E);
8119 return false;
8120 }
8121 if (Info.noteFailure()) {
8122 StmtVisitorTy::Visit(E->getTrueExpr());
8123 StmtVisitorTy::Visit(E->getFalseExpr());
8124 }
8125 return false;
8126 }
8127
8128 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
8129 return StmtVisitorTy::Visit(EvalExpr);
8130 }
8131
8132protected:
8133 EvalInfo &Info;
8134 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
8135 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
8136
8137 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
8138 return Info.CCEDiag(E, D);
8139 }
8140
8141 bool ZeroInitialization(const Expr *E) { return Error(E); }
8142
8143 bool IsConstantEvaluatedBuiltinCall(const CallExpr *E) {
8144 unsigned BuiltinOp = E->getBuiltinCallee();
8145 return BuiltinOp != 0 &&
8146 Info.Ctx.BuiltinInfo.isConstantEvaluated(BuiltinOp);
8147 }
8148
8149public:
8150 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
8151
8152 EvalInfo &getEvalInfo() { return Info; }
8153
8154 /// Report an evaluation error. This should only be called when an error is
8155 /// first discovered. When propagating an error, just return false.
8156 bool Error(const Expr *E, diag::kind D) {
8157 Info.FFDiag(E, D) << E->getSourceRange();
8158 return false;
8159 }
8160 bool Error(const Expr *E) {
8161 return Error(E, diag::note_invalid_subexpr_in_const_expr);
8162 }
8163
8164 bool VisitStmt(const Stmt *) {
8165 llvm_unreachable("Expression evaluator should not be called on stmts");
8166 }
8167 bool VisitExpr(const Expr *E) {
8168 return Error(E);
8169 }
8170
8171 bool VisitEmbedExpr(const EmbedExpr *E) {
8172 const auto It = E->begin();
8173 return StmtVisitorTy::Visit(*It);
8174 }
8175
8176 bool VisitPredefinedExpr(const PredefinedExpr *E) {
8177 return StmtVisitorTy::Visit(E->getFunctionName());
8178 }
8179 bool VisitConstantExpr(const ConstantExpr *E) {
8180 if (E->hasAPValueResult())
8181 return DerivedSuccess(E->getAPValueResult(), E);
8182
8183 return StmtVisitorTy::Visit(E->getSubExpr());
8184 }
8185
8186 bool VisitParenExpr(const ParenExpr *E)
8187 { return StmtVisitorTy::Visit(E->getSubExpr()); }
8188 bool VisitUnaryExtension(const UnaryOperator *E)
8189 { return StmtVisitorTy::Visit(E->getSubExpr()); }
8190 bool VisitUnaryPlus(const UnaryOperator *E)
8191 { return StmtVisitorTy::Visit(E->getSubExpr()); }
8192 bool VisitChooseExpr(const ChooseExpr *E)
8193 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
8194 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
8195 { return StmtVisitorTy::Visit(E->getResultExpr()); }
8196 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
8197 { return StmtVisitorTy::Visit(E->getReplacement()); }
8198 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
8199 TempVersionRAII RAII(*Info.CurrentCall);
8200 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
8201 return StmtVisitorTy::Visit(E->getExpr());
8202 }
8203 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
8204 TempVersionRAII RAII(*Info.CurrentCall);
8205 // The initializer may not have been parsed yet, or might be erroneous.
8206 if (!E->getExpr())
8207 return Error(E);
8208 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
8209 return StmtVisitorTy::Visit(E->getExpr());
8210 }
8211
8212 bool VisitExprWithCleanups(const ExprWithCleanups *E) {
8213 FullExpressionRAII Scope(Info);
8214 return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy();
8215 }
8216
8217 // Temporaries are registered when created, so we don't care about
8218 // CXXBindTemporaryExpr.
8219 bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
8220 return StmtVisitorTy::Visit(E->getSubExpr());
8221 }
8222
8223 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
8224 CCEDiag(E, diag::note_constexpr_invalid_cast)
8225 << diag::ConstexprInvalidCastKind::Reinterpret;
8226 return static_cast<Derived*>(this)->VisitCastExpr(E);
8227 }
8228 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
8229 if (!Info.Ctx.getLangOpts().CPlusPlus20)
8230 CCEDiag(E, diag::note_constexpr_invalid_cast)
8231 << diag::ConstexprInvalidCastKind::Dynamic;
8232 return static_cast<Derived*>(this)->VisitCastExpr(E);
8233 }
8234 bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
8235 return static_cast<Derived*>(this)->VisitCastExpr(E);
8236 }
8237
8238 bool VisitBinaryOperator(const BinaryOperator *E) {
8239 switch (E->getOpcode()) {
8240 default:
8241 return Error(E);
8242
8243 case BO_Comma:
8244 VisitIgnoredValue(E->getLHS());
8245 return StmtVisitorTy::Visit(E->getRHS());
8246
8247 case BO_PtrMemD:
8248 case BO_PtrMemI: {
8249 LValue Obj;
8250 if (!HandleMemberPointerAccess(Info, E, Obj))
8251 return false;
8253 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
8254 return false;
8255 return DerivedSuccess(Result, E);
8256 }
8257 }
8258 }
8259
8260 bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) {
8261 return StmtVisitorTy::Visit(E->getSemanticForm());
8262 }
8263
8264 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
8265 // Evaluate and cache the common expression. We treat it as a temporary,
8266 // even though it's not quite the same thing.
8267 LValue CommonLV;
8268 if (!Evaluate(Info.CurrentCall->createTemporary(
8269 E->getOpaqueValue(),
8270 getStorageType(Info.Ctx, E->getOpaqueValue()),
8271 ScopeKind::FullExpression, CommonLV),
8272 Info, E->getCommon()))
8273 return false;
8274
8275 return HandleConditionalOperator(E);
8276 }
8277
8278 bool VisitConditionalOperator(const ConditionalOperator *E) {
8279 bool IsBcpCall = false;
8280 // If the condition (ignoring parens) is a __builtin_constant_p call,
8281 // the result is a constant expression if it can be folded without
8282 // side-effects. This is an important GNU extension. See GCC PR38377
8283 // for discussion.
8284 if (const CallExpr *CallCE =
8285 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
8286 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
8287 IsBcpCall = true;
8288
8289 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
8290 // constant expression; we can't check whether it's potentially foldable.
8291 // FIXME: We should instead treat __builtin_constant_p as non-constant if
8292 // it would return 'false' in this mode.
8293 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
8294 return false;
8295
8296 FoldConstant Fold(Info, IsBcpCall);
8297 if (!HandleConditionalOperator(E)) {
8298 Fold.keepDiagnostics();
8299 return false;
8300 }
8301
8302 return true;
8303 }
8304
8305 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
8306 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E);
8307 Value && !Value->isAbsent())
8308 return DerivedSuccess(*Value, E);
8309
8310 const Expr *Source = E->getSourceExpr();
8311 if (!Source)
8312 return Error(E);
8313 if (Source == E) {
8314 assert(0 && "OpaqueValueExpr recursively refers to itself");
8315 return Error(E);
8316 }
8317 return StmtVisitorTy::Visit(Source);
8318 }
8319
8320 bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
8321 for (const Expr *SemE : E->semantics()) {
8322 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
8323 // FIXME: We can't handle the case where an OpaqueValueExpr is also the
8324 // result expression: there could be two different LValues that would
8325 // refer to the same object in that case, and we can't model that.
8326 if (SemE == E->getResultExpr())
8327 return Error(E);
8328
8329 // Unique OVEs get evaluated if and when we encounter them when
8330 // emitting the rest of the semantic form, rather than eagerly.
8331 if (OVE->isUnique())
8332 continue;
8333
8334 LValue LV;
8335 if (!Evaluate(Info.CurrentCall->createTemporary(
8336 OVE, getStorageType(Info.Ctx, OVE),
8337 ScopeKind::FullExpression, LV),
8338 Info, OVE->getSourceExpr()))
8339 return false;
8340 } else if (SemE == E->getResultExpr()) {
8341 if (!StmtVisitorTy::Visit(SemE))
8342 return false;
8343 } else {
8344 if (!EvaluateIgnoredValue(Info, SemE))
8345 return false;
8346 }
8347 }
8348 return true;
8349 }
8350
8351 bool VisitCallExpr(const CallExpr *E) {
8353 if (!handleCallExpr(E, Result, nullptr))
8354 return false;
8355 return DerivedSuccess(Result, E);
8356 }
8357
8358 bool handleCallExpr(const CallExpr *E, APValue &Result,
8359 const LValue *ResultSlot) {
8360 CallScopeRAII CallScope(Info);
8361
8362 const Expr *Callee = E->getCallee()->IgnoreParens();
8363 QualType CalleeType = Callee->getType();
8364
8365 const FunctionDecl *FD = nullptr;
8366 LValue *This = nullptr, ObjectArg;
8367 auto Args = ArrayRef(E->getArgs(), E->getNumArgs());
8368 bool HasQualifier = false;
8369
8370 CallRef Call;
8371
8372 // Extract function decl and 'this' pointer from the callee.
8373 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
8374 const CXXMethodDecl *Member = nullptr;
8375 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
8376 // Explicit bound member calls, such as x.f() or p->g();
8377 if (!EvaluateObjectArgument(Info, ME->getBase(), ObjectArg))
8378 return false;
8379 Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
8380 if (!Member)
8381 return Error(Callee);
8382 This = &ObjectArg;
8383 HasQualifier = ME->hasQualifier();
8384 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
8385 // Indirect bound member calls ('.*' or '->*').
8386 const ValueDecl *D =
8387 HandleMemberPointerAccess(Info, BE, ObjectArg, false);
8388 if (!D)
8389 return false;
8390 Member = dyn_cast<CXXMethodDecl>(D);
8391 if (!Member)
8392 return Error(Callee);
8393 This = &ObjectArg;
8394 } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
8395 if (!Info.getLangOpts().CPlusPlus20)
8396 Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
8397 return EvaluateObjectArgument(Info, PDE->getBase(), ObjectArg) &&
8398 HandleDestruction(Info, PDE, ObjectArg, PDE->getDestroyedType());
8399 } else
8400 return Error(Callee);
8401 FD = Member;
8402 } else if (CalleeType->isFunctionPointerType()) {
8403 LValue CalleeLV;
8404 if (!EvaluatePointer(Callee, CalleeLV, Info))
8405 return false;
8406
8407 if (!CalleeLV.getLValueOffset().isZero())
8408 return Error(Callee);
8409 if (CalleeLV.isNullPointer()) {
8410 Info.FFDiag(Callee, diag::note_constexpr_null_callee)
8411 << const_cast<Expr *>(Callee);
8412 return false;
8413 }
8414 FD = dyn_cast_or_null<FunctionDecl>(
8415 CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>());
8416 if (!FD)
8417 return Error(Callee);
8418 // Don't call function pointers which have been cast to some other type.
8419 // Per DR (no number yet), the caller and callee can differ in noexcept.
8421 CalleeType->getPointeeType(), FD->getType())) {
8422 return Error(E);
8423 }
8424
8425 // For an (overloaded) assignment expression, evaluate the RHS before the
8426 // LHS.
8427 auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
8428 if (OCE && OCE->isAssignmentOp()) {
8429 assert(Args.size() == 2 && "wrong number of arguments in assignment");
8430 Call = Info.CurrentCall->createCall(FD);
8431 bool HasThis = false;
8432 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
8433 HasThis = MD->isImplicitObjectMemberFunction();
8434 if (!EvaluateArgs(HasThis ? Args.slice(1) : Args, Call, Info, FD,
8435 /*RightToLeft=*/true, &ObjectArg))
8436 return false;
8437 }
8438
8439 // Overloaded operator calls to member functions are represented as normal
8440 // calls with '*this' as the first argument.
8441 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8442 if (MD &&
8443 (MD->isImplicitObjectMemberFunction() || (OCE && MD->isStatic()))) {
8444 // FIXME: When selecting an implicit conversion for an overloaded
8445 // operator delete, we sometimes try to evaluate calls to conversion
8446 // operators without a 'this' parameter!
8447 if (Args.empty())
8448 return Error(E);
8449
8450 if (!EvaluateObjectArgument(Info, Args[0], ObjectArg))
8451 return false;
8452
8453 // If we are calling a static operator, the 'this' argument needs to be
8454 // ignored after being evaluated.
8455 if (MD->isInstance())
8456 This = &ObjectArg;
8457
8458 // If this is syntactically a simple assignment using a trivial
8459 // assignment operator, start the lifetimes of union members as needed,
8460 // per C++20 [class.union]5.
8461 if (Info.getLangOpts().CPlusPlus20 && OCE &&
8462 OCE->getOperator() == OO_Equal && MD->isTrivial() &&
8463 !MaybeHandleUnionActiveMemberChange(Info, Args[0], ObjectArg))
8464 return false;
8465
8466 Args = Args.slice(1);
8467 } else if (MD && MD->isLambdaStaticInvoker()) {
8468 // Map the static invoker for the lambda back to the call operator.
8469 // Conveniently, we don't have to slice out the 'this' argument (as is
8470 // being done for the non-static case), since a static member function
8471 // doesn't have an implicit argument passed in.
8472 const CXXRecordDecl *ClosureClass = MD->getParent();
8473 assert(
8474 ClosureClass->captures().empty() &&
8475 "Number of captures must be zero for conversion to function-ptr");
8476
8477 const CXXMethodDecl *LambdaCallOp =
8478 ClosureClass->getLambdaCallOperator();
8479
8480 // Set 'FD', the function that will be called below, to the call
8481 // operator. If the closure object represents a generic lambda, find
8482 // the corresponding specialization of the call operator.
8483
8484 if (ClosureClass->isGenericLambda()) {
8485 assert(MD->isFunctionTemplateSpecialization() &&
8486 "A generic lambda's static-invoker function must be a "
8487 "template specialization");
8488 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
8489 FunctionTemplateDecl *CallOpTemplate =
8490 LambdaCallOp->getDescribedFunctionTemplate();
8491 void *InsertPos = nullptr;
8492 FunctionDecl *CorrespondingCallOpSpecialization =
8493 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
8494 assert(CorrespondingCallOpSpecialization &&
8495 "We must always have a function call operator specialization "
8496 "that corresponds to our static invoker specialization");
8497 assert(isa<CXXMethodDecl>(CorrespondingCallOpSpecialization));
8498 FD = CorrespondingCallOpSpecialization;
8499 } else
8500 FD = LambdaCallOp;
8502 if (FD->getDeclName().isAnyOperatorNew()) {
8503 LValue Ptr;
8504 if (!HandleOperatorNewCall(Info, E, Ptr))
8505 return false;
8506 Ptr.moveInto(Result);
8507 return CallScope.destroy();
8508 } else {
8509 return HandleOperatorDeleteCall(Info, E) && CallScope.destroy();
8510 }
8511 }
8512 } else
8513 return Error(E);
8514
8515 // Evaluate the arguments now if we've not already done so.
8516 if (!Call) {
8517 Call = Info.CurrentCall->createCall(FD);
8518 if (!EvaluateArgs(Args, Call, Info, FD, /*RightToLeft*/ false,
8519 &ObjectArg))
8520 return false;
8521 }
8522
8523 SmallVector<QualType, 4> CovariantAdjustmentPath;
8524 if (This) {
8525 auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
8526 if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
8527 // Perform virtual dispatch, if necessary.
8528 FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
8529 CovariantAdjustmentPath);
8530 if (!FD)
8531 return false;
8532 } else if (NamedMember && NamedMember->isImplicitObjectMemberFunction()) {
8533 // Check that the 'this' pointer points to an object of the right type.
8534 // FIXME: If this is an assignment operator call, we may need to change
8535 // the active union member before we check this.
8536 if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
8537 return false;
8538 }
8539 }
8540
8541 // Destructor calls are different enough that they have their own codepath.
8542 if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
8543 assert(This && "no 'this' pointer for destructor call");
8544 return HandleDestruction(Info, E, *This,
8545 Info.Ctx.getCanonicalTagType(DD->getParent())) &&
8546 CallScope.destroy();
8547 }
8548
8549 const FunctionDecl *Definition = nullptr;
8550 Stmt *Body = FD->getBody(Definition);
8551 SourceLocation Loc = E->getExprLoc();
8552
8553 // Treat the object argument as `this` when evaluating defaulted
8554 // special menmber functions
8556 This = &ObjectArg;
8557
8558 if (!CheckConstexprFunction(Info, Loc, FD, Definition, Body) ||
8559 !HandleFunctionCall(Loc, Definition, This, E, Args, Call, Body, Info,
8560 Result, ResultSlot))
8561 return false;
8562
8563 if (!CovariantAdjustmentPath.empty() &&
8565 CovariantAdjustmentPath))
8566 return false;
8567
8568 return CallScope.destroy();
8569 }
8570
8571 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
8572 return StmtVisitorTy::Visit(E->getInitializer());
8573 }
8574 bool VisitInitListExpr(const InitListExpr *E) {
8575 if (E->getNumInits() == 0)
8576 return DerivedZeroInitialization(E);
8577 if (E->getNumInits() == 1)
8578 return StmtVisitorTy::Visit(E->getInit(0));
8579 return Error(E);
8580 }
8581 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
8582 return DerivedZeroInitialization(E);
8583 }
8584 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
8585 return DerivedZeroInitialization(E);
8586 }
8587 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
8588 return DerivedZeroInitialization(E);
8589 }
8590
8591 /// A member expression where the object is a prvalue is itself a prvalue.
8592 bool VisitMemberExpr(const MemberExpr *E) {
8593 assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
8594 "missing temporary materialization conversion");
8595 assert(!E->isArrow() && "missing call to bound member function?");
8596
8597 APValue Val;
8598 if (!Evaluate(Val, Info, E->getBase()))
8599 return false;
8600
8601 QualType BaseTy = E->getBase()->getType();
8602
8603 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
8604 if (!FD) return Error(E);
8605 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
8606 assert(BaseTy->castAsCanonical<RecordType>()->getOriginalDecl() ==
8607 FD->getParent()->getCanonicalDecl() &&
8608 "record / field mismatch");
8609
8610 // Note: there is no lvalue base here. But this case should only ever
8611 // happen in C or in C++98, where we cannot be evaluating a constexpr
8612 // constructor, which is the only case the base matters.
8613 CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
8614 SubobjectDesignator Designator(BaseTy);
8615 Designator.addDeclUnchecked(FD);
8616
8618 return extractSubobject(Info, E, Obj, Designator, Result) &&
8619 DerivedSuccess(Result, E);
8620 }
8621
8622 bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) {
8623 APValue Val;
8624 if (!Evaluate(Val, Info, E->getBase()))
8625 return false;
8626
8627 if (Val.isVector()) {
8628 SmallVector<uint32_t, 4> Indices;
8629 E->getEncodedElementAccess(Indices);
8630 if (Indices.size() == 1) {
8631 // Return scalar.
8632 return DerivedSuccess(Val.getVectorElt(Indices[0]), E);
8633 } else {
8634 // Construct new APValue vector.
8635 SmallVector<APValue, 4> Elts;
8636 for (unsigned I = 0; I < Indices.size(); ++I) {
8637 Elts.push_back(Val.getVectorElt(Indices[I]));
8638 }
8639 APValue VecResult(Elts.data(), Indices.size());
8640 return DerivedSuccess(VecResult, E);
8641 }
8642 }
8643
8644 return false;
8645 }
8646
8647 bool VisitCastExpr(const CastExpr *E) {
8648 switch (E->getCastKind()) {
8649 default:
8650 break;
8651
8652 case CK_AtomicToNonAtomic: {
8653 APValue AtomicVal;
8654 // This does not need to be done in place even for class/array types:
8655 // atomic-to-non-atomic conversion implies copying the object
8656 // representation.
8657 if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
8658 return false;
8659 return DerivedSuccess(AtomicVal, E);
8660 }
8661
8662 case CK_NoOp:
8663 case CK_UserDefinedConversion:
8664 return StmtVisitorTy::Visit(E->getSubExpr());
8665
8666 case CK_LValueToRValue: {
8667 LValue LVal;
8668 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
8669 return false;
8670 APValue RVal;
8671 // Note, we use the subexpression's type in order to retain cv-qualifiers.
8673 LVal, RVal))
8674 return false;
8675 return DerivedSuccess(RVal, E);
8676 }
8677 case CK_LValueToRValueBitCast: {
8678 APValue DestValue, SourceValue;
8679 if (!Evaluate(SourceValue, Info, E->getSubExpr()))
8680 return false;
8681 if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
8682 return false;
8683 return DerivedSuccess(DestValue, E);
8684 }
8685
8686 case CK_AddressSpaceConversion: {
8687 APValue Value;
8688 if (!Evaluate(Value, Info, E->getSubExpr()))
8689 return false;
8690 return DerivedSuccess(Value, E);
8691 }
8692 }
8693
8694 return Error(E);
8695 }
8696
8697 bool VisitUnaryPostInc(const UnaryOperator *UO) {
8698 return VisitUnaryPostIncDec(UO);
8699 }
8700 bool VisitUnaryPostDec(const UnaryOperator *UO) {
8701 return VisitUnaryPostIncDec(UO);
8702 }
8703 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
8704 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8705 return Error(UO);
8706
8707 LValue LVal;
8708 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
8709 return false;
8710 APValue RVal;
8711 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
8712 UO->isIncrementOp(), &RVal))
8713 return false;
8714 return DerivedSuccess(RVal, UO);
8715 }
8716
8717 bool VisitStmtExpr(const StmtExpr *E) {
8718 // We will have checked the full-expressions inside the statement expression
8719 // when they were completed, and don't need to check them again now.
8720 llvm::SaveAndRestore NotCheckingForUB(Info.CheckingForUndefinedBehavior,
8721 false);
8722
8723 const CompoundStmt *CS = E->getSubStmt();
8724 if (CS->body_empty())
8725 return true;
8726
8727 BlockScopeRAII Scope(Info);
8729 BE = CS->body_end();
8730 /**/; ++BI) {
8731 if (BI + 1 == BE) {
8732 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
8733 if (!FinalExpr) {
8734 Info.FFDiag((*BI)->getBeginLoc(),
8735 diag::note_constexpr_stmt_expr_unsupported);
8736 return false;
8737 }
8738 return this->Visit(FinalExpr) && Scope.destroy();
8739 }
8740
8742 StmtResult Result = { ReturnValue, nullptr };
8743 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
8744 if (ESR != ESR_Succeeded) {
8745 // FIXME: If the statement-expression terminated due to 'return',
8746 // 'break', or 'continue', it would be nice to propagate that to
8747 // the outer statement evaluation rather than bailing out.
8748 if (ESR != ESR_Failed)
8749 Info.FFDiag((*BI)->getBeginLoc(),
8750 diag::note_constexpr_stmt_expr_unsupported);
8751 return false;
8752 }
8753 }
8754
8755 llvm_unreachable("Return from function from the loop above.");
8756 }
8757
8758 bool VisitPackIndexingExpr(const PackIndexingExpr *E) {
8759 return StmtVisitorTy::Visit(E->getSelectedExpr());
8760 }
8761
8762 /// Visit a value which is evaluated, but whose value is ignored.
8763 void VisitIgnoredValue(const Expr *E) {
8764 EvaluateIgnoredValue(Info, E);
8765 }
8766
8767 /// Potentially visit a MemberExpr's base expression.
8768 void VisitIgnoredBaseExpression(const Expr *E) {
8769 // While MSVC doesn't evaluate the base expression, it does diagnose the
8770 // presence of side-effecting behavior.
8771 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
8772 return;
8773 VisitIgnoredValue(E);
8774 }
8775};
8776
8777} // namespace
8778
8779//===----------------------------------------------------------------------===//
8780// Common base class for lvalue and temporary evaluation.
8781//===----------------------------------------------------------------------===//
8782namespace {
8783template<class Derived>
8784class LValueExprEvaluatorBase
8785 : public ExprEvaluatorBase<Derived> {
8786protected:
8787 LValue &Result;
8788 bool InvalidBaseOK;
8789 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
8790 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
8791
8792 bool Success(APValue::LValueBase B) {
8793 Result.set(B);
8794 return true;
8795 }
8796
8797 bool evaluatePointer(const Expr *E, LValue &Result) {
8798 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
8799 }
8800
8801public:
8802 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
8803 : ExprEvaluatorBaseTy(Info), Result(Result),
8804 InvalidBaseOK(InvalidBaseOK) {}
8805
8806 bool Success(const APValue &V, const Expr *E) {
8807 Result.setFrom(this->Info.Ctx, V);
8808 return true;
8809 }
8810
8811 bool VisitMemberExpr(const MemberExpr *E) {
8812 // Handle non-static data members.
8813 QualType BaseTy;
8814 bool EvalOK;
8815 if (E->isArrow()) {
8816 EvalOK = evaluatePointer(E->getBase(), Result);
8817 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
8818 } else if (E->getBase()->isPRValue()) {
8819 assert(E->getBase()->getType()->isRecordType());
8820 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
8821 BaseTy = E->getBase()->getType();
8822 } else {
8823 EvalOK = this->Visit(E->getBase());
8824 BaseTy = E->getBase()->getType();
8825 }
8826 if (!EvalOK) {
8827 if (!InvalidBaseOK)
8828 return false;
8829 Result.setInvalid(E);
8830 return true;
8831 }
8832
8833 const ValueDecl *MD = E->getMemberDecl();
8834 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
8835 assert(BaseTy->castAsCanonical<RecordType>()->getOriginalDecl() ==
8836 FD->getParent()->getCanonicalDecl() &&
8837 "record / field mismatch");
8838 (void)BaseTy;
8839 if (!HandleLValueMember(this->Info, E, Result, FD))
8840 return false;
8841 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
8842 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
8843 return false;
8844 } else
8845 return this->Error(E);
8846
8847 if (MD->getType()->isReferenceType()) {
8848 APValue RefValue;
8849 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
8850 RefValue))
8851 return false;
8852 return Success(RefValue, E);
8853 }
8854 return true;
8855 }
8856
8857 bool VisitBinaryOperator(const BinaryOperator *E) {
8858 switch (E->getOpcode()) {
8859 default:
8860 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8861
8862 case BO_PtrMemD:
8863 case BO_PtrMemI:
8864 return HandleMemberPointerAccess(this->Info, E, Result);
8865 }
8866 }
8867
8868 bool VisitCastExpr(const CastExpr *E) {
8869 switch (E->getCastKind()) {
8870 default:
8871 return ExprEvaluatorBaseTy::VisitCastExpr(E);
8872
8873 case CK_DerivedToBase:
8874 case CK_UncheckedDerivedToBase:
8875 if (!this->Visit(E->getSubExpr()))
8876 return false;
8877
8878 // Now figure out the necessary offset to add to the base LV to get from
8879 // the derived class to the base class.
8880 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
8881 Result);
8882 }
8883 }
8884};
8885}
8886
8887//===----------------------------------------------------------------------===//
8888// LValue Evaluation
8889//
8890// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
8891// function designators (in C), decl references to void objects (in C), and
8892// temporaries (if building with -Wno-address-of-temporary).
8893//
8894// LValue evaluation produces values comprising a base expression of one of the
8895// following types:
8896// - Declarations
8897// * VarDecl
8898// * FunctionDecl
8899// - Literals
8900// * CompoundLiteralExpr in C (and in global scope in C++)
8901// * StringLiteral
8902// * PredefinedExpr
8903// * ObjCStringLiteralExpr
8904// * ObjCEncodeExpr
8905// * AddrLabelExpr
8906// * BlockExpr
8907// * CallExpr for a MakeStringConstant builtin
8908// - typeid(T) expressions, as TypeInfoLValues
8909// - Locals and temporaries
8910// * MaterializeTemporaryExpr
8911// * Any Expr, with a CallIndex indicating the function in which the temporary
8912// was evaluated, for cases where the MaterializeTemporaryExpr is missing
8913// from the AST (FIXME).
8914// * A MaterializeTemporaryExpr that has static storage duration, with no
8915// CallIndex, for a lifetime-extended temporary.
8916// * The ConstantExpr that is currently being evaluated during evaluation of an
8917// immediate invocation.
8918// plus an offset in bytes.
8919//===----------------------------------------------------------------------===//
8920namespace {
8921class LValueExprEvaluator
8922 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
8923public:
8924 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
8925 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
8926
8927 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
8928 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
8929
8930 bool VisitCallExpr(const CallExpr *E);
8931 bool VisitDeclRefExpr(const DeclRefExpr *E);
8932 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
8933 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
8934 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
8935 bool VisitMemberExpr(const MemberExpr *E);
8936 bool VisitStringLiteral(const StringLiteral *E) {
8937 return Success(APValue::LValueBase(
8938 E, 0, Info.getASTContext().getNextStringLiteralVersion()));
8939 }
8940 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
8941 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
8942 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
8943 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
8944 bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E);
8945 bool VisitUnaryDeref(const UnaryOperator *E);
8946 bool VisitUnaryReal(const UnaryOperator *E);
8947 bool VisitUnaryImag(const UnaryOperator *E);
8948 bool VisitUnaryPreInc(const UnaryOperator *UO) {
8949 return VisitUnaryPreIncDec(UO);
8950 }
8951 bool VisitUnaryPreDec(const UnaryOperator *UO) {
8952 return VisitUnaryPreIncDec(UO);
8953 }
8954 bool VisitBinAssign(const BinaryOperator *BO);
8955 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
8956
8957 bool VisitCastExpr(const CastExpr *E) {
8958 switch (E->getCastKind()) {
8959 default:
8960 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
8961
8962 case CK_LValueBitCast:
8963 this->CCEDiag(E, diag::note_constexpr_invalid_cast)
8964 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
8965 << Info.Ctx.getLangOpts().CPlusPlus;
8966 if (!Visit(E->getSubExpr()))
8967 return false;
8968 Result.Designator.setInvalid();
8969 return true;
8970
8971 case CK_BaseToDerived:
8972 if (!Visit(E->getSubExpr()))
8973 return false;
8974 return HandleBaseToDerivedCast(Info, E, Result);
8975
8976 case CK_Dynamic:
8977 if (!Visit(E->getSubExpr()))
8978 return false;
8980 }
8981 }
8982};
8983} // end anonymous namespace
8984
8985/// Get an lvalue to a field of a lambda's closure type.
8986static bool HandleLambdaCapture(EvalInfo &Info, const Expr *E, LValue &Result,
8987 const CXXMethodDecl *MD, const FieldDecl *FD,
8988 bool LValueToRValueConversion) {
8989 // Static lambda function call operators can't have captures. We already
8990 // diagnosed this, so bail out here.
8991 if (MD->isStatic()) {
8992 assert(Info.CurrentCall->This == nullptr &&
8993 "This should not be set for a static call operator");
8994 return false;
8995 }
8996
8997 // Start with 'Result' referring to the complete closure object...
8999 // Self may be passed by reference or by value.
9000 const ParmVarDecl *Self = MD->getParamDecl(0);
9001 if (Self->getType()->isReferenceType()) {
9002 APValue *RefValue = Info.getParamSlot(Info.CurrentCall->Arguments, Self);
9003 if (!RefValue->allowConstexprUnknown() || RefValue->hasValue())
9004 Result.setFrom(Info.Ctx, *RefValue);
9005 } else {
9006 const ParmVarDecl *VD = Info.CurrentCall->Arguments.getOrigParam(Self);
9007 CallStackFrame *Frame =
9008 Info.getCallFrameAndDepth(Info.CurrentCall->Arguments.CallIndex)
9009 .first;
9010 unsigned Version = Info.CurrentCall->Arguments.Version;
9011 Result.set({VD, Frame->Index, Version});
9012 }
9013 } else
9014 Result = *Info.CurrentCall->This;
9015
9016 // ... then update it to refer to the field of the closure object
9017 // that represents the capture.
9018 if (!HandleLValueMember(Info, E, Result, FD))
9019 return false;
9020
9021 // And if the field is of reference type (or if we captured '*this' by
9022 // reference), update 'Result' to refer to what
9023 // the field refers to.
9024 if (LValueToRValueConversion) {
9025 APValue RVal;
9026 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result, RVal))
9027 return false;
9028 Result.setFrom(Info.Ctx, RVal);
9029 }
9030 return true;
9031}
9032
9033/// Evaluate an expression as an lvalue. This can be legitimately called on
9034/// expressions which are not glvalues, in three cases:
9035/// * function designators in C, and
9036/// * "extern void" objects
9037/// * @selector() expressions in Objective-C
9038static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
9039 bool InvalidBaseOK) {
9040 assert(!E->isValueDependent());
9041 assert(E->isGLValue() || E->getType()->isFunctionType() ||
9043 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
9044}
9045
9046bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
9047 const ValueDecl *D = E->getDecl();
9048
9049 // If we are within a lambda's call operator, check whether the 'VD' referred
9050 // to within 'E' actually represents a lambda-capture that maps to a
9051 // data-member/field within the closure object, and if so, evaluate to the
9052 // field or what the field refers to.
9053 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
9055 // We don't always have a complete capture-map when checking or inferring if
9056 // the function call operator meets the requirements of a constexpr function
9057 // - but we don't need to evaluate the captures to determine constexprness
9058 // (dcl.constexpr C++17).
9059 if (Info.checkingPotentialConstantExpression())
9060 return false;
9061
9062 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(D)) {
9063 const auto *MD = cast<CXXMethodDecl>(Info.CurrentCall->Callee);
9064 return HandleLambdaCapture(Info, E, Result, MD, FD,
9065 FD->getType()->isReferenceType());
9066 }
9067 }
9068
9069 if (isa<FunctionDecl, MSGuidDecl, TemplateParamObjectDecl,
9070 UnnamedGlobalConstantDecl>(D))
9071 return Success(cast<ValueDecl>(D));
9072 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
9073 return VisitVarDecl(E, VD);
9074 if (const BindingDecl *BD = dyn_cast<BindingDecl>(D))
9075 return Visit(BD->getBinding());
9076 return Error(E);
9077}
9078
9079bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
9080 CallStackFrame *Frame = nullptr;
9081 unsigned Version = 0;
9082 if (VD->hasLocalStorage()) {
9083 // Only if a local variable was declared in the function currently being
9084 // evaluated, do we expect to be able to find its value in the current
9085 // frame. (Otherwise it was likely declared in an enclosing context and
9086 // could either have a valid evaluatable value (for e.g. a constexpr
9087 // variable) or be ill-formed (and trigger an appropriate evaluation
9088 // diagnostic)).
9089 CallStackFrame *CurrFrame = Info.CurrentCall;
9090 if (CurrFrame->Callee && CurrFrame->Callee->Equals(VD->getDeclContext())) {
9091 // Function parameters are stored in some caller's frame. (Usually the
9092 // immediate caller, but for an inherited constructor they may be more
9093 // distant.)
9094 if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) {
9095 if (CurrFrame->Arguments) {
9096 VD = CurrFrame->Arguments.getOrigParam(PVD);
9097 Frame =
9098 Info.getCallFrameAndDepth(CurrFrame->Arguments.CallIndex).first;
9099 Version = CurrFrame->Arguments.Version;
9100 }
9101 } else {
9102 Frame = CurrFrame;
9103 Version = CurrFrame->getCurrentTemporaryVersion(VD);
9104 }
9105 }
9106 }
9107
9108 if (!VD->getType()->isReferenceType()) {
9109 if (Frame) {
9110 Result.set({VD, Frame->Index, Version});
9111 return true;
9112 }
9113 return Success(VD);
9114 }
9115
9116 if (!Info.getLangOpts().CPlusPlus11) {
9117 Info.CCEDiag(E, diag::note_constexpr_ltor_non_integral, 1)
9118 << VD << VD->getType();
9119 Info.Note(VD->getLocation(), diag::note_declared_at);
9120 }
9121
9122 APValue *V;
9123 if (!evaluateVarDeclInit(Info, E, VD, Frame, Version, V))
9124 return false;
9125
9126 if (!V) {
9127 Result.set(VD);
9128 Result.AllowConstexprUnknown = true;
9129 return true;
9130 }
9131
9132 return Success(*V, E);
9133}
9134
9135bool LValueExprEvaluator::VisitCallExpr(const CallExpr *E) {
9136 if (!IsConstantEvaluatedBuiltinCall(E))
9137 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9138
9139 switch (E->getBuiltinCallee()) {
9140 default:
9141 return false;
9142 case Builtin::BIas_const:
9143 case Builtin::BIforward:
9144 case Builtin::BIforward_like:
9145 case Builtin::BImove:
9146 case Builtin::BImove_if_noexcept:
9147 if (cast<FunctionDecl>(E->getCalleeDecl())->isConstexpr())
9148 return Visit(E->getArg(0));
9149 break;
9150 }
9151
9152 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9153}
9154
9155bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
9156 const MaterializeTemporaryExpr *E) {
9157 // Walk through the expression to find the materialized temporary itself.
9160 const Expr *Inner =
9161 E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
9162
9163 // If we passed any comma operators, evaluate their LHSs.
9164 for (const Expr *E : CommaLHSs)
9165 if (!EvaluateIgnoredValue(Info, E))
9166 return false;
9167
9168 // A materialized temporary with static storage duration can appear within the
9169 // result of a constant expression evaluation, so we need to preserve its
9170 // value for use outside this evaluation.
9171 APValue *Value;
9172 if (E->getStorageDuration() == SD_Static) {
9173 if (Info.EvalMode == EvaluationMode::ConstantFold)
9174 return false;
9175 // FIXME: What about SD_Thread?
9176 Value = E->getOrCreateValue(true);
9177 *Value = APValue();
9178 Result.set(E);
9179 } else {
9180 Value = &Info.CurrentCall->createTemporary(
9181 E, Inner->getType(),
9182 E->getStorageDuration() == SD_FullExpression ? ScopeKind::FullExpression
9183 : ScopeKind::Block,
9184 Result);
9185 }
9186
9187 QualType Type = Inner->getType();
9188
9189 // Materialize the temporary itself.
9190 if (!EvaluateInPlace(*Value, Info, Result, Inner)) {
9191 *Value = APValue();
9192 return false;
9193 }
9194
9195 // Adjust our lvalue to refer to the desired subobject.
9196 for (unsigned I = Adjustments.size(); I != 0; /**/) {
9197 --I;
9198 switch (Adjustments[I].Kind) {
9200 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
9201 Type, Result))
9202 return false;
9203 Type = Adjustments[I].DerivedToBase.BasePath->getType();
9204 break;
9205
9207 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
9208 return false;
9209 Type = Adjustments[I].Field->getType();
9210 break;
9211
9213 if (!HandleMemberPointerAccess(this->Info, Type, Result,
9214 Adjustments[I].Ptr.RHS))
9215 return false;
9216 Type = Adjustments[I].Ptr.MPT->getPointeeType();
9217 break;
9218 }
9219 }
9220
9221 return true;
9222}
9223
9224bool
9225LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
9226 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
9227 "lvalue compound literal in c++?");
9228 APValue *Lit;
9229 // If CompountLiteral has static storage, its value can be used outside
9230 // this expression. So evaluate it once and store it in ASTContext.
9231 if (E->hasStaticStorage()) {
9232 Lit = &E->getOrCreateStaticValue(Info.Ctx);
9233 Result.set(E);
9234 // Reset any previously evaluated state, otherwise evaluation below might
9235 // fail.
9236 // FIXME: Should we just re-use the previously evaluated value instead?
9237 *Lit = APValue();
9238 } else {
9239 assert(!Info.getLangOpts().CPlusPlus);
9240 Lit = &Info.CurrentCall->createTemporary(E, E->getInitializer()->getType(),
9241 ScopeKind::Block, Result);
9242 }
9243 // FIXME: Evaluating in place isn't always right. We should figure out how to
9244 // use appropriate evaluation context here, see
9245 // clang/test/AST/static-compound-literals-reeval.cpp for a failure.
9246 if (!EvaluateInPlace(*Lit, Info, Result, E->getInitializer())) {
9247 *Lit = APValue();
9248 return false;
9249 }
9250 return true;
9251}
9252
9253bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
9254 TypeInfoLValue TypeInfo;
9255
9256 if (!E->isPotentiallyEvaluated()) {
9257 if (E->isTypeOperand())
9258 TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
9259 else
9260 TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
9261 } else {
9262 if (!Info.Ctx.getLangOpts().CPlusPlus20) {
9263 Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
9264 << E->getExprOperand()->getType()
9265 << E->getExprOperand()->getSourceRange();
9266 }
9267
9268 if (!Visit(E->getExprOperand()))
9269 return false;
9270
9271 std::optional<DynamicType> DynType =
9273 if (!DynType)
9274 return false;
9275
9276 TypeInfo = TypeInfoLValue(
9277 Info.Ctx.getCanonicalTagType(DynType->Type).getTypePtr());
9278 }
9279
9280 return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
9281}
9282
9283bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
9284 return Success(E->getGuidDecl());
9285}
9286
9287bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
9288 // Handle static data members.
9289 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
9290 VisitIgnoredBaseExpression(E->getBase());
9291 return VisitVarDecl(E, VD);
9292 }
9293
9294 // Handle static member functions.
9295 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
9296 if (MD->isStatic()) {
9297 VisitIgnoredBaseExpression(E->getBase());
9298 return Success(MD);
9299 }
9300 }
9301
9302 // Handle non-static data members.
9303 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
9304}
9305
9306bool LValueExprEvaluator::VisitExtVectorElementExpr(
9307 const ExtVectorElementExpr *E) {
9308 bool Success = true;
9309
9310 APValue Val;
9311 if (!Evaluate(Val, Info, E->getBase())) {
9312 if (!Info.noteFailure())
9313 return false;
9314 Success = false;
9315 }
9316
9318 E->getEncodedElementAccess(Indices);
9319 // FIXME: support accessing more than one element
9320 if (Indices.size() > 1)
9321 return false;
9322
9323 if (Success) {
9324 Result.setFrom(Info.Ctx, Val);
9325 QualType BaseType = E->getBase()->getType();
9326 if (E->isArrow())
9327 BaseType = BaseType->getPointeeType();
9328 const auto *VT = BaseType->castAs<VectorType>();
9329 HandleLValueVectorElement(Info, E, Result, VT->getElementType(),
9330 VT->getNumElements(), Indices[0]);
9331 }
9332
9333 return Success;
9334}
9335
9336bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
9337 if (E->getBase()->getType()->isSveVLSBuiltinType())
9338 return Error(E);
9339
9340 APSInt Index;
9341 bool Success = true;
9342
9343 if (const auto *VT = E->getBase()->getType()->getAs<VectorType>()) {
9344 APValue Val;
9345 if (!Evaluate(Val, Info, E->getBase())) {
9346 if (!Info.noteFailure())
9347 return false;
9348 Success = false;
9349 }
9350
9351 if (!EvaluateInteger(E->getIdx(), Index, Info)) {
9352 if (!Info.noteFailure())
9353 return false;
9354 Success = false;
9355 }
9356
9357 if (Success) {
9358 Result.setFrom(Info.Ctx, Val);
9359 HandleLValueVectorElement(Info, E, Result, VT->getElementType(),
9360 VT->getNumElements(), Index.getExtValue());
9361 }
9362
9363 return Success;
9364 }
9365
9366 // C++17's rules require us to evaluate the LHS first, regardless of which
9367 // side is the base.
9368 for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) {
9369 if (SubExpr == E->getBase() ? !evaluatePointer(SubExpr, Result)
9370 : !EvaluateInteger(SubExpr, Index, Info)) {
9371 if (!Info.noteFailure())
9372 return false;
9373 Success = false;
9374 }
9375 }
9376
9377 return Success &&
9378 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
9379}
9380
9381bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
9382 bool Success = evaluatePointer(E->getSubExpr(), Result);
9383 // [C++26][expr.unary.op]
9384 // If the operand points to an object or function, the result
9385 // denotes that object or function; otherwise, the behavior is undefined.
9386 // Because &(*(type*)0) is a common pattern, we do not fail the evaluation
9387 // immediately.
9389 return Success;
9391 E->getType())) ||
9392 Info.noteUndefinedBehavior();
9393}
9394
9395bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
9396 if (!Visit(E->getSubExpr()))
9397 return false;
9398 // __real is a no-op on scalar lvalues.
9399 if (E->getSubExpr()->getType()->isAnyComplexType())
9400 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
9401 return true;
9402}
9403
9404bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
9405 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
9406 "lvalue __imag__ on scalar?");
9407 if (!Visit(E->getSubExpr()))
9408 return false;
9409 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
9410 return true;
9411}
9412
9413bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
9414 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9415 return Error(UO);
9416
9417 if (!this->Visit(UO->getSubExpr()))
9418 return false;
9419
9420 return handleIncDec(
9421 this->Info, UO, Result, UO->getSubExpr()->getType(),
9422 UO->isIncrementOp(), nullptr);
9423}
9424
9425bool LValueExprEvaluator::VisitCompoundAssignOperator(
9426 const CompoundAssignOperator *CAO) {
9427 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9428 return Error(CAO);
9429
9430 bool Success = true;
9431
9432 // C++17 onwards require that we evaluate the RHS first.
9433 APValue RHS;
9434 if (!Evaluate(RHS, this->Info, CAO->getRHS())) {
9435 if (!Info.noteFailure())
9436 return false;
9437 Success = false;
9438 }
9439
9440 // The overall lvalue result is the result of evaluating the LHS.
9441 if (!this->Visit(CAO->getLHS()) || !Success)
9442 return false;
9443
9445 this->Info, CAO,
9446 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
9447 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
9448}
9449
9450bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
9451 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9452 return Error(E);
9453
9454 bool Success = true;
9455
9456 // C++17 onwards require that we evaluate the RHS first.
9457 APValue NewVal;
9458 if (!Evaluate(NewVal, this->Info, E->getRHS())) {
9459 if (!Info.noteFailure())
9460 return false;
9461 Success = false;
9462 }
9463
9464 if (!this->Visit(E->getLHS()) || !Success)
9465 return false;
9466
9467 if (Info.getLangOpts().CPlusPlus20 &&
9469 return false;
9470
9471 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
9472 NewVal);
9473}
9474
9475//===----------------------------------------------------------------------===//
9476// Pointer Evaluation
9477//===----------------------------------------------------------------------===//
9478
9479/// Convenience function. LVal's base must be a call to an alloc_size
9480/// function.
9482 const LValue &LVal,
9483 llvm::APInt &Result) {
9484 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
9485 "Can't get the size of a non alloc_size function");
9486 const auto *Base = LVal.getLValueBase().get<const Expr *>();
9487 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
9488 std::optional<llvm::APInt> Size =
9489 CE->evaluateBytesReturnedByAllocSizeCall(Ctx);
9490 if (!Size)
9491 return false;
9492
9493 Result = std::move(*Size);
9494 return true;
9495}
9496
9497/// Attempts to evaluate the given LValueBase as the result of a call to
9498/// a function with the alloc_size attribute. If it was possible to do so, this
9499/// function will return true, make Result's Base point to said function call,
9500/// and mark Result's Base as invalid.
9502 LValue &Result) {
9503 if (Base.isNull())
9504 return false;
9505
9506 // Because we do no form of static analysis, we only support const variables.
9507 //
9508 // Additionally, we can't support parameters, nor can we support static
9509 // variables (in the latter case, use-before-assign isn't UB; in the former,
9510 // we have no clue what they'll be assigned to).
9511 const auto *VD =
9512 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
9513 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
9514 return false;
9515
9516 const Expr *Init = VD->getAnyInitializer();
9517 if (!Init || Init->getType().isNull())
9518 return false;
9519
9520 const Expr *E = Init->IgnoreParens();
9521 if (!tryUnwrapAllocSizeCall(E))
9522 return false;
9523
9524 // Store E instead of E unwrapped so that the type of the LValue's base is
9525 // what the user wanted.
9526 Result.setInvalid(E);
9527
9528 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
9529 Result.addUnsizedArray(Info, E, Pointee);
9530 return true;
9531}
9532
9533namespace {
9534class PointerExprEvaluator
9535 : public ExprEvaluatorBase<PointerExprEvaluator> {
9536 LValue &Result;
9537 bool InvalidBaseOK;
9538
9539 bool Success(const Expr *E) {
9540 Result.set(E);
9541 return true;
9542 }
9543
9544 bool evaluateLValue(const Expr *E, LValue &Result) {
9545 return EvaluateLValue(E, Result, Info, InvalidBaseOK);
9546 }
9547
9548 bool evaluatePointer(const Expr *E, LValue &Result) {
9549 return EvaluatePointer(E, Result, Info, InvalidBaseOK);
9550 }
9551
9552 bool visitNonBuiltinCallExpr(const CallExpr *E);
9553public:
9554
9555 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
9556 : ExprEvaluatorBaseTy(info), Result(Result),
9557 InvalidBaseOK(InvalidBaseOK) {}
9558
9559 bool Success(const APValue &V, const Expr *E) {
9560 Result.setFrom(Info.Ctx, V);
9561 return true;
9562 }
9563 bool ZeroInitialization(const Expr *E) {
9564 Result.setNull(Info.Ctx, E->getType());
9565 return true;
9566 }
9567
9568 bool VisitBinaryOperator(const BinaryOperator *E);
9569 bool VisitCastExpr(const CastExpr* E);
9570 bool VisitUnaryAddrOf(const UnaryOperator *E);
9571 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
9572 { return Success(E); }
9573 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
9575 return Success(E);
9576 if (Info.noteFailure())
9577 EvaluateIgnoredValue(Info, E->getSubExpr());
9578 return Error(E);
9579 }
9580 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
9581 { return Success(E); }
9582 bool VisitCallExpr(const CallExpr *E);
9583 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
9584 bool VisitBlockExpr(const BlockExpr *E) {
9585 if (!E->getBlockDecl()->hasCaptures())
9586 return Success(E);
9587 return Error(E);
9588 }
9589 bool VisitCXXThisExpr(const CXXThisExpr *E) {
9590 auto DiagnoseInvalidUseOfThis = [&] {
9591 if (Info.getLangOpts().CPlusPlus11)
9592 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
9593 else
9594 Info.FFDiag(E);
9595 };
9596
9597 // Can't look at 'this' when checking a potential constant expression.
9598 if (Info.checkingPotentialConstantExpression())
9599 return false;
9600
9601 bool IsExplicitLambda =
9602 isLambdaCallWithExplicitObjectParameter(Info.CurrentCall->Callee);
9603 if (!IsExplicitLambda) {
9604 if (!Info.CurrentCall->This) {
9605 DiagnoseInvalidUseOfThis();
9606 return false;
9607 }
9608
9609 Result = *Info.CurrentCall->This;
9610 }
9611
9612 if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
9613 // Ensure we actually have captured 'this'. If something was wrong with
9614 // 'this' capture, the error would have been previously reported.
9615 // Otherwise we can be inside of a default initialization of an object
9616 // declared by lambda's body, so no need to return false.
9617 if (!Info.CurrentCall->LambdaThisCaptureField) {
9618 if (IsExplicitLambda && !Info.CurrentCall->This) {
9619 DiagnoseInvalidUseOfThis();
9620 return false;
9621 }
9622
9623 return true;
9624 }
9625
9626 const auto *MD = cast<CXXMethodDecl>(Info.CurrentCall->Callee);
9627 return HandleLambdaCapture(
9628 Info, E, Result, MD, Info.CurrentCall->LambdaThisCaptureField,
9629 Info.CurrentCall->LambdaThisCaptureField->getType()->isPointerType());
9630 }
9631 return true;
9632 }
9633
9634 bool VisitCXXNewExpr(const CXXNewExpr *E);
9635
9636 bool VisitSourceLocExpr(const SourceLocExpr *E) {
9637 assert(!E->isIntType() && "SourceLocExpr isn't a pointer type?");
9638 APValue LValResult = E->EvaluateInContext(
9639 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
9640 Result.setFrom(Info.Ctx, LValResult);
9641 return true;
9642 }
9643
9644 bool VisitEmbedExpr(const EmbedExpr *E) {
9645 llvm::report_fatal_error("Not yet implemented for ExprConstant.cpp");
9646 return true;
9647 }
9648
9649 bool VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr *E) {
9650 std::string ResultStr = E->ComputeName(Info.Ctx);
9651
9652 QualType CharTy = Info.Ctx.CharTy.withConst();
9653 APInt Size(Info.Ctx.getTypeSize(Info.Ctx.getSizeType()),
9654 ResultStr.size() + 1);
9655 QualType ArrayTy = Info.Ctx.getConstantArrayType(
9656 CharTy, Size, nullptr, ArraySizeModifier::Normal, 0);
9657
9658 StringLiteral *SL =
9659 StringLiteral::Create(Info.Ctx, ResultStr, StringLiteralKind::Ordinary,
9660 /*Pascal*/ false, ArrayTy, E->getLocation());
9661
9662 evaluateLValue(SL, Result);
9663 Result.addArray(Info, E, cast<ConstantArrayType>(ArrayTy));
9664 return true;
9665 }
9666
9667 // FIXME: Missing: @protocol, @selector
9668};
9669} // end anonymous namespace
9670
9671static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
9672 bool InvalidBaseOK) {
9673 assert(!E->isValueDependent());
9674 assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
9675 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
9676}
9677
9678bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
9679 if (E->getOpcode() != BO_Add &&
9680 E->getOpcode() != BO_Sub)
9681 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9682
9683 const Expr *PExp = E->getLHS();
9684 const Expr *IExp = E->getRHS();
9685 if (IExp->getType()->isPointerType())
9686 std::swap(PExp, IExp);
9687
9688 bool EvalPtrOK = evaluatePointer(PExp, Result);
9689 if (!EvalPtrOK && !Info.noteFailure())
9690 return false;
9691
9692 llvm::APSInt Offset;
9693 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
9694 return false;
9695
9696 if (E->getOpcode() == BO_Sub)
9697 negateAsSigned(Offset);
9698
9699 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
9700 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
9701}
9702
9703bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
9704 return evaluateLValue(E->getSubExpr(), Result);
9705}
9706
9707// Is the provided decl 'std::source_location::current'?
9709 if (!FD)
9710 return false;
9711 const IdentifierInfo *FnII = FD->getIdentifier();
9712 if (!FnII || !FnII->isStr("current"))
9713 return false;
9714
9715 const auto *RD = dyn_cast<RecordDecl>(FD->getParent());
9716 if (!RD)
9717 return false;
9718
9719 const IdentifierInfo *ClassII = RD->getIdentifier();
9720 return RD->isInStdNamespace() && ClassII && ClassII->isStr("source_location");
9721}
9722
9723bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
9724 const Expr *SubExpr = E->getSubExpr();
9725
9726 switch (E->getCastKind()) {
9727 default:
9728 break;
9729 case CK_BitCast:
9730 case CK_CPointerToObjCPointerCast:
9731 case CK_BlockPointerToObjCPointerCast:
9732 case CK_AnyPointerToBlockPointerCast:
9733 case CK_AddressSpaceConversion:
9734 if (!Visit(SubExpr))
9735 return false;
9736 if (E->getType()->isFunctionPointerType() ||
9737 SubExpr->getType()->isFunctionPointerType()) {
9738 // Casting between two function pointer types, or between a function
9739 // pointer and an object pointer, is always a reinterpret_cast.
9740 CCEDiag(E, diag::note_constexpr_invalid_cast)
9741 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
9742 << Info.Ctx.getLangOpts().CPlusPlus;
9743 Result.Designator.setInvalid();
9744 } else if (!E->getType()->isVoidPointerType()) {
9745 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
9746 // permitted in constant expressions in C++11. Bitcasts from cv void* are
9747 // also static_casts, but we disallow them as a resolution to DR1312.
9748 //
9749 // In some circumstances, we permit casting from void* to cv1 T*, when the
9750 // actual pointee object is actually a cv2 T.
9751 bool HasValidResult = !Result.InvalidBase && !Result.Designator.Invalid &&
9752 !Result.IsNullPtr;
9753 bool VoidPtrCastMaybeOK =
9754 Result.IsNullPtr ||
9755 (HasValidResult &&
9756 Info.Ctx.hasSimilarType(Result.Designator.getType(Info.Ctx),
9757 E->getType()->getPointeeType()));
9758 // 1. We'll allow it in std::allocator::allocate, and anything which that
9759 // calls.
9760 // 2. HACK 2022-03-28: Work around an issue with libstdc++'s
9761 // <source_location> header. Fixed in GCC 12 and later (2022-04-??).
9762 // We'll allow it in the body of std::source_location::current. GCC's
9763 // implementation had a parameter of type `void*`, and casts from
9764 // that back to `const __impl*` in its body.
9765 if (VoidPtrCastMaybeOK &&
9766 (Info.getStdAllocatorCaller("allocate") ||
9767 IsDeclSourceLocationCurrent(Info.CurrentCall->Callee) ||
9768 Info.getLangOpts().CPlusPlus26)) {
9769 // Permitted.
9770 } else {
9771 if (SubExpr->getType()->isVoidPointerType() &&
9772 Info.getLangOpts().CPlusPlus) {
9773 if (HasValidResult)
9774 CCEDiag(E, diag::note_constexpr_invalid_void_star_cast)
9775 << SubExpr->getType() << Info.getLangOpts().CPlusPlus26
9776 << Result.Designator.getType(Info.Ctx).getCanonicalType()
9777 << E->getType()->getPointeeType();
9778 else
9779 CCEDiag(E, diag::note_constexpr_invalid_cast)
9780 << diag::ConstexprInvalidCastKind::CastFrom
9781 << SubExpr->getType();
9782 } else
9783 CCEDiag(E, diag::note_constexpr_invalid_cast)
9784 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
9785 << Info.Ctx.getLangOpts().CPlusPlus;
9786 Result.Designator.setInvalid();
9787 }
9788 }
9789 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
9790 ZeroInitialization(E);
9791 return true;
9792
9793 case CK_DerivedToBase:
9794 case CK_UncheckedDerivedToBase:
9795 if (!evaluatePointer(E->getSubExpr(), Result))
9796 return false;
9797 if (!Result.Base && Result.Offset.isZero())
9798 return true;
9799
9800 // Now figure out the necessary offset to add to the base LV to get from
9801 // the derived class to the base class.
9802 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
9803 castAs<PointerType>()->getPointeeType(),
9804 Result);
9805
9806 case CK_BaseToDerived:
9807 if (!Visit(E->getSubExpr()))
9808 return false;
9809 if (!Result.Base && Result.Offset.isZero())
9810 return true;
9811 return HandleBaseToDerivedCast(Info, E, Result);
9812
9813 case CK_Dynamic:
9814 if (!Visit(E->getSubExpr()))
9815 return false;
9817
9818 case CK_NullToPointer:
9819 VisitIgnoredValue(E->getSubExpr());
9820 return ZeroInitialization(E);
9821
9822 case CK_IntegralToPointer: {
9823 CCEDiag(E, diag::note_constexpr_invalid_cast)
9824 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
9825 << Info.Ctx.getLangOpts().CPlusPlus;
9826
9827 APValue Value;
9828 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
9829 break;
9830
9831 if (Value.isInt()) {
9832 unsigned Size = Info.Ctx.getTypeSize(E->getType());
9833 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
9834 if (N == Info.Ctx.getTargetNullPointerValue(E->getType())) {
9835 Result.setNull(Info.Ctx, E->getType());
9836 } else {
9837 Result.Base = (Expr *)nullptr;
9838 Result.InvalidBase = false;
9839 Result.Offset = CharUnits::fromQuantity(N);
9840 Result.Designator.setInvalid();
9841 Result.IsNullPtr = false;
9842 }
9843 return true;
9844 } else {
9845 // In rare instances, the value isn't an lvalue.
9846 // For example, when the value is the difference between the addresses of
9847 // two labels. We reject that as a constant expression because we can't
9848 // compute a valid offset to convert into a pointer.
9849 if (!Value.isLValue())
9850 return false;
9851
9852 // Cast is of an lvalue, no need to change value.
9853 Result.setFrom(Info.Ctx, Value);
9854 return true;
9855 }
9856 }
9857
9858 case CK_ArrayToPointerDecay: {
9859 if (SubExpr->isGLValue()) {
9860 if (!evaluateLValue(SubExpr, Result))
9861 return false;
9862 } else {
9863 APValue &Value = Info.CurrentCall->createTemporary(
9864 SubExpr, SubExpr->getType(), ScopeKind::FullExpression, Result);
9865 if (!EvaluateInPlace(Value, Info, Result, SubExpr))
9866 return false;
9867 }
9868 // The result is a pointer to the first element of the array.
9869 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
9870 if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
9871 Result.addArray(Info, E, CAT);
9872 else
9873 Result.addUnsizedArray(Info, E, AT->getElementType());
9874 return true;
9875 }
9876
9877 case CK_FunctionToPointerDecay:
9878 return evaluateLValue(SubExpr, Result);
9879
9880 case CK_LValueToRValue: {
9881 LValue LVal;
9882 if (!evaluateLValue(E->getSubExpr(), LVal))
9883 return false;
9884
9885 APValue RVal;
9886 // Note, we use the subexpression's type in order to retain cv-qualifiers.
9888 LVal, RVal))
9889 return InvalidBaseOK &&
9890 evaluateLValueAsAllocSize(Info, LVal.Base, Result);
9891 return Success(RVal, E);
9892 }
9893 }
9894
9895 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9896}
9897
9899 UnaryExprOrTypeTrait ExprKind) {
9900 // C++ [expr.alignof]p3:
9901 // When alignof is applied to a reference type, the result is the
9902 // alignment of the referenced type.
9903 T = T.getNonReferenceType();
9904
9905 if (T.getQualifiers().hasUnaligned())
9906 return CharUnits::One();
9907
9908 const bool AlignOfReturnsPreferred =
9909 Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
9910
9911 // __alignof is defined to return the preferred alignment.
9912 // Before 8, clang returned the preferred alignment for alignof and _Alignof
9913 // as well.
9914 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
9915 return Ctx.toCharUnitsFromBits(Ctx.getPreferredTypeAlign(T.getTypePtr()));
9916 // alignof and _Alignof are defined to return the ABI alignment.
9917 else if (ExprKind == UETT_AlignOf)
9918 return Ctx.getTypeAlignInChars(T.getTypePtr());
9919 else
9920 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
9921}
9922
9924 UnaryExprOrTypeTrait ExprKind) {
9925 E = E->IgnoreParens();
9926
9927 // The kinds of expressions that we have special-case logic here for
9928 // should be kept up to date with the special checks for those
9929 // expressions in Sema.
9930
9931 // alignof decl is always accepted, even if it doesn't make sense: we default
9932 // to 1 in those cases.
9933 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9934 return Ctx.getDeclAlign(DRE->getDecl(),
9935 /*RefAsPointee*/ true);
9936
9937 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
9938 return Ctx.getDeclAlign(ME->getMemberDecl(),
9939 /*RefAsPointee*/ true);
9940
9941 return GetAlignOfType(Ctx, E->getType(), ExprKind);
9942}
9943
9944static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) {
9945 if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>())
9946 return Info.Ctx.getDeclAlign(VD);
9947 if (const auto *E = Value.Base.dyn_cast<const Expr *>())
9948 return GetAlignOfExpr(Info.Ctx, E, UETT_AlignOf);
9949 return GetAlignOfType(Info.Ctx, Value.Base.getTypeInfoType(), UETT_AlignOf);
9950}
9951
9952/// Evaluate the value of the alignment argument to __builtin_align_{up,down},
9953/// __builtin_is_aligned and __builtin_assume_aligned.
9954static bool getAlignmentArgument(const Expr *E, QualType ForType,
9955 EvalInfo &Info, APSInt &Alignment) {
9956 if (!EvaluateInteger(E, Alignment, Info))
9957 return false;
9958 if (Alignment < 0 || !Alignment.isPowerOf2()) {
9959 Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment;
9960 return false;
9961 }
9962 unsigned SrcWidth = Info.Ctx.getIntWidth(ForType);
9963 APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1));
9964 if (APSInt::compareValues(Alignment, MaxValue) > 0) {
9965 Info.FFDiag(E, diag::note_constexpr_alignment_too_big)
9966 << MaxValue << ForType << Alignment;
9967 return false;
9968 }
9969 // Ensure both alignment and source value have the same bit width so that we
9970 // don't assert when computing the resulting value.
9971 APSInt ExtAlignment =
9972 APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true);
9973 assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 &&
9974 "Alignment should not be changed by ext/trunc");
9975 Alignment = ExtAlignment;
9976 assert(Alignment.getBitWidth() == SrcWidth);
9977 return true;
9978}
9979
9980// To be clear: this happily visits unsupported builtins. Better name welcomed.
9981bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
9982 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
9983 return true;
9984
9985 if (!(InvalidBaseOK && E->getCalleeAllocSizeAttr()))
9986 return false;
9987
9988 Result.setInvalid(E);
9989 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
9990 Result.addUnsizedArray(Info, E, PointeeTy);
9991 return true;
9992}
9993
9994bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
9995 if (!IsConstantEvaluatedBuiltinCall(E))
9996 return visitNonBuiltinCallExpr(E);
9997 return VisitBuiltinCallExpr(E, E->getBuiltinCallee());
9998}
9999
10000// Determine if T is a character type for which we guarantee that
10001// sizeof(T) == 1.
10003 return T->isCharType() || T->isChar8Type();
10004}
10005
10006bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
10007 unsigned BuiltinOp) {
10008 if (IsOpaqueConstantCall(E))
10009 return Success(E);
10010
10011 switch (BuiltinOp) {
10012 case Builtin::BIaddressof:
10013 case Builtin::BI__addressof:
10014 case Builtin::BI__builtin_addressof:
10015 return evaluateLValue(E->getArg(0), Result);
10016 case Builtin::BI__builtin_assume_aligned: {
10017 // We need to be very careful here because: if the pointer does not have the
10018 // asserted alignment, then the behavior is undefined, and undefined
10019 // behavior is non-constant.
10020 if (!evaluatePointer(E->getArg(0), Result))
10021 return false;
10022
10023 LValue OffsetResult(Result);
10024 APSInt Alignment;
10025 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
10026 Alignment))
10027 return false;
10028 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
10029
10030 if (E->getNumArgs() > 2) {
10031 APSInt Offset;
10032 if (!EvaluateInteger(E->getArg(2), Offset, Info))
10033 return false;
10034
10035 int64_t AdditionalOffset = -Offset.getZExtValue();
10036 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
10037 }
10038
10039 // If there is a base object, then it must have the correct alignment.
10040 if (OffsetResult.Base) {
10041 CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult);
10042
10043 if (BaseAlignment < Align) {
10044 Result.Designator.setInvalid();
10045 CCEDiag(E->getArg(0), diag::note_constexpr_baa_insufficient_alignment)
10046 << 0 << BaseAlignment.getQuantity() << Align.getQuantity();
10047 return false;
10048 }
10049 }
10050
10051 // The offset must also have the correct alignment.
10052 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
10053 Result.Designator.setInvalid();
10054
10055 (OffsetResult.Base
10056 ? CCEDiag(E->getArg(0),
10057 diag::note_constexpr_baa_insufficient_alignment)
10058 << 1
10059 : CCEDiag(E->getArg(0),
10060 diag::note_constexpr_baa_value_insufficient_alignment))
10061 << OffsetResult.Offset.getQuantity() << Align.getQuantity();
10062 return false;
10063 }
10064
10065 return true;
10066 }
10067 case Builtin::BI__builtin_align_up:
10068 case Builtin::BI__builtin_align_down: {
10069 if (!evaluatePointer(E->getArg(0), Result))
10070 return false;
10071 APSInt Alignment;
10072 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
10073 Alignment))
10074 return false;
10075 CharUnits BaseAlignment = getBaseAlignment(Info, Result);
10076 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset);
10077 // For align_up/align_down, we can return the same value if the alignment
10078 // is known to be greater or equal to the requested value.
10079 if (PtrAlign.getQuantity() >= Alignment)
10080 return true;
10081
10082 // The alignment could be greater than the minimum at run-time, so we cannot
10083 // infer much about the resulting pointer value. One case is possible:
10084 // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we
10085 // can infer the correct index if the requested alignment is smaller than
10086 // the base alignment so we can perform the computation on the offset.
10087 if (BaseAlignment.getQuantity() >= Alignment) {
10088 assert(Alignment.getBitWidth() <= 64 &&
10089 "Cannot handle > 64-bit address-space");
10090 uint64_t Alignment64 = Alignment.getZExtValue();
10091 CharUnits NewOffset = CharUnits::fromQuantity(
10092 BuiltinOp == Builtin::BI__builtin_align_down
10093 ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64)
10094 : llvm::alignTo(Result.Offset.getQuantity(), Alignment64));
10095 Result.adjustOffset(NewOffset - Result.Offset);
10096 // TODO: diagnose out-of-bounds values/only allow for arrays?
10097 return true;
10098 }
10099 // Otherwise, we cannot constant-evaluate the result.
10100 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust)
10101 << Alignment;
10102 return false;
10103 }
10104 case Builtin::BI__builtin_operator_new:
10105 return HandleOperatorNewCall(Info, E, Result);
10106 case Builtin::BI__builtin_launder:
10107 return evaluatePointer(E->getArg(0), Result);
10108 case Builtin::BIstrchr:
10109 case Builtin::BIwcschr:
10110 case Builtin::BImemchr:
10111 case Builtin::BIwmemchr:
10112 if (Info.getLangOpts().CPlusPlus11)
10113 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
10114 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
10115 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
10116 else
10117 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
10118 [[fallthrough]];
10119 case Builtin::BI__builtin_strchr:
10120 case Builtin::BI__builtin_wcschr:
10121 case Builtin::BI__builtin_memchr:
10122 case Builtin::BI__builtin_char_memchr:
10123 case Builtin::BI__builtin_wmemchr: {
10124 if (!Visit(E->getArg(0)))
10125 return false;
10126 APSInt Desired;
10127 if (!EvaluateInteger(E->getArg(1), Desired, Info))
10128 return false;
10129 uint64_t MaxLength = uint64_t(-1);
10130 if (BuiltinOp != Builtin::BIstrchr &&
10131 BuiltinOp != Builtin::BIwcschr &&
10132 BuiltinOp != Builtin::BI__builtin_strchr &&
10133 BuiltinOp != Builtin::BI__builtin_wcschr) {
10134 APSInt N;
10135 if (!EvaluateInteger(E->getArg(2), N, Info))
10136 return false;
10137 MaxLength = N.getZExtValue();
10138 }
10139 // We cannot find the value if there are no candidates to match against.
10140 if (MaxLength == 0u)
10141 return ZeroInitialization(E);
10142 if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
10143 Result.Designator.Invalid)
10144 return false;
10145 QualType CharTy = Result.Designator.getType(Info.Ctx);
10146 bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
10147 BuiltinOp == Builtin::BI__builtin_memchr;
10148 assert(IsRawByte ||
10149 Info.Ctx.hasSameUnqualifiedType(
10150 CharTy, E->getArg(0)->getType()->getPointeeType()));
10151 // Pointers to const void may point to objects of incomplete type.
10152 if (IsRawByte && CharTy->isIncompleteType()) {
10153 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
10154 return false;
10155 }
10156 // Give up on byte-oriented matching against multibyte elements.
10157 // FIXME: We can compare the bytes in the correct order.
10158 if (IsRawByte && !isOneByteCharacterType(CharTy)) {
10159 Info.FFDiag(E, diag::note_constexpr_memchr_unsupported)
10160 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp) << CharTy;
10161 return false;
10162 }
10163 // Figure out what value we're actually looking for (after converting to
10164 // the corresponding unsigned type if necessary).
10165 uint64_t DesiredVal;
10166 bool StopAtNull = false;
10167 switch (BuiltinOp) {
10168 case Builtin::BIstrchr:
10169 case Builtin::BI__builtin_strchr:
10170 // strchr compares directly to the passed integer, and therefore
10171 // always fails if given an int that is not a char.
10172 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
10173 E->getArg(1)->getType(),
10174 Desired),
10175 Desired))
10176 return ZeroInitialization(E);
10177 StopAtNull = true;
10178 [[fallthrough]];
10179 case Builtin::BImemchr:
10180 case Builtin::BI__builtin_memchr:
10181 case Builtin::BI__builtin_char_memchr:
10182 // memchr compares by converting both sides to unsigned char. That's also
10183 // correct for strchr if we get this far (to cope with plain char being
10184 // unsigned in the strchr case).
10185 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
10186 break;
10187
10188 case Builtin::BIwcschr:
10189 case Builtin::BI__builtin_wcschr:
10190 StopAtNull = true;
10191 [[fallthrough]];
10192 case Builtin::BIwmemchr:
10193 case Builtin::BI__builtin_wmemchr:
10194 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
10195 DesiredVal = Desired.getZExtValue();
10196 break;
10197 }
10198
10199 for (; MaxLength; --MaxLength) {
10200 APValue Char;
10201 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
10202 !Char.isInt())
10203 return false;
10204 if (Char.getInt().getZExtValue() == DesiredVal)
10205 return true;
10206 if (StopAtNull && !Char.getInt())
10207 break;
10208 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
10209 return false;
10210 }
10211 // Not found: return nullptr.
10212 return ZeroInitialization(E);
10213 }
10214
10215 case Builtin::BImemcpy:
10216 case Builtin::BImemmove:
10217 case Builtin::BIwmemcpy:
10218 case Builtin::BIwmemmove:
10219 if (Info.getLangOpts().CPlusPlus11)
10220 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
10221 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
10222 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
10223 else
10224 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
10225 [[fallthrough]];
10226 case Builtin::BI__builtin_memcpy:
10227 case Builtin::BI__builtin_memmove:
10228 case Builtin::BI__builtin_wmemcpy:
10229 case Builtin::BI__builtin_wmemmove: {
10230 bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
10231 BuiltinOp == Builtin::BIwmemmove ||
10232 BuiltinOp == Builtin::BI__builtin_wmemcpy ||
10233 BuiltinOp == Builtin::BI__builtin_wmemmove;
10234 bool Move = BuiltinOp == Builtin::BImemmove ||
10235 BuiltinOp == Builtin::BIwmemmove ||
10236 BuiltinOp == Builtin::BI__builtin_memmove ||
10237 BuiltinOp == Builtin::BI__builtin_wmemmove;
10238
10239 // The result of mem* is the first argument.
10240 if (!Visit(E->getArg(0)))
10241 return false;
10242 LValue Dest = Result;
10243
10244 LValue Src;
10245 if (!EvaluatePointer(E->getArg(1), Src, Info))
10246 return false;
10247
10248 APSInt N;
10249 if (!EvaluateInteger(E->getArg(2), N, Info))
10250 return false;
10251 assert(!N.isSigned() && "memcpy and friends take an unsigned size");
10252
10253 // If the size is zero, we treat this as always being a valid no-op.
10254 // (Even if one of the src and dest pointers is null.)
10255 if (!N)
10256 return true;
10257
10258 // Otherwise, if either of the operands is null, we can't proceed. Don't
10259 // try to determine the type of the copied objects, because there aren't
10260 // any.
10261 if (!Src.Base || !Dest.Base) {
10262 APValue Val;
10263 (!Src.Base ? Src : Dest).moveInto(Val);
10264 Info.FFDiag(E, diag::note_constexpr_memcpy_null)
10265 << Move << WChar << !!Src.Base
10266 << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
10267 return false;
10268 }
10269 if (Src.Designator.Invalid || Dest.Designator.Invalid)
10270 return false;
10271
10272 // We require that Src and Dest are both pointers to arrays of
10273 // trivially-copyable type. (For the wide version, the designator will be
10274 // invalid if the designated object is not a wchar_t.)
10275 QualType T = Dest.Designator.getType(Info.Ctx);
10276 QualType SrcT = Src.Designator.getType(Info.Ctx);
10277 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
10278 // FIXME: Consider using our bit_cast implementation to support this.
10279 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
10280 return false;
10281 }
10282 if (T->isIncompleteType()) {
10283 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
10284 return false;
10285 }
10286 if (!T.isTriviallyCopyableType(Info.Ctx)) {
10287 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
10288 return false;
10289 }
10290
10291 // Figure out how many T's we're copying.
10292 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
10293 if (TSize == 0)
10294 return false;
10295 if (!WChar) {
10296 uint64_t Remainder;
10297 llvm::APInt OrigN = N;
10298 llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
10299 if (Remainder) {
10300 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
10301 << Move << WChar << 0 << T << toString(OrigN, 10, /*Signed*/false)
10302 << (unsigned)TSize;
10303 return false;
10304 }
10305 }
10306
10307 // Check that the copying will remain within the arrays, just so that we
10308 // can give a more meaningful diagnostic. This implicitly also checks that
10309 // N fits into 64 bits.
10310 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
10311 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
10312 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
10313 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
10314 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
10315 << toString(N, 10, /*Signed*/false);
10316 return false;
10317 }
10318 uint64_t NElems = N.getZExtValue();
10319 uint64_t NBytes = NElems * TSize;
10320
10321 // Check for overlap.
10322 int Direction = 1;
10323 if (HasSameBase(Src, Dest)) {
10324 uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
10325 uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
10326 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
10327 // Dest is inside the source region.
10328 if (!Move) {
10329 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
10330 return false;
10331 }
10332 // For memmove and friends, copy backwards.
10333 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
10334 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
10335 return false;
10336 Direction = -1;
10337 } else if (!Move && SrcOffset >= DestOffset &&
10338 SrcOffset - DestOffset < NBytes) {
10339 // Src is inside the destination region for memcpy: invalid.
10340 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
10341 return false;
10342 }
10343 }
10344
10345 while (true) {
10346 APValue Val;
10347 // FIXME: Set WantObjectRepresentation to true if we're copying a
10348 // char-like type?
10349 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
10350 !handleAssignment(Info, E, Dest, T, Val))
10351 return false;
10352 // Do not iterate past the last element; if we're copying backwards, that
10353 // might take us off the start of the array.
10354 if (--NElems == 0)
10355 return true;
10356 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
10357 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
10358 return false;
10359 }
10360 }
10361
10362 default:
10363 return false;
10364 }
10365}
10366
10367static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
10368 APValue &Result, const InitListExpr *ILE,
10369 QualType AllocType);
10370static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
10371 APValue &Result,
10372 const CXXConstructExpr *CCE,
10373 QualType AllocType);
10374
10375bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) {
10376 if (!Info.getLangOpts().CPlusPlus20)
10377 Info.CCEDiag(E, diag::note_constexpr_new);
10378
10379 // We cannot speculatively evaluate a delete expression.
10380 if (Info.SpeculativeEvaluationDepth)
10381 return false;
10382
10383 FunctionDecl *OperatorNew = E->getOperatorNew();
10384 QualType AllocType = E->getAllocatedType();
10385 QualType TargetType = AllocType;
10386
10387 bool IsNothrow = false;
10388 bool IsPlacement = false;
10389
10390 if (E->getNumPlacementArgs() == 1 &&
10391 E->getPlacementArg(0)->getType()->isNothrowT()) {
10392 // The only new-placement list we support is of the form (std::nothrow).
10393 //
10394 // FIXME: There is no restriction on this, but it's not clear that any
10395 // other form makes any sense. We get here for cases such as:
10396 //
10397 // new (std::align_val_t{N}) X(int)
10398 //
10399 // (which should presumably be valid only if N is a multiple of
10400 // alignof(int), and in any case can't be deallocated unless N is
10401 // alignof(X) and X has new-extended alignment).
10402 LValue Nothrow;
10403 if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info))
10404 return false;
10405 IsNothrow = true;
10406 } else if (OperatorNew->isReservedGlobalPlacementOperator()) {
10407 if (Info.CurrentCall->isStdFunction() || Info.getLangOpts().CPlusPlus26 ||
10408 (Info.CurrentCall->CanEvalMSConstexpr &&
10409 OperatorNew->hasAttr<MSConstexprAttr>())) {
10410 if (!EvaluatePointer(E->getPlacementArg(0), Result, Info))
10411 return false;
10412 if (Result.Designator.Invalid)
10413 return false;
10414 TargetType = E->getPlacementArg(0)->getType();
10415 IsPlacement = true;
10416 } else {
10417 Info.FFDiag(E, diag::note_constexpr_new_placement)
10418 << /*C++26 feature*/ 1 << E->getSourceRange();
10419 return false;
10420 }
10421 } else if (E->getNumPlacementArgs()) {
10422 Info.FFDiag(E, diag::note_constexpr_new_placement)
10423 << /*Unsupported*/ 0 << E->getSourceRange();
10424 return false;
10425 } else if (!OperatorNew
10426 ->isUsableAsGlobalAllocationFunctionInConstantEvaluation()) {
10427 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
10428 << isa<CXXMethodDecl>(OperatorNew) << OperatorNew;
10429 return false;
10430 }
10431
10432 const Expr *Init = E->getInitializer();
10433 const InitListExpr *ResizedArrayILE = nullptr;
10434 const CXXConstructExpr *ResizedArrayCCE = nullptr;
10435 bool ValueInit = false;
10436
10437 if (std::optional<const Expr *> ArraySize = E->getArraySize()) {
10438 const Expr *Stripped = *ArraySize;
10439 for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
10440 Stripped = ICE->getSubExpr())
10441 if (ICE->getCastKind() != CK_NoOp &&
10442 ICE->getCastKind() != CK_IntegralCast)
10443 break;
10444
10445 llvm::APSInt ArrayBound;
10446 if (!EvaluateInteger(Stripped, ArrayBound, Info))
10447 return false;
10448
10449 // C++ [expr.new]p9:
10450 // The expression is erroneous if:
10451 // -- [...] its value before converting to size_t [or] applying the
10452 // second standard conversion sequence is less than zero
10453 if (ArrayBound.isSigned() && ArrayBound.isNegative()) {
10454 if (IsNothrow)
10455 return ZeroInitialization(E);
10456
10457 Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative)
10458 << ArrayBound << (*ArraySize)->getSourceRange();
10459 return false;
10460 }
10461
10462 // -- its value is such that the size of the allocated object would
10463 // exceed the implementation-defined limit
10464 if (!Info.CheckArraySize(ArraySize.value()->getExprLoc(),
10466 Info.Ctx, AllocType, ArrayBound),
10467 ArrayBound.getZExtValue(), /*Diag=*/!IsNothrow)) {
10468 if (IsNothrow)
10469 return ZeroInitialization(E);
10470 return false;
10471 }
10472
10473 // -- the new-initializer is a braced-init-list and the number of
10474 // array elements for which initializers are provided [...]
10475 // exceeds the number of elements to initialize
10476 if (!Init) {
10477 // No initialization is performed.
10478 } else if (isa<CXXScalarValueInitExpr>(Init) ||
10480 ValueInit = true;
10481 } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) {
10482 ResizedArrayCCE = CCE;
10483 } else {
10484 auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType());
10485 assert(CAT && "unexpected type for array initializer");
10486
10487 unsigned Bits =
10488 std::max(CAT->getSizeBitWidth(), ArrayBound.getBitWidth());
10489 llvm::APInt InitBound = CAT->getSize().zext(Bits);
10490 llvm::APInt AllocBound = ArrayBound.zext(Bits);
10491 if (InitBound.ugt(AllocBound)) {
10492 if (IsNothrow)
10493 return ZeroInitialization(E);
10494
10495 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small)
10496 << toString(AllocBound, 10, /*Signed=*/false)
10497 << toString(InitBound, 10, /*Signed=*/false)
10498 << (*ArraySize)->getSourceRange();
10499 return false;
10500 }
10501
10502 // If the sizes differ, we must have an initializer list, and we need
10503 // special handling for this case when we initialize.
10504 if (InitBound != AllocBound)
10505 ResizedArrayILE = cast<InitListExpr>(Init);
10506 }
10507
10508 AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr,
10509 ArraySizeModifier::Normal, 0);
10510 } else {
10511 assert(!AllocType->isArrayType() &&
10512 "array allocation with non-array new");
10513 }
10514
10515 APValue *Val;
10516 if (IsPlacement) {
10518 struct FindObjectHandler {
10519 EvalInfo &Info;
10520 const Expr *E;
10521 QualType AllocType;
10522 const AccessKinds AccessKind;
10523 APValue *Value;
10524
10525 typedef bool result_type;
10526 bool failed() { return false; }
10527 bool checkConst(QualType QT) {
10528 if (QT.isConstQualified()) {
10529 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
10530 return false;
10531 }
10532 return true;
10533 }
10534 bool found(APValue &Subobj, QualType SubobjType) {
10535 if (!checkConst(SubobjType))
10536 return false;
10537 // FIXME: Reject the cases where [basic.life]p8 would not permit the
10538 // old name of the object to be used to name the new object.
10539 unsigned SubobjectSize = 1;
10540 unsigned AllocSize = 1;
10541 if (auto *CAT = dyn_cast<ConstantArrayType>(AllocType))
10542 AllocSize = CAT->getZExtSize();
10543 if (auto *CAT = dyn_cast<ConstantArrayType>(SubobjType))
10544 SubobjectSize = CAT->getZExtSize();
10545 if (SubobjectSize < AllocSize ||
10546 !Info.Ctx.hasSimilarType(Info.Ctx.getBaseElementType(SubobjType),
10547 Info.Ctx.getBaseElementType(AllocType))) {
10548 Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type)
10549 << SubobjType << AllocType;
10550 return false;
10551 }
10552 Value = &Subobj;
10553 return true;
10554 }
10555 bool found(APSInt &Value, QualType SubobjType) {
10556 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
10557 return false;
10558 }
10559 bool found(APFloat &Value, QualType SubobjType) {
10560 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
10561 return false;
10562 }
10563 } Handler = {Info, E, AllocType, AK, nullptr};
10564
10565 CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType);
10566 if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler))
10567 return false;
10568
10569 Val = Handler.Value;
10570
10571 // [basic.life]p1:
10572 // The lifetime of an object o of type T ends when [...] the storage
10573 // which the object occupies is [...] reused by an object that is not
10574 // nested within o (6.6.2).
10575 *Val = APValue();
10576 } else {
10577 // Perform the allocation and obtain a pointer to the resulting object.
10578 Val = Info.createHeapAlloc(E, AllocType, Result);
10579 if (!Val)
10580 return false;
10581 }
10582
10583 if (ValueInit) {
10584 ImplicitValueInitExpr VIE(AllocType);
10585 if (!EvaluateInPlace(*Val, Info, Result, &VIE))
10586 return false;
10587 } else if (ResizedArrayILE) {
10588 if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE,
10589 AllocType))
10590 return false;
10591 } else if (ResizedArrayCCE) {
10592 if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE,
10593 AllocType))
10594 return false;
10595 } else if (Init) {
10596 if (!EvaluateInPlace(*Val, Info, Result, Init))
10597 return false;
10598 } else if (!handleDefaultInitValue(AllocType, *Val)) {
10599 return false;
10600 }
10601
10602 // Array new returns a pointer to the first element, not a pointer to the
10603 // array.
10604 if (auto *AT = AllocType->getAsArrayTypeUnsafe())
10605 Result.addArray(Info, E, cast<ConstantArrayType>(AT));
10606
10607 return true;
10608}
10609//===----------------------------------------------------------------------===//
10610// Member Pointer Evaluation
10611//===----------------------------------------------------------------------===//
10612
10613namespace {
10614class MemberPointerExprEvaluator
10615 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
10616 MemberPtr &Result;
10617
10618 bool Success(const ValueDecl *D) {
10619 Result = MemberPtr(D);
10620 return true;
10621 }
10622public:
10623
10624 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
10625 : ExprEvaluatorBaseTy(Info), Result(Result) {}
10626
10627 bool Success(const APValue &V, const Expr *E) {
10628 Result.setFrom(V);
10629 return true;
10630 }
10631 bool ZeroInitialization(const Expr *E) {
10632 return Success((const ValueDecl*)nullptr);
10633 }
10634
10635 bool VisitCastExpr(const CastExpr *E);
10636 bool VisitUnaryAddrOf(const UnaryOperator *E);
10637};
10638} // end anonymous namespace
10639
10640static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
10641 EvalInfo &Info) {
10642 assert(!E->isValueDependent());
10643 assert(E->isPRValue() && E->getType()->isMemberPointerType());
10644 return MemberPointerExprEvaluator(Info, Result).Visit(E);
10645}
10646
10647bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
10648 switch (E->getCastKind()) {
10649 default:
10650 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10651
10652 case CK_NullToMemberPointer:
10653 VisitIgnoredValue(E->getSubExpr());
10654 return ZeroInitialization(E);
10655
10656 case CK_BaseToDerivedMemberPointer: {
10657 if (!Visit(E->getSubExpr()))
10658 return false;
10659 if (E->path_empty())
10660 return true;
10661 // Base-to-derived member pointer casts store the path in derived-to-base
10662 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
10663 // the wrong end of the derived->base arc, so stagger the path by one class.
10664 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
10665 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
10666 PathI != PathE; ++PathI) {
10667 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
10668 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
10669 if (!Result.castToDerived(Derived))
10670 return Error(E);
10671 }
10672 if (!Result.castToDerived(E->getType()
10673 ->castAs<MemberPointerType>()
10674 ->getMostRecentCXXRecordDecl()))
10675 return Error(E);
10676 return true;
10677 }
10678
10679 case CK_DerivedToBaseMemberPointer:
10680 if (!Visit(E->getSubExpr()))
10681 return false;
10682 for (CastExpr::path_const_iterator PathI = E->path_begin(),
10683 PathE = E->path_end(); PathI != PathE; ++PathI) {
10684 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
10685 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
10686 if (!Result.castToBase(Base))
10687 return Error(E);
10688 }
10689 return true;
10690 }
10691}
10692
10693bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
10694 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
10695 // member can be formed.
10696 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
10697}
10698
10699//===----------------------------------------------------------------------===//
10700// Record Evaluation
10701//===----------------------------------------------------------------------===//
10702
10703namespace {
10704 class RecordExprEvaluator
10705 : public ExprEvaluatorBase<RecordExprEvaluator> {
10706 const LValue &This;
10707 APValue &Result;
10708 public:
10709
10710 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
10711 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
10712
10713 bool Success(const APValue &V, const Expr *E) {
10714 Result = V;
10715 return true;
10716 }
10717 bool ZeroInitialization(const Expr *E) {
10718 return ZeroInitialization(E, E->getType());
10719 }
10720 bool ZeroInitialization(const Expr *E, QualType T);
10721
10722 bool VisitCallExpr(const CallExpr *E) {
10723 return handleCallExpr(E, Result, &This);
10724 }
10725 bool VisitCastExpr(const CastExpr *E);
10726 bool VisitInitListExpr(const InitListExpr *E);
10727 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
10728 return VisitCXXConstructExpr(E, E->getType());
10729 }
10730 bool VisitLambdaExpr(const LambdaExpr *E);
10731 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
10732 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
10733 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
10734 bool VisitBinCmp(const BinaryOperator *E);
10735 bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E);
10736 bool VisitCXXParenListOrInitListExpr(const Expr *ExprToVisit,
10737 ArrayRef<Expr *> Args);
10738 };
10739}
10740
10741/// Perform zero-initialization on an object of non-union class type.
10742/// C++11 [dcl.init]p5:
10743/// To zero-initialize an object or reference of type T means:
10744/// [...]
10745/// -- if T is a (possibly cv-qualified) non-union class type,
10746/// each non-static data member and each base-class subobject is
10747/// zero-initialized
10748static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
10749 const RecordDecl *RD,
10750 const LValue &This, APValue &Result) {
10751 assert(!RD->isUnion() && "Expected non-union class type");
10752 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
10753 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
10754 std::distance(RD->field_begin(), RD->field_end()));
10755
10756 if (RD->isInvalidDecl()) return false;
10757 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
10758
10759 if (CD) {
10760 unsigned Index = 0;
10762 End = CD->bases_end(); I != End; ++I, ++Index) {
10763 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
10764 LValue Subobject = This;
10765 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
10766 return false;
10767 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
10768 Result.getStructBase(Index)))
10769 return false;
10770 }
10771 }
10772
10773 for (const auto *I : RD->fields()) {
10774 // -- if T is a reference type, no initialization is performed.
10775 if (I->isUnnamedBitField() || I->getType()->isReferenceType())
10776 continue;
10777
10778 LValue Subobject = This;
10779 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
10780 return false;
10781
10782 ImplicitValueInitExpr VIE(I->getType());
10783 if (!EvaluateInPlace(
10784 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
10785 return false;
10786 }
10787
10788 return true;
10789}
10790
10791bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
10792 const auto *RD = T->castAsRecordDecl();
10793 if (RD->isInvalidDecl()) return false;
10794 if (RD->isUnion()) {
10795 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
10796 // object's first non-static named data member is zero-initialized
10798 while (I != RD->field_end() && (*I)->isUnnamedBitField())
10799 ++I;
10800 if (I == RD->field_end()) {
10801 Result = APValue((const FieldDecl*)nullptr);
10802 return true;
10803 }
10804
10805 LValue Subobject = This;
10806 if (!HandleLValueMember(Info, E, Subobject, *I))
10807 return false;
10808 Result = APValue(*I);
10809 ImplicitValueInitExpr VIE(I->getType());
10810 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
10811 }
10812
10813 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
10814 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
10815 return false;
10816 }
10817
10818 return HandleClassZeroInitialization(Info, E, RD, This, Result);
10819}
10820
10821bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
10822 switch (E->getCastKind()) {
10823 default:
10824 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10825
10826 case CK_ConstructorConversion:
10827 return Visit(E->getSubExpr());
10828
10829 case CK_DerivedToBase:
10830 case CK_UncheckedDerivedToBase: {
10831 APValue DerivedObject;
10832 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
10833 return false;
10834 if (!DerivedObject.isStruct())
10835 return Error(E->getSubExpr());
10836
10837 // Derived-to-base rvalue conversion: just slice off the derived part.
10838 APValue *Value = &DerivedObject;
10839 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
10840 for (CastExpr::path_const_iterator PathI = E->path_begin(),
10841 PathE = E->path_end(); PathI != PathE; ++PathI) {
10842 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
10843 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
10844 Value = &Value->getStructBase(getBaseIndex(RD, Base));
10845 RD = Base;
10846 }
10847 Result = *Value;
10848 return true;
10849 }
10850 }
10851}
10852
10853bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
10854 if (E->isTransparent())
10855 return Visit(E->getInit(0));
10856 return VisitCXXParenListOrInitListExpr(E, E->inits());
10857}
10858
10859bool RecordExprEvaluator::VisitCXXParenListOrInitListExpr(
10860 const Expr *ExprToVisit, ArrayRef<Expr *> Args) {
10861 const auto *RD = ExprToVisit->getType()->castAsRecordDecl();
10862 if (RD->isInvalidDecl()) return false;
10863 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
10864 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
10865
10866 EvalInfo::EvaluatingConstructorRAII EvalObj(
10867 Info,
10868 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
10869 CXXRD && CXXRD->getNumBases());
10870
10871 if (RD->isUnion()) {
10872 const FieldDecl *Field;
10873 if (auto *ILE = dyn_cast<InitListExpr>(ExprToVisit)) {
10874 Field = ILE->getInitializedFieldInUnion();
10875 } else if (auto *PLIE = dyn_cast<CXXParenListInitExpr>(ExprToVisit)) {
10876 Field = PLIE->getInitializedFieldInUnion();
10877 } else {
10878 llvm_unreachable(
10879 "Expression is neither an init list nor a C++ paren list");
10880 }
10881
10882 Result = APValue(Field);
10883 if (!Field)
10884 return true;
10885
10886 // If the initializer list for a union does not contain any elements, the
10887 // first element of the union is value-initialized.
10888 // FIXME: The element should be initialized from an initializer list.
10889 // Is this difference ever observable for initializer lists which
10890 // we don't build?
10891 ImplicitValueInitExpr VIE(Field->getType());
10892 const Expr *InitExpr = Args.empty() ? &VIE : Args[0];
10893
10894 LValue Subobject = This;
10895 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
10896 return false;
10897
10898 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
10899 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
10900 isa<CXXDefaultInitExpr>(InitExpr));
10901
10902 if (EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr)) {
10903 if (Field->isBitField())
10904 return truncateBitfieldValue(Info, InitExpr, Result.getUnionValue(),
10905 Field);
10906 return true;
10907 }
10908
10909 return false;
10910 }
10911
10912 if (!Result.hasValue())
10913 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
10914 std::distance(RD->field_begin(), RD->field_end()));
10915 unsigned ElementNo = 0;
10916 bool Success = true;
10917
10918 // Initialize base classes.
10919 if (CXXRD && CXXRD->getNumBases()) {
10920 for (const auto &Base : CXXRD->bases()) {
10921 assert(ElementNo < Args.size() && "missing init for base class");
10922 const Expr *Init = Args[ElementNo];
10923
10924 LValue Subobject = This;
10925 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
10926 return false;
10927
10928 APValue &FieldVal = Result.getStructBase(ElementNo);
10929 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
10930 if (!Info.noteFailure())
10931 return false;
10932 Success = false;
10933 }
10934 ++ElementNo;
10935 }
10936
10937 EvalObj.finishedConstructingBases();
10938 }
10939
10940 // Initialize members.
10941 for (const auto *Field : RD->fields()) {
10942 // Anonymous bit-fields are not considered members of the class for
10943 // purposes of aggregate initialization.
10944 if (Field->isUnnamedBitField())
10945 continue;
10946
10947 LValue Subobject = This;
10948
10949 bool HaveInit = ElementNo < Args.size();
10950
10951 // FIXME: Diagnostics here should point to the end of the initializer
10952 // list, not the start.
10953 if (!HandleLValueMember(Info, HaveInit ? Args[ElementNo] : ExprToVisit,
10954 Subobject, Field, &Layout))
10955 return false;
10956
10957 // Perform an implicit value-initialization for members beyond the end of
10958 // the initializer list.
10959 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
10960 const Expr *Init = HaveInit ? Args[ElementNo++] : &VIE;
10961
10962 if (Field->getType()->isIncompleteArrayType()) {
10963 if (auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType())) {
10964 if (!CAT->isZeroSize()) {
10965 // Bail out for now. This might sort of "work", but the rest of the
10966 // code isn't really prepared to handle it.
10967 Info.FFDiag(Init, diag::note_constexpr_unsupported_flexible_array);
10968 return false;
10969 }
10970 }
10971 }
10972
10973 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
10974 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
10976
10977 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
10978 if (Field->getType()->isReferenceType()) {
10979 LValue Result;
10981 FieldVal)) {
10982 if (!Info.noteFailure())
10983 return false;
10984 Success = false;
10985 }
10986 } else if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
10987 (Field->isBitField() &&
10988 !truncateBitfieldValue(Info, Init, FieldVal, Field))) {
10989 if (!Info.noteFailure())
10990 return false;
10991 Success = false;
10992 }
10993 }
10994
10995 EvalObj.finishedConstructingFields();
10996
10997 return Success;
10998}
10999
11000bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
11001 QualType T) {
11002 // Note that E's type is not necessarily the type of our class here; we might
11003 // be initializing an array element instead.
11004 const CXXConstructorDecl *FD = E->getConstructor();
11005 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
11006
11007 bool ZeroInit = E->requiresZeroInitialization();
11008 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
11009 if (ZeroInit)
11010 return ZeroInitialization(E, T);
11011
11013 }
11014
11015 const FunctionDecl *Definition = nullptr;
11016 auto Body = FD->getBody(Definition);
11017
11018 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
11019 return false;
11020
11021 // Avoid materializing a temporary for an elidable copy/move constructor.
11022 if (E->isElidable() && !ZeroInit) {
11023 // FIXME: This only handles the simplest case, where the source object
11024 // is passed directly as the first argument to the constructor.
11025 // This should also handle stepping though implicit casts and
11026 // and conversion sequences which involve two steps, with a
11027 // conversion operator followed by a converting constructor.
11028 const Expr *SrcObj = E->getArg(0);
11029 assert(SrcObj->isTemporaryObject(Info.Ctx, FD->getParent()));
11030 assert(Info.Ctx.hasSameUnqualifiedType(E->getType(), SrcObj->getType()));
11031 if (const MaterializeTemporaryExpr *ME =
11032 dyn_cast<MaterializeTemporaryExpr>(SrcObj))
11033 return Visit(ME->getSubExpr());
11034 }
11035
11036 if (ZeroInit && !ZeroInitialization(E, T))
11037 return false;
11038
11039 auto Args = ArrayRef(E->getArgs(), E->getNumArgs());
11040 return HandleConstructorCall(E, This, Args,
11042 Result);
11043}
11044
11045bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
11046 const CXXInheritedCtorInitExpr *E) {
11047 if (!Info.CurrentCall) {
11048 assert(Info.checkingPotentialConstantExpression());
11049 return false;
11050 }
11051
11052 const CXXConstructorDecl *FD = E->getConstructor();
11053 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
11054 return false;
11055
11056 const FunctionDecl *Definition = nullptr;
11057 auto Body = FD->getBody(Definition);
11058
11059 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
11060 return false;
11061
11062 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
11064 Result);
11065}
11066
11067bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
11068 const CXXStdInitializerListExpr *E) {
11069 const ConstantArrayType *ArrayType =
11070 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
11071
11072 LValue Array;
11073 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
11074 return false;
11075
11076 assert(ArrayType && "unexpected type for array initializer");
11077
11078 // Get a pointer to the first element of the array.
11079 Array.addArray(Info, E, ArrayType);
11080
11081 // FIXME: What if the initializer_list type has base classes, etc?
11082 Result = APValue(APValue::UninitStruct(), 0, 2);
11083 Array.moveInto(Result.getStructField(0));
11084
11085 auto *Record = E->getType()->castAsRecordDecl();
11086 RecordDecl::field_iterator Field = Record->field_begin();
11087 assert(Field != Record->field_end() &&
11088 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
11089 ArrayType->getElementType()) &&
11090 "Expected std::initializer_list first field to be const E *");
11091 ++Field;
11092 assert(Field != Record->field_end() &&
11093 "Expected std::initializer_list to have two fields");
11094
11095 if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType())) {
11096 // Length.
11097 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
11098 } else {
11099 // End pointer.
11100 assert(Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
11101 ArrayType->getElementType()) &&
11102 "Expected std::initializer_list second field to be const E *");
11103 if (!HandleLValueArrayAdjustment(Info, E, Array,
11104 ArrayType->getElementType(),
11105 ArrayType->getZExtSize()))
11106 return false;
11107 Array.moveInto(Result.getStructField(1));
11108 }
11109
11110 assert(++Field == Record->field_end() &&
11111 "Expected std::initializer_list to only have two fields");
11112
11113 return true;
11114}
11115
11116bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
11117 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
11118 if (ClosureClass->isInvalidDecl())
11119 return false;
11120
11121 const size_t NumFields =
11122 std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
11123
11124 assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
11125 E->capture_init_end()) &&
11126 "The number of lambda capture initializers should equal the number of "
11127 "fields within the closure type");
11128
11129 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
11130 // Iterate through all the lambda's closure object's fields and initialize
11131 // them.
11132 auto *CaptureInitIt = E->capture_init_begin();
11133 bool Success = true;
11134 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(ClosureClass);
11135 for (const auto *Field : ClosureClass->fields()) {
11136 assert(CaptureInitIt != E->capture_init_end());
11137 // Get the initializer for this field
11138 Expr *const CurFieldInit = *CaptureInitIt++;
11139
11140 // If there is no initializer, either this is a VLA or an error has
11141 // occurred.
11142 if (!CurFieldInit || CurFieldInit->containsErrors())
11143 return Error(E);
11144
11145 LValue Subobject = This;
11146
11147 if (!HandleLValueMember(Info, E, Subobject, Field, &Layout))
11148 return false;
11149
11150 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
11151 if (!EvaluateInPlace(FieldVal, Info, Subobject, CurFieldInit)) {
11152 if (!Info.keepEvaluatingAfterFailure())
11153 return false;
11154 Success = false;
11155 }
11156 }
11157 return Success;
11158}
11159
11160static bool EvaluateRecord(const Expr *E, const LValue &This,
11161 APValue &Result, EvalInfo &Info) {
11162 assert(!E->isValueDependent());
11163 assert(E->isPRValue() && E->getType()->isRecordType() &&
11164 "can't evaluate expression as a record rvalue");
11165 return RecordExprEvaluator(Info, This, Result).Visit(E);
11166}
11167
11168//===----------------------------------------------------------------------===//
11169// Temporary Evaluation
11170//
11171// Temporaries are represented in the AST as rvalues, but generally behave like
11172// lvalues. The full-object of which the temporary is a subobject is implicitly
11173// materialized so that a reference can bind to it.
11174//===----------------------------------------------------------------------===//
11175namespace {
11176class TemporaryExprEvaluator
11177 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
11178public:
11179 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
11180 LValueExprEvaluatorBaseTy(Info, Result, false) {}
11181
11182 /// Visit an expression which constructs the value of this temporary.
11183 bool VisitConstructExpr(const Expr *E) {
11184 APValue &Value = Info.CurrentCall->createTemporary(
11185 E, E->getType(), ScopeKind::FullExpression, Result);
11186 return EvaluateInPlace(Value, Info, Result, E);
11187 }
11188
11189 bool VisitCastExpr(const CastExpr *E) {
11190 switch (E->getCastKind()) {
11191 default:
11192 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
11193
11194 case CK_ConstructorConversion:
11195 return VisitConstructExpr(E->getSubExpr());
11196 }
11197 }
11198 bool VisitInitListExpr(const InitListExpr *E) {
11199 return VisitConstructExpr(E);
11200 }
11201 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
11202 return VisitConstructExpr(E);
11203 }
11204 bool VisitCallExpr(const CallExpr *E) {
11205 return VisitConstructExpr(E);
11206 }
11207 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
11208 return VisitConstructExpr(E);
11209 }
11210 bool VisitLambdaExpr(const LambdaExpr *E) {
11211 return VisitConstructExpr(E);
11212 }
11213};
11214} // end anonymous namespace
11215
11216/// Evaluate an expression of record type as a temporary.
11217static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
11218 assert(!E->isValueDependent());
11219 assert(E->isPRValue() && E->getType()->isRecordType());
11220 return TemporaryExprEvaluator(Info, Result).Visit(E);
11221}
11222
11223//===----------------------------------------------------------------------===//
11224// Vector Evaluation
11225//===----------------------------------------------------------------------===//
11226
11227namespace {
11228 class VectorExprEvaluator
11229 : public ExprEvaluatorBase<VectorExprEvaluator> {
11230 APValue &Result;
11231 public:
11232
11233 VectorExprEvaluator(EvalInfo &info, APValue &Result)
11234 : ExprEvaluatorBaseTy(info), Result(Result) {}
11235
11236 bool Success(ArrayRef<APValue> V, const Expr *E) {
11237 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
11238 // FIXME: remove this APValue copy.
11239 Result = APValue(V.data(), V.size());
11240 return true;
11241 }
11242 bool Success(const APValue &V, const Expr *E) {
11243 assert(V.isVector());
11244 Result = V;
11245 return true;
11246 }
11247 bool ZeroInitialization(const Expr *E);
11248
11249 bool VisitUnaryReal(const UnaryOperator *E)
11250 { return Visit(E->getSubExpr()); }
11251 bool VisitCastExpr(const CastExpr* E);
11252 bool VisitInitListExpr(const InitListExpr *E);
11253 bool VisitUnaryImag(const UnaryOperator *E);
11254 bool VisitBinaryOperator(const BinaryOperator *E);
11255 bool VisitUnaryOperator(const UnaryOperator *E);
11256 bool VisitCallExpr(const CallExpr *E);
11257 bool VisitConvertVectorExpr(const ConvertVectorExpr *E);
11258 bool VisitShuffleVectorExpr(const ShuffleVectorExpr *E);
11259
11260 // FIXME: Missing: conditional operator (for GNU
11261 // conditional select), ExtVectorElementExpr
11262 };
11263} // end anonymous namespace
11264
11265static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
11266 assert(E->isPRValue() && E->getType()->isVectorType() &&
11267 "not a vector prvalue");
11268 return VectorExprEvaluator(Info, Result).Visit(E);
11269}
11270
11271static llvm::APInt ConvertBoolVectorToInt(const APValue &Val) {
11272 assert(Val.isVector() && "expected vector APValue");
11273 unsigned NumElts = Val.getVectorLength();
11274
11275 // Each element is one bit, so create an integer with NumElts bits.
11276 llvm::APInt Result(NumElts, 0);
11277
11278 for (unsigned I = 0; I < NumElts; ++I) {
11279 const APValue &Elt = Val.getVectorElt(I);
11280 assert(Elt.isInt() && "expected integer element in bool vector");
11281
11282 if (Elt.getInt().getBoolValue())
11283 Result.setBit(I);
11284 }
11285
11286 return Result;
11287}
11288
11289bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
11290 const VectorType *VTy = E->getType()->castAs<VectorType>();
11291 unsigned NElts = VTy->getNumElements();
11292
11293 const Expr *SE = E->getSubExpr();
11294 QualType SETy = SE->getType();
11295
11296 switch (E->getCastKind()) {
11297 case CK_VectorSplat: {
11298 APValue Val = APValue();
11299 if (SETy->isIntegerType()) {
11300 APSInt IntResult;
11301 if (!EvaluateInteger(SE, IntResult, Info))
11302 return false;
11303 Val = APValue(std::move(IntResult));
11304 } else if (SETy->isRealFloatingType()) {
11305 APFloat FloatResult(0.0);
11306 if (!EvaluateFloat(SE, FloatResult, Info))
11307 return false;
11308 Val = APValue(std::move(FloatResult));
11309 } else {
11310 return Error(E);
11311 }
11312
11313 // Splat and create vector APValue.
11314 SmallVector<APValue, 4> Elts(NElts, Val);
11315 return Success(Elts, E);
11316 }
11317 case CK_BitCast: {
11318 APValue SVal;
11319 if (!Evaluate(SVal, Info, SE))
11320 return false;
11321
11322 if (!SVal.isInt() && !SVal.isFloat() && !SVal.isVector()) {
11323 // Give up if the input isn't an int, float, or vector. For example, we
11324 // reject "(v4i16)(intptr_t)&a".
11325 Info.FFDiag(E, diag::note_constexpr_invalid_cast)
11326 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
11327 << Info.Ctx.getLangOpts().CPlusPlus;
11328 return false;
11329 }
11330
11331 if (!handleRValueToRValueBitCast(Info, Result, SVal, E))
11332 return false;
11333
11334 return true;
11335 }
11336 case CK_HLSLVectorTruncation: {
11337 APValue Val;
11338 SmallVector<APValue, 4> Elements;
11339 if (!EvaluateVector(SE, Val, Info))
11340 return Error(E);
11341 for (unsigned I = 0; I < NElts; I++)
11342 Elements.push_back(Val.getVectorElt(I));
11343 return Success(Elements, E);
11344 }
11345 default:
11346 return ExprEvaluatorBaseTy::VisitCastExpr(E);
11347 }
11348}
11349
11350bool
11351VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
11352 const VectorType *VT = E->getType()->castAs<VectorType>();
11353 unsigned NumInits = E->getNumInits();
11354 unsigned NumElements = VT->getNumElements();
11355
11356 QualType EltTy = VT->getElementType();
11357 SmallVector<APValue, 4> Elements;
11358
11359 // MFloat8 type doesn't have constants and thus constant folding
11360 // is impossible.
11361 if (EltTy->isMFloat8Type())
11362 return false;
11363
11364 // The number of initializers can be less than the number of
11365 // vector elements. For OpenCL, this can be due to nested vector
11366 // initialization. For GCC compatibility, missing trailing elements
11367 // should be initialized with zeroes.
11368 unsigned CountInits = 0, CountElts = 0;
11369 while (CountElts < NumElements) {
11370 // Handle nested vector initialization.
11371 if (CountInits < NumInits
11372 && E->getInit(CountInits)->getType()->isVectorType()) {
11373 APValue v;
11374 if (!EvaluateVector(E->getInit(CountInits), v, Info))
11375 return Error(E);
11376 unsigned vlen = v.getVectorLength();
11377 for (unsigned j = 0; j < vlen; j++)
11378 Elements.push_back(v.getVectorElt(j));
11379 CountElts += vlen;
11380 } else if (EltTy->isIntegerType()) {
11381 llvm::APSInt sInt(32);
11382 if (CountInits < NumInits) {
11383 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
11384 return false;
11385 } else // trailing integer zero.
11386 sInt = Info.Ctx.MakeIntValue(0, EltTy);
11387 Elements.push_back(APValue(sInt));
11388 CountElts++;
11389 } else {
11390 llvm::APFloat f(0.0);
11391 if (CountInits < NumInits) {
11392 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
11393 return false;
11394 } else // trailing float zero.
11395 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
11396 Elements.push_back(APValue(f));
11397 CountElts++;
11398 }
11399 CountInits++;
11400 }
11401 return Success(Elements, E);
11402}
11403
11404bool
11405VectorExprEvaluator::ZeroInitialization(const Expr *E) {
11406 const auto *VT = E->getType()->castAs<VectorType>();
11407 QualType EltTy = VT->getElementType();
11408 APValue ZeroElement;
11409 if (EltTy->isIntegerType())
11410 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
11411 else
11412 ZeroElement =
11413 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
11414
11415 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
11416 return Success(Elements, E);
11417}
11418
11419bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
11420 VisitIgnoredValue(E->getSubExpr());
11421 return ZeroInitialization(E);
11422}
11423
11424bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
11425 BinaryOperatorKind Op = E->getOpcode();
11426 assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp &&
11427 "Operation not supported on vector types");
11428
11429 if (Op == BO_Comma)
11430 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
11431
11432 Expr *LHS = E->getLHS();
11433 Expr *RHS = E->getRHS();
11434
11435 assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() &&
11436 "Must both be vector types");
11437 // Checking JUST the types are the same would be fine, except shifts don't
11438 // need to have their types be the same (since you always shift by an int).
11439 assert(LHS->getType()->castAs<VectorType>()->getNumElements() ==
11440 E->getType()->castAs<VectorType>()->getNumElements() &&
11441 RHS->getType()->castAs<VectorType>()->getNumElements() ==
11442 E->getType()->castAs<VectorType>()->getNumElements() &&
11443 "All operands must be the same size.");
11444
11445 APValue LHSValue;
11446 APValue RHSValue;
11447 bool LHSOK = Evaluate(LHSValue, Info, LHS);
11448 if (!LHSOK && !Info.noteFailure())
11449 return false;
11450 if (!Evaluate(RHSValue, Info, RHS) || !LHSOK)
11451 return false;
11452
11453 if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue))
11454 return false;
11455
11456 return Success(LHSValue, E);
11457}
11458
11459static std::optional<APValue> handleVectorUnaryOperator(ASTContext &Ctx,
11460 QualType ResultTy,
11462 APValue Elt) {
11463 switch (Op) {
11464 case UO_Plus:
11465 // Nothing to do here.
11466 return Elt;
11467 case UO_Minus:
11468 if (Elt.getKind() == APValue::Int) {
11469 Elt.getInt().negate();
11470 } else {
11471 assert(Elt.getKind() == APValue::Float &&
11472 "Vector can only be int or float type");
11473 Elt.getFloat().changeSign();
11474 }
11475 return Elt;
11476 case UO_Not:
11477 // This is only valid for integral types anyway, so we don't have to handle
11478 // float here.
11479 assert(Elt.getKind() == APValue::Int &&
11480 "Vector operator ~ can only be int");
11481 Elt.getInt().flipAllBits();
11482 return Elt;
11483 case UO_LNot: {
11484 if (Elt.getKind() == APValue::Int) {
11485 Elt.getInt() = !Elt.getInt();
11486 // operator ! on vectors returns -1 for 'truth', so negate it.
11487 Elt.getInt().negate();
11488 return Elt;
11489 }
11490 assert(Elt.getKind() == APValue::Float &&
11491 "Vector can only be int or float type");
11492 // Float types result in an int of the same size, but -1 for true, or 0 for
11493 // false.
11494 APSInt EltResult{Ctx.getIntWidth(ResultTy),
11495 ResultTy->isUnsignedIntegerType()};
11496 if (Elt.getFloat().isZero())
11497 EltResult.setAllBits();
11498 else
11499 EltResult.clearAllBits();
11500
11501 return APValue{EltResult};
11502 }
11503 default:
11504 // FIXME: Implement the rest of the unary operators.
11505 return std::nullopt;
11506 }
11507}
11508
11509bool VectorExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
11510 Expr *SubExpr = E->getSubExpr();
11511 const auto *VD = SubExpr->getType()->castAs<VectorType>();
11512 // This result element type differs in the case of negating a floating point
11513 // vector, since the result type is the a vector of the equivilant sized
11514 // integer.
11515 const QualType ResultEltTy = VD->getElementType();
11516 UnaryOperatorKind Op = E->getOpcode();
11517
11518 APValue SubExprValue;
11519 if (!Evaluate(SubExprValue, Info, SubExpr))
11520 return false;
11521
11522 // FIXME: This vector evaluator someday needs to be changed to be LValue
11523 // aware/keep LValue information around, rather than dealing with just vector
11524 // types directly. Until then, we cannot handle cases where the operand to
11525 // these unary operators is an LValue. The only case I've been able to see
11526 // cause this is operator++ assigning to a member expression (only valid in
11527 // altivec compilations) in C mode, so this shouldn't limit us too much.
11528 if (SubExprValue.isLValue())
11529 return false;
11530
11531 assert(SubExprValue.getVectorLength() == VD->getNumElements() &&
11532 "Vector length doesn't match type?");
11533
11534 SmallVector<APValue, 4> ResultElements;
11535 for (unsigned EltNum = 0; EltNum < VD->getNumElements(); ++EltNum) {
11536 std::optional<APValue> Elt = handleVectorUnaryOperator(
11537 Info.Ctx, ResultEltTy, Op, SubExprValue.getVectorElt(EltNum));
11538 if (!Elt)
11539 return false;
11540 ResultElements.push_back(*Elt);
11541 }
11542 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
11543}
11544
11545static bool handleVectorElementCast(EvalInfo &Info, const FPOptions FPO,
11546 const Expr *E, QualType SourceTy,
11547 QualType DestTy, APValue const &Original,
11548 APValue &Result) {
11549 if (SourceTy->isIntegerType()) {
11550 if (DestTy->isRealFloatingType()) {
11551 Result = APValue(APFloat(0.0));
11552 return HandleIntToFloatCast(Info, E, FPO, SourceTy, Original.getInt(),
11553 DestTy, Result.getFloat());
11554 }
11555 if (DestTy->isIntegerType()) {
11556 Result = APValue(
11557 HandleIntToIntCast(Info, E, DestTy, SourceTy, Original.getInt()));
11558 return true;
11559 }
11560 } else if (SourceTy->isRealFloatingType()) {
11561 if (DestTy->isRealFloatingType()) {
11562 Result = Original;
11563 return HandleFloatToFloatCast(Info, E, SourceTy, DestTy,
11564 Result.getFloat());
11565 }
11566 if (DestTy->isIntegerType()) {
11567 Result = APValue(APSInt());
11568 return HandleFloatToIntCast(Info, E, SourceTy, Original.getFloat(),
11569 DestTy, Result.getInt());
11570 }
11571 }
11572
11573 Info.FFDiag(E, diag::err_convertvector_constexpr_unsupported_vector_cast)
11574 << SourceTy << DestTy;
11575 return false;
11576}
11577
11578static bool evalPackBuiltin(const CallExpr *E, EvalInfo &Info, APValue &Result,
11579 llvm::function_ref<APInt(const APSInt &)> PackFn) {
11580 APValue LHS, RHS;
11581 if (!EvaluateAsRValue(Info, E->getArg(0), LHS) ||
11582 !EvaluateAsRValue(Info, E->getArg(1), RHS))
11583 return false;
11584
11585 unsigned LHSVecLen = LHS.getVectorLength();
11586 unsigned RHSVecLen = RHS.getVectorLength();
11587
11588 assert(LHSVecLen != 0 && LHSVecLen == RHSVecLen &&
11589 "pack builtin LHSVecLen must equal to RHSVecLen");
11590
11591 const VectorType *VT0 = E->getArg(0)->getType()->castAs<VectorType>();
11592 const unsigned SrcBits = Info.Ctx.getIntWidth(VT0->getElementType());
11593
11594 const VectorType *DstVT = E->getType()->castAs<VectorType>();
11595 QualType DstElemTy = DstVT->getElementType();
11596 const bool DstIsUnsigned = DstElemTy->isUnsignedIntegerType();
11597
11598 const unsigned SrcPerLane = 128 / SrcBits;
11599 const unsigned Lanes = LHSVecLen * SrcBits / 128;
11600
11602 Out.reserve(LHSVecLen + RHSVecLen);
11603
11604 for (unsigned Lane = 0; Lane != Lanes; ++Lane) {
11605 unsigned base = Lane * SrcPerLane;
11606 for (unsigned I = 0; I != SrcPerLane; ++I)
11607 Out.emplace_back(APValue(
11608 APSInt(PackFn(LHS.getVectorElt(base + I).getInt()), DstIsUnsigned)));
11609 for (unsigned I = 0; I != SrcPerLane; ++I)
11610 Out.emplace_back(APValue(
11611 APSInt(PackFn(RHS.getVectorElt(base + I).getInt()), DstIsUnsigned)));
11612 }
11613
11614 Result = APValue(Out.data(), Out.size());
11615 return true;
11616}
11617
11618bool VectorExprEvaluator::VisitCallExpr(const CallExpr *E) {
11619 if (!IsConstantEvaluatedBuiltinCall(E))
11620 return ExprEvaluatorBaseTy::VisitCallExpr(E);
11621
11622 auto EvaluateBinOpExpr =
11623 [&](llvm::function_ref<APInt(const APSInt &, const APSInt &)> Fn) {
11624 APValue SourceLHS, SourceRHS;
11625 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
11626 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
11627 return false;
11628
11629 auto *DestTy = E->getType()->castAs<VectorType>();
11630 QualType DestEltTy = DestTy->getElementType();
11631 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
11632 unsigned SourceLen = SourceLHS.getVectorLength();
11633 SmallVector<APValue, 4> ResultElements;
11634 ResultElements.reserve(SourceLen);
11635
11636 if (SourceRHS.isInt()) {
11637 const APSInt &RHS = SourceRHS.getInt();
11638 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
11639 const APSInt &LHS = SourceLHS.getVectorElt(EltNum).getInt();
11640 ResultElements.push_back(
11641 APValue(APSInt(Fn(LHS, RHS), DestUnsigned)));
11642 }
11643 } else {
11644 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
11645 const APSInt &LHS = SourceLHS.getVectorElt(EltNum).getInt();
11646 const APSInt &RHS = SourceRHS.getVectorElt(EltNum).getInt();
11647 ResultElements.push_back(
11648 APValue(APSInt(Fn(LHS, RHS), DestUnsigned)));
11649 }
11650 }
11651 return Success(APValue(ResultElements.data(), SourceLen), E);
11652 };
11653
11654 switch (E->getBuiltinCallee()) {
11655 default:
11656 return false;
11657 case Builtin::BI__builtin_elementwise_popcount:
11658 case Builtin::BI__builtin_elementwise_bitreverse: {
11659 APValue Source;
11660 if (!EvaluateAsRValue(Info, E->getArg(0), Source))
11661 return false;
11662
11663 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
11664 unsigned SourceLen = Source.getVectorLength();
11665 SmallVector<APValue, 4> ResultElements;
11666 ResultElements.reserve(SourceLen);
11667
11668 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
11669 APSInt Elt = Source.getVectorElt(EltNum).getInt();
11670 switch (E->getBuiltinCallee()) {
11671 case Builtin::BI__builtin_elementwise_popcount:
11672 ResultElements.push_back(APValue(
11673 APSInt(APInt(Info.Ctx.getIntWidth(DestEltTy), Elt.popcount()),
11674 DestEltTy->isUnsignedIntegerOrEnumerationType())));
11675 break;
11676 case Builtin::BI__builtin_elementwise_bitreverse:
11677 ResultElements.push_back(
11678 APValue(APSInt(Elt.reverseBits(),
11679 DestEltTy->isUnsignedIntegerOrEnumerationType())));
11680 break;
11681 }
11682 }
11683
11684 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
11685 }
11686 case Builtin::BI__builtin_elementwise_abs: {
11687 APValue Source;
11688 if (!EvaluateAsRValue(Info, E->getArg(0), Source))
11689 return false;
11690
11691 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
11692 unsigned SourceLen = Source.getVectorLength();
11693 SmallVector<APValue, 4> ResultElements;
11694 ResultElements.reserve(SourceLen);
11695
11696 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
11697 APValue CurrentEle = Source.getVectorElt(EltNum);
11698 APValue Val = DestEltTy->isFloatingType()
11699 ? APValue(llvm::abs(CurrentEle.getFloat()))
11700 : APValue(APSInt(
11701 CurrentEle.getInt().abs(),
11702 DestEltTy->isUnsignedIntegerOrEnumerationType()));
11703 ResultElements.push_back(Val);
11704 }
11705
11706 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
11707 }
11708
11709 case Builtin::BI__builtin_elementwise_add_sat:
11710 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
11711 return LHS.isSigned() ? LHS.sadd_sat(RHS) : LHS.uadd_sat(RHS);
11712 });
11713
11714 case Builtin::BI__builtin_elementwise_sub_sat:
11715 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
11716 return LHS.isSigned() ? LHS.ssub_sat(RHS) : LHS.usub_sat(RHS);
11717 });
11718
11719 case clang::X86::BI__builtin_ia32_pavgb128:
11720 case clang::X86::BI__builtin_ia32_pavgw128:
11721 case clang::X86::BI__builtin_ia32_pavgb256:
11722 case clang::X86::BI__builtin_ia32_pavgw256:
11723 case clang::X86::BI__builtin_ia32_pavgb512:
11724 case clang::X86::BI__builtin_ia32_pavgw512:
11725 return EvaluateBinOpExpr(llvm::APIntOps::avgCeilU);
11726
11727 case clang::X86::BI__builtin_ia32_pmulhuw128:
11728 case clang::X86::BI__builtin_ia32_pmulhuw256:
11729 case clang::X86::BI__builtin_ia32_pmulhuw512:
11730 return EvaluateBinOpExpr(llvm::APIntOps::mulhu);
11731
11732 case clang::X86::BI__builtin_ia32_pmulhw128:
11733 case clang::X86::BI__builtin_ia32_pmulhw256:
11734 case clang::X86::BI__builtin_ia32_pmulhw512:
11735 return EvaluateBinOpExpr(llvm::APIntOps::mulhs);
11736
11737 case clang::X86::BI__builtin_ia32_psllv2di:
11738 case clang::X86::BI__builtin_ia32_psllv4di:
11739 case clang::X86::BI__builtin_ia32_psllv4si:
11740 case clang::X86::BI__builtin_ia32_psllv8di:
11741 case clang::X86::BI__builtin_ia32_psllv8hi:
11742 case clang::X86::BI__builtin_ia32_psllv8si:
11743 case clang::X86::BI__builtin_ia32_psllv16hi:
11744 case clang::X86::BI__builtin_ia32_psllv16si:
11745 case clang::X86::BI__builtin_ia32_psllv32hi:
11746 case clang::X86::BI__builtin_ia32_psllwi128:
11747 case clang::X86::BI__builtin_ia32_pslldi128:
11748 case clang::X86::BI__builtin_ia32_psllqi128:
11749 case clang::X86::BI__builtin_ia32_psllwi256:
11750 case clang::X86::BI__builtin_ia32_pslldi256:
11751 case clang::X86::BI__builtin_ia32_psllqi256:
11752 case clang::X86::BI__builtin_ia32_psllwi512:
11753 case clang::X86::BI__builtin_ia32_pslldi512:
11754 case clang::X86::BI__builtin_ia32_psllqi512:
11755 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
11756 if (RHS.uge(LHS.getBitWidth())) {
11757 return APInt::getZero(LHS.getBitWidth());
11758 }
11759 return LHS.shl(RHS.getZExtValue());
11760 });
11761
11762 case clang::X86::BI__builtin_ia32_psrav4si:
11763 case clang::X86::BI__builtin_ia32_psrav8di:
11764 case clang::X86::BI__builtin_ia32_psrav8hi:
11765 case clang::X86::BI__builtin_ia32_psrav8si:
11766 case clang::X86::BI__builtin_ia32_psrav16hi:
11767 case clang::X86::BI__builtin_ia32_psrav16si:
11768 case clang::X86::BI__builtin_ia32_psrav32hi:
11769 case clang::X86::BI__builtin_ia32_psravq128:
11770 case clang::X86::BI__builtin_ia32_psravq256:
11771 case clang::X86::BI__builtin_ia32_psrawi128:
11772 case clang::X86::BI__builtin_ia32_psradi128:
11773 case clang::X86::BI__builtin_ia32_psraqi128:
11774 case clang::X86::BI__builtin_ia32_psrawi256:
11775 case clang::X86::BI__builtin_ia32_psradi256:
11776 case clang::X86::BI__builtin_ia32_psraqi256:
11777 case clang::X86::BI__builtin_ia32_psrawi512:
11778 case clang::X86::BI__builtin_ia32_psradi512:
11779 case clang::X86::BI__builtin_ia32_psraqi512:
11780 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
11781 if (RHS.uge(LHS.getBitWidth())) {
11782 return LHS.ashr(LHS.getBitWidth() - 1);
11783 }
11784 return LHS.ashr(RHS.getZExtValue());
11785 });
11786
11787 case clang::X86::BI__builtin_ia32_psrlv2di:
11788 case clang::X86::BI__builtin_ia32_psrlv4di:
11789 case clang::X86::BI__builtin_ia32_psrlv4si:
11790 case clang::X86::BI__builtin_ia32_psrlv8di:
11791 case clang::X86::BI__builtin_ia32_psrlv8hi:
11792 case clang::X86::BI__builtin_ia32_psrlv8si:
11793 case clang::X86::BI__builtin_ia32_psrlv16hi:
11794 case clang::X86::BI__builtin_ia32_psrlv16si:
11795 case clang::X86::BI__builtin_ia32_psrlv32hi:
11796 case clang::X86::BI__builtin_ia32_psrlwi128:
11797 case clang::X86::BI__builtin_ia32_psrldi128:
11798 case clang::X86::BI__builtin_ia32_psrlqi128:
11799 case clang::X86::BI__builtin_ia32_psrlwi256:
11800 case clang::X86::BI__builtin_ia32_psrldi256:
11801 case clang::X86::BI__builtin_ia32_psrlqi256:
11802 case clang::X86::BI__builtin_ia32_psrlwi512:
11803 case clang::X86::BI__builtin_ia32_psrldi512:
11804 case clang::X86::BI__builtin_ia32_psrlqi512:
11805 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
11806 if (RHS.uge(LHS.getBitWidth())) {
11807 return APInt::getZero(LHS.getBitWidth());
11808 }
11809 return LHS.lshr(RHS.getZExtValue());
11810 });
11811 case X86::BI__builtin_ia32_packsswb128:
11812 case X86::BI__builtin_ia32_packsswb256:
11813 case X86::BI__builtin_ia32_packsswb512:
11814 case X86::BI__builtin_ia32_packssdw128:
11815 case X86::BI__builtin_ia32_packssdw256:
11816 case X86::BI__builtin_ia32_packssdw512:
11817 return evalPackBuiltin(E, Info, Result, [](const APSInt &Src) {
11818 return APSInt(Src).truncSSat(Src.getBitWidth() / 2);
11819 });
11820 case X86::BI__builtin_ia32_packusdw128:
11821 case X86::BI__builtin_ia32_packusdw256:
11822 case X86::BI__builtin_ia32_packusdw512:
11823 case X86::BI__builtin_ia32_packuswb128:
11824 case X86::BI__builtin_ia32_packuswb256:
11825 case X86::BI__builtin_ia32_packuswb512:
11826 return evalPackBuiltin(E, Info, Result, [](const APSInt &Src) {
11827 unsigned DstBits = Src.getBitWidth() / 2;
11828 if (Src.isNegative())
11829 return APInt::getZero(DstBits);
11830 if (Src.isIntN(DstBits))
11831 return APInt((Src).trunc(DstBits));
11832 return APInt::getAllOnes(DstBits);
11833 });
11834 case clang::X86::BI__builtin_ia32_pmuldq128:
11835 case clang::X86::BI__builtin_ia32_pmuldq256:
11836 case clang::X86::BI__builtin_ia32_pmuldq512:
11837 case clang::X86::BI__builtin_ia32_pmuludq128:
11838 case clang::X86::BI__builtin_ia32_pmuludq256:
11839 case clang::X86::BI__builtin_ia32_pmuludq512: {
11840 APValue SourceLHS, SourceRHS;
11841 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
11842 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
11843 return false;
11844
11845 unsigned SourceLen = SourceLHS.getVectorLength();
11846 SmallVector<APValue, 4> ResultElements;
11847 ResultElements.reserve(SourceLen / 2);
11848
11849 for (unsigned EltNum = 0; EltNum < SourceLen; EltNum += 2) {
11850 APSInt LHS = SourceLHS.getVectorElt(EltNum).getInt();
11851 APSInt RHS = SourceRHS.getVectorElt(EltNum).getInt();
11852
11853 switch (E->getBuiltinCallee()) {
11854 case clang::X86::BI__builtin_ia32_pmuludq128:
11855 case clang::X86::BI__builtin_ia32_pmuludq256:
11856 case clang::X86::BI__builtin_ia32_pmuludq512:
11857 ResultElements.push_back(
11858 APValue(APSInt(llvm::APIntOps::muluExtended(LHS, RHS), true)));
11859 break;
11860 case clang::X86::BI__builtin_ia32_pmuldq128:
11861 case clang::X86::BI__builtin_ia32_pmuldq256:
11862 case clang::X86::BI__builtin_ia32_pmuldq512:
11863 ResultElements.push_back(
11864 APValue(APSInt(llvm::APIntOps::mulsExtended(LHS, RHS), false)));
11865 break;
11866 }
11867 }
11868
11869 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
11870 }
11871
11872 case clang::X86::BI__builtin_ia32_vprotbi:
11873 case clang::X86::BI__builtin_ia32_vprotdi:
11874 case clang::X86::BI__builtin_ia32_vprotqi:
11875 case clang::X86::BI__builtin_ia32_vprotwi:
11876 case clang::X86::BI__builtin_ia32_prold128:
11877 case clang::X86::BI__builtin_ia32_prold256:
11878 case clang::X86::BI__builtin_ia32_prold512:
11879 case clang::X86::BI__builtin_ia32_prolq128:
11880 case clang::X86::BI__builtin_ia32_prolq256:
11881 case clang::X86::BI__builtin_ia32_prolq512:
11882 return EvaluateBinOpExpr(
11883 [](const APSInt &LHS, const APSInt &RHS) { return LHS.rotl(RHS); });
11884
11885 case clang::X86::BI__builtin_ia32_prord128:
11886 case clang::X86::BI__builtin_ia32_prord256:
11887 case clang::X86::BI__builtin_ia32_prord512:
11888 case clang::X86::BI__builtin_ia32_prorq128:
11889 case clang::X86::BI__builtin_ia32_prorq256:
11890 case clang::X86::BI__builtin_ia32_prorq512:
11891 return EvaluateBinOpExpr(
11892 [](const APSInt &LHS, const APSInt &RHS) { return LHS.rotr(RHS); });
11893
11894 case Builtin::BI__builtin_elementwise_max:
11895 case Builtin::BI__builtin_elementwise_min: {
11896 APValue SourceLHS, SourceRHS;
11897 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
11898 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
11899 return false;
11900
11901 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
11902
11903 if (!DestEltTy->isIntegerType())
11904 return false;
11905
11906 unsigned SourceLen = SourceLHS.getVectorLength();
11907 SmallVector<APValue, 4> ResultElements;
11908 ResultElements.reserve(SourceLen);
11909
11910 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
11911 APSInt LHS = SourceLHS.getVectorElt(EltNum).getInt();
11912 APSInt RHS = SourceRHS.getVectorElt(EltNum).getInt();
11913 switch (E->getBuiltinCallee()) {
11914 case Builtin::BI__builtin_elementwise_max:
11915 ResultElements.push_back(
11916 APValue(APSInt(std::max(LHS, RHS),
11917 DestEltTy->isUnsignedIntegerOrEnumerationType())));
11918 break;
11919 case Builtin::BI__builtin_elementwise_min:
11920 ResultElements.push_back(
11921 APValue(APSInt(std::min(LHS, RHS),
11922 DestEltTy->isUnsignedIntegerOrEnumerationType())));
11923 break;
11924 }
11925 }
11926
11927 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
11928 }
11929 case X86::BI__builtin_ia32_vpshldd128:
11930 case X86::BI__builtin_ia32_vpshldd256:
11931 case X86::BI__builtin_ia32_vpshldd512:
11932 case X86::BI__builtin_ia32_vpshldq128:
11933 case X86::BI__builtin_ia32_vpshldq256:
11934 case X86::BI__builtin_ia32_vpshldq512:
11935 case X86::BI__builtin_ia32_vpshldw128:
11936 case X86::BI__builtin_ia32_vpshldw256:
11937 case X86::BI__builtin_ia32_vpshldw512: {
11938 APValue SourceHi, SourceLo, SourceAmt;
11939 if (!EvaluateAsRValue(Info, E->getArg(0), SourceHi) ||
11940 !EvaluateAsRValue(Info, E->getArg(1), SourceLo) ||
11941 !EvaluateAsRValue(Info, E->getArg(2), SourceAmt))
11942 return false;
11943
11944 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
11945 unsigned SourceLen = SourceHi.getVectorLength();
11946 SmallVector<APValue, 32> ResultElements;
11947 ResultElements.reserve(SourceLen);
11948
11949 APInt Amt = SourceAmt.getInt();
11950 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
11951 APInt Hi = SourceHi.getVectorElt(EltNum).getInt();
11952 APInt Lo = SourceLo.getVectorElt(EltNum).getInt();
11953 APInt R = llvm::APIntOps::fshl(Hi, Lo, Amt);
11954 ResultElements.push_back(
11956 }
11957
11958 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
11959 }
11960 case X86::BI__builtin_ia32_vpshrdd128:
11961 case X86::BI__builtin_ia32_vpshrdd256:
11962 case X86::BI__builtin_ia32_vpshrdd512:
11963 case X86::BI__builtin_ia32_vpshrdq128:
11964 case X86::BI__builtin_ia32_vpshrdq256:
11965 case X86::BI__builtin_ia32_vpshrdq512:
11966 case X86::BI__builtin_ia32_vpshrdw128:
11967 case X86::BI__builtin_ia32_vpshrdw256:
11968 case X86::BI__builtin_ia32_vpshrdw512: {
11969 // NOTE: Reversed Hi/Lo operands.
11970 APValue SourceHi, SourceLo, SourceAmt;
11971 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLo) ||
11972 !EvaluateAsRValue(Info, E->getArg(1), SourceHi) ||
11973 !EvaluateAsRValue(Info, E->getArg(2), SourceAmt))
11974 return false;
11975
11976 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
11977 unsigned SourceLen = SourceHi.getVectorLength();
11978 SmallVector<APValue, 32> ResultElements;
11979 ResultElements.reserve(SourceLen);
11980
11981 APInt Amt = SourceAmt.getInt();
11982 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
11983 APInt Hi = SourceHi.getVectorElt(EltNum).getInt();
11984 APInt Lo = SourceLo.getVectorElt(EltNum).getInt();
11985 APInt R = llvm::APIntOps::fshr(Hi, Lo, Amt);
11986 ResultElements.push_back(
11988 }
11989
11990 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
11991 }
11992 case X86::BI__builtin_ia32_blendpd:
11993 case X86::BI__builtin_ia32_blendpd256:
11994 case X86::BI__builtin_ia32_blendps:
11995 case X86::BI__builtin_ia32_blendps256:
11996 case X86::BI__builtin_ia32_pblendw128:
11997 case X86::BI__builtin_ia32_pblendw256:
11998 case X86::BI__builtin_ia32_pblendd128:
11999 case X86::BI__builtin_ia32_pblendd256: {
12000 APValue SourceF, SourceT, SourceC;
12001 if (!EvaluateAsRValue(Info, E->getArg(0), SourceF) ||
12002 !EvaluateAsRValue(Info, E->getArg(1), SourceT) ||
12003 !EvaluateAsRValue(Info, E->getArg(2), SourceC))
12004 return false;
12005
12006 const APInt &C = SourceC.getInt();
12007 unsigned SourceLen = SourceF.getVectorLength();
12008 SmallVector<APValue, 32> ResultElements;
12009 ResultElements.reserve(SourceLen);
12010 for (unsigned EltNum = 0; EltNum != SourceLen; ++EltNum) {
12011 const APValue &F = SourceF.getVectorElt(EltNum);
12012 const APValue &T = SourceT.getVectorElt(EltNum);
12013 ResultElements.push_back(C[EltNum % 8] ? T : F);
12014 }
12015
12016 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12017 }
12018
12019 case X86::BI__builtin_ia32_blendvpd:
12020 case X86::BI__builtin_ia32_blendvpd256:
12021 case X86::BI__builtin_ia32_blendvps:
12022 case X86::BI__builtin_ia32_blendvps256:
12023 case X86::BI__builtin_ia32_pblendvb128:
12024 case X86::BI__builtin_ia32_pblendvb256: {
12025 // SSE blendv by mask signbit: "Result = C[] < 0 ? T[] : F[]".
12026 APValue SourceF, SourceT, SourceC;
12027 if (!EvaluateAsRValue(Info, E->getArg(0), SourceF) ||
12028 !EvaluateAsRValue(Info, E->getArg(1), SourceT) ||
12029 !EvaluateAsRValue(Info, E->getArg(2), SourceC))
12030 return false;
12031
12032 unsigned SourceLen = SourceF.getVectorLength();
12033 SmallVector<APValue, 32> ResultElements;
12034 ResultElements.reserve(SourceLen);
12035
12036 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12037 const APValue &F = SourceF.getVectorElt(EltNum);
12038 const APValue &T = SourceT.getVectorElt(EltNum);
12039 const APValue &C = SourceC.getVectorElt(EltNum);
12040 APInt M = C.isInt() ? (APInt)C.getInt() : C.getFloat().bitcastToAPInt();
12041 ResultElements.push_back(M.isNegative() ? T : F);
12042 }
12043
12044 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12045 }
12046 case X86::BI__builtin_ia32_selectb_128:
12047 case X86::BI__builtin_ia32_selectb_256:
12048 case X86::BI__builtin_ia32_selectb_512:
12049 case X86::BI__builtin_ia32_selectw_128:
12050 case X86::BI__builtin_ia32_selectw_256:
12051 case X86::BI__builtin_ia32_selectw_512:
12052 case X86::BI__builtin_ia32_selectd_128:
12053 case X86::BI__builtin_ia32_selectd_256:
12054 case X86::BI__builtin_ia32_selectd_512:
12055 case X86::BI__builtin_ia32_selectq_128:
12056 case X86::BI__builtin_ia32_selectq_256:
12057 case X86::BI__builtin_ia32_selectq_512:
12058 case X86::BI__builtin_ia32_selectph_128:
12059 case X86::BI__builtin_ia32_selectph_256:
12060 case X86::BI__builtin_ia32_selectph_512:
12061 case X86::BI__builtin_ia32_selectpbf_128:
12062 case X86::BI__builtin_ia32_selectpbf_256:
12063 case X86::BI__builtin_ia32_selectpbf_512:
12064 case X86::BI__builtin_ia32_selectps_128:
12065 case X86::BI__builtin_ia32_selectps_256:
12066 case X86::BI__builtin_ia32_selectps_512:
12067 case X86::BI__builtin_ia32_selectpd_128:
12068 case X86::BI__builtin_ia32_selectpd_256:
12069 case X86::BI__builtin_ia32_selectpd_512: {
12070 // AVX512 predicated move: "Result = Mask[] ? LHS[] : RHS[]".
12071 APValue SourceMask, SourceLHS, SourceRHS;
12072 if (!EvaluateAsRValue(Info, E->getArg(0), SourceMask) ||
12073 !EvaluateAsRValue(Info, E->getArg(1), SourceLHS) ||
12074 !EvaluateAsRValue(Info, E->getArg(2), SourceRHS))
12075 return false;
12076
12077 APSInt Mask = SourceMask.getInt();
12078 unsigned SourceLen = SourceLHS.getVectorLength();
12079 SmallVector<APValue, 4> ResultElements;
12080 ResultElements.reserve(SourceLen);
12081
12082 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12083 const APValue &LHS = SourceLHS.getVectorElt(EltNum);
12084 const APValue &RHS = SourceRHS.getVectorElt(EltNum);
12085 ResultElements.push_back(Mask[EltNum] ? LHS : RHS);
12086 }
12087
12088 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12089 }
12090 case Builtin::BI__builtin_elementwise_clzg:
12091 case Builtin::BI__builtin_elementwise_ctzg: {
12092 APValue SourceLHS;
12093 std::optional<APValue> Fallback;
12094 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS))
12095 return false;
12096 if (E->getNumArgs() > 1) {
12097 APValue FallbackTmp;
12098 if (!EvaluateAsRValue(Info, E->getArg(1), FallbackTmp))
12099 return false;
12100 Fallback = FallbackTmp;
12101 }
12102
12103 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
12104 unsigned SourceLen = SourceLHS.getVectorLength();
12105 SmallVector<APValue, 4> ResultElements;
12106 ResultElements.reserve(SourceLen);
12107
12108 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12109 APSInt LHS = SourceLHS.getVectorElt(EltNum).getInt();
12110 if (!LHS) {
12111 // Without a fallback, a zero element is undefined
12112 if (!Fallback) {
12113 Info.FFDiag(E, diag::note_constexpr_countzeroes_zero)
12114 << /*IsTrailing=*/(E->getBuiltinCallee() ==
12115 Builtin::BI__builtin_elementwise_ctzg);
12116 return false;
12117 }
12118 ResultElements.push_back(Fallback->getVectorElt(EltNum));
12119 continue;
12120 }
12121 switch (E->getBuiltinCallee()) {
12122 case Builtin::BI__builtin_elementwise_clzg:
12123 ResultElements.push_back(APValue(
12124 APSInt(APInt(Info.Ctx.getIntWidth(DestEltTy), LHS.countl_zero()),
12125 DestEltTy->isUnsignedIntegerOrEnumerationType())));
12126 break;
12127 case Builtin::BI__builtin_elementwise_ctzg:
12128 ResultElements.push_back(APValue(
12129 APSInt(APInt(Info.Ctx.getIntWidth(DestEltTy), LHS.countr_zero()),
12130 DestEltTy->isUnsignedIntegerOrEnumerationType())));
12131 break;
12132 }
12133 }
12134
12135 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12136 }
12137
12138 case Builtin::BI__builtin_elementwise_fma: {
12139 APValue SourceX, SourceY, SourceZ;
12140 if (!EvaluateAsRValue(Info, E->getArg(0), SourceX) ||
12141 !EvaluateAsRValue(Info, E->getArg(1), SourceY) ||
12142 !EvaluateAsRValue(Info, E->getArg(2), SourceZ))
12143 return false;
12144
12145 unsigned SourceLen = SourceX.getVectorLength();
12146 SmallVector<APValue> ResultElements;
12147 ResultElements.reserve(SourceLen);
12148 llvm::RoundingMode RM = getActiveRoundingMode(getEvalInfo(), E);
12149 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12150 const APFloat &X = SourceX.getVectorElt(EltNum).getFloat();
12151 const APFloat &Y = SourceY.getVectorElt(EltNum).getFloat();
12152 const APFloat &Z = SourceZ.getVectorElt(EltNum).getFloat();
12153 APFloat Result(X);
12154 (void)Result.fusedMultiplyAdd(Y, Z, RM);
12155 ResultElements.push_back(APValue(Result));
12156 }
12157 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12158 }
12159
12160 case Builtin::BI__builtin_elementwise_fshl:
12161 case Builtin::BI__builtin_elementwise_fshr: {
12162 APValue SourceHi, SourceLo, SourceShift;
12163 if (!EvaluateAsRValue(Info, E->getArg(0), SourceHi) ||
12164 !EvaluateAsRValue(Info, E->getArg(1), SourceLo) ||
12165 !EvaluateAsRValue(Info, E->getArg(2), SourceShift))
12166 return false;
12167
12168 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
12169 if (!DestEltTy->isIntegerType())
12170 return false;
12171
12172 unsigned SourceLen = SourceHi.getVectorLength();
12173 SmallVector<APValue> ResultElements;
12174 ResultElements.reserve(SourceLen);
12175 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12176 const APSInt &Hi = SourceHi.getVectorElt(EltNum).getInt();
12177 const APSInt &Lo = SourceLo.getVectorElt(EltNum).getInt();
12178 const APSInt &Shift = SourceShift.getVectorElt(EltNum).getInt();
12179 switch (E->getBuiltinCallee()) {
12180 case Builtin::BI__builtin_elementwise_fshl:
12181 ResultElements.push_back(APValue(
12182 APSInt(llvm::APIntOps::fshl(Hi, Lo, Shift), Hi.isUnsigned())));
12183 break;
12184 case Builtin::BI__builtin_elementwise_fshr:
12185 ResultElements.push_back(APValue(
12186 APSInt(llvm::APIntOps::fshr(Hi, Lo, Shift), Hi.isUnsigned())));
12187 break;
12188 }
12189 }
12190
12191 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12192 }
12193
12194 case X86::BI__builtin_ia32_insertf32x4_256:
12195 case X86::BI__builtin_ia32_inserti32x4_256:
12196 case X86::BI__builtin_ia32_insertf64x2_256:
12197 case X86::BI__builtin_ia32_inserti64x2_256:
12198 case X86::BI__builtin_ia32_insertf32x4:
12199 case X86::BI__builtin_ia32_inserti32x4:
12200 case X86::BI__builtin_ia32_insertf64x2_512:
12201 case X86::BI__builtin_ia32_inserti64x2_512:
12202 case X86::BI__builtin_ia32_insertf32x8:
12203 case X86::BI__builtin_ia32_inserti32x8:
12204 case X86::BI__builtin_ia32_insertf64x4:
12205 case X86::BI__builtin_ia32_inserti64x4:
12206 case X86::BI__builtin_ia32_vinsertf128_ps256:
12207 case X86::BI__builtin_ia32_vinsertf128_pd256:
12208 case X86::BI__builtin_ia32_vinsertf128_si256:
12209 case X86::BI__builtin_ia32_insert128i256: {
12210 APValue SourceDst, SourceSub;
12211 if (!EvaluateAsRValue(Info, E->getArg(0), SourceDst) ||
12212 !EvaluateAsRValue(Info, E->getArg(1), SourceSub))
12213 return false;
12214
12215 APSInt Imm;
12216 if (!EvaluateInteger(E->getArg(2), Imm, Info))
12217 return false;
12218
12219 assert(SourceDst.isVector() && SourceSub.isVector());
12220 unsigned DstLen = SourceDst.getVectorLength();
12221 unsigned SubLen = SourceSub.getVectorLength();
12222 assert(SubLen != 0 && DstLen != 0 && (DstLen % SubLen) == 0);
12223 unsigned NumLanes = DstLen / SubLen;
12224 unsigned LaneIdx = (Imm.getZExtValue() % NumLanes) * SubLen;
12225
12226 SmallVector<APValue, 16> ResultElements;
12227 ResultElements.reserve(DstLen);
12228
12229 for (unsigned EltNum = 0; EltNum < DstLen; ++EltNum) {
12230 if (EltNum >= LaneIdx && EltNum < LaneIdx + SubLen)
12231 ResultElements.push_back(SourceSub.getVectorElt(EltNum - LaneIdx));
12232 else
12233 ResultElements.push_back(SourceDst.getVectorElt(EltNum));
12234 }
12235
12236 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12237 }
12238 }
12239}
12240
12241bool VectorExprEvaluator::VisitConvertVectorExpr(const ConvertVectorExpr *E) {
12242 APValue Source;
12243 QualType SourceVecType = E->getSrcExpr()->getType();
12244 if (!EvaluateAsRValue(Info, E->getSrcExpr(), Source))
12245 return false;
12246
12247 QualType DestTy = E->getType()->castAs<VectorType>()->getElementType();
12248 QualType SourceTy = SourceVecType->castAs<VectorType>()->getElementType();
12249
12250 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
12251
12252 auto SourceLen = Source.getVectorLength();
12253 SmallVector<APValue, 4> ResultElements;
12254 ResultElements.reserve(SourceLen);
12255 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12256 APValue Elt;
12257 if (!handleVectorElementCast(Info, FPO, E, SourceTy, DestTy,
12258 Source.getVectorElt(EltNum), Elt))
12259 return false;
12260 ResultElements.push_back(std::move(Elt));
12261 }
12262
12263 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12264}
12265
12266static bool handleVectorShuffle(EvalInfo &Info, const ShuffleVectorExpr *E,
12267 QualType ElemType, APValue const &VecVal1,
12268 APValue const &VecVal2, unsigned EltNum,
12269 APValue &Result) {
12270 unsigned const TotalElementsInInputVector1 = VecVal1.getVectorLength();
12271 unsigned const TotalElementsInInputVector2 = VecVal2.getVectorLength();
12272
12273 APSInt IndexVal = E->getShuffleMaskIdx(EltNum);
12274 int64_t index = IndexVal.getExtValue();
12275 // The spec says that -1 should be treated as undef for optimizations,
12276 // but in constexpr we'd have to produce an APValue::Indeterminate,
12277 // which is prohibited from being a top-level constant value. Emit a
12278 // diagnostic instead.
12279 if (index == -1) {
12280 Info.FFDiag(
12281 E, diag::err_shufflevector_minus_one_is_undefined_behavior_constexpr)
12282 << EltNum;
12283 return false;
12284 }
12285
12286 if (index < 0 ||
12287 index >= TotalElementsInInputVector1 + TotalElementsInInputVector2)
12288 llvm_unreachable("Out of bounds shuffle index");
12289
12290 if (index >= TotalElementsInInputVector1)
12291 Result = VecVal2.getVectorElt(index - TotalElementsInInputVector1);
12292 else
12293 Result = VecVal1.getVectorElt(index);
12294 return true;
12295}
12296
12297bool VectorExprEvaluator::VisitShuffleVectorExpr(const ShuffleVectorExpr *E) {
12298 // FIXME: Unary shuffle with mask not currently supported.
12299 if (E->getNumSubExprs() == 2)
12300 return Error(E);
12301 APValue VecVal1;
12302 const Expr *Vec1 = E->getExpr(0);
12303 if (!EvaluateAsRValue(Info, Vec1, VecVal1))
12304 return false;
12305 APValue VecVal2;
12306 const Expr *Vec2 = E->getExpr(1);
12307 if (!EvaluateAsRValue(Info, Vec2, VecVal2))
12308 return false;
12309
12310 VectorType const *DestVecTy = E->getType()->castAs<VectorType>();
12311 QualType DestElTy = DestVecTy->getElementType();
12312
12313 auto TotalElementsInOutputVector = DestVecTy->getNumElements();
12314
12315 SmallVector<APValue, 4> ResultElements;
12316 ResultElements.reserve(TotalElementsInOutputVector);
12317 for (unsigned EltNum = 0; EltNum < TotalElementsInOutputVector; ++EltNum) {
12318 APValue Elt;
12319 if (!handleVectorShuffle(Info, E, DestElTy, VecVal1, VecVal2, EltNum, Elt))
12320 return false;
12321 ResultElements.push_back(std::move(Elt));
12322 }
12323
12324 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12325}
12326
12327//===----------------------------------------------------------------------===//
12328// Array Evaluation
12329//===----------------------------------------------------------------------===//
12330
12331namespace {
12332 class ArrayExprEvaluator
12333 : public ExprEvaluatorBase<ArrayExprEvaluator> {
12334 const LValue &This;
12335 APValue &Result;
12336 public:
12337
12338 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
12339 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
12340
12341 bool Success(const APValue &V, const Expr *E) {
12342 assert(V.isArray() && "expected array");
12343 Result = V;
12344 return true;
12345 }
12346
12347 bool ZeroInitialization(const Expr *E) {
12348 const ConstantArrayType *CAT =
12349 Info.Ctx.getAsConstantArrayType(E->getType());
12350 if (!CAT) {
12351 if (E->getType()->isIncompleteArrayType()) {
12352 // We can be asked to zero-initialize a flexible array member; this
12353 // is represented as an ImplicitValueInitExpr of incomplete array
12354 // type. In this case, the array has zero elements.
12355 Result = APValue(APValue::UninitArray(), 0, 0);
12356 return true;
12357 }
12358 // FIXME: We could handle VLAs here.
12359 return Error(E);
12360 }
12361
12362 Result = APValue(APValue::UninitArray(), 0, CAT->getZExtSize());
12363 if (!Result.hasArrayFiller())
12364 return true;
12365
12366 // Zero-initialize all elements.
12367 LValue Subobject = This;
12368 Subobject.addArray(Info, E, CAT);
12369 ImplicitValueInitExpr VIE(CAT->getElementType());
12370 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
12371 }
12372
12373 bool VisitCallExpr(const CallExpr *E) {
12374 return handleCallExpr(E, Result, &This);
12375 }
12376 bool VisitInitListExpr(const InitListExpr *E,
12377 QualType AllocType = QualType());
12378 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
12379 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
12380 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
12381 const LValue &Subobject,
12382 APValue *Value, QualType Type);
12383 bool VisitStringLiteral(const StringLiteral *E,
12384 QualType AllocType = QualType()) {
12385 expandStringLiteral(Info, E, Result, AllocType);
12386 return true;
12387 }
12388 bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E);
12389 bool VisitCXXParenListOrInitListExpr(const Expr *ExprToVisit,
12390 ArrayRef<Expr *> Args,
12391 const Expr *ArrayFiller,
12392 QualType AllocType = QualType());
12393 };
12394} // end anonymous namespace
12395
12396static bool EvaluateArray(const Expr *E, const LValue &This,
12397 APValue &Result, EvalInfo &Info) {
12398 assert(!E->isValueDependent());
12399 assert(E->isPRValue() && E->getType()->isArrayType() &&
12400 "not an array prvalue");
12401 return ArrayExprEvaluator(Info, This, Result).Visit(E);
12402}
12403
12404static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
12405 APValue &Result, const InitListExpr *ILE,
12406 QualType AllocType) {
12407 assert(!ILE->isValueDependent());
12408 assert(ILE->isPRValue() && ILE->getType()->isArrayType() &&
12409 "not an array prvalue");
12410 return ArrayExprEvaluator(Info, This, Result)
12411 .VisitInitListExpr(ILE, AllocType);
12412}
12413
12414static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
12415 APValue &Result,
12416 const CXXConstructExpr *CCE,
12417 QualType AllocType) {
12418 assert(!CCE->isValueDependent());
12419 assert(CCE->isPRValue() && CCE->getType()->isArrayType() &&
12420 "not an array prvalue");
12421 return ArrayExprEvaluator(Info, This, Result)
12422 .VisitCXXConstructExpr(CCE, This, &Result, AllocType);
12423}
12424
12425// Return true iff the given array filler may depend on the element index.
12426static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
12427 // For now, just allow non-class value-initialization and initialization
12428 // lists comprised of them.
12429 if (isa<ImplicitValueInitExpr>(FillerExpr))
12430 return false;
12431 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
12432 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
12433 if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
12434 return true;
12435 }
12436
12437 if (ILE->hasArrayFiller() &&
12438 MaybeElementDependentArrayFiller(ILE->getArrayFiller()))
12439 return true;
12440
12441 return false;
12442 }
12443 return true;
12444}
12445
12446bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E,
12447 QualType AllocType) {
12448 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
12449 AllocType.isNull() ? E->getType() : AllocType);
12450 if (!CAT)
12451 return Error(E);
12452
12453 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
12454 // an appropriately-typed string literal enclosed in braces.
12455 if (E->isStringLiteralInit()) {
12456 auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParenImpCasts());
12457 // FIXME: Support ObjCEncodeExpr here once we support it in
12458 // ArrayExprEvaluator generally.
12459 if (!SL)
12460 return Error(E);
12461 return VisitStringLiteral(SL, AllocType);
12462 }
12463 // Any other transparent list init will need proper handling of the
12464 // AllocType; we can't just recurse to the inner initializer.
12465 assert(!E->isTransparent() &&
12466 "transparent array list initialization is not string literal init?");
12467
12468 return VisitCXXParenListOrInitListExpr(E, E->inits(), E->getArrayFiller(),
12469 AllocType);
12470}
12471
12472bool ArrayExprEvaluator::VisitCXXParenListOrInitListExpr(
12473 const Expr *ExprToVisit, ArrayRef<Expr *> Args, const Expr *ArrayFiller,
12474 QualType AllocType) {
12475 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
12476 AllocType.isNull() ? ExprToVisit->getType() : AllocType);
12477
12478 bool Success = true;
12479
12480 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
12481 "zero-initialized array shouldn't have any initialized elts");
12482 APValue Filler;
12483 if (Result.isArray() && Result.hasArrayFiller())
12484 Filler = Result.getArrayFiller();
12485
12486 unsigned NumEltsToInit = Args.size();
12487 unsigned NumElts = CAT->getZExtSize();
12488
12489 // If the initializer might depend on the array index, run it for each
12490 // array element.
12491 if (NumEltsToInit != NumElts &&
12492 MaybeElementDependentArrayFiller(ArrayFiller)) {
12493 NumEltsToInit = NumElts;
12494 } else {
12495 for (auto *Init : Args) {
12496 if (auto *EmbedS = dyn_cast<EmbedExpr>(Init->IgnoreParenImpCasts()))
12497 NumEltsToInit += EmbedS->getDataElementCount() - 1;
12498 }
12499 if (NumEltsToInit > NumElts)
12500 NumEltsToInit = NumElts;
12501 }
12502
12503 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
12504 << NumEltsToInit << ".\n");
12505
12506 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
12507
12508 // If the array was previously zero-initialized, preserve the
12509 // zero-initialized values.
12510 if (Filler.hasValue()) {
12511 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
12512 Result.getArrayInitializedElt(I) = Filler;
12513 if (Result.hasArrayFiller())
12514 Result.getArrayFiller() = Filler;
12515 }
12516
12517 LValue Subobject = This;
12518 Subobject.addArray(Info, ExprToVisit, CAT);
12519 auto Eval = [&](const Expr *Init, unsigned ArrayIndex) {
12520 if (Init->isValueDependent())
12521 return EvaluateDependentExpr(Init, Info);
12522
12523 if (!EvaluateInPlace(Result.getArrayInitializedElt(ArrayIndex), Info,
12524 Subobject, Init) ||
12525 !HandleLValueArrayAdjustment(Info, Init, Subobject,
12526 CAT->getElementType(), 1)) {
12527 if (!Info.noteFailure())
12528 return false;
12529 Success = false;
12530 }
12531 return true;
12532 };
12533 unsigned ArrayIndex = 0;
12534 QualType DestTy = CAT->getElementType();
12535 APSInt Value(Info.Ctx.getTypeSize(DestTy), DestTy->isUnsignedIntegerType());
12536 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
12537 const Expr *Init = Index < Args.size() ? Args[Index] : ArrayFiller;
12538 if (ArrayIndex >= NumEltsToInit)
12539 break;
12540 if (auto *EmbedS = dyn_cast<EmbedExpr>(Init->IgnoreParenImpCasts())) {
12541 StringLiteral *SL = EmbedS->getDataStringLiteral();
12542 for (unsigned I = EmbedS->getStartingElementPos(),
12543 N = EmbedS->getDataElementCount();
12544 I != EmbedS->getStartingElementPos() + N; ++I) {
12545 Value = SL->getCodeUnit(I);
12546 if (DestTy->isIntegerType()) {
12547 Result.getArrayInitializedElt(ArrayIndex) = APValue(Value);
12548 } else {
12549 assert(DestTy->isFloatingType() && "unexpected type");
12550 const FPOptions FPO =
12551 Init->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
12552 APFloat FValue(0.0);
12553 if (!HandleIntToFloatCast(Info, Init, FPO, EmbedS->getType(), Value,
12554 DestTy, FValue))
12555 return false;
12556 Result.getArrayInitializedElt(ArrayIndex) = APValue(FValue);
12557 }
12558 ArrayIndex++;
12559 }
12560 } else {
12561 if (!Eval(Init, ArrayIndex))
12562 return false;
12563 ++ArrayIndex;
12564 }
12565 }
12566
12567 if (!Result.hasArrayFiller())
12568 return Success;
12569
12570 // If we get here, we have a trivial filler, which we can just evaluate
12571 // once and splat over the rest of the array elements.
12572 assert(ArrayFiller && "no array filler for incomplete init list");
12573 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
12574 ArrayFiller) &&
12575 Success;
12576}
12577
12578bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
12579 LValue CommonLV;
12580 if (E->getCommonExpr() &&
12581 !Evaluate(Info.CurrentCall->createTemporary(
12582 E->getCommonExpr(),
12583 getStorageType(Info.Ctx, E->getCommonExpr()),
12584 ScopeKind::FullExpression, CommonLV),
12585 Info, E->getCommonExpr()->getSourceExpr()))
12586 return false;
12587
12589
12590 uint64_t Elements = CAT->getZExtSize();
12591 Result = APValue(APValue::UninitArray(), Elements, Elements);
12592
12593 LValue Subobject = This;
12594 Subobject.addArray(Info, E, CAT);
12595
12596 bool Success = true;
12597 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
12598 // C++ [class.temporary]/5
12599 // There are four contexts in which temporaries are destroyed at a different
12600 // point than the end of the full-expression. [...] The second context is
12601 // when a copy constructor is called to copy an element of an array while
12602 // the entire array is copied [...]. In either case, if the constructor has
12603 // one or more default arguments, the destruction of every temporary created
12604 // in a default argument is sequenced before the construction of the next
12605 // array element, if any.
12606 FullExpressionRAII Scope(Info);
12607
12608 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
12609 Info, Subobject, E->getSubExpr()) ||
12610 !HandleLValueArrayAdjustment(Info, E, Subobject,
12611 CAT->getElementType(), 1)) {
12612 if (!Info.noteFailure())
12613 return false;
12614 Success = false;
12615 }
12616
12617 // Make sure we run the destructors too.
12618 Scope.destroy();
12619 }
12620
12621 return Success;
12622}
12623
12624bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
12625 return VisitCXXConstructExpr(E, This, &Result, E->getType());
12626}
12627
12628bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
12629 const LValue &Subobject,
12630 APValue *Value,
12631 QualType Type) {
12632 bool HadZeroInit = Value->hasValue();
12633
12634 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
12635 unsigned FinalSize = CAT->getZExtSize();
12636
12637 // Preserve the array filler if we had prior zero-initialization.
12638 APValue Filler =
12639 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
12640 : APValue();
12641
12642 *Value = APValue(APValue::UninitArray(), 0, FinalSize);
12643 if (FinalSize == 0)
12644 return true;
12645
12646 bool HasTrivialConstructor = CheckTrivialDefaultConstructor(
12647 Info, E->getExprLoc(), E->getConstructor(),
12649 LValue ArrayElt = Subobject;
12650 ArrayElt.addArray(Info, E, CAT);
12651 // We do the whole initialization in two passes, first for just one element,
12652 // then for the whole array. It's possible we may find out we can't do const
12653 // init in the first pass, in which case we avoid allocating a potentially
12654 // large array. We don't do more passes because expanding array requires
12655 // copying the data, which is wasteful.
12656 for (const unsigned N : {1u, FinalSize}) {
12657 unsigned OldElts = Value->getArrayInitializedElts();
12658 if (OldElts == N)
12659 break;
12660
12661 // Expand the array to appropriate size.
12662 APValue NewValue(APValue::UninitArray(), N, FinalSize);
12663 for (unsigned I = 0; I < OldElts; ++I)
12664 NewValue.getArrayInitializedElt(I).swap(
12665 Value->getArrayInitializedElt(I));
12666 Value->swap(NewValue);
12667
12668 if (HadZeroInit)
12669 for (unsigned I = OldElts; I < N; ++I)
12670 Value->getArrayInitializedElt(I) = Filler;
12671
12672 if (HasTrivialConstructor && N == FinalSize && FinalSize != 1) {
12673 // If we have a trivial constructor, only evaluate it once and copy
12674 // the result into all the array elements.
12675 APValue &FirstResult = Value->getArrayInitializedElt(0);
12676 for (unsigned I = OldElts; I < FinalSize; ++I)
12677 Value->getArrayInitializedElt(I) = FirstResult;
12678 } else {
12679 for (unsigned I = OldElts; I < N; ++I) {
12680 if (!VisitCXXConstructExpr(E, ArrayElt,
12681 &Value->getArrayInitializedElt(I),
12682 CAT->getElementType()) ||
12683 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
12684 CAT->getElementType(), 1))
12685 return false;
12686 // When checking for const initilization any diagnostic is considered
12687 // an error.
12688 if (Info.EvalStatus.Diag && !Info.EvalStatus.Diag->empty() &&
12689 !Info.keepEvaluatingAfterFailure())
12690 return false;
12691 }
12692 }
12693 }
12694
12695 return true;
12696 }
12697
12698 if (!Type->isRecordType())
12699 return Error(E);
12700
12701 return RecordExprEvaluator(Info, Subobject, *Value)
12702 .VisitCXXConstructExpr(E, Type);
12703}
12704
12705bool ArrayExprEvaluator::VisitCXXParenListInitExpr(
12706 const CXXParenListInitExpr *E) {
12707 assert(E->getType()->isConstantArrayType() &&
12708 "Expression result is not a constant array type");
12709
12710 return VisitCXXParenListOrInitListExpr(E, E->getInitExprs(),
12711 E->getArrayFiller());
12712}
12713
12714//===----------------------------------------------------------------------===//
12715// Integer Evaluation
12716//
12717// As a GNU extension, we support casting pointers to sufficiently-wide integer
12718// types and back in constant folding. Integer values are thus represented
12719// either as an integer-valued APValue, or as an lvalue-valued APValue.
12720//===----------------------------------------------------------------------===//
12721
12722namespace {
12723class IntExprEvaluator
12724 : public ExprEvaluatorBase<IntExprEvaluator> {
12725 APValue &Result;
12726public:
12727 IntExprEvaluator(EvalInfo &info, APValue &result)
12728 : ExprEvaluatorBaseTy(info), Result(result) {}
12729
12730 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
12731 assert(E->getType()->isIntegralOrEnumerationType() &&
12732 "Invalid evaluation result.");
12733 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
12734 "Invalid evaluation result.");
12735 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
12736 "Invalid evaluation result.");
12737 Result = APValue(SI);
12738 return true;
12739 }
12740 bool Success(const llvm::APSInt &SI, const Expr *E) {
12741 return Success(SI, E, Result);
12742 }
12743
12744 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
12745 assert(E->getType()->isIntegralOrEnumerationType() &&
12746 "Invalid evaluation result.");
12747 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
12748 "Invalid evaluation result.");
12749 Result = APValue(APSInt(I));
12750 Result.getInt().setIsUnsigned(
12752 return true;
12753 }
12754 bool Success(const llvm::APInt &I, const Expr *E) {
12755 return Success(I, E, Result);
12756 }
12757
12758 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
12759 assert(E->getType()->isIntegralOrEnumerationType() &&
12760 "Invalid evaluation result.");
12761 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
12762 return true;
12763 }
12764 bool Success(uint64_t Value, const Expr *E) {
12765 return Success(Value, E, Result);
12766 }
12767
12768 bool Success(CharUnits Size, const Expr *E) {
12769 return Success(Size.getQuantity(), E);
12770 }
12771
12772 bool Success(const APValue &V, const Expr *E) {
12773 // C++23 [expr.const]p8 If we have a variable that is unknown reference or
12774 // pointer allow further evaluation of the value.
12775 if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate() ||
12776 V.allowConstexprUnknown()) {
12777 Result = V;
12778 return true;
12779 }
12780 return Success(V.getInt(), E);
12781 }
12782
12783 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
12784
12785 friend std::optional<bool> EvaluateBuiltinIsWithinLifetime(IntExprEvaluator &,
12786 const CallExpr *);
12787
12788 //===--------------------------------------------------------------------===//
12789 // Visitor Methods
12790 //===--------------------------------------------------------------------===//
12791
12792 bool VisitIntegerLiteral(const IntegerLiteral *E) {
12793 return Success(E->getValue(), E);
12794 }
12795 bool VisitCharacterLiteral(const CharacterLiteral *E) {
12796 return Success(E->getValue(), E);
12797 }
12798
12799 bool CheckReferencedDecl(const Expr *E, const Decl *D);
12800 bool VisitDeclRefExpr(const DeclRefExpr *E) {
12801 if (CheckReferencedDecl(E, E->getDecl()))
12802 return true;
12803
12804 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
12805 }
12806 bool VisitMemberExpr(const MemberExpr *E) {
12807 if (CheckReferencedDecl(E, E->getMemberDecl())) {
12808 VisitIgnoredBaseExpression(E->getBase());
12809 return true;
12810 }
12811
12812 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
12813 }
12814
12815 bool VisitCallExpr(const CallExpr *E);
12816 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
12817 bool VisitBinaryOperator(const BinaryOperator *E);
12818 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
12819 bool VisitUnaryOperator(const UnaryOperator *E);
12820
12821 bool VisitCastExpr(const CastExpr* E);
12822 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
12823
12824 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
12825 return Success(E->getValue(), E);
12826 }
12827
12828 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
12829 return Success(E->getValue(), E);
12830 }
12831
12832 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
12833 if (Info.ArrayInitIndex == uint64_t(-1)) {
12834 // We were asked to evaluate this subexpression independent of the
12835 // enclosing ArrayInitLoopExpr. We can't do that.
12836 Info.FFDiag(E);
12837 return false;
12838 }
12839 return Success(Info.ArrayInitIndex, E);
12840 }
12841
12842 // Note, GNU defines __null as an integer, not a pointer.
12843 bool VisitGNUNullExpr(const GNUNullExpr *E) {
12844 return ZeroInitialization(E);
12845 }
12846
12847 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
12848 if (E->isStoredAsBoolean())
12849 return Success(E->getBoolValue(), E);
12850 if (E->getAPValue().isAbsent())
12851 return false;
12852 assert(E->getAPValue().isInt() && "APValue type not supported");
12853 return Success(E->getAPValue().getInt(), E);
12854 }
12855
12856 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
12857 return Success(E->getValue(), E);
12858 }
12859
12860 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
12861 return Success(E->getValue(), E);
12862 }
12863
12864 bool VisitOpenACCAsteriskSizeExpr(const OpenACCAsteriskSizeExpr *E) {
12865 // This should not be evaluated during constant expr evaluation, as it
12866 // should always be in an unevaluated context (the args list of a 'gang' or
12867 // 'tile' clause).
12868 return Error(E);
12869 }
12870
12871 bool VisitUnaryReal(const UnaryOperator *E);
12872 bool VisitUnaryImag(const UnaryOperator *E);
12873
12874 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
12875 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
12876 bool VisitSourceLocExpr(const SourceLocExpr *E);
12877 bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E);
12878 bool VisitRequiresExpr(const RequiresExpr *E);
12879 // FIXME: Missing: array subscript of vector, member of vector
12880};
12881
12882class FixedPointExprEvaluator
12883 : public ExprEvaluatorBase<FixedPointExprEvaluator> {
12884 APValue &Result;
12885
12886 public:
12887 FixedPointExprEvaluator(EvalInfo &info, APValue &result)
12888 : ExprEvaluatorBaseTy(info), Result(result) {}
12889
12890 bool Success(const llvm::APInt &I, const Expr *E) {
12891 return Success(
12892 APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
12893 }
12894
12895 bool Success(uint64_t Value, const Expr *E) {
12896 return Success(
12897 APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
12898 }
12899
12900 bool Success(const APValue &V, const Expr *E) {
12901 return Success(V.getFixedPoint(), E);
12902 }
12903
12904 bool Success(const APFixedPoint &V, const Expr *E) {
12905 assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
12906 assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
12907 "Invalid evaluation result.");
12908 Result = APValue(V);
12909 return true;
12910 }
12911
12912 bool ZeroInitialization(const Expr *E) {
12913 return Success(0, E);
12914 }
12915
12916 //===--------------------------------------------------------------------===//
12917 // Visitor Methods
12918 //===--------------------------------------------------------------------===//
12919
12920 bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
12921 return Success(E->getValue(), E);
12922 }
12923
12924 bool VisitCastExpr(const CastExpr *E);
12925 bool VisitUnaryOperator(const UnaryOperator *E);
12926 bool VisitBinaryOperator(const BinaryOperator *E);
12927};
12928} // end anonymous namespace
12929
12930/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
12931/// produce either the integer value or a pointer.
12932///
12933/// GCC has a heinous extension which folds casts between pointer types and
12934/// pointer-sized integral types. We support this by allowing the evaluation of
12935/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
12936/// Some simple arithmetic on such values is supported (they are treated much
12937/// like char*).
12938static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
12939 EvalInfo &Info) {
12940 assert(!E->isValueDependent());
12941 assert(E->isPRValue() && E->getType()->isIntegralOrEnumerationType());
12942 return IntExprEvaluator(Info, Result).Visit(E);
12943}
12944
12945static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
12946 assert(!E->isValueDependent());
12947 APValue Val;
12948 if (!EvaluateIntegerOrLValue(E, Val, Info))
12949 return false;
12950 if (!Val.isInt()) {
12951 // FIXME: It would be better to produce the diagnostic for casting
12952 // a pointer to an integer.
12953 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
12954 return false;
12955 }
12956 Result = Val.getInt();
12957 return true;
12958}
12959
12960bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
12962 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
12963 return Success(Evaluated, E);
12964}
12965
12966static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
12967 EvalInfo &Info) {
12968 assert(!E->isValueDependent());
12969 if (E->getType()->isFixedPointType()) {
12970 APValue Val;
12971 if (!FixedPointExprEvaluator(Info, Val).Visit(E))
12972 return false;
12973 if (!Val.isFixedPoint())
12974 return false;
12975
12976 Result = Val.getFixedPoint();
12977 return true;
12978 }
12979 return false;
12980}
12981
12982static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
12983 EvalInfo &Info) {
12984 assert(!E->isValueDependent());
12985 if (E->getType()->isIntegerType()) {
12986 auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
12987 APSInt Val;
12988 if (!EvaluateInteger(E, Val, Info))
12989 return false;
12990 Result = APFixedPoint(Val, FXSema);
12991 return true;
12992 } else if (E->getType()->isFixedPointType()) {
12993 return EvaluateFixedPoint(E, Result, Info);
12994 }
12995 return false;
12996}
12997
12998/// Check whether the given declaration can be directly converted to an integral
12999/// rvalue. If not, no diagnostic is produced; there are other things we can
13000/// try.
13001bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
13002 // Enums are integer constant exprs.
13003 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
13004 // Check for signedness/width mismatches between E type and ECD value.
13005 bool SameSign = (ECD->getInitVal().isSigned()
13007 bool SameWidth = (ECD->getInitVal().getBitWidth()
13008 == Info.Ctx.getIntWidth(E->getType()));
13009 if (SameSign && SameWidth)
13010 return Success(ECD->getInitVal(), E);
13011 else {
13012 // Get rid of mismatch (otherwise Success assertions will fail)
13013 // by computing a new value matching the type of E.
13014 llvm::APSInt Val = ECD->getInitVal();
13015 if (!SameSign)
13016 Val.setIsSigned(!ECD->getInitVal().isSigned());
13017 if (!SameWidth)
13018 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
13019 return Success(Val, E);
13020 }
13021 }
13022 return false;
13023}
13024
13025/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
13026/// as GCC.
13028 const LangOptions &LangOpts) {
13029 assert(!T->isDependentType() && "unexpected dependent type");
13030
13031 QualType CanTy = T.getCanonicalType();
13032
13033 switch (CanTy->getTypeClass()) {
13034#define TYPE(ID, BASE)
13035#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
13036#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
13037#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
13038#include "clang/AST/TypeNodes.inc"
13039 case Type::Auto:
13040 case Type::DeducedTemplateSpecialization:
13041 llvm_unreachable("unexpected non-canonical or dependent type");
13042
13043 case Type::Builtin:
13044 switch (cast<BuiltinType>(CanTy)->getKind()) {
13045#define BUILTIN_TYPE(ID, SINGLETON_ID)
13046#define SIGNED_TYPE(ID, SINGLETON_ID) \
13047 case BuiltinType::ID: return GCCTypeClass::Integer;
13048#define FLOATING_TYPE(ID, SINGLETON_ID) \
13049 case BuiltinType::ID: return GCCTypeClass::RealFloat;
13050#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
13051 case BuiltinType::ID: break;
13052#include "clang/AST/BuiltinTypes.def"
13053 case BuiltinType::Void:
13054 return GCCTypeClass::Void;
13055
13056 case BuiltinType::Bool:
13057 return GCCTypeClass::Bool;
13058
13059 case BuiltinType::Char_U:
13060 case BuiltinType::UChar:
13061 case BuiltinType::WChar_U:
13062 case BuiltinType::Char8:
13063 case BuiltinType::Char16:
13064 case BuiltinType::Char32:
13065 case BuiltinType::UShort:
13066 case BuiltinType::UInt:
13067 case BuiltinType::ULong:
13068 case BuiltinType::ULongLong:
13069 case BuiltinType::UInt128:
13070 return GCCTypeClass::Integer;
13071
13072 case BuiltinType::UShortAccum:
13073 case BuiltinType::UAccum:
13074 case BuiltinType::ULongAccum:
13075 case BuiltinType::UShortFract:
13076 case BuiltinType::UFract:
13077 case BuiltinType::ULongFract:
13078 case BuiltinType::SatUShortAccum:
13079 case BuiltinType::SatUAccum:
13080 case BuiltinType::SatULongAccum:
13081 case BuiltinType::SatUShortFract:
13082 case BuiltinType::SatUFract:
13083 case BuiltinType::SatULongFract:
13084 return GCCTypeClass::None;
13085
13086 case BuiltinType::NullPtr:
13087
13088 case BuiltinType::ObjCId:
13089 case BuiltinType::ObjCClass:
13090 case BuiltinType::ObjCSel:
13091#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
13092 case BuiltinType::Id:
13093#include "clang/Basic/OpenCLImageTypes.def"
13094#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
13095 case BuiltinType::Id:
13096#include "clang/Basic/OpenCLExtensionTypes.def"
13097 case BuiltinType::OCLSampler:
13098 case BuiltinType::OCLEvent:
13099 case BuiltinType::OCLClkEvent:
13100 case BuiltinType::OCLQueue:
13101 case BuiltinType::OCLReserveID:
13102#define SVE_TYPE(Name, Id, SingletonId) \
13103 case BuiltinType::Id:
13104#include "clang/Basic/AArch64ACLETypes.def"
13105#define PPC_VECTOR_TYPE(Name, Id, Size) \
13106 case BuiltinType::Id:
13107#include "clang/Basic/PPCTypes.def"
13108#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
13109#include "clang/Basic/RISCVVTypes.def"
13110#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
13111#include "clang/Basic/WebAssemblyReferenceTypes.def"
13112#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
13113#include "clang/Basic/AMDGPUTypes.def"
13114#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
13115#include "clang/Basic/HLSLIntangibleTypes.def"
13116 return GCCTypeClass::None;
13117
13118 case BuiltinType::Dependent:
13119 llvm_unreachable("unexpected dependent type");
13120 };
13121 llvm_unreachable("unexpected placeholder type");
13122
13123 case Type::Enum:
13124 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
13125
13126 case Type::Pointer:
13127 case Type::ConstantArray:
13128 case Type::VariableArray:
13129 case Type::IncompleteArray:
13130 case Type::FunctionNoProto:
13131 case Type::FunctionProto:
13132 case Type::ArrayParameter:
13133 return GCCTypeClass::Pointer;
13134
13135 case Type::MemberPointer:
13136 return CanTy->isMemberDataPointerType()
13139
13140 case Type::Complex:
13141 return GCCTypeClass::Complex;
13142
13143 case Type::Record:
13144 return CanTy->isUnionType() ? GCCTypeClass::Union
13146
13147 case Type::Atomic:
13148 // GCC classifies _Atomic T the same as T.
13150 CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
13151
13152 case Type::Vector:
13153 case Type::ExtVector:
13154 return GCCTypeClass::Vector;
13155
13156 case Type::BlockPointer:
13157 case Type::ConstantMatrix:
13158 case Type::ObjCObject:
13159 case Type::ObjCInterface:
13160 case Type::ObjCObjectPointer:
13161 case Type::Pipe:
13162 case Type::HLSLAttributedResource:
13163 case Type::HLSLInlineSpirv:
13164 // Classify all other types that don't fit into the regular
13165 // classification the same way.
13166 return GCCTypeClass::None;
13167
13168 case Type::BitInt:
13169 return GCCTypeClass::BitInt;
13170
13171 case Type::LValueReference:
13172 case Type::RValueReference:
13173 llvm_unreachable("invalid type for expression");
13174 }
13175
13176 llvm_unreachable("unexpected type class");
13177}
13178
13179/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
13180/// as GCC.
13181static GCCTypeClass
13183 // If no argument was supplied, default to None. This isn't
13184 // ideal, however it is what gcc does.
13185 if (E->getNumArgs() == 0)
13186 return GCCTypeClass::None;
13187
13188 // FIXME: Bizarrely, GCC treats a call with more than one argument as not
13189 // being an ICE, but still folds it to a constant using the type of the first
13190 // argument.
13191 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
13192}
13193
13194/// EvaluateBuiltinConstantPForLValue - Determine the result of
13195/// __builtin_constant_p when applied to the given pointer.
13196///
13197/// A pointer is only "constant" if it is null (or a pointer cast to integer)
13198/// or it points to the first character of a string literal.
13201 if (Base.isNull()) {
13202 // A null base is acceptable.
13203 return true;
13204 } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
13205 if (!isa<StringLiteral>(E))
13206 return false;
13207 return LV.getLValueOffset().isZero();
13208 } else if (Base.is<TypeInfoLValue>()) {
13209 // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
13210 // evaluate to true.
13211 return true;
13212 } else {
13213 // Any other base is not constant enough for GCC.
13214 return false;
13215 }
13216}
13217
13218/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
13219/// GCC as we can manage.
13220static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
13221 // This evaluation is not permitted to have side-effects, so evaluate it in
13222 // a speculative evaluation context.
13223 SpeculativeEvaluationRAII SpeculativeEval(Info);
13224
13225 // Constant-folding is always enabled for the operand of __builtin_constant_p
13226 // (even when the enclosing evaluation context otherwise requires a strict
13227 // language-specific constant expression).
13228 FoldConstant Fold(Info, true);
13229
13230 QualType ArgType = Arg->getType();
13231
13232 // __builtin_constant_p always has one operand. The rules which gcc follows
13233 // are not precisely documented, but are as follows:
13234 //
13235 // - If the operand is of integral, floating, complex or enumeration type,
13236 // and can be folded to a known value of that type, it returns 1.
13237 // - If the operand can be folded to a pointer to the first character
13238 // of a string literal (or such a pointer cast to an integral type)
13239 // or to a null pointer or an integer cast to a pointer, it returns 1.
13240 //
13241 // Otherwise, it returns 0.
13242 //
13243 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
13244 // its support for this did not work prior to GCC 9 and is not yet well
13245 // understood.
13246 if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
13247 ArgType->isAnyComplexType() || ArgType->isPointerType() ||
13248 ArgType->isNullPtrType()) {
13249 APValue V;
13250 if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) {
13251 Fold.keepDiagnostics();
13252 return false;
13253 }
13254
13255 // For a pointer (possibly cast to integer), there are special rules.
13256 if (V.getKind() == APValue::LValue)
13258
13259 // Otherwise, any constant value is good enough.
13260 return V.hasValue();
13261 }
13262
13263 // Anything else isn't considered to be sufficiently constant.
13264 return false;
13265}
13266
13267/// Retrieves the "underlying object type" of the given expression,
13268/// as used by __builtin_object_size.
13270 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
13271 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
13272 return VD->getType();
13273 } else if (const Expr *E = B.dyn_cast<const Expr*>()) {
13275 return E->getType();
13276 } else if (B.is<TypeInfoLValue>()) {
13277 return B.getTypeInfoType();
13278 } else if (B.is<DynamicAllocLValue>()) {
13279 return B.getDynamicAllocType();
13280 }
13281
13282 return QualType();
13283}
13284
13285/// A more selective version of E->IgnoreParenCasts for
13286/// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
13287/// to change the type of E.
13288/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
13289///
13290/// Always returns an RValue with a pointer representation.
13291static const Expr *ignorePointerCastsAndParens(const Expr *E) {
13292 assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
13293
13294 const Expr *NoParens = E->IgnoreParens();
13295 const auto *Cast = dyn_cast<CastExpr>(NoParens);
13296 if (Cast == nullptr)
13297 return NoParens;
13298
13299 // We only conservatively allow a few kinds of casts, because this code is
13300 // inherently a simple solution that seeks to support the common case.
13301 auto CastKind = Cast->getCastKind();
13302 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
13303 CastKind != CK_AddressSpaceConversion)
13304 return NoParens;
13305
13306 const auto *SubExpr = Cast->getSubExpr();
13307 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isPRValue())
13308 return NoParens;
13309 return ignorePointerCastsAndParens(SubExpr);
13310}
13311
13312/// Checks to see if the given LValue's Designator is at the end of the LValue's
13313/// record layout. e.g.
13314/// struct { struct { int a, b; } fst, snd; } obj;
13315/// obj.fst // no
13316/// obj.snd // yes
13317/// obj.fst.a // no
13318/// obj.fst.b // no
13319/// obj.snd.a // no
13320/// obj.snd.b // yes
13321///
13322/// Please note: this function is specialized for how __builtin_object_size
13323/// views "objects".
13324///
13325/// If this encounters an invalid RecordDecl or otherwise cannot determine the
13326/// correct result, it will always return true.
13327static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
13328 assert(!LVal.Designator.Invalid);
13329
13330 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD) {
13331 const RecordDecl *Parent = FD->getParent();
13332 if (Parent->isInvalidDecl() || Parent->isUnion())
13333 return true;
13334 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
13335 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
13336 };
13337
13338 auto &Base = LVal.getLValueBase();
13339 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
13340 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
13341 if (!IsLastOrInvalidFieldDecl(FD))
13342 return false;
13343 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
13344 for (auto *FD : IFD->chain()) {
13345 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD)))
13346 return false;
13347 }
13348 }
13349 }
13350
13351 unsigned I = 0;
13352 QualType BaseType = getType(Base);
13353 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
13354 // If we don't know the array bound, conservatively assume we're looking at
13355 // the final array element.
13356 ++I;
13357 if (BaseType->isIncompleteArrayType())
13358 BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
13359 else
13360 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
13361 }
13362
13363 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
13364 const auto &Entry = LVal.Designator.Entries[I];
13365 if (BaseType->isArrayType()) {
13366 // Because __builtin_object_size treats arrays as objects, we can ignore
13367 // the index iff this is the last array in the Designator.
13368 if (I + 1 == E)
13369 return true;
13370 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
13371 uint64_t Index = Entry.getAsArrayIndex();
13372 if (Index + 1 != CAT->getZExtSize())
13373 return false;
13374 BaseType = CAT->getElementType();
13375 } else if (BaseType->isAnyComplexType()) {
13376 const auto *CT = BaseType->castAs<ComplexType>();
13377 uint64_t Index = Entry.getAsArrayIndex();
13378 if (Index != 1)
13379 return false;
13380 BaseType = CT->getElementType();
13381 } else if (auto *FD = getAsField(Entry)) {
13382 if (!IsLastOrInvalidFieldDecl(FD))
13383 return false;
13384 BaseType = FD->getType();
13385 } else {
13386 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
13387 return false;
13388 }
13389 }
13390 return true;
13391}
13392
13393/// Tests to see if the LValue has a user-specified designator (that isn't
13394/// necessarily valid). Note that this always returns 'true' if the LValue has
13395/// an unsized array as its first designator entry, because there's currently no
13396/// way to tell if the user typed *foo or foo[0].
13397static bool refersToCompleteObject(const LValue &LVal) {
13398 if (LVal.Designator.Invalid)
13399 return false;
13400
13401 if (!LVal.Designator.Entries.empty())
13402 return LVal.Designator.isMostDerivedAnUnsizedArray();
13403
13404 if (!LVal.InvalidBase)
13405 return true;
13406
13407 // If `E` is a MemberExpr, then the first part of the designator is hiding in
13408 // the LValueBase.
13409 const auto *E = LVal.Base.dyn_cast<const Expr *>();
13410 return !E || !isa<MemberExpr>(E);
13411}
13412
13413/// Attempts to detect a user writing into a piece of memory that's impossible
13414/// to figure out the size of by just using types.
13415static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
13416 const SubobjectDesignator &Designator = LVal.Designator;
13417 // Notes:
13418 // - Users can only write off of the end when we have an invalid base. Invalid
13419 // bases imply we don't know where the memory came from.
13420 // - We used to be a bit more aggressive here; we'd only be conservative if
13421 // the array at the end was flexible, or if it had 0 or 1 elements. This
13422 // broke some common standard library extensions (PR30346), but was
13423 // otherwise seemingly fine. It may be useful to reintroduce this behavior
13424 // with some sort of list. OTOH, it seems that GCC is always
13425 // conservative with the last element in structs (if it's an array), so our
13426 // current behavior is more compatible than an explicit list approach would
13427 // be.
13428 auto isFlexibleArrayMember = [&] {
13430 FAMKind StrictFlexArraysLevel =
13431 Ctx.getLangOpts().getStrictFlexArraysLevel();
13432
13433 if (Designator.isMostDerivedAnUnsizedArray())
13434 return true;
13435
13436 if (StrictFlexArraysLevel == FAMKind::Default)
13437 return true;
13438
13439 if (Designator.getMostDerivedArraySize() == 0 &&
13440 StrictFlexArraysLevel != FAMKind::IncompleteOnly)
13441 return true;
13442
13443 if (Designator.getMostDerivedArraySize() == 1 &&
13444 StrictFlexArraysLevel == FAMKind::OneZeroOrIncomplete)
13445 return true;
13446
13447 return false;
13448 };
13449
13450 return LVal.InvalidBase &&
13451 Designator.Entries.size() == Designator.MostDerivedPathLength &&
13452 Designator.MostDerivedIsArrayElement && isFlexibleArrayMember() &&
13453 isDesignatorAtObjectEnd(Ctx, LVal);
13454}
13455
13456/// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
13457/// Fails if the conversion would cause loss of precision.
13458static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
13459 CharUnits &Result) {
13460 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
13461 if (Int.ugt(CharUnitsMax))
13462 return false;
13463 Result = CharUnits::fromQuantity(Int.getZExtValue());
13464 return true;
13465}
13466
13467/// If we're evaluating the object size of an instance of a struct that
13468/// contains a flexible array member, add the size of the initializer.
13469static void addFlexibleArrayMemberInitSize(EvalInfo &Info, const QualType &T,
13470 const LValue &LV, CharUnits &Size) {
13471 if (!T.isNull() && T->isStructureType() &&
13472 T->castAsRecordDecl()->hasFlexibleArrayMember())
13473 if (const auto *V = LV.getLValueBase().dyn_cast<const ValueDecl *>())
13474 if (const auto *VD = dyn_cast<VarDecl>(V))
13475 if (VD->hasInit())
13476 Size += VD->getFlexibleArrayInitChars(Info.Ctx);
13477}
13478
13479/// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
13480/// determine how many bytes exist from the beginning of the object to either
13481/// the end of the current subobject, or the end of the object itself, depending
13482/// on what the LValue looks like + the value of Type.
13483///
13484/// If this returns false, the value of Result is undefined.
13485static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
13486 unsigned Type, const LValue &LVal,
13487 CharUnits &EndOffset) {
13488 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
13489
13490 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
13491 if (Ty.isNull())
13492 return false;
13493
13494 Ty = Ty.getNonReferenceType();
13495
13496 if (Ty->isIncompleteType() || Ty->isFunctionType())
13497 return false;
13498
13499 return HandleSizeof(Info, ExprLoc, Ty, Result);
13500 };
13501
13502 // We want to evaluate the size of the entire object. This is a valid fallback
13503 // for when Type=1 and the designator is invalid, because we're asked for an
13504 // upper-bound.
13505 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
13506 // Type=3 wants a lower bound, so we can't fall back to this.
13507 if (Type == 3 && !DetermineForCompleteObject)
13508 return false;
13509
13510 llvm::APInt APEndOffset;
13511 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
13512 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
13513 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
13514
13515 if (LVal.InvalidBase)
13516 return false;
13517
13518 QualType BaseTy = getObjectType(LVal.getLValueBase());
13519 const bool Ret = CheckedHandleSizeof(BaseTy, EndOffset);
13520 addFlexibleArrayMemberInitSize(Info, BaseTy, LVal, EndOffset);
13521 return Ret;
13522 }
13523
13524 // We want to evaluate the size of a subobject.
13525 const SubobjectDesignator &Designator = LVal.Designator;
13526
13527 // The following is a moderately common idiom in C:
13528 //
13529 // struct Foo { int a; char c[1]; };
13530 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
13531 // strcpy(&F->c[0], Bar);
13532 //
13533 // In order to not break too much legacy code, we need to support it.
13534 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
13535 // If we can resolve this to an alloc_size call, we can hand that back,
13536 // because we know for certain how many bytes there are to write to.
13537 llvm::APInt APEndOffset;
13538 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
13539 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
13540 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
13541
13542 // If we cannot determine the size of the initial allocation, then we can't
13543 // given an accurate upper-bound. However, we are still able to give
13544 // conservative lower-bounds for Type=3.
13545 if (Type == 1)
13546 return false;
13547 }
13548
13549 CharUnits BytesPerElem;
13550 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
13551 return false;
13552
13553 // According to the GCC documentation, we want the size of the subobject
13554 // denoted by the pointer. But that's not quite right -- what we actually
13555 // want is the size of the immediately-enclosing array, if there is one.
13556 int64_t ElemsRemaining;
13557 if (Designator.MostDerivedIsArrayElement &&
13558 Designator.Entries.size() == Designator.MostDerivedPathLength) {
13559 uint64_t ArraySize = Designator.getMostDerivedArraySize();
13560 uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
13561 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
13562 } else {
13563 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
13564 }
13565
13566 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
13567 return true;
13568}
13569
13570/// Tries to evaluate the __builtin_object_size for @p E. If successful,
13571/// returns true and stores the result in @p Size.
13572///
13573/// If @p WasError is non-null, this will report whether the failure to evaluate
13574/// is to be treated as an Error in IntExprEvaluator.
13575static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
13576 EvalInfo &Info, uint64_t &Size) {
13577 // Determine the denoted object.
13578 LValue LVal;
13579 {
13580 // The operand of __builtin_object_size is never evaluated for side-effects.
13581 // If there are any, but we can determine the pointed-to object anyway, then
13582 // ignore the side-effects.
13583 SpeculativeEvaluationRAII SpeculativeEval(Info);
13584 IgnoreSideEffectsRAII Fold(Info);
13585
13586 if (E->isGLValue()) {
13587 // It's possible for us to be given GLValues if we're called via
13588 // Expr::tryEvaluateObjectSize.
13589 APValue RVal;
13590 if (!EvaluateAsRValue(Info, E, RVal))
13591 return false;
13592 LVal.setFrom(Info.Ctx, RVal);
13593 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
13594 /*InvalidBaseOK=*/true))
13595 return false;
13596 }
13597
13598 // If we point to before the start of the object, there are no accessible
13599 // bytes.
13600 if (LVal.getLValueOffset().isNegative()) {
13601 Size = 0;
13602 return true;
13603 }
13604
13605 CharUnits EndOffset;
13606 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
13607 return false;
13608
13609 // If we've fallen outside of the end offset, just pretend there's nothing to
13610 // write to/read from.
13611 if (EndOffset <= LVal.getLValueOffset())
13612 Size = 0;
13613 else
13614 Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
13615 return true;
13616}
13617
13618bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
13619 if (!IsConstantEvaluatedBuiltinCall(E))
13620 return ExprEvaluatorBaseTy::VisitCallExpr(E);
13621 return VisitBuiltinCallExpr(E, E->getBuiltinCallee());
13622}
13623
13624static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info,
13625 APValue &Val, APSInt &Alignment) {
13626 QualType SrcTy = E->getArg(0)->getType();
13627 if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment))
13628 return false;
13629 // Even though we are evaluating integer expressions we could get a pointer
13630 // argument for the __builtin_is_aligned() case.
13631 if (SrcTy->isPointerType()) {
13632 LValue Ptr;
13633 if (!EvaluatePointer(E->getArg(0), Ptr, Info))
13634 return false;
13635 Ptr.moveInto(Val);
13636 } else if (!SrcTy->isIntegralOrEnumerationType()) {
13637 Info.FFDiag(E->getArg(0));
13638 return false;
13639 } else {
13640 APSInt SrcInt;
13641 if (!EvaluateInteger(E->getArg(0), SrcInt, Info))
13642 return false;
13643 assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() &&
13644 "Bit widths must be the same");
13645 Val = APValue(SrcInt);
13646 }
13647 assert(Val.hasValue());
13648 return true;
13649}
13650
13651bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
13652 unsigned BuiltinOp) {
13653
13654 auto HandleMaskBinOp =
13655 [&](llvm::function_ref<APSInt(const APSInt &, const APSInt &)> Fn)
13656 -> bool {
13657 APValue LHS, RHS;
13658 if (!Evaluate(LHS, Info, E->getArg(0)) ||
13659 !Evaluate(RHS, Info, E->getArg(1)))
13660 return false;
13661
13662 APSInt ResultInt = Fn(LHS.getInt(), RHS.getInt());
13663
13664 return Success(APValue(ResultInt), E);
13665 };
13666
13667 switch (BuiltinOp) {
13668 default:
13669 return false;
13670
13671 case Builtin::BI__builtin_dynamic_object_size:
13672 case Builtin::BI__builtin_object_size: {
13673 // The type was checked when we built the expression.
13674 unsigned Type =
13675 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
13676 assert(Type <= 3 && "unexpected type");
13677
13678 uint64_t Size;
13679 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
13680 return Success(Size, E);
13681
13682 if (E->getArg(0)->HasSideEffects(Info.Ctx))
13683 return Success((Type & 2) ? 0 : -1, E);
13684
13685 // Expression had no side effects, but we couldn't statically determine the
13686 // size of the referenced object.
13687 switch (Info.EvalMode) {
13688 case EvaluationMode::ConstantExpression:
13689 case EvaluationMode::ConstantFold:
13690 case EvaluationMode::IgnoreSideEffects:
13691 // Leave it to IR generation.
13692 return Error(E);
13693 case EvaluationMode::ConstantExpressionUnevaluated:
13694 // Reduce it to a constant now.
13695 return Success((Type & 2) ? 0 : -1, E);
13696 }
13697
13698 llvm_unreachable("unexpected EvalMode");
13699 }
13700
13701 case Builtin::BI__builtin_os_log_format_buffer_size: {
13702 analyze_os_log::OSLogBufferLayout Layout;
13703 analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
13704 return Success(Layout.size().getQuantity(), E);
13705 }
13706
13707 case Builtin::BI__builtin_is_aligned: {
13708 APValue Src;
13709 APSInt Alignment;
13710 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
13711 return false;
13712 if (Src.isLValue()) {
13713 // If we evaluated a pointer, check the minimum known alignment.
13714 LValue Ptr;
13715 Ptr.setFrom(Info.Ctx, Src);
13716 CharUnits BaseAlignment = getBaseAlignment(Info, Ptr);
13717 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset);
13718 // We can return true if the known alignment at the computed offset is
13719 // greater than the requested alignment.
13720 assert(PtrAlign.isPowerOfTwo());
13721 assert(Alignment.isPowerOf2());
13722 if (PtrAlign.getQuantity() >= Alignment)
13723 return Success(1, E);
13724 // If the alignment is not known to be sufficient, some cases could still
13725 // be aligned at run time. However, if the requested alignment is less or
13726 // equal to the base alignment and the offset is not aligned, we know that
13727 // the run-time value can never be aligned.
13728 if (BaseAlignment.getQuantity() >= Alignment &&
13729 PtrAlign.getQuantity() < Alignment)
13730 return Success(0, E);
13731 // Otherwise we can't infer whether the value is sufficiently aligned.
13732 // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N)
13733 // in cases where we can't fully evaluate the pointer.
13734 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute)
13735 << Alignment;
13736 return false;
13737 }
13738 assert(Src.isInt());
13739 return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E);
13740 }
13741 case Builtin::BI__builtin_align_up: {
13742 APValue Src;
13743 APSInt Alignment;
13744 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
13745 return false;
13746 if (!Src.isInt())
13747 return Error(E);
13748 APSInt AlignedVal =
13749 APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1),
13750 Src.getInt().isUnsigned());
13751 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
13752 return Success(AlignedVal, E);
13753 }
13754 case Builtin::BI__builtin_align_down: {
13755 APValue Src;
13756 APSInt Alignment;
13757 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
13758 return false;
13759 if (!Src.isInt())
13760 return Error(E);
13761 APSInt AlignedVal =
13762 APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned());
13763 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
13764 return Success(AlignedVal, E);
13765 }
13766
13767 case Builtin::BI__builtin_bitreverse8:
13768 case Builtin::BI__builtin_bitreverse16:
13769 case Builtin::BI__builtin_bitreverse32:
13770 case Builtin::BI__builtin_bitreverse64:
13771 case Builtin::BI__builtin_elementwise_bitreverse: {
13772 APSInt Val;
13773 if (!EvaluateInteger(E->getArg(0), Val, Info))
13774 return false;
13775
13776 return Success(Val.reverseBits(), E);
13777 }
13778
13779 case Builtin::BI__builtin_bswap16:
13780 case Builtin::BI__builtin_bswap32:
13781 case Builtin::BI__builtin_bswap64: {
13782 APSInt Val;
13783 if (!EvaluateInteger(E->getArg(0), Val, Info))
13784 return false;
13785
13786 return Success(Val.byteSwap(), E);
13787 }
13788
13789 case Builtin::BI__builtin_classify_type:
13790 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
13791
13792 case Builtin::BI__builtin_clrsb:
13793 case Builtin::BI__builtin_clrsbl:
13794 case Builtin::BI__builtin_clrsbll: {
13795 APSInt Val;
13796 if (!EvaluateInteger(E->getArg(0), Val, Info))
13797 return false;
13798
13799 return Success(Val.getBitWidth() - Val.getSignificantBits(), E);
13800 }
13801
13802 case Builtin::BI__builtin_clz:
13803 case Builtin::BI__builtin_clzl:
13804 case Builtin::BI__builtin_clzll:
13805 case Builtin::BI__builtin_clzs:
13806 case Builtin::BI__builtin_clzg:
13807 case Builtin::BI__builtin_elementwise_clzg:
13808 case Builtin::BI__lzcnt16: // Microsoft variants of count leading-zeroes
13809 case Builtin::BI__lzcnt:
13810 case Builtin::BI__lzcnt64: {
13811 APSInt Val;
13812 if (E->getArg(0)->getType()->isExtVectorBoolType()) {
13813 APValue Vec;
13814 if (!EvaluateVector(E->getArg(0), Vec, Info))
13815 return false;
13816 Val = ConvertBoolVectorToInt(Vec);
13817 } else if (!EvaluateInteger(E->getArg(0), Val, Info)) {
13818 return false;
13819 }
13820
13821 std::optional<APSInt> Fallback;
13822 if ((BuiltinOp == Builtin::BI__builtin_clzg ||
13823 BuiltinOp == Builtin::BI__builtin_elementwise_clzg) &&
13824 E->getNumArgs() > 1) {
13825 APSInt FallbackTemp;
13826 if (!EvaluateInteger(E->getArg(1), FallbackTemp, Info))
13827 return false;
13828 Fallback = FallbackTemp;
13829 }
13830
13831 if (!Val) {
13832 if (Fallback)
13833 return Success(*Fallback, E);
13834
13835 // When the argument is 0, the result of GCC builtins is undefined,
13836 // whereas for Microsoft intrinsics, the result is the bit-width of the
13837 // argument.
13838 bool ZeroIsUndefined = BuiltinOp != Builtin::BI__lzcnt16 &&
13839 BuiltinOp != Builtin::BI__lzcnt &&
13840 BuiltinOp != Builtin::BI__lzcnt64;
13841
13842 if (BuiltinOp == Builtin::BI__builtin_elementwise_clzg) {
13843 Info.FFDiag(E, diag::note_constexpr_countzeroes_zero)
13844 << /*IsTrailing=*/false;
13845 }
13846
13847 if (ZeroIsUndefined)
13848 return Error(E);
13849 }
13850
13851 return Success(Val.countl_zero(), E);
13852 }
13853
13854 case Builtin::BI__builtin_constant_p: {
13855 const Expr *Arg = E->getArg(0);
13856 if (EvaluateBuiltinConstantP(Info, Arg))
13857 return Success(true, E);
13858 if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
13859 // Outside a constant context, eagerly evaluate to false in the presence
13860 // of side-effects in order to avoid -Wunsequenced false-positives in
13861 // a branch on __builtin_constant_p(expr).
13862 return Success(false, E);
13863 }
13864 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
13865 return false;
13866 }
13867
13868 case Builtin::BI__noop:
13869 // __noop always evaluates successfully and returns 0.
13870 return Success(0, E);
13871
13872 case Builtin::BI__builtin_is_constant_evaluated: {
13873 const auto *Callee = Info.CurrentCall->getCallee();
13874 if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression &&
13875 (Info.CallStackDepth == 1 ||
13876 (Info.CallStackDepth == 2 && Callee->isInStdNamespace() &&
13877 Callee->getIdentifier() &&
13878 Callee->getIdentifier()->isStr("is_constant_evaluated")))) {
13879 // FIXME: Find a better way to avoid duplicated diagnostics.
13880 if (Info.EvalStatus.Diag)
13881 Info.report((Info.CallStackDepth == 1)
13882 ? E->getExprLoc()
13883 : Info.CurrentCall->getCallRange().getBegin(),
13884 diag::warn_is_constant_evaluated_always_true_constexpr)
13885 << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated"
13886 : "std::is_constant_evaluated");
13887 }
13888
13889 return Success(Info.InConstantContext, E);
13890 }
13891
13892 case Builtin::BI__builtin_is_within_lifetime:
13893 if (auto result = EvaluateBuiltinIsWithinLifetime(*this, E))
13894 return Success(*result, E);
13895 return false;
13896
13897 case Builtin::BI__builtin_ctz:
13898 case Builtin::BI__builtin_ctzl:
13899 case Builtin::BI__builtin_ctzll:
13900 case Builtin::BI__builtin_ctzs:
13901 case Builtin::BI__builtin_ctzg:
13902 case Builtin::BI__builtin_elementwise_ctzg: {
13903 APSInt Val;
13904 if (E->getArg(0)->getType()->isExtVectorBoolType()) {
13905 APValue Vec;
13906 if (!EvaluateVector(E->getArg(0), Vec, Info))
13907 return false;
13908 Val = ConvertBoolVectorToInt(Vec);
13909 } else if (!EvaluateInteger(E->getArg(0), Val, Info)) {
13910 return false;
13911 }
13912
13913 std::optional<APSInt> Fallback;
13914 if ((BuiltinOp == Builtin::BI__builtin_ctzg ||
13915 BuiltinOp == Builtin::BI__builtin_elementwise_ctzg) &&
13916 E->getNumArgs() > 1) {
13917 APSInt FallbackTemp;
13918 if (!EvaluateInteger(E->getArg(1), FallbackTemp, Info))
13919 return false;
13920 Fallback = FallbackTemp;
13921 }
13922
13923 if (!Val) {
13924 if (Fallback)
13925 return Success(*Fallback, E);
13926
13927 if (BuiltinOp == Builtin::BI__builtin_elementwise_ctzg) {
13928 Info.FFDiag(E, diag::note_constexpr_countzeroes_zero)
13929 << /*IsTrailing=*/true;
13930 }
13931 return Error(E);
13932 }
13933
13934 return Success(Val.countr_zero(), E);
13935 }
13936
13937 case Builtin::BI__builtin_eh_return_data_regno: {
13938 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
13939 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
13940 return Success(Operand, E);
13941 }
13942
13943 case Builtin::BI__builtin_elementwise_abs: {
13944 APSInt Val;
13945 if (!EvaluateInteger(E->getArg(0), Val, Info))
13946 return false;
13947
13948 return Success(Val.abs(), E);
13949 }
13950
13951 case Builtin::BI__builtin_expect:
13952 case Builtin::BI__builtin_expect_with_probability:
13953 return Visit(E->getArg(0));
13954
13955 case Builtin::BI__builtin_ptrauth_string_discriminator: {
13956 const auto *Literal =
13958 uint64_t Result = getPointerAuthStableSipHash(Literal->getString());
13959 return Success(Result, E);
13960 }
13961
13962 case Builtin::BI__builtin_ffs:
13963 case Builtin::BI__builtin_ffsl:
13964 case Builtin::BI__builtin_ffsll: {
13965 APSInt Val;
13966 if (!EvaluateInteger(E->getArg(0), Val, Info))
13967 return false;
13968
13969 unsigned N = Val.countr_zero();
13970 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
13971 }
13972
13973 case Builtin::BI__builtin_fpclassify: {
13974 APFloat Val(0.0);
13975 if (!EvaluateFloat(E->getArg(5), Val, Info))
13976 return false;
13977 unsigned Arg;
13978 switch (Val.getCategory()) {
13979 case APFloat::fcNaN: Arg = 0; break;
13980 case APFloat::fcInfinity: Arg = 1; break;
13981 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
13982 case APFloat::fcZero: Arg = 4; break;
13983 }
13984 return Visit(E->getArg(Arg));
13985 }
13986
13987 case Builtin::BI__builtin_isinf_sign: {
13988 APFloat Val(0.0);
13989 return EvaluateFloat(E->getArg(0), Val, Info) &&
13990 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
13991 }
13992
13993 case Builtin::BI__builtin_isinf: {
13994 APFloat Val(0.0);
13995 return EvaluateFloat(E->getArg(0), Val, Info) &&
13996 Success(Val.isInfinity() ? 1 : 0, E);
13997 }
13998
13999 case Builtin::BI__builtin_isfinite: {
14000 APFloat Val(0.0);
14001 return EvaluateFloat(E->getArg(0), Val, Info) &&
14002 Success(Val.isFinite() ? 1 : 0, E);
14003 }
14004
14005 case Builtin::BI__builtin_isnan: {
14006 APFloat Val(0.0);
14007 return EvaluateFloat(E->getArg(0), Val, Info) &&
14008 Success(Val.isNaN() ? 1 : 0, E);
14009 }
14010
14011 case Builtin::BI__builtin_isnormal: {
14012 APFloat Val(0.0);
14013 return EvaluateFloat(E->getArg(0), Val, Info) &&
14014 Success(Val.isNormal() ? 1 : 0, E);
14015 }
14016
14017 case Builtin::BI__builtin_issubnormal: {
14018 APFloat Val(0.0);
14019 return EvaluateFloat(E->getArg(0), Val, Info) &&
14020 Success(Val.isDenormal() ? 1 : 0, E);
14021 }
14022
14023 case Builtin::BI__builtin_iszero: {
14024 APFloat Val(0.0);
14025 return EvaluateFloat(E->getArg(0), Val, Info) &&
14026 Success(Val.isZero() ? 1 : 0, E);
14027 }
14028
14029 case Builtin::BI__builtin_signbit:
14030 case Builtin::BI__builtin_signbitf:
14031 case Builtin::BI__builtin_signbitl: {
14032 APFloat Val(0.0);
14033 return EvaluateFloat(E->getArg(0), Val, Info) &&
14034 Success(Val.isNegative() ? 1 : 0, E);
14035 }
14036
14037 case Builtin::BI__builtin_isgreater:
14038 case Builtin::BI__builtin_isgreaterequal:
14039 case Builtin::BI__builtin_isless:
14040 case Builtin::BI__builtin_islessequal:
14041 case Builtin::BI__builtin_islessgreater:
14042 case Builtin::BI__builtin_isunordered: {
14043 APFloat LHS(0.0);
14044 APFloat RHS(0.0);
14045 if (!EvaluateFloat(E->getArg(0), LHS, Info) ||
14046 !EvaluateFloat(E->getArg(1), RHS, Info))
14047 return false;
14048
14049 return Success(
14050 [&] {
14051 switch (BuiltinOp) {
14052 case Builtin::BI__builtin_isgreater:
14053 return LHS > RHS;
14054 case Builtin::BI__builtin_isgreaterequal:
14055 return LHS >= RHS;
14056 case Builtin::BI__builtin_isless:
14057 return LHS < RHS;
14058 case Builtin::BI__builtin_islessequal:
14059 return LHS <= RHS;
14060 case Builtin::BI__builtin_islessgreater: {
14061 APFloat::cmpResult cmp = LHS.compare(RHS);
14062 return cmp == APFloat::cmpResult::cmpLessThan ||
14063 cmp == APFloat::cmpResult::cmpGreaterThan;
14064 }
14065 case Builtin::BI__builtin_isunordered:
14066 return LHS.compare(RHS) == APFloat::cmpResult::cmpUnordered;
14067 default:
14068 llvm_unreachable("Unexpected builtin ID: Should be a floating "
14069 "point comparison function");
14070 }
14071 }()
14072 ? 1
14073 : 0,
14074 E);
14075 }
14076
14077 case Builtin::BI__builtin_issignaling: {
14078 APFloat Val(0.0);
14079 return EvaluateFloat(E->getArg(0), Val, Info) &&
14080 Success(Val.isSignaling() ? 1 : 0, E);
14081 }
14082
14083 case Builtin::BI__builtin_isfpclass: {
14084 APSInt MaskVal;
14085 if (!EvaluateInteger(E->getArg(1), MaskVal, Info))
14086 return false;
14087 unsigned Test = static_cast<llvm::FPClassTest>(MaskVal.getZExtValue());
14088 APFloat Val(0.0);
14089 return EvaluateFloat(E->getArg(0), Val, Info) &&
14090 Success((Val.classify() & Test) ? 1 : 0, E);
14091 }
14092
14093 case Builtin::BI__builtin_parity:
14094 case Builtin::BI__builtin_parityl:
14095 case Builtin::BI__builtin_parityll: {
14096 APSInt Val;
14097 if (!EvaluateInteger(E->getArg(0), Val, Info))
14098 return false;
14099
14100 return Success(Val.popcount() % 2, E);
14101 }
14102
14103 case Builtin::BI__builtin_abs:
14104 case Builtin::BI__builtin_labs:
14105 case Builtin::BI__builtin_llabs: {
14106 APSInt Val;
14107 if (!EvaluateInteger(E->getArg(0), Val, Info))
14108 return false;
14109 if (Val == APSInt(APInt::getSignedMinValue(Val.getBitWidth()),
14110 /*IsUnsigned=*/false))
14111 return false;
14112 if (Val.isNegative())
14113 Val.negate();
14114 return Success(Val, E);
14115 }
14116
14117 case Builtin::BI__builtin_popcount:
14118 case Builtin::BI__builtin_popcountl:
14119 case Builtin::BI__builtin_popcountll:
14120 case Builtin::BI__builtin_popcountg:
14121 case Builtin::BI__builtin_elementwise_popcount:
14122 case Builtin::BI__popcnt16: // Microsoft variants of popcount
14123 case Builtin::BI__popcnt:
14124 case Builtin::BI__popcnt64: {
14125 APSInt Val;
14126 if (E->getArg(0)->getType()->isExtVectorBoolType()) {
14127 APValue Vec;
14128 if (!EvaluateVector(E->getArg(0), Vec, Info))
14129 return false;
14130 Val = ConvertBoolVectorToInt(Vec);
14131 } else if (!EvaluateInteger(E->getArg(0), Val, Info)) {
14132 return false;
14133 }
14134
14135 return Success(Val.popcount(), E);
14136 }
14137
14138 case Builtin::BI__builtin_rotateleft8:
14139 case Builtin::BI__builtin_rotateleft16:
14140 case Builtin::BI__builtin_rotateleft32:
14141 case Builtin::BI__builtin_rotateleft64:
14142 case Builtin::BI_rotl8: // Microsoft variants of rotate right
14143 case Builtin::BI_rotl16:
14144 case Builtin::BI_rotl:
14145 case Builtin::BI_lrotl:
14146 case Builtin::BI_rotl64: {
14147 APSInt Val, Amt;
14148 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
14149 !EvaluateInteger(E->getArg(1), Amt, Info))
14150 return false;
14151
14152 return Success(Val.rotl(Amt.urem(Val.getBitWidth())), E);
14153 }
14154
14155 case Builtin::BI__builtin_rotateright8:
14156 case Builtin::BI__builtin_rotateright16:
14157 case Builtin::BI__builtin_rotateright32:
14158 case Builtin::BI__builtin_rotateright64:
14159 case Builtin::BI_rotr8: // Microsoft variants of rotate right
14160 case Builtin::BI_rotr16:
14161 case Builtin::BI_rotr:
14162 case Builtin::BI_lrotr:
14163 case Builtin::BI_rotr64: {
14164 APSInt Val, Amt;
14165 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
14166 !EvaluateInteger(E->getArg(1), Amt, Info))
14167 return false;
14168
14169 return Success(Val.rotr(Amt.urem(Val.getBitWidth())), E);
14170 }
14171
14172 case Builtin::BI__builtin_elementwise_add_sat: {
14173 APSInt LHS, RHS;
14174 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
14175 !EvaluateInteger(E->getArg(1), RHS, Info))
14176 return false;
14177
14178 APInt Result = LHS.isSigned() ? LHS.sadd_sat(RHS) : LHS.uadd_sat(RHS);
14179 return Success(APSInt(Result, !LHS.isSigned()), E);
14180 }
14181 case Builtin::BI__builtin_elementwise_sub_sat: {
14182 APSInt LHS, RHS;
14183 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
14184 !EvaluateInteger(E->getArg(1), RHS, Info))
14185 return false;
14186
14187 APInt Result = LHS.isSigned() ? LHS.ssub_sat(RHS) : LHS.usub_sat(RHS);
14188 return Success(APSInt(Result, !LHS.isSigned()), E);
14189 }
14190 case Builtin::BI__builtin_elementwise_max: {
14191 APSInt LHS, RHS;
14192 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
14193 !EvaluateInteger(E->getArg(1), RHS, Info))
14194 return false;
14195
14196 APInt Result = std::max(LHS, RHS);
14197 return Success(APSInt(Result, !LHS.isSigned()), E);
14198 }
14199 case Builtin::BI__builtin_elementwise_min: {
14200 APSInt LHS, RHS;
14201 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
14202 !EvaluateInteger(E->getArg(1), RHS, Info))
14203 return false;
14204
14205 APInt Result = std::min(LHS, RHS);
14206 return Success(APSInt(Result, !LHS.isSigned()), E);
14207 }
14208 case Builtin::BI__builtin_elementwise_fshl:
14209 case Builtin::BI__builtin_elementwise_fshr: {
14210 APSInt Hi, Lo, Shift;
14211 if (!EvaluateInteger(E->getArg(0), Hi, Info) ||
14212 !EvaluateInteger(E->getArg(1), Lo, Info) ||
14213 !EvaluateInteger(E->getArg(2), Shift, Info))
14214 return false;
14215
14216 switch (BuiltinOp) {
14217 case Builtin::BI__builtin_elementwise_fshl: {
14218 APSInt Result(llvm::APIntOps::fshl(Hi, Lo, Shift), Hi.isUnsigned());
14219 return Success(Result, E);
14220 }
14221 case Builtin::BI__builtin_elementwise_fshr: {
14222 APSInt Result(llvm::APIntOps::fshr(Hi, Lo, Shift), Hi.isUnsigned());
14223 return Success(Result, E);
14224 }
14225 }
14226 llvm_unreachable("Fully covered switch above");
14227 }
14228 case Builtin::BIstrlen:
14229 case Builtin::BIwcslen:
14230 // A call to strlen is not a constant expression.
14231 if (Info.getLangOpts().CPlusPlus11)
14232 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
14233 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
14234 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
14235 else
14236 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
14237 [[fallthrough]];
14238 case Builtin::BI__builtin_strlen:
14239 case Builtin::BI__builtin_wcslen: {
14240 // As an extension, we support __builtin_strlen() as a constant expression,
14241 // and support folding strlen() to a constant.
14242 uint64_t StrLen;
14243 if (EvaluateBuiltinStrLen(E->getArg(0), StrLen, Info))
14244 return Success(StrLen, E);
14245 return false;
14246 }
14247
14248 case Builtin::BIstrcmp:
14249 case Builtin::BIwcscmp:
14250 case Builtin::BIstrncmp:
14251 case Builtin::BIwcsncmp:
14252 case Builtin::BImemcmp:
14253 case Builtin::BIbcmp:
14254 case Builtin::BIwmemcmp:
14255 // A call to strlen is not a constant expression.
14256 if (Info.getLangOpts().CPlusPlus11)
14257 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
14258 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
14259 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
14260 else
14261 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
14262 [[fallthrough]];
14263 case Builtin::BI__builtin_strcmp:
14264 case Builtin::BI__builtin_wcscmp:
14265 case Builtin::BI__builtin_strncmp:
14266 case Builtin::BI__builtin_wcsncmp:
14267 case Builtin::BI__builtin_memcmp:
14268 case Builtin::BI__builtin_bcmp:
14269 case Builtin::BI__builtin_wmemcmp: {
14270 LValue String1, String2;
14271 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
14272 !EvaluatePointer(E->getArg(1), String2, Info))
14273 return false;
14274
14275 uint64_t MaxLength = uint64_t(-1);
14276 if (BuiltinOp != Builtin::BIstrcmp &&
14277 BuiltinOp != Builtin::BIwcscmp &&
14278 BuiltinOp != Builtin::BI__builtin_strcmp &&
14279 BuiltinOp != Builtin::BI__builtin_wcscmp) {
14280 APSInt N;
14281 if (!EvaluateInteger(E->getArg(2), N, Info))
14282 return false;
14283 MaxLength = N.getZExtValue();
14284 }
14285
14286 // Empty substrings compare equal by definition.
14287 if (MaxLength == 0u)
14288 return Success(0, E);
14289
14290 if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
14291 !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
14292 String1.Designator.Invalid || String2.Designator.Invalid)
14293 return false;
14294
14295 QualType CharTy1 = String1.Designator.getType(Info.Ctx);
14296 QualType CharTy2 = String2.Designator.getType(Info.Ctx);
14297
14298 bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
14299 BuiltinOp == Builtin::BIbcmp ||
14300 BuiltinOp == Builtin::BI__builtin_memcmp ||
14301 BuiltinOp == Builtin::BI__builtin_bcmp;
14302
14303 assert(IsRawByte ||
14304 (Info.Ctx.hasSameUnqualifiedType(
14305 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
14306 Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
14307
14308 // For memcmp, allow comparing any arrays of '[[un]signed] char' or
14309 // 'char8_t', but no other types.
14310 if (IsRawByte &&
14311 !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) {
14312 // FIXME: Consider using our bit_cast implementation to support this.
14313 Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported)
14314 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp) << CharTy1
14315 << CharTy2;
14316 return false;
14317 }
14318
14319 const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
14320 return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
14321 handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
14322 Char1.isInt() && Char2.isInt();
14323 };
14324 const auto &AdvanceElems = [&] {
14325 return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
14326 HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
14327 };
14328
14329 bool StopAtNull =
14330 (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
14331 BuiltinOp != Builtin::BIwmemcmp &&
14332 BuiltinOp != Builtin::BI__builtin_memcmp &&
14333 BuiltinOp != Builtin::BI__builtin_bcmp &&
14334 BuiltinOp != Builtin::BI__builtin_wmemcmp);
14335 bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
14336 BuiltinOp == Builtin::BIwcsncmp ||
14337 BuiltinOp == Builtin::BIwmemcmp ||
14338 BuiltinOp == Builtin::BI__builtin_wcscmp ||
14339 BuiltinOp == Builtin::BI__builtin_wcsncmp ||
14340 BuiltinOp == Builtin::BI__builtin_wmemcmp;
14341
14342 for (; MaxLength; --MaxLength) {
14343 APValue Char1, Char2;
14344 if (!ReadCurElems(Char1, Char2))
14345 return false;
14346 if (Char1.getInt().ne(Char2.getInt())) {
14347 if (IsWide) // wmemcmp compares with wchar_t signedness.
14348 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
14349 // memcmp always compares unsigned chars.
14350 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
14351 }
14352 if (StopAtNull && !Char1.getInt())
14353 return Success(0, E);
14354 assert(!(StopAtNull && !Char2.getInt()));
14355 if (!AdvanceElems())
14356 return false;
14357 }
14358 // We hit the strncmp / memcmp limit.
14359 return Success(0, E);
14360 }
14361
14362 case Builtin::BI__atomic_always_lock_free:
14363 case Builtin::BI__atomic_is_lock_free:
14364 case Builtin::BI__c11_atomic_is_lock_free: {
14365 APSInt SizeVal;
14366 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
14367 return false;
14368
14369 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
14370 // of two less than or equal to the maximum inline atomic width, we know it
14371 // is lock-free. If the size isn't a power of two, or greater than the
14372 // maximum alignment where we promote atomics, we know it is not lock-free
14373 // (at least not in the sense of atomic_is_lock_free). Otherwise,
14374 // the answer can only be determined at runtime; for example, 16-byte
14375 // atomics have lock-free implementations on some, but not all,
14376 // x86-64 processors.
14377
14378 // Check power-of-two.
14379 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
14380 if (Size.isPowerOfTwo()) {
14381 // Check against inlining width.
14382 unsigned InlineWidthBits =
14384 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
14385 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
14386 Size == CharUnits::One())
14387 return Success(1, E);
14388
14389 // If the pointer argument can be evaluated to a compile-time constant
14390 // integer (or nullptr), check if that value is appropriately aligned.
14391 const Expr *PtrArg = E->getArg(1);
14392 Expr::EvalResult ExprResult;
14393 APSInt IntResult;
14394 if (PtrArg->EvaluateAsRValue(ExprResult, Info.Ctx) &&
14395 ExprResult.Val.toIntegralConstant(IntResult, PtrArg->getType(),
14396 Info.Ctx) &&
14397 IntResult.isAligned(Size.getAsAlign()))
14398 return Success(1, E);
14399
14400 // Otherwise, check if the type's alignment against Size.
14401 if (auto *ICE = dyn_cast<ImplicitCastExpr>(PtrArg)) {
14402 // Drop the potential implicit-cast to 'const volatile void*', getting
14403 // the underlying type.
14404 if (ICE->getCastKind() == CK_BitCast)
14405 PtrArg = ICE->getSubExpr();
14406 }
14407
14408 if (auto PtrTy = PtrArg->getType()->getAs<PointerType>()) {
14409 QualType PointeeType = PtrTy->getPointeeType();
14410 if (!PointeeType->isIncompleteType() &&
14411 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
14412 // OK, we will inline operations on this object.
14413 return Success(1, E);
14414 }
14415 }
14416 }
14417 }
14418
14419 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
14420 Success(0, E) : Error(E);
14421 }
14422 case Builtin::BI__builtin_addcb:
14423 case Builtin::BI__builtin_addcs:
14424 case Builtin::BI__builtin_addc:
14425 case Builtin::BI__builtin_addcl:
14426 case Builtin::BI__builtin_addcll:
14427 case Builtin::BI__builtin_subcb:
14428 case Builtin::BI__builtin_subcs:
14429 case Builtin::BI__builtin_subc:
14430 case Builtin::BI__builtin_subcl:
14431 case Builtin::BI__builtin_subcll: {
14432 LValue CarryOutLValue;
14433 APSInt LHS, RHS, CarryIn, CarryOut, Result;
14434 QualType ResultType = E->getArg(0)->getType();
14435 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
14436 !EvaluateInteger(E->getArg(1), RHS, Info) ||
14437 !EvaluateInteger(E->getArg(2), CarryIn, Info) ||
14438 !EvaluatePointer(E->getArg(3), CarryOutLValue, Info))
14439 return false;
14440 // Copy the number of bits and sign.
14441 Result = LHS;
14442 CarryOut = LHS;
14443
14444 bool FirstOverflowed = false;
14445 bool SecondOverflowed = false;
14446 switch (BuiltinOp) {
14447 default:
14448 llvm_unreachable("Invalid value for BuiltinOp");
14449 case Builtin::BI__builtin_addcb:
14450 case Builtin::BI__builtin_addcs:
14451 case Builtin::BI__builtin_addc:
14452 case Builtin::BI__builtin_addcl:
14453 case Builtin::BI__builtin_addcll:
14454 Result =
14455 LHS.uadd_ov(RHS, FirstOverflowed).uadd_ov(CarryIn, SecondOverflowed);
14456 break;
14457 case Builtin::BI__builtin_subcb:
14458 case Builtin::BI__builtin_subcs:
14459 case Builtin::BI__builtin_subc:
14460 case Builtin::BI__builtin_subcl:
14461 case Builtin::BI__builtin_subcll:
14462 Result =
14463 LHS.usub_ov(RHS, FirstOverflowed).usub_ov(CarryIn, SecondOverflowed);
14464 break;
14465 }
14466
14467 // It is possible for both overflows to happen but CGBuiltin uses an OR so
14468 // this is consistent.
14469 CarryOut = (uint64_t)(FirstOverflowed | SecondOverflowed);
14470 APValue APV{CarryOut};
14471 if (!handleAssignment(Info, E, CarryOutLValue, ResultType, APV))
14472 return false;
14473 return Success(Result, E);
14474 }
14475 case Builtin::BI__builtin_add_overflow:
14476 case Builtin::BI__builtin_sub_overflow:
14477 case Builtin::BI__builtin_mul_overflow:
14478 case Builtin::BI__builtin_sadd_overflow:
14479 case Builtin::BI__builtin_uadd_overflow:
14480 case Builtin::BI__builtin_uaddl_overflow:
14481 case Builtin::BI__builtin_uaddll_overflow:
14482 case Builtin::BI__builtin_usub_overflow:
14483 case Builtin::BI__builtin_usubl_overflow:
14484 case Builtin::BI__builtin_usubll_overflow:
14485 case Builtin::BI__builtin_umul_overflow:
14486 case Builtin::BI__builtin_umull_overflow:
14487 case Builtin::BI__builtin_umulll_overflow:
14488 case Builtin::BI__builtin_saddl_overflow:
14489 case Builtin::BI__builtin_saddll_overflow:
14490 case Builtin::BI__builtin_ssub_overflow:
14491 case Builtin::BI__builtin_ssubl_overflow:
14492 case Builtin::BI__builtin_ssubll_overflow:
14493 case Builtin::BI__builtin_smul_overflow:
14494 case Builtin::BI__builtin_smull_overflow:
14495 case Builtin::BI__builtin_smulll_overflow: {
14496 LValue ResultLValue;
14497 APSInt LHS, RHS;
14498
14499 QualType ResultType = E->getArg(2)->getType()->getPointeeType();
14500 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
14501 !EvaluateInteger(E->getArg(1), RHS, Info) ||
14502 !EvaluatePointer(E->getArg(2), ResultLValue, Info))
14503 return false;
14504
14505 APSInt Result;
14506 bool DidOverflow = false;
14507
14508 // If the types don't have to match, enlarge all 3 to the largest of them.
14509 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
14510 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
14511 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
14512 bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
14514 bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
14516 uint64_t LHSSize = LHS.getBitWidth();
14517 uint64_t RHSSize = RHS.getBitWidth();
14518 uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
14519 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
14520
14521 // Add an additional bit if the signedness isn't uniformly agreed to. We
14522 // could do this ONLY if there is a signed and an unsigned that both have
14523 // MaxBits, but the code to check that is pretty nasty. The issue will be
14524 // caught in the shrink-to-result later anyway.
14525 if (IsSigned && !AllSigned)
14526 ++MaxBits;
14527
14528 LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
14529 RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
14530 Result = APSInt(MaxBits, !IsSigned);
14531 }
14532
14533 // Find largest int.
14534 switch (BuiltinOp) {
14535 default:
14536 llvm_unreachable("Invalid value for BuiltinOp");
14537 case Builtin::BI__builtin_add_overflow:
14538 case Builtin::BI__builtin_sadd_overflow:
14539 case Builtin::BI__builtin_saddl_overflow:
14540 case Builtin::BI__builtin_saddll_overflow:
14541 case Builtin::BI__builtin_uadd_overflow:
14542 case Builtin::BI__builtin_uaddl_overflow:
14543 case Builtin::BI__builtin_uaddll_overflow:
14544 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
14545 : LHS.uadd_ov(RHS, DidOverflow);
14546 break;
14547 case Builtin::BI__builtin_sub_overflow:
14548 case Builtin::BI__builtin_ssub_overflow:
14549 case Builtin::BI__builtin_ssubl_overflow:
14550 case Builtin::BI__builtin_ssubll_overflow:
14551 case Builtin::BI__builtin_usub_overflow:
14552 case Builtin::BI__builtin_usubl_overflow:
14553 case Builtin::BI__builtin_usubll_overflow:
14554 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
14555 : LHS.usub_ov(RHS, DidOverflow);
14556 break;
14557 case Builtin::BI__builtin_mul_overflow:
14558 case Builtin::BI__builtin_smul_overflow:
14559 case Builtin::BI__builtin_smull_overflow:
14560 case Builtin::BI__builtin_smulll_overflow:
14561 case Builtin::BI__builtin_umul_overflow:
14562 case Builtin::BI__builtin_umull_overflow:
14563 case Builtin::BI__builtin_umulll_overflow:
14564 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
14565 : LHS.umul_ov(RHS, DidOverflow);
14566 break;
14567 }
14568
14569 // In the case where multiple sizes are allowed, truncate and see if
14570 // the values are the same.
14571 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
14572 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
14573 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
14574 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
14575 // since it will give us the behavior of a TruncOrSelf in the case where
14576 // its parameter <= its size. We previously set Result to be at least the
14577 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
14578 // will work exactly like TruncOrSelf.
14579 APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
14580 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
14581
14582 if (!APSInt::isSameValue(Temp, Result))
14583 DidOverflow = true;
14584 Result = Temp;
14585 }
14586
14587 APValue APV{Result};
14588 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
14589 return false;
14590 return Success(DidOverflow, E);
14591 }
14592
14593 case Builtin::BI__builtin_reduce_add:
14594 case Builtin::BI__builtin_reduce_mul:
14595 case Builtin::BI__builtin_reduce_and:
14596 case Builtin::BI__builtin_reduce_or:
14597 case Builtin::BI__builtin_reduce_xor:
14598 case Builtin::BI__builtin_reduce_min:
14599 case Builtin::BI__builtin_reduce_max: {
14600 APValue Source;
14601 if (!EvaluateAsRValue(Info, E->getArg(0), Source))
14602 return false;
14603
14604 unsigned SourceLen = Source.getVectorLength();
14605 APSInt Reduced = Source.getVectorElt(0).getInt();
14606 for (unsigned EltNum = 1; EltNum < SourceLen; ++EltNum) {
14607 switch (BuiltinOp) {
14608 default:
14609 return false;
14610 case Builtin::BI__builtin_reduce_add: {
14612 Info, E, Reduced, Source.getVectorElt(EltNum).getInt(),
14613 Reduced.getBitWidth() + 1, std::plus<APSInt>(), Reduced))
14614 return false;
14615 break;
14616 }
14617 case Builtin::BI__builtin_reduce_mul: {
14619 Info, E, Reduced, Source.getVectorElt(EltNum).getInt(),
14620 Reduced.getBitWidth() * 2, std::multiplies<APSInt>(), Reduced))
14621 return false;
14622 break;
14623 }
14624 case Builtin::BI__builtin_reduce_and: {
14625 Reduced &= Source.getVectorElt(EltNum).getInt();
14626 break;
14627 }
14628 case Builtin::BI__builtin_reduce_or: {
14629 Reduced |= Source.getVectorElt(EltNum).getInt();
14630 break;
14631 }
14632 case Builtin::BI__builtin_reduce_xor: {
14633 Reduced ^= Source.getVectorElt(EltNum).getInt();
14634 break;
14635 }
14636 case Builtin::BI__builtin_reduce_min: {
14637 Reduced = std::min(Reduced, Source.getVectorElt(EltNum).getInt());
14638 break;
14639 }
14640 case Builtin::BI__builtin_reduce_max: {
14641 Reduced = std::max(Reduced, Source.getVectorElt(EltNum).getInt());
14642 break;
14643 }
14644 }
14645 }
14646
14647 return Success(Reduced, E);
14648 }
14649
14650 case clang::X86::BI__builtin_ia32_addcarryx_u32:
14651 case clang::X86::BI__builtin_ia32_addcarryx_u64:
14652 case clang::X86::BI__builtin_ia32_subborrow_u32:
14653 case clang::X86::BI__builtin_ia32_subborrow_u64: {
14654 LValue ResultLValue;
14655 APSInt CarryIn, LHS, RHS;
14656 QualType ResultType = E->getArg(3)->getType()->getPointeeType();
14657 if (!EvaluateInteger(E->getArg(0), CarryIn, Info) ||
14658 !EvaluateInteger(E->getArg(1), LHS, Info) ||
14659 !EvaluateInteger(E->getArg(2), RHS, Info) ||
14660 !EvaluatePointer(E->getArg(3), ResultLValue, Info))
14661 return false;
14662
14663 bool IsAdd = BuiltinOp == clang::X86::BI__builtin_ia32_addcarryx_u32 ||
14664 BuiltinOp == clang::X86::BI__builtin_ia32_addcarryx_u64;
14665
14666 unsigned BitWidth = LHS.getBitWidth();
14667 unsigned CarryInBit = CarryIn.ugt(0) ? 1 : 0;
14668 APInt ExResult =
14669 IsAdd
14670 ? (LHS.zext(BitWidth + 1) + (RHS.zext(BitWidth + 1) + CarryInBit))
14671 : (LHS.zext(BitWidth + 1) - (RHS.zext(BitWidth + 1) + CarryInBit));
14672
14673 APInt Result = ExResult.extractBits(BitWidth, 0);
14674 uint64_t CarryOut = ExResult.extractBitsAsZExtValue(1, BitWidth);
14675
14676 APValue APV{APSInt(Result, /*isUnsigned=*/true)};
14677 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
14678 return false;
14679 return Success(CarryOut, E);
14680 }
14681
14682 case clang::X86::BI__builtin_ia32_bextr_u32:
14683 case clang::X86::BI__builtin_ia32_bextr_u64:
14684 case clang::X86::BI__builtin_ia32_bextri_u32:
14685 case clang::X86::BI__builtin_ia32_bextri_u64: {
14686 APSInt Val, Idx;
14687 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
14688 !EvaluateInteger(E->getArg(1), Idx, Info))
14689 return false;
14690
14691 unsigned BitWidth = Val.getBitWidth();
14692 uint64_t Shift = Idx.extractBitsAsZExtValue(8, 0);
14693 uint64_t Length = Idx.extractBitsAsZExtValue(8, 8);
14694 Length = Length > BitWidth ? BitWidth : Length;
14695
14696 // Handle out of bounds cases.
14697 if (Length == 0 || Shift >= BitWidth)
14698 return Success(0, E);
14699
14700 uint64_t Result = Val.getZExtValue() >> Shift;
14701 Result &= llvm::maskTrailingOnes<uint64_t>(Length);
14702 return Success(Result, E);
14703 }
14704
14705 case clang::X86::BI__builtin_ia32_bzhi_si:
14706 case clang::X86::BI__builtin_ia32_bzhi_di: {
14707 APSInt Val, Idx;
14708 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
14709 !EvaluateInteger(E->getArg(1), Idx, Info))
14710 return false;
14711
14712 unsigned BitWidth = Val.getBitWidth();
14713 unsigned Index = Idx.extractBitsAsZExtValue(8, 0);
14714 if (Index < BitWidth)
14715 Val.clearHighBits(BitWidth - Index);
14716 return Success(Val, E);
14717 }
14718
14719 case clang::X86::BI__builtin_ia32_lzcnt_u16:
14720 case clang::X86::BI__builtin_ia32_lzcnt_u32:
14721 case clang::X86::BI__builtin_ia32_lzcnt_u64: {
14722 APSInt Val;
14723 if (!EvaluateInteger(E->getArg(0), Val, Info))
14724 return false;
14725 return Success(Val.countLeadingZeros(), E);
14726 }
14727
14728 case clang::X86::BI__builtin_ia32_tzcnt_u16:
14729 case clang::X86::BI__builtin_ia32_tzcnt_u32:
14730 case clang::X86::BI__builtin_ia32_tzcnt_u64: {
14731 APSInt Val;
14732 if (!EvaluateInteger(E->getArg(0), Val, Info))
14733 return false;
14734 return Success(Val.countTrailingZeros(), E);
14735 }
14736
14737 case clang::X86::BI__builtin_ia32_pdep_si:
14738 case clang::X86::BI__builtin_ia32_pdep_di: {
14739 APSInt Val, Msk;
14740 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
14741 !EvaluateInteger(E->getArg(1), Msk, Info))
14742 return false;
14743
14744 unsigned BitWidth = Val.getBitWidth();
14745 APInt Result = APInt::getZero(BitWidth);
14746 for (unsigned I = 0, P = 0; I != BitWidth; ++I)
14747 if (Msk[I])
14748 Result.setBitVal(I, Val[P++]);
14749 return Success(Result, E);
14750 }
14751
14752 case clang::X86::BI__builtin_ia32_pext_si:
14753 case clang::X86::BI__builtin_ia32_pext_di: {
14754 APSInt Val, Msk;
14755 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
14756 !EvaluateInteger(E->getArg(1), Msk, Info))
14757 return false;
14758
14759 unsigned BitWidth = Val.getBitWidth();
14760 APInt Result = APInt::getZero(BitWidth);
14761 for (unsigned I = 0, P = 0; I != BitWidth; ++I)
14762 if (Msk[I])
14763 Result.setBitVal(P++, Val[I]);
14764 return Success(Result, E);
14765 }
14766
14767 case X86::BI__builtin_ia32_kandqi:
14768 case X86::BI__builtin_ia32_kandhi:
14769 case X86::BI__builtin_ia32_kandsi:
14770 case X86::BI__builtin_ia32_kanddi: {
14771 return HandleMaskBinOp(
14772 [](const APSInt &LHS, const APSInt &RHS) { return LHS & RHS; });
14773 }
14774
14775 case X86::BI__builtin_ia32_kandnqi:
14776 case X86::BI__builtin_ia32_kandnhi:
14777 case X86::BI__builtin_ia32_kandnsi:
14778 case X86::BI__builtin_ia32_kandndi: {
14779 return HandleMaskBinOp(
14780 [](const APSInt &LHS, const APSInt &RHS) { return ~LHS & RHS; });
14781 }
14782
14783 case X86::BI__builtin_ia32_korqi:
14784 case X86::BI__builtin_ia32_korhi:
14785 case X86::BI__builtin_ia32_korsi:
14786 case X86::BI__builtin_ia32_kordi: {
14787 return HandleMaskBinOp(
14788 [](const APSInt &LHS, const APSInt &RHS) { return LHS | RHS; });
14789 }
14790
14791 case X86::BI__builtin_ia32_kxnorqi:
14792 case X86::BI__builtin_ia32_kxnorhi:
14793 case X86::BI__builtin_ia32_kxnorsi:
14794 case X86::BI__builtin_ia32_kxnordi: {
14795 return HandleMaskBinOp(
14796 [](const APSInt &LHS, const APSInt &RHS) { return ~(LHS ^ RHS); });
14797 }
14798
14799 case X86::BI__builtin_ia32_kxorqi:
14800 case X86::BI__builtin_ia32_kxorhi:
14801 case X86::BI__builtin_ia32_kxorsi:
14802 case X86::BI__builtin_ia32_kxordi: {
14803 return HandleMaskBinOp(
14804 [](const APSInt &LHS, const APSInt &RHS) { return LHS ^ RHS; });
14805 }
14806
14807 case X86::BI__builtin_ia32_knotqi:
14808 case X86::BI__builtin_ia32_knothi:
14809 case X86::BI__builtin_ia32_knotsi:
14810 case X86::BI__builtin_ia32_knotdi: {
14811 APSInt Val;
14812 if (!EvaluateInteger(E->getArg(0), Val, Info))
14813 return false;
14814 APSInt Result = ~Val;
14815 return Success(APValue(Result), E);
14816 }
14817
14818 case X86::BI__builtin_ia32_kaddqi:
14819 case X86::BI__builtin_ia32_kaddhi:
14820 case X86::BI__builtin_ia32_kaddsi:
14821 case X86::BI__builtin_ia32_kadddi: {
14822 return HandleMaskBinOp(
14823 [](const APSInt &LHS, const APSInt &RHS) { return LHS + RHS; });
14824 }
14825 }
14826}
14827
14828/// Determine whether this is a pointer past the end of the complete
14829/// object referred to by the lvalue.
14831 const LValue &LV) {
14832 // A null pointer can be viewed as being "past the end" but we don't
14833 // choose to look at it that way here.
14834 if (!LV.getLValueBase())
14835 return false;
14836
14837 // If the designator is valid and refers to a subobject, we're not pointing
14838 // past the end.
14839 if (!LV.getLValueDesignator().Invalid &&
14840 !LV.getLValueDesignator().isOnePastTheEnd())
14841 return false;
14842
14843 // A pointer to an incomplete type might be past-the-end if the type's size is
14844 // zero. We cannot tell because the type is incomplete.
14845 QualType Ty = getType(LV.getLValueBase());
14846 if (Ty->isIncompleteType())
14847 return true;
14848
14849 // Can't be past the end of an invalid object.
14850 if (LV.getLValueDesignator().Invalid)
14851 return false;
14852
14853 // We're a past-the-end pointer if we point to the byte after the object,
14854 // no matter what our type or path is.
14855 auto Size = Ctx.getTypeSizeInChars(Ty);
14856 return LV.getLValueOffset() == Size;
14857}
14858
14859namespace {
14860
14861/// Data recursive integer evaluator of certain binary operators.
14862///
14863/// We use a data recursive algorithm for binary operators so that we are able
14864/// to handle extreme cases of chained binary operators without causing stack
14865/// overflow.
14866class DataRecursiveIntBinOpEvaluator {
14867 struct EvalResult {
14868 APValue Val;
14869 bool Failed = false;
14870
14871 EvalResult() = default;
14872
14873 void swap(EvalResult &RHS) {
14874 Val.swap(RHS.Val);
14875 Failed = RHS.Failed;
14876 RHS.Failed = false;
14877 }
14878 };
14879
14880 struct Job {
14881 const Expr *E;
14882 EvalResult LHSResult; // meaningful only for binary operator expression.
14883 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
14884
14885 Job() = default;
14886 Job(Job &&) = default;
14887
14888 void startSpeculativeEval(EvalInfo &Info) {
14889 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
14890 }
14891
14892 private:
14893 SpeculativeEvaluationRAII SpecEvalRAII;
14894 };
14895
14896 SmallVector<Job, 16> Queue;
14897
14898 IntExprEvaluator &IntEval;
14899 EvalInfo &Info;
14900 APValue &FinalResult;
14901
14902public:
14903 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
14904 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
14905
14906 /// True if \param E is a binary operator that we are going to handle
14907 /// data recursively.
14908 /// We handle binary operators that are comma, logical, or that have operands
14909 /// with integral or enumeration type.
14910 static bool shouldEnqueue(const BinaryOperator *E) {
14911 return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
14915 }
14916
14917 bool Traverse(const BinaryOperator *E) {
14918 enqueue(E);
14919 EvalResult PrevResult;
14920 while (!Queue.empty())
14921 process(PrevResult);
14922
14923 if (PrevResult.Failed) return false;
14924
14925 FinalResult.swap(PrevResult.Val);
14926 return true;
14927 }
14928
14929private:
14930 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
14931 return IntEval.Success(Value, E, Result);
14932 }
14933 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
14934 return IntEval.Success(Value, E, Result);
14935 }
14936 bool Error(const Expr *E) {
14937 return IntEval.Error(E);
14938 }
14939 bool Error(const Expr *E, diag::kind D) {
14940 return IntEval.Error(E, D);
14941 }
14942
14943 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
14944 return Info.CCEDiag(E, D);
14945 }
14946
14947 // Returns true if visiting the RHS is necessary, false otherwise.
14948 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
14949 bool &SuppressRHSDiags);
14950
14951 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
14952 const BinaryOperator *E, APValue &Result);
14953
14954 void EvaluateExpr(const Expr *E, EvalResult &Result) {
14955 Result.Failed = !Evaluate(Result.Val, Info, E);
14956 if (Result.Failed)
14957 Result.Val = APValue();
14958 }
14959
14960 void process(EvalResult &Result);
14961
14962 void enqueue(const Expr *E) {
14963 E = E->IgnoreParens();
14964 Queue.resize(Queue.size()+1);
14965 Queue.back().E = E;
14966 Queue.back().Kind = Job::AnyExprKind;
14967 }
14968};
14969
14970}
14971
14972bool DataRecursiveIntBinOpEvaluator::
14973 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
14974 bool &SuppressRHSDiags) {
14975 if (E->getOpcode() == BO_Comma) {
14976 // Ignore LHS but note if we could not evaluate it.
14977 if (LHSResult.Failed)
14978 return Info.noteSideEffect();
14979 return true;
14980 }
14981
14982 if (E->isLogicalOp()) {
14983 bool LHSAsBool;
14984 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
14985 // We were able to evaluate the LHS, see if we can get away with not
14986 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
14987 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
14988 Success(LHSAsBool, E, LHSResult.Val);
14989 return false; // Ignore RHS
14990 }
14991 } else {
14992 LHSResult.Failed = true;
14993
14994 // Since we weren't able to evaluate the left hand side, it
14995 // might have had side effects.
14996 if (!Info.noteSideEffect())
14997 return false;
14998
14999 // We can't evaluate the LHS; however, sometimes the result
15000 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
15001 // Don't ignore RHS and suppress diagnostics from this arm.
15002 SuppressRHSDiags = true;
15003 }
15004
15005 return true;
15006 }
15007
15008 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
15010
15011 if (LHSResult.Failed && !Info.noteFailure())
15012 return false; // Ignore RHS;
15013
15014 return true;
15015}
15016
15017static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
15018 bool IsSub) {
15019 // Compute the new offset in the appropriate width, wrapping at 64 bits.
15020 // FIXME: When compiling for a 32-bit target, we should use 32-bit
15021 // offsets.
15022 assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
15023 CharUnits &Offset = LVal.getLValueOffset();
15024 uint64_t Offset64 = Offset.getQuantity();
15025 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
15026 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
15027 : Offset64 + Index64);
15028}
15029
15030bool DataRecursiveIntBinOpEvaluator::
15031 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
15032 const BinaryOperator *E, APValue &Result) {
15033 if (E->getOpcode() == BO_Comma) {
15034 if (RHSResult.Failed)
15035 return false;
15036 Result = RHSResult.Val;
15037 return true;
15038 }
15039
15040 if (E->isLogicalOp()) {
15041 bool lhsResult, rhsResult;
15042 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
15043 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
15044
15045 if (LHSIsOK) {
15046 if (RHSIsOK) {
15047 if (E->getOpcode() == BO_LOr)
15048 return Success(lhsResult || rhsResult, E, Result);
15049 else
15050 return Success(lhsResult && rhsResult, E, Result);
15051 }
15052 } else {
15053 if (RHSIsOK) {
15054 // We can't evaluate the LHS; however, sometimes the result
15055 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
15056 if (rhsResult == (E->getOpcode() == BO_LOr))
15057 return Success(rhsResult, E, Result);
15058 }
15059 }
15060
15061 return false;
15062 }
15063
15064 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
15066
15067 if (LHSResult.Failed || RHSResult.Failed)
15068 return false;
15069
15070 const APValue &LHSVal = LHSResult.Val;
15071 const APValue &RHSVal = RHSResult.Val;
15072
15073 // Handle cases like (unsigned long)&a + 4.
15074 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
15075 Result = LHSVal;
15076 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
15077 return true;
15078 }
15079
15080 // Handle cases like 4 + (unsigned long)&a
15081 if (E->getOpcode() == BO_Add &&
15082 RHSVal.isLValue() && LHSVal.isInt()) {
15083 Result = RHSVal;
15084 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
15085 return true;
15086 }
15087
15088 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
15089 // Handle (intptr_t)&&A - (intptr_t)&&B.
15090 if (!LHSVal.getLValueOffset().isZero() ||
15091 !RHSVal.getLValueOffset().isZero())
15092 return false;
15093 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
15094 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
15095 if (!LHSExpr || !RHSExpr)
15096 return false;
15097 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
15098 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
15099 if (!LHSAddrExpr || !RHSAddrExpr)
15100 return false;
15101 // Make sure both labels come from the same function.
15102 if (LHSAddrExpr->getLabel()->getDeclContext() !=
15103 RHSAddrExpr->getLabel()->getDeclContext())
15104 return false;
15105 Result = APValue(LHSAddrExpr, RHSAddrExpr);
15106 return true;
15107 }
15108
15109 // All the remaining cases expect both operands to be an integer
15110 if (!LHSVal.isInt() || !RHSVal.isInt())
15111 return Error(E);
15112
15113 // Set up the width and signedness manually, in case it can't be deduced
15114 // from the operation we're performing.
15115 // FIXME: Don't do this in the cases where we can deduce it.
15116 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
15118 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
15119 RHSVal.getInt(), Value))
15120 return false;
15121 return Success(Value, E, Result);
15122}
15123
15124void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
15125 Job &job = Queue.back();
15126
15127 switch (job.Kind) {
15128 case Job::AnyExprKind: {
15129 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
15130 if (shouldEnqueue(Bop)) {
15131 job.Kind = Job::BinOpKind;
15132 enqueue(Bop->getLHS());
15133 return;
15134 }
15135 }
15136
15137 EvaluateExpr(job.E, Result);
15138 Queue.pop_back();
15139 return;
15140 }
15141
15142 case Job::BinOpKind: {
15143 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
15144 bool SuppressRHSDiags = false;
15145 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
15146 Queue.pop_back();
15147 return;
15148 }
15149 if (SuppressRHSDiags)
15150 job.startSpeculativeEval(Info);
15151 job.LHSResult.swap(Result);
15152 job.Kind = Job::BinOpVisitedLHSKind;
15153 enqueue(Bop->getRHS());
15154 return;
15155 }
15156
15157 case Job::BinOpVisitedLHSKind: {
15158 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
15159 EvalResult RHS;
15160 RHS.swap(Result);
15161 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
15162 Queue.pop_back();
15163 return;
15164 }
15165 }
15166
15167 llvm_unreachable("Invalid Job::Kind!");
15168}
15169
15170namespace {
15171enum class CmpResult {
15172 Unequal,
15173 Less,
15174 Equal,
15175 Greater,
15176 Unordered,
15177};
15178}
15179
15180template <class SuccessCB, class AfterCB>
15181static bool
15183 SuccessCB &&Success, AfterCB &&DoAfter) {
15184 assert(!E->isValueDependent());
15185 assert(E->isComparisonOp() && "expected comparison operator");
15186 assert((E->getOpcode() == BO_Cmp ||
15188 "unsupported binary expression evaluation");
15189 auto Error = [&](const Expr *E) {
15190 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
15191 return false;
15192 };
15193
15194 bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp;
15195 bool IsEquality = E->isEqualityOp();
15196
15197 QualType LHSTy = E->getLHS()->getType();
15198 QualType RHSTy = E->getRHS()->getType();
15199
15200 if (LHSTy->isIntegralOrEnumerationType() &&
15201 RHSTy->isIntegralOrEnumerationType()) {
15202 APSInt LHS, RHS;
15203 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
15204 if (!LHSOK && !Info.noteFailure())
15205 return false;
15206 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
15207 return false;
15208 if (LHS < RHS)
15209 return Success(CmpResult::Less, E);
15210 if (LHS > RHS)
15211 return Success(CmpResult::Greater, E);
15212 return Success(CmpResult::Equal, E);
15213 }
15214
15215 if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
15216 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
15217 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
15218
15219 bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
15220 if (!LHSOK && !Info.noteFailure())
15221 return false;
15222 if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
15223 return false;
15224 if (LHSFX < RHSFX)
15225 return Success(CmpResult::Less, E);
15226 if (LHSFX > RHSFX)
15227 return Success(CmpResult::Greater, E);
15228 return Success(CmpResult::Equal, E);
15229 }
15230
15231 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
15232 ComplexValue LHS, RHS;
15233 bool LHSOK;
15234 if (E->isAssignmentOp()) {
15235 LValue LV;
15236 EvaluateLValue(E->getLHS(), LV, Info);
15237 LHSOK = false;
15238 } else if (LHSTy->isRealFloatingType()) {
15239 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
15240 if (LHSOK) {
15241 LHS.makeComplexFloat();
15242 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
15243 }
15244 } else {
15245 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
15246 }
15247 if (!LHSOK && !Info.noteFailure())
15248 return false;
15249
15250 if (E->getRHS()->getType()->isRealFloatingType()) {
15251 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
15252 return false;
15253 RHS.makeComplexFloat();
15254 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
15255 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
15256 return false;
15257
15258 if (LHS.isComplexFloat()) {
15259 APFloat::cmpResult CR_r =
15260 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
15261 APFloat::cmpResult CR_i =
15262 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
15263 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
15264 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
15265 } else {
15266 assert(IsEquality && "invalid complex comparison");
15267 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
15268 LHS.getComplexIntImag() == RHS.getComplexIntImag();
15269 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
15270 }
15271 }
15272
15273 if (LHSTy->isRealFloatingType() &&
15274 RHSTy->isRealFloatingType()) {
15275 APFloat RHS(0.0), LHS(0.0);
15276
15277 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
15278 if (!LHSOK && !Info.noteFailure())
15279 return false;
15280
15281 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
15282 return false;
15283
15284 assert(E->isComparisonOp() && "Invalid binary operator!");
15285 llvm::APFloatBase::cmpResult APFloatCmpResult = LHS.compare(RHS);
15286 if (!Info.InConstantContext &&
15287 APFloatCmpResult == APFloat::cmpUnordered &&
15289 // Note: Compares may raise invalid in some cases involving NaN or sNaN.
15290 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
15291 return false;
15292 }
15293 auto GetCmpRes = [&]() {
15294 switch (APFloatCmpResult) {
15295 case APFloat::cmpEqual:
15296 return CmpResult::Equal;
15297 case APFloat::cmpLessThan:
15298 return CmpResult::Less;
15299 case APFloat::cmpGreaterThan:
15300 return CmpResult::Greater;
15301 case APFloat::cmpUnordered:
15302 return CmpResult::Unordered;
15303 }
15304 llvm_unreachable("Unrecognised APFloat::cmpResult enum");
15305 };
15306 return Success(GetCmpRes(), E);
15307 }
15308
15309 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
15310 LValue LHSValue, RHSValue;
15311
15312 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
15313 if (!LHSOK && !Info.noteFailure())
15314 return false;
15315
15316 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
15317 return false;
15318
15319 // Reject differing bases from the normal codepath; we special-case
15320 // comparisons to null.
15321 if (!HasSameBase(LHSValue, RHSValue)) {
15322 // Bail out early if we're checking potential constant expression.
15323 // Otherwise, prefer to diagnose other issues.
15324 if (Info.checkingPotentialConstantExpression() &&
15325 (LHSValue.AllowConstexprUnknown || RHSValue.AllowConstexprUnknown))
15326 return false;
15327 auto DiagComparison = [&] (unsigned DiagID, bool Reversed = false) {
15328 std::string LHS = LHSValue.toString(Info.Ctx, E->getLHS()->getType());
15329 std::string RHS = RHSValue.toString(Info.Ctx, E->getRHS()->getType());
15330 Info.FFDiag(E, DiagID)
15331 << (Reversed ? RHS : LHS) << (Reversed ? LHS : RHS);
15332 return false;
15333 };
15334 // Inequalities and subtractions between unrelated pointers have
15335 // unspecified or undefined behavior.
15336 if (!IsEquality)
15337 return DiagComparison(
15338 diag::note_constexpr_pointer_comparison_unspecified);
15339 // A constant address may compare equal to the address of a symbol.
15340 // The one exception is that address of an object cannot compare equal
15341 // to a null pointer constant.
15342 // TODO: Should we restrict this to actual null pointers, and exclude the
15343 // case of zero cast to pointer type?
15344 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
15345 (!RHSValue.Base && !RHSValue.Offset.isZero()))
15346 return DiagComparison(diag::note_constexpr_pointer_constant_comparison,
15347 !RHSValue.Base);
15348 // C++2c [intro.object]/10:
15349 // Two objects [...] may have the same address if [...] they are both
15350 // potentially non-unique objects.
15351 // C++2c [intro.object]/9:
15352 // An object is potentially non-unique if it is a string literal object,
15353 // the backing array of an initializer list, or a subobject thereof.
15354 //
15355 // This makes the comparison result unspecified, so it's not a constant
15356 // expression.
15357 //
15358 // TODO: Do we need to handle the initializer list case here?
15359 if (ArePotentiallyOverlappingStringLiterals(Info, LHSValue, RHSValue))
15360 return DiagComparison(diag::note_constexpr_literal_comparison);
15361 if (IsOpaqueConstantCall(LHSValue) || IsOpaqueConstantCall(RHSValue))
15362 return DiagComparison(diag::note_constexpr_opaque_call_comparison,
15363 !IsOpaqueConstantCall(LHSValue));
15364 // We can't tell whether weak symbols will end up pointing to the same
15365 // object.
15366 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
15367 return DiagComparison(diag::note_constexpr_pointer_weak_comparison,
15368 !IsWeakLValue(LHSValue));
15369 // We can't compare the address of the start of one object with the
15370 // past-the-end address of another object, per C++ DR1652.
15371 if (LHSValue.Base && LHSValue.Offset.isZero() &&
15372 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue))
15373 return DiagComparison(diag::note_constexpr_pointer_comparison_past_end,
15374 true);
15375 if (RHSValue.Base && RHSValue.Offset.isZero() &&
15376 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue))
15377 return DiagComparison(diag::note_constexpr_pointer_comparison_past_end,
15378 false);
15379 // We can't tell whether an object is at the same address as another
15380 // zero sized object.
15381 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
15382 (LHSValue.Base && isZeroSized(RHSValue)))
15383 return DiagComparison(
15384 diag::note_constexpr_pointer_comparison_zero_sized);
15385 if (LHSValue.AllowConstexprUnknown || RHSValue.AllowConstexprUnknown)
15386 return DiagComparison(
15387 diag::note_constexpr_pointer_comparison_unspecified);
15388 // FIXME: Verify both variables are live.
15389 return Success(CmpResult::Unequal, E);
15390 }
15391
15392 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
15393 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
15394
15395 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
15396 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
15397
15398 // C++11 [expr.rel]p2:
15399 // - If two pointers point to non-static data members of the same object,
15400 // or to subobjects or array elements fo such members, recursively, the
15401 // pointer to the later declared member compares greater provided the
15402 // two members have the same access control and provided their class is
15403 // not a union.
15404 // [...]
15405 // - Otherwise pointer comparisons are unspecified.
15406 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
15407 bool WasArrayIndex;
15408 unsigned Mismatch = FindDesignatorMismatch(
15409 LHSValue.Base.isNull() ? QualType()
15410 : getType(LHSValue.Base).getNonReferenceType(),
15411 LHSDesignator, RHSDesignator, WasArrayIndex);
15412 // At the point where the designators diverge, the comparison has a
15413 // specified value if:
15414 // - we are comparing array indices
15415 // - we are comparing fields of a union, or fields with the same access
15416 // Otherwise, the result is unspecified and thus the comparison is not a
15417 // constant expression.
15418 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
15419 Mismatch < RHSDesignator.Entries.size()) {
15420 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
15421 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
15422 if (!LF && !RF)
15423 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
15424 else if (!LF)
15425 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
15426 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
15427 << RF->getParent() << RF;
15428 else if (!RF)
15429 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
15430 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
15431 << LF->getParent() << LF;
15432 else if (!LF->getParent()->isUnion() &&
15433 LF->getAccess() != RF->getAccess())
15434 Info.CCEDiag(E,
15435 diag::note_constexpr_pointer_comparison_differing_access)
15436 << LF << LF->getAccess() << RF << RF->getAccess()
15437 << LF->getParent();
15438 }
15439 }
15440
15441 // The comparison here must be unsigned, and performed with the same
15442 // width as the pointer.
15443 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
15444 uint64_t CompareLHS = LHSOffset.getQuantity();
15445 uint64_t CompareRHS = RHSOffset.getQuantity();
15446 assert(PtrSize <= 64 && "Unexpected pointer width");
15447 uint64_t Mask = ~0ULL >> (64 - PtrSize);
15448 CompareLHS &= Mask;
15449 CompareRHS &= Mask;
15450
15451 // If there is a base and this is a relational operator, we can only
15452 // compare pointers within the object in question; otherwise, the result
15453 // depends on where the object is located in memory.
15454 if (!LHSValue.Base.isNull() && IsRelational) {
15455 QualType BaseTy = getType(LHSValue.Base).getNonReferenceType();
15456 if (BaseTy->isIncompleteType())
15457 return Error(E);
15458 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
15459 uint64_t OffsetLimit = Size.getQuantity();
15460 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
15461 return Error(E);
15462 }
15463
15464 if (CompareLHS < CompareRHS)
15465 return Success(CmpResult::Less, E);
15466 if (CompareLHS > CompareRHS)
15467 return Success(CmpResult::Greater, E);
15468 return Success(CmpResult::Equal, E);
15469 }
15470
15471 if (LHSTy->isMemberPointerType()) {
15472 assert(IsEquality && "unexpected member pointer operation");
15473 assert(RHSTy->isMemberPointerType() && "invalid comparison");
15474
15475 MemberPtr LHSValue, RHSValue;
15476
15477 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
15478 if (!LHSOK && !Info.noteFailure())
15479 return false;
15480
15481 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
15482 return false;
15483
15484 // If either operand is a pointer to a weak function, the comparison is not
15485 // constant.
15486 if (LHSValue.getDecl() && LHSValue.getDecl()->isWeak()) {
15487 Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison)
15488 << LHSValue.getDecl();
15489 return false;
15490 }
15491 if (RHSValue.getDecl() && RHSValue.getDecl()->isWeak()) {
15492 Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison)
15493 << RHSValue.getDecl();
15494 return false;
15495 }
15496
15497 // C++11 [expr.eq]p2:
15498 // If both operands are null, they compare equal. Otherwise if only one is
15499 // null, they compare unequal.
15500 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
15501 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
15502 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
15503 }
15504
15505 // Otherwise if either is a pointer to a virtual member function, the
15506 // result is unspecified.
15507 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
15508 if (MD->isVirtual())
15509 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
15510 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
15511 if (MD->isVirtual())
15512 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
15513
15514 // Otherwise they compare equal if and only if they would refer to the
15515 // same member of the same most derived object or the same subobject if
15516 // they were dereferenced with a hypothetical object of the associated
15517 // class type.
15518 bool Equal = LHSValue == RHSValue;
15519 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
15520 }
15521
15522 if (LHSTy->isNullPtrType()) {
15523 assert(E->isComparisonOp() && "unexpected nullptr operation");
15524 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
15525 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
15526 // are compared, the result is true of the operator is <=, >= or ==, and
15527 // false otherwise.
15528 LValue Res;
15529 if (!EvaluatePointer(E->getLHS(), Res, Info) ||
15530 !EvaluatePointer(E->getRHS(), Res, Info))
15531 return false;
15532 return Success(CmpResult::Equal, E);
15533 }
15534
15535 return DoAfter();
15536}
15537
15538bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
15539 if (!CheckLiteralType(Info, E))
15540 return false;
15541
15542 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
15544 switch (CR) {
15545 case CmpResult::Unequal:
15546 llvm_unreachable("should never produce Unequal for three-way comparison");
15547 case CmpResult::Less:
15548 CCR = ComparisonCategoryResult::Less;
15549 break;
15550 case CmpResult::Equal:
15551 CCR = ComparisonCategoryResult::Equal;
15552 break;
15553 case CmpResult::Greater:
15554 CCR = ComparisonCategoryResult::Greater;
15555 break;
15556 case CmpResult::Unordered:
15557 CCR = ComparisonCategoryResult::Unordered;
15558 break;
15559 }
15560 // Evaluation succeeded. Lookup the information for the comparison category
15561 // type and fetch the VarDecl for the result.
15562 const ComparisonCategoryInfo &CmpInfo =
15563 Info.Ctx.CompCategories.getInfoForType(E->getType());
15564 const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD;
15565 // Check and evaluate the result as a constant expression.
15566 LValue LV;
15567 LV.set(VD);
15568 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
15569 return false;
15570 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
15571 ConstantExprKind::Normal);
15572 };
15573 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
15574 return ExprEvaluatorBaseTy::VisitBinCmp(E);
15575 });
15576}
15577
15578bool RecordExprEvaluator::VisitCXXParenListInitExpr(
15579 const CXXParenListInitExpr *E) {
15580 return VisitCXXParenListOrInitListExpr(E, E->getInitExprs());
15581}
15582
15583bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
15584 // We don't support assignment in C. C++ assignments don't get here because
15585 // assignment is an lvalue in C++.
15586 if (E->isAssignmentOp()) {
15587 Error(E);
15588 if (!Info.noteFailure())
15589 return false;
15590 }
15591
15592 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
15593 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
15594
15595 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
15597 "DataRecursiveIntBinOpEvaluator should have handled integral types");
15598
15599 if (E->isComparisonOp()) {
15600 // Evaluate builtin binary comparisons by evaluating them as three-way
15601 // comparisons and then translating the result.
15602 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
15603 assert((CR != CmpResult::Unequal || E->isEqualityOp()) &&
15604 "should only produce Unequal for equality comparisons");
15605 bool IsEqual = CR == CmpResult::Equal,
15606 IsLess = CR == CmpResult::Less,
15607 IsGreater = CR == CmpResult::Greater;
15608 auto Op = E->getOpcode();
15609 switch (Op) {
15610 default:
15611 llvm_unreachable("unsupported binary operator");
15612 case BO_EQ:
15613 case BO_NE:
15614 return Success(IsEqual == (Op == BO_EQ), E);
15615 case BO_LT:
15616 return Success(IsLess, E);
15617 case BO_GT:
15618 return Success(IsGreater, E);
15619 case BO_LE:
15620 return Success(IsEqual || IsLess, E);
15621 case BO_GE:
15622 return Success(IsEqual || IsGreater, E);
15623 }
15624 };
15625 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
15626 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
15627 });
15628 }
15629
15630 QualType LHSTy = E->getLHS()->getType();
15631 QualType RHSTy = E->getRHS()->getType();
15632
15633 if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
15634 E->getOpcode() == BO_Sub) {
15635 LValue LHSValue, RHSValue;
15636
15637 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
15638 if (!LHSOK && !Info.noteFailure())
15639 return false;
15640
15641 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
15642 return false;
15643
15644 // Reject differing bases from the normal codepath; we special-case
15645 // comparisons to null.
15646 if (!HasSameBase(LHSValue, RHSValue)) {
15647 if (Info.checkingPotentialConstantExpression() &&
15648 (LHSValue.AllowConstexprUnknown || RHSValue.AllowConstexprUnknown))
15649 return false;
15650
15651 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
15652 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
15653
15654 auto DiagArith = [&](unsigned DiagID) {
15655 std::string LHS = LHSValue.toString(Info.Ctx, E->getLHS()->getType());
15656 std::string RHS = RHSValue.toString(Info.Ctx, E->getRHS()->getType());
15657 Info.FFDiag(E, DiagID) << LHS << RHS;
15658 if (LHSExpr && LHSExpr == RHSExpr)
15659 Info.Note(LHSExpr->getExprLoc(),
15660 diag::note_constexpr_repeated_literal_eval)
15661 << LHSExpr->getSourceRange();
15662 return false;
15663 };
15664
15665 if (!LHSExpr || !RHSExpr)
15666 return DiagArith(diag::note_constexpr_pointer_arith_unspecified);
15667
15668 if (ArePotentiallyOverlappingStringLiterals(Info, LHSValue, RHSValue))
15669 return DiagArith(diag::note_constexpr_literal_arith);
15670
15671 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
15672 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
15673 if (!LHSAddrExpr || !RHSAddrExpr)
15674 return Error(E);
15675 // Make sure both labels come from the same function.
15676 if (LHSAddrExpr->getLabel()->getDeclContext() !=
15677 RHSAddrExpr->getLabel()->getDeclContext())
15678 return Error(E);
15679 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
15680 }
15681 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
15682 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
15683
15684 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
15685 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
15686
15687 // C++11 [expr.add]p6:
15688 // Unless both pointers point to elements of the same array object, or
15689 // one past the last element of the array object, the behavior is
15690 // undefined.
15691 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
15692 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
15693 RHSDesignator))
15694 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
15695
15696 QualType Type = E->getLHS()->getType();
15697 QualType ElementType = Type->castAs<PointerType>()->getPointeeType();
15698
15699 CharUnits ElementSize;
15700 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
15701 return false;
15702
15703 // As an extension, a type may have zero size (empty struct or union in
15704 // C, array of zero length). Pointer subtraction in such cases has
15705 // undefined behavior, so is not constant.
15706 if (ElementSize.isZero()) {
15707 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
15708 << ElementType;
15709 return false;
15710 }
15711
15712 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
15713 // and produce incorrect results when it overflows. Such behavior
15714 // appears to be non-conforming, but is common, so perhaps we should
15715 // assume the standard intended for such cases to be undefined behavior
15716 // and check for them.
15717
15718 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
15719 // overflow in the final conversion to ptrdiff_t.
15720 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
15721 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
15722 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
15723 false);
15724 APSInt TrueResult = (LHS - RHS) / ElemSize;
15725 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
15726
15727 if (Result.extend(65) != TrueResult &&
15728 !HandleOverflow(Info, E, TrueResult, E->getType()))
15729 return false;
15730 return Success(Result, E);
15731 }
15732
15733 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
15734}
15735
15736/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
15737/// a result as the expression's type.
15738bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
15739 const UnaryExprOrTypeTraitExpr *E) {
15740 switch(E->getKind()) {
15741 case UETT_PreferredAlignOf:
15742 case UETT_AlignOf: {
15743 if (E->isArgumentType())
15744 return Success(
15745 GetAlignOfType(Info.Ctx, E->getArgumentType(), E->getKind()), E);
15746 else
15747 return Success(
15748 GetAlignOfExpr(Info.Ctx, E->getArgumentExpr(), E->getKind()), E);
15749 }
15750
15751 case UETT_PtrAuthTypeDiscriminator: {
15752 if (E->getArgumentType()->isDependentType())
15753 return false;
15754 return Success(
15756 }
15757 case UETT_VecStep: {
15758 QualType Ty = E->getTypeOfArgument();
15759
15760 if (Ty->isVectorType()) {
15761 unsigned n = Ty->castAs<VectorType>()->getNumElements();
15762
15763 // The vec_step built-in functions that take a 3-component
15764 // vector return 4. (OpenCL 1.1 spec 6.11.12)
15765 if (n == 3)
15766 n = 4;
15767
15768 return Success(n, E);
15769 } else
15770 return Success(1, E);
15771 }
15772
15773 case UETT_DataSizeOf:
15774 case UETT_SizeOf: {
15775 QualType SrcTy = E->getTypeOfArgument();
15776 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
15777 // the result is the size of the referenced type."
15778 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
15779 SrcTy = Ref->getPointeeType();
15780
15781 CharUnits Sizeof;
15782 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof,
15783 E->getKind() == UETT_DataSizeOf ? SizeOfType::DataSizeOf
15784 : SizeOfType::SizeOf)) {
15785 return false;
15786 }
15787 return Success(Sizeof, E);
15788 }
15789 case UETT_OpenMPRequiredSimdAlign:
15790 assert(E->isArgumentType());
15791 return Success(
15792 Info.Ctx.toCharUnitsFromBits(
15794 .getQuantity(),
15795 E);
15796 case UETT_VectorElements: {
15797 QualType Ty = E->getTypeOfArgument();
15798 // If the vector has a fixed size, we can determine the number of elements
15799 // at compile time.
15800 if (const auto *VT = Ty->getAs<VectorType>())
15801 return Success(VT->getNumElements(), E);
15802
15803 assert(Ty->isSizelessVectorType());
15804 if (Info.InConstantContext)
15805 Info.CCEDiag(E, diag::note_constexpr_non_const_vectorelements)
15806 << E->getSourceRange();
15807
15808 return false;
15809 }
15810 case UETT_CountOf: {
15811 QualType Ty = E->getTypeOfArgument();
15812 assert(Ty->isArrayType());
15813
15814 // We don't need to worry about array element qualifiers, so getting the
15815 // unsafe array type is fine.
15816 if (const auto *CAT =
15817 dyn_cast<ConstantArrayType>(Ty->getAsArrayTypeUnsafe())) {
15818 return Success(CAT->getSize(), E);
15819 }
15820
15821 assert(!Ty->isConstantSizeType());
15822
15823 // If it's a variable-length array type, we need to check whether it is a
15824 // multidimensional array. If so, we need to check the size expression of
15825 // the VLA to see if it's a constant size. If so, we can return that value.
15826 const auto *VAT = Info.Ctx.getAsVariableArrayType(Ty);
15827 assert(VAT);
15828 if (VAT->getElementType()->isArrayType()) {
15829 // Variable array size expression could be missing (e.g. int a[*][10]) In
15830 // that case, it can't be a constant expression.
15831 if (!VAT->getSizeExpr()) {
15832 Info.FFDiag(E->getBeginLoc());
15833 return false;
15834 }
15835
15836 std::optional<APSInt> Res =
15837 VAT->getSizeExpr()->getIntegerConstantExpr(Info.Ctx);
15838 if (Res) {
15839 // The resulting value always has type size_t, so we need to make the
15840 // returned APInt have the correct sign and bit-width.
15841 APInt Val{
15842 static_cast<unsigned>(Info.Ctx.getTypeSize(Info.Ctx.getSizeType())),
15843 Res->getZExtValue()};
15844 return Success(Val, E);
15845 }
15846 }
15847
15848 // Definitely a variable-length type, which is not an ICE.
15849 // FIXME: Better diagnostic.
15850 Info.FFDiag(E->getBeginLoc());
15851 return false;
15852 }
15853 }
15854
15855 llvm_unreachable("unknown expr/type trait");
15856}
15857
15858bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
15859 CharUnits Result;
15860 unsigned n = OOE->getNumComponents();
15861 if (n == 0)
15862 return Error(OOE);
15863 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
15864 for (unsigned i = 0; i != n; ++i) {
15865 OffsetOfNode ON = OOE->getComponent(i);
15866 switch (ON.getKind()) {
15867 case OffsetOfNode::Array: {
15868 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
15869 APSInt IdxResult;
15870 if (!EvaluateInteger(Idx, IdxResult, Info))
15871 return false;
15872 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
15873 if (!AT)
15874 return Error(OOE);
15875 CurrentType = AT->getElementType();
15876 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
15877 Result += IdxResult.getSExtValue() * ElementSize;
15878 break;
15879 }
15880
15881 case OffsetOfNode::Field: {
15882 FieldDecl *MemberDecl = ON.getField();
15883 const auto *RD = CurrentType->getAsRecordDecl();
15884 if (!RD)
15885 return Error(OOE);
15886 if (RD->isInvalidDecl()) return false;
15887 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
15888 unsigned i = MemberDecl->getFieldIndex();
15889 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
15890 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
15891 CurrentType = MemberDecl->getType().getNonReferenceType();
15892 break;
15893 }
15894
15896 llvm_unreachable("dependent __builtin_offsetof");
15897
15898 case OffsetOfNode::Base: {
15899 CXXBaseSpecifier *BaseSpec = ON.getBase();
15900 if (BaseSpec->isVirtual())
15901 return Error(OOE);
15902
15903 // Find the layout of the class whose base we are looking into.
15904 const auto *RD = CurrentType->getAsCXXRecordDecl();
15905 if (!RD)
15906 return Error(OOE);
15907 if (RD->isInvalidDecl()) return false;
15908 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
15909
15910 // Find the base class itself.
15911 CurrentType = BaseSpec->getType();
15912 const auto *BaseRD = CurrentType->getAsCXXRecordDecl();
15913 if (!BaseRD)
15914 return Error(OOE);
15915
15916 // Add the offset to the base.
15917 Result += RL.getBaseClassOffset(BaseRD);
15918 break;
15919 }
15920 }
15921 }
15922 return Success(Result, OOE);
15923}
15924
15925bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
15926 switch (E->getOpcode()) {
15927 default:
15928 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
15929 // See C99 6.6p3.
15930 return Error(E);
15931 case UO_Extension:
15932 // FIXME: Should extension allow i-c-e extension expressions in its scope?
15933 // If so, we could clear the diagnostic ID.
15934 return Visit(E->getSubExpr());
15935 case UO_Plus:
15936 // The result is just the value.
15937 return Visit(E->getSubExpr());
15938 case UO_Minus: {
15939 if (!Visit(E->getSubExpr()))
15940 return false;
15941 if (!Result.isInt()) return Error(E);
15942 const APSInt &Value = Result.getInt();
15943 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow()) {
15944 if (Info.checkingForUndefinedBehavior())
15945 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
15946 diag::warn_integer_constant_overflow)
15947 << toString(Value, 10, Value.isSigned(), /*formatAsCLiteral=*/false,
15948 /*UpperCase=*/true, /*InsertSeparators=*/true)
15949 << E->getType() << E->getSourceRange();
15950
15951 if (!HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
15952 E->getType()))
15953 return false;
15954 }
15955 return Success(-Value, E);
15956 }
15957 case UO_Not: {
15958 if (!Visit(E->getSubExpr()))
15959 return false;
15960 if (!Result.isInt()) return Error(E);
15961 return Success(~Result.getInt(), E);
15962 }
15963 case UO_LNot: {
15964 bool bres;
15965 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
15966 return false;
15967 return Success(!bres, E);
15968 }
15969 }
15970}
15971
15972/// HandleCast - This is used to evaluate implicit or explicit casts where the
15973/// result type is integer.
15974bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
15975 const Expr *SubExpr = E->getSubExpr();
15976 QualType DestType = E->getType();
15977 QualType SrcType = SubExpr->getType();
15978
15979 switch (E->getCastKind()) {
15980 case CK_BaseToDerived:
15981 case CK_DerivedToBase:
15982 case CK_UncheckedDerivedToBase:
15983 case CK_Dynamic:
15984 case CK_ToUnion:
15985 case CK_ArrayToPointerDecay:
15986 case CK_FunctionToPointerDecay:
15987 case CK_NullToPointer:
15988 case CK_NullToMemberPointer:
15989 case CK_BaseToDerivedMemberPointer:
15990 case CK_DerivedToBaseMemberPointer:
15991 case CK_ReinterpretMemberPointer:
15992 case CK_ConstructorConversion:
15993 case CK_IntegralToPointer:
15994 case CK_ToVoid:
15995 case CK_VectorSplat:
15996 case CK_IntegralToFloating:
15997 case CK_FloatingCast:
15998 case CK_CPointerToObjCPointerCast:
15999 case CK_BlockPointerToObjCPointerCast:
16000 case CK_AnyPointerToBlockPointerCast:
16001 case CK_ObjCObjectLValueCast:
16002 case CK_FloatingRealToComplex:
16003 case CK_FloatingComplexToReal:
16004 case CK_FloatingComplexCast:
16005 case CK_FloatingComplexToIntegralComplex:
16006 case CK_IntegralRealToComplex:
16007 case CK_IntegralComplexCast:
16008 case CK_IntegralComplexToFloatingComplex:
16009 case CK_BuiltinFnToFnPtr:
16010 case CK_ZeroToOCLOpaqueType:
16011 case CK_NonAtomicToAtomic:
16012 case CK_AddressSpaceConversion:
16013 case CK_IntToOCLSampler:
16014 case CK_FloatingToFixedPoint:
16015 case CK_FixedPointToFloating:
16016 case CK_FixedPointCast:
16017 case CK_IntegralToFixedPoint:
16018 case CK_MatrixCast:
16019 case CK_HLSLAggregateSplatCast:
16020 llvm_unreachable("invalid cast kind for integral value");
16021
16022 case CK_BitCast:
16023 case CK_Dependent:
16024 case CK_LValueBitCast:
16025 case CK_ARCProduceObject:
16026 case CK_ARCConsumeObject:
16027 case CK_ARCReclaimReturnedObject:
16028 case CK_ARCExtendBlockObject:
16029 case CK_CopyAndAutoreleaseBlockObject:
16030 return Error(E);
16031
16032 case CK_UserDefinedConversion:
16033 case CK_LValueToRValue:
16034 case CK_AtomicToNonAtomic:
16035 case CK_NoOp:
16036 case CK_LValueToRValueBitCast:
16037 case CK_HLSLArrayRValue:
16038 case CK_HLSLElementwiseCast:
16039 return ExprEvaluatorBaseTy::VisitCastExpr(E);
16040
16041 case CK_MemberPointerToBoolean:
16042 case CK_PointerToBoolean:
16043 case CK_IntegralToBoolean:
16044 case CK_FloatingToBoolean:
16045 case CK_BooleanToSignedIntegral:
16046 case CK_FloatingComplexToBoolean:
16047 case CK_IntegralComplexToBoolean: {
16048 bool BoolResult;
16049 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
16050 return false;
16051 uint64_t IntResult = BoolResult;
16052 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
16053 IntResult = (uint64_t)-1;
16054 return Success(IntResult, E);
16055 }
16056
16057 case CK_FixedPointToIntegral: {
16058 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
16059 if (!EvaluateFixedPoint(SubExpr, Src, Info))
16060 return false;
16061 bool Overflowed;
16062 llvm::APSInt Result = Src.convertToInt(
16063 Info.Ctx.getIntWidth(DestType),
16064 DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
16065 if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
16066 return false;
16067 return Success(Result, E);
16068 }
16069
16070 case CK_FixedPointToBoolean: {
16071 // Unsigned padding does not affect this.
16072 APValue Val;
16073 if (!Evaluate(Val, Info, SubExpr))
16074 return false;
16075 return Success(Val.getFixedPoint().getBoolValue(), E);
16076 }
16077
16078 case CK_IntegralCast: {
16079 if (!Visit(SubExpr))
16080 return false;
16081
16082 if (!Result.isInt()) {
16083 // Allow casts of address-of-label differences if they are no-ops
16084 // or narrowing. (The narrowing case isn't actually guaranteed to
16085 // be constant-evaluatable except in some narrow cases which are hard
16086 // to detect here. We let it through on the assumption the user knows
16087 // what they are doing.)
16088 if (Result.isAddrLabelDiff())
16089 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
16090 // Only allow casts of lvalues if they are lossless.
16091 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
16092 }
16093
16094 if (Info.Ctx.getLangOpts().CPlusPlus && DestType->isEnumeralType()) {
16095 const auto *ED = DestType->getAsEnumDecl();
16096 // Check that the value is within the range of the enumeration values.
16097 //
16098 // This corressponds to [expr.static.cast]p10 which says:
16099 // A value of integral or enumeration type can be explicitly converted
16100 // to a complete enumeration type ... If the enumeration type does not
16101 // have a fixed underlying type, the value is unchanged if the original
16102 // value is within the range of the enumeration values ([dcl.enum]), and
16103 // otherwise, the behavior is undefined.
16104 //
16105 // This was resolved as part of DR2338 which has CD5 status.
16106 if (!ED->isFixed()) {
16107 llvm::APInt Min;
16108 llvm::APInt Max;
16109
16110 ED->getValueRange(Max, Min);
16111 --Max;
16112
16113 if (ED->getNumNegativeBits() &&
16114 (Max.slt(Result.getInt().getSExtValue()) ||
16115 Min.sgt(Result.getInt().getSExtValue())))
16116 Info.CCEDiag(E, diag::note_constexpr_unscoped_enum_out_of_range)
16117 << llvm::toString(Result.getInt(), 10) << Min.getSExtValue()
16118 << Max.getSExtValue() << ED;
16119 else if (!ED->getNumNegativeBits() &&
16120 Max.ult(Result.getInt().getZExtValue()))
16121 Info.CCEDiag(E, diag::note_constexpr_unscoped_enum_out_of_range)
16122 << llvm::toString(Result.getInt(), 10) << Min.getZExtValue()
16123 << Max.getZExtValue() << ED;
16124 }
16125 }
16126
16127 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
16128 Result.getInt()), E);
16129 }
16130
16131 case CK_PointerToIntegral: {
16132 CCEDiag(E, diag::note_constexpr_invalid_cast)
16133 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
16134 << Info.Ctx.getLangOpts().CPlusPlus << E->getSourceRange();
16135
16136 LValue LV;
16137 if (!EvaluatePointer(SubExpr, LV, Info))
16138 return false;
16139
16140 if (LV.getLValueBase()) {
16141 // Only allow based lvalue casts if they are lossless.
16142 // FIXME: Allow a larger integer size than the pointer size, and allow
16143 // narrowing back down to pointer width in subsequent integral casts.
16144 // FIXME: Check integer type's active bits, not its type size.
16145 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
16146 return Error(E);
16147
16148 LV.Designator.setInvalid();
16149 LV.moveInto(Result);
16150 return true;
16151 }
16152
16153 APSInt AsInt;
16154 APValue V;
16155 LV.moveInto(V);
16156 if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
16157 llvm_unreachable("Can't cast this!");
16158
16159 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
16160 }
16161
16162 case CK_IntegralComplexToReal: {
16163 ComplexValue C;
16164 if (!EvaluateComplex(SubExpr, C, Info))
16165 return false;
16166 return Success(C.getComplexIntReal(), E);
16167 }
16168
16169 case CK_FloatingToIntegral: {
16170 APFloat F(0.0);
16171 if (!EvaluateFloat(SubExpr, F, Info))
16172 return false;
16173
16174 APSInt Value;
16175 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
16176 return false;
16177 return Success(Value, E);
16178 }
16179 case CK_HLSLVectorTruncation: {
16180 APValue Val;
16181 if (!EvaluateVector(SubExpr, Val, Info))
16182 return Error(E);
16183 return Success(Val.getVectorElt(0), E);
16184 }
16185 }
16186
16187 llvm_unreachable("unknown cast resulting in integral value");
16188}
16189
16190bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
16191 if (E->getSubExpr()->getType()->isAnyComplexType()) {
16192 ComplexValue LV;
16193 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
16194 return false;
16195 if (!LV.isComplexInt())
16196 return Error(E);
16197 return Success(LV.getComplexIntReal(), E);
16198 }
16199
16200 return Visit(E->getSubExpr());
16201}
16202
16203bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
16204 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
16205 ComplexValue LV;
16206 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
16207 return false;
16208 if (!LV.isComplexInt())
16209 return Error(E);
16210 return Success(LV.getComplexIntImag(), E);
16211 }
16212
16213 VisitIgnoredValue(E->getSubExpr());
16214 return Success(0, E);
16215}
16216
16217bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
16218 return Success(E->getPackLength(), E);
16219}
16220
16221bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
16222 return Success(E->getValue(), E);
16223}
16224
16225bool IntExprEvaluator::VisitConceptSpecializationExpr(
16226 const ConceptSpecializationExpr *E) {
16227 return Success(E->isSatisfied(), E);
16228}
16229
16230bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) {
16231 return Success(E->isSatisfied(), E);
16232}
16233
16234bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
16235 switch (E->getOpcode()) {
16236 default:
16237 // Invalid unary operators
16238 return Error(E);
16239 case UO_Plus:
16240 // The result is just the value.
16241 return Visit(E->getSubExpr());
16242 case UO_Minus: {
16243 if (!Visit(E->getSubExpr())) return false;
16244 if (!Result.isFixedPoint())
16245 return Error(E);
16246 bool Overflowed;
16247 APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
16248 if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
16249 return false;
16250 return Success(Negated, E);
16251 }
16252 case UO_LNot: {
16253 bool bres;
16254 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
16255 return false;
16256 return Success(!bres, E);
16257 }
16258 }
16259}
16260
16261bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
16262 const Expr *SubExpr = E->getSubExpr();
16263 QualType DestType = E->getType();
16264 assert(DestType->isFixedPointType() &&
16265 "Expected destination type to be a fixed point type");
16266 auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
16267
16268 switch (E->getCastKind()) {
16269 case CK_FixedPointCast: {
16270 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
16271 if (!EvaluateFixedPoint(SubExpr, Src, Info))
16272 return false;
16273 bool Overflowed;
16274 APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
16275 if (Overflowed) {
16276 if (Info.checkingForUndefinedBehavior())
16277 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
16278 diag::warn_fixedpoint_constant_overflow)
16279 << Result.toString() << E->getType();
16280 if (!HandleOverflow(Info, E, Result, E->getType()))
16281 return false;
16282 }
16283 return Success(Result, E);
16284 }
16285 case CK_IntegralToFixedPoint: {
16286 APSInt Src;
16287 if (!EvaluateInteger(SubExpr, Src, Info))
16288 return false;
16289
16290 bool Overflowed;
16291 APFixedPoint IntResult = APFixedPoint::getFromIntValue(
16292 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
16293
16294 if (Overflowed) {
16295 if (Info.checkingForUndefinedBehavior())
16296 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
16297 diag::warn_fixedpoint_constant_overflow)
16298 << IntResult.toString() << E->getType();
16299 if (!HandleOverflow(Info, E, IntResult, E->getType()))
16300 return false;
16301 }
16302
16303 return Success(IntResult, E);
16304 }
16305 case CK_FloatingToFixedPoint: {
16306 APFloat Src(0.0);
16307 if (!EvaluateFloat(SubExpr, Src, Info))
16308 return false;
16309
16310 bool Overflowed;
16311 APFixedPoint Result = APFixedPoint::getFromFloatValue(
16312 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
16313
16314 if (Overflowed) {
16315 if (Info.checkingForUndefinedBehavior())
16316 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
16317 diag::warn_fixedpoint_constant_overflow)
16318 << Result.toString() << E->getType();
16319 if (!HandleOverflow(Info, E, Result, E->getType()))
16320 return false;
16321 }
16322
16323 return Success(Result, E);
16324 }
16325 case CK_NoOp:
16326 case CK_LValueToRValue:
16327 return ExprEvaluatorBaseTy::VisitCastExpr(E);
16328 default:
16329 return Error(E);
16330 }
16331}
16332
16333bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
16334 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
16335 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
16336
16337 const Expr *LHS = E->getLHS();
16338 const Expr *RHS = E->getRHS();
16339 FixedPointSemantics ResultFXSema =
16340 Info.Ctx.getFixedPointSemantics(E->getType());
16341
16342 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
16343 if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
16344 return false;
16345 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
16346 if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
16347 return false;
16348
16349 bool OpOverflow = false, ConversionOverflow = false;
16350 APFixedPoint Result(LHSFX.getSemantics());
16351 switch (E->getOpcode()) {
16352 case BO_Add: {
16353 Result = LHSFX.add(RHSFX, &OpOverflow)
16354 .convert(ResultFXSema, &ConversionOverflow);
16355 break;
16356 }
16357 case BO_Sub: {
16358 Result = LHSFX.sub(RHSFX, &OpOverflow)
16359 .convert(ResultFXSema, &ConversionOverflow);
16360 break;
16361 }
16362 case BO_Mul: {
16363 Result = LHSFX.mul(RHSFX, &OpOverflow)
16364 .convert(ResultFXSema, &ConversionOverflow);
16365 break;
16366 }
16367 case BO_Div: {
16368 if (RHSFX.getValue() == 0) {
16369 Info.FFDiag(E, diag::note_expr_divide_by_zero);
16370 return false;
16371 }
16372 Result = LHSFX.div(RHSFX, &OpOverflow)
16373 .convert(ResultFXSema, &ConversionOverflow);
16374 break;
16375 }
16376 case BO_Shl:
16377 case BO_Shr: {
16378 FixedPointSemantics LHSSema = LHSFX.getSemantics();
16379 llvm::APSInt RHSVal = RHSFX.getValue();
16380
16381 unsigned ShiftBW =
16382 LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding();
16383 unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1);
16384 // Embedded-C 4.1.6.2.2:
16385 // The right operand must be nonnegative and less than the total number
16386 // of (nonpadding) bits of the fixed-point operand ...
16387 if (RHSVal.isNegative())
16388 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal;
16389 else if (Amt != RHSVal)
16390 Info.CCEDiag(E, diag::note_constexpr_large_shift)
16391 << RHSVal << E->getType() << ShiftBW;
16392
16393 if (E->getOpcode() == BO_Shl)
16394 Result = LHSFX.shl(Amt, &OpOverflow);
16395 else
16396 Result = LHSFX.shr(Amt, &OpOverflow);
16397 break;
16398 }
16399 default:
16400 return false;
16401 }
16402 if (OpOverflow || ConversionOverflow) {
16403 if (Info.checkingForUndefinedBehavior())
16404 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
16405 diag::warn_fixedpoint_constant_overflow)
16406 << Result.toString() << E->getType();
16407 if (!HandleOverflow(Info, E, Result, E->getType()))
16408 return false;
16409 }
16410 return Success(Result, E);
16411}
16412
16413//===----------------------------------------------------------------------===//
16414// Float Evaluation
16415//===----------------------------------------------------------------------===//
16416
16417namespace {
16418class FloatExprEvaluator
16419 : public ExprEvaluatorBase<FloatExprEvaluator> {
16420 APFloat &Result;
16421public:
16422 FloatExprEvaluator(EvalInfo &info, APFloat &result)
16423 : ExprEvaluatorBaseTy(info), Result(result) {}
16424
16425 bool Success(const APValue &V, const Expr *e) {
16426 Result = V.getFloat();
16427 return true;
16428 }
16429
16430 bool ZeroInitialization(const Expr *E) {
16431 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
16432 return true;
16433 }
16434
16435 bool VisitCallExpr(const CallExpr *E);
16436
16437 bool VisitUnaryOperator(const UnaryOperator *E);
16438 bool VisitBinaryOperator(const BinaryOperator *E);
16439 bool VisitFloatingLiteral(const FloatingLiteral *E);
16440 bool VisitCastExpr(const CastExpr *E);
16441
16442 bool VisitUnaryReal(const UnaryOperator *E);
16443 bool VisitUnaryImag(const UnaryOperator *E);
16444
16445 // FIXME: Missing: array subscript of vector, member of vector
16446};
16447} // end anonymous namespace
16448
16449static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
16450 assert(!E->isValueDependent());
16451 assert(E->isPRValue() && E->getType()->isRealFloatingType());
16452 return FloatExprEvaluator(Info, Result).Visit(E);
16453}
16454
16455static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
16456 QualType ResultTy,
16457 const Expr *Arg,
16458 bool SNaN,
16459 llvm::APFloat &Result) {
16460 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
16461 if (!S) return false;
16462
16463 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
16464
16465 llvm::APInt fill;
16466
16467 // Treat empty strings as if they were zero.
16468 if (S->getString().empty())
16469 fill = llvm::APInt(32, 0);
16470 else if (S->getString().getAsInteger(0, fill))
16471 return false;
16472
16473 if (Context.getTargetInfo().isNan2008()) {
16474 if (SNaN)
16475 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
16476 else
16477 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
16478 } else {
16479 // Prior to IEEE 754-2008, architectures were allowed to choose whether
16480 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
16481 // a different encoding to what became a standard in 2008, and for pre-
16482 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
16483 // sNaN. This is now known as "legacy NaN" encoding.
16484 if (SNaN)
16485 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
16486 else
16487 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
16488 }
16489
16490 return true;
16491}
16492
16493bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
16494 if (!IsConstantEvaluatedBuiltinCall(E))
16495 return ExprEvaluatorBaseTy::VisitCallExpr(E);
16496
16497 switch (E->getBuiltinCallee()) {
16498 default:
16499 return false;
16500
16501 case Builtin::BI__builtin_huge_val:
16502 case Builtin::BI__builtin_huge_valf:
16503 case Builtin::BI__builtin_huge_vall:
16504 case Builtin::BI__builtin_huge_valf16:
16505 case Builtin::BI__builtin_huge_valf128:
16506 case Builtin::BI__builtin_inf:
16507 case Builtin::BI__builtin_inff:
16508 case Builtin::BI__builtin_infl:
16509 case Builtin::BI__builtin_inff16:
16510 case Builtin::BI__builtin_inff128: {
16511 const llvm::fltSemantics &Sem =
16512 Info.Ctx.getFloatTypeSemantics(E->getType());
16513 Result = llvm::APFloat::getInf(Sem);
16514 return true;
16515 }
16516
16517 case Builtin::BI__builtin_nans:
16518 case Builtin::BI__builtin_nansf:
16519 case Builtin::BI__builtin_nansl:
16520 case Builtin::BI__builtin_nansf16:
16521 case Builtin::BI__builtin_nansf128:
16522 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
16523 true, Result))
16524 return Error(E);
16525 return true;
16526
16527 case Builtin::BI__builtin_nan:
16528 case Builtin::BI__builtin_nanf:
16529 case Builtin::BI__builtin_nanl:
16530 case Builtin::BI__builtin_nanf16:
16531 case Builtin::BI__builtin_nanf128:
16532 // If this is __builtin_nan() turn this into a nan, otherwise we
16533 // can't constant fold it.
16534 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
16535 false, Result))
16536 return Error(E);
16537 return true;
16538
16539 case Builtin::BI__builtin_elementwise_abs:
16540 case Builtin::BI__builtin_fabs:
16541 case Builtin::BI__builtin_fabsf:
16542 case Builtin::BI__builtin_fabsl:
16543 case Builtin::BI__builtin_fabsf128:
16544 // The C standard says "fabs raises no floating-point exceptions,
16545 // even if x is a signaling NaN. The returned value is independent of
16546 // the current rounding direction mode." Therefore constant folding can
16547 // proceed without regard to the floating point settings.
16548 // Reference, WG14 N2478 F.10.4.3
16549 if (!EvaluateFloat(E->getArg(0), Result, Info))
16550 return false;
16551
16552 if (Result.isNegative())
16553 Result.changeSign();
16554 return true;
16555
16556 case Builtin::BI__arithmetic_fence:
16557 return EvaluateFloat(E->getArg(0), Result, Info);
16558
16559 // FIXME: Builtin::BI__builtin_powi
16560 // FIXME: Builtin::BI__builtin_powif
16561 // FIXME: Builtin::BI__builtin_powil
16562
16563 case Builtin::BI__builtin_copysign:
16564 case Builtin::BI__builtin_copysignf:
16565 case Builtin::BI__builtin_copysignl:
16566 case Builtin::BI__builtin_copysignf128: {
16567 APFloat RHS(0.);
16568 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
16569 !EvaluateFloat(E->getArg(1), RHS, Info))
16570 return false;
16571 Result.copySign(RHS);
16572 return true;
16573 }
16574
16575 case Builtin::BI__builtin_fmax:
16576 case Builtin::BI__builtin_fmaxf:
16577 case Builtin::BI__builtin_fmaxl:
16578 case Builtin::BI__builtin_fmaxf16:
16579 case Builtin::BI__builtin_fmaxf128: {
16580 APFloat RHS(0.);
16581 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
16582 !EvaluateFloat(E->getArg(1), RHS, Info))
16583 return false;
16584 Result = maxnum(Result, RHS);
16585 return true;
16586 }
16587
16588 case Builtin::BI__builtin_fmin:
16589 case Builtin::BI__builtin_fminf:
16590 case Builtin::BI__builtin_fminl:
16591 case Builtin::BI__builtin_fminf16:
16592 case Builtin::BI__builtin_fminf128: {
16593 APFloat RHS(0.);
16594 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
16595 !EvaluateFloat(E->getArg(1), RHS, Info))
16596 return false;
16597 Result = minnum(Result, RHS);
16598 return true;
16599 }
16600
16601 case Builtin::BI__builtin_fmaximum_num:
16602 case Builtin::BI__builtin_fmaximum_numf:
16603 case Builtin::BI__builtin_fmaximum_numl:
16604 case Builtin::BI__builtin_fmaximum_numf16:
16605 case Builtin::BI__builtin_fmaximum_numf128: {
16606 APFloat RHS(0.);
16607 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
16608 !EvaluateFloat(E->getArg(1), RHS, Info))
16609 return false;
16610 Result = maximumnum(Result, RHS);
16611 return true;
16612 }
16613
16614 case Builtin::BI__builtin_fminimum_num:
16615 case Builtin::BI__builtin_fminimum_numf:
16616 case Builtin::BI__builtin_fminimum_numl:
16617 case Builtin::BI__builtin_fminimum_numf16:
16618 case Builtin::BI__builtin_fminimum_numf128: {
16619 APFloat RHS(0.);
16620 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
16621 !EvaluateFloat(E->getArg(1), RHS, Info))
16622 return false;
16623 Result = minimumnum(Result, RHS);
16624 return true;
16625 }
16626
16627 case Builtin::BI__builtin_elementwise_fma: {
16628 if (!E->getArg(0)->isPRValue() || !E->getArg(1)->isPRValue() ||
16629 !E->getArg(2)->isPRValue()) {
16630 return false;
16631 }
16632 APFloat SourceY(0.), SourceZ(0.);
16633 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
16634 !EvaluateFloat(E->getArg(1), SourceY, Info) ||
16635 !EvaluateFloat(E->getArg(2), SourceZ, Info))
16636 return false;
16637 llvm::RoundingMode RM = getActiveRoundingMode(getEvalInfo(), E);
16638 (void)Result.fusedMultiplyAdd(SourceY, SourceZ, RM);
16639 return true;
16640 }
16641 }
16642}
16643
16644bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
16645 if (E->getSubExpr()->getType()->isAnyComplexType()) {
16646 ComplexValue CV;
16647 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
16648 return false;
16649 Result = CV.FloatReal;
16650 return true;
16651 }
16652
16653 return Visit(E->getSubExpr());
16654}
16655
16656bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
16657 if (E->getSubExpr()->getType()->isAnyComplexType()) {
16658 ComplexValue CV;
16659 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
16660 return false;
16661 Result = CV.FloatImag;
16662 return true;
16663 }
16664
16665 VisitIgnoredValue(E->getSubExpr());
16666 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
16667 Result = llvm::APFloat::getZero(Sem);
16668 return true;
16669}
16670
16671bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
16672 switch (E->getOpcode()) {
16673 default: return Error(E);
16674 case UO_Plus:
16675 return EvaluateFloat(E->getSubExpr(), Result, Info);
16676 case UO_Minus:
16677 // In C standard, WG14 N2478 F.3 p4
16678 // "the unary - raises no floating point exceptions,
16679 // even if the operand is signalling."
16680 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
16681 return false;
16682 Result.changeSign();
16683 return true;
16684 }
16685}
16686
16687bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
16688 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
16689 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
16690
16691 APFloat RHS(0.0);
16692 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
16693 if (!LHSOK && !Info.noteFailure())
16694 return false;
16695 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
16696 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
16697}
16698
16699bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
16700 Result = E->getValue();
16701 return true;
16702}
16703
16704bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
16705 const Expr* SubExpr = E->getSubExpr();
16706
16707 switch (E->getCastKind()) {
16708 default:
16709 return ExprEvaluatorBaseTy::VisitCastExpr(E);
16710
16711 case CK_IntegralToFloating: {
16712 APSInt IntResult;
16713 const FPOptions FPO = E->getFPFeaturesInEffect(
16714 Info.Ctx.getLangOpts());
16715 return EvaluateInteger(SubExpr, IntResult, Info) &&
16716 HandleIntToFloatCast(Info, E, FPO, SubExpr->getType(),
16717 IntResult, E->getType(), Result);
16718 }
16719
16720 case CK_FixedPointToFloating: {
16721 APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
16722 if (!EvaluateFixedPoint(SubExpr, FixResult, Info))
16723 return false;
16724 Result =
16725 FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->getType()));
16726 return true;
16727 }
16728
16729 case CK_FloatingCast: {
16730 if (!Visit(SubExpr))
16731 return false;
16732 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
16733 Result);
16734 }
16735
16736 case CK_FloatingComplexToReal: {
16737 ComplexValue V;
16738 if (!EvaluateComplex(SubExpr, V, Info))
16739 return false;
16740 Result = V.getComplexFloatReal();
16741 return true;
16742 }
16743 case CK_HLSLVectorTruncation: {
16744 APValue Val;
16745 if (!EvaluateVector(SubExpr, Val, Info))
16746 return Error(E);
16747 return Success(Val.getVectorElt(0), E);
16748 }
16749 }
16750}
16751
16752//===----------------------------------------------------------------------===//
16753// Complex Evaluation (for float and integer)
16754//===----------------------------------------------------------------------===//
16755
16756namespace {
16757class ComplexExprEvaluator
16758 : public ExprEvaluatorBase<ComplexExprEvaluator> {
16759 ComplexValue &Result;
16760
16761public:
16762 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
16763 : ExprEvaluatorBaseTy(info), Result(Result) {}
16764
16765 bool Success(const APValue &V, const Expr *e) {
16766 Result.setFrom(V);
16767 return true;
16768 }
16769
16770 bool ZeroInitialization(const Expr *E);
16771
16772 //===--------------------------------------------------------------------===//
16773 // Visitor Methods
16774 //===--------------------------------------------------------------------===//
16775
16776 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
16777 bool VisitCastExpr(const CastExpr *E);
16778 bool VisitBinaryOperator(const BinaryOperator *E);
16779 bool VisitUnaryOperator(const UnaryOperator *E);
16780 bool VisitInitListExpr(const InitListExpr *E);
16781 bool VisitCallExpr(const CallExpr *E);
16782};
16783} // end anonymous namespace
16784
16785static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
16786 EvalInfo &Info) {
16787 assert(!E->isValueDependent());
16788 assert(E->isPRValue() && E->getType()->isAnyComplexType());
16789 return ComplexExprEvaluator(Info, Result).Visit(E);
16790}
16791
16792bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
16793 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
16794 if (ElemTy->isRealFloatingType()) {
16795 Result.makeComplexFloat();
16796 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
16797 Result.FloatReal = Zero;
16798 Result.FloatImag = Zero;
16799 } else {
16800 Result.makeComplexInt();
16801 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
16802 Result.IntReal = Zero;
16803 Result.IntImag = Zero;
16804 }
16805 return true;
16806}
16807
16808bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
16809 const Expr* SubExpr = E->getSubExpr();
16810
16811 if (SubExpr->getType()->isRealFloatingType()) {
16812 Result.makeComplexFloat();
16813 APFloat &Imag = Result.FloatImag;
16814 if (!EvaluateFloat(SubExpr, Imag, Info))
16815 return false;
16816
16817 Result.FloatReal = APFloat(Imag.getSemantics());
16818 return true;
16819 } else {
16820 assert(SubExpr->getType()->isIntegerType() &&
16821 "Unexpected imaginary literal.");
16822
16823 Result.makeComplexInt();
16824 APSInt &Imag = Result.IntImag;
16825 if (!EvaluateInteger(SubExpr, Imag, Info))
16826 return false;
16827
16828 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
16829 return true;
16830 }
16831}
16832
16833bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
16834
16835 switch (E->getCastKind()) {
16836 case CK_BitCast:
16837 case CK_BaseToDerived:
16838 case CK_DerivedToBase:
16839 case CK_UncheckedDerivedToBase:
16840 case CK_Dynamic:
16841 case CK_ToUnion:
16842 case CK_ArrayToPointerDecay:
16843 case CK_FunctionToPointerDecay:
16844 case CK_NullToPointer:
16845 case CK_NullToMemberPointer:
16846 case CK_BaseToDerivedMemberPointer:
16847 case CK_DerivedToBaseMemberPointer:
16848 case CK_MemberPointerToBoolean:
16849 case CK_ReinterpretMemberPointer:
16850 case CK_ConstructorConversion:
16851 case CK_IntegralToPointer:
16852 case CK_PointerToIntegral:
16853 case CK_PointerToBoolean:
16854 case CK_ToVoid:
16855 case CK_VectorSplat:
16856 case CK_IntegralCast:
16857 case CK_BooleanToSignedIntegral:
16858 case CK_IntegralToBoolean:
16859 case CK_IntegralToFloating:
16860 case CK_FloatingToIntegral:
16861 case CK_FloatingToBoolean:
16862 case CK_FloatingCast:
16863 case CK_CPointerToObjCPointerCast:
16864 case CK_BlockPointerToObjCPointerCast:
16865 case CK_AnyPointerToBlockPointerCast:
16866 case CK_ObjCObjectLValueCast:
16867 case CK_FloatingComplexToReal:
16868 case CK_FloatingComplexToBoolean:
16869 case CK_IntegralComplexToReal:
16870 case CK_IntegralComplexToBoolean:
16871 case CK_ARCProduceObject:
16872 case CK_ARCConsumeObject:
16873 case CK_ARCReclaimReturnedObject:
16874 case CK_ARCExtendBlockObject:
16875 case CK_CopyAndAutoreleaseBlockObject:
16876 case CK_BuiltinFnToFnPtr:
16877 case CK_ZeroToOCLOpaqueType:
16878 case CK_NonAtomicToAtomic:
16879 case CK_AddressSpaceConversion:
16880 case CK_IntToOCLSampler:
16881 case CK_FloatingToFixedPoint:
16882 case CK_FixedPointToFloating:
16883 case CK_FixedPointCast:
16884 case CK_FixedPointToBoolean:
16885 case CK_FixedPointToIntegral:
16886 case CK_IntegralToFixedPoint:
16887 case CK_MatrixCast:
16888 case CK_HLSLVectorTruncation:
16889 case CK_HLSLElementwiseCast:
16890 case CK_HLSLAggregateSplatCast:
16891 llvm_unreachable("invalid cast kind for complex value");
16892
16893 case CK_LValueToRValue:
16894 case CK_AtomicToNonAtomic:
16895 case CK_NoOp:
16896 case CK_LValueToRValueBitCast:
16897 case CK_HLSLArrayRValue:
16898 return ExprEvaluatorBaseTy::VisitCastExpr(E);
16899
16900 case CK_Dependent:
16901 case CK_LValueBitCast:
16902 case CK_UserDefinedConversion:
16903 return Error(E);
16904
16905 case CK_FloatingRealToComplex: {
16906 APFloat &Real = Result.FloatReal;
16907 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
16908 return false;
16909
16910 Result.makeComplexFloat();
16911 Result.FloatImag = APFloat(Real.getSemantics());
16912 return true;
16913 }
16914
16915 case CK_FloatingComplexCast: {
16916 if (!Visit(E->getSubExpr()))
16917 return false;
16918
16919 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
16920 QualType From
16921 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
16922
16923 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
16924 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
16925 }
16926
16927 case CK_FloatingComplexToIntegralComplex: {
16928 if (!Visit(E->getSubExpr()))
16929 return false;
16930
16931 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
16932 QualType From
16933 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
16934 Result.makeComplexInt();
16935 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
16936 To, Result.IntReal) &&
16937 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
16938 To, Result.IntImag);
16939 }
16940
16941 case CK_IntegralRealToComplex: {
16942 APSInt &Real = Result.IntReal;
16943 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
16944 return false;
16945
16946 Result.makeComplexInt();
16947 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
16948 return true;
16949 }
16950
16951 case CK_IntegralComplexCast: {
16952 if (!Visit(E->getSubExpr()))
16953 return false;
16954
16955 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
16956 QualType From
16957 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
16958
16959 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
16960 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
16961 return true;
16962 }
16963
16964 case CK_IntegralComplexToFloatingComplex: {
16965 if (!Visit(E->getSubExpr()))
16966 return false;
16967
16968 const FPOptions FPO = E->getFPFeaturesInEffect(
16969 Info.Ctx.getLangOpts());
16970 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
16971 QualType From
16972 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
16973 Result.makeComplexFloat();
16974 return HandleIntToFloatCast(Info, E, FPO, From, Result.IntReal,
16975 To, Result.FloatReal) &&
16976 HandleIntToFloatCast(Info, E, FPO, From, Result.IntImag,
16977 To, Result.FloatImag);
16978 }
16979 }
16980
16981 llvm_unreachable("unknown cast resulting in complex value");
16982}
16983
16984void HandleComplexComplexMul(APFloat A, APFloat B, APFloat C, APFloat D,
16985 APFloat &ResR, APFloat &ResI) {
16986 // This is an implementation of complex multiplication according to the
16987 // constraints laid out in C11 Annex G. The implementation uses the
16988 // following naming scheme:
16989 // (a + ib) * (c + id)
16990
16991 APFloat AC = A * C;
16992 APFloat BD = B * D;
16993 APFloat AD = A * D;
16994 APFloat BC = B * C;
16995 ResR = AC - BD;
16996 ResI = AD + BC;
16997 if (ResR.isNaN() && ResI.isNaN()) {
16998 bool Recalc = false;
16999 if (A.isInfinity() || B.isInfinity()) {
17000 A = APFloat::copySign(APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0),
17001 A);
17002 B = APFloat::copySign(APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0),
17003 B);
17004 if (C.isNaN())
17005 C = APFloat::copySign(APFloat(C.getSemantics()), C);
17006 if (D.isNaN())
17007 D = APFloat::copySign(APFloat(D.getSemantics()), D);
17008 Recalc = true;
17009 }
17010 if (C.isInfinity() || D.isInfinity()) {
17011 C = APFloat::copySign(APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0),
17012 C);
17013 D = APFloat::copySign(APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0),
17014 D);
17015 if (A.isNaN())
17016 A = APFloat::copySign(APFloat(A.getSemantics()), A);
17017 if (B.isNaN())
17018 B = APFloat::copySign(APFloat(B.getSemantics()), B);
17019 Recalc = true;
17020 }
17021 if (!Recalc && (AC.isInfinity() || BD.isInfinity() || AD.isInfinity() ||
17022 BC.isInfinity())) {
17023 if (A.isNaN())
17024 A = APFloat::copySign(APFloat(A.getSemantics()), A);
17025 if (B.isNaN())
17026 B = APFloat::copySign(APFloat(B.getSemantics()), B);
17027 if (C.isNaN())
17028 C = APFloat::copySign(APFloat(C.getSemantics()), C);
17029 if (D.isNaN())
17030 D = APFloat::copySign(APFloat(D.getSemantics()), D);
17031 Recalc = true;
17032 }
17033 if (Recalc) {
17034 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
17035 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
17036 }
17037 }
17038}
17039
17040void HandleComplexComplexDiv(APFloat A, APFloat B, APFloat C, APFloat D,
17041 APFloat &ResR, APFloat &ResI) {
17042 // This is an implementation of complex division according to the
17043 // constraints laid out in C11 Annex G. The implementation uses the
17044 // following naming scheme:
17045 // (a + ib) / (c + id)
17046
17047 int DenomLogB = 0;
17048 APFloat MaxCD = maxnum(abs(C), abs(D));
17049 if (MaxCD.isFinite()) {
17050 DenomLogB = ilogb(MaxCD);
17051 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
17052 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
17053 }
17054 APFloat Denom = C * C + D * D;
17055 ResR =
17056 scalbn((A * C + B * D) / Denom, -DenomLogB, APFloat::rmNearestTiesToEven);
17057 ResI =
17058 scalbn((B * C - A * D) / Denom, -DenomLogB, APFloat::rmNearestTiesToEven);
17059 if (ResR.isNaN() && ResI.isNaN()) {
17060 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
17061 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
17062 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
17063 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
17064 D.isFinite()) {
17065 A = APFloat::copySign(APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0),
17066 A);
17067 B = APFloat::copySign(APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0),
17068 B);
17069 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
17070 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
17071 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
17072 C = APFloat::copySign(APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0),
17073 C);
17074 D = APFloat::copySign(APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0),
17075 D);
17076 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
17077 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
17078 }
17079 }
17080}
17081
17082bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
17083 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
17084 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
17085
17086 // Track whether the LHS or RHS is real at the type system level. When this is
17087 // the case we can simplify our evaluation strategy.
17088 bool LHSReal = false, RHSReal = false;
17089
17090 bool LHSOK;
17091 if (E->getLHS()->getType()->isRealFloatingType()) {
17092 LHSReal = true;
17093 APFloat &Real = Result.FloatReal;
17094 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
17095 if (LHSOK) {
17096 Result.makeComplexFloat();
17097 Result.FloatImag = APFloat(Real.getSemantics());
17098 }
17099 } else {
17100 LHSOK = Visit(E->getLHS());
17101 }
17102 if (!LHSOK && !Info.noteFailure())
17103 return false;
17104
17105 ComplexValue RHS;
17106 if (E->getRHS()->getType()->isRealFloatingType()) {
17107 RHSReal = true;
17108 APFloat &Real = RHS.FloatReal;
17109 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
17110 return false;
17111 RHS.makeComplexFloat();
17112 RHS.FloatImag = APFloat(Real.getSemantics());
17113 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
17114 return false;
17115
17116 assert(!(LHSReal && RHSReal) &&
17117 "Cannot have both operands of a complex operation be real.");
17118 switch (E->getOpcode()) {
17119 default: return Error(E);
17120 case BO_Add:
17121 if (Result.isComplexFloat()) {
17122 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
17123 APFloat::rmNearestTiesToEven);
17124 if (LHSReal)
17125 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
17126 else if (!RHSReal)
17127 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
17128 APFloat::rmNearestTiesToEven);
17129 } else {
17130 Result.getComplexIntReal() += RHS.getComplexIntReal();
17131 Result.getComplexIntImag() += RHS.getComplexIntImag();
17132 }
17133 break;
17134 case BO_Sub:
17135 if (Result.isComplexFloat()) {
17136 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
17137 APFloat::rmNearestTiesToEven);
17138 if (LHSReal) {
17139 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
17140 Result.getComplexFloatImag().changeSign();
17141 } else if (!RHSReal) {
17142 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
17143 APFloat::rmNearestTiesToEven);
17144 }
17145 } else {
17146 Result.getComplexIntReal() -= RHS.getComplexIntReal();
17147 Result.getComplexIntImag() -= RHS.getComplexIntImag();
17148 }
17149 break;
17150 case BO_Mul:
17151 if (Result.isComplexFloat()) {
17152 // This is an implementation of complex multiplication according to the
17153 // constraints laid out in C11 Annex G. The implementation uses the
17154 // following naming scheme:
17155 // (a + ib) * (c + id)
17156 ComplexValue LHS = Result;
17157 APFloat &A = LHS.getComplexFloatReal();
17158 APFloat &B = LHS.getComplexFloatImag();
17159 APFloat &C = RHS.getComplexFloatReal();
17160 APFloat &D = RHS.getComplexFloatImag();
17161 APFloat &ResR = Result.getComplexFloatReal();
17162 APFloat &ResI = Result.getComplexFloatImag();
17163 if (LHSReal) {
17164 assert(!RHSReal && "Cannot have two real operands for a complex op!");
17165 ResR = A;
17166 ResI = A;
17167 // ResR = A * C;
17168 // ResI = A * D;
17169 if (!handleFloatFloatBinOp(Info, E, ResR, BO_Mul, C) ||
17170 !handleFloatFloatBinOp(Info, E, ResI, BO_Mul, D))
17171 return false;
17172 } else if (RHSReal) {
17173 // ResR = C * A;
17174 // ResI = C * B;
17175 ResR = C;
17176 ResI = C;
17177 if (!handleFloatFloatBinOp(Info, E, ResR, BO_Mul, A) ||
17178 !handleFloatFloatBinOp(Info, E, ResI, BO_Mul, B))
17179 return false;
17180 } else {
17181 HandleComplexComplexMul(A, B, C, D, ResR, ResI);
17182 }
17183 } else {
17184 ComplexValue LHS = Result;
17185 Result.getComplexIntReal() =
17186 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
17187 LHS.getComplexIntImag() * RHS.getComplexIntImag());
17188 Result.getComplexIntImag() =
17189 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
17190 LHS.getComplexIntImag() * RHS.getComplexIntReal());
17191 }
17192 break;
17193 case BO_Div:
17194 if (Result.isComplexFloat()) {
17195 // This is an implementation of complex division according to the
17196 // constraints laid out in C11 Annex G. The implementation uses the
17197 // following naming scheme:
17198 // (a + ib) / (c + id)
17199 ComplexValue LHS = Result;
17200 APFloat &A = LHS.getComplexFloatReal();
17201 APFloat &B = LHS.getComplexFloatImag();
17202 APFloat &C = RHS.getComplexFloatReal();
17203 APFloat &D = RHS.getComplexFloatImag();
17204 APFloat &ResR = Result.getComplexFloatReal();
17205 APFloat &ResI = Result.getComplexFloatImag();
17206 if (RHSReal) {
17207 ResR = A;
17208 ResI = B;
17209 // ResR = A / C;
17210 // ResI = B / C;
17211 if (!handleFloatFloatBinOp(Info, E, ResR, BO_Div, C) ||
17212 !handleFloatFloatBinOp(Info, E, ResI, BO_Div, C))
17213 return false;
17214 } else {
17215 if (LHSReal) {
17216 // No real optimizations we can do here, stub out with zero.
17217 B = APFloat::getZero(A.getSemantics());
17218 }
17219 HandleComplexComplexDiv(A, B, C, D, ResR, ResI);
17220 }
17221 } else {
17222 ComplexValue LHS = Result;
17223 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
17224 RHS.getComplexIntImag() * RHS.getComplexIntImag();
17225 if (Den.isZero())
17226 return Error(E, diag::note_expr_divide_by_zero);
17227
17228 Result.getComplexIntReal() =
17229 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
17230 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
17231 Result.getComplexIntImag() =
17232 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
17233 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
17234 }
17235 break;
17236 }
17237
17238 return true;
17239}
17240
17241bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
17242 // Get the operand value into 'Result'.
17243 if (!Visit(E->getSubExpr()))
17244 return false;
17245
17246 switch (E->getOpcode()) {
17247 default:
17248 return Error(E);
17249 case UO_Extension:
17250 return true;
17251 case UO_Plus:
17252 // The result is always just the subexpr.
17253 return true;
17254 case UO_Minus:
17255 if (Result.isComplexFloat()) {
17256 Result.getComplexFloatReal().changeSign();
17257 Result.getComplexFloatImag().changeSign();
17258 }
17259 else {
17260 Result.getComplexIntReal() = -Result.getComplexIntReal();
17261 Result.getComplexIntImag() = -Result.getComplexIntImag();
17262 }
17263 return true;
17264 case UO_Not:
17265 if (Result.isComplexFloat())
17266 Result.getComplexFloatImag().changeSign();
17267 else
17268 Result.getComplexIntImag() = -Result.getComplexIntImag();
17269 return true;
17270 }
17271}
17272
17273bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
17274 if (E->getNumInits() == 2) {
17275 if (E->getType()->isComplexType()) {
17276 Result.makeComplexFloat();
17277 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
17278 return false;
17279 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
17280 return false;
17281 } else {
17282 Result.makeComplexInt();
17283 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
17284 return false;
17285 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
17286 return false;
17287 }
17288 return true;
17289 }
17290 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
17291}
17292
17293bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) {
17294 if (!IsConstantEvaluatedBuiltinCall(E))
17295 return ExprEvaluatorBaseTy::VisitCallExpr(E);
17296
17297 switch (E->getBuiltinCallee()) {
17298 case Builtin::BI__builtin_complex:
17299 Result.makeComplexFloat();
17300 if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info))
17301 return false;
17302 if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info))
17303 return false;
17304 return true;
17305
17306 default:
17307 return false;
17308 }
17309}
17310
17311//===----------------------------------------------------------------------===//
17312// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
17313// implicit conversion.
17314//===----------------------------------------------------------------------===//
17315
17316namespace {
17317class AtomicExprEvaluator :
17318 public ExprEvaluatorBase<AtomicExprEvaluator> {
17319 const LValue *This;
17320 APValue &Result;
17321public:
17322 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
17323 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
17324
17325 bool Success(const APValue &V, const Expr *E) {
17326 Result = V;
17327 return true;
17328 }
17329
17330 bool ZeroInitialization(const Expr *E) {
17331 ImplicitValueInitExpr VIE(
17332 E->getType()->castAs<AtomicType>()->getValueType());
17333 // For atomic-qualified class (and array) types in C++, initialize the
17334 // _Atomic-wrapped subobject directly, in-place.
17335 return This ? EvaluateInPlace(Result, Info, *This, &VIE)
17336 : Evaluate(Result, Info, &VIE);
17337 }
17338
17339 bool VisitCastExpr(const CastExpr *E) {
17340 switch (E->getCastKind()) {
17341 default:
17342 return ExprEvaluatorBaseTy::VisitCastExpr(E);
17343 case CK_NullToPointer:
17344 VisitIgnoredValue(E->getSubExpr());
17345 return ZeroInitialization(E);
17346 case CK_NonAtomicToAtomic:
17347 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
17348 : Evaluate(Result, Info, E->getSubExpr());
17349 }
17350 }
17351};
17352} // end anonymous namespace
17353
17354static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
17355 EvalInfo &Info) {
17356 assert(!E->isValueDependent());
17357 assert(E->isPRValue() && E->getType()->isAtomicType());
17358 return AtomicExprEvaluator(Info, This, Result).Visit(E);
17359}
17360
17361//===----------------------------------------------------------------------===//
17362// Void expression evaluation, primarily for a cast to void on the LHS of a
17363// comma operator
17364//===----------------------------------------------------------------------===//
17365
17366namespace {
17367class VoidExprEvaluator
17368 : public ExprEvaluatorBase<VoidExprEvaluator> {
17369public:
17370 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
17371
17372 bool Success(const APValue &V, const Expr *e) { return true; }
17373
17374 bool ZeroInitialization(const Expr *E) { return true; }
17375
17376 bool VisitCastExpr(const CastExpr *E) {
17377 switch (E->getCastKind()) {
17378 default:
17379 return ExprEvaluatorBaseTy::VisitCastExpr(E);
17380 case CK_ToVoid:
17381 VisitIgnoredValue(E->getSubExpr());
17382 return true;
17383 }
17384 }
17385
17386 bool VisitCallExpr(const CallExpr *E) {
17387 if (!IsConstantEvaluatedBuiltinCall(E))
17388 return ExprEvaluatorBaseTy::VisitCallExpr(E);
17389
17390 switch (E->getBuiltinCallee()) {
17391 case Builtin::BI__assume:
17392 case Builtin::BI__builtin_assume:
17393 // The argument is not evaluated!
17394 return true;
17395
17396 case Builtin::BI__builtin_operator_delete:
17397 return HandleOperatorDeleteCall(Info, E);
17398
17399 default:
17400 return false;
17401 }
17402 }
17403
17404 bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
17405};
17406} // end anonymous namespace
17407
17408bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
17409 // We cannot speculatively evaluate a delete expression.
17410 if (Info.SpeculativeEvaluationDepth)
17411 return false;
17412
17413 FunctionDecl *OperatorDelete = E->getOperatorDelete();
17414 if (!OperatorDelete
17415 ->isUsableAsGlobalAllocationFunctionInConstantEvaluation()) {
17416 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
17417 << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;
17418 return false;
17419 }
17420
17421 const Expr *Arg = E->getArgument();
17422
17423 LValue Pointer;
17424 if (!EvaluatePointer(Arg, Pointer, Info))
17425 return false;
17426 if (Pointer.Designator.Invalid)
17427 return false;
17428
17429 // Deleting a null pointer has no effect.
17430 if (Pointer.isNullPointer()) {
17431 // This is the only case where we need to produce an extension warning:
17432 // the only other way we can succeed is if we find a dynamic allocation,
17433 // and we will have warned when we allocated it in that case.
17434 if (!Info.getLangOpts().CPlusPlus20)
17435 Info.CCEDiag(E, diag::note_constexpr_new);
17436 return true;
17437 }
17438
17439 std::optional<DynAlloc *> Alloc = CheckDeleteKind(
17440 Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New);
17441 if (!Alloc)
17442 return false;
17443 QualType AllocType = Pointer.Base.getDynamicAllocType();
17444
17445 // For the non-array case, the designator must be empty if the static type
17446 // does not have a virtual destructor.
17447 if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 &&
17449 Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor)
17450 << Arg->getType()->getPointeeType() << AllocType;
17451 return false;
17452 }
17453
17454 // For a class type with a virtual destructor, the selected operator delete
17455 // is the one looked up when building the destructor.
17456 if (!E->isArrayForm() && !E->isGlobalDelete()) {
17457 const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType);
17458 if (VirtualDelete &&
17459 !VirtualDelete
17460 ->isUsableAsGlobalAllocationFunctionInConstantEvaluation()) {
17461 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
17462 << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete;
17463 return false;
17464 }
17465 }
17466
17467 if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(),
17468 (*Alloc)->Value, AllocType))
17469 return false;
17470
17471 if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) {
17472 // The element was already erased. This means the destructor call also
17473 // deleted the object.
17474 // FIXME: This probably results in undefined behavior before we get this
17475 // far, and should be diagnosed elsewhere first.
17476 Info.FFDiag(E, diag::note_constexpr_double_delete);
17477 return false;
17478 }
17479
17480 return true;
17481}
17482
17483static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
17484 assert(!E->isValueDependent());
17485 assert(E->isPRValue() && E->getType()->isVoidType());
17486 return VoidExprEvaluator(Info).Visit(E);
17487}
17488
17489//===----------------------------------------------------------------------===//
17490// Top level Expr::EvaluateAsRValue method.
17491//===----------------------------------------------------------------------===//
17492
17493static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
17494 assert(!E->isValueDependent());
17495 // In C, function designators are not lvalues, but we evaluate them as if they
17496 // are.
17497 QualType T = E->getType();
17498 if (E->isGLValue() || T->isFunctionType()) {
17499 LValue LV;
17500 if (!EvaluateLValue(E, LV, Info))
17501 return false;
17502 LV.moveInto(Result);
17503 } else if (T->isVectorType()) {
17504 if (!EvaluateVector(E, Result, Info))
17505 return false;
17506 } else if (T->isIntegralOrEnumerationType()) {
17507 if (!IntExprEvaluator(Info, Result).Visit(E))
17508 return false;
17509 } else if (T->hasPointerRepresentation()) {
17510 LValue LV;
17511 if (!EvaluatePointer(E, LV, Info))
17512 return false;
17513 LV.moveInto(Result);
17514 } else if (T->isRealFloatingType()) {
17515 llvm::APFloat F(0.0);
17516 if (!EvaluateFloat(E, F, Info))
17517 return false;
17518 Result = APValue(F);
17519 } else if (T->isAnyComplexType()) {
17520 ComplexValue C;
17521 if (!EvaluateComplex(E, C, Info))
17522 return false;
17523 C.moveInto(Result);
17524 } else if (T->isFixedPointType()) {
17525 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
17526 } else if (T->isMemberPointerType()) {
17527 MemberPtr P;
17528 if (!EvaluateMemberPointer(E, P, Info))
17529 return false;
17530 P.moveInto(Result);
17531 return true;
17532 } else if (T->isArrayType()) {
17533 LValue LV;
17534 APValue &Value =
17535 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
17536 if (!EvaluateArray(E, LV, Value, Info))
17537 return false;
17538 Result = Value;
17539 } else if (T->isRecordType()) {
17540 LValue LV;
17541 APValue &Value =
17542 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
17543 if (!EvaluateRecord(E, LV, Value, Info))
17544 return false;
17545 Result = Value;
17546 } else if (T->isVoidType()) {
17547 if (!Info.getLangOpts().CPlusPlus11)
17548 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
17549 << E->getType();
17550 if (!EvaluateVoid(E, Info))
17551 return false;
17552 } else if (T->isAtomicType()) {
17553 QualType Unqual = T.getAtomicUnqualifiedType();
17554 if (Unqual->isArrayType() || Unqual->isRecordType()) {
17555 LValue LV;
17556 APValue &Value = Info.CurrentCall->createTemporary(
17557 E, Unqual, ScopeKind::FullExpression, LV);
17558 if (!EvaluateAtomic(E, &LV, Value, Info))
17559 return false;
17560 Result = Value;
17561 } else {
17562 if (!EvaluateAtomic(E, nullptr, Result, Info))
17563 return false;
17564 }
17565 } else if (Info.getLangOpts().CPlusPlus11) {
17566 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
17567 return false;
17568 } else {
17569 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
17570 return false;
17571 }
17572
17573 return true;
17574}
17575
17576/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
17577/// cases, the in-place evaluation is essential, since later initializers for
17578/// an object can indirectly refer to subobjects which were initialized earlier.
17579static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
17580 const Expr *E, bool AllowNonLiteralTypes) {
17581 assert(!E->isValueDependent());
17582
17583 // Normally expressions passed to EvaluateInPlace have a type, but not when
17584 // a VarDecl initializer is evaluated before the untyped ParenListExpr is
17585 // replaced with a CXXConstructExpr. This can happen in LLDB.
17586 if (E->getType().isNull())
17587 return false;
17588
17589 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
17590 return false;
17591
17592 if (E->isPRValue()) {
17593 // Evaluate arrays and record types in-place, so that later initializers can
17594 // refer to earlier-initialized members of the object.
17595 QualType T = E->getType();
17596 if (T->isArrayType())
17597 return EvaluateArray(E, This, Result, Info);
17598 else if (T->isRecordType())
17599 return EvaluateRecord(E, This, Result, Info);
17600 else if (T->isAtomicType()) {
17601 QualType Unqual = T.getAtomicUnqualifiedType();
17602 if (Unqual->isArrayType() || Unqual->isRecordType())
17603 return EvaluateAtomic(E, &This, Result, Info);
17604 }
17605 }
17606
17607 // For any other type, in-place evaluation is unimportant.
17608 return Evaluate(Result, Info, E);
17609}
17610
17611/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
17612/// lvalue-to-rvalue cast if it is an lvalue.
17613static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
17614 assert(!E->isValueDependent());
17615
17616 if (E->getType().isNull())
17617 return false;
17618
17619 if (!CheckLiteralType(Info, E))
17620 return false;
17621
17622 if (Info.EnableNewConstInterp) {
17623 if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result))
17624 return false;
17625 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
17626 ConstantExprKind::Normal);
17627 }
17628
17629 if (!::Evaluate(Result, Info, E))
17630 return false;
17631
17632 // Implicit lvalue-to-rvalue cast.
17633 if (E->isGLValue()) {
17634 LValue LV;
17635 LV.setFrom(Info.Ctx, Result);
17636 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
17637 return false;
17638 }
17639
17640 // Check this core constant expression is a constant expression.
17641 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
17642 ConstantExprKind::Normal) &&
17643 CheckMemoryLeaks(Info);
17644}
17645
17646static bool FastEvaluateAsRValue(const Expr *Exp, APValue &Result,
17647 const ASTContext &Ctx, bool &IsConst) {
17648 // Fast-path evaluations of integer literals, since we sometimes see files
17649 // containing vast quantities of these.
17650 if (const auto *L = dyn_cast<IntegerLiteral>(Exp)) {
17651 Result =
17652 APValue(APSInt(L->getValue(), L->getType()->isUnsignedIntegerType()));
17653 IsConst = true;
17654 return true;
17655 }
17656
17657 if (const auto *L = dyn_cast<CXXBoolLiteralExpr>(Exp)) {
17658 Result = APValue(APSInt(APInt(1, L->getValue())));
17659 IsConst = true;
17660 return true;
17661 }
17662
17663 if (const auto *FL = dyn_cast<FloatingLiteral>(Exp)) {
17664 Result = APValue(FL->getValue());
17665 IsConst = true;
17666 return true;
17667 }
17668
17669 if (const auto *L = dyn_cast<CharacterLiteral>(Exp)) {
17670 Result = APValue(Ctx.MakeIntValue(L->getValue(), L->getType()));
17671 IsConst = true;
17672 return true;
17673 }
17674
17675 if (const auto *CE = dyn_cast<ConstantExpr>(Exp)) {
17676 if (CE->hasAPValueResult()) {
17677 APValue APV = CE->getAPValueResult();
17678 if (!APV.isLValue()) {
17679 Result = std::move(APV);
17680 IsConst = true;
17681 return true;
17682 }
17683 }
17684
17685 // The SubExpr is usually just an IntegerLiteral.
17686 return FastEvaluateAsRValue(CE->getSubExpr(), Result, Ctx, IsConst);
17687 }
17688
17689 // This case should be rare, but we need to check it before we check on
17690 // the type below.
17691 if (Exp->getType().isNull()) {
17692 IsConst = false;
17693 return true;
17694 }
17695
17696 return false;
17697}
17698
17701 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
17702 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
17703}
17704
17705static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
17706 const ASTContext &Ctx, EvalInfo &Info) {
17707 assert(!E->isValueDependent());
17708 bool IsConst;
17709 if (FastEvaluateAsRValue(E, Result.Val, Ctx, IsConst))
17710 return IsConst;
17711
17712 return EvaluateAsRValue(Info, E, Result.Val);
17713}
17714
17716 const ASTContext &Ctx,
17717 Expr::SideEffectsKind AllowSideEffects,
17718 EvalInfo &Info) {
17719 assert(!E->isValueDependent());
17721 return false;
17722
17723 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
17724 !ExprResult.Val.isInt() ||
17725 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
17726 return false;
17727
17728 return true;
17729}
17730
17732 const ASTContext &Ctx,
17733 Expr::SideEffectsKind AllowSideEffects,
17734 EvalInfo &Info) {
17735 assert(!E->isValueDependent());
17736 if (!E->getType()->isFixedPointType())
17737 return false;
17738
17739 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
17740 return false;
17741
17742 if (!ExprResult.Val.isFixedPoint() ||
17743 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
17744 return false;
17745
17746 return true;
17747}
17748
17749/// EvaluateAsRValue - Return true if this is a constant which we can fold using
17750/// any crazy technique (that has nothing to do with language standards) that
17751/// we want to. If this function returns true, it returns the folded constant
17752/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
17753/// will be applied to the result.
17755 bool InConstantContext) const {
17756 assert(!isValueDependent() &&
17757 "Expression evaluator can't be called on a dependent expression.");
17758 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsRValue");
17759 EvalInfo Info(Ctx, Result, EvaluationMode::IgnoreSideEffects);
17760 Info.InConstantContext = InConstantContext;
17761 return ::EvaluateAsRValue(this, Result, Ctx, Info);
17762}
17763
17765 bool InConstantContext) const {
17766 assert(!isValueDependent() &&
17767 "Expression evaluator can't be called on a dependent expression.");
17768 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsBooleanCondition");
17769 EvalResult Scratch;
17770 return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
17771 HandleConversionToBool(Scratch.Val, Result);
17772}
17773
17775 SideEffectsKind AllowSideEffects,
17776 bool InConstantContext) const {
17777 assert(!isValueDependent() &&
17778 "Expression evaluator can't be called on a dependent expression.");
17779 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsInt");
17780 EvalInfo Info(Ctx, Result, EvaluationMode::IgnoreSideEffects);
17781 Info.InConstantContext = InConstantContext;
17782 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
17783}
17784
17786 SideEffectsKind AllowSideEffects,
17787 bool InConstantContext) const {
17788 assert(!isValueDependent() &&
17789 "Expression evaluator can't be called on a dependent expression.");
17790 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFixedPoint");
17791 EvalInfo Info(Ctx, Result, EvaluationMode::IgnoreSideEffects);
17792 Info.InConstantContext = InConstantContext;
17793 return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
17794}
17795
17796bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
17797 SideEffectsKind AllowSideEffects,
17798 bool InConstantContext) const {
17799 assert(!isValueDependent() &&
17800 "Expression evaluator can't be called on a dependent expression.");
17801
17802 if (!getType()->isRealFloatingType())
17803 return false;
17804
17805 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFloat");
17807 if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
17808 !ExprResult.Val.isFloat() ||
17809 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
17810 return false;
17811
17812 Result = ExprResult.Val.getFloat();
17813 return true;
17814}
17815
17817 bool InConstantContext) const {
17818 assert(!isValueDependent() &&
17819 "Expression evaluator can't be called on a dependent expression.");
17820
17821 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsLValue");
17822 EvalInfo Info(Ctx, Result, EvaluationMode::ConstantFold);
17823 Info.InConstantContext = InConstantContext;
17824 LValue LV;
17825 CheckedTemporaries CheckedTemps;
17826
17827 if (Info.EnableNewConstInterp) {
17828 if (!Info.Ctx.getInterpContext().evaluate(Info, this, Result.Val,
17829 ConstantExprKind::Normal))
17830 return false;
17831
17832 LV.setFrom(Ctx, Result.Val);
17834 Info, getExprLoc(), Ctx.getLValueReferenceType(getType()), LV,
17835 ConstantExprKind::Normal, CheckedTemps);
17836 }
17837
17838 if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() ||
17839 Result.HasSideEffects ||
17842 ConstantExprKind::Normal, CheckedTemps))
17843 return false;
17844
17845 LV.moveInto(Result.Val);
17846 return true;
17847}
17848
17850 APValue DestroyedValue, QualType Type,
17851 SourceLocation Loc, Expr::EvalStatus &EStatus,
17852 bool IsConstantDestruction) {
17853 EvalInfo Info(Ctx, EStatus,
17854 IsConstantDestruction ? EvaluationMode::ConstantExpression
17856 Info.setEvaluatingDecl(Base, DestroyedValue,
17857 EvalInfo::EvaluatingDeclKind::Dtor);
17858 Info.InConstantContext = IsConstantDestruction;
17859
17860 LValue LVal;
17861 LVal.set(Base);
17862
17863 if (!HandleDestruction(Info, Loc, Base, DestroyedValue, Type) ||
17864 EStatus.HasSideEffects)
17865 return false;
17866
17867 if (!Info.discardCleanups())
17868 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
17869
17870 return true;
17871}
17872
17874 ConstantExprKind Kind) const {
17875 assert(!isValueDependent() &&
17876 "Expression evaluator can't be called on a dependent expression.");
17877 bool IsConst;
17878 if (FastEvaluateAsRValue(this, Result.Val, Ctx, IsConst) &&
17879 Result.Val.hasValue())
17880 return true;
17881
17882 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsConstantExpr");
17884 EvalInfo Info(Ctx, Result, EM);
17885 Info.InConstantContext = true;
17886
17887 if (Info.EnableNewConstInterp) {
17888 if (!Info.Ctx.getInterpContext().evaluate(Info, this, Result.Val, Kind))
17889 return false;
17890 return CheckConstantExpression(Info, getExprLoc(),
17891 getStorageType(Ctx, this), Result.Val, Kind);
17892 }
17893
17894 // The type of the object we're initializing is 'const T' for a class NTTP.
17895 QualType T = getType();
17896 if (Kind == ConstantExprKind::ClassTemplateArgument)
17897 T.addConst();
17898
17899 // If we're evaluating a prvalue, fake up a MaterializeTemporaryExpr to
17900 // represent the result of the evaluation. CheckConstantExpression ensures
17901 // this doesn't escape.
17902 MaterializeTemporaryExpr BaseMTE(T, const_cast<Expr*>(this), true);
17903 APValue::LValueBase Base(&BaseMTE);
17904 Info.setEvaluatingDecl(Base, Result.Val);
17905
17906 LValue LVal;
17907 LVal.set(Base);
17908 // C++23 [intro.execution]/p5
17909 // A full-expression is [...] a constant-expression
17910 // So we need to make sure temporary objects are destroyed after having
17911 // evaluating the expression (per C++23 [class.temporary]/p4).
17912 FullExpressionRAII Scope(Info);
17913 if (!::EvaluateInPlace(Result.Val, Info, LVal, this) ||
17914 Result.HasSideEffects || !Scope.destroy())
17915 return false;
17916
17917 if (!Info.discardCleanups())
17918 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
17919
17920 if (!CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this),
17921 Result.Val, Kind))
17922 return false;
17923 if (!CheckMemoryLeaks(Info))
17924 return false;
17925
17926 // If this is a class template argument, it's required to have constant
17927 // destruction too.
17928 if (Kind == ConstantExprKind::ClassTemplateArgument &&
17930 true) ||
17931 Result.HasSideEffects)) {
17932 // FIXME: Prefix a note to indicate that the problem is lack of constant
17933 // destruction.
17934 return false;
17935 }
17936
17937 return true;
17938}
17939
17941 const VarDecl *VD,
17943 bool IsConstantInitialization) const {
17944 assert(!isValueDependent() &&
17945 "Expression evaluator can't be called on a dependent expression.");
17946 assert(VD && "Need a valid VarDecl");
17947
17948 llvm::TimeTraceScope TimeScope("EvaluateAsInitializer", [&] {
17949 std::string Name;
17950 llvm::raw_string_ostream OS(Name);
17951 VD->printQualifiedName(OS);
17952 return Name;
17953 });
17954
17955 Expr::EvalStatus EStatus;
17956 EStatus.Diag = &Notes;
17957
17958 EvalInfo Info(Ctx, EStatus,
17959 (IsConstantInitialization &&
17960 (Ctx.getLangOpts().CPlusPlus || Ctx.getLangOpts().C23))
17963 Info.setEvaluatingDecl(VD, Value);
17964 Info.InConstantContext = IsConstantInitialization;
17965
17966 SourceLocation DeclLoc = VD->getLocation();
17967 QualType DeclTy = VD->getType();
17968
17969 if (Info.EnableNewConstInterp) {
17970 auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext();
17971 if (!InterpCtx.evaluateAsInitializer(Info, VD, this, Value))
17972 return false;
17973
17974 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value,
17975 ConstantExprKind::Normal);
17976 } else {
17977 LValue LVal;
17978 LVal.set(VD);
17979
17980 {
17981 // C++23 [intro.execution]/p5
17982 // A full-expression is ... an init-declarator ([dcl.decl]) or a
17983 // mem-initializer.
17984 // So we need to make sure temporary objects are destroyed after having
17985 // evaluated the expression (per C++23 [class.temporary]/p4).
17986 //
17987 // FIXME: Otherwise this may break test/Modules/pr68702.cpp because the
17988 // serialization code calls ParmVarDecl::getDefaultArg() which strips the
17989 // outermost FullExpr, such as ExprWithCleanups.
17990 FullExpressionRAII Scope(Info);
17991 if (!EvaluateInPlace(Value, Info, LVal, this,
17992 /*AllowNonLiteralTypes=*/true) ||
17993 EStatus.HasSideEffects)
17994 return false;
17995 }
17996
17997 // At this point, any lifetime-extended temporaries are completely
17998 // initialized.
17999 Info.performLifetimeExtension();
18000
18001 if (!Info.discardCleanups())
18002 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
18003 }
18004
18005 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value,
18006 ConstantExprKind::Normal) &&
18007 CheckMemoryLeaks(Info);
18008}
18009
18012 Expr::EvalStatus EStatus;
18013 EStatus.Diag = &Notes;
18014
18015 // Only treat the destruction as constant destruction if we formally have
18016 // constant initialization (or are usable in a constant expression).
18017 bool IsConstantDestruction = hasConstantInitialization();
18018
18019 // Make a copy of the value for the destructor to mutate, if we know it.
18020 // Otherwise, treat the value as default-initialized; if the destructor works
18021 // anyway, then the destruction is constant (and must be essentially empty).
18022 APValue DestroyedValue;
18023 if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent())
18024 DestroyedValue = *getEvaluatedValue();
18025 else if (!handleDefaultInitValue(getType(), DestroyedValue))
18026 return false;
18027
18028 if (!EvaluateDestruction(getASTContext(), this, std::move(DestroyedValue),
18029 getType(), getLocation(), EStatus,
18030 IsConstantDestruction) ||
18031 EStatus.HasSideEffects)
18032 return false;
18033
18034 ensureEvaluatedStmt()->HasConstantDestruction = true;
18035 return true;
18036}
18037
18038/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
18039/// constant folded, but discard the result.
18041 assert(!isValueDependent() &&
18042 "Expression evaluator can't be called on a dependent expression.");
18043
18045 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
18047}
18048
18049APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
18050 assert(!isValueDependent() &&
18051 "Expression evaluator can't be called on a dependent expression.");
18052
18053 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstInt");
18054 EvalResult EVResult;
18055 EvalInfo Info(Ctx, EVResult, EvaluationMode::IgnoreSideEffects);
18056 Info.InConstantContext = true;
18057
18058 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
18059 (void)Result;
18060 assert(Result && "Could not evaluate expression");
18061 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
18062
18063 return EVResult.Val.getInt();
18064}
18065
18068 assert(!isValueDependent() &&
18069 "Expression evaluator can't be called on a dependent expression.");
18070
18071 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstIntCheckOverflow");
18072 EvalResult EVResult;
18073 EVResult.Diag = Diag;
18074 EvalInfo Info(Ctx, EVResult, EvaluationMode::IgnoreSideEffects);
18075 Info.InConstantContext = true;
18076 Info.CheckingForUndefinedBehavior = true;
18077
18078 bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
18079 (void)Result;
18080 assert(Result && "Could not evaluate expression");
18081 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
18082
18083 return EVResult.Val.getInt();
18084}
18085
18087 assert(!isValueDependent() &&
18088 "Expression evaluator can't be called on a dependent expression.");
18089
18090 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateForOverflow");
18091 bool IsConst;
18092 EvalResult EVResult;
18093 if (!FastEvaluateAsRValue(this, EVResult.Val, Ctx, IsConst)) {
18094 EvalInfo Info(Ctx, EVResult, EvaluationMode::IgnoreSideEffects);
18095 Info.CheckingForUndefinedBehavior = true;
18096 (void)::EvaluateAsRValue(Info, this, EVResult.Val);
18097 }
18098}
18099
18101 assert(Val.isLValue());
18102 return IsGlobalLValue(Val.getLValueBase());
18103}
18104
18105/// isIntegerConstantExpr - this recursive routine will test if an expression is
18106/// an integer constant expression.
18107
18108/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
18109/// comma, etc
18110
18111// CheckICE - This function does the fundamental ICE checking: the returned
18112// ICEDiag contains an ICEKind indicating whether the expression is an ICE.
18113//
18114// Note that to reduce code duplication, this helper does no evaluation
18115// itself; the caller checks whether the expression is evaluatable, and
18116// in the rare cases where CheckICE actually cares about the evaluated
18117// value, it calls into Evaluate.
18118
18119namespace {
18120
18121enum ICEKind {
18122 /// This expression is an ICE.
18123 IK_ICE,
18124 /// This expression is not an ICE, but if it isn't evaluated, it's
18125 /// a legal subexpression for an ICE. This return value is used to handle
18126 /// the comma operator in C99 mode, and non-constant subexpressions.
18127 IK_ICEIfUnevaluated,
18128 /// This expression is not an ICE, and is not a legal subexpression for one.
18129 IK_NotICE
18130};
18131
18132struct ICEDiag {
18133 ICEKind Kind;
18134 SourceLocation Loc;
18135
18136 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
18137};
18138
18139}
18140
18141static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
18142
18143static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
18144
18145static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
18146 Expr::EvalResult EVResult;
18147 Expr::EvalStatus Status;
18148 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantExpression);
18149
18150 Info.InConstantContext = true;
18151 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
18152 !EVResult.Val.isInt())
18153 return ICEDiag(IK_NotICE, E->getBeginLoc());
18154
18155 return NoDiag();
18156}
18157
18158static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
18159 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
18161 return ICEDiag(IK_NotICE, E->getBeginLoc());
18162
18163 switch (E->getStmtClass()) {
18164#define ABSTRACT_STMT(Node)
18165#define STMT(Node, Base) case Expr::Node##Class:
18166#define EXPR(Node, Base)
18167#include "clang/AST/StmtNodes.inc"
18168 case Expr::PredefinedExprClass:
18169 case Expr::FloatingLiteralClass:
18170 case Expr::ImaginaryLiteralClass:
18171 case Expr::StringLiteralClass:
18172 case Expr::ArraySubscriptExprClass:
18173 case Expr::MatrixSubscriptExprClass:
18174 case Expr::ArraySectionExprClass:
18175 case Expr::OMPArrayShapingExprClass:
18176 case Expr::OMPIteratorExprClass:
18177 case Expr::MemberExprClass:
18178 case Expr::CompoundAssignOperatorClass:
18179 case Expr::CompoundLiteralExprClass:
18180 case Expr::ExtVectorElementExprClass:
18181 case Expr::DesignatedInitExprClass:
18182 case Expr::ArrayInitLoopExprClass:
18183 case Expr::ArrayInitIndexExprClass:
18184 case Expr::NoInitExprClass:
18185 case Expr::DesignatedInitUpdateExprClass:
18186 case Expr::ImplicitValueInitExprClass:
18187 case Expr::ParenListExprClass:
18188 case Expr::VAArgExprClass:
18189 case Expr::AddrLabelExprClass:
18190 case Expr::StmtExprClass:
18191 case Expr::CXXMemberCallExprClass:
18192 case Expr::CUDAKernelCallExprClass:
18193 case Expr::CXXAddrspaceCastExprClass:
18194 case Expr::CXXDynamicCastExprClass:
18195 case Expr::CXXTypeidExprClass:
18196 case Expr::CXXUuidofExprClass:
18197 case Expr::MSPropertyRefExprClass:
18198 case Expr::MSPropertySubscriptExprClass:
18199 case Expr::CXXNullPtrLiteralExprClass:
18200 case Expr::UserDefinedLiteralClass:
18201 case Expr::CXXThisExprClass:
18202 case Expr::CXXThrowExprClass:
18203 case Expr::CXXNewExprClass:
18204 case Expr::CXXDeleteExprClass:
18205 case Expr::CXXPseudoDestructorExprClass:
18206 case Expr::UnresolvedLookupExprClass:
18207 case Expr::RecoveryExprClass:
18208 case Expr::DependentScopeDeclRefExprClass:
18209 case Expr::CXXConstructExprClass:
18210 case Expr::CXXInheritedCtorInitExprClass:
18211 case Expr::CXXStdInitializerListExprClass:
18212 case Expr::CXXBindTemporaryExprClass:
18213 case Expr::ExprWithCleanupsClass:
18214 case Expr::CXXTemporaryObjectExprClass:
18215 case Expr::CXXUnresolvedConstructExprClass:
18216 case Expr::CXXDependentScopeMemberExprClass:
18217 case Expr::UnresolvedMemberExprClass:
18218 case Expr::ObjCStringLiteralClass:
18219 case Expr::ObjCBoxedExprClass:
18220 case Expr::ObjCArrayLiteralClass:
18221 case Expr::ObjCDictionaryLiteralClass:
18222 case Expr::ObjCEncodeExprClass:
18223 case Expr::ObjCMessageExprClass:
18224 case Expr::ObjCSelectorExprClass:
18225 case Expr::ObjCProtocolExprClass:
18226 case Expr::ObjCIvarRefExprClass:
18227 case Expr::ObjCPropertyRefExprClass:
18228 case Expr::ObjCSubscriptRefExprClass:
18229 case Expr::ObjCIsaExprClass:
18230 case Expr::ObjCAvailabilityCheckExprClass:
18231 case Expr::ShuffleVectorExprClass:
18232 case Expr::ConvertVectorExprClass:
18233 case Expr::BlockExprClass:
18234 case Expr::NoStmtClass:
18235 case Expr::OpaqueValueExprClass:
18236 case Expr::PackExpansionExprClass:
18237 case Expr::SubstNonTypeTemplateParmPackExprClass:
18238 case Expr::FunctionParmPackExprClass:
18239 case Expr::AsTypeExprClass:
18240 case Expr::ObjCIndirectCopyRestoreExprClass:
18241 case Expr::MaterializeTemporaryExprClass:
18242 case Expr::PseudoObjectExprClass:
18243 case Expr::AtomicExprClass:
18244 case Expr::LambdaExprClass:
18245 case Expr::CXXFoldExprClass:
18246 case Expr::CoawaitExprClass:
18247 case Expr::DependentCoawaitExprClass:
18248 case Expr::CoyieldExprClass:
18249 case Expr::SYCLUniqueStableNameExprClass:
18250 case Expr::CXXParenListInitExprClass:
18251 case Expr::HLSLOutArgExprClass:
18252 return ICEDiag(IK_NotICE, E->getBeginLoc());
18253
18254 case Expr::InitListExprClass: {
18255 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
18256 // form "T x = { a };" is equivalent to "T x = a;".
18257 // Unless we're initializing a reference, T is a scalar as it is known to be
18258 // of integral or enumeration type.
18259 if (E->isPRValue())
18260 if (cast<InitListExpr>(E)->getNumInits() == 1)
18261 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
18262 return ICEDiag(IK_NotICE, E->getBeginLoc());
18263 }
18264
18265 case Expr::SizeOfPackExprClass:
18266 case Expr::GNUNullExprClass:
18267 case Expr::SourceLocExprClass:
18268 case Expr::EmbedExprClass:
18269 case Expr::OpenACCAsteriskSizeExprClass:
18270 return NoDiag();
18271
18272 case Expr::PackIndexingExprClass:
18273 return CheckICE(cast<PackIndexingExpr>(E)->getSelectedExpr(), Ctx);
18274
18275 case Expr::SubstNonTypeTemplateParmExprClass:
18276 return
18277 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
18278
18279 case Expr::ConstantExprClass:
18280 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
18281
18282 case Expr::ParenExprClass:
18283 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
18284 case Expr::GenericSelectionExprClass:
18285 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
18286 case Expr::IntegerLiteralClass:
18287 case Expr::FixedPointLiteralClass:
18288 case Expr::CharacterLiteralClass:
18289 case Expr::ObjCBoolLiteralExprClass:
18290 case Expr::CXXBoolLiteralExprClass:
18291 case Expr::CXXScalarValueInitExprClass:
18292 case Expr::TypeTraitExprClass:
18293 case Expr::ConceptSpecializationExprClass:
18294 case Expr::RequiresExprClass:
18295 case Expr::ArrayTypeTraitExprClass:
18296 case Expr::ExpressionTraitExprClass:
18297 case Expr::CXXNoexceptExprClass:
18298 return NoDiag();
18299 case Expr::CallExprClass:
18300 case Expr::CXXOperatorCallExprClass: {
18301 // C99 6.6/3 allows function calls within unevaluated subexpressions of
18302 // constant expressions, but they can never be ICEs because an ICE cannot
18303 // contain an operand of (pointer to) function type.
18304 const CallExpr *CE = cast<CallExpr>(E);
18305 if (CE->getBuiltinCallee())
18306 return CheckEvalInICE(E, Ctx);
18307 return ICEDiag(IK_NotICE, E->getBeginLoc());
18308 }
18309 case Expr::CXXRewrittenBinaryOperatorClass:
18310 return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(),
18311 Ctx);
18312 case Expr::DeclRefExprClass: {
18313 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
18314 if (isa<EnumConstantDecl>(D))
18315 return NoDiag();
18316
18317 // C++ and OpenCL (FIXME: spec reference?) allow reading const-qualified
18318 // integer variables in constant expressions:
18319 //
18320 // C++ 7.1.5.1p2
18321 // A variable of non-volatile const-qualified integral or enumeration
18322 // type initialized by an ICE can be used in ICEs.
18323 //
18324 // We sometimes use CheckICE to check the C++98 rules in C++11 mode. In
18325 // that mode, use of reference variables should not be allowed.
18326 const VarDecl *VD = dyn_cast<VarDecl>(D);
18327 if (VD && VD->isUsableInConstantExpressions(Ctx) &&
18328 !VD->getType()->isReferenceType())
18329 return NoDiag();
18330
18331 return ICEDiag(IK_NotICE, E->getBeginLoc());
18332 }
18333 case Expr::UnaryOperatorClass: {
18334 const UnaryOperator *Exp = cast<UnaryOperator>(E);
18335 switch (Exp->getOpcode()) {
18336 case UO_PostInc:
18337 case UO_PostDec:
18338 case UO_PreInc:
18339 case UO_PreDec:
18340 case UO_AddrOf:
18341 case UO_Deref:
18342 case UO_Coawait:
18343 // C99 6.6/3 allows increment and decrement within unevaluated
18344 // subexpressions of constant expressions, but they can never be ICEs
18345 // because an ICE cannot contain an lvalue operand.
18346 return ICEDiag(IK_NotICE, E->getBeginLoc());
18347 case UO_Extension:
18348 case UO_LNot:
18349 case UO_Plus:
18350 case UO_Minus:
18351 case UO_Not:
18352 case UO_Real:
18353 case UO_Imag:
18354 return CheckICE(Exp->getSubExpr(), Ctx);
18355 }
18356 llvm_unreachable("invalid unary operator class");
18357 }
18358 case Expr::OffsetOfExprClass: {
18359 // Note that per C99, offsetof must be an ICE. And AFAIK, using
18360 // EvaluateAsRValue matches the proposed gcc behavior for cases like
18361 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
18362 // compliance: we should warn earlier for offsetof expressions with
18363 // array subscripts that aren't ICEs, and if the array subscripts
18364 // are ICEs, the value of the offsetof must be an integer constant.
18365 return CheckEvalInICE(E, Ctx);
18366 }
18367 case Expr::UnaryExprOrTypeTraitExprClass: {
18369 if ((Exp->getKind() == UETT_SizeOf) &&
18371 return ICEDiag(IK_NotICE, E->getBeginLoc());
18372 if (Exp->getKind() == UETT_CountOf) {
18373 QualType ArgTy = Exp->getTypeOfArgument();
18374 if (ArgTy->isVariableArrayType()) {
18375 // We need to look whether the array is multidimensional. If it is,
18376 // then we want to check the size expression manually to see whether
18377 // it is an ICE or not.
18378 const auto *VAT = Ctx.getAsVariableArrayType(ArgTy);
18379 if (VAT->getElementType()->isArrayType())
18380 // Variable array size expression could be missing (e.g. int a[*][10])
18381 // In that case, it can't be a constant expression.
18382 return VAT->getSizeExpr() ? CheckICE(VAT->getSizeExpr(), Ctx)
18383 : ICEDiag(IK_NotICE, E->getBeginLoc());
18384
18385 // Otherwise, this is a regular VLA, which is definitely not an ICE.
18386 return ICEDiag(IK_NotICE, E->getBeginLoc());
18387 }
18388 }
18389 return NoDiag();
18390 }
18391 case Expr::BinaryOperatorClass: {
18392 const BinaryOperator *Exp = cast<BinaryOperator>(E);
18393 switch (Exp->getOpcode()) {
18394 case BO_PtrMemD:
18395 case BO_PtrMemI:
18396 case BO_Assign:
18397 case BO_MulAssign:
18398 case BO_DivAssign:
18399 case BO_RemAssign:
18400 case BO_AddAssign:
18401 case BO_SubAssign:
18402 case BO_ShlAssign:
18403 case BO_ShrAssign:
18404 case BO_AndAssign:
18405 case BO_XorAssign:
18406 case BO_OrAssign:
18407 // C99 6.6/3 allows assignments within unevaluated subexpressions of
18408 // constant expressions, but they can never be ICEs because an ICE cannot
18409 // contain an lvalue operand.
18410 return ICEDiag(IK_NotICE, E->getBeginLoc());
18411
18412 case BO_Mul:
18413 case BO_Div:
18414 case BO_Rem:
18415 case BO_Add:
18416 case BO_Sub:
18417 case BO_Shl:
18418 case BO_Shr:
18419 case BO_LT:
18420 case BO_GT:
18421 case BO_LE:
18422 case BO_GE:
18423 case BO_EQ:
18424 case BO_NE:
18425 case BO_And:
18426 case BO_Xor:
18427 case BO_Or:
18428 case BO_Comma:
18429 case BO_Cmp: {
18430 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
18431 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
18432 if (Exp->getOpcode() == BO_Div ||
18433 Exp->getOpcode() == BO_Rem) {
18434 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
18435 // we don't evaluate one.
18436 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
18437 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
18438 if (REval == 0)
18439 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
18440 if (REval.isSigned() && REval.isAllOnes()) {
18441 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
18442 if (LEval.isMinSignedValue())
18443 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
18444 }
18445 }
18446 }
18447 if (Exp->getOpcode() == BO_Comma) {
18448 if (Ctx.getLangOpts().C99) {
18449 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
18450 // if it isn't evaluated.
18451 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
18452 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
18453 } else {
18454 // In both C89 and C++, commas in ICEs are illegal.
18455 return ICEDiag(IK_NotICE, E->getBeginLoc());
18456 }
18457 }
18458 return Worst(LHSResult, RHSResult);
18459 }
18460 case BO_LAnd:
18461 case BO_LOr: {
18462 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
18463 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
18464 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
18465 // Rare case where the RHS has a comma "side-effect"; we need
18466 // to actually check the condition to see whether the side
18467 // with the comma is evaluated.
18468 if ((Exp->getOpcode() == BO_LAnd) !=
18469 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
18470 return RHSResult;
18471 return NoDiag();
18472 }
18473
18474 return Worst(LHSResult, RHSResult);
18475 }
18476 }
18477 llvm_unreachable("invalid binary operator kind");
18478 }
18479 case Expr::ImplicitCastExprClass:
18480 case Expr::CStyleCastExprClass:
18481 case Expr::CXXFunctionalCastExprClass:
18482 case Expr::CXXStaticCastExprClass:
18483 case Expr::CXXReinterpretCastExprClass:
18484 case Expr::CXXConstCastExprClass:
18485 case Expr::ObjCBridgedCastExprClass: {
18486 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
18487 if (isa<ExplicitCastExpr>(E)) {
18488 if (const FloatingLiteral *FL
18489 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
18490 unsigned DestWidth = Ctx.getIntWidth(E->getType());
18491 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
18492 APSInt IgnoredVal(DestWidth, !DestSigned);
18493 bool Ignored;
18494 // If the value does not fit in the destination type, the behavior is
18495 // undefined, so we are not required to treat it as a constant
18496 // expression.
18497 if (FL->getValue().convertToInteger(IgnoredVal,
18498 llvm::APFloat::rmTowardZero,
18499 &Ignored) & APFloat::opInvalidOp)
18500 return ICEDiag(IK_NotICE, E->getBeginLoc());
18501 return NoDiag();
18502 }
18503 }
18504 switch (cast<CastExpr>(E)->getCastKind()) {
18505 case CK_LValueToRValue:
18506 case CK_AtomicToNonAtomic:
18507 case CK_NonAtomicToAtomic:
18508 case CK_NoOp:
18509 case CK_IntegralToBoolean:
18510 case CK_IntegralCast:
18511 return CheckICE(SubExpr, Ctx);
18512 default:
18513 return ICEDiag(IK_NotICE, E->getBeginLoc());
18514 }
18515 }
18516 case Expr::BinaryConditionalOperatorClass: {
18518 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
18519 if (CommonResult.Kind == IK_NotICE) return CommonResult;
18520 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
18521 if (FalseResult.Kind == IK_NotICE) return FalseResult;
18522 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
18523 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
18524 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
18525 return FalseResult;
18526 }
18527 case Expr::ConditionalOperatorClass: {
18529 // If the condition (ignoring parens) is a __builtin_constant_p call,
18530 // then only the true side is actually considered in an integer constant
18531 // expression, and it is fully evaluated. This is an important GNU
18532 // extension. See GCC PR38377 for discussion.
18533 if (const CallExpr *CallCE
18534 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
18535 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
18536 return CheckEvalInICE(E, Ctx);
18537 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
18538 if (CondResult.Kind == IK_NotICE)
18539 return CondResult;
18540
18541 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
18542 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
18543
18544 if (TrueResult.Kind == IK_NotICE)
18545 return TrueResult;
18546 if (FalseResult.Kind == IK_NotICE)
18547 return FalseResult;
18548 if (CondResult.Kind == IK_ICEIfUnevaluated)
18549 return CondResult;
18550 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
18551 return NoDiag();
18552 // Rare case where the diagnostics depend on which side is evaluated
18553 // Note that if we get here, CondResult is 0, and at least one of
18554 // TrueResult and FalseResult is non-zero.
18555 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
18556 return FalseResult;
18557 return TrueResult;
18558 }
18559 case Expr::CXXDefaultArgExprClass:
18560 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
18561 case Expr::CXXDefaultInitExprClass:
18562 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
18563 case Expr::ChooseExprClass: {
18564 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
18565 }
18566 case Expr::BuiltinBitCastExprClass: {
18567 if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
18568 return ICEDiag(IK_NotICE, E->getBeginLoc());
18569 return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
18570 }
18571 }
18572
18573 llvm_unreachable("Invalid StmtClass!");
18574}
18575
18576/// Evaluate an expression as a C++11 integral constant expression.
18578 const Expr *E,
18579 llvm::APSInt *Value) {
18581 return false;
18582
18583 APValue Result;
18584 if (!E->isCXX11ConstantExpr(Ctx, &Result))
18585 return false;
18586
18587 if (!Result.isInt())
18588 return false;
18589
18590 if (Value) *Value = Result.getInt();
18591 return true;
18592}
18593
18595 assert(!isValueDependent() &&
18596 "Expression evaluator can't be called on a dependent expression.");
18597
18598 ExprTimeTraceScope TimeScope(this, Ctx, "isIntegerConstantExpr");
18599
18600 if (Ctx.getLangOpts().CPlusPlus11)
18601 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr);
18602
18603 ICEDiag D = CheckICE(this, Ctx);
18604 if (D.Kind != IK_ICE)
18605 return false;
18606 return true;
18607}
18608
18609std::optional<llvm::APSInt>
18611 if (isValueDependent()) {
18612 // Expression evaluator can't succeed on a dependent expression.
18613 return std::nullopt;
18614 }
18615
18616 if (Ctx.getLangOpts().CPlusPlus11) {
18617 APSInt Value;
18619 return Value;
18620 return std::nullopt;
18621 }
18622
18623 if (!isIntegerConstantExpr(Ctx))
18624 return std::nullopt;
18625
18626 // The only possible side-effects here are due to UB discovered in the
18627 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
18628 // required to treat the expression as an ICE, so we produce the folded
18629 // value.
18631 Expr::EvalStatus Status;
18632 EvalInfo Info(Ctx, Status, EvaluationMode::IgnoreSideEffects);
18633 Info.InConstantContext = true;
18634
18635 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
18636 llvm_unreachable("ICE cannot be evaluated!");
18637
18638 return ExprResult.Val.getInt();
18639}
18640
18642 assert(!isValueDependent() &&
18643 "Expression evaluator can't be called on a dependent expression.");
18644
18645 return CheckICE(this, Ctx).Kind == IK_ICE;
18646}
18647
18649 assert(!isValueDependent() &&
18650 "Expression evaluator can't be called on a dependent expression.");
18651
18652 // We support this checking in C++98 mode in order to diagnose compatibility
18653 // issues.
18654 assert(Ctx.getLangOpts().CPlusPlus);
18655
18656 bool IsConst;
18657 APValue Scratch;
18658 if (FastEvaluateAsRValue(this, Scratch, Ctx, IsConst) && Scratch.hasValue()) {
18659 if (Result)
18660 *Result = Scratch;
18661 return true;
18662 }
18663
18664 // Build evaluation settings.
18665 Expr::EvalStatus Status;
18667 Status.Diag = &Diags;
18668 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantExpression);
18669
18670 bool IsConstExpr =
18671 ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) &&
18672 // FIXME: We don't produce a diagnostic for this, but the callers that
18673 // call us on arbitrary full-expressions should generally not care.
18674 Info.discardCleanups() && !Status.HasSideEffects;
18675
18676 return IsConstExpr && Diags.empty();
18677}
18678
18680 const FunctionDecl *Callee,
18682 const Expr *This) const {
18683 assert(!isValueDependent() &&
18684 "Expression evaluator can't be called on a dependent expression.");
18685
18686 llvm::TimeTraceScope TimeScope("EvaluateWithSubstitution", [&] {
18687 std::string Name;
18688 llvm::raw_string_ostream OS(Name);
18689 Callee->getNameForDiagnostic(OS, Ctx.getPrintingPolicy(),
18690 /*Qualified=*/true);
18691 return Name;
18692 });
18693
18694 Expr::EvalStatus Status;
18695 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantExpressionUnevaluated);
18696 Info.InConstantContext = true;
18697
18698 LValue ThisVal;
18699 const LValue *ThisPtr = nullptr;
18700 if (This) {
18701#ifndef NDEBUG
18702 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
18703 assert(MD && "Don't provide `this` for non-methods.");
18704 assert(MD->isImplicitObjectMemberFunction() &&
18705 "Don't provide `this` for methods without an implicit object.");
18706#endif
18707 if (!This->isValueDependent() &&
18708 EvaluateObjectArgument(Info, This, ThisVal) &&
18709 !Info.EvalStatus.HasSideEffects)
18710 ThisPtr = &ThisVal;
18711
18712 // Ignore any side-effects from a failed evaluation. This is safe because
18713 // they can't interfere with any other argument evaluation.
18714 Info.EvalStatus.HasSideEffects = false;
18715 }
18716
18717 CallRef Call = Info.CurrentCall->createCall(Callee);
18718 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
18719 I != E; ++I) {
18720 unsigned Idx = I - Args.begin();
18721 if (Idx >= Callee->getNumParams())
18722 break;
18723 const ParmVarDecl *PVD = Callee->getParamDecl(Idx);
18724 if ((*I)->isValueDependent() ||
18725 !EvaluateCallArg(PVD, *I, Call, Info) ||
18726 Info.EvalStatus.HasSideEffects) {
18727 // If evaluation fails, throw away the argument entirely.
18728 if (APValue *Slot = Info.getParamSlot(Call, PVD))
18729 *Slot = APValue();
18730 }
18731
18732 // Ignore any side-effects from a failed evaluation. This is safe because
18733 // they can't interfere with any other argument evaluation.
18734 Info.EvalStatus.HasSideEffects = false;
18735 }
18736
18737 // Parameter cleanups happen in the caller and are not part of this
18738 // evaluation.
18739 Info.discardCleanups();
18740 Info.EvalStatus.HasSideEffects = false;
18741
18742 // Build fake call to Callee.
18743 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, This,
18744 Call);
18745 // FIXME: Missing ExprWithCleanups in enable_if conditions?
18746 FullExpressionRAII Scope(Info);
18747 return Evaluate(Value, Info, this) && Scope.destroy() &&
18748 !Info.EvalStatus.HasSideEffects;
18749}
18750
18753 PartialDiagnosticAt> &Diags) {
18754 // FIXME: It would be useful to check constexpr function templates, but at the
18755 // moment the constant expression evaluator cannot cope with the non-rigorous
18756 // ASTs which we build for dependent expressions.
18757 if (FD->isDependentContext())
18758 return true;
18759
18760 llvm::TimeTraceScope TimeScope("isPotentialConstantExpr", [&] {
18761 std::string Name;
18762 llvm::raw_string_ostream OS(Name);
18764 /*Qualified=*/true);
18765 return Name;
18766 });
18767
18768 Expr::EvalStatus Status;
18769 Status.Diag = &Diags;
18770
18771 EvalInfo Info(FD->getASTContext(), Status,
18773 Info.InConstantContext = true;
18774 Info.CheckingPotentialConstantExpression = true;
18775
18776 // The constexpr VM attempts to compile all methods to bytecode here.
18777 if (Info.EnableNewConstInterp) {
18778 Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD);
18779 return Diags.empty();
18780 }
18781
18782 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
18783 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
18784
18785 // Fabricate an arbitrary expression on the stack and pretend that it
18786 // is a temporary being used as the 'this' pointer.
18787 LValue This;
18788 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getCanonicalTagType(RD)
18789 : Info.Ctx.IntTy);
18790 This.set({&VIE, Info.CurrentCall->Index});
18791
18793
18794 APValue Scratch;
18795 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
18796 // Evaluate the call as a constant initializer, to allow the construction
18797 // of objects of non-literal types.
18798 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
18799 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
18800 } else {
18801 SourceLocation Loc = FD->getLocation();
18803 Loc, FD, (MD && MD->isImplicitObjectMemberFunction()) ? &This : nullptr,
18804 &VIE, Args, CallRef(), FD->getBody(), Info, Scratch,
18805 /*ResultSlot=*/nullptr);
18806 }
18807
18808 return Diags.empty();
18809}
18810
18812 const FunctionDecl *FD,
18814 PartialDiagnosticAt> &Diags) {
18815 assert(!E->isValueDependent() &&
18816 "Expression evaluator can't be called on a dependent expression.");
18817
18818 Expr::EvalStatus Status;
18819 Status.Diag = &Diags;
18820
18821 EvalInfo Info(FD->getASTContext(), Status,
18823 Info.InConstantContext = true;
18824 Info.CheckingPotentialConstantExpression = true;
18825
18826 if (Info.EnableNewConstInterp) {
18828 return Diags.empty();
18829 }
18830
18831 // Fabricate a call stack frame to give the arguments a plausible cover story.
18832 CallStackFrame Frame(Info, SourceLocation(), FD, /*This=*/nullptr,
18833 /*CallExpr=*/nullptr, CallRef());
18834
18835 APValue ResultScratch;
18836 Evaluate(ResultScratch, Info, E);
18837 return Diags.empty();
18838}
18839
18841 unsigned Type) const {
18842 if (!getType()->isPointerType())
18843 return false;
18844
18845 Expr::EvalStatus Status;
18846 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantFold);
18847 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
18848}
18849
18850static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,
18851 EvalInfo &Info, std::string *StringResult) {
18852 if (!E->getType()->hasPointerRepresentation() || !E->isPRValue())
18853 return false;
18854
18855 LValue String;
18856
18857 if (!EvaluatePointer(E, String, Info))
18858 return false;
18859
18860 QualType CharTy = E->getType()->getPointeeType();
18861
18862 // Fast path: if it's a string literal, search the string value.
18863 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
18864 String.getLValueBase().dyn_cast<const Expr *>())) {
18865 StringRef Str = S->getBytes();
18866 int64_t Off = String.Offset.getQuantity();
18867 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
18868 S->getCharByteWidth() == 1 &&
18869 // FIXME: Add fast-path for wchar_t too.
18870 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
18871 Str = Str.substr(Off);
18872
18873 StringRef::size_type Pos = Str.find(0);
18874 if (Pos != StringRef::npos)
18875 Str = Str.substr(0, Pos);
18876
18877 Result = Str.size();
18878 if (StringResult)
18879 *StringResult = Str;
18880 return true;
18881 }
18882
18883 // Fall through to slow path.
18884 }
18885
18886 // Slow path: scan the bytes of the string looking for the terminating 0.
18887 for (uint64_t Strlen = 0; /**/; ++Strlen) {
18888 APValue Char;
18889 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
18890 !Char.isInt())
18891 return false;
18892 if (!Char.getInt()) {
18893 Result = Strlen;
18894 return true;
18895 } else if (StringResult)
18896 StringResult->push_back(Char.getInt().getExtValue());
18897 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
18898 return false;
18899 }
18900}
18901
18902std::optional<std::string> Expr::tryEvaluateString(ASTContext &Ctx) const {
18903 Expr::EvalStatus Status;
18904 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantFold);
18905 uint64_t Result;
18906 std::string StringResult;
18907
18908 if (EvaluateBuiltinStrLen(this, Result, Info, &StringResult))
18909 return StringResult;
18910 return {};
18911}
18912
18913template <typename T>
18914static bool EvaluateCharRangeAsStringImpl(const Expr *, T &Result,
18915 const Expr *SizeExpression,
18916 const Expr *PtrExpression,
18917 ASTContext &Ctx,
18918 Expr::EvalResult &Status) {
18919 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantExpression);
18920 Info.InConstantContext = true;
18921
18922 if (Info.EnableNewConstInterp)
18923 return Info.Ctx.getInterpContext().evaluateCharRange(Info, SizeExpression,
18924 PtrExpression, Result);
18925
18926 LValue String;
18927 FullExpressionRAII Scope(Info);
18928 APSInt SizeValue;
18929 if (!::EvaluateInteger(SizeExpression, SizeValue, Info))
18930 return false;
18931
18932 uint64_t Size = SizeValue.getZExtValue();
18933
18934 // FIXME: better protect against invalid or excessive sizes
18935 if constexpr (std::is_same_v<APValue, T>)
18936 Result = APValue(APValue::UninitArray{}, Size, Size);
18937 else {
18938 if (Size < Result.max_size())
18939 Result.reserve(Size);
18940 }
18941 if (!::EvaluatePointer(PtrExpression, String, Info))
18942 return false;
18943
18944 QualType CharTy = PtrExpression->getType()->getPointeeType();
18945 for (uint64_t I = 0; I < Size; ++I) {
18946 APValue Char;
18947 if (!handleLValueToRValueConversion(Info, PtrExpression, CharTy, String,
18948 Char))
18949 return false;
18950
18951 if constexpr (std::is_same_v<APValue, T>) {
18952 Result.getArrayInitializedElt(I) = std::move(Char);
18953 } else {
18954 APSInt C = Char.getInt();
18955
18956 assert(C.getBitWidth() <= 8 &&
18957 "string element not representable in char");
18958
18959 Result.push_back(static_cast<char>(C.getExtValue()));
18960 }
18961
18962 if (!HandleLValueArrayAdjustment(Info, PtrExpression, String, CharTy, 1))
18963 return false;
18964 }
18965
18966 return Scope.destroy() && CheckMemoryLeaks(Info);
18967}
18968
18970 const Expr *SizeExpression,
18971 const Expr *PtrExpression, ASTContext &Ctx,
18972 EvalResult &Status) const {
18973 return EvaluateCharRangeAsStringImpl(this, Result, SizeExpression,
18974 PtrExpression, Ctx, Status);
18975}
18976
18978 const Expr *SizeExpression,
18979 const Expr *PtrExpression, ASTContext &Ctx,
18980 EvalResult &Status) const {
18981 return EvaluateCharRangeAsStringImpl(this, Result, SizeExpression,
18982 PtrExpression, Ctx, Status);
18983}
18984
18985bool Expr::tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const {
18986 Expr::EvalStatus Status;
18987 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantFold);
18988
18989 if (Info.EnableNewConstInterp)
18990 return Info.Ctx.getInterpContext().evaluateStrlen(Info, this, Result);
18991
18992 return EvaluateBuiltinStrLen(this, Result, Info);
18993}
18994
18995namespace {
18996struct IsWithinLifetimeHandler {
18997 EvalInfo &Info;
18998 static constexpr AccessKinds AccessKind = AccessKinds::AK_IsWithinLifetime;
18999 using result_type = std::optional<bool>;
19000 std::optional<bool> failed() { return std::nullopt; }
19001 template <typename T>
19002 std::optional<bool> found(T &Subobj, QualType SubobjType) {
19003 return true;
19004 }
19005};
19006
19007std::optional<bool> EvaluateBuiltinIsWithinLifetime(IntExprEvaluator &IEE,
19008 const CallExpr *E) {
19009 EvalInfo &Info = IEE.Info;
19010 // Sometimes this is called during some sorts of constant folding / early
19011 // evaluation. These are meant for non-constant expressions and are not
19012 // necessary since this consteval builtin will never be evaluated at runtime.
19013 // Just fail to evaluate when not in a constant context.
19014 if (!Info.InConstantContext)
19015 return std::nullopt;
19016 assert(E->getBuiltinCallee() == Builtin::BI__builtin_is_within_lifetime);
19017 const Expr *Arg = E->getArg(0);
19018 if (Arg->isValueDependent())
19019 return std::nullopt;
19020 LValue Val;
19021 if (!EvaluatePointer(Arg, Val, Info))
19022 return std::nullopt;
19023
19024 if (Val.allowConstexprUnknown())
19025 return true;
19026
19027 auto Error = [&](int Diag) {
19028 bool CalledFromStd = false;
19029 const auto *Callee = Info.CurrentCall->getCallee();
19030 if (Callee && Callee->isInStdNamespace()) {
19031 const IdentifierInfo *Identifier = Callee->getIdentifier();
19032 CalledFromStd = Identifier && Identifier->isStr("is_within_lifetime");
19033 }
19034 Info.CCEDiag(CalledFromStd ? Info.CurrentCall->getCallRange().getBegin()
19035 : E->getExprLoc(),
19036 diag::err_invalid_is_within_lifetime)
19037 << (CalledFromStd ? "std::is_within_lifetime"
19038 : "__builtin_is_within_lifetime")
19039 << Diag;
19040 return std::nullopt;
19041 };
19042 // C++2c [meta.const.eval]p4:
19043 // During the evaluation of an expression E as a core constant expression, a
19044 // call to this function is ill-formed unless p points to an object that is
19045 // usable in constant expressions or whose complete object's lifetime began
19046 // within E.
19047
19048 // Make sure it points to an object
19049 // nullptr does not point to an object
19050 if (Val.isNullPointer() || Val.getLValueBase().isNull())
19051 return Error(0);
19052 QualType T = Val.getLValueBase().getType();
19053 assert(!T->isFunctionType() &&
19054 "Pointers to functions should have been typed as function pointers "
19055 "which would have been rejected earlier");
19056 assert(T->isObjectType());
19057 // Hypothetical array element is not an object
19058 if (Val.getLValueDesignator().isOnePastTheEnd())
19059 return Error(1);
19060 assert(Val.getLValueDesignator().isValidSubobject() &&
19061 "Unchecked case for valid subobject");
19062 // All other ill-formed values should have failed EvaluatePointer, so the
19063 // object should be a pointer to an object that is usable in a constant
19064 // expression or whose complete lifetime began within the expression
19065 CompleteObject CO =
19066 findCompleteObject(Info, E, AccessKinds::AK_IsWithinLifetime, Val, T);
19067 // The lifetime hasn't begun yet if we are still evaluating the
19068 // initializer ([basic.life]p(1.2))
19069 if (Info.EvaluatingDeclValue && CO.Value == Info.EvaluatingDeclValue)
19070 return Error(2);
19071
19072 if (!CO)
19073 return false;
19074 IsWithinLifetimeHandler handler{Info};
19075 return findSubobject(Info, E, CO, Val.getLValueDesignator(), handler);
19076}
19077} // 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)
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 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 EvaluateDecl(EvalInfo &Info, const Decl *D, bool EvaluateConditionDecl=false)
static void expandArray(APValue &Array, unsigned Index)
static bool handleLogicalOpForVector(const APInt &LHSValue, BinaryOperatorKind Opcode, const APInt &RHSValue, APInt &Result)
static unsigned FindDesignatorMismatch(QualType ObjType, const SubobjectDesignator &A, const SubobjectDesignator &B, bool &WasArrayIndex)
Find the position where two subobject designators diverge, or equivalently the length of the common i...
static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx, const LValue &LV)
Determine whether this is a pointer past the end of the complete object referred to by the lvalue.
static unsigned getBaseIndex(const CXXRecordDecl *Derived, const CXXRecordDecl *Base)
Get the base index of the given base class within an APValue representing the given derived class.
static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result, EvalInfo &Info)
Evaluate only a fixed point expression into an APResult.
void HandleComplexComplexMul(APFloat A, APFloat B, APFloat C, APFloat D, APFloat &ResR, APFloat &ResI)
static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type, EvalInfo &Info, uint64_t &Size)
Tries to evaluate the __builtin_object_size for E. If successful, returns true and stores the result ...
static bool EvalPointerValueAsBool(const APValue &Value, bool &Result)
static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E, BinaryOperatorKind Opcode, APValue &LHSValue, const APValue &RHSValue)
static const FunctionDecl * getVirtualOperatorDelete(QualType T)
static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal)
Checks to see if the given LValue's Designator is at the end of the LValue's record layout....
static bool CheckArraySize(EvalInfo &Info, const ConstantArrayType *CAT, SourceLocation CallLoc={})
static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This, const Expr *E, bool AllowNonLiteralTypes=false)
EvaluateInPlace - Evaluate an expression in-place in an APValue. In some cases, the in-place evaluati...
static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E, APFloat &LHS, BinaryOperatorKind Opcode, const APFloat &RHS)
Perform the given binary floating-point operation, in-place, on LHS.
static std::optional< DynAlloc * > CheckDeleteKind(EvalInfo &Info, const Expr *E, const LValue &Pointer, DynAlloc::Kind DeallocKind)
Check that the given object is a suitable pointer to a heap allocation that still exists and is of th...
static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, bool InvalidBaseOK=false)
Evaluate an expression as an lvalue. This can be legitimately called on expressions which are not glv...
static bool FastEvaluateAsRValue(const Expr *Exp, APValue &Result, const ASTContext &Ctx, bool &IsConst)
static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E, APValue &Result, ArrayRef< QualType > Path)
Perform the adjustment from a value returned by a virtual function to a value of the statically expec...
static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info, const SwitchStmt *SS)
Evaluate a switch statement.
static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S, APValue &Result, QualType AllocType=QualType())
static bool EvaluateArgs(ArrayRef< const Expr * > Args, CallRef Call, EvalInfo &Info, const FunctionDecl *Callee, bool RightToLeft=false, LValue *ObjectArg=nullptr)
Evaluate the arguments to a function call.
static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, EvalInfo &Info)
static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, const LValue &LVal, llvm::APInt &Result)
Convenience function. LVal's base must be a call to an alloc_size function.
static bool handleIntIntBinOp(EvalInfo &Info, const BinaryOperator *E, const APSInt &LHS, BinaryOperatorKind Opcode, APSInt RHS, APSInt &Result)
Perform the given binary integer operation.
static bool EvaluateInitForDeclOfReferenceType(EvalInfo &Info, const ValueDecl *D, const Expr *Init, LValue &Result, APValue &Val)
Evaluates the initializer of a reference.
static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This, AccessKinds AK, bool Polymorphic)
Check that we can access the notional vptr of an object / determine its dynamic type.
static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E, QualType SrcType, const APFloat &Value, QualType DestType, APSInt &Result)
static bool getAlignmentArgument(const Expr *E, QualType ForType, EvalInfo &Info, APSInt &Alignment)
Evaluate the value of the alignment argument to __builtin_align_{up,down}, __builtin_is_aligned and _...
static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc, QualType Type, const APValue &Value)
Check that this evaluated value is fully-initialized and can be loaded by an lvalue-to-rvalue convers...
static SubobjectHandler::result_type findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj, const SubobjectDesignator &Sub, SubobjectHandler &handler)
Find the designated sub-object of an rvalue.
static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc, unsigned Type, const LValue &LVal, CharUnits &EndOffset)
Helper for tryEvaluateBuiltinObjectSize – Given an LValue, this will determine how many bytes exist f...
static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int, CharUnits &Result)
Converts the given APInt to CharUnits, assuming the APInt is unsigned. Fails if the conversion would ...
static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg, CallRef Call, EvalInfo &Info, bool NonNull=false, APValue **EvaluatedArg=nullptr)
llvm::SmallPtrSet< const MaterializeTemporaryExpr *, 8 > CheckedTemporaries
Materialized temporaries that we've already checked to determine if they're initializsed by a constan...
GCCTypeClass EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts)
EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way as GCC.
static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info)
static bool MaybeEvaluateDeferredVarDeclInit(EvalInfo &Info, const VarDecl *VD)
static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E, QualType DestType, QualType SrcType, const APSInt &Value)
static std::optional< APValue > handleVectorUnaryOperator(ASTContext &Ctx, QualType ResultTy, UnaryOperatorKind Op, APValue Elt)
static bool lifetimeStartedInEvaluation(EvalInfo &Info, APValue::LValueBase Base, bool MutableSubobject=false)
static bool isOneByteCharacterType(QualType T)
static bool HandleLambdaCapture(EvalInfo &Info, const Expr *E, LValue &Result, const CXXMethodDecl *MD, const FieldDecl *FD, bool LValueToRValueConversion)
Get an lvalue to a field of a lambda's closure type.
static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl, const Expr *Cond, bool &Result)
Evaluate a condition (either a variable declaration or an expression).
static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult, const ASTContext &Ctx, Expr::SideEffectsKind AllowSideEffects, EvalInfo &Info)
static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result)
EvaluateAsRValue - Try to evaluate this expression, performing an implicit lvalue-to-rvalue cast if i...
static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK, QualType T)
Diagnose an attempt to read from any unreadable field within the specified type, which might be a cla...
static ICEDiag CheckICE(const Expr *E, const ASTContext &Ctx)
static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc, const FunctionDecl *Declaration, const FunctionDecl *Definition, const Stmt *Body)
CheckConstexprFunction - Check that a function can be called in a constant expression.
static bool EvaluateDestruction(const ASTContext &Ctx, APValue::LValueBase Base, APValue DestroyedValue, QualType Type, SourceLocation Loc, Expr::EvalStatus &EStatus, bool IsConstantDestruction)
static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, const Stmt *S, const SwitchCase *SC=nullptr)
static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This, APValue &Result, const InitListExpr *ILE, QualType AllocType)
static bool HasSameBase(const LValue &A, const LValue &B)
static bool CheckLocalVariableDeclaration(EvalInfo &Info, const VarDecl *VD)
static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj, const CXXRecordDecl *Derived, const CXXRecordDecl *Base, const ASTRecordLayout *RL=nullptr)
static bool IsGlobalLValue(APValue::LValueBase B)
static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E)
Get rounding mode to use in evaluation of the specified expression.
static QualType getObjectType(APValue::LValueBase B)
Retrieves the "underlying object type" of the given expression, as used by __builtin_object_size.
static bool handleCompareOpForVectorHelper(const APTy &LHSValue, BinaryOperatorKind Opcode, const APTy &RHSValue, APInt &Result)
static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E)
static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD)
Determine whether a type would actually be read by an lvalue-to-rvalue conversion.
static void negateAsSigned(APSInt &Int)
Negate an APSInt in place, converting it to a signed form if necessary, and preserving its value (by ...
static bool HandleFunctionCall(SourceLocation CallLoc, const FunctionDecl *Callee, const LValue *ObjectArg, const Expr *E, ArrayRef< const Expr * > Args, CallRef Call, const Stmt *Body, EvalInfo &Info, APValue &Result, const LValue *ResultSlot)
Evaluate a function call.
static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal)
Attempts to detect a user writing into a piece of memory that's impossible to figure out the size of ...
static bool GetLValueBaseAsString(const EvalInfo &Info, const LValue &LVal, LValueBaseString &AsString)
static bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E)
static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, EvalInfo &Info)
EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and produce either the intege...
static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E, LValue &Ptr)
Apply the given dynamic cast operation on the provided lvalue.
static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E, LValue &Result)
Perform a call to 'operator new' or to ‘__builtin_operator_new’.
static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E, QualType SrcType, QualType DestType, APFloat &Result)
static bool MaybeHandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr, const LValue &LHS)
Handle a builtin simple-assignment or a call to a trivial assignment operator whose left-hand side mi...
static bool isFormalAccess(AccessKinds AK)
Is this an access per the C++ definition?
static bool handleCompoundAssignment(EvalInfo &Info, const CompoundAssignOperator *E, const LValue &LVal, QualType LValType, QualType PromotedLValType, BinaryOperatorKind Opcode, const APValue &RVal)
Perform a compound assignment of LVal <op>= RVal.
static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal, QualType LValType, bool IsIncrement, APValue *Old)
Perform an increment or decrement on LVal.
static ICEDiag NoDiag()
static bool EvaluateVoid(const Expr *E, EvalInfo &Info)
static bool HandleDestruction(EvalInfo &Info, const Expr *E, const LValue &This, QualType ThisType)
Perform a destructor or pseudo-destructor call on the given object, which might in general not be a c...
static bool HandleDestructionImpl(EvalInfo &Info, SourceRange CallRange, const LValue &This, APValue &Value, QualType T)
static bool ArePotentiallyOverlappingStringLiterals(const EvalInfo &Info, const LValue &LHS, const LValue &RHS)
TokenType getType() const
Returns the token's type, e.g.
FormatToken * Next
The next token in the unwrapped line.
tooling::Replacements cleanup(const FormatStyle &Style, StringRef Code, ArrayRef< tooling::Range > Ranges, StringRef FileName="<stdin>")
Clean up any erroneous/redundant code in the given Ranges in Code.
#define X(type, name)
Definition Value.h:97
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Record Record
Definition MachO.h:31
Implements a partial diagnostic which may not be emitted.
llvm::DenseMap< Stmt *, Stmt * > MapTy
Definition ParentMap.cpp:21
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
Expr * getExpr()
Get 'expr' part of the associated expression/statement.
static QualType getPointeeType(const MemRegion *R)
Enumerates target-specific builtins in their own namespaces within namespace clang.
Defines the clang::TypeLoc interface and its subclasses.
C Language Family Type Representation.
__DEVICE__ long long abs(long long __n)
a trap message and trap category.
llvm::APInt getValue() const
QualType getType() const
Definition APValue.cpp:63
unsigned getVersion() const
Definition APValue.cpp:113
QualType getDynamicAllocType() const
Definition APValue.cpp:122
QualType getTypeInfoType() const
Definition APValue.cpp:117
static LValueBase getTypeInfo(TypeInfoLValue LV, QualType TypeInfo)
Definition APValue.cpp:55
static LValueBase getDynamicAlloc(DynamicAllocLValue LV, QualType Type)
Definition APValue.cpp:47
A non-discriminated union of a base, field, or array index.
Definition APValue.h:207
BaseOrMemberType getAsBaseOrMember() const
Definition APValue.h:221
static LValuePathEntry ArrayIndex(uint64_t Index)
Definition APValue.h:215
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:122
bool hasArrayFiller() const
Definition APValue.h:584
const LValueBase getLValueBase() const
Definition APValue.cpp:983
APValue & getArrayInitializedElt(unsigned I)
Definition APValue.h:576
void swap(APValue &RHS)
Swaps the contents of this and the given APValue.
Definition APValue.cpp:474
APSInt & getInt()
Definition APValue.h:489
APValue & getStructField(unsigned i)
Definition APValue.h:617
const FieldDecl * getUnionField() const
Definition APValue.h:629
bool isVector() const
Definition APValue.h:473
APSInt & getComplexIntImag()
Definition APValue.h:527
bool isAbsent() const
Definition APValue.h:463
bool isComplexInt() const
Definition APValue.h:470
llvm::PointerIntPair< const Decl *, 1, bool > BaseOrMemberType
A FieldDecl or CXXRecordDecl, along with a flag indicating whether we mean a virtual or non-virtual b...
Definition APValue.h:204
ValueKind getKind() const
Definition APValue.h:461
unsigned getArrayInitializedElts() const
Definition APValue.h:595
static APValue IndeterminateValue()
Definition APValue.h:432
bool isFloat() const
Definition APValue.h:468
APFixedPoint & getFixedPoint()
Definition APValue.h:511
bool hasValue() const
Definition APValue.h:465
bool hasLValuePath() const
Definition APValue.cpp:998
const ValueDecl * getMemberPointerDecl() const
Definition APValue.cpp:1066
APValue & getUnionValue()
Definition APValue.h:633
CharUnits & getLValueOffset()
Definition APValue.cpp:993
void printPretty(raw_ostream &OS, const ASTContext &Ctx, QualType Ty) const
Definition APValue.cpp:703
bool isComplexFloat() const
Definition APValue.h:471
APValue & getVectorElt(unsigned I)
Definition APValue.h:563
APValue & getArrayFiller()
Definition APValue.h:587
unsigned getVectorLength() const
Definition APValue.h:571
bool isLValue() const
Definition APValue.h:472
void setUnion(const FieldDecl *Field, const APValue &Value)
Definition APValue.cpp:1059
bool isIndeterminate() const
Definition APValue.h:464
bool isInt() const
Definition APValue.h:467
unsigned getArraySize() const
Definition APValue.h:599
bool allowConstexprUnknown() const
Definition APValue.h:318
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition APValue.cpp:956
bool isFixedPoint() const
Definition APValue.h:469
@ Indeterminate
This object has an indeterminate value (C++ [basic.indet]).
Definition APValue.h:131
@ None
There is no such object (it's outside its lifetime).
Definition APValue.h:129
bool isStruct() const
Definition APValue.h:475
APSInt & getComplexIntReal()
Definition APValue.h:519
APFloat & getComplexFloatImag()
Definition APValue.h:543
APFloat & getComplexFloatReal()
Definition APValue.h:535
APFloat & getFloat()
Definition APValue.h:503
APValue & getStructBase(unsigned i)
Definition APValue.h:612
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:188
SourceManager & getSourceManager()
Definition ASTContext.h:798
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.
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,...
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
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:739
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:891
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:790
llvm::FixedPointSemantics getFixedPointSemantics(QualType Ty) const
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
llvm::APSInt MakeIntValue(uint64_t Value, QualType Type) const
Make an APSInt of the appropriate width and signedness for the given Value and integer Type.
const VariableArrayType * getAsVariableArrayType(QualType T) const
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:856
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
CanQualType getCanonicalTagType(const TagDecl *TD) const
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:3038
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3720
QualType getElementType() const
Definition TypeBase.h:3732
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition TypeBase.h:8084
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:4770
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:2659
bool isArrayForm() const
Definition ExprCXX.h:2646
bool isGlobalDelete() const
Definition ExprCXX.h:2645
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:2428
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:2463
Expr * getPlacementArg(unsigned I)
Definition ExprCXX.h:2497
unsigned getNumPlacementArgs() const
Definition ExprCXX.h:2488
SourceRange getSourceRange() const
Definition ExprCXX.h:2604
FunctionDecl * getOperatorNew() const
Definition ExprCXX.h:2453
Expr * getInitializer()
The initializer of this new-expression.
Definition ExprCXX.h:2527
bool getValue() const
Definition ExprCXX.h:4326
MutableArrayRef< Expr * > getInitExprs()
Definition ExprCXX.h:5175
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 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:5538
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:3758
unsigned getSizeBitWidth() const
Return the bit width of the size type.
Definition TypeBase.h:3821
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:3847
bool isZeroSize() const
Return true if the size is zero.
Definition TypeBase.h:3828
const Expr * getSizeExpr() const
Return a pointer to the size expression.
Definition TypeBase.h:3854
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3814
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition TypeBase.h:3834
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:427
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:524
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:4412
void getEncodedElementAccess(SmallVectorImpl< uint32_t > &Elts) const
getEncodedElementAccess - Encode the elements accessed into an llvm aggregate Constant of ConstantInt...
Definition Expr.cpp:4444
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:3157
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3260
unsigned getBitWidthValue() const
Computes the bit width of this field, if this is a bit field.
Definition Decl.cpp:4693
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition Decl.h:3242
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3393
FieldDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this field.
Definition Decl.h:3404
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:102
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:1078
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:1999
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2794
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition Decl.cpp:3271
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition Decl.cpp:4146
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition Decl.cpp:4134
bool hasCXXExplicitFunctionObjectParameter() const
Definition Decl.cpp:3806
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition Decl.h:2376
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition Decl.cpp:4270
ArrayRef< ParmVarDecl * >::const_iterator param_const_iterator
Definition Decl.h:2780
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition Decl.h:2469
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:3414
bool isDefaulted() const
Whether this function is defaulted.
Definition Decl.h:2384
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:3117
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:1026
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:3464
ArrayRef< NamedDecl * > chain() const
Definition Decl.h:3485
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:4914
StorageDuration getStorageDuration() const
Retrieve the storage duration for the materialized temporary.
Definition ExprCXX.h:4939
Expr * getSubExpr() const
Retrieve the temporary-generating subexpression whose value will be materialized into a glvalue.
Definition ExprCXX.h:4931
APValue * getOrCreateValue(bool MayCreate) const
Get the storage for the constant value of a materialized temporary of static storage duration.
Definition ExprCXX.h:4947
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:273
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:294
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:300
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:339
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:4633
const Expr * getSubExpr() const
Definition Expr.h:2199
Represents a parameter to a function.
Definition Decl.h:1789
unsigned getFunctionScopeIndex() const
Returns the index of this parameter in its prototype or method scope.
Definition Decl.h:1849
bool isExplicitObjectParameter() const
Definition Decl.h:1877
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:8369
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:8285
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:8470
QualType getCanonicalType() const
Definition TypeBase.h:8337
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8379
void removeLocalVolatile()
Definition TypeBase.h:8401
void addVolatile()
Add the volatile type qualifier to this QualType.
Definition TypeBase.h:1164
void removeLocalConst()
Definition TypeBase.h:8393
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8358
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:8331
Represents a struct/union/class.
Definition Decl.h:4309
field_iterator field_end() const
Definition Decl.h:4515
field_range fields() const
Definition Decl.h:4512
specific_decl_iterator< FieldDecl > field_iterator
Definition Decl.h:4509
bool isAnonymousStructOrUnion() const
Whether this is an anonymous struct or union.
Definition Decl.h:4361
bool field_empty() const
Definition Decl.h:4520
field_iterator field_begin() const
Definition Decl.cpp:5154
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:4509
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:334
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:346
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:1144
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:4840
bool isUnion() const
Definition Decl.h:3919
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:8267
bool getBoolValue() const
Definition ExprCXX.h:2941
const APValue & getAPValue() const
Definition ExprCXX.h:2946
bool isStoredAsBoolean() const
Definition ExprCXX.h:2937
The base class of the type hierarchy.
Definition TypeBase.h:1833
bool isVoidType() const
Definition TypeBase.h:8878
bool isBooleanType() const
Definition TypeBase.h:9008
bool isFunctionReferenceType() const
Definition TypeBase.h:8596
bool isMFloat8Type() const
Definition TypeBase.h:8903
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:2994
bool isIncompleteArrayType() const
Definition TypeBase.h:8629
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:9174
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:8625
bool isNothrowT() const
Definition Type.cpp:3171
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition Type.h:41
bool isVoidPointerType() const
Definition Type.cpp:712
bool isConstantSizeType() const
Return true if this is not a variable sized type, according to the rules of C99 6....
Definition Type.cpp:2426
bool isArrayType() const
Definition TypeBase.h:8621
bool isFunctionPointerType() const
Definition TypeBase.h:8589
bool isPointerType() const
Definition TypeBase.h:8522
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:8922
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9165
bool isReferenceType() const
Definition TypeBase.h:8546
bool isEnumeralType() const
Definition TypeBase.h:8653
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:8633
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition Type.cpp:2608
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:752
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:8996
bool isExtVectorBoolType() const
Definition TypeBase.h:8669
bool isMemberDataPointerType() const
Definition TypeBase.h:8614
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition TypeBase.h:8847
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:8657
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:8934
bool isMemberPointerType() const
Definition TypeBase.h:8603
bool isAtomicType() const
Definition TypeBase.h:8704
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:9151
bool isObjectType() const
Determine whether this type is an object type.
Definition TypeBase.h:2510
EnumDecl * getAsEnumDecl() const
Retrieves the EnumDecl this type refers to.
Definition Type.h:53
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2436
bool isFunctionType() const
Definition TypeBase.h:8518
bool isVectorType() const
Definition TypeBase.h:8661
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:8530
TypeClass getTypeClass() const
Definition TypeBase.h:2385
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9098
bool isNullPtrType() const
Definition TypeBase.h:8915
bool isRecordType() const
Definition TypeBase.h:8649
bool isUnionType() const
Definition Type.cpp:718
bool isSizelessVectorType() const
Returns true for all scalable vector types.
Definition Type.cpp:2570
bool hasPointerRepresentation() const
Whether this type is represented natively as a pointer.
Definition TypeBase.h:9042
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:711
QualType getType() const
Definition Decl.h:722
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr.
Definition Decl.cpp:5453
QualType getType() const
Definition Value.cpp:237
bool hasValue() const
Definition Value.h:135
Represents a variable declaration or definition.
Definition Decl.h:925
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition Decl.h:1568
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:1577
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:1207
ThreadStorageClassSpecifier getTSCSpec() const
Definition Decl.h:1176
const Expr * getInit() const
Definition Decl.h:1367
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:1183
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:1252
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:1357
Expr * getSizeExpr() const
Definition TypeBase.h:3978
Represents a GCC generic vector type.
Definition TypeBase.h:4173
unsigned getNumElements() const
Definition TypeBase.h:4188
QualType getElementType() const
Definition TypeBase.h:4187
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:1205
Stmt * getBody()
Definition Stmt.h:2761
bool evaluateCharRange(State &Parent, const Expr *SizeExpr, const Expr *PtrExpr, APValue &Result)
Definition Context.cpp:224
bool evaluateStrlen(State &Parent, const Expr *E, uint64_t &Result)
Evalute.
Definition Context.cpp:240
void isPotentialConstantExprUnevaluated(State &Parent, const Expr *E, const FunctionDecl *FD)
Definition Context.cpp:57
bool isPotentialConstantExpr(State &Parent, const FunctionDecl *FD)
Checks if a function is a potential constant expression.
Definition Context.cpp:37
bool evaluateAsRValue(State &Parent, const Expr *E, APValue &Result)
Evaluates a toplevel expression as an rvalue.
Definition Context.cpp:70
bool evaluate(State &Parent, const Expr *E, APValue &Result, ConstantExprKind Kind)
Like evaluateAsRvalue(), but does no implicit lvalue-to-rvalue conversion.
Definition Context.cpp:100
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.
bool NE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1260
llvm::FixedPointSemantics FixedPointSemantics
Definition Interp.h:41
bool This(InterpState &S, CodePtr OpPC)
Definition Interp.h:2816
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:3477
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:146
@ 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:5874
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ Other
Other implicit parameter.
Definition Decl.h:1745
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